summaryrefslogtreecommitdiff
path: root/core/symbol.c
diff options
context:
space:
mode:
Diffstat (limited to 'core/symbol.c')
-rw-r--r--core/symbol.c130
1 files changed, 130 insertions, 0 deletions
diff --git a/core/symbol.c b/core/symbol.c
new file mode 100644
index 0000000..daa4411
--- /dev/null
+++ b/core/symbol.c
@@ -0,0 +1,130 @@
+/*
+ * Copyright (c) 2026, Chloe M.
+ * Provided under the BSD-3 clause
+ */
+
+#include <stdint.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include "cescal/symbol.h"
+
+/*
+ * Push a symbol into a symbol table
+ *
+ * @symtab: Symbol table to push to
+ * @symbol: Symbol to push
+ *
+ * Returns zero on success
+ */
+static int
+symbol_table_push(struct symbol_table *symtab, struct symbol *symbol)
+{
+ if (symtab == NULL || symbol == NULL) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ symbol->next = NULL;
+ if (symtab->head == NULL || symtab->tail == NULL) {
+ symtab->head = symbol;
+ symtab->tail = symbol;
+ } else {
+ symtab->head->next = symbol;
+ symtab->head = symbol;
+ }
+
+ return 0;
+}
+
+int
+symbol_table_init(struct symbol_table *symtab)
+{
+ if (symtab == NULL) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ symtab->head = NULL;
+ symtab->tail = NULL;
+ return 0;
+}
+
+int
+symbol_allocate(struct symbol_table *symtab, const char *name,
+ symtype_t type, struct symbol **res)
+{
+ struct symbol *symbol;
+
+ if (symtab == NULL || name == NULL) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ if (res == NULL) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ symbol = malloc(sizeof(*symbol));
+ if (symbol == NULL) {
+ errno = -ENOMEM;
+ return -1;
+ }
+
+ symbol->name = strdup(name);
+ symbol->type = type;
+ if (symbol_table_push(symtab, symbol) < 0) {
+ free(symbol);
+ return -1;
+ }
+
+ *res = symbol;
+ return 0;
+}
+
+void
+symbol_table_destroy(struct symbol_table *symtab)
+{
+ struct symbol *symbol, *tmp;
+
+ if (symtab == NULL) {
+ return;
+ }
+
+ symbol = symtab->tail;
+ while (symbol != NULL) {
+ tmp = symbol;
+ if (tmp->name != NULL)
+ free(tmp->name);
+ free(tmp);
+ symbol = symbol->next;
+ }
+}
+
+struct symbol *
+symbol_byname(struct symbol_table *symtab, const char *name)
+{
+ struct symbol *symbol;
+
+ if (symtab == NULL || name == NULL) {
+ return NULL;
+ }
+
+ symbol = symtab->head;
+ while (symbol != NULL) {
+ if (*symbol->name != *name) {
+ symbol = symbol->next;
+ continue;
+ }
+
+ if (strcmp(symbol->name, name) == 0) {
+ return symbol;
+ }
+
+ symbol = symbol->next;
+ }
+
+ return NULL;
+}