diff --git a/src/parser.c b/src/parser.c index 6902d5e..0d1d9f7 100644 --- a/src/parser.c +++ b/src/parser.c @@ -1,11 +1,14 @@ #include "../includes/parser.h" #include +#include #include #ifndef HIGHMEMORY #define HIGHMEMORY 65535 //64KiB - 1 AKA 0xFFFF #endif +#define HEAPTOP HIGHMEMORY + typedef struct { Token* token; int address; @@ -18,10 +21,12 @@ int CurrentToken = 0; void AddSymbol(Token*, int); void PrintSymbols(void); void HandleOperation(void); +void HandleAssemblerDirective(void); void AdvanceParser(void); Token* PeekToken(void); int ParserAtEnd(void); int Expect(int, ...); +int ExpectTokenClass(int, ...); Token* GetSymbol(char*); List* SymbolsTable; unsigned int ProgramCounter = 0; @@ -53,6 +58,9 @@ void ParseTokens(List* tokens) { ProgramCounter++; HandleOperation(); } + else if (t->token_class == Directive) { + HandleAssemblerDirective(); + } AdvanceParser(); @@ -65,6 +73,37 @@ void ParseTokens(List* tokens) { printf("Program Counter: %d\n", ProgramCounter); } +void HandleAssemblerDirective(void) { + Token* token = PeekToken(); + AdvanceParser(); + + if (token->type == DB) { + token = PeekToken(); + if (!Expect(1, IDENTIFIER)) { + fprintf(stderr, "Expected identifier on line %d\n", PeekToken()->line); + exit(1); + } + //This should be done only after the directive is parsed fully. + AddSymbol(token, HEAPTOP); + + if (PeekToken()-> type == STRING) { + AdvanceParser(); + + if (PeekToken()-> type == COMMA) { + AdvanceParser(); + if (PeekToken()-> type != NUMBER) { + fprintf(stderr, "Expected string termination byte on line %d\n", PeekToken()->line); + exit(1); + } + // else { + // //Setup string and return + // return; + // } + } + } + } +} + void HandleOperation(void) { const Instruction* inst = GetOpcodeDetails(PeekToken()->type); @@ -76,6 +115,11 @@ void HandleOperation(void) { if (inst->parameter_one && PeekToken()->token_class > 0) { printf("Matched '%s'\n", PeekToken()->lexeme); + + if (inst->parameter_one == Reg) { + //Encode the register number here. + } + AdvanceParser(); } @@ -98,23 +142,43 @@ void HandleOperation(void) { } } -// int Expect(int count, ...) { -// va_list list; +int ExpectTokenClass(int count, ...) { + va_list list; + Token* token = PeekToken(); -// va_start(list, count); + va_start(list, count); -// for(int i = 0; i < count; i++) { -// if (va_arg(list, TokenClass) == PeekToken()->token_class) { -// va_end(list); -// //advance -// return 1; -// } -// } + for(int i = 0; i < count; i++) { + if (va_arg(list, TokenClass) == token->token_class) { + va_end(list); + AdvanceParser(); + return 1; + } + } -// va_end(list); + va_end(list); -// return 0; -// } + return 0; +} + +int Expect(int count, ...) { + va_list list; + Token* token = PeekToken(); + + va_start(list, count); + + for(int i = 0; i < count; i++) { + if (va_arg(list, TokenType) == token->type) { + va_end(list); + AdvanceParser(); + return 1; + } + } + + va_end(list); + + return 0; +} void PrintSymbols(void) { printf("-----SYMBOLS-----\n");