Commit Graph

272 Commits

Author SHA1 Message Date
agra
17c19d5d30 ERR/E2.1a: value-carrying failable producer (return value + raise → tuple ABI)
The producer side of the error-channel tuple ABI for value-carrying `-> (T, !)`
functions. A failable that returns a value OR an error now lowers correctly;
the result is consumed via destructure (`v, err := f()`). Single-value
`-> (T, !)`; multi-value `-> (T1, T2, !)` and the value-carrying try/catch
consumers (E2.1b) follow.

- lowerReturn: a value-carrying failable's `return v;` assembles the success
  tuple `{v, 0}` (compiler appends the no-error slot) via lowerFailableSuccessReturn
  (tuple_init). Forwarding a full failable tuple (`return other_failable()` /
  explicit `return (v, e)`) returns as-is. Multi-value returns bail loudly (E2).
- lowerRaise: the value-carrying branch (previously a loud bail) now builds
  `{undef value slots..., tag}` (constUndef per value slot + the error tag) and
  returns it — any arity.
- helpers: buildFailableTuple (tuple_init from value refs + tag) + emitTupleRet
  (return honoring inline-comptime targets).

Value-carrying `try` / `catch` still bail (E2.1b). Tests:
examples/228-value-failable.sx (return value + both raises, consumed by
destructure; exit 60). Gates: zig build, zig build test, 266/266 examples.
2026-05-31 21:42:51 +03:00
agra
0bbff9d7fb ERR/E1.5: catch sema (pure-failable slice) + error-set match subjects
`expr catch [e] BODY` consumes a failable's error inline. Pure-failable slice
(value-carrying `-> (T, !)` catch deferred to E2's tuple ABI).

- lowerExpr `.catch_expr` -> lowerCatch; inferExprType `.catch_expr` ->
  operand's success type (void for pure-failable).
- lowerCatch: operand must be failable (else "catch requires a failable
  expression"); pure-failable LHS only (value-carrying bails to E2). Eval
  operand -> err tag; condBr to handle (error) / merge (success). In handle:
  child scope binds `e` to the tag (typed as the error set), lower body
  (block or expr); if the body didn't diverge, br merge. Result is void.
  `catch` needs no failable enclosing function — it handles the error locally.
- All four body forms work: block, no-binding `catch { }`, bare-expr, and
  the match-body `catch e == { case ... }`. Re-raise (`raise e`) and diverging
  bodies (`return`) rely on E1.3 / E1.4c.

Also: lowerMatch now supports error-set subjects — `case .X` resolves to the
global tag id (was the arm index, dispatching wrong), and the switch operand
is the error-set value (its u32 tag) directly rather than via enumTag. This
is what the catch match-body form (and a plain `if e == { case .X }`) needs.

Tests: examples/226-catch.sx (block / no-binding / match-body / re-raise /
diverging body / success-skip; exit 18), examples/227-catch-rejections.sx
(operand-not-failable; exit 1). Gates: zig build, zig build test,
265/265 examples.
2026-05-31 21:10:56 +03:00
agra
28b18f812a fix(issue-0057): all-diverging match arms no longer fail LLVM verification
A match (`if subject == { case ... }`) whose arms all diverge (each
`return`s / `raise`s) failed LLVM verification with a `void` phi plus
"Terminator found in the middle of a basic block". Two causes in lowerMatch:

- The value-arm path did `lowerBlockValue(arm.body) orelse constInt(0, …)`,
  emitting the fallback `const` into a block the body had ALREADY terminated
  (a diverging arm), so `currentBlockHasTerminator()` then saw the const (not
  the `ret`) and emitted a `br merge` after the terminator. Fix: materialize
  the fallback value + branch only when the block hasn't terminated.
- A fully-diverging match infers `result_type == .noreturn` yet still built a
  value-merge phi. Fix: `has_value_merge` excludes `.noreturn`, so such a
  match builds no phi; its arms terminate and the merge block is unreachable.

Also: inferMatchResultType now skips `.noreturn` arms (a diverging arm doesn't
decide the result type) and reports `.noreturn` only when EVERY arm diverges —
so a mixed match (some arms yield values, some diverge) infers the value type.

This unblocks ERR E1.5's `catch` match-body form (`x catch e == { case .A:
return …; else: raise e; }`), which desugars to an all-diverging match.

Regression: examples/225-match-diverging-arms.sx (all-diverging + mixed,
exit 134). Gates: zig build, zig build test, 263/263 examples.
2026-05-31 21:04:06 +03:00
agra
d2cba4e460 ERR/E1.4b: whole-program inferred error sets + empty-inferred warning
The type-convergence side of E1.4 (the SCC slice). A bare `-> !` function's
error set is now converged whole-program from its literal raises plus the
sets of the pure-failable functions it `try`s.

- convergeInferredErrorSets: a pre-lowering fix-point pass (lowerRoot Pass
  1d, after scanDecls / before body lowering) that walks each top-level
  bare-`!` function's body AST (collectErrorSites, stopping at nested-fn
  boundaries) for literal `raise error.X` tags + pure `try g()` edges, then
  unions each set with its edges' sets until stable. Stored in a side map
  `inferred_error_sets` (fn name -> sorted []u32) — sidesteps the name-only
  error-set interning collision (the shared `!` placeholder stays empty).
- lowerTry widening: a named caller `try`-ing a bare-`!` callee now checks
  the callee's converged set (previously a false-negative — the empty
  placeholder was trivially a subset). Factored diagTagsNotInSet out of
  checkErrorSetSubset.
- empty-inferred warning: a top-level non-main bare-`!` function with an
  empty converged set warns. Not user-visible yet (the compile driver
  renders diagnostics only on failure — a LANG follow-up), so unit-tested
  on the DiagnosticList.
- corrected two now-stale bail messages (failable-`or` -> E2.4;
  value-carrying `try` -> E2).

Deferred to E2.4: failable-`or` chains / value-terminators (and `try`
fallback routing) — gated on the value-carrying tuple ABI.

Tests: examples/223-inferred-error-sets.sx (transitive convergence +
widening passes, exit 7), examples/224-inferred-widening-reject.sx
(transitive widening rejection, exit 1), unit test in lower.test.zig.
Gates: zig build, zig build test, 262/262 examples.
2026-05-31 20:21:44 +03:00
agra
aa1aa63bb3 ERR/E1.4a: standalone try sema + pure-failable propagation + named widening
`try f()` (standalone form) now propagates a failable callee's error to the
enclosing failable function. E1.4 was split: E1.4a = standalone try (failure
target = function-propagation); E1.4b = fallback-target routing +
failable-`or` + whole-program SCC for inferred sets + empty-inferred warning.

- lowerExpr: `.try_expr` -> lowerTry
- lowerTry: (1) try legal only inside a failable fn; (2) the sole
  failable-operand check (errorChannelOf(inferExprType(operand))); (3)
  named-caller widening (checkErrorSetSubset at the propagation site); (4)
  pure-failable lowering — condBr on tag != 0: propagate (run defers + ret
  the widened tag) vs continue on success
- inferExprType: `.try_expr` arm (success type: void for pure-failable)
- lowerBinaryOp .or_op: bail loudly on a failable LHS (exprIsFailable);
  the optional-`or` path is unchanged for non-failable LHS
- value-carrying callee/caller `try` bail loudly (pending E2's tuple ABI)

Tests: examples/221-try.sx (positive propagation, exit 5),
examples/222-try-rejections.sx (3 stable rejections: outside-failable,
non-failable operand, named-widening miss; exit 1). Gates: zig build,
zig build test, 260/260 examples.
2026-05-31 19:47:19 +03:00
agra
9984fa6b96 ERR/E1.3: raise sema + pure-failable lowering
`raise EXPR` now terminates a failable function via the error channel.
Scope (Option 2): full raise sema checks + lowering for the pure-failable
shape (`-> !` / `-> !Named`); the value-carrying `-> (T..., !)` shape bails
loudly, deferred to E2's error-channel tuple ABI.

- lowerStmt + tryLowerAsExpr: `.raise_stmt` -> lowerRaise (also routes a
  raise that is a block's last statement, which previously hit unknown_expr)
- lowerRaise: failable-context check (effectiveReturnType + errorChannelOf);
  literal membership via lowerErrorTagLiteral; variable form subset-checked
  via checkErrorSetSubset; pure-failable emits ret(tag)
- lowerErrorTagLiteral skips membership for the bare-`!` inferred placeholder
- plain `return;` in a pure-failable fn emits ret(0) (success / no error)
- parser: in_defer_body flag rejects `raise` inside a `defer` body

Tests: examples/219-raise.sx (positive, exit 8),
examples/220-raise-rejections.sx (3 sema rejections, exit 1), inline parser
test for raise-in-defer. Gates: zig build, zig build test, 258/258 examples.
2026-05-31 19:09:32 +03:00
agra
f5974e5846 ERR/E1.1 (slice 2): error.X value lowering + enum-like == typing
Completes E1.1. All in ir/lower.zig (the IR layer, per slice 1's finding).

- lowerFieldAccess intercepts `error.X` (parsed as field_access(identifier
  "error", X)) → lowerErrorTagLiteral: interns the tag; when target_type is a
  named error set, types the value as that set and validates X ∈ set (out-of-set
  → diagnostic); otherwise emits the raw u32 global tag id (the spec's
  context-free default — not a silent guess).
- tryLowerErrorSetEquality (early branch in lowerBinaryOp) + errorSetTypeOf /
  isErrorTagLiteralNode: an error-set value or `error.X` literal forces the other
  operand to be one too, else a diagnostic ("compares only with an error.X tag or
  another error-set value; coerce with `xx`"). Both sides lower under the set type
  as context (error.X resolves + membership-checks); two bare tag literals with no
  context compare as global u32 ids. Handles both operand orders.

First ERR examples (end-to-end): 217-error-sets.sx (declared set + error.X +
== true/false + u32 coercion → "error-set result: 25", exit 25) and
218-error-set-typing.sx (out-of-set literal + tag-vs-raw-int → 2 diagnostics).

Failable `!`/`!Named` signatures and raise/try/catch/onfail semantics remain
(E1.2+). zig build, zig build test, and 256/256 examples green.
2026-05-31 17:59:47 +03:00
agra
14d1d9d3a8 lower: generalise the *T-where-T-expected diagnostic to any pointer
The check only caught `for xs: (*m)` loop captures; passing a `*T`
parameter or any pointer local where `T` is expected still slipped through
to the LLVM verifier. Key the diagnostic on the lowered argument's type
instead of the capture, so a `*Move` parameter forwarded into a by-value
parameter is reported the same way. Ref-capture wording is preserved.

Add example 216 (pointer-parameter case) alongside 215 (loop capture).
2026-05-31 14:17:25 +03:00
agra
39d51fc26d lower: diagnose passing a by-ref loop capture where a value is expected
`for xs: (*m)` binds `m` to a `*T`. Passing it directly to a parameter
that wants `T` produced invalid IR that only LLVM's verifier caught, with
the opaque 'Call parameter type does not match function signature'. Detect
it at the call site and emit a clear error with a fix-it suggesting `m.*`.

Add example 215 + expected output as a regression test.
2026-05-31 13:56:45 +03:00
agra
5c9d8c23ca lang: for-loop over List(T); deref a *T method receiver
The collection for-loop now iterates a List(T)-like struct ({ items: [*]T, len, … }) — and a *List — by viewing it as items[0..len]. So 'for legal: (m)' / 'for pieces: (*p)' work like iterating a slice, with by-ref captures writing back into the backing.

fixupMethodReceiver also derefs a *T receiver when the method takes T by value, so a 'for xs: (*x)' capture can call value-self methods (x.method()). Regression: examples/for-list.sx.
2026-05-31 11:13:57 +03:00
agra
6b5edc77b4 lang: require ':' before a for-loop range cursor
The cursor clause now matches the collection form's ': (capture)' — 'for 0..N: (i)' instead of 'for 0..N (i)'. The colon is required when a cursor is present; the no-cursor form 'for 0..N { }' is unchanged. Updated examples/200, the pack-index doc comment, and the spec.
2026-05-31 10:57:21 +03:00
agra
185df9afb7 lang: for-loop by-ref element capture (for xs: (*x))
(*x) binds x to a pointer into the collection (index_gep) instead of a per-element value copy: passing it on (e.g. to a *T param) is zero-copy and mutations write back. In a value position x auto-derefs — a binary-op operand loads the element, a pointer-typed slot keeps the pointer, and an 'if x == {...}' match derefs the pointee for its tag/payload. Arrays GEP through their storage so writes hit the original. Regression test: examples/for-by-ref-capture.sx.
2026-05-31 10:29:16 +03:00
agra
29a4891374 imports: dedup flat decl list by node identity (issue 0056 FIXED)
Impl blocks are anonymous (no declName), so a parameterised-protocol impl in a module reached via a diamond import was appended once per path and registered twice — 'duplicate impl Into for source s64'. mergeFlat and the directory-import merge loop now also dedup by node pointer; a physical AST node is lowered once regardless of how many import paths reach it.

Regression: examples/issue-0056-diamond-param-impl.sx.
2026-05-30 17:36:35 +03:00
agra
ac7f1d10e5 lang: extend operand-type check to ordering + bitwise/shift (issue 0055 follow-up)
The arithmetic-only check from the previous commit shared a hole with the
comparison and bitwise/shift ops: lowerBinaryOp derives the result type
from the LHS, so `s64 < string` fed mismatched types to `icmp` (LLVM
verifier failure) and `s64 & string` reinterpreted the string's bytes.

Add isOrderingOperand (numeric / enum / pointer / bool / vector) and
isBitwiseOperand (integer / enum / bool / vector), and route `< <= > >=`
and `& | ^ << >>` through them alongside the existing arithmetic check, all
sharing one diagnostic + placeholder-sentinel path. Flags-enum bitwise
(`.read | .write`, `perm & .read`), enum/pointer comparison, and int
literals stay legal (50-smoke unaffected).

Equality `== / !=` is deliberately left unchecked — its path is heavily
special-cased (str_eq, Any unbox, optional == null); folding a check in
without regressing those is a separate change, noted in the issue.

Regression test renamed arith→binop and broadened to cover `+ * < & <<`
against a string operand: examples/214-binop-operand-type-check.sx.
2026-05-30 10:30:57 +03:00
agra
6016b08712 lang: reject mismatched operand types in scalar arithmetic (issue 0055)
lowerBinaryOp derived the result type from the LHS alone and emitted
add/sub/mul/div/mod without checking the RHS, so `s64 + string` lowered
as `add : s64` and reinterpreted the string's bytes — printing garbage
instead of erroring.

Add isArithOperand (int / float / vector / pointer, plus custom int
widths) and, for `+ - * / %`, diagnose `cannot apply '<op>' to operands
of type '<lhs>' and '<rhs>'` and return a placeholder sentinel instead of
the corrupting op. `.unresolved` operands pass through so a type we
couldn't infer is never falsely rejected; the existing optional-unwrap
and int×float promotion are accounted for before the check.

Ordering (`< <= > >=`) and bitwise/shift (`& | ^ << >>`) ops share the
same LHS-derived-type hole and are left as a noted follow-up in the issue.

Regression: examples/214-arith-operand-type-check.sx (s64 + string, and
non-numeric LHS string * s64).
2026-05-30 09:56:32 +03:00
agra
8e74e4acb2 lang F1 Phase 6: canonical heterogeneous map — $R inference through closure params
The full canonical `map` now compiles and runs (examples/213 → 42):

    map :: (mapper: Closure(..sources.T) -> $R, ..sources: VL) -> VL($R)

Final piece: infer a pack-fn's generic return `$R` from a closure-typed
prefix param's lowered return type.

- collectGenericNames descends into closure_type_expr (params + return),
  so `$R` in `Closure(..) -> $R` registers as a function type-param.
- matchTypeParam/extractTypeParam descend into closures: `$R` is extracted
  from the lowered mapper's closure `.ret`.
- lowerPackFnCall infers type-param bindings from the lowered prefix args,
  folds them into the mangle, and threads them into monomorphizePackFn,
  which installs self.type_bindings for return-type resolution + body
  lowering (`-> VL($R)` ⇒ VL(s64); `Combined($R, ..)` ⇒ Combined(s64, ..)).

s64-elimination follow-through:

- An unbound generic `$R` resolves to `.unresolved` in resolveTypeWithBindings
  rather than fabricating an empty-struct stub (`R{}`).
- Lambda return-type inference skips an `.unresolved` target-closure ret and
  infers from the body, so the concrete return drives `$R`.
- The `.unresolved` codegen tripwire then caught a latent bug: a generic-struct
  source impl (`impl VL($R) for Combined($R, ..$Ts)`) was declaring its template
  method `Combined.get` (`-> $R`) as a standalone IR function. Fixed: a
  generic-struct source registers methods as TEMPLATES only (findable in
  fn_ast_map for per-instance monomorphization via createProtocolThunk), never
  declareFunction'd.

Feature 1 (heterogeneous variadic packs) all six phases complete.
248 examples + all unit tests green.
2026-05-30 03:46:46 +03:00
agra
1f6e27d8f2 lang F1 6: generic-struct -> parameterized-protocol erasure (issue 0054 FIXED)
Two fixes, root-caused from xx Combined -> VL(s64) trapping:
- instantiateGenericStruct binds the template name to the concrete instance
  (tb.put(tmpl.name, id)), so an impl method self: *Combined resolves self.field
  to the instance (Combined__s64_s64), not the 0-field generic stub. This was a
  general pre-existing bug: self.x on ANY generic-struct impl method failed.
- createProtocolThunk monomorphizes the template method for a generic-struct
  instance (Combined.get -> Combined__s64_s64.get with the instance bindings),
  so the erasure vtable dispatches instead of hitting an unreachable thunk.

xx c on a generic Combined now dispatches correctly (examples/212 -> 99).
247 examples + unit green.
2026-05-30 03:25:04 +03:00
agra
66c4ee168b lang F1 6: contextually type pack-fn prefix args (mapper lambda)
lowerPackFnCall lowered the runtime prefix args with no target_type, so a
lambda arg (mapper: Closure(...) -> ...) could not infer its param types.
Now set target_type to the param type while lowering each prefix arg. With
the existing value-projection call-arg spread, mapper(..sources.get) works:
the lambda is contextually typed and the projected values spread into the
call. examples/211 ((a,b)=>a+b over two sources -> 42). 246 + unit green.
2026-05-30 03:15:07 +03:00
agra
87ee3d3e65 lang F1 6: (..sources) materializes a pack into a protocol-typed tuple field
lowerTupleLiteral now coerces/erases each spliced spread element to the
contextual target tuple field type (computed even when a spread is present,
indexed by output position). New coerceOrErase: protocol target -> xx-erase
via buildProtocolErasure, else coerceToType. So c.sources = (..sources) on a
(..VL(Ts)) field erases each concrete pack element to its VL(Ti) slot.

examples/210 (build(IntCell, StrCell) -> 10 hi). 245 examples + unit green.
2026-05-30 03:11:55 +03:00
agra
e395a08331 lang F1 6: pack-spread in parameterized-type args (Combined($R, ..sources.T))
Parser now accepts a `..` spread in a parameterized-type arg list; in
instantiateGenericStruct a spread arg bound to the variadic type-param expands
via packTypeElems (so `..sources.T` projects each source pack element protocol
type-arg into ..$Ts). `Combined(s64, ..sources.T)` for a VL(s64) source
instantiates Combined(s64, s64). examples/209 (with explicit per-element xx
erase). 244 examples + unit green.

Next: (..sources) whole-pack materialization with per-element erasure into the
protocol-typed field (c.sources = (..sources) currently segfaults).
2026-05-30 03:06:03 +03:00
agra
39d77ff886 lang: tuple element assignment + named-tuple field names
Two fixes:
- Element assignment `t.0 = v` (the known Phase-4.2 gap): the lvalue path
  looked the element up by NAME via getStructFields, never matched a tuple
  (positional), and left field_ty .unresolved -> ptr(.unresolved) -> codegen
  panic. Added a tuple branch to the field-assignment lowering that indexes by
  position (numeric) or name (tup.names), mirroring the read path. Fixes
  `c.sources.0 = v` on a generic-instance pack field too.
- Named tuples: the parser dropped captured field names for a tuple TYPE
  `(x: T, y: U)` (passed field_names=null), and resolveTupleTypeWithBindings
  also nulled them. Both now preserve names (synthesizing _<i> for any unnamed
  slot), so `t.x` reads/writes by name and `.0` by position.

examples/208. 243 examples + unit green.
2026-05-30 03:00:58 +03:00
agra
a922814ba3 lang F1 4.2: (..F(Ts)) per-element type application in pack-shaped fields
packTypeElems now handles a parameterized spread operand F(Ts): for each pack
element T_i it temporarily binds the pack name to T_i and resolves F(T_i),
yielding (VL(T0), VL(T1), ...). Combined with parameterized-protocol value
types, the canonical Combined struct field sources: (..VL(Ts)) now resolves to
a tuple of real protocol values.

End-to-end (examples/207): instantiate Combined(s64, s64, string), whole-store
c.sources = (xx IntCell, xx StrCell), and per-element dispatch c.sources.0.get()
/ c.sources.1.get() all work. 242 examples + unit green.
2026-05-30 02:45:46 +03:00
agra
2f27f93bcf lang F1 4.2: parameterized protocol as a runtime value type
VL(s64) used as a value/field type resolved to a 0-field stub (size 0); a
plain protocol was already a 16-byte {ctx,vtable} value. New
instantiateParamProtocol materializes a parameterized protocol per
instantiation: a 16-byte protocol value (is_protocol), protocol_decl_map
methods resolved under the type-arg binding (get -> T becomes get -> s64 for
VL(s64)), a vtable struct, and the type-arg binding recorded for projection.
Hooked into resolveParameterizedWithBindings before the empty-struct fallback.

xx-erasing a conforming struct into VL(s64)/VL(string) + method dispatch now
works (examples/206). This is the keystone for the canonical Combined field
(..VL(Ts)). 241 examples + unit green.
2026-05-30 02:41:01 +03:00
agra
b48766d153 lang F1 4.2 (core): generic struct pack type-param + (..$Ts) tuple field
A generic struct can take a pack type-param ..$Ts: []Type that binds the
remaining type args as a sequence, and a pack-shaped tuple field (..$Ts)
resolves to a tuple of those per-position types.

- parser/ast: accept a leading .. on a struct generic param; StructTypeParam
  gains is_variadic.
- registration: TemplateParam carries is_variadic (and is a type param).
- instantiateGenericStruct: a variadic type-param consumes the remaining args
  into pack_bindings + pack_arg_types (mangled into the name); restored after.
- resolveTypeWithBindings: a tuple-literal-as-type containing a pack spread
  (e.g. (..$Ts)) expands via packTypeElems.

Instantiate + correct per-position field types + whole-tuple store + element
read all work (examples/205). Not yet: protocol-applied field (..F(Ts)) (the
canonical (..VL(Ts)) shape) and nested element assignment b.pair.0 = v.
240 examples + unit green.
2026-05-30 02:30:49 +03:00
agra
82b46bc412 lang: xx <pack> materializes a comptime pack into a runtime slice (issue 0053)
xx args with a slice target now bridges a comptime pack to a runtime slice:
[]Any boxes each element to Any; []P xx-erases each to the protocol (reusing
the slice-of-protocol erasure from 0052). New lowerPackToSlice; the unary-op
arm intercepts xx <pack> before the pack-as-value diagnostic. This is the
working forward to a runtime []Any/[]P helper -- log_count(xx args) -> 3 --
so the 2.7 pack-as-value diagnostics now suggest xx <name> for the call case.

examples/204-pack-xx-to-slice.sx (both []Any and []P paths); 203 help text
updated. issue 0053 FIXED. 239 examples + unit green.
2026-05-30 02:17:55 +03:00
agra
8a875d354c lang F1 2.7: pack-as-value diagnostics (Phase 2 complete)
Using a bare pack name where a runtime value is required was silent garbage
(f(xs)/return xs produced a stray pointer). Now a clear, context-tailored
compile error: isPackName + diagPackAsValue, caught at lowerVarDecl (storage),
lowerReturn (return), lowerFor (iterate), and an identifier-arm catch-all for
call/other. Storage binds a placeholder so there is no cascade error.

Suggestions point at WORKING fixes -- materialize (..xs), or declare the slice
form ..xs: []P for runtime use. The plan category-B "spread ..xs" is broken
(spreading a comptime pack into a []Any param crashes the LLVM verifier; filed
issue 0053), so the diagnostics steer to the slice-of-protocol variadic instead.

Repurposed examples/162-pack-bare-args.sx (was an aspirational bare-$args->[]Any
auto-materialise, contradicting Decision 1) into the slice-form forward
(..args: []Any). examples/203 is the four-category negative test. specs.md "Pack
as value" updated. 238 examples + unit green.
2026-05-30 02:09:41 +03:00
agra
ab572359ae lang: slice-of-protocol variadic ..xs: []P erases each arg to the protocol
packVariadicCallArgs stored the raw concrete arg into a [N x P] array when the
element type was a protocol, so an 8-byte struct landed in a 16-byte {ctx,
vtable} slot -> garbage vtable -> Bus error on dispatch. Now, when the slice
element type is a protocol, each arg is xx-erased to the protocol value via
buildProtocolErasure (same impl-driven machinery as the xx cast). This makes
..xs: []P the runtime, protocol-erased counterpart to the comptime
heterogeneous pack ..xs: P (which stays comptime-only): xs[runtime_i].method()
now works in an ordinary loop.

specs.md: full variadic/pack form-comparison table (concrete-vs-erased,
comptime-vs-runtime). Regression: examples/202. Issue 0052 (FIXED). 237 green.
2026-05-30 01:50:29 +03:00
agra
82bdcd634a lang F1 2.6: pack-index edge cases (runtime-index error, comptime OOB)
Per locked Decision 1 a pack is comptime-only with no runtime value, so xs[i]
is valid only for a comptime index. lowerIndexExpr now emits a clear error
("pack <p> must be indexed by a compile-time constant ...") for a runtime
index, instead of the confusing "unresolved <p>" the slice-index fall-through
produced. diagPackIndexOOB switched from int-literal-only to comptimeIndexOf so
an inline-for cursor that goes out of bounds is also caught.

Repurposed examples/163-pack-runtime-index.sx (was aspirational: expected
runtime indexing to materialise a []Any slice and print 4, contradicting
Decision 1) into the runtime-index error test. Comptime + OOB cases already
covered by examples/199/200/161. 236 examples + unit green.
2026-05-30 01:30:11 +03:00
agra
5fd513466f lang F1 2.5: contextual typing for multi-param closure literals
An untyped lambda (a, b, c) => ... now takes each param's type
positionally from the expected Closure(T0, T1, T2) -> R signature, for
heterogeneous param types, in both assignment and argument position.

Previously only the first param (or all-same-typed params) resolved:
lowerLambda's signature loop applied contextual typing into params, but
the return-type-inference temp scope and the body param binding both
re-resolved each param via resolveParamType -- which defaults an untyped
(inferred_type) param to s64. So b in Closure(s64, string) bound as s64
and b.len errored. Both sites now read the already-resolved signature
types params.items[user_param_base + i].ty (user_param_base skips the
pre-populated ctx/env slots).

Regression: examples/201-closure-contextual-params.sx.

Note: a generic return $R inferred through a closure-typed parameter is
still unresolved (folds into Phase 4 function monomorphization); concrete
returns work.
2026-05-29 22:00:42 +03:00
agra
27c88d4d26 lang F1: range-based for + inline-for unroll over packs
Add range loop syntax:
- runtime  for start..end (i) { }   counting loop, cursor optional, end exclusive
- comptime inline for start..end (i) { }   comptime-unrolled body

The inline form binds the cursor as an int_val comptime constant per
iteration, so xs[i] over a heterogeneous pack substitutes the concrete
per-position element -- the canonical's pack-iteration vehicle
(inline for 0..sources.len (i) { sources[i].addListener(...) }).

- AST: ForExpr.range_end, ForExpr.is_inline
- parser: parseForExpr range vs collection form; suppress_call flag so
  N (i) is not read as a call N(i) while parsing a range bound
- lower: lowerRuntimeRangeFor / lowerInlineRangeFor; evalComptimeInt;
  comptimeIndexOf extends pack-index resolution beyond int literals

Revises spec's inline for i in 0..N to the no-in, range-first, paren-cursor
form. Regression: examples/200-for-range.sx.
2026-05-29 21:36:17 +03:00
agra
27fd5e1e6a lang 2.3: TYPE-position pack projection xs.T (tuple type + closure sig)
`xs.T` projects each pack element's protocol type-arg into a type list, usable
in TYPE/signature positions:
- tuple type `(..xs.T)` → e.g. `(s64, string)` (new resolveTupleTypeWithBindings)
- closure sig `Closure(..xs.T) -> R` → e.g. `Closure(s64, s64) -> s64`, which
  contextually types a closure literal (resolveClosureTypeWithBindings now
  expands a protocol pack via packTypeArgs).

Wired `tuple_type_expr` into `resolveTypeWithBindings` (type_bridge's tuple
resolver is stateless — can't see packs). `packTypeArgs(pack_name, projection)`
is shared: bare `..xs` → element types (`pack_arg_types`); `..xs.T` → each
element's `impl Box(args) for elem` target_arg (`elementProtocolTypeArg` scans
`param_impl_map`). In type position `xs.T` parses as a dotted `type_expr`, so
packTypeElems splits on '.'. examples/199-pack-type-projection.sx.

This completes 2.3's core: all spread/projection forms — call-arg, tuple value,
tuple type, closure sig — now lower. The canonical's `Closure(..sources.T)` /
`mapper(..sources.value)` / `(..sources)` shapes are functional.
2026-05-29 20:39:57 +03:00
agra
72731f97ee lang 2.3: tuple materialization from a pack — (..xs) / (..xs.method)
A `spread_expr` element inside a tuple literal now expands the pack into the
tuple's fields: `(..xs.get)` ≈ `(xs[0].get(), …, xs[N-1].get())` (Decision 2 —
a pack is stored by materializing a tuple). lowerTupleLiteral detects a
pack-spread element via packSpreadRefs and splices the per-element Refs as
fields (typed via getRefType); for Box(T) the materialized tuple is
heterogeneous. A spread whose operand isn't a pack falls through to the
existing spread_expr diagnostic (tuple-value spread not yet handled).

When any element is a spread, field-count ≠ element-count, so the contextual
target-tuple alignment is skipped (field types inferred from the expanded refs).
examples/198-pack-tuple-materialize.sx.
2026-05-29 20:07:41 +03:00
agra
d7ecf02d7a lang 2.3: pack spread into call args (f(..xs) / f(..xs.value))
A pack spread in call-arg position now expands to N positional args:
`add2(..xs.get)` ≈ `add2(xs[0].get(), xs[1].get())` — the canonical's
`mapper(..sources.value)` shape. The call-arg loop detects a spread whose
operand is a pack (`..xs`) or a pack projection (`..xs.method`) and splices the
per-element Refs in; a runtime-slice spread (`..arr`) is still left to the
slice-variadic path.

Factored the per-element synthesis out of lowerPackValueProjection into
`lowerPackElems` (used by both projection-to-tuple and spread-to-args), plus a
`packSpreadRefs` helper. examples/197-pack-spread-call.sx (2- and 3-arg, mixed
element types).
2026-05-29 19:53:04 +03:00
agra
c03db7938c lang 2.4: value-position pack projection xs.value + mixed-tuple type fix
`xs.<method>` over a constrained pack projects a (zero-arg) protocol method
across every element into a tuple: `xs.get` ≈ `(xs[0].get(), …, xs[N-1].get())`.
lowerFieldAccess intercepts `xs.<m>` on a pack base (where <m> is a protocol
method) and synthesizes/lowers `xs[i].<m>()` per element into a tuple_init.
For a parameterised `Box(T)` the projected tuple is heterogeneous (each element
returns its own T). examples/196-pack-value-projection.sx.

Surfaced and fixed a pre-existing bug: inferExprType didn't handle tuple field
access (`t.0` / `t.x`), so a mixed-size tuple like `(42, "hi")` inferred the
string field as s64 — the wrong type then drove a bad `print` pack mangle and
coerced the string to i64 (garbage). Added the tuple arm (numeric + named).
Regression: a `(s64, string)` case in examples/190-tuple-values.sx.
2026-05-29 19:45:49 +03:00
agra
19bc644b11 lang 2.4: enforce interface-only access on pack elements
A protocol-constrained pack element exposes only the constraint protocol's
interface (the locked decision): `xs[i].<member>` is rejected unless `<member>`
is one of the protocol's methods. `xs[i].v` (a concrete field of IntCell, not
declared on Box) now errors, like a constrained generic — even though the
substituted element is concretely an IntCell.

monomorphizePackFn records the pack param's constraint protocol in a new
`pack_constraint` map (pack-name → protocol); lowerFieldAccess checks it on an
`xs[i]` (index_expr) base BEFORE substitution erases the "constrained to P"
context. Protocol method calls (`xs[i].get()`) pass — the name is in the
protocol. Regression: examples/195-pack-interface-only.sx.
2026-05-29 19:34:03 +03:00
agra
e604868ffb lang 2.4: parameterized-protocol method calls on pack elements
`xs[i].get()` on a parameterised `..xs: Box(T)` pack now resolves — the
canonical `ValueListenable` shape. registerParamImpl, for a CONCRETE-struct
source, now also registers the impl's methods as `<Source>.<method>` in
fn_ast_map (like a non-parameterised impl), so UFCS finds them. Such methods
are already fully concrete (`impl Box(s64) for IntCell` → `get(self: *IntCell)
-> s64`), so there's nothing to monomorphize; generic/pack sources stay lazy in
param_impl_map. First impl wins on a name collision.

Heterogeneous parameterised packs work: each `xs[i]` binds a different T and
dispatches to its own impl. Regression:
examples/194-protocol-pack-parameterized.sx (Box(s64) IntCell + Box(string)
StrCell, order-independent).
2026-05-29 19:24:06 +03:00
agra
a67627a691 lang 2.4: protocol-interface method calls on pack elements + conformance fix
Calling a protocol method on a pack element now works: `xs[i].greet()` on a
`..xs: Greeter` pack dispatches to the concrete element's impl, and elements
may be heterogeneous (Dog, Cat). This is the protocol-interface access the
pack is for. (Protocol method decls omit the implicit `self`; impls list it —
the earlier malformed `(self: *Self)` decls were why dispatch looked broken.)

Also fixes packArgConformsTo for non-parameterised protocols: it queried
`protocol_thunk_map`, which is only populated lazily when a protocol VALUE is
built with `xx`, so it false-negatived valid conformers. Now it queries
impl-declaration state directly — `param_impl_map` for parameterised protocols,
or `<ty>.<method>` entries in `fn_ast_map` for non-parameterised ones.

examples/193-protocol-pack-methods.sx (heterogeneous Dog+Cat pack, per-element
greet(), order-independent).
2026-05-29 18:53:32 +03:00
agra
fc4d239fdd lang 2.4: enforce protocol-pack conformance per position
Each argument bound to a `..xs: P` pack must conform to P — previously the
constraint was decorative (any type was accepted). `lowerPackFnCall` now
captures the pack param's constraint protocol and checks each pack arg via a
new `packArgConformsTo`, which accepts: a plain-protocol impl
(`protocol_thunk_map`), any parameterised impl `P(<args>) for T` (scan of
`param_impl_map` for a `P\x00…\x00mangle(T)` key — the per-element type-args
are inferred from the impl, not written out), or an arg already erased to P's
own protocol struct. Non-conformers get a per-position error pointing at the
argument. Only enforced for a known protocol constraint.

Regression: examples/192-pack-non-conform.sx (a struct lacking `impl Show` in a
`..xs: Show` pack → diagnostic, exit 1).
2026-05-29 18:01:48 +03:00
agra
934585ac74 lang 2.4: lock protocol-pack access semantics (interface-only)
Design decision: a protocol-constrained pack element is viewed THROUGH the
constraint protocol — only the protocol's interface (its methods, and the
projections xs.T / xs.value) is accessible, not arbitrary concrete members,
exactly like a constrained generic `T: Show`. So `xs[i].v` (a field on the
concrete IntBox, not declared on Show) is an error; the constraint is enforced
and bounds the body regardless of the concrete arg types at a call site.

The previous example 191 demonstrated `xs[i].v` — which only compiled because
the constraint is not yet enforced. Trimmed it to the protocol-agnostic part
that's correct today (per-shape binding + comptime `xs.len` across arities /
heterogeneous shapes); protocol-interface access + projection are the remaining
2.4 work. specs.md records the access rule.
2026-05-29 17:55:11 +03:00
agra
0b8e947736 lang 2.4: bind protocol-constrained packs (per-shape mono, concrete elements)
`..xs: Protocol` now binds like the comptime `..$args` pack instead of
falling through to a runtime `[]Protocol` slice: each call site
monomorphizes with the concrete per-position arg types, and `xs[i]` is the
concrete element via AST substitution (Decision 1 — a pack is a comptime
mechanism, no runtime pack value). So `xs[i]`'s own fields/methods dispatch
statically and elements may be heterogeneous, while `xs.len` is a comptime
constant.

Mechanism: one `isPackParam(p) = is_variadic and (is_comptime or is_pack)`
predicate replaces the four `is_variadic and is_comptime` pack-detection
sites (call-arg split, mangle, arg lowering, monomorphizePackFn), and the
early call dispatch routes any `isPackFn` call to `lowerPackFnCall` before
the `hasComptimeParams` gate (which is false for a protocol pack).

examples/191-protocol-pack.sx exercises N=0, N=2, concrete field access, and
a heterogeneous IntBox+StrBox pack. Conformance checking and projection
(`xs.T` / `xs.value`) are the remaining 2.4 work.
2026-05-29 17:45:22 +03:00
agra
98526ab9b4 lang 1.2: parse pack-expansion forms in all four positions
Pack/tuple spread now parses in tuple-value `(..xs)` / `(..xs.field)`,
tuple-type `(..F(Ts))` / `(..F(Ts.Arg))`, call-arg `f(..xs)` (already),
and closure-sig `Closure(..Ts)` / `Closure(..sources.T)` positions.

Design: the uniform spread node is the existing `spread_expr` (its
operand sub-expression carries the projection `xs.field` and
type-application `F(Ts)` shapes) rather than a new PackExpansion node —
call-arg slice-spread (`..arr`) and pack-spread (`..pack`) are
syntactically identical, so they must share one node, and spread_expr
already serves it with working slice lowering. Closure-sig packs gain
`ClosureTypeExpr.pack_projection` alongside the existing `pack_name`.

Parser-only; sema/lowering land in Phase 2. 6 new parser unit tests +
examples/probes/pack-expansion-parses.sx. Build + 225-suite green.
2026-05-29 12:33:27 +03:00
agra
87f739cef2 lang 1.1: parse pack-constrained variadic parameter
`..xs: Protocol` (a bare protocol, no `[]`, no `$`) on a variadic
parameter now parses to `ast.Param.is_pack = true` — a heterogeneous
protocol-constrained pack, distinct from a slice variadic
(`..xs: []T`, is_pack=false) and the comptime type-pack (`..$args`,
is_comptime=true). Parser-only: sema/lowering for the pack form land in
Phase 2; existing forms are unaffected (zero examples used a bare
non-slice variadic annotation). Adds three parser unit tests and
examples/probes/pack-param-parses.sx.
2026-05-29 12:15:50 +03:00
agra
9618f99d0d ir: fix tuple literal element widths (construction was garbage)
A tuple_init's element values must match its field types exactly — LLVM
`insertvalue` does no implicit conversion. An inferred `pair := (40, 2)`
lowered its elements under the enclosing fn's `target_type` (e.g. main's
s32 return), producing i32 values, while the field types were inferred
independently as s64. The {i64,i64} aggregate was filled with i32
constants, so reading any element back returned garbage (40 + 2^32) and
tuple equality was always false.

lowerTupleLiteral now lowers each element under its resolved field type
(the contextual target tuple's fields when present, else per-element
inference) and coerces to it, so value width always matches field width.
Assignment to a tuple-typed field/element now also propagates the target
tuple type. Adds examples/190-tuple-values.sx as a regression test and
examples/probes/tuple-baseline.sx as the Step 0.4 audit artifact.
2026-05-29 11:52:28 +03:00
agra
6d258ad82b ffi M1.2 A.1 follow-up: struct args/returns in Obj-C type encoding
`appendObjcEncoding` previously bailed on `.@"struct"`, which blocked
sx-defined `#objc_class` methods from declaring CGPoint / CGRect /
NSRange-shape signatures — the `class_addMethod` registration path
would emit a "type kind not yet supported by Obj-C encoding"
diagnostic. The helper now emits Apple's `{Name=field0field1...}`
form recursively, with a small `ObjcEncodingStack` (cap 16) that
breaks transitive struct→struct cycles by emitting the abbreviated
`{Name}` form instead of recursing forever.

`{Point=dd}`, `{_NSRange=QQ}`, `{CGRect={CGPoint=dd}{CGSize=dd}}`
all flow through the existing `objc_msg_send` + `class_addMethod`
path with no further plumbing.

Tests:
- `lower.test.zig` gains four cases: optional unwrap (single + nested),
  flat struct (CGPoint, NSRange shape), nested struct (CGRect with
  CGPoint+CGSize), bringing the helper's test coverage from
  primitives + pointers to the full encoding table.
- `examples/ffi-objc-defined-class-02-struct-encoding.sx` exercises
  a sx-defined `SxMover` class with `goto(p: Point)` setter and
  `here() -> Point` getter end-to-end on macOS; the IR snapshot
  confirms `v@:{Point=dd}` and `{Point=dd}@:` land in
  `OBJC_METH_VAR_TYPE_` constants wired to `class_addMethod`.

Checkpoint cleanup: the "Next step (M1.2 A.1 — type-encoding
derivation table)" header in CHECKPOINT-FFI.md was stale (A.1
shipped in 6cc016c; A.0–A.7 all done; commit list now linked).
The encoding table stays as reference material.

