Commit Graph

3086 Commits

Author SHA1 Message Date
byd1
355aec9742 changed to parser 2026-09-22 18:41:25 +08:00
Jonathan Brouwer
a7be2941de Rollup merge of #163083 - nnethercote:rm-Diag-G, r=oli-obk
Remove `G` generic param from `Diag<'_, G>`

The benefits are outweighed by the costs. Details in invidual commits.

some minor earlier discussion about this change in https://github.com/rust-lang/rust/pull/162630#discussion_r3988468478
2026-09-21 15:19:21 +02:00
Nicholas Nethercote
30b8dfc353 Remove G generic param from Diag<'_, G>
It encodes the `emit` behaviour, one of:
- `BugAbort`: Abort as a bug.
- `FatalAbort`: Abort as a fatal error.
- `ErrorGuaranteed`: Return an `ErrorGuaranteed` (the default).
- `()`: return `()`.

This is useful but `Diag` is very widely used and it's arguably not
useful enough to be worth the generic parameter. This commit removes it.

Benefits:
- Many fewer generic parameters, including many functions where the
  genericity is entirely uninteresting. This includes every
  `Diagnostic::into_diag` and `Subdiagnostic::add_to_diag`. Removes the
  need for the comment about `<G>` on `trait Diagnostic`.
- No `PhantomData` in `Diag`.
- Makes bootstrapping a bit faster.

The downside is there is no longer a single `emit` method.
- Getting a `!` return type requires calling `emit_bug` or `emit_fatal`.
  This only affects a few call sites.
- Getting an `ErrorGuaranteed` return type requires calling `emit_err`.
  This affects a lot of call sites. (It arguably makes call sites more
  self-documenting.)
- Using the wrong `emit_*` on a diagnostic causes a runtime abort, which
  previously couldn't occur. Seems unlikely, but it's not impossible.
- Note: If no particular return type is needed, `emit` can be used for
  any diagnostic. (Bug/fatal diagnostics will still trigger abort.)
2026-09-21 09:57:42 +10:00
Nicholas Nethercote
23ba1fae5f Convert create_err(e).emit() occurrences to emit_err(e) 2026-09-21 09:57:26 +10:00
León Orell Valerian Liehr
3caa23d7e7 Introduce helper Token::non_raw_ident 2026-09-20 18:03:22 +02:00
León Orell Valerian Liehr
aceae2d116 Replace IdentIsRaw with IdentKind 2026-09-20 18:03:19 +02:00
Roland Xu
96c6172a4c Rollup merge of #163006 - lapla-cogito:letelse_fullwidthbrace, r=folkertdev
Use `end_point` for trailing brace in `let...else` diagnostics

The following ICEs because `}` is a fullwidth lookalike of `}`:

```rs
fn main() {
    let x = {1} else { return; };
}
```

The diagnostic for a trailing curly brace before else in a let...else statement computed the brace span with `span.hi() - BytePos(1)`. That assumes the brace is a single ASCII byte.
2026-09-20 09:23:42 +08:00
Roland Xu
955bef3c61 Rollup merge of #162988 - inkreasing:attempt2-fix-162947, r=chenyukang
recover `true` and `false` in type position as `bool`

Fixes https://github.com/rust-lang/rust/issues/162947

I asked for a bit of help in [#t-compiler/help > parser help with issue 162947](https://rust-lang.zulipchat.com/#narrow/channel/182449-t-compiler.2Fhelp/topic/parser.20help.20with.20issue.20162947/with/625278094) and was advised to this solution.

This doesn't help if another keyword instead of `true` or `false` is used in type position, but i assume this is rare (don't think it has ever happened to me).
I also think this could lead to confusing error messages if the user has a type called `True` or `False`. When this then is typoed as lowercase it would be made to a bool. I assume this is also rare.

No AI used.
2026-09-20 09:23:41 +08:00
Roland Xu
5435e3887e Rollup merge of #162705 - fmease:fix-c-array-diag, r=JonathanBrouwer
Trigger "C array" parse error recovery in far fewer cases

Previously we would trigger on

1. `unsafe { 1, 2, 3 }` and suggest `[ { 1, 2, 3 ]` (sic!)
2. `'label: { 1, 2, 3 }` and suggest `[: { 1, 2, 3 ]` (sic!)
3. `X::<{ 1, 2, 3 }>` and suggest `X::<[ 1, 2, 3]>` (wrong)
4. `|| -> i32 { 1, 2, 3 }` and suggest `|| -> i32 [ 1, 2, 3 ]` (wrong)
5. `await { 1, 2, 3 }` and suggest `await [ 1, 2, 3 ]` (wrong)

