From 98893c163ff19177003fb649a4c60eca93cb2320 Mon Sep 17 00:00:00 2001 From: "Alice V." Date: Tue, 1 Dec 2026 00:36:39 +0000 Subject: [PATCH 01/12] frill: forward-referenced calls adopt the callee's declared return type MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A call to a function parsed later in the module (Frill parses top-level lets in source order) defaulted its result type to u8, and let that default spread into the binding and its variable references. The mir2 VM returns the full machine register regardless of the contract, so the mistyped forward call only produced wrong code on the Z80 backend, which reads exactly the contract register (A for u8) — visible as 'assert eval "5" == 5 got 0' in examples/frill/expr_eval.frl under --asserts-force z80 (eval_atom's forward call to eval_expr was u8 while eval_expr returns u16, truncating the parenthesised-input path to 0). After the whole module is parsed, rewrite call result types from the now- known p.returnTypes, fix let-bound variable references, re-derive the return types of functions whose annotation was inferred from a body that contained such a call, and walk again. Regression test: pkg/frill/forward_ref_type_test.go. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS --- minzc/pkg/frill/forward_ref_type_test.go | 133 ++++++++++++++++ minzc/pkg/frill/frill.go | 185 ++++++++++++++++++++--- 2 files changed, 295 insertions(+), 23 deletions(-) create mode 100644 minzc/pkg/frill/forward_ref_type_test.go diff --git a/minzc/pkg/frill/forward_ref_type_test.go b/minzc/pkg/frill/forward_ref_type_test.go new file mode 100644 index 000000000..e36ef746c --- /dev/null +++ b/minzc/pkg/frill/forward_ref_type_test.go @@ -0,0 +1,133 @@ +package frill + +import ( + "testing" + + "github.com/minz/minzc/pkg/hir" + "github.com/minz/minzc/pkg/mir2" + "github.com/minz/minzc/pkg/pipeline" +) + +// A call to a function parsed later in the module used to default its result +// type to u8. The mir2 VM returns the full register regardless of the +// contract, so the wrong type only produced wrong code on the Z80 backend, +// which reads exactly the contract register (A for u8). Regression for the +// frill/expr_eval.frl z80 assert failure (eval_atom → forward call to +// eval_expr typed u8). +const forwardRefSrc = ` +let use_helper (x : u16) : u16 = helper x +let helper (n : u16) : u16 = n + 256 + +(* the callee's return type is inferred from a body with a forward call *) +let use_g (x : u16) : u16 = g x +let g (n : u16) = n + 256 + +assert use_helper 0 == 256 +assert use_g 0 == 256 +` + +func TestForwardCallAdoptsDeclaredReturnType(t *testing.T) { + hm, err := Compile(forwardRefSrc, "forward_ref.frl") + if err != nil { + t.Fatalf("compile: %v", err) + } + for _, pair := range [][2]string{{"use_helper", "helper"}, {"use_g", "g"}} { + fname, callee := pair[0], pair[1] + fn := funcByName(hm, fname) + if fn == nil { + t.Fatalf("function %s not found", fname) + } + found := false + walkBodyExprs(fn.Body, func(e hir.Expr) { + if call, ok := e.(*hir.CallExpr); ok && call.Fn == callee { + found = true + if call.Ty != mir2.TyU16 { + t.Errorf("%s: call to %s has type %v, want u16", fname, callee, call.Ty) + } + } + }) + if !found { + t.Fatalf("%s: no call to %s found", fname, callee) + } + } +} + +func TestForwardCallZ80Asserts(t *testing.T) { + hm, err := Compile(forwardRefSrc, "forward_ref.frl") + if err != nil { + t.Fatalf("compile: %v", err) + } + opts := pipeline.DefaultOptions() + opts.AssertMode = "none" + steps, err := pipeline.CompileHIRSteps(hm, opts) + if err != nil { + t.Fatalf("compile steps: %v", err) + } + if err := pipeline.RunAssertsMIR2(hm, steps.MIR2Module); err != nil { + t.Errorf("mir2: %v", err) + } + if err := pipeline.RunAssertsZ80(hm, steps.MIR2Module, steps.Allocation, steps.Assembly); err != nil { + t.Errorf("z80: %v", err) + } +} + +func funcByName(hm *hir.Module, name string) *hir.Func { + for _, f := range hm.Funcs { + if f.Name == name { + return f + } + } + return nil +} + +func walkBodyExprs(b *hir.Block, fn func(hir.Expr)) { + if b == nil { + return + } + var walkStmt func(s hir.Stmt) + var walkExpr func(e hir.Expr) + walkExpr = func(e hir.Expr) { + if e == nil { + return + } + fn(e) + switch t := e.(type) { + case *hir.BinExpr: + walkExpr(t.L) + walkExpr(t.R) + case *hir.CallExpr: + for _, a := range t.Args { + walkExpr(a) + } + case *hir.CastExpr: + walkExpr(t.X) + case *hir.CondExpr: + walkExpr(t.Cond) + walkExpr(t.Then) + walkExpr(t.Else) + case *hir.LetInExpr: + walkExpr(t.Init) + walkExpr(t.Body) + case *hir.UnaryExpr: + walkExpr(t.X) + } + } + walkStmt = func(s hir.Stmt) { + switch t := s.(type) { + case *hir.ReturnStmt: + if t.Val != nil { + walkExpr(t.Val) + } + for _, v := range t.Vals { + walkExpr(v) + } + case *hir.VarDeclStmt: + walkExpr(t.Init) + case *hir.ExprStmt: + walkExpr(t.Expr) + } + } + for _, s := range b.Body { + walkStmt(s) + } +} diff --git a/minzc/pkg/frill/frill.go b/minzc/pkg/frill/frill.go index 0d4a50fc4..1b860487f 100644 --- a/minzc/pkg/frill/frill.go +++ b/minzc/pkg/frill/frill.go @@ -66,7 +66,8 @@ func CompileWithOpts(src, name string, opts CompileOpts) (*hir.Module, error) { src: src, pos: 0, line: 1, name: name, adts: make(map[string]*adtDef), ctors: make(map[string]*adtCtor), arities: make(map[string]int), returnTypes: make(map[string]mir2.Ty), classes: make(map[string][]string), - stringIdx: make(map[string]int), varTypes: make(map[string]mir2.Ty), + inferredRetTys: make(map[string]bool), + stringIdx: make(map[string]int), varTypes: make(map[string]mir2.Ty), polyFuncs: make(map[string]*polyFunc), polySpeced: make(map[string]bool), ioFuncs: make(map[string]bool), baseDir: opts.BaseDir, @@ -115,28 +116,29 @@ type adtCtor struct { } type parser struct { - src string - pos int - line int - name string - peeked *token - adts map[string]*adtDef // type name → definition - ctors map[string]*adtCtor // constructor name → ctor (for match + expr) - autoFuncs []*hir.Func // auto-generated helpers (__tag, __payload, lambdas) - lambdaCount int // counter for unique lambda names - strings []string // interned string literals - stringIdx map[string]int // dedup: content → index in strings[] - records []*mir2.StructTy // record type declarations - arities map[string]int // function name → param count (for partial application) - returnTypes map[string]mir2.Ty // known function signatures, including Nanz imports - varTypes map[string]mir2.Ty // variable/param name → declared type (for VarRefExpr) - polyFuncs map[string]*polyFunc // polymorphic function templates - polySpeced map[string]bool // already-specialized mangled names - ioFuncs map[string]bool // functions marked as IO (effectful) - baseDir string // for import resolution - lastTuple []hir.Expr // pending tuple elements from (e1, e2) - classes map[string][]string // class name → method names - warnings []string // linearity warnings + src string + pos int + line int + name string + peeked *token + adts map[string]*adtDef // type name → definition + ctors map[string]*adtCtor // constructor name → ctor (for match + expr) + autoFuncs []*hir.Func // auto-generated helpers (__tag, __payload, lambdas) + lambdaCount int // counter for unique lambda names + strings []string // interned string literals + stringIdx map[string]int // dedup: content → index in strings[] + records []*mir2.StructTy // record type declarations + arities map[string]int // function name → param count (for partial application) + returnTypes map[string]mir2.Ty // known function signatures, including Nanz imports + inferredRetTys map[string]bool // functions whose return type was inferred, not annotated + varTypes map[string]mir2.Ty // variable/param name → declared type (for VarRefExpr) + polyFuncs map[string]*polyFunc // polymorphic function templates + polySpeced map[string]bool // already-specialized mangled names + ioFuncs map[string]bool // functions marked as IO (effectful) + baseDir string // for import resolution + lastTuple []hir.Expr // pending tuple elements from (e1, e2) + classes map[string][]string // class name → method names + warnings []string // linearity warnings } @@ -574,6 +576,35 @@ func (p *parser) parseModule() (*hir.Module, error) { // Append auto-generated helper functions (__tag, __payload) mod.Funcs = append(mod.Funcs, p.autoFuncs...) + // Forward references: a call to a function parsed later in the module + // defaults its result type to u8 (parseCall, callRetTy fallback) because + // p.returnTypes does not know the callee yet. The mir2 VM happens to + // return the full machine register regardless of that contract, so the + // wrong type only surfaces as wrong code on the Z80 backend, which reads + // exactly the contract register (A for u8). Now that every signature is + // known, adopt the declared return types. A second pass then re-derives + // the return types of functions whose annotation was *inferred* from a + // body that contained such a mistyped call, and fixes all bodies again. + for _, fn := range mod.Funcs { + if fn.Body != nil { + p.fixForwardCallTypes(fn) + } + } + for _, fn := range mod.Funcs { + if fn.Body == nil || !p.inferredRetTys[fn.Name] { + continue + } + if val := bodyReturnValue(fn.Body); val != nil && val.ExprTy() != fn.RetTy { + fn.RetTy = val.ExprTy() + p.returnTypes[fn.Name] = fn.RetTy + } + } + for _, fn := range mod.Funcs { + if fn.Body != nil { + p.fixForwardCallTypes(fn) + } + } + // Intern string literals as CStrings (null-terminated) for i, s := range p.strings { mod.Strings = append(mod.Strings, s) @@ -584,6 +615,113 @@ func (p *parser) parseModule() (*hir.Module, error) { return mod, nil } +// bodyReturnValue returns the value expression of a function's trailing +// return statement, or nil. +func bodyReturnValue(b *hir.Block) hir.Expr { + if b == nil || len(b.Body) == 0 { + return nil + } + ret, ok := b.Body[len(b.Body)-1].(*hir.ReturnStmt) + if !ok || ret.Val == nil { + return nil + } + return ret.Val +} + +// fixForwardCallTypes rewrites result types that were defaulted to u8 when a +// call referenced a function parsed later in the module (forward reference). +// The declared return type is now known, so the call, its let-binding and +// references to the bound variable all adopt it. +func (p *parser) fixForwardCallTypes(fn *hir.Func) { + fixed := map[string]mir2.Ty{} + var walkStmt func(s hir.Stmt) + var walkExpr func(e hir.Expr) + walkBlock := func(b *hir.Block) { + if b == nil { + return + } + for _, s := range b.Body { + walkStmt(s) + } + } + walkExpr = func(e hir.Expr) { + switch t := e.(type) { + case *hir.CallExpr: + for _, a := range t.Args { + walkExpr(a) + } + if declared, ok := p.returnTypes[t.Fn]; ok && t.Ty != declared { + t.Ty = declared + } + case *hir.BinExpr: + walkExpr(t.L) + walkExpr(t.R) + case *hir.UnaryExpr: + walkExpr(t.X) + case *hir.CastExpr: + walkExpr(t.X) + case *hir.LoadExpr: + walkExpr(t.Ptr) + case *hir.DerefExpr: + walkExpr(t.Ptr) + case *hir.CondExpr: + walkExpr(t.Cond) + walkExpr(t.Then) + walkExpr(t.Else) + case *hir.LetInExpr: + walkExpr(t.Init) + if t.Init != nil && t.Init.ExprTy() != t.Ty { + t.Ty = t.Init.ExprTy() + fixed[t.Name] = t.Ty + } + walkExpr(t.Body) + case *hir.VarRefExpr: + if ty, ok := fixed[t.Name]; ok { + t.Ty = ty + } + } + } + walkStmt = func(s hir.Stmt) { + switch t := s.(type) { + case *hir.ReturnStmt: + if t.Val != nil { + walkExpr(t.Val) + } + for _, v := range t.Vals { + walkExpr(v) + } + case *hir.VarDeclStmt: + walkExpr(t.Init) + if t.Init != nil && t.Init.ExprTy() != t.Ty { + t.Ty = t.Init.ExprTy() + fixed[t.Name] = t.Ty + } + case *hir.AssignStmt: + walkExpr(t.Target) + walkExpr(t.Val) + case *hir.ExprStmt: + walkExpr(t.Expr) + case *hir.StoreStmt: + walkExpr(t.Ptr) + walkExpr(t.Val) + case *hir.TupleLetStmt: + walkExpr(t.Call) + case *hir.IfStmt: + walkExpr(t.Cond) + walkBlock(t.Then) + walkBlock(t.Else) + case *hir.WhileStmt: + walkExpr(t.Cond) + walkBlock(t.Body) + case *hir.ForRangeStmt: + walkExpr(t.Start) + walkExpr(t.End) + walkBlock(t.Body) + } + } + walkBlock(fn.Body) +} + // parseTypeDecl: type Name = Ctor1 | Ctor2 of ty | Ctor3 // Registers constructors in p.ctors for use in match arms and expressions. func (p *parser) parseTypeDecl() error { @@ -1178,6 +1316,7 @@ func (p *parser) parseLet() (*hir.Func, error) { if inferRetTy && body != nil { fn.RetTy = body.ExprTy() p.returnTypes[fn.Name] = fn.RetTy + p.inferredRetTys[fn.Name] = true } // where-bindings come BEFORE the let-in bindings and body From 33afa823eb2239c0119ce1843ada9e93f30018a5 Mon Sep 17 00:00:00 2001 From: "Alice V." Date: Tue, 1 Dec 2026 00:36:52 +0000 Subject: [PATCH 02/12] frill: parse let bindings at the top of while/for loop bodies MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit parseLoopBody recognised only do/for/while/poke statements and broke on anything else, so a loop body starting with 'let x = ... in' (e.g. the nested while loops in examples/frill/graphics.frl render_xor) ended the body early. The 'end' tokens then fell out of sync, and the leftover 'end 0' was silently parsed as a call to an unknown function 'end', emitting 'JP end' with an undefined label — the z80 assert failed with 'assemble errors: line 448: unknown instruction or invalid operands: JP'. Parse 'let name = expr in' in loop bodies as a flat VarDeclStmt, matching parseBodyExpr, so the nesting depth stays aligned. Regression test: pkg/frill/loop_body_let_test.go (nested while with a let at the top of the outer body used to leave a call to "end" in the HIR). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS --- minzc/pkg/frill/frill.go | 19 ++++++++++ minzc/pkg/frill/loop_body_let_test.go | 54 +++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 minzc/pkg/frill/loop_body_let_test.go diff --git a/minzc/pkg/frill/frill.go b/minzc/pkg/frill/frill.go index 1b860487f..4f15c1a70 100644 --- a/minzc/pkg/frill/frill.go +++ b/minzc/pkg/frill/frill.go @@ -993,6 +993,25 @@ func (p *parser) parseLoopBody() ([]hir.Stmt, error) { p.lambdaCount++ body = append(body, &hir.VarDeclStmt{Name: dn, Ty: doE.ExprTy(), Init: doE}) } + } else if p.peek().kind == tokIdent && p.peek().text == "let" { + // let binding at the top of a loop body (flat scope, like + // parseBodyExpr). Without this the loop body ends early, the + // matching "end" is left in the token stream and is silently + // misparsed as a call to an unknown "end" function. + p.next() // consume "let" + nameTok := p.next() + if err := p.expect(tokEq, "="); err != nil { + return nil, err + } + val, err := p.parseExpr() + if err != nil { + return nil, err + } + if err := p.expect(tokIdent, "in"); err != nil { + return nil, err + } + body = append(body, &hir.VarDeclStmt{Name: nameTok.text, Ty: val.ExprTy(), Init: val}) + p.varTypes[nameTok.text] = val.ExprTy() } else if p.peek().kind == tokIdent && p.peek().text == "for" { // Nested for loop p.next() diff --git a/minzc/pkg/frill/loop_body_let_test.go b/minzc/pkg/frill/loop_body_let_test.go new file mode 100644 index 000000000..009d537b8 --- /dev/null +++ b/minzc/pkg/frill/loop_body_let_test.go @@ -0,0 +1,54 @@ +package frill + +import ( + "testing" + + "github.com/minz/minzc/pkg/hir" + "github.com/minz/minzc/pkg/pipeline" +) + +// parseLoopBody used to break on any statement it did not recognise, so a +// loop body starting with "let x = ... in" ended the body early; the matching +// "end" then fell out of sync and the leftover "end 0" tokens were silently +// parsed as a call to an unknown "end" function, emitting JP end (undefined +// label). Regression for the frill/graphics.frl z80 assert failure. +const nestedLoopLetSrc = ` +let count_loops (dummy : u8) : u8 = + let y = 0 in + while y < 3 do + let x = 0 in + while x < 2 do + do x <- x + 1 + end + do y <- y + 1 + end + y + +assert count_loops 0 == 3 +` + +func TestNestedWhileBodyWithLet(t *testing.T) { + hm, err := Compile(nestedLoopLetSrc, "nested_loop_let.frl") + if err != nil { + t.Fatalf("compile: %v", err) + } + for _, f := range hm.Funcs { + walkBodyExprs(f.Body, func(e hir.Expr) { + if call, ok := e.(*hir.CallExpr); ok && call.Fn == "end" { + t.Errorf("function %s: leftover misparse produced a call to %q", f.Name, call.Fn) + } + }) + } + opts := pipeline.DefaultOptions() + opts.AssertMode = "none" + steps, err := pipeline.CompileHIRSteps(hm, opts) + if err != nil { + t.Fatalf("compile steps: %v", err) + } + if err := pipeline.RunAssertsMIR2(hm, steps.MIR2Module); err != nil { + t.Errorf("mir2: %v", err) + } + if err := pipeline.RunAssertsZ80(hm, steps.MIR2Module, steps.Allocation, steps.Assembly); err != nil { + t.Errorf("z80: %v", err) + } +} From 8db446fc564f0be24deadf3db46979ade2d2ba86 Mon Sep 17 00:00:00 2001 From: "Alice V." Date: Tue, 1 Dec 2026 00:38:48 +0000 Subject: [PATCH 03/12] mir2: emit ObjC vtable symbol addresses in the Z80 globals section MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ObjC protocol vtable globals (pkg/c89 objc_lower, producer c89.generateVtable) carry VtableSyms: the function name for each slot. The VM patches the addresses into its heap at load, which is why dynamic dispatch passed under mir2, but the Z80 emitter only wrote the zero initialiser — every vtable was assembled as 'DW 0, 0', so a dynamic dispatch jumped to address 0 and wandered through memory until the cycle limit. examples/objc/dynamic.m under --asserts-force z80 returned garbage (0xFEFA) for 'Drawable Circle{radius:7}.area() == 49' with the same root cause in canvas_shapes.m and plasma.m. Emit each slot as 'DW ' (DW 0 for an empty slot), the static equivalent of what the VM patches at load. Regression test: pkg/mir2/objc_vtable_codegen_test.go. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS --- minzc/pkg/mir2/objc_vtable_codegen_test.go | 42 ++++++++++++++++++++++ minzc/pkg/mir2/z80codegen.go | 15 ++++++-- 2 files changed, 55 insertions(+), 2 deletions(-) create mode 100644 minzc/pkg/mir2/objc_vtable_codegen_test.go diff --git a/minzc/pkg/mir2/objc_vtable_codegen_test.go b/minzc/pkg/mir2/objc_vtable_codegen_test.go new file mode 100644 index 000000000..95e48085d --- /dev/null +++ b/minzc/pkg/mir2/objc_vtable_codegen_test.go @@ -0,0 +1,42 @@ +package mir2_test + +import ( + "strings" + "testing" + + "github.com/minz/minzc/pkg/mir2" +) + +// ObjC protocol vtable globals carry VtableSyms: function names whose +// addresses belong in the slots. The VM patches them into its heap at load; +// the Z80 emitter used to emit plain zero words (DW 0, 0), so a dynamic +// dispatch on Z80 jumped to address 0. Regression for the examples/objc +// dynamic.m / canvas_shapes.m / plasma.m z80 assert failures +// (`Drawable Circle{radius:7}.area() == 49` got -262). +func TestZ80VtableGlobalEmitsSymbols(t *testing.T) { + m := &mir2.Module{Name: "objc_dyn"} + f := m.AddFunc("Circle_area") + f.Contract.Returns = []mir2.Return{{Ty: mir2.TyU16, Class: mir2.ClassPointer}} + bld := mir2.NewBuilder(f) + bld.SwitchToNewBlock("entry") + zero := bld.Const(0, mir2.TyU16, mir2.ClassPointer) + bld.Ret(zero) + + m.Globals = append(m.Globals, mir2.Global{ + Name: "__vtable_Circle_Drawable", + Ty: mir2.NewArray(mir2.TyPtr, 2), + VtableSyms: []string{"Circle_draw", "Circle_area"}, + Producer: "c89.generateVtable", + }) + + lr := mir2.ComputeLiveness(f) + ar := mir2.Allocate(f, lr, mir2.Z80CostTable{}) + asm := mustZ80Asm(mir2.Z80Codegen(m, ar)) + + if !strings.Contains(asm, "DW Circle_area") || !strings.Contains(asm, "DW Circle_draw") { + t.Errorf("vtable slots must be emitted as symbol addresses, got:\n%s", asm) + } + if strings.Contains(asm, "DW 0, 0") { + t.Errorf("vtable slots must not be zero words, got:\n%s", asm) + } +} diff --git a/minzc/pkg/mir2/z80codegen.go b/minzc/pkg/mir2/z80codegen.go index 3b2a7ea68..f7e71d204 100644 --- a/minzc/pkg/mir2/z80codegen.go +++ b/minzc/pkg/mir2/z80codegen.go @@ -551,9 +551,20 @@ func z80CodegenWithLeafWrites(m *Module, ar *AllocResult, leafWrites map[string] fmt.Fprintf(&sb, " ALIGN %d\n", at.Align) } sb.WriteString(sanitized + ":\n") - if len(g.Relocs) > 0 { + switch { + case len(g.Relocs) > 0: emitRelocatedGlobalData(&sb, g, relocationBytes(m)) - } else { + case len(g.VtableSyms) > 0: + // ObjC protocol vtables: each slot holds a function address + // (the VM patches the same syms into its heap at load). + for _, sym := range g.VtableSyms { + if sym == "" { + sb.WriteString(" DW 0\n") + } else { + fmt.Fprintf(&sb, " DW %s\n", sanitizeIdent(sym)) + } + } + default: emitTypedGlobalData(&sb, g.Ty, g.Init) } if opt.ADL && adlWideGlobal(g) { From a1f4a78c719263ab067299aaac363a9f7e917a5c Mon Sep 17 00:00:00 2001 From: "Alice V." Date: Tue, 1 Dec 2026 00:42:25 +0000 Subject: [PATCH 04/12] mir2: emit a zero-return stub for host-only externs (Attrs.NoImpl) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An addressless extern had no implementation anywhere — the mir2 VM dispatches those calls to registered host functions, but on Z80 the emitted symbol was a bare label, so a CALL fell through into whatever function followed. examples/nanz/canvas_house.nanz under --asserts-force z80 ran off into unrelated code until the cycle limit reported 'execution limit exceeded'; its canvas_* hosts are exactly such addressless @extern declarations. Frontends now mark host-only externs (nanz @extern without an address, C89/ObjC prototypes registered as externs — next commit) with NoImpl; the Z80 backend then emits a defined stub: LD HL,0 / RET (16-bit returns), XOR A / RET (8-bit), RET (void). Plain externs keep the bare label — their bodies may be linked in later or live at ExternAddr, which several tests rely on by concatenating their own bodies. Regression test: pkg/mir2/extern_stub_codegen_test.go. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS --- minzc/pkg/hir/hir.go | 1 + minzc/pkg/hir/lower.go | 1 + minzc/pkg/mir2/extern_stub_codegen_test.go | 44 ++++++++++++++++++++++ minzc/pkg/mir2/func.go | 6 +++ minzc/pkg/mir2/z80codegen.go | 17 +++++++++ minzc/pkg/nanz/parse.go | 5 +++ 6 files changed, 74 insertions(+) create mode 100644 minzc/pkg/mir2/extern_stub_codegen_test.go diff --git a/minzc/pkg/hir/hir.go b/minzc/pkg/hir/hir.go index b421447f8..522f1f5dd 100644 --- a/minzc/pkg/hir/hir.go +++ b/minzc/pkg/hir/hir.go @@ -167,6 +167,7 @@ type Func struct { ExternClobbers []string // nil = unknown; non-nil = explicit Z80 write contract IsExtern bool ExternAddr uint16 // non-zero → @extern(addr) — call via CALL/RST to fixed address + NoImpl bool // extern with no implementation anywhere (host hook); Z80 emits a zero-return stub IsIO bool // true = effectful (IO); false = pure (compile-time safe) } diff --git a/minzc/pkg/hir/lower.go b/minzc/pkg/hir/lower.go index 320567533..b6d006e6f 100644 --- a/minzc/pkg/hir/lower.go +++ b/minzc/pkg/hir/lower.go @@ -627,6 +627,7 @@ func lowerFuncWithFuncNames(m *mir2.Module, f *Func, funcNames map[string]bool, if f.IsExtern { mf.Attrs.IsExtern = true mf.Attrs.ExternAddr = f.ExternAddr + mf.Attrs.NoImpl = f.NoImpl mf.Contract.ExternClobbers = f.ExternClobbers } diff --git a/minzc/pkg/mir2/extern_stub_codegen_test.go b/minzc/pkg/mir2/extern_stub_codegen_test.go new file mode 100644 index 000000000..93a81db98 --- /dev/null +++ b/minzc/pkg/mir2/extern_stub_codegen_test.go @@ -0,0 +1,44 @@ +package mir2_test + +import ( + "strings" + "testing" + + "github.com/minz/minzc/pkg/mir2" +) + +// An extern declaration without an address has no implementation on this +// target. The Z80 emitter used to emit only the label, so a CALL fell through +// into whatever function followed. It must emit a defined stub that returns +// zeroes. Regression for the examples/nanz/canvas_house.nanz z80 assert +// (execution limit exceeded while running off into unrelated code). +func TestZ80AddresslessExternStubReturns(t *testing.T) { + m := &mir2.Module{Name: "externs"} + + u16fn := m.AddFunc("canvas_pixel") + u16fn.Attrs.IsExtern = true + u16fn.Attrs.NoImpl = true + u16fn.Contract.Returns = []mir2.Return{{Ty: mir2.TyU16, Class: mir2.ClassPointer}} + + voidfn := m.AddFunc("canvas_clear") + voidfn.Attrs.IsExtern = true + voidfn.Attrs.NoImpl = true + + lr := mir2.ComputeLiveness(u16fn) + ar := mir2.Allocate(u16fn, lr, mir2.Z80CostTable{}) + asm := mustZ80Asm(mir2.Z80Codegen(m, ar)) + + for _, name := range []string{"canvas_pixel", "canvas_clear"} { + idx := strings.Index(asm, name+":") + if idx < 0 { + t.Fatalf("missing label for %s:\n%s", name, asm) + } + tail := asm[idx:] + if !strings.Contains(tail[:min(len(tail), 120)], "RET") { + t.Errorf("%s: stub must RET instead of falling through:\n%s", name, tail[:min(len(tail), 120)]) + } + } + if !strings.Contains(asm, "LD HL, 0") { + t.Errorf("u16-returning extern stub should return HL=0:\n%s", asm) + } +} diff --git a/minzc/pkg/mir2/func.go b/minzc/pkg/mir2/func.go index 0adb175ef..519a62eb0 100644 --- a/minzc/pkg/mir2/func.go +++ b/minzc/pkg/mir2/func.go @@ -119,6 +119,12 @@ type FuncAttrs struct { // Recursive functions cannot use absolute $F0xx locals on Z80 — they need // a stack frame. IsRecursive bool + + // NoImpl: this extern has no implementation anywhere — the frontend knows + // the symbol only as a host hook (e.g. the mir2 canvas_* hosts). The Z80 + // backend then emits a defined zero-return stub instead of the bare + // label, which fell through into the next function when called. + NoImpl bool `json:",omitempty"` } // ── Construction helpers ────────────────────────────────────────────────────── diff --git a/minzc/pkg/mir2/z80codegen.go b/minzc/pkg/mir2/z80codegen.go index f7e71d204..d70ec8e50 100644 --- a/minzc/pkg/mir2/z80codegen.go +++ b/minzc/pkg/mir2/z80codegen.go @@ -1417,6 +1417,23 @@ func (g *z80cg) genFunc(f *Func) { g.emitf("%s: DS %d", locs[p.Reg].Name, ByteWidth(p.Ty)) } } + // A host-only extern (Attrs.NoImpl) has no implementation anywhere. + // The bare label alone made a CALL fall through into whatever + // function follows; emit a defined stub that returns zeroes. + // Plain externs keep the bare label: their bodies may be linked in + // later or live at ExternAddr. + if f.Attrs.NoImpl { + switch { + case len(f.Contract.Returns) > 0 && ByteWidth(f.Contract.Returns[0].Ty) >= 2: + g.emit(" LD HL, 0") + g.emit(" RET") + case len(f.Contract.Returns) > 0 && ByteWidth(f.Contract.Returns[0].Ty) == 1: + g.emit(" XOR A") + g.emit(" RET") + default: + g.emit(" RET") + } + } return } var frameErr error diff --git a/minzc/pkg/nanz/parse.go b/minzc/pkg/nanz/parse.go index 3f9df82bb..e54575cd6 100644 --- a/minzc/pkg/nanz/parse.go +++ b/minzc/pkg/nanz/parse.go @@ -1072,6 +1072,11 @@ func (p *parser) parseModule() (*hir.Module, error) { } f.ExternAddr = externAddr f.ExternClobbers = externClobbers + if externAddr == 0 { + // An addressless @extern is a host hook (e.g. the mir2 + // canvas_* hosts): it has no implementation anywhere. + f.NoImpl = true + } m.Funcs = append(m.Funcs, f) } else if attr.kind == tokIdent && attr.val == "screen" && p.metaFuncs["screen"] == "" { // Built-in @screen metafunction (only if no user-defined @screen) From 8f76fa5d65ea9a537f25c227dac8e22e4cdd1356 Mon Sep 17 00:00:00 2001 From: "Alice V." Date: Tue, 1 Dec 2026 00:43:22 +0000 Subject: [PATCH 05/12] c89: register file-scope prototypes as extern functions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit C prototypes without a body were dropped entirely ('Skip function declarations'), so a call to a prototype-only function emitted a CALL to a symbol nothing defined — the objc examples' canvas_* VM hosts failed to assemble under the z80 asserts with 'unknown instruction or invalid operands: CALL' (examples/objc/canvas_shapes.m line 88, plasma.m line 271), and plasma's Plasma.render assert executed that dangling call, running off into unrelated code until the cycle limit. The mir2 VM resolved those calls through its host table, which is why only the z80 verdicts failed. Prototypes are now registered as extern hir.Funcs marked NoImpl, so the Z80 backend emits a defined zero-return stub (see the previous commit); a later definition replaces the placeholder, and a direct call adopts the declared return type when the parse falls back to the C89 implicit-int rule (void canvas_* hosts called from int-returning ObjC methods used to make the HIR verifier reject 'call canvas_circle return type u16, declared void'). The VM path is unchanged: vm.execCall consults the host table before module functions, so registered hosts keep working. Test accommodation: pkg/pipeline/grace_infinite_loop_test.go linked the tick body by appending a second 'tick:' label to the assembly; it now inserts the body after the existing (stub) label like the nanz branch already did. Regression test: pkg/c89/extern_prototype_test.go (external test package — pkg/c89 cannot import pkg/pipeline in-package). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS --- minzc/pkg/c89/extern_prototype_test.go | 77 ++++++++++++++++++ minzc/pkg/c89/lower.go | 79 ++++++++++++++++++- .../pkg/pipeline/grace_infinite_loop_test.go | 8 +- 3 files changed, 159 insertions(+), 5 deletions(-) create mode 100644 minzc/pkg/c89/extern_prototype_test.go diff --git a/minzc/pkg/c89/extern_prototype_test.go b/minzc/pkg/c89/extern_prototype_test.go new file mode 100644 index 000000000..fc5825881 --- /dev/null +++ b/minzc/pkg/c89/extern_prototype_test.go @@ -0,0 +1,77 @@ +package c89_test + +import ( + "strings" + "testing" + + "github.com/minz/minzc/pkg/c89" + "github.com/minz/minzc/pkg/hir" + "github.com/minz/minzc/pkg/mir2" + "github.com/minz/minzc/pkg/pipeline" +) + +// A file-scope function declaration without a body (a prototype) used to be +// dropped entirely, so calls to it assembled to a CALL with no definition — +// e.g. the canvas_* VM hosts in the objc examples failed to assemble under +// the z80 asserts ("unknown instruction or invalid operands: CALL"). +// Prototypes must be registered as extern functions, and a call's result type +// must follow the declared prototype (the parse falls back to the C89 +// implicit-int rule for calls it does not link to their declaration). +const externPrototypeSrc = ` +void canvas_host(int x, int color); + +int caller(int v) { + canvas_host(v, 3); + return v * 2; +} + +// assert caller(21) == 42 via z80 +` + +func TestExternPrototypeRegistered(t *testing.T) { + hm, err := c89.Compile(externPrototypeSrc, "extern_proto.c") + if err != nil { + t.Fatalf("compile: %v", err) + } + var proto *hir.Func + for _, f := range hm.Funcs { + if f.Name == "canvas_host" { + proto = f + break + } + } + if proto == nil { + t.Fatal("prototype canvas_host was not registered as an extern function") + } + if !proto.IsExtern { + t.Errorf("canvas_host: IsExtern = false") + } + if proto.RetTy != mir2.TyVoid { + t.Errorf("canvas_host: RetTy = %v, want void", proto.RetTy) + } +} + +func TestExternPrototypeZ80Assert(t *testing.T) { + hm, err := c89.Compile(externPrototypeSrc, "extern_proto.c") + if err != nil { + t.Fatalf("compile: %v", err) + } + opts := pipeline.DefaultOptions() + opts.AssertMode = "none" + steps, err := pipeline.CompileHIRSteps(hm, opts) + if err != nil { + t.Fatalf("compile steps: %v", err) + } + asm := steps.Assembly + idx := strings.Index(asm, "canvas_host:") + if idx < 0 { + t.Fatalf("assembly missing canvas_host stub:\n%s", asm) + } + tail := asm[idx:] + if !strings.Contains(tail[:min(len(tail), 120)], "RET") { + t.Errorf("canvas_host stub must RET instead of falling through:\n%s", tail[:min(len(tail), 120)]) + } + if err := pipeline.RunAssertsZ80(hm, steps.MIR2Module, steps.Allocation, steps.Assembly); err != nil { + t.Errorf("z80: %v", err) + } +} diff --git a/minzc/pkg/c89/lower.go b/minzc/pkg/c89/lower.go index e399ab878..37e7e71cf 100644 --- a/minzc/pkg/c89/lower.go +++ b/minzc/pkg/c89/lower.go @@ -21,6 +21,7 @@ type lowerer struct { typedefs map[string]mir2.Ty structs map[string]*mir2.StructTy cStructs map[cc.Type]string // C struct type → MIR2 struct name + externProtos map[string]bool // prototypes already registered as extern decls // ObjC: class info from @interface declarations. objcClasses map[string]*objcClassInfo @@ -163,6 +164,16 @@ func (l *lowerer) isFunction(name string) bool { return false } +// moduleFunc returns the module function with the given symbol name, or nil. +func (l *lowerer) moduleFunc(name string) *hir.Func { + for _, f := range l.hm.Funcs { + if f.Name == name { + return f + } + } + return nil +} + // ── Top-level declarations ────────────────────────────────────────────────── func (l *lowerer) lowerTopDecl(d *cc.Declaration) error { @@ -226,8 +237,14 @@ func (l *lowerer) lowerTopDecl(d *cc.Declaration) error { continue } - // Skip function declarations (prototypes). + // Function declarations (prototypes): register as extern functions so + // the backend emits a defined stub for the symbol. Without this, a + // call to a prototype-only function (e.g. the canvas_* VM hosts in + // the objc examples) assembles to a reference with no definition. if ty.Kind() == cc.Function { + if ft, ok := ty.(*cc.FunctionType); ok && !ft.IsVariadic() { + l.registerExternPrototype(name, ft) + } continue } @@ -538,6 +555,47 @@ func (l *lowerer) evalConstInit(init *cc.Initializer) (int64, bool) { // ── Function lowering ─────────────────────────────────────────────────────── +// registerExternPrototype records a file-scope function declaration without a +// body as an extern hir.Func. The Z80 backend then emits a defined stub for +// the symbol instead of leaving its calls pointing at nothing; on the mir2 VM +// the host table is consulted before module functions, so registered hosts +// (canvas_*, …) keep working. +func (l *lowerer) registerExternPrototype(name string, ft *cc.FunctionType) { + sym := l.symbolName(name) + if l.externProtos == nil { + l.externProtos = make(map[string]bool) + } + if l.externProtos[sym] { + return + } + for _, f := range l.hm.Funcs { + if f.Name == sym { + return // already defined (or declared) in the module + } + } + l.externProtos[sym] = true + retTy := l.mapType(ft.Result()) + var params []hir.Param + for _, p := range ft.Parameters() { + if p.Type() != nil && p.Type().Kind() == cc.Void { + continue + } + pname := p.Name() + if pname == "" { + pname = fmt.Sprintf("_p%d", len(params)) + } + params = append(params, hir.Param{Name: pname, Ty: l.mapType(p.Type())}) + } + // NoImpl: a prototype has no implementation in this compilation, so the + // Z80 backend emits a defined zero-return stub — a dropped prototype + // left its CALL referencing a symbol nothing defined (the objc examples' + // canvas_* VM hosts failed to assemble; asserted functions that call + // them ran off into whatever code followed the bare label). The mir2 VM + // resolves the same calls through its host table, which still wins over + // module functions. + l.hm.Funcs = append(l.hm.Funcs, &hir.Func{Name: sym, IsExtern: true, NoImpl: true, Params: params, RetTy: retTy}) +} + func (l *lowerer) lowerFunc(fd *cc.FunctionDefinition) (*hir.Func, error) { decl := fd.Declarator name := decl.Name() @@ -549,6 +607,15 @@ func (l *lowerer) lowerFunc(fd *cc.FunctionDefinition) (*hir.Func, error) { if !ok { return nil, fmt.Errorf("function %s: expected function type", name) } + // A prototype registered this name earlier: drop the extern placeholder + // so the module keeps exactly one function per symbol. + sym := l.symbolName(name) + for i, f := range l.hm.Funcs { + if f.Name == sym && f.IsExtern { + l.hm.Funcs = append(l.hm.Funcs[:i], l.hm.Funcs[i+1:]...) + break + } + } if ft.IsVariadic() { return nil, fmt.Errorf("function %s: variadic definitions require an unsupported Z80 varargs ABI", name) } @@ -1863,7 +1930,15 @@ func (fl *funcLow) lowerCall(pf *cc.PostfixExpression) (*exprResult, error) { return indirect(fnPtr), nil } // Function name → direct call. - return wrapExpr(hir.Call(fl.low.symbolName(name), retTy, args...)), nil + callTy := retTy + if f := fl.low.moduleFunc(fl.low.symbolName(name)); f != nil && f.RetTy != retTy { + // The parse may fall back to the C89 implicit-int rule for calls + // it does not link to their declaration; the declared prototype + // wins (e.g. void canvas_* hosts called from int-returning + // ObjC methods). + callTy = f.RetTy + } + return wrapExpr(hir.Call(fl.low.symbolName(name), callTy, args...)), nil } // Callee is a complex expression → lower it and do indirect call. diff --git a/minzc/pkg/pipeline/grace_infinite_loop_test.go b/minzc/pkg/pipeline/grace_infinite_loop_test.go index e21c9dbe0..82cb0d9a8 100644 --- a/minzc/pkg/pipeline/grace_infinite_loop_test.go +++ b/minzc/pkg/pipeline/grace_infinite_loop_test.go @@ -83,11 +83,13 @@ func TestGracePreservesInfiniteLoops(t *testing.T) { } // Execute a bounded prefix on the real backend; returning would hit // the sentinel instead of remaining inside the assembled program. + // Body insertion (not appending a second tick label): since C + // prototypes register as NoImpl externs, the assembly already + // defines tick with a stub body. assembly := "ORG 0x8000\n" + s.Assembly - if language == "c" { + assembly = strings.Replace(assembly, "\ntick:\n", "\ntick:\n RET\n", 1) + if !strings.Contains(assembly, "tick:\n RET") && !strings.Contains(assembly, "tick:\n RET") { assembly += "\ntick:\n RET\n" - } else { - assembly = strings.Replace(assembly, "\ntick:\n", "\ntick:\n RET\n", 1) } r, err := z80asm.NewAssembler().AssembleString(assembly) if err != nil || len(r.Errors) != 0 { From 43833ba91778754b9eacfb2278a03424e876de50 Mon Sep 17 00:00:00 2001 From: "Alice V." Date: Tue, 1 Dec 2026 02:50:38 +0000 Subject: [PATCH 06/12] pipeline: resolve assert string arguments to their data labels on Z80 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit buildAssertBootstrap loaded assertion arguments as raw integers, but a string-literal argument's raw value is a placeholder 0 — the real address lives in the interned data label (_mir2_str_N). The mir2 runner resolves the same symbols via vm.ResolveSymbol, which is why 'assert eval "5" == 5' passed under mir2 and returned 0 under z80: the asserted function received a pointer to address 0 (examples/frill/expr_eval.frl line 65, examples/frill/stress_test.frl line 87 under --asserts-force z80). Emit the sanitized label for register-held string arguments (LD HL, _mir2_str_N), and build the address in HL and store both bytes through A for a string argument spilled to memory; trampolineSize accounts for the 11-byte spill form so the sandbox NOP padding stays exact. Regression test: pkg/frill/assert_string_args_test.go. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS --- minzc/pkg/frill/assert_string_args_test.go | 38 ++++++++++++++++++++++ minzc/pkg/pipeline/pipeline.go | 32 +++++++++++++++++- 2 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 minzc/pkg/frill/assert_string_args_test.go diff --git a/minzc/pkg/frill/assert_string_args_test.go b/minzc/pkg/frill/assert_string_args_test.go new file mode 100644 index 000000000..fda4e9f40 --- /dev/null +++ b/minzc/pkg/frill/assert_string_args_test.go @@ -0,0 +1,38 @@ +package frill + +import ( + "testing" + + "github.com/minz/minzc/pkg/pipeline" +) + +// The Z80 assert bootstrap used to load string-literal arguments as the raw +// placeholder value 0 instead of the interned string label, so the asserted +// function received a pointer to address 0. The mir2 runner resolves the same +// symbols via vm.ResolveSymbol, which is why only the z80 verdicts were wrong. +// Regression for the frill/expr_eval.frl and frill/stress_test.frl failures +// (`eval "5" == 5` got 0, `char_at 0 0 == 65` got 0). +const stringArgAssertSrc = ` +let first_byte (s : u16) : u8 = peek s + +assert first_byte "A" == 65 +` + +func TestZ80AssertResolvesStringArgs(t *testing.T) { + hm, err := Compile(stringArgAssertSrc, "string_arg.frl") + if err != nil { + t.Fatalf("compile: %v", err) + } + opts := pipeline.DefaultOptions() + opts.AssertMode = "none" + steps, err := pipeline.CompileHIRSteps(hm, opts) + if err != nil { + t.Fatalf("compile steps: %v", err) + } + if err := pipeline.RunAssertsMIR2(hm, steps.MIR2Module); err != nil { + t.Errorf("mir2: %v", err) + } + if err := pipeline.RunAssertsZ80(hm, steps.MIR2Module, steps.Allocation, steps.Assembly); err != nil { + t.Errorf("z80: %v", err) + } +} diff --git a/minzc/pkg/pipeline/pipeline.go b/minzc/pkg/pipeline/pipeline.go index 29e13955d..bae2b218f 100644 --- a/minzc/pkg/pipeline/pipeline.go +++ b/minzc/pkg/pipeline/pipeline.go @@ -1656,6 +1656,14 @@ func buildAssertBootstrap(org int, a hir.Assert, mf *mir2.Func, ar *mir2.AllocRe var boot strings.Builder fmt.Fprintf(&boot, " ORG 0x%04X\n", org) boot.WriteString(" LD SP, 0xFF00\n") + // String arguments are interned as data labels in the emitted assembly + // (_mir2_str_N); the raw value in a.Args is a placeholder 0. The mir2 + // runner resolves the same symbols via vm.ResolveSymbol; here we emit the + // label so the assembler resolves the real address. + strLabels := make(map[int]string, len(a.StringArgs)) + for idx, sym := range a.StringArgs { + strLabels[idx] = asmutil.SanitizeZ80Label(sym) + } // Hidden result storage is reserved below this invocation's initial SP; // source assertion arguments and their fingerprints remain unchanged. args := append([]int64(nil), a.Args...) @@ -1679,6 +1687,15 @@ func buildAssertBootstrap(org int, a hir.Assert, mf *mir2.Func, ar *mir2.AllocRe continue } label := mir2.Z80SpillLabel(mf.Name, param.Reg) + if strLabel, isStr := strLabels[i]; isStr { + // A string pointer spilled to memory: build the address in HL + // (registers are re-established by the loop below) and store both + // bytes through A. + fmt.Fprintf(&boot, " LD HL, %s\n", strLabel) + fmt.Fprintf(&boot, " LD A, L\n LD (%s), A\n", label) + fmt.Fprintf(&boot, " LD A, H\n LD (%s+1), A\n", label) + continue + } for b := range mir2.NativeSpillWidth(param.Ty) { suffix := "" if b > 0 { @@ -1696,6 +1713,10 @@ func buildAssertBootstrap(org int, a hir.Assert, mf *mir2.Func, ar *mir2.AllocRe if loc.Kind == mir2.LocMem || loc.Name == "" { continue } + if strLabel, isStr := strLabels[i]; isStr { + fmt.Fprintf(&boot, " LD %s, %s\n", loc.Name, strLabel) + continue + } fmt.Fprintf(&boot, " LD %s, %d\n", loc.Name, arg) } fmt.Fprintf(&boot, " CALL %s\n", asmutil.SanitizeZ80Label(a.FuncName)) @@ -1741,6 +1762,10 @@ func assertParamLocation(param mir2.Param, ar *mir2.AllocResult) mir2.PhysLoc { // trampolines keep their shared code and data at a stable address. func trampolineSize(a hir.Assert, mf *mir2.Func, ar *mir2.AllocResult) int { size := 8 // LD SP,nn + CALL nn + DI + HALT + strLabels := make(map[int]string, len(a.StringArgs)) + for idx, sym := range a.StringArgs { + strLabels[idx] = asmutil.SanitizeZ80Label(sym) + } for i := range a.Args { if i >= len(mf.Contract.Params) { break @@ -1748,7 +1773,12 @@ func trampolineSize(a hir.Assert, mf *mir2.Func, ar *mir2.AllocResult) int { param := mf.Contract.Params[i] loc := assertParamLocation(param, ar) if loc.Kind == mir2.LocMem { - size += 5 * max(1, (param.Ty.Width()+7)/8) // LD A,n + LD (nn),A per byte + if _, isStr := strLabels[i]; isStr { + // LD HL,label + LD A,L + LD (nn),A + LD A,H + LD (nn+1),A + size += 11 + } else { + size += 5 * max(1, (param.Ty.Width()+7)/8) // LD A,n + LD (nn),A per byte + } continue } switch loc.Name { From 80f68f7e986145438befb87db5a8e8bf377adcc0 Mon Sep 17 00:00:00 2001 From: "Alice V." Date: Tue, 1 Dec 2026 04:01:08 +0000 Subject: [PATCH 07/12] Revert "c89: register file-scope prototypes as extern functions" This reverts commit 8f76fa5d65ea9a537f25c227dac8e22e4cdd1356. --- minzc/pkg/c89/extern_prototype_test.go | 77 ------------------ minzc/pkg/c89/lower.go | 79 +------------------ .../pkg/pipeline/grace_infinite_loop_test.go | 8 +- 3 files changed, 5 insertions(+), 159 deletions(-) delete mode 100644 minzc/pkg/c89/extern_prototype_test.go diff --git a/minzc/pkg/c89/extern_prototype_test.go b/minzc/pkg/c89/extern_prototype_test.go deleted file mode 100644 index fc5825881..000000000 --- a/minzc/pkg/c89/extern_prototype_test.go +++ /dev/null @@ -1,77 +0,0 @@ -package c89_test - -import ( - "strings" - "testing" - - "github.com/minz/minzc/pkg/c89" - "github.com/minz/minzc/pkg/hir" - "github.com/minz/minzc/pkg/mir2" - "github.com/minz/minzc/pkg/pipeline" -) - -// A file-scope function declaration without a body (a prototype) used to be -// dropped entirely, so calls to it assembled to a CALL with no definition — -// e.g. the canvas_* VM hosts in the objc examples failed to assemble under -// the z80 asserts ("unknown instruction or invalid operands: CALL"). -// Prototypes must be registered as extern functions, and a call's result type -// must follow the declared prototype (the parse falls back to the C89 -// implicit-int rule for calls it does not link to their declaration). -const externPrototypeSrc = ` -void canvas_host(int x, int color); - -int caller(int v) { - canvas_host(v, 3); - return v * 2; -} - -// assert caller(21) == 42 via z80 -` - -func TestExternPrototypeRegistered(t *testing.T) { - hm, err := c89.Compile(externPrototypeSrc, "extern_proto.c") - if err != nil { - t.Fatalf("compile: %v", err) - } - var proto *hir.Func - for _, f := range hm.Funcs { - if f.Name == "canvas_host" { - proto = f - break - } - } - if proto == nil { - t.Fatal("prototype canvas_host was not registered as an extern function") - } - if !proto.IsExtern { - t.Errorf("canvas_host: IsExtern = false") - } - if proto.RetTy != mir2.TyVoid { - t.Errorf("canvas_host: RetTy = %v, want void", proto.RetTy) - } -} - -func TestExternPrototypeZ80Assert(t *testing.T) { - hm, err := c89.Compile(externPrototypeSrc, "extern_proto.c") - if err != nil { - t.Fatalf("compile: %v", err) - } - opts := pipeline.DefaultOptions() - opts.AssertMode = "none" - steps, err := pipeline.CompileHIRSteps(hm, opts) - if err != nil { - t.Fatalf("compile steps: %v", err) - } - asm := steps.Assembly - idx := strings.Index(asm, "canvas_host:") - if idx < 0 { - t.Fatalf("assembly missing canvas_host stub:\n%s", asm) - } - tail := asm[idx:] - if !strings.Contains(tail[:min(len(tail), 120)], "RET") { - t.Errorf("canvas_host stub must RET instead of falling through:\n%s", tail[:min(len(tail), 120)]) - } - if err := pipeline.RunAssertsZ80(hm, steps.MIR2Module, steps.Allocation, steps.Assembly); err != nil { - t.Errorf("z80: %v", err) - } -} diff --git a/minzc/pkg/c89/lower.go b/minzc/pkg/c89/lower.go index 37e7e71cf..e399ab878 100644 --- a/minzc/pkg/c89/lower.go +++ b/minzc/pkg/c89/lower.go @@ -21,7 +21,6 @@ type lowerer struct { typedefs map[string]mir2.Ty structs map[string]*mir2.StructTy cStructs map[cc.Type]string // C struct type → MIR2 struct name - externProtos map[string]bool // prototypes already registered as extern decls // ObjC: class info from @interface declarations. objcClasses map[string]*objcClassInfo @@ -164,16 +163,6 @@ func (l *lowerer) isFunction(name string) bool { return false } -// moduleFunc returns the module function with the given symbol name, or nil. -func (l *lowerer) moduleFunc(name string) *hir.Func { - for _, f := range l.hm.Funcs { - if f.Name == name { - return f - } - } - return nil -} - // ── Top-level declarations ────────────────────────────────────────────────── func (l *lowerer) lowerTopDecl(d *cc.Declaration) error { @@ -237,14 +226,8 @@ func (l *lowerer) lowerTopDecl(d *cc.Declaration) error { continue } - // Function declarations (prototypes): register as extern functions so - // the backend emits a defined stub for the symbol. Without this, a - // call to a prototype-only function (e.g. the canvas_* VM hosts in - // the objc examples) assembles to a reference with no definition. + // Skip function declarations (prototypes). if ty.Kind() == cc.Function { - if ft, ok := ty.(*cc.FunctionType); ok && !ft.IsVariadic() { - l.registerExternPrototype(name, ft) - } continue } @@ -555,47 +538,6 @@ func (l *lowerer) evalConstInit(init *cc.Initializer) (int64, bool) { // ── Function lowering ─────────────────────────────────────────────────────── -// registerExternPrototype records a file-scope function declaration without a -// body as an extern hir.Func. The Z80 backend then emits a defined stub for -// the symbol instead of leaving its calls pointing at nothing; on the mir2 VM -// the host table is consulted before module functions, so registered hosts -// (canvas_*, …) keep working. -func (l *lowerer) registerExternPrototype(name string, ft *cc.FunctionType) { - sym := l.symbolName(name) - if l.externProtos == nil { - l.externProtos = make(map[string]bool) - } - if l.externProtos[sym] { - return - } - for _, f := range l.hm.Funcs { - if f.Name == sym { - return // already defined (or declared) in the module - } - } - l.externProtos[sym] = true - retTy := l.mapType(ft.Result()) - var params []hir.Param - for _, p := range ft.Parameters() { - if p.Type() != nil && p.Type().Kind() == cc.Void { - continue - } - pname := p.Name() - if pname == "" { - pname = fmt.Sprintf("_p%d", len(params)) - } - params = append(params, hir.Param{Name: pname, Ty: l.mapType(p.Type())}) - } - // NoImpl: a prototype has no implementation in this compilation, so the - // Z80 backend emits a defined zero-return stub — a dropped prototype - // left its CALL referencing a symbol nothing defined (the objc examples' - // canvas_* VM hosts failed to assemble; asserted functions that call - // them ran off into whatever code followed the bare label). The mir2 VM - // resolves the same calls through its host table, which still wins over - // module functions. - l.hm.Funcs = append(l.hm.Funcs, &hir.Func{Name: sym, IsExtern: true, NoImpl: true, Params: params, RetTy: retTy}) -} - func (l *lowerer) lowerFunc(fd *cc.FunctionDefinition) (*hir.Func, error) { decl := fd.Declarator name := decl.Name() @@ -607,15 +549,6 @@ func (l *lowerer) lowerFunc(fd *cc.FunctionDefinition) (*hir.Func, error) { if !ok { return nil, fmt.Errorf("function %s: expected function type", name) } - // A prototype registered this name earlier: drop the extern placeholder - // so the module keeps exactly one function per symbol. - sym := l.symbolName(name) - for i, f := range l.hm.Funcs { - if f.Name == sym && f.IsExtern { - l.hm.Funcs = append(l.hm.Funcs[:i], l.hm.Funcs[i+1:]...) - break - } - } if ft.IsVariadic() { return nil, fmt.Errorf("function %s: variadic definitions require an unsupported Z80 varargs ABI", name) } @@ -1930,15 +1863,7 @@ func (fl *funcLow) lowerCall(pf *cc.PostfixExpression) (*exprResult, error) { return indirect(fnPtr), nil } // Function name → direct call. - callTy := retTy - if f := fl.low.moduleFunc(fl.low.symbolName(name)); f != nil && f.RetTy != retTy { - // The parse may fall back to the C89 implicit-int rule for calls - // it does not link to their declaration; the declared prototype - // wins (e.g. void canvas_* hosts called from int-returning - // ObjC methods). - callTy = f.RetTy - } - return wrapExpr(hir.Call(fl.low.symbolName(name), callTy, args...)), nil + return wrapExpr(hir.Call(fl.low.symbolName(name), retTy, args...)), nil } // Callee is a complex expression → lower it and do indirect call. diff --git a/minzc/pkg/pipeline/grace_infinite_loop_test.go b/minzc/pkg/pipeline/grace_infinite_loop_test.go index 82cb0d9a8..e21c9dbe0 100644 --- a/minzc/pkg/pipeline/grace_infinite_loop_test.go +++ b/minzc/pkg/pipeline/grace_infinite_loop_test.go @@ -83,13 +83,11 @@ func TestGracePreservesInfiniteLoops(t *testing.T) { } // Execute a bounded prefix on the real backend; returning would hit // the sentinel instead of remaining inside the assembled program. - // Body insertion (not appending a second tick label): since C - // prototypes register as NoImpl externs, the assembly already - // defines tick with a stub body. assembly := "ORG 0x8000\n" + s.Assembly - assembly = strings.Replace(assembly, "\ntick:\n", "\ntick:\n RET\n", 1) - if !strings.Contains(assembly, "tick:\n RET") && !strings.Contains(assembly, "tick:\n RET") { + if language == "c" { assembly += "\ntick:\n RET\n" + } else { + assembly = strings.Replace(assembly, "\ntick:\n", "\ntick:\n RET\n", 1) } r, err := z80asm.NewAssembler().AssembleString(assembly) if err != nil || len(r.Errors) != 0 { From f36554beb1301cf4b91a44ee21d2ae725ec3f44e Mon Sep 17 00:00:00 2001 From: "Alice V." Date: Tue, 1 Dec 2026 04:02:06 +0000 Subject: [PATCH 08/12] mir2: keep addressless externs as bare labels in product output Review of 43833ba91^..43833ba91 (compile_sweep vs main) rejected the product-path zero-return stubs: addressless @extern symbols are provided by the platform, host, or a later link step, and emitting RET / XOR A / LD HL,0 bodies for them silently changed real programs (22 Nanz outputs moved, e.g. tui_demo, tetris_tui, sqlite_demo, irc_client). Remove the NoImpl attribute (mir2.FuncAttrs, hir.Func, the hir lowerer's threading and the nanz @extern marker) and the genFunc stub emission; product output for every addressless extern is again the bare label that main produces, reported by label-audit when it stays undefined. The assert sandbox gets its own accommodation in the next commit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS --- minzc/pkg/hir/hir.go | 1 - minzc/pkg/hir/lower.go | 1 - minzc/pkg/mir2/extern_stub_codegen_test.go | 44 ---------------------- minzc/pkg/mir2/func.go | 6 --- minzc/pkg/mir2/z80codegen.go | 21 ++--------- minzc/pkg/nanz/parse.go | 5 --- 6 files changed, 4 insertions(+), 74 deletions(-) delete mode 100644 minzc/pkg/mir2/extern_stub_codegen_test.go diff --git a/minzc/pkg/hir/hir.go b/minzc/pkg/hir/hir.go index 522f1f5dd..b421447f8 100644 --- a/minzc/pkg/hir/hir.go +++ b/minzc/pkg/hir/hir.go @@ -167,7 +167,6 @@ type Func struct { ExternClobbers []string // nil = unknown; non-nil = explicit Z80 write contract IsExtern bool ExternAddr uint16 // non-zero → @extern(addr) — call via CALL/RST to fixed address - NoImpl bool // extern with no implementation anywhere (host hook); Z80 emits a zero-return stub IsIO bool // true = effectful (IO); false = pure (compile-time safe) } diff --git a/minzc/pkg/hir/lower.go b/minzc/pkg/hir/lower.go index b6d006e6f..320567533 100644 --- a/minzc/pkg/hir/lower.go +++ b/minzc/pkg/hir/lower.go @@ -627,7 +627,6 @@ func lowerFuncWithFuncNames(m *mir2.Module, f *Func, funcNames map[string]bool, if f.IsExtern { mf.Attrs.IsExtern = true mf.Attrs.ExternAddr = f.ExternAddr - mf.Attrs.NoImpl = f.NoImpl mf.Contract.ExternClobbers = f.ExternClobbers } diff --git a/minzc/pkg/mir2/extern_stub_codegen_test.go b/minzc/pkg/mir2/extern_stub_codegen_test.go deleted file mode 100644 index 93a81db98..000000000 --- a/minzc/pkg/mir2/extern_stub_codegen_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package mir2_test - -import ( - "strings" - "testing" - - "github.com/minz/minzc/pkg/mir2" -) - -// An extern declaration without an address has no implementation on this -// target. The Z80 emitter used to emit only the label, so a CALL fell through -// into whatever function followed. It must emit a defined stub that returns -// zeroes. Regression for the examples/nanz/canvas_house.nanz z80 assert -// (execution limit exceeded while running off into unrelated code). -func TestZ80AddresslessExternStubReturns(t *testing.T) { - m := &mir2.Module{Name: "externs"} - - u16fn := m.AddFunc("canvas_pixel") - u16fn.Attrs.IsExtern = true - u16fn.Attrs.NoImpl = true - u16fn.Contract.Returns = []mir2.Return{{Ty: mir2.TyU16, Class: mir2.ClassPointer}} - - voidfn := m.AddFunc("canvas_clear") - voidfn.Attrs.IsExtern = true - voidfn.Attrs.NoImpl = true - - lr := mir2.ComputeLiveness(u16fn) - ar := mir2.Allocate(u16fn, lr, mir2.Z80CostTable{}) - asm := mustZ80Asm(mir2.Z80Codegen(m, ar)) - - for _, name := range []string{"canvas_pixel", "canvas_clear"} { - idx := strings.Index(asm, name+":") - if idx < 0 { - t.Fatalf("missing label for %s:\n%s", name, asm) - } - tail := asm[idx:] - if !strings.Contains(tail[:min(len(tail), 120)], "RET") { - t.Errorf("%s: stub must RET instead of falling through:\n%s", name, tail[:min(len(tail), 120)]) - } - } - if !strings.Contains(asm, "LD HL, 0") { - t.Errorf("u16-returning extern stub should return HL=0:\n%s", asm) - } -} diff --git a/minzc/pkg/mir2/func.go b/minzc/pkg/mir2/func.go index 519a62eb0..0adb175ef 100644 --- a/minzc/pkg/mir2/func.go +++ b/minzc/pkg/mir2/func.go @@ -119,12 +119,6 @@ type FuncAttrs struct { // Recursive functions cannot use absolute $F0xx locals on Z80 — they need // a stack frame. IsRecursive bool - - // NoImpl: this extern has no implementation anywhere — the frontend knows - // the symbol only as a host hook (e.g. the mir2 canvas_* hosts). The Z80 - // backend then emits a defined zero-return stub instead of the bare - // label, which fell through into the next function when called. - NoImpl bool `json:",omitempty"` } // ── Construction helpers ────────────────────────────────────────────────────── diff --git a/minzc/pkg/mir2/z80codegen.go b/minzc/pkg/mir2/z80codegen.go index d70ec8e50..b831032c3 100644 --- a/minzc/pkg/mir2/z80codegen.go +++ b/minzc/pkg/mir2/z80codegen.go @@ -1417,23 +1417,10 @@ func (g *z80cg) genFunc(f *Func) { g.emitf("%s: DS %d", locs[p.Reg].Name, ByteWidth(p.Ty)) } } - // A host-only extern (Attrs.NoImpl) has no implementation anywhere. - // The bare label alone made a CALL fall through into whatever - // function follows; emit a defined stub that returns zeroes. - // Plain externs keep the bare label: their bodies may be linked in - // later or live at ExternAddr. - if f.Attrs.NoImpl { - switch { - case len(f.Contract.Returns) > 0 && ByteWidth(f.Contract.Returns[0].Ty) >= 2: - g.emit(" LD HL, 0") - g.emit(" RET") - case len(f.Contract.Returns) > 0 && ByteWidth(f.Contract.Returns[0].Ty) == 1: - g.emit(" XOR A") - g.emit(" RET") - default: - g.emit(" RET") - } - } + // Deliberately no stub body: externs are provided by the platform, + // host, or a later link step, and a silent zero-return stub would + // change real programs. The assert sandbox (RunAssertsZ80) appends + // its own stubs for undefined call targets when executing asserts. return } var frameErr error diff --git a/minzc/pkg/nanz/parse.go b/minzc/pkg/nanz/parse.go index e54575cd6..3f9df82bb 100644 --- a/minzc/pkg/nanz/parse.go +++ b/minzc/pkg/nanz/parse.go @@ -1072,11 +1072,6 @@ func (p *parser) parseModule() (*hir.Module, error) { } f.ExternAddr = externAddr f.ExternClobbers = externClobbers - if externAddr == 0 { - // An addressless @extern is a host hook (e.g. the mir2 - // canvas_* hosts): it has no implementation anywhere. - f.NoImpl = true - } m.Funcs = append(m.Funcs, f) } else if attr.kind == tokIdent && attr.val == "screen" && p.metaFuncs["screen"] == "" { // Built-in @screen metafunction (only if no user-defined @screen) From 59d1d90208760e402a4283e296d45dd6ea9814d7 Mon Sep 17 00:00:00 2001 From: "Alice V." Date: Tue, 1 Dec 2026 04:29:14 +0000 Subject: [PATCH 09/12] pipeline: confine the extern accommodation to the assert-sandbox build MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review of the first round (compile_sweep vs main) rejected product-path accommodations: NoImpl zero-return stubs after addressless @extern labels silently changed 22 Nanz programs (tui_demo, tetris_tui, sqlite_demo, irc_client, …) whose externs are provided by the platform at link time, and registering C prototypes changed call ABI and exit status for previously compiling files (examples/c89/fatfs ff.c / ffsystem.c: 'external ABI f_expand unsupported parameter width'). After 80f68f7e9 (C prototypes reverted) and f36554beb (product stubs removed), this commit puts the whole accommodation inside the assert sandbox: - Z80CodegenOptions.AssertSandbox: for a CALL to a symbol with no function in the module (dropped C prototype, host-only extern), the result is picked up from the convention register (A for bytes, HL for words) instead of being silently dropped when its destination home differs — examples/objc/plasma.m Diamond_render read canvas_width/ canvas_height into garbage homes and looped forever on the resulting garbage bounds. Product codegen never sets the flag. - Steps.assertSandboxAssembly re-emits the product with the flag (same allocation and variant decisions) and is what RunAssertsZ80 executes in both the direct and the variant-search path; Steps.Assembly is byte-identical to main's product. - withAssertSandboxStubs (sandbox assembly text only): an undefined CALL/JP target gets an appended zero-return definition; a bare-label extern (nanz @extern without address) gets the stub body inserted in place, only when the module says the symbol is an extern without blocks — a function whose body merely starts with a local label is never touched. Product output stays byte-identical to main for every file except the fixed assert examples; verified by compile_sweep. Regression test: pkg/pipeline/assert_sandbox_stubs_test.go (product assembly keeps the bare undefined label; the sandbox assert passes). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS --- minzc/pkg/mir2/z80codegen.go | 12 +- minzc/pkg/mir2/z80codegen_call.go | 18 ++ .../pkg/pipeline/assert_sandbox_stubs_test.go | 47 +++++ minzc/pkg/pipeline/pipeline.go | 191 +++++++++++++++++- minzc/pkg/pipeline/variant_search.go | 2 +- 5 files changed, 262 insertions(+), 8 deletions(-) create mode 100644 minzc/pkg/pipeline/assert_sandbox_stubs_test.go diff --git a/minzc/pkg/mir2/z80codegen.go b/minzc/pkg/mir2/z80codegen.go index b831032c3..d17634b19 100644 --- a/minzc/pkg/mir2/z80codegen.go +++ b/minzc/pkg/mir2/z80codegen.go @@ -210,6 +210,12 @@ type Z80CodegenOptions struct { // Target is the processor description (ADR 0056); nil is TargetZ80. // Instruction choices beyond the Z80 base ask it (Has, Cost). Target *Target + // AssertSandbox marks the assert-sandbox emission (RunAssertsZ80): calls + // to symbols with no function in the module (dropped C prototypes, + // host-only externs) pick up their convention-register result instead of + // silently dropping it. Product output never sets this, so product bytes + // stay identical to the historical behavior. + AssertSandbox bool } // ValidateZ80Symbols rejects distinct functions/data that emit the same symbol. @@ -427,7 +433,7 @@ func z80CodegenWithLeafWrites(m *Module, ar *AllocResult, leafWrites map[string] if target == nil { target = TargetZ80 } - cg := &z80cg{target: target, adl: opt.ADL, clobberCache: leafWrites, legacyLeafClobbers: opt.NoExactClobbers, calledMain: opt.CalledMain, cpmApplicationEntry: opt.CPMApplicationEntry, cpmGlobalStores: guardedStores, runtimeStackBytes: opt.RuntimeStackBytes, runtime: opt.Runtime, nativeCallSpillSink: opt.NativeCallSpills, unsignedPairComparePolicy: opt.UnsignedPairComparePolicy, ar: ar, sb: &sb, mod: m, annotateT: opt.AnnotateTStates, disableLoopRotation: opt.DisableLoopRotation, nativeMemoryOrigins: opt.NativeMemoryAccessOrigins, nativeMemorySink: opt.NativeMemoryAccesses, nativeCallFrameSink: opt.NativeCallFrames, nativeAccessCount: map[*Inst]int{}, nativeOrphanLabels: map[string]string{}} + cg := &z80cg{target: target, adl: opt.ADL, clobberCache: leafWrites, legacyLeafClobbers: opt.NoExactClobbers, calledMain: opt.CalledMain, cpmApplicationEntry: opt.CPMApplicationEntry, cpmGlobalStores: guardedStores, runtimeStackBytes: opt.RuntimeStackBytes, runtime: opt.Runtime, nativeCallSpillSink: opt.NativeCallSpills, unsignedPairComparePolicy: opt.UnsignedPairComparePolicy, ar: ar, sb: &sb, mod: m, annotateT: opt.AnnotateTStates, disableLoopRotation: opt.DisableLoopRotation, nativeMemoryOrigins: opt.NativeMemoryAccessOrigins, nativeMemorySink: opt.NativeMemoryAccesses, nativeCallFrameSink: opt.NativeCallFrames, nativeAccessCount: map[*Inst]int{}, nativeOrphanLabels: map[string]string{}, assertSandbox: opt.AssertSandbox} sb.WriteString("; generated by MIR2 Z80 codegen\n\n") if opt.ZXApplicationEntry { @@ -1057,6 +1063,10 @@ type z80cg struct { disableLoopRotation bool domFn *Func dom map[string]map[string]bool + + // assertSandbox: Z80CodegenOptions.AssertSandbox (RunAssertsZ80 builds). + // Unknown-callee results are picked up from the convention register. + assertSandbox bool } func (g *z80cg) emit(s string) { diff --git a/minzc/pkg/mir2/z80codegen_call.go b/minzc/pkg/mir2/z80codegen_call.go index 73b41e7eb..ec9f3d354 100644 --- a/minzc/pkg/mir2/z80codegen_call.go +++ b/minzc/pkg/mir2/z80codegen_call.go @@ -439,6 +439,24 @@ func (g *z80cg) genCall(inst *Inst) error { dstPhys = g.loc(inst.Dst) results = append(results, parallelCopy{srcName: canonicalReturnLoc(ret.Class, ret.Ty), dstName: dstPhys, ty: ret.Ty}) } + } else if inst.Dst != NoReg && callee == nil && g.assertSandbox { + // Unknown callee (called symbol with no function in the module — a + // dropped C prototype or a host hook). No contract is available, so + // the Z80 convention is the only source of truth: byte results come + // back in A, word results in HL. Without this pickup the result is + // silently dropped whenever its destination home is not that + // register. Assert-sandbox builds only: product output must stay + // byte-identical to the historical behavior. + ty := inst.Ty + if ty == nil || ty == TyVoid { + ty = TyU16 + } + cls := ClassPointer + if ByteWidth(ty) == 1 { + cls = ClassAcc + } + dstPhys = g.loc(inst.Dst) + results = append(results, parallelCopy{srcName: canonicalReturnLoc(cls, ty), dstName: dstPhys, ty: ty}) } if inst.FallibleCY { if callee == nil || !callee.Attrs.FallibleCY || len(inst.ExtraRets) != 2 { diff --git a/minzc/pkg/pipeline/assert_sandbox_stubs_test.go b/minzc/pkg/pipeline/assert_sandbox_stubs_test.go new file mode 100644 index 000000000..1fd5162dd --- /dev/null +++ b/minzc/pkg/pipeline/assert_sandbox_stubs_test.go @@ -0,0 +1,47 @@ +package pipeline + +import ( + "strings" + "testing" + + "github.com/minz/minzc/pkg/nanz" +) + +// An addressless @extern is provided by the host at runtime; product output +// keeps it an undefined label (label-audit reports it) and must not grow a +// silent stub. Only the assert sandbox may define it, so a forced-z80 assert +// that calls through the extern executes defined code instead of wandering +// through memory after the call. Regression for the examples/nanz/ +// canvas_house.nanz and examples/objc/plasma.m z80 assert failures, without +// changing product output (compile_sweep regression found in review). +const assertSandboxStubSrc = ` +@extern fun host_nop() -> u16 + +fun twice() -> u16 { + return host_nop() * 2 +} + +assert twice() == 0 via z80 +` + +func TestAssertSandboxStubsUndefinedExtern(t *testing.T) { + hm, err := nanz.Parse(assertSandboxStubSrc, "sandbox_stub.nanz") + if err != nil { + t.Fatalf("parse: %v", err) + } + steps, err := CompileHIRSteps(hm, Options{AssertMode: "none"}) + if err != nil { + t.Fatalf("compile: %v", err) + } + // Product output: the extern stays a bare, undefined label. + if strings.Count(steps.Assembly, "host_nop:") != 1 { + t.Fatalf("product assembly must reference host_nop exactly once as a bare label:\n%s", steps.Assembly) + } + if tail := steps.Assembly[strings.Index(steps.Assembly, "host_nop:"):]; strings.Contains(tail[:min(len(tail), 120)], "RET") { + t.Errorf("product assembly must not define a stub body for the extern:\n%s", tail[:min(len(tail), 120)]) + } + // Sandbox execution: the assert passes against the appended stub. + if err := RunAssertsZ80(hm, steps.MIR2Module, steps.Allocation, steps.Assembly); err != nil { + t.Errorf("z80 sandbox assert: %v", err) + } +} diff --git a/minzc/pkg/pipeline/pipeline.go b/minzc/pkg/pipeline/pipeline.go index bae2b218f..22b6756d8 100644 --- a/minzc/pkg/pipeline/pipeline.go +++ b/minzc/pkg/pipeline/pipeline.go @@ -60,6 +60,7 @@ type Steps struct { MIR2Module *mir2.Module // MIR2 module (for LLVM/WASM/ABAP emit) Allocation *mir2.AllocResult // physical locations used by Z80 codegen Assembly string // Final .a80 text + SandboxAssembly string // assert-sandbox variant (AssertSandbox codegen); empty = reuse Assembly ez80Body string // eZ80: emitted body before the output-shape wrapper Traces map[string]*FuncTrace // per-function compilation trace (keyed by func name) } @@ -441,7 +442,7 @@ func compileMIRSteps(hm *hir.Module, opt Options, s Steps, splitInfo map[string] if !opt.SkipZ80Emission || NeedsZ80Asserts(hm, opt.AssertMode) { // Z80 binary assertion checks (skip for eZ80 — different encoding). if opt.Backend != "ez80" && opt.AssertMode != "mir2" && opt.AssertMode != "none" && opt.AssertMode != "wasm" { - if err := RunAssertsZ80Target(hm, m, s.Allocation, s.Assembly, opt.target()); err != nil { + if err := RunAssertsZ80Target(hm, m, s.Allocation, s.assertSandboxAssembly(m, opt), opt.target()); err != nil { return s, err } } @@ -1502,6 +1503,57 @@ func RunAssertsZ80Target(hm *hir.Module, m *mir2.Module, ar *mir2.AllocResult, a return nil } +// assertSandboxAssembly returns the assert-sandbox Z80 product: the same +// codegen as the emitted product with AssertSandbox enabled, so calls to +// symbols with no function in the module (dropped C prototypes, host-only +// externs) pick up their convention-register result. Product output +// (Steps.Assembly) is never affected. The result is cached on the Steps. +func (s *Steps) assertSandboxAssembly(m *mir2.Module, opt Options) string { + if s.SandboxAssembly != "" { + return s.SandboxAssembly + } + asm, err := mir2.Z80Codegen(m, s.Allocation, mir2.Z80CodegenOptions{ + FullABI: nil, + OptimizeForSize: opt.OptSize, + FunctionOptions: s.sandboxFunctionOptions(opt), + CalledMain: opt.Backend == "ez80" || opt.CPMApplicationEntry || opt.Runtime == mir2.Z80RuntimeAgonZ80, + CPMApplicationEntry: opt.CPMApplicationEntry, + ZXApplicationEntry: opt.ZXApplicationEntry, + Runtime: opt.Runtime, + RuntimeStackBytes: opt.RuntimeStackBytes, + UnsignedPairComparePolicy: s.UnsignedPairComparePolicy, + NoExactClobbers: opt.NoExactClobbers, + DisableLoopRotation: s.DisableLoopRotation, + ADL: opt.Backend == "ez80", + Target: opt.target(), + AssertSandbox: true, + }) + if err != nil { + // Sandbox codegen must never break assertion runs: fall back to the + // product assembly (the historical behavior). + return s.Assembly + } + asm = emitExternStubs(asm, m) + s.SandboxAssembly = asm + return asm +} + +// sandboxFunctionOptions reconstructs the per-function codegen options of the +// emitted product: explicit user variants plus the selected variant-search +// decisions (their MIR-level axes are already baked into the module). +func (s *Steps) sandboxFunctionOptions(opt Options) map[string]mir2.Z80FunctionOptions { + p := variantCodegenOptions(opt) + for _, d := range s.VariantDecisions { + p[d.Function] = mir2.Z80FunctionOptions{ + CompactByteLoops: d.Recipe.CompactByteLoops, + BitTests: d.Recipe.BitTests, + DJNZTrampoline: d.Recipe.DJNZTrampoline, + CompactShifts: d.Recipe.CompactShifts, + } + } + return p +} + // runOneAssertZ80 runs a single assert on a fresh emulator (top-level, isolated). func runOneAssertZ80(z *emulator.RemogattoZ80, a hir.Assert, mir2Funcs map[string]*mir2.Func, hirFuncs map[string]*hir.Func, @@ -1513,7 +1565,7 @@ func runOneAssertZ80(z *emulator.RemogattoZ80, a hir.Assert, } boot := buildAssertBootstrap(assertLoadAddr, a, mf, ar) - src := boot + "\n" + asmSrc + src := boot + "\n" + withAssertSandboxStubs(asmSrc, mir2Funcs) as := assemblerFor(z) res, err := as.AssembleString(src) @@ -1560,7 +1612,7 @@ func RunZ80Cycles(hm *hir.Module, m *mir2.Module, ar *mir2.AllocResult, asmSrc, } a := hir.Assert{FuncName: fnName, Args: args, Source: "z80 cycles"} z := emulator.NewRemogattoZ80() - if err := runOneAssertZ80Raw(z, a, mf, hirFuncs, ar, asmSrc); err != nil { + if err := runOneAssertZ80Raw(z, a, mf, hirFuncs, ar, asmSrc, mir2Funcs); err != nil { return 0, 0, err } if len(mf.Contract.Returns) == 0 { @@ -1575,9 +1627,9 @@ func RunZ80Cycles(hm *hir.Module, m *mir2.Module, ar *mir2.AllocResult, asmSrc, // runOneAssertZ80Raw is runOneAssertZ80 without the result check. func runOneAssertZ80Raw(z *emulator.RemogattoZ80, a hir.Assert, mf *mir2.Func, - hirFuncs map[string]*hir.Func, ar *mir2.AllocResult, asmSrc string) error { + hirFuncs map[string]*hir.Func, ar *mir2.AllocResult, asmSrc string, mir2Funcs map[string]*mir2.Func) error { boot := buildAssertBootstrap(assertLoadAddr, a, mf, ar) - src := boot + "\n" + asmSrc + src := boot + "\n" + withAssertSandboxStubs(asmSrc, mir2Funcs) as := assemblerFor(z) res, err := as.AssembleString(src) if err != nil { @@ -1619,7 +1671,7 @@ func runOneAssertZ80Sandbox(z *emulator.RemogattoZ80, a hir.Assert, // Insert NOPs between the ORG line and the first instruction — actually, // the bootstrap starts with ORG, then instructions, then HALT. // Easier: append NOPs after HALT (they're unreachable, just padding). - src := boot + nops + asmSrc + src := boot + nops + withAssertSandboxStubs(asmSrc, mir2Funcs) as := assemblerFor(z) res, err := as.AssembleString(src) @@ -2074,6 +2126,133 @@ func isInstruction(s string) bool { return false } +// withAssertSandboxStubs gives call/jump targets that have no executable +// body a stub, in the assert sandbox only. Two shapes exist: labels the +// assembly never defines (prototypes dropped by the C frontend — they get an +// appended definition) and empty labels (addressless @extern functions whose +// body lives on the host — the stub is inserted directly after the bare +// label, which product output keeps so linking stays honest). Without this, +// a forced-z80 assert assembles to an error or falls through the label into +// unrelated code. The stub returns zeroes in A and HL, which covers void, +// u8 and u16 externs that asserted code treats as opaque host effects. +// A defined label only counts as empty when the module says the symbol is an +// extern function without blocks — a function whose body merely begins with +// a local label is never touched. +func withAssertSandboxStubs(asmSrc string, mir2Funcs map[string]*mir2.Func) string { + lines := strings.Split(asmSrc, "\n") + externNoBlocks := map[string]bool{} + for _, f := range mir2Funcs { + if len(f.Blocks) == 0 && !f.Attrs.HasAsm { + externNoBlocks[asmutil.SanitizeZ80Label(f.Name)] = true + } + } + hasBody := map[string]bool{} // label name → followed by an instruction or data + seen := map[string]bool{} + var referenced []string + for i, line := range lines { + code, _, _ := strings.Cut(line, ";") + code = strings.TrimSpace(code) + if code == "" { + continue + } + if name, ok := strings.CutSuffix(code, ":"); ok && !strings.ContainsAny(name, " \t") { + // A label has a body when the next significant line is an + // instruction or data; consecutive labels (the nanz @extern + // section) are empty. + body := "" + for _, next := range lines[i+1:] { + nc, _, _ := strings.Cut(next, ";") + nc = strings.TrimSpace(nc) + if nc == "" { + continue + } + body = nc + break + } + hasBody[name] = body != "" && !strings.HasSuffix(body, ":") + continue + } + fields := strings.Fields(code) + if len(fields) < 2 { + continue + } + switch strings.ToUpper(fields[0]) { + case "CALL", "JP", "JR", "JRS", "DJNZ": + default: + continue + } + target := fields[len(fields)-1] + if !isAsmSymbolTarget(target) || seen[target] { + continue + } + seen[target] = true + referenced = append(referenced, target) + } + stubBody := []string{" XOR A", " LD L, A", " LD H, A", " RET", ""} + out := make([]string, 0, len(lines)+4*len(referenced)) + appended := false + for _, line := range lines { + out = append(out, line) + code, _, _ := strings.Cut(line, ";") + code = strings.TrimSpace(code) + name, ok := strings.CutSuffix(code, ":") + if !ok || strings.ContainsAny(name, " \t") || hasBody[name] || !seen[name] || !externNoBlocks[name] { + continue + } + // Empty label of a referenced extern: insert the stub body in place + // (appending would define the label twice). + out = append(out, stubBody...) + appended = true + } + var missing []string + for _, target := range referenced { + scoped := target + if i := strings.LastIndexByte(scoped, '.'); i >= 0 { + scoped = scoped[i:] + } + // A target the assembly defines as a label is handled by the in-place + // insertion above (empty) or already has a body — either way done. + if _, ok := hasBody[target]; ok { + continue + } + if _, ok := hasBody[scoped]; ok { + continue + } + missing = append(missing, target) + } + for _, target := range missing { + out = append(out, "; "+target+" — assert-sandbox stub (extern provided at runtime)") + out = append(out, target+":") + out = append(out, stubBody...) + appended = true + } + if !appended { + return asmSrc + } + return strings.Join(out, "\n") +} + +// isAsmSymbolTarget reports whether an operand field is a plausible label +// name (not an indirect register or a numeric address). +func isAsmSymbolTarget(target string) bool { + if strings.ContainsAny(target, "()" ) { + return false + } + for i, r := range target { + switch { + case r == '_' || r == '.' || r == '$': + case r >= '0' && r <= '9': + if i == 0 { + return false + } + case r >= 'A' && r <= 'Z', r >= 'a' && r <= 'z': + default: + return false + } + } + return true +} + // emitExternStubs appends label stubs for @extern functions that are called // in the assembly but have no label definition after function emission. func emitExternStubs(asm string, m *mir2.Module) string { diff --git a/minzc/pkg/pipeline/variant_search.go b/minzc/pkg/pipeline/variant_search.go index 1770eb36f..58d68d5ae 100644 --- a/minzc/pkg/pipeline/variant_search.go +++ b/minzc/pkg/pipeline/variant_search.go @@ -569,7 +569,7 @@ func finishVariantSearch(h *hir.Module, s Steps, mode string) (Steps, error) { } } if mode != "mir2" && mode != "none" && mode != "wasm" && mode != "llvm" { - if err := RunAssertsZ80Target(h, s.MIR2Module, s.Allocation, s.Assembly, s.target()); err != nil { + if err := RunAssertsZ80Target(h, s.MIR2Module, s.Allocation, s.assertSandboxAssembly(s.MIR2Module, Options{OptSize: s.OptSize}), s.target()); err != nil { return s, err } } From 501e9149062a0604ec6b25b7febcb6f611249c13 Mon Sep 17 00:00:00 2001 From: "Alice V." Date: Tue, 1 Dec 2026 04:37:38 +0000 Subject: [PATCH 10/12] pipeline: keep the assert-sandbox emission silent The assert-sandbox re-emission (59d1d9020) printed its own Z80-VALIDATE report to stdout, duplicating the product's diagnostics for modules with invalid instructions (examples/_archive editor_demo.minz printed the report twice; compile_sweep stdout_changes). The sandbox emission now discards its validation report; product diagnostics are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS --- minzc/pkg/pipeline/pipeline.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/minzc/pkg/pipeline/pipeline.go b/minzc/pkg/pipeline/pipeline.go index 22b6756d8..4797d0616 100644 --- a/minzc/pkg/pipeline/pipeline.go +++ b/minzc/pkg/pipeline/pipeline.go @@ -61,6 +61,7 @@ type Steps struct { Allocation *mir2.AllocResult // physical locations used by Z80 codegen Assembly string // Final .a80 text SandboxAssembly string // assert-sandbox variant (AssertSandbox codegen); empty = reuse Assembly + sandboxValidationLog []string // discarded Z80-VALIDATE report of the sandbox emission ez80Body string // eZ80: emitted body before the output-shape wrapper Traces map[string]*FuncTrace // per-function compilation trace (keyed by func name) } @@ -1527,6 +1528,9 @@ func (s *Steps) assertSandboxAssembly(m *mir2.Module, opt Options) string { ADL: opt.Backend == "ez80", Target: opt.target(), AssertSandbox: true, + // The sandbox emission must stay silent: its Z80-VALIDATE report is + // discarded, never duplicated on stdout. + ValidationLog: &s.sandboxValidationLog, }) if err != nil { // Sandbox codegen must never break assertion runs: fall back to the From d18bde2bca8f792d4c59e7428f8a2e7828290819 Mon Sep 17 00:00:00 2001 From: "Alice V." Date: Tue, 1 Dec 2026 04:38:49 +0000 Subject: [PATCH 11/12] ci: classify TestAssertSandboxStubsUndefinedExtern in the fast profile The stable pipeline requires every pkg/pipeline test to appear exactly once in the profile manifest; the new assert-sandbox regression test runs in seconds and belongs in fast. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS --- scripts/ci/pipeline_profiles.json | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/ci/pipeline_profiles.json b/scripts/ci/pipeline_profiles.json index 971adad8c..4d1c76197 100644 --- a/scripts/ci/pipeline_profiles.json +++ b/scripts/ci/pipeline_profiles.json @@ -21,6 +21,7 @@ "TestAssertBootstrapInitializesAllocatedSpill", "TestAssertMissingReturnContracts", "TestAssertRejectsMalformedRawResults", + "TestAssertSandboxStubsUndefinedExtern", "TestAssertSignedReturnDomains", "TestBitAccumNewShapesUnderOsize", "TestBitStorePointerHomeClearE2E", From ee96b1c85d4554bc6299b3bf009d211e6eeaa7eb Mon Sep 17 00:00:00 2001 From: "Alice V." Date: Tue, 1 Dec 2026 05:05:01 +0000 Subject: [PATCH 12/12] pipeline: generate the assert-sandbox emission inside the product emitter The first sandbox wiring regenerated Z80 code in the assert runners with reconstructed per-function variant options, which lost the Z80N MUL selection for the winning variants (TestZ80NMulExhaustive looped on shift-and-add fallbacks) and, for variant-search products whose trials compile with AssertMode none, produced no sandbox emission at all (examples/objc/plasma.m still hit the execution limit). compileMIRProductSteps now emits Steps.SandboxAssembly right after the product: identical options (the caller's FunctionVariants are the selected decisions in variant candidates), AssertSandbox on, validation report discarded. Variant-search trials skip the extra emission via variantCandidate; compileVariantSearch sets assertSandboxEmission so the winning product still carries it, and finishVariantSearch regenerates from the recorded recipes when a product predates the field. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01N957godRAhTkyy1mTB6roS --- minzc/pkg/pipeline/pipeline.go | 101 ++++++++++++--------------- minzc/pkg/pipeline/variant_search.go | 36 +++++++++- 2 files changed, 81 insertions(+), 56 deletions(-) diff --git a/minzc/pkg/pipeline/pipeline.go b/minzc/pkg/pipeline/pipeline.go index 4797d0616..c6b3faf73 100644 --- a/minzc/pkg/pipeline/pipeline.go +++ b/minzc/pkg/pipeline/pipeline.go @@ -61,6 +61,7 @@ type Steps struct { Allocation *mir2.AllocResult // physical locations used by Z80 codegen Assembly string // Final .a80 text SandboxAssembly string // assert-sandbox variant (AssertSandbox codegen); empty = reuse Assembly + FunctionVariants map[string]FunctionVariant // winning variant recipes of the emitted product sandboxValidationLog []string // discarded Z80-VALIDATE report of the sandbox emission ez80Body string // eZ80: emitted body before the output-shape wrapper Traces map[string]*FuncTrace // per-function compilation trace (keyed by func name) @@ -165,6 +166,11 @@ type Options struct { // disableShiftCarryPreference: the module's codegen refused the // preferred homes (see compileMIRProductSteps); allocate without it. disableShiftCarryPreference bool + // assertSandboxEmission: generate Steps.SandboxAssembly even though the + // trials compile with AssertMode none (compileVariantSearch sets this for + // its products; the final winning product needs the assert-sandbox + // emission without executing asserts per trial). + assertSandboxEmission bool // CPMApplicationEntry selects ordinary native CP/M application entry, // independently of the guarded runtime and semantic bare/called harnesses. CPMApplicationEntry bool `json:",omitempty"` @@ -443,7 +449,11 @@ func compileMIRSteps(hm *hir.Module, opt Options, s Steps, splitInfo map[string] if !opt.SkipZ80Emission || NeedsZ80Asserts(hm, opt.AssertMode) { // Z80 binary assertion checks (skip for eZ80 — different encoding). if opt.Backend != "ez80" && opt.AssertMode != "mir2" && opt.AssertMode != "none" && opt.AssertMode != "wasm" { - if err := RunAssertsZ80Target(hm, m, s.Allocation, s.assertSandboxAssembly(m, opt), opt.target()); err != nil { + assertAsm := s.SandboxAssembly + if assertAsm == "" { + assertAsm = s.Assembly + } + if err := RunAssertsZ80Target(hm, m, s.Allocation, assertAsm, opt.target()); err != nil { return s, err } } @@ -893,6 +903,41 @@ func compileMIRProductSteps(hm *hir.Module, opt Options, s Steps, splitInfo map[ // Deduplicate labels in assembly. s.Assembly = dedupAsmLabels(s.Assembly) + // Assert-sandbox variant: the same codegen options (the caller's + // FunctionVariants are the selected variant decisions here) with + // AssertSandbox enabled, so calls to symbols with no function in the + // module (dropped C prototypes, host-only externs) pick up their + // convention-register result when an assert executes them. Product + // output above is never affected. Generated only for the final + // product, never inside variant-search trials. + s.FunctionVariants = opt.FunctionVariants + assertsAllowSandbox := (opt.AssertMode != "none" && opt.AssertMode != "mir2" && opt.AssertMode != "wasm") || opt.assertSandboxEmission + if assertsAllowSandbox && !opt.SkipZ80Emission { + sandboxValidationLog := []string{} + sandboxAsm, sandboxErr := mir2.Z80Codegen(m, combined, mir2.Z80CodegenOptions{ + FullABI: fullABI, + OptimizeForSize: opt.OptSize, + FunctionOptions: variantCodegenOptions(opt), + CalledMain: opt.Backend == "ez80" || opt.CPMApplicationEntry || opt.Runtime == mir2.Z80RuntimeAgonZ80, + CPMApplicationEntry: opt.CPMApplicationEntry, + ZXApplicationEntry: opt.ZXApplicationEntry, + Runtime: opt.Runtime, + RuntimeStackBytes: opt.RuntimeStackBytes, + UnsignedPairComparePolicy: s.UnsignedPairComparePolicy, + NoExactClobbers: opt.NoExactClobbers, + DisableLoopRotation: s.DisableLoopRotation, + ADL: opt.Backend == "ez80", + Target: opt.target(), + AssertSandbox: true, + ValidationLog: &sandboxValidationLog, + }) + if sandboxErr == nil { + s.SandboxAssembly = emitExternStubs(sandboxAsm, m) + } + // A sandbox codegen error never breaks the build: the runners fall + // back to the product assembly (the historical behavior). + } + // eZ80: place the ADL body in the selected output shape. if opt.Backend == "ez80" { s.ez80Body = s.Assembly @@ -1504,60 +1549,6 @@ func RunAssertsZ80Target(hm *hir.Module, m *mir2.Module, ar *mir2.AllocResult, a return nil } -// assertSandboxAssembly returns the assert-sandbox Z80 product: the same -// codegen as the emitted product with AssertSandbox enabled, so calls to -// symbols with no function in the module (dropped C prototypes, host-only -// externs) pick up their convention-register result. Product output -// (Steps.Assembly) is never affected. The result is cached on the Steps. -func (s *Steps) assertSandboxAssembly(m *mir2.Module, opt Options) string { - if s.SandboxAssembly != "" { - return s.SandboxAssembly - } - asm, err := mir2.Z80Codegen(m, s.Allocation, mir2.Z80CodegenOptions{ - FullABI: nil, - OptimizeForSize: opt.OptSize, - FunctionOptions: s.sandboxFunctionOptions(opt), - CalledMain: opt.Backend == "ez80" || opt.CPMApplicationEntry || opt.Runtime == mir2.Z80RuntimeAgonZ80, - CPMApplicationEntry: opt.CPMApplicationEntry, - ZXApplicationEntry: opt.ZXApplicationEntry, - Runtime: opt.Runtime, - RuntimeStackBytes: opt.RuntimeStackBytes, - UnsignedPairComparePolicy: s.UnsignedPairComparePolicy, - NoExactClobbers: opt.NoExactClobbers, - DisableLoopRotation: s.DisableLoopRotation, - ADL: opt.Backend == "ez80", - Target: opt.target(), - AssertSandbox: true, - // The sandbox emission must stay silent: its Z80-VALIDATE report is - // discarded, never duplicated on stdout. - ValidationLog: &s.sandboxValidationLog, - }) - if err != nil { - // Sandbox codegen must never break assertion runs: fall back to the - // product assembly (the historical behavior). - return s.Assembly - } - asm = emitExternStubs(asm, m) - s.SandboxAssembly = asm - return asm -} - -// sandboxFunctionOptions reconstructs the per-function codegen options of the -// emitted product: explicit user variants plus the selected variant-search -// decisions (their MIR-level axes are already baked into the module). -func (s *Steps) sandboxFunctionOptions(opt Options) map[string]mir2.Z80FunctionOptions { - p := variantCodegenOptions(opt) - for _, d := range s.VariantDecisions { - p[d.Function] = mir2.Z80FunctionOptions{ - CompactByteLoops: d.Recipe.CompactByteLoops, - BitTests: d.Recipe.BitTests, - DJNZTrampoline: d.Recipe.DJNZTrampoline, - CompactShifts: d.Recipe.CompactShifts, - } - } - return p -} - // runOneAssertZ80 runs a single assert on a fresh emulator (top-level, isolated). func runOneAssertZ80(z *emulator.RemogattoZ80, a hir.Assert, mir2Funcs map[string]*mir2.Func, hirFuncs map[string]*hir.Func, diff --git a/minzc/pkg/pipeline/variant_search.go b/minzc/pkg/pipeline/variant_search.go index 58d68d5ae..334770ea2 100644 --- a/minzc/pkg/pipeline/variant_search.go +++ b/minzc/pkg/pipeline/variant_search.go @@ -226,6 +226,9 @@ func compileVariantSearch(source *hir.Module, options ...Options) (Steps, error) // only the retained exact product, with the caller's original assertion mode. mode, stats := o.AssertMode, o.GraceStats o.AssertMode = "none" + // The winning product still needs the assert-sandbox emission for + // finishVariantSearch; trials simply never execute the asserts. + o.assertSandboxEmission = true o.GraceStats = nil o.FunctionVariants = map[string]FunctionVariant{} // Trials are compared without Z80 loop rotation: the static model and the @@ -569,13 +572,44 @@ func finishVariantSearch(h *hir.Module, s Steps, mode string) (Steps, error) { } } if mode != "mir2" && mode != "none" && mode != "wasm" && mode != "llvm" { - if err := RunAssertsZ80Target(h, s.MIR2Module, s.Allocation, s.assertSandboxAssembly(s.MIR2Module, Options{OptSize: s.OptSize}), s.target()); err != nil { + assertAsm := s.sandboxAssemblyForAsserts() + if err := RunAssertsZ80Target(h, s.MIR2Module, s.Allocation, assertAsm, s.target()); err != nil { return s, err } } return s, nil } +// sandboxAssemblyForAsserts returns the assert-sandbox assembly: the product +// re-emitted with AssertSandbox enabled (variant trials compile with +// AssertMode none, so the winning product carries its recipes instead and the +// sandbox is regenerated here from them). Falls back to the product assembly. +func (s *Steps) sandboxAssemblyForAsserts() string { + if s.SandboxAssembly != "" { + return s.SandboxAssembly + } + if len(s.FunctionVariants) == 0 || s.MIR2Module == nil || s.Allocation == nil { + return s.Assembly + } + sandboxValidationLog := []string{} + asm, err := mir2.Z80Codegen(s.MIR2Module, s.Allocation, mir2.Z80CodegenOptions{ + OptimizeForSize: s.OptSize, + FunctionOptions: variantCodegenOptions(Options{FunctionVariants: s.FunctionVariants}), + UnsignedPairComparePolicy: s.UnsignedPairComparePolicy, + DisableLoopRotation: s.DisableLoopRotation, + ADL: s.target() == mir2.TargetEZ80, + Target: s.target(), + AssertSandbox: true, + ValidationLog: &sandboxValidationLog, + }) + if err != nil { + return s.Assembly + } + asm = emitExternStubs(asm, s.MIR2Module) + s.SandboxAssembly = asm + return asm +} + // Only an unreferenced entry with the same logical signature can change its // allocated entry registers. Fixed/explicit conventions retain the strict gate. func sameVariantEntryABI(before, after *mir2.Module, name string) bool {