Repository navigation
chore: Configure Renovate - #1
Closed
renovate[bot] wants to merge 2 commits into
Closed
renovate[bot] wants to merge 2 commits into
renovate[bot] wants to merge 2 commits into
Conversation
siyul-park
force-pushed
the
main
branch
3 times, most recently
from
September 10, 2025 13:03
2e84ccc to
b992aa2
Compare
siyul-park
force-pushed
the
main
branch
12 times, most recently
from
September 15, 2025 23:59
6643bcf to
acf8995
Compare
siyul-park
force-pushed
the
main
branch
5 times, most recently
from
October 1, 2025 15:29
47ab09e to
b8ee43e
Compare
siyul-park
force-pushed
the
main
branch
8 times, most recently
from
October 12, 2025 09:26
9742a4d to
f83c525
Compare
siyul-park
force-pushed
the
main
branch
7 times, most recently
from
October 19, 2025 09:46
d2891a0 to
fdb89c1
Compare
siyul-park
force-pushed
the
main
branch
3 times, most recently
from
October 22, 2025 15:16
d26316d to
f7e9553
Compare
siyul-park
force-pushed
the
main
branch
2 times, most recently
from
May 5, 2026 13:45
3e04b59 to
bb8587f
Compare
siyul-park
added a commit
that referenced
this pull request
May 30, 2026
…c name The earlier split surfaced two types — scanner (linear-scan policy) and the rewrite/rewriteOp/resolveVReg trio (operand substitution) — when both serve a single transformation: rewrite the instruction list so its operands reference physical registers. Both became the rewriter. The work still happens in two passes internally — assign first, then rewriteAll — because pin preemption can evict a vreg from the pool at the same instruction that still references it (e.g. `ADDI vSPOut, vSPE, #1` where both vregs share scratch slot rSP). Splitting into "build the persistent vreg → preg map, then substitute" lets the rewrite pass see the assignment even after the pool has reclaimed the slot. The merge is in the public surface: rewriter.run is the only entry point; assign / rewriteAll / ensure / resolve are private steps. regPool reverts to its prior name regAlloc — the rewriter handles the "linear scan register allocation" framing, so the underlying pool can keep its established label without confusing the layering. Files reshuffle to one concept each: - asm/regalloc.go — the register pool with both-direction bindings. - asm/rewriter.go — assign + rewriteAll + ensure + resolve + lastUses. - asm/emit.go — encode pipeline (renamed from encode.go to avoid visual clash with encoder.go). Assembler.Build now delegates to a single rewriter.run call instead of calling scanner + rewrite separately.
siyul-park
added a commit
that referenced
this pull request
Jun 4, 2026
* refactor(asm,jit): rebuild asm + introduce top-level jit skeleton asm is now arch-neutral and has zero minivm dependencies. The public surface is asmjit-inspired: Arch is an interface returned by per-arch factory functions; Assembler.Build produces a Code (bytes + label table + relocations); Link writes Codes into a Buffer, patches external relocations against a Resolver, and binds Callables via the ABI. Signature is now data-only (Args, Returns, Scratch) - multi-exit semantics move out of asm/. Buffer manages W^X internally; the new Data type owns the always-writable region used for runtime-patched slots. Callable exposes Addr() so consumers can emit direct branches without re-entering Go. asm/arm64 wraps the existing AArch64 encoder and trampoline behind the new Arch interface; asm/amd64 is a compile-clean stub returning ErrNotImplemented from every Encode/NewCallable call. A new top-level jit/ package owns the compilation driver, the Slots indirection table, a Layout struct that consumers register via Bind so jit never imports them, and a Lowerer interface dispatched by runtime.GOARCH. jit/arm64 and jit/amd64 contain Lowerer scaffolding; real opcode lowering follows in the next change. interp loses its asm.Buffer field, takes a *jit.Compiler instead, and falls back to threaded execution for every opcode until Phase A lowering lands. JIT-specific tests continue to gate on jit.Active() and stay skipped while the Lowerer is unregistered. * feat(jit): wire compile pipeline + NOP segment proof-of-concept The Lowerer interface gains an Arch() method so each backend declares its own asm.Arch, plus an Exit hook that emits the segment terminator (write next IP into the agreed scratch slot, then RET). Compiler.Compile now walks the function bytecode from IP 0, dispatches per opcode through the registered Lowerer, and produces an asm.Code linked into the compiler's buffer; the resulting Callable lands in Module.Segments. The arm64 Lowerer wires up scratch-slot conventions used by every Phase A segment (stack base, sp in/out, globals, constants, next IP at slot 4) and implements NOP as the first lowered opcode. A direct asm.Callable invocation test confirms the round trip: a chain of NOPs compiles, links, executes, and writes the correct exit IP into scratch[4]. interp.adaptSegment is now a real boxing closure: it packs i.stack, i.sp, i.globals, and i.constants base addresses into the scratch buffer before calling the segment and reads sp + next-IP back afterwards. The arm64 Lowerer is intentionally still unregistered, so JIT-related interp tests continue to skip while Phase A opcode coverage is incomplete. asm.regAlloc grows an `excluded` mask separate from `blocked`: ABI scratch registers are now withheld from auto-allocation while staying reservable via Pin, which is what Lowerer.Exit needs to write scratch[4]. * feat(jit/arm64): lower DROP, DUP, and the *_CONST family Each Phase A segment now tracks a logical VM-stack shadow in Context.Stack: pushes append a fresh VReg, pops drop the trailing entry, and DROP reuses the cheaper logical removal instead of touching memory. Exit walks the shadow at the end of the segment, computes the byte address of i.stack[sp] from the scratch register pair, and writes each retained VReg back at its (sp + i) slot before adjusting sp by the net delta. The four *_CONST opcodes lower to a pre-computed NaN-boxed 64-bit immediate so the constant is materialized exactly once at compile time. I64_CONST rejects unboxable magnitudes that the threaded path would otherwise heap-promote, preserving correctness without dragging the heap into the segment ABI. A direct asm.Callable test exercises three patterns end-to-end: const-only spill, const + DROP (top discarded without a store), and const + DUP (MOV plus dual spill). All three confirm the resulting stack memory and sp delta. The arm64 Lowerer stays unregistered with jit; interp-side JIT tests continue to skip until enough Phase A opcodes land for an end-to-end program to compile cleanly. * feat(jit/arm64): lower SWAP, CONST_GET, LOCAL_*, and GLOBAL_* Compile now takes a jit.Snapshot of the consumer's tables (constants, globals, and local kinds) so kind-sensitive opcodes can check at compile time whether they have to bail out for the runtime retain that Phase A does not yet model. The interp side builds the snapshot from i.constants, i.globals, and fn.Typ.Params ++ fn.Locals before each i.jit() attempt. SWAP is a pure stack-shadow reorder. CONST_GET emits the boxed value directly as a 64-bit immediate so the constants table never needs a runtime base pointer, freeing the third scratch slot for the frame bp. GLOBAL_GET/SET issue plain LDR/STR off the globals scratch base, rejecting any idx whose current value is a ref. LOCAL_GET/SET compute their effective address as rStack + rBP*8 plus a fixed idx*8 displacement, again rejecting refs by kind. The Lowerer remains unregistered with jit, so interp-level JIT tests continue to skip. Direct asm.Callable tests cover all five new opcodes end-to-end, including a GLOBAL_SET → GLOBAL_GET round trip and a LOCAL_SET → LOCAL_GET round trip with a non-zero bp. * refactor(asm,jit,interp): align with project file layout conventions Errors move from the centralized asm/errors.go to the file that owns each sentinel's producer (memory.go for the mmap family, buffer.go for ErrBufferFull, assembler.go for ErrConflictingPin, encoder.go for ErrInvalidOperand, link.go for ErrUnresolvedLabel, abi.go for the arity sentinels, regalloc.go for ErrNoRegistersAvailable, etc.). This matches how the rest of the project keeps errors near the code that returns them. Files now follow the slot order from docs/coding-patterns.md §2.4: public types first, then private types, consts, vars (including interface compliance assertions), and finally functions and methods. Constructors live right under their type. asm/reg.go and asm/operand.go move every public function above the methods that use them; jit/compiler.go puts Option next to Compiler instead of after the private config; and jit/lowerer.go orders Lowerer → Context → Snapshot so each declaration sits above the types it references. Interface compliance assertions are now declared for every concrete asm.Arch / asm.ABI / asm.Encoder / jit.Lowerer implementation so the type system catches accidental signature drift. The unused ErrTooManyScratch sentinel in asm/arm64/abi.go is removed. stackBase in interp/interp.go moves to the package-level helper section at the bottom of the file alongside unboxRef. * refactor(jit): drop speculative accessors, rename emptyModule, tidy docs Helper audit per docs/coding-patterns.md: - Compiler.Buffer() and Compiler.Data() had zero callers and no near-term use (Step 4 reaches the slot table via Compiler.Slots / SetSlots, which stay). Removed both accessors. - Compiler config carried a separate arch field even though arch is always derived from cfg.lowerer.Arch(). Inlined and dropped the field. - jit.Bound() was a speculative "is layout set" probe with no caller and no upcoming consumer. Removed alongside the matching `bound` flag. - emptyModule misled — it returns a Module that already carries ParamKinds / ReturnKinds. Renamed to newModule, swapped the param order to (fn, addr) to match other constructors, and folded the two emptyModule(...) call sites in Compile into a single shared variable. Layout / Slots / Module.ParamKinds / ReturnKinds and the WithBuffer / WithData options stay as-is because Steps 3–4 (whole-function Entry and direct-BL CALL) already need them. * refactor(asm): regAlloc → regPool, introduce scanner, simplify build.go The build pipeline used to ship state to a 6-argument package function that owned four closures over local maps. The rewrite splits the mechanism (the register pool) from the policy (the linear-scan walk over the instruction list). regAlloc is renamed to regPool — its real role. It now tracks both directions of every binding (vreg → preg via bindings, preg → vreg via owners) so pin-conflict detection can ask "who currently owns this slot?" without a parallel reverse map upstream. The scratch-vs-blocked distinction stays as before. A new scanner type wraps the pool and owns the scan-time policy: pin preemption, lifetime-driven free, persistent assigned map, and the width back-fill that widthMap previously handled in a separate pass. The four closures (keyOf/bind/free/ensure) become explicit methods. Instruction grows Def() and Uses() helpers so the scanner reads its operands through a clean API instead of three package-private query functions. memBase moves with them as a private helper on the same file. rewrite/rewriteOp dedupe their VReg / MemOperand branches via a small resolveVReg helper. encode splits its two passes into named helpers (encodeWithPlaceholders + emitFinal) so the placeholder/patch dance is visible at the top of encode itself. Assembler.Build no longer routes through a six-argument build() function; it orchestrates scanner.run → rewrite → encode inline. Net effect: build.go drops the standalone build()/assignRegs/widthMap trio (≈100 LOC of state plumbing), scan-time state becomes addressable fields instead of closure captures, and the pool/policy split is the public design. * feat(asm): implement linear-scan register allocation with scanner and encoding functions * refactor(asm): simplify scanner methods and unify backfill functionality * refactor(asm): move lastUses function to scanner for better organization * refactor(asm): merge scanner + rewrite into rewriter, restore regAlloc name The earlier split surfaced two types — scanner (linear-scan policy) and the rewrite/rewriteOp/resolveVReg trio (operand substitution) — when both serve a single transformation: rewrite the instruction list so its operands reference physical registers. Both became the rewriter. The work still happens in two passes internally — assign first, then rewriteAll — because pin preemption can evict a vreg from the pool at the same instruction that still references it (e.g. `ADDI vSPOut, vSPE, #1` where both vregs share scratch slot rSP). Splitting into "build the persistent vreg → preg map, then substitute" lets the rewrite pass see the assignment even after the pool has reclaimed the slot. The merge is in the public surface: rewriter.run is the only entry point; assign / rewriteAll / ensure / resolve are private steps. regPool reverts to its prior name regAlloc — the rewriter handles the "linear scan register allocation" framing, so the underlying pool can keep its established label without confusing the layering. Files reshuffle to one concept each: - asm/regalloc.go — the register pool with both-direction bindings. - asm/rewriter.go — assign + rewriteAll + ensure + resolve + lastUses. - asm/emit.go — encode pipeline (renamed from encode.go to avoid visual clash with encoder.go). Assembler.Build now delegates to a single rewriter.run call instead of calling scanner + rewrite separately. * refactor(asm): emit pipeline becomes Assembler methods, drop emit.go emit / emitDraft / emitFinal now hang off *Assembler so they pick up the encoder through a.arch.Encoder() instead of receiving it on every call. Build delegates to a.emit(rewritten) in one line. emit.go disappears — all three methods live alongside Build in assembler.go. Naming sweep at the same time: - encode → emit (the byte-stream pipeline; "encode" was confusable with Encoder.Encode, which handles only one instruction). - encodeWithPlaceholders → emitDraft (draft = preliminary; pairs with emitFinal). - rewriter: rewriteAll → rewrite (slice form), the old per-inst rewrite → rewriteInst, and backfillPinWidths inlines into assign since it is five lines used in one place. * feat(jit/arm64): lower I32 arithmetic, bitwise, and EQZ Six i32 opcodes lower to native code via the segment-stack shadow: - I32_ADD / I32_SUB / I32_MUL fold through a single helper that runs the op on the 64-bit boxed inputs, then masks the result to 32 bits and re-tags it as a fresh Boxed. - I32_AND / I32_OR take the fast path because ANDing or ORing two identically tagged values preserves the tag — no re-box required. - I32_XOR cancels the tag bits, so the lowering ORs the tag back in after the EOR. - I32_EQZ masks the operand to 32 bits, compares to zero, and uses CSET + the existing boxI32 helper to produce a boxed boolean i32. A shared boxI32 helper threads the ANDI mask + LDI tag + ORR sequence behind a single call so each opcode keeps its body short. The encoded tag constant lives next to the helper as boxedI32Tag for clarity. Two arm64 lowerer tests cover the new opcodes end to end (CONST + ADD gives a boxed sum, CONST + EQZ gives boxed 1/0). * feat(jit/arm64): lower I32 comparisons and shifts Thirteen more i32 opcodes lower to native code: - I32_SHL / I32_SHR_S / I32_SHR_U share a lowerI32Shift helper. The shift count is ANDed with 0x1F so ARM64's wider register-shift semantics match WebAssembly's i32 shift modulo 32. The value lane is prepped per opcode — zero-extend for logical shifts, sign-extend for the arithmetic right shift. - I32_EQ / I32_NE compare boxed inputs directly (tags match so a 64-bit CMP is correct without prep). - I32_LT_S / I32_LE_S / I32_GT_S / I32_GE_S sign-extend each operand via SXTW before the 64-bit CMP so the chosen LT/LE/GT/GE condition code reads the proper N/V flags. - I32_LT_U / I32_LE_U / I32_GT_U / I32_GE_U zero-extend via an ANDI mask and use the unsigned condition codes (CC/LS/HI/CS). Two new helpers — signExtendI32 and zeroExtendI32 — keep the prep shapes consistent across compares and shifts. Five lowerer tests cover the cases where signed/unsigned bit patterns diverge. * feat(jit/arm64): lower I64 arithmetic, comparisons, and shifts Fourteen i64 opcodes lower to native code, modeled after the i32 set with adjustments for the 49-bit value lane: - I64_ADD / I64_SUB / I64_MUL sign-extend both inputs to 64 bits, run the op, then mask back to 49 bits and re-tag. Results that exceed the boxable range silently wrap — full heap-promote handling lands in a later phase. - I64_EQ / I64_NE compare boxed inputs directly (tags match). - I64_EQZ masks off the tag and compares the value lane to zero, pushing a boxed i32 0/1 per WebAssembly semantics. - I64_LT_S / LE_S / GT_S / GE_S sign-extend via shift-pair and use the signed condition codes; LT_U / LE_U / GT_U / GE_U zero-extend with the value-lane mask and use the unsigned codes. - I64_SHL / SHR_S / SHR_U mirror the i32 shifts but mask the count to 6 bits (the i64 shift modulo). Three helpers carry the new shape: signExtendI64 / zeroExtendI64 / boxI64. Five lowerer tests cover ADD, signed compare with a negative input, EQZ for zero and non-zero, and SHL. WebAssembly i64 does not have AND / OR / XOR opcodes in this VM, so the bitwise family is intentionally absent from the dispatch table. * refactor(jit,asm): return segment stack via ABI returns Segments now expose their stack shadow through asm.Callable returns instead of writing back through a scratch slot. The jit package owns the shared scratch layout (jit/segment.go) used by lowerers and the interpreter adapter, and asm extracts its emit pipeline into a dedicated emitter struct (asm/emitter.go). - jit/compiler: cap segment stack at ABI MaxReturns, plumb Returns into the Code signature - jit/lowerer: add Context.Returns; Exit maps stack shadow to returns - jit/arm64: rewrite lowerer around the new ABI; inline BoxReturn at callsites as types.Boxed(v.Bits()) - interp/adaptSegment: read returns off the Callable and push onto the interpreter stack via jit.Scratch* indices - docs/jit-internals: sync prose with the new ABI * feat(jit): enhance segment handling with input args and stack management * feat(jit): compile profiled segments * feat(jit): expose internal segment entries * feat(jit/arm64): lower F32/F64 arithmetic, comparisons, and conversions Add float scalar lowering to the arm64 JIT backend: - F32/F64 binary ops (ADD, SUB, MUL, DIV) via FADD/FSUB/FMUL/FDIV - F32/F64 comparisons (EQ, NE, LT, GT, LE, GE) via FCMP + CSET - Int-to-float conversions (I32/I64 → F32/F64, signed and unsigned) via SCVTF/UCVTF - F32↔F64 widening/narrowing via FCVT - Extend FMOV encoder to accept cross-width Int64↔Float32 operand pairs - 7 new TestLowerer_Compile subtests covering all new paths * refactor: JIT Compiler and Lowerer for Improved Function Compilation - Updated the `lowerer_test.go` to enhance test coverage for CONST_GET and function compilation scenarios, including immediate calls and entry point validations. - Refactored the `compiler.go` to streamline the compilation process, introducing a whole-function compilation strategy that allows for direct callable entries when all opcodes lower successfully. - Enhanced the `lowerer.go` to support whole-function compilation and improved context management during opcode lowering. - Modified the `module.go` to clarify the structure of the Module, separating Params and Returns for better clarity and usability. - Adjusted the `slots.go` to improve slot management and ensure thread safety with mutex protection. * feat: implement JIT support for reference operations: REF_NULL, REF_IS_NULL, and REF_EQ - Added handling for REF_NULL in the ARM64 lowerer to push a null reference constant onto the shadow stack. - Implemented REF_IS_NULL to check if a boxed reference is null, returning BoxI32(1) for null and BoxI32(0) otherwise. - Implemented REF_EQ to compare two boxed references, returning BoxI32(1) if they are the same and BoxI32(0) otherwise. - Updated tests to verify the correct behavior of REF_NULL, REF_IS_NULL, and REF_EQ operations in the JIT context. * feat(jit): implement BR_TABLE lowering and corresponding tests * feat(jit): implement multi-block entry and intra-function branching for BR_IF and BR instructions * fix: prevent use-after-free in Buffer/Data grow and tighten JIT correctness - asm/data.go: retire old mmap regions to `old []memory` instead of munmap-ing them; Alloc pointers baked into compiled native code remain valid until Data.Free() releases all regions at once - asm/buffer.go: same lifetime fix for Buffer; grow seals the current region before archiving it, writeAt now searches both current and archived regions so LinkAll relocation patching works across a grow - jit/arm64/lowerer.go: guard globalGet/globalSet against idx > 4095 to prevent int16 overflow in 12-bit LDR/STR unsigned-offset encoding - jit/register.go: promote registryMu to sync.RWMutex; Lookup uses RLock to avoid write contention on every Active() call in the hot path - jit/compiler.go: check emit result in blocks(); bail instead of installing malformed native code when a lowerer rejects during emit - jit/arm64/lowerer_test.go: add NaN comparison tests (f32_lt/gt/ge/ne) documenting that AArch64 FCMP NaN flags (N=0,Z=0,C=1,V=1) produce correct Wasm results for all six ordered-comparison conditions * refactor: simplify jit asm boundaries * feat(jit): enhance JIT for recursive functions and improve entry handling * perf(jit): direct self-recursive calls * feat(jit): carry block stack state * perf(interp): inline jitted fused calls * Refactor ARM64 Lowerer and Compiler for Improved Clarity and Functionality - Updated the Lowerer interface and its Context structure to enhance clarity and maintainability. - Replaced direct references to sign and zero extension functions with instance methods in the Lowerer struct. - Modified the Compiler struct to reorder fields for better organization and readability. - Streamlined the Compile method to handle whole-function and multi-block entries more efficiently. - Introduced a new Invoke function to encapsulate the invocation logic for callables, improving separation of concerns. - Enhanced the handling of stack and globals in the Invoke function, ensuring proper memory management. - Removed redundant functions and comments to clean up the codebase and improve overall readability. * docs: update coding patterns and agent guidelines with frequent style traps * refactor(jit,asm,interp): collapse boilerplate across compile pipeline Driver-side IP advance: jit.Compiler.walk now bumps c.IP by opcode width after Lower returns true; arm64 handlers no longer carry the `c.IP += instr.Instruction(c.Code[c.IP:]).Width()` postlude. Stop-mode handlers (br/brIf/brTable/ret) still own their IP. Lower contract updated in docs/jit-internals.md. jit/compiler.go: whole() and blocks() share function() + walkFunction() + prepare(); pin/pins parallel maps replaced by a single assign() over basis + per-candidate local maps in entries(). jit/lowerer.go: Context fields layered per docs/coding-patterns.md §2.5 (infra → program data → runtime state → flow → flags). arm64/lowerer.go: pinReturns() method replaces a 6-line block copied across Exit/brIf/brTable. global() drops its width return now that the driver advances IP. imm() drops its width parameter. interp/interp.go: jit() split into ensureCompiler + install. snapshot() and New() share types.(*Function).LocalKinds() via the new types.Kinds helper. asm/buffer.go: writeAt() consolidates current/archived region paths through buffer.locate() + memory.within(). Tests + race detector green across all packages. * refactor(jit,arm64): rename pinReturns to returns for clarity * fix(jit/amd64): drop stub auto-registration so x86 reports no JIT The amd64 backend is a skeletal Lowerer that rejects every opcode. While it was registered via init(), jit.Active() returned a non-nil stub on x86_64, which made interp_test.go's requireJIT helper see "JIT available" and run JIT-counter tests that can never pass on the stub. Removing the init registration lets jit.Lookup("amd64") return nil, so Active() is nil on x86_64 and requireJIT skips the affected tests cleanly. The interpreter already short-circuits when Active() is nil, so the threaded fallback path is preserved. The Lowerer type stays in place as a drop-in for a future real codegen pass. * refactor(asm,jit,interp): drop redundant wrappers and white-box test peek - asm: remove Link() wrapper around LinkAll(); the only call site was one test, all production callers already use LinkAll directly - asm: inline single-use helpers (rewriter.recordWidth, Instruction.memBase, regAlloc.keyOf) per project counter-rule for one-shot extraction - asm: move region.mu to bottom of struct so sync primitives follow policy/infrastructure/runtime/config fields - interp: drop white-box assertion on unexported i.jitted map; downstream Run output and profiler stats already cover the behavior * refactor(asm): rename LinkAll to Link The All suffix was needed only while the old Link() wrapper still existed. With that wrapper removed, the simpler name is free. * refactor(jit): tighten Compiler method names - walkFunction -> walkBlocks: describes the per-block dispatch loop, less generic than "Function" and complements the inner walk over opcodes - context -> newContext: standard Go constructor-style name for a method that allocates and returns a fresh Context
This was referenced Jun 13, 2026
Merged
Merged
siyul-park
added a commit
that referenced
this pull request
Aug 26, 2026
…solidate the test suite (#220) * refactor: move asm packages under internal/ docs/compatibility.md already classified asm, asm/arm64, and asm/amd64 as "low-level implementation packages that may change without a major version bump", but nothing enforced it. Moving them under internal/ makes the compiler enforce the boundary the doc claimed, and stops pkg.go.dev from advertising ~190 exported assembler symbols as consumable API. The module has no release tags, so there is no source-compatibility cost. No exported symbol anywhere in the module referenced asm, arm64, or amd64, so the move is invisible to every public API. cgo, platform build tags, and abi_arm64.s are file-scoped and survive the move unchanged. Also convert internal/asm/arm64/abi_arm64_test.go to package arm64_test, the last non-interp violation of docs/coding-patterns.md §12.2. Its only private access was a linked.(*caller) assertion; it now calls through the public asm.Callable interface. Lost claim, recorded in a doc comment on the test: the concrete-type assertion kept ctx on the goroutine stack across invoke, exercising a Go-stack-resident context pointer surviving stack growth and relocation. An interface call heap-escapes ctx, so that property is no longer covered there. Exporting the concrete type solely to preserve it would be test-only API widening, which §12.2 forbids; the interp JIT tests exercise the same trampoline under real stack growth. Remove externalize_tests_tmp.go, an orphaned package main at the repo root from an earlier test-migration sweep, referenced by nothing. golang.org/x/tools remains a direct dependency via internal/cmd/geninterp. TestARM64_StackReserve read abi_arm64.s by relative filesystem path, not just by import; that path is updated too. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * refactor(interp): export Option and RegistryOption New, NewPool, and NewRegistry declared their option parameters as func(*option) and func(*registry) with both structs unexported. Because the option type could not be named from outside the package, no external caller could declare a variable, slice, parameter, or return value of it — options could only be written inline at a call site, so an embedder had no way to factor out a reusable option set. Option and RegistryOption are defined types rather than aliases, per docs/coding-patterns.md §5.1, which requires an alias to carry a distinct contract. The underlying structs stay unexported, so only the With constructors can produce a value; that is the intended contract. Source-compatible: every existing call site of the form interp.New(prog, interp.WithFuel(10)) is unchanged. The 23 sites that spelled the literal func(*option) shape were all in-package test helpers forwarding option slices, and now name the exported type. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test: dedupe and simplify instr, program, interp, and cli tests First pass of a suite-wide consolidation driven by docs/coding-patterns.md §12. Behavior-preserving: no assertion was added or removed, and every subtest name survives so existing "go test -run" targets keep working. §12.1 setter/getter ownership — TestHostStruct_Field, TestHostArray_Element, and TestHostMap_Get folded into their setter owners, ordered read-then-write so each pair reads as one specification. The two fault cases that collided on merge are renamed "reading ..." and "writing ..." rather than left to Go's "#1" disambiguation. §12.1 declaration order — instr/code_test.go, program/builder_test.go, and interp/codec_test.go now follow their production files. Functions moved whole; no body edited. §12.4 table tests — program/verify_test.go collapses three same-shape families (index-bounds, type-mismatch, function-slot) and the copy-pasted balanced/unbalanced merge skeleton, parameterizing only the one differing push so the branch shape stays visible. interp/codec_test.go collapses the three VM-function-context cases. cli/run_test.go collapses all seven TestNewRunCommand cases. §12.2 construction — five raw &types.Function{} literals in verify_test.go now go through types.NewFunctionBuilder. The sixth is deliberately kept: the "control/function branch to end" case needs a BR_IF whose operand jumps past the emitted code, which a label-based builder cannot produce, and rejecting that body is the point of the test. Two real defects surfaced: - TestWithFS passed cli.OS(), which is already Root()'s default, so it proved nothing about the override. It now injects a MapFS-backed WriteFS holding a path absent from the real filesystem, which the default could not open. - TestREPL_Run named its 60 table cases with fmt.Sprint(tt.input) — raw, often multi-line REPL input — producing untypable -run targets. Cases now carry short behavioral names. Still unaudited: types, internal/asm, transform, optimize, analysis, pass, prof, and the benchmarks module. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test: order prof tests by declaration and give pass.go its own test file Second pass of the suite-wide consolidation. analysis/ was audited and found clean; no changes there. §12.1 declaration order — prof/collector_test.go, prof/jit_test.go, and prof/profiler_test.go now follow their production files. Functions moved whole; no body edited. §12.1 file ownership — TestPreserveAll and TestPreserveNone own exported functions declared in pass/pass.go but lived in pass/manager_test.go. "Each test file MUST match the production file owning the symbol", so they move to a new pass/pass_test.go. docs/testing.md:431-432 already recorded pass/pass.go as their owner, so the matrix now matches reality. These two tests overlap the "preserve all keeps results" and "drops cached results" subtests of TestManager_Invalidate, and that overlap is intentional: PreserveAll and PreserveNone return a struct with only an unexported field, so their effect is observable only through Invalidate. The two owners assert different contracts over the same mechanism -- what the Preserved value means versus how Invalidate honors it -- and both are required by §12.1's one top-level test per exported function. Left alone deliberately: prof's Profiler/Collector metric tests, which look parallel but cover aggregation-after-Flush versus direct storage; TestProfiler_Flush's concurrent case, per §12.5; and analysis's TestGVNAnalysis_Run subtests, which assert different fields and would need per-case assertion functions to tabulate -- the second abstraction layer §12.3 forbids. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test: order optimize tests by declaration and split New from Level Third pass of the suite-wide consolidation. transform/ was audited and found clean: each file has a constructor test and a Run test in declaration order, one t.Run level, and a trailing "preserves execution" parity subtest that §12.5 requires. cf_test.go is large because FoldPass.Run folds every numeric opcode and the table carries one entry per opcode -- exhaustive coverage, not duplication. §12.1 declaration order -- optimizer.go declares New, Optimize, Level, Add; the test file had Optimize last. Functions moved whole. TestNew and TestOptimizer_Level were the same three-line assertion at different levels, so neither owned a distinct contract. Both are required owners per docs/testing.md, so rather than delete one, each now tests what it owns: TestNew asserts the constructor returns an optimizer already wired with its analyses and level pipeline, usable without further registration; TestOptimizer_Level asserts the getter round-trips across O0 through O3. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test: flatten nested asm subtests and name amd64 test for its owner Fourth pass of the suite-wide consolidation. §12.4 "Aim for at most one t.Run level" -- TestAssembler_Build nested per-instruction cases under a "relaxes out-of-range branches" grouping subtest, the only two-level t.Run in internal/asm. Flattened to one level. The two cases were named "CBZ" and "B.cond", which only read correctly under the parent name, so they become "relaxes an out-of-range CBZ branch" and "relaxes an out-of-range B.cond branch". Same assertions, same fixtures. §12.1 "Each test file MUST match the production file owning the symbol" -- internal/asm/amd64's only test is TestNew, which owns arch.go's New; it lived in encoder_test.go. Renamed to arch_test.go. docs/testing.md:122 already recorded arch.go as the owner, so the filename now matches the matrix. The test reaches Encoder, ABI, and Frame through the returned arch, which is correct: those are methods on an unexported receiver and are not externally nameable, so they get no owner test of their own. Left alone deliberately: the ARM64 instruction-factory family. docs/testing.md documents TestEncoder_Encode owning exact machine bytes and TestInstructionFactories owning wrapper shape behind an AST completeness gate, in place of 152 one-line top-level tests. That arrangement is a deliberate exception, and no encoder byte literal was touched anywhere. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test: merge struct accessor pairs and order types tests by declaration Fifth pass of the suite-wide consolidation, covering the largest package. §12.1 "Setter and getter behavior MUST be tested together under the setter owner" -- TestStruct_Field folds into TestStruct_SetField and TestStruct_Raw into TestStruct_SetRaw. Each pair reads and writes the same Data slots with no independent contract, so they are genuine accessor pairs. Merged subtests are named for the direction they exercise rather than left to Go's "#1" disambiguation. §12.1 declaration order -- struct, map, function, array, boxed, closure, and parse test files now follow their production files. map_test.go and struct_test.go were the worst: NewStructType was tested twelve functions late, and TypedMap's and Map's accessor blocks were shuffled. Functions moved whole; no body edited. docs/testing.md: dropped the TestStruct_Field and TestStruct_Raw ownership rows, since those symbols are now covered under their setter owners, and adjusted the types count from 173 to 171. Also corrected four stale rows that named TestFunctionBuilder_WithParams/WithReturns/WithLocals/WithCaptures; the methods and their tests have never carried a With prefix. Left alone deliberately: Map.Get/Set and TypedMap.Get/Set look like an accessor pair but are not -- Set returns (old, ok) and owns overwrite semantics, -0.0 collapsing, and NaN non-retrievability, all independently tested. Box constructors against Boxed accessors are round-trip encode/decode, not mutable state. types/fuzz_test.go untouched, per §12.6. Subtests went 209 to 213: the four new t.Run wrappers from the two merges, with every original assertion preserved. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(interp): name runtime cases by their program and benchmark the corpus The runtime opcode corpus carried a hand-written name on every one of its 258 cases, so the name could drift from the program it labelled, and the corpus drove only TestInterpreter_Run -- per-operation dispatch cost was never measured against the programs the specification documents. The name field is gone. Subtest names now come from the program itself: runTestName renders prog.String()'s .code section to one line, stripping offset prefixes and joining with "; ", so a case reads as TestInterpreter_Run/i32.const_0x00000001;_nop/standalone The name cannot drift from what runs because it is derived from what runs, and there is nothing left to keep in sync. BenchmarkInterpreter_Run gains a PerOp block iterating the same slice, so the benchmark measures exactly the programs the test specifies. Cases with an expected error are skipped there -- timing a trap's exit path is noise. Four cases collide on their derived name, because the name renders only the .code section and these differ solely in their constants or types: a function returning one i32 versus two, "Hi"+"There" versus ""+"", a map keyed by string versus any, and a closure capturing an array versus a struct. All four are genuinely distinct cases, so the old hard failure on duplicate names is now a t.Logf report and Go's #1 suffix disambiguates them. Subtest count is unchanged at 633, and the "covers every runtime opcode" gate still passes. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(instr): accept and emit symbolic branch labels in listings program.Parse already round-trips every section, but instr.Parse accepted only numeric branch operands, so any program with a loop had to be built with program.Builder's Label/Bind/Br. That is why every benchmark fixture is a 40-200 line Emit chain, and why hand-writing a loop means computing signed i16 deltas by hand. ParseAll now accepts a label definition on its own line and a symbolic operand on br, br_if, and br_table, resolving through instr.Builder rather than a second back-patcher. Format emits a label line for every branch target and renders branch operands as those names, falling back to numeric form for a target that does not land on an instruction boundary. Labels are named L%04d by absolute offset, so they are deterministic without a counter. A loop now reads as: 0000: i32.const 0x00000000 0005: local.set 0x00 L0007: 0007: local.get 0x00 0015: br_if L0031 0028: br L0007 L0031: 0031: return br_table keeps its encoding order -- count, cases, then the default, which is the clamp target the interpreter selects when the index is out of range. An intermediate version dropped the count and moved the default to the front, giving the opcode two incompatible dialects; §5.4 asks text input and output to be symmetric, so Format's form is now a strict superset of Instruction.String()'s: same fields, same order, label names allowed in target positions. Numeric operands parse exactly as before; this is additive. Instruction.String(), single-line instr.Parse, and the REPL's @-absolute syntax are unchanged -- a single line cannot resolve a forward reference. FuzzFormatRoundTrip covers Marshal(ParseAll(Format(code))) == code. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(benchmarks): write control and call fixtures as assembly listings Every benchmark fixture was a hand-emitted Emit chain from which no reader could recover the program under measurement. iterativeFib was 22 lines of b.Emit(...) with two opaque Label handles; the sieve was worse. Now that branch targets can be written symbolically, each fixture is a listing parsed by program.Parse, with labels named for what they do -- loop, done, next, scan -- instead of L0007. Instructions are indented and labels sit at column 0, so the control flow is visible at a glance. Converted: iterativeFib, sieve, recursiveFib, indirectRecursiveFib, closureCounter, nqueens, fannkuch. Each conversion was checked byte-for-byte against the previous builder before the builder was deleted: the old functions were extracted from git HEAD, placed alongside the new ones, and compared with reflect.DeepEqual over the whole *program.Program -- Code, Locals, Globals, Constants, Types, Handlers -- for all eight parameterizations the benchmarks actually use. No workload, iteration count, want value, or benchmarkCompare script changed. closureCounter's 128 call/drop pairs are still generated by a loop over the listing text; spelling out 128 repeats would hurt readability rather than help. Two syntax details worth recording, both found empirically rather than assumed: local type declarations take one type per line, and inside a .constants function body every continuation line including a label definition must carry leading whitespace, or it reads as the start of a new constant. The files grow -- control 243 to 312 lines, call 643 to 797 -- because one instruction per line is longer than a packed Emit chain. That is the intended trade: the point is a reader recovering the algorithm, not fewer lines. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(benchmarks): write memory and numeric fixtures as assembly listings Converts eight of twelve fixtures to listings, matching the pattern set for control and call: branchTree, mandelbrot, matmul, spectralnorm, nbody, allocationGraph, permutationFlips, sortStress. Each was checked byte-for-byte before its builder was deleted -- old builder extracted from git HEAD, compared with reflect.DeepEqual over the whole *program.Program at the exact parameters the benchmarks use. No workload, iteration count, want value, or benchmarkCompare script changed. branchTree generates its label names per iteration, since 96 node branches share one .code listing and a label may only be defined once. spectralnorm's two helper functions are now two literal .constants entries rather than one parameterized Go generator: they differ by a single argument order, and duplicating thirty lines of listing reads better than the abstraction did. Four fixtures keep their builders because the text format cannot express what they need. These are pre-existing round-trip gaps, surfaced rather than caused by this work: - typedArraySum needs a 256-element TypedArray constant. parseLiteral handles only scalars, and a 256-element literal would not read better than the builder even if it could be spelled. - stringBuild needs types.String constants. parseLiteral has no string case, so a program carrying one does not survive Parse(prog.String()). - structTreeWalk and binaryTrees name their struct fields. StructField carries a Name, but StructType.String() omits it and parseStructType rebuilds fields without one, so a round trip silently drops the names. The last two are §5.4 symmetry defects in a public API, not merely missing convenience. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(program): round-trip string constants and named struct fields program.Parse(prog.String()) was lossy two ways, both §5.4 symmetry defects in a public API: parseLiteral switched on i32, i64, f32, f64, i1, i8, and any, with no string case, so any program carrying a types.String constant failed to parse with "unknown constant type". Program.String() already rendered such a constant as `string "..."` via %q, so only the reader was missing; it now unquotes with strconv.Unquote. While adding it, a second bug surfaced: parseLiteral split the line with strings.Fields and rejoined with a single space, collapsing repeated internal whitespace. That would have silently corrupted any string holding consecutive spaces or tabs even once the string case existed. The split is now index-based so the quoted literal is preserved exactly. types.StructField carries a Name, but StructType.String() omitted it and parseStructType rebuilt each field bare, so a named struct type lost its names on a round trip. Both now use `name: type`, a marker no other Type.String() produces. Unnamed fields render exactly as before, so existing listings and golden strings stay valid. One existing assertion changed: interp/host_test.go's TestHostStruct_String hard-coded the lossy rendering, expecting "struct {i32}" for a host struct whose field is named Count. It now expects "struct {Count: i32}" -- it was pinning the bug. program/fuzz_test.go's FuzzParseProgram already carried a types.String seed that the parse failure had been silently swallowing; it now exercises the round trip for real. Seeds for named structs were added there and in types/fuzz_test.go. This unblocks three benchmark fixtures still written as Emit chains -- stringBuild, structTreeWalk, and binaryTrees. typedArraySum stays a builder: it needs a 256-element array constant, and no literal syntax for that would read better than the builder. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(benchmarks): write remaining memory fixtures as listings Converts stringBuild, structTreeWalk, and binaryTrees, which the previous commit's round-trip fixes unblocked. Each was compared with reflect.DeepEqual over the whole *program.Program against its git-HEAD builder at the exact benchmark parameters before the builder was deleted. typedArraySum keeps its builder: it needs a 256-element TypedArray constant, and no literal syntax for that would read better than the loop that fills it. Converting them exposed a parser bug. parseTypes, parseConstants, and parseLocals each stripped a listing line at the first colon, to drop the "NNNN:" index Format writes. A struct field name carries a colon too, so a hand-written "struct {value: i64}" line lost everything up to it and parsed as a corrupt type. Only a leading run of digits followed by a colon is an index now, extracted as stripIndexPrefix and shared by all three call sites. The bug was reachable only from hand-written listings -- Program.String() always emits the index -- so a round trip never hit it, which is why the fuzz targets did not catch it. program/parse_test.go gains a case that parses a named struct type with no index prefix. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(geninterp): table the check-mode cases and isolate their arrange Last unaudited package in the suite-wide consolidation. TestGenerator already honored §12.2's rule for a main package: it builds the real binary and drives it as a subprocess, asserting on exit status, output, and the bytes written to interp/threaded.go, never reaching inside the package. It held three copy-pasted check-mode blocks differing only in the file's pre-state and the expected error, so §12.4 makes them a table: up-to-date output passes silently, stale output is rejected without being rewritten, and missing output fails to read. Per §12.3 each subtest now owns a fresh TempDir and writes its own state instead of mutating one directory in sequence; the only shared reads are the immutable golden bytes and the built binary path. The AST-shape assertions stay as they are. They pin generator invariants -- the threader struct, init, Compile, no Interpreter-receiver methods, no calls into the forbidden set -- and are a different shape, not a duplicate of the check-mode cases. No production file changed and make check-generated still passes, so interp/threaded.go is untouched. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(interp): add RefCount and Flush, and use them in tests Two gaps in the public API kept interp_test.go reaching into private state, and both are real caller contracts rather than test accessors. RefCount reports the live reference count for a heap address. An embedder that passes references across the host boundary with Retain and Release had no way to verify the two stayed balanced; this is the ownership counterpart to the existing heap methods, and it validates and errors like its neighbours. Flush publishes pending samples and JIT counters into the attached profiler without closing the interpreter. Close already did this internally, so a long-running embedded VM previously had to shut down to read its own metrics. With those in place, most private reads in the simpler tests turn out to have had public equivalents all along: i.sp is Len, i.stack[n] is Peek, and i.constants[idx] is Const. TestInterpreter_Reset's frame assertions now go through FP and Frame, and its heap-baseline case asserts what it actually means -- that an Alloc after Reset reuses the address an earlier Alloc returned -- instead of reading the heap slice. Converted: TestNew, TestWithProfiler, TestWithFrame, TestInterpreter_Reset. TestWithHeap and TestInterpreter_Alloc needed nothing. One subtest is left as-is: "finalizes and clears dynamic values" scans the backing array past len for non-nil slots, pinning Go slice and GC hygiene rather than a caller-facing contract. Exporting an accessor for that would be test-only widening, which §12.2 forbids, so it waits for the pass that decides whether the claim survives. The file is still package interp. Later units clear TestWithThreshold and TestInterpreter_Run before the clause flips, so the tree compiles at each step. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(interp): route TestInterpreter_Run assertions through public API Replaces private-state reads in TestInterpreter_Run with their public equivalents, which mostly already existed: i.sp is Len, i.stack[n] is Peek, i.constants[idx] is Const, i.globals[idx] is Global, and i.rc[addr] is the RefCount added in the previous commit. Private touchpoints in this test drop from 63 to 14, with the subtest count unchanged at 633. What remains needs more than a rename. Two subtests read tracer loop bookkeeping, the threaded dispatch table, and the cooling flags to pin tier-up behavior, and two scan the whole refcount table with i.rc[1:] to assert no reference leaked. The table scan needs a way to enumerate heap slots, which the next commit adds; the tier-up bookkeeping is decided in the pass that covers TestWithThreshold. The file is still package interp so the tree compiles at each step. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(interp): add HeapCap and use it to scan refcounts publicly Two assertions in TestInterpreter_Run walked the whole refcount table with i.rc[1:] to prove no reference leaked. RefCount already answered the question per address, but nothing public bounded the walk. HeapCap returns one past the highest allocated heap address. It bounds a scan; it is deliberately not a count of live values, because a released slot stays in range until it is reused, and the doc comment says so. The caller contract is memory pressure: WithHeap and WithHeapLimit are public tuning knobs, and until now an embedder could set a limit but never watch usage approach it. Both scans now walk 1..HeapCap and skip addresses RefCount rejects. Dead slots carried a count of zero before, so the totals are unchanged. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(interp): reproduce the native trace-cut for real, drop the fake entry installFakeExit fabricated a native module -- a hand-built anchor, module, native entry, and exitDescriptor pushed in through the private install -- and fakeExitCallable wrote raw frame-journal cells that only the ARM64 code generator should ever write. §12.2 forbids proxying a real implementation to inject failure, and §12.3 says a condition no public mechanism can produce must not be kept alive by a proxy double. The correctness half turned out to be reproducible for real. staticPlan disqualifies a module-level entry containing a CALL, so such a function can only compile through the trace frontend; padding its loop body past opLimit makes the recorded trace exhaust its budget before completing an iteration, so the compiled entry takes a genuine ExitTraceCut on every entry. The new subtest asserts results stay correct across warm Run/Reset cycles and reads vm_jit_native_exits_total with reason=trace-cut through the public profiler. Verified non-flaky under -race -count=5. Two claims had no public expression and are deleted: - Retirement timing: that an entry retires once give-up exits cross retireGiveUpThreshold within one retireWindow. The watchdog's give-up classification is private policy with no counter behind it, and isCold and natives are private. - That a healthy entry is never retired however many exits it takes. Telling "still installed" from "retired" has no public observable, and forcing a workload that produces only ExitLoop and nothing else is not reachable through the public API either. The first mirrored the RecursiveFib/35 regression, so the loss is real, but a fabricated entry proved the harness rather than the runtime. TestWithProfiler goes from 9 subtests to 8: two fabricated cases out, one genuine reproduction in. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(interp): assert JIT tiering through profiler metrics TestWithThreshold held 126 of the file's remaining private touchpoints. It read tracer trees, the threaded dispatch table, cooling flags, hot-entry counters, and decoded raw bytecode out of i.instrs to work out which branch returned which constant. All of it now goes through prof, which already publishes the same events: an installed entry is vm_jit_compiles_total{outcome=emitted}, a learned branch going native is trigger=side-exit, and the tracer's per-branch hit counter is vm_jit_native_exits_total. Around fifteen subtests that walked bytecode to find a branch now just wait for the side-exit compile counter to move, which is the same guarantee without the introspection. 126 touchpoints down to 2, subtest count unchanged at 64, stable under -race -count=3. One assertion turned out to have never tested anything. "warm entry skips sampling" attached no profiler, and sample() is gated on one being present, so its require.Equal compared 0 to 0 whatever the runtime did. Attaching a profiler to make it observable shows the callee accrues one safepoint sample per call indefinitely, because a CALL from a non-native frame never links into the callee's compiled code -- so the original wording is not merely untested, it is wrong. The "compiles to native" half stays; the sampling half is gone with a comment recording what was found. Two subtests are deleted with their claims recorded. "entry counter saturates" drove an overflow edge by writing MaxUint64 into the counter and calling hit() directly, and "records entry only from actual entry state" manipulated frame ip and peeked at tracer trees; neither edge is reachable from any public entry point. Two touchpoints remain, both reading the per-address hot-entry counter to prove RESUME and the host-callback trampoline route through the normal entry hook. docs/profile.md states that contract, and its observable consequence is that such functions tier up like any other, so the next commit asserts the tier-up rather than exporting the counter. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(interp): clear the last private reads from interp_test.go Live private access in this file is now zero; the six remaining matches are comments recording what each assertion used to do. Converted: - "no tracing when the threshold is unreachable" now asserts through the profiler. Probing showed one incidental partial-outcome capture always fires on first entry regardless of threshold -- ordinary entry warmup, since backedge() gates real loop discovery behind the threshold -- so the faithful projection is that no capture ever reaches outcome=published. - "preserves native handlers when cooling backedges" is reproduced for real rather than deleted. Cooling is reached deterministically by the fifth run at WithThreshold(1), driven by entryWarmup and coolLimit, so the test drives eight runs, checkpoints attempts and native entries, drives eight more, and asserts attempts stayed flat while native entries kept growing -- which is the contract docs/profile.md states. - The coroutine and host-callback entry-count subtests assert the tier-up their counters caused instead of reading the counters. Thresholds are set so the test only passes if both CALL and RESUME count as entries, which is the claim; the exact counts stay as prose. - The give-up case compares vm_jit_attempts_total across sixteen further runs, since one reading cannot show a function went cold but a flat pair can. - Reset's dynamic-value case now uses RefCount before and after: live with count one, then rejected, proving Reset did not leave it reachable. Deleted with the claim recorded in place: - The scan of i.heap past len for non-nil slots. It pins Go slice and GC hygiene of the backing array, which no caller can observe. - require.Nil(t, i.profiler). With no profiler attached there is nothing public to read, so the assertion has no observable form. Subtest count is unchanged at 208, stable under -race -count=3. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(interp): make interp_test.go an external test package interp/interp_test.go is now package interp_test, exercising the interpreter as an importing client, per docs/coding-patterns.md §12.2. The earlier commits removed its private state access; this one completes the move. The two symbols the compiler surfaced last both resolved through the public surface rather than new API: - Three subtests compared whole refcount tables with threaded.rc[1:] against jit.rc[1:]. A local refCounts helper snapshots 1..HeapCap with RefCount, which is the same shape TestInterpreter_Run already uses, and comparing the maps is slightly stronger: a dead slot is absent rather than zero, so a liveness divergence between the two runs now fails too. - Five sites called the unexported stub(addr) to check native code was installed. §14 requires a warm JIT benchmark to prove installation before timing, and the profiler reports it. That second one needed care. A profiler on the timed interpreter fails dispatch's fast-path guard, and with WithTick(1) that means a safepoint on every instruction -- BenchmarkInterpreter_Run/JITWarm would have measured tick overhead instead of JIT throughput. It now runs a throwaway probe with a profiler to prove the program and option set install natively, then times an identically warmed interpreter with no profiler, so the mode stays comparable to Threaded and Fused. BenchmarkInterpreter_Reset is unaffected: it times Reset, which never consults the profiler. trackedValue is duplicated into trace_test.go, which is still package interp. Fifteen lines across a package boundary beats a shared helper file, which §12.1 forbids. Four unexported constants -- heapRunway 64, exitThreshold 8, opLimit 1024, nativeFrameLimit 128 -- are mirrored as test-local constants naming their production counterpart. §5.1 says policy knobs must not be exported, so this accepts a documented drift risk rather than widening the API for tests. trace_test.go, jit_plan_test.go, and jit_arm64_test.go remain package interp. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(instr): reject an oversized br_table count instead of panicking Review of the branch found a crash reachable from text input, introduced by the label commit. parseBranch narrowed the parsed br_table count to int before checking it against the operands supplied. A count near the top of uint64 wraps negative, which satisfied the arity check with zero operands, under-allocated the operand slice, and panicked inside New with an index out of range. ParseAll is a trust boundary, and the generic parseOperands path it replaced returned a clean error for the same input. The count is now compared as uint64 before any narrowing. FuzzParseAll covers the gap that hid this: FuzzParse drives a single line, and FuzzFormatRoundTrip only ever feeds ParseAll well-formed Format output, so neither reached the label table or the br_table count that only ParseAll interprets. It asserts a listing either errors or round-trips, and seeds include the overflow, a duplicate label, and an unbound branch. Clean over 5M executions. Two more findings from the same review: HeapCap returned len(i.heap), but cap(i.heap) is a genuinely different quantity in that file -- the allocator doubles the backing array, so capacity runs ahead of the high-water mark. The name fought the code; it is HeapLen now, and the doc says it is neither a live count nor the capacity. StructType.String() renders field names but Equals still compares only types, so Equals no longer implies equal rendering. Nothing keys off String for identity today, but FieldIndex does treat names as meaningful, so Equals now documents that it means structural compatibility. Also fixed a pre-existing round-trip defect the review surfaced next door: parseStructType split fields on every ";", so a nested struct with two or more fields was cut mid-type and failed to parse. The split now tracks brace depth. Named fields make nested structs more attractive, which is why it is worth fixing here rather than leaving it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(interp): name the hollowed subtests honestly and record the gaps Test review found two subtests that kept names promising invariants their bodies no longer check, and one mechanism left with no coverage at all. "entry counter saturates" and "records entry only from actual entry state" were reduced to running a program and expecting no error when their private drivers were removed. The bodies are right -- the overflow edge and the fabricated-frame-ip path are not reachable publicly -- but the names implied otherwise to anyone reading -run output. They now say what they verify, with the lost invariant recorded in a comment above each. docs/testing.md gains a Known Coverage Gaps section. The one that matters is Interpreter.retire and its watchdog: nothing in the suite exercises it since the fabricated native entry came out. I tried to restore it -- ExitTraceCut counts as a give-up, and the genuine trace-cut program produces one on every native entry -- but native entry counts grow linearly past 80,000 with no plateau, so retirement has no observable signature through the public metrics. Writing a test that passes without proving anything would be worse than recording the gap, so it is written down with what closing it would take. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(instr): label the end of code, and address review findings From the automated review on PR #220. Format did not treat one-past-the-last-instruction as a label site, so a loop that exits by branching to the end of the code rendered its target numerically -- exactly the pattern the label feature exists to make readable. That offset is a boundary: program/verify.go accepts it, and a loop exit is the ordinary way to reach it. Format now names it and emits a trailing label line. The test that documented the old behavior conflated two cases under one name. It is split: one case for the end-of-code boundary, which is now labelled, and one for a target genuinely past the end, which still falls back to numeric. The §6 ownership table in docs/coding-patterns.md still listed the parent package as asm while the row beneath it already said internal/asm/<arch>. The docs pass missed it. interp/codec_test.go's table closure returned (int32, error, context.Context), putting error in the middle. Convention wants it last, and my table conversion introduced the ordering; go vet does not flag it and the repo has no staticcheck config, so nothing caught it. Two findings need no change. The nested-struct split was already fixed in d0040d1 -- the exact case cited round-trips. And interp/interp_test.go has been package interp_test since c28a5c2; jit_arm64_test.go is the file still declaring package interp, which docs/testing.md already records. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(interp): gate the trace-cut assertion to arm64, fold sibling Parse tests CI caught what my local runs could not: TestWithProfiler's genuine trace-cut subtest failed on ubuntu amd64. The exit reason it asserts requires a backend that emits native code, and the ARM64 lowering is not compiled on amd64 at all, so no native exit is ever recorded. The result-correctness half is architecture-independent and stays unconditional; only the metric assertion is gated now. I had flagged in the PR that green amd64 CI proves nothing about the JIT paths, then wrote a test that needed them. The suite now also runs under GOARCH=amd64 locally through Rosetta, which reproduces the CI arch and would have caught this before pushing. TestParse_NestedStructFields and TestParse_StructFieldNames were sibling top-level tests for types.Parse, which TestParse already owns. §12.1 forbids sibling top-level tests per case, so all three cases move under TestParse as subtests. No assertion changed; TestParse now runs 37 subtests. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Welcome to Renovate! This is an onboarding PR to help you understand and configure settings before regular Pull Requests begin.
🚦 To activate Renovate, merge this Pull Request. To disable Renovate, simply close this Pull Request unmerged.
Detected Package Files
go.mod(gomod)Configuration Summary
Based on the default config's presets, Renovate will:
fixfor dependencies andchorefor all others if semantic commits are in use.node_modules,bower_components,vendorand various test/tests (except for nuget) directories.🔡 Do you want to change how Renovate upgrades your dependencies? Add your custom config to
renovate.jsonin this branch. Renovate will update the Pull Request description the next time it runs.What to Expect
It looks like your repository dependencies are already up-to-date and no Pull Requests will be necessary right away.
❓ Got questions? Check out Renovate's Docs, particularly the Getting Started section.
If you need any further assistance then you can also request help here.
This PR was generated by Mend Renovate. View the repository job log.