Moreover, stop looking for identifiers after the `{` as that case can no longer be reached anyway as `maybe_recover_bad_struct_literal_path` will always snatch it first.

I haven't added any regression tests as I don't think it'd be worth it / proportionate (it's a niche parse error recovery gone awry in very odd cases). Let me know if you think otherwise.

<sub>(No LLM was or will be used by me during the entire creation process of this PR)</sub>
2026-09-20 09:23:39 +08:00
Roland Xu
a49b3c8eff Rollup merge of #162700 - fmease:rm-dead-ascr-recov, r=fee1-dead
Remove incorrect parse error recovery code that mistakes `as` casts for the long removed type ascription

Back when we still had type ascription syntax `$expr : $ty`, `parse_assoc_op_cast` would parse both `as` casts & type ascription.

During that time (namely in commit 8c5dafdcb8), parse error recovery from code like `label: loop {}` was added (label lacks leading apostrophe). However, it never checked if we did actually parse a `:` and not an `as` meaning *to this day* we emit a nonsensical diagnostic for expressions like `label as loop {}`! This PR does away with this code & further cleans up in the area (thanks to type ascription being gone).

In case you're wondering, we do still recover from expr *stmts* like `label: loop {}` as we have some code in the stmt parser for this.

Since the removal of the type ascription syntax we do indeed no longer provide that recovery for arbitrary exprs (e.g, `(label: loop {})`) which I find absolutely acceptable.

<sub>(No LLM was or will be used by me during the entire creation process of this PR)</sub>
2026-09-20 09:23:38 +08:00
Roland Xu
dff5c55b7c Rollup merge of #158515 - bb1yd:let-else-detect-invisible-delimiter, r=jackh726
Make let-else respect macro_rules expr metavariable grouping

Fixes rust-lang/rust#147899
2026-09-20 09:23:32 +08:00
León Orell Valerian Liehr
8a0a23db23 Trigger "C array" parse error recovery in far fewer cases
Previously we would trigger on

1. `unsafe { 1, 2, 3 }` and suggest `[ { 1, 2, 3 ]` (sic!)
2. `'label: { 1, 2, 3 }` and suggest `[: { 1, 2, 3 ]` (sic!)
3. `X::<{ 1, 2, 3 }>` and suggest `X::<[ 1, 2, 3]>` (wrong)
4. `|| -> i32 { 1, 2, 3 }` and suggest `|| -> i32 [ 1, 2, 3 ]` (wrong)
5. `await { 1, 2, 3 }` and suggest `await [ 1, 2, 3 ]` (wrong)

Moreover, stop looking for identifiers after the `{` as that case can no
longer be reached anyway as `maybe_recover_bad_struct_literal_path`
will always snatch it first.
2026-09-19 17:20:36 +02:00
León Orell Valerian Liehr
e224f8f81e Further simplify parse_assoc_op_cast 2026-09-19 16:39:05 +02:00
increasing
fe96227afd recover true and false as bool type 2026-09-19 16:34:48 +02:00
León Orell Valerian Liehr
6524ec5bde Remove incorrect parse error recovery code that mistakes as casts for the long removed type ascription 2026-09-19 16:31:39 +02:00
lapla
c30f2a421f Use end_point for trailing brace in let...else diagnostics 2026-09-19 15:45:50 +09:00
León Orell Valerian Liehr
28158721a2 Don't mistake <-> for <>
Previously we would check if the current operator was `Binary(Lt)` and
the current token was `>` to determine if we're looking at `<>`.

However, since `AssocOp::from_token` also treats `<-` as `Binary(Lt)`
for better error recovery, the condition would also hold for `<->`
(`<-`, `>`) which is not what we want. E.g., given `1 <-> 2` we would
previously emit diagnostic "invalid comparison operator `<>`".

---

Also update `recover_from_spaceship_cmp_op` to do something similar --
not to fix anything but simply to eliminate param `op: Spanned<AssocOp>`.
2026-09-18 16:29:52 +02:00
León Orell Valerian Liehr
f0ae097b36 Refactor check_assoc_op to make it more legible 2026-09-18 16:29:45 +02:00
León Orell Valerian Liehr
d85d3f5505 Refactor the way we finish parsing expr ops
1. Remove unnecessary rebindings (`op_span` and `op = op.node`)
2. Remove binding `cur_op_span` as it's equal to `op.span`
3. Merge two `match`es on `op.node` into one to make the control flow
   more obvious and to render everything more legible. Moreover,
   it allows us to drop an ungly `unreachable!()`