224/224 example tests pass; zig build test green.
2026-05-28 14:24:02 +03:00
agra
3ac13b7442 ir: Type as first-class value (Any-shaped {tag, value})
Previously, `t : Type = f64` stored a boxed string carrying the literal
name "f64"; comparisons and `type_of`/`type_name` round-trips lost the
underlying TypeId. This switches `Type` to a runtime-representable Any
pair: `{ tag = .any.index() (meta-marker), value = TypeId.index() }`.

Mechanism:
- `const_type` emits a 16-byte Any aggregate via insertvalue.
- `TypeId.any` advertises 16 bytes / 8-byte alignment so structs that
  embed `t: Type` size correctly under verifySizes.
- `lowerBinaryOp` folds `==`/`!=` between static type-refs to a
  `const_bool`, and decomposes runtime Any-vs-Any compares via
  `unbox_any` so LLVM doesn't see icmp on aggregates.
- `lowerMatch`'s `is_type_match` path unboxes Any-typed subjects to
  the i64 type tag before the switch, so `case type:` etc. fire.
- `lowerRuntimeDispatchCall` (used by `case T: ... cast(t) val`) does
  the same unbox for the type-tag arg.
- `type_of(val: Any)` rebuilds an Any with `{.any, tag_of(val)}` so
  the result is itself a `Type` value, not a bare i64.
