Not the cleanest way to do this but added in keyword detection.

This commit is contained in:
2022-02-17 21:52:26 +00:00
parent c55a3434de
commit 227d566261
2 changed files with 45 additions and 1 deletions
+44 -1
View File
@@ -4,6 +4,30 @@
#include <string.h>
#include <ctype.h>
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;
}
+1
View File
@@ -2,6 +2,7 @@
#define SCANNER_H
#define DEFAULT_TOKENLIST_SIZE 32
#define KEYWORD_COUNT 16
typedef enum {
//Single-character tokens