2026-09-18 16:29:35 +02:00
León Orell Valerian Liehr
1adccf221f Inline fns & data types related to parse error recovery from C-style inc/dec ops 2026-09-18 16:29:33 +02:00
León Orell Valerian Liehr
ddb9380cde Move parse error recovery from C-style inc/dec ops out of line 2026-09-18 16:26:21 +02:00
León Orell Valerian Liehr
6c0ab88a20 Dismantle bespoke diagnostic suggestion wrapper API
There's literally no upside to use it and only downsides:
It's not more concise, only adds code and obfuscates.
Its `MultiSugg::emit{,_verbose}` didn't even *emit* the diagnostic,
they merely *decorated* it!
2026-09-18 16:26:21 +02:00
León Orell Valerian Liehr
ceede0ba9c Remove odd special case of some parse error recovery functions
`recover_from_inc_dec` *always* returns a (fatal) `Err(_)` *except* if
the increment/decrement operator is a subexpression *and* the source of
the operand is not available in which case it emits the diagnostic and
returns `Ok(_)` (rendering it non-fatal).

This makes no sense whatsoever. For illustration purposes, listed below
are steps that would make us reach this case:

1. `rustc a.rs --crate-type=lib` where `a.rs` contains:
   `#[macro_export] macro_rules! m { () => { i++ } }`.
2. Move or remove `a.rs`
3. `rustc b.rs --edition 2018 --extern a -L.` where
   `b.rs` contains:
   `fn main() { (a::m!()); }`.

Just make the error unconditionally fatal and add a FIXME to make it non
fatal in the future which would allow us to report name resolution errors
and what not. However, since that would be slightly more involved and
represent a behavior change (in the error path), this is out of scope for
a mere cleanup commit like this one.
2026-09-18 16:26:21 +02:00
León Orell Valerian Liehr
b945d684dc Don't needlessly pass the operand through some recovery functions by value
These functions didn't actually modifiy the operand or return a new or
different expression. So essentially the "`fn(Box<Expr>) -> Box<Expr>`
part" was an identity function. Just change it to "fn(&Expr)".
2026-09-18 16:26:21 +02:00
León Orell Valerian Liehr
e7d3a6a9e6 Move parse error recovery from some invalid expr ops out of line 2026-09-18 16:26:16 +02:00
Stuart Cook
9d7b74c416 Rollup merge of #162794 - nnethercote:simplify-UseTreeKind, r=petrochenkov
Simplify `ast::UseTreeKind`

We can make things simpler by adjusting how the ids are stored. Details in individual commits.

r? @petrochenkov
2026-09-16 23:41:56 +10:00
Nicholas Nethercote
4bfe145fcb Introduce ast::UseTreeAndId
Currently a `NodeId` is stored in a pair with each nested use tree. This
commit changes the pair to a named type `UseTreeAndId`. In most places
this doesn't make much difference but in the AST visitor it gets rid of
several weird special cases.
2026-09-16 14:15:32 +10:00
Jonathan Brouwer
c26fc64e36 Rollup merge of #162704 - fmease:uninterpolate-more, r=petrochenkov
Parser: Uninterpolate when checking for const closures, try bikeshed blocks & in relevant diagnostic code

On main, various places in the parser manually check for `TokenKind::Ident(…)` while in *most* cases that's not correct / complete as it doesn't account for *interpolated* identifiers (`TokenKind::NtIdent(…)`, "non-terminal" identifiers, i.e., ones that originate from macro metavariables `$ident`).

I've looked at all occurrences of `TokenKind::Ident` & `token::Ident` in the parser to see if each place was intentionally ignoring `NtIdent` or not. I found out that the code pertaining to const closures (unstable feature `const_closures`), to try bikeshed blocks (unstable feature `try_blocks_heterogeneous`) and to some diagnostics & parse error recoveries did not intend to ignore interpolated identifiers. This PR rectifies that.

Note that in most cases, it's not necessary to manually match against `NtIdent` as you can simply utilize helpers like `Token::uninterpolate`, `Token::ident`, `Token::is_keyword`, `Token::is_non_raw_ident` which handle them internally.

I also took the chance to clean up in each vicinity.