- `buildPackSliceValue` stops re-boxing const_type — the value is
  already canonical Any.
- `__sx_type_names` now indexes by TypeId across the whole table
  using the new `types.formatTypeName` (structural names for `*T`,
  `[]T`, `[N]T`, `?T`, `Vector(N,T)`, function/closure/tuple) so
  runtime `type_name(t)` works for compound types.
- `interp.zig`'s comptime `type_name` accepts either the bare
  `.type_tag` Value or the Any-boxed aggregate it now sees.
- `scanDecls` registers `Vec4 :: Vector(4, f32)` style aliases in
  `type_alias_map` (before the `fn_ast_map` check; `Vector` IS a
  `#builtin` fn). Lets `Vec4` in expression position lower as
  `const_type(<vector tid>)`.
- `isStaticTypeArg` becomes scope-aware: a name shadowed by a runtime
  local is not static. `isStaticTypeRef` is the symmetric helper for
  the eq fold.
- `inferExprType` returns `.any` for bare type names (identifier and
  type_expr) so pack arg types are correct.

Side effect: `print("{}", Vec4)` now prints the structural name
`Vector(4,f32)` rather than the alias literal `Vec4` — 12-meta's
expectation updated. Aliases stay pointer-equal to their target
(`Vec4 == Vector(4, f32)` is true).

