Created the skeleton for the parser.

This commit is contained in:
2022-02-07 15:33:58 +00:00
parent 7c6e5e1541
commit 3d4ab57f05
5 changed files with 74 additions and 3 deletions
+13
View File
@@ -0,0 +1,13 @@
#ifndef PARSER_H
#define PARSER_H
#include "list.h"
typedef struct {
char* name;
int address;
} Symbol;
void ParseTokens(List*);
#endif
-2
View File
@@ -1,5 +1,3 @@
; comments are ignored
; This is a very simple test file for an assemblier.
.org 0x100
.db msg "Hello, world!", 0
+5
View File
@@ -3,6 +3,7 @@
#include <string.h>
#include "../includes/list.h"
#include "../includes/lexer.h"
#include "../includes/parser.h"
typedef struct {
char *opcode;
@@ -38,6 +39,10 @@ int main(int argc, char* args[]) {
while((bytes_read = getline(&line, &len, file)) != -1) {
List* tokens = GetTokensFromLine(line);
if (line_number == 1 || line_number == 2) {
ParseTokens(tokens);
}
for (int i = 0; i < tokens->size; i++) {
Token* t = (Token*) tokens->content[i];
+1 -1
View File
@@ -6,7 +6,7 @@ char *opcodes[OPCODECOUNT] = {
"sub",
"jz",
"int",
"hlt",
"yld",
"ret"
};
+55
View File
@@ -0,0 +1,55 @@
#include "../includes/parser.h"
#include "../includes/lexer.h"
#include <stdio.h>
#include <stdlib.h>
static List* SymbolsTable;
static unsigned int program_counter = 0;
void ProcessDirective(List*);
void ProcessVariableDeclaration(List*);
void ParseTokens(List* tokens) {
for(int i = 0; i < tokens->size; i++) {
if (((Token *) tokens->content[i])->type == TK_Directive){
ProcessDirective(tokens);
}
}
}
void ProcessDirective(List* tokens) {
if (tokens->size < 2) {
printf("Directives failed\n");
return;
}
Token* directive = (Token *) tokens->content[0];
if (strcmp(".org", directive->value) == 0) {
Token* address_start = (Token*) tokens->content[1];
if (address_start->type == TK_Number) {
long address = strtol(address_start->value, NULL, 10);
printf("Address starting at '%ld'\n", address);
}
else if (address_start->type == TK_Hex) {
long address = strtol(address_start->value, NULL, 16);
printf("Setting address to '%ld'\n", address);
}
}
if (strcmp(".db", directive->value) == 0) {
ProcessVariableDeclaration(tokens);
}
}
void ProcessVariableDeclaration(List* tokens) {
if (tokens->size < 3) {
printf("Invalid variable delcaration\n");
return;
}
Token* symbol_token = (Token*) tokens->content[1];
Token* string_literal = (Token*) tokens->content[2];
printf("Found string literal.\n");
printf("Name '%s' value: '%s'\n", symbol_token->value, string_literal->value);
}