44 lines
1.0 KiB
C
44 lines
1.0 KiB
C
// scope.c
|
|
#include "scope.h"
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
typedef struct Scope Scope;
|
|
|
|
Scope* scope_create(Scope* parent) {
|
|
Scope* scope = malloc(sizeof(Scope));
|
|
hmap_init(&scope->symbols);
|
|
scope->parent = parent;
|
|
scope->base_offset = 0;
|
|
scope->cur_offset = 0;
|
|
return scope;
|
|
}
|
|
|
|
void scope_destroy(Scope* scope) {
|
|
hmap_destroy(&scope->symbols);
|
|
free(scope);
|
|
}
|
|
|
|
void scope_insert(Scope* scope, const char* name, void* symbol) {
|
|
if (hmap_contains(&scope->symbols, name)) {
|
|
// 处理重复定义错误
|
|
fprintf(stderr, "Error: Symbol '%s' already defined\n", name);
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
hmap_put(&scope->symbols, name, symbol);
|
|
}
|
|
|
|
void* scope_lookup(Scope* scope, const char* name) {
|
|
void* symbol = NULL;
|
|
while (scope) {
|
|
symbol = hmap_get(&scope->symbols, name);
|
|
if (symbol) break;
|
|
scope = scope->parent;
|
|
}
|
|
return symbol;
|
|
}
|
|
|
|
void* scope_lookup_current(Scope* scope, const char* name) {
|
|
return hmap_get(&scope->symbols, name);
|
|
}
|