100 lines
2.0 KiB
C
100 lines
2.0 KiB
C
|
#include "sym.h"
|
||
|
|
||
|
void sym_init(sym_t* sym, tysy_t* tysy, err_t* err)
|
||
|
{
|
||
|
assert(sym);
|
||
|
|
||
|
sym->tysy = tysy;
|
||
|
sym->err = err;
|
||
|
|
||
|
sym->entries.id_counter = 0;
|
||
|
sym->entries.size = 0;
|
||
|
sym->entries.cap = 0;
|
||
|
sym->entries.data = NULL;
|
||
|
}
|
||
|
|
||
|
void sym_free(sym_t* sym)
|
||
|
{
|
||
|
assert(sym);
|
||
|
|
||
|
for (size_t i=0; i<sym->entries.size; i++)
|
||
|
{
|
||
|
sym_entry_t* entry = sym->entries.data[i];
|
||
|
free(entry->name);
|
||
|
free(entry);
|
||
|
}
|
||
|
|
||
|
free(sym->entries.data);
|
||
|
sym->entries.size = 0;
|
||
|
sym->entries.cap = 0;
|
||
|
}
|
||
|
|
||
|
int sym_declare(sym_t* sym, char* name, type_t* type)
|
||
|
{
|
||
|
assert(sym);
|
||
|
assert(name);
|
||
|
assert(type);
|
||
|
|
||
|
if (sym->entries.data == NULL)
|
||
|
{
|
||
|
sym->entries.cap = 2;
|
||
|
sym->entries.data = malloc(sizeof(sym_entry_t*)
|
||
|
* sym->entries.cap);
|
||
|
}
|
||
|
|
||
|
if (sym->entries.size >= sym->entries.cap)
|
||
|
{
|
||
|
sym->entries.cap *= 2;
|
||
|
sym->entries.data = realloc(sym->entries.data,
|
||
|
sizeof(sym_entry_t*) * sym->entries.cap);
|
||
|
}
|
||
|
|
||
|
sym->entries.data[sym->entries.size] = malloc(sizeof(sym_entry_t));
|
||
|
|
||
|
int id = sym->entries.id_counter;
|
||
|
sym->entries.id_counter++;
|
||
|
|
||
|
sym->entries.data[sym->entries.size]->name = strdup(name);
|
||
|
sym->entries.data[sym->entries.size]->id = id;
|
||
|
sym->entries.data[sym->entries.size]->type = type;
|
||
|
|
||
|
sym->entries.size++;
|
||
|
|
||
|
return id;
|
||
|
}
|
||
|
|
||
|
sym_entry_t* sym_try_find_by_name(sym_t* sym, char* name)
|
||
|
{
|
||
|
assert(sym);
|
||
|
|
||
|
for (size_t i=0; i<sym->entries.size; i++)
|
||
|
{
|
||
|
if (strcmp(sym->entries.data[i]->name, name) == 0)
|
||
|
{
|
||
|
return sym->entries.data[i];
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return NULL;
|
||
|
}
|
||
|
|
||
|
size_t sym_str(sym_t* sym, char* buffer, size_t size)
|
||
|
{
|
||
|
assert(sym);
|
||
|
assert(buffer);
|
||
|
size_t sz = 0;
|
||
|
|
||
|
for (size_t i=0; i<sym->entries.size; i++)
|
||
|
{
|
||
|
sym_entry_t* entry = sym->entries.data[i];
|
||
|
sz += snprintf(buffer + sz, size - sz, "(%d %s ",
|
||
|
entry->id, entry->name);
|
||
|
|
||
|
sz += type_str(entry->type, buffer + sz, size - sz);
|
||
|
|
||
|
sz += snprintf(buffer + sz, size - sz, ")\n");
|
||
|
}
|
||
|
|
||
|
return sz;
|
||
|
}
|