2624 Commits

Author SHA1 Message Date
Stuart Cook
d037d1097f
Rollup merge of #146422 - fmease:less-greedy-maybe-const-bounds, r=estebank
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-11 14:06:32 +10:00
León Orell Valerian Liehr
f5dad62d4c
Less greedily parse [const] bounds 2025-09-10 23:24:31 +02:00
León Orell Valerian Liehr
1558e65c9e
Restore the test intention of several MBE trait bound modifier tests 2025-09-10 23:24:31 +02:00
Matthias Krüger
86d39a0673
Rollup merge of #146340 - fmease:frontmatter-containment, r=fee1-dead,Urgau
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-10 20:29:09 +02:00
León Orell Valerian Liehr
7a66925a81
Strip frontmatter in fewer places 2025-09-09 19:49:40 +02:00
Matthias Krüger
12e548704e
Rollup merge of #145463 - jieyouxu:error-suffix, r=fmease
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).

- 256af3c72f: 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 256af3c72f/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-09 17:32:20 +02:00
Moritz Hedtke
7fada167f9 Make LetChainsPolicy public for rustfmt usage 2025-09-06 18:01:31 +02:00
Urgau
d224d3a8fa Disallow shebang in --cfg and --check-cfg arguments 2025-09-06 00:21:04 +02:00
Stuart Cook
10cbfe6e20
Rollup merge of #146137 - Urgau:cfg-disallow-frontmatter, r=fmease
Disallow frontmatter in `--cfg` and `--check-cfg` arguments

This PR disallows the frontmatter syntax in `--cfg` and `--check-cfg` arguments.

Fixes https://github.com/rust-lang/rust/issues/146130
r? fmease
2025-09-04 10:02:03 +10:00
Stuart Cook
6f490f7ae1
Rollup merge of #146112 - scrabsha:push-utkysktvulto, r=WaffleLapkin
don't uppercase error messages
2025-09-04 10:01:59 +10:00
Sasha Pourcelot
5c4b61b4b4 don't uppercase error messages
a more general version of https://github.com/rust-lang/rust/pull/146080.

after a bit of hacking in [`fluent.rs`](https://github.com/rust-lang/rust/blob/master/compiler/rustc_fluent_macro/src/fluent.rs), i discovered that i'm not the only one that is bad at following guidelines 😅. this pr lowercases the first letter of all the error messages in the codebase.

(i did not change things that are traditionally uppercased such as _MIR_, _ABI_ or _C_)

i think it's reasonable to run a `@bors try` so all the test suite is checked, as i cannot run some of the tests on my machine. i double checked (and replaced manually) all the old error messages, but better be safe than sorry.

in the future i will try to add a check in `x test tidy` that errors if an error message starts with an uppercase letter.
2025-09-03 15:24:49 +02:00
Stuart Cook
56213a553e
Rollup merge of #146106 - epage:whitespace, r=fee1-dead
fix(lexer): Only allow horizontal whitespace in frontmatter

In writing up the reference for frontmatter, I realized that we probably
shouldn't be accepting Unicode Line Ending characters between the code
fence and infostring or trailing after the infostring or a code fence.

In digging into the unicode specification we use for Whitespace, it
divides it up into categories, so I'm deferring to what it says for
horizontal whitespace for what should be used within a line.

Note, I am leaving out support for Unicode Default Ignorable characters.
I figure that can be discussed outside of this change within the
reference and tracking issue.

Fixes rust-lang/rust#145971

Frontmatter tracking issue: rust-lang/rust#136889
2025-09-03 23:08:10 +10:00
Urgau
0fa93a3434 Disallow frontmatter in --cfg and --check-cfg arguments 2025-09-03 08:01:03 +02:00
Guillaume Gomez
8408bca605
Rollup merge of #146094 - mohe2015:patch-2, r=lcnr
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-02 17:08:57 +02:00
Guillaume Gomez
af315b0725
Rollup merge of #145783 - Erk-:et-cetera-span, r=compiler-errors
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-02 17:08:52 +02:00
Nicholas Nethercote
301655eafe Revert introduction of [workspace.dependencies].
This was done in #145740 and #145947. It is causing problems for people
using r-a on anything that uses the rustc-dev rustup package, e.g. Miri,
clippy.

This repository has lots of submodules and subtrees and various
different projects are carved out of pieces of it. It seems like
`[workspace.dependencies]` will just be more trouble than it's worth.
2025-09-02 19:12:54 +10:00
Ed Page
6f0da976c5 fix(lexer): Only allow horizontal whitespace in frontmatter
In writing up the reference for frontmatter, I realized that we probably
shouldn't be accepting Unicode Line Ending characters between the code
fence and infostring or trailing after the infostring or a code fence.

In digging into the unicode specification we use for Whitespace, it
divides it up into categories, so I'm deferring to what it says for
horizontal whitespace for what should be used within a line.

Note, I am leaving out support for Unicde Default Ignorable characters.
I figure that can be discussed outside of this change within the
reference and tracking issue.
2025-09-01 20:51:39 -05:00
Moritz Hedtke
d8df6312d5 Make Parser::parse_for_head public for rustfmt usage 2025-09-01 17:30:47 +02:00
bors
64a99db105 Auto merge of #145582 - estebank:issue-107806, r=chenyukang
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-31 03:00:54 +00:00
Esteban Küber
3af81cf0b7 review comment: move Visitor 2025-08-30 18:42:07 +00:00
Jonathan Brouwer
f328709276
Improve error messages around invalid literals in attribute arguments
Signed-off-by: Jonathan Brouwer <jonathantbrouwer@gmail.com>
2025-08-28 20:05:04 +02:00
Nicholas Nethercote
c50d2cc807 Add tracing to [workspace.dependencies]. 2025-08-27 14:21:19 +10:00
Nicholas Nethercote
32b0fff8fe Add rustc-literal-escaper to [workspace.dependencies]. 2025-08-27 13:59:32 +10:00
Nicholas Nethercote
82c4b9c51b Add bitflags to [workspace.dependencies]. 2025-08-27 13:59:32 +10:00
Nicholas Nethercote
777e2d6a2a Add thin-vec to newly added [workspace.dependencies]. 2025-08-27 13:59:32 +10:00
Valdemar Erk
75d8687f2b add span to struct pattern rest (..) 2025-08-25 09:55:50 +02:00
Nicholas Nethercote
a06c3887bd Remove the lifetime from ExpTokenPair/SeqSep.
`TokenKind` now impls `Copy`, so we can store it directly rather than a
reference.
2025-08-25 08:02:52 +10:00
Jacob Pratt
d3c9908a8a
Rollup merge of #145747 - joshtriplett:builtin-diag-dyn, r=jdonszelmann
Refactor lint buffering to avoid requiring a giant enum

Lint buffering currently relies on a giant enum `BuiltinLintDiag` containing all the lints that might potentially get buffered. In addition to being an unwieldy enum in a central crate, this also makes `rustc_lint_defs` a build bottleneck: it depends on various types from various crates (with a steady pressure to add more), and many crates depend on it.

Having all of these variants in a separate crate also prevents detecting when a variant becomes unused, which we can do with a dedicated type defined and used in the same crate.

Refactor this to use a dyn trait, to allow using `LintDiagnostic` types directly.

Because the existing `BuiltinLintDiag` requires some additional types in order to decorate some variants, which are only available later in `rustc_lint`, use an enum `DecorateDiagCompat` to handle both the `dyn LintDiagnostic` case and the `BuiltinLintDiag` case.

---

With the infrastructure in place, use it to migrate three of the enum variants to use `LintDiagnostic` directly, as a proof of concept and to demonstrate that the net result is a reduction in code size and a removal of a boilerplate-heavy layer of indirection.

Also remove an unused `BuiltinLintDiag` variant.
2025-08-22 22:00:59 -04:00
Jacob Pratt
2dbd411d22
Rollup merge of #144897 - fee1-dead-contrib:raw_lifetimes_printing, r=fmease
print raw lifetime idents with r#

This replaces rust-lang/rust#143185 and fixes rust-lang/rust#143150

cc ``@fmease``
2025-08-22 22:00:47 -04:00
Jacob Pratt
85c9af57f4
Rollup merge of #137396 - compiler-errors:param-default, r=fmease
Recover `param: Ty = EXPR`

Fixes #137310

Pretty basic recovery here, but better than giving an unexpected token error.
2025-08-22 22:00:44 -04:00
Michael Goulet
6caa586f57
Recover param: Ty = EXPR 2025-08-22 21:45:28 +02:00
Josh Triplett
52fadd8f96 Migrate BuiltinLintDiag::HiddenUnicodeCodepoints to use LintDiagnostic directly 2025-08-22 03:01:35 -07:00
Jonathan Brouwer
549314bdb7
Rewrite the new attribute parser 2025-08-22 08:38:37 +02:00
Jonathan Brouwer
21d3189779
Move validate_attr to rustc_attr_parsing 2025-08-22 08:37:19 +02:00
Deadbeef
4970127c33 address review comments 2025-08-22 13:16:44 +08:00
Deadbeef
30bb7045d6 don't print invalid labels with r# 2025-08-22 12:58:37 +08:00
Jacob Pratt
f49d69093e
Rollup merge of #145604 - compiler-errors:static-closure, r=fmease
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-21 17:57:52 -04:00
Jacob Pratt
25b81bf5ad
Rollup merge of #145590 - nnethercote:ModKind-Inline, r=petrochenkov
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-21 01:12:19 -04:00
Esteban Küber
d216ca0506 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 {
   |                         ++++
```
2025-08-20 18:26:04 +00:00
bors
bec747418c Auto merge of #145348 - nnethercote:parse_token_tree-speedup-for-uom, r=petrochenkov
Sometimes skip over tokens in `parse_token_tree`.

r? `@petrochenkov`
2025-08-20 09:01:41 +00:00
bors
f605b57042 Auto merge of #145601 - jieyouxu:rollup-t5mbqhc, r=jieyouxu
Rollup of 10 pull requests

Successful merges:

 - rust-lang/rust#145538 (bufreader::Buffer::backshift: don't move the uninit bytes)
 - rust-lang/rust#145542 (triagebot: Don't warn no-mentions on subtree updates)
 - rust-lang/rust#145549 (Update rust maintainers in openharmony.md)
 - rust-lang/rust#145550 (Avoid using `()` in `derive(From)` output.)
 - rust-lang/rust#145556 (Allow stability attributes on extern crates)
 - rust-lang/rust#145560 (Remove unused `PartialOrd`/`Ord` from bootstrap)
 - rust-lang/rust#145568 (ignore frontmatters in `TokenStream::new`)
 - rust-lang/rust#145571 (remove myself from some adhoc-groups and pings)
 - rust-lang/rust#145576 (Add change tracker entry for `--timings`)
 - rust-lang/rust#145578 (Add VEXos "linked files" support to `armv7a-vex-v5`)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-08-19 23:52:06 +00:00
Michael Goulet
db0c825d2c Gate static coroutines behind a parser feature 2025-08-19 13:12:31 +00:00
Nicholas Nethercote
bfd5d59f97 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(_)`.
2025-08-19 21:57:31 +10:00
许杰友 Jieyou Xu (Joe)
b638266f23
Rollup merge of #145474 - fmease:paren-use-bounds-fix, r=fee1-dead
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-19 19:45:33 +08:00
Jieyou Xu
ddd99930f3
Turn invalid index suffixes into hard errors 2025-08-18 21:57:11 +08:00
Deadbeef
c335d5781d ignore frontmatters in TokenStream::new 2025-08-18 20:28:29 +08:00
León Orell Valerian Liehr
f8f7c27d4f
Clean up parsers related to generic bounds 2025-08-16 16:15:58 +02:00
León Orell Valerian Liehr
eb3e0d4c8a
Properly recover from parenthesized use-bounds (precise capturing) 2025-08-16 01:21:35 +02:00
Stuart Cook
dc047f1385
Rollup merge of #145378 - xizheyin:144968, r=davidtwco
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-15 16:16:41 +10:00
Jakub Beránek
01bd889098
Rollup merge of #145233 - joshtriplett:cfg-select-expr, r=jieyouxu
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-14 21:48:42 +02:00