9 Commits
Author SHA1 Message Date
ed 67d54debfa offset corections (dwarf) 2026-07-22 18:00:09 -04:00
ed 3c25306070 fixes 2026-07-22 09:47:01 -04:00
ed c3cf05950e good enough for now 2026-07-21 22:29:22 -04:00
ed f6b4d9895e Adjustments to offset convention (don't want 1s based addresssing to mess with the spec defined encoding) 2026-07-21 20:52:13 -04:00
ed e70361b548 curation: first pass 2026-07-21 19:20:30 -04:00
ed ed3eb45b1d Fixes atom component gdb stepping. New phase/ctx annotations for atoms. Attempt at type views on registers (gdb pretty print failures).
Needs heavy curation and problably simplicication.
2026-07-18 10:29:04 -04:00
ed d7770b6e1d review pass on c code. 2026-07-15 08:56:37 -04:00
ed 137549b1c8 First pass review 2026-07-14 22:55:16 -04:00
ed 7d5b13aadb TODO: need to review snapshot 2026-07-14 12:16:00 -04:00
28 changed files with 5298 additions and 2079 deletions
+5 -4
View File
@@ -24,7 +24,7 @@
"osx": {
"gdbpath": "gdb"
},
"executable": "${workspaceRoot}/build/hello_psyq.elf",
"executable": "${workspaceRoot}/build/hello_gte.elf",
"setupCommands": [
{ "text": "set mi-async off" },
{ "text": "set remotetimeout 0" },
@@ -33,7 +33,7 @@
],
"autorun": [
"monitor reset shellhalt",
"load hello_psyq.elf",
"load hello_gte.elf",
"source scripts/gdb/gdb_tape_atoms.gdb",
"tbreak main",
"continue"
@@ -59,7 +59,7 @@
"osx": {
"gdbpath": "gdb"
},
"executable": "${workspaceRoot}/build/hello_gpu.elf",
"executable": "${workspaceRoot}/build/hello_gte.elf",
"setupCommands": [
{ "text": "set mi-async off" },
{ "text": "set remotetimeout 0" },
@@ -68,7 +68,7 @@
],
"autorun": [
"monitor reset shellhalt",
"load hello_gpu.elf",
"load hello_gte.elf",
"tbreak main",
"continue"
]
@@ -138,6 +138,7 @@
"monitor reset shellhalt",
"load build/hello_gte.dwarf-injected.elf",
"source scripts/gdb/gdb_tape_atoms.gdb",
"source build/gen/hello_gte.gdbinit",
"tbreak main",
"continue"
]
+73 -119
View File
@@ -3,34 +3,18 @@
* ============================================================================
*
* ATOM DSL: Annotation layer for tape atoms (lottes_tape.h).
* The metaprogram (scripts/passes/annotation.lua) reads source-as-written and validates:
* - atom_info(...) shape: up to three sub-calls (atom_bind(Binds_X), atom_reads(...), atom_writes(...)) in any order and are optional.
* - rbind atoms (atom_info(..., atom_bind(Binds_X), ...)) reference a real Binds_* struct declaration.
* - atom word-counts in word_counts.metadata.h match the body's actual .word count.
*
* WHAT THIS HEADER IS
* -------------------
* The metaprogram (scripts/passes/annotation.lua) reads source-as-written
* and validates:
* - atom_info(...) shape: up to three sub-calls (atom_bind(Binds_X),
* atom_reads(...), atom_writes(...)) in any order. All optional.
* (No phase token for now; phases may be reintroduced later.)
* - rbind atoms (atom_info(..., atom_bind(Binds_X), ...)) reference a
* real Binds_* struct declaration.
* - wave-context positions only reference the canonical 4-register
* set: R_PrimCursor / R_FaceCursor / R_VertBase / R_OtBase.
* - atom word-counts in word_counts.metadata.h agree with the body's
* actual .word count.
*
* WHY A PURE MACRO (atom_info, atom_bind, atom_reads, atom_writes, atom_label)
* -----------------------------------------------------------------
* Each of these expands to a C comment or to nothing. The C preprocessor
* strips them to whitespace. The metaprogram reads the literal token from
* source-as-written, NOT from the preprocessed output. This means:
* - the C compiler does no work for them (no __attribute__, no
* _Pragma, no asm side-effects)
* - they can never silently drift from the metaprogram's view
* (the metaprogram re-reads the source on every build)
* - the annotation is invisible to the linker, debugger, and IDE
* Pure macro anntation.
* ---------------
* Don't want to constraint the macro usage to some attribute placment constraint, etc, don't want ot dela with the compiler.
* atom_info, atom_bind, atom_reads, atom_writes, atom_label, atom_dbg_skip_over each expand to a C comment or to nothing
* (C preprocessor strips them to whitespace).
*
* ============================================================================
*
* Usage:
* MipsAtom_(cube_tri) atom_info(
* atom_reads (R_PrimCursor, R_FaceCursor, R_VertBase, R_OtBase)
@@ -60,30 +44,15 @@
*
* Annotation rules
* ----------------
* 1. atom_info(...) is OPTIONAL. Most atoms have no annotation.
* Atoms without atom_info are silently skipped by the metaprogram.
*
* 2. If present, atom_info takes up to three sub-calls, all
* order-independent within the arg list:
* - atom_bind(Binds_X) (optional; only for rbind atoms)
* - atom_reads(...) (optional; wave-context registers)
* - atom_writes(...) (optional; wave-context registers)
*
* 3. atom_bind(Binds_X) pins the ABI-struct shape -- the metaprogram
* cross-references Binds_X against the
* `typedef struct Binds_X { ... } Binds_X;` declaration.
*
* 4. atom_reads(...) and atom_writes(...) args are wave-context
* registers: R_PrimCursor / R_FaceCursor / R_VertBase / R_OtBase.
* Closed set. GTE / SP / DMA / I/O state is declared in source
* comments, not in atom_reads/atom_writes.
*
* 5. atom_label(name) is an anchor -- the macro is empty in C; the
* metaprogram records the marker at the current pos for offset
* calculation.
*
* 6. atom_offset(F, T) is resolved by gen/atom_offsets.h, generated
* from the atom_label markers.
* 1. atom_info(...) is OPTIONAL. Atoms without atom_info are silently skipped by the metaprogram.
* 2. If present, atom_info takes up to three sub-calls, all order-independent within the arg list:
* - atom_bind(Binds_X)
* - atom_reads(...)
* - atom_writes(...)
* 3. atom_bind(Binds_X): metaprogram cross-references Binds_X against the `typedef struct Binds_X { ... } Binds_X;` declaration.
* 4. atom_reads(...) and atom_writes(...): Used to to check if registers are used correctly in macros: R_PrimCursor / R_FaceCursor / R_VertBase / R_OtBase.
* 5. atom_label(name: Utilize with atom_offset as a target location.
* 6. atom_offset(F, T): Resolved by gen/atom_offsets.h, generated from the atom_label markers. Calculated during the offset pass of the lua metaprogram.
*/
#ifdef INTELLISENSE_DIRECTIVES
@@ -92,64 +61,69 @@
#endif
/* ============================================================================
* WAVE-CONTEXT REGISTERS -- canonical register set for the tape wave model.
*
* R_PrimCursor output pointer into the prim arena (next OT entry to write)
* R_FaceCursor input pointer into the face array (next face to consume)
* R_VertBase base pointer into the vertex arena (this wave's vertices)
* R_OtBase base pointer into the ordering table (this wave's OT slot)
*
* Closed set. If your atom needs to touch GTE / SP / DMA / other side state,
* declare it at the source level as you normally would -- but DO NOT put
* those registers in atom_reads/atom_writes.
*
* ============================================================================*/
/* ============================================================================
* atom_reads(...) / atom_writes(...) -- wave-context register list
*
* atom_reads(R_PrimCursor, R_FaceCursor)
* -> (R_PrimCursor, R_FaceCursor) // comma-evaluated, discarded
*
* The macro produces a comma-evaluated expression that the C compiler
* silently discards (it sits in an unused arg position -- the result is
* never bound). The Lua tool pattern-matches the "atom_reads(...)" /
* "atom_writes(...)" token to extract the list.
*
* You can have at most one atom_reads(...) and at most one atom_writes(...)
* in an atom_info(...) call. To declare multiple disjoint sets (rare), just
* declare the union -- the metaprogram doesn't track which reads need which
* writes at this granularity.
* atom_reads(...) / atom_writes(...)
*
* Used during the static analysis pass of the metaprogram to do
* ============================================================================*/
#define atom_reads(...) (__VA_ARGS__)
#define atom_writes(...) (__VA_ARGS__)
/* ----------------------------------------------------------------------------
* atom_reg (per-enum opt-in marker for the DWARF register-alias registry)
*
* The bare `atom_reg` token adjacent to an enum entry in mips.h / lottes_tape.h flags that alias as debug-visible for scan_source's register_alias_registry.
* The C preprocessor strips it to a comment so no runtime symbol is created; the Lua scanner reads the bare token.
* ----------------------------------------------------------------------------*/
#define atom_reg /* atom_reg: opt the preceding enum entry into the DWARF registry */
/* ============================================================================
* ATOM ANNOTATION MACROS
*
* atom_info -- single unified annotation. OPTIONAL. Most atoms have none.
*
* atom_info :
* MipsAtom_(cube_tri) atom_info(
* atom_reads (R_PrimCursor, R_FaceCursor, R_VertBase, R_OtBase)
* , atom_writes(R_PrimCursor, R_FaceCursor)
* ){ ... };
*
* Shape (sub-args order-independent; all optional):
* - atom_bind(Binds_X): at most one; pins the ABI-struct shape
* - atom_reads(...): at most one; comma-list of wave-context registers
* - atom_writes(...): at most one; comma-list of wave-context registers
*
* No phase token for now. The metaprogram doesn't check ordering across
* atoms -- phases (init / bind / setup / work / commit / terminate) will
* be reintroduced when ordering checks are added.
*
* The macro expands to a C comment (or to nothing). The C compiler does
* no work. The metaprogram reads the source-as-written directly.
*
*
* - atom_bind(Binds_X): metaprogram cross-references Binds_X against the `typedef struct Binds_X { ... } Binds_X;` declaration.
* - atom_reads(...): comma-list of registers
* - atom_writes(...): comma-list of registers
* ============================================================================*/
#define atom_info(...) /* atom_info(__VA_ARGS__) */
/* ----------------------------------------------------------------------------
* DEBUG SOURCE-STEP MARKERS
*
* Place atom_dbg_skip_over() before a MipsAtom_, MipsAtomComp_, or MipsAtomComp_Proc_.
* The following declaration kind determines whether the marker selects a whole atom or a component inline view.
* The source scanner associates the marker with that declaration; placement diagnostics are handled by the annotation pass.
* ----------------------------------------------------------------------------*/
#define atom_dbg_skip_over() /* atom_dbg_skip_over: skip the following atom or component source view */
/* ----------------------------------------------------------------------------
* Typed-view annotations (Registry for DWARF RR_<R_X> chain resolution)
* atom_type(<T>) -- overloaded:
* (a) enum-site default: `R_Foo = R_Tn, atom_reg atom_type(T)`
* Sets the per-alias default typed view in the register_alias_registry.
* Consumed by the DWARF chain step (e) when no per-atom atom_ctx / atom_phase / atom_type callsite provides a stronger resolution.
* (b) callsite override: `atom_reads(R_Foo atom_type(T), ...)` Overrides the per-alias default for THIS atom only.
* Last-write-wins per R_Name; conflict -> error.
* atom_ctx(<atom_name>) -- atom-info sub-call:
* Propagate another atom's atom.rbind.fields (its Binds_* typed fields) into THIS atom's typed-view resolution.
* The named atom must be an rbind atom (have `atom_bind(Binds_X)` in its `atom_info`).
* Used as the escape hatch when atom_phase is not the natural correlation.
* atom_phase(<label>) -- atom-info sub-call:
* Free-form C-identifier label for grouping atoms.
* Within a phase, the FIRST atom in source-order that owns its own atom.rbind provides
* the Binds_* field types used by all other atoms in the same phase.
* The preferred correlation mechanism; atom_ctx is the escape hatch for non-natural cases.
*
* All three expand to C comments
* (the bare-token convention matching `atom_reg` and `atom_dbg_skip_over`).
* The Lua scanner reads the bare tokens in source-as-written; the C preprocessor strips them.
* ----------------------------------------------------------------------------*/
#define atom_type(T) /* atom_type: associate <T> with the preceding enum entry (enum site) or this register (atom-info site) */
#define atom_ctx(atom_name) /* atom_ctx: propagate <atom_name>'s Binds_* field types into this atom's typed views */
#define atom_phase(label) /* atom_phase: tag this atom with <label> for grouped typed-view resolution */
/* ----------------------------------------------------------------------------
* atom_bind(Binds_X) -- rbind sub-call of atom_info
*
@@ -158,13 +132,7 @@
* , atom_writes(R_PrimCursor, R_FaceCursor, R_VertBase, R_OtBase)
* ){ ... };
*
* The Binds_X MUST be a typedef'd type (declared via
* `typedef struct Binds_X { ... } Binds_X;` somewhere in the source).
* The Lua tool cross-references this. Missing struct = error.
*
* atom_bind is a SUB-CALL of atom_info, not a standalone annotation macro.
*
* The macro expands to a C comment. The metaprogram reads source-as-written.
* The Binds_X MUST be a typedef'd type (declared via `typedef struct Binds_X { ... } Binds_X;` somewhere in the source).
* ----------------------------------------------------------------------------*/
#define atom_bind(binds_struct) /* atom_bind(binds_struct) */
@@ -177,25 +145,11 @@
*
* atom_offset(culling, bounds_chk) ← resolved by gen/.offsets.h
*
* The metaprogram generates gen/atom_offsets.h with one
* #define atom_offset__culling__bounds_chk ((target - branch_pos - 1))
* per atom_offset(F, T) call. The preprocessor then expands your call to
* the right immediate value.
*
* If gen/atom_offsets.h is stale (or atom_label(name) is undefined),
* `atom_offset__F__T` becomes an undefined macro and the C build fails.
* This catches:
* - typo in atom_label (no anchor → metaprogram doesn't emit the macro)
* - .offsets.h not regenerated after body edits
* - body edit that broke the offset math (recompile + retest picks it up
* in CPU emulator)
* The metaprogram generates gen/atom_offsets.h with one #define with the offset value per atom_offset(F, T) call.
* The preprocessor then expands the call to the right immediate value.
*
* If gen/atom_offsets.h is stale (or atom_label(name) is undefined), `atom_offset_F_T` becomes an undefined macro and the C build fails.
* ============================================================================*/
#define atom_offset(F, T) atom_offset_ ## F ## _ ## T
/* atom_label is a pure annotation for the metaprogram's offset calculations.
* The macro expands to a C comment, so the C preprocessor strips it to
* whitespace — NO instruction word is emitted in the asm. The metaprogram
* still recognises the literal `atom_label(name)` token in source and
* records the marker at the current pos. */
// atom_label is a pure annotation for the metaprogram's offset calculations.
#define atom_label(name) /* atom_label anchor: name */
+1 -2
View File
@@ -23,7 +23,6 @@ WORD_COUNT(mac_yield, 4)
, load_half_u(R_T2, R_FaceCursor, 2 * S_(S2))
WORD_COUNT(mac_load_tri_indices, 3)
/* Words: 18; Translates indices to vertex addresses and pushes them to GTE */
#define mac_gte_load_tri_verts(...) \
shift_lleft(R_AT, R_T0, v3s2_byteoff) \
, add_u_self(R_AT, R_VertBase) \
@@ -77,7 +76,7 @@ WORD_COUNT(mac_insert_ot_tag_g4, 11)
#define mac_pack_color_word(off, cmd, r, g, b) \
load_upper_i(R_AT, (cmd) << 8 | (b)) \
, or_i_self( R_AT, ((g) << 8) | (r)) \
, or_i_self( R_AT, ((g) << 8) | (r)) \
, store_word( R_AT, R_PrimCursor, (off))
WORD_COUNT(mac_pack_color_word, 3)
+37 -64
View File
@@ -1,7 +1,6 @@
/* ============================================================================
* duffle DSL Suffix Conventions
* ============================================================================
*
* Every mnemonic in this header follows the same suffix grammar:
*
* Primitive commands: gp0_cmd_poly_f3 = 0x20 (byte opcode)
@@ -26,8 +25,7 @@
* 0. Opcode IDs gp0_cmd_poly_f3 = 0x20
*
* Vendor mnemonics (gte_mtc2, gte_mfc2, etc.) are NOT in this header.
* They live in the opt-in `gp_vendor_sym.h` for users who prefer the
* PSYQ-style names.
* They live in the opt-in `gp_vendor_sym.h` for users who prefer the PSYQ-style names.
* ============================================================================ */
#ifdef INTELLISENSE_DIRECTIVES
@@ -41,15 +39,14 @@
/* ============================================================================
* Hardware MMIO Addresses
* ============================================================================
*
* PSX GPU has two 32-bit ports in the I/O register region at KSEG2
* 0x1F800000+. GP0 (offset 0x10) is the data port (commands + params).
* GP1 (offset 0x14) is the control port (status, ctrl writes).
* ============================================================================ */
/* IO base address (KSEG2 0x1F800000+ for the I/O register region).
* The 16-bit upper half `IO_BASE_ADDR_HI16` is the form used by
* tape-side macros that pin a register to hold the IO base and access
* ports via offsets — `lui $reg, 0x1F80` (1 word) then `sw $data, GPIO_PORT*_OFFSET($reg)` (1 word).
* The 16-bit upper half `IO_BASE_ADDR_HI16` is the form used by tape-side macros that pin a register
* to hold the IO base and access ports via offsets:
* `lui $reg, 0x1F80` (1 word) then `sw $data, GPIO_PORT*_OFFSET($reg)` (1 word).
* Mirrors the `IO_BASE_ADDR equ 0x1F80` + `gpio_port0 equ 0x1810` pattern from graphics_hello/gp.s. */
enum {
IO_BASE_ADDR = 0x1F800000, /* full 32-bit I/O region base */
@@ -75,12 +72,10 @@ enum {
/* ============================================================================
* GP0 command byte constants + Layer 1 (GPU bitfield shifts)
* ============================================================================
*
* 8-bit GP0 opcodes (the upper byte of a primitive's first word). These are the BYTE only.
* The layer-1 bitfield-layout constants live in the same enum block
* so the encoder can reference them by name.
* NO macro body past this point uses a raw shift or raw mask.
* Every shift/width/mask is named here, named once.
* The layer-1 bitfield-layout constants live in the same enum block so the encoder can reference them by name.
* NO macro body past this point uses a raw shift or raw mask.
* Every shift/width/mask is named here, named once.
* Mirrors the OPCODE_SHIFT / RS_SHIFT / REG_MASK convention from mips.h.
* ============================================================================ */
enum {
@@ -143,9 +138,7 @@ enum {
/* ============================================================================
* Layer 1.5 (per-field encoders) + Layer 2 (composite) + Layer 3 (semantic GP0 word builders)
* ============================================================================
*
* Layer 1.5 encoders take one field's value, mask it to its own width,
* and shift it to its own position.
* Layer 1.5 encoders take one field's value, mask it to its own width, and shift it to its own position.
* Mirrors `enc_op` / `enc_rs` / `enc_rt` in mips.h and `enc_gte_sf` / `enc_gte_mx` in gte.h.
* Layer-2 composite encoders OR the per-field encoders together; layer-3 semantic macros delegate to the composites.
* No raw shifts or magic numbers in any macro body below this point.
@@ -186,10 +179,9 @@ enum {
/* ============================================================================
* GP1 command byte constants + Layer 1 (display-mode + range + draw-area bitfield shifts)
* ============================================================================
*
* GP1 status bits are read from HW_GP1; ctrl writes use GP1 commands
* packed into 32-bit words (cmd byte in the upper 8 bits via
* `enc_gp0_cmd(cmd)` — never a raw shift).
* GP1 status bits are read from HW_GP1;
* ctrl writes use GP1 commands packed into 32-bit words
* (cmd byte in the upper 8 bits via `enc_gp0_cmd(cmd)`).
* ============================================================================ */
enum {
gp1_cmd_Reset = 0x00,
@@ -202,10 +194,9 @@ enum {
gp1_cmd_VerticalDisplayRange = 0x07,
gp1_cmd_DisplayMode = 0x08,
/* Note: GP1 only has commands 0x00..0x08.
* The state-setter commands (SetTextureWindow, * SetDrawArea*,
* SetDrawOffset, SetMaskBit) live in the GP0 enum as * 0xE1..0xE6.
* DrawArea word builders are below as GP0s * macros
* (since they emit GP0 commands). */
* The state-setter commands (SetTextureWindow, * SetDrawArea*, SetDrawOffset, SetMaskBit)
* live in the GP0 enum as * 0xE1..0xE6.
* DrawArea word builders are below as GP0s * macros (since they emit GP0 commands). */
/* ---- Display-mode payload flags (per PSX-SPX §"GP1 Display Mode").
* Bit positions match the encoder shifts below; values are the
@@ -259,8 +250,7 @@ enum {
#define enc_gp1_vrange_word(y1, y2) (enc_gp0_cmd(gp1_cmd_VerticalDisplayRange) | enc_gp1_vrange_y1(y1) | enc_gp1_vrange_y2(y2))
/* ---- Layer 2: GP0 state-setter composite encoders ----
* GP0(0xE3) SetDrawArea top-left and GP0(0xE4) SetDrawArea bottom-right
* both use the same X/Y 10-bit signed payload as GP1 DisplayRange. */
* GP0(0xE3) SetDrawArea top-left and GP0(0xE4) SetDrawArea bottom-right both use the same X/Y 10-bit signed payload as GP1 DisplayRange. */
#define enc_gp0_draw_area_tl_word(x, y) (enc_gp0_cmd(gp0_cmd_SetDrawArea_TopLeft) | enc_gp1_draw_x(x) | enc_gp1_draw_y(y))
#define enc_gp0_draw_area_br_word(x, y) (enc_gp0_cmd(gp0_cmd_SetDrawArea_BotRight) | enc_gp1_draw_x(x) | enc_gp1_draw_y(y))
@@ -282,7 +272,6 @@ enum {
/* ============================================================================
* Pre-baked GPU state words
* ============================================================================
*
* Common command words for boot-time GPU init and standard display configurations.
* ============================================================================ */
@@ -356,7 +345,6 @@ enum {
/* ============================================================================
* Primitive structs (8 polygon variants + tag)
* ============================================================================
*
* Each struct follows the GPU-documented memory layout for the corresponding primitive command.
* The PolyTag is the OT-link header; the rest of the struct is the primitive's body.
*
@@ -390,9 +378,9 @@ typedef Struct_(PolyTag) {
* No raw C-style casts. RHS values are assumed to be `U4` — caller passes a `U4` directly. */
#define set_len(tag,v) (C_(PolyTag_R,tag)->len = u4_(v))
#define set_addr(tag,v) (C_(PolyTag_R,tag)->addr = u4_(v))
/* `set_code` is no longer in the new PolyTag design — the code byte lives
* in the primitive body (e.g. `((Poly_F3*)(p))->code`), not in the tag.
* Use the typed primitive structs (Poly_F3, Poly_G4, etc.) and the `set_poly_*` setters,
/* `set_code` is no longer in the new PolyTag design — the code byte lives in the primitive body
* (e.g. `((Poly_F3*)(p))->code`), not in the tag.
* Use the typed primitive structs (Poly_F3, Poly_G4, etc.) and the `set_poly_*` setters,
* which set both the tag's length and the code. */
#define get_len(tag) C_(U4,C_(PolyTag_R,tag)->len)
#define get_addr(tag) C_(U4,C_(PolyTag_R,tag)->addr)
@@ -511,7 +499,6 @@ typedef Struct_(Poly_GT4) {
/* ============================================================================
* Texture Page (TPage) bit layout
* ============================================================================
*
* The TPage data word sent via GP0(0x2X) has:
* bits 0..3 = texture page X (4 bits, 64-px units, 0..16)
* bit 4 = texture page Y (1 bit, 64-px units, 0/1)
@@ -575,7 +562,6 @@ typedef Struct_(TexturePage) { U4 raw; };
/* ============================================================================
* CLUT (Color Look-Up Table) semantics
* ============================================================================
*
* CLUT is loaded into VRAM by sending a GP0 command whose payload is:
* bits 0..5 = Y in 16-px units (palette row)
* bits 6..14 = X in 16-px units (palette column)
@@ -608,7 +594,6 @@ enum {
/* ============================================================================
* TIM file format constants and headers
* ============================================================================
*
* TIM (Sony .TIM texture image) file structure:
* +0x00 U4 file_id (always 0x10 = TIM magic)
* +0x04 U4 version (always 0x00 for v1)
@@ -626,9 +611,8 @@ enum {
* +0x06 U2 px_height
* +0x08 ... pixel data
*
* Future?: add `tim_load_to_vram(tim_ptr, vram_addr)` that
* emits the necessary GP0 commands. Stoppped for now at the
* struct + enum level.
* Future?: add `tim_load_to_vram(tim_ptr, vram_addr)` that emits the necessary GP0 commands.
* Stoppped for now at the struct + enum level.
* ============================================================================ */
enum {
tim_file_id_magic = 0x10,
@@ -659,35 +643,24 @@ typedef Struct_(TIM_SectionHeader) {
* Tape-side GPU operations (NOT in this header)
* ============================================================================
*
* No `mac_gp0_send` or related macros live in gp.h. Rationale: the
* Lottes tape model uses OT-DMA for primitive submission, so atom bodies
* write to main RAM (the OT/primitive buffer) and to GTE state — never
* directly to the GPU ports at 0x1F801810 / 0x1F801814. See
* `mac_format_f3_color`, `mac_insert_ot_tag`, `mac_gte_store_f3` in
* lottes_tape.h for the patterns atom bodies actually use.
* No `mac_gp0_send` or related macros live in gp.h.
* Rationale: the Lottes tape model uses OT-DMA for primitive submission, so atom bodies write to main RAM (the OT/primitive buffer)
* and to GTE state — never directly to the GPU ports at 0x1F801810 / 0x1F801814.
* See `mac_format_f3_color`, `mac_insert_ot_tag`, `mac_gte_store_f3` in lottes_tape.h for the patterns atom bodies actually use.
*
* If a feature need arises requires tape-side GPU port writes (e.g. DMA-kick to
* start GPU consumption of the OT, VBlank sync via GP1 status poll),
* the right home is `lottes_tape.h` alongside the rest of the `mac_*`
* family — the encoder infrastructure is already in place:
* If a feature need arises requires tape-side GPU port writes
* (e.g. DMA-kick to start GPU consumption of the OT, VBlank sync via GP1 status poll),
* the right home is `lottes_tape.h` alongside the rest of the `mac_*` family:
* 1. The caller pins a register to hold the IO base, e.g. register U4 r_io rgcc(R_T4) = IO_BASE_ADDR;
* The compiler emits `lui R_T4, IO_BASE_ADDR_HI16` outside the atom body (in the C prologue before tape_run).
* 2. The atom body uses `store_word(R_data, R_T4, GPIO_PORT0_OFFSET)` to write to GP0, and `store_word(R_data, R_T4, GPIO_PORT1_OFFSET)`
* to write to GP1. Both are preprocessor-encodable because R_T4 is a fixed register and the GPIO_PORT*_OFFSET constants
* fit in the `sw`'s 16-bit signed offset field. No placeholder-pun, no asm constraints, no hidden register choice.
* Same pattern as the old graphics_hello/hello_gp_routines.s `reg_io_offset`/`gcmd_push` convention.
*
* 1. The caller pins a register to hold the IO base, e.g.
* register U4 r_io rgcc(R_T4) = IO_BASE_ADDR;
* The compiler emits `lui R_T4, IO_BASE_ADDR_HI16` outside the
* atom body (in the C prologue before tape_run).
*
* 2. The atom body uses `store_word(R_data, R_T4, GPIO_PORT0_OFFSET)`
* to write to GP0, and `store_word(R_data, R_T4, GPIO_PORT1_OFFSET)`
* to write to GP1. Both are preprocessor-encodable because R_T4 is
* a fixed register and the GPIO_PORT*_OFFSET constants fit in the
* `sw`'s 16-bit signed offset field. No placeholder-pun, no asm
* constraints, no hidden register choice. Same pattern as the
* old graphics_hello/hello_gp_routines.s `reg_io_offset`/`gcmd_push`
* convention.
*
* This mirrors the existing tape-side wave-context discipline: the
* caller binds the IO-base register via `rgcc()`, the macro assumes
* the binding is in effect, and the encoding falls out at preprocessor
* time. No additional GPU-domain macro layer required.
* This mirrors the existing tape-side wave-context discipline:
* the caller binds the IO-base register via `rgcc()`, the macro assumes the binding is in effect,
* and the encoding falls out at preprocessor time.
* No additional GPU-domain macro layer required.
* ============================================================================ */
#pragma endregion Tape-Side Macros
+6 -12
View File
@@ -2,10 +2,8 @@
* duffle DSL — GPU Vendor Mnemonics (opt-in)
* ============================================================================
*
* Provides the PSYQ-style CamelCase aliases for the canonical duffle GPU
* primitive setters and OT operations. The duffle snake_case names are
* primary; this header is for users who prefer the PSYQ SDK function
* names from the legacy C API.
* Provides the PSYQ-style CamelCase aliases for the canonical duffle GPU primitive setters and OT operations.
* The duffle snake_case names are primary; this header is for users who prefer the PSYQ SDK function names from the legacy C API.
*
* USAGE: #include "duffle/gp_vendor_sym.h" // after gp.h
*
@@ -23,15 +21,11 @@
* OT operations:
* AddPrim(ot, p) -> orderingtbl_add_primitive(ot, p)
*
* The gp0_cmd_* / gp1_cmd_* byte constants are already short and
* descriptive; no vendor alias is provided for them.
*
* The vendor mnemonics are NOT registered with the duffle word-count
* metadata (word_counts.metadata.h). They expand to the duffle canonical
* macros which DO have word-count entries (the ones emitted by
* mac_format_f3_color / mac_gte_store_f3 / etc.). Verification: V13
* (objdump byte-identical) holds.
* The gp0_cmd_* / gp1_cmd_* byte constants are already short and descriptive; no vendor alias is provided for them.
*
* The vendor mnemonics are NOT registered with the duffle word-count metadata (word_counts.metadata.h).
* They expand to the duffle canonical macros which DO have word-count entries
* (the ones emitted by mac_format_f3_color / mac_gte_store_f3 / etc.). Verification: V13 (objdump byte-identical) holds.
* ============================================================================ */
#ifdef INTELLISENSE_DIRECTIVES
+2 -4
View File
@@ -2,10 +2,8 @@
* duffle DSL — GTE Vendor Mnemonics (opt-in)
* ============================================================================
*
* Provides the textbook MIPS assembly mnemonics for the GTE/COP2
* instructions as thin aliases to the canonical duffle macros in gte.h.
* The duffle names are primary; this header is for users who prefer
* the textbook mnemonics.
* Provides the textbook MIPS assembly mnemonics for the GTE/COP2 instructions as thin aliases to the canonical duffle macros in gte.h.
* The duffle names are primary; this header is for users who prefer the textbook mnemonics.
*
* USAGE: #include "duffle/gte_vendor_sym.h" // after gte.h
*
+13 -17
View File
@@ -16,14 +16,12 @@ typedef Slice_MipsCode MipsAtom;
#define MipsAtom_(sym) MipsCode sym [] align_(4) =
// Bare form: file-scope declaration with hardcoded body.
// Used for components with no args (e.g., ac_load_tri_indices) or identifier-args (hardcoded register names).
// MipsAtomComp_(ac_X) { body }
// expands to:
// MipsCode ac_X[] align_(4) = { body };
#define MipsAtomComp_(sym) MipsCode sym [] align_(4) =
// Function form: function-body block that returns a MipsAtom slice.
// Used for components with value-args (e.g., ac_format_f3_color).
// FI_ MipsAtom ac_X(args) MipsAtomComp_Proc_(ac_X, { body })
// expands to:
@@ -34,16 +32,16 @@ typedef Slice_MipsCode MipsAtom;
/* Register aliases */
enum {
R_AtomJmp = R_T9,
R_TapePtr = R_T8, /* The Instruction Stream Pointer */
R_InCursor = R_T4, /* Input data cursor */
R_AtomJmp = R_T9 atom_reg, /* debug-visible; tape yield handshake scratch */
R_TapePtr = R_T8 atom_reg, /* The Instruction Stream Pointer */
R_InCursor = R_T4,
R_PrimCursor = R_T7, /* VRAM output cursor (primitive buffer) */
R_FaceCursor = R_T4, /* Input data cursor (indices/faces) */
R_VertBase = R_T5, /* Base address of the vertex array */
R_OtBase = R_T6, /* Base address of the Ordering Table */
R_PrimCursor = R_T7 atom_reg atom_type(U4 *), /* VRAM output cursor (primitive buffer) */
R_FaceCursor = R_T4 atom_reg atom_type(V4_S2 *), /* Cube face-index cursor (V4_S2*); floor context switches to V3_S2* via atom_phase */
R_VertBase = R_T5 atom_reg atom_type(V3_S2 *), /* Base address of the vertex array */
R_OtBase = R_T6 atom_reg atom_type(U4 *), /* Base address of the Ordering Table */
/* Stringification codes for the GCC inline assembler clobber lists */
/* Stringification codes for the GCC inline assembler clobber lists. */
#define R_TapePtr_Code R_T8_Code
#define R_InCursor_Code R_T4_Code
@@ -109,8 +107,7 @@ FI_ Slice_U4 tb_slice(TapeBuilder tb) { return (Sli
MipsAtomComp_(ac_yield) {
load_word(R_AtomJmp, R_TapePtr, 0),
add_ui_self( R_TapePtr, S_(MipsCode)),
jump_reg( R_AtomJmp),
nop,
jump_reg( R_AtomJmp), nop,
};
/* Words: 3; Loads 3 S2 indices from the face array */
@@ -121,6 +118,7 @@ MipsAtomComp_(ac_load_tri_indices) {
};
/* Words: 18; Translates indices to vertex addresses and pushes them to GTE */
atom_dbg_skip_over()
MipsAtomComp_(ac_gte_load_tri_verts) {
shift_lleft(R_AT, R_T0, v3s2_byteoff), add_u_self(R_AT, R_VertBase), load_word(R_V0, R_AT, O_(V3_S2,x)), load_word(R_V1, R_AT, O_(V3_S2,z)), gte_mv_to_data_r(R_V0, C2_VXY0), gte_mv_to_data_r(R_V1, C2_VZ0),
shift_lleft(R_AT, R_T1, v3s2_byteoff), add_u_self(R_AT, R_VertBase), load_word(R_V0, R_AT, O_(V3_S2,x)), load_word(R_V1, R_AT, O_(V3_S2,z)), gte_mv_to_data_r(R_V0, C2_VXY1), gte_mv_to_data_r(R_V1, C2_VZ1),
@@ -162,13 +160,12 @@ MipsAtomComp_(ac_insert_ot_tag_g4) {
FI_ MipsAtom ac_pack_color_word(U4 off, U4 cmd, U1 r, U1 g, U1 b)
MipsAtomComp_Proc_(ac_pack_color_word, {
load_upper_i(R_AT, (cmd) << 8 | (b)),
or_i_self( R_AT, ((g) << 8) | (r)),
or_i_self( R_AT, ((g) << 8) | (r)),
store_word( R_AT, R_PrimCursor, (off)),
})
/* Words: 3; Emits the F3 command+color word (cmd byte | BLUE | GREEN | RED)
* Args: _r, _g, _b are 8-bit RGB byte values (not raw 16-bit fields).
* Migrated from hello_gte_tape.c; takes RGB form per the Phase 3 convention. */
* Args: _r, _g, _b are 8-bit RGB byte values (not raw 16-bit fields). */
FI_ MipsAtom ac_format_f3_color(U1 r, U1 g, U1 b)
MipsAtomComp_Proc_(ac_format_f3_color, { mac_pack_color_word(O_(Poly_F3,color), gp0_cmd_poly_f3, r, g, b) })
@@ -268,8 +265,7 @@ internal MipsAtom_(mips_flush_icache) {
store_word(rret_addr, rstack_ptr, S_(U4)), // sw $ra, 4($sp)
add_ui(rret_0, rdiscard, bios_flushcache), // addiu $a0, $0, 0x44
add_ui(rtmp_0, rdiscard, bios_table_addr), // addiu $t0, $0, 0xA0
jump_link(rtmp_0, rret_addr), // jalr $t0, $ra
nop, // BD slot
jump_link(rtmp_0, rret_addr), nop, // jalr $t0, $ra, BD slot
load_word(rret_addr, rstack_ptr, S_(U4)), // lw $ra, 4($sp)
jump_reg(rret_addr), // jr $ra
add_ui(rstack_ptr, rstack_ptr, MipsStackAlignment), // sp += 8 (BD)
+72 -111
View File
@@ -1,38 +1,28 @@
/* ============================================================================
* duffle DSL Suffix Conventions
* ============================================================================
*
* Every mnemonic in this header follows the same suffix grammar:
*
* _i Immediate value (16-bit constant operand). Combine with
* _u or _s (single-letter modifier + type combined): add_ui,
* add_si. Examples: add_ui, add_si, and_i, or_i, xor_i,
* load_upper_i. and_i is sign-agnostic (andi zero-extends).
* load_upper_i is a unique verb; _i is the immediate marker,
* not a modifier+type combination.
*
* _u Unsigned (no-overflow, no-sign-extension). R-type
* arithmetic examples: add_u, sub_u, mult_u, div_u. I-type
* (combined with _i): add_ui.
*
* _s Signed (overflow-traps, sign-extends). R-type: add_s,
* sub_s, mult_s, div_s, set_lt_s. I-type (combined with _i):
* add_si.
* _i: Immediate value (16-bit constant operand).
* Combine with _u or _s (single-letter modifier + type combined): add_ui, add_si.
* Examples: add_ui, add_si, and_i, or_i, xor_i, load_upper_i. and_i is sign-agnostic (andi zero-extends).
* load_upper_i is a unique verb; _i is the immediate marker, not a modifier+type combination.
* _u: Unsigned (no-overflow, no-sign-extension).
* R-type arithmetic examples: add_u, sub_u, mult_u, div_u. I-type (combined with _i): add_ui.
* _s: Signed (overflow-traps, sign-extends).
* R-type: add_s, sub_s, mult_s, div_s, set_lt_s. I-type (combined with _i): add_si.
*
* --- Shift family (R-type): verb-modifier-direction ---
* The shift macros use `shift_<modifier><direction>`. Modifier is
* the single letter `l` (logical) or `a` (arithmetic). Direction
* is the word `left` or `right`. Combined: `_lleft`, `_lright`,
* `_aright`. Examples: shift_lleft( rd, rt, shamt) (= sll)
* shift_lright(rd, rt, shamt) (= srl)
* shift_aright(rd, rt, shamt) (= sra)
* (no `_aleft`; MIPS has no `sla` — arithmetic-left is bit-identical
* to logical-left, so use shift_lleft for that case)
* The shift macros use `shift_<modifier><direction>`.
* Modifier is the single letter `l` (logical) or `a` (arithmetic).
* Direction is the word `left` or `right`. Combined: `_lleft`, `_lright`, `_aright`.
* Examples: shift_lleft( rd, rt, shamt) (= sll)
* shift_lright(rd, rt, shamt) (= srl)
* shift_aright(rd, rt, shamt) (= sra)
* (no `_aleft`; MIPS has no `sla` — arithmetic-left is bit-identical to logical-left, so use shift_lleft for that case)
*
* --- Jump/Call family ---
* Simple jumps keep the original short names: jump (j), jump_reg
* (jr), jump_link (jalr rs, rd). The jump-and-link-to variants
* (jal, jalr rs with default $ra) get the `call_` verb instead:
* Simple jumps keep the original short names: jump (j), jump_reg (jr), jump_link (jalr rs, rd).
* The jump-and-link-to variants (jal, jalr rs with default $ra) get the `call_` verb instead:
* call_addr (jal), call_reg (jalr rs, default $ra).
* Examples: jump(off) (= j)
* jump_reg(rs) (= jr)
@@ -40,32 +30,22 @@
* call_reg(rs) (= jalr rs, default $ra)
* call_addr(off) (= jal)
*
* _r Register marker — used only when the register type needs
* disambiguation (e.g., GTE data register vs control
* register). NOT used in plain R-type arithmetic (the
* R-type is implicit). Examples: gte_mv_to_data_r,
* gte_mv_to_ctrl_r.
* _r: Register marker — used only when the register type needs disambiguation (e.g., GTE data register vs control register).
* NOT used in plain R-type arithmetic (the R-type is implicit). Examples: gte_mv_to_data_r, gte_mv_to_ctrl_r.
* _self: Destination equals one source operand.
* Examples: add_ui_self (I-type, to self), add_u_self (R-type, to self).
* _mv_to_: Direction: data flows into X.
* Example: gte_mv_to_data_r, gte_mv_to_ctrl_r.
* _mv_from_: Direction: data flows out of X.
* Example: gte_mv_from_data_r, gte_mv_from_ctrl_r.
* _str: String-form — emits inline-asm string instead of `.word`.
* Example: gte_rtpt_asm_str.
* _2w / _1w: Word count of the emitted sequence.
* Example: load_imm_2w.
*
* _self Destination equals one source operand.
* Examples: add_ui_self (I-type, to self),
* add_u_self (R-type, to self).
*
* _mv_to_ Direction: data flows into X.
* Example: gte_mv_to_data_r, gte_mv_to_ctrl_r.
*
* _mv_from_ Direction: data flows out of X.
* Example: gte_mv_from_data_r, gte_mv_from_ctrl_r.
*
* _str String-form — emits inline-asm string instead of `.word`.
* Example: gte_rtpt_asm_str.
*
* _2w / _1w Word count of the emitted sequence.
* Example: load_imm_2w.
*
* _cop2 RESERVED — DO NOT USE in macro names. The `gte_` namespace
* prefix already implies coprocessor 2. Use `c2` only in:
* (a) integer opcode enums (op_lwc2 = 0x32, op_swc2 = 0x3A)
* (b) vendor-mnemonic macro aliases (gte_mtc2, gte_mfc2)
* _cop2: RESERVED — DO NOT USE in macro names. The `gte_` namespace prefix already implies coprocessor 2. Use `c2` only in:
* (a) integer opcode enums (op_lwc2 = 0x32, op_swc2 = 0x3A)
* (b) vendor-mnemonic macro aliases (gte_mtc2, gte_mfc2)
*
* Primitive commands: gp0_cmd_poly_f3 = 0x20 (byte opcode)
* Packed 32-bit cmd: gp0_word_poly_f3(r, g, b) (32-bit, shifted)
@@ -80,9 +60,8 @@
* gte_lw_v0_xy(base) (gte + lw + v0 + xy)
* load_upper_i (load-upper + immediate, unique verb)
*
* Vendor mnemonics (sll, srl, sra, jr, j, jal, jalr) are NOT in this
* header. They live in the opt-in `mips_vendor_sym.h` for users who
* prefer the textbook MIPS assembly mnemonics.
* Vendor mnemonics (sll, srl, sra, jr, j, jal, jalr) are NOT in this header.
* They live in the opt-in `mips_vendor_sym.h` for users who prefer the textbook MIPS assembly mnemonics.
* ============================================================================ */
#ifdef INTELLISENSE_DIRECTIVES
@@ -98,19 +77,17 @@ enum {
/* ============================================================================
* REGISTER INTEGER IDS (preprocessor-visible)
* ============================================================================
* Every R_* enum below has a parallel R_*_Code `#define` so that the
* preprocessor can stringify the integer (e.g. for asm clobber lists and
* register-variable declarations via `rgcc(R_X)`). The enum value is
* bound to the `#define` so the two forms cannot drift apart.
* Every R_* enum below has a parallel R_*_Code `#define` so that the preprocessor can stringify the integer
* (e.g. for asm clobber lists and register-variable declarations via `rgcc(R_X)`).
* The enum value is bound to the `#define` so the two forms cannot drift apart.
*
* Only registers that get stringified need a `_Code` form; the rest are
* plain enum values. If you need to add a new one, follow the pattern:
* Only registers that get stringified need a `_Code` form; the rest are plain enum values.
* If you need to add a new one, follow the pattern:
* #define R_T7_Code 15
* R_T7 = R_T7_Code, // in the enum
* R_T7 = R_T7_Code, // in the enum
*
* User code should always reference the enum form (`R_T4`) at arithmetic
* sites and let `rlit(R_T4_Code)` / `rgcc(R_T4)` handle the stringify
* cases — never write the bare number `12`.
* User code should always reference the enum form (`R_T4`) at arithmetic sites and let
* `rlit(R_T4_Code)` / `rgcc(R_T4)` handle the stringify cases — never write the bare number `12`.
* ============================================================================ */
#define R_0_Code 0
#define R_AT_Code 1
@@ -225,7 +202,6 @@ enum {
/* 2F: N/A */
// , op_lwc0
// , op_load_addr = op_la
// , op_load_imm = op_li
, op_jump = op_j
@@ -327,15 +303,15 @@ enum { _BitOffsets = 0
* Argument order matches the MIPS assembly syntax:
* dest-first, then source operands, then immediate last.
*
* load_word(rt, base, off) → lw rt, off(base)
* store_word(rt, base, off) → sw rt, off(base)
* add_ui(rt, rs, imm) → addiu rt, rs, imm
* shift_lleft(rd, rt, shamt) → sll rd, rt, shamt
* shift_lright(rd, rt, shamt) → srl rd, rt, shamt
* shift_aright(rd, rt, shamt) → sra rd, rt, shamt
* jump_reg(rs) → jr rs
* jump_link(rs, rd) → jalr rs (link in rd, default $ra)
* nop → sll $0, $0, 0
* load_word(rt, base, off) → lw rt, off(base)
* store_word(rt, base, off) → sw rt, off(base)
* add_ui(rt, rs, imm) → addiu rt, rs, imm
* shift_lleft(rd, rt, shamt) → sll rd, rt, shamt
* shift_lright(rd, rt, shamt) → srl rd, rt, shamt
* shift_aright(rd, rt, shamt) → sra rd, rt, shamt
* jump_reg(rs) → jr rs
* jump_link(rs, rd) → jalr rs (link in rd, default $ra)
* nop → sll $0, $0, 0
*/
#define load_word(rt, base, off) enc_i(op_lw, (base), (rt), (off))
#define load_byte(rt, base, off) enc_i(op_lb, (base), (rt), (off))
@@ -404,12 +380,9 @@ enum { _BitOffsets = 0
* mult_s / mult_u → mult / multu (writes HI/LO; result in LO)
* div_s / div_u → div / divu (LO = quot, HI = rem)
*
* NOTE: dsl.h defines `add_s`/`sub_s`/`mut_s`/`gt_s`/etc. as
* _Generic-based signed integer-arithmetic helpers for U1/U2/U4. Those
* live in a different conceptual layer (generic arithmetic on DSL
* types) and would collide with the instruction encoders here. The
* `#undef` below lets the gas-style names below win; if a file needs
* both, the dsl.h versions can be reached via their long forms
* NOTE: dsl.h defines `add_s`/`sub_s`/`mut_s`/`gt_s`/etc. as _Generic-based signed integer-arithmetic helpers for U1/U2/U4.
* Those live in a different conceptual layer (generic arithmetic on DSL types) and would collide with the instruction encoders here.
* The `#undef` below lets the gas-style names below win; if a file needs both, the dsl.h versions can be reached via their long forms
* (e.g. `def_signed_op`-style or the underlying `add_s1/s2/s4`). */
#undef add_s
#undef sub_s
@@ -441,7 +414,7 @@ enum { _BitOffsets = 0
#define mov_to_low(rs) enc_r(op_special, (rs), R_0, R_0, 0, fc_mtlo)
/* --- Atomic branches (no pseudos like bgt/bge; compose with slt_* + branch_ne) ---
* branch_equal rs, rt, off → beq rs, rt, off
* branch_equal rs, rt, off → beq rs, rt, off
* branch_ne rs, rt, off → bne rs, rt, off
* branch_lt_zero rs, off → bltz rs, off
* branch_gt_zero rs, off → bgtz rs, off
@@ -472,22 +445,18 @@ enum { _BitOffsets = 0
/* load_imm_2w — unconditional 2-word `li` form: `lui` + (ori | addi).
*
* Granular companion to `load_imm`: skips the compile-time range checks
* and always emits 2 .words. Use this when:
* Granular companion to `load_imm`: skips the compile-time range checks and always emits 2 .words. Use this when:
* - you know `imm` is > 0xFFFF (otherwise you're wasting a word), OR
* - `imm` is not a compile-time constant and you want predictable
* 2-word emission without the `__builtin_constant_p` branches.
*
* The lo16 strategy is still chosen at expansion time on the lo half:
* lo16 in 0x0000..0x7FFF → addi (sign-ext is harmless, the lui
* already cleared bits 15..0)
* lo16 in 0x8000..0xFFFF → ori (zero-extends to preserve the
* intended bit pattern)
* lo16 in 0x0000..0x7FFF → addi (sign-ext is harmless, the lui already cleared bits 15..0)
* lo16 in 0x8000..0xFFFF ori (zero-extends to preserve the intended bit pattern)
*
* For situations where you need to bypass even this choice (e.g. to
* force a specific encoding for a known discontiguous high/low pair),
* For situations where you need to bypass even this choice
* (e.g. to force a specific encoding for a known discontiguous high/low pair),
* see `load_imm_2w_ori_forced` and `load_imm_2w_addi_forced` below.
*
* Statement-level (not expression-level): emits its own `asm volatile(...)`.
*/
#define load_imm_2w(rt, imm) do { \
@@ -518,9 +487,8 @@ enum { _BitOffsets = 0
} while (0)
/* load_imm_2w_addi_forced — force the `lui` + `addi` form regardless of lo16 sign.
* Use when you know sign-extension is fine (e.g. lo16 is treated as
* signed downstream) and you want a smaller effective instruction
* (the assembler/MIPS hardware will sign-extend the imm16). */
* Use when you know sign-extension is fine (e.g. lo16 is treated as signed downstream)
* and you want a smaller effective instruction (the assembler/MIPS hardware will sign-extend the imm16). */
#define load_imm_2w_addi_forced(rt, imm) do { \
/*U4 _li2a_imm_ = (U4)(imm);*/ \
asm volatile(asm_words( \
@@ -532,23 +500,17 @@ enum { _BitOffsets = 0
/* load_imm rt, imm — true `li` semantics (assembler `li` pseudo)
*
* Dispatches at compile time on the immediate's range, picking the
* smallest single-instruction form when possible:
*
* imm in 0 .. 0x7FFF addi rt, $0, imm (1 word)
* imm in 0x8000 .. 0xFFFF → ori rt, $0, imm (1 word; sign-bit must be zeroed)
* imm in 0x10000 .. 0xFFFFFFFF → lui + (ori | addi) (2 words)
*
* Statement-level (not expression-level): the macro emits its own
* `asm volatile(...)` block with 1 or 2 .word constants. Callers can
* group multiple `load_imm` calls in a single volatile by using the
* lower-level encoders directly:
* Dispatches at compile time on the immediate's range, picking the smallest single-instruction form when possible:
* imm in 0 .. 0x7FFF → addi rt, $0, imm (1 word)
* imm in 0x8000 .. 0xFFFF → ori rt, $0, imm (1 word; sign-bit must be zeroed)
* imm in 0x10000 .. 0xFFFFFFFF → lui + (ori | addi) (2 words)
*
* Statement-level (not expression-level): the macro emits its own `asm volatile(...)` block with 1 or 2 .word constants.
* Callers can group multiple `load_imm` calls in a single volatile by using the lower-level encoders directly:
* load_imm(R_T4, 0x12345678); // emits 2 .words
*
* Falls back to a 2-word form if `imm` is not a compile-time constant,
* but that path is unusual (load_imm is most useful with literal
* addresses and magic numbers). */
* Falls back to a 2-word form if `imm` is not a compile-time constant, but that path is unusual
* (load_imm is most useful with literal addresses and magic numbers). */
#define load_imm(rt, imm) do { \
if (cexpr_(imm) && ((imm) <= 0x7FFFU)) { \
/* Small positive: addi rt, $0, imm */ \
@@ -588,9 +550,8 @@ enum { _BitOffsets = 0
/* Standard clobber list for pure-MIPS asm volatile blocks: caller-saved
* GPRs that the kernel treats as volatile (v0/v1/t0/t1/ra) plus the
* "memory" barrier. The register ids are passed through `rlit` so
* the R_*_Code `#define`s are stringified into "$N" at expansion time. */
* GPRs that the kernel treats as volatile (v0/v1/t0/t1/ra) plus the "memory" barrier.
* The register ids are passed through `rlit` so the R_*_Code `#define`s are stringified into "$N" at expansion time. */
#define clbr_volatile_gprs rlit(R_V0), rlit(R_T0), rlit(R_T1), rlit(R_RA), clb_mem_drain
#define asm_mips_flush_icache() asm volatile( asm_words( \
+2 -3
View File
@@ -2,9 +2,8 @@
* duffle DSL — MIPS Vendor Mnemonics (opt-in)
* ============================================================================
*
* Provides the textbook MIPS assembly mnemonics as thin aliases to the
* canonical duffle macros in mips.h. The duffle names are primary; this
* header is for users who prefer the textbook mnemonics.
* Provides the textbook MIPS assembly mnemonics as thin aliases to the canonical duffle macros in mips.h.
* The duffle names are primary; this header is for users who prefer the textbook mnemonics.
*
* USAGE: #include "duffle/mips_vendor_sym.h" // after mips.h
*
+4 -5
View File
@@ -5,11 +5,10 @@
// Format: WORD_COUNT(MACRO_NAME, COUNT)
// One line per macro that appears in your atom sources.
//
// This file is encoding-macros-only. The auto-generated component
// macros (mac_X) live in duffle/gen/<dir>.macs.h (included separately
// by the unity build). The unity build should include THIS file and
// the .macs.h file in the same TU, with both wrapped (or the
// include guard order handled) to avoid WORD_COUNT redeclaration.
// This file is encoding-macros-only.
// The auto-generated component macros (mac_X) live in duffle/gen/<dir>.macs.h (included separately by the unity build).
// The unity build should include THIS file and the .macs.h file in the same TU, with both wrapped
// (or the include guard order handled) to avoid WORD_COUNT redeclaration.
//
// To regenerate: hand-count the instructions in each macro definition.
// (You'll only need to do this once per macro — they don't change often.)
+2 -2
View File
@@ -259,8 +259,8 @@ void update(PrimitiveArena* pa, U4* ordering_buf)
U4 prim_base = u4_(pa->buf[smem.active_buf_id]);
U4 prim_cursor = prim_base + pa->used;
LP_ U4 mem_temp_tape[512]; FArena tape_arena; farena_init(& tape_arena, slice_ut_arr(mem_temp_tape));
TapeBuilder tb = tb_make_old(&tape_arena); tb_scope(& tb) {
LP_ U4 mem_temp_tape[512];
TapeBuilder tb = tb_make(slice_ut_arr(mem_temp_tape)); tb_scope(& tb) {
tb_emit(& tb, rbind_cube_g4_face);
tb_data(& tb, prim_cursor);
tb_data(& tb, u4_(smem.cube.faces));
+6 -10
View File
@@ -22,7 +22,7 @@ typedef Struct_(Binds_CubeTri) {
V3_S2* VertBase;
U4* OtBase;
};
internal MipsAtom_(rbind_cube_g4_face) atom_info(atom_bind(Binds_CubeTri)
internal MipsAtom_(rbind_cube_g4_face) atom_info(atom_bind(Binds_CubeTri), atom_phase(cube_g4)
, atom_reads(R_TapePtr)
, atom_writes(R_PrimCursor, R_FaceCursor, R_VertBase, R_OtBase)
){
@@ -35,14 +35,9 @@ internal MipsAtom_(rbind_cube_g4_face) atom_info(atom_bind(Binds_CubeTri)
mac_yield()
};
/* ============================================================================
* cube_g4_face — Draw one cube face (Gouraud-shaded quad) via the GTE tape pipeline
* ============================================================================
* Reads 4 indices from R_FaceCur (V4_S2 = 8 bytes), loads 4 vertices into
* the GTE, runs the PsyQ RotAverageNclip4 sequence, and renders a Poly_G4.
*/
// cube_g4_face — Draw one cube face (Gouraud-shaded quad) via the GTE tape pipeline
internal
MipsAtom_(cube_g4_face) atom_info(
MipsAtom_(cube_g4_face) atom_info(atom_phase(cube_g4),
atom_reads( R_PrimCursor, R_FaceCursor, R_VertBase, R_OtBase),
atom_writes(R_PrimCursor, R_FaceCursor)
){
@@ -95,7 +90,7 @@ typedef Struct_(Binds_FloorTri) {
U4* OtBase;
};
internal
MipsAtom_(rbind_floor_f3_face) atom_info(atom_bind(Binds_FloorTri)
MipsAtom_(rbind_floor_f3_face) atom_info(atom_bind(Binds_FloorTri), atom_phase(floor_f3)
, atom_reads(R_TapePtr)
, atom_writes(R_PrimCursor, R_FaceCursor, R_VertBase, R_OtBase)
){
@@ -109,7 +104,8 @@ MipsAtom_(rbind_floor_f3_face) atom_info(atom_bind(Binds_FloorTri)
};
internal
MipsAtom_(floor_f3_face) atom_info(
atom_dbg_skip_over()
MipsAtom_(floor_f3_face) atom_info(atom_phase(floor_f3)
, atom_reads( R_PrimCursor, R_FaceCursor, R_VertBase, R_OtBase)
, atom_writes(R_PrimCursor, R_FaceCursor)
) {
+58 -94
View File
@@ -321,7 +321,7 @@ function ps1-meta { param(
[Parameter(Mandatory=$true)][string[]]$sources,
[Parameter(Mandatory=$true)][string]$metadata,
[string]$out_root = (join-path $path_build 'gen'),
[string[]]$passes = @('--all'),
[string[]]$passes = @('--pre-link'),
[string[]]$extra_args = @()
)
$script = join-path $path_scripts 'ps1_meta.lua'
@@ -379,114 +379,78 @@ function build-gte_hello {
$link_args += $f_debug
# $link_args += $f_optimize_size
$link_modules = @(
$module_asm_crt,
$module_asm_crt,
$module_c
)
link-modules $link_modules $elf $link_args
make-binary $elf $exe
# TODO(Ed): Do both -gdb-runtime and dwarf-injection passes in a single ps1-meta call.
# Post-link: emit ONLY build/gen/gdb_tape_atoms_runtime.gdb.
# The per-source *.atoms.sourcemap.txt was already generated by the pre-link --all call,
# so we skip --atoms-source-map here to avoid re-doing the work.
# The gdb-runtime emission requires --elf (for nm-based address lookup) so it MUST happen post-link.
# Post-link: gdb-runtime + dwarf-injection in a single Lua invocation (one luajit cold start).
ps1-meta -sources $atom_sources -metadata $path_atom_metadata `
-out_root (join-path $path_build 'gen') `
-passes @('--gdb-runtime') `
-extra_args @('--elf', $elf)
# F' + G' consolidated: --dwarf-injection now emits 7 .bin blobs
# (.debug_line, .debug_aranges, .debug_rnglists, .debug_info, .debug_abbrev, .debug_str, .debug_loc) all in one pass.
ps1-meta -sources $atom_sources -metadata $path_atom_metadata `
-out_root (join-path $path_build 'gen') `
-passes @('--dwarf-injection') `
-passes @('--post-link') `
-extra_args @('--elf', $elf)
#TODO(Ed): Move the below into ps-1 meta pass to reduce syscall latency?
# F' track: post-link DWARF injection. The new Lua pass writes build/gen/<basename>.dwarf_*.bin blobs;
# we splice them into a COPY of the ELF via objcopy --update-section (works fine from PowerShell).
# The un-injected $elf + $exe are unchanged (shipping binary).
$dwarfLineBin = Join-Path (Join-Path $path_build 'gen') 'hello_gte.dwarf_line.bin'
$dwarfArangesBin = Join-Path (Join-Path $path_build 'gen') 'hello_gte.dwarf_aranges.bin'
$dwarfRnglistsBin = Join-Path (Join-Path $path_build 'gen') 'hello_gte.dwarf_rnglists.bin'
$injectElf = Join-Path $path_build 'hello_gte.dwarf-injected.elf'
if ((Test-Path $dwarfLineBin) -and (Test-Path $dwarfArangesBin) -and (Test-Path $dwarfRnglistsBin))
# F' + G' splice: collapse 9 objcopy subprocess invocations into 3.
# - 1 call: 3x --update-section for F' (line / aranges / rnglists)
# - 1 call: 3x --update-section for G' (info / abbrev / str)
# - 1 call: 2x --add-section for G' (loc / loclists — these don't exist in the source ELF)
# - 1 call: 1x --set-section-flags (.rodata / .data enable code flag)
# = 4 objcopy calls (was 9; saved 5 spawns).
$dwarfLineBin = join-path (join-path $path_build 'gen') 'hello_gte.dwarf_line.bin'
$dwarfArangesBin = join-path (join-path $path_build 'gen') 'hello_gte.dwarf_aranges.bin'
$dwarfRnglistsBin = join-path (join-path $path_build 'gen') 'hello_gte.dwarf_rnglists.bin'
$injectElf = join-path $path_build 'hello_gte.dwarf-injected.elf'
if ((Test-Path $dwarfLineBin) -and (Test-Path $dwarfArangesBin) -and (Test-Path $dwarfRnglistsBin))
{
Write-Host "[build] DWARF-injecting $elf -> $injectElf"
Copy-Item -LiteralPath $elf -Destination $injectElf
& $Objcopy --update-section ".debug_line=$dwarfLineBin" $injectElf
$last_exit_code_error = $LASTEXITCODE -ne 0
if ($last_exit_code_error) {
Write-Warning "[build] objcopy .debug_line update failed (exit $LASTEXITCODE); removing $injectElf"
Remove-Item -LiteralPath $injectElf -ErrorAction SilentlyContinue
return;
}
& $Objcopy --update-section ".debug_aranges=$dwarfArangesBin" $injectElf
$last_exit_code_error = $LASTEXITCODE -ne 0
if ($LASTEXITCODE -ne 0) {
Write-Warning "[build] objcopy .debug_aranges update failed (exit $LASTEXITCODE); removing $injectElf"
Remove-Item -LiteralPath $injectElf -ErrorAction SilentlyContinue
return;
}
& $Objcopy --update-section ".debug_rnglists=$dwarfRnglistsBin" $injectElf
if ($LASTEXITCODE -ne 0) {
Write-Warning "[build] objcopy .debug_rnglists update failed (exit $LASTEXITCODE); removing $injectElf"
Remove-Item -LiteralPath $injectElf -ErrorAction SilentlyContinue
}
else
{
# Baked atoms execute from RAM but are emitted as C data arrays, so their ELF sections lack SHF_EXECINSTR.
# GDB discards line rows for non-code sections.
# Mark only the debug-copy sections executable; the shipping ELF and PS-EXE remain byte/flag unchanged.
& $Objcopy `
--set-section-flags ".rodata=alloc,load,readonly,code,contents" `
--set-section-flags ".data=alloc,load,data,code,contents" `
$injectElf
if ($LASTEXITCODE -ne 0) {
Write-Warning "[build] objcopy atom-section flag update failed (exit $LASTEXITCODE); removing $injectElf"
Remove-Item -LiteralPath $injectElf -ErrorAction SilentlyContinue
} else {
Write-Host "[build] DWARF-injected ELF: $injectElf"
}
}
}
Copy-Item -LiteralPath $elf -Destination $injectElf -Force
# G' (atom locals) is now part of --dwarf-injection.
# The F' splice block above already covered .debug_line / .debug_aranges / .debug_rnglists;
# we extend the same Copy-Item + objcopy chain to splice the G' 4 sections
# (.debug_info, .debug_abbrev, .debug_str via --update-section; .debug_loc via --add-section since it doesn't exist in the source ELF).
$dwarfInfoBin = Join-Path (Join-Path $path_build 'gen') 'hello_gte.dwarf_info.bin'
$dwarfAbbrevBin = Join-Path (Join-Path $path_build 'gen') 'hello_gte.dwarf_abbrev.bin'
$dwarfStrBin = Join-Path (Join-Path $path_build 'gen') 'hello_gte.dwarf_str.bin'
$dwarfLocBin = Join-Path (Join-Path $path_build 'gen') 'hello_gte.dwarf_loc.bin'
if ((Test-Path $dwarfInfoBin) -and (Test-Path $dwarfAbbrevBin) -and (Test-Path $dwarfStrBin) -and (Test-Path $dwarfLocBin))
{
Write-Host "[build] G' atom-locals: splicing .debug_info/.debug_abbrev/.debug_str/.debug_loc into $injectElf"
& $Objcopy --update-section ".debug_info=$dwarfInfoBin" $injectElf
$last_exit_code_error = ($LASTEXITCODE -ne 0)
if ($last_exit_code_error) {
Write-Warning "[build] objcopy .debug_info update failed (exit $LASTEXITCODE)"
return;
}
& $Objcopy --update-section ".debug_abbrev=$dwarfAbbrevBin" $injectElf
# Single objcopy call: 3x --update-section for F' (line, aranges, rnglists).
$f_args = @(
"--update-section=.debug_line=$dwarfLineBin",
"--update-section=.debug_aranges=$dwarfArangesBin",
"--update-section=.debug_rnglists=$dwarfRnglistsBin"
)
& $Objcopy @f_args $injectElf 2>&1 | Out-Null
if ($LASTEXITCODE -ne 0) {
Write-Warning "[build] objcopy .debug_abbrev update failed (exit $LASTEXITCODE)"
Write-Warning "[build] objcopy F' splice failed (exit $LASTEXITCODE); removing $injectElf"
Remove-Item -LiteralPath $injectElf -ErrorAction SilentlyContinue
return;
}
& $Objcopy --update-section ".debug_str=$dwarfStrBin" $injectElf
}
# G' 5-section splice: 3 update-section (info / abbrev / str) + 2 add-section (loc / loclists).
$dwarfInfoBin = join-path (join-path $path_build 'gen') 'hello_gte.dwarf_info.bin'
$dwarfAbbrevBin = join-path (join-path $path_build 'gen') 'hello_gte.dwarf_abbrev.bin'
$dwarfStrBin = join-path (join-path $path_build 'gen') 'hello_gte.dwarf_str.bin'
$dwarfLocBin = join-path (join-path $path_build 'gen') 'hello_gte.dwarf_loc.bin'
$dwarfLoclistsBin = join-path (join-path $path_build 'gen') 'hello_gte.dwarf_loclists.bin'
$g_args = @(
"--update-section=.debug_info=$dwarfInfoBin",
"--update-section=.debug_abbrev=$dwarfAbbrevBin",
"--update-section=.debug_str=$dwarfStrBin",
"--add-section=.debug_loc=$dwarfLocBin",
"--add-section=.debug_loclists=$dwarfLoclistsBin"
)
& $Objcopy @g_args $injectElf 2>&1 | Out-Null
if ($LASTEXITCODE -ne 0) {
Write-Warning "[build] objcopy .debug_str update failed (exit $LASTEXITCODE)"
}
else
{
# .debug_loc doesn't exist in the source ELF; --add-section creates it.
& $Objcopy --add-section ".debug_loc=$dwarfLocBin" $injectElf
if ($LASTEXITCODE -ne 0) {
Write-Warning "[build] objcopy .debug_loc add-section failed (exit $LASTEXITCODE)"
} else {
Write-Host "[build] G' atom-locals-injected: $injectElf"
}
Write-Warning "[build] objcopy G' splice failed (exit $LASTEXITCODE); removing $injectElf"
Remove-Item -LiteralPath $injectElf -ErrorAction SilentlyContinue
return;
}
# Baked atoms execute from RAM but are emitted as C data arrays, so their ELF sections lack SHF_EXECINSTR.
# GDB discards line rows for non-code sections. Mark only the debug-copy sections executable.
# The shipping ELF and PS-EXE remain byte/flag unchanged.
& $Objcopy `
--set-section-flags ".rodata=alloc,load,readonly,code,contents" `
--set-section-flags ".data=alloc,load,data,code,contents" `
$injectElf 2>&1 | Out-Null
if ($LASTEXITCODE -ne 0) {
Write-Warning "[build] atom-section flag update failed (exit $LASTEXITCODE); removing $injectElf"
Remove-Item -LiteralPath $injectElf -ErrorAction SilentlyContinue
} else {
Write-Host "[build] DWARF-injected ELF: $injectElf"
}
}
}
+81 -96
View File
@@ -8,8 +8,7 @@
--- - **C-language scanner** (`skip_ws_and_cmt`, `skip_str_or_cmt`, `read_ident`, `read_parens`, `read_braces`, `read_brackets`, `read_balanced`, `scan_to_char`, `split_top_level_commas`).
--- - **Word-count loader** (`load_word_counts` for `WORD_COUNT(...)` metadata files).
--- - **Line lookup** (`LineIndex` returns an O(log N) `line_of(pos)` closure for source-mapping).
--- - **Domain tables** (`WAVE_CONTEXT_REGS`, `TAPE_ATOM_MACROS`, `GTE_PIPELINE_LATENCY`, `GP0_CMD_SIZE`, `GP0_CMD_BY_SHAPE`, `GP0_MACRO_CONTRIB`, `INSTRUCTION_LATENCY`).
--- - **Process-bootstrap helper** (`setup_package_path`replaces the 8-line `arg[0]`-resolution boilerplate duplicated across 7 entry scripts)
--- - **Domain tables** (`TAPE_ATOM_MACROS`, `GTE_PIPELINE_LATENCY`, `GP0_CMD_SIZE`, `GP0_CMD_BY_SHAPE`, `GP0_MACRO_CONTRIB`, `INSTRUCTION_LATENCY`).
---
--- **Conventions**: tabs (1/level), EmmyLua annotations, no regex.
@@ -74,21 +73,14 @@ local BYTE_DIGIT_9 = 0x39 -- '9'
-- Section -1: Bootstrap (path-setup at module load)
-- ════════════════════════════════════════════════════════════════════════════
--
-- Path setup is done by `scripts/duffle_paths.lua`, which derives the repo
-- root from `debug.getinfo(1, "S").source` (NO subprocess, ~0ms) and
-- then calls `require("duffle")`. The prior `io.popen("git rev-parse ...")`
-- approach in this section was removed during F'' because:
--
-- 1. Every entry script + every passes script now uses
-- `dofile("duffle_paths.lua")` (14 call sites; verified via grep).
-- The `find_repo_root` / `setup_package_path` defined here was dead
-- code in practice.
-- Path setup is done by `scripts/duffle_paths.lua`, which derives the repo root from `debug.getinfo(1, "S").source` (NO subprocess, ~0ms) and then calls `require("duffle")`.
-- The prior `io.popen("git rev-parse ...")` approach in this section was removed during F'' because:
-- 1. Every entry script + every passes script now uses `dofile("duffle_paths.lua")` (14 call sites; verified via grep).
-- The `find_repo_root` / `setup_package_path` defined here was dead code in practice.
-- 2. `git rev-parse` costs ~100-180ms per subprocess spawn on Windows.
-- `debug.getinfo` is <1ms. There's no reason to keep the slow path
-- even as a "fallback".
-- `debug.getinfo` is <1ms. There's no reason to keep the slow path even as a "fallback".
--
-- If a future use case ever needs to load `duffle.lua` WITHOUT going
-- through `duffle_paths.lua`, set `package.path` manually before `require`.
-- If a future use case ever needs to load `duffle.lua` WITHOUT going through `duffle_paths.lua`, set `package.path` manually before `require`.
-- See `docs/guide_metaprogram_ssdl.md` §"I/O primitives" for the pattern.
-- ════════════════════════════════════════════════════════════════════════════
@@ -144,10 +136,8 @@ local lpeg_scan_to_target_pat = function(target) return (P(1) - P(target))^0 en
-- ════════════════════════════════════════════════════════════════════════════
-- Section 1: character classification (byte-based for hot loops)
-- ════════════════════════════════════════════════════════════════════════════
-- Two APIs:
-- is_space(c), is_alpha(c), etc. — accept a single-char STRING (legacy)
-- is_space_byte(b), is_alpha_byte(b), etc. — accept a single-byte INTEGER
-- The byte-based versions are 5-10x faster in tight loops because they avoid the string allocation per s:sub(pos, pos) call.
-- Byte-based versions (accept a single-byte INTEGER).
-- Used in all hot loops because they avoid the string allocation per s:sub(pos, pos) call.
-- Whitespace characters per C locale.
function M.is_space_byte(b) return b == BYTE_SPACE or b == BYTE_TAB or b == BYTE_NEWLINE or b == BYTE_CR or b == BYTE_VT or b == BYTE_FF end
@@ -238,6 +228,9 @@ end
-- Section 3: I/O primitives
-- ════════════════════════════════════════════════════════════════════════════
-- File contents intentionally use io.open below. LuaFileSystem handles path
-- metadata, directory iteration, the current directory, and mkdir; it does not
-- expose file-content read/write streams.
function M.read_file(path)
local f = io.open(path, "r")
if not f then error("Cannot open " .. path) end
@@ -256,16 +249,13 @@ end
-- @param path string
-- @param content string
function M.write_file_lf(path, content)
local f = io.open(path, "wb")
local f = io.open(path, "wb")
if not f then error("Cannot write " .. path) end
f:write(content); f:close()
end
-- Return `{path, ...}` for files in `out_root` whose basename matches
-- `pattern` (Lua pattern, NOT regex — `%.` not `\.`). Empty list if
-- `out_root` doesn't exist or matches nothing.
--
-- **Cost:** ~2ms native (lfs.dir) vs ~56ms subprocess (`dir /b`).
-- Return `{path, ...}` for files in `out_root` whose basename matches `pattern` (Lua pattern, NOT regex — `%.` not `\.`).
-- Empty list if `out_root` doesn't exist or matches nothing.
-- @param out_root Path
-- @param pattern string -- Lua pattern matched against basename only
-- @return string[]
@@ -284,8 +274,7 @@ end
-- Normalizes forward slashes to backslashes on Windows.
-- Used for byte-identical emit: the // Source: comment line uses the absolute path.
--
-- The CWD is memoized on first call (one lfs.currentdir() per process — ~0ms).
-- Without the cache, calling this per-source in the components pass added ~1.5s to a 30-source build.
-- The CWD is memoized on first call.
-- @param path string
-- @return string
local _absolute_path_cache = {}
@@ -298,20 +287,16 @@ function M.to_absolute_path(path)
_absolute_path_cache[path] = result
return result
end
-- lfs.currentdir() is ~0ms vs io.popen("cd") at ~50ms per call on Windows.
local cwd = lfs.currentdir()
local cwd = lfs.currentdir()
if not cwd then _absolute_path_cache[path] = path; return path end
cwd = cwd:gsub("/", "\\")
local tail = (path:gsub("/", "\\"))
local tail = (path:gsub("/", "\\"))
local result = cwd .. "\\" .. tail
_absolute_path_cache[path] = result
return result
end
-- Cache of directories already verified to exist in this process.
-- Each ensure_dir() call may otherwise spawn a `cmd.exe mkdir` (50-100ms per call on Windows) — calling it inside per-source loops added 1.5+
-- seconds to the report pass. Cache makes ensure_dir idempotent within the process lifetime.
-- (safe across passes; the dir state doesn't change).
local _ensured_dirs = {}
function M.ensure_dir(path)
@@ -409,15 +394,11 @@ function M.scan_to_char(s, target, start)
local target_byte = target:byte()
local pos = start
while pos <= #s do
local c = s:byte(pos)
if c == target_byte then return pos end
-- scan: ... <target found> | <skipping to target>
if c == BYTE_OPEN_PAREN then local _, a = M.read_balanced(s, "(", ")", pos); pos = a
-- scan: ... ( <balanced> ) ...
elseif c == BYTE_OPEN_BRACE then local _, a = M.read_balanced(s, "{", "}", pos); pos = a
-- scan: ... { <balanced> } ...
elseif c == BYTE_OPEN_BRACK then local _, a = M.read_balanced(s, "[", "]", pos); pos = a
-- scan: ... [ <balanced> ] ...
local c = s:byte(pos)
if c == target_byte then return pos end -- scan: ... <target found> | <skipping to target>
if c == BYTE_OPEN_PAREN then local _, a = M.read_balanced(s, "(", ")", pos); pos = a -- scan: ... ( <balanced> ) ...
elseif c == BYTE_OPEN_BRACE then local _, a = M.read_balanced(s, "{", "}", pos); pos = a -- scan: ... { <balanced> } ...
elseif c == BYTE_OPEN_BRACK then local _, a = M.read_balanced(s, "[", "]", pos); pos = a -- scan: ... [ <balanced> ] ...
else
local nx = M.skip_str_or_cmt(s, pos)
pos = (nx > pos) and nx or (pos + 1)
@@ -440,12 +421,11 @@ function M.skip_preprocessor_line(s, pos)
return scan + 1
end
-- Split a brace-body into top-level comma-separated tokens. Honors nested
-- parens/braces/brackets and skips strings/comments.
-- Split a brace-body into top-level comma-separated tokens. Honors nested parens/braces/brackets and skips strings/comments.
--
-- FIX (2026-07-09): split at top-level NEWLINES and SEMICOLONS too, AND emit a token break after a top-level comment/string.
-- Previous behavior glued the macro call after a comment into the same token, so `word_count_of_token` only saw the
-- leading ident (often nil after stripping the comment), undercounting the body. See Phase 1 of the branch-offset regression investigation.
-- leading ident (often nil after stripping the comment), undercounting the body.
-- Pure-comment / pure-string chunks (which now appear between real statements) are filtered out so they contribute 0 words instead of 1.
function M.split_top_level_commas(body)
local tokens = {}
@@ -534,15 +514,11 @@ function M.split_top_level_commas(body)
end
-- ════════════════════════════════════════════════════════════════════════════
-- Section 4b: tokenize_body + build_body_line_index (shared, memoized)
-- Section 4: tokenize_body + build_body_line_index (shared, memoized)
-- ════════════════════════════════════════════════════════════════════════════
-- Moved here from passes/static_analysis.lua so all passes can share the memoized
-- per-body tokenization. The memoization key is the body string (immutable per pass).
local _tokenize_body_cache = {}
local _tokenize_body_simple_cache = {}
local _body_line_index_cache = {}
local _tokenize_body_cache = {}
local _body_line_index_cache = {}
--- Tokenize the body inner-text into a flat list of `{tok, rel}` pairs.
--- `tok` is the trimmed token string; `rel` is the byte offset within `body`.
@@ -552,30 +528,27 @@ local _body_line_index_cache = {}
function M.tokenize_body(body)
if _tokenize_body_cache[body] ~= nil then return _tokenize_body_cache[body] end
local out = {}
local len = #body
local rel = 1
local len = #body
local rel = 1
while rel <= len do
local ws_end = M.skip_ws_and_cmt(body, rel)
if ws_end > rel then rel = ws_end end
if rel > len then break end
if rel > len then break end
local scan = rel
while scan <= len do
local c = body:byte(scan)
-- Terminator bytes (delimit a token at the top level): ',' = 0x2C,
-- '\n' = 0x0A, ';' = 0x3B. These also appear as separators between
-- argument lists inside the parens/braces/brackets, so we stop the
-- scan when we hit any of them.
-- Terminator bytes (delimit a token at the top level): ',' = 0x2C, '\n' = 0x0A, ';' = 0x3B.
-- These also appear as separators between argument lists inside the parens/braces/brackets,
-- so we stop the scan when we hit any of them.
if c == BYTE_COMMA then break end
if c == BYTE_NEWLINE then break end
if c == BYTE_SEMI then break end
-- Group opener bytes (consume the balanced group via the matching reader):
-- '(' = 0x28, '{' = 0x7B, '[' = 0x5B.
-- Group opener bytes (consume the balanced group via the matching reader): '(' = 0x28, '{' = 0x7B, '[' = 0x5B.
if c == BYTE_OPEN_PAREN then local _, a = M.read_parens (body, scan); scan = a
elseif c == BYTE_OPEN_BRACE then local _, a = M.read_braces (body, scan); scan = a
elseif c == BYTE_OPEN_BRACK then local _, a = M.read_brackets (body, scan); scan = a
-- String-literal byte ('"' = 0x22 or '\'' = 0x27): skip past the
-- quoted region in one shot.
-- String-literal byte ('"' = 0x22 or '\'' = 0x27): skip past the quoted region in one shot.
elseif c == BYTE_DQUOTE or c == BYTE_SQUOTE then
scan = M.skip_str_or_cmt(body, scan) + 1
else
@@ -595,21 +568,6 @@ function M.tokenize_body(body)
return out
end
--- Tokenize the body into a flat list of trimmed string tokens (preserves comments).
--- Uses `split_top_level_commas` (which appends trailing comments to the previous token)
--- so the components pass can emit `/* Words: ... */` comments in the .macs.h output.
--- Memoized on body string (R7 lift; mirror of M.tokenize_body's memoization).
--- @param body string
--- @return string[]
function M.tokenize_body_simple(body)
if _tokenize_body_simple_cache[body] ~= nil then return _tokenize_body_simple_cache[body] end
local tokens = M.split_top_level_commas(body)
local out = {}
for i = 1, #tokens do out[i] = M.trim(tokens[i]) end
_tokenize_body_simple_cache[body] = out
return out
end
--- Build a line-index: count `\n` chars from offset 1 up to the offset; that count + 1 is the line number (1-based).
--- Memoized on the body string.
--- @param body string
@@ -617,7 +575,7 @@ end
function M.build_body_line_index(body)
if _body_line_index_cache[body] ~= nil then return _body_line_index_cache[body] end
local index = {}
local len = #body
local len = #body
local newline_count = 0
for pos = 1, len do
if pos > 1 then
@@ -639,7 +597,7 @@ end
--- @param tok string
--- @return integer|nil
function M.find_marker_call_end(tok)
local ident, after = M.read_ident(tok, 1)
local ident, after = M.read_ident(tok, 1)
if not ident then return nil end
if ident ~= "atom_label" and ident ~= "atom_offset" then return nil end
local paren_pos = M.skip_ws_and_cmt(tok, after)
@@ -648,6 +606,41 @@ function M.find_marker_call_end(tok)
return close
end
--- True iff `tok` is an atom-label or atom-offset marker call.
--- Sibling helper to M.find_marker_call_end; uses the same string constants.
--- @param tok string
--- @return boolean
function M.is_marker_token(tok)
local leading = M.read_ident(tok, 1)
return leading == "atom_label" or leading == "atom_offset"
end
--- Count words contributed by the non-marker portion of `tok` (after the marker's closing `)`).
--- Returns 0 if `tok` isn't a marker call or has no trailing content.
---
--- `count_token_words_fn` is injected by the caller rather than imported here because the
--- dependency arrow already points the other way: `passes/offsets.lua` and
--- `passes/atoms_source_map.lua` both `require("word_count_eval")` and pass its
--- `count_token_words` as the 3rd argument to this function, while `word_count_eval`
--- itself loads `duffle` via `duffle_paths.lua` (see `passes/word_count_eval.lua` near
--- the top of the file) and calls `duffle.trim` / `duffle.read_ident` /
--- `duffle.skip_ws_and_cmt` from `M.count_token_words`. Importing `word_count_eval`
--- from this module would reverse that direction and form a recursive require cycle.
--- The callback keeps the marker-syntax helpers (`find_marker_call_end`,
--- `is_marker_token`, this function) shared in `duffle` without making the foundational
--- utility depend on a pass module.
--- @param tok string
--- @param word_counts table
--- @param count_token_words_fn fun(tok: string, wc: table): integer
--- @return integer
function M.count_marker_rest(tok, word_counts, count_token_words_fn)
local marker_end = M.find_marker_call_end(tok)
if not marker_end or marker_end >= #tok then return 0 end
local rest = M.trim(tok:sub(marker_end))
if rest == "" then return 0 end
return count_token_words_fn(rest, word_counts)
end
-- ════════════════════════════════════════════════════════════════════════════
-- Section 5: load_word_counts
-- ════════════════════════════════════════════════════════════════════════════
@@ -706,13 +699,6 @@ end
-- Section 7: domain tables
-- ════════════════════════════════════════════════════════════════════════════
M.WAVE_CONTEXT_REGS = {
["R_PrimCursor"] = { alias = "R_T7", size = 4, role = "output cursor (prim arena)" },
["R_FaceCursor"] = { alias = "R_T4", size = 4, role = "input cursor (face array)" },
["R_VertBase"] = { alias = "R_T5", size = 4, role = "base pointer (vertex array)" },
["R_OtBase"] = { alias = "R_T6", size = 4, role = "base pointer (ordering table)" },
}
-- The annotation DSL has been reduced to a single annotation macro:
-- atom_info(atom_bind(Binds_X), atom_reads(...), atom_writes(...))
-- All phase / region / cadence / async / resource / group tokens have been dropped.
@@ -725,18 +711,17 @@ M.TAPE_ATOM_MACROS = {
-- GTE pipeline-fill latency table.
--
-- For each `gte_cmdw_*` macro in code/duffle/gte.h, the minimum number of consecutive COP2 "nop" words that MUST appear
-- before the command issues so that any preceding `lwc2`/`swc2`/C2 state writes have retired before the GTE starts
-- reading its input registers.
-- before the command issues so that any preceding `lwc2`/`swc2`/C2 state writes have retired before the GTE starts reading its input registers.
--
-- The check (`scripts/passes/static_analysis.lua :: check_gte_pipeline_fill`) walks each atom body,
-- counts the consecutive nop words before every `gte_cmdw_*` invocation, and reports a finding if the count is below this minimum.
--
-- PRE-FILL vs POST-FILL: this table models PRE-cmdw nops (retiring preceding C2 writes), NOT the post-cmdw input-latch
-- window. The PSX-SPX pipeline timings doc (`docs/psx-spx/docs/gtepipelinetimings.md`) measures a DIFFERENT number:
-- the smallest N nops between `cop2` and `mtc2` to a specific input register at which the write no longer affects
-- the output. For nearly all instructions, inputs latch in the first 0-4 cycles — the GTE snapshots its input
-- register file early and works from internal pipeline storage afterward. The documented total cycle count is
-- NOT the "do not touch inputs" window; the actual read window is much shorter.
-- PRE-FILL vs POST-FILL: this table models PRE-cmdw nops (retiring preceding C2 writes).
-- The PSX-SPX pipeline timings doc (`docs/psx-spx/docs/gtepipelinetimings.md`) measures a DIFFERENT number:
-- the smallest N nops between `cop2` and `mtc2` to a specific input register at which the write no longer affects the output.
-- For nearly all instructions, inputs latch in the first 0-4 cycles — the GTE snapshots its input register file early and works
-- from internal pipeline storage afterward.
-- The documented total cycle count is NOT the "do not touch inputs" window; the actual read window is much shorter.
--
-- The `gte_rtpt()` / `gte_nclip()` wrapper macros in gte.h emit the pre-cmd nops internally (asm_words(nop, nop, ...)),
-- but THOSE WRAPPERS ARE NOT USED INSIDE ATOM BODIES in this codebase.
@@ -961,7 +946,7 @@ M.INSTRUCTION_LATENCY = {
["gte_nclip"] = 8, -- alias for nclip
["gte_avsz3"] = 5,
["gte_avsz4"] = 6,
-- Legacy single-cycle store helpers (gte_stotz, gte_stsxy3 are 1 cycle)
-- Single-cycle store helpers (gte_stotz, gte_stsxy3 are 1 cycle)
["gte_stotz"] = 1,
["gte_stsxy3"] = 1,
-- High-level GTE helpers (gte_load_v0/v1/v2 do multiple lwc2s)
+540 -129
View File
@@ -1,10 +1,9 @@
--- elf_dwarf.lua — ELF32 + DWARF + atoms source-map utilities for the F'' track.
---
--- elf_dwarf.lua — ELF32 + DWARF + atoms source-map utilities.
--- All ELF32 + DWARF-specific code lives here.
---
--- **What this module contains:**
--- - **Format-constant tables** (the byte-offset / opcode / size encyclopedias for ELF32, DWARF4 aranges, DWARF5 rnglists, DWARF line-program, MIPS).
--- Every constant carries a spec:` comment naming the spec section that defines it (convention established by F'').
--- Every constant carries a spec:` comment naming the spec section that defines it.
--- - **I/O helpers**: little-endian byte read/write, ELF32 section walker, nm symbol reader, source-map parser, native directory glob.
---
--- **Conventions:** tabs (1/level), EmmyLua annotations, no regex,
@@ -14,13 +13,82 @@
-- Native dependencies
-- ════════════════════════════════════════════════════════════════════════════
-- lfs is wired into package.cpath by `duffle_paths.lua` (vendored under
-- `toolchain/lfs/lfs.dll`). Required here for native directory ops
-- (replaces the ~56ms `dir /b` subprocess with ~2ms native).
-- lfs is wired into package.cpath by `duffle_paths.lua` (vendored under `toolchain/lfs/lfs.dll`).
local lfs = require("lfs")
local M = {}
-- ════════════════════════════════════════════════════════════════════════════
-- DWARF tag + form constants
-- ════════════════════════════════════════════
-- (DWARF5 §7.5.5 "Tag Encodings" + Table 7.1; gcc emits these exact values for the DWARF3-extension and DWARF5 line units.)
M.DW_TAG = {
compile_unit = 0x11,
subprogram = 0x2E,
variable = 0x34,
structure_type = 0x13,
member = 0x0D,
base_type = 0x24,
typedef = 0x2A,
pointer_type = 0x0F,
const_type = 0x26,
volatile_type = 0x27,
inlined_subroutine = 0x1D,
-- We index the canonical gcc-emitted tags. Anything else falls through.
}
M.DW_AT = {
name = 0x03,
low_pc = 0x11,
high_pc = 0x12,
language = 0x13,
location = 0x02,
comp_dir = 0x1B,
byte_size = 0x0B,
encoding = 0x3E,
data_member_location = 0x38,
type = 0x49,
linkage_name = 0x6E,
external = 0x3F,
abstract_origin = 0x31,
call_file = 0x58,
call_line = 0x59,
inline = 0x20,
decl_file = 0x3A,
decl_line = 0x3B,
}
M.DW_FORM = {
addr = 0x01,
data1 = 0x0B,
data2 = 0x05,
data4 = 0x06,
string = 0x08,
strp = 0x0E,
exprloc = 0x18,
ref4 = 0x13,
udata = 0x0F,
ref_sig8 = 0x20,
implicit_const = 0x21,
flag_present = 0x19,
sec_offset = 0x17,
}
M.DW_ATE = {
address = 0x01,
boolean = 0x02,
complex_float = 0x03,
float = 0x04,
signed = 0x05,
signed_char = 0x06,
unsigned = 0x07,
unsigned_char = 0x08,
}
-- DWARF5 §7.5.6 DW_FORM_implicit_const
local DW_FORM_implicit_const = 0x21
-- ════════════════════════════════════════════════════════════════════════════
-- Format-constant tables
-- ════════════════════════════════════════════════════════════════════════════
@@ -32,51 +100,51 @@ local M = {}
--- spec: MIPS o32 ABI §"Register Usage" — 32-bit general-purpose registers
M.MIPS_BYTES_PER_WORD = 0x04
-- ----------------------------------------------------------------------------
-- ELF32 (System V ABI gABI v1.2)
-- ----------------------------------------------------------------------------
--
-- All offsets are 1-INDEXED (matching Lua string.sub convention),
-- expressed in hex so they map directly to the wire-format byte positions in the binary file.
-- To compute the 0-indexed file offset, subtract 1.
--
-- Example: e_shoff_offset = 0x21 means the 4-byte e_shoff field
-- starts at string.sub byte 0x21 (= 33 in 1-indexed), i.e. file offset 0x20 (= 32).
--- **Wire-offset contract:** format offsets, fixed-width reader offsets, LEB/parser cursors,
--- and section-relative values are zero-based wire offsets. Only Lua string APIs receive
--- a `+ 1` conversion at their boundary (`byte`, `sub`, and `find`).
---
--- ELF/DWARF field offsets are expressed in hex so they map directly to the
--- zero-based byte positions in the binary file.
--- spec: System V ABI gABI v1.2 §"ELF Header" (Table 1) + §"Section Header Table"
M.ELF32 = {
magic_offset = 0x01, -- 4-byte magic "\127ELF" at file offset 0x00
magic_offset = 0x00, -- 4-byte magic "\127ELF" at file offset 0x00
magic = "\127ELF",
class_offset = 0x05, -- 1-byte; 1 = ELF32, 2 = ELF64
class_offset = 0x04, -- 1-byte; 1 = ELF32, 2 = ELF64
class_elf32 = 1,
endian_offset = 0x06, -- 1-byte; 1 = little-endian, 2 = big-endian
endian_offset = 0x05, -- 1-byte; 1 = little-endian, 2 = big-endian
endian_little = 1,
header_bytes = 0x34, -- spec: gABI v1.2 §"ELF Header" — ELF32 header is 52 bytes total
e_shoff_offset = 0x21, -- 4-byte LE; section-header table file offset
e_shentsize_offset = 0x2F, -- 2-byte LE; section-header entry size in bytes
e_shnum_offset = 0x31, -- 2-byte LE; number of section headers
e_shstrndx_offset = 0x33, -- 2-byte LE; index of section-name string table
e_shoff_offset = 0x20, -- 4-byte LE; section-header table file offset
e_shentsize_offset = 0x2E, -- 2-byte LE; section-header entry size in bytes
e_shnum_offset = 0x30, -- 2-byte LE; number of section headers
e_shstrndx_offset = 0x32, -- 2-byte LE; index of section-name string table
sh_size_bytes = 0x28, -- spec: gABI v1.2 §"Section Header Table" — each entry is 40 bytes
sh_name_offset = 0x01, -- 4-byte LE; offset into .shstrtab
sh_type_offset = 0x05, -- 4-byte LE; section type (SHT_*)
sh_offset_offset = 0x11, -- 4-byte LE; section's file offset
sh_size_offset = 0x15, -- 4-byte LE; section's size in bytes
sh_name_offset = 0x00, -- 4-byte LE; offset into .shstrtab
sh_type_offset = 0x04, -- 4-byte LE; section type (SHT_*)
sh_offset_offset = 0x10, -- 4-byte LE; section's file offset
sh_size_offset = 0x14, -- 4-byte LE; section's size in bytes
dw_dwarf32_terminator = 0xFFFFFFFF, -- spec: DWARF4 spec §7.4 — 32-bit DWARF initial-length terminator
}
-- ----------------------------------------------------------------------------
-- DWARF4 .debug_aranges (per DWARF5 spec §7.4 — Address Range Table)
-- ----------------------------------------------------------------------------
--
-- All offsets are 1-INDEXED (matching Lua string.sub convention), in hex.
-- All offsets are zero-based wire offsets.
--- spec: DWARF5 spec §7.4 (Address Range Table) — 32-bit DWARF form
M.DWARF4_ARANGES = {
unit_length_offset = 0x01, -- 4-byte LE; length of unit body (excludes these 4 bytes)
version_offset = 0x05, -- 2-byte LE; expected = 2
cu_offset_offset = 0x07, -- 4-byte LE; CU DIE offset in .debug_info
addr_size_offset = 0x0B, -- 1-byte; expected = 4 (32-bit MIPS)
seg_size_offset = 0x0C, -- 1-byte; expected = 0
unit_length_offset = 0x00, -- 4-byte LE; length of unit body (excludes these 4 bytes)
version_offset = 0x04, -- 2-byte LE; expected = 2
cu_offset_offset = 0x06, -- 4-byte LE; CU DIE offset in .debug_info
addr_size_offset = 0x0A, -- 1-byte; expected = 4 (32-bit MIPS)
seg_size_offset = 0x0B, -- 1-byte; expected = 0
entry_size = 0x08, -- 4-byte addr + 4-byte length (per §7.4)
terminator_size = 0x08, -- 8 zero bytes (per §7.4 end-of-list marker)
version_expected = 2,
@@ -87,17 +155,16 @@ M.DWARF4_ARANGES = {
-- ----------------------------------------------------------------------------
-- DWARF5 .debug_rnglists (per DWARF5 spec §2.17 + §7.21)
-- ----------------------------------------------------------------------------
--
-- All offsets are 1-INDEXED (matching Lua string.sub convention), in hex.
-- All offsets are zero-based wire offsets.
--- spec: DWARF5 spec §2.17 + §7.21 (Range List Table) — 32-bit DWARF form
M.DWARF5_RNGLISTS = {
unit_length_offset = 0x01, -- 4-byte LE
version_offset = 0x05, -- 2-byte LE; expected = 5
addr_size_offset = 0x07, -- 1-byte; expected = 4
seg_size_offset = 0x08, -- 1-byte; expected = 0
offset_count_offset = 0x09, -- 4-byte LE; expected = 0
first_entry_offset = 0x0D,
unit_length_offset = 0x00, -- 4-byte LE
version_offset = 0x04, -- 2-byte LE; expected = 5
addr_size_offset = 0x06, -- 1-byte; expected = 4
seg_size_offset = 0x07, -- 1-byte; expected = 0
offset_count_offset = 0x08, -- 4-byte LE; expected = 0
first_entry_offset = 0x0C,
end_of_list = 0x00, -- spec: DWARF5 §7.7 — DW_RLE_end_of_list byte value
start_length = 0x07, -- spec: DWARF5 §7.7 — DW_RLE_start_length byte value
version_expected = 5,
@@ -109,7 +176,6 @@ M.DWARF5_RNGLISTS = {
-- ----------------------------------------------------------------------------
-- DWARF line-program opcodes (per DWARF5 spec §6.2.5)
-- ----------------------------------------------------------------------------
--
-- Opcode VALUES stay in decimal — they're identifiers (DW_LNS_copy = 1), not binary positions.
-- Compare to the *_offset fields above which are hex.
@@ -121,6 +187,7 @@ M.DWARF_LINE_OPS = {
DW_LNS_advance_pc = 2,
DW_LNS_advance_line = 3,
DW_LNS_set_file = 4,
DW_LNS_negate_stmt = 6, -- spec: §6.2.5.2 — toggle the line-state is_stmt register
-- Extended sub-opcodes (§6.2.5.3)
DW_LNE_end_sequence = 1, -- spec: §6.2.5.3
DW_LNE_set_address = 2, -- spec: §6.2.5.3
@@ -141,39 +208,282 @@ M.DWARF_LINE_OPS = {
-- I/O helpers: little-endian byte read/write
-- ════════════════════════════════════════════════════════════════════════════
--- Read a 4-byte little-endian unsigned integer from `buf` at 1-indexed offset `off`.
--- Equivalent to `string.unpack("<I4", buf, off)` but avoids the table-return shape + works under LuaJIT 2.1
--- Read a 4-byte little-endian unsigned integer from `buf` at zero-based wire offset `off`.
--- Equivalent to `string.unpack("<I4", buf, off + 1)` but avoids the table-return shape + works under LuaJIT 2.1
--- (which has partial `string.unpack` coverage).
---
--- **Convention:** offsets are 1-indexed (matching Lua `string.sub`).
--- **Convention:** `off` is a zero-based wire offset; `+ 1` is applied only at the `string.byte` boundary.
---
--- **Byte weights** are written as `0x100`, `0x10000`, `0x1000000` (i.e.
--- 2^8, 2^16, 2^24) so the LE byte positions are visually explicit:
--- **Byte weights** are written as `0x100`, `0x10000`, `0x1000000` (i.e. 2^8, 2^16, 2^24) so the LE byte positions are visually explicit:
--- byte 0 contributes its value directly; byte 1 is shifted left by 8
--- (= 0x100); byte 2 by 16 (= 0x10000); byte 3 by 24 (= 0x1000000).
---
--- @param buf string
--- @param off integer -- 1-indexed
--- @param off integer -- zero-based wire offset
--- @return integer
function M.read_u32_le(buf, off)
return buf:byte(off)
+ buf:byte(off + 0x01) * 0x00000100
+ buf:byte(off + 0x02) * 0x00010000
+ buf:byte(off + 0x03) * 0x01000000
local byte_off = off + 1
return buf:byte(byte_off)
+ buf:byte(byte_off + 0x01) * 0x00000100
+ buf:byte(byte_off + 0x02) * 0x00010000
+ buf:byte(byte_off + 0x03) * 0x01000000
end
--- Read a 2-byte little-endian unsigned integer from `buf` at 1-indexed offset `off`.
--- (1-indexed convention; matches `M.read_u32_le`.)
--- Read a 2-byte little-endian unsigned integer from `buf` at zero-based wire offset `off`.
--- (`off` is zero-based; `+ 1` is applied only at the `string.byte` boundary.)
--- @param buf string
--- @param off integer -- 1-indexed
--- @param off integer -- zero-based wire offset
--- @return integer
function M.read_u16_le(buf, off)
return buf:byte(off) + buf:byte(off + 0x01) * 0x00000100
local byte_off = off + 1
return buf:byte(byte_off) + buf:byte(byte_off + 0x01) * 0x00000100
end
-- Pure-Lua 5.3 LEB128 readers (no `bit` library). `2^shift` arithmetic matches the existing parser.
-- Offsets are 0-based; returns (value, next_pos).
-- Track A Task 10: promoted from `local function` to M.* exports so passes/dwarf_injection.lua
-- can import them as file-scope locals per the 2nd-caller lift precedent
-- (the uleb128 + sleb128 encoders were promoted the same way).
function M.read_uleb128_at(buf, pos)
local value, shift = 0, 0
local len = #buf
while pos < len do
local b = buf:byte(pos + 1)
value = value + (b % 0x80) * (2 ^ shift)
shift = shift + 7
pos = pos + 1
if b < 0x80 then return value, pos end
end
return nil, pos
end
function M.read_sleb128_at(buf, pos)
local value, shift = 0, 0
local len = #buf
while pos < len do
local b = buf:byte(pos + 1)
value = value + (b % 0x80) * (2 ^ shift)
shift = shift + 7
pos = pos + 1
if b < 0x80 then
if b >= 0x40 then value = value - (2 ^ shift) end
return value, pos
end
end
return nil, pos
end
-- Find the 0-based offset of the table-terminator byte (a single 0) for the abbrev table starting at `table_start`.
-- Returns nil on truncated input. Walks declaration headers
-- (code, tag, has_children, attr/form pairs, DW_FORM_implicit_const constant) until it finds a 0 byte that follows a complete declaration.
function M.find_abbrev_table_end(table_bytes, table_start)
local pos, len = table_start, #table_bytes
if pos >= len or table_bytes:byte(pos + 1) == 0 then return pos end
while pos < len do
local _code, code_end = M.read_uleb128_at(table_bytes, pos)
if not _code then return nil end
pos = code_end
local _tag, tag_end = M.read_uleb128_at(table_bytes, pos)
if not _tag then return nil end
pos = tag_end
if pos >= len then return nil end
pos = pos + 1 -- has_children byte
while pos < len do
local attr, attr_end = M.read_uleb128_at(table_bytes, pos)
if not attr then return nil end
pos = attr_end
local form, form_end = M.read_uleb128_at(table_bytes, pos)
if not form then return nil end
pos = form_end
if attr == 0 and form == 0 then break end
if form == DW_FORM_implicit_const then
local _c, ce = M.read_sleb128_at(table_bytes, pos)
if not _c then return nil end
pos = ce
end
end
if pos >= len then return nil end
if table_bytes:byte(pos + 1) == 0 then return pos end
end
return nil
end
-- Read the null-terminated C string at 0-based offset `off` in `buf`.
-- Stops at the first 0 byte or end of buffer.
local function read_c_string_at(buf, off)
local len = #buf
local start = off
while off < len and buf:byte(off + 1) ~= 0 do off = off + 1 end
return buf:sub(start + 1, off)
end
-- Walk the .debug_abbrev table starting at 0-based offset `table_start` and return a list of declarations:
-- {code, tag, has_children, attrs={ {name, form}, ... }}.
-- Stops at the table terminator.
local function parse_abbrev_table(table_bytes, table_start)
local table_end = M.find_abbrev_table_end(table_bytes, table_start)
if not table_end then return nil, "no terminator" end
local decls = {}
local pos = table_start
while pos < table_end do
local code, code_end = M.read_uleb128_at(table_bytes, pos)
if not code then return nil, "truncated code" end
pos = code_end
local tag, tag_end = M.read_uleb128_at(table_bytes, pos)
if not tag then return nil, "truncated tag" end
pos = tag_end
local has_children = table_bytes:byte(pos + 1)
pos = pos + 1
local attrs = {}
while true do
local attr, attr_end = M.read_uleb128_at(table_bytes, pos)
if not attr then return nil, "truncated attr" end
pos = attr_end
local form, form_end = M.read_uleb128_at(table_bytes, pos)
if not form then return nil, "truncated form" end
pos = form_end
if attr == 0 and form == 0 then break end
attrs[#attrs + 1] = { name = attr, form = form }
if form == DW_FORM_implicit_const then
local _c, ce = M.read_sleb128_at(table_bytes, pos)
if not _c then return nil, "truncated const" end
pos = ce
end
end
decls[#decls + 1] = { code = code, tag = tag, has_children = has_children, attrs = attrs }
end
return decls
end
-- Read a ULEB attribute value at 0-based offset `pos` for the given `form`.
-- Returns (value, next_pos). For DW_FORM_string we return the inline string.
-- For DW_FORM_strp we return the inline string resolved from `str_buf`.
-- For DW_FORM_ref4 we return the absolute CU-relative offset.
-- The caller decides whether to interpret that as a section offset.
local function read_form_value(buf, str_buf, pos, form)
if form == M.DW_FORM.addr then
return M.read_u32_le(buf, pos), pos + 4
elseif form == M.DW_FORM.string then
local s = read_c_string_at(buf, pos)
return s, pos + #s + 1
elseif form == M.DW_FORM.strp then
-- DW_FORM_strp: 4-byte offset into .debug_str.
local strp_off = M.read_u32_le(buf, pos)
return read_c_string_at(str_buf, strp_off), pos + 4
elseif form == M.DW_FORM.udata then return M.read_uleb128_at(buf, pos)
elseif form == M.DW_FORM.data1 then return buf:byte(pos + 1), pos + 1
elseif form == M.DW_FORM.data2 then return M.read_u16_le(buf, pos), pos + 2
elseif form == M.DW_FORM.data4 then return M.read_u32_le(buf, pos), pos + 4
elseif form == M.DW_FORM.ref4 then return M.read_u32_le(buf, pos), pos + 4
elseif form == M.DW_FORM.sec_offset then
-- DW_FORM_sec_offset: 4-byte offset (size depends on DWARF version;
-- on DWARF5 32-bit it's always 4 bytes).
return M.read_u32_le(buf, pos), pos + 4
elseif form == M.DW_FORM.flag_present then
return 1, pos
elseif form == M.DW_FORM.exprloc then
-- DW_FORM_exprloc: ULEB byte count + that many bytes of DW_OP_*.
local len, ne = M.read_uleb128_at(buf, pos)
if not len then return nil, pos end
return nil, ne + len
elseif form == DW_FORM_implicit_const then
-- The constant is declared in the abbrev; no value bytes in the DIE.
return nil, pos
elseif form == M.DW_FORM.ref_sig8 then
-- DW_FORM_ref_sig8 (DWARF5 §7.4.2): an 8-byte value identifying a type
-- by signature. The low 4 bytes (LE) are the type signature (content hash);
-- the high 4 bytes (LE) are a CU-relative offset into the matching type unit.
-- Consumers use the low 4 to look up the type unit (see M.find_type_unit_by_signature)
-- then the high 4 to resolve the specific type within it.
-- Return the low 4 as the primary value to preserve the (value, next_pos) shape;
-- the high 4 is exposed via M.read_ref_sig8 (which returns both halves).
local _, _, next_pos = M.read_ref_sig8(buf, pos)
return M.read_u32_le(buf, pos), next_pos
else
return nil, pos
end
end
--- Read a `DW_FORM_ref_sig8` value at 0-based offset `pos` from `buf`.
--- Returns the low 4 bytes (LE) as `low`, the high 4 bytes (LE) as `high`, and
--- the cursor position after the 8-byte value as `next_pos`.
--- Callers that need the full type-unit + type-offset pair
--- (e.g. to resolve a type identifier embedded as a signature)
--- should use this directly rather than going through `read_form_value`,
--- which only exposes the low 4 bytes to preserve its existing (value, next_pos) return shape.
--- @param buf string
--- @param pos integer -- zero-based wire offset
--- @return integer -- low 4 bytes (LE), the type signature
--- @return integer -- high 4 bytes (LE), the offset within the matching type unit
--- @return integer -- cursor after the 8-byte value
function M.read_ref_sig8(buf, pos)
return M.read_u32_le(buf, pos), M.read_u32_le(buf, pos + 4), pos + 8
end
-- DWARF5 §7.5.6 (Type Entries).
-- Walk all units in `info` and return the 0-based offset of the first unit
-- whose `DW_AT_type_signature` (8-byte value at the end of the unit header) equals `target_sig`.
-- The signature is interpreted as two 32-bit halves (low/high) per the read_ref_sig8 contract;
-- we match both halves (i.e. the 8-byte value as a whole). Returns nil if no matching unit exists.
--
-- Unit header layout (from pos 0):
-- unit_length(4) + version(2) + unit_type(1) + address_size(1) + debug_abbrev_offset(4)
-- -- followed by type_unit_specific fields:
-- type_signature(8) + type_offset(4)
-- The type_signature is at byte offset 8 of the body (right after debug_abbrev_offset).
-- @param info string -- the .debug_info section bytes
-- @param target_sig_lo integer -- low 4 bytes (LE) of the desired signature
-- @param target_sig_hi integer -- high 4 bytes (LE) of the desired signature
-- @return integer|nil, integer|nil -- unit offset, type_offset within the unit
function M.find_type_unit_by_signature(info, target_sig_lo, target_sig_hi)
local pos = 0
local section_len = #info
while pos + 4 < section_len do
local unit_length = M.read_u32_le(info, pos)
if unit_length == 0xFFFFFFFF then
return nil, nil -- DWARF64 not supported
end
-- unit_length is the body size, NOT including the 4-byte unit_length field itself.
local body_start = pos + 4
local body_end = body_start + unit_length
if body_end > section_len then
return nil, nil -- malformed
end
-- Per DWARF5 §7.5.6, the type_unit (DW_UT_type = 0x02) body layout is:
-- 0: version (2)
-- 2: unit_type (1) -- DW_UT_type = 0x02
-- 3: address_size (1)
-- 4: debug_abbrev_offset (4)
-- 8: type_signature (8)
-- 16: type_offset (4)
-- 20: <children>
if body_end - body_start >= 20 then
-- read_ref_sig8 / write_u32_le / etc. are 1-indexed (string:byte);
-- pos / body_start / body_end are 0-based wire offsets, so the
-- 1-indexed byte at 0-based wire offset X is string:byte(X + 1).
-- Per DWARF5 §7.5.6, the type_unit body is laid out as:
-- byte 0-1: version (2)
-- byte 2: unit_type (1) -- DW_UT_type = 0x02
-- byte 3: address_size (1)
-- byte 4-7: debug_abbrev_offset (4)
-- byte 8-15: type_signature (8)
-- byte 16-19: type_offset (4)
local unit_type = info:byte(body_start + 2 + 1) -- 0-based +2 = unit_type in 1-indexed
if unit_type == 0x02 then -- DW_UT_type
local sig_lo, sig_hi, _ = M.read_ref_sig8(info, body_start + 8) -- 0-based +8 = type_signature in 1-indexed
if sig_lo == target_sig_lo and sig_hi == target_sig_hi then
local type_offset = M.read_u32_le(info, body_start + 16) -- 0-based +16 = type_offset in 1-indexed
return pos, type_offset
end
end
end
-- Advance to the next unit (the 4-byte unit_length + the body).
pos = body_end
end
return nil, nil
end
--- Return a 4-byte little-endian byte string for `value`.
--- Caller concatenates with `..` if composing multi-word blobs.
---
--- **Byte weights** written as `0x100` etc. (see `M.read_u32_le` for rationale).
--- @param value integer -- 0 ≤ value ≤ 0xFFFFFFFF
--- @return string
@@ -199,14 +509,14 @@ end
--- Read the named sections from a post-link ELF32 by walking the ELF32 section-header table directly
--- (no subprocess; lfs only for the existence check). Returns `{[name] = bytes_or_empty_string, ...}`.
---
--- **Convention:** offsets from `M.ELF32` (1-indexed for string.sub).
--- Every requested name has an entry in the returned dict; missing sections have an empty string (NOT nil)
--- so callers can do `sections[".debug_x"] or ""` for the missing case.
--- **Convention:** ELF/DWARF offsets are zero-based wire offsets. Direct Lua string APIs add `+ 1` at the boundary.
--- Every requested name has an entry in the returned dict;
--- missing sections have an empty string (NOT nil) so callers can do `sections[".debug_x"] or ""` for the missing case.
---
--- **Cost:** one file open + one `f:seek` + one `f:read` per section header
--- (we walk all `e_shnum` headers regardless of how many names are requested, to find the .shstrtab first).
--- For frequent callers, pass the union of all needed sections in one call.
-- can add `.debug_info` + `.debug_loc` + `.debug_str_offsets` to the list without writing a 2nd ELF walker.
-- Can add `.debug_info` + `.debug_loc` + `.debug_str_offsets` to the list without writing a 2nd ELF walker.
--- @param elf_path Path
--- @param section_names string[] -- list of section names to read
--- @return table<string, string>
@@ -241,17 +551,17 @@ function M.read_elf_sections(elf_path, section_names)
end
-- Sanity-check magic + class + endianness.
if header:sub(M.ELF32.magic_offset, M.ELF32.magic_offset + 0x03) ~= M.ELF32.magic then
if header:sub(M.ELF32.magic_offset + 1, M.ELF32.magic_offset + 0x04) ~= M.ELF32.magic then
io.stderr:write("[elf_dwarf.read_elf_sections] not an ELF file\n")
f:close()
return result
end
if header:byte(M.ELF32.class_offset) ~= M.ELF32.class_elf32 then
io.stderr:write(string.format("[elf_dwarf.read_elf_sections] not ELF32 (class=%d)\n", header:byte(M.ELF32.class_offset)))
if header:byte(M.ELF32.class_offset + 1) ~= M.ELF32.class_elf32 then
io.stderr:write(string.format("[elf_dwarf.read_elf_sections] not ELF32 (class=%d)\n", header:byte(M.ELF32.class_offset + 1)))
f:close()
return result
end
if header:byte(M.ELF32.endian_offset) ~= M.ELF32.endian_little then
if header:byte(M.ELF32.endian_offset + 1) ~= M.ELF32.endian_little then
io.stderr:write("[elf_dwarf.read_elf_sections] not little-endian; unsupported\n")
f:close()
return result
@@ -305,16 +615,12 @@ end
--- Read ELF symbol addresses by walking the `.symtab` + `.strtab` sections directly (no `nm` subprocess).
--- Returns a map `{name -> {addr, size_bytes}}` for every `code_<name>` symbol.
---
--- **Why direct parsing instead of `mipsel-none-elf-nm -S`?**
--- The `nm` subprocess costs ~50ms per spawn on Windows (cmd.exe + mipsel-none-elf-nm.exe). Parsing `.symtab` ourselves is ~0ms.
--- Same return shape, same `code_` prefix filter.
---
--- **Conventions:**
--- - ELF32 symtab entry = 16 bytes (`st_name:4 + st_value:4 + st_size:4 + st_info:1 + st_other:1 + st_shndx:2`). 1-indexed for Lua string.sub.
--- - ELF32 symtab entry = 16 bytes (`st_name:4 + st_value:4 + st_size:4 + st_info:1 + st_other:1 + st_shndx:2`); offsets within each entry are zero-based wire offsets.
--- - Direct Lua `string.byte`/`string.sub`/`string.find` boundaries receive `+ 1`.
--- - We filter on STB_GLOBAL (high nibble of st_info = 1) to match `nm`'s default (external symbols only). STB_WEAK excluded.
--- - We strip the `code_` prefix to match the previous `read_nm` output.
--- - `st_size > 0` filter excludes undefined/imported symbols.
---
--- @param elf_path Path
--- @return table<string, {integer, integer}>
function M.read_nm(elf_path)
@@ -330,32 +636,31 @@ function M.read_nm(elf_path)
end
-- Iterate the 16-byte ELF32 symtab entries.
-- Each entry (1-indexed): st_name at 1, st_value at 5, st_size at 9,
-- st_info at 13, st_other at 14, st_shndx at 15.
-- Each entry (zero-based): st_name at 0, st_value at 4, st_size at 8, st_info at 12, st_other at 13, st_shndx at 14.
local SYM_ENTRY_BYTES = 0x10
local SYM_ST_NAME = 0x01
local SYM_ST_VALUE = 0x05
local SYM_ST_SIZE = 0x09
local SYM_ST_INFO = 0x0D
local SYM_ST_NAME = 0x00
local SYM_ST_VALUE = 0x04
local SYM_ST_SIZE = 0x08
local SYM_ST_INFO = 0x0C
local n_syms = #symtab / SYM_ENTRY_BYTES
for i = 0, n_syms - 1 do
local entry_off = i * SYM_ENTRY_BYTES + 1 -- 1-indexed
local st_info = symtab:byte(entry_off + SYM_ST_INFO - 1)
local entry_off = i * SYM_ENTRY_BYTES
local st_info = symtab:byte(entry_off + SYM_ST_INFO + 1)
-- High nibble = binding (STB_LOCAL=0, STB_GLOBAL=1, STB_WEAK=2).
-- Use math.floor(/16) instead of bit.rshift for LuaJIT 2.1 compat
-- (LuaJIT's `>>` is 5.3+, but math.floor(x/16) works on all versions).
local binding = math.floor(st_info / 16)
if binding == 0 or binding == 1 then -- STB_LOCAL or STB_GLOBAL
local st_size = M.read_u32_le(symtab, entry_off + SYM_ST_SIZE - 1)
local st_size = M.read_u32_le(symtab, entry_off + SYM_ST_SIZE)
if st_size > 0 then
local st_name_off = M.read_u32_le(symtab, entry_off + SYM_ST_NAME - 1)
local st_name_off = M.read_u32_le(symtab, entry_off + SYM_ST_NAME)
-- Extract the name from .strtab (null-terminated C string).
local name_end = strtab:find("\0", st_name_off + 1, true) or (st_name_off + 1)
local name = strtab:sub(st_name_off + 1, name_end - 1)
-- Filter: keep all symbol-table symbols (atoms emit their name as the bare `<name>` since the `code_` prefix was removed from the MipsAtom_ macro).
-- The atoms_source_map pass already filters out non-atom symbols via the source-map.txt cross-ref.
if name and #name > 0 then
local st_value = M.read_u32_le(symtab, entry_off + SYM_ST_VALUE - 1)
local st_value = M.read_u32_le(symtab, entry_off + SYM_ST_VALUE)
addrs[name] = { st_value, st_size }
end
end
@@ -373,7 +678,6 @@ end
-- Both encoders pack 7 bits of data per byte + 1 bit of "more bytes follow" signaling.
--
-- Per-byte layout:
--
-- bit: 7 6 5 4 3 2 1 0
-- │ └───── 7-bit data ─────┘
-- └─ continuation flag (LEB_CONT_BIT = 0x80)
@@ -399,16 +703,19 @@ local LEB_DATA_MASK = 0x7F
local SLEB_SIGN_BIT = 0x40
--- ULEB128 (Unsigned Little-Endian Base 128) encoder. Returns the byte string for the non-negative integer `n`.
---
--- Algorithm:
--- - Extract the low 7 bits of `n` (LEB_DATA_MASK = 0x7F).
--- - Shift `n` right by 7 bits.
--- - If more bytes remain, OR in the continuation flag (LEB_CONT_BIT).
--- - Repeat until `n` is fully consumed.
---
--- @param n integer -- non-negative
--- @return string
function M.uleb128(n)
if n == nil or type(n) ~= "number" then
io.stderr:write("[elf_dwarf.uleb128] got " .. type(n) .. ": " .. tostring(n) .. "\n")
io.stderr:write(debug.traceback() .. "\n")
error("uleb128 requires non-negative number")
end
assert(n >= 0, "uleb128 requires non-negative input")
local bytes = {}
repeat
@@ -420,26 +727,22 @@ function M.uleb128(n)
return table.concat(bytes)
end
--- SLEB128 (Signed Little-Endian Base 128) encoder. Returns the byte
--- string for the integer `n` (may be negative).
---
--- Algorithm differs from ULEB128 by the termination condition: stop when
--- the remaining bits can be inferred from the sign bit in the last byte's
--- 7-bit data payload.
--- SLEB128 (Signed Little-Endian Base 128) encoder. Returns the byte string for the integer `n` (may be negative).
--- Algorithm differs from ULEB128 by the termination condition:
--- stop when the remaining bits can be inferred from the sign bit in the last byte's 7-bit data payload.
--- - If `n == 0` (no more value bits) AND bit 6 of the data = 0 → positive terminator (sign bit says "zero-extend").
--- - If `n == -1` (sign-extended all-1s) AND bit 6 of the data = 1 → negative terminator (sign bit says "one-extend").
---
--- Without these checks, the decoder would round-trip to a different value
--- (e.g. encoding `0` as `0x80 0x00` decodes to `0` correctly but is 2 bytes long; the termination check picks the 1-byte `0x00` form).
---
--- @param n integer -- any integer (negative allowed)
--- @return string
function M.sleb128(n)
local bytes = {}
local more = true
while more do
local b = n % (LEB_DATA_MASK + 1) -- extract low 7 bits
n = (n - b) / (LEB_DATA_MASK + 1) -- arithmetic shift right by 7
local b = n % (LEB_DATA_MASK + 1) -- extract low 7 bits
n = (n - b) / (LEB_DATA_MASK + 1) -- arithmetic shift right by 7
-- Termination: remaining value bits fit in the sign bit of the last byte.
if n == 0 and b < SLEB_SIGN_BIT then more = false end -- positive terminator
if n == -1 and b >= SLEB_SIGN_BIT then more = false end -- negative terminator
@@ -449,10 +752,96 @@ function M.sleb128(n)
return table.concat(bytes)
end
--- ULEB128 byte-length: number of bytes the encoder M.uleb128 would produce for `n`.
--- Used by callers that need to size a buffer before encoding (e.g. compute_loclists_offsets
--- needs the encoded length of an `uleb128(4)` for a `DW_OP_piece + uleb128(U4_BYTE_SIZE)` tail).
--- @param n integer -- non-negative
--- @return integer -- 1..5 for n in [0, 2^32)
function M.uleb128_size(n)
assert(n >= 0, "uleb128_size requires non-negative input")
if n == 0 then return 1 end
local bytes = 1
while n >= 0x80 do
n = (n - (n % (LEB_DATA_MASK + 1))) / (LEB_DATA_MASK + 1) -- arithmetic shift right by 7
bytes = bytes + 1
end
return bytes
end
--- SLEB128 byte-length: number of bytes the encoder M.sleb128 would produce for `n`.
--- Used by callers that need to size a buffer before encoding.
--- (e.g. compute_loclists_offsets needs the encoded length of an `sleb128(field.offset)` in a tape piece).
--- Handles the signed DWARF5 termination: positive terminator if (n == 0) and bit 6 of last byte is unset;
--- negative terminator if (n == -1) and bit 6 of last byte is set.
--- @param n integer -- any integer (negative allowed)
--- @return integer
function M.sleb128_size(n)
local more = true
local bytes = 0
local v = n
while more do
local b = v % (LEB_DATA_MASK + 1) -- extract low 7 bits
v = (v - b) / (LEB_DATA_MASK + 1) -- arithmetic shift right by 7
if v == 0 and b < SLEB_SIGN_BIT then more = false end -- positive terminator
if v == -1 and b >= SLEB_SIGN_BIT then more = false end -- negative terminator
if more then b = b + LEB_CONT_BIT end
bytes = bytes + 1
end
return bytes
end
-- ════════════════════════════════════════════════════════════════════════════
-- I/O helpers: atoms source-map + native directory glob
-- ════════════════════════════════════════════════════════════════════════════
--- Parse a FORMAT_VERSION <expected_version> atoms-meta file (sourcemap or provenance).
--- Shared by M.parse_source_map_file + M.parse_provenance_file.
--- The two callers differ only in how they parse WORD lines; that's `extract_word(line)`.
--- Returns the standard `{name -> {total, words}}` shape.
--- Returns `{}` on format-version mismatch (and logs to stderr).
--- @param path string
--- @param expected_version integer
--- @param extract_word fun(line: string): table|nil -- caller-supplied per-line parser
--- @return table<string, table>
function M.parse_atom_records(path, expected_version, extract_word)
local out = {}
local cur_name, cur_words = nil, {}
for raw in io.lines(path) do
local line = raw
if line:match("^#") then
local ver = line:match("^# FORMAT_VERSION%s+(%d+)")
if ver and tonumber(ver) ~= expected_version then
io.stderr:write(string.format(
"[elf_dwarf.parse_atom_records] version mismatch (got %s, expected %d) in %s\n",
ver, expected_version, path))
return {}
end
-- skip other comments
elseif line:sub(1, 4) == "ATOM" then
-- ATOM <name> "<abs-source-path>" <total>
local _, _, name = line:find("ATOM%s+(%S+)%s+\"[^\"]*\"%s+(%d+)")
if name then
cur_name = name
cur_words = {}
out[name] = { total = 0, words = cur_words }
end
elseif line == "ENDATOM" then
-- Update the recorded total from the entries count
-- (matches the `lines[1] = lines[1]:gsub(" 0$", " " .. total)` patch in atoms_source_map.lua:170).
if cur_name and out[cur_name] then
out[cur_name].total = #cur_words
end
cur_name, cur_words = nil, {}
elseif line:sub(1, 4) == "WORD" and cur_name then
local field = extract_word(line)
if field then
cur_words[#cur_words + 1] = field
end
end
end
return out
end
--- Parse a FORMAT_VERSION <expected_version> `*.atoms.sourcemap.txt` file.
--- Returns `{name -> {total = N, words = {{pos, line}, ...}}}`.
--- Returns `{}` on format-version mismatch (and logs to stderr).
@@ -472,43 +861,65 @@ end
--- @param expected_version integer -- expected FORMAT_VERSION line
--- @return table<string, table>
function M.parse_source_map_file(sm_path, expected_version)
local out = {}
local cur_name, cur_words = nil, {}
for raw in io.lines(sm_path) do
local line = raw
if line:match("^#") then
local ver = line:match("^# FORMAT_VERSION%s+(%d+)")
if ver and tonumber(ver) ~= expected_version then
io.stderr:write(string.format(
"[elf_dwarf.parse_source_map_file] source-map version mismatch (got %s, expected %d) in %s\n",
ver, expected_version, sm_path))
return {}
end
-- skip other comments
elseif line:sub(1, 4) == "ATOM" then
-- ATOM <name> "<abs-source-path>" <total>
local _, _, name = line:find("ATOM%s+(%S+)%s+\"[^\"]*\"%s+(%d+)")
if name then
cur_name = name
cur_words = {}
out[name] = { total = 0, words = cur_words }
end
elseif line == "ENDATOM" then
-- Update the recorded total from the entries count
-- (matches the `lines[1] = lines[1]:gsub(" 0$", " " .. total)` patch in atoms_source_map.lua:170).
if cur_name and out[cur_name] then
out[cur_name].total = #cur_words
end
cur_name, cur_words = nil, {}
elseif line:sub(1, 4) == "WORD" and cur_name then
-- WORD <n> LINE <line> TEXT <text...>
local _, n, _, src_line = line:find("WORD%s+(%d+)%s+LINE%s+(%d+)")
if n and src_line then
cur_words[#cur_words + 1] = { pos = tonumber(n), line = tonumber(src_line) }
end
return M.parse_atom_records(sm_path, expected_version, function(line)
local _, n, _, src_line = line:find("WORD%s+(%d+)%s+LINE%s+(%d+)")
if n and src_line then
return { pos = tonumber(n), line = tonumber(src_line) }
end
end
return out
end)
end
--- Parse a FORMAT_VERSION <expected_version> `*.atoms.provenance.txt` file.
--- Returns `{name -> {total = N, words = {{pos, call_file, call_line, comp_name, comp_file, comp_line}, ...}}}`.
--- Returns `{}` on format-version mismatch (and logs to stderr).
---
--- **Wire format** (emitted by `passes/atoms_source_map.lua`):
--- ```
--- # FORMAT_VERSION <n>
--- ATOM <name> "<abs-source-path>" <total>
--- WORD <n> CALL <src-file>:<src-line> RAW
--- WORD <n> CALL <src-file>:<src-line> MACRO <comp_name> "<comp-file>:<comp-line>"
--- ...
--- ENDATOM
--- ```
---
--- **Used by** `passes/dwarf_injection.lua` to:
--- - group consecutive MACRO rows into component invocations (one `DW_TAG_inlined_subroutine` each)
--- - emit abstract `DW_TAG_subprogram` per unique component name
--- - extend `.debug_line` so stepping into a `mac_X(...)` lands on the component's source line.
--- @param prov_path string -- path to *.atoms.provenance.txt
--- @param expected_version integer -- expected FORMAT_VERSION line
--- @return table<string, table>
function M.parse_provenance_file(prov_path, expected_version)
return M.parse_atom_records(prov_path, expected_version, function(line)
-- Two accepted shapes:
-- WORD <n> CALL <call-file>:<call-line> RAW
-- WORD <n> CALL <call-file>:<call-line> MACRO <comp_name> "<comp-file>:<comp-line>"
local pos, call_file, call_line, comp_name, comp_file, comp_line =
line:match('WORD%s+(%d+)%s+CALL%s+(.-):(%d+)%s+MACRO%s+(%S+)%s+"([^"]*):(%d+)"')
if pos then
return {
pos = tonumber(pos),
call_file = call_file,
call_line = tonumber(call_line),
comp_name = comp_name,
comp_file = comp_file,
comp_line = tonumber(comp_line),
}
end
-- RAW row.
local raw_pos, raw_file, raw_line = line:match('WORD%s+(%d+)%s+CALL%s+(.-):(%d+)%s+RAW')
if raw_pos then
return {
pos = tonumber(raw_pos),
call_file = raw_file,
call_line = tonumber(raw_line),
comp_name = nil,
comp_file = nil,
comp_line = nil,
}
end
end)
end
return M
+15 -29
View File
@@ -1,29 +1,15 @@
# scripts/gdb/gdb_tape_atoms.gdb
#
# Wrapper for the tape-atom step-debug helpers. The 9 user commands are defined
# here as STUBS (degraded-state messages). The real implementations + the
# per-atom data tables are emitted by `passes/atoms_source_map.lua` (post-link
# invocation: `ps1_meta.lua --atoms-source-map --gdb-runtime --elf <elf>`) into
# `build/gen/gdb_tape_atoms_runtime.gdb`. Sourcing that file RE-DEFINES the
# commands with real implementations.
# Wrapper for the tape-atom step-debug helpers.
# The 9 user commands are defined here as STUBS (degraded-state messages).
# The real implementations + the per-atom data tables are emitted by `passes/atoms_source_map.lua`
# (post-link invocation: `ps1_meta.lua --atoms-source-map --gdb-runtime --elf <elf>`) into `build/gen/gdb_tape_atoms_runtime.gdb`.
# Sourcing that file RE-DEFINES the commands with real implementations.
#
# If `build/gen/gdb_tape_atoms_runtime.gdb` is missing or stale, the stubs
# remain (E1: no source map). The user just needs to re-run `build_psyq.ps1`
# to regenerate. No exceptions; no crashes.
#
# Why a wrapper + separate runtime file?
# - The runtime file is auto-generated per-build; not in git.
# - The wrapper is checked into git; always works.
# - This split keeps the script trivial and the data plumbing out of git.
#
# Compatible with every gdb build (no Python, no Tcl, no Guile required) —
# pure gdb command scripting + `set $var = val` + `define ... end`.
#
# Generated by track gdb_tape_atom_debugging_20260711 — see
# C:\projects\Pikuma\ps1-ai\docs\gdb_tape_atom_debugging.md for the manual.
# If `build/gen/gdb_tape_atoms_runtime.gdb` is missing or stale, the stubs remain (E1: no source map).
# The user just needs to re-run `build_psyq.ps1` to regenerate.
# ── Stub commands (defined here so they're always present, even if the
# runtime file is missing). The runtime file overrides these if sourced. ──
# ── Stub commands (defined here so they're always present, even if the runtime file is missing). The runtime file overrides these if sourced. ──
define tape_atoms
echo "[gdb_tape_atoms] STUB: runtime file build/gen/gdb_tape_atoms_runtime.gdb not found."
@@ -77,7 +63,7 @@ define show_c2
printf "C2[14] 0x%08x [sxy2]\n", $c2_data[14]
printf "C2[24] 0x%08x [mac0]\n", $c2_data[24]
printf "...\n"
echo "(STUB state: only 7 representative regs shown. Run build_psyq.ps1 for full dump.)"
echo "(STUB state: only 7 representative regs shown. Run build_psyq.ps1 for full dump.)"
end
document show_c2
Pretty-print all 32 C2 data registers as hex + named alias. STUB state (7 reg subset).
@@ -107,13 +93,13 @@ end
# Try to source from project-root-relative path first (the typical case).
# If the user is in a different CWD, the source will fail and stubs remain.
# The runtime file path is computed relative to the ELF's source map convention
# (build/gen/gdb_tape_atoms_runtime.gdb).
# The runtime file path is computed relative to the ELF's source map convention (build/gen/gdb_tape_atoms_runtime.gdb).
echo [gdb_tape_atoms] Wrapper loaded. Sourcing runtime file...
# Suppress the "Redefine command" prompts that would otherwise appear when the
# runtime file overrides the 9 stub commands defined above. The runtime's
# `define` blocks are intended to overwrite — there's no ambiguity to confirm.
# Suppress the "Redefine command" prompts that would otherwise appear when the runtime file overrides the 9 stub commands defined above.
# The runtime's `define` blocks are intended to overwrite — there's no ambiguity to confirm.
set confirm off
# Source the runtime file (re-defines commands with real impls + data).
source build/gen/gdb_tape_atoms_runtime.gdb
set confirm on
echo [gdb_tape_atoms] Runtime sourced successfully (9 commands now have real implementations).
echo [gdb_tape_atoms] Runtime sourced successfully (9 commands now have real implementations).
+5
View File
@@ -28,6 +28,11 @@ param(
$ErrorActionPreference = 'Stop'
$gdbInitPath = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..\build\gen\hello_gte.gdbinit'))
if (-not (Test-Path -LiteralPath $gdbInitPath -PathType Leaf)) {
Write-Warning "Generated GDB skip sidecar missing (non-fatal): $gdbInitPath. Run the GTE build to regenerate it; debugger launch will continue without generated skip-over commands."
}
# ── Pre-checks ──
foreach ($p in @($PcsxPath, $ExePath, $HelperZip)) {
if (-not (Test-Path $p)) {
+323 -83
View File
@@ -3,7 +3,7 @@
--- Validates `MipsAtom_(name) atom_info(atom_bind(Binds_X), atom_reads(...), atom_writes(...)) { ... }` declarations in source files.
--- Also reads: `Binds_*` struct declarations (`typedef Struct_(Binds_X) { ... };`)
---
--- Source scanning: done ONCE upstream by `duffle.scan_source()` (ps1_meta.lua pre-scans each source and stashes the result in `src.scan`).
--- Source scanning: done ONCE upstream by `duffle.scan_source()` (ps1_meta.lua pre-scans each source and stashes the result in `src.scan`).
---
--- Writes:
--- - `<ctx.out_root>/<dir_basename>.errors.h` — one per module, with `#error` directives on findings (the C compile will surface the error)
@@ -13,8 +13,7 @@
-- Bootstrap: same as entry scripts. See `ps1_meta.lua` for the rationale.
-- Bootstrap: load `scripts/duffle_paths.lua` (sets package.path + package.cpath).
-- Uses `debug.getinfo` to find this file's own directory, so it works
-- both standalone and when require'd from the orchestrator.
-- Uses `debug.getinfo` to find this file's own directory, so it works both standalone and when require'd from the orchestrator.
-- Bootstrap: load `duffle_paths.lua` via `debug.getinfo(1, "S").source` (works both standalone + when require'd).
-- duffle_paths.lua sets package.path then returns `require("duffle")` at the bottom, so the dofile value IS the duffle module.
local _bootstrap_dir = debug.getinfo(1, "S").source:match("^@?(.*[/\\])") or "./"
@@ -22,10 +21,9 @@ local duffle = dofile(_bootstrap_dir .. "../duffle_paths.lua")
local write_file = duffle.write_file
local ensure_dir = duffle.ensure_dir
-- Domain tables (single source of truth in duffle.lua).
local WAVE_CONTEXT_REGS = duffle.WAVE_CONTEXT_REGS
local function is_wave_context_reg(n) return WAVE_CONTEXT_REGS[n] ~= nil end
-- The annotation pass now consults the source-derived registries built by scan_source:
-- * pipe_ctx.register_alias_registry — for atom_dbg_reg_default(R_X, ...) and atom_reg_types(R_X, ...) member-identity checks
-- * pipe_ctx.type_name_registry — for atom_dbg_reg_default(<T>, ...) and atom_reg_types(<T>, ...) type-identity checks
-- ════════════════════════════════════════════════════════════════════════════
-- Type declarations
@@ -47,7 +45,7 @@ local function is_wave_context_reg(n) return WAVE_CONTEXT_REGS[n] ~= nil end
--- @field project_root string
--- @field upstream table<string, table>
--- @field flags table
--- @field flags._annot_results table[] -- stashed by annotation pass; consumed by report.lua
--- @field flags._annot_results table[] -- stashed by annotation pass; consumed by report.lua
--- @field dry_run boolean
--- @field verbose boolean
@@ -66,9 +64,19 @@ local function is_wave_context_reg(n) return WAVE_CONTEXT_REGS[n] ~= nil end
--- @field writes string[] -- R_* names (write targets)
--- @field errors string[]|nil -- parse-time errors from scan_source (atom_info body malformed)
--- @class SkipOverMarker -- sub-shape of scan_source.lua's @class SkipOverMarker
--- @field marker_kind string -- exact marker ident (always "atom_dbg_skip_over")
--- @field marker_line integer
--- @field args string|nil -- trimmed text inside the parens (nil when has_parens is false)
--- @field has_parens boolean
--- @field pending boolean -- true while awaiting the following declaration
--- @field superseded_by_marker_line integer|nil -- set on a marker that was bumped out of the pending slot
--- @field target_kind string|nil -- "atom" | "comp_bare" | "comp_proc" | "unrelated" once observed
--- @field declaration_line integer|nil
--- @class Finding
--- @field line integer -- source line (or 0 for pass-level)
--- @field msg string -- finding message
--- @field line integer -- source line (or 0 for pass-level)
--- @field msg string -- finding message
--- @class Findings
--- @field errors Finding[]
@@ -76,9 +84,14 @@ local function is_wave_context_reg(n) return WAVE_CONTEXT_REGS[n] ~= nil end
--- @field info Finding[]
--- @class PipeCtx
--- @field atom_index table<string, AtomAnnotation> -- name -> AtomAnnotation (only kind=="atom")
--- @field binds_index table<string, BindsStruct> -- name -> BindsStruct
--- @field annot_counts table<string, integer> -- name -> annotation count (for unique_annotation check)
--- @field atom_index table<string, AtomAnnotation> -- name -> AtomAnnotation (only kind=="atom")
--- @field binds_index table<string, BindsStruct> -- name -> BindsStruct
--- @field annot_counts table<string, integer> -- name -> annotation count (for unique_annotation check)
--- @field types table<string, RegTypeDefault> -- from scan_source
--- @field atom_views table<string, AtomViewEntry> -- from scan_source
--- @field seen_defaults table<string, integer> -- duplicate atom_dbg_reg_default detection
--- @field seen_field table<string, integer> -- Binds_* -> count of fields (set/checked by check_binds_no_duplicate_fields)
--- @field _scan SourceScan -- full scan payload (typed-view sub-calls live here)
--- @class AnnotatedResult
--- @field atoms AtomEntry[]
@@ -96,8 +109,8 @@ local function is_wave_context_reg(n) return WAVE_CONTEXT_REGS[n] ~= nil end
-- Each check has a uniform `append_to_findings` shape (errors[] / warnings[] / info[]).
-- The dispatcher in `validate()` decides which findings list each check writes to — by convention,
-- "existence" checks (declaration must exist, struct must exist) write errors[]; "shape" checks
-- (writes/reads must be wave-context) write warnings[]. The `macro_word_drift` check writes
-- both errors[] (missing/mismatch) and info[] (match).
-- (writes/reads must be wave-context) write warnings[].
-- The `macro_word_drift` check writes both errors[] (missing/mismatch) and info[] (match).
--- Check: every annotated atom must have a matching MipsAtom_(name) declaration.
--- @param a AtomAnnotation
@@ -128,15 +141,14 @@ local function check_unique_annotation(pipe_ctx, findings)
end
--- Check: BIND atoms must reference a real Binds_* struct.
--- Demoted from error to warning (2026-07-10): the same condition is now caught by passes/static_analysis.lua's
--- check_abi_handoff() as an error. Emitting a warning here keeps the annotation pass from being stop-on-error
--- for the common test-fixture case, while still surfacing the issue in the report.
--- Emitting a warning here keeps the annotation pass from being stop-on-error for the common test-fixture case,
--- while still surfacing the issue in the report.
--- The static-analysis report remains the source of truth for build-stopping errors.
--- @param a AtomAnnotation
--- @param pipe_ctx PipeCtx
--- @param findings Findings
local function check_binds_struct_exists(a, pipe_ctx, findings)
if not a.binds then return end
if not a.binds then return end
if pipe_ctx.binds_index[a.binds] then return end
findings.warnings[#findings.warnings + 1] = {
line = a.line,
@@ -146,57 +158,13 @@ local function check_binds_struct_exists(a, pipe_ctx, findings)
}
end
--- Check: Binds_* struct fields must correspond to known wave-context registers.
--- Also checks that all `atom_writes(...)` entries are wave-context registers.
--- @param a AtomAnnotation
--- @param pipe_ctx PipeCtx
--- @param findings Findings
local function check_binds_field_wave_context(a, pipe_ctx, findings)
if not (a.binds and pipe_ctx.binds_index[a.binds]) then return end
local bs = pipe_ctx.binds_index[a.binds]
for _, f in ipairs(bs.fields) do
local candidate = "R_" .. f.name
if not is_wave_context_reg(candidate) then
findings.warnings[#findings.warnings + 1] = {
line = bs.line,
msg = string.format("%s field '%s' doesn't match a known wave-context register (candidate '%s')", a.binds, f.name, candidate),
}
end
end
for _, w in ipairs(a.writes) do
if not is_wave_context_reg(w) then
findings.warnings[#findings.warnings + 1] = {
line = a.line,
msg = string.format("%s writes '%s' which is not a known wave-context register", a.name, w),
}
end
end
end
--- Check: atom_reads(...) entries should be wave-context registers (or R_TapePtr for rbind).
--- @param a AtomAnnotation
--- @param pipe_ctx PipeCtx
--- @param findings Findings
local function check_reads_wave_context(a, pipe_ctx, findings)
for _, r in ipairs(a.reads) do
if not is_wave_context_reg(r) and r ~= "R_TapePtr" then
findings.warnings[#findings.warnings + 1] = {
line = a.line,
msg = string.format("atom '%s' reads '%s' which is not a known wave-context register", a.name, r),
}
end
end
end
--- Check: TAPE_WORDS(mac_X, N) ↔ WORD_COUNT(mac_X, N) drift.
--- Three outcomes: missing (error), mismatch (error), match (info).
--- @param m MacroEntry
--- @param wc table<string, integer> -- the shared word-count table (from ctx.shared.word_counts)
--- @param wc table<string, integer> -- the shared word-count table (from ctx.shared.word_counts)
--- @param findings Findings
local function check_macro_word_drift(m, wc, findings)
local declared = wc[m.name]
local declared = wc[m.name]
if not declared then
findings.errors[#findings.errors + 1] = {
line = m.line,
@@ -217,24 +185,261 @@ local function check_macro_word_drift(m, wc, findings)
}
end
--- Check: atom_dbg_reg_default(R_X, <type>) must target a register declared as a debug-visible alias in `pipe_ctx.register_alias_registry`,
--- with a type name found in `pipe_ctx.type_name_registry`.
--- Pointer depth is still bounded to 0 or 1. Duplicate defaults are still detected.
--- @param _src SourceFile -- unused (kept for the per_source shape)
--- @param pipe_ctx PipeCtx
--- @param findings Findings
local function check_semantic_reg_defaults(_src, pipe_ctx, findings)
-- Detect duplicate defaults using the ordered occurrence list (the out.types hash only retains the last declaration).
local seen_first_line = {}
for _, occ in ipairs(pipe_ctx.type_occurrences or {}) do
if seen_first_line[occ.reg] == nil then
seen_first_line[occ.reg] = occ.source_line
else
findings.errors[#findings.errors + 1] = {
line = occ.source_line,
msg = string.format(
"duplicate atom_dbg_reg_default for %q at line %d (first declared at line %d); one default per register",
occ.reg, occ.source_line, seen_first_line[occ.reg]),
}
end
end
local reg_registry = pipe_ctx.register_alias_registry or {}
local type_registry = pipe_ctx.type_name_registry or {}
for reg, def in pairs(pipe_ctx.types or {}) do
if not reg_registry[reg] then
findings.errors[#findings.errors + 1] = {
line = def.source_line,
msg = string.format(
"atom_dbg_reg_default at line %d references unknown register %q (not in register_alias_registry)",
def.source_line, reg),
}
end
if def.pointer_depth == nil or def.pointer_depth < 0 or def.pointer_depth > 1 then
findings.errors[#findings.errors + 1] = {
line = def.source_line,
msg = string.format(
"atom_dbg_reg_default at line %d for %q has unsupported pointer depth %d (expected 0 or 1)",
def.source_line, reg, def.pointer_depth or -1),
}
end
if not def.type_name or not type_registry[def.type_name] then
findings.errors[#findings.errors + 1] = {
line = def.source_line,
msg = string.format(
"atom_dbg_reg_default at line %d for %q uses unknown type %q (not in type_name_registry)",
def.source_line, reg, tostring(def.type_name)),
}
end
end
end
--- Check: atom_reg_types(R_X, <type>) entries must point to a register declared in `pipe_ctx.register_alias_registry`, with a type name found in `pipe_ctx.type_name_registry`.
--- The alias ident `R_<n>` now encodes the GPR identity only for entries that are explicitly opted in via the bare `atom_reg` marker.
--- R_T0..R_T3 are intentionally NOT auto-included (per the prototype principle: no auto-include of wave-context; explicit opt-in only).
--- The check fires for any R_T0..R_T3 reference that hasn't been opted in via `#define atom_reg`.
--- @param _src SourceFile
--- @param pipe_ctx PipeCtx
--- @param findings Findings
local function check_atom_reg_types(_src, pipe_ctx, findings)
local reg_registry = pipe_ctx.register_alias_registry or {}
local type_registry = pipe_ctx.type_name_registry or {}
for _, ai in ipairs(pipe_ctx.atom_infos_list or {}) do
if ai.reg_type_overrides then
for reg, ov in pairs(ai.reg_type_overrides) do
if not reg_registry[reg] then
findings.errors[#findings.errors + 1] = {
line = ai.info_line,
msg = string.format(
"atom '%s' has atom_reg_types for %q; compute-register types are restricted to opt-in aliases (%q not in register_alias_registry)",
ai.atom_name, reg, reg),
}
end
if not ov.type_name or not type_registry[ov.type_name] then
findings.errors[#findings.errors + 1] = {
line = ai.info_line,
msg = string.format(
"atom '%s' atom_reg_types for %q uses unknown compute type %q (not in type_name_registry)",
ai.atom_name, reg, tostring(ov.type_name)),
}
end
end
end
end
end
--- Check: atom_view(Binds_X) entries must reference a real Binds_* struct and that struct must declare at least one field.
--- @param _src SourceFile
--- @param pipe_ctx PipeCtx
--- @param findings Findings
local function check_atom_view_layout(_src, pipe_ctx, findings)
for atom_name, view in pairs(pipe_ctx.atom_views or {}) do
if not view.binds_name then
-- The atom had atom_reg_types but no atom_view; no layout check needed.
else
local bs = pipe_ctx.binds_index[view.binds_name]
if not bs then
findings.errors[#findings.errors + 1] = {
line = view.info_line,
msg = string.format(
"atom '%s' has atom_view(%s) but no Struct_(%s) { ... } declaration was found",
atom_name, view.binds_name, view.binds_name),
}
elseif not bs.fields or #bs.fields == 0 then
findings.errors[#findings.errors + 1] = {
line = bs.line,
msg = string.format(
"atom '%s' has atom_view(%s) but that struct declares zero typed fields",
atom_name, view.binds_name),
}
end
end
end
end
--- Check: Binds_* structs may not have duplicate field names
--- (they would defeat the typed-field name lookup that atom_view exposes in gdb).
--- @param _src SourceFile
--- @param pipe_ctx PipeCtx
--- @param findings Findings
local function check_binds_no_duplicate_fields(_src, pipe_ctx, findings)
for _, bs in ipairs(pipe_ctx.binds_list or {}) do
local seen = {}
for _, f in ipairs(bs.fields or {}) do
seen[f.name] = (seen[f.name] or 0) + 1
end
for name, count in pairs(seen) do
if count > 1 then
findings.errors[#findings.errors + 1] = {
line = bs.line,
msg = string.format(
"%s has duplicate field name %q (count %d); the typed-view contract requires unique field names",
bs.name, name, count),
}
end
end
end
end
-- Check: skip-over markers must satisfy shape + placement constraints.
--- Walks the priority list once; at most one error is appended per marker so that a single source-level defect does not cascade into multiple findings.
--- Priority order (first defect wins):
--- 1. has_parens == false -> requires parentheses: marker()
--- 2. args ~= "" -> takes no arguments
--- 3. superseded_by_marker_line -> duplicate marker (cite superseding line)
--- 4. pending + no target_kind -> dangling (no following declaration)
--- 5. unsupported target_kind -> marker precedes an unrelated declaration
--- Valid markers before whole-atom / bare-component / proc-component declarations emit no error and remain in src.scan.skip_over.atoms / .components.
--- @param marker SkipOverMarker
--- @param _pipe_ctx PipeCtx -- unused today; kept for plex-shape consistency with per_annot
--- @param findings Findings
local function check_skip_marker(marker, _pipe_ctx, findings)
local kind = marker.marker_kind
local line = marker.marker_line
if not marker.has_parens then
findings.errors[#findings.errors + 1] = {
line = line,
msg = string.format("%s marker at line %d requires parentheses: marker()", kind, line),
}
return
end
if marker.args ~= nil and marker.args ~= "" then
findings.errors[#findings.errors + 1] = {
line = line,
msg = string.format("%s marker at line %d takes no arguments; found %q", kind, line, marker.args),
}
return
end
if marker.superseded_by_marker_line then
findings.errors[#findings.errors + 1] = {
line = line,
msg = string.format("duplicate %s marker at line %d; superseded by another %s marker at line %d"
, kind, line, kind, marker.superseded_by_marker_line),
}
return
end
if marker.pending and not marker.target_kind then
findings.errors[#findings.errors + 1] = {
line = line,
msg = string.format("dangling %s marker at line %d: no following MipsAtom_/MipsAtomComp_/MipsAtomComp_Proc_ declaration"
, kind, line),
}
return
end
if marker.target_kind
and marker.target_kind ~= "atom"
and marker.target_kind ~= "comp_bare"
and marker.target_kind ~= "comp_proc" then
findings.errors[#findings.errors + 1] = {
line = line,
msg = string.format("%s marker at line %d must precede MipsAtom_, MipsAtomComp_, or MipsAtomComp_Proc_; found an unrelated declaration"
, kind, line),
}
end
end
--- Migration warning emitted alongside the new registry-membership check.
---
--- R_TapePtr / R_AtomJmp / R_PrimCursor / R_FaceCursor / R_VertBase / R_OtBase
--- are the wave-context aliases opted in via `#define atom_reg` in lottes_tape.h (Task 21).
--- Any source referencing an R_X that's NOT in the registry will trip the new check; a single pass-level info entry
--- (emitted only when at least one such rejection lands in this source) tells users where to look.
---
--- This check is a stop-gap until users migrate off raw C-ABI register names.
--- @param _src SourceFile
--- @param pipe_ctx PipeCtx
--- @param findings Findings
local function check_wave_context_migration(_src, pipe_ctx, findings)
if not (pipe_ctx.types and next(pipe_ctx.types)) then return end
if not (pipe_ctx.atom_infos_list) then return end
local reg_registry = pipe_ctx.register_alias_registry or {}
for _, ai in ipairs(pipe_ctx.atom_infos_list) do
if ai.reg_type_overrides then
for reg, _ in pairs(ai.reg_type_overrides) do
if not reg_registry[reg] then
findings.warnings[#findings.warnings + 1] = {
line = 0,
msg = "wave-context removed; opt in via #define atom_reg in mips.h "
.. "(every R_<alias> that should be visible to the annotation pass "
.. "must be enum-declared with the bare atom_reg marker)",
}
return
end
end
end
end
end
-- ════════════════════════════════════════════════════════════════════════════
-- CHECK_RULES — data-driven check dispatch (the plex pattern)
-- ════════════════════════════════════════════════════════════════════════════
--
-- Each rule entry picks one of three "shapes" of dispatch:
-- per_annot(annot, pipe_ctx, findings) runs once per AtomAnnotation
-- post(pipe_ctx, findings) runs once after all per_annot calls complete (full-corpus aggregation)
-- per_macro(macro, wc, findings) runs once per TAPE_WORDS / _Pragma macro declaration
-- Each rule entry picks one of four "shapes" of dispatch:
-- per_annot(annot, pipe_ctx, findings) -- runs once per AtomAnnotation
-- post(pipe_ctx, findings) -- runs once after all per_annot calls complete (full-corpus aggregation)
-- per_macro(macro, wc, findings) -- runs once per TAPE_WORDS / _Pragma macro declaration
-- per_skip_marker(marker, pipe_ctx, findings) -- runs once per src.scan.skip_over.markers entry
--
-- Adding a new check = 1 row here + 1 function above. The `validate()` dispatch loop never needs editing.
local CHECK_RULES = {
{ name = "atom_decl_exists", per_annot = check_atom_decl_exists },
{ name = "binds_struct_exists", per_annot = check_binds_struct_exists },
{ name = "binds_field_wave_context", per_annot = check_binds_field_wave_context },
{ name = "reads_wave_context", per_annot = check_reads_wave_context },
{ name = "unique_annotation", post = check_unique_annotation },
{ name = "macro_word_drift", per_macro = check_macro_word_drift },
{ name = "atom_decl_exists", per_annot = check_atom_decl_exists },
{ name = "binds_struct_exists", per_annot = check_binds_struct_exists },
{ name = "unique_annotation", post = check_unique_annotation },
{ name = "macro_word_drift", per_macro = check_macro_word_drift },
{ name = "skip_marker_validation", per_skip_marker = check_skip_marker },
{ name = "semantic_reg_defaults", per_source = check_semantic_reg_defaults },
{ name = "atom_reg_types", per_source = check_atom_reg_types },
{ name = "atom_view_layout", per_source = check_atom_view_layout },
{ name = "binds_no_duplicate_fields", per_source = check_binds_no_duplicate_fields },
{ name = "wave_context_migration", per_source = check_wave_context_migration },
}
-- ════════════════════════════════════════════════════════════════════════════
@@ -276,10 +481,30 @@ local function validate(ctx, src)
-- Build pipe_ctx (Fleury: expose structure). Pre-compute everything the per-check functions need.
-- Single source of truth for atom / binds / annotation-count lookups.
-- pipe_ctx.types / pipe_ctx.atom_views / pipe_ctx.seen_defaults are projected from the scan payload so per_source check rules can iterate.
local seen_defaults = {}
for reg, _ in pairs(scan.types or {}) do
seen_defaults[reg] = (seen_defaults[reg] or 0) + 1
end
local atom_infos_list = {}
for _, ai in ipairs(scan.atom_infos or {}) do
atom_infos_list[#atom_infos_list + 1] = ai
end
local pipe_ctx = {
atom_index = {},
binds_index = {},
annot_counts = {},
atom_index = {},
binds_index = {},
annot_counts = {},
types = scan.types or {},
type_occurrences = scan.type_occurrences or {},
atom_views = scan.atom_views or {},
seen_defaults = seen_defaults,
atom_infos_list = atom_infos_list,
binds_list = scan.binds or {},
-- Project the source-derived registries from the scan payload so per_source checks consult them instead of the deleted
-- SEMANTIC_DEFAULT_REGS / KNOWN_REG_DEFAULT_TYPES / etc.
register_alias_registry = scan.register_alias_registry or {},
type_name_registry = scan.type_name_registry or {},
}
for _, a in ipairs(atoms) do pipe_ctx.atom_index [a.name] = a end
for _, b in ipairs(scan.binds) do pipe_ctx.binds_index[b.name] = b end
@@ -319,6 +544,17 @@ local function validate(ctx, src)
if rule.post then rule.post(pipe_ctx, findings) end
end
-- Per-skip-marker rules.
-- Each raw marker recorded by scan_source (in scan.skip_over.markers) is validated independently;
-- the check emits at most one error per marker.
-- Valid markers stay attached to scan.skip_over.atoms /.components for dwarf_injection.lua consumer.
local skip_markers = scan.skip_over and scan.skip_over.markers or {}
for _, marker in ipairs(skip_markers) do
for _, rule in ipairs(CHECK_RULES) do
if rule.per_skip_marker then rule.per_skip_marker(marker, pipe_ctx, findings) end
end
end
-- Per-macro rules (TAPE_WORDS vs WORD_COUNT drift).
local wc = ctx.shared.word_counts
for _, m in ipairs(scan.macros) do
@@ -327,6 +563,12 @@ local function validate(ctx, src)
end
end
-- Per-source rules (reg defaults, atom_view layout, compute-register type overrides, Binds_* field uniqueness).
-- Each per_source rule sees the full scan payload via pipe_ctx.
for _, rule in ipairs(CHECK_RULES) do
if rule.per_source then rule.per_source(src, pipe_ctx, findings) end
end
-- Information summary (always emitted).
findings.info[#findings.info + 1] = {
line = 0,
@@ -409,14 +651,12 @@ function M.run(ctx)
local errors = {}
local warnings = {}
-- Per-DIRECTORY (per-module) aggregation. Group sources by `src.dir`,
-- validate every source in the dir, then emit ONE errors.h per dir.
-- Per-DIRECTORY (per-module) aggregation. Group sources by `src.dir`, validate every source in the dir, then emit ONE errors.h per dir.
-- `ctx.by_dir` is pre-computed in build_ctx (shared across all passes).
local by_dir = ctx.by_dir or duffle.group_sources_by_dir(ctx.sources)
for dir, dir_sources in pairs(by_dir) do
local dir_basename = dir:match("([^/\\]+)$") or dir
local dir_atoms = 0
local dir_errors = {}
local dir_warnings = {}
@@ -425,8 +665,8 @@ function M.run(ctx)
ctx.flags._annot_source_results = ctx.flags._annot_source_results or {}
for _, src in ipairs(dir_sources) do
local result = validate(ctx, src)
result.source = src.path -- tag for downstream rendering
ctx.flags._annot_source_results[src.path] = result -- stash so report.lua reads from cache instead of re-running validate()
result.source = src.path -- tag for downstream rendering
ctx.flags._annot_source_results[src.path] = result -- stash so report.lua reads from cache instead of re-running validate()
dir_atoms = dir_atoms + #result.atoms
for _, e in ipairs(result.errors) do
dir_errors[#dir_errors + 1] = { line = e.line, msg = e.msg, source = src.path }
+273 -110
View File
@@ -10,14 +10,14 @@
--- **Two output forms** (per the workspace's per-emission-form pattern from
--- `guide_metaprogram_ssdl.md`):
--- 1. **Canonical text form** — `<out_root>/<basename>.atoms.sourcemap.txt`.
--- Always emitted. Format-version-tagged for forward-compat.
--- Lives in `<out_root>/` (build/gen) NOT `<source_dir>/gen/`. This file is a **build report**, not a compile artifact.
--- Format-version-tagged for forward-compat.
--- Lives in `<out_root>/` (build/gen).
--- Matches the convention used by `annotation.lua` (`<out_root>/<basename>.errors.h`) + `static_analysis.lua` (`<out_root>/<basename>.static_analysis.txt`).
--- Compile artifacts (`*.macs.h`, `*.offsets.h`) stay in `<source_dir>/gen/`.
--- 2. **gdb-runtime form** — `<ctx.out_root>/gdb_tape_atoms_runtime.gdb`
--- (pure gdb command script; addresses pre-computed via `nm`; the 9 user commands defined as `define ... end` blocks).
--- Emitted ONLY when `ctx.flags.gdb_runtime` is true AND `ctx.flags.elf_path` points to an existing ELF.
--- The gdb runtime form lets `gdb-multiarch --without-python` users (the common case on Windows MinGW builds)
--- The gdb runtime form lets `gdb-multiarch --without-python` users (the common case on Windows MinGW builds)
--- load the source-map data via `source <path>` — no Python/Tcl/Guile required.
---
--- **Output format** (canonical text form):
@@ -36,9 +36,8 @@
---
--- Marker calls (`atom_label(...)`, `atom_offset(...)`) emit 0 `.word`s.
--- They share the same walking convention as `passes/offsets.lua :: scan_atom_body`:
--- markers do NOT advance the word-offset counter, but if a marker is bundled on the same token with a
--- trailing instruction (e.g. `atom_label(foo) load_half_u(...)`),
--- the trailing instruction's word count is added. This matches `offsets.lua :: count_marker_rest`.
--- Markers do NOT advance the word-offset counter, but if a marker is bundled on the same token with a trailing instruction
--- (e.g. `atom_label(foo) load_half_u(...)`), the trailing instruction's word count is added. This matches `offsets.lua :: count_marker_rest`.
---
--- **Conventions:** tabs (1/level), EmmyLua annotations, no regex,
--- Lua 5.3 compatible.
@@ -47,9 +46,9 @@
-- Module-scope requires + package.path setup
-- ════════════════════════════════════════════════════════════════════════════
-- Bootstrap: load `duffle_paths.lua` via `debug.getinfo(1, "S").source` (works
-- both standalone + when require'd). `duffle_paths.lua` sets package.path then
-- returns `require("duffle")` at the bottom, so the dofile value IS the duffle module.
-- Bootstrap: load `duffle_paths.lua` via `debug.getinfo(1, "S").source`
-- (works both standalone + when require'd). `duffle_paths.lua` sets package.path then returns `require("duffle")`
-- at the bottom, so the dofile value IS the duffle module.
local _bootstrap_dir = debug.getinfo(1, "S").source:match("^@?(.*[/\\])") or "./"
local duffle = dofile(_bootstrap_dir .. "../duffle_paths.lua")
local elf_dwarf = require("elf_dwarf")
@@ -60,8 +59,8 @@ local count_token_words = word_count_eval.count_token_words
-- Constants
-- ════════════════════════════════════════════════════════════════════════════
-- Format version emitted as the first line. Bump + add a migration test if the
-- format changes; the gdb runtime loader rejects mismatches (E2).
-- Format version emitted as the first line. Bump + add a migration test if the format changes;
-- the gdb runtime loader rejects mismatches (E2).
local FORMAT_VERSION = 1
-- Marker-call identifiers (mirrors offsets.lua:33-34).
@@ -73,51 +72,81 @@ local OFFSET_MARKER = "atom_offset"
-- ════════════════════════════════════════════════════════════════════════════
--- @class AtomSourceMapCtx
--- @field sources table[] -- SourceScan payload per source (from `ctx.sources`)
--- @field shared table -- `ctx.shared`
--- @field shared.word_counts table -- macro name -> word count (populated by word-counts + components passes)
--- @field out_root string -- output root (e.g. "build/gen")
--- @field dry_run boolean -- if true, compute but don't write
--- @field flags table -- `ctx.flags`; reads `flags.gdb_runtime` + `flags.elf_path`
--- @field sources table[] -- SourceScan payload per source (from `ctx.sources`)
--- @field shared table -- `ctx.shared`
--- @field shared.word_counts table -- macro name -> word count (populated by word-counts + components passes)
--- @field out_root string -- output root (e.g. "build/gen")
--- @field dry_run boolean -- if true, compute but don't write
--- @field flags table -- `ctx.flags`; reads `flags.gdb_runtime` + `flags.elf_path`
-- ════════════════════════════════════════════════════════════════════════════
-- Helpers
-- ════════════════════════════════════════════════════════════════════════════
--- True iff the leading identifier of `tok` is a marker call (`atom_label` / `atom_offset`).
--- Mirrors `passes/offsets.lua :: is_marker_token` (which is file-local there).
-- ════════════════════════════════════════════════════════════════════════════
-- Provenance emission
-- ════════════════════════════════════════════════════════════════════════════
-- Component-macro invocation prefix (mirrors components.lua's MAC_PREFIX).
local MAC_PREFIX = "mac_"
local MAC_PREFIX_LEN = 4
--- Strip the `mac_` prefix from a token's leading identifier.
--- Returns nil if the identifier doesn't start with `mac_`
--- (so non-component tokens like `load_half_u`, `nop2`, `gte_cmdw_*` fall through cleanly).
--- @param tok string
--- @return boolean
local function is_marker_token(tok)
--- @return string|nil
local function strip_mac_prefix_from_token(tok)
local leading = duffle.read_ident(tok, 1)
return leading == LABEL_MARKER or leading == OFFSET_MARKER
if not leading then return nil end
if leading:sub(1, MAC_PREFIX_LEN) == MAC_PREFIX then
return leading:sub(MAC_PREFIX_LEN + 1)
end
return nil
end
--- Count words contributed by the non-marker portion of `tok` (after the marker's closing `)`).
--- Mirrors offsets.lua:182 `count_marker_rest`.
--- Returns 0 if there's no trailing content after the marker call.
--- @param tok string
--- Fetch the per-word body lines for a `mac_X(...)` invocation.
--- Walks the component's pre-tokenized body in lockstep with `count_token_words` and attributes each emitted `.word`
--- to a source line via `idx.line_of(...)`.
--- Atom labels (`atom_label(...)`) emit 0 `.word`s and are skipped.
--- @param bare string|nil -- the bare component name (e.g. `gte_load_tri_verts`)
--- @param comp_body_index table
--- @param wc table
--- @return integer
local function count_marker_rest(tok, wc)
local marker_end = duffle.find_marker_call_end(tok)
if not marker_end or marker_end >= #tok then return 0 end
local rest = duffle.trim(tok:sub(marker_end))
if rest == "" then return 0 end
return count_token_words(rest, wc)
--- @return table|nil -- list of source lines, 1-based by word position
local function fetch_body_lines(bare, comp_body_index, wc)
if not (bare and comp_body_index) then return nil end
local idx = comp_body_index[bare]
if not (idx and idx.body_tokens and idx.line_of) then return nil end
local lines = {}
for _, bt in ipairs(idx.body_tokens) do
local bt_tok = duffle.trim(bt.tok or "")
if bt_tok ~= "" then
local leading = duffle.read_ident(bt_tok, 1)
local bt_words
if leading == "atom_label" or leading == "atom_offset" then
bt_words = 0
else
bt_words = count_token_words(bt_tok, wc)
end
if bt_words > 0 then
local body_line = idx.line_of(idx.body_off + bt.rel)
for _ = 1, bt_words do lines[#lines + 1] = body_line end
end
end
end
return lines
end
--- Compute per-word entries for an atom.
--- Shared between the canonical text form (per-source `.atoms.sourcemap.txt`)
--- and the gdb-runtime form (`gdb_tape_atoms_runtime.gdb`).
---
--- Returns a list of `{pos, line, text}` entries + the total word count.
--- Markers contribute 0 entries (the marker call emits 0 `.word`s).
--- @param atom table -- one entry of scan.atoms / scan.raw_atoms
--- @param src table -- SourceFile (has .scan with .line_of(), .path)
--- @param wc table -- shared.word_counts
--- Unified per-word entry walker. `mode` is "sourcemap" (3 fields) or "provenance" (8 fields including component + body-line lookup).
--- Returns (entries, total_words). Markers contribute 0 entries.
--- @param atom table
--- @param src table
--- @param wc table
--- @param mode string -- "sourcemap" | "provenance"
--- @param comp table|nil -- shared.components map (provenance only)
--- @param comp_body_index table|nil -- per-source body index (provenance only)
--- @return table[], integer
local function compute_word_entries(atom, src, wc)
local function compute_word_entries(atom, src, wc, mode, comp, comp_body_index)
local entries = {}
local pos = 0
for _, t in ipairs(atom.body_tokens) do
@@ -125,22 +154,46 @@ local function compute_word_entries(atom, src, wc)
local rel = t.rel
local words
if is_marker_token(tok) then
words = count_marker_rest(tok, wc)
if duffle.is_marker_token(tok) then
words = duffle.count_marker_rest(tok, wc, count_token_words)
else
words = count_token_words(tok, wc)
end
-- Provenance-only: resolve component + body_lines (one fetch per token).
local comp_name, comp_line, comp_path, comp_kind
local body_lines
if mode == "provenance" then
local bare = strip_mac_prefix_from_token(tok)
if bare and comp and comp[bare] then
comp_name = bare
comp_line = comp[bare].line
comp_path = comp[bare].path
comp_kind = comp[bare].kind
end
if comp_name then body_lines = fetch_body_lines(bare, comp_body_index, wc) end
end
if words > 0 then
-- Source line for THIS token = line containing byte offset `atom.body_off + rel`.
-- `src.scan.line_of(...)` is O(log N) via LineIndex.
local line = src.scan.line_of(atom.body_off + rel)
-- Flatten newlines + tabs in TEXT to spaces so each WORD entry fits on
-- one physical line. The gdb Python parser (or our pure-gdb parser)
-- does line-based splits; multi-line TEXT would break it.
local text = duffle.trim(tok):gsub("[\t\r\n]+", " ")
for _ = 1, words do
entries[#entries + 1] = { pos = pos, line = line, text = text }
for i = 1, words do
local entry
if mode == "provenance" then
entry = {
pos = pos,
line = line,
text = text,
comp_name = comp_name,
comp_line = comp_line,
comp_path = comp_path,
comp_kind = comp_kind,
body_line = body_lines and body_lines[i],
}
else -- "sourcemap" (default)
entry = { pos = pos, line = line, text = text }
end
entries[#entries + 1] = entry
pos = pos + 1
end
end
@@ -148,8 +201,87 @@ local function compute_word_entries(atom, src, wc)
return entries, pos
end
--- Render one atom's stanza for the canonical text form
--- (ATOM header line, N WORD lines, ENDATOM marker). Returns (lines, total_words).
--- Render one atom's provenance stanza. Format:
--- `WORD N CALL <src-path>:<src-line> MACRO <name> "<def-path>:<def-line>" [BODY <line>]` (for component words)
--- `WORD N CALL <src-path>:<src-line> RAW` (for direct instructions)
--- `BODY <line>` is the source line of THIS specific word within the macro body
--- (lottes_tape.h:N where N is the per-word body line).
--- Absent for RAW rows and for component rows whose component declaration could not be indexed (older pass combinations / external macros).
--- Downstream consumers (dwarf_injection, tests) fall back to DefLine / comp_line when BODY is absent.
--- Returns (lines, total_words).
--- @param src table
--- @param atom table
--- @param wc table
--- @param comp table -- shared.components map
--- @param comp_body_index table -- per-source component body index: bare_name -> {body_off, body_tokens, line_of}
--- @return string[], integer
local function emit_provenance_stanza(src, atom, wc, comp, comp_body_index)
local lines = {}
local rel_path = src.path:gsub("\\", "/")
local entries, total = compute_word_entries(atom, src, wc, "provenance", comp, comp_body_index)
-- ATOM header line with placeholder total (patched after we know it).
lines[#lines + 1] = string.format('ATOM %s "%s" 0', atom.raw_name or atom.name, rel_path)
for _, pe in ipairs(entries) do
if pe.comp_name then
local body_suffix = ""
if pe.body_line then
body_suffix = " BODY " .. tostring(pe.body_line)
end
lines[#lines + 1] = string.format('WORD %d CALL %s:%d MACRO %s "%s:%d"%s',
pe.pos, rel_path, pe.line, pe.comp_name, pe.comp_path, pe.comp_line, body_suffix)
else
lines[#lines + 1] = string.format("WORD %d CALL %s:%d RAW", pe.pos, rel_path, pe.line)
end
end
-- Patch the placeholder total in the ATOM header line.
lines[1] = lines[1]:gsub(" 0$", " " .. tostring(total))
lines[#lines + 1] = "ENDATOM"
return lines, total
end
--- Build a per-source component body index keyed by the bare component name (e.g. `gte_load_tri_verts`).
--- Each entry holds the data we need to map each emitted `.word` to its actual source line within the macro body:
--- body_off -- byte offset of the `{` (start of body) in the component's source file.
--- body_tokens -- list of {tok, rel} pairs; `rel` is the byte offset within the body.
--- line_of -- closure resolving byte offsets in the component's source file to lines.
--- Only `comp_bare` + `comp_proc` declarations contribute (a macro invocation can only resolve to one of those).
--- First declaration wins (subsequent redeclarations would collide; today's sources declare each component exactly once).
--- Render the full provenance file content for one source (one `.atoms.provenance.txt` per source).
--- @param src table
--- @param wc table
--- @param comp table -- shared.components map
--- @param comp_body_index table -- cross-source component body index (built once in M.run; may be empty)
--- @return string
local function render_provenance(src, wc, comp, comp_body_index)
local lines = {}
lines[#lines + 1] = "# FORMAT_VERSION 1"
lines[#lines + 1] = "# auto-generated by ps1_meta.lua (passes/atoms_source_map.lua) — DO NOT EDIT"
lines[#lines + 1] = "# Per-.word provenance: maps each emitted .word to its call site (atom body"
lines[#lines + 1] = "# file:line) and, when the word was emitted by a `mac_X(...)` component invocation,"
lines[#lines + 1] = "# the component's definition file:line + the per-word BODY line. Used by"
lines[#lines + 1] = "# dwarf_injection to synthesize DW_TAG_inlined_subroutine instances + per-word"
lines[#lines + 1] = "# line program rows for native source-level step into component bodies."
-- The cross-source component body index is passed in from M.run (one global lookup shared across every source's provenance file).
-- A per-source lookup would miss every component whose declaration is in another source (e.g. `gte_load_tri_verts` is declared in `lottes_tape.h` but invoked from `hello_gte_tape.c`).
for _, atom in ipairs(src.scan.atoms or {}) do
local stanza = emit_provenance_stanza(src, atom, wc, comp, comp_body_index)
for _, line in ipairs(stanza) do lines[#lines + 1] = line end
end
for _, atom in ipairs(src.scan.raw_atoms or {}) do
local stanza = emit_provenance_stanza(src, atom, wc, comp, comp_body_index)
for _, line in ipairs(stanza) do lines[#lines + 1] = line end
end
return table.concat(lines, "\n") .. "\n"
end
--- Render one atom's stanza for the canonical text form (ATOM header line, N WORD lines, ENDATOM marker).
--- Returns (lines, total_words).
--- @param src table
--- @param atom table
--- @param wc table
@@ -161,7 +293,6 @@ local function emit_atom_stanza(src, atom, wc)
-- ATOM header line with placeholder total (patched after we know it).
lines[#lines + 1] = string.format('ATOM %s "%s" 0', atom.raw_name or atom.name, rel_path)
for _, we in ipairs(entries) do
lines[#lines + 1] = string.format("WORD %d LINE %d TEXT %s",
we.pos, we.line, we.text)
@@ -183,17 +314,13 @@ local function render_source_map(src, wc)
lines[#lines + 1] = "# FORMAT_VERSION " .. FORMAT_VERSION
lines[#lines + 1] = "# auto-generated by ps1_meta.lua (passes/atoms_source_map.lua) — DO NOT EDIT"
for _, atom in ipairs(src.scan.atoms or {}) do
for _, atom in ipairs(src.scan.atoms or {}) do
local stanza = emit_atom_stanza(src, atom, wc)
for _, line in ipairs(stanza) do
lines[#lines + 1] = line
end
for _, line in ipairs(stanza) do lines[#lines + 1] = line end
end
for _, atom in ipairs(src.scan.raw_atoms or {}) do
for _, atom in ipairs(src.scan.raw_atoms or {}) do
local stanza = emit_atom_stanza(src, atom, wc)
for _, line in ipairs(stanza) do
lines[#lines + 1] = line
end
for _, line in ipairs(stanza) do lines[#lines + 1] = line end
end
return table.concat(lines, "\n") .. "\n"
@@ -216,7 +343,7 @@ end
--- @param ctx PassCtx
--- @return table[] -- list of {idx, name, src_path, file_base, addr, size_bytes, words, entries}
local function build_atom_table(ctx)
local wc = (ctx.shared and ctx.shared.word_counts) or {}
local wc = (ctx.shared and ctx.shared.word_counts) or {}
local addrs = elf_dwarf.read_nm(ctx.flags.elf_path)
local matched = {}
@@ -274,7 +401,6 @@ end
---
--- Each command is a static sequence of `printf` / `tbreak` / `if ... end` blocks.
--- The Lua pass emits N atoms' worth of lines — no runtime iteration.
--- With 7 atoms + ~200 word entries, the runtime file is ~2000 lines, all auto-generated, no human edit ever.
--- @param lines table -- output line buffer (mutated in place)
--- @param matched table -- list of atom records from `build_atom_table`
local function append_gdb_commands(lines, matched)
@@ -284,8 +410,7 @@ local function append_gdb_commands(lines, matched)
for _, a in ipairs(matched) do
-- gdb 12.1 quirk: literals in printf args require an attached target.
-- Use the per-atom convenience vars set above as printf args.
lines[#lines + 1] = string.format(
' printf " code_%%-32s @ 0x%%08x %%4d words\\n", $__atom_name_%d, $__atom_addr_%d, $__atom_words_%d',
lines[#lines + 1] = string.format(' printf " code_%%-32s @ 0x%%08x %%4d words\\n", $__atom_name_%d, $__atom_addr_%d, $__atom_words_%d',
a.idx, a.idx, a.idx)
end
lines[#lines + 1] = "end"
@@ -298,8 +423,7 @@ local function append_gdb_commands(lines, matched)
lines[#lines + 1] = "define break_atom"
lines[#lines + 1] = ' echo "Usage: break_atom_<exact_name> (pick from the list below)"'
for _, a in ipairs(matched) do
lines[#lines + 1] = string.format(
' printf " break_atom_%%-32s\\n", $__atom_name_%d', a.idx)
lines[#lines + 1] = string.format(' printf " break_atom_%%-32s\\n", $__atom_name_%d', a.idx)
end
lines[#lines + 1] = "end"
lines[#lines + 1] = "document break_atom"
@@ -310,8 +434,7 @@ local function append_gdb_commands(lines, matched)
for _, a in ipairs(matched) do
lines[#lines + 1] = string.format("define break_atom_%s", a.name)
lines[#lines + 1] = string.format(" break *$__atom_addr_%d", a.idx)
lines[#lines + 1] = string.format(
' printf " Breakpoint set at code_%s (0x%%08x)\\n", $__atom_addr_%d', a.name, a.idx)
lines[#lines + 1] = string.format(' printf " Breakpoint set at code_%s (0x%%08x)\\n", $__atom_addr_%d', a.name, a.idx)
lines[#lines + 1] = "end"
lines[#lines + 1] = string.format("document break_atom_%s", a.name)
lines[#lines + 1] = string.format(" Set a breakpoint at code_%s.", a.name)
@@ -347,33 +470,24 @@ local function append_gdb_commands(lines, matched)
lines[#lines + 1] = " set $__matched = 0"
for _, a in ipairs(matched) do
-- Precompute end_addr (gdb 12.1's expression evaluator chokes on `addr + words*4`).
lines[#lines + 1] = string.format(
" set $__end_%d = $__atom_addr_%d + $__atom_words_%d * 4", a.idx, a.idx, a.idx)
lines[#lines + 1] = string.format(
" if $__pc >= $__atom_addr_%d && $__pc < $__end_%d", a.idx, a.idx)
lines[#lines + 1] = string.format(
' printf "atom: code_%%s\\n", $__atom_name_%d', a.idx)
lines[#lines + 1] = string.format(" set $__end_%d = $__atom_addr_%d + $__atom_words_%d * 4", a.idx, a.idx, a.idx)
lines[#lines + 1] = string.format(" if $__pc >= $__atom_addr_%d && $__pc < $__end_%d", a.idx, a.idx)
lines[#lines + 1] = string.format(' printf "atom: code_%%s\\n", $__atom_name_%d', a.idx)
lines[#lines + 1] = ' printf "addr: 0x%08x\\n", $__pc'
lines[#lines + 1] = string.format(
" set $__word = ($__pc - $__atom_addr_%d) / 4", a.idx)
lines[#lines + 1] = string.format(
' printf "word: %%d/%%d\\n", $__word, $__atom_words_%d', a.idx)
lines[#lines + 1] = string.format(" set $__word = ($__pc - $__atom_addr_%d) / 4", a.idx)
lines[#lines + 1] = string.format(' printf "word: %%d/%%d\\n", $__word, $__atom_words_%d', a.idx)
-- One inner-if per WORD entry. Each word's line + text hardcoded.
for _, we in ipairs(a.entries) do
lines[#lines + 1] = string.format(
" if $__word == %d", we.pos)
lines[#lines + 1] = string.format(" if $__word == %d", we.pos)
-- Escape TEXT for printf format string.
local escaped_text = we.text:gsub("%%", "%%%%"):gsub('"', '\\"')
lines[#lines + 1] = string.format(
' printf "source: %%s:%%d %%s\\n", $__atom_file_%d, %d, "%s"',
a.idx, we.line, escaped_text)
lines[#lines + 1] = string.format(' printf "source: %%s:%%d %%s\\n", $__atom_file_%d, %d, "%s"', a.idx, we.line, escaped_text)
lines[#lines + 1] = " end"
end
-- Fallback for words beyond the source map (shouldn't happen if nm matches).
local max_word = 0
if #a.entries > 0 then max_word = a.entries[#a.entries].pos end
lines[#lines + 1] = string.format(
' if $__word > %d', max_word)
lines[#lines + 1] = string.format(' if $__word > %d', max_word)
lines[#lines + 1] = ' printf "source: (no source-map entry for word %%d; map may be stale)\\n", $__word'
lines[#lines + 1] = " end"
lines[#lines + 1] = " set $__matched = 1"
@@ -390,19 +504,16 @@ local function append_gdb_commands(lines, matched)
-- ── stepi_inside_atom ──
-- Hardcoded one if-containment-check per atom (no loop).
-- Precompute end_addr in Lua so we don't ask gdb to evaluate `addr + words*4`
-- inside the if condition (gdb 12.1's expression evaluator chokes on the
-- `*` and emits a misleading 'function malloc' error in some gdb builds).
-- Precompute end_addr in Lua so we don't ask gdb to evaluate `addr + words*4` inside the if condition
-- (gdb 12.1's expression evaluator chokes on the `*` and emits a misleading 'function malloc' error in some gdb builds).
lines[#lines + 1] = "define stepi_inside_atom"
lines[#lines + 1] = " set $__in_atom = 0"
lines[#lines + 1] = " set $__did_step = 0"
lines[#lines + 1] = " set $__pc = (unsigned int)$pc"
for _, a in ipairs(matched) do
-- Precompute end_addr in the convenience var (single expression gdb handles).
lines[#lines + 1] = string.format(
" set $__end_%d = $__atom_addr_%d + $__atom_words_%d * 4", a.idx, a.idx, a.idx)
lines[#lines + 1] = string.format(
" if $__pc >= $__atom_addr_%d && $__pc < $__end_%d", a.idx, a.idx)
lines[#lines + 1] = string.format(" set $__end_%d = $__atom_addr_%d + $__atom_words_%d * 4", a.idx, a.idx, a.idx)
lines[#lines + 1] = string.format(" if $__pc >= $__atom_addr_%d && $__pc < $__end_%d", a.idx, a.idx)
lines[#lines + 1] = " set $__in_atom = 1"
lines[#lines + 1] = " stepi"
lines[#lines + 1] = " set $__did_step = 1"
@@ -419,8 +530,7 @@ local function append_gdb_commands(lines, matched)
lines[#lines + 1] = ""
-- ── show_c2 ──
-- GTE data regs (COP2). pcsx-redux's gdb stub doesn't expose COP2 (only
-- 72 regs: 32 GPR + COP0 + FPR).
-- GTE data regs (COP2). pcsx-redux's gdb stub doesn't expose COP2 (only 72 regs: 32 GPR + COP0 + FPR).
-- curl http://localhost:8080/api/v1/lua/gte
-- We keep the command definition as a stub that points the user at the plugin.
lines[#lines + 1] = "define show_c2"
@@ -462,7 +572,7 @@ end
--- @param ctx PassCtx
local function emit_gdb_runtime(ctx)
if not (ctx.flags and ctx.flags.gdb_runtime) then return end
local elf_path = ctx.flags.elf_path
local elf_path = ctx.flags.elf_path
if not elf_path or elf_path == "" then
io.stderr:write("[atoms_source_map] --gdb-runtime requires --elf <elf>\n")
return
@@ -531,10 +641,46 @@ end
local M = {}
--- Pass entry: emit one `<out_root>/<basename>.atoms.sourcemap.txt` per source file
--- that contains at least one `MipsAtom_(name)` / `MipsCode code_<name>` declaration.
--- Optionally also emit `<ctx.out_root>/gdb_tape_atoms_runtime.gdb` when
--- `ctx.flags.gdb_runtime` is true.
--- Build the cross-source component body index used by `render_provenance` to attribute each emitted `.word` to its actual line within the macro body.
---
--- Components are declared in one source (the header that contains `MipsAtomComp_(ac_X)` / `MipsAtomComp_Proc_(ac_X, ...)`)
--- but invoked from many source files (every atom body that calls `mac_X(...)`).
--- The body_offset + body_tokens + line_of live with the declaration source, so a per-source index would miss invocations from other sources.
---
--- The cross-source index is keyed by the bare component name (`gte_load_tri_verts`, NOT `ac_gte_load_tri_verts`)
--- `strip_mac_prefix_from_token` strips the `mac_` prefix from call-site identifiers and yields that exact bare name;
--- matching it here keeps the lookup aligned with the `ctx.shared.components` map's keying convention.
--- First declaration wins (subsequent redeclarations would collide; today's sources declare each component exactly once).
--- @param ctx PassCtx
--- @return table<string, table> -- {[comp_name] = {body_off, body_tokens, line_of}}
local function build_cross_source_component_body_index(ctx)
local index = {}
for _, src in ipairs(ctx.sources or {}) do
if src.scan and src.scan.atoms then
local line_of = src.scan.line_of
for _, atom in ipairs(src.scan.atoms) do
if atom.kind == "comp_bare" or atom.kind == "comp_proc" then
-- Prefer `atom.name` (stripped of `ac_` prefix); fall back to `raw_name`
-- only if the stripped name is absent (defensive — current scan-source always sets both).
local name = atom.name or atom.raw_name
if name and not index[name] then
index[name] = {
body_off = atom.body_off,
body_tokens = atom.body_tokens,
line_of = line_of,
}
end
end
end
end
end
return index
end
--- Pass entry: emit one `<out_root>/<basename>.atoms.sourcemap.txt` per source file that contains at least one `MipsAtom_(name)` / `MipsCode code_<name>` declaration.
--- Also emits `<out_root>/<basename>.atoms.provenance.txt`:
--- per-.word provenance with `mac_X(...)` component resolution back to the component's definition file:line + the per-word body line.
--- Optionally also emit `<ctx.out_root>/gdb_tape_atoms_runtime.gdb` when `ctx.flags.gdb_runtime` is true.
--- @param ctx PassCtx
--- @return PassResult
function M.run(ctx)
@@ -552,6 +698,17 @@ function M.run(ctx)
}
end
-- shared.components map is populated by `passes/components.lua`.
-- Used to attribute each emitted `.word` to either a component macro or the enclosing atom body.
-- If absent, all words fall through as RAW (correct behavior — provenance is additive).
local comp = (ctx.shared and ctx.shared.components) or {}
-- Cross-source component body index.
-- Built ONCE so every source's provenance writer can resolve `mac_X(...)` invocations back to the macro's body tokens (regardless of which source declared the component).
-- Per-source copies were insufficient — the atom file (`hello_gte_tape.c`) does not contain the `MipsAtomComp_(...)` declarations,
-- so the body data would be missing for every component invocation the atom file emitted.
local comp_body_index = build_cross_source_component_body_index(ctx)
-- Always emit the canonical text form (per-source).
for _, src in ipairs(ctx.sources) do
if src.scan then
@@ -559,18 +716,24 @@ function M.run(ctx)
local n_raw_atoms = src.scan.raw_atoms and #src.scan.raw_atoms or 0
if n_atoms + n_raw_atoms > 0 then
local basename = duffle.basename_no_ext(src.path)
-- Build report, NOT compile artifact: live in <out_root> alongside the other reports
-- (annotation.lua's *.errors.h, static_analysis.lua's *.static_analysis.txt, gdb_tape_atoms_runtime.gdb).
-- The per-source <source_dir>/gen/ is reserved for headers actually #included by C.
local out_path = ctx.out_root .. "/" .. basename .. ".atoms.sourcemap.txt"
local content = render_source_map(src, wc)
-- (1) atoms.sourcemap.txt — per-.word line map (unchanged contract).
local sourcemap_path = ctx.out_root .. "/" .. basename .. ".atoms.sourcemap.txt"
local sourcemap_body = render_source_map(src, wc)
-- (2) atoms.provenance.txt — per-.word provenance with `mac_X(...)` component resolution back to the component's definition file:line.
-- Consumed by `passes/dwarf_injection.lua` to synthesize `DW_TAG_inlined_subroutine` instances for source-level Step Into on component invocations.
local prov_path = ctx.out_root .. "/" .. basename .. ".atoms.provenance.txt"
local prov_body = render_provenance(src, wc, comp, comp_body_index)
if not ctx.dry_run then
duffle.ensure_dir(duffle.dirname(out_path))
duffle.write_file_lf(out_path, content)
duffle.ensure_dir(duffle.dirname(sourcemap_path))
duffle.write_file_lf(sourcemap_path, sourcemap_body)
duffle.write_file_lf(prov_path, prov_body)
end
outputs[#outputs + 1] = { kind = "report", path = out_path }
outputs[#outputs + 1] = { kind = "report", path = sourcemap_path }
outputs[#outputs + 1] = { kind = "report", path = prov_path }
end
end
end
+144 -197
View File
@@ -1,12 +1,12 @@
--- passes/components.lua — Component-macro header generator.
---
--- Reads the pre-scanned SourceScan payload (produced once upstream by `duffle.scan_source`)
--- for `MipsAtomComp_(ac_X)` and `MipsAtomComp_Proc_(ac_X, { body })` declarations, then does
--- per-source backward lookups for the function-args string (from the preceding `FI_ MipsAtom ac_X(...)`
--- function declaration) and the preceding comment block (for LSP/IntelliSense signature docs).
--- for `MipsAtomComp_(ac_X)` and `MipsAtomComp_Proc_(ac_X, { body })` declarations, then does per-source backward lookups
--- for the function-args string (from the preceding `FI_ MipsAtom ac_X(...)` function declaration)
--- and the preceding comment block (for LSP/IntelliSense signature docs).
---
--- Emits a per-directory `<dir_basename>.macs.h` containing one `#define mac_X(sig) \` macro per component
--- + `WORD_COUNT(mac_X, N)` entries for downstream offset computation.
--- Emits a per-directory `<dir_basename>.macs.h` containing one `#define mac_X(sig) \` macro per component + `WORD_COUNT(mac_X, N)`
--- entries for downstream offset computation.
---
--- **Conventions**: tabs (1/level), EmmyLua annotations, no regex,
--- Lua 5.3 compatible.
@@ -26,8 +26,7 @@
-- Bootstrap: same as entry scripts. See `ps1_meta.lua` for the rationale.
-- Bootstrap: load `scripts/duffle_paths.lua` (sets package.path + package.cpath).
-- Uses `debug.getinfo` to find this file's own directory, so it works
-- both standalone and when require'd from the orchestrator.
-- Uses `debug.getinfo` to find this file's own directory, so it works both standalone and when require'd from the orchestrator.
-- Bootstrap: load `duffle_paths.lua` via `debug.getinfo(1, "S").source` (works both standalone + when require'd).
-- duffle_paths.lua sets package.path then returns `require("duffle")` at the bottom, so the dofile value IS the duffle module.
local _bootstrap_dir = debug.getinfo(1, "S").source:match("^@?(.*[/\\])") or "./"
@@ -43,9 +42,9 @@ local ATOM_COMP_PROC = "MipsAtomComp_Proc_"
local MIPS_ATOM = "MipsAtom" -- prefix on the function declaration that wraps an AtomComp_Proc_
-- Component-name prefixes.
local AC_PREFIX = "ac_" -- arg to MipsAtomComp_(ac_X); the X is the atom name
local AC_PREFIX = "ac_" -- arg to MipsAtomComp_(ac_X); the X is the atom name
local AC_PREFIX_LEN = 3
local MAC_PREFIX = "mac_" -- prefix on generated macros; the rest is the atom name
local MAC_PREFIX = "mac_" -- prefix on generated macros; the rest is the atom name
local MAC_PREFIX_LEN = 4
-- ASCII byte values used in tokenization.
@@ -84,11 +83,11 @@ local GEN_SUBDIR = "gen"
--- @field warnings table[] -- {line=, msg=} entries; build-succeeds
--- @class Component
--- @field name string -- atom name (without `ac_` prefix)
--- @field body string -- brace-delimited body (without the braces)
--- @field args string|nil -- function-args string (function form only)
--- @field line integer -- source line of the declaration
--- @field comment string|nil -- preceding `/* */` or `//` comment block (signature doc)
--- @field name string -- atom name (without `ac_` prefix)
--- @field body string -- brace-delimited body (without the braces)
--- @field args string|nil -- function-args string (function form only)
--- @field line integer -- source line of the declaration
--- @field comment string|nil -- preceding `/* */` or `//` comment block (signature doc)
-- ════════════════════════════════════════════════════════════════════════════
-- Local helpers (file I/O + path normalization)
@@ -97,16 +96,24 @@ local GEN_SUBDIR = "gen"
local M = {}
-- ════════════════════════════════════════════════════════════════════════════
-- Function-args extraction (precedes MipsAtomComp_Proc_ invocations)
-- Back-walk helpers (composed into the 2 entry points below: find_function_args_for + preceding_comment_block)
-- ════════════════════════════════════════════════════════════════════════════
-- Find the LAST occurrence of `name + "("` in `source[1..before_pos]`.
-- Returns the position of the open paren, or nil if not found.
-- @param source string
-- @param name string
-- @param before_pos integer
-- @return integer|nil
local function find_last_name_open_paren(source, name, before_pos)
--- Find the args of the function declaration that immediately precedes a `MipsAtomComp_Proc_` invocation of the given name.
--- Returns the args string (e.g., `"U4 off, U4 code, U1 r, U1 g, U1 b"`) or nil if no function declaration is found.
---
--- Convention: function form is
--- `FI_ MipsAtom ac_X(args) MipsAtomComp_Proc_(ac_X, { body })`
--- We find the LAST occurrence of `"ac_X("` before `before_pos` and extract the args from inside the parens.
--- We then verify the preceding context ends with `MipsAtom`
--- (the function-decl keyword with possible qualifiers between).
---
--- @param source string
--- @param name string
--- @param before_pos integer
--- @return string|nil
local function find_function_args_for(source, name, before_pos)
-- Find the LAST occurrence of `name + "("` in `source[1..before_pos]`.
local name_open = name .. "("
local last_idx = nil
local scan_pos = 1
@@ -118,24 +125,6 @@ local function find_last_name_open_paren(source, name, before_pos)
last_idx = found
scan_pos = found + #name_open
end
return last_idx
end
--- Find the args of the function declaration that immediately precedes a `MipsAtomComp_Proc_` invocation of the given name.
--- Returns the args string (e.g., `"U4 off, U4 code, U1 r, U1 g, U1 b"`) or nil if no function declaration is found.
---
--- Convention: function form is
--- `FI_ MipsAtom ac_X(args) MipsAtomComp_Proc_(ac_X, { body })`
--- We find the LAST occurrence of `"ac_X("` before `before_pos` and extract the args from inside the parens.
--- We then verify the preceding context ends with `MipsAtom`
--- (the function-decl keyword with possible qualifiers between).
---
--- @param source string
--- @param name string
--- @param before_pos integer
--- @return string|nil
local function find_function_args_for(source, name, before_pos)
local last_idx = find_last_name_open_paren(source, name, before_pos)
if not last_idx then return nil end
-- Verify the preceding context ends with "MipsAtom" (with possible qualifiers between).
@@ -154,100 +143,11 @@ local function find_function_args_for(source, name, before_pos)
return inner
end
-- ════════════════════════════════════════════════════════════════════════════
-- Preceding-comment-block extraction
-- ════════════════════════════════════════════════════════════════════════════
-- Skip whitespace (space/tab/newline/CR) backward from `pos`, returning the position of the first non-whitespace char.
-- @param source string
-- @param pos integer
-- @return integer
local function skip_ws_backward(source, pos)
local back = pos - 1
while back > 0 do
local ch = source:sub(back, back)
if ch == " " or ch == "\t" or ch == "\n" or ch == "\r" then
back = back - 1
else
break
end
end
return back
end
-- Find the opening `/*` for a block comment whose `*/` ends at `close_pos`.
-- Returns the position of `/`, or nil if not found.
-- @param source string
-- @param close_pos integer -- position of the closing `*` of `*/`
-- @return integer|nil
local function find_block_comment_open(source, close_pos)
local prefix = source:sub(1, close_pos - 1)
local open_at = nil
for scan = #prefix - 1, 1, -1 do
if prefix:sub(scan, scan + 1) == "/*" then
open_at = scan
break
end
end
return open_at
end
-- Walk back from `open_at` over leading spaces + tabs to include the indentation before the `/*` in the captured comment.
-- @param source string
-- @param open_at integer
-- @return integer
local function extend_left_over_indent(source, open_at)
local start = open_at
while start > 1 do
local ch = source:sub(start - 1, start - 1)
if ch == " " or ch == "\t" then
start = start - 1
else
break
end
end
return start
end
-- Walk back from `line_end` to the start of the source line (the most recent `\n` or position 1).
-- @param source string
-- @param line_end integer
-- @return integer
local function find_line_start(source, line_end)
local start = line_end
while start > 1 and source:sub(start - 1, start - 1) ~= "\n" do
start = start - 1
end
return start
end
-- (internal) Capture one `/* ... */` block comment whose closing `*/`
-- ends at `close_end_pos`. Returns (block_text, new_scan_pos) where `new_scan_pos`
-- is where to continue scanning for more comments, or nil if no block comment was found.
local function capture_block_comment(source, close_end_pos)
local open_at = find_block_comment_open(source, close_end_pos)
if not open_at then return nil end
local block_start = extend_left_over_indent(source, open_at)
return source:sub(block_start, close_end_pos), block_start
end
-- (internal) Capture one `// ...` line comment ending at `line_end_pos`.
-- Returns (comment_text, new_scan_pos) or nil if the line is not a `//` comment.
local function capture_line_comment(source, line_end_pos)
local line_start = find_line_start(source, line_end_pos)
local line = source:sub(line_start, line_end_pos)
if line:sub(1, 2) == "//" then
return line, line_start - 1
end
return nil
end
--- Find the contiguous comment block immediately preceding `pos` in `source`.
--- Returns the comment text (with the `/* */` or `//` markers preserved) or an empty string if no comment is adjacent.
---
--- Used to copy signature comments from the source declaration (`MipsAtomComp_` / `MipsAtomComp_Proc_` / function decl)
--- over to the generated `mac_X` macro, so LSP/IntelliSense displays the args doc.
---
--- @param source string
--- @param pos integer
--- @return string
@@ -255,22 +155,59 @@ local function preceding_comment_block(source, pos)
local scan_pos = pos
local pieces = {}
while true do
local non_ws = skip_ws_backward(source, scan_pos)
if non_ws == 0 then break end
-- Skip whitespace (space/tab/newline/CR) backward from `scan_pos`,
-- returning the position of the first non-whitespace char.
local non_ws = scan_pos - 1
while non_ws > 0 do
local ch = source:sub(non_ws, non_ws)
if ch == " " or ch == "\t" or ch == "\n" or ch == "\r" then
non_ws = non_ws - 1
else
break
end
end
if non_ws == 0 then break end
local is_block_close = non_ws >= 2 and source:sub(non_ws - 1, non_ws) == "*/"
local is_line_end = source:sub(non_ws, non_ws) == "\n" or source:sub(non_ws, non_ws) == "\r"
if is_block_close then
local block_text, new_scan_pos = capture_block_comment(source, non_ws)
if not block_text then break end
table.insert(pieces, 1, block_text)
scan_pos = new_scan_pos
-- Find the opening `/*` for a block comment whose `*/` ends at `non_ws`.
-- Walk back from `non_ws` over `/*` candidates.
local prefix = source:sub(1, non_ws - 1)
local open_at = nil
for scan = #prefix - 1, 1, -1 do
if prefix:sub(scan, scan + 1) == "/*" then
open_at = scan
break
end
end
if not open_at then break end
-- Walk back from `open_at` over leading spaces + tabs to include the indentation before the `/*`.
local block_start = open_at
while block_start > 1 do
local ch = source:sub(block_start - 1, block_start - 1)
if ch == " " or ch == "\t" then
block_start = block_start - 1
else
break
end
end
table.insert(pieces, 1, source:sub(block_start, non_ws))
scan_pos = block_start
elseif is_line_end then
local line_text, new_scan_pos = capture_line_comment(source, non_ws)
if not line_text then break end
table.insert(pieces, 1, line_text)
scan_pos = new_scan_pos
-- Walk back from `non_ws` to the start of the source line (the most recent `\n` or position 1).
local line_start = non_ws
while line_start > 1 and source:sub(line_start - 1, line_start - 1) ~= "\n" do
line_start = line_start - 1
end
local line = source:sub(line_start, non_ws)
if line:sub(1, 2) == "//" then
table.insert(pieces, 1, line)
scan_pos = line_start - 1
else
break
end
else
break
end
@@ -283,42 +220,6 @@ end
-- Argument-name extraction
-- ════════════════════════════════════════════════════════════════════════════
-- Walk `trimmed` backward from `pos` over trailing whitespace / asterisks / brackets,
-- returning the position of the first non-trailer character (i.e. the end of the identifier).
-- @param trimmed string
-- @param pos integer
-- @return integer
local function trim_trailer_back(trimmed, pos)
local back = pos
while back > 0 do
local ch = trimmed:sub(back, back)
if ch == " " or ch == "\t" or ch == "*" or ch == "]" or ch == "[" then
back = back - 1
else
break
end
end
return back
end
-- Walk `trimmed` backward from `pos` over identifier chars (alnum + `_`),
-- returning the position just before the identifier starts.
-- @param trimmed string
-- @param pos integer
-- @return integer
local function trim_ident_back(trimmed, pos)
local back = pos
while back > 0 do
local ch = trimmed:sub(back, back)
if duffle.is_alnum(ch) or ch == "_" then
back = back - 1
else
break
end
end
return back
end
--- Extract just the parameter NAMES from a function-args string (stripping type annotations). E.g.,
--- `"U4 off, U4 code, U1 r, U1 g, U1 b"` -> `{"off", "code", "r", "g", "b"}`
--- `"U4 *ptr"` -> `{"ptr"}`
@@ -332,9 +233,29 @@ local function extract_arg_names(args_str)
for _, tok in ipairs(tokens) do
local trimmed = duffle.trim(tok)
if trimmed ~= "" then
local ident_end = trim_trailer_back(trimmed, #trimmed)
local ident_start = trim_ident_back(trimmed, ident_end) + 1
local name = trimmed:sub(ident_start, ident_end)
-- Find the identifier at the end: walk back over trailers (whitespace + `*` + `[]`),
-- then walk back over the identifier chars (alnum + `_`).
-- Plex: inlined the 2 single-caller helpers (no 2-caller rule met).
local ident_end = #trimmed
while ident_end > 0 do
local ch = trimmed:sub(ident_end, ident_end)
if ch == " " or ch == "\t" or ch == "*" or ch == "]" or ch == "[" then
ident_end = ident_end - 1
else
break
end
end
local ident_start = ident_end
while ident_start > 0 do
local ch = trimmed:sub(ident_start, ident_start)
if duffle.is_alnum(ch) or ch == "_" then
ident_start = ident_start - 1
else
break
end
end
ident_start = ident_start + 1
local name = trimmed:sub(ident_start, ident_end)
if name ~= "" then names[#names + 1] = name end
end
end
@@ -348,8 +269,7 @@ end
-- Project pre-scanned MipsAtomComp_ / MipsAtomComp_Proc_ entries into Component shape.
-- Does per-source backward lookups for args (preceding function decl) and comment (preceding comment block).
-- Carries `body_tokens` forward from scan-source so word_count_rec reads from the precomputed table
-- instead of calling duffle.tokenize_body again.
-- Carries `body_tokens` forward from scan-source so word_count_rec reads from the precomputed table instead of calling duffle.tokenize_body again.
-- @param source string -- the full source text (needed for backward lookups)
-- @param scan table -- SourceScan from duffle.scan_source
-- @return Component[]
@@ -366,6 +286,7 @@ local function project_components(source, scan)
body_tokens = a.body_tokens,
args = args,
comment = comment,
kind = a.kind, -- "comp_bare" | "comp_proc"; provenance emitter reads this.
}
end
end
@@ -473,10 +394,9 @@ end
--- Compute word counts for every component in `components` in a single pass.
--- The name-lookup table + memoization cache are built ONCE (per source) instead of per-component,
--- so the cache survives across siblings and a component's recursive `mac_Y(...)` references hit memoized values
--- instead of re-walking the body.
--- so the cache survives across siblings and a component's recursive `mac_Y(...)`
--- references hit memoized values instead of re-walking the body.
--- Cycle detection (A -> B -> A) is preserved via the in-progress `-1` sentinel in `cache`.
---
--- @param components Component[]
--- @param wc table<string, integer>
--- @return table<string, integer> -- map of component name (without `mac_`) -> word count
@@ -515,13 +435,6 @@ local function split_comment_lines(s)
return out
end
--- Split an atom body by top-level commas; drop empty tokens.
--- @param body string
--- @return string[]
local function tokens_from_body(body)
return duffle.tokenize_body_simple(body)
end
--- Determine the macro signature: function-args list (function form) or variadic-ignored (bare form).
--- @param args_str string|nil
--- @return string
@@ -571,7 +484,8 @@ local function build_component_lines(c, counts)
end
end
local tokens = tokens_from_body(c.body)
local tokens = duffle.split_top_level_commas(c.body)
for i = 1, #tokens do tokens[i] = duffle.trim(tokens[i]) end
local sig = signature_from_args(c.args)
-- Direct lookup against the per-source precomputed `counts` table (built once by count_all_components).
local n = counts[c.name]
@@ -607,8 +521,8 @@ local function header_boilerplate(src)
"// Component atoms (MipsAtomComp_(ac_*)) -> macro variants (mac_*)",
"",
-- Self-contained: define WORD_COUNT if not already defined.
-- We use the same definition here so the auto-generated entries below expand to compile-time constants whether
-- the metadata file is included first or not.
-- We use the same definition here so the auto-generated entries below expand
-- to compile-time constants whether the metadata file is included first or not.
"#ifndef WORD_COUNT",
"#define WORD_COUNT(name, count) enum { words_##name = (count) };",
"#endif",
@@ -618,7 +532,7 @@ end
-- Compute the output path for one source's `.macs.h` file.
-- The pre-rework convention uses the *directory* basename
-- (not the source file basename) e.g. `code/duffle/lottes_tape.h` produces `code/duffle/gen/duffle.macs.h`.
-- (not the source file basename) e.g. `code/duffle/lottes_tape.h` produces `code/duffle/gen/duffle.macs.h`.
-- This matches what the C codebase #includes.
-- @param src SourceFile
-- @return string -- the output directory
@@ -632,7 +546,6 @@ end
--- Emit a per-source `.macs.h` header with the `mac_X` macros + `WORD_COUNT` entries.
--- Writes in BINARY mode so LF line endings are preserved (the git blob is LF; Windows text-mode would emit CRLF and break the byte-identical diff).
--- Honors `ctx.dry_run`: prints the intended path but does not write the file.
---
--- @param ctx PassCtx
--- @param src SourceFile
--- @param components Component[]
@@ -665,8 +578,7 @@ end
-- Pass entry
-- ════════════════════════════════════════════════════════════════════════════
-- (internal) Extend `ctx.shared.word_counts` with this source's component macros
-- so offsets sees them without re-reading the file.
-- (internal) Extend `ctx.shared.word_counts` with this source's component macros so offsets sees them without re-reading the file.
-- @param ctx PassCtx
-- @param components Component[]
-- @param counts table<string, integer> -- precomputed word counts (from count_all_components)
@@ -677,6 +589,33 @@ local function update_shared_word_counts(ctx, components, counts)
end
end
--- @class ComponentDef
--- @field name string -- bare name (without ac_/mac_ prefix)
--- @field line integer -- definition source line (line of `MipsAtomComp_(ac_X)` / `MipsAtomComp_Proc_(ac_X, ...)`)
--- @field path string -- absolute source path of the definition
--- @field kind string -- "comp_bare" | "comp_proc"
--- (internal) Extend `ctx.shared.components` with this source's components-by-name map so downstream passes
--- (atoms_source_map, dwarf_injection) can resolve `mac_X(...)` invocations back to their component definition file:line.
--- provenance emission uses this to attribute each emitted `.word` to either a component macro or the enclosing atom body.
-- @param ctx PassCtx
-- @param src SourceFile
-- @param components Component[]
local function update_shared_components(ctx, src, components)
ctx.shared.components = ctx.shared.components or {}
local rel_path = src.path:gsub("\\", "/")
for _, c in ipairs(components) do
-- Keyed by bare name (e.g. `yield`, `load_tri_indices`).
-- The atoms_source_map pass strips the `mac_` prefix from the call site identifier before lookup.
ctx.shared.components[c.name] = {
name = c.name,
line = c.line,
path = rel_path,
kind = c.kind or "comp_bare",
}
end
end
--- @param ctx PassCtx
--- @return PassResult
function M.run(ctx)
@@ -684,6 +623,11 @@ function M.run(ctx)
local errors = {}
local warnings = {}
-- Initialize shared component map.
-- The atoms_source_map and dwarf_injection passes consume `ctx.shared.components` to resolve `mac_X(...)`
-- invocations back to the component's definition file:line.
ctx.shared.components = ctx.shared.components or {}
for _, src in ipairs(ctx.sources) do
-- project_components reads from src.scan + does backward lookups on src.text
local components = project_components(src.text, src.scan)
@@ -694,6 +638,9 @@ function M.run(ctx)
if macs_path then
outputs[#outputs + 1] = { macs_h = macs_path }
update_shared_word_counts(ctx, components, counts)
-- share component definitions with downstream passes.
-- `mac_X(...)` invocations in atom bodies resolve back to (path, line) via this map.
update_shared_components(ctx, src, components)
end
end
end
File diff suppressed because it is too large Load Diff
+3 -30
View File
@@ -172,32 +172,6 @@ local function scan_for_atom_markers(token, at_pos, labels, branches)
end
end
-- (internal) Count words emitted by the rest of `tok` after a marker call
-- (the marker call itself emits 0 words, but the source pattern may bundle the marker with the next instruction on the same line,
-- separated by no top-level comma).
-- Returns the word count contributed by that rest.
-- @param tok string
-- @param word_counts table
-- @return integer
local function count_marker_rest(tok, word_counts)
-- duffle.find_marker_call_end returns the position PAST the closing `)` of the marker call
-- (or nil if `tok` isn't a marker call). Canonical impl in duffle.lua is faster than the
-- file-local copy that used to live here (byte-indexed, no `tok:sub` per char).
local marker_end = duffle.find_marker_call_end(tok)
if not marker_end or marker_end >= #tok then return 0 end
local rest = duffle.trim(tok:sub(marker_end))
if rest == "" then return 0 end
return count_token_words(rest, word_counts)
end
-- (internal) Is this token a marker call (`atom_label` or `atom_offset`)?
-- @param tok string
-- @return boolean
local function is_marker_token(tok)
local leading_ident = duffle.read_ident(tok, 1)
return leading_ident == LABEL_MARKER or leading_ident == OFFSET_MARKER
end
--- Scan an atom body for labels + branches, count total words.
--- Returns (labels, branches, total_words).
--- @param body string
@@ -214,10 +188,10 @@ local function scan_atom_body(body_tokens, word_counts)
local branches = {}
for _, t in ipairs(body_tokens) do
local tok = t.tok
if is_marker_token(tok) then
if duffle.is_marker_token(tok) then
-- Marker call: record at the current pos, do NOT advance pos.
scan_for_atom_markers(tok, pos, labels, branches)
pos = pos + count_marker_rest(tok, word_counts)
pos = pos + duffle.count_marker_rest(tok, word_counts, count_token_words)
else
local words = count_token_words(tok, word_counts)
scan_for_atom_markers(tok, pos, labels, branches)
@@ -231,8 +205,7 @@ end
-- Offset computation + header generation
-- ════════════════════════════════════════════════════════════════════════════
-- Compute branch offsets as `target_word - branch_word - 1`
-- (the standard MIPS branch-immediate encoding).
-- Compute branch offsets as `target_word - branch_word - 1` (the standard MIPS branch-immediate encoding).
-- @param labels table<string, integer>
-- @param branches table[]
-- @return BranchOffset[]
+12 -13
View File
@@ -16,7 +16,6 @@
-- ════════════════════════════════════════════════════════════════════════════
-- Resolve `arg[0]` to an absolute-ish script directory so that `require("duffle")` resolves against `scripts/` regardless of CWD.
-- Note: this boilerplate is duplicated in 6 other entry scripts; a Phase-6 extraction target (`duffle.setup_package_path()`).
-- Bootstrap: see `ps1_meta.lua` for the rationale.
-- Bootstrap: load `scripts/duffle_paths.lua` (sets package.path + package.cpath).
-- Uses `debug.getinfo` to find this file's own directory, so it works
@@ -61,16 +60,16 @@ local PASS_NAME = "report"
--- @field basename string -- filename without extension
--- @class PassCtx
--- @field sources SourceFile[] -- all source files in the build
--- @field metadata_path string -- path to word_count.metadata.h
--- @field shared table -- cross-pass shared state
--- @field out_root string -- output root (e.g. "build/gen")
--- @field project_root string -- project root (e.g. "code/")
--- @field upstream table<string, table> -- per-pass upstream outputs
--- @field flags table -- CLI flags + per-pass stash
--- @field flags._annot_results ModuleEntry[] -- stashed by annotation pass
--- @field dry_run boolean -- if true, compute but don't write
--- @field verbose boolean -- if true, log diagnostic info
--- @field sources SourceFile[] -- all source files in the build
--- @field metadata_path string -- path to word_count.metadata.h
--- @field shared table -- cross-pass shared state
--- @field out_root string -- output root (e.g. "build/gen")
--- @field project_root string -- project root (e.g. "code/")
--- @field upstream table<string, table> -- per-pass upstream outputs
--- @field flags table -- CLI flags + per-pass stash
--- @field flags._annot_results ModuleEntry[] -- stashed by annotation pass
--- @field dry_run boolean -- if true, compute but don't write
--- @field verbose boolean -- if true, log diagnostic info
--- @class PassResult
--- @field outputs table[] -- {kind=, path=} entries describing emit files
@@ -312,8 +311,8 @@ local function render_module_report(dir, sources, results)
macros = total_macros, errors = total_errors, warnings = total_warnings,
}
-- THE per-section dispatch. ONE loop over SECTION_RENDERERS. Each renderer writes its
-- header + content via the `add` closure (pre-bound above).
-- THE per-section dispatch. ONE loop over SECTION_RENDERERS.
-- Each renderer writes its header + content via the `add` closure (pre-bound above).
-- Adding a new section = 1 row here + 1 render_<thing>_section function.
for _, section in ipairs(SECTION_RENDERERS) do
add(section.header)
File diff suppressed because it is too large Load Diff
+362 -99
View File
@@ -1,16 +1,24 @@
--- passes/static_analysis.lua — Per-atom static-analysis checks.
---
--- The 5 checks currently shipped:
--- 1. **GTE pipeline-fill** — every `gte_cmdw_*` invocation must be preceded by the minimum number of `nop` words
--- (per `duffle.GTE_PIPELINE_LATENCY`) so the COP2 pipeline latency is fully retired before the command issues.
--- 2. **mac_yield uniformity** — every atom body must contain exactly one `mac_yield()` call (control transfer pattern).
--- 3. **ABI handoff** — every `atom_bind(Binds_X)` must reference a `typedef Struct_(Binds_X) { ... }` declaration.
--- 4. **GPU port-store shape** — per-shape (`f3`/`f4`/`g4`/etc.) the sum of `mac_format_X_color` + `mac_gte_store_X_*` +
--- `mac_insert_ot_tag_X` words must equal the GP0 cmd's expected packet size.
--- 5. **per-atom cycle budget** — sum each atom body's instruction latencies (per `duffle.INSTRUCTION_LATENCY`); report total.
--- The 9 checks currently shipped:
--- Per-atom rules:
--- 1. **GTE pipeline-fill** — every `gte_cmdw_*` invocation must be preceded by the minimum number of `nop` words
--- (per `duffle.GTE_PIPELINE_LATENCY`) so the COP2 pipeline latency is fully retired before the command issues.
--- 2. **mac_yield uniformity** — every atom body must contain exactly one `mac_yield()` call (control transfer pattern).
--- 3. **ABI handoff** — every `atom_bind(Binds_X)` must reference a `typedef Struct_(Binds_X) { ... }` declaration.
--- 4. **GPU port-store shape** — per-shape (`f3`/`f4`/`g4`/etc.) the sum of `mac_format_X_color` + `mac_gte_store_X_*` +
--- `mac_insert_ot_tag_X` words must equal the GP0 cmd's expected packet size.
--- 5. **per-atom cycle budget** — sum each atom body's instruction latencies (per `duffle.INSTRUCTION_LATENCY`); report total.
--- Per-source rules (registry-driven, added 2026-07-16):
--- 6. **enum_alias_membership** — every `R_X` referenced from `atom_dbg_reg_default`, `atom_reg_types`,
--- `atom_type(...)`, `atom_reads`, or `atom_writes` must be in `scan.register_alias_registry`. Missing -> warning.
--- 7. **atom_type_consistency** — every `reg_type_overrides[R_X].type_name` must resolve in `scan.type_name_registry`. Missing -> error.
--- 8. **binds_no_substruct_deref** — every `load_word(R_A, R_B, O_(Type, Field))` and `store_word(...)` in every atom body
--- must reference a leaf scalar (pointer-to-struct counts as leaf; nested struct members do NOT). Missing -> warning (build continues).
--- 9. **reads_writes_alias_membership** — distinct check name duplicating #6's reads/writes coverage so the report can
--- attribute failures to a precedence class. Missing -> warning (build continues).
---
--- The orchestrator (`ps1_meta.lua`) wires this module in via the
--- PASSES table:
--- The orchestrator (`ps1_meta.lua`) wires this module in via the PASSES table:
--- `["static-analysis"] = { module = "passes.static_analysis", kind = "validation", deps = {"word-counts", "components"},
--- out = { { kind = "report", path_template = "<out_root>/<basename>.static_analysis.txt" } } }`
---
@@ -25,7 +33,7 @@
-- Bootstrap: load `duffle_paths.lua` via `debug.getinfo(1, "S").source` (works both standalone + when require'd).
-- duffle_paths.lua sets package.path then returns `require("duffle")` at the bottom, so the dofile value IS the duffle module.
local _bootstrap_dir = debug.getinfo(1, "S").source:match("^@?(.*[/\\])") or "./"
local duffle = dofile(_bootstrap_dir .. "../duffle_paths.lua")
local duffle = dofile(_bootstrap_dir .. "../duffle_paths.lua")
-- ════════════════════════════════════════════════════════════════════════════
-- Constants
@@ -37,22 +45,22 @@ local ATOM_COMP = "MipsAtomComp_"
local ATOM_COMP_PROC = "MipsAtomComp_Proc_"
-- Marker-call identifiers inside atom bodies.
local ATOM_LABEL = "atom_label"
local ATOM_OFFSET = "atom_offset"
local ATOM_INFO = "atom_info"
local ATOM_BIND = "atom_bind"
local ATOM_READS = "atom_reads"
local ATOM_WRITES = "atom_writes"
local ATOM_YIELD = "mac_yield"
local ATOM_LABEL = "atom_label"
local ATOM_OFFSET = "atom_offset"
local ATOM_INFO = "atom_info"
local ATOM_BIND = "atom_bind"
local ATOM_READS = "atom_reads"
local ATOM_WRITES = "atom_writes"
local ATOM_YIELD = "mac_yield"
local WORD_COUNT_PRAGMA = "WORD_COUNT("
-- ASCII byte values used in tokenization.
local BYTE_NEWLINE = 10
local BYTE_HASH = 35 -- '#'
local BYTE_OPEN_PAREN = 40
local BYTE_OPEN_BRACE = 123
local BYTE_OPEN_BRACK = 91
local BYTE_SEMI = 59
local BYTE_NEWLINE = 10
local BYTE_HASH = 35 -- '#'
local BYTE_OPEN_PAREN = 40
local BYTE_OPEN_BRACE = 123
local BYTE_OPEN_BRACK = 91
local BYTE_SEMI = 59
-- Per-check output paths (relative to ctx.out_root).
local OUTPUT_EXTENSION = ".static_analysis.txt"
@@ -84,8 +92,7 @@ local OUTPUT_EXTENSION = ".static_analysis.txt"
--- @field errors table[]
--- @field warnings table[]
--- @alias AtomName string -- lower_snake_case atom name
--- @alias MacroName string -- lower_snake_case macro identifier
--- @alias AtomName string -- lower_snake_case atom nameMacroName string -- lower_snake_case macro identifier
--- @alias CheckName string -- "gte_pipeline_fill" | "mac_yield_uniformity" | "abi_handoff" | "gpu_port_store_shape" | "per_atom_cycle_budget"
--- @class AtomBody
@@ -96,23 +103,23 @@ local OUTPUT_EXTENSION = ".static_analysis.txt"
--- @field kind string -- "atom" | "comp_bare" | "comp_proc"
--- @class Token
--- @field tok string -- the raw token text (trimmed)
--- @field line integer -- source line of the token's start
--- @field tok string -- the raw token text (trimmed)
--- @field line integer -- source line of the token's start
--- @field ident string|nil -- the leading ident of the token (if any)
--- @field kind string -- "n_words" | "mac_yield" | "gte_cmdw" | "mac_format" | "mac_gte_store" | "mac_insert_ot_tag" | "atom_label" | "atom_offset" | "other"
--- @field kind string -- "n_words" | "mac_yield" | "gte_cmdw" | "mac_format" | "mac_gte_store" | "mac_insert_ot_tag" | "atom_label" | "atom_offset" | "other"
--- @class Finding
--- @field line integer -- source line of the finding
--- @field atom AtomName -- the atom this finding is for (or "")
--- @class Finding
--- @field line integer -- source line of the finding
--- @field atom AtomName -- the atom this finding is for (or "")
--- @field check CheckName -- the check identifier
--- @field kind string -- "error" | "warning" | "info"
--- @field msg string -- the finding message
--- @field kind string -- "error" | "warning" | "info"
--- @field msg string -- the finding message
--- @class AtomAnalysis
--- @field atom AtomBody
--- @field tokens Token[] -- the tokens in the atom body, annotated
--- @field findings Finding[] -- findings for this atom
--- @field total_cycles integer -- sum of token cycle costs
--- @field tokens Token[] -- the tokens in the atom body, annotated
--- @field findings Finding[] -- findings for this atom
--- @field total_cycles integer -- sum of token cycle costs
-- ════════════════════════════════════════════════════════════════════════════
-- classify_tokens — per-token classification (the plex's pre-computed data layer)
@@ -156,8 +163,8 @@ local OUTPUT_EXTENSION = ".static_analysis.txt"
--- @field o_arg2 string|nil -- second arg of O_(<a>, <b>) captures
--- @field s_arg1 string|nil -- arg of S_(<a>) captures; nil for non-S_ tokens
-- Patterns for O_(<arg1>, <arg2>) and S_(<arg>) captures. UNANCHORED — the substring can appear
-- anywhere in the token (e.g., `load_word(R_T0, R_TapePtr, O_(Binds_X, field))` matches at position ~24).
-- Patterns for O_(<arg1>, <arg2>) and S_(<arg>) captures.
-- UNANCHORED, the substring can appea anywhere in the token (e.g., `load_word(R_T0, R_TapePtr, O_(Binds_X, field))` matches at position ~24).
-- The binds_name match is deferred to check_abi_handoff (which compares tc.o_arg1 == atom.info.binds).
local O_PATTERN = "O_%(([%w_]+),%s*([%w_]+)%s*%)"
local S_PATTERN = "S_%(([%w_]+)%s*%)"
@@ -181,15 +188,15 @@ local function classify_tokens(tokens)
local is_load_word = ident == "load_word"
local is_store_word = ident == "store_word"
-- Per-check pre-computes (R3 lift). Each pre-compute eliminates one per-token regex/string-find
-- call from check_abi_handoff / check_gpu_portstore_shape.
local mac_format_shape = nil
local is_gte_store = false
local is_ot_tag = false
-- Per-check pre-computes (R3 lift).
-- Each pre-compute eliminates one per-token regex/string-find call from check_abi_handoff / check_gpu_portstore_shape.
local mac_format_shape = nil
local is_gte_store = false
local is_ot_tag = false
local writes_r_prim_cursor = false
local reads_r_tape_ptr = false
local o_arg1, o_arg2 = nil, nil
local s_arg1 = nil
local reads_r_tape_ptr = false
local o_arg1, o_arg2 = nil, nil
local s_arg1 = nil
if ident == "atom_label" then
is_atom_label = true
@@ -235,10 +242,8 @@ local function classify_tokens(tokens)
s_arg1 = s_arg1,
}
-- Advance the nop run for the NEXT token.
if nop_words > 0 then
nop_run = nop_run + nop_words
else
nop_run = 0
if nop_words > 0 then nop_run = nop_run + nop_words
else nop_run = 0
end
end
return tc
@@ -268,9 +273,9 @@ local function check_one_gte_cmdw(atom, tc_entry, ti, line_in_body, findings)
"%s at line %d uses `gte_cmdw_%s` but that macro is not in duffle.GTE_PIPELINE_LATENCY -- add a min_nops entry",
atom.name, line, variant),
}
elseif need > 0 then
elseif need > 0 then
local have = tc_entry.nop_prefix
if have < need then
if have < need then
findings[#findings + 1] = {
atom = atom.name,
line = line,
@@ -435,8 +440,8 @@ local function check_abi_handoff(atom, pipe_ctx, findings)
local found_field_set = {}
local found_advance = false
-- Reads from tc_entry fields pre-computed by classify_tokens (R3 lift). Eliminates 3 per-token
-- string-find/match calls (R_TapePtr + O_(binds_name,...) + bind_re) → 3 O(1) field reads.
-- Reads from tc_entry fields pre-computed by classify_tokens (R3 lift).
-- Eliminates 3 per-token string-find/match calls (R_TapePtr + O_(binds_name,...) + bind_re) → 3 O(1) field reads.
for tok_idx = 1, #tokens do
local tc_entry = tc[tok_idx]
-- scan: load_word(R_*, R_TapePtr, O_(<Binds_X>, <field>))
@@ -506,11 +511,11 @@ local function check_gpu_portstore_shape(atom, pipe_ctx, findings)
local saw_format = false
local saw_prim_write = false
-- Reads from tc_entry fields pre-computed by classify_tokens (R3 lift). Eliminates 4 per-token
-- string matches (mac_format_X_color + mac_gte_store_<shape> + mac_insert_ot_tag_<shape> + R_PrimCursor)
-- Reads from tc_entry fields pre-computed by classify_tokens (R3 lift).
-- Eliminates 4 per-token string matches (mac_format_X_color + mac_gte_store_<shape> + mac_insert_ot_tag_<shape> + R_PrimCursor)
for tok_idx = 1, #tokens do
local tc_entry = tc[tok_idx]
local shape = tc_entry.mac_format_shape
local shape = tc_entry.mac_format_shape
if shape and duffle.GP0_CMD_BY_SHAPE[shape] then
if not cmd_byte then
cmd_byte = duffle.GP0_CMD_BY_SHAPE[shape]
@@ -607,14 +612,10 @@ local function analyze_atom_paths(atom)
end
-- A token is a terminator if it's `mac_yield`.
local function is_terminator(tok_idx)
return tc[tok_idx].is_yield
end
local function is_terminator(tok_idx) return tc[tok_idx].is_yield end
-- A token is a "branch" if the classification says so.
local function is_branch(tok_idx)
return tc[tok_idx].is_branch
end
local function is_branch(tok_idx) return tc[tok_idx].is_branch end
local function successors(tok_idx)
local tok = tokens[tok_idx].tok
if is_terminator(tok_idx) then
@@ -635,13 +636,11 @@ local function analyze_atom_paths(atom)
end
end
-- For literal-offset branches (label == false), the taken path would jump to a non-tracked address; conservatively omit.
-- Return (succ, nil) -- the second value is the terminator marker (nil = not a terminator).
-- Return (succ, nil), the second value is the terminator marker (nil = not a terminator).
return succ, nil
end
-- Normal token: just the next one
if tok_idx + 1 <= n then
return { tok_idx + 1 }, nil
end
if tok_idx + 1 <= n then return { tok_idx + 1 }, nil end
return {}, nil
end
@@ -696,7 +695,7 @@ local function analyze_atom_paths(atom)
-- If no paths were recorded (e.g. atom body is empty), cycles_min/max default to 0 (atom costs nothing).
if cycles_min == math.huge then cycles_min = 0 end
if cycles_max == -1 then cycles_max = 0 end
if cycles_max == -1 then cycles_max = 0 end
local unknown_list = {}
for macro_name in pairs(unknown_set) do unknown_list[#unknown_list + 1] = macro_name end
@@ -709,7 +708,6 @@ local function analyze_atom_paths(atom)
-- Mutate the pre-allocated `atom.paths` slot in place (caller owns the table).
-- Mega-struct move: a single source of truth for all per-atom path-analysis data,
-- instead of returning a fresh table that would just get copied onto 5 atom fields.
-- If a caller ever DIDN'T pre-allocate (legacy code path), fall back to a fresh slot.
local p = atom.paths or {}
p.cycles_min = cycles_min
p.cycles_max = cycles_max
@@ -722,14 +720,9 @@ end
--- Per-source check that emits one finding per unknown macro seen
--- (deduplicated across atoms so the warning section doesn't get spammed with N copies of "macro X not in duffle.INSTRUCTION_LATENCY").
--- Reuses `analyze_atom_paths`'s per-atom unknown_macros discovery (it's the canonical place that walks tokens
--- and computes per-token cycle costs). We just sort + emit.
--- Per-atom: emit one finding per unknown macro seen, deduplicated across atoms (so the warning
--- section doesn't get spammed with N copies of "macro X not in duffle.INSTRUCTION_LATENCY").
--- Reuses `analyze_atom_paths`'s per-atom unknown_macros discovery (it's the canonical place that walks tokens
--- and computes per-token cycle costs). We just sort + emit.
--- Signature changed in Stage 1B: `(atom, pipe_ctx, findings)` — the `unknown_seen` dedup table lives on
--- `pipe_ctx` so it persists across the per-atom loop in validate().
--- Per-atom: emit one finding per unknown macro seen, deduplicated across atoms
--- (so the warning section doesn't get spammed with N copies of "macro X not in duffle.INSTRUCTION_LATENCY").
--- Reuses `analyze_atom_paths`'s per-atom unknown_macros discovery (it's the canonical place that walks tokens and computes per-token cycle costs).
local function check_per_atom_cycle_budget(atom, pipe_ctx, findings)
local p = atom.paths or {}
for _, name in ipairs(p.unknown_macros or {}) do
@@ -746,21 +739,272 @@ local function check_per_atom_cycle_budget(atom, pipe_ctx, findings)
end
end
-- ════════════════════════════════════════════════════════════════════════════
-- Check #6: enum_alias_membership
-- ════════════════════════════════════════════════════════════════════════════
-- Every R_X referenced from a debug-visible surface — atom_dbg_reg_default, atom_reg_types, atom_type sub-entries, atom_reads, atom_writes;
-- MUST be present in `pipe_ctx.register_alias_registry`.
-- The registry is the source-derived answer to "is this R_X a real, opt-in alias?"
-- (populated by scan_source's `parse_enum_aliases` from `enum { R_X = N atom_reg }` declarations).
-- Per-source rule (called once per source via the CHECK_RULES dispatch).
-- Signature matches the per_source shape established by check_semantic_reg_defaults.
--
-- Severity: WARNING (build continues).
-- The rule is intentionally permissive because the production `code/duffle/` and `code/gte_hello/`
-- sources use R_* aliases in atom_reads / atom_writes that may not yet be opted in via the
-- bare `atom_reg` marker. R_TapePtr / R_AtomJmp / R_PrimCursor / R_FaceCursor / R_VertBase / R_OtBase ARE opted in (lottes_tape.h Task 21).
-- Raw C-ABI aliases like R_T0..R_T3 are intentionally NOT auto-included (per the prototype principle:
-- no auto-include of wave-context; explicit opt-in only). Warnings keep the build green
-- and surface the migration gap so users see which atoms still need opt-in registration.
local function check_enum_alias_membership(_src, pipe_ctx, findings)
local reg_registry = pipe_ctx.register_alias_registry or {}
-- (a) atom_dbg_reg_default(R_X, T) -- pipe_ctx.types.
-- source_line is on every entry; emit the diagnostic against the default declaration's own line so the report's
-- "Findings by atom" section can attribute the failure to the marker location.
for reg, def in pairs(pipe_ctx.types or {}) do
if not reg_registry[reg] then
findings[#findings + 1] = {
atom = "", line = def.source_line or 0,
check = "enum_alias_membership", kind = "warning",
msg = string.format(
"atom_dbg_reg_default at line %d references unknown register %q (not in register_alias_registry)",
def.source_line or 0, reg),
}
end
end
-- (b) atom_reg_types(R_X, T) + (c) atom_type(R_X, T) sub-entries both populate `ai.reg_type_overrides`.
-- (d) atom_reads(R_X) + (e) atom_writes(R_X) populate the reads/writes arrays.
-- All four are checked against the same registry; the per-rule dispatch iterates `ai` once and covers all three locations
-- so we don't re-walk atom_infos for each sub-check.
for _, ai in ipairs(pipe_ctx.atom_infos_list or {}) do
local info_line = ai.info_line or 0
local atom_name = ai.atom_name or ""
if ai.reg_type_overrides then
for reg in pairs(ai.reg_type_overrides) do
if not reg_registry[reg] then
findings[#findings + 1] = {
atom = atom_name, line = info_line,
check = "enum_alias_membership", kind = "warning",
msg = string.format(
"atom '%s' at line %d has reg_type_overrides for %q; the alias is not in register_alias_registry",
atom_name, info_line, reg),
}
end
end
end
for _, reg in ipairs(ai.reads or {}) do
if not reg_registry[reg] then
findings[#findings + 1] = {
atom = atom_name, line = info_line,
check = "enum_alias_membership", kind = "warning",
msg = string.format(
"atom '%s' at line %d has atom_reads for %q; the alias is not in register_alias_registry",
atom_name, info_line, reg),
}
end
end
for _, reg in ipairs(ai.writes or {}) do
if not reg_registry[reg] then
findings[#findings + 1] = {
atom = atom_name, line = info_line,
check = "enum_alias_membership", kind = "warning",
msg = string.format(
"atom '%s' at line %d has atom_writes for %q; the alias is not in register_alias_registry",
atom_name, info_line, reg),
}
end
end
end
end
-- ════════════════════════════════════════════════════════════════════════════
-- Check #7: atom_type_consistency
-- ════════════════════════════════════════════════════════════════════════════
-- Every `reg_type_overrides[R_X].type_name` (populated by BOTH `atom_reg_types(R_X, <type>)`
-- and `atom_type(R_X, <type>)` sub-entries inside atom_reads/atom_writes) MUST resolve to a `type_name_registry` entry.
-- The registry is the source-derived answer to "is this type name declared in this translation unit?"
-- (populated by `typedef Struct_(...)`, `typedef Enum_(...)`, `typedef ... TSet_(...)` declarations).
-- Missing type names are errors (the build stops) so the user adds the typedef before re-running.
-- Per-source rule.
local function check_atom_type_consistency(_src, pipe_ctx, findings)
local type_registry = pipe_ctx.type_name_registry or {}
for _, ai in ipairs(pipe_ctx.atom_infos_list or {}) do
local info_line = ai.info_line or 0
local atom_name = ai.atom_name or ""
if ai.reg_type_overrides then
for reg, ov in pairs(ai.reg_type_overrides) do
if not ov.type_name or not type_registry[ov.type_name] then
findings[#findings + 1] = {
atom = atom_name, line = info_line,
check = "atom_type_consistency", kind = "error",
msg = string.format(
"atom '%s' at line %d reg_type_overrides[%q] uses unknown type %q (not in type_name_registry)",
atom_name, info_line, reg, tostring(ov.type_name)),
}
end
end
end
end
end
-- ════════════════════════════════════════════════════════════════════════════
-- Check #8: binds_no_substruct_deref
-- ════════════════════════════════════════════════════════════════════════════
-- For every `load_word(R_A, R_B, O_(<Type>, <Field>))` and matching `store_word(...)` call in every atom body,
-- the `<Field>` MUST resolve to a leaf scalar of `<Type>`. A "leaf scalar" is:
-- * a non-struct field with `pointer_depth >= 1` (pointer-to-struct IS a leaf — the field is a pointer; the pointee is unrelated), OR
-- * a non-struct field whose type_name resolves to a typedef / enum / builtin in `type_name_registry`.
-- A nested struct member (pointer_depth == 0 AND type_name resolves to a `kind = "struct"` registry entry) is NOT a leaf scalar and is flagged.
-- The check also flags fields whose Type has no `fields` table (typedefs and enums don't have fields — any Field reference against them is bogus)
-- and fields whose name doesn't appear in the resolved Type's fields array.
--
-- Walks every atom's pre-computed `paths.tok_class`
-- (set by `classify_tokens` once per atom in validate()) and uses the `o_arg1` / `o_arg2` captures instead of re-matching the token string.
-- Resolution consults `pipe_ctx.type_name_registry`
-- (Binds_* structs are registered there by scan_source's `register_struct_type`, so a unified lookup works for both Binds_* and non-Binds structs).
--
-- Severity: warning (build continues) — this catches a category of bugs
-- (passing a struct by value through the tape payload) where the symptom is runtime corruption, not a compile error.
-- Look up a field by name in a type's `fields` array. Returns the matching field entry, or nil if not found.
-- Extracted to keep check_binds_no_substruct_deref's nesting depth <= 5 (the project convention; this is the 5th nesting level:
-- function -> for-atom -> for-token -> if-load/store -> if-type-resolves -> [helper]).
local function find_field_by_name(type_entry, field_name)
for _, f in ipairs(type_entry.fields or {}) do
if f.name == field_name then return f end
end
return nil
end
-- True iff a (field, type_registry) pair is a leaf scalar (safe to dereference as a tape-payload field).
-- Pointer-to-X is always leaf; non-pointer struct members are NOT leaf.
local function is_field_leaf(field, type_registry)
if field.pointer_depth and field.pointer_depth > 0 then
return true
end
local ftype_entry = type_registry[field.type_name]
if ftype_entry and ftype_entry.kind == "struct" then
return false
end
return true
end
local function check_binds_no_substruct_deref(_src, pipe_ctx, findings)
local type_registry = pipe_ctx.type_name_registry or {}
for _, a in ipairs(pipe_ctx.atoms or {}) do
local tc = a.paths and a.paths.tok_class or {}
local tokens = a.paths and a.paths.tokens or {}
local line_in_body = a.paths and a.paths.line_in_body or {}
for ti = 1, #tokens do
local tc_entry = tc[ti]
if (tc_entry.is_load_word or tc_entry.is_store_word)
and tc_entry.o_arg1 and tc_entry.o_arg2 then
local type_name = tc_entry.o_arg1
local field_name = tc_entry.o_arg2
local body_line = a.line + (line_in_body[tokens[ti].rel] or 0)
local type_entry = type_registry[type_name]
if not type_entry or not type_entry.fields then
findings[#findings + 1] = {
atom = a.name, line = body_line,
check = "binds_no_substruct_deref", kind = "warning",
msg = string.format(
"atom '%s' at line %d O_(%s, %s) refers to type %q which has no fields table in type_name_registry",
a.name, body_line, type_name, field_name, type_name),
}
else
local field = find_field_by_name(type_entry, field_name)
if not field then
findings[#findings + 1] = {
atom = a.name, line = body_line,
check = "binds_no_substruct_deref", kind = "warning",
msg = string.format(
"atom '%s' at line %d O_(%s, %s) does not resolve to a field of %s",
a.name, body_line, type_name, field_name, type_name),
}
elseif not is_field_leaf(field, type_registry) then
findings[#findings + 1] = {
atom = a.name, line = body_line,
check = "binds_no_substruct_deref", kind = "warning",
msg = string.format(
"atom '%s' at line %d O_(%s, %s) dereferences a non-pointer struct field of type %q; nested struct members are forbidden",
a.name, body_line, type_name, field_name, field.type_name),
}
end
end
end
end
end
end
-- ════════════════════════════════════════════════════════════════════════════
-- Check #9: reads_writes_alias_membership
-- ════════════════════════════════════════════════════════════════════════════
-- For every `atom_reads(R_X)` and `atom_writes(R_X)` entry in every `atom_infos` entry, the `R_X` MUST be present in `pipe_ctx.register_alias_registry`.
-- This DUPLICATES `enum_alias_membership`'s coverage of the reads/writes arrays;
-- the distinct check name is intentional so the report can attribute the failure to a precedence-class (warnings vs errors) — the production reads/writes
-- paths are intentionally permissive at the warning level even when the registry-driven check is strict at the error level.
-- Per-source rule. Severity: warning (build continues).
local function check_reads_writes_alias_membership(_src, pipe_ctx, findings)
local reg_registry = pipe_ctx.register_alias_registry or {}
for _, ai in ipairs(pipe_ctx.atom_infos_list or {}) do
local info_line = ai.info_line or 0
local atom_name = ai.atom_name or ""
for _, reg in ipairs(ai.reads or {}) do
if not reg_registry[reg] then
findings[#findings + 1] = {
atom = atom_name, line = info_line,
check = "reads_writes_alias_membership", kind = "warning",
msg = string.format(
"atom '%s' at line %d atom_reads for %q; the alias is not in register_alias_registry",
atom_name, info_line, reg),
}
end
end
for _, reg in ipairs(ai.writes or {}) do
if not reg_registry[reg] then
findings[#findings + 1] = {
atom = atom_name, line = info_line,
check = "reads_writes_alias_membership", kind = "warning",
msg = string.format(
"atom '%s' at line %d atom_writes for %q; the alias is not in register_alias_registry",
atom_name, info_line, reg),
}
end
end
end
end
-- ════════════════════════════════════════════════════════════════════════════
-- CHECK_RULES — data-driven check dispatch (Muratori: data over control flow)
-- ════════════════════════════════════════════════════════════════════════════
-- Each rule is a table entry: { name, per_atom }.
-- `per_atom(atom, pipe_ctx, findings)` runs once per atom inside validate()'s single loop.
-- Adding a new check = 1 row here + 1 check_* function. No validate() edit required.
-- Each rule is a table entry: { name, <dispatch> }.
-- Dispatch shapes:
-- per_atom(atom, pipe_ctx, findings) — runs once per atom inside validate()'s single loop
-- post(pipe_ctx, findings) — runs once after all per-atom calls complete
-- per_macro(macro, wc, findings) — runs once per TAPE_WORDS / _Pragma macro declaration
-- per_skip_marker(marker, pipe_ctx, findings) — runs once per src.scan.skip_over.markers entry
-- per_source(src, pipe_ctx, findings) — runs once per source AFTER the per-atom loop completes
-- (added for the registry-driven rule set; same CHECK_RULES table — no parallel dispatch)
-- Adding a new check = 1 row here + 1 check_* function. validate() is updated only to invoke the per_source dispatch loop (the per_atom dispatch loop never changes).
-- This is the plex pattern: the iteration is in ONE place (validate), the variation is in DATA (this table).
local CHECK_RULES = {
{ name = "gte_pipeline_fill", per_atom = check_gte_pipeline_fill },
{ name = "mac_yield_uniformity", per_atom = check_mac_yield_uniformity },
{ name = "abi_handoff", per_atom = check_abi_handoff },
{ name = "gpu_portstore_shape", per_atom = check_gpu_portstore_shape },
{ name = "per_atom_cycle_budget", per_atom = check_per_atom_cycle_budget },
{ name = "gte_pipeline_fill", per_atom = check_gte_pipeline_fill },
{ name = "mac_yield_uniformity", per_atom = check_mac_yield_uniformity },
{ name = "abi_handoff", per_atom = check_abi_handoff },
{ name = "gpu_portstore_shape", per_atom = check_gpu_portstore_shape },
{ name = "per_atom_cycle_budget", per_atom = check_per_atom_cycle_budget },
{ name = "enum_alias_membership", per_source = check_enum_alias_membership },
{ name = "atom_type_consistency", per_source = check_atom_type_consistency },
{ name = "binds_no_substruct_deref", per_source = check_binds_no_substruct_deref },
{ name = "reads_writes_alias_membership",per_source = check_reads_writes_alias_membership},
}
-- ════════════════════════════════════════════════════════════════════════════
@@ -782,19 +1026,30 @@ local function validate(ctx, src)
end
-- pipe_ctx: the cross-atom shared state for the per-atom pipeline (Fleury "expose structure").
-- Pre-allocated here, mutated by each per-atom check call below. Replaces the per-check
-- local tables that used to live inside each check_* function body.
-- info_by_atom — atom_name -> atom_info (built once; check_abi_handoff reads it)
-- binds_index — Binds_X -> binds struct (built once; check_abi_handoff reads it)
-- unknown_seen — macro_name -> first atom line (accumulated across atoms; check_per_atom_cycle_budget dedups)
-- Pre-allocated here, mutated by each per-atom check call below.
-- Replaces the per-check local tables that used to live inside each check_* function body.
-- info_by_atom — atom_name -> atom_info (built once; check_abi_handoff reads it)
-- binds_index — Binds_X -> binds struct (built once; check_abi_handoff reads it)
-- unknown_seen — macro_name -> first atom line (accumulated across atoms; check_per_atom_cycle_budget dedups)
-- atoms — full atom list (used by check_binds_no_substruct_deref's per-source body walk)
-- types — R_X -> default-type info from atom_dbg_reg_default (check_enum_alias_membership source a)
-- atom_infos_list — flat list of atom_info entries (checks #6/#7/#9 iterate it)
-- register_alias_registry — R_X -> {name, code, has_atom_reg, source_line} from parse_enum_aliases
-- type_name_registry — T -> {name, kind, fields, ...} from parse_typedef_binds
-- All registry fields are READ from src.scan (the dep-closed scan-source payload); this pass never re-parses.
local info_by_atom = {}
for _, info in ipairs(atom_infos) do
info_by_atom[info.atom_name] = info
end
local pipe_ctx = {
info_by_atom = info_by_atom,
binds_index = binds_index,
unknown_seen = {},
info_by_atom = info_by_atom,
binds_index = binds_index,
unknown_seen = {},
atoms = atoms,
types = scan.types or {},
atom_infos_list = atom_infos or {},
register_alias_registry = scan.register_alias_registry or {},
type_name_registry = scan.type_name_registry or {},
}
-- THE per-atom pipeline. ONE iteration of atoms; the 5 check_* functions + analyze_atom_paths
@@ -802,6 +1057,7 @@ local function validate(ctx, src)
-- Plex move: every piece of state derived from an atom body lives on `atom.paths` (the per-atom mega-struct);
-- readers (analyze_atom_paths, the 5 checks, the renderers) all consume `atom.paths`, not the raw `atoms` list.
-- Stage 1B: each check_* now takes `(atom, ...)` instead of `(atoms, findings)` — no more single-atom `{a}` shim.
-- Per-source rules run once after this loop completes (no parallel dispatch table).
local findings = {}
for _, a in ipairs(atoms) do
a.paths = a.paths or {}
@@ -812,13 +1068,20 @@ local function validate(ctx, src)
-- analyze_atom_paths fills the *cycles / branches / has_loops / unknown_macros* fields of a.paths.
analyze_atom_paths(a)
-- Run all checks on this one atom via the CHECK_RULES data table (Muratori: data over control flow).
-- Run all per-atom checks on this one atom via the CHECK_RULES data table (Muratori: data over control flow).
-- Adding a new check = 1 row in CHECK_RULES; this loop never needs editing.
for _, rule in ipairs(CHECK_RULES) do
rule.per_atom(a, pipe_ctx, findings)
if rule.per_atom then rule.per_atom(a, pipe_ctx, findings) end
end
end
-- Per-source dispatch. Run once per source AFTER the per-atom loop;
-- consults pipe_ctx's cross-atom registries (register_alias_registry, type_name_registry).
-- Same CHECK_RULES table; no parallel dispatch table.
for _, rule in ipairs(CHECK_RULES) do
if rule.per_source then rule.per_source(src, pipe_ctx, findings) end
end
local errors = {}
local warnings = {}
local info = {}
@@ -919,7 +1182,7 @@ local function emit_module_static_analysis_txt(ctx, dir, dir_sources, atoms, fin
-- Group findings by atom (with source prefix when multi-source module)
local multi_source = #dir_sources > 1
local by_atom = {}
local by_atom = {}
for _, f in ipairs(findings) do
by_atom[f.atom] = by_atom[f.atom] or {}
by_atom[f.atom][#by_atom[f.atom] + 1] = f
@@ -1066,9 +1329,9 @@ function M.run(ctx)
local errors = {}
local warnings = {}
-- Aggregate per-DIRECTORY (per-module). One static_analysis.txt per source-directory, emitted only if the directory contains at least one atom.
-- Aggregate per-DIRECTORY (per-module).
-- One static_analysis.txt per source-directory, emitted only if the directory contains at least one atom.
-- Empty-source directories (e.g. duffle headers with no atoms) produce no report.
--
-- Group sources by `src.dir`. The first component of `dir` is the module name (e.g. "code/duffle" -> "duffle", "code/gte_hello" -> "gte_hello").
-- Output path is `<out_root>/<module_basename>.static_analysis.txt`.
local by_dir = ctx.by_dir or duffle.group_sources_by_dir(ctx.sources)
-15
View File
@@ -15,7 +15,6 @@
-- ════════════════════════════════════════════════════════════════════════════
-- Resolve `arg[0]` to an absolute-ish script directory so that `require("duffle")` resolves against `scripts/` regardless of CWD.
-- Note: this boilerplate is duplicated in 6 other entry scripts; a Phase-6 extraction target (`duffle.setup_package_path()`).
-- Bootstrap: see `ps1_meta.lua` for the rationale.
-- Bootstrap: load `scripts/duffle_paths.lua` (sets package.path + package.cpath).
-- Uses `debug.getinfo` to find this file's own directory, so it works both standalone and when require'd from the orchestrator.
@@ -28,9 +27,6 @@ local duffle = dofile(_bootstrap_dir .. "../duffle_paths.lua")
-- Constants
-- ════════════════════════════════════════════════════════════════════════════
-- Windows separator char — used by `fname:match` to recognize `.macs.h` files.
local PATH_SEP_BACKSLASH = "\\"
-- Required native extension: lfs (LuaFileSystem). Built by `update_deps.ps1` to
-- `toolchain/lfs/lfs.dll` and wired into package.cpath by `scripts/duffle_paths.lua`.
-- If lfs is missing, `require` throws — fail loud per the build-tool convention.
@@ -80,7 +76,6 @@ local M = {}
--- For most tokens (regular MIPS instructions) this returns 1.
--- For `mac_X(...)` calls, this returns the resolved word count from `wc` (recursively if needed). For `nop2` etc., returns wc[name].
--- For unknown macros, returns 1 and (optionally) warns.
---
--- @param token string -- a single token from split_top_level_commas
--- @param wc WordCounts -- the shared word-count table
--- @return integer
@@ -101,14 +96,6 @@ end
-- │ Shared utility: scan_dir │
-- └────────────────────────────────────────────────────────────────────┘
--- Recursively scan a directory for files matching a glob suffix.
---
--- The `.macs.h` files produced by the components pass always live at `<project_root>/<module>/gen/`.
--- Native walk via lfs.attributes + lfs.dir: ~2ms vs ~56ms for the prior `dir /b /s` subprocess.
---
--- @param dir string -- directory to scan (absolute or relative)
--- @param suffix string -- file pattern, e.g. "*.macs.h"
--- @return string[]
-- Cache the scan_dir result per (dir, suffix) in package.loaded.
-- The cache persists for the lifetime of the Lua process (cleared when ps1_meta.lua exits).
-- If a build removes/creates .macs.h files mid-process, the caller can invalidate by calling `M._invalidate_scan_cache()`.
@@ -116,7 +103,6 @@ local SCAN_CACHE_KEY = "__word_count_eval_scan_cache__"
--- Scan `code/` for files matching `suffix` (e.g. `*.macs.h`).
--- Native directory enumeration via lfs (~2ms). Zero subprocess spawns.
---
--- @param dir string -- project root directory
--- @param suffix string -- file pattern, e.g. "*.macs.h"
--- @return string[]
@@ -160,7 +146,6 @@ function M._invalidate_scan_cache() package.loaded[SCAN_CACHE_KEY] = nil end
--- Load metadata.h + scan for existing *.macs.h files into ctx.shared.word_counts.
--- Loading the .macs.h files is idempotent: entries from later (current-build) .macs.h files override metadata.h entries of the same name.
---
--- @param ctx PassCtx
--- @return PassResult
function M.run(ctx)
+7 -11
View File
@@ -1,17 +1,15 @@
-- autoexec.lua - pcsx_debug_helper plugin entry point.
-- Packaged in scripts/pcsx_debug_helper.zip. Loaded by pcsx-redux via
-- the -archive CLI flag (see scripts/launch_pcsx_debug.ps1).
-- Packaged in scripts/pcsx_debug_helper.zip. Loaded by pcsx-redux via the -archive CLI flag (see scripts/launch_pcsx_debug.ps1).
--
-- Registers two web handlers for external CLI tools:
-- /api/v1/lua/gte - full GTE state (32 data + 32 control regs + PC)
-- /api/v1/lua/gp - GP state summary (screenshot endpoint + VRAM endpoint refs)
--
-- The GTE handler reads COP2 regs via PCSX.getRegisters().CP2D/CP2C. The
-- pcsx-redux gdb stub doesn't expose COP2, so this is the only way for
-- external tools to see GTE state.
-- The GTE handler reads COP2 regs via PCSX.getRegisters().CP2D/CP2C.
-- The pcsx-redux gdb stub doesn't expose COP2, so this is the only way for external tools to see GTE state.
--
-- The GP handler is a thin pointer: pcsx-redux's Lua API exposes only PCSX.GPU.takeScreenShot()
-- (no GPUSTAT, no GP0/GP1 command log, no display state). For richer GP state, the existing web endpoints are the practical path:
-- The GP handler is a thin pointer:
-- pcsx-redux's Lua API exposes only PCSX.GPU.takeScreenShot() (no GPUSTAT, no GP0/GP1 command log, no display state). For richer GP state, the existing web endpoints are the practical path:
-- /api/v1/state/still - PNG screenshot
-- /api/v1/gpu/vram/raw - VRAM raw bytes (1MB)
--
@@ -48,8 +46,6 @@ local function register_handlers()
end
local ok, err = pcall(register_handlers)
if ok then
print("[pcsx_debug_helper] handlers registered: gte, gp")
else
print("[pcsx_debug_helper] registration failed: " .. tostring(err))
if ok then print("[pcsx_debug_helper] handlers registered: gte, gp")
else print("[pcsx_debug_helper] registration failed: " .. tostring(err))
end
+421 -164
View File
@@ -1,16 +1,14 @@
--- ps1_meta.lua — Orchestrator entry point for the tape-atom metaprogram pipeline.
--- ps1_meta.lua — Orchestrator entry point for the tape-atom metaprogram.
---
--- Dispatches to pass modules under `scripts/passes/`, resolving
--- dependencies topologically (Kahn's algorithm + cycle detection).
--- Single CLI surface (`--<pass>` flags + auto-dep expansion + --dry-run).
--- Dispatches to pass modules under `scripts/passes/`, resolving dependencies topologically (Kahn's algorithm + cycle detection).
---
--- **Architecture**:
--- - **PASSES table** — declarative dep graph (data, not code).
--- - **FLAG_HANDLERS table** — per-flag CLI dispatchers (handler-map pattern; replaces an 8-way if/elseif chain).
--- - **parse_args** → **build_ctx** (just opens + reads source files; no inline scanning) → **topo_sort** → **dispatch_passes**.
--- - The first pass in the dep graph is `scan-source` (see `passes/scan_source.lua`).
--- - The first pass in the dep graph is `scan-source` (see `passes/scan_source.lua`).
--- It calls `duffle.scan_source` once per source to produce the fat `SourceScan` payload, which is attached to each `src.scan`.
--- Every other pass that reads source structure depends on `scan-source` and consumes `src.scan` as a read-only payload.
--- Every other pass that reads source structure depends on `scan-source` and consumes `src.scan` as a read-only.
---
--- **Conventions**: tabs (1/level), EmmyLua annotations, no regex,
--- Lua 5.3 compatible.
@@ -19,10 +17,25 @@
-- Module-scope requires + package.path setup
-- ════════════════════════════════════════════════════════════════════════════
-- Bootstrap: load `duffle_paths.lua` via `arg[0]` (this script's own path).
-- That single statement: (a) sets `package.path` + `package.cpath` (via cached `git rev-parse`),
-- (b) at the bottom returns `require("duffle")`. So the dofile's return value is the duffle module.
local duffle = dofile((arg[0]:match("(.*[/\\])") or "./") .. "duffle_paths.lua")
-- Bootstrap: load `duffle_paths.lua` via this script's own path.
-- Use `arg[0]` when this file is the entry script (`arg[0]` ends in
-- "ps1_meta.lua"); fall back to `debug.getinfo(1, "S").source` when this
-- file is being dofile()'d or require()'d (in which case `arg[0]` is the
-- *caller's* path, not ours).
--
-- That single statement: (a) sets `package.path` + `package.cpath`
-- (via cached `git rev-parse`), (b) at the bottom returns `require("duffle")`.
-- So the dofile's return value is the duffle module.
local _is_entry_script = arg and arg[0] and arg[0]:match("ps1_meta%.lua$") ~= nil
local _bootstrap_src
if _is_entry_script then
_bootstrap_src = arg[0]
else
-- debug.getinfo(1, "S").source returns "@<path>" for the current chunk;
-- strip the leading "@" so the directory match works in both cases.
_bootstrap_src = debug.getinfo(1, "S").source:sub(2)
end
local duffle = dofile((_bootstrap_src:match("(.*[/\\])") or "./") .. "duffle_paths.lua")
-- ════════════════════════════════════════════════════════════════════════════
-- Constants
@@ -51,6 +64,8 @@ local PASS_FLAG_DISPATCH_KEY = "__pass__"
--- @field module string -- module name passed to require()
--- @field kind string -- "shared" | "header-output" | "validation" | "report"
--- @field deps string[] -- names of upstream passes
--- @field groups string[]? -- OPTIONAL build-phase groups this pass is a root of
--- -- (e.g. { "pre-link" }, { "post-link" }); absent ⇒ dependency-only
--- @field desc string -- human description (used by --help + ASCII graph)
--- @field out PassOutput[] -- output paths (used by --dry-run + report)
@@ -102,18 +117,26 @@ local PASS_FLAG_DISPATCH_KEY = "__pass__"
-- PASSES table (data, not code) — the orchestrator's dep graph
-- ════════════════════════════════════════════════════════════════════════════
-- Build-phase groups: each PASSES row may declare membership in one or more
-- named groups via `groups = { ... }`. The CLI flags --pre-link and
-- --post-link request the *roots* of their group; topo_sort then closes
-- transitive dependencies from those roots, and dispatch_passes runs every
-- pass in the resulting closure without phase-filtering.
--
-- A row without a `groups` entry is dependency-only: it runs only when a
-- transitive dep requests it, but it remains directly requestable through
-- its explicit CLI flag (e.g. --atoms-source-map, --scan-source).
local PASSES = {
["scan-source"] = {
module = "passes.scan_source",
kind = "shared",
deps = {},
kind = "shared", deps = {},
desc = "Walk each source once; produce the fat SourceScan payload for downstream passes",
out = {},
},
["word-counts"] = {
module = "passes.word_count_eval",
kind = "shared",
deps = {},
kind = "shared", deps = {},
desc = "Build the shared metadata table (metadata.h + .macs.h)",
out = {},
},
@@ -138,6 +161,7 @@ local PASSES = {
module = "passes.offsets",
kind = "header-output",
deps = {"scan-source", "word-counts", "components"},
groups = { "pre-link" },
desc = "Compute branch offsets for atom_label / atom_offset",
out = { { kind = "header", path_template = "<source_dir>/gen/<basename>.offsets.h" } },
},
@@ -145,21 +169,25 @@ local PASSES = {
module = "passes.static_analysis",
kind = "validation",
deps = {"scan-source", "word-counts", "components"},
desc = "[FUTURE] GTE pipeline-fill, mac_yield uniformity, etc.",
desc = "Static analysis: GTE pipeline-fill, mac_yield uniformity, ABI handoff, GPU port-store shape, per-atom cycle budget, type consistency",
out = { { kind = "report", path_template = "<out_root>/<basename>.static_analysis.txt" } },
},
["atoms-source-map"] = {
module = "passes.atoms_source_map",
kind = "header-output",
deps = {"word-counts", "components"},
desc = "Emit gen/<basename>.atoms.sourcemap.txt (per-.word C source line map for gdb debugging)",
out = { { kind = "header", path_template = "<source_dir>/gen/<basename>.atoms.sourcemap.txt" } },
desc = "Emit gen/<basename>.atoms.sourcemap.txt (per-.word C source line map for gdb debugging) AND gen/<basename>.atoms.provenance.txt (per-.word provenance; each word tagged with its call-site file:line and, when emitted by a mac_X(...) component invocation, the component's definition file:line). Consumed by passes/dwarf_injection.lua to synthesize DW_TAG_inlined_subroutine instances for source-level Step Into on component invocations.",
out = {
{ kind = "report", path_template = "<out_root>/<basename>.atoms.sourcemap.txt" },
{ kind = "report", path_template = "<out_root>/<basename>.atoms.provenance.txt" },
},
},
["dwarf-injection"] = {
module = "passes.dwarf_injection",
kind = "shared",
deps = {"scan-source", "atoms-source-map"},
desc = "Inject per-atom .debug_line + .debug_aranges (F') + per-atom .debug_info subprogram + per-wave-context-reg .debug_info variables (G') into the ELF (post-link; writes 7 section .bin blobs for objcopy splice). (rbind composite) reads ctx.sources[i].scan to find atom_bind(Binds_X) atoms + their Binds_X struct fields; emits per-Binds_X DW_TAG_structure_type DIEs + per-rbind-atom DW_TAG_variable 'bind_args' DIEs with piece-chain DW_OP_bregN/DW_OP_piece location expressions.",
groups = { "post-link" },
desc = "Inject per-atom .debug_line + .debug_aranges (F') + per-atom .debug_info subprogram + per-wave-context-reg .debug_info variables (G') into the ELF (post-link; writes 7 section .bin blobs plus one deterministic .gdbinit sidecar). (rbind composite) reads ctx.sources[i].scan to find atom_bind(Binds_X) atoms + their Binds_X struct fields; emits per-Binds_X DW_TAG_structure_type DIEs + per-rbind-atom DW_TAG_variable 'bind_args' DIEs with piece-chain DW_OP_bregN/DW_OP_piece location expressions.",
out = {
{ kind = "report", path_template = "<out_root>/<basename>.dwarf_line.bin" },
{ kind = "report", path_template = "<out_root>/<basename>.dwarf_aranges.bin" },
@@ -168,17 +196,63 @@ local PASSES = {
{ kind = "report", path_template = "<out_root>/<basename>.dwarf_info.bin" },
{ kind = "report", path_template = "<out_root>/<basename>.dwarf_str.bin" },
{ kind = "report", path_template = "<out_root>/<basename>.dwarf_loc.bin" },
{ kind = "report", path_template = "<out_root>/<basename>.gdbinit" },
},
},
report = {
module = "passes.report",
kind = "report",
deps = {"annotation", "static-analysis"},
groups = { "pre-link" },
desc = "Render the per-project summary",
out = { { kind = "report", path_template = "<out_root>/annotation_validation.txt" } },
},
}
-- ────────────────────────────────────────────────────────────────────────────
-- Phase-root selection: derive the sorted set of roots belonging to a named
-- build-phase group, then append them to `args.requested_set`. topo_sort
-- closes the transitive deps from there; dispatch_passes runs every resolved
-- pass without phase-filtering.
-- ────────────────────────────────────────────────────────────────────────────
--- @param group_name string -- the build-phase group ("pre-link" | "post-link")
--- @return string[] -- sorted root pass names belonging to that group
local function roots_for_group(group_name)
local names = {}
for name, pass in pairs(PASSES) do
if pass.groups then
for _, g in ipairs(pass.groups) do
if g == group_name then
names[#names + 1] = name
break
end
end
end
end
table.sort(names)
return names
end
--- Append every root belonging to `group_name` to `args.requested_set`.
--- Errors loudly if no PASSES row declares the group, so a typo'd or
--- future-removed group name cannot silently fall through to pre-link
--- (or any other default) and dispatch nothing.
--- @param args ParsedArgs
--- @param group_name string
local function request_roots_for_group(args, group_name)
local roots = roots_for_group(group_name)
if #roots == 0 then
error(string.format(
"ps1_meta: build-phase group %q has zero roots in PASSES; "
.. "check PASSES rows for a `groups = { %q }` field",
group_name, group_name))
end
for _, name in ipairs(roots) do
args.requested_set[#args.requested_set + 1] = name
end
end
-- Pass-kind taxonomy: which kinds stop the build on errors?
local PASS_KIND_STOP_ON_ERROR = {
["shared"] = false,
@@ -188,6 +262,13 @@ local PASS_KIND_STOP_ON_ERROR = {
}
-- Closed set of CLI flags -> pass names.
-- Per-pass flags (e.g. --word-counts) live here; phase flags (--pre-link,
-- --post-link, --all) live in FLAG_HANDLERS because they own side effects
-- or invoke group-derivation logic. --dwarf-injection is *also* a per-pass
-- opt-in flag, but its selection + opt-in state are both owned by the
-- explicit FLAG_HANDLERS entry below (it sets args.flags.dwarf_injection
-- and appends "dwarf-injection" to requested_set), so it is intentionally
-- absent from this table.
local PASS_FLAG_TO_NAME = {
["--word-counts"] = "word-counts",
["--components"] = "components",
@@ -195,28 +276,27 @@ local PASS_FLAG_TO_NAME = {
["--offsets"] = "offsets",
["--static-analysis"] = "static-analysis",
["--atoms-source-map"] = "atoms-source-map",
["--dwarf-injection"] = "dwarf-injection",
["--report"] = "report",
["--scan-source"] = "scan-source",
["--all"] = ALL_PASSES_SENTINEL,
}
local ALL_PASS_NAMES = {
"scan-source", "word-counts", "components", "annotation",
"offsets", "static-analysis", "atoms-source-map", "dwarf-injection", "report",
}
--- Append every pass name to args.requested_set. Used by --all and by the "default to --all if no pass flags were given" fallback.
--- Append every pass name to args.requested_set. Names are derived from
--- PASSES (no parallel name list); used by --all and by any caller that
--- wants the full closure.
--- @param args ParsedArgs
local function request_all_passes(args)
for _, n in ipairs(ALL_PASS_NAMES) do
local names = {}
for name in pairs(PASSES) do names[#names + 1] = name end
table.sort(names)
for _, n in ipairs(names) do
args.requested_set[#args.requested_set + 1] = n
end
end
-- Per-flag handlers. Each handler takes (args, argv, arg_idx) and returns the new arg_idx (so multi-arg flags like --source FILE advance it).
-- Returning nil + os.exit() handles termination flags (--help).
-- This replaces the 8-way `if/elseif/elseif...` chain that nested 4 levels deep and made the dispatch logic hard to scan.
-- This replaces the 8-way `if/elseif/elseif...` chain that nested 4 levels deep and made the dispatch logic hard to scan.
local FLAG_HANDLERS = {}
-- ════════════════════════════════════════════════════════════════════════════
@@ -231,16 +311,28 @@ ps1_meta.lua - Tape-atom metaprogram orchestrator
USAGE:
ps1_meta.lua [PASS_FLAGS] [COMMON_FLAGS]
PASS_FLAGS (pick one or more, or use --all):
--word-counts Load metadata.h + scan for existing .macs.h
--components Generate <module>/gen/<basename>.macs.h
--validate Run atom annotation DSL validation
--offsets Generate <module>/gen/<basename>.offsets.h
--atoms-source-map Generate <basename>.atoms.sourcemap.txt per source
--dwarf-injection Inject per-atom .debug_line + .debug_aranges (post-link, requires --elf)
--static-analysis [FUTURE] GTE pipeline-fill, mac_yield uniformity
--report Render per-project summary
--all Equivalent to all 6 flags above (default)
PASS_FLAGS:
Pick a phase or one-or-more individual passes:
--pre-link [phase; default] Run the pre-link group + transitive deps.
The root set is data-driven from each PASSES row's
`groups` field; no parallel name list is maintained.
--post-link [phase] Run the post-link group + transitive deps.
Requires --elf. Sets --gdb-runtime and --dwarf-injection
opt-in flags as well.
--all Select every row of the PASSES table. Pass-local opt-in
guards remain active, so --dwarf-injection still requires
--elf and --gdb-runtime still requires a runtime emission.
Or pick any subset:
--scan-source Scan sources into the fat SourceScan payload
--word-counts Load metadata.h + scan for existing .macs.h
--components Generate <module>/gen/<basename>.macs.h
--validate Run atom annotation DSL validation
--offsets Generate <module>/gen/<basename>.offsets.h
--atoms-source-map Generate <basename>.atoms.sourcemap.txt per source
--dwarf-injection [opt-in] Select the post-link dwarf-injection pass + set the
opt-in flag. Requires --elf.
--static-analysis Static analysis: GTE pipeline-fill, mac_yield, ABI handoff, cycle budget
--report Render per-project summary
COMMON_FLAGS:
--source FILE Source file to process (repeatable)
@@ -248,7 +340,6 @@ COMMON_FLAGS:
--out-root DIR Output root for reports (default: build/gen)
--project-root DIR Project root for .macs.h scan (default: dirname(metadata))
--gdb-runtime Also emit <out_root>/gdb_tape_atoms_runtime.gdb (post-link, requires --elf)
--dwarf-injection Opt in to DWARF injection (writes <basename>.dwarf_*.bin blobs for objcopy splice; requires --elf)
--elf PATH Path to linked .elf (for --gdb-runtime / --dwarf-injection)
--dry-run Print dep order + ASCII graph; exit 0 without running
--verbose Print per-pass debug output
@@ -260,7 +351,9 @@ EXIT CODES:
2 Metaprogram internal error
EXAMPLE:
ps1_meta.lua --all --metadata metadata.h --source code/foo.c --source code/bar.c
ps1_meta.lua --pre-link --metadata metadata.h --source code/foo.c --source code/bar.c
ps1_meta.lua --post-link --metadata metadata.h --source code/foo.c --source code/bar.c --elf build/hello_gte.elf
ps1_meta.lua --all --metadata metadata.h --source code/foo.c --source code/bar.c
]])
end
@@ -282,21 +375,40 @@ FLAG_HANDLERS["--metadata"] = function(args, argv, arg_idx) args.metadata
FLAG_HANDLERS["--out-root"] = function(args, argv, arg_idx) args.out_root = argv[arg_idx + 1]; return arg_idx + 1 end
FLAG_HANDLERS["--project-root"] = function(args, argv, arg_idx) args.project_root = argv[arg_idx + 1]; return arg_idx + 1 end
-- Per-pass stash flags. Read by `passes/atoms_source_map.lua` to opt into the
-- post-link gdb-runtime emission. Same shape as the existing per-flag handlers:
-- mutates `args.flags` (which propagates into `ctx.flags`).
FLAG_HANDLERS["--gdb-runtime"] = function(args) args.flags = args.flags or {}; args.flags.gdb_runtime = true end
FLAG_HANDLERS["--elf"] = function(args, argv, arg_idx) args.flags = args.flags or {}; args.flags.elf_path = argv[arg_idx + 1]; return arg_idx + 1 end
-- F' track: enable DWARF injection (default OFF; opt-in via .vscode/launch.json or ps1_meta CLI).
-- Per-pass stash flags. Read by `passes/atoms_source_map.lua` to opt into the post-link gdb-runtime emission.
-- Same shape as the existing per-flag handlers. mutates `args.flags` (which propagates into `ctx.flags`).
FLAG_HANDLERS["--gdb-runtime"] = function(args) args.flags = args.flags or {}; args.flags.gdb_runtime = true end
FLAG_HANDLERS["--elf"] = function(args, argv, arg_idx) args.flags = args.flags or {}; args.flags.elf_path = argv[arg_idx + 1]; return arg_idx + 1 end
-- Enable DWARF injection (default OFF). Opts in to the post-link pass and
-- sets the flag in one shot — the explicit handler below owns both
-- selection and opt-in state, so --dwarf-injection is intentionally absent
-- from PASS_FLAG_TO_NAME.
FLAG_HANDLERS["--dwarf-injection"] = function(args)
args.flags = args.flags or {}
args.flags = args.flags or {}
args.flags.dwarf_injection = true
args.requested_set[#args.requested_set + 1] = "dwarf-injection"
end
-- Build-phase flags: --pre-link and --post-link request the roots of their
-- declared groups (see roots_for_group). topo_sort closes transitive deps
-- from those roots; dispatch_passes runs every pass in the resolved
-- closure without phase-filtering.
FLAG_HANDLERS["--pre-link"] = function(args)
request_roots_for_group(args, "pre-link")
end
-- Batch post-link phase: gdb-runtime + dwarf-injection in one luajit cold
-- start. Sets the same opt-in flags as --gdb-runtime + --dwarf-injection
-- and selects the post-link build-phase group.
-- --elf is required; parse_args enforces it after all flags are parsed.
FLAG_HANDLERS["--post-link"] = function(args)
args.flags = args.flags or {}
args.flags.gdb_runtime = true
args.flags.dwarf_injection = true
request_roots_for_group(args, "post-link")
end
-- G' (atom locals) is now consolidated into --dwarf-injection; no separate flag.
-- Pass-flag handler. Reads the closed-set table, expands --all, appends to requested_set. Single-statement, no nesting.
-- Pass-flag handler. Reads the closed-set table, expands --all, appends to requested_set.
FLAG_HANDLERS[PASS_FLAG_DISPATCH_KEY] = function(args, a)
local name = PASS_FLAG_TO_NAME[a]
if name == ALL_PASSES_SENTINEL then
@@ -307,7 +419,6 @@ FLAG_HANDLERS[PASS_FLAG_DISPATCH_KEY] = function(args, a)
end
--- Parse argv into a structured table. Validates against a closed enum.
---
--- @param argv string[]
--- @return ParsedArgs
local function parse_args(argv)
@@ -337,8 +448,10 @@ local function parse_args(argv)
pos = pos + 1
end
-- Default: --all if no explicit pass flags.
if #args.requested_set == 0 then request_all_passes(args) end
-- Default: --pre-link if no explicit pass flags were given. The first
-- invocation of a build is always pre-link, so this avoids silently
-- also invoking post-link work in builds without an ELF artifact.
if #args.requested_set == 0 then request_roots_for_group(args, "pre-link") end
-- Defaults: project_root = dirname(metadata).
if args.metadata and not args.project_root then
@@ -358,6 +471,20 @@ local function parse_args(argv)
os.exit(EXIT_INTERNAL_ERROR)
end
-- Post-link opt-ins (--gdb-runtime, --dwarf-injection) write output that
-- depends on the linked ELF. Without --elf the metaprogram can't satisfy
-- those requests, so refuse loud and early. This covers the explicit
-- --post-link batch, --dwarf-injection by itself, and --gdb-runtime by
-- itself.
local flags = args.flags or {}
local elf_path = flags.elf_path
local has_elf = type(elf_path) == "string" and #elf_path > 0
local post_links = flags.gdb_runtime or flags.dwarf_injection
if post_links and not has_elf then
io.stderr:write("ps1_meta: --elf PATH is required for post-link output\n")
os.exit(EXIT_INTERNAL_ERROR)
end
return args
end
@@ -367,12 +494,13 @@ end
--- Build the PassCtx from parsed args. Reads each source file once at startup;
--- passes consume `src.text`, not the path (path is preserved for error reporting).
---
--- @param args ParsedArgs
--- @return PassCtx
local function build_ctx(args)
local sources = {}
for _, path in ipairs(args.sources) do
-- lfs handles path metadata and directories, not file-content streams.
-- Keep this io.open local so this entry point preserves its tailored diagnostic and exit path below.
local f = io.open(path, "r")
if not f then
io.stderr:write("ps1_meta: cannot open --source " .. path .. "\n")
@@ -420,12 +548,17 @@ end
-- Topological sort (Kahn's algorithm + cycle detection)
-- ════════════════════════════════════════════════════════════════════════════
--- Compute the dep-closure of `requested_set`: include every pass name transitively required by the requested set.
---
--- Topologically sort the requested pass set, augmented with all transitive deps.
--- Detects cycles and errors out with details.
--- @param passes table<string, PassDescriptor>
--- @param requested_set string[]
--- @return table<string, boolean> -- set of pass names needed (including transitive deps)
local function dep_closure(passes, requested_set)
--- @return string[] -- execution order
---
--- Implementation note: the 4 algorithm phases (dep-closure, in-degree, ready-queue, sort) are inlined as 3 small blocks within this function.
--- Each was a 1-caller helper; the 2-caller rule doesn't apply, so inlining produces a single readable function
--- (plex: small patterns → shared, but only when shared; here they're not).
local function topo_sort(passes, requested_set)
-- Phase 1: dep-closure. Include every pass name transitively required by `requested_set`.
local needed = {}
for _, name in ipairs(requested_set) do needed[name] = true end
local changed = true
@@ -444,24 +577,8 @@ local function dep_closure(passes, requested_set)
end
end
end
return needed
end
--- Count entries in a hash table (Lua's `#t` doesn't work for hash tables).
--- @param t table
--- @return integer
local function count_entries(t)
local n = 0
for _ in pairs(t) do n = n + 1 end
return n
end
--- Compute in-degrees for the Kahn sort: for each pass in `needed`, the number of its deps that are also in `needed`.
---
--- @param passes table<string, PassDescriptor>
--- @param needed table<string, boolean>
--- @return table<string, integer>
local function compute_in_degrees(passes, needed)
-- Phase 2: in-degrees for Kahn's algorithm. For each pass in `needed`, the number of its deps that are also in `needed`.
local in_degree = {}
for name, _ in pairs(needed) do in_degree[name] = 0 end
for name, _ in pairs(needed) do
@@ -471,67 +588,41 @@ local function compute_in_degrees(passes, needed)
end
end
end
return in_degree
end
--- Seed the Kahn ready queue with passes whose in-degree is 0, sorted alphabetically for deterministic execution order.
---
--- @param in_degree table<string, integer>
--- @return string[]
local function seed_ready_queue(in_degree)
-- Phase 3: seed the ready queue with passes whose in-degree is 0, sorted alphabetically for deterministic order.
local ready = {}
for name, deg in pairs(in_degree) do
if deg == 0 then ready[#ready + 1] = name end
end
table.sort(ready)
return ready
end
-- (internal) Pop the next ready pass, decrement the in-degree of every remaining pass that depended on it
-- (inserting newly-zero-degree passes back into the ready queue), and append to `order`. Keeps `ready` sorted.
-- @param passes table<string, PassDescriptor>
-- @param needed table<string, boolean>
-- @param in_degree table<string, integer>
-- @param ready string[]
-- @param order string[]
local function process_next_ready(passes, needed, in_degree, ready, order)
local just_finished = table.remove(ready, 1)
order[#order + 1] = just_finished
for name, _ in pairs(needed) do
if name ~= just_finished then
for _, dep in ipairs(passes[name].deps) do
if dep == just_finished then
in_degree[name] = in_degree[name] - 1
if in_degree[name] == 0 then
ready[#ready + 1] = name
table.sort(ready)
-- Phase 4: drain the ready queue. For each popped pass, decrement the in-degree of every remaining pass that depended on it.
-- Newly-zero-degree passes are inserted back into the ready queue (kept sorted).
local order = {}
while #ready > 0 do
local just_finished = table.remove(ready, 1)
order[#order + 1] = just_finished
for name, _ in pairs(needed) do
if name ~= just_finished then
for _, dep in ipairs(passes[name].deps) do
if dep == just_finished then
in_degree[name] = in_degree[name] - 1
if in_degree[name] == 0 then
ready[#ready + 1] = name
table.sort(ready)
end
end
end
end
end
end
end
--- Topologically sort the requested pass set, augmented with all transitive deps.
--- Detects cycles and errors out with details.
---
--- @param passes table<string, PassDescriptor>
--- @param requested_set string[]
--- @return string[] -- execution order
local function topo_sort(passes, requested_set)
local needed = dep_closure(passes, requested_set)
local in_degree = compute_in_degrees(passes, needed)
local ready = seed_ready_queue(in_degree)
local order = {}
while #ready > 0 do
process_next_ready(passes, needed, in_degree, ready, order)
end
-- Cycle detection: if order doesn't include all needed passes, some are stuck with in_degree > 0
-- Cycle detection: if `order` doesn't include all needed passes, some are stuck with in_degree > 0
-- (the cycle closed on itself before Kahn could process them).
-- Without this check, a fully-closed cycle (e.g. A -> B -> A) would silently return an emspty order list, leaving the orchestrator to dispatch nothing.
if #order ~= count_entries(needed) then
-- Without this check, a fully-closed cycle (e.g. A -> B -> A) would silently return an empty order list, leaving the orchestrator to dispatch nothing.
local needed_count = 0
for _ in pairs(needed) do needed_count = needed_count + 1 end -- count hash entries; Lua's #t doesn't work
if #order ~= needed_count then
for name, deg in pairs(in_degree) do
if deg > 0 then
error("dependency cycle detected involving pass '" .. name .. "'")
@@ -548,18 +639,16 @@ end
--- Render the dep graph as ASCII art. Output width capped at 78 columns.
--- Falls back to the simpler "Resolved dependency order" list only if graph width exceeds terminal width.
---
--- @param passes table<string, PassDescriptor>
--- @param requested string[] -- originally-requested passes (subset of closed)
--- @param closed string[] -- dep-closed execution order
--- @return string
local function render_dep_graph(passes, requested, closed)
local function render_dep_graph(passes, closed)
local lines = {}
local function add(s) lines[#lines + 1] = s end
add("[ps1_meta] Resolved dependency order (closed under deps):")
for pass_idx, name in ipairs(closed) do
local p = passes[name]
local p = passes[name]
local deps_str = (#p.deps == 0) and "(no deps)" or
"(deps: " .. table.concat(p.deps, ", ") .. ")"
add(string.format(" %d. %-22s %-45s [%s]",
@@ -568,52 +657,204 @@ local function render_dep_graph(passes, requested, closed)
add("")
-- Data-driven ASCII graph built from the actual PASSES table.
-- Shows the source -> scan_source -> pass chain. Each pass is
-- shown once; edges are "feeds into" arrows based on deps.
-- Kahn layers determine the row of each box; each pass becomes a 4-row
-- box (top border, name, kind+output-count, bottom border). Boxes in
-- the same layer are rendered side-by-side; layers are connected by a
-- 'v' marker row whose 'v' chars are centered under each box, indicating
-- the downward 'feeds into' direction.
--
-- Layout invariants enforced here:
-- * MAX_GRAPH_WIDTH = 78 cols: no emitted line exceeds this. The
-- "simplest" way to stay under the budget is to limit each sub-row
-- to MAX_BOXES_PER_ROW = 3 boxes; for the canonical 9-row PASSES
-- table the largest layer has 3 boxes, so no wrap engages today.
-- If a future layer grows past 3 boxes, the layer is split into
-- adjacent sub-rows (each ending in its own 'v'-marker row).
-- * No silent truncation: per-layer box width is computed from the
-- layer's widest content (max(name length, kind-suffix length))
-- plus a 1-char leading + 1-char trailing padding + 2 wall chars.
-- Long names widen the box; they are NEVER truncated.
-- * Collision-safety: every PASSES row has a unique name, kind, and
-- out-list, so two distinct passes cannot produce visually identical
-- boxes.
add("[ps1_meta] Pass graph (read top-to-bottom; edges = 'feeds into'):")
add("")
-- Compute which passes feed which other passes (reverse of deps).
local feeds = {} -- feeds[X] = list of passes that X feeds into
for _, name in ipairs(closed) do feeds[name] = {} end
for name, p in pairs(passes) do
for _, dep in ipairs(p.deps) do
if feeds[dep] then feeds[dep][#feeds[dep] + 1] = name end
-- Compute Kahn layer per pass: layer L = max(deps' layer) + 1, layer 0
-- for deps-less passes. Repeated sweeps until every pass in `closed` is
-- assigned (handles forward refs that resolve on the second pass).
local pass_layer, max_layer = {}, 0
local sorted_closed = {}
for _, name in ipairs(closed) do sorted_closed[#sorted_closed + 1] = name end
table.sort(sorted_closed)
local function assign_layers()
local assigned_count = 0
for _, name in ipairs(sorted_closed) do
if pass_layer[name] == nil then
local p = passes[name]
local max_dep, ready = -1, true
for _, dep in ipairs(p.deps) do
if pass_layer[dep] == nil then ready = false; break end
if pass_layer[dep] > max_dep then max_dep = pass_layer[dep] end
end
if ready then
pass_layer[name] = max_dep + 1
if pass_layer[name] > max_layer then max_layer = pass_layer[name] end
assigned_count = assigned_count + 1
end
end
end
return assigned_count
end
while assign_layers() > 0 do end
-- Defensive invariant: any unresolved pass is a bug. topo_sort already
-- errors on cycles before this point, so reaching here means a logic
-- error in the renderer (or a synthetic call that bypassed topo_sort).
-- Surface the failure loudly with the offending names; never silently
-- place unresolved passes at layer 0 (which would corrupt the graph).
local unresolved = {}
for _, name in ipairs(sorted_closed) do
if pass_layer[name] == nil then unresolved[#unresolved + 1] = name end
end
if #unresolved > 0 then
error("render_dep_graph: unresolved Kahn layer for pass(es): "
.. table.concat(unresolved, ", ")
.. "; topo_sort should have caught this earlier")
end
-- Bucket passes by layer; sort each bucket alphabetically for stability.
local layers = {}
for i = 0, max_layer do layers[i] = {} end
for _, name in ipairs(sorted_closed) do
layers[pass_layer[name]][#layers[pass_layer[name]] + 1] = name
end
for i = 0, max_layer do table.sort(layers[i]) end
-- Layout constants. Boxes in the same layer share the same width
-- (computed as the layer's widest content + padding + walls).
local MAX_GRAPH_WIDTH = 78
local MAX_BOXES_PER_ROW = 3
local GAP = 3
local function pad_right(s, width)
if #s >= width then return s:sub(1, width) end
return s .. string.rep(" ", width - #s)
end
-- Compute the box width (in chars, including both walls) for a layer.
-- The interior is the wider of (a) the longest pass name + 1 leading
-- space and (b) the longest "<kind> <N>" suffix + 1 leading space.
-- Then add 2 for the wall chars.
--
-- Why +1 (not +2): the +1 formula means the layer's max-content row
-- has 0 padding before the right wall (the `|` is immediately after
-- the content). This is the collision-safe widening policy the task
-- requires — long names widen the box and never get trailing padding.
-- Shorter passes in the same layer get trailing padding to fill the
-- interior to the layer's uniform width; they never get truncated.
local function box_w_for_layer(bucket)
local max_content = 0
for _, name in ipairs(bucket) do
local p = passes[name]
local out_n = #(p.out or {})
local kind_suf = string.format("%s %d>", p.kind, out_n)
if #name > max_content then max_content = #name end
if #kind_suf > max_content then max_content = #kind_suf end
end
-- Interior = 1 leading space + max_content + 0 trailing (the
-- trailing `|` IS the right boundary); walls = 2.
return max_content + 3
end
-- Render one pass as a 4-row box at the given box_w. The interior is
-- always padded to fit exactly; no string is ever truncated.
local function render_box(name, box_w)
local p = passes[name]
local out_n = #(p.out or {})
local kind_suf = string.format("%s %d>", p.kind, out_n)
local interior = box_w - 2
local border = "+" .. string.rep("-", interior) .. "+"
return {
border,
"|" .. pad_right(" " .. name, interior) .. "|",
"|" .. pad_right(" " .. kind_suf, interior) .. "|",
border,
}
end
-- Join a single row (1..4) across all boxes in a sub-row, with GAP
-- spaces between adjacent boxes.
local function join_row(box_rows, row_idx)
local parts = {}
for i, b in ipairs(box_rows) do
parts[#parts + 1] = b[row_idx]
if i < #box_rows then parts[#parts + 1] = string.rep(" ", GAP) end
end
return table.concat(parts)
end
-- 'v' marker row beneath a sub-row: one 'v' centered under each box.
local function v_marker_row(box_rows)
local total = 0
local centers = {}
for i, b in ipairs(box_rows) do
local w = #b[1] -- box width = length of the top border row
local center = total + math.floor(w / 2)
centers[#centers + 1] = center
total = total + w + GAP
end
-- total now includes a trailing GAP we don't want; trim it.
total = total - GAP
local s = string.rep(" ", total)
for _, c in ipairs(centers) do
s = s:sub(1, c) .. "v" .. s:sub(c + 2)
end
return s
end
-- Render a single sub-row (a contiguous chunk of a layer's bucket).
-- Emits the 4 box rows + an empty line + the 'v' marker row + an
-- empty line, EXCEPT the very last sub-row of the very last layer
-- omits the trailing 'v' marker (nothing flows below it).
local function render_subrow(bucket_chunk, is_last_subrow, is_last_layer)
local box_w = box_w_for_layer(bucket_chunk)
local boxes = {}
for _, name in ipairs(bucket_chunk) do boxes[#boxes + 1] = render_box(name, box_w) end
add(join_row(boxes, 1)) -- top borders
add(join_row(boxes, 2)) -- names
add(join_row(boxes, 3)) -- kind + output-count
add(join_row(boxes, 4)) -- bottom borders
-- 'v' marker row beneath this sub-row connects downward to the
-- next sub-row of the same layer (if any) OR to the next layer.
-- Skip the trailing 'v' only on the very last sub-row of the
-- final layer, where nothing flows below it.
if not is_last_subrow or not is_last_layer then
add("")
add(v_marker_row(boxes))
add("")
end
end
-- Layout: source -> scan_source -> word-counts -> {components, annotation, offsets, static-analysis} -> report
-- Outputs are listed under each pass.
local outputs_for = function(name)
local p = passes[name]
if not p or not p.out or #p.out == 0 then return "" end
local outs = {}
for _, o in ipairs(p.out) do outs[#outs + 1] = o.path_template end
return table.concat(outs, ", ")
for layer_idx = 0, max_layer do
local bucket = layers[layer_idx]
local is_last = (layer_idx == max_layer)
-- Split the layer into sub-rows of at most MAX_BOXES_PER_ROW boxes.
-- With a 20-char box width (the canonical case: name "static-analysis"
-- is 15 chars, suffix "header-output 2>" is 16 chars) and GAP=3,
-- 3 boxes per sub-row = 3*20 + 2*3 = 66 cols + a 'v' row of 66 cols;
-- well within MAX_GRAPH_WIDTH. A 4th box would push to 4*20 + 3*3 = 89,
-- which is why MAX_BOXES_PER_ROW = 3 (wrap when >3).
local chunk_size = math.min(MAX_BOXES_PER_ROW, #bucket)
if chunk_size < 1 then chunk_size = 1 end
for chunk_start = 1, #bucket, chunk_size do
local chunk_end = math.min(chunk_start + chunk_size - 1, #bucket)
local chunk = {}
for i = chunk_start, chunk_end do chunk[#chunk + 1] = bucket[i] end
local is_last_subrow = (chunk_end == #bucket)
render_subrow(chunk, is_last_subrow, is_last)
end
end
add(" +-----------+ +-------------------+ +-----------------+")
add(" | source |-->| scan_source |--->| word-counts |")
add(" | files | | (scan_source.lua) | | (load) |")
add(" +-----------+ +-------------------+ +-----------------+")
add(" (single walk) |")
add(" |")
add(" +-------------------+-------------------+-----------+")
add(" v v v v")
add(" +--------------+ +--------------+ +--------------+ +---------------+")
add(" | components | | annotation | | offsets | |static-analysis|")
add(" +--------------+ +--------------+ +--------------+ +---------------+")
add(" |<src>/gen/ | |build/gen/ | |<src>/gen/ | |build/gen/ |")
add(" |<base>.macs.h | |<base>.errors | |<base>.offsets| |<base>.static |")
add(" | (header) | | .h | | .h | | _analysis |")
add(" +------+-------+ | +annot.txt | | (header) | | .txt |")
add(" | +--+-----------+ +--------------+ +------+--------+")
add(" v v v")
add(" +------+----------------+ +------+-------+ |")
add(" |offsets|static-analysis| |report| |<--------------------+")
add(" | | | +------+-------+")
add(" +-------+---------------+")
return table.concat(lines, "\n") .. "\n"
end
@@ -654,7 +895,6 @@ local function report_validation_errors(pass_name, pass, result)
end
-- (internal) Run each pass in `order` in topological sequence.
--
-- @param ctx PassCtx
-- @param order string[]
-- @return boolean -- true if any validation errors were reported
@@ -663,6 +903,7 @@ local function dispatch_passes(ctx, order)
local had_errors = false
for _, pass_name in ipairs(order) do
local pass = PASSES[pass_name]
io.stderr:write(string.format("[ps1_meta] %-22s running\n", pass_name))
local mod = require(pass.module)
local result = mod.run(ctx)
@@ -686,7 +927,7 @@ local function main(argv)
-- --dry-run: print dep order + ASCII graph, exit OK.
if args.dry_run then
io.write(render_dep_graph(PASSES, requested, closed))
io.write(render_dep_graph(PASSES, closed))
os.exit(EXIT_OK)
end
@@ -702,4 +943,20 @@ local function main(argv)
os.exit(EXIT_OK)
end
main({...})
-- Module export for in-process consumers (tests that dofile this script).
-- The closure above, `render_dep_graph`, and the canonical `PASSES` table
-- are exposed so a test can render the graph for synthetic PASSES tables
-- without spawning a subprocess. The conditional `main(...)` call below
-- only fires when this file is invoked as the entry script (arg[0] ends
-- in "ps1_meta.lua"); in dofile() mode (test's arg[0] does not match),
-- main() is skipped and the chunk returns `_M` to the caller.
local _M = {
render_dep_graph = render_dep_graph,
PASSES = PASSES,
}
if arg and arg[0] and arg[0]:match("ps1_meta%.lua$") then
main({...})
end
return _M