summaryrefslogtreecommitdiff
path: root/masm/symtbl.c
blob: b75c7524ee31b4376872d689f173245840cf0506 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <merror.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "parse.h"

#define SYMTBL_INIT_LEN 24

int symtbl_init(struct symbol_table *sym_tbl)
{
        sym_tbl->len = SYMTBL_INIT_LEN;
        sym_tbl->count = 0;
        sym_tbl->symbols = malloc(sizeof(struct symbol) * SYMTBL_INIT_LEN);

        if (sym_tbl->symbols == NULL) {
                ERROR("cannot alloc");
                return M_ERROR;
        }

        return M_SUCCESS;
}

void symtbl_free(struct symbol_table *sym_tbl)
{
        free(sym_tbl->symbols);
}

int symtbl_push(struct symbol_table *sym_tbl, struct symbol sym)
{
        if (sym_tbl->count >= sym_tbl->len) {
                sym_tbl->len *= 2;
                sym_tbl->symbols = realloc(sym_tbl->symbols,
                                        sizeof(struct symbol) * sym_tbl->len);
                if (sym_tbl->symbols == NULL) {
                        ERROR("cannot relloc");
                        return M_ERROR;
                }
        }

        sym_tbl->symbols[sym_tbl->count++] = sym;
        return M_SUCCESS;
}

int symtbl_find(struct symbol_table *sym_tbl, struct symbol **ptr,
                const char name[MAX_LEX_LENGTH])
{
        for (uint32_t i = 0; i < sym_tbl->count; i++) {
                struct symbol *sym = &sym_tbl->symbols[i];
                if (strcmp(sym->name, name) == 0) {
                        if (ptr != NULL)
                                *ptr = sym;
                        return M_SUCCESS;
                }
        }
        return M_ERROR;
}