From 9fa48520c7f5b28d94ee7d3b6b61990f76dccaf4 Mon Sep 17 00:00:00 2001 From: Garritt McCune Date: Wed, 4 May 2022 22:58:06 -0500 Subject: [PATCH] Added support for 'labels' in the Scanner. --- includes/token.h | 1 + src/scanner.c | 37 +++++++++++++++++++++++++------------ 2 files changed, 26 insertions(+), 12 deletions(-) diff --git a/includes/token.h b/includes/token.h index 4e1b6c1..e01efa6 100644 --- a/includes/token.h +++ b/includes/token.h @@ -16,6 +16,7 @@ typedef enum { COMMA, STRING, IDENTIFIER, + LABEL, NUMBER, HEX, //Keywords diff --git a/src/scanner.c b/src/scanner.c index 48ffe8e..f842619 100644 --- a/src/scanner.c +++ b/src/scanner.c @@ -92,14 +92,18 @@ Token* ParseNumber(void) { while(!ScannerAtEnd() && isdigit(PeekScanner())) AdvanceScanner(); } - char* lexeme = calloc(Position - start + 1, sizeof(char)); + int length = Position - start; + + if (length == 0) return NULL; + + char* lexeme = calloc(sizeof(char), length); if (!lexeme) { fprintf(stderr, "Failed to calloc space for number.\n"); return NULL; } - memcpy(lexeme, &SourceCode[start], Position - start); + memcpy(lexeme, &SourceCode[start], length); if (base == 10) return CreateToken(NUMBER, lexeme); @@ -110,17 +114,19 @@ Token* ParseDirective(void) { int start = Position; while(!ScannerAtEnd() && PeekScanner() != ' ' && PeekScanner() != '\n') AdvanceScanner(); - - if (start == Position) return NULL; - char* directive = calloc(Position - start + 1, sizeof(char)); + int length = Position - start; + + if (length == 0) return NULL; + + char* directive = calloc(sizeof(char), length); if (!directive) { fprintf(stderr, "Failed to calloc for the assmebler directive.\n"); return NULL; } - memcpy(directive, &SourceCode[start], Position - start); + memcpy(directive, &SourceCode[start], length); if (strcmp(directive, ".db") == 0) { return CreateToken(DB, directive); @@ -154,8 +160,12 @@ Token* ParseString(void) { AdvanceScanner(); } - char* lexeme = calloc(Position - start, sizeof(char)); - memcpy(lexeme, &SourceCode[start], Position - start); + int length = Position - start; + + if (length == 0) return NULL; + + char* lexeme = calloc(sizeof(char), length); + memcpy(lexeme, &SourceCode[start], length); AdvanceScanner(); //Consume the trailing double quote. @@ -171,14 +181,17 @@ Token* ParseIdentifier(void) { AdvanceScanner(); } - if (Position - start == 0) return NULL; + int length = Position - start; + + if (length == 0) return NULL; - char* lexeme = calloc(Position - start, sizeof(char)); - TokenType type; - memcpy(lexeme, &SourceCode[start], Position - start); + TokenType type; + char* lexeme = calloc(sizeof(char), length); + memcpy(lexeme, &SourceCode[start], length); if (IsOpcode(lexeme, &type)) return CreateToken(type, lexeme); if (IsRegister(lexeme, &type)) return CreateToken(type, lexeme); + if (lexeme[length - 1] == ':') return CreateToken(LABEL, lexeme); return CreateToken(IDENTIFIER, lexeme); }