Use hashmap for keyword lookup

This commit is contained in:
Rui Ueyama 2020-09-03 22:55:50 +09:00
parent 655954e301
commit f6944133d2
2 changed files with 32 additions and 24 deletions

10
parse.c
View File

@ -1479,6 +1479,9 @@ static void gvar_initializer(Token **rest, Token *tok, Obj *var) {
// Returns true if a given token represents a type.
static bool is_typename(Token *tok) {
static HashMap map;
if (map.capacity == 0) {
static char *kw[] = {
"void", "_Bool", "char", "short", "int", "long", "struct", "union",
"typedef", "enum", "static", "extern", "_Alignas", "signed", "unsigned",
@ -1488,9 +1491,10 @@ static bool is_typename(Token *tok) {
};
for (int i = 0; i < sizeof(kw) / sizeof(*kw); i++)
if (equal(tok, kw[i]))
return true;
return find_typedef(tok);
hashmap_put(&map, kw[i], (void *)1);
}
return hashmap_get2(&map, tok->loc, tok->len) || find_typedef(tok);
}
// asm-stmt = "asm" ("volatile" | "inline")* "(" string-literal ")"

View File

@ -156,6 +156,9 @@ static int read_punct(char *p) {
}
static bool is_keyword(Token *tok) {
static HashMap map;
if (map.capacity == 0) {
static char *kw[] = {
"return", "if", "else", "for", "while", "int", "sizeof", "char",
"struct", "union", "short", "long", "void", "typedef", "_Bool",
@ -167,9 +170,10 @@ static bool is_keyword(Token *tok) {
};
for (int i = 0; i < sizeof(kw) / sizeof(*kw); i++)
if (equal(tok, kw[i]))
return true;
return false;
hashmap_put(&map, kw[i], (void *)1);
}
return hashmap_get2(&map, tok->loc, tok->len);
}
static int read_escaped_char(char **new_pos, char *p) {