From: bylex Date: Wed, 2 Oct 2024 06:07:46 +0000 (+0200) Subject: Add basic assembler code X-Git-Url: https://git.bylex.cz/?a=commitdiff_plain;h=680802b20b3c26a0f51df502e1f87502e0fe9d60;p=maturita.git Add basic assembler code Assembler is still work in progress --- diff --git a/Makefile b/Makefile index 6a6f3b3..db9300c 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,7 @@ +CFLAGS = -g -w -O0 + all: int ass + int: $(CC) $(CFLAGS) interpreter.c -o interpreter ass: diff --git a/assembler.c b/assembler.c new file mode 100644 index 0000000..09bc341 --- /dev/null +++ b/assembler.c @@ -0,0 +1,99 @@ +#include +#include +#include +#include +#include + +#include "assembler.h" + + + +struct inst_t +{ + bool contains_instruction; + uint8_t instruction_code; + uint8_t params[3]; +} instruction_default = {false, 0, 0, 0, 0}; + +void parse_line(FILE** input_file) +{ + char line_buffer[256]; + + int token_count = 0; + char* token; + struct inst_t inst = instruction_default; + + fgets(line_buffer, 256, *input_file); + + if(line_buffer[0] == ';') + { + return; + } + else + { + inst.contains_instruction = true; + } + + token = strtok(line_buffer, " "); + while(token) + { + switch(token_count) + { + case 0: + // current token is instruction code + uint8_t i = 0; + while(i < N_INSTRUCTIONS - 1) + { + if(strcmp(token, opcodes_strings[i]) == 0) + { + inst.instruction_code = i; + break; + } + i++; + } + break; + case 1: + // current token is first parameter + inst.params[0] = (uint8_t)atoi(token); + break; + case 2: + // current token is second parameter + uint16_t token_int = atoi(token); + inst.params[1] = token_int; + break; + case 3: + // current token is third parameter + break; + } + token_count++; + token = strtok(NULL, " "); + } +} + +int main(int argc, char *argv[]) +{ + + if(argc <= 2 || argc >= 4) + { + printf("Usage: %s \n", argv[0]); + return 1; + } + + FILE* input_file = fopen(argv[1], "r"); + if(!input_file) + { + perror("Cannot open input file for reading\n"); + return 1; + } + + FILE* output_file = fopen(argv[2], "w"); + if(!output_file) + { + perror("Cannot open output file for writing\n"); + return 1; + } + while(!feof(input_file)) + { + parse_line(&input_file); + } +} diff --git a/assembler.h b/assembler.h new file mode 100644 index 0000000..22714f8 --- /dev/null +++ b/assembler.h @@ -0,0 +1,3 @@ +#include "common.h" + +char opcodes_strings[N_INSTRUCTIONS][4] = {"nop", "inc", "dec", "lod", "ldl", "sav", "swp", "jmp", "jez", "hlt", "pts", "pfs"}; diff --git a/common.h b/common.h new file mode 100644 index 0000000..cd94b24 --- /dev/null +++ b/common.h @@ -0,0 +1 @@ +#define N_INSTRUCTIONS 12