Commit Graph

1584 Commits

Author SHA1 Message Date
Matthias Krüger
20473eba0b
Rollup merge of #118394 - nnethercote:rm-hir-Ops, r=cjgillot
Remove HIR opkinds

`hir::BinOp`, `hir::BinOpKind`, and `hir::UnOp` are identical to `ast::BinOp`, `ast::BinOpKind`, and `ast::UnOp`, respectively. This seems silly, so this PR removes the HIR ones. (A re-export lets the AST ones be referred to using a `hir::` qualifier, which avoids renaming churn.)

r? `@cjgillot`
2023-11-29 04:23:23 +01:00
Nadrieril
a3838c8550 Add never_patterns feature gate 2023-11-29 03:58:29 +01:00
Esteban Küber
55e4e3e393 Suggest let or == on typo'd let-chain
When encountering a bare assignment in a let-chain, suggest turning the
assignment into a `let` expression or an equality check.

```
error: expected expression, found `let` statement
  --> $DIR/bad-if-let-suggestion.rs:5:8
   |
LL |     if let x = 1 && i = 2 {}
   |        ^^^^^^^^^
   |
   = note: only supported directly in conditions of `if` and `while` expressions
help: you might have meant to continue the let-chain
   |
LL |     if let x = 1 && let i = 2 {}
   |                     +++
help: you might have meant to compare for equality
   |
LL |     if let x = 1 && i == 2 {}
   |                        +
```
2023-11-28 18:07:52 +00:00
Michael Goulet
203aaf62a9
Rollup merge of #111133 - hkmatsumoto:handle-python-slicing, r=TaKO8Ki
Detect Python-like slicing and suggest how to fix

Fix #108215
2023-11-27 19:06:45 -05:00
Nicholas Nethercote
705b484922 Rename BinOpKind::lazy as BinOpKind::is_lazy.
To match `BinOpKind::is_comparison` and `hir::BinOpKind::is_lazy`.
2023-11-28 09:45:40 +11:00
Nicholas Nethercote
0efd2a9d8f Rework ast::BinOpKind::to_string and ast::UnOp::to_string.
- Rename them both `as_str`, which is the typical name for a function
  that returns a `&str`. (`to_string` is appropriate for functions
  returning `String` or maybe `Cow<'a, str>`.)
- Change `UnOp::as_str` from an associated function (weird!) to a
  method.
- Avoid needless `self` dereferences.
2023-11-28 09:42:07 +11:00
Hirochika Matsumoto
acec70de9b Change help message to make some sense in broader context 2023-11-27 22:18:03 +09:00
Hirochika Matsumoto
730d299354 Address review feedbacks
Also addressed merge conflicts upon rebasing.
2023-11-27 22:06:42 +09:00
Hirochika Matsumoto
61c3e4d56e Make tidy test happy 2023-11-27 21:48:10 +09:00
Hirochika Matsumoto
e65c060d78 Detect Python-like slicing and suggest how to fix
Fix #108215
2023-11-27 21:48:10 +09:00
Hirochika Matsumoto
f4c2bdeec9 Suggest swapping the order of ref and box 2023-11-27 21:38:19 +09:00
Nicholas Nethercote
57cd5e6551 Use rustc_fluent_macro::fluent_messages! directly.
Currently we always do this:
```
use rustc_fluent_macro::fluent_messages;
...
fluent_messages! { "./example.ftl" }
```
But there is no need, we can just do this everywhere:
```
rustc_fluent_macro::fluent_messages! { "./example.ftl" }
```
which is shorter.
2023-11-26 08:38:40 +11:00
Nicholas Nethercote
a733082be9 Avoid need for {D,Subd}iagnosticMessage imports.
The `fluent_messages!` macro produces uses of
`crate::{D,Subd}iagnosticMessage`, which means that every crate using
the macro must have this import:
```
use rustc_errors::{DiagnosticMessage, SubdiagnosticMessage};
```

This commit changes the macro to instead use
`rustc_errors::{D,Subd}iagnosticMessage`, which avoids the need for the
imports.
2023-11-26 08:38:00 +11:00
Deadbeef
16040a1628 Add Span to TraitBoundModifier 2023-11-24 14:32:05 +00:00
Nilstrieb
21a870515b Fix clippy::needless_borrow in the compiler
`x clippy compiler -Aclippy::all -Wclippy::needless_borrow --fix`.

Then I had to remove a few unnecessary parens and muts that were exposed
now.
2023-11-21 20:13:40 +01:00
Michael Goulet
e6a3ca0c65
Rollup merge of #117988 - estebank:issue-106020, r=cjgillot
Handle attempts to have multiple `cfg`d tail expressions

When encountering code that seems like it might be trying to have multiple tail expressions depending on `cfg` information, suggest alternatives that will success to parse.

```rust
fn foo() -> String {
    #[cfg(feature = "validation")]
    [1, 2, 3].iter().map(|c| c.to_string()).collect::<String>()
    #[cfg(not(feature = "validation"))]
    String::new()
}
```

```
error: expected `;`, found `#`
  --> $DIR/multiple-tail-expr-behind-cfg.rs:5:64
   |
LL |     #[cfg(feature = "validation")]
   |     ------------------------------ only `;` terminated statements or tail expressions are allowed after this attribute
LL |     [1, 2, 3].iter().map(|c| c.to_string()).collect::<String>()
   |                                                                ^ expected `;` here
LL |     #[cfg(not(feature = "validation"))]
   |     - unexpected token
   |
help: add `;` here
   |
LL |     [1, 2, 3].iter().map(|c| c.to_string()).collect::<String>();
   |                                                                +
help: alternatively, consider surrounding the expression with a block
   |
