diff options
author | kdx <kdx@42l.fr> | 2023-03-14 03:11:14 +0100 |
---|---|---|
committer | kdx <kdx@42l.fr> | 2023-03-14 03:11:14 +0100 |
commit | b94b63bd30541f5311f20ac5f08f7717c3f9a672 (patch) | |
tree | 6f7c0ecc8516d857627ef14248fe4504d9066168 | |
parent | f76ff3d3300760efead590bef95f0770bf2860af (diff) | |
download | golem-b94b63bd30541f5311f20ac5f08f7717c3f9a672.tar.gz |
lex keywords
-rw-r--r-- | lexer.c | 20 | ||||
-rw-r--r-- | slice.c | 9 | ||||
-rw-r--r-- | slice.h | 1 | ||||
-rw-r--r-- | token.h | 6 |
4 files changed, 34 insertions, 2 deletions
@@ -76,11 +76,27 @@ lexer(Slice slice) continue; } - // Word token. + // Word token, and keywords by extension. if (iswordy(slice.str[i])) { Slice word = slice_match(slice_sub(slice, i, slice.end), iswordy); - token_append(&toks, token_create(word, TOK_NUMBER)); + + // Keywords. + unsigned int type = TOK_WORD; + if (slice_equal(word, slice_from_str("while"))) + type = TOK_KW_WHILE; + else if (slice_equal(word, slice_from_str("if"))) + type = TOK_KW_IF; + else if (slice_equal(word, slice_from_str("else"))) + type = TOK_KW_ELSE; + else if (slice_equal(word, slice_from_str("local"))) + type = TOK_KW_LOCAL; + else if (slice_equal(word, slice_from_str("return"))) + type = TOK_KW_RETURN; + else if (slice_equal(word, slice_from_str("global"))) + type = TOK_KW_GLOBAL; + + token_append(&toks, token_create(word, type)); i = word.end; continue; } @@ -26,3 +26,12 @@ slice_sub(Slice src, int begin, int end) { return (Slice){ src.str, begin, end }; } + +int +slice_equal(Slice s0, Slice s1) +{ + if (s0.end - s0.begin != s1.end - s1.begin) + return 0; + return 0 == + strncmp(s0.str + s0.begin, s1.str + s1.begin, s0.end - s0.begin); +} @@ -9,3 +9,4 @@ typedef struct { Slice slice_print(Slice slice); Slice slice_from_str(char *str); Slice slice_sub(Slice src, int begin, int end); +int slice_equal(Slice s0, Slice s1); @@ -15,6 +15,12 @@ enum { TOK_CHARACTER = 'a', TOK_STRING = 's', TOK_WORD = 'w', + TOK_KW_LOCAL = 'L', + TOK_KW_GLOBAL = 'G', + TOK_KW_IF = 'I', + TOK_KW_ELSE = 'E', + TOK_KW_WHILE = 'W', + TOK_KW_RETURN = 'R', }; typedef struct Token Token; |