Skip to content

Enums: payload discriminants, casts, generic layouts, and fn-type compatibility (#1768 #1769 #1770 #1772 #1003) - #1811

Merged
ehartford merged 9 commits into
mainfrom
fix-enums
Sep 28, 2026
Merged

ehartford merged 9 commits into
mainfrom
fix-enums

Conversation

@ehartford

@ehartford ehartford commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Stack layer 2 of #1813 (on #1801). One commit per issue, each with a test that fails before and passes after:

@ehartford
ehartford added this pull request to stack #1813 September 27, 2026 23:34
@ehartford ehartford changed the title fix enums Enums: payload discriminants, casts, generic layouts, and fn-type compatibility (#1768 #1769 #1770 #1772 #1003) Sep 27, 2026
@ehartford
ehartford force-pushed the fix-enums branch 2 times, most recently from 3a630fd to 63be345 Compare September 28, 2026 02:24
@ehartford

Copy link
Copy Markdown
Contributor Author

Battery GREEN on the stack top 3fddbecd (#1801 → #1811 → #1812 → #1821, on main 7fd175c), driven by the new seed nightly-20260927-local-1-99939352ffda: :gate rc=0 in 651 s; :battery-checks (seed-driver, fixpoint, test-with-audits incl. drop and move audits and every test lane, user-programs-safe, last-green) rc=0 in 2563 s. Earlier reds on this stack were each fixed in the layer that caused them (run 1: six lanes; run 3: the native runner skipped the missing-input check — fixed by bea5908, bottom of #1811). Merge: gh stack merge 1821 --yes --squash.

Eric Hartford added 9 commits September 28, 2026 01:11
…orker runs it — the native runner dispatched an action whose declared input was missing, and it succeeded

run_build_action_from_build_w (the comptime path) refused an action with no
declared output, invalid process arguments, a missing declared input or an
uncreatable output directory; the scheduler's two native-runner dispatches
(pooled and serial) went straight to the runner. cli-selfhost-build-w-tests'
build_w_action_missing_input passed only by accident: its fixture action was
spelled `ctx: &ActionCtx`, which (through #1772's fn-type hole) lowered to
invalid MIR, so the runner compile failed and the build fell back to the
comptime path — the one that checks. With the fixture spelled as the action
type declares it (`ctx: ActionCtx`), the runner ran the action and the
build reported success with the input missing (red on the #1813 battery;
main's cffa4a40 does the same on that fixture).

The four checks are one function, build_action_preflight, called by the
comptime path and by the scheduler before any action runs. Verified with the
release binary on the fixture: input missing → rc=1 "missing declared
input", nothing written; input present → rc=0, output written.
…il is the body's tail, because D73 makes it a statement there and the fn returns Unit

§4.2 / D73: "An assignment in tail position is a statement"; its value is
used only in a value position, including "the tail of a body whose
declared return type is not `Unit` (D60)". Sema discarded an assignment
tail only when it was the tail of `body_tail_block`, the body block
itself, or the whole single-statement body. A body ending in a wrapper
that yields its own tail kept the place's type: `fn init_once:` whose
body is `unsafe:` + `ONCE_COUNT = ONCE_COUNT + 1` inferred `-> i32`
(`analyze ... select:stage=sema,kind=signature`: bump `return=3`, i32,
beside a bare-assignment body's `return=14`, Unit). The #1772 fn-type
check then refused `once.call_once(init_once)` against `fn() -> Unit`
(test/spec/spec_ss14_17_once.w, red in the stack's battery).

The body's tail is now found by following the wrappers D60's read side
(`record_tail_reads`) already follows — `unsafe:` / `unsafe { }`,
`no_suspend`, plain blocks, through groupings — to the innermost holder
(`body_tail_holder_of`, the new `body_tail_holder`, set for fn and closure
bodies). A one-statement `unsafe:` body is the statement itself
(Parser.parse_block_or_expr), so the holder is either a block, whose tail
check_block discards, or the wrapper, whose child the unsafe and
no_suspend arms discard (`wrapper_tail_type`). `body_tail_block` keeps its
meaning for the escape and closure-env checks. A tail `if`/`match` is not
a wrapper: its written arms keep the place's type and join (D43,
err_d43_cannot_infer_match.w). MirLower already lowers these in discard
mode: the fn is Unit and the wrappers' discard lowering reaches the
assignment as a statement.

Before (release binary of the layer's previous tip): the new behavior test
failed with "wrong argument type in call to 'call_unit' ... argument
expression 'bump' has type fn() -> i32 / parameter 'f' expects
fn() -> Unit". After: 1 2 12 12 — `fn bump:` and `fn bump_braced:`
return Unit, and `fn bump_ten() -> i32:` with the same `unsafe:` tail
still returns the read of the place (D60).

Refs #1479
…s hole)

`fn apply_void(f: fn() -> i32)` was passed `() => print(s)`, a closure
returning Unit; it compiled only because Sema compared no fn type's
result (#1772). The helper's name and use say Unit, so the parameter says
it.
…declared action type (they relied on #1772's hole)

A target's action is `action: fn(ActionCtx) -> i32` (lib/std/build.w:464),
and every real action in build.w, build/*.w and
docs/spec/toolchain/with-build.md spells `ctx: ActionCtx`. The 17 action
fixtures build/selfhost.w writes into generated build.w / actions.w files
took `ctx: &ActionCtx` — a borrow where the action type consumes, a
different passing mode — and were accepted only because Sema compared no
fn type's parameters (#1772). With the check, cli-selfhost-build-w-tests
(case build-w-action-explain) failed with "type mismatch in assignment"
at `generate_target.action = generate`. Each fixture function used as an
action (`.action = X`) now takes `ctx: ActionCtx`; the self-host helpers
(`bs_*`), which are called with a borrowed context, keep `&ActionCtx`.
…agree, because an i32 result read as i64 is garbage

`types_compatible`, `types_compatible_fast` and their frozen twins accepted
any `fn` type for any other `fn` type: the TY_FN/TY_FN branch returned
`callable_unsafe_coercion_ok`, so only unsafe-ness was compared, never the
parameters or the result (TY_EXTERN_FN already compared them through
`fn_types_compatible`). The four branches now call `fn_types_assignable`:
the §16.11 unsafe rule, the same parameter count, and each parameter and
the result identical (`types_identical`; an unresolved side, type 0, does
not decide). Identity, not `types_compatible`, because that test lets every
integer accept every integer and a fn value's result width is its ABI.

Before (stage1 of 9993935): `apply64(add1, -10)` with `add1: fn(i32) -> i32`
passed to `fn(i32) -> i64` printed 4294967287; `let f: fn(i32) -> str = add1`
passed Sema and the MIR validator reported "use rvalue type is incompatible
with assign destination (dest ty=296 kind=12, src ty=456 kind=12)".
After: "wrong argument type in call to 'apply64'" (parameter 'f' expects
fn(i32) -> i64, argument has type fn(i32) -> i32) and "type mismatch in
binding". The closure, fn-value and generic behavior tests still check.

Fixes #1772
…type at every width and signedness, because a truncated tag crashes match

SemaDecl's discriminant walk range-checked an explicit `= N` only for i8
and i16 (`repr_type_tid == self.ty_i8` / `ty_i16` with literal bounds);
every other repr let any value through, and it entered the type record
narrowed: `B = 300` in a u8 became 44 and a match on it crashed, `B = -1`
in a u32 wrapped to 4294967295 and no arm fired. The auto-incremented
discriminants were already checked through `disc_auto_next`/
`disc_fits_repr`; the explicit ones now go through the same
`disc_fits_repr(value, repr_bits, repr_signed)`, and the diagnostic names
the repr ("discriminant value 300 out of range for u8") at the literal.

Before (stage1 of 9993935): both compile-error fixtures reported `ok`.

Fixes #1003
…o cast from an enum aggregate

`MirLower.lower_cast` emitted `RK_CAST(enum -> i32)` for `R.C as i32`
(MIR `_3 = cast(copy _2 as i32)` with `_2 = aggregate(variant=2)`).
CodegenDispatch's RK_CAST arm has no enum-to-integer case: an enum with a
payload variant is an LLVM `{ i32, [N x i8] }`, the value fell to
`coerce_value_to_type`, whose last line returns it unchanged, and the
aggregate went on as the integer: `print(f"{R.C as i32}")` printed `C`,
`R.C as i32 + 1` was "Call parameter type does not match function
signature!" / INVALID LLVM FUNCTION main. Through a parameter the
place's tag load happened to be what was read.

Every value cast now goes through one `lower_value_cast`: `as` itself
and the two D22 materializations that emitted their own RK_CAST (the
contextual copy adjustment — `k as i64` with `k: &Kind` derefs and casts
there, not in lower_cast — and the join arm). For an enum source and a
number target it is the operation MIR already has: the operand is
materialized, `lower_enum_discriminant` reads the tag (RK_DISCRIMINANT,
typed by `enum_discriminant_type`: the repr — of the base enum for a
generic instance — else i32), and a cast from the tag's type follows only
when the target differs. This replaces the #1502 enum→float special case
(repr cast, then widen), which is the same read.

The validator stayed silent over the aggregate cast, so
`mir_validate_cast_supported` now refuses an RK_CAST from TY_ENUM to
TY_INT/TY_FLOAT, and "unsupported cast in MIR" names the source and
target types (the bare message needed lldb on an -O1 binary to learn
which cast it meant). With the lowering fixed none exists: src/main.w
checks, and the enum/discriminant/flags tests pass, under the new rule.

Before (stage1 of 9993935): the behavior test printed `C` and then the
invalid-LLVM dump. After: 2 3 2 7 8 1.

Fixes #1770
…ause a generic discriminant enum's payloads reached MIR unresolved

A discriminant enum's extras are `[repr, count, (name, disc, pcount,
payloads...)*]`; a plain enum's `[count, (name, pcount, payloads...)*]`.
Four SemaCheck walkers and one SemaDecl walker knew only the plain
layout and tested `sub_kind != TypeDeclKind.Enum`:

- `infer_generic_enum_variant_type_of` returned 0 ("cannot infer type
  parameter 'T' for this call" on `E.B(v) => print(v)`),
- `resolve_generic_enum_payload` returned no payload types, so the
  pattern binding's type was 0 and the MIR validator stopped codegen
  ("use rvalue does not resolve to a concrete MIR type (place local=1
  local_ty=482 projs=2 proj0_kind=3)" at the `E.B(v)` arm),
- `setup_generic_inst_substitution` and the impl-method return-type
  fallback computed tp_start/tp_count by hand and found 0 params,
- `type_decl_type_param_count` likewise.

The layout has one owner now: `type_decl_is_enum`,
`enum_decl_count_index` and `enum_decl_variant_head` in Ast.w beside
`type_decl_sub_kind`, and the type-parameter positions come from the
existing `type_decl_tp_start`/`type_decl_tp_count`, which already knew
both layouts. The parser's `@[flags]` refusal for a generic payload enum
(#1482's stopgap naming this issue) is gone with the `generic` parameter
it gated on; its fixture is now a behavior test (Slot.Gone = 4).

Before (stage1 of 9993935): the behavior test failed with the two
diagnostics above. The compiler's own sources still check.

Fixes #1768
…inant enum in the inferred i32, because a parsed value must never be dropped

`parse_enum_variants_block` parsed `= N` on every variant but, with a
payload present and no `@[flags]`, emitted the plain-enum extras, which
have no discriminant slot: `enum M: A = 5; B(i32)` was an ADT enum whose
tag was the variant index, and `M.A as i32` printed 0 with no diagnostic
(No Silent Fallbacks). The braced form did not parse `= N` at all
("expected identifier").

Both forms now record whether any variant spelled a discriminant, and
that makes the enum a discriminant enum in the inferred i32, the rule the
canon already applies to a fieldless backing-less enum (#309) and to a
backing-less `@[flags]` enum with payloads (D71 / #1482): `= N` spells
the meaning, the width is a representation default. The parser stays the
single owner of the decision (`add_backingless_enum_extras`'s `as_disc`).

The specification is silent on this case (§4.4a shows payload
discriminant enums only with a representation type). Proposed sentence
for §4.4a, put to Eric for blessing; the implementation does not wait on
it:

  "An enum with no representation type and an explicit `= N` on any
  variant is a discriminant enum in the default integer representation,
  payload variants or not."

Before (stage1 of 9993935): the behavior test printed 0 1 2; the
out-of-range fixture reported `ok`. After: 5 6 9, and `A = 3000000000`
on such an enum is "discriminant value 3000000000 out of range for i32".

Fixes #1769
@ehartford
ehartford merged commit 29f38f6 into main Sep 28, 2026
@ehartford
ehartford deleted the fix-enums branch September 28, 2026 05:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant