Repository navigation
Add const where predicates - #1576
Conversation
96b4bba to
2cda47f
Compare
2cda47f to
3499bc4
Compare
3499bc4 to
0a7f1c7
Compare
0a7f1c7 to
5a69cce
Compare
|
Update addressing most of your review, rebased on master: the Known open, fix in progress for the next push: a constrained type in other path positions is still unchecked ( |
|
Following up on my comment above: this push closes the path positions it listed as in progress. The same review found that the impl premises were unsound through trait arguments: trait solving can select 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. |
5e52850 to
0144f5a
Compare
|
Rebased onto master ( |
`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.
0144f5a to
c4d12cd
Compare
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
Thanks for the review. I've pushed the second update, rebased on current master. Since your last look:
Known limits, both covered by tests:
|
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Didn't find any major issues. Breezy! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
🛡️ Codex Security Review · Automatically triggeredSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
|
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. |
This lets an item state a boolean condition in its
whereclause, such asN > 0, and have the compiler check it wherever the item is used.A
whereclause can hold boolean conditions next to trait boundsbounded<1>()is accepted andbounded<0>()is rejected, even though the body never readsN. On master, awhereclause takes only trait bounds, sowhere N > 0is a parse error.A generic caller satisfies a condition by stating the same one
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
Every written use of
Bounded<0>is rejected, including unused type annotations, defaults, types written inside a const parameter's default, aliases,withkeys, and a type at any segment of a path, such asBounded<0>::helper(),Bounded<0>::Out,Bounded<0>::Out::make()and the unbraced const argument inHolder<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 inHolder<{ dec<0>() }>::Out, and so is one written in a type parameter's default, such asstruct 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 asU = Bounded<0>incall(Holder<0> {})forfn call<U, T: Tr<U>>(_ x: T), is rejected at the call. For a constrained enum, unit variants such asChoice<0>::Emptyand constructor values such asChoice<0>::Valueare 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 themThis 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 andwithkeys; 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
A condition that needs several lines can be written as a block
where Twithout: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, soerror[16-0003]can name two different errors.A few decisions:
N > 1does not establishN > 0error[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 asBounded { value: 1 }inlet x: Bounded<0> = Bounded { value: 1 }, does not report it again{right afterwhereor a,opens a braced condition when the token after its matching}continues the clause: a,, another predicate or the item's own{. Sowhere 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 bodywhereclause is a condition. In a trait function, a block right afterwhereis onefe fmtkeeps a trailing,after a final braced condition, since that comma decides which block is the bodyLimits:
implblocks themselves and on items nested in generic items are rejected with an error that says soimpl<const N: usize> Tr<Bounded<N>> for Holder<N>forHolder<0>with the argumentBounded<0>, which no written type holds. So that header is rejected, sinceBounded<N>there needsN > 0and the impl cannot state it, and so is the call that infersBounded<0>. The principled fix is to check well-formedness obligations when trait solving selects an impl#[arithmetic(unchecked)]covers its body, not itswhereclause, as for the other constants in its signaturefn g<const M: usize>(_ x: Bounded<{ M + 1 }>) where M + 1 > 0is rejected, althoughimpl<const M: usize> Bounded<{ M + 1 }>works; such a function can takeBounded<N>withwhere N > 0insteadChoice::Empty<{ positive<0>() }>, are ignored and never evaluated, as on master>can continue an expression, as inwhere N < 8, M > (0),M > -1orf(a < b, c > (d)), or when the>ends a line. Writing the comparison in parentheses,(M > 0), avoids itAlso included:
fe testfixture for explicit const arguments of method and associated function calls, such asWindow<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 fmtand the tree-sitter grammar understand the new syntax.falsereports only that, since borrow checking runs once type checking succeeds.ref selfmethod or taken by value, a generic caller forwards both the condition and the provider, and a call that fails the condition is rejected inside thewithblock.let a: [u8; { n }] = ..with a runtimenpanics, and an undefined name there, or in a default argument that an alias drops, such asstruct S<T = Drop<{ nope }>>withtype 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 errorswhereclause keeps its type bounds and conditions in one list, in source order, and HIR printing follows itwhereclause of every function, struct, enum, impl and traitRecent mainline changes:
primary_diagand the HIR visitor; this PR uses their new forms.static_assertdoes. An evaluation that fails or still waits on an unknown value is an error.CompleteSubst), which also covers a method's impl parameters, and evaluated withGenericSubst::for_body_owner. Anonymous constants in structs and enums already get their item's bounds from fix: complete generic function call defaults #1535'sconst_body_assumptions.const_check.rsthat this PR moves, and added a refusal inctfe/machine.rsnext to the check this PR adds. Both keep Run more ordinary Fe at compile time #1582's rules: a const fn's effects are accepted by Run more ordinary Fe at compile time #1582'sconst_effects_supported, and its refusal of unsupported providers runs before this PR's check for a type lowering cycle.continueinforloops, nested qualified generic arguments, and associated type lookup through bounds #1600 changed the parser's imports inparam.rs, added a formatter test at the same place as this PR's infmt/tests/format_snapshots.rs, and changed the tree-sitter scanner. Both tests are kept, and the vendored wasm and its stamp are regenerated from this PR's grammar and Fixcontinueinforloops, nested qualified generic arguments, and associated type lookup through bounds #1600's scanner.const_ty.rsthat this PR replaces.instance/template.rs, where both sides edit the same imports,borrowck/check.rs, where this PR visits const conditions as body owners in the same loop, andty_lower.rs. They also cache lowered impl headers and reject mismatched impl headers before instantiating them. The conditions an impl assumes are read from its self type, not from trait solving, so they need no change, and no snapshot changes.Overlap with open PRs (
git merge-treeagainst their current heads, compared with each PR merged into master alone): this PR conflicts with #1643 inty_check/mod.rs, where both add functions at the same place, and with draft #1536 ininstance/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:
::, now closed for every segment of every path written in a type, an expression, a pattern or awithkey, 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::.let x: Bounded<0> = Bounded { value: 1 }each report once; andwhere ownreports only the parse error.The second update addresses the rest:
fe fmtkeeps the comma after a final braced condition; comparisons separated by commas parse as comparisons; extern functions acceptwhere A, { B }; a syntax error inside a braced condition stays in the condition; tree-sitter readswhere 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 oneItemBlockkind with one guard; the tree-sitter rule reuses theifcondition rule.infer_bodywithout adding a query cycle (explained in the commit and a comment);has_diagnosticsis 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;TypedBodyno longer derefs to its tables, and writes go throughtables_mut;check_body_requirementsis split into one step per job;predicate_keycomputes its context once.