Skip to content

Add const where predicates - #1576

Merged
sbillig merged 76 commits into
masterfrom
pr/checked-generation-const-predicates
Oct 1, 2026
Merged

sbillig merged 76 commits into
masterfrom
pr/checked-generation-const-predicates

Conversation

@micahscopes

@micahscopes micahscopes commented Sep 22, 2026 •

Copy link
Copy Markdown
Collaborator

This lets an item state a boolean condition in its where clause, such as N > 0, and have the compiler check it wherever the item is used.

  • A where clause can hold boolean conditions next to trait bounds

    const fn bounded<const N: usize>() -> u256 where N > 0 { 42 }
    

    bounded<1>() is accepted and bounded<0>() is rejected, even though the body never reads N. On master, a where clause takes only trait bounds, so where N > 0 is a parse error.

  • A generic caller satisfies a condition by stating the same one

    const fn forward<const COUNT: usize>() -> u256 where COUNT > 0 { bounded<COUNT>() }
    

    The same holds in anonymous constants of the caller's signature and body, such as an array length.

  • Structs, enums and inherent methods take conditions too

    struct Bounded<const N: usize> where N > 0 { value: u256 }
    

    Every written use of Bounded<0> is rejected, including unused type annotations, defaults, types written inside a const parameter's default, aliases, with keys, and a type at any segment of a path, such as Bounded<0>::helper(), Bounded<0>::Out, Bounded<0>::Out::make() and the unbraced const argument in Holder<Bounded<0>::L>. An anonymous constant passed to a type, trait or alias segment of a path is checked against that segment's parameter, even when an alias drops it or it only selects an impl, as in Holder<{ dec<0>() }>::Out, and so is one written in a type parameter's default, such as struct S<T = Holder<{ dec<0>() }>::Out>. As a backstop that does not depend on listing positions, the type that inference gives each expression and the generic arguments it infers for each call are checked too, so a type that only trait solving supplies, such as U = Bounded<0> in call(Holder<0> {}) for fn call<U, T: Tr<U>>(_ x: T), is rejected at the call. For a constrained enum, unit variants such as Choice<0>::Empty and constructor values such as Choice<0>::Value are rejected too. Method conditions are checked on the method that ordinary resolution picks.

  • Inside an impl, the conditions of the types in its self type hold without restating them

    impl<const N: usize> Bounded<N> {
        fn get(self) -> u256 { self.value + bounded<N>() }
    }
    

    This covers inherent and trait impls, enums and computed arguments such as Bounded<{ M + 1 }>. It rests on the self type being checked wherever the impl is reached: an item path checks the type before :: at every segment, in types, generic arguments, expressions, patterns and with keys; a method call's receiver, and the type that trait solving matches the impl against, is the type of a checked value or a written type; and a call checks the header types it instantiates. A trait impl's trait arguments supply no conditions (see Limits). A generic type alias likewise assumes its aliased type's conditions, since each application is checked after expansion.

  • A condition without generic parameters is checked where it is declared, even if nothing uses the item, and a failure is reported there once, not again at each use

    fn unused() where false {}
    
  • A condition that needs several lines can be written as a block

    fn bounded<const N: usize>() where {
        let limit: usize = 8
        N < limit
    } {}
    
  • where T without : now parses as a condition, and type checking reports the missing trait bound. On master it is a parse error.

  • #[error] lowering errors get code prefix 13. On master they share prefix 16 with borrow-checking errors, so error[16-0003] can name two different errors.

A few decisions:

  • Forwarding is exact, not implication: after substitution the two conditions must be the same resolved expression, so N > 1 does not establish N > 0
  • A concrete condition is evaluated at compile time, and a failed evaluation is an error, never a pass
  • Conditions never select impls or methods and add no solver assumptions
  • Requirements are checked after type checking and never feed back into it. A constant's unmet requirement is reported once, where the constant is written, not at each type that uses it. Types and compile-time evaluation still see the constant's value, and the program is rejected at the constant
  • Every unmet requirement is error[8-0093], whether the use is a call or a type. A type's unmet requirement is reported where the type is written, including a type before ::, which is reported at its path; an expression whose type a written type gives, such as Bounded { value: 1 } in let x: Bounded<0> = Bounded { value: 1 }, does not report it again
  • A { right after where or a , opens a braced condition when the token after its matching } continues the clause: a ,, another predicate or the item's own {. So where T: Copy, { body } keeps its meaning. Only the braces are matched, so a syntax error inside the block stays inside the condition; an unbalanced { leaves no match, and the block is read as the body
  • In an extern function every block in the where clause is a condition. In a trait function, a block right after where is one
  • fe fmt keeps a trailing , after a final braced condition, since that comma decides which block is the body

