Commit Graph

1296 Commits

Author SHA1 Message Date
Yuki Okushi
668d9fd7bc
Always suggest as MachineApplicable in recover_intersection_pat
Signed-off-by: Yuki Okushi <jtitor@2k36.org>
2022-12-23 07:18:48 +09:00
Dylan DPC
a9005b6cc0
Rollup merge of #105864 - matthiaskrgr:compl, r=Nilstrieb
clippy::complexity fixes

filter_next
needless_question_mark
bind_instead_of_map
manual_find
derivable_impls
map_identity
redundant_slicing
skip_while_next
unnecessary_unwrap
needless_bool

r? `@compiler-errors`
2022-12-19 14:41:35 +05:30
Matthias Krüger
1da4a49912 clippy::complexity fixes
filter_next
needless_question_mark
bind_instead_of_map
manual_find
derivable_impls
map_identity
redundant_slicing
skip_while_next
unnecessary_unwrap
needless_bool
2022-12-19 00:04:28 +01:00
Matthias Krüger
0aa4cde747 avoid .into() conversion to identical types 2022-12-18 16:20:32 +01:00
Deep Majumder
4af9e6a1c2 Little fixes 2022-12-16 18:41:08 +05:30
Deep Majumder
c4d0c91161 Allow .. to be parsed as let initializer
.. and ..= are valid expressions, however when used in a let statement
it is not parsed.
2022-12-14 19:12:30 +05:30
Matthias Krüger
c8fd654d7c
Rollup merge of #105502 - chenyukang:yukang/fix-105366-impl, r=estebank
Suggest impl in the scenario of typo with fn

Fixes #105366
2022-12-14 10:31:06 +01:00
bors
309c469eec Auto merge of #104875 - chenyukang:yukang/fix-104867-inc, r=estebank
Properly handle postfix inc/dec in standalone and subexpr scenarios

Fixes #104867
r? `@estebank`
2022-12-14 04:00:05 +00:00
Yiming Lei
419df5f4a0 error parsing lifetime following by Sized and message + between them
detect the pattern at the general site parse_impl_ty()
this will fix #102598
2022-12-13 16:49:20 -08:00
Nilstrieb
d72a0c437b Properly calculate best failure in macro matching
Previously, we used spans. This was not good. Sometimes, the span of the
token that failed to match may come from a position later in the file
which has been transcribed into a token stream way earlier in the file.
If precisely this token fails to match, we think that it was the best
match because its span is so high, even though other arms might have
gotten further in the token stream.

We now try to properly use the location in the token stream.
2022-12-12 17:05:27 +01:00
bors
2cd2070af7 Auto merge of #105160 - nnethercote:rm-Lit-token_lit, r=petrochenkov
Remove `token::Lit` from `ast::MetaItemLit`.

Currently `ast::MetaItemLit` represents the literal kind twice. This PR removes that redundancy. Best reviewed one commit at a time.

r? `@petrochenkov`
2022-12-12 05:16:50 +00:00
Matthias Krüger
4154e14f9a
Rollup merge of #105369 - chenyukang:yukang/fix-105226, r=TaKO8Ki
Detect spurious ; before assoc fn body

Fixes #105226

r? ``@TaKO8Ki``
2022-12-11 23:36:46 +01:00
KaDiWa
9bc69925cb
compiler: remove unnecessary imports and qualified paths 2022-12-10 18:45:34 +01:00
yukang
b70a869d8f fix #105366, suggest impl in the scenario of typo with fn 2022-12-10 11:01:52 +08:00
yukang
5599f2ad09 fix #105226, Detect spurious ; before assoc fn body 2022-12-07 16:13:39 +08:00
Matthias Krüger
48172ff64b
Rollup merge of #105098 - lyming2007:issue-103869-fix, r=eholk
propagate the error from parsing enum variant to the parser and emit out

While parsing enum variant, the error message always disappear
Because the error message that emit out is from main error of parser
The information of enum variant disappears while parsing enum variant with error
We only check the syntax of expecting token, i.e, in case https://github.com/rust-lang/rust/issues/103869
It will error it without telling the message that this error is from pasring enum variant.
Propagate the sub-error from parsing enum variant to the main error of parser by chaining it with map_err
Check the sub-error before emitting the main error of parser and attach it.
Fix https://github.com/rust-lang/rust/issues/103869
2022-12-06 13:27:41 +01:00
Matthias Krüger
66a4cb5368
Rollup merge of #105223 - lukas-code:(ExprWithBlock), r=petrochenkov
suggest parenthesis around ExprWithBlock BinOp ExprWithBlock

fix https://github.com/rust-lang/rust/issues/105179
fix https://github.com/rust-lang/rust/issues/102171
2022-12-05 20:43:44 +01:00
Nicholas Nethercote
d887615b4c Parameterise Parser::{recover_unclosed_char,handle_missing_lit}.
These two methods both produce a `MetaItemLit`, and then some of the
call sites convert the `MetaItemLit` to a `token::Lit` with
`as_token_lit`.

This commit parameterises these two methods with a `mk_lit_char`
closure, which can be used to produce either `MetaItemLit` or
`token::Lit` directly as necessary.
2022-12-05 15:04:33 +11:00
Matthias Krüger
b1816833bd
Rollup merge of #105141 - ohno418:fix-ice-on-invalid-var-decl-in-macro-call, r=compiler-errors
Fix ICE on invalid variable declarations in macro calls

This fixes ICE that happens with invalid variable declarations in macro calls like:

```rust
macro_rules! m { ($s:stmt) => {} }
m! { var x }
m! { auto x }
m! { mut x }
```

Found this is because of not collecting tokens on recovery, so I changed to force collect them.

Fixes https://github.com/rust-lang/rust/issues/103529.
2022-12-04 16:25:32 +01:00
Lukas Markeffsky
c808d0b289 more comments 2022-12-03 23:54:06 +01:00
Lukas Markeffsky
35c00a9731 suggest parenthesis around ExprWithBlock BinOp ExprWithBlock 2022-12-03 20:02:39 +01:00
Matthias Krüger
c89bff29e5
Rollup merge of #104199 - SarthakSingh31:issue-97417-1, r=cjgillot
Keep track of the start of the argument block of a closure

