博客 / 詳情

返回

編程語言符號表的管理

首先為表中的符號, 設置一個初始annote值的, 其中size是長度,

static void symtable_add_global(struct symtable *st)
{
    struct sym *sym;

    sym = &st->table[st->len++];
    sym->annot.type = FS_INT;
    sym->annot.size = 8;
    sym->name = "@$";
    sym->size = sym->annot.size;
    sym->keys = fs_str_new(strdup("0123456789abcdef"));
}

創建一個符號表:

struct symtable *symtable_new(void)
{
    struct symtable *st;
    int i;

    st = calloc(1, sizeof(*st));
    assert(st);

    st->cap = 16;
    st->table = calloc(st->cap, sizeof(*st->table));
    assert(st->table);

    symtable_add_global(st);

    for (i = BPF_REG_0; i < __MAX_BPF_REG; i++)
        *(int *)(&st->reg[i].reg) = i;
    return st;
}

首先獲取符號的信息, 並將對應的信息傳遞給node

int symtable_transfer(symtable_t* st, node_t* n) {
    sym_t* sym;
    if ( n->type != TYPE_VAR ) {
        return 0;
    }

    sym = symtable_get(st, n->name); //首先獲取變量
    n->annot = sym->annot; //將符號的信息轉化成為node的信息
    return 0;
}

其次在符號表中添加對應的符號:

int symtable_add(struct symtable *st, struct fs_node *n)
{
    struct sym *sym;
    sym = symtable_get(st, n->string);
    
    if (sym) { //首先查找變量, 變量存在直接返回
        if (n->type == FS_VAR)
            return 0;
    }

    //如果不存在, 在table的尾部進行添加
    sym = &st->table[st->len++];
    sym->name  = n->string;
    sym->annot = n->annot;  
    sym->size  = n->annot.size;
    sym->addr = symtable_reserve(st, sym->size);
    return 0;
}

然後就是symtable_get的邏輯:

struct sym* symtable_get(struct symtable *st, const char *name)
{
    size_t i;

    for (i = 0; i < st->len; i++) {
        if (!strcmp(st->table[i].name, name))
            return &st->table[i];
    }

    return NULL;
}

然後加入變量檢查模式

user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.