Tests:
- examples/189-type-all-interactions.sx: 12-section comprehensive
  coverage — literal `==`, `type_of(value) == T`, `Type` var storage,
  `type_name` (static + runtime), printing Type values, generic
  dispatch via `$T: Type`, `identity($T, val)`, `Wrap($T)`, reflection
  builtins (`size_of`, `align_of`, `field_count`, `type_eq`),
  `..$args` pack walking, `Type` in struct field, compound type
  literals (`*Point`, `[4]s32`, `[]bool`, `?f64`).
- examples/12-meta.sx: expected output updated to reflect structural
  name for the Vec4 alias path.
- ffi-objc-call-06-sret-return.ir: regenerated to absorb the new
  type-name strings now emitted globally.

223/223 examples pass.
2026-05-28 14:02:10 +03:00
agra
9e76a83f69 ffi block-string-arg ABI mismatch — expected-failing lock-in
Generic `Into(Block) for Closure(string) -> void` (step 5.2) emits
a trampoline whose `callconv(.c)` param type collapses through
`abiCoerceParamType`'s `string → ptr` heuristic — the libc
"char *" convention. The caller side (typed fn-pointer cast +
indirect call through `b.invoke`) keeps the full `{ptr, i64}`
slice. Result on AArch64: caller passes 16 bytes in x0+x1,
trampoline reads 8 bytes from x0 only, the slice len is lost or
mis-tracked, and the trampoline's `memcpy` from the half-formed
string segfaults.

