about summary refs log tree commit diff
path: root/compiler/rustc_parse/src/parser
AgeCommit message (Collapse)AuthorLines
2025-10-03Rollup merge of #147245 - ↵Matthias Krüger-18/+16
karolzwolak:only-replace-intended-bar-not-all-in-pattern, r=lcnr only replace the intended comma in pattern suggestions Only suggest to replace the intended comma, not all bars in the pattern. Fixes rust-lang/rust#143330. This continues rust-lang/rust#143331, the credit for making the fix goes to `@A4-Tacks.` I just blessed tests and added a regression test.
2025-10-02bring back plural 'alternatives' in suggestion messageKarol Zwolak-1/+1
2025-10-02Rollup merge of #147004 - estebank:ascription-in-pat, r=fee1-deadMatthias Krüger-40/+58
Tweak handling of "struct like start" where a struct isn't supported This improves the case where someone tries to write a `match` expr where the patterns have type ascription syntax. Makes them less verbose, by giving up on the first encounter in the block, and makes them more accurate by only treating them as a struct literal if successfully parsed as such. Before, encountering something like `match a { b:` would confuse the parser and think everything after `match` *must* be a struct, and if it wasn't it would generate a cascade of unnecessary diagnostics.
2025-10-01Fix diagnostics str::replace comma to barA4-Tacks-18/+16
2025-09-29Use `Iterator::eq` and (dogfood) `eq_by` in compiler and libraryYotam Ofek-1/+1
2025-09-27Simplify logic slightlyEsteban Küber-15/+22
2025-09-24Tweak handling of "struct like start" where a struct isn't supportedEsteban Küber-45/+56
This improves the case where someone tries to write a `match` expr where the patterns have type ascription syntax. Makes them less verbose, by giving up on the first encounter in the block, and makes them more accurate by only treating them as a struct literal if successfuly parsed as such.
2025-09-16Detect top-level `...` in argument typeEsteban Küber-2/+11
When writing something like the expression `|_: ...| {}`, we now detect the `...` during parsing explicitly instead of relying on the detection in `parse_ty_common` so that we don't talk about "nested `...` are not supported". ``` error: unexpected `...` --> $DIR/no-closure.rs:6:35 | LL | const F: extern "C" fn(...) = |_: ...| {}; | ^^^ | = note: only `extern "C"` and `extern "C-unwind"` functions may have a C variable argument list ```
2025-09-15Detect attempt to use var-args in closureEsteban Küber-8/+19
``` error: unexpected `...` --> $DIR/varargs-in-closure-isnt-supported.rs:5:20 | LL | let mut lol = |...| (); | ^^^ not a valid pattern | = note: C-variadic type `...` is not allowed here ```
2025-09-11Rollup merge of #146422 - fmease:less-greedy-maybe-const-bounds, r=estebankStuart Cook-8/+11
Less greedily parse `[const]` bounds > [!IMPORTANT] > If you're coming here from any beta backport nomination thread on Zulip, only the last commit is truly relevant (the first commit doesn't need to be backported, it only contains test modifications)! Don't consider `[` to start a bound, only consider `[const]` in its entirety to do so. This drastically reduces (but doesn't eliminate!) the chance of *real* breakages. Like `const`, `~const` and `async` before, `[const]` unavoidably brings along theoretical breakages, see preexisting tests: `macro-const-trait-bound-theoretical-regression.rs` and `macro-async-trait-bound-theoretical-regression.rs`. Side note: It's unfortunate that we have to do this but apart from the known fact that MBE hurts forward compatibility, the `[const]` syntax is simply a bit scuffed (also CC'ing https://github.com/rust-lang/rust/issues/146122, section (3)). Fixes [after beta backport] rust-lang/rust#146417. * 1st commit: Restore the original test intentions of several preexisting related tests that were unfortunately lost over time * I've added a bunch of SCREAMING comments to make it less likely to be lost again * CC PR rust-lang/rust#119099 which added most of these tests * CC [#144409 (comment)](https://github.com/rust-lang/rust/pull/144409#discussion_r2337587513) for further context (NB: It's not the only PR that negatively affected the test intention) * 2nd commit: Actually address the regression r? `@oli-obk` or anyone
2025-09-10Less greedily parse `[const]` boundsLeón Orell Valerian Liehr-5/+8
2025-09-10Restore the test intention of several MBE trait bound modifier testsLeón Orell Valerian Liehr-3/+3
2025-09-10Rollup merge of #146340 - fmease:frontmatter-containment, r=fee1-dead,UrgauMatthias Krüger-2/+5
Strip frontmatter in fewer places * Stop stripping frontmatter in `proc_macro::Literal::from_str` (RUST-146132) * Stop stripping frontmatter in expr-ctxt (but not item-ctxt!) `include`s (RUST-145945) * Stop stripping shebang (!) in `proc_macro::Literal::from_str` * Not a breaking change because it did compare spans already to ensure there wasn't extra whitespace or comments (`Literal::from_str("#!\n0")` already yields `Err(_)` thankfully!) * Stop stripping frontmatter+shebang inside some rustdoc code where it doesn't make any observable difference (see self review comments) * (Stop stripping frontmatter+shebang inside internal test code) Fixes https://github.com/rust-lang/rust/issues/145945. Fixes https://github.com/rust-lang/rust/issues/146132. r? fee1-dead
2025-09-09Strip frontmatter in fewer placesLeón Orell Valerian Liehr-2/+5
2025-09-09Rollup merge of #145463 - jieyouxu:error-suffix, r=fmeaseMatthias Krüger-21/+10
Reject invalid literal suffixes in tuple indexing, tuple struct indexing, and struct field name position Tracking issue: rust-lang/rust#60210 Closes rust-lang/rust#60210 ## Summary Bump the ["suffixes on a tuple index are invalid" non-lint pseudo future-incompatibility warning (#60210)][issue-60210][^non-lint] to a **hard error** across all editions, rejecting the remaining carve outs from accidentally accepted invalid suffixes since Rust **1.27**. - We accidentally accepted invalid suffixes in tuple indexing positions in Rust **1.27**. Originally reported at https://github.com/rust-lang/rust/issues/59418. - We tried to hard reject all invalid suffixes in https://github.com/rust-lang/rust/pull/59421, but unfortunately it turns out there were proc macros accidentally relying on it: https://github.com/rust-lang/rust/issues/60138. - We temporarily accepted `{i,u}{32,size}` in https://github.com/rust-lang/rust/pull/60186 (the "*carve outs*") to mitigate *immediate* ecosystem impact, but it came with an FCW warning indicating that we wanted to reject it after a few Rust releases. - Now (1.89.0) is a few Rust releases later (1.35.0), thus I'm proposing to **also reject the carve outs**. - `std::mem::offset_of!` stabilized in Rust **1.77.0** happens to use the same "don't expect suffix" code path which has the carve outs, so it also accepted the carve out suffixes. I'm proposing to **reject this case as well**. ## What specifically breaks? Code that still relied on invalid `{i,u}{32,size}` suffixes being temporarily accepted by rust-lang/rust#60186 as an ecosystem impact mitigation measure (cf. rust-lang/rust#60138). Specifically, the following cases (particularly the construction of these forms in proc macros like reported in rust-lang/rust#60138): ### Position 1: Invalid `{i,u}{32,size}` suffixes in tuple indexing ```rs fn main() { let _x = (42,).0invalid; // Already error, already rejected by #59421 let _x = (42,).0i8; // Already error, not one of the #60186 carve outs. let _x = (42,).0usize; // warning: suffixes on a tuple index are invalid } ``` ### Position 2: Invalid `{i,u}{32,size}` suffixes in tuple struct indexing ```rs fn main() { struct X(i32); let _x = X(42); let _x = _x.0invalid; // Already error, already rejected by #59421 let _x = _x.0i8; // Already error, not one of the #60186 carve outs. let _x = _x.0usize; // warning: suffixes on a tuple index are invalid } ``` ### Position 3: Invalid `{i,u}{32,size}` suffixes in numeric struct field names ```rs fn main() { struct X(i32, i32, i32); let _x = X(1, 2, 3); let _y = X { 0usize: 42, 1: 42, 2: 42 }; // warning: suffixes on a tuple index are invalid match _x { X { 0usize: 1, 1: 2, 2: 3 } => todo!(), // warning: suffixes on a tuple index are invalid _ => {} } } ``` ### Position 4: Invalid `{i,u}{32,size}` suffixes in `std::mem::offset_of!` While investigating the warning, unfortunately I noticed `std::mem::offset_of!` also happens to use the "expect no suffix" code path which had the carve outs. So this was accepted since Rust **1.77.0** with the same FCW: ```rs fn main() { #[repr(C)] pub struct Struct<T>(u8, T); assert_eq!(std::mem::offset_of!(Struct<u32>, 0usize), 0); //~^ WARN suffixes on a tuple index are invalid } ``` ### The above forms in proc macros For instance, constructions like (see tracking issue rust-lang/rust#60210): ```rs let i = 0; quote! { foo.$i } ``` where the user needs to actually write ```rs let i = syn::Index::from(0); quote! { foo.$i } ``` ### Crater results Conducted a crater run (https://github.com/rust-lang/rust/pull/145463#issuecomment-3194920383). - https://github.com/AmlingPalantir/r4/tree/256af3c72f094b298cd442097ef7c571d8001f29: genuine regression; "invalid suffix `usize`" in derive macro. Has a ton of other build warnings, last updated 6 years ago. - Exactly the kind of intended breakage. Minimized down to https://github.com/AmlingPalantir/r4/blob/256af3c72f094b298cd442097ef7c571d8001f29/validates_derive/src/lib.rs#L71-L75, where when interpolation uses `quote`'s `ToTokens` on a `usize` index (i.e. on tuple struct `Tup(())`), the generated suffix becomes `.0usize` (cf. Position 2). - Notified crate author of breakage in https://github.com/AmlingPalantir/r4/issues/1. - Other failures are unrelated or spurious. ## Review remarks - Commits 1-3 expands the test coverage to better reflect the current situation before doing any functional changes. - Commit 4 is an intentional **breaking change**. We bump the non-lint "suffixes on a tuple index are invalid" warning into a hard error. Thus, this will need a crater run and a T-lang FCP. ## Tasks - [x] Run crater to check if anyone is still relying on this being not a hard error. Determine degree of ecosystem breakage. - [x] If degree of breakage seems acceptable, draft nomination report for T-lang for FCP. - [x] Determine hard error on Edition 2024+, or on all editions. ## Accompanying Reference update - https://github.com/rust-lang/reference/pull/1966 [^non-lint]: The FCW was implemented as a *non-lint* warning (meaning it has no associated lint name, and you can't `#![deny(..)]` it) because spans coming from proc macros could not be distinguished from regular field access. This warning was also intentionally impossible to silence. See https://github.com/rust-lang/rust/pull/60186#issuecomment-485581694. [issue-60210]: https://github.com/rust-lang/rust/issues/60210
2025-09-06Make `LetChainsPolicy` public for rustfmt usageMoritz Hedtke-1/+3
2025-09-02Rollup merge of #146094 - mohe2015:patch-2, r=lcnrGuillaume Gomez-1/+2
Make `Parser::parse_for_head` public for rustfmt usage Similar to https://github.com/rust-lang/rust/pull/138511, I want to add [dioxus rsx](https://dioxuslabs.com/learn/0.6/reference/rsx) formatting to [my rustfmt fork](https://github.com/tucant/rustfmt) and it would be much easier if that method would be public. Thanks.
2025-09-02Rollup merge of #145783 - Erk-:et-cetera-span, r=compiler-errorsGuillaume Gomez-1/+1
add span to struct pattern rest (..) Struct pattern rest (`..`) did not retain span information compared to normal fields. This patch adds span information for it. The motivation of this patch comes from when I implemented this PR for Clippy: https://github.com/rust-lang/rust-clippy/pull/15000#discussion_r2134145163 It is possible to get the span of the Et cetera in a bit roundabout way, but I thought this would be nicer.
2025-09-01Make `Parser::parse_for_head` public for rustfmt usageMoritz Hedtke-1/+2
2025-08-31Auto merge of #145582 - estebank:issue-107806, r=chenyukangbors-0/+96
Detect missing `if let` or `let-else` During `let` binding parse error and encountering a block, detect if there is a likely missing `if` or `else`: ``` error: expected one of `.`, `;`, `?`, `else`, or an operator, found `{` --> $DIR/missing-if-let-or-let-else.rs:14:25 | LL | let Some(x) = foo() { | ^ expected one of `.`, `;`, `?`, `else`, or an operator | help: you might have meant to use `if let` | LL | if let Some(x) = foo() { | ++ help: alternatively, you might have meant to use `let else` | LL | let Some(x) = foo() else { | ++++ ``` Fix rust-lang/rust#107806.
2025-08-30review comment: move `Visitor`Esteban Küber-27/+29
2025-08-28Improve error messages around invalid literals in attribute argumentsJonathan Brouwer-2/+2
Signed-off-by: Jonathan Brouwer <jonathantbrouwer@gmail.com>
2025-08-25add span to struct pattern rest (..)Valdemar Erk-1/+1
2025-08-25Remove the lifetime from `ExpTokenPair`/`SeqSep`.Nicholas Nethercote-49/+49
`TokenKind` now impls `Copy`, so we can store it directly rather than a reference.
2025-08-22Rollup merge of #144897 - fee1-dead-contrib:raw_lifetimes_printing, r=fmeaseJacob Pratt-3/+2
print raw lifetime idents with r# This replaces rust-lang/rust#143185 and fixes rust-lang/rust#143150 cc ``@fmease``
2025-08-22Rollup merge of #137396 - compiler-errors:param-default, r=fmeaseJacob Pratt-2/+25
Recover `param: Ty = EXPR` Fixes #137310 Pretty basic recovery here, but better than giving an unexpected token error.
2025-08-22Recover param: Ty = EXPRMichael Goulet-2/+25
2025-08-22Rewrite the new attribute parserJonathan Brouwer-11/+12
2025-08-22Move validate_attr to `rustc_attr_parsing`Jonathan Brouwer-1/+1
2025-08-22address review commentsDeadbeef-9/+2
2025-08-22don't print invalid labels with `r#`Deadbeef-1/+7
2025-08-21Rollup merge of #145604 - compiler-errors:static-closure, r=fmeaseJacob Pratt-2/+6
Gate static closures behind a parser feature I'd like to gate `static ||` closures behind a feature gate, since we shouldn't allow people to take advantage of this syntax if it's currently unstable. Right now, since it's only rejected after ast lowering, it's accessible to macros. Let's crater this to see if we can claw it back without breaking anyone's code.
2025-08-21Rollup merge of #145590 - nnethercote:ModKind-Inline, r=petrochenkovJacob Pratt-1/+1
Prevent impossible combinations in `ast::ModKind`. `ModKind::Loaded` has an `inline` field and a `had_parse_error` field. If the `inline` field is `Inline::Yes` then `had_parse_error` must be `Ok(())`. This commit moves the `had_parse_error` field into the `Inline::No` variant. This makes it impossible to create the nonsensical combination of `inline == Inline::Yes` and `had_parse_error = Err(_)`. r? ```@Urgau```
2025-08-20Detect missing `if let` or `let-else`Esteban Küber-0/+94
During `let` binding parse error and encountering a block, detect if there is a likely missing `if` or `else`: ``` error: expected one of `.`, `;`, `?`, `else`, or an operator, found `{` --> $DIR/missing-if-let-or-let-else.rs:14:25 | LL | let Some(x) = foo() { | ^ expected one of `.`, `;`, `?`, `else`, or an operator | help: you might have meant to use `if let` | LL | if let Some(x) = foo() { | ++ help: alternatively, you might have meant to use `let else` | LL | let Some(x) = foo() else { | ++++ ```
2025-08-20Auto merge of #145348 - nnethercote:parse_token_tree-speedup-for-uom, ↵bors-6/+17
r=petrochenkov Sometimes skip over tokens in `parse_token_tree`. r? `@petrochenkov`
2025-08-19Gate static coroutines behind a parser featureMichael Goulet-2/+6
2025-08-19Prevent impossible combinations in `ast::ModKind`.Nicholas Nethercote-1/+1
`ModKind::Loaded` has an `inline` field and a `had_parse_error` field. If the `inline` field is `Inline::Yes` then `had_parse_error` must be `Ok(())`. This commit moves the `had_parse_error` field into the `Inline::No` variant. This makes it impossible to create the nonsensical combination of `inline == Inline::Yes` and `had_parse_error = Err(_)`.
2025-08-19Rollup merge of #145474 - fmease:paren-use-bounds-fix, r=fee1-dead许杰友 Jieyou Xu (Joe)-73/+89
Properly recover from parenthesized use-bounds (precise capturing lists) plus small cleanups Fixes https://github.com/rust-lang/rust/issues/145470. First commit fixes the issue, second one performs some desperately needed cleanups. The fix shouldn't be a breaking change because IINM the parser always ensures that all brackets are balanced (via a buffer of brackets). Meaning even though we used to accept `(use<>` as a valid precise capturing list, it was guaranteed that we would fail in the end.
2025-08-18Turn invalid index suffixes into hard errorsJieyou Xu-21/+10
2025-08-16Clean up parsers related to generic boundsLeón Orell Valerian Liehr-73/+79
2025-08-16Properly recover from parenthesized use-bounds (precise capturing)León Orell Valerian Liehr-16/+26
2025-08-15Rollup merge of #145378 - xizheyin:144968, r=davidtwcoStuart Cook-34/+94
Add `FnContext` in parser for diagnostic Fixes rust-lang/rust#144968 Inspired by https://github.com/rust-lang/rust/issues/144968#issuecomment-3156094581, I implemented `FnContext` to indicate whether a function should have a self parameter, for example, whether the function is a trait method, whether it is in an impl block. And I removed the outdated note. I made two commits to show the difference. cc ``@estebank`` ``@djc`` r? compiler
2025-08-14Rollup merge of #145233 - joshtriplett:cfg-select-expr, r=jieyouxuJakub Beránek-11/+19
cfg_select: Support unbraced expressions Tracking issue for `cfg_select`: rust-lang/rust#115585 When operating on expressions, `cfg_select!` can now handle expressions without braces. (It still requires braces for other things, such as items.) Expand the test coverage and documentation accordingly. --- I'm not sure whether deciding to extend `cfg_select!` in this way is T-lang or T-libs-api. I've labeled for both, with the request that both teams don't block on each other. :)
2025-08-14Rollup merge of #137872 - estebank:extra-vert, r=compiler-errorsJakub Beránek-8/+10
Include whitespace in "remove |" suggestion and make it hidden Tweak error rendering of patterns with an extra `|` on either end. Built on #137409. Only last commit is relevant. ? ``@compiler-errors``
2025-08-14Add FnContext in parser for diagnosticxizheyin-34/+94
Signed-off-by: xizheyin <xizheyin@smail.nju.edu.cn>
2025-08-14Sometimes skip over tokens in `parse_token_tree`.Nicholas Nethercote-6/+17
This sometimes avoids a lot of `bump` calls.
2025-08-11Extract ast TraitImplHeaderCameron Steffen-14/+13
2025-08-11Tweak trait modifier errorsCameron Steffen-19/+10
2025-08-11Move trait impl modifier errors to parsingCameron Steffen-1/+35
This is a technically a breaking change for what can be parsed in `#[cfg(false)]`.
2025-08-10cfg_select: Support unbraced expressionsJosh Triplett-11/+19
When operating on expressions, `cfg_select!` can now handle expressions without braces. (It still requires braces for other things, such as items.) Expand the test coverage and documentation accordingly.