summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorkdx <kdx@42l.fr>2023-03-14 03:11:14 +0100
committerkdx <kdx@42l.fr>2023-03-14 03:11:14 +0100
commitb94b63bd30541f5311f20ac5f08f7717c3f9a672 (patch)
tree6f7c0ecc8516d857627ef14248fe4504d9066168
parentf76ff3d3300760efead590bef95f0770bf2860af (diff)
downloadgolem-b94b63bd30541f5311f20ac5f08f7717c3f9a672.tar.gz
lex keywords
-rw-r--r--lexer.c20
-rw-r--r--slice.c9
-rw-r--r--slice.h1
-rw-r--r--token.h6
4 files changed, 34 insertions, 2 deletions
diff --git a/lexer.c b/lexer.c
index 803949e..a3394be 100644
--- a/lexer.c
+++ b/lexer.c
@@ -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;
}
diff --git a/slice.c b/slice.c
index 8640d0f..f658124 100644
--- a/slice.c
+++ b/slice.c
@@ -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);
+}
diff --git a/slice.h b/slice.h
index 9669132..aa4ed4d 100644
--- a/slice.h
+++ b/slice.h
@@ -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);
diff --git a/token.h b/token.h
index 9c6de47..5934f7b 100644
--- a/token.h
+++ b/token.h
@@ -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;