Add compiler #14
@@ -1,16 +1,53 @@
|
|||||||
#include "compiler.h"
|
#include "compiler.h"
|
||||||
|
#include "interpreter.h"
|
||||||
#include "types.h"
|
#include "types.h"
|
||||||
#include "include/estr.h"
|
#include "include/estr.h"
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
char* compileGroundProgram(GroundProgram* program) {
|
char* compileGroundProgram(GroundProgram* program) {
|
||||||
Estr start = CREATE_ESTR("global _start\nsection .text\n_start:\n");
|
Estr start = CREATE_ESTR("global _start\nsection .text\n_start:\n");
|
||||||
Estr data = CREATE_ESTR("section .rodata\n");
|
Estr data = CREATE_ESTR("section .rodata\n");
|
||||||
|
|
||||||
|
// Create data section
|
||||||
for (size_t i = 0; i < program->size; i++) {
|
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: {
|
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 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");
|
APPEND_ESTR(start, " syscall\n");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
#include "types.h"
|
#include "types.h"
|
||||||
|
#include "interpreter.h"
|
||||||
|
|
||||||
char* compileGroundProgram(GroundProgram* program);
|
char* compileGroundProgram(GroundProgram* program);
|
||||||
|
[[noreturn]] void runtimeError(GroundRuntimeError error, char* what, GroundInstruction* where, int whereLine);
|
||||||
|
|||||||
Reference in New Issue
Block a user