diff options
-rw-r--r-- | Makefile | 2 | ||||
-rw-r--r-- | Scope.c | 36 | ||||
-rw-r--r-- | Scope.h | 17 |
3 files changed, 54 insertions, 1 deletions
@@ -4,7 +4,7 @@ SRC := $(wildcard *.c) OBJ := $(patsubst %.c,%.o,$(patsubst %.cpp,%.o,$(SRC))) NAME := golem CFLAGS := -g -O0 -Wall -Wextra -std=c99 -pedantic -LDFLAGS := +LDFLAGS := -lxxhash all: $(NAME) @@ -0,0 +1,36 @@ +#include "Scope.h" +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <xxhash.h> + +Scope *scope_create(const Scope *parent) +{ + Scope *const scope = malloc(sizeof(Scope)); + if (scope == NULL) { + perror("scope_create"); + return NULL; + } + scope->used = 0; + scope->parent = parent; + return scope; +} + +int scope_insert(Scope *scope, const char *word, int value) +{ + if (scope->used >= SCOPE_WORD_MAX) { + fprintf(stderr, "scope full\n"); + return 1; + } + const XXH32_hash_t hash = XXH32(word, strlen(word), 0); + for (int i = 0; i < scope->used; i++) + if (scope->words_hash[i] == hash) { + fprintf(stderr, "shadowed word\n"); + return 1; + } + scope->words[scope->used] = word; + scope->values[scope->used] = value; + scope->words_hash[scope->used] = hash; + scope->used += 1; + return 0; +} @@ -0,0 +1,17 @@ +#pragma once +#include <xxhash.h> + +#define SCOPE_WORD_MAX 256 + +/* member strings are borrowed and shouldn't be freed by the node */ +typedef struct Scope Scope; +struct Scope { + int used; + const char *words[SCOPE_WORD_MAX]; + int values[SCOPE_WORD_MAX]; + XXH32_hash_t words_hash[SCOPE_WORD_MAX]; + const Scope *parent; +}; + +Scope *scope_create(const Scope *parent); +int scope_insert(Scope *scope, const char *word, int value); |