Limits:

  • Conditions in traits, in trait impls with generic parameters, on generic methods of any trait impl, on generic impl blocks themselves and on items nested in generic items are rejected with an error that says so
  • A trait method assumes no conditions, so its signature and default body cannot use a constrained type or function with a generic argument
  • A trait impl assumes nothing from its trait arguments: trait solving can select impl<const N: usize> Tr<Bounded<N>> for Holder<N> for Holder<0> with the argument Bounded<0>, which no written type holds. So that header is rejected, since Bounded<N> there needs N > 0 and the impl cannot state it, and so is the call that infers Bounded<0>. The principled fix is to check well-formedness obligations when trait solving selects an impl
  • A condition is evaluated in its module's arithmetic mode. A function's own #[arithmetic(unchecked)] covers its body, not its where clause, as for the other constants in its signature
  • Only literals, const paths, unary and binary operations, casts and calls to const functions can be forwarded. Blocks, control flow and other expressions need concrete arguments. A braced const argument is a block, so fn g<const M: usize>(_ x: Bounded<{ M + 1 }>) where M + 1 > 0 is rejected, although impl<const M: usize> Bounded<{ M + 1 }> works; such a function can take Bounded<N> with where N > 0 instead
  • Generic arguments written on an enum variant or module segment, such as Choice::Empty<{ positive<0>() }>, are ignored and never evaluated, as on master
  • A constrained struct or enum must be fully applied; it cannot pass through a higher-kinded parameter
  • Comparisons separated by commas still read as generic arguments when the token after the > can continue an expression, as in where N < 8, M > (0), M > -1 or f(a < b, c > (d)), or when the > ends a line. Writing the comparison in parentheses, (M > 0), avoids it