LL |     { [1, 2, 3].iter().map(|c| c.to_string()).collect::<String>() }
   |     +                                                             +
help: it seems like you are trying to provide different expressions depending on `cfg`, consider using `if cfg!(..)`
   |
LL ~     if cfg!(feature = "validation") {
LL ~         [1, 2, 3].iter().map(|c| c.to_string()).collect::<String>()
LL ~     } else if cfg!(not(feature = "validation")) {
LL ~         String::new()
LL +     }
   |
```

Fix #106020.

r? `@oli-obk`
2023-11-19 19:14:34 -08:00
Michael Goulet
a7f805d277
Rollup merge of #117891 - compiler-errors:recover-for-dyn, r=davidtwco
Recover `dyn` and `impl` after `for<...>`

Recover `dyn` and `impl` after `for<...>` in types. Reuses the logic for parsing bare trait objects, so it doesn't fix cases like `for<'a> dyn Trait + dyn Trait` or anything, but that seems somewhat of a different issue.

Parsing recovery logic is a bit involved, but I couldn't find a way to simplify it.

Fixes #117882
2023-11-19 19:14:33 -08:00
Esteban Küber
f1ae02f4bd Don't sort span_suggestions, leave that to caller 2023-11-19 17:50:45 +00:00
bors
2831701757 Auto merge of #114292 - estebank:issue-71039, r=b-naber
More detail when expecting expression but encountering bad macro argument

On nested macro invocations where the same macro fragment changes fragment type from one to the next, point at the chain of invocations and at the macro fragment definition place, explaining that the change has occurred.

Fix #71039.

```
error: expected expression, found pattern `1 + 1`
  --> $DIR/trace_faulty_macros.rs:49:37
   |
LL |     (let $p:pat = $e:expr) => {test!(($p,$e))};
   |                   -------                -- this is interpreted as expression, but it is expected to be pattern
   |                   |
   |                   this macro fragment matcher is expression
...
LL |     (($p:pat, $e:pat)) => {let $p = $e;};
   |               ------                ^^ expected expression
   |               |
   |               this macro fragment matcher is pattern
...
LL |     test!(let x = 1+1);
   |     ------------------
   |     |             |
   |     |             this is expected to be expression
   |     in this macro invocation
   |
   = note: when forwarding a matched fragment to another macro-by-example, matchers in the second macro will see an opaque AST of the fragment type, not the underlying tokens
   = note: this error originates in the macro `test` (in Nightly builds, run with -Z macro-backtrace for more info)
```
2023-11-17 20:57:12 +00:00
Matthias Krüger
a5d7f8bcf2
Rollup merge of #117990 - estebank:issue-100825-part-deux, r=Nilstrieb
Tweak error and move tests

r? `@Nilstrieb`

Split off #117565.
2023-11-17 00:41:24 +01:00
Matthias Krüger
92aba63d6b
Rollup merge of #117892 - estebank:fat-arrow-typo, r=compiler-errors
Detect more `=>` typos

Handle and recover `match expr { pat >= { arm } }`.
2023-11-17 00:41:22 +01:00
Esteban Küber
099eb40932 Fix code indentation 2023-11-16 21:54:04 +00:00
Esteban Küber
a16722d221 Handle attempts to have multiple cfgd tail expressions
When encountering code that seems like it might be trying to have
multiple tail expressions depending on `cfg` information, suggest
alternatives that will success to parse.

```rust
fn foo() -> String {
    #[cfg(feature = "validation")]
    [1, 2, 3].iter().map(|c| c.to_string()).collect::<String>()
    #[cfg(not(feature = "validation"))]
    String::new()
}
```

```
error: expected `;`, found `#`
  --> $DIR/multiple-tail-expr-behind-cfg.rs:5:64
   |
LL |     #[cfg(feature = "validation")]
   |     ------------------------------ only `;` terminated statements or tail expressions are allowed after this attribute
LL |     [1, 2, 3].iter().map(|c| c.to_string()).collect::<String>()
   |                                                                ^ expected `;` here
LL |     #[cfg(not(feature = "validation"))]
   |     - unexpected token
   |
help: add `;` here
   |
LL |     [1, 2, 3].iter().map(|c| c.to_string()).collect::<String>();
   |                                                                +
help: alternatively, consider surrounding the expression with a block
   |
LL |     { [1, 2, 3].iter().map(|c| c.to_string()).collect::<String>() }
   |     +                                                             +
help: it seems like you are trying to provide different expressions depending on `cfg`, consider using `if cfg!(..)`
   |
LL ~     if cfg!(feature = "validation") {
LL ~         [1, 2, 3].iter().map(|c| c.to_string()).collect::<String>()
LL ~     } else if cfg!(not(feature = "validation")) {
LL ~         String::new()
LL +     }
   |