This removes a call to `tcx.sess.source_map()` from [compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs](https://github.com/rust-lang/rust/compare/master...SarthakSingh31:issue-97417-1?expand=1#diff-8406bbc0d0b43d84c91b1933305df896ecdba0d1f9269e6744f13d87a2ab268a) as required by #97417.

VsCode automatically applied `rustfmt` to the files I edited under `src/tools`. I can undo that if its a problem.

r? `@cjgillot`
2022-12-03 17:37:41 +01:00
Yutaro Ohno
e4812583c7 parser: refactoring on recovery from invalid variable declarations
Previously, the `recover_local_after_let` function was called from the
body of the `recover_stmt_local` function. Unifying these two functions
make it more simple and more readable.
2022-12-03 23:41:42 +09:00
Yutaro Ohno
690addc6ec parser: fix ICE with invalid variable declaration in macro call
Fix ICE on parsing an invalid variable declaration as a statement like:

```
macro_rules! m { ($s:stmt) => {} }
m! { var x }
```
2022-12-03 23:24:49 +09:00
Yiming Lei
0e19fb92e1 While parsing enum variant, the error message always disappear
Because the error message that emit out is from main error of parser
The information of enum variant disappears while parsing enum variant with error
We only check the syntax of expecting token, i.e, in case #103869
It will error it without telling the message that this error is from pasring enum variant.
Propagate the sub-error from parsing enum variant to the main error of parser by chaining it with map_err
Check the sub-error before emitting the main error of parser and attach it.
Fix #103869
2022-12-01 22:48:52 -08:00
Nicholas Nethercote
2fd364acff Remove token::Lit from ast::MetaItemLit.
`token::Lit` contains a `kind` field that indicates what kind of literal
it is. `ast::MetaItemLit` currently wraps a `token::Lit` but also has
its own `kind` field. This means that `ast::MetaItemLit` encodes the
literal kind in two different ways.

This commit changes `ast::MetaItemLit` so it no longer wraps
`token::Lit`. It now contains the `symbol` and `suffix` fields from
`token::Lit`, but not the `kind` field, eliminating the redundancy.
2022-12-02 13:49:19 +11:00
Vadim Petrochenkov
b32a4edb20 rustc_ast_lowering: Stop lowering imports into multiple items
Lower them into a single item with multiple resolutions instead.
This also allows to remove additional `NodId`s and `DefId`s related to those additional items.
2022-12-01 18:51:20 +03:00
Nicholas Nethercote
c9ae38c71e Avoid unnecessary MetaItem/Attribute conversions.
`check_builtin_attribute` calls `parse_meta` to convert an `Attribute`
to a `MetaItem`, which it then checks. However, many callers of
`check_builtin_attribute` start with a `MetaItem`, and then convert it
to an `Attribute` by calling `cx.attribute(meta_item)`. This `MetaItem`
to `Attribute` to `MetaItem` conversion is silly.

This commit adds a new function `check_builtin_meta_item`, which can be
called instead from these call sites. `check_builtin_attribute` also now
calls it. The commit also renames `check_meta` as `check_attr` to better
match its arguments.
2022-11-29 12:08:57 +11:00
Sarthak Singh
8f705e2425 Keep track of the start of the argument block of a closure 2022-11-28 14:09:00 +05:30
Nicholas Nethercote
a60e337c88 Rename NestedMetaItem::[Ll]iteral as NestedMetaItem::[Ll]it.
We already use a mix of `Literal` and `Lit`. The latter is better
because it is shorter without causing any ambiguity.
2022-11-28 15:18:53 +11:00
Nicholas Nethercote
e4a9150872 Rename ast::Lit as ast::MetaItemLit. 2022-11-28 15:18:49 +11:00
Maybe Waffle
1d42936b18 Prefer doc comments over //-comments in compiler 2022-11-27 11:19:04 +00:00
yukang
ded10a13d2 will not suggest for postfix operator when can not handle precedences well 2022-11-26 17:08:25 +08:00
yukang
dee85a391f add start_stmt to handle postfix increment 2022-11-26 05:34:12 +08:00
yukang
7c11a53f9c fix #104867, Properly handle postfix inc/dec in standalone and subexpr scenarios 2022-11-25 17:13:45 +08:00
Matthias Krüger
5197ef66b7
Rollup merge of #103908 - estebank:consider-cloning, r=compiler-errors
Suggest `.clone()` or `ref binding` on E0382
2022-11-24 08:42:33 +01:00
bors
872631d0f0 Auto merge of #104507 - WaffleLapkin:asderefsyou, r=wesleywiser
Use `as_deref` in compiler (but only where it makes sense)

This simplifies some code :3

(there are some changes that are not exacly `as_deref`, but more like "clever `Option`/`Result` method use")
2022-11-24 00:17:35 +00:00
Esteban Küber
9e72e35ceb Suggest .clone() or ref binding on E0382 2022-11-23 12:17:47 -08:00
bors
70f8737b2f Auto merge of #104410 - WaffleLapkin:unregress, r=estebank
Fix perf regression by correctly matching keywords

This should (hopefully) fix regression from #99918

r? `@estebank`
2022-11-23 19:52:43 +00:00
Maybe Waffle
616df0f03b rustc_parse: remove ref patterns 2022-11-22 18:49:16 +00:00
Matthias Krüger
589d843bd0
Rollup merge of #104559 - nnethercote:split-MacArgs, r=petrochenkov
Split `MacArgs` in two.

`MacArgs` is an enum with three variants: `Empty`, `Delimited`, and `Eq`. It's used in two ways:
- For representing attribute macro arguments (e.g. in `AttrItem`), where all three variants are used.
- For representing function-like macros (e.g. in `MacCall` and `MacroDef`), where only the `Delimited` variant is used.

In other words, `MacArgs` is used in two quite different places due to them having partial overlap. I find this makes the code hard to read. It also leads to various unreachable code paths, and allows invalid values (such as accidentally using `MacArgs::Empty` in a `MacCall`).

This commit splits `MacArgs` in two:
- `DelimArgs` is a new struct just for the "delimited arguments" case. It is now used in `MacCall` and `MacroDef`.
- `AttrArgs` is a renaming of the old `MacArgs` enum for the attribute macro case. Its `Delimited` variant now contains a `DelimArgs`.

Various other related things are renamed as well.

These changes make the code clearer, avoids several unreachable paths, and disallows the invalid values.

r? `@petrochenkov`
2022-11-22 00:01:09 +01:00
Nicholas Nethercote
3e3a4192d8 Split MacArgs in two.
`MacArgs` is an enum with three variants: `Empty`, `Delimited`, and `Eq`. It's
used in two ways:
- For representing attribute macro arguments (e.g. in `AttrItem`), where all
  three variants are used.
- For representing function-like macros (e.g. in `MacCall` and `MacroDef`),
  where only the `Delimited` variant is used.

In other words, `MacArgs` is used in two quite different places due to them
having partial overlap. I find this makes the code hard to read. It also leads
to various unreachable code paths, and allows invalid values (such as
accidentally using `MacArgs::Empty` in a `MacCall`).

This commit splits `MacArgs` in two:
- `DelimArgs` is a new struct just for the "delimited arguments" case. It is
  now used in `MacCall` and `MacroDef`.
- `AttrArgs` is a renaming of the old `MacArgs` enum for the attribute macro
  case. Its `Delimited` variant now contains a `DelimArgs`.

Various other related things are renamed as well.

These changes make the code clearer, avoids several unreachable paths, and
disallows the invalid values.
2022-11-22 09:04:15 +11:00
mejrs
fe212eca76 Match crate and slug names 2022-11-21 15:24:50 +01:00
Nilstrieb
825b8db34a
Cleanup macro matching recovery
The retry has been implemented already.
2022-11-19 17:46:04 +01:00
Dylan DPC
3c6fc06906
Rollup merge of #104566 - matthiaskrgr:clippy_perf_nov18, r=oli-obk
couple of clippy::perf fixes
2022-11-19 11:54:46 +05:30
bors
b833ad56f4 Auto merge of #104573 - matthiaskrgr:rollup-k36ybtp, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #101162 (Migrate rustc_resolve to use SessionDiagnostic, part # 1)
 - #103386 (Don't allow `CoerceUnsized` into `dyn*` (except for trait upcasting))
 - #103405 (Detect incorrect chaining of if and if let conditions and recover)
 - #103594 (Fix non-associativity of `Instant` math on `aarch64-apple-darwin` targets)
 - #104006 (Add variant_name function to `LangItem`)
 - #104494 (Migrate GUI test to use functions)
 - #104516 (rustdoc: clean up sidebar width CSS)
 - #104550 (fix a typo)

Failed merges:

 - #104554 (Use `ErrorGuaranteed::unchecked_claim_error_was_emitted` less)

r? `@ghost`
`@rustbot` modify labels: rollup
2022-11-18 20:26:58 +00:00
Matthias Krüger
3efbf30220
Rollup merge of #103405 - chenyukang:yukang/fix-103381-and-if, r=compiler-errors
Detect incorrect chaining of if and if let conditions and recover

Fixes #103381
2022-11-18 14:13:36 +01:00
Matthias Krüger
e3036df003 couple of clippy::perf fixes 2022-11-18 10:30:47 +01:00
Nicholas Nethercote
67d5cc0462 Use ThinVec in ast::Path. 2022-11-17 13:56:38 +11:00
Nicholas Nethercote
6b7ca2fcf2 Box ExprKind::{Closure,MethodCall}, and QSelf in expressions, types, and patterns. 2022-11-17 13:45:59 +11:00
bors
bebd57a960 Auto merge of #102944 - nnethercote:ast-Lit-third-time-lucky, r=petrochenkov
Use `token::Lit` in `ast::ExprKind::Lit`.

Instead of `ast::Lit`.

Literal lowering now happens at two different times. Expression literals are lowered when HIR is crated. Attribute literals are lowered during parsing.

r? `@petrochenkov`
2022-11-16 23:03:14 +00:00
Maybe Waffle
94470f4efd Use as_deref in compiler (but only where it makes sense) 2022-11-16 21:58:58 +00:00
Maybe Waffle
e2a28165a3 Fix perf regression by correctly matching keywords 2022-11-16 13:42:30 +00:00
Nicholas Nethercote
358a603f11 Use token::Lit in ast::ExprKind::Lit.
Instead of `ast::Lit`.

Literal lowering now happens at two different times. Expression literals
are lowered when HIR is crated. Attribute literals are lowered during
parsing.

This commit changes the language very slightly. Some programs that used
to not compile now will compile. This is because some invalid literals
that are removed by `cfg` or attribute macros will no longer trigger
errors. See this comment for more details:
https://github.com/rust-lang/rust/pull/102944#issuecomment-1277476773
2022-11-16 09:41:28 +11:00
Nilstrieb
b7b67228f9
Only do parser recovery on retried macro matching
This prevents issues with eager parser recovery during macro matching.
2022-11-15 19:34:35 +01:00
yukang
ff18c73065 comment feedback 2022-11-15 08:58:23 +08:00
yukang
9db8e183dc fix #104088, Slightly improve error message for invalid identifier 2022-11-15 08:58:19 +08:00
yukang
74c9a6c6df fix #103381, Detect incorrect chaining of if and if let conditions 2022-11-15 08:53:17 +08:00
Matthias Krüger
a86bdb4c50
Rollup merge of #104223 - fmease:recover-fn-ptr-with-generics, r=estebank
Recover from function pointer types with generic parameter list

Give a more helpful error when encountering function pointer types with a generic parameter list like `fn<'a>(&'a str) -> bool` or `fn<T>(T) -> T` and suggest moving lifetime parameters to a `for<>` parameter list.

I've added a bunch of extra code to properly handle (unlikely?) corner cases like `for<'a> fn<'b>()` (where there already exists a `for<>` parameter list) correctly suggesting `for<'a, 'b> fn()` (merging the lists). If you deem this useless, I can simplify the code by suggesting nothing at all in this case.

I am quite open to suggestions regarding the wording of the diagnostic messages.

Fixes #103487.
``@rustbot`` label A-diagnostics
r? diagnostics
2022-11-14 19:26:16 +01:00
Maybe Waffle
df86ad8d36 Add delay_span_bug to AttrWrapper::take_for_recovery 2022-11-13 13:09:23 +00:00
bors
8ef2485bd5 Auto merge of #103812 - clubby789:improve-include-bytes, r=petrochenkov
Delay `include_bytes` to AST lowering

Hopefully addresses #65818.
This PR introduces a new `ExprKind::IncludedBytes` which stores the path and bytes of a file included with `include_bytes!()`. We can then create a literal from the bytes during AST lowering, which means we don't need to escape the bytes into valid UTF8 which is the cause of most of the overhead of embedding large binary blobs.
2022-11-12 14:30:34 +00:00
Manish Goregaokar
fd5ff82f28
Rollup merge of #103468 - chenyukang:yukang/fix-103435-extra-parentheses, r=estebank
Fix unused lint and parser caring about spaces to won't produce invalid code

Fixes #103435
2022-11-11 12:12:29 -05:00
clubby789
b2da155a9a Introduce ExprKind::IncludedBytes 2022-11-11 16:31:32 +00:00
León Orell Valerian Liehr
c2b906ba9a
Recover from fn ptr tys with generic param list 2022-11-11 13:42:40 +01:00
bors
5b82ea74b7 Auto merge of #99918 - WaffleLapkin:fnFnfun, r=estebank
Recover wrong-cased keywords that start items

(_this pr was inspired by [this tweet](https://twitter.com/Azumanga/status/1552982326409367561)_)

r? `@estebank`

We've talked a bit about this recovery, but I just wanted to make sure that this is the right approach :)

For now I've only added the case insensitive recovery to `use`s, since most other items like `impl` blocks, modules, functions can start with multiple keywords which complicates the matter.
2022-11-11 02:07:52 +00:00
bors
01a6f30324 Auto merge of #104236 - compiler-errors:rollup-adjshd6, r=compiler-errors
Rollup of 9 pull requests

Successful merges:

 - #102763 (Some diagnostic-related nits)
 - #103443 (Parser: Recover from using colon as path separator in imports)
 - #103675 (remove redundent "<>" for ty::Slice with reference type)
 - #104046 (bootstrap: add support for running Miri on a file)
 - #104115 (Migrate crate-search element to CSS variables)
 - #104190 (Ignore "Change InferCtxtBuilder from enter to build" in git blame)
 - #104201 (Add check in GUI test for file loading failure)
 - #104211 (⬆️ rust-analyzer)
 - #104231 (Update mailmap)

Failed merges:

 - #104169 (Migrate `:target` rules to use CSS variables)

r? `@ghost`
`@rustbot` modify labels: rollup
2022-11-10 13:04:51 +00:00
Michael Goulet
0c4a81c97b
Rollup merge of #103443 - mucinoab:recover-colon-as-path-separetor, r=compiler-errors
Parser: Recover from using colon as path separator in imports

I don't know if this is the right approach, any feedback is welcome.

r? ```@compiler-errors```

Fixes #103269
2022-11-09 21:53:34 -08:00
Michael Goulet
e5ecf629dd
Rollup merge of #102763 - compiler-errors:nits, r=cjgillot
Some diagnostic-related nits

1. Use `&mut Diagnostic` instead of `&mut DiagnosticBuilder<'_, T>`
2. Make `diag.span_suggestions` take an `IntoIterator` instead of `Iterator`, just to remove some `.into_iter` calls on the caller.

idk if I should add a lint to make sure people use `&mut Diagnostic` instead of `&mut DiagnosticBuilder<'_, T>` in cases where we're just, e.g., adding subdiagnostics to the diagnostic... maybe a followup.
2022-11-09 21:53:34 -08:00
bors
11fa0850f0 Auto merge of #103636 - chenyukang:yukang/fix-103587-sugg-if-let, r=jackh276,davidtwco
Recover from common if let syntax mistakes/typos

Fixes #103587
2022-11-10 05:19:10 +00:00
Michael Goulet
e807cb3c41 Make span_suggestions take IntoIterator 2022-11-09 19:42:23 +00:00
Dylan DPC
4b50fb3745
Rollup merge of #103919 - nnethercote:unescaping-cleanups, r=matklad
Unescaping cleanups

Some code improvements, and some error message improvements.

Best reviewed one commit at a time.

r? ````@matklad````
2022-11-09 19:21:22 +05:30
Bruno A. Muciño
aa5a3266f4 Parser: Recover from using colon as path separator in imports 2022-11-08 20:13:10 -06:00
Waffle Maybe
268ea3528d
Fix outdated comment
Co-authored-by: clubby789 <jamie@hill-daniel.co.uk>
2022-11-08 21:49:58 +04:00
Maybe Waffle
e5d01dcc78 Remove an address comparison from the parser 2022-11-08 11:51:10 +00:00
yukang
9e7d2287cd use subdiagnostic for sugesting add let 2022-11-08 16:25:37 +08:00
yukang
667b15bb0e fix #103587, Recover from common if let syntax mistakes/typos 2022-11-08 14:10:04 +08:00
Dylan DPC
170ad4a0ab
Rollup merge of #103986 - compiler-errors:oh-no-bad-block-should-not-have-label, r=lcnr
Don't silently eat label before block in block-like expr

Fixes #103983
cc #92823 (where the regression was introduced)
2022-11-07 18:35:24 +05:30
Yuki Okushi
19c780ab13
Rollup merge of #103914 - nnethercote:close-42326, r=petrochenkov
Make underscore_literal_suffix a hard error.

It's been a warning for 5.5 years. Time to make it a hard error.

Closes #42326.

r? ``@pnkfelix``
2022-11-07 09:46:26 +09:00
Nicholas Nethercote
dba6fc3ef5 Make underscore_literal_suffix a hard error.
It's been a warning for 5.5 years. Time to make it a hard error.

Closes #42326.
2022-11-07 10:00:36 +11:00
Michael Goulet
28d82ddfc2
Fix typo 2022-11-05 19:33:12 -07:00
Michael Goulet
4e7fc663cc Don't silently eat label before block in block-like expr 2022-11-04 21:35:58 +00:00
yukang
4b77e730b5 fake a base to suppress later extra error message 2022-11-04 19:32:32 +08:00
Nicholas Nethercote
a203482d2a Inline and remove validate_int_literal.
It has a single callsite, and is fairly small. The `Float` match arm
already has base-specific checking inline, so this makes things more
consistent.
2022-11-04 14:24:41 +11:00
Nicholas Nethercote
d963686f5a Refactor cook_lexer_literal.
It deals with eight cases: ints, floats, and the six quoted types
(char/byte/strings). For ints and floats we have an early return, and
the other six types fall through to the code at the end, which makes the
function hard to read.

This commit rearranges things to avoid the early returns.
2022-11-04 14:24:41 +11:00
Nicholas Nethercote
7dbf2c0ed8 Make non-ASCII errors more consistent.
There are three kinds of "byte" literals: byte literals, byte string
literals, and raw byte string literals. None are allowed to have
non-ASCII chars in them.

Two `EscapeError` variants exist for when that constraint is violated.
- `NonAsciiCharInByte`: used for byte literals and byte string literals.
- `NonAsciiCharInByteString`: used for raw byte string literals.

As a result, the messages for raw byte string literals use different
wording, without good reason. Also, byte string literals are incorrectly
described as "byte constants" in some error messages.

This commit eliminates `NonAsciiCharInByteString` so the three cases are
handled similarly, and described correctly. The `mode` is enough to
distinguish them.

Note: Some existing error messages mention "byte constants" and some
mention "byte literals". I went with the latter here, because it's a
more correct name, as used by the Reference.
2022-11-04 14:23:40 +11:00
yukang
1e25882944 fix #102806, suggest use .. to fill in the rest of the fields of Struct 2022-11-04 10:35:36 +08:00
Nicholas Nethercote
34b32b0dac Use Mode less.
It's passed to numerous places where we just need an `is_byte` bool.
Passing the bool avoids the need for some assertions.

Also rename `is_bytes()` as `is_byte()`, to better match `Mode::Byte`,
`Mode::ByteStr`, and `Mode::RawByteStr`.
2022-11-03 15:58:19 +11:00
Dylan DPC
109f887bf5
Rollup merge of #103703 - Nilstrieb:flag-recovery-1, r=compiler-errors
Gate some parser recovery behind the check

Mainly in `expr.rs`. `may_recover` doesn't do anything useful yet until I implement that on top of #103439.

r? `@compiler-errors`
2022-11-02 22:32:03 +05:30
Manish Goregaokar
69e705564d
Rollup merge of #103575 - Xiretza:suggestions-style-attr, r=davidtwco
Change #[suggestion_*] attributes to use style="..."

As discussed [on Zulip](https://rust-lang.zulipchat.com/#narrow/stream/336883-i18n/topic/.23100717.20tool_only_span_suggestion), this changes `#[(multipart_)suggestion_{short,verbose,hidden}(...)]` attributes to plain `#[(multipart_)suggestion(...)]` attributes with a `style = "{short,verbose,hidden}"` parameter.

It also adds a new style, `tool-only`, that corresponds to `tool_only_span_suggestion`/`tool_only_multipart_suggestion` and causes the suggestion to not be shown in human-readable output at all.

Best reviewed commit-by-commit, there's a bit of noise in there.

cc #100717 `@compiler-errors`
r? `@davidtwco`
2022-11-01 20:00:38 -04:00
bors
11ebe6512b Auto merge of #103217 - mejrs:track, r=eholk
Track where diagnostics were created.

This implements the `-Ztrack-diagnostics` flag, which uses `#[track_caller]` to track where diagnostics are created. It is meant as a debugging tool much like `-Ztreat-err-as-bug`.

For example, the following code...

```rust
struct A;
struct B;

fn main(){
    let _: A = B;
}
```
...now emits the following error message:

```
error[E0308]: mismatched types
 --> src\main.rs:5:16
  |
5 |     let _: A = B;
  |            -   ^ expected struct `A`, found struct `B`
  |            |
  |            expected due to this
-Ztrack-diagnostics: created at compiler\rustc_infer\src\infer\error_reporting\mod.rs:2275:31
```
2022-11-01 21:09:45 +00:00
mejrs
cbeb244b05 Add more track_caller 2022-10-31 16:14:29 +01:00
Nilstrieb
29e50e8d35
Gate some recovery behind a flag
Mainly in `expr.rs`
2022-10-28 22:07:36 +02:00
Matthias Krüger
f9dfb6e32f
Rollup merge of #103544 - Nilstrieb:no-recovery-pls, r=compiler-errors
Add flag to forbid recovery in the parser

To start the effort of fixing #103534, this adds a new flag to the parser, which forbids the parser from doing recovery, which it shouldn't do in macros.

This doesn't add any new checks for recoveries yet and is just here to bikeshed the names for the functions here before doing more.

r? `@compiler-errors`
2022-10-27 15:03:58 +02:00
nils
da407ed38f
Fix typo
Co-authored-by: Esteban Kuber <estebank@users.noreply.github.com>
2022-10-26 22:06:35 +02:00
Nilstrieb
796114a5b0
Add documentation 2022-10-26 21:09:28 +02:00
Xiretza
cd621be782 Convert all #[suggestion_*] attributes to #[suggestion(style = "...")]
Using the following command:

find compiler/ -type f -name '*.rs' -exec perl -i -gpe \
    's/(#\[\w*suggestion)_(short|verbose|hidden)\(\s*(\S+,)?/\1(\3style = "\2",/g' \
    '{}' +
2022-10-26 15:04:09 +02:00
Dylan DPC
742741f9c1
Rollup merge of #103444 - chenyukang:yukang/fix-103425-extra-diag, r=davidtwco
Remove extra type error after missing semicolon error

Fixes #103425
2022-10-26 11:29:55 +05:30
Nilstrieb
ed14202864
Add flag to forbid recovery in the parser 2022-10-25 22:06:53 +02:00
Yuki Okushi
11d11e3415
Rollup merge of #103333 - chenyukang:yukang/fix-103143, r=wesleywiser
Fix assertion failed for break_last_token and trailing token

Fixes #103143
2022-10-25 08:01:27 +09:00
yukang
a46af18cb1 fix parentheses surrounding spacing issue in parser 2022-10-24 18:24:10 +08:00
yukang
f54c336c80 fix #103425, remove extra type error after missing semicolon error 2022-10-24 09:20:07 +08:00
bors
9be2f35a4c Auto merge of #103431 - Dylan-DPC:rollup-oozfo89, r=Dylan-DPC
Rollup of 6 pull requests

Successful merges:

 - #101293 (Recover when unclosed char literal is parsed as a lifetime in some positions)
 - #101908 (Suggest let for assignment, and some code refactor)
 - #103192 (rustdoc: Eliminate uses of `EarlyDocLinkResolver::all_traits`)
 - #103226 (Check `needs_infer` before `needs_drop` during HIR generator analysis)
 - #103249 (resolve: Revert "Set effective visibilities for imports more precisely")
 - #103305 (Move some tests to more reasonable places)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-10-23 11:33:18 +00:00
Dylan DPC
e029c1fd43
Rollup merge of #101293 - compiler-errors:lt-is-actually-char, r=estebank
Recover when unclosed char literal is parsed as a lifetime in some positions

Fixes #101278
2022-10-23 15:20:16 +05:30
bors
e64f1110c0 Auto merge of #103345 - Nilstrieb:diag-flat, r=compiler-errors
Flatten diagnostic slug modules

This makes it easier to grep for the slugs in the code.

See https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Localization.20infra.20interferes.20with.20grepping.20for.20error for more discussion about it.

This was mostly done with a few regexes and a bunch of manual work. This also exposes a pretty annoying inconsistency for the extra labels. Some of the extra labels are defined as additional properties in the fluent message (which makes them not prefixed with the crate name) and some of them are new fluent messages themselves (which makes them prefixed with the crate name). I don't know whether we want to clean this up at some point but it's useful to know.

r? `@davidtwco`
2022-10-23 09:06:39 +00:00
Nilstrieb
c65ebae221
Migrate all diagnostics 2022-10-23 10:09:44 +02:00
Matthias Krüger
b656f5e9a6
Rollup merge of #103354 - clubby789:escape-string-literals, r=compiler-errors
Escape string literals when fixing overlong char literal

Fixes #103323

````@rustbot```` label +A-diagnostics +A-suggestion-diagnostics
2022-10-23 08:14:31 +02:00
Michael Goulet
3d7b1f0d18 Don't erroneously deny semicolons after closure expr within parentheses in a macro 2022-10-22 06:59:49 +00:00
Michael Goulet
0270b50eb0 Recover unclosed char literal being parsed as lifetime 2022-10-22 06:57:12 +00:00
clubby789
ed40d46159 Properly escape quotes when suggesting switching between char/string literals 2022-10-22 02:37:15 +01:00
Dylan DPC
0a0e9f73af
Rollup merge of #102922 - kper:bugfix/102902-filtering-json, r=oli-obk
Filtering spans when emitting json

According to the issue #102902, we shouldn't emit spans which have an empty span and no suggested replacement.
2022-10-21 17:29:58 +05:30
yukang
2414357374 fix assertion failed for break_last_token and trailing token 2022-10-20 20:16:27 +08:00
Kevin Per
28d0312b7d Implement assertions and fixes to not emit empty spans without suggestions 2022-10-20 08:25:31 +00:00
yukang
0af255a5aa Fix the bug of next_point in span 2022-10-18 02:59:38 +08:00
Rageking8
7122abaddf more dupe word typos 2022-10-14 12:57:56 +08:00
Dylan DPC
a9a5529eac
Rollup merge of #102927 - compiler-errors:let, r=davidtwco
Fix `let` keyword removal suggestion in structs

(1.) Fixes a bug where, given this code:
```rust
struct Foo {
  let x: i32,
}
```

We were parsing the field name as `let` instead of `x`, which causes issues later on in the type-checking phase.

(2.) Also, suggestions for `let: i32` as a field regressed, displaying this extra `help:` which is removed by this PR

```
help: remove the let, the `let` keyword is not allowed in struct field definitions
  |
2 -     let: i32,
2 +     : i32,
```

(3.) Makes the suggestion text a bit more succinct, since we don't need to re-explain that `let` is not allowed in this position (since it's in a note that follows). This causes the suggestion to render inline as well.

cc `@gimbles,` this addresses a few nits I mentioned in your PR.
2022-10-12 22:13:26 +05:30
Nilstrieb
7bfef19844 Use tidy-alphabetical in the compiler 2022-10-12 17:49:10 +05:30
Michael Goulet
f9d3c83526 Fix let removal suggestion in struct 2022-10-11 17:35:50 +00:00
bors
518263d889 Auto merge of #102896 - matthiaskrgr:rollup-jg5xawz, r=matthiaskrgr
Rollup of 6 pull requests

Successful merges:

 - #101360 (Point out incompatible closure bounds)
 - #101789 (`let`'s not needed in struct field definitions)
 - #102846 (update to syn-1.0.102)
 - #102871 (rustdoc: clean up overly complex `.trait-impl` CSS selectors)
 - #102876 (suggest candidates for unresolved import)
 - #102888 (Improve rustdoc-gui search-color test)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-10-11 00:36:26 +00:00
Matthias Krüger
01a2246000
Rollup merge of #101789 - gimbles:let, r=estebank
`let`'s not needed in struct field definitions

Fixes #101683
2022-10-10 20:47:32 +02:00
Guillaume Gomez
adc24d1b5e Fix compiler docs 2022-10-10 18:28:29 +02:00
gimbles
6071b4b8a6 let is not allowed in struct field definitions
Co-authored-by: jyn514 <jyn514@gmail.com>
Co-authored-by: Esteban Kuber <estebank@users.noreply.github.com>
2022-10-10 16:53:13 +05:30
Yuki Okushi
303ebd5b04
Rollup merge of #102345 - chenyukang:fix-102182-impl-trait, r=estebank
Recover from impl Trait in type param bound

Fixes #102182
r? ``@estebank``
2022-10-10 10:23:04 +09:00
Urgau
5ae73634dc Stabilize half_open_range_patterns 2022-10-08 11:00:13 +02:00
yukang
7b2f04a2b3 fix #102182, recover from impl Trait in type param bound 2022-10-08 06:47:26 +08:00
bors
0152393048 Auto merge of #99324 - reez12g:issue-99144, r=jyn514
Enable doctests in compiler/ crates

Helps with https://github.com/rust-lang/rust/issues/99144
2022-10-06 03:01:57 +00:00
Nicholas Nethercote
4e5ddf1adf Invert is_top_level to avoid negation. 2022-10-03 11:42:29 +11:00
Nicholas Nethercote
a822d08bd1 Remove TokenStreamBuilder.
It's now only used in one function. Also, the "should we glue the
tokens?" check is only necessary when pushing a `TokenTree::Token`, not
when pushing a `TokenTree::Delimited`.

As part of this, we now do the "should we glue the tokens?" check
immediately, which avoids having look back at the previous token. It
also puts all the logic dealing with token gluing in a single place.
2022-10-03 11:42:29 +11:00
Nicholas Nethercote
8d0754d602 Inline and remove parse_token_tree_non_delim_non_eof.
It has a single call site.
2022-10-03 11:42:29 +11:00
Nicholas Nethercote
ce7676829e Merge parse_token_trees_until_close_delim and parse_all_token_trees.
Because they're very similar, and this will allow some follow-up
changes.
2022-10-03 11:42:29 +11:00
Nicholas Nethercote
9de9cf19d7 Add comments to TokenCursor::desugar.
It took me some time to work out what this code was doing.
2022-10-03 11:42:29 +11:00
Matthias Krüger
cc009bc536
Rollup merge of #102500 - compiler-errors:parse-sess-cleanup, r=cjgillot
Remove `expr_parentheses_needed` from `ParseSess`

Not sure why this method needed to exist on `ParseSess`, but we can achieve the same behavior by just inlining it everywhere.
2022-10-01 16:45:05 +02:00
Maybe Waffle
d86f9cd464 Replace some bool params with an enum 2022-10-01 10:13:02 +00:00
Maybe Waffle
38b0865248 Recover wrong cased keywords starting functions 2022-10-01 10:08:53 +00:00
Maybe Waffle
3694429d09 recover wrong-cased uses (Use, USE, etc) 2022-10-01 10:07:47 +00:00
Matthias Krüger
eaf1c7a0da
Rollup merge of #102493 - nnethercote:improve-size-assertions-some-more, r=lqd
Group together more size assertions.

Also add a few more assertions for some relevant token-related types.

And fix an erroneous comment in `rustc_errors`.

r? `@lqd`
2022-09-30 23:38:27 +02:00
Nicholas Nethercote
5ab68a82d5 Group together more size assertions.
Also add a few more assertions for some relevant token-related types.

And fix an erroneous comment in `rustc_errors`.
2022-10-01 07:30:23 +10:00
Matthias Krüger
6906e64c30
Rollup merge of #102350 - TaKO8Ki:incomplete-fn-in-struct-definition, r=fee1-dead
Improve errors for incomplete functions in struct definitions

Given the following code:

```rust
fn main() {}

struct Foo {
    fn
}
```

[playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=29139f870511f6918324be5ddc26c345)

The current output is:

```
   Compiling playground v0.0.1 (/playground)
error: functions are not allowed in struct definitions
 --> src/main.rs:4:5
  |
4 |     fn
  |     ^^
  |
  = help: unlike in C++, Java, and C#, functions are declared in `impl` blocks
  = help: see https://doc.rust-lang.org/book/ch05-03-method-syntax.html for more information

error: could not compile `playground` due to previous error
```

In this case, rustc should suggest escaping `fn` to use it as an identifier.
2022-09-30 10:22:37 +02:00
Michael Goulet
85a726e754 Remove expr_parentheses_needed from ParseSess 2022-09-30 01:39:20 +00:00
reez12g
9a4c5abe45 Remove from compiler/ crates 2022-09-29 16:49:04 +09:00
Rageking8
2ee2ffa9a7 improve E0585 help 2022-09-29 00:34:31 +08:00
bors
09ae7846a2 Auto merge of #101619 - Xiretza:rustc_parse-session-diagnostics, r=davidtwco
Migrate more of rustc_parse to SessionDiagnostic

Still far from complete, but I thought I'd add a checkpoint here because rebasing was starting to get annoying.
2022-09-28 11:11:42 +00:00
bors
6201eabde8 Auto merge of #102302 - nnethercote:more-lexer-improvements, r=matklad
More lexer improvements

A follow-up to #99884.

r? `@matklad`
2022-09-28 08:14:04 +00:00
Nicholas Nethercote
d0a26acb2a Address review comments. 2022-09-28 11:15:23 +10:00
Matthias Krüger
8b635cba1d
Rollup merge of #102284 - compiler-errors:missing-type-in-raw-ptr, r=davidtwco
Structured suggestion for missing `mut`/`const` in raw pointer

Fixes #102261
2022-09-27 21:42:23 +02:00
Xiretza
d7c64574e0 Implement IntoDiagnosticArg for rustc_ast::token::Token(Kind) 2022-09-27 20:29:19 +02:00
Xiretza
37fdcb4b36 Don't unnecessarily stringify paths in diagnostics 2022-09-27 20:29:19 +02:00
Xiretza
caefac034e Document use of Symbol::to_string() 2022-09-27 20:29:19 +02:00
Xiretza
00f95468c4 Migrate even more diagnostics in rustc_parse to diagnostic structs 2022-09-27 20:29:19 +02:00
Xiretza
760c4352d6 Migrate "struct literal body without path" error to diagnostic struct 2022-09-27 20:29:19 +02:00
Xiretza
ba10f2c0f2 Migrate "expected semicolon" diagnostics to diagnostic structs 2022-09-27 20:29:19 +02:00
Xiretza
7507ee29fc Migrate "expected identifier" diagnostics to diagnostic structs 2022-09-27 20:29:19 +02:00
Xiretza
21b5194a3a Rework "inner attribute not permitted" errors 2022-09-27 20:29:19 +02:00
Xiretza
4d0519a4e7 Remove error condition in parse_attribute
This function is only ever called when the `#` has already been
consumed, no need to produce an error message here.
2022-09-27 20:29:19 +02:00
Xiretza
e1b1d7b029 Migrate more rustc_parse diagnostics to diagnostic structs 2022-09-27 20:29:18 +02:00
Xiretza
e56d6a68db Move rustc_parse diagnostic structs to separate module 2022-09-27 20:29:18 +02:00
Xiretza
6ae7a30927 Migrate "invalid literal suffix" diagnostic to diagnostic structs 2022-09-27 20:29:18 +02:00
Xiretza
ab7c7dc7ce Migrate more diagnostics in rustc_parse to diagnostic structs 2022-09-27 20:29:18 +02:00
Takayuki Maeda
d7b6bd8f13 improve errors for incomplete functions in struct definitions 2022-09-28 01:03:18 +09:00
Michael Goulet
594134d873 Structured suggestion for missing mut/const in pointer 2022-09-27 02:47:07 +00:00
Nicholas Nethercote
7f7e2165b1 Rename some variables.
These make the delimiter processing clearer.
2022-09-27 12:04:03 +10:00
Takayuki Maeda
4f44dee501 add a label to struct/enum/union ident name 2022-09-27 10:28:50 +09:00
Takayuki Maeda
e123a61297 create a new local var 2022-09-27 10:22:46 +09:00
Nicholas Nethercote
880ebb657a Minor improvements.
Add some comments, and mark one path as unreachable.
2022-09-27 09:53:04 +10:00
Matthias Krüger
6f5e8c2ed4
Rollup merge of #102286 - compiler-errors:recover-semi-in-block-item, r=davidtwco
Recover some items that expect braces and don't take semicolons

Fixes #102262
2022-09-26 19:19:21 +02:00
Pietro Albini
3975d55d98
remove cfg(bootstrap) 2022-09-26 10:14:45 +02:00
bors
72f4923979 Auto merge of #102297 - fee1-dead-contrib:rollup-2np0cre, r=fee1-dead
Rollup of 5 pull requests

Successful merges:

 - #102143 (Recover from struct nested in struct)
 - #102178 (bootstrap: the backtrace feature is stable, no need to allow it any more)
 - #102197 (Stabilize const `BTree{Map,Set}::new`)
 - #102267 (Don't set RUSTC in the bootstrap build script)
 - #102270 (Remove benches from `rustc_middle`)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-09-26 05:27:43 +00:00
Nicholas Nethercote
fb4dba0a17 Inline and remove cook_lexer_token.
This is a small performance win, alas.
2022-09-26 13:50:13 +10:00
Nicholas Nethercote
da84f0f4c3 Add rustc_lexer::TokenKind::Eof.
For alignment with `rust_ast::TokenKind::Eof`. Plus it's a bit faster,
due to less `Option` manipulation in `StringReader::next_token`.
2022-09-26 13:48:08 +10:00
Nicholas Nethercote
ceb25d125f Use less DRY in cook_lexer_token.
This is a case where a small amount of repetition results in code that
is faster and easier to read.
2022-09-26 13:41:58 +10:00
Nicholas Nethercote
aa6bfaf04b Make rustc_lexer::cursor::Cursor public.
`Cursor` is currently hidden, and the main tokenization path uses
`rustc_lexer::first_token` which involves constructing a new `Cursor`
for every single token, which is weird. Also, `first_token` also can't
handle empty input, so callers have to check for that first.

This commit makes `Cursor` public, so `StringReader` can contain a
`Cursor`, which results in a simpler structure. The commit also changes
`StringReader::advance_token` so it returns an `Option<Token>`,
simplifying the the empty input case.
2022-09-26 13:36:35 +10:00
Nicholas Nethercote
33516ac09a [ui] Rearrange StringReader/TokenTreesReader creation.
`TokenTreesReader` wraps a `StringReader`, but the `into_token_trees`
function obscures this. This commit moves to a more straightforward
control flow.
2022-09-26 13:35:46 +10:00
Nicholas Nethercote
33ba2776c9 Remove ast::Token::take.
Instead of replacing `TokenTreesReader::token` in two steps, we can just
do it in one, which is both simpler and faster.
2022-09-26 13:35:43 +10:00
Nicholas Nethercote
5b2075e03d Remove TokenTreesReader::bump.
It's an unnecessary layer that obfuscates when I am looking for
optimizations.
2022-09-26 13:34:04 +10:00
Nicholas Nethercote
d7928a92e5 Clarify spacing computation.
The spacing computation is done in two parts. In the first part
`next_token` and `bump` use `Spacing::Alone` to mean "preceded by
whitespace" and `Spacing::Joint` to mean the opposite. In the second
part `parse_token_tree_other` then adjusts the `spacing` value to mean
the usual thing (i.e. "is the following token joinable punctuation?").
This shift in meaning is very confusing and it took me some time to
understand what was going on.

This commit changes the first part to use a bool, and adds some
comments, which makes things much clearer.
2022-09-26 13:21:26 +10:00
Nicholas Nethercote
9640d1c023 Move #! checking.
Currently does the "is this a `#!` at the start of the file?" check for
every single token(!)

This commit moves it so it only happens once.
2022-09-26 13:19:14 +10:00
Michael Goulet
4d0d688a3c Recover some items that expect braces and don't take semicolons 2022-09-25 22:34:25 +00:00
Nicholas Nethercote
14281e6147 Remove unnecessary spacing assignment.
It has no useful effect.
2022-09-26 08:28:45 +10:00
Nicholas Nethercote
66e9b1149c Rearrange TokenTreesReader::parse_token_tree.
`parse_token_tree` is basically a match with four arms: `Eof`,
`OpenDelim`, `CloseDelim`, and "other". It has two call sites, and at
each call site one of the arms is unreachable. It's also not inlined.

This commit removes `parse_token_tree` by splitting it into four
functions and inlining them. This avoids some repeated conditional
tests and also some non-inlined function calls on the hot path.
2022-09-26 08:28:45 +10:00
Rageking8
a1062b9bdc
recover from struct nested in struct 2022-09-22 23:41:38 +08:00
Xiretza
ae56d2a118 Add missing code="" attributes to suggestion subdiagnostics 2022-09-22 17:25:50 +02:00
Jhonny Bill Mena
e52e2344dc FIX - adopt new Diagnostic naming in newly migrated modules
FIX - ambiguous Diagnostic link in docs

UPDATE - rename diagnostic_items to IntoDiagnostic and AddToDiagnostic

[Gardening] FIX - formatting via `x fmt`

FIX - rebase conflicts. NOTE: Confirm wheather or not we want to handle TargetDataLayoutErrorsWrapper this way

DELETE - unneeded allow attributes in Handler method

FIX - broken test

FIX - Rebase conflict

UPDATE - rename residual _SessionDiagnostic and fix LintDiag link
2022-09-21 11:43:22 -04:00
Jhonny Bill Mena
5f91719f75 UPDATE - rename SessionSubdiagnostic macro to Subdiagnostic
Also renames:
- sym::AddSubdiagnostic to sym:: Subdiagnostic
- rustc_diagnostic_item = "AddSubdiagnostic" to rustc_diagnostic_item = "Subdiagnostic"
2022-09-21 11:39:53 -04:00
Jhonny Bill Mena
a3396b2070 UPDATE - rename DiagnosticHandler macro to Diagnostic 2022-09-21 11:39:53 -04:00
Jhonny Bill Mena
19b348fed4 UPDATE - rename DiagnosticHandler trait to IntoDiagnostic 2022-09-21 11:39:52 -04:00
Jhonny Bill Mena
5b8152807c UPDATE - move SessionDiagnostic from rustc_session to rustc_errors 2022-09-21 11:39:52 -04:00
bors
b79b7d8b4e Auto merge of #101846 - chenyukang:fix-101793, r=davidtwco
Fix the wording of help msg for bitwise not

Fixes #101793
2022-09-21 12:32:54 +00:00
Michael Howell
14b27cfd11
Rollup merge of #100250 - cjgillot:recover-token-stream, r=Aaron1011
Manually cleanup token stream when macro expansion aborts.

In case of syntax error in macro expansion, the expansion code can decide to stop processing anything. In that case, the token stream is malformed. This makes downstream users, like derive macros, ICE.

In this case, this PR manually cleans up the token stream by closing all currently open delimiters.

Fixes https://github.com/rust-lang/rust/issues/96818.
Fixes https://github.com/rust-lang/rust/issues/80447.
Fixes https://github.com/rust-lang/rust/issues/81920.
Fixes https://github.com/rust-lang/rust/issues/91023.
2022-09-20 10:12:56 -07:00
Dylan DPC
3ad81e0dd8
Rollup merge of #93628 - est31:stabilize_let_else, r=joshtriplett
Stabilize `let else`

🎉  **Stabilizes the `let else` feature, added by [RFC 3137](https://github.com/rust-lang/rfcs/pull/3137).** 🎉

Reference PR: https://github.com/rust-lang/reference/pull/1156

closes #87335 (`let else` tracking issue)

FCP: https://github.com/rust-lang/rust/pull/93628#issuecomment-1029383585

----------

## Stabilization report

### Summary

The feature allows refutable patterns in `let` statements if the expression is
followed by a diverging `else`:

```Rust
fn get_count_item(s: &str) -> (u64, &str) {
    let mut it = s.split(' ');
    let (Some(count_str), Some(item)) = (it.next(), it.next()) else {
        panic!("Can't segment count item pair: '{s}'");
    };
    let Ok(count) = u64::from_str(count_str) else {
        panic!("Can't parse integer: '{count_str}'");
    };
    (count, item)
}
assert_eq!(get_count_item("3 chairs"), (3, "chairs"));
```

### Differences from the RFC / Desugaring

Outside of desugaring I'm not aware of any differences between the implementation and the RFC. The chosen desugaring has been changed from the RFC's [original](https://rust-lang.github.io/rfcs/3137-let-else.html#reference-level-explanations). You can read a detailed discussion of the implementation history of it in `@cormacrelf` 's [summary](https://github.com/rust-lang/rust/pull/93628#issuecomment-1041143670) in this thread, as well as the [followup](https://github.com/rust-lang/rust/pull/93628#issuecomment-1046598419). Since that followup, further changes have happened to the desugaring, in #98574, #99518, #99954. The later changes were mostly about the drop order: On match, temporaries drop in the same order as they would for a `let` declaration. On mismatch, temporaries drop before the `else` block.

### Test cases

In chronological order as they were merged.

Added by df9a2e0687 (#87688):

* [`ui/pattern/usefulness/top-level-alternation.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/pattern/usefulness/top-level-alternation.rs) to ensure the unreachable pattern lint visits patterns inside `let else`.

Added by 5b95df4bdc (#87688):

* [`ui/let-else/let-else-bool-binop-init.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-bool-binop-init.rs) to ensure that no lazy boolean expressions (using `&&` or `||`) are allowed in the expression, as the RFC mandates.
* [`ui/let-else/let-else-brace-before-else.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-brace-before-else.rs) to ensure that no `}` directly preceding the `else` is allowed in the expression, as the RFC mandates.
* [`ui/let-else/let-else-check.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-check.rs) to ensure that `#[allow(...)]` attributes added to the entire `let` statement apply for the `else` block.
* [`ui/let-else/let-else-irrefutable.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-irrefutable.rs) to ensure that the `irrefutable_let_patterns` lint fires.
* [`ui/let-else/let-else-missing-semicolon.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-missing-semicolon.rs) to ensure the presence of semicolons at the end of the `let` statement.
* [`ui/let-else/let-else-non-diverging.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-non-diverging.rs) to ensure the `else` block diverges.
* [`ui/let-else/let-else-run-pass.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-run-pass.rs) to ensure the feature works in some simple test case settings.
* [`ui/let-else/let-else-scope.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-scope.rs) to ensure the bindings created by the outer `let` expression are not available in the `else` block of it.

Added by bf7c32a447 (#89965):

* [`ui/let-else/issue-89960.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/issue-89960.rs) as a regression test for the ICE-on-error bug #89960 . Later in 102b9125e1 this got removed in favour of more comprehensive tests.

Added by 856541963c (#89974):

* [`ui/let-else/let-else-if.rs`](https://github.com/rust-lang/rust/blob/1.58.1/src/test/ui/let-else/let-else-if.rs) to test for the improved error message that points out that `let else if` is not possible.

Added by 9b45713b6c:

* [`ui/let-else/let-else-allow-unused.rs`](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-allow-unused.rs) as a regression test for #89807, to ensure that `#[allow(...)]` attributes added to the entire `let` statement apply for bindings created by the `let else` pattern.

Added by 61bcd8d307 (#89841):

* [`ui/let-else/let-else-non-copy.rs`](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-non-copy.rs) to ensure that a copy is performed out of non-copy wrapper types. This mirrors `if let` behaviour. The test case bases on rustc internal changes originally meant for #89933 but then removed from the PR due to the error prior to the improvements of #89841.
* [`ui/let-else/let-else-source-expr-nomove-pass.rs `](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-source-expr-nomove-pass.rs) to ensure that while there is a move of the binding in the successful case, the `else` case can still access the non-matching value. This mirrors `if let` behaviour.

Added by 102b9125e1 (#89841):

* [`ui/let-else/let-else-ref-bindings.rs`](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-ref-bindings.rs) and [`ui/let-else/let-else-ref-bindings-pass.rs `](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-ref-bindings-pass.rs) to check `ref` and `ref mut` keywords in the pattern work correctly and error when needed.

Added by 2715c5f984 (#89841):

* Match ergonomic tests adapted from the `rfc2005` test suite.

Added by fec8a507a2 (#89841):

* [`ui/let-else/let-else-deref-coercion-annotated.rs`](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-deref-coercion-annotated.rs) and [`ui/let-else/let-else-deref-coercion.rs`](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-deref-coercion.rs) to check deref coercions.

#### Added since this stabilization report was originally written (2022-02-09)

Added by 76ea566677 (#94211):

* [`ui/let-else/let-else-destructuring.rs`](https://github.com/rust-lang/rust/blob/1.63.0/src/test/ui/let-else/let-else-destructuring.rs) to give a nice error message if an user tries to do an assignment with a (possibly refutable) pattern and an `else` block, like asked for in #93995.

Added by e7730dcb7e (#94208):

* [`ui/let-else/let-else-allow-in-expr.rs`](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-allow-in-expr.rs) to test whether `#[allow(unused_variables)]` works in the expr, as well as its non presence, as well as putting it on the entire `let else` *affects* the expr, too. This was adding a missing test as pointed out by the stabilization report.
* Expansion of `ui/let-else/let-else-allow-unused.rs` and `ui/let-else/let-else-check.rs` to ensure that non-presence of `#[allow(unused)]` does issue the unused lint. This was adding a missing test case as pointed out by the stabilization report.

Added by 5bd71063b3 (#94208):

* [`ui/let-else/let-else-slicing-error.rs`](https://github.com/rust-lang/rust/blob/1.61.0/src/test/ui/let-else/let-else-slicing-error.rs), a regression test for #92069, which got fixed without addition of a regression test. This resolves a missing test as pointed out by the stabilization report.

Added by 5374688e1d (#98574):

* [`src/test/ui/async-await/async-await-let-else.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/async-await/async-await-let-else.rs) to test the interaction of async/await with `let else`

Added by 6c529ded86 (#98574):

* [`src/test/ui/let-else/let-else-temporary-lifetime.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/let-else/let-else-temporary-lifetime.rs) as a (partial) regression test for #98672

Added by 9b56640106 (#99518):

* [`src/test/ui/let-else/let-else-temp-borrowck.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/let-else/let-else-temporary-lifetime.rs) as a regression test for #93951
* Extension of `src/test/ui/let-else/let-else-temporary-lifetime.rs` to include a partial regression test for #98672 (especially regarding `else` drop order)

Added by baf9a7cb57 (#99518):

* Extension of `src/test/ui/let-else/let-else-temporary-lifetime.rs` to include a partial regression test for #93951, similar to `let-else-temp-borrowck.rs`

Added by 60be2de8b7 (#99518):

* Extension of `src/test/ui/let-else/let-else-temporary-lifetime.rs` to include a program that can now be compiled thanks to borrow checker implications of #99518

Added by 47a7a91c96 (#100132):

* [`src/test/ui/let-else/issue-100103.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/let-else/issue-100103.rs), as a regression test for #100103, to ensure that there is no ICE when doing `Err(...)?` inside else blocks.

Added by e3c5bd617d (#100443):

* [`src/test/ui/let-else/let-else-then-diverge.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/let-else/let-else-then-diverge.rs), to verify that there is no unreachable code error with the current desugaring.

Added by 981852677c (#100443):

* [`src/test/ui/let-else/issue-94176.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/let-else/issue-94176.rs), to make sure that a correct span is emitted for a missing trailing expression error. Regression test for #94176.

Added by e182d12a84 (#100434):

* [src/test/ui/unpretty/pretty-let-else.rs](https://github.com/rust-lang/rust/blob/master/src/test/ui/unpretty/pretty-let-else.rs), as a regression test to ensure pretty printing works for `let else` (this bug surfaced in many different ways)

Added by e26285603c (#99954):

* [`src/test/ui/let-else/let-else-temporary-lifetime.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/let-else/let-else-temporary-lifetime.rs) extended to contain & borrows as well, as this was identified as an earlier issue with the desugaring: https://github.com/rust-lang/rust/issues/98672#issuecomment-1200196921

Added by 2d8460ef43 (#99291):

* [`src/test/ui/let-else/let-else-drop-order.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/let-else/let-else-drop-order.rs) a matrix based test for various drop order behaviour of `let else`. Especially, it verifies equality of `let` and `let else` drop orders, [resolving](https://github.com/rust-lang/rust/pull/93628#issuecomment-1238498468) a [stabilization blocker](https://github.com/rust-lang/rust/pull/93628#issuecomment-1055738523).

Added by 1b87ce0d40 (#101410):

* Edit to `src/test/ui/let-else/let-else-temporary-lifetime.rs` to add the `-Zvalidate-mir` flag, as a regression test for #99228

Added by af591ebe4d (#101410):

* [`src/test/ui/let-else/issue-99975.rs`](https://github.com/rust-lang/rust/blob/master/src/test/ui/let-else/issue-99975.rs) as a regression test for the ICE #99975.

Added by this PR:

* `ui/let-else/let-else.rs`, a simple run-pass check, similar to `ui/let-else/let-else-run-pass.rs`.

### Things not currently tested

* ~~The `#[allow(...)]` tests check whether allow works, but they don't check whether the non-presence of allow causes a lint to fire.~~ → *test added by e7730dcb7eb29a10ee73f269f4dc6e9d606db0da*
* ~~There is no `#[allow(...)]` test for the expression, as there are tests for the pattern and the else block.~~ → *test added by e7730dcb7eb29a10ee73f269f4dc6e9d606db0da*
* ~~`let-else-brace-before-else.rs` forbids the `let ... = {} else {}` pattern and there is a rustfix to obtain `let ... = ({}) else {}`. I'm not sure whether the `.fixed` files are checked by the tooling that they compile. But if there is no such check, it would be neat to make sure that `let ... = ({}) else {}` compiles.~~ → *test added by e7730dcb7eb29a10ee73f269f4dc6e9d606db0da*
* ~~#92069 got closed as fixed, but no regression test was added. Not sure it's worth to add one.~~ → *test added by 5bd71063b3810d977aa376d1e6dd7cec359330cc*
* ~~consistency between `let else` and `if let` regarding lifetimes and drop order: https://github.com/rust-lang/rust/pull/93628#issuecomment-1055738523~~ → *test added by 2d8460ef43d902f34ba2133fe38f66ee8d2fdafc*

Edit: they are all tested now.

### Possible future work / Refutable destructuring assignments

[RFC 2909](https://rust-lang.github.io/rfcs/2909-destructuring-assignment.html) specifies destructuring assignment, allowing statements like `FooBar { a, b, c } = foo();`.
As it was stabilized, destructuring assignment only allows *irrefutable* patterns, which before the advent of `let else` were the only patterns that `let` supported.
So the combination of `let else` and destructuring assignments gives reason to think about extensions of the destructuring assignments feature that allow refutable patterns, discussed in #93995.

A naive mapping of `let else` to destructuring assignments in the form of `Some(v) = foo() else { ... };` might not be the ideal way. `let else` needs a diverging `else` clause as it introduces new bindings, while assignments have a default behaviour to fall back to if the pattern does not match, in the form of not performing the assignment. Thus, there is no good case to require divergence, or even an `else` clause at all, beyond the need for having *some* introducer syntax so that it is clear to readers that the assignment is not a given (enums and structs look similar). There are better candidates for introducer syntax however than an empty `else {}` clause, like `maybe` which could be added as a keyword on an edition boundary:

```Rust
let mut v = 0;
maybe Some(v) = foo(&v);
maybe Some(v) = foo(&v) else { bar() };
```

Further design discussion is left to an RFC, or the linked issue.
2022-09-17 15:31:06 +05:30
Guillaume Gomez
9a72ded562
Rollup merge of #101859 - Rageking8:slight-vertical-formatting, r=compiler-errors
Slight vertical formatting
2022-09-16 13:07:18 +02:00
yukang
484b612909 use subdiagnostic for logical negation, bitwise not 2022-09-16 14:41:42 +08:00
est31
173eb6f407 Only enable the let_else feature on bootstrap
On later stages, the feature is already stable.

Result of running:

rg -l "feature.let_else" compiler/ src/librustdoc/ library/ | xargs sed -s -i "s#\\[feature.let_else#\\[cfg_attr\\(bootstrap, feature\\(let_else\\)#"
2022-09-15 21:06:45 +02:00
yukang
4bf7d2ca91 tweak suggestion 2022-09-16 01:09:26 +08:00
Rageking8
6d7beafc87 slight vertical formatting 2022-09-15 23:51:43 +08:00
yukang
f43562b95b more tweak on diagnostic messages 2022-09-15 22:39:16 +08:00
yukang
98e20c097c fix #101797: Suggest associated const for incorrect use of let in traits 2022-09-15 16:15:38 +08:00
bors
750bd1a7ff Auto merge of #101313 - SparrowLii:mk_attr_id, r=cjgillot
make `mk_attr_id` part of `ParseSess`

Updates #48685

The current `mk_attr_id` uses the `AtomicU32` type, which is not very efficient and adds a lot of lock contention in a parallel environment.

This PR refers to the task list in #48685, uses `mk_attr_id` as a method of the `AttrIdGenerator` struct, and adds a new field `attr_id_generator` to `ParseSess`.

`AttrIdGenerator` uses the `WorkerLocal`, which has two advantages: 1. `Cell` is more efficient than `AtomicU32`, and does not increase any lock contention. 2. We put the index of the work thread in the first few bits of the generated `AttrId`, so that the `AttrId` generated in different threads can be easily guaranteed to be unique.

cc `@cjgillot`
2022-09-14 20:52:18 +00:00
bors
6153d3cbe6 Auto merge of #101212 - eholk:dyn-star, r=compiler-errors
Initial implementation of dyn*

This PR adds extremely basic and incomplete support for [dyn*](https://smallcultfollowing.com/babysteps//blog/2022/03/29/dyn-can-we-make-dyn-sized/). The goal is to get something in tree behind a flag to make collaboration easier, and also to make sure the implementation so far is not unreasonable. This PR does quite a few things:

* Introduce `dyn_star` feature flag
* Adds parsing for `dyn* Trait` types
* Defines `dyn* Trait` as a sized type
* Adds support for explicit casts, like `42usize as dyn* Debug`
  * Including const evaluation of such casts
* Adds codegen for drop glue so things are cleaned up properly when a `dyn* Trait` object goes out of scope
* Adds codegen for method calls, at least for methods that take `&self`

Quite a bit is still missing, but this gives us a starting point. Note that this is never intended to become stable surface syntax for Rust, but rather `dyn*` is planned to be used as an implementation detail for async functions in dyn traits.

Joint work with `@nikomatsakis` and `@compiler-errors.`

r? `@bjorn3`
2022-09-14 18:10:51 +00:00
SparrowLii
1a3ecbdb6a make mk_attr_id part of ParseSess 2022-09-14 08:49:10 +08:00
Eric Holk
cf04547b0b Address code review comments 2022-09-13 14:50:12 -07:00
Camille GILLOT
cb5ea8d0b6 Emit an error instead of reconstructing token stream. 2022-09-13 19:47:50 +02:00
Camille GILLOT
8823634db8 Manually cleanup token stream when macro expansion aborts. 2022-09-13 19:46:01 +02:00
Eric Holk
eff35e59c6 Introduce dyn_star feature flag
The primary purpose of this commit is to introduce the
dyn_star flag so we can begin experimenting with implementation.

In order to have something to do in the feature gate test, we also add
parser support for `dyn* Trait` objects. These are currently treated
just like `dyn Trait` objects, but this will change in the future.

Note that for now `dyn* Trait` is experimental syntax to enable
implementing some of the machinery needed for async fn in dyn traits
without fully supporting the feature.
2022-09-12 16:55:55 -07:00
Nicholas Nethercote
d2df07c425 Rename {Create,Lazy}TokenStream as {To,Lazy}AttrTokenStream.
`To` is better than `Create` for indicating that this is a non-consuming
conversion, rather than creating something out of nothing.

And the addition of `Attr` is because the current names makes them sound
like they relate to `TokenStream`, but really they relate to
`AttrTokenStream`.
2022-09-09 17:25:38 +10:00
Nicholas Nethercote
a56d345490 Rename AttrAnnotatedToken{Stream,Tree}.
These two type names are long and have long matching prefixes. I find
them hard to read, especially in combinations like
`AttrAnnotatedTokenStream::new(vec![AttrAnnotatedTokenTree::Token(..)])`.

This commit renames them as `AttrToken{Stream,Tree}`.
2022-09-09 12:45:26 +10:00
Nicholas Nethercote
890e759ffc Move Spacing out of AttrAnnotatedTokenStream.
And into `AttrAnnotatedTokenTree::Token`.

PR #99887 did the same thing for `TokenStream`.
2022-09-09 12:00:46 +10:00
Dylan DPC
8d2a492d73
Rollup merge of #101515 - chenyukang:fix-101477, r=fee1-dead
Recover from typo where == is used in place of =

Fixes #101477
2022-09-08 20:48:37 +05:30
yukang
ddb225f1f5 fixes #101477: Recover from typo where == is used in place of = 2022-09-08 15:14:18 +08:00
Matthias Krüger
c365ce3ffd
Rollup merge of #101502 - TaKO8Ki:do-not-suggest-semicolon-for-macro-without-exclamation-mark, r=wesleywiser
Do not suggest a semicolon for a macro without `!`

Fixes a regression in #101490
2022-09-07 21:48:15 +02:00
Takayuki Maeda
7ac124803f do not suggest a semicolon for a macro without ! 2022-09-07 03:59:47 +09:00
Guillaume Gomez
78968e5959
Rollup merge of #101457 - ChayimFriedman2:struct-field-semi, r=fee1-dead
Recover from using `;` as separator between fields

Partially fixes #101440 (only for record structs).

Doing that for tuple structs is harder as their parsing passes through a bunch of helper functions. I don't know how to do that. But [their error message is better anyway](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=cc6ee8bb2593596c0cea89d49e79bcb4) and suggests using a comma, even if it doesn't suggest replacing the semicolon with it.
2022-09-06 17:00:28 +02:00
Guillaume Gomez
4d830b7775
Rollup merge of #101434 - JhonnyBillM:replace-session-for-handler-in-into-diagnostic, r=davidtwco
Update `SessionDiagnostic::into_diagnostic` to take `Handler` instead of `ParseSess`

Suggested by the team in [this Zulip Topic](https://rust-lang.zulipchat.com/#narrow/stream/336883-i18n/topic/.23100717.20SessionDiagnostic.20on.20Handler).

`Handler` already has almost all the capabilities of `ParseSess` when it comes to diagnostic emission, in this migration we only needed to add the ability to access `source_map` from the emitter in order to get a `Snippet` and the `start_point`. Not sure if adding these two methods [`span_to_snippet_from_emitter` and  `span_start_point_from_emitter`] is the best way to address this gap.

P.S. If this goes in the right direction, then we probably may want to move `SessionDiagnostic` to `rustc_errors` and rename it to `DiagnosticHandler` or something similar.

r? `@davidtwco`
r? `@compiler-errors`
2022-09-06 17:00:26 +02:00
bors
a594044533 Auto merge of #101362 - compiler-errors:unnecessary-let, r=cjgillot
Suggest removing unnecessary prefix let in patterns

Helps with #101291, though I think `@estebank` probably wants this:

> Finally, I think it'd be nice if we could detect that we don't know for sure and "just" swallow the rest of the expression (find the next ; accounting for nested braces) or the end of the item (easier).

... to be implemented before we close that issue out completely.
2022-09-06 08:49:54 +00:00
bors
6c358c67d4 Auto merge of #101241 - camsteffen:refactor-binding-annotations, r=cjgillot
`BindingAnnotation` refactor

* `ast::BindingMode` is deleted and replaced with `hir::BindingAnnotation` (which is moved to `ast`)
* `BindingAnnotation` is changed from an enum to a tuple struct e.g. `BindingAnnotation(ByRef::No, Mutability::Mut)`
* Associated constants added for convenience `BindingAnnotation::{NONE, REF, MUT, REF_MUT}`

One goal is to make it more clear that `BindingAnnotation` merely represents syntax `ref mut` and not the actual binding mode. This was especially confusing since we had `ast::BindingMode`->`hir::BindingAnnotation`->`thir::BindingMode`.

I wish there were more symmetry between `ByRef` and `Mutability` (variant) naming (maybe `Mutable::Yes`?), and I also don't love how long the name `BindingAnnotation` is, but this seems like the best compromise. Ideas welcome.
2022-09-06 03:16:29 +00:00
Chayim Refael Friedman
fbf11cfc13 Recover from using ; as separator between fields 2022-09-05 19:15:23 +00:00
Jhonny Bill Mena
321e60bf34 UPDATE - into_diagnostic to take a Handler instead of a ParseSess
Suggested by the team in this Zulip Topic https://rust-lang.zulipchat.com/#narrow/stream/336883-i18n/topic/.23100717.20SessionDiagnostic.20on.20Handler

Handler already has almost all the capabilities of ParseSess when it comes to diagnostic emission, in this migration we only needed to add the ability to access source_map from the emitter in order to get a Snippet and the start_point. Not sure if this is the best way to address this gap
2022-09-05 02:18:45 -04:00
Matthias Krüger
57198b549f remove redundant clones 2022-09-03 07:58:41 +02:00
Michael Goulet
91674cc56c Suggest removing unnecessary prefix let in patterns 2022-09-03 05:39:46 +00:00
Cameron Steffen
02ba216e3c Refactor and re-use BindingAnnotation 2022-09-02 12:55:05 -05:00
Oli Scherer
ee3c835018 Always import all tracing macros for the entire crate instead of piecemeal by module 2022-09-01 14:54:27 +00:00
bors
eac6c33bc6 Auto merge of #100869 - nnethercote:replace-ThinVec, r=spastorino
Replace `rustc_data_structures::thin_vec::ThinVec` with `thin_vec::ThinVec`

`rustc_data_structures::thin_vec::ThinVec` looks like this:
```
pub struct ThinVec<T>(Option<Box<Vec<T>>>);
```
It's just a zero word if the vector is empty, but requires two
allocations if it is non-empty. So it's only usable in cases where the
vector is empty most of the time.

This commit removes it in favour of `thin_vec::ThinVec`, which is also
word-sized, but stores the length and capacity in the same allocation as
the elements. It's good in a wider variety of situation, e.g. in enum
variants where the vector is usually/always non-empty.

The commit also:
- Sorts some `Cargo.toml` dependency lists, to make additions easier.
- Sorts some `use` item lists, to make additions easier.
- Changes `clean_trait_ref_with_bindings` to take a
  `ThinVec<TypeBinding>` rather than a `&[TypeBinding]`, because this
  avoid some unnecessary allocations.

r? `@spastorino`
2022-09-01 08:01:06 +00:00
Dezhi Wu
b1430fb7ca Fix a bunch of typo
This PR will fix some typos detected by [typos].

I only picked the ones I was sure were spelling errors to fix, mostly in
the comments.

[typos]: https://github.com/crate-ci/typos
2022-08-31 18:24:55 +08:00
Nilstrieb
d1ef8180f9 Revert let_chains stabilization
This reverts commit 3266460749.

This is the revert against master, the beta revert was already done in #100538.
2022-08-29 19:34:11 +02:00
Nicholas Nethercote
c768617f6f Improve parse_dot_or_call_expr_with.
Avoid all the extra work in the very common case where `attrs` is empty.
2022-08-29 15:42:16 +10:00
Nicholas Nethercote
b38106b6d8 Replace rustc_data_structures::thin_vec::ThinVec with thin_vec::ThinVec.
`rustc_data_structures::thin_vec::ThinVec` looks like this:
```
pub struct ThinVec<T>(Option<Box<Vec<T>>>);
```
It's just a zero word if the vector is empty, but requires two
allocations if it is non-empty. So it's only usable in cases where the
vector is empty most of the time.

This commit removes it in favour of `thin_vec::ThinVec`, which is also
word-sized, but stores the length and capacity in the same allocation as
the elements. It's good in a wider variety of situation, e.g. in enum
variants where the vector is usually/always non-empty.

The commit also:
- Sorts some `Cargo.toml` dependency lists, to make additions easier.
- Sorts some `use` item lists, to make additions easier.
- Changes `clean_trait_ref_with_bindings` to take a
  `ThinVec<TypeBinding>` rather than a `&[TypeBinding]`, because this
  avoid some unnecessary allocations.
2022-08-29 15:42:13 +10:00
bors
ce36e88256 Auto merge of #100497 - kadiwa4:remove_clone_into_iter, r=cjgillot
Avoid cloning a collection only to iterate over it

`@rustbot` label: +C-cleanup
2022-08-28 18:31:08 +00:00
Yuki Okushi
ed8cfc86a2
Rollup merge of #100188 - chenyukang:fix-issue-100165, r=estebank
Parser will not suggest invalid expression when use public

Fixes #100165
2022-08-25 08:50:56 +09:00
Yuki Okushi
f4550a6edf
Rollup merge of #99332 - jyn514:stabilize-label-break-value, r=petrochenkov
Stabilize `#![feature(label_break_value)]`

See the stabilization report in https://github.com/rust-lang/rust/issues/48594#issuecomment-1186213313.
2022-08-25 08:50:54 +09:00
Joshua Nelson
31e39446ec Stabilize #![feature(label_break_value)]
# Stabilization proposal

The feature was implemented in https://github.com/rust-lang/rust/pull/50045 by est31 and has been in nightly since 2018-05-16 (over 4 years now).
There are [no open issues][issue-label] other than the tracking issue. There is a strong consensus that `break` is the right keyword and we should not use `return`.

There have been several concerns raised about this feature on the tracking issue (other than the one about tests, which has been fixed, and an interaction with try blocks, which has been fixed).
1. nrc's original comment about cost-benefit analysis: https://github.com/rust-lang/rust/issues/48594#issuecomment-422235234
2. joshtriplett's comments about seeing use cases: https://github.com/rust-lang/rust/issues/48594#issuecomment-422281176
3. withoutboats's comments that Rust does not need more control flow constructs: https://github.com/rust-lang/rust/issues/48594#issuecomment-450050630

Many different examples of code that's simpler using this feature have been provided:
- A lexer by rpjohnst which must repeat code without label-break-value: https://github.com/rust-lang/rust/issues/48594#issuecomment-422502014
- A snippet by SergioBenitez which avoids using a new function and adding several new return points to a function: https://github.com/rust-lang/rust/issues/48594#issuecomment-427628251. This particular case would also work if `try` blocks were stabilized (at the cost of making the code harder to optimize).
- Several examples by JohnBSmith: https://github.com/rust-lang/rust/issues/48594#issuecomment-434651395
- Several examples by Centril: https://github.com/rust-lang/rust/issues/48594#issuecomment-440154733
- An example by petrochenkov where this is used in the compiler itself to avoid duplicating error checking code: https://github.com/rust-lang/rust/issues/48594#issuecomment-443557569
- Amanieu recently provided another example related to complex conditions, where try blocks would not have helped: https://github.com/rust-lang/rust/issues/48594#issuecomment-1184213006

Additionally, petrochenkov notes that this is strictly more powerful than labelled loops due to macros which accidentally exit a loop instead of being consumed by the macro matchers: https://github.com/rust-lang/rust/issues/48594#issuecomment-450246249

nrc later resolved their concern, mostly because of the aforementioned macro problems.
joshtriplett suggested that macros could be able to generate IR directly
(https://github.com/rust-lang/rust/issues/48594#issuecomment-451685983) but there are no open RFCs,
and the design space seems rather speculative.

joshtriplett later resolved his concerns, due to a symmetry between this feature and existing labelled break: https://github.com/rust-lang/rust/issues/48594#issuecomment-632960804

withoutboats has regrettably left the language team.

joshtriplett later posted that the lang team would consider starting an FCP given a stabilization report: https://github.com/rust-lang/rust/issues/48594#issuecomment-1111269353

[issue-label]: https://github.com/rust-lang/rust/issues?q=is%3Aissue+is%3Aopen+label%3AF-label_break_value+

 ## Report

+ Feature gate:
    - d695a497bb/src/test/ui/feature-gates/feature-gate-label_break_value.rs
+ Diagnostics:
    - 6b2d3d5f3c/compiler/rustc_parse/src/parser/diagnostics.rs (L2629)
    - f65bf0b2bb/compiler/rustc_resolve/src/diagnostics.rs (L749)
    - f65bf0b2bb/compiler/rustc_resolve/src/diagnostics.rs (L1001)
    - 111df9e6ed/compiler/rustc_passes/src/loops.rs (L254)
    - d695a497bb/compiler/rustc_parse/src/parser/expr.rs (L2079)
    - d695a497bb/compiler/rustc_parse/src/parser/expr.rs (L1569)
+ Tests:
    - https://github.com/rust-lang/rust/blob/master/src/test/ui/label/label_break_value_continue.rs
    - https://github.com/rust-lang/rust/blob/master/src/test/ui/label/label_break_value_unlabeled_break.rs
    - https://github.com/rust-lang/rust/blob/master/src/test/ui/label/label_break_value_illegal_uses.rs
    - https://github.com/rust-lang/rust/blob/master/src/test/ui/lint/unused_labels.rs
    - https://github.com/rust-lang/rust/blob/master/src/test/ui/run-pass/for-loop-while/label_break_value.rs

 ## Interactions with other features

Labels follow the hygiene of local variables.

label-break-value is permitted within `try` blocks:
```rust
let _: Result<(), ()> = try {
    'foo: {
        Err(())?;
        break 'foo;
    }
};
```

label-break-value is disallowed within closures, generators, and async blocks:
```rust
'a: {
    || break 'a
    //~^ ERROR use of unreachable label `'a`
    //~| ERROR `break` inside of a closure
}
```

label-break-value is disallowed on [_BlockExpression_]; it can only occur as a [_LoopExpression_]:
```rust
fn labeled_match() {
    match false 'b: { //~ ERROR block label not supported here
        _ => {}
    }
}

macro_rules! m {
    ($b:block) => {
        'lab: $b; //~ ERROR cannot use a `block` macro fragment here
        unsafe $b; //~ ERROR cannot use a `block` macro fragment here
        |x: u8| -> () $b; //~ ERROR cannot use a `block` macro fragment here
    }
}

fn foo() {
    m!({});
}
```

[_BlockExpression_]: https://doc.rust-lang.org/nightly/reference/expressions/block-expr.html
[_LoopExpression_]: https://doc.rust-lang.org/nightly/reference/expressions/loop-expr.html
2022-08-23 21:14:12 -05:00
Dylan DPC
28ead17745
Rollup merge of #100909 - nnethercote:minor-ast-LitKind-improvement, r=petrochenkov
Minor `ast::LitKind` improvements

r? `@petrochenkov`
2022-08-23 20:40:09 +05:30
yukang
351acc87f5 parser will not give wrong help message for 'public' 2022-08-23 17:02:40 +08:00
Nicholas Nethercote
6087dc2054 Remove the symbol from ast::LitKind::Err.
Because it's never used meaningfully.
2022-08-23 16:56:24 +10:00
Matthias Krüger
54d0f50677
Rollup merge of #100565 - TaKO8Ki:suggest-adding-missing-semicolon-before-item, r=compiler-errors
Suggest adding a missing semicolon before an item

fixes #100533
2022-08-23 06:55:24 +02:00
Dylan DPC
75b7089d1e
Rollup merge of #100713 - Xiretza:parser-expr-session-diagnostics, r=estebank
Convert diagnostics in parser/expr to SessionDiagnostic

This migrates all the easy cases in `rustc_parse::parser::expr` to `SessionDiagnostic`s, I've left things such as `multipart_suggestion`s out for now in the hopes of a derive API being developed soon.
2022-08-22 20:34:14 +05:30
Dylan DPC
3842117ef2
Rollup merge of #99915 - WaffleLapkin:recover_keyword_bounds, r=compiler-errors
Recover keywords in trait bounds

(_this pr was inspired by [this tweet](https://twitter.com/Azumanga/status/1552982326409367561)_)

Recover keywords in trait bound, motivational example:
```rust
fn f(_: impl fn()) {} // mistyped, meant `Fn`
```

<details><summary>Current nightly (3 needless and confusing errors!)</summary>
<p>

```text
error: expected identifier, found keyword `fn`
 --> ./t.rs:1:15
  |
1 | fn _f(_: impl fn()) {}
  |               ^^ expected identifier, found keyword
  |
help: escape `fn` to use it as an identifier
  |
1 | fn _f(_: impl r#fn()) {}
  |               ++

error: expected one of `:` or `|`, found `)`
 --> ./t.rs:1:19
  |
1 | fn _f(_: impl fn()) {}
  |                   ^ expected one of `:` or `|`

error: expected one of `!`, `(`, `)`, `,`, `?`, `for`, `~`, lifetime, or path, found keyword `fn`
 --> ./t.rs:1:15
  |
1 | fn _f(_: impl fn()) {}
  |              -^^ expected one of 9 possible tokens
  |              |
  |              help: missing `,`

error: at least one trait must be specified
 --> ./t.rs:1:10
  |
1 | fn _f(_: impl fn()) {}
  |          ^^^^
```

</p>
</details>

This PR:
```text
error: expected identifier, found keyword `fn`
 --> ./t.rs:1:15
  |
1 | fn _f(_: impl fn()) {}
  |               ^^ expected identifier, found keyword
  |
help: escape `fn` to use it as an identifier
  |
1 | fn _f(_: impl r#fn()) {}
  |               ++

error[E0405]: cannot find trait `r#fn` in this scope
  --> ./t.rs:1:15
   |
1  | fn _f(_: impl fn()) {}
   |               ^^ help: a trait with a similar name exists (notice the capitalization): `Fn`
   |
  ::: /home/waffle/projects/repos/rust/library/core/src/ops/function.rs:74:1
   |
74 | pub trait Fn<Args>: FnMut<Args> {
   | ------------------------------- similarly named trait `Fn` defined here
```

It would be nice to have suggestion in the first error like "have you meant `Fn` trait", instead of a separate error, but the recovery is deep inside ident parsing, which makes it a lot harder to do.

r? `@compiler-errors`
2022-08-22 11:45:42 +05:30
Nicholas Nethercote
619b8abaa6 Use AttrVec in more places.
In some places we use `Vec<Attribute>` and some places we use
`ThinVec<Attribute>` (a.k.a. `AttrVec`). This results in various points
where we have to convert between `Vec` and `ThinVec`.

This commit changes the places that use `Vec<Attribute>` to use
`AttrVec`. A lot of this is mechanical and boring, but there are
some interesting parts:
- It adds a few new methods to `ThinVec`.
- It implements `MapInPlace` for `ThinVec`, and introduces a macro to
  avoid the repetition of this trait for `Vec`, `SmallVec`, and
  `ThinVec`.

Overall, it makes the code a little nicer, and has little effect on
performance. But it is a precursor to removing
`rustc_data_structures::thin_vec::ThinVec` and replacing it with
`thin_vec::ThinVec`, which is implemented more efficiently.
2022-08-22 07:35:33 +10:00
Xiretza
ffcaa0dee2 Migrate diagnostics in parser/expr to SessionDiagnostic 2022-08-21 14:54:05 +02:00
Maybe Waffle
5d5e451618 recover const Tr bounds (no ~) 2022-08-21 14:58:42 +04:00
Xiretza
7f3a6fd7f6 Replace #[lint/warning/error] with #[diag] 2022-08-21 09:17:43 +02:00
bors
dd01122b5c Auto merge of #100564 - nnethercote:box-ast-MacCall, r=spastorino
Box the `MacCall` in various types.

r? `@spastorino`
2022-08-20 10:26:54 +00:00
Matthias Krüger
af89769c82
Rollup merge of #100750 - akabinds:akabinds/improved-invalid-function-qual-error, r=davidtwco
improved diagnostic for function defined with `def`, `fun`, `func`, or `function` instead of `fn`

Closes #99751
2022-08-20 07:09:05 +02:00
Matthias Krüger
eacbe5437e
Rollup merge of #100667 - Xiretza:diag-structs-parser-ivd, r=davidtwco
Migrate "invalid variable declaration" errors to SessionDiagnostic

After seeing the great blog post on Inside Rust, I decided to try my hand at this. Just one diagnostic for now to get used to the workflow and to check if this is the way to do it or if there are any problems.
2022-08-20 07:09:01 +02:00
akabinds
1b54ad0585 added improved diagnostic for a function defined with an invalid qualifier 2022-08-18 16:14:04 -05:00
Matthias Krüger
5548e585c1
Rollup merge of #100670 - Xiretza:parser-stmt-force-collect-docs, r=davidtwco
Fix documentation of rustc_parse::parser::Parser::parse_stmt_without_recovery

Something seems to have gotten out of sync during the creation of #81177, where both the argument and comment were introduced.
2022-08-18 05:10:49 +02:00
Xiretza
e8499cfadc Migrate "invalid variable declaration" errors to SessionDiagnostic 2022-08-17 19:08:37 +02:00
Matthias Krüger
d5dca26a94
Rollup merge of #100018 - nnethercote:clean-up-LitKind, r=petrochenkov
Clean up `LitKind`

r? ``@petrochenkov``
2022-08-17 12:32:49 +02:00
Xiretza
d3bf103d1b Fix documentation of rustc_parse::parser::Parser::parse_stmt_without_recovery
Something seems to have gotten out of sync during the creation of #81177,
where both the argument and comment were introduced.
2022-08-17 11:18:48 +02:00
Nicholas Nethercote
eafd0dfd05 Box the MacCall in various types. 2022-08-17 08:10:56 +10:00
Nicholas Nethercote
5d3cc1713a Rename some things related to literals.
- Rename `ast::Lit::token` as `ast::Lit::token_lit`, because its type is
  `token::Lit`, which is not a token. (This has been confusing me for a
  long time.)
  reasonable because we have an `ast::token::Lit` inside an `ast::Lit`.
- Rename `LitKind::{from,to}_lit_token` as
  `LitKind::{from,to}_token_lit`, to match the above change and
  `token::Lit`.
2022-08-16 13:41:34 +10:00
Nicholas Nethercote
9619a2e3a3 Avoid unnecessary cloning in Parser::get_ident_from_generic_arg. 2022-08-16 12:14:52 +10:00
Nicholas Nethercote
3e04fed6fa Remove {ast,hir}::WhereEqPredicate::id.
These fields are unused.
2022-08-16 12:13:23 +10:00
Matthias Krüger
e14d12cb66
Rollup merge of #100559 - nnethercote:parser-simplifications, r=compiler-errors
Parser simplifications

Best reviewed one commit at a time.

r? ``@compiler-errors``
2022-08-15 20:11:38 +02:00
Matthias Krüger
e369ec871e
Rollup merge of #100458 - compiler-errors:fn-argument-span, r=estebank
Adjust span of fn argument declaration

Span of a fn argument declaration goes from:

```
fn foo(i : i32 , ...)
       ^^^^^^^^
```

to:

```
fn foo(i : i32 , ...)
       ^^^^^^^
```

That is, we don't include the extra spacing up to the trailing comma, which I think is more correct.

cc https://github.com/rust-lang/rust/pull/99646#discussion_r944568074
r? ``@estebank``

---

The two tests that had dramatic changes in their rendering I think actually are improved, though they are kinda poor spans both before and after the changes. 🤷 Thoughts?
2022-08-15 20:11:35 +02:00
Matthias Krüger
fece51174b
Rollup merge of #100566 - TaKO8Ki:use-create-snapshot-for-diagnostic, r=cjgillot
Use `create_snapshot_for_diagnostic` instead of `clone` for `Parser`

follow-up to #98020
2022-08-15 10:28:14 +02:00
Matthias Krüger
748925bf1b
Rollup merge of #100534 - Rageking8:Rageking8-refactor1, r=compiler-errors
Make code slightly more uniform
2022-08-15 10:28:13 +02:00
Takayuki Maeda
84f0d5e460 use create_snapshot_for_diagnostic instead of clone for Parser 2022-08-15 16:42:58 +09:00
Takayuki Maeda
40dcf89a26 suggest adding a missing semicolon before an item 2022-08-15 16:10:31 +09:00
Nicholas Nethercote
2ef0479568 Simplify attribute handling in parse_bottom_expr.
`Parser::parse_bottom_expr` currently constructs an empty `attrs` and
then passes it to a large number of other functions. This makes the code
harder to read than it should be, because it's not clear that many
`attrs` arguments are always empty.

This commit removes `attrs` and the passing, simplifying a lot of
functions. The commit also renames `Parser::mk_expr` (which takes an
`attrs` argument) as `mk_expr_with_attrs`, and introduces a new
`mk_expr` which creates an expression with no attributes, which is the
more common case.
2022-08-15 13:29:28 +10:00
Nicholas Nethercote
1e8497351d Streamline parse_path_start_expr.
Let-chaining avoids some code duplication.
2022-08-15 09:51:11 +10:00
Matthias Krüger
13b8b6ede0
Rollup merge of #100253 - obeis:issue-100197, r=cjgillot
Recover from mutable variable declaration where `mut` is placed before `let`

Closes #100197
2022-08-14 20:16:00 +02:00
Rageking8
44f878d75f
Make code slightly more uniform 2022-08-14 22:17:49 +08:00
Dylan DPC
7473484d52
Rollup merge of #100115 - obeis:issue-99910, r=cjgillot
Suggest removing `let` if `const let` or `let const` is used

Closes #99910
2022-08-14 17:09:15 +05:30
Michael Goulet
86e1d1e28f
Rollup merge of #100446 - TaKO8Ki:suggest-removing-semicolon-after-impl-trait-items, r=compiler-errors
Suggest removing a semicolon after impl/trait items

fixes #99822
2022-08-13 21:06:51 -07:00
Michael Goulet
2af344595a
Rollup merge of #99646 - compiler-errors:arg-mismatch-single-arg-label, r=estebank
Only point out a single function parameter if we have a single arg incompatibility

Fixes #99635
2022-08-13 21:06:46 -07:00
Michael Goulet
29f905bfaf
Rollup merge of #100475 - chenyukang:fix-100461, r=fee1-dead
Give a helpful diagnostic when the next struct field has an attribute

Fixes #100461
2022-08-13 14:10:12 -07:00
KaDiWa
4eebcb9910
avoid cloning and then iterating 2022-08-13 16:16:52 +02:00
Takayuki Maeda
d47df26784 use span_suggestion instead of span_suggestion_verbose 2022-08-13 22:10:54 +09:00
yukang
52a15180d2 give a helpful diagnostic even when the next struct field has an attribute 2022-08-13 12:50:53 +08:00
Mark Rousskov
154a09dd91 Adjust cfgs 2022-08-12 16:28:15 -04:00
Michael Goulet
9b0edd099d Adjust span of fn arguments 2022-08-12 15:21:39 +00:00
Michael Goulet
237cbe91a8 Adjust span of closure param 2022-08-12 15:18:40 +00:00
Dylan DPC
9914c96f06
Rollup merge of #100396 - chenyukang:fix-100394, r=petrochenkov
Suggest const and static for global variable

Fixing #100394
2022-08-12 20:39:16 +05:30
Takayuki Maeda
48c0341a70 suggest removing a semicolon after impl/trait items 2022-08-12 18:11:01 +09:00
Matthias Krüger
6ae0414122
Rollup merge of #100350 - jhpratt:stringify-vis, r=cjgillot
Stringify non-shorthand visibility correctly

This makes `stringify!(pub(in crate))` evaluate to `pub(in crate)` rather than `pub(crate)`, matching the behavior before the `crate` shorthand was removed. Further, this changes `stringify!(pub(in super))` to evaluate to `pub(in super)` rather than the current `pub(super)`. If the latter is not desired (it is _technically_ breaking), it can be undone.

Fixes #99981

`@rustbot` label +C-bug +regression-from-stable-to-beta +T-compiler
2022-08-11 22:53:06 +02:00
Dylan DPC
b5f5bdce87
Rollup merge of #100351 - compiler-errors:diagnostic-convention, r=fee1-dead
Use `&mut Diagnostic` instead of `&mut DiagnosticBuilder` unless needed

This seems to be the established convention (02ff9e0) when `DiagnosticBuilder` was first added. I am guilty of introducing some of these.
2022-08-11 22:47:03 +05:30
chenyukang
98518c2379 suggest const or static for global variable 2022-08-11 23:15:39 +08:00
Camille GILLOT
9701845287 Do not consider method call receiver as an argument in AST. 2022-08-10 18:34:54 +02:00
Michael Goulet
a2b6744af0 Use &mut Diagnostic instead of &mut DiagnosticBuilder unless needed 2022-08-10 03:45:42 +00:00
Jacob Pratt
be5672ecb2
Stringify non-shorthand visibility correctly 2022-08-09 23:31:45 -04:00
Takayuki Maeda
6d85bb9535 suggest a missing semicolon before an array 2022-08-10 02:29:28 +09:00
Obei Sideg
ea2df3a798 Recover from mutable variable declaration where mut is placed before let 2022-08-09 00:55:37 +03:00
Matthias Krüger
18ddb41184
Rollup merge of #100167 - chenyukang:require-suggestion, r=estebank
Recover `require`, `include` instead of `use` in item

Fix #100140
2022-08-06 16:15:59 +02:00
Dylan DPC
e7ed8443ea
Rollup merge of #100168 - WaffleLapkin:improve_diagnostics_for_missing_type_in_a_const_item, r=compiler-errors
Improve diagnostics for `const a: = expr;`

Adds a suggestion to write a type when there is a colon, but the type is not present.
I've also shrunk spans a little, so the suggestions are a little nicer.

Resolves #100146

r? `@compiler-errors`
2022-08-05 21:54:37 +05:30
Maybe Waffle
743ad07c4b Improve diagnostics for const a: = expr; 2022-08-05 16:19:28 +04:00
yukang
2b15fc6d9a recover require,include instead of use in item 2022-08-05 19:20:03 +08:00
Matthias Krüger
f6ea143f93
Rollup merge of #98796 - compiler-errors:no-semi-if-comma, r=estebank
Do not exclusively suggest `;` when `,` is also a choice

Fixes #96791
2022-08-04 22:24:59 +02:00
Obei Sideg
accb8e34c5 Suggest removing let if let const is used 2022-08-04 01:23:14 +03:00
Matthias Krüger
9c18fdc71f
Rollup merge of #99786 - obeis:issue-99625, r=compiler-errors
Recover from C++ style `enum struct`

Closes #99625
2022-08-03 22:29:29 +02:00
Obei Sideg
2af92bbf2e Suggest removing let if const let is used 2022-08-03 18:43:29 +03:00
Matthias Krüger
beb4cdddde
Rollup merge of #100011 - compiler-errors:let-chain-restriction, r=fee1-dead
Use Parser's `restrictions` instead of `let_expr_allowed`

This also means that the `ALLOW_LET` flag is reset properly for subexpressions, so we can properly deny things like `a && (b && let c = d)`. Also the parser is a tiny bit smaller now.

It doesn't reject _all_ bad `let` expr usages, just a bit more.

cc `@c410-f3r`
2022-08-02 07:30:44 +02:00
Michael Goulet
6be7a87f9c Use expr parse restrictions for let expr parsing 2022-08-01 01:13:16 +00:00
Nicholas Nethercote
99f5c79d64 Shrink Token.
From 72 bytes to 12 bytes (on x86-64).

There are two parts to this:
- Changing various source code offsets from 64-bit to 32-bit. This is
  not a problem because the rest of rustc also uses 32-bit source code
  offsets. This means `Token` is no longer `Copy` but this causes no
  problems.
- Removing the `RawStrError` from `LiteralKind`. Raw string literal
  invalidity is now indicated by a `None` value within
  `RawStr`/`RawByteStr`, and the new `validate_raw_str` function can be
  used to re-lex an invalid raw string literal to get the `RawStrError`.

There is one very small change in behaviour. Previously, if a raw string
literal matched both the `InvalidStarter` and `TooManyHashes` cases,
the latter would override the former. This has now changed, because
`raw_double_quoted_string` now uses `?` and so returns immediately upon
detecting the `InvalidStarter` case. I think this is a slight
improvement to report the earlier-detected error, and it explains the
change in the `test_too_many_hashes` test.

The commit also removes a couple of comments that refer to #77629 and
say that the size of these types don't affect performance. These
comments are wrong, though the performance effect is small.
2022-08-01 08:53:04 +10:00
Nicholas Nethercote
e6b9fccfb1 Add a size assertion for Token. 2022-08-01 08:27:43 +10:00
Nicholas Nethercote
ddf62b5bd4 Inline TokenStreamBuilder::push.
Because it's small and hot.
2022-08-01 08:27:41 +10:00
Nicholas Nethercote
c01a36d5e4 Avoid an unnecessary return. 2022-08-01 08:25:56 +10:00
Nicholas Nethercote
bd23d68b41 Remove StringReader::end_src_index.
It not needed, always being set to the end of the text.
2022-08-01 08:11:15 +10:00
Nicholas Nethercote
55185992d6 Improve shebang handling.
Avoid doing stuff until it's necessary.
2022-08-01 08:11:15 +10:00
bors
038f9e6bef Auto merge of #99948 - Dylan-DPC:rollup-ed5136t, r=Dylan-DPC
Rollup of 5 pull requests

Successful merges:

 - #99311 (change maybe_body_owned_by to take local def id)
 - #99862 (Improve type mismatch w/ function signatures)
 - #99895 (don't call type ascription "cast")
 - #99900 (remove some manual hash stable impls)
 - #99903 (Add diagnostic when using public instead of pub)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-07-30 17:30:50 +00:00
Dylan DPC
df2cf97830
Rollup merge of #99903 - gimbles:pub, r=davidtwco
Add diagnostic when using public instead of pub

Forwarding from https://github.com/rust-lang/rust/pull/99706

I accidentally broke something(??) in git and the commits in that PR are absolutely not what I did in that branch

Anyways, this is the PR for this now. Adding tests again in a minute.

cc `@davidtwco`
2022-07-30 20:39:50 +05:30
bors
1202bbaf48 Auto merge of #99887 - nnethercote:rm-TreeAndSpacing, r=petrochenkov
Remove `TreeAndSpacing`.

A `TokenStream` contains a `Lrc<Vec<(TokenTree, Spacing)>>`. But this is
not quite right. `Spacing` makes sense for `TokenTree::Token`, but does
not make sense for `TokenTree::Delimited`, because a
`TokenTree::Delimited` cannot be joined with another `TokenTree`.

This commit fixes this problem, by adding `Spacing` to `TokenTree::Token`,
changing `TokenStream` to contain a `Lrc<Vec<TokenTree>>`, and removing the
`TreeAndSpacing` typedef.

The commit removes these two impls:
- `impl From<TokenTree> for TokenStream`
- `impl From<TokenTree> for TreeAndSpacing`

These were useful, but also resulted in code with many `.into()` calls
that was hard to read, particularly for anyone not highly familiar with
the relevant types. This commit makes some other changes to compensate:
- `TokenTree::token()` becomes `TokenTree::token_{alone,joint}()`.
- `TokenStream::token_{alone,joint}()` are added.
- `TokenStream::delimited` is added.

This results in things like this:
```rust
TokenTree::token(token::Semi, stmt.span).into()
```
changing to this:
```rust
TokenStream::token_alone(token::Semi, stmt.span)
```
This makes the type of the result, and its spacing, clearer.

These changes also simplifies `Cursor` and `CursorRef`, because they no longer
need to distinguish between `next` and `next_with_spacing`.

r? `@petrochenkov`
2022-07-30 14:50:05 +00:00
Maybe Waffle
c6558c0bc7 Recover keywords in bounds
For example, this fixes a error for `impl fn()` (notice the capitalization)
2022-07-29 21:43:35 +04:00