Wednesday, 18 November 2026

🦆Part 3 — Backends: C Transpiler and 16-bit NASM

The C backend

The C backend is the simpler of the two. It emits C source and lets gcc do the hard work.

Structure:

  • gen_c.c — top-level entry: emits preamble, structs, forward decls, globals, function definitions, then main().
  • gen_c_stmt.c — statements (DIM, ASSIGN, IF, WHILE, PRINT, etc.).
  • gen_c_expr.c — expressions (arithmetic, function calls, field access, array access).
  • gen_c.h — CGen state struct threaded through all emitters.

The runtime is a C file (runtime_c.c) that’s compiled into a string literal at build time and injected into every generated .c file. It provides _check_bounds, sys_open, sys_read, etc.

Key design decisions:

  1. All state is in a CGen struct. No globals. This makes reentrancy possible (though not currently used) and makes threading state through emitters explicit.

  2. Type mapping is done via static inline functions in gen_c.h — no separate TU needed.

  3. Array accesses get bounds checks via a runtime helper:

    buf[_check_bounds(i, 16, "buf")]
    

    The helper prints an error and calls exit(1) on violation.

  4. String assignment uses strcpy, comparison uses strcmp. The typechecker ensures STRING ops only happen where they’re valid.

  5. Struct field access emits .field for variables, ->field for params. The codegen knows which is which because it tracks current_function and checks the param list.

The NASM backend

The NASM backend is where the real engineering lives. Every operation must be expressed in 16-bit x86, with no libc, no linker, no relocations — just a flat binary loaded at 0x100.

Structure:

  • gen_nasm.c — entry point, string pool, symbol lookup, program emission.
  • gen_nasm_stmt.c — statements.
  • gen_nasm_expr.c — expressions.
  • gen_nasm_data.c — data segment emission, struct field offset lookup.
  • runtime_com.inc — runtime library (print, read, copy, etc.).
  • fixed.inc — Q16:16 fixed-point math.
  • fileio.inc — DOS file I/O wrappers.

Key design decisions:

  1. Every value lives in AX (and DX for FLOAT). This is a naive register allocation strategy — no spilling, no liveness analysis. It’s slow but correct.

  2. Binary operations use the stack:

    ; evaluate left into AX
    push dx
    push ax
    ; evaluate right into AX
    push dx
    push ax
    pop bx      ; right low
    pop cx      ; right high
    pop ax      ; left low
    pop dx      ; left high
    ; now DX:AX = left, CX:BX = right
    
  3. Q16:16 fixed-point arithmetic — no floating point unit on 8086, so all “floats” are stored as 32-bit fixed-point (16.16). Addition is add/adc. Multiplication and division are hand-written 32-bit signed routines in fixed.inc, each ~60 lines of assembly.

  4. String constants live in a string pool — deduplicated, emitted at the end of the binary, referenced as str_N.

  5. Everything is in a .COM file — flat binary, loaded at 0x100, no relocations. org 0x100 at the top.

  6. Runtime library is .inc-included — no linking. The %include directives pull in runtime_com.inc, fixed.inc, fileio.inc at assembly time.

The SERIALIZE / DESERIALIZE byte layout

Both backends implement a locked byte layout for struct serialization:

Field type Bytes
INT 2 (little-endian)
BOOL 2 (little-endian)
FLOAT (Q16:16) 4 (little-endian)
CHAR 1
STRING 256 (fixed-size, null-padded)

The layout is documented in both gen_c_stmt.c and gen_nasm_stmt.c, and it’s the contract that allows a .dkb program to serialize a struct on the C backend and deserialize it on NASM (or vice versa, across process boundaries).

The C backend emits byte-by-byte memcpy calls, truncating int to short on serialize and sign-extending on deserialize. This is necessary because C’s native int is 4 bytes but duckBASIC’s INT is 2 bytes — the layout must match the NASM backend’s.

The NASM backend emits mov sequences (and rep movsb for strings). No truncation needed since NASM’s INT is natively 2 bytes.

The byte layout was a deliberate design decision: it made SERIALIZE / DESERIALIZE work identically on both backends without any translation layer, and it exposed a number of lurking bugs (like C’s int being 4 bytes) that would have been catastrophic later.

No comments:

Post a Comment

🦆Part 5 — Looking Forward What Phase 1 has 75 tests passing on both backends Structs , struct params, arrays of structs, local structs...