`examples/188-block-string-arg.sx` pins the post-fix behaviour
("got: <hello>"). Today's run segfaults inside the trampoline's
first read. The next commit splits `abiCoerceParamType` into a
foreign-only path (extern decls keep the libc collapse) and a
preserve-slice path (sx-internal `callconv(.c)`).
2026-05-28 12:24:49 +03:00
agra
82f291e5af ffi M5.A.next.4B.A: compile_error intrinsic — expected-failing lock-in
`compile_error(msg)` raises a build-time diagnostic at the call site
with `msg` as the error text. The arg must be a string literal —
runtime expressions can't be reported as compile errors. Used by
builder fns to reject malformed pack shapes / arg combinations
cleanly instead of silently emitting wrong code.

Today: `unresolved 'compile_error'`. Expected (post-fix): focused
diagnostic with the literal message at the call site's span. The
next commit adds the lowering arm.
2026-05-28 12:17:49 +03:00
agra
280c12c630 issues: promote 6 fixed bug repros to focused regression tests
All six produce their target outputs cleanly today; renamed out of
the `issue-*` namespace per CLAUDE.md "Resolving an open issue":

| Old                  | New                                       |
|----------------------|-------------------------------------------|
| issue-0032           | 181-impl-duplicate-same-file              |
| issue-0041           | 182-compound-type-in-expression           |
| issue-0042           | 183-type-alias-size-align                 |
| issue-0044           | 184-objc-defined-class-method-self        |
| issue-0045           | 185-pack-fn-comptime-return               |
| issue-0046           | 186-nested-comptime-return                |

