From 6c0e03f824a2a218a28a066d07da96e9b5cb99a5 Mon Sep 17 00:00:00 2001 From: cozis Date: Sat, 2 Apr 2022 01:37:52 +0200 Subject: [PATCH] if-else chain now is an iteration over a table --- src/compiler/parse.c | 76 ++++++++++++++++---------------------------- 1 file changed, 27 insertions(+), 49 deletions(-) diff --git a/src/compiler/parse.c b/src/compiler/parse.c index da8cec4..b52a3a8 100644 --- a/src/compiler/parse.c +++ b/src/compiler/parse.c @@ -309,62 +309,40 @@ static Token *tokenize(Source *src, BPAlloc *alloc, Error *error) // Determine the token - #define matchop(str, len, const_str) \ - (len == sizeof(const_str)-1 && !strncmp(str, const_str, sizeof(const_str)-1)) + static const struct { + TokenKind kind; + int size; + const char *text; + } optable[] = { + { TADD, 1, "+" }, + { TSUB, 1, "-" }, + { TMUL, 1, "*" }, + { TDIV, 1, "/" }, + { TEQL, 2, "==" }, + { TNQL, 2, "!=" }, + { TLSS, 1, "<" }, + { TLEQ, 2, "<=" }, + { TGRT, 1, ">" }, + { TGEQ, 2, ">=" }, + { TASS, 1, "=" }, + }; - if(matchop(str + tok->offset, tok->length, "+")) - { - tok->kind = TADD; - } - else if(matchop(str + tok->offset, tok->length, "-")) - { - tok->kind = TSUB; - } - else if(matchop(str + tok->offset, tok->length, "*")) - { - tok->kind = TMUL; - } - else if(matchop(str + tok->offset, tok->length, "/")) - { - tok->kind = TDIV; - } - else if(matchop(str + tok->offset, tok->length, "==")) - { - tok->kind = TEQL; - } - else if(matchop(str + tok->offset, tok->length, "!=")) - { - tok->kind = TNQL; - } - else if(matchop(str + tok->offset, tok->length, "<")) - { - tok->kind = TLSS; - } - else if(matchop(str + tok->offset, tok->length, "<=")) - { - tok->kind = TLEQ; - } - else if(matchop(str + tok->offset, tok->length, ">")) - { - tok->kind = TGRT; - } - else if(matchop(str + tok->offset, tok->length, ">=")) - { - tok->kind = TGEQ; - } - else if(matchop(str + tok->offset, tok->length, "=")) - { - tok->kind = TASS; - } - else + _Bool found = 0; + for(unsigned int i = 0; i < sizeof(optable)/sizeof(*optable); i += 1) + if(optable[i].size == tok->length && !strncmp(optable[i].text, str + tok->offset, tok->length)) + { + found = 1; + tok->kind = optable[i].kind; + break; + } + + if(found == 0) { // Not a known operator. tok->kind = str[tok->offset]; tok->length = 1; i = tok->offset + 1; } - - #undef matchop } else {