diff --git a/scanner.c b/scanner.c index 5b2c0e4..846b66d 100644 --- a/scanner.c +++ b/scanner.c @@ -4,6 +4,30 @@ #include #include +typedef struct { + char* keyword; + TokenType type; +} KeywordPair; + +KeywordPair keywords[KEYWORD_COUNT] = { + { "and", AND }, + { "class", CLASS }, + { "else", ELSE }, + { "false", FALSE }, + { "for", FOR }, + { "fun", FUN }, + { "if", IF }, + { "nil", NIL }, + { "or", OR }, + { "print", PRINT }, + { "return", RETURN }, + { "super", SUPER }, + { "this", THIS }, + { "true", TRUE }, + { "var", VAR }, + { "while", WHILE } +}; + const char* source_code; //Start and Current hold the offsets that index into the string source_code. int start; //Points to the first character in the lexeme being scanned. @@ -23,6 +47,7 @@ void ParseString(TokenList *); void ParseNumber(TokenList *); void ParseIdentifier(TokenList *); int IsAlpha(char c); +KeywordPair* Get(char*); TokenList* ScanTokens(const char* source) { if (!source) return NULL; @@ -255,11 +280,29 @@ char PeekNext() { void ParseIdentifier(TokenList * list) { while(IsAlpha(Peek())) Advance(); - AddTokenToList(Identifier, &source_code[start], current - start, list); + char* lexeme = calloc(sizeof(char*), (current - start + 1)); + + snprintf(lexeme, current - start + 1, "%s", &source_code[start]); + + KeywordPair* result = Get(lexeme); + + if (result) AddTokenToList(result->type, &source_code[start], current - start, list); + else AddTokenToList(Identifier, &source_code[start], current - start, list); + + free(lexeme); } int IsAlpha(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c == '_'); +} + +KeywordPair* Get(char* text) { + if (!text) return NULL; + + for (int i = 0; i < KEYWORD_COUNT; i++) + if (strcmp(text, keywords[i].keyword) == 0) return &keywords[i]; + + return NULL; } \ No newline at end of file diff --git a/scanner.h b/scanner.h index 1c981f7..f476881 100644 --- a/scanner.h +++ b/scanner.h @@ -2,6 +2,7 @@ #define SCANNER_H #define DEFAULT_TOKENLIST_SIZE 32 +#define KEYWORD_COUNT 16 typedef enum { //Single-character tokens