From d25c1a379a67e489ecfbf181b361f13feb2ca12d Mon Sep 17 00:00:00 2001 From: Danila Fedorin Date: Fri, 16 Mar 2018 22:11:05 -0700 Subject: [PATCH] Add function to search for reserved operators. --- CMakeLists.txt | 2 +- include/reserved.h | 41 +++++++++++++++++++++++++++++++++++++++++ src/reserved.c | 21 +++++++++++++++++++++ 3 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 include/reserved.h create mode 100644 src/reserved.c diff --git a/CMakeLists.txt b/CMakeLists.txt index 6377365..2bdf8ae 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,7 +8,7 @@ project(libabacus) add_compile_options(-pedantic -Wall) -add_library(abacus STATIC src/lexer.c src/util.c src/table.c src/parser.c src/libabacus.c src/tree.c src/debug.c src/parsetype.c) +add_library(abacus STATIC src/lexer.c src/util.c src/table.c src/parser.c src/libabacus.c src/tree.c src/debug.c src/parsetype.c src/reserved.c) add_executable(libabacus src/main.c) add_subdirectory(external/liblex) diff --git a/include/reserved.h b/include/reserved.h new file mode 100644 index 0000000..f4f93e7 --- /dev/null +++ b/include/reserved.h @@ -0,0 +1,41 @@ +#ifndef LIBABACUS_RESERVED_H +#define LIBABACUS_RESERVED_H + +#include "result.h" +#include "parsetype.h" +#include "tree.h" +#include "value.h" +#include "libabacus.h" + +/** + * Struct that represents a reserved operator that contains + * interpreter-internal behavior. + */ +struct libab_reserved_operator_s { + /** + * The reserved operator. + */ + const char* op; + /** + * The precedence of this operator. + */ + int precedence; + /** + * The associativity of this operator. + */ + int associativity; +}; + +typedef struct libab_reserved_operator_s libab_reserved_operator; + +/** + * Attempts to find a reserved operator with the given name. + * This function operates under the assumption that there are + * few reserved operators in libabacus. As such, it does effectively + * a polynomial time search - strcmp for every element until the operator is found. + * @param name the name to search for. + * @return the reserved operator, if it is found. + */ +const libab_reserved_operator* libab_find_reserved_operator(const char* name); + +#endif diff --git a/src/reserved.c b/src/reserved.c new file mode 100644 index 0000000..c14f9ba --- /dev/null +++ b/src/reserved.c @@ -0,0 +1,21 @@ +#include "reserved.h" +#include "string.h" + +static const libab_reserved_operator libab_reserved_operators[] = { + { + "=", /* Assignment */ + 0, /* Lowest precedence */ + 1 /* Right associative, a = b = 6 should be a = (b = 6) */ + } +}; + +const libab_reserved_operator* libab_find_reserved_operator(const char* name) { + static const size_t element_count = + sizeof(libab_reserved_operators) / sizeof(libab_reserved_operator); + size_t i; + for(i = 0; i < element_count; i++) { + if(strcmp(name, libab_reserved_operators[i].op) == 0) + return &libab_reserved_operators[i]; + } + return NULL; +}