```

Fix #106020.
2023-11-16 21:21:26 +00:00
Esteban Küber
1c6bd0b12b Smaller span for unnessary mut suggestion 2023-11-16 16:58:41 +00:00
Esteban Küber
4e418805da More detail when expecting expression but encountering bad macro argument
Partially address #71039.
2023-11-16 16:19:04 +00:00
Mark Rousskov
917f6540ed Re-format code with new rustfmt 2023-11-15 21:45:48 -05:00
bohan
4138702621 discard invalid spans in external blocks 2023-11-15 15:28:38 +08:00
cui fliter
a44a4edc0e Fix some typos
Signed-off-by: cui fliter <imcusg@gmail.com>
2023-11-14 23:06:50 +08:00
Esteban Küber
f830fe313b Detect more => typos
Handle and recover `match expr { pat >= { arm } }`.
2023-11-14 00:46:37 +00:00
Michael Goulet
a8a2ee4e8f Recover dyn and impl after for<...> 2023-11-14 00:15:10 +00:00
bors
ea1e5cc91f Auto merge of #117770 - sjwang05:issue-117766, r=estebank,TaKO8Ki
Catch stray `{` in let-chains

Fixes #117766
2023-11-13 01:57:59 +00:00
sjwang05
274824b917
Fix is_keyword_ahead visibility
Co-authored-by: Takayuki Maeda <takoyaki0316@gmail.com>
2023-11-12 14:46:01 -08:00
sjwang05
f88cf0206f
Move unclosed delim errors to separate function 2023-11-11 13:39:08 -08:00
sjwang05
a49368f00b
Correctly handle while-let-chains 2023-11-10 12:13:53 -08:00
sjwang05
9455259450
Catch an edge case 2023-11-09 20:07:17 -08:00
sjwang05
0094238157
Catch stray { in let-chains 2023-11-09 18:47:49 -08:00
sjwang05
5693a34db2
Suggest fix for ; within let-chains 2023-11-09 00:31:42 -08:00
Guillaume Gomez
c828371179
Rollup merge of #117282 - clubby789:recover-wrong-function-header, r=TaKO8Ki
Recover from incorrectly ordered/duplicated function keywords

Fixes #115714
2023-11-08 17:14:36 +01:00
bors
187d1afa9d Auto merge of #117297 - clubby789:fn-trait-missing-paren, r=TaKO8Ki
Give a better diagnostic for missing parens in Fn* bounds

Fixes #108109

It would be nice to try and recover here, but I'm not sure it's worth the effort, especially as the bounds on the recovered function would be incorrect.
2023-11-07 13:04:56 +00:00
Dinu Blanovschi
a6b41aa6ba fmt 2023-11-04 20:04:02 +01:00
Dinu Blanovschi
8de489918b feat(hir): Store the Span of the move keyword 2023-11-04 19:39:32 +01:00
bors
9c20ddd956 Auto merge of #117507 - nnethercote:rustc_span, r=Nilstrieb
`rustc_span` cleanups

Just some things I found while looking over this crate.

r? `@oli-obk`
2023-11-03 14:57:40 +00:00
Nicholas Nethercote
f405ce86c2 Minimize pub usage in source_map.rs.
Most notably, this commit changes the `pub use crate::*;` in that file
to `use crate::*;`. This requires a lot of `use` items in other crates
to be adjusted, because everything defined within `rustc_span::*` was
also available via `rustc_span::source_map::*`, which is bizarre.

The commit also removes `SourceMap::span_to_relative_line_string`, which
is unused.
2023-11-02 19:35:00 +11:00
Matthias Krüger
2b2360abb1
Rollup merge of #117298 - clubby789:fn-missing-params, r=petrochenkov
Recover from missing param list in function definitions

Addresses the other issue mentioned in #108109
2023-11-01 21:40:05 +01:00
bors
b0a07595b5 Auto merge of #117289 - estebank:issue-72298, r=cjgillot
Account for `ref` and `mut` in the wrong place for pattern ident renaming

If the user writes `S { ref field: name }` instead of `S { field: ref name }`, we suggest the correct code.

Fix #72298.
2023-11-01 18:39:01 +00:00
clubby789
904aceec7d Give a better diagnostic for missing parens in Fn* bounds 2023-11-01 15:33:46 +00:00
clubby789
ca1bcb6466 Recover from missing param list in function definitions 2023-11-01 14:48:20 +00:00
John Millikin
0f41bc21b9 Stabilize C string literals 2023-11-01 09:16:34 +09:00
Matthias Krüger
7035c3d718
Rollup merge of #116712 - estebank:issue-116252, r=petrochenkov
When encountering unclosed delimiters during lexing, check for diff markers

Fix #116252.
2023-10-31 12:55:09 +01:00
bors
31bc7e2c47 Auto merge of #117415 - matthiaskrgr:rollup-jr2p1t2, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #116862 (Detect when trait is implemented for type and suggest importing it)
 - #117389 (Some diagnostics improvements of `gen` blocks)
 - #117396 (Don't treat closures/coroutine types as part of the public API)
 - #117398 (Correctly handle nested or-patterns in exhaustiveness)
 - #117403 (Poison check_well_formed if method receivers are invalid to prevent typeck from running on it)
 - #117411 (Improve some diagnostics around `?Trait` bounds)
 - #117414 (Don't normalize to an un-revealed opaque when we hit the recursion limit)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-10-30 20:50:14 +00:00
Oli Scherer
745c600617 Talk about gen fn in diagnostics about gen fn 2023-10-30 10:13:12 +00:00
Esteban Küber
50ca5ef07f When encountering unclosed delimiters during parsing, check for diff markers
Fix #116252.
2023-10-30 00:56:46 +00:00
Esteban Küber
b589f47441 Account for ref and mut in the wrong place for pattern ident renaming
If the user writes `S { ref field: name }` instead of
`S { field: ref name }`, we suggest the correct code.

Fix #72298.
2023-10-30 00:15:49 +00:00
Nicholas Nethercote
8ff624a9f2 Clean up rustc_*/Cargo.toml.
- Sort dependencies and features sections.
- Add `tidy` markers to the sorted sections so they stay sorted.
- Remove empty `[lib`] sections.
- Remove "See more keys..." comments.

Excluded files:
- rustc_codegen_{cranelift,gcc}, because they're external.
- rustc_lexer, because it has external use.
- stable_mir, because it has external use.
2023-10-30 08:46:02 +11:00
bors
88ae8c9385 Auto merge of #116889 - MU001999:master, r=petrochenkov
Eat close paren if capture_cfg to avoid unbalanced parens

Fixes #116781
2023-10-29 16:46:47 +00:00
bors
2cad938a81 Auto merge of #116447 - oli-obk:gen_fn, r=compiler-errors
Implement `gen` blocks in the 2024 edition

Coroutines tracking issue https://github.com/rust-lang/rust/issues/43122
`gen` block tracking issue https://github.com/rust-lang/rust/issues/117078

This PR implements `gen` blocks that implement `Iterator`. Most of the logic with `async` blocks is shared, and thus I renamed various types that were referring to `async` specifically.

An example usage of `gen` blocks is

```rust
fn foo() -> impl Iterator<Item = i32> {
    gen {
        yield 42;
        for i in 5..18 {
            if i.is_even() { continue }
            yield i * 2;
        }
    }
}
```

The limitations (to be resolved) of the implementation are listed in the tracking issue
2023-10-29 00:03:52 +00:00
Mu001999
fe00cfef57 restore snapshot when parse_param_general 2023-10-28 08:53:51 +08:00
clubby789
be0b42fabe Recover from incorrectly ordered/duplicated function keywords 2023-10-27 18:29:43 +00:00
Matthias Krüger
b2295375f8
Rollup merge of #117212 - clubby789:fix-ternary-recover, r=compiler-errors
Properly restore snapshot when failing to recover parsing ternary

If the recovery parsed an expression, then failed to eat a `:`, it would return `false` without restoring the snapshot. Fix this by always restoring the snapshot when returning `false`.

Draft for now because I'd like to try and improve this recovery further.

Fixes #117208
2023-10-27 19:46:07 +02:00
Oli Scherer
4ac25faf9f Handle move generators 2023-10-27 13:05:48 +00:00
Oli Scherer
638d2d6fc1 Feature gate gen blocks, even in 2024 edition 2023-10-27 13:05:48 +00:00
Oli Scherer
621494382d Add gen blocks to ast and do some broken ast lowering 2023-10-27 13:05:48 +00:00
clubby789
e81a5c65d9 Recover ternary expression as error 2023-10-26 23:04:20 +00:00
clubby789
041f0313cf Properly restore snapshot when failing to recover parsing ternary 2023-10-26 11:11:36 +00:00
Oli Scherer
a61cf673cd Reserve gen keyword for gen {} blocks and gen fn in 2024 edition 2023-10-26 06:49:17 +00:00
Esteban Küber
2dec1bc685 Avoid unbounded O(n^2) when parsing nested type args
When encountering code like `f::<f::<f::<f::<f::<f::<f::<f::<...` with
unmatched closing angle brackets, add a linear check that avoids the
exponential behavior of the parse recovery mechanism.

Fix #117080.
2023-10-25 19:07:34 +00:00
Oli Scherer
e96ce20b34 s/generator/coroutine/ 2023-10-20 21:14:01 +00:00
Esteban Küber
20de5c762d Move where doc comment meant as comment check
The new place makes more sense and covers more cases beyond individual
statements.

```
error: expected one of `.`, `;`, `?`, `else`, or an operator, found doc comment `//!foo
  --> $DIR/doc-comment-in-stmt.rs:25:22
   |
LL |     let y = x.max(1) //!foo
   |                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected one of `.`, `;`, `?`, `else`, or an operator
   |
help: add a space before `!` to write a regular comment
   |
LL |     let y = x.max(1) // !foo
   |                        +
```

Fix #65329.
2023-10-20 02:54:45 +00:00
bors
a48396984a Auto merge of #116688 - compiler-errors:rustfmt-up, r=WaffleLapkin,Nilstrieb
Format all the let-chains in compiler crates

Since rust-lang/rustfmt#5910 has landed, soon we will have support for formatting let-chains (as soon as rustfmt syncs and beta gets bumped).

This PR applies the changes [from master rustfmt to rust-lang/rust eagerly](https://rust-lang.zulipchat.com/#narrow/stream/122651-general/topic/out.20formatting.20of.20prs/near/374997516), so that the next beta bump does not have to deal with a 200+ file diff and can remain concerned with other things like `cfg(bootstrap)` -- #113637 was a pain to land, for example, because of let-else.

I will also add this commit to the ignore list after it has landed.

The commands that were run -- I'm not great at bash-foo, but this applies rustfmt to every compiler crate, and then reverts the two crates that should probably be formatted out-of-tree.
```
~/rustfmt $ ls -1d ~/rust/compiler/* | xargs -I@ cargo run --bin rustfmt -- `@/src/lib.rs` --config-path ~/rust --edition=2021 # format all of the compiler crates
~/rust $ git checkout HEAD -- compiler/rustc_codegen_{gcc,cranelift} # revert changes to cg-gcc and cg-clif
```

cc `@rust-lang/rustfmt`
r? `@WaffleLapkin` or `@Nilstrieb` who said they may be able to review this purely mechanical PR :>

cc `@Mark-Simulacrum` and `@petrochenkov,` who had some thoughts on the order of operations with big formatting changes in https://github.com/rust-lang/rust/pull/95262#issue-1178993801. I think the situation has changed since then, given that let-chains support exists on master rustfmt now, and I'm fairly confident that this formatting PR should land even if *bootstrap* rustfmt doesn't yet format let-chains in order to lessen the burden of the next beta bump.
2023-10-15 13:23:55 +00:00
bors
09eff44889 Auto merge of #116645 - estebank:issue-116608, r=oli-obk
Detect ruby-style closure in parser

When parsing a closure without a body that is surrounded by a block, suggest moving the opening brace after the closure head.

Fix #116608.
2023-10-13 19:26:27 +00:00
Michael Goulet
b2d2184ede Format all the let chains in compiler 2023-10-13 08:59:36 +00:00
Esteban Küber
6b2c6c7fd3 Detect ruby-style closure in parser
When parsing a closure without a body that is surrounded by a block,
suggest moving the opening brace after the closure head.

Fix #116608.
2023-10-12 21:50:18 +00:00
Nicholas Nethercote
bb9c2f50c3 Reorder an expression to improve readability. 2023-10-12 08:46:15 +11:00
Nicholas Nethercote
becf4942a2 Rename Token::is_op as Token::is_punct.
For consistency with `proc_macro::Punct`.
2023-10-12 08:46:15 +11:00
Jubilee
0d68e416a5
Rollup merge of #116400 - estebank:issue-78585, r=WaffleLapkin
Detect missing `=>` after match guard during parsing

```
error: expected one of `,`, `:`, or `}`, found `.`
  --> $DIR/missing-fat-arrow.rs:25:14
   |
LL |         Some(a) if a.value == b {
   |                               - while parsing this struct
LL |             a.value = 1;
   |             -^ expected one of `,`, `:`, or `}`
   |             |
   |             while parsing this struct field
   |
help: try naming a field
   |
LL |             a: a.value = 1;
   |             ++
help: you might have meant to start a match arm after the match guard
   |
LL |         Some(a) if a.value == b => {
   |                                 ++
```

Fix #78585.
2023-10-06 16:37:47 -07:00
Michael Goulet
137b6d0b01 Point to where missing return type should go 2023-10-04 21:09:54 +00:00
Matthias Krüger
4ed2291624
Rollup merge of #116393 - compiler-errors:auto-bad, r=WaffleLapkin
Emit feature gate *warning* for `auto` traits pre-expansion

Auto traits were introduced before we were more careful about not stabilizing new syntax pre-expansion.

This is a more conservative step in the general direction we want to go in https://rust-lang.zulipchat.com/#narrow/stream/213817-t-lang/topic/Removal.20of.20.60auto.20trait.60.20syntax.

Fixes #116121
2023-10-04 05:02:07 +02:00
Esteban Küber
8fd345dd4b review comments 2023-10-04 01:35:07 +00:00
Esteban Küber
18ec4e9bcd Move some tests around 2023-10-03 21:31:27 +00:00
Esteban Küber
745c1ea438 Detect missing => after match guard during parsing
```
error: expected one of `,`, `:`, or `}`, found `.`
  --> $DIR/missing-fat-arrow.rs:25:14
   |
LL |         Some(a) if a.value == b {
   |                               - while parsing this struct
LL |             a.value = 1;
   |             -^ expected one of `,`, `:`, or `}`
   |             |
   |             while parsing this struct field
   |
help: try naming a field
   |
LL |             a: a.value = 1;
   |             ++
help: you might have meant to start a match arm after the match guard
   |
LL |         Some(a) if a.value == b => {
   |                                 ++
```

