all repos — xyw @ 2c85cdfa5445444a0dfbf7f655c7d616b17c0bb4

A minimal virtual machine and assembler for terminals.

Implemented reference patching.
h3rald h3rald@h3rald.com
Fri, 28 Nov 2025 14:31:14 +0100
commit

2c85cdfa5445444a0dfbf7f655c7d616b17c0bb4

parent

627854f1c9c38c480edd6764bd34ea556cf3309f

1 files changed, 38 insertions(+), 8 deletions(-)

jump to
M xywasm.cxywasm.c

@@ -243,23 +243,28 @@ }

return 0; } -// Write raw bytecode data -static inline void write(xyw_short val) +static inline void write(xyw_short addr, xyw_short val) { if (val > 0xff) { - data[ptr++] = val & 0xFF; - data[ptr++] = (val >> 8) & 0xFF; + data[addr] = val & 0xFF; + data[addr] = (val >> 8) & 0xFF; return; } - data[ptr++] = (xyw_byte)val; + data[addr] = (xyw_byte)val; +} + +// Append raw bytecode data +static inline void append(xyw_short val) +{ + write(ptr++, val); } // Encode a push instruction static inline void push(xyw_short val) { - (val > 0xff) ? write(PSH | MODE_W) : write(PSH); - write(val); + (val > 0xff) ? append(PSH | MODE_W) : append(PSH); + append(val); } static int macro(xyw_context *ctx, char *name, char *contents)

@@ -491,12 +496,15 @@ // TODO: Remove

char bits[9]; byte_to_binary(opcode, bits); printf("Instruction:\t%s\t(%02X - %s)\n", token, opcode, bits); - write(opcode); token_type = TOKEN_TYPE_INSTRUCTION; token_value = opcode; if (!directive) { push(opcode); + } + else + { + append(opcode); } return 0; }

@@ -989,6 +997,28 @@ if (!fp)

{ fprintf(stderr, "Could not open output file for writing"); return -1; + } + // Patch labels + for (xyw_short i = 0; i < refcount; i++) + { + xyw_symbol *refsym = &refs[i]; + int symindex = find_symbol(refsym->name); + if (symindex == -1) + { + fprintf(stderr, "Undefined symbol: %s\n", refsym->name); + fclose(fp); + return -1; + } + xyw_symbol *defsym = &symbols[symindex]; + if (defsym->type != SYMBOL_TYPE_LABEL) + { + fprintf(stderr, "Invalid reference to non-label symbol: %s\n", refsym->name); + fclose(fp); + return -1; + } + // Patch the data at the reference address with the label address + write(refsym->address, defsym->address); + printf("Patched:\t%s -> $%04X @ $%04X\n", defsym->name, defsym->address, refsym->address); } fwrite(data, 1, ptr, fp); fclose(fp);