diff options
| author | hachem <im@hachem.wtf> | 2026-08-30 17:57:24 +0200 |
|---|---|---|
| committer | hachem <im@hachem.wtf> | 2026-08-30 17:57:24 +0200 |
| commit | ea2ebf063cc6a87c73068a3e8b06fb744655159f (patch) | |
| tree | fa928314c3618262c48501265cb56bc7b00c4b66 /src/codegen/nasm.c | |
| parent | 542e15041ea1d93e74a06c588f16ce7956d6a9bb (diff) | |
add: start code gen
Diffstat (limited to 'src/codegen/nasm.c')
| -rw-r--r-- | src/codegen/nasm.c | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/src/codegen/nasm.c b/src/codegen/nasm.c new file mode 100644 index 0000000..0782ee1 --- /dev/null +++ b/src/codegen/nasm.c @@ -0,0 +1,48 @@ +#include <stdio.h> +#include <stddef.h> + +#include "codegen/nasm.h" + +static void emit_consts(struct Program* program, FILE* out) +{ + for (size_t i = 0; i < program->const_count; i += 1) + { + struct ConstDecl decl = program->consts[i]; + fprintf(out, "%.*s equ %.*s\n", + (int)decl.name.length, decl.name.start, + (int)decl.value.length, decl.value.start); + } +} + +static void emit_data(struct Program* program, FILE* out) +{ + fprintf(out, "section .data\n"); + + for (size_t i = 0; i < program->data_count; i += 1) + { + struct DataDecl decl = program->data_decls[i]; + + // the value lexeme keeps its surrounding double quotes; NASM backtick + // strings interpret the same escapes, so re-wrap the inner content + fprintf(out, "%.*s: db `%.*s`\n", + (int)decl.name.length, decl.name.start, + (int)(decl.value.length - 2), decl.value.start + 1); + fprintf(out, ".len equ $ - %.*s\n", + (int)decl.name.length, decl.name.start); + } +} + +void generate_nasm(struct Program* program, FILE* out) +{ + if (program->const_count > 0) + { + emit_consts(program, out); + fprintf(out, "\n"); + } + + emit_data(program, out); + fprintf(out, "\n"); + + fprintf(out, "section .text\n"); + fprintf(out, "global _start\n"); +} |