Fix #78585.
2023-10-03 21:21:02 +00:00
Michael Goulet
7815641be0 Gate against auto traits pre-expansion 2023-10-03 19:12:00 +00:00
Matthias Krüger
144862ede8
Rollup merge of #115863 - chenyukang:yukang-add-message-tidy-check, r=davidtwco
Add check_unused_messages in tidy

From https://github.com/rust-lang/rust/pull/115728#issuecomment-1715490553
The check is not 100% accurate, I guess it's enough for now.
2023-10-03 12:24:11 +02:00
Esteban Küber
3848ffcee7 Tweak wording of missing angle backets in qualified path 2023-09-28 00:37:20 +00:00
yukang
42a033affa Cleanup unused messages in ftl files 2023-09-20 19:09:01 +08:00
bors
dac91a82e1 Auto merge of #115677 - matthewjasper:let-expr-recovery, r=b-naber
Improve invalid let expression handling

- Move all of the checks for valid let expression positions to parsing.
- Add a field to ExprKind::Let in AST/HIR to mark whether it's in a valid location.
- Suppress some later errors and MIR construction for invalid let expressions.
- Fix a (drop) scope issue that was also responsible for #104172.

Fixes #104172
Fixes #104868
2023-09-14 19:56:55 +00:00
Matthew Jasper
e324a59eb6 Address review comments
- Add doc comment to new type
- Restore "only supported directly in conditions of `if` and `while` expressions" note
- Rename variant with clearer name
2023-09-13 15:00:31 +00:00
León Orell Valerian Liehr
3ed77e98fa
Only suggest turbofish in patterns if we may recover 2023-09-12 16:38:59 +02:00
Matthew Jasper
b011a0a13b Reduce double errors for invalid let expressions
Previously some invalid let expressions would result in both a feature
error and a parsing error. Avoid this and ensure that we only emit the
parsing error when this happens.
2023-09-11 16:17:06 +00:00
Matthew Jasper
333388fd3c Move let expression checking to parsing
There was an incomplete version of the check in parsing and a second
version in AST validation. This meant that some, but not all, invalid
uses were allowed inside macros/disabled cfgs. It also means that later
passes have a hard time knowing when the let expression is in a valid
location, sometimes causing ICEs.