Comment headers tightened to feature-focused (drop the issue-NNNN
provenance — that's in git history now). Missing expected `.txt` /
`.exit` files captured for 0041 + 0042 (they were untracked because
the bugs were fixed silently in adjacent work).

`examples/issue-*` after this commit: just `issue-0030.sx` — a
feature request (`extern G : T;` cross-file globals) that's never
been implemented. Staying in the issue namespace as a parked
proposal until the feature lands or gets formally rejected.

220/220 example tests + `zig build test` green.
2026-05-28 12:14:52 +03:00
agra
da6f318a3f issues 0033 + 0034: rename repros to focused regression tests
Both repros emit their target diagnostics cleanly today (verified
2026-05-28 against HEAD):

- `issue-0033` → "no visible xx conversion from 's64' to 'Wrap'
  — impl exists in another module but is not imported". Catches
  the case where an `impl Into(X) for Y` is registered globally
  via one module's import chain but is NOT transitively imported
  by the file containing the `xx` site.
- `issue-0034` → "duplicate xx conversion from 's64' to 'Wrap':
  impls in <a> and <b>". Catches two impls covering the same
  (Source, Target) pair both reachable from a single `xx` site.

Renamed to focused feature names:

- `issue-0033*` → `179-impl-visibility*` (4 files: main + impl +
  types + user).
- `issue-0034*` → `180-impl-duplicate*` (4 files: main + impl-a +
  impl-b + types).

Path references inside the files updated. Comment headers tightened
to feature-focused (drop issue-NNNN provenance — that's in git
history now). Expected `.txt` / `.exit` files captured against the
full diagnostic text and exit code 1.

The `issue-*` namespace in `examples/` now shrinks to the literal
list of UNRESOLVED bug repros. 218/218.
2026-05-28 12:08:54 +03:00
agra
54e404bca1 ffi any_to_string optional dispatch — expected-failing lock-in
`examples/178-any-to-string-optional.sx` prints a struct whose
three fields are `?s64` / `?string` / `?bool`, in both Some and
None form. The struct-print path goes through `field_value(s, i)
-> Any` and then `any_to_string(Any)`. Today: `any_to_string`
has no `case optional:` arm and `resolveTypeCategoryTags` has no
"optional" category — every optional field falls through to the
`<?>` default. Expected output captures the working post-fix
form (`a: 42`, `b: hi`, `c: true` for Some; `null` across the
board for None).

The next commit adds `optional_to_string` + `case optional:` to
std and "optional" to `resolveTypeCategoryTags`. Variadic
auto-unwrap (`packVariadicCallArgs`) keeps printing direct
`print(opt)` calls correctly today; this fix closes the gap for
struct fields, slice elements, and anywhere else an optional
flows through Any.
2026-05-28 07:50:59 +03:00