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.)
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.
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.
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>
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>
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>`.
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!()`
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!
`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.
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)".
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.
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>
Suggest keyword order for `extern "C" const unsafe fn`
closesrust-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.
Simplify the `G` in `Diag<'a, G>`
The `EmissionGuarantee` trait isn't necessary, and just complicates things. Details in individual commits.
r? @oli-obk
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
This makes code like this compile:
#![feature(try_blocks_heterogeneous)]
macro_rules! make { ($kw:ident) => { try $kw Option<()> {} } }
fn scope() { make!(bikeshed); }
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.
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
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.
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.
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.
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.
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.
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.
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.