Also included:

  • A fe test fixture for explicit const arguments of method and associated function calls, such as Window<1> {}.take<3>(), which compile-time evaluation reads. Since fix: complete generic function call defaults #1535 they are evaluated against the parameter's type; before, this panicked.
  • fe fmt and the tree-sitter grammar understand the new syntax.
  • Predicate blocks are borrow checked like other const bodies, and can borrow their own locals, which compile-time evaluation supports since Run more ordinary Fe at compile time #1582. A predicate that evaluates to false reports only that, since borrow checking runs once type checking succeeds.
  • Tests for a condition on a const fn that takes a trait provider (Run more ordinary Fe at compile time #1582): the provider is borrowed through a ref self method or taken by value, a generic caller forwards both the condition and the provider, and a call that fails the condition is rejected inside the with block.
  • An anonymous constant that fails type checking is reported, in a type, in a generic argument of a type, trait or function, and in a type parameter's default. On master, let a: [u8; { n }] = .. with a runtime n panics, and an undefined name there, or in a default argument that an alias drops, such as struct S<T = Drop<{ nope }>> with type Drop<const N: usize> = u8, compiles without an error.
  • f(a < b, c > d) and (a < b, c > 0) now parse, as comparisons. On master they are parse errors
  • A where clause keeps its type bounds and conditions in one list, in source order, and HIR printing follows it
  • Language server references: each reference in struct and enum conditions, field array lengths and type aliases is recorded once, and a msg variant's generated return type points at the written type, so renaming that type no longer edits the variant name
  • A test that the tree-sitter grammar and the compiler's parser agree on the where clause of every function, struct, enum, impl and trait

Recent mainline changes:

Overlap with open PRs (git merge-tree against their current heads, compared with each PR merged into master alone): this PR conflicts with #1643 in ty_check/mod.rs, where both add functions at the same place, and with draft #1536 in instance/template.rs. #1589 and #1606 get no conflicts.

Const predicates on trait impls would build on this requirement checking.

Review follow-up

This PR is rebased onto current master (1329ce2a0).

The first update addressed these parts of the review:

  • Correctness: the requirement bypass through the type written before ::, now closed for every segment of every path written in a type, an expression, a pattern or a with key, including the anonymous constants passed to each type, trait or alias segment, also inside type parameter defaults, not only the reported examples, with a check of every type inference gives an expression behind it; the salsa query cycle panic; the silently accepted runtime value in a type's constant; and the gap that no generic impl could target a constrained type, now closed by letting an impl assume its self type's conditions, which rests on the check of the type before ::.
  • Diagnostics: a failing ground condition is reported once, at its declaration; a record's condition inside a type level constant reports its reason; a named constant's unmet requirement and let x: Bounded<0> = Bounded { value: 1 } each report once; and where own reports only the parse error.
  • Code quality: one error code and a typed reason for an unmet requirement, instead of three string representations; discharge returns a typed outcome instead of diagnostics; static assertions and conditions share their outcome handling; the free function or inherent method test, the const condition body owner and the evaluability guard each exist once; borrow checking and layout evidence share one list of condition owners; and substitution failures in requirement checking fail the requirement instead of being dropped.

The second update addresses the rest:

  • Syntax and tools: fe fmt keeps the comma after a final braced condition; comparisons separated by commas parse as comparisons; extern functions accept where A, { B }; a syntax error inside a braced condition stays in the condition; tree-sitter reads where T: Copy, followed by a body as the compiler does; a where clause keeps one predicate list in source order; the braced-condition decision is one ItemBlock kind with one guard; the tree-sitter rule reuses the if condition rule.
  • Language server: renaming a msg return type no longer touches the variant, and struct, enum and alias references are recorded once.
  • Code: conditions go through the same checking pipeline as other bodies, and their const-language check runs in infer_body without adding a query cycle (explained in the commit and a comment); has_diagnostics is removed; the type lowering cycle check is in one place; a predicate's genericity is decided from the parameters it mentions; the formation cycle handler runs no query; TypedBody no longer derefs to its tables, and writes go through tables_mut; check_body_requirements is split into one step per job; predicate_key computes its context once.
  • One behaviour change: a condition that fails the const-language check is no longer checked for requirements, as with a const function's body. A fixture pins it.

@micahscopes micahscopes changed the title Checked generation and const where predicates Add const where predicates Sep 23, 2026
@micahscopes
micahscopes force-pushed the pr/checked-generation-const-predicates branch 4 times, most recently from 96b4bba to 2cda47f Compare September 23, 2026 22:10
@micahscopes
micahscopes force-pushed the pr/checked-generation-const-predicates branch from 2cda47f to 3499bc4 Compare September 25, 2026 04:34
@micahscopes
micahscopes marked this pull request as ready for review September 25, 2026 05:11
@micahscopes
micahscopes force-pushed the pr/checked-generation-const-predicates branch from 3499bc4 to 0a7f1c7 Compare September 28, 2026 02:54
@micahscopes
micahscopes requested a review from sbillig September 28, 2026 15:51
@micahscopes
micahscopes force-pushed the pr/checked-generation-const-predicates branch from 0a7f1c7 to 5a69cce Compare September 29, 2026 12:23
@micahscopes

micahscopes commented Sep 29, 2026 •

Copy link
Copy Markdown
Collaborator Author

Update addressing most of your review, rebased on master: the Type<args>::item bypass, the query cycle (fixed by layering), the silent anonymous-const case, generic impls of constrained types (an impl now assumes its header types' conditions), one error code and one typed outcome for unmet requirements, the duplicated diagnostics, and the smaller code items.

Known open, fix in progress for the next push: a constrained type in other path positions is still unchecked (fn f(_ x: Bounded<0>::Out), Bounded<0>::Out::make(), Holder<Bounded<0>::L>), and with the impl premises that can reach an item whose condition is false. The fix records every constrained type the resolver passes through and checks them all after inference, instead of listing positions. The formatter, parser and tree-sitter items, the LSP ones and the rest of the code quality items follow after that. The PR description is updated with that push.

@micahscopes

Copy link
Copy Markdown
Collaborator Author

Following up on my comment above: this push closes the path positions it listed as in progress. fn f(_ x: Bounded<0>::Out), Bounded<0>::Out::make() and Holder<Bounded<0>::L> are rejected, because the checker records every constrained type that path resolution passes through, at every segment (aa449b739). Further review found more positions of the same kind, also fixed here: an argument an alias drops (c5856499e), a braced argument on a qualifier that only selects an impl, such as Holder<{ dec<0>() }>::Out, or on an alias in an expression path (82776a8f7), with keys (6789a7902), and the same constants inside a type parameter's default, such as struct S<T = Holder<{ dec<0>() }>::Out> (e845e23d5). Behind these, every type that inference gives an expression, and every generic argument it infers for a call, is now checked too, so a type that only trait solving supplies, such as U = Bounded<0> in call(Holder<0> {}) for fn call<U, T: Tr<U>>(_ x: T), is rejected at the call (5813965f9).

The same review found that the impl premises were unsound through trait arguments: trait solving can select impl<const N: usize> Tr<Bounded<N>> for Holder<N> for Holder<0> with Bounded<0>, which nothing had checked. So an impl now assumes only its self type's conditions (30e366013). That is a new limit: a trait impl whose trait arguments name a constrained type with its own parameters, like the one above, is rejected, unless its self type states the same condition, as in impl<const N: usize> Same<Bounded<N>> for Bounded<N>. Checking well-formedness when trait solving selects an impl would lift it.

The PR description is updated to match. The formatter, parser, tree-sitter and LSP items and the remaining code quality items follow in the next update. The branch now conflicts with master after today's merges; a rebase onto master comes next.

@micahscopes
micahscopes force-pushed the pr/checked-generation-const-predicates branch from 5e52850 to 0144f5a Compare September 30, 2026 00:01
@micahscopes

Copy link
Copy Markdown
Collaborator Author

Rebased onto master (cfeb8aed4). The conflicts with #1582 and #1600 are resolved keeping master's code: the moved effects check now uses #1582's const_effects_supported, and the tree-sitter wasm is regenerated from the merged grammar. Two test commits are added: const where predicates on functions that take trait providers (the combination with #1582), and borrow checking inside predicate blocks.

`DiagnosticPass::ErrorLower` and `DiagnosticPass::SemanticBorrowck`
both used pass code 16, so `error[16-0003]` could name either a generic
`#[error]` struct or a borrow-checking error. Give error lowering the
unused code 13. Only the four `#[error]` diagnostics change their
rendered code.
An explicit const argument such as the `3` in `Window<1> {}.take<3>()`
or `Window<1>::sum<3>()` must be evaluated against the parameter's type,
as a free function's is, so that constant evaluation of a method or
associated function can read its const parameter.

#1535 made this so: explicit call arguments of every function, methods
included, now go through the generic parameter schema's completion,
which evaluates them. Before #1535 such a constant panicked with
"instantiated constant template retains its value description". This
`fe test` fixture pins that behavior for methods and associated
functions.
Parse boolean conditions in `where` clauses next to type bounds, and
check each condition that mentions no generic parameter where it is
declared, even if the item is unused. A condition passes only when it
evaluates to `true`; type errors, non-const operations and failed
evaluation are errors. Const conditions in generic scopes are rejected
until use-site checking exists.

`where T` without `:` now parses as a const condition, so a lone path
that names a type reports the missing trait bound instead of a type
used as a value.

The tree-sitter grammar, its vendored wasm build and the formatter
learn the new predicate form.

A predicate block goes through semantic borrow checking like any const
body. Its test needs frame-local borrows in const evaluation (#1582)
to evaluate the valid case, so it is added with that change.
Allow const `where` conditions on top-level generic functions. The
declaration checks each condition's type and const-ness, and every use
of the function discharges its conditions after inference: a concrete
condition is evaluated, and a condition that still mentions a caller's
parameter must match one of the caller's own conditions exactly after
substitution. Function values and calls in anonymous constant bodies
use the same check.

Inference and discharge are separate queries, so evaluation can use a
finished inference while a condition is checked. A failed requirement
is reported once, at the call site, with the reason.
An anonymous constant in a generic function's signature or body, such
as an array length, could not use the function's conditions, so a call
to a constrained helper there always failed. Let such constants forward
the enclosing function's conditions by the same exact-match rule as
calls. A predicate still cannot use the function's conditions to
justify itself, including through constants nested inside it.
Allow const `where` conditions on generic structs. Every concrete use
of the type must satisfy them: construction, type annotations, defaults,
aliases, fields and trait arguments, whether declared or inferred. A
generic use forwards a condition only by stating the same condition,
as with generic functions. Mentioning `Bounded<N>` does not establish
`N > 0`.

Each unmet condition is reported once, where the type enters: at the
innermost written type, or at the expression that instantiates it. An
enclosing type does not repeat a failure a nested written type reported.
A call's generic arguments are either written in its path, and checked
there, or inferred from expressions that are checked themselves, so a
function-typed expression is not checked for them. Patterns, binding
uses, blocks and branches only carry a type that entered elsewhere.

A constrained record must be fully applied where it is used as a type,
since nothing would carry its conditions through a higher-kinded
parameter.
Allow const `where` conditions on generic enums, with the same rules as
records. The conditions apply to the whole type, so constructing a unit
variant of `Choice<0>` fails too, and every variant's payload types must
be valid even when that variant is never built. Payloads may forward the
enum's conditions into nested constrained types, and a predicate can
still rely on ordinary trait bounds such as `T::ALLOWED`.

A tuple-variant constructor used as a value, such as `let make =
Choice<0>::Value`, enters its enum type without a call expression, so
the value itself is checked. A called constructor is checked at the call.
Allow const `where` conditions on inherent methods and associated
functions, over both the impl's parameters and the method's own. The
conditions of the method that ordinary resolution picked are discharged
at each receiver or qualified call; they never take part in choosing a
method. The checker maps the impl's parameters onto the method's leading
generic slots before applying the call's arguments.

The unsupported-context error now names where const predicates are and
are not supported.
A block condition had to be parenthesized, as in `where ({ ... })`,
because a `{` after `where` could also open the item's body. Accept a
bare block as a predicate right after `where` or after a `,`, when what
follows it continues the header: a `,`, another predicate, or the
item's own `{`. A `{` after a completed predicate is always the body,
so `where T: Copy { body }` and `where T: Copy, { body }` keep their
meaning, including when the body starts on the next line. Trait and
extern function declarations, whose bodies are optional, read a block
right after `where` as a predicate.

The tree-sitter grammar accepts a block predicate as well, and the
vendored wasm build is regenerated. The tooling grammar cannot look
past the block, so it reads the `where T: Copy, { body }` form as a
predicate with no body.
The driver tests check substrings of the errors, so duplicate or
misplaced labels pass unnoticed. Snapshot the rendered errors for
declaration failures, calls to generic functions and inherent methods,
record and enum uses, recursive requirements, and the contexts that are
rejected.
A type whose arguments still hold an inference variable is not checked
at that use, and a layout hole leaves such a variable without a "type
annotation needed" error. Check that the concrete arguments are still
checked where the type is declared, next to a valid control case.

Also cover a record requirement that reaches its own record through a
function's requirement. The cycle must be rejected with the same
diagnostics in every query order.
The where clause parser kept pieces of its earlier shape. It tested
`is_type_start(kind) || is_const_predicate_start(kind)` in three
places, and `is_const_predicate_start` listed by hand the tokens that
start an expression but not a type, which the expression parser already
knows. One of the three places also checked
`current_kind().is_some() && current_kind().is_some_and(..)`. And
`WherePredicateScope` still reported a missing `:`, although the clause
enters it only after a trial parse found the `:`.

Whether a token starts a predicate is now one function,
`starts_predicate`: a type start or an expression start, from the
expression parser's new `is_expr_start`, other than `{`. It accepts the
same tokens as before. The doubled condition and the unreachable branch
are gone.

No behavior changes: the parser's syntax and recovery snapshots are
unchanged.
Whether a `{` in a where clause opens a braced condition or the item's
own block was decided by an `Option<WhereBracePolicy>` that the clause
loop reset after every predicate and comma, by a single-use helper, and
by a policy that each caller passed in. Function signatures took
`FuncSignatureScope::new(allow_self, allow_body, policy)`, three
positional flags that all follow from the function kind.

The clause now takes `ItemBlock`, whether the item's block is required,
optional (a trait function's default body) or absent (an extern
function), and one guard, `brace_opens_predicate`, decides a `{` at the
start of a predicate from that and from whether the predicate is the
first. The loop has no reading state left: a `{` is only considered at
the start of a predicate, right after `where` or a `,`, and after a
completed predicate it ends the clause. `FuncSignatureScope` takes the
function kind, `FuncDefScope`, and derives whether `self` is allowed and
whether a body follows. The body parsing that three helpers repeated is
one match on the kind.

No behavior changes: an extern function still reads a block after a `,`
the way a trait function does, which the next commit changes. The
parser's syntax and recovery snapshots are unchanged.
`extern { fn g<const N: usize>() where N > 0, { N < 8 } }` failed to
parse with "only `fn` is allowed in this block". An extern function read
a block after a `,` the way a trait function does: as a condition only
when a `,`, another predicate or a `{` follows it. A trait function may
have a default body there, but an extern function has no body, so the
block could only be a condition and the parser left it to the extern
block, which rejected it.

A block anywhere in an extern function's where clause is now a
condition.

Failing first: the new syntax fixture `const_where_extern_braces.fe`
has parse errors on the parent commit. Now it parses without errors,
with both blocks as conditions. No existing snapshot changes.
In `fn f<const N: usize>() -> usize where N > 0, { N < } { 1 }` the
condition `{ N < }` became the function's body, and `{ 1 }` was left
over. To decide whether a block after a `,` is a condition, the parser
parsed the block on trial and looked at what followed it, and a block
with an error failed the trial parse, so it was read as the body. Error
recovery inside the condition changed how the surrounding clause
parsed.

The decision now matches the braces instead of parsing the block: it
skips from the `{` to its matching `}` and looks at the token after it.
An error inside the block is reported as the block is parsed, as part
of the condition.

Failing first: on the parent commit the new recovery fixture
`const_where_brace_syntax_error.fe` parses `{ N < }` as the body. Now it
is a condition, with the error inside it, and `{ 1 }` is the body. No
existing snapshot changes.

An unbalanced `{` inside the block leaves it without a matching `}`, so
the block is read as the body, and the error is reported there. The
recovery fixtures `const_where_brace_unbalanced.fe`, a parser tree and
the rendered error, pin that, and that the next item still parses.
…ments

`where N < 8, M > 0` parsed as one predicate, the path `N<8, M>`
followed by a stray `0`. The same happens on master in call arguments
and tuples: `f(a < b, c > d)` and `(a < b, c > 0)` fail to parse. After
a path segment, the expression parser read `<` as opening generic
arguments whenever a trial parse of the arguments succeeded, whatever
came after the closing `>`.

A `<` after a segment of an expression's path now opens generic
arguments only if the token after the closing `>` can follow a path.
It cannot when it starts an operand and can never continue an
expression after one, such as a literal, a name, `if`, `match`, `!` or
`~`, or when it is the `=` of a `>=`. Those parses were always errors,
so no program that parsed before parses differently. A token that can
continue an expression keeps the generic arguments, so
`(foo < i32, (u32) > (1))` is still a call with generic arguments. The
tree-sitter scanner applies the same rule when both readings are
possible, and the vendored wasm build and its stamp are regenerated.

Failing first: on the parent commit the new syntax fixtures
`const_where_comparisons.fe` and `generic_arg_comparisons.fe` have
parse errors, and `const_where/comparison_predicates.fe` stops at the
parse error. Now they parse, and each condition is checked on its own.
No existing snapshot changes.

The rule looks only at the token after the `>`, on the same line. So
`where N < 8, M > (0)`, like `M > -1` or a `>` that ends a line, still
reads as generic arguments, and `const_where/comparison_before_parenthesis.fe`
pins the error it reports; `(M > 0)` avoids it.
In a trait, `fn f<T>() -> bool where T: Copy, { true },` states a
condition, which is rejected since trait functions cannot state them.
`fe fmt` dropped the trailing comma, and without it the parser reads the
block as a default body, so the formatted program passed `fe check`.
In an extern block the same formatting made the program stop parsing.

The formatter now keeps the `,` after a where clause's last predicate
when that predicate is a braced condition. That comma is what makes the
block a condition there, so formatting no longer changes which block is
the body. A trailing comma after any other predicate is still dropped.

Two invariants now run over every const where fixture of the type
checking tests: formatting twice gives the same text as formatting
once, and the formatted program reports the same errors as the
original. The uitest crate takes `fe-fmt` as a dev-dependency for this.

Failing first: on the parent commit the formatter fixture
`const_where_trailing_comma.fe` loses its commas, and the new type
checking fixture `trailing_comma_after_a_braced_condition.fe` reports
one error fewer after formatting. Now both keep their meaning. No
existing snapshot changes.
The tree-sitter rule for a const where predicate listed 17 expression
kinds by hand instead of reusing an expression rule, and the grammar
declared four conflicts for it alone.

A const where predicate is now `_condition_no_let`, the rule that
already reads an `if` or `match` operand: an expression without a record
literal, as the compiler's parser reads a condition with
`parse_expr_no_struct`. Two conflicts between that rule and the
expression and path rules replace the four. The vendored wasm build and
its stamp are regenerated.

No behavior changes in the compiler. The tree-sitter parse tests pass
over the same files, including the syntax and formatter fixtures and the
core and std ingots.
…tree-sitter

The tree-sitter grammar read the existing `where T: Copy,\n{ body }`
style, used in `ingots/std/src/evm/mutex.fe`, as a braced condition with
no body. Both readings parse, since a function's body is optional in the
grammar, and it kept the condition.

The grammar now prefers the reading the compiler's parser gives:
- a block that can be a function's body is the body, through a dynamic
  precedence on the body;
- a top level statement is read as one only when nothing else reads its
  tokens, so `where T: Copy, { N > 0 } {}` keeps `{ N > 0 }` as the
  condition and `{}` as the body instead of a statement after the
  function;
- an extern function has no body, so a block in its where clause is a
  condition. Extern blocks use the function signature rule under the
  `function_definition` name.

A new test checks that tree-sitter and the compiler's parser agree on
every function's body and where predicates over the syntax and
formatter fixtures and the core and std ingots. The vendored wasm build
and its stamp are regenerated.

Failing first: with the parent commit's grammar, tree-sitter reads
`peek` in `mutex.fe` and the `trailing` function of
`const_where_brace_boundaries.fe` without a body, which the new test
reports. Now the two parsers agree on every function in those files.
Renaming a constant used in a struct's or enum's `where` condition
edited each use twice, and so did one used in a field's array length or
a type alias's. The reference index collects each item's references and,
separately, each body's, since every body is an item of its own in the
scope graph: a function body, a field type's array length, a `where`
condition. The collectors for functions, impls and traits skip nested
bodies for that reason, but those for structs, enums and type aliases
visited them, so their bodies' references were recorded twice.

Those collectors now skip nested bodies too, and the flag says why.

A new test snapshots the module reference index that rename edits, one
line per referring span and target, with a count when a reference is
recorded more than once.

Failing first: on the parent commit the new fixture
`module_references/const_predicates.fe` records each reference in the
struct and enum conditions and in the field's array length twice. Now
once each, as in the function's condition, and so is the alias's.
Renaming `Foo` in `msg Api { Alpha -> Foo }` also rewrote the variant
name `Alpha`. A msg variant is lowered to a struct and an
`impl MsgVariant` with `type Return = Foo`, and since this PR the
visitor walks a trait impl's associated types, so references and
written type checks see that type. Its span resolved through the impl's
origin, the variant's name, so the reference to `Foo` was recorded at
`Alpha`, and a requirement failure in a return type was reported there.

The span of an associated type's definition now resolves, for a msg
variant's generated impl, to the variant's written return type, which
the type is lowered from. The paths in it get their written spans, so
rename edits `Foo` where it is written.

Failing first: on the parent commit the new fixture
`module_references/msg_return_types.fe` records the references to `Foo`
and `Pair` at the variant names. Now they are at the return types.
Const conditions narrowed `WhereClauseId::data` to mean the type bound
predicates only, with the conditions in a second list next to it, and
the AST's `WhereClause` iterator skipped conditions silently, so the
formatter had to check for them separately. Two lists also lost the
clause's order: `where N > 0, T: Copy` printed as
`where T: Copy, (N > 0)`.

A where clause now holds one list of predicates in source order, in the
AST (`WhereClausePredicate`, with `kind()` giving a type bound or a
condition) and in HIR (`WhereClauseId::predicates`, of
`WhereClausePredicate`). `type_predicates` and `const_predicates` give
each kind by name, and a type bound keeps its position among all
predicates, which is also its span index, so spans and constraint
sources index one list. The formatter and HIR printing iterate the one
list.

Failing first: the parent commit's printer writes every type bound
before every condition, so the new pretty printing fixture
`where_clauses.fe`, `where N > 0, T: Copy, N < 8`, would print as
`where T: Copy, (N > 0), (N < 8)`. Now it prints in source order. No
other snapshot changes.
`TypedBody::has_diagnostics` is written by inference and by the checked
body queries but never read, on master as here. This PR kept it outside
the shared tables and added writes to it.

The field and its writes are gone. No behavior changes: nothing read it,
and the existing tests pass unchanged.
Compile-time evaluation refuses a body whose inference met a type
lowering cycle, since its typed body is a provisional fixpoint value.
The fact was checked in two places: `inference_met_lowering_cycle`
looked at the inference diagnostics, and its one caller, in the
evaluator, also checked the typed body's result type for the same
cycle.

`inference_met_lowering_cycle` now takes the inference result and checks
both, the body's diagnostics and the result type it was checked
against, and the evaluator asks it once. No behavior changes: the
existing tests pass unchanged.
To decide whether a use leaves a predicate generic, discharge
substituted the use's arguments into the predicate's whole typed body,
patched the constant references that the fold leaves formal, and
scanned the result for parameters. Deciding whether the predicate
mentions parameters at all cloned the typed body to clear its
assumptions and scanned it the same way.

The generic parameters a predicate's expression mentions are now one
query, `predicate_params`, over the body's types without its ambient
assumptions (`TypedBody::visit_body_types`). A predicate depends on
parameters when that list is not empty, and a use leaves it generic
when the argument for one of those parameters still mentions a
parameter. The check under the generic branch that the predicate
depends on parameters could no longer be false, so it is gone.

No behavior changes: the const requirement fixtures and tests pass
unchanged.
The cycle initial value of `check_predicate_formation` ran `infer_body`
to fill in the typed body of a formation that is recursive, which
discharge never reads.

A formation's typed body now lives in its status, as
`FormationStatus::WellFormed(typed)`, the only status that discharge
reads it from, so a recursive or ill-formed formation carries none. The
cycle handler builds the recursive formation without a query.

No behavior changes: the const requirement fixtures and tests pass
unchanged.
`check_predicate_formation` was a second checking pipeline for where
conditions: it repeated `check_body`, inference followed by the
requirement checks, and ran the const-language checks itself, while a
const function's const-language checks live in `infer_body`.

A condition's const-language checks now run in `infer_body` too, for an
owner that `BodyOwner::is_const_predicate` recognizes, once inference
leaves the condition evaluable as before. `check_body` and the
formation query share `checked_body`, which infers the body and then,
when it is evaluable, checks its requirements, and which also reports
whether a requirement depends on itself. The formation query only adds
the formation status on top.

A condition whose const-language check fails is now no longer checked
for requirements, as a const function's body is not. The fixture
`generic_predicates_check_const_language_before_becoming_premises/requirements.fe`
pins this against a condition that passes the check and fails the same
requirement. Existing snapshots are unchanged.

The new work in `infer_body` cannot close a query cycle. Recognizing a
condition reads only its item's lowered `where` clause. The
const-language check reads each callee's declaration, its effect
requirements and trait method resolution, the same reads `infer_body`
already makes for a const function's body. A condition's body is
inferred only by requirement checking, the formation query,
declaration checks, borrow checking and layout evidence. Those run
above type lowering and compile-time evaluation, which is all the
reads above can reach, and neither of those calls back into them: type
lowering evaluates a constant without checking its requirements. So
the new edge points down the layers.
`TypedBody` dereferenced to its shared tables, mutably too, so a plain
field assignment on a typed body silently copied every table whenever
the body was still shared, and folding took the pattern store out with
`std::mem::take` to get around the borrow.

The `Deref` and `DerefMut` impls are gone. Reads go through the
accessors, or through the private `tables` field inside `TypedBody`'s
own methods. The few writes, the cycle initial value, the finalizer and
two tests, call `tables_mut`, which says that it copies shared tables.
Folding takes the tables with `Arc::unwrap_or_clone` and folds each
field by value, and requirement checking reads the path applications
through `path_applications`.

No behavior changes.
`check_body_requirements` checked the applications of the body's
paths, the type of each expression, the header types an item reached
through a path enters, the requirements of each callee and constructor
value, and every inferred type, in one function. It computed an
expression's type twice and shadowed `caller` with a filtered copy.

The steps are now methods of `BodyRequirements`, which holds the state
they share: the applications that written types and paths carry, the
failing applications reported so far, and the diagnostics.
`check_body_requirements` runs them in order: path applications, each
expression (`check_expr`, which computes the type once and hands it to
`check_callee`), then the inferred types over the expressions that the
second step checked, then the anonymous constants in expressions. A
callee's requirements split into its headers, a constructor value's
enum type, and the discharge of its conditions, which names the
filtered owner `premise_owner`. The test for a function type is one
helper, also used by `check_entered_header`.

No behavior changes.
`predicate_key` recursed through the predicate's expression with its
whole context as arguments, looked up the predicate's arithmetic mode
again at every node, and asked for a call's callable twice.

`predicate_key` now takes the predicate and computes its arithmetic
mode once, and `PredicateKeyBuilder` carries that context through the
recursion. Each node looks up its callable once.

No behavior changes.
The agreement test between the tree-sitter grammar and the compiler's
parser compared only functions: whether each has a body, and the kinds
of its `where` predicates. It now compares the `where` clauses of
structs, enums, impls, trait impls and traits too, and fails if any of
those kinds is never seen with a predicate, so that no kind agrees only
because neither side found its clause.

It also reads the `const_where` type checking fixtures, the largest set
of `where` clauses. Four of them use syntax that the grammar cannot
read, a block in a generic parameter's default and generic arguments
on a pattern or record path, as on master. They are listed by name, so
any other disagreement still fails.
@micahscopes
micahscopes force-pushed the pr/checked-generation-const-predicates branch from 0144f5a to c4d12cd Compare September 30, 2026 17:32
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@micahscopes

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. I've pushed the second update, rebased on current master.

Since your last look:

  • fe fmt keeps the comma after a final braced condition, so formatting can't change which block is the body.
  • where N < 8, M > 0 reads as two conditions. As a side effect, f(a < b, c > d) and (a < b, c > 0) now parse.
  • Extern functions accept where A, { B }.
  • A syntax error inside a braced condition stays inside it.
  • The tree-sitter grammar agrees with the compiler on where clauses, and a test checks it.
  • Renaming a msg return type no longer renames the variant; references in struct, enum and alias conditions are recorded once.
  • The code clean-ups: one checking path for conditions, the TypedBody deref removed, check_body_requirements split up, and predicate_key and the cycle handler simplified.

Known limits, both covered by tests:

  • A comparison like M > (0) still reads as generic arguments; (M > 0) avoids it.
  • An unbalanced { inside a braced condition makes the block the function body.

@sbillig

sbillig commented Sep 30, 2026

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-30T22:37:23.957224Z c4d12cd Manual request
🔒 Security Review ✅ Completed 2026-09-30T22:58:36.827261Z c4d12cd Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: c4d12cdfad

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review · Automatically triggered

Security review completed. No security issues were found in this pull request.

Reviewed commit: c4d12cdfad

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@sbillig
sbillig merged commit 208ec3b into master Oct 1, 2026
9 checks passed
@sbillig
sbillig deleted the pr/checked-generation-const-predicates branch October 1, 2026 03:21
@micahscopes

Copy link
Copy Markdown
Collaborator Author

For the record this got paired down because the machinery to get full on const where predicates in trait impls is wrapped up in the first class constraints/obligations stuff, which is still being re-materialized. So that will come with a later chunk.

I don't want to artificially force stuff at the cost of fragmenting core machinery.

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.

2 participants