<sub>(No LLM was or will be used by me during the entire creation process of this PR)</sub>
2026-09-15 23:26:56 +02:00
Jonathan Brouwer
3405f96025 Rollup merge of #162204 - KevinA-cpu:extern-const-unsafe-does-not-trigger-note-issue-140171, r=chenyukang
Suggest keyword order for `extern "C" const unsafe fn`

closes rust-lang/rust#140171

This implementation does not accurately follow the desired output in the issue as it could introduces a much bigger change, where as the one item suggestion approach is also decently helpful and sufficient already.
2026-09-15 09:32:34 +02:00
Jonathan Brouwer
305d36bc80 Rollup merge of #162630 - nnethercote:simplify-Diag-G, r=oli-obk
Simplify the `G` in `Diag<'a, G>`

The `EmissionGuarantee` trait isn't necessary, and just complicates things. Details in individual commits.

r? @oli-obk
2026-09-14 15:16:02 +02:00
Jonathan Brouwer
fa6e214d31 Rollup merge of #162634 - JonathanBrouwer:named-fn-trait-params-semantics, r=folkertdev
Implement semantic analysis for named `Fn` trait params

This PR can be reviewed commit by commit.
Every commit passes uitests individually.

The goal of this PR is to make the semantic of named fn trait parameters match those of `fn` pointers, which is what was decided on the RFC: https://github.com/rust-lang/rfcs/pull/3955.
This is achieved, which can be observed by the fact that the output of the `named-fn-trait-params.rs` test matches that of `fn-ptr-pattern.rs`.

This PR also marks the feature as complete.

Tracking issue: https://github.com/rust-lang/rust/issues/158499
2026-09-14 15:15:58 +02:00
Jonathan Brouwer
d5e94f259e Remove parse_param_general 2026-09-14 10:27:06 +02:00
León Orell Valerian Liehr
613c86f930 Uninterpolate when checking for try bikeshed blocks
This makes code like this compile:

    #![feature(try_blocks_heterogeneous)]
    macro_rules! make { ($kw:ident) => { try $kw Option<()> {} } }
    fn scope() { make!(bikeshed); }
2026-09-13 00:52:09 +02:00
León Orell Valerian Liehr
996bad35dd Parser: Uninterpolate in relevant diagnostic code 2026-09-13 00:52:09 +02:00
León Orell Valerian Liehr
2c8990aed3 Parser: Uninterpolate when checking for const closures 2026-09-13 00:52:08 +02:00
Nicholas Nethercote
09bf6de39e Remove EmissionGuarantee
It's a trait that is used to give `Diag::emit` different return types
depending on the `G` in `Diag<'_, G>`. It works, but it's overkill.
There are only four different `G` types in practice (`BugAbort`,
`FatalAbort`, `ErrorGuaranteed`, and `()`) and having inherent `emit`
methods for each of those four concrete `Diag<'_, G>` types is good
enough.

This commit makes that change. This removes `EmissionGuarantee`
trait bounds from many places, which is nice.
2026-09-12 11:21:03 +10:00
Nicholas Nethercote
603380ed39 Avoid some struct_foo(..).emit() chains
These can be replaced with `foo(..)`.

Also make the return type of `report_unterminated_block_comment` more
precise.
2026-09-12 11:21:00 +10:00
khyperia
e93270b1d0 yeet type const 2026-09-11 17:08:12 +02:00
Jonathan Brouwer
e603db4aa6 Enable recover_arg_parse for parenthesized argument lists 2026-09-11 13:24:03 +02:00
Jonathan Brouwer
19c0f5c216 Don't suggest using a pattern when recover_arg_parse fails
While the stderrs in this commit are neutral, some better some worse, there were quite a few bad diagnostics if we enable `recover_arg_parse` for parenthesized argument lists
2026-09-11 13:23:11 +02:00
Jonathan Brouwer
acc7dd9f86 Add FnContext::ParenthesizedArgumentList 2026-09-11 12:15:44 +02:00
Jonathan Brouwer
19978b4b07 Correctly track first_param 2026-09-11 12:08:13 +02:00
León Orell Valerian Liehr
8a845e5d15 Clarify the code responsible for parsing bare trait object types
1. Rename `parse_ty_tuple_or_parens` to `parse_paren_start_ty` since it
   doesn't just parse parenthesized types and tuple types, it also parses
   bare trait object types where the first bound is parenthesized.
   Naming is inspired by `parse_path_start_ty`.
2. Don't use `parse_remaining_bounds_path` ("finish parsing bare trait
   object type") when recovering from `for<…> impl …` / `for<…> impl …`
   since we're in fact not parsing a bare trait object type but either an
   impl-Trait type or a dyn-Trait type. This means we no longer need to
   match on the `TyKind` to extract the `bounds`.
