From dac983b68470412214ca821d6018e63c58b05845 Mon Sep 17 00:00:00 2001 From: Maxwell Jeffress Date: Wed, 21 Jan 2026 11:38:37 +1100 Subject: [PATCH] Update compiler --- src/compiler.c | 41 +++++++++++++++++++++++++++++++++++++++-- src/compiler.h | 2 ++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/src/compiler.c b/src/compiler.c index 6934c41..10f5fdb 100644 --- a/src/compiler.c +++ b/src/compiler.c @@ -1,16 +1,53 @@ #include "compiler.h" +#include "interpreter.h" #include "types.h" #include "include/estr.h" +#include char* compileGroundProgram(GroundProgram* program) { Estr start = CREATE_ESTR("global _start\nsection .text\n_start:\n"); Estr data = CREATE_ESTR("section .rodata\n"); + // Create data section for (size_t i = 0; i < program->size; i++) { - switch (program->instructions[i].type) { + + } + + // Generate assembly + for (size_t i = 0; i < program->size; i++) { + GroundInstruction gi = program->instructions[i]; + switch (gi.type) { case END: { + if (gi.args.length < 1) { + runtimeError(TOO_FEW_ARGS, "Expecting 1 arg for end instruction", &gi, i); + } + if (gi.args.length > 1) { + runtimeError(TOO_MANY_ARGS, "Expecting 1 arg for end instruction", &gi, i); + } + if (gi.args.args[0].type != VALUE) { + runtimeError(ARG_TYPE_MISMATCH, "Expecting an Int for end instruction", &gi, i); + } + if (gi.args.args[0].value.value.type != INT) { + runtimeError(ARG_TYPE_MISMATCH, "Expecting an Int for end instruction", &gi, i); + } + + int64_t bigretint = gi.args.args[0].value.value.data.intVal; + int retint; + if (bigretint > 255) { + retint = 255; + } + else if (bigretint < 0) { + retint = 0; + } + else { + retint = bigretint; + } + char retstr[8]; + snprintf(retstr, sizeof(retstr), "%d", retint); APPEND_ESTR(start, " mov rax, 60\n"); - APPEND_ESTR(start, " mov rdi, 0\n"); + APPEND_ESTR(start, " mov rdi, "); + APPEND_ESTR(start, retstr); + APPEND_ESTR(start, "\n"); APPEND_ESTR(start, " syscall\n"); break; } diff --git a/src/compiler.h b/src/compiler.h index 366671e..ffda11e 100644 --- a/src/compiler.h +++ b/src/compiler.h @@ -1,3 +1,5 @@ #include "types.h" +#include "interpreter.h" char* compileGroundProgram(GroundProgram* program); +[[noreturn]] void runtimeError(GroundRuntimeError error, char* what, GroundInstruction* where, int whereLine);