- Add a field to ExprKind::Let in AST/HIR to mark whether it's in a
  valid location.
- Suppress later errors and MIR construction for invalid let
  expressions.
2023-09-11 15:51:18 +00:00
Matthias Krüger
da44234b64
Rollup merge of #115596 - nnethercote:two-small-changes, r=lqd
A small change

A small change I made while poking around the code.

r? `@lqd`
2023-09-06 19:31:50 +02:00
Matthias Krüger
4a31cc859b
Rollup merge of #115473 - gurry:113110-expected-item, r=compiler-errors
Add explanatory note to 'expected item' error

Fixes #113110

It changes the diagnostic from this:

```
error: expected item, found `5`
 --> ../test.rs:1:1
  |
1 | 5
  | ^ expected item
 ```
to this:
```
error: expected item, found `5`
 --> ../test.rs:1:1
  |
1 | 5
  | ^ expected item
  |
  = note: items are things that can appear at the root of a module
  = note: for a full list see https://doc.rust-lang.org/reference/items.html
```
2023-09-06 19:31:48 +02:00
Nicholas Nethercote
42dbc72d7b Adjust to_attr_token_stream.
It uses `once` chained with `(0..self.num_calls).map(...)` followed by
`.take(self.num_calls`. I found this hard to read. It's simpler to just
use `repeat_with`.
2023-09-06 17:12:07 +10:00
Gurinder Singh
6a286e775c Add explanatory note to 'expected item' error 2023-09-06 09:05:07 +05:30
bors
25283f4e13 Auto merge of #115371 - matthewjasper:if-let-guard-parsing, r=cjgillot
Make if let guard parsing consistent with normal guards