3. Rename `parse_remaining_bounds_path` to
   `finish_parsing_bare_trait_object_ty` since the previous name really
   didn't make it clear that it's specific to bare trait object types.
4. Add a bunch of comments explaining what we're doing in (now)
   `parse_paren_start_ty` to successfully parse a bare trait object type
   where the first bound is parenthesized.
5. Inline `parse_remaining_bounds` since it didn't really have any reason
   to exist. The callsites look just fine or even better with the inlined
   body.
2026-09-07 21:43:51 +02:00
León Orell Valerian Liehr
4c139efaa5 Simplify recovery from outer attributes on cfg_select branches
Admittedly, this slightly regresses diagnostic quality in certain
scenarios but this can be improved in the future *for all* users of
`recover_from_outer_attributes`.

For example, it's a bit contradictory to say "expected outer doc comment"
followed by "doc comments cannot be applied to XY". We should probably
only emit a single error saying "doc comments cannot be applied to XY"
but that needs modifications to `parse_outer_attributes` or something
similar.
2026-09-07 21:43:51 +02:00
León Orell Valerian Liehr
3d5b7aaa01 Simplify recovery from outer attributes on generic args
Use our new routine. Again, this means we can now also recover from
leading doc comments and inner attributes.

Moreover, we now actually store type & const arguments that have outer
attributes in the AST instead of using `{type error}` & `{const error}`
for them, respectively.
2026-09-07 21:43:51 +02:00
León Orell Valerian Liehr
712a16edb1 Remove specialized recovery from outer attributes on parameter types
Given we now recover from outer attributes on any type,
this specialized logic is no longer necessary.

Given we now recover from outer attributes on any type,
this specialized logic is no longer necessary.
2026-09-07 21:43:51 +02:00
León Orell Valerian Liehr
9875dda210 Remove unreachable condition from recovery code
In commit 0564168895, the check for doc
comments was added to prevent us from trying to reparse the type as a
const expression and suggesting to wrap it in `{` `}` if successful as
that's unlikely what the user meant.

However, now that we always try to parse outer attributes (including
doc comments) on types to provide better diagnostics, this case in
`parse_generic_arg` can't be reached anymore.
2026-09-07 21:43:51 +02:00
León Orell Valerian Liehr
e92a69499d Simplify recovery from outer attributes on types
Instead of checking for `#[` before trying to parse outer attributes,
check for `#` or doc comments instead. This way, we automatically recover
from leading doc comments and inner attributes on types, too.

Previously, we would only recover from doc comments and inner attributes
on types if they were preceded by normal outer attributes.

Move the whole recovery into a separate more general function in
preparation for using it in various other places, too.

This means we drop the recovery from attributes in type contexts that
aren't ascribed to a valid type (at least until the next sync point).
For example, `type T = #[a];` and `fn f() -> #[a] {}` are now fatal
(meaning the parser will only continue parsing from the next sync point).

This could be considered unfortunate but honestly it didn't make much sense:
Why would we only defatalize syntax errors in type contexts if there are
preceding attributes (which aren't legal / expected on types in the first
place, mind you); there's no reason to recover from e.g., `type T = #[a] @;`
(which used to lead to bad follow-up diagnostics). Defatalizing syntax
errors isn't inherently bad, it just needs to be done carefully and not
made dependent on "random" conditions.
2026-09-07 21:43:45 +02:00
León Orell Valerian Liehr
d82b08755b Remove obsolete recovery code from parse_generic_arg
See the previous commit for details.
2026-09-07 21:39:19 +02:00
León Orell Valerian Liehr
8af341adc3 Remove obsolete recovery logic for array & slice types
The logic was added in commit ff61949860
(2020) to suppress noisy follow-up syntax errors. For example, consider
`src/test/ui/issues/issue-39616.rs` from said commit.

However, removing it nowadays doesn't regress any diagnostics.

On the contrary, since we no longer try to recover from such malformed
array & slice types, the code in `parse_generic_arg` responsible for
attempting to recover from complex const exprs that weren't wrapped in
braces `{` `}` has an easier time to recover from e.g., `[10]` (as in
`Wrap<[10]>`) and doesn't need to create "dummy" diagnostics to attach
suggestions onto.

In the next commit, we'll remove the special casing of recovered array &
array types in `parse_generic_arg` that's no longer necessary.
2026-09-07 21:39:19 +02:00