- Add tests that struct expressions are not allowed in `if let` and `while let` (no change, consistent with `if` and `while`)
- Allow struct expressions in `if let` guards (consistent with `if` guards).

r? `@cjgillot`

Closes #93817
cc #51114
2023-09-06 00:46:21 +00:00
Camille GILLOT
258ace613d Use relative positions inside a SourceFile. 2023-09-03 12:56:10 +00:00
Matthias Krüger
58c690729c
Rollup merge of #115347 - y21:generic-bound-impl-trait-ty, r=compiler-errors
suggest removing `impl` in generic trait bound position

rustc already does this recovery in type param position (`<T: impl Trait>` -> `<T: Trait>`).
This PR also adds that suggestion in trait bound position (e.g. `where T: impl Trait` or `trait Trait { type Assoc: impl Trait; }`)
2023-08-30 07:18:12 +02:00
Matthias Krüger
639116505a
Rollup merge of #114704 - bvanjoi:fix-114636, r=compiler-errors
parser: not insert dummy field in struct

Fixes #114636

This PR eliminates the dummy field, initially introduced in #113999, thereby enabling unrestricted use of `ident.unwrap()`. A side effect of this action is that we can only report the error of the first macro invocation field within the struct node.

An alternative solution might be giving a virtual name to the macro, but it appears more complex.(https://github.com/rust-lang/rust/issues/114636#issuecomment-1670228715). Furthermore, if you think https://github.com/rust-lang/rust/issues/114636#issuecomment-1670228715 is a better solution, feel free to close this PR.
2023-08-30 07:18:10 +02:00
y21
507f10baee suggest removing impl in generic trait bound position 2023-08-29 20:27:38 +02:00
Matthew Jasper
89235fd837 Allow stuct literals in if let guards
This is consistent with normal match guards.
2023-08-28 10:31:45 +01:00
bors
18be2728bd Auto merge of #115131 - frank-king:feature/unnamed-fields-lite, r=petrochenkov
Parse unnamed fields and anonymous structs or unions (no-recovery)

It is part of #114782 which implements #49804. Only parse anonymous structs or unions in struct field definition positions.

r? `@petrochenkov`
2023-08-24 12:52:35 +00:00
Frank King
868706d9b5 Parse unnamed fields and anonymous structs or unions
Anonymous structs or unions are only allowed in struct field
definitions.

Co-authored-by: carbotaniuman <41451839+carbotaniuman@users.noreply.github.com>
2023-08-24 11:17:54 +08:00
Mark Rousskov
0a916062aa Bump cfg(bootstrap) 2023-08-23 20:05:14 -04:00
bohan
3ed435f8cb discard dummy field for macro invocation when parse struct 2023-08-21 21:05:01 +08:00
John Kåre Alsaker
1e87ef66f4 Fix a stack overflow with long else if chains 2023-08-19 13:11:16 +02:00
bors
ee5cb9e3a6 Auto merge of #114915 - nnethercote:Nonterminal-cleanups, r=petrochenkov
`Nonterminal`-related cleanups

In #114647 I am trying to remove `Nonterminal`. It has a number of preliminary cleanups that are worth merging even if #114647 doesn't merge, so let's do them in this PR.

r? `@petrochenkov`
2023-08-18 16:07:40 +00:00
Nicholas Nethercote
9e22351c74 Rename NtOrTt as ParseNtResult.
It's more descriptive, and future-proofs it if/when additional variants
get added.
2023-08-18 16:50:41 +10:00
Nicholas Nethercote
9167eea553 Use interpolated_or_expr_span in one suitable place. 2023-08-18 16:50:41 +10:00
Nicholas Nethercote
dee6c9241f Refactor interpolated_or_expr_span.
It's much more complicated than it needs to be, and it doesn't modify
the expression. We can do the `Result` handling outside of it, and
change it to just return a span.

Also fix an errant comma that makes the comment hard to read.
2023-08-18 16:50:41 +10:00
Josh Stone
7ea4de9632
Rollup merge of #114913 - beetrees:escape-double-quote, r=davidtwco
Fix suggestion for attempting to define a string with single quotes

Currently attempting to compile `fn main() { let _ = '\\"'; }` will result in the following error message:
```
error: character literal may only contain one codepoint
 --> src/main.rs:1:21
  |
1 | fn main() { let _ = '\\"'; }
  |                     ^^^^^
  |
help: if you meant to write a `str` literal, use double quotes
  |
1 | fn main() { let _ = "\\""; }
  |                     ~~~~~
```
The suggestion is invalid as it fails to escape the `"`. This PR fixes the suggestion so that it now reads:
```
help: if you meant to write a `str` literal, use double quotes
  |
1 | fn main() { let _ = "\\\""; }
  |                     ~~~~~~
```
The relevant test is also updated to ensure that this does not regress in future.
2023-08-17 15:40:09 -07:00
Nicholas Nethercote
e46caaf84b Simplify a match.
`may_be_ident` is true for `NtPath` and `NtMeta`, so we don't need to
check for them separately.
2023-08-17 09:06:03 +10:00
Nicholas Nethercote
9a3c907bdb Make some matches exhaustive in nonterminal.rs.
For ones matching more than one or two variants, this is easier to think
about.
2023-08-17 09:05:37 +10:00
Nicholas Nethercote
f8a21a5df0 Use Nonterminal::* in nonterminal.rs.
It makes the code more readable.
2023-08-17 09:05:07 +10:00
Nicholas Nethercote
acd3a5e35f Remove unnecessary braces on PatWithOr patterns. 2023-08-17 09:04:54 +10:00
Nicholas Nethercote
e8f733370f Add some useful comments to Parser::look_ahead. 2023-08-17 09:03:56 +10:00
Nicholas Nethercote
04cf6b4ac5 Rename parse_no_question_mark_recover.
Adding a `ty_` makes its purpose much clearer, and consistent with other
`parse_ty_*` functions.
2023-08-17 09:01:12 +10:00
Nicholas Nethercote
434bfc3162 Remove outdated comment.
All nonterminals collect and store tokens now. (Unless they are very
simple, e.g. single-token, and can precisely recover them without
collecting.)
2023-08-17 08:26:56 +10:00
beetrees
072d8c8bbc
Fix suggestion for attempting to define a string with single quotes 2023-08-16 21:51:57 +01:00
yukang
ddcd7cac41 Fix bad suggestion when wrong parentheses around a dyn trait 2023-08-16 00:26:10 +08:00
bjorn3
ef2da4a49b Remove reached_eof from ParseSess
It was only ever set in a function which isn't called anywhere.
2023-08-13 13:33:37 +00:00
darklyspaced
89284af8fe
inlined kind 2023-08-08 10:59:15 +08:00
darklyspaced
13ac0234c6
always return ExprKind::Err 2023-08-07 22:32:28 +08:00
Matthias Krüger
99e4127d85
Rollup merge of #114434 - Nilstrieb:indexing-spans, r=est31
Improve spans for indexing expressions

fixes #114388

Indexing is similar to method calls in having an arbitrary left-hand-side and then something on the right, which is the main part of the expression. Method calls already have a span for that right part, but indexing does not. This means that long method chains that use indexing have really bad spans, especially when the indexing panics and that span in coverted into a panic location.

This does the same thing as method calls for the AST and HIR, storing an extra span which is then put into the `fn_span` field in THIR.

r? compiler-errors
2023-08-04 21:31:57 +02:00
Nilstrieb
5706be1854 Improve spans for indexing expressions
Indexing is similar to method calls in having an arbitrary
left-hand-side and then something on the right, which is the main part
of the expression. Method calls already have a span for that right part,
but indexing does not. This means that long method chains that use
indexing have really bad spans, especially when the indexing panics and
that span in coverted into a panic location.

This does the same thing as method calls for the AST and HIR, storing an
extra span which is then put into the `fn_span` field in THIR.
2023-08-04 13:17:39 +02:00
Matthias Krüger
1f076fe1d8
Rollup merge of #113999 - Centri3:macro-arm-expand, r=wesleywiser
Specify macro is invalid in certain contexts

Adds a note when a macro is used where it really shouldn't be.

Closes #113766
2023-08-04 07:25:45 +02:00
bors
1fe384649a Auto merge of #108955 - Nilstrieb:dont-use-me-pls, r=oli-obk
Add `internal_features` lint

Implements https://github.com/rust-lang/compiler-team/issues/596

Also requires some more test blessing for codegen tests etc

`@jyn514` had the idea of just `allow`ing the lint by default in the test suite. I'm not sure whether this is a good idea, but it's definitely one worth considering. Additional input encouraged.
2023-08-03 22:58:02 +00:00
Matthias Krüger
51d1dacdc2
Rollup merge of #114300 - MU001999:fix/turbofish-pat, r=estebank
Suggests turbofish in patterns

Fixes #114112

r? ```@estebank```
2023-08-03 17:29:07 +02:00
Matthias Krüger
649d0a9525
Rollup merge of #114237 - bvanjoi:fix-114219, r=cjgillot
parser: more friendly hints for handling `async move` in the 2015 edition

Fixes #114219

An error is emitted when encountering an async move block in the 2015 edition.

Another appropriate location to raise an error is after executing [let path = this.parse_path(PathStyle::Expr)?](https://github.com/rust-lang/rust/blob/master/compiler/rustc_parse/src/parser/stmt.rs#L152), but it seems somewhat premature to invoke `create_err` at that stage.
2023-08-03 17:29:07 +02:00
Nilstrieb
5830ca216d Add internal_features lint
It lints against features that are inteded to be internal to the
compiler and standard library. Implements MCP #596.

We allow `internal_features` in the standard library and compiler as those
use many features and this _is_ the standard library from the "internal to the compiler and
standard library" after all.

Marking some features as internal wasn't exactly the most scientific approach, I just marked some
mostly obvious features. While there is a categorization in the macro,
it's not very well upheld (should probably be fixed in another PR).

We always pass `-Ainternal_features` in the testsuite
About 400 UI tests and several other tests use internal features.
Instead of throwing the attribute on each one, just always allow them.
There's nothing wrong with testing internal features^^
2023-08-03 14:50:50 +02:00
r0cky
dce7e87b16 Reduce arbitrary self type suggestions 2023-08-03 10:34:57 +00:00
r0cky
8c8af6cf99 Avoid too many expected symbols and reduce Nones 2023-08-03 08:56:31 +00:00
r0cky
41e85c3d23 Apply suggestions 2023-08-03 05:18:19 +00:00
Catherine Flores
bbd69e4a4c Add test for enum with fields 2023-08-02 23:59:30 +00:00
Nicholas Nethercote
d75ee2a6bc Remove MacDelimiter.
It's the same as `Delimiter`, minus the `Invisible` variant. I'm
generally in favour of using types to make impossible states
unrepresentable, but this one feels very low-value, and the conversions
between the two types are annoying and confusing.

Look at the change in `src/tools/rustfmt/src/expr.rs` for an example:
the old code converted from `MacDelimiter` to `Delimiter` and back
again, for no good reason. This suggests the author was confused about
the types.
2023-08-03 09:03:30 +10:00
Mu001999
89b2fe7750 Keep the suggestion for wrong arbitrary self types 2023-08-03 00:00:56 +08:00
Nicholas Nethercote
ac64a53e17 Avoid an unnecessary local variable. 2023-08-02 10:29:13 +10:00
Nicholas Nethercote
6fc2c481e5 Move TokenCursor::break_last_token into Parser.
Similar to the last commit, it's more of a `Parser`-level concern than a
`TokenCursor`-level concern. And the struct size reductions are nice.

After this change, `TokenCursor` is as minimal as possible (two fields
and two methods) which is nice.
2023-08-02 10:11:41 +10:00
Nicholas Nethercote
54eb6bc34c Move TokenCursor::num_next_calls into Parser and rename it.
It's more of a `Parser`-level concern than a `TokenCursor`-level
concern. Also, `num_bump_calls` is a more accurate name, because it's
incremented in `Parser::bump`.
2023-08-02 10:07:18 +10:00
Nicholas Nethercote
db7b07aa02 Inline and remove parse_all_token_trees.
It has a single call site.
2023-08-02 10:03:16 +10:00
Nicholas Nethercote
d9f2fdfaed parse_all_token_trees cannot fail. 2023-08-02 10:01:49 +10:00
bors
d12c6e947c Auto merge of #114273 - nnethercote:move-doc-comment-desugaring, r=petrochenkov
Move doc comment desugaring out of `TokenCursor`.

It's awkward that `TokenCursor` sometimes desugars doc comments on the fly, but usually doesn't.

r? `@petrochenkov`
2023-08-01 21:27:48 +00:00
Mu001999
049c728c60 Suggests turbofish in patterns 2023-08-01 23:30:40 +08:00
Nicholas Nethercote
2e6ce68fba Remove desugar_doc_comments arg from Parser::new().
It's only true at one call site; do the desugaring there instead.
2023-07-31 14:47:08 +10:00
Nicholas Nethercote
ff7d5ba65e Move doc comment desugaring out of TokenCursor.
`TokenCursor` currently does doc comment desugaring on the fly, if the
`desugar_doc_comment` field is set. This requires also modifying the
token stream on the fly with `replace_prev_and_rewind`.

This commit moves the doc comment desugaring out of `TokenCursor`, by
introducing a new `TokenStream::desugar_doc_comment` method. This
separation of desugaring and iterating makes the code nicer.
2023-07-31 14:47:03 +10:00
bohan
8e32dade71 parser: more friendly hints for handling async move in the 2015 edition 2023-07-31 11:04:28 +08:00
Nicholas Nethercote
cfc1aa3c5d Fix a typo in a comment. 2023-07-31 11:14:39 +10:00
Nicholas Nethercote
f8650114bd Remove an unnecessary return keyword. 2023-07-31 11:14:39 +10:00
Matthias Krüger
97bacad9c2
Rollup merge of #114256 - Urgau:fix-issue-114180, r=WaffleLapkin
Fix invalid suggestion for mismatched types in closure arguments

This PR fixes the invalid suggestion for mismatched types in closure arguments.

The invalid suggestion came from a wrongly created span in the parser for closure arguments that don't have a type specified. Specifically, the span in this case was the last token span, but in the case of tuples, the span represented the last parenthesis instead of the whole tuple, which is fixed by taking the more accurate span of the pattern.

There is one unfortunate downside of this fix, it worsens even more the diagnostic for mismatched types in closure args without an explicit type. This happens because there is no correct span for implied inferred type. I tried also fixing this but it's a rabbit hole.

Fixes https://github.com/rust-lang/rust/issues/114180
2023-07-30 20:36:35 +02:00
Urgau
8ea7e45e44 Fix invalid suggestion for mismatched types in closure arguments
The invalid suggestion came from a wrongly created span in `rustc_parse'
for closure arguments that didn't have a type specified. Specifically,
the span in this case was the last token span, but in the case of
tuples, the span represented the last parenthesis instead of the whole
tuple, which is fixed by taking the more accurate span of the pattern.
2023-07-30 17:15:55 +02:00
Matthias Krüger
23815467a2 inline format!() args up to and including rustc_middle 2023-07-30 13:18:33 +02:00
bors
a04e649c09 Auto merge of #114028 - Centri3:ternary-operator, r=compiler-errors
Gracefully handle ternary operator

Fixes #112578

~~May not be the best way to do this as it doesn't check for a single `:`, so it could perhaps appear even when the actual issue is just a missing semicolon. May not be the biggest deal, though?~~

Nevermind, got it working properly now ^^
2023-07-29 16:45:29 +00:00