Commit Graph

2128 Commits

Author SHA1 Message Date
Oli Scherer
8d290058c9 Always pass the visitor as the first argument to walk* functions 2024-07-22 14:01:24 +00:00
Oli Scherer
754bdef793 Sync mut_visit function names with immut visit ones (s/noop_visit/walk/) 2024-07-22 14:01:24 +00:00
bors
3811f40d27 Auto merge of #127957 - matthiaskrgr:rollup-1u5ivck, r=matthiaskrgr
Rollup of 6 pull requests

Successful merges:

 - #127350 (Parser: Suggest Placing the Return Type After Function Parameters)
 - #127621 (Rewrite and rename `issue-22131` and `issue-26006` `run-make` tests to rmake)
 - #127662 (When finding item gated behind a `cfg` flag, point at it)
 - #127903 (`force_collect` improvements)
 - #127932 (rustdoc: fix `current` class on sidebar modnav)
 - #127943 (Don't allow unsafe statics outside of extern blocks)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-07-19 13:39:12 +00:00
Matthias Krüger
9ada89d9a1
Rollup merge of #127903 - nnethercote:force_collect-improvements, r=petrochenkov
`force_collect` improvements

Yet more cleanups relating to `cfg_attr` processing.

r? ````@petrochenkov````
2024-07-19 10:48:05 +02:00
Matthias Krüger
c86e13f330
Rollup merge of #127350 - veera-sivarajan:bugfix-126311, r=lcnr
Parser: Suggest Placing the Return Type After Function Parameters

Fixes #126311

This PR suggests placing the return type after the function parameters when it's misplaced after a `where` clause.

This also tangentially improves diagnostics for cases like [this](86d6f1312a/tests/ui/parser/issues/misplaced-return-type-without-where-issue-126311.rs (L1C1-L1C28)) and adds doc comments for `parser::AllowPlus`.
2024-07-19 10:48:03 +02:00
Nicholas Nethercote
1dd566a6d0 Overhaul comments in collect_tokens_trailing_token.
Adding details, clarifying lots of little things, etc. In particular,
the commit adds details of an example. I find this very helpful, because
it's taken me a long time to understand how this code works.
2024-07-19 15:25:55 +10:00
Nicholas Nethercote
ca6649516f Make Parser::num_bump_calls 0-indexed.
Currently in `collect_tokens_trailing_token`, `start_pos` and `end_pos`
are 1-indexed by `replace_ranges` is 0-indexed, which is really
confusing. Making them both 0-indexed makes debugging much easier.
2024-07-19 15:25:55 +10:00
Nicholas Nethercote
f9c7ca70cb Move inner_attr code downwards.
This puts it just before the `replace_ranges` initialization, which
makes sense because the two variables are closely related.
2024-07-19 15:25:54 +10:00
Nicholas Nethercote
1f67cf9e63 Remove final_attrs local variable.
It's no shorter than `ret.attrs()`, and `ret.attrs()` is used multiple
times earlier in the function.
2024-07-19 15:25:54 +10:00
Nicholas Nethercote
757f73f506 Simplify CaptureState::inner_attr_ranges.
The `Option`s within the `ReplaceRange`s within the hashmap are always
`None`. This PR omits them and inserts them when they are extracted from
the hashmap.
2024-07-19 15:25:54 +10:00
Nicholas Nethercote
4158a1c48f Only check force_collect in collect_tokens_trailing_token.
There are three places where we currently check `force_collect` and call
`collect_tokens_no_attrs` for `ForceCollect::Yes` and a vanilla parsing
function for `ForceCollect::No`.

But we can instead just pass in `force_collect` and let
`collect_tokens_trailing_token` do the appropriate thing.
2024-07-19 08:42:33 +10:00
Nicholas Nethercote
9d908a2877 Use ForceCollect in parse_attr_item.
Instead of a `bool`. Because `ForceCollect` is used in this way
everywhere else.
2024-07-19 08:24:54 +10:00
Nicholas Nethercote
7d7e2a173a Don't always force collect tokens in recover_stmt_local_after_let.
Use a parameter to decide whether to force collect, as is done for the
closely related `parse_local_mk` method.
2024-07-19 08:24:53 +10:00
Nicholas Nethercote
e69ff1c106 Remove an unnecessary ForceCollect::Yes.
No need to collect tokens on this recovery path, because the parsed
statement isn't even looked at.
2024-07-19 08:20:57 +10:00
Veera
4cad705017 Parser: Suggest Placing the Return Type After Function Parameters 2024-07-18 17:56:34 -04:00
Matthias Krüger
50a90e394e
Rollup merge of #127835 - estebank:issue-127823, r=compiler-errors
Fix ICE in suggestion caused by `⩵` being recovered as `==`

The second suggestion shown here would previously incorrectly assume that the span corresponding to `⩵` was 2 bytes wide composed by 2 1 byte wide chars, so a span pointing at `==` could point only at one of the `=` to remove it. Instead, we now replace the whole thing (as we should have the whole time):

```
error: unknown start of token: \u{2a75}
  --> $DIR/unicode-double-equals-recovery.rs:1:16
   |
LL | const A: usize ⩵ 2;
   |                ^
   |
help: Unicode character '⩵' (Two Consecutive Equals Signs) looks like '==' (Double Equals Sign), but it is not
   |
LL | const A: usize == 2;
   |                ~~

error: unexpected `==`
  --> $DIR/unicode-double-equals-recovery.rs:1:16
   |
LL | const A: usize ⩵ 2;
   |                ^
   |
help: try using `=` instead
   |
LL | const A: usize = 2;
   |                ~
```

Fix #127823.
2024-07-18 23:05:21 +02:00
Esteban Küber
67ec1326ee Fix ICE in suggestion caused by being recovered as ==
The second suggestion shown here would previously incorrectly assume that the span corresponding to `⩵` was 2 bytes wide composed by 2 1 byte wide chars, so a span pointing at `==` could point only at one of the `=` to remove it. Instead, we now replace the whole thing (as we should have the whole time):

```
error: unknown start of token: \u{2a75}
  --> $DIR/unicode-double-equals-recovery.rs:1:16
   |
LL | const A: usize ⩵ 2;
   |                ^
   |
help: Unicode character '⩵' (Two Consecutive Equals Signs) looks like '==' (Double Equals Sign), but it is not
   |
LL | const A: usize == 2;
   |                ~~

error: unexpected `==`
  --> $DIR/unicode-double-equals-recovery.rs:1:16
   |
LL | const A: usize ⩵ 2;
   |                ^
   |
help: try using `=` instead
   |
LL | const A: usize = 2;
   |                ~
```
2024-07-18 17:47:31 +00:00
Trevor Gross
e2e0681e3a
Rollup merge of #127842 - nnethercote:rm-TrailingToken, r=petrochenkov
Remove `TrailingToken`.

It's used in `Parser::collect_tokens_trailing_token` to decide whether to capture a trailing token. But the callers actually know whether to capture a trailing token, so it's simpler for them to just pass in a bool.

Also, the `TrailingToken::Gt` case was weird, because it didn't result in a trailing token being captured. It could have been subsumed by the `TrailingToken::MaybeComma` case, and it effectively is in the new code.

r? `@petrochenkov`
2024-07-18 05:14:07 -05:00
Nicholas Nethercote
487802d6c8 Remove TrailingToken.
It's used in `Parser::collect_tokens_trailing_token` to decide whether
to capture a trailing token. But the callers actually know whether to
capture a trailing token, so it's simpler for them to just pass in a
bool.

Also, the `TrailingToken::Gt` case was weird, because it didn't result
in a trailing token being captured. It could have been subsumed by the
`TrailingToken::MaybeComma` case, and it effectively is in the new code.
2024-07-18 17:28:49 +10:00
Matthias Krüger
77e5bbf341
Rollup merge of #127889 - estebank:anon-arg-sugg, r=compiler-errors
More accurate span for anonymous argument suggestion

Use smaller span for suggesting adding `_:` ahead of a type:

```
error: expected one of `(`, `...`, `..=`, `..`, `::`, `:`, `{`, or `|`, found `)`
  --> $DIR/anon-params-denied-2018.rs:12:47
   |
LL |     fn foo_with_qualified_path(<Bar as T>::Baz);
   |                                               ^ expected one of 8 possible tokens
   |
   = note: anonymous parameters are removed in the 2018 edition (see RFC 1685)
help: explicitly ignore the parameter name
   |
LL |     fn foo_with_qualified_path(_: <Bar as T>::Baz);
   |                                ++
```
2024-07-18 08:09:02 +02:00
Trevor Gross
fa1303662a
Rollup merge of #127806 - nnethercote:parser-improvements, r=spastorino
Some parser improvements

I was looking closely at attribute handling in the parser while debugging some issues relating to #124141, and found a few small improvements.

``@spastorino``
2024-07-17 19:53:27 -05:00
Esteban Küber
f6c4679547 More accurate span for anonymous argument suggestion
Use smaller span for suggesting adding `_:` ahead of a type:

```
error: expected one of `(`, `...`, `..=`, `..`, `::`, `:`, `{`, or `|`, found `)`
  --> $DIR/anon-params-denied-2018.rs:12:47
   |
LL |     fn foo_with_qualified_path(<Bar as T>::Baz);
   |                                               ^ expected one of 8 possible tokens
   |
   = note: anonymous parameters are removed in the 2018 edition (see RFC 1685)
help: explicitly ignore the parameter name
   |
LL |     fn foo_with_qualified_path(_: <Bar as T>::Baz);
   |                                ++
```
2024-07-18 00:19:27 +00:00
Michael Goulet
d0a1851ec2 Deny keyword lifetimes pre-expansion 2024-07-16 12:06:25 -04:00
Nicholas Nethercote
9c4f3dbd06 Remove references to maybe_whole_expr.
It was removed in #126571.
2024-07-16 16:40:35 +10:00
Nicholas Nethercote
8cb6bc3b5a Fix a comment. 2024-07-16 16:39:19 +10:00
Nicholas Nethercote
96b39f1204 Inline and remove Parser::parse_expr_dot_or_call_with_.
It only has two call sites, and it extremely similar to
`Parser::parse_expr_dot_or_call_with`, in both name and behaviour. The
only difference is the latter has an `attrs` argument and an
`ensure_sufficient_stack` call. We can pass in an empty `attrs` as
necessary, as is already done at some `parse_expr_dot_or_call_with` call
sites.
2024-07-16 16:16:38 +10:00
Nicholas Nethercote
96cc9c99b2 Inline and remove Parser::parse_and_disallow_postfix_after_cast.
It has a single call site. Removing it removes the need for an
`ExprKind` check. The commit also clarifies the relevant comment.
2024-07-16 16:09:36 +10:00
Nicholas Nethercote
d247489ac2 Reorder Parser::parse_expr_dot_or_call_with arguments.
Put `attrs` before `e0` because that matches the order in the source
code, where outer attributes appear before expressions.
2024-07-16 15:54:34 +10:00
Nicholas Nethercote
48cdfc388d Inline Parser::parse_item_common_.
It has a single call site, it isn't that big, and its name is
confusingly similar to `Parser::parse_item_common`.
2024-07-16 15:07:42 +10:00
Nicholas Nethercote
2f305ff460 Remove an unnecessary ?. 2024-07-16 15:03:25 +10:00
Matthias Krüger
2b82729b91
Rollup merge of #127407 - estebank:parser-suggestions, r=oli-obk
Make parse error suggestions verbose and fix spans

Go over all structured parser suggestions and make them verbose style.

When suggesting to add or remove delimiters, turn them into multiple suggestion parts.
2024-07-15 21:11:48 +02:00
Matthias Krüger
febe4423c1
Rollup merge of #127273 - nnethercote:fix-DebugParser, r=workingjubilee
Fix `DebugParser`.

I tried using this and it didn't work at all. `prev_token` is never eof, so the accumulator is always false, which means the `then_some` always returns `None`, which means `scan` always returns `None`, and `tokens` always ends up an empty vec. I'm not sure how this code was supposed to work.

(An aside: I find `Iterator::scan` to be a pretty wretched function, that produces code which is very hard to understand. Probably why this is just one of two uses of it in the entire compiler.)

This commit changes it to a simpler imperative style that produces a valid `tokens` vec.

r? `@workingjubilee`
2024-07-14 20:24:58 +02:00
Jubilee
125343e7ab
Rollup merge of #127558 - nnethercote:more-Attribute-cleanups, r=petrochenkov
More attribute cleanups

A follow-up to #127308.

r? ```@petrochenkov```
2024-07-13 20:19:46 -07:00
Jubilee
1c8ea14272
Rollup merge of #127477 - nnethercote:tweak-inner_attr_ranges, r=petrochenkov
Clear `inner_attr_ranges` regularly.

There's a comment saying we don't do it for performance reasons, but it doesn't actually affect performance.

The commit also tweaks the control flow, to make clearer that two code paths are mutually exclusive.

r? ````@petrochenkov````
2024-07-13 20:19:46 -07:00
Nicholas Nethercote
aa0e8e1475 Fix DebugParser.
It currently doesn't work at all. This commit changes it to a simpler
imperative style that produces a valid `tokens` vec.

(An aside: I find `Iterator::scan` to be a pretty wretched function,
that produces code which is very hard to understand. Probably why this
is just one of two uses of it in the entire compiler.)
2024-07-13 16:42:00 +10:00
Nicholas Nethercote
cf2dfb2ced Add a test for Parser::debug_lookahead.
That method is currently badly broken, and the test output reflects
this. The obtained tokens list is always empty, except in the case where
we go two `bump`s past the final token, whereupon it will produce as
many `Eof` tokens as asked for.
2024-07-13 15:55:40 +10:00
Nicholas Nethercote
69f6145ad8 Change look from a macro to a function.
Using `#[track_caller]` works if the assertion is moved outside of the
closure.
2024-07-13 12:02:12 +10:00
bors
62c068feea Auto merge of #127636 - nnethercote:fix-Parser-look_ahead, r=oli-obk
Fix `Parser::look_ahead`

`Parser::look_ahead` has a slow but simple general case, and a fast special case that is hit most of the time. But the special case is buggy and behaves differently to the general case. There are also no unit tests. This PR fixes all of this, resulting in a `Parser::look_ahead` that is equally fast, slightly simpler, more correct, and better tested.

r? `@davidtwco`
2024-07-12 17:28:21 +00:00
Nicholas Nethercote
100f3fd133 Add a new special case to Parser::look_ahead.
This new special case is simpler than the old special case because it
only is used when `dist == 1`. But that's still enough to cover ~98% of
cases. This results in equivalent performance to the old special case,
and identical behaviour as the general case.
2024-07-12 13:35:24 +10:00
Nicholas Nethercote
ebe1305b1e Remove the bogus special case from Parser::look_ahead.
The general case at the bottom of `look_ahead` is slow, because it
clones the token cursor. Above it there is a special case for
performance that is hit most of the time and avoids the cloning.
Unfortunately, its behaviour differs from the general case in two ways.

- When within a pair of delimiters, if you look any distance past the
  closing delimiter you get the closing delimiter instead of what comes
  after the closing delimiter.

- It uses `tree_cursor.look_ahead(dist - 1)` which totally confuses
  tokens with token trees. This means that only the first token in a
  token tree will be seen. E.g. in a sequence like `{ a }` the `a` and
  `}` will be skipped over. Bad!

It's likely that these differences weren't noticed before now because
the use of `look_ahead` in the parser is limited to small distances and
relatively few contexts.

Removing the special case causes slowdowns up of to 2% on a range of
benchmarks. The next commit will add a new, correct special case to
regain that lost performance.
2024-07-12 13:33:38 +10:00
Nicholas Nethercote
dad95578b0 Add unit tests for Parser::look_ahead.
It's currently buggy, so some of the test results are surprising, as
described in the `FIXME` comments. The bugs will be fixed in subsequent
commits.
2024-07-12 13:30:00 +10:00
Esteban Küber
71f16bdb32 Make ; suggestions inline 2024-07-12 03:22:32 +00:00
Esteban Küber
b6f518877f fix unused binding 2024-07-12 03:04:06 +00:00
Esteban Küber
377d14be88 More accurate incorrect use of await suggestion 2024-07-12 03:02:58 +00:00
Esteban Küber
b5f94c61f7 Use more accurate span for : to :: suggestion 2024-07-12 03:02:58 +00:00
Esteban Küber
c2b3287483 Make impl and ! removal suggestion short 2024-07-12 03:02:57 +00:00
Esteban Küber
692bc344d5 Make parse error suggestions verbose and fix spans
Go over all structured parser suggestions and make them verbose style.

When suggesting to add or remove delimiters, turn them into multiple suggestion parts.
2024-07-12 03:02:57 +00:00
bors
4a31a6c32a Auto merge of #127382 - estebank:const-let, r=compiler-errors
Use verbose style when suggesting changing `const` with `let`
2024-07-12 01:18:12 +00:00
Esteban Küber
b56dc8ee90 Use verbose style when suggesting changing const with let 2024-07-11 20:39:24 +00:00
trevyn
a01f49e7f3 check is_ident before parse_ident 2024-07-11 12:12:00 +04:00
Michael Goulet
de88bc5c89 And additionally enforce ? and async/const aren't mixed 2024-07-11 00:00:03 -04:00
Michael Goulet
898ed2ffa6 Enforce that ? and for<...> are not combined 2024-07-10 17:49:50 -04:00
Michael Goulet
32c8bfdb11 Improve error message 2024-07-10 17:15:02 -04:00
Michael Goulet
e8445818d4 Reorder modifiers and polarity to be *after* binder in trait bounds 2024-07-10 17:15:02 -04:00
bors
0c81f94b9a Auto merge of #127419 - trevyn:issue-125446, r=fee1-dead
Add suggestions for possible missing `fn`, `struct`, or `enum` keywords

Closes #125446
Closes #65381
2024-07-10 18:27:32 +00:00
Nicholas Nethercote
d8b6aa6d0d Use cfg_attr as a name more.
In various functions where the attribute being processed is known to be
a `#[cfg_attr(...)]` attribute. I find this a helpful reminder.
2024-07-10 15:11:57 +10:00
Nicholas Nethercote
8a390bae06 Change empty replace range condition.
The new condition is equivalent in practice, but it's much more obvious
that it would result in an empty range, because the condition lines up
with the contents of the iterator.
2024-07-10 14:41:39 +10:00
Nicholas Nethercote
f5527949f2 Move Spacing into FlatToken.
It's only needed for the `FlatToken::Token` variant. This makes things a
little more concise.
2024-07-09 21:54:32 +10:00
Nicholas Nethercote
a88c4d67d9 Split the stack in make_attr_token_stream.
It makes for shorter code, and fewer allocations.
2024-07-08 19:04:13 +10:00
Nicholas Nethercote
b16201317e Use iterator normally in make_attr_token_stream.
In a `for` loop, instead of a `while` loop.
2024-07-08 19:04:13 +10:00
Nicholas Nethercote
a47ae57a18 Use an @ pattern to shorten some code. 2024-07-08 19:03:50 +10:00
Nicholas Nethercote
99721c8469 Clear inner_attr_ranges regularly.
There's a comment saying we don't do it for performance reasons, but it
doesn't actually affect performance.

The commit also tweaks the control flow, to make clearer that two code
paths are mutually exclusive.
2024-07-08 16:53:10 +10:00
trevyn
b40adc9d3b Add suggestions for possible missing fn, struct, or enum keywords 2024-07-08 10:04:03 +04:00
Nicholas Nethercote
022582ca46 Remove Clone derive from LazyAttrTokenStreamImpl. 2024-07-07 16:24:51 +10:00
Nicholas Nethercote
3a5c4b6e4e Rename some attribute types for consistency.
- `AttributesData` -> `AttrsTarget`
- `AttrTokenTree::Attributes` -> `AttrTokenTree::AttrsTarget`
- `FlatToken::AttrTarget` -> `FlatToken::AttrsTarget`
2024-07-07 16:14:30 +10:00
Nicholas Nethercote
9d33a8fe51 Simplify ReplaceRange.
Currently the second element is a `Vec<(FlatToken, Spacing)>`. But the
vector always has zero or one elements, and the `FlatToken` is always
`FlatToken::AttrTarget` (which contains an `AttributesData`), and the
spacing is always `Alone`. So we can simplify it to
`Option<AttributesData>`.

An assertion in `to_attr_token_stream` can can also be removed, because
`new_tokens.len()` was always 0 or 1, which means than `range.len()`
is always greater than or equal to it, because `range.is_empty()` is
always false (as per the earlier assertion).
2024-07-07 15:58:36 +10:00
Nicholas Nethercote
dd790ab8ef Remove some unnecessary integer conversions.
These should have been removed in #127233 when the positions were
changed from `usize` to `u32`.
2024-07-05 08:27:17 +10:00
Matthias Krüger
33e9f25e91
Rollup merge of #127092 - compiler-errors:rtn-dots-redux, r=estebank
Change return-type-notation to use `(..)`

Aligns the syntax with the current wording of [RFC 3654](https://github.com/rust-lang/rfcs/pull/3654). Also implements rustfmt support (along with making a match exhaustive).

Tracking:
* https://github.com/rust-lang/rust/issues/109417
2024-07-03 23:30:07 +02:00
Nicholas Nethercote
edeebe675b Import std::{iter,mem}. 2024-07-02 20:29:01 +10:00
Nicholas Nethercote
6f6015679f Rename make_token_stream.
And update the comment. Clearly the return type of this function was
changed at some point in the past, but its name and comment weren't
updated to match.
2024-07-02 17:38:43 +10:00
Nicholas Nethercote
3d750e2702 Shrink parser positions from usize to u32.
The number of source code bytes can't exceed a `u32`'s range, so a token
position also can't. This reduces the size of `Parser` and
`LazyAttrTokenStreamImpl` by eight bytes each.
2024-07-02 17:03:53 +10:00
Nicholas Nethercote
f5b28968db Move more things around in collect_tokens_trailing_token.
To make things a little clearer, and to avoid some `mut` variables.
2024-07-02 10:46:44 +10:00
Nicholas Nethercote
8b5a7eb7f4 Move things around in collect_tokens_trailing_token.
So that the `capturing` state is adjusted immediately before and after
the call to `f`.
2024-07-02 10:46:44 +10:00
Nicholas Nethercote
2342770f49 Flip an if/else in AttrTokenStream::to_attr_token_stream.
To put the simple case first.
2024-07-02 10:46:44 +10:00
Nicholas Nethercote
36c30a968b Fix comment.
Both the indenting, and the missing `)`.
2024-07-02 10:46:44 +10:00
Nicholas Nethercote
d6c0b8117e Fix a typo in a comment. 2024-07-02 10:46:43 +10:00
Matthias Krüger
a4e92bfef0
Rollup merge of #127103 - compiler-errors:tighten-trait-bound-parsing, r=fmease
Move binder and polarity parsing into `parse_generic_ty_bound`

Let's pull out the parts of #127054 which just:
1. Make the parsing code less confusing
2. Fix `?use<>` (to correctly be denied)
3. Improve `T: for<'a> 'a` diagnostics

This should have no user-facing effects on stable parsing.

r? fmease
2024-06-29 09:14:59 +02:00
Michael Goulet
3bc3247200 Move binder and polarity parsing into parse_generic_ty_bound 2024-06-28 19:40:31 -04:00
Michael Goulet
b1a0c0b123 Change RTN to use .. again 2024-06-28 14:20:43 -04:00
Michael Goulet
789ee88bd0 Tighten spans for async blocks 2024-06-27 15:19:08 -04:00
Jacob Pratt
5ec93b8e36
Rollup merge of #126571 - nnethercote:less-maybe_whole-expr-2, r=petrochenkov
Less `maybe_whole_expr`, take 2

I first tried this in #107550. I now think it's worth doing again, as a precursor to #124141.

r? ```@petrochenkov```
2024-06-27 02:06:18 -04:00
Nicholas Nethercote
cf0251d92c Fix a span in parse_ty_bare_fn.
It currently goes one token too far.

Example: line 259 of `tests/ui/abi/compatibility.rs`:
```
test_abi_compatible!(fn_fn, fn(), fn(i32) -> i32);
```
This commit changes the span for the second element from `fn(),` to
`fn()`, i.e. removes the extraneous comma.
2024-06-26 08:23:57 +10:00
Nicholas Nethercote
379b761462 Inline and remove maybe_whole_expr!.
And remove the `NtPath` and `NtBlock` cases in
`parse_literal_maybe_minus`, because they are unnecessary.
2024-06-25 14:57:56 +10:00
Michael Goulet
9ce2a070b3
Rollup merge of #126682 - Zalathar:coverage-attr, r=lcnr
coverage: Overhaul validation of the `#[coverage(..)]` attribute

This PR makes sweeping changes to how the (currently-unstable) coverage attribute is validated:
- Multiple coverage attributes on the same item/expression are now treated as an error.
- The attribute must always be `#[coverage(off)]` or `#[coverage(on)]`, and the error messages for this are more consistent.
  -  A trailing comma is still allowed after off/on, since that's part of the normal attribute syntax.
- Some places that silently ignored a coverage attribute now produce an error instead.
  - These cases were all clearly bugs.
- Some places that ignored a coverage attribute (with a warning) now produce an error instead.
  - These were originally added as lints, but I don't think it makes much sense to knowingly allow new attributes to be used in meaningless places.
  - Some of these errors might soon disappear, if it's easy to extend recursive coverage attributes to things like modules and impl blocks.

---

One of the goals of this PR is to lay a more solid foundation for making the coverage attribute recursive, so that it applies to all nested functions/closures instead of just the one it is directly attached to.

Fixes #126658.

This PR incorporates #126659, which adds more tests for validation of the coverage attribute.

`@rustbot` label +A-code-coverage
2024-06-24 15:51:03 -04:00
Matthias Krüger
a80ee9159b
Rollup merge of #126882 - estebank:multiline-order, r=WaffleLapkin
Special case when a code line only has multiline span starts

Minimize multline span overlap when there are multiple of them starting on the same line:

```
3 |       X0 Y0 Z0
  |  _____^  -  -
  | | _______|  |
  | || _________|
4 | |||   X1 Y1 Z1
5 | |||   X2 Y2 Z2
  | |||____^__-__- `Z` label
  | ||_____|__|
  | |______|  `Y` is a good letter too
  |        `X` is a good letter
```
2024-06-24 15:06:23 +02:00
Zalathar
a000fa8b54 coverage: Tighten validation of #[coverage(off)] and #[coverage(on)] 2024-06-24 20:15:01 +10:00
Matthias Krüger
9a591ea1ce
Rollup merge of #126177 - carbotaniuman:unsafe_attr_errors, r=jieyouxu
Add hard error and migration lint for unsafe attrs

More implementation work for https://github.com/rust-lang/rust/issues/123757

This adds the migration lint for unsafe attributes, as well as making it a hard error in Rust 2024.
2024-06-24 06:27:12 +02:00
carbotaniuman
a23917cfd0 Add hard error and migration lint for unsafe attrs 2024-06-23 19:02:14 -05:00
Esteban Küber
284437d434 Special case when a code line only has multiline span starts
```
3 |       X0 Y0 Z0
  |  _____^  -  -
  | | _______|  |
  | || _________|
4 | |||   X1 Y1 Z1
5 | |||   X2 Y2 Z2
  | |||____^__-__- `Z` label
  | ||_____|__|
  | |______|  `Y` is a good letter too
  |        `X` is a good letter
```
2024-06-23 22:00:52 +00:00
Nicholas Nethercote
e2aa38e6ab Rework pattern and expression nonterminal kinds.
Merge `PatParam`/`PatWithOr`, and `Expr`/`Expr2021`, for a few reasons.

- It's conceptually nice, because the two pattern kinds and the two
  expression kinds are very similar.

- With expressions in particular, there are several places where both
  expression kinds get the same treatment.

- It removes one unreachable match arm.

- Most importantly, for #124141 I will need to introduce a new type
  `MetaVarKind` that is very similar to `NonterminalKind`, but records a
  couple of extra fields for expression metavars. It's nicer to have a
  single `MetaVarKind::Expr` expression variant to hold those extra
  fields instead of duplicating them across two variants
  `MetaVarKind::{Expr,Expr2021}`. And then it makes sense for patterns
  to be treated the same way, and for `NonterminalKind` to also be
  treated the same way.

I also clarified the comments, because I have long found them a little
hard to understand.
2024-06-23 15:57:24 +10:00
Matthias Krüger
f577d808b7
Rollup merge of #126767 - compiler-errors:static-foreign-item, r=spastorino
`StaticForeignItem` and `StaticItem` are the same

The struct `StaticItem` and `StaticForeignItem` are the same, so remove `StaticForeignItem`. Having them be separate is unique to `static` items -- unlike `ForeignItemKind::{Fn,TyAlias}`, which use the normal AST item.

r? ``@spastorino`` or ``@oli-obk``
2024-06-21 09:12:37 +02:00
Matthias Krüger
3bd84f18bc
Rollup merge of #126700 - compiler-errors:fragment, r=fmease
Make edition dependent `:expr` macro fragment act like the edition-dependent `:pat` fragment does

Parse the `:expr` fragment as `:expr_2021` in editions <=2021, and as `:expr` in edition 2024. This is similar to how we parse `:pat` as `:pat_param` in edition <=2018 and `:pat_with_or` in >=2021, and means we can get rid of a span dependency from `nonterminal_may_begin_with`.

Specifically, this fixes a theoretical regression since the `expr_2021` macro fragment previously would allow `const {}` if the *caller* is edition 2024. This is inconsistent with the way that the `pat` macro fragment was upgraded, and also leads to surprising behavior when a macro *caller* crate upgrades to edtion 2024, since they may have parsing changes that they never asked for (with no way of opting out of it).

This PR also allows using `expr_2021` in all editions. Why was this was disallowed in the first place? It's purely additive, and also it's still feature gated?

r? ```@fmease``` ```@eholk``` cc ```@vincenzopalazzo```
cc #123865

Tracking:

- https://github.com/rust-lang/rust/issues/123742
2024-06-21 09:12:36 +02:00
Matthias Krüger
73cc4eca56
Rollup merge of #126125 - dev-ardi:conflict-markers, r=estebank
Improve conflict marker recovery

<!--
If this PR is related to an unstable feature or an otherwise tracked effort,
please link to the relevant tracking issue here. If you don't know of a related
tracking issue or there are none, feel free to ignore this.

This PR will get automatically assigned to a reviewer. In case you would like
a specific user to review your work, you can assign it to them by using

    r​? <reviewer name>
-->
closes #113826
r? ```@estebank``` since you reviewed #115413
cc: ```@rben01``` since you opened up the issue in the first place
2024-06-21 09:12:34 +02:00
bors
4e6de37349 Auto merge of #126757 - compiler-errors:safe, r=spastorino
Properly gate `safe` keyword in pre-expansion

This PR gates `safe` keyword in pre-expansion contexts. Should mitigate the fallout of https://github.com/rust-lang/rust/issues/126755, which is that `safe` is now usable on beta lol.

r? `@spastorino` or `@oli-obk`

cc #124482 tracking #123743
2024-06-21 04:22:02 +00:00
Michael Goulet
3e59f0c3c5 StaticForeignItem and StaticItem are the same 2024-06-20 19:51:09 -04:00
Michael Goulet
108b3f214a Properly gate safe keyword in pre-expansion 2024-06-20 14:14:49 -04:00
Matthias Krüger
ef2e8bfcbf
Rollup merge of #126717 - nnethercote:rustfmt-use-pre-cleanups, r=jieyouxu
Clean up some comments near `use` declarations

#125443 will reformat all `use` declarations in the repository. There are a few edge cases involving comments on `use` declarations that require care. This PR cleans up some clumsy comment cases, taking us a step closer to #125443 being able to merge.

r? ``@lqd``
2024-06-20 14:07:04 +02:00
Nicholas Nethercote
b104fbec85 Add blank lines after module-level // comments.
Similar to the previous commit.
2024-06-20 09:23:20 +10:00
Nicholas Nethercote
c6f78270b6 Introduce can_begin_string_literal.
We currently use `can_begin_literal_maybe_minus` in a couple of places
where only string literals are allowed. This commit introduces a
more specific function, which makes things clearer. It doesn't change
behaviour because the two functions affected (`is_unsafe_foreign_mod`
and `check_keyword_case`) are always followed by a call to `parse_abi`,
which checks again for a string literal.
2024-06-20 04:50:40 +10:00
Nicholas Nethercote
7d9a92ba31 Inline can_begin_literal_maybe_minus call into two places.
It's clearer this way, because the `Interpolated` cases in
`can_begin_const_arg` and `is_pat_range_end_start` are more permissive
than the `Interpolated` cases in `can_begin_literal_maybe_minus`.
2024-06-20 04:50:38 +10:00
Michael Goulet
3e8898a4e1 Allow naming expr_2021 in all editions 2024-06-19 12:37:49 -04:00
bors
894f7a4ba6 Auto merge of #126678 - nnethercote:fix-duplicated-attrs-on-nt-expr, r=petrochenkov
Fix duplicated attributes on nonterminal expressions

This PR fixes a long-standing bug (#86055) whereby expression attributes can be duplicated when expanded through declarative macros.

First, consider how items are parsed in declarative macros:
```
Items:
- parse_nonterminal
  - parse_item(ForceCollect::Yes)
    - parse_item_
      - attrs = parse_outer_attributes
      - parse_item_common(attrs)
        - maybe_whole!
        - collect_tokens_trailing_token
```
The important thing is that the parsing of outer attributes is outside token collection, so the item's tokens don't include the attributes. This is how it's supposed to be.

Now consider how expression are parsed in declarative macros:
```
Exprs:
- parse_nonterminal
  - parse_expr_force_collect
    - collect_tokens_no_attrs
      - collect_tokens_trailing_token
        - parse_expr
          - parse_expr_res(None)
            - parse_expr_assoc_with
              - parse_expr_prefix
                - parse_or_use_outer_attributes
                - parse_expr_dot_or_call
```
The important thing is that the parsing of outer attributes is inside token collection, so the the expr's tokens do include the attributes, i.e. in `AttributesData::tokens`.

This PR fixes the bug by rearranging expression parsing to that outer attribute parsing happens outside of token collection. This requires a number of small refactorings because expression parsing is somewhat complicated. While doing so the PR makes the code a bit cleaner and simpler, by eliminating `parse_or_use_outer_attributes` and `Option<AttrWrapper>` arguments (in favour of the simpler `parse_outer_attributes` and `AttrWrapper` arguments), and simplifying `LhsExpr`.

r? `@petrochenkov`
2024-06-19 13:58:21 +00:00
Nicholas Nethercote
64c2e9ed3b Change how parse_expr_force_collect works.
It now parses outer attributes before collecting tokens. This avoids the
problem where the outer attribute tokens were being stored twice -- for
the attribute tokesn, and also for the expression tokens.

Fixes #86055.
2024-06-19 19:15:06 +10:00
Nicholas Nethercote
8170acb197 Refactor parse_expr_res.
This removes the final `Option<AttrWrapper>` argument.
2024-06-19 19:12:02 +10:00
Nicholas Nethercote
43eae4cef4 Simplify LhsExpr::Unparsed.
By making the `AttrWrapper` non-optional.
2024-06-19 19:12:02 +10:00
Nicholas Nethercote
aaa220e875 Move parse_or_use_outer_attributes out of parse_expr_prefix_range.
This eliminates another `Option<AttrWrapper>` argument and changes one
obscure error message.
2024-06-19 19:12:00 +10:00
Nicholas Nethercote
802779f77d Move parse_or_use_outer_attributes out of parse_expr_prefix.
This eliminates one `Option<AttrWrapper>` argument.
2024-06-19 18:53:25 +10:00
Nicholas Nethercote
ead0a45202 Inline and remove parse_expr_assoc.
It has a single call site.
2024-06-19 18:53:25 +10:00
Nicholas Nethercote
25523ba382 Refactor LhsExpr.
Combine `NotYetParsed` and `AttributesParsed` into a single variant,
because (a) that reflects the structure of the code that consumes
`LhsExpr`, and (b) because that variant will have the `Option` removed
in a later commit.
2024-06-19 18:53:25 +10:00
Nicholas Nethercote
42e47dfe82 Remove From impls for LhsExpr.
The `Option<AttrWrapper>` one maps to the first two variants, and the
`P<Expr>` one maps to the third. Weird. The code is shorter and clearer
without them.
2024-06-19 18:53:25 +10:00
Nicholas Nethercote
1c28229ada Simplify Parser::parse_expr_dot_or_call.
The call in `parse_expr_prefix` for the `++` case passes an empty
`attrs`, but it doesn' need to. This commit changes it to pass the
parsed `attrs`, which doesn't change any behaviour. As a result,
`parse_expr_dot_or_call` no longer needs an `Option` argument, and no
longer needs to call `parse_or_use_outer_attributes`.
2024-06-19 18:53:25 +10:00
Nicholas Nethercote
1fbb3eca67 Expand another comment. 2024-06-19 18:53:24 +10:00
许杰友 Jieyou Xu (Joe)
f8ce1cfbf5
Rollup merge of #124135 - petrochenkov:deleglob, r=fmease
delegation: Implement glob delegation

Support delegating to all trait methods in one go.
Overriding globs with explicit definitions is also supported.

The implementation is generally based on the design from https://github.com/rust-lang/rfcs/pull/3530#issuecomment-2020869823, but unlike with list delegation in https://github.com/rust-lang/rust/pull/123413 we cannot expand glob delegation eagerly.
We have to enqueue it into the queue of unexpanded macros (most other macros are processed this way too), and then a glob delegation waits in that queue until its trait path is resolved, and enough code expands to generate the identifier list produced from the glob.

Glob delegation is only allowed in impls, and can only point to traits.
Supporting it in other places gives very little practical benefit, but significantly raises the implementation complexity.

Part of https://github.com/rust-lang/rust/issues/118212.
2024-06-19 01:51:36 +01:00
ardi
9f6371236f make this comment correct 2024-06-19 00:27:41 +02:00
ardi
d51b4462ec Improve conflict marker recovery 2024-06-19 00:27:41 +02:00
Oli Scherer
3f34196839 Remove redundant argument from subdiagnostic method 2024-06-18 15:42:11 +00:00
Oli Scherer
7ba82d61eb Use a dedicated type instead of a reference for the diagnostic context
This paves the way for tracking more state (e.g. error tainting) in the diagnostic context handle
2024-06-18 15:42:11 +00:00
Oli Scherer
c91edc3888 Prefer dcx methods over fields or fields' methods 2024-06-18 13:45:08 +00:00
Michael Goulet
b1efe1ab5d Rework precise capturing syntax 2024-06-17 22:35:25 -04:00
Michael Goulet
68bd001c00 Make parse_seq_to_before_tokens take expected/nonexpected tokens, use in parse_precise_capturing_syntax 2024-06-17 22:35:25 -04:00
Vadim Petrochenkov
22d0b1ee18 delegation: Implement glob delegation 2024-06-14 19:27:51 +03:00
Nicholas Nethercote
75b164d836 Use tidy to sort crate attributes for all compiler crates.
We already do this for a number of crates, e.g. `rustc_middle`,
`rustc_span`, `rustc_metadata`, `rustc_span`, `rustc_errors`.

For the ones we don't, in many cases the attributes are a mess.
- There is no consistency about order of attribute kinds (e.g.
  `allow`/`deny`/`feature`).
- Within attribute kind groups (e.g. the `feature` attributes),
  sometimes the order is alphabetical, and sometimes there is no
  particular order.
- Sometimes the attributes of a particular kind aren't even grouped
  all together, e.g. there might be a `feature`, then an `allow`, then
  another `feature`.

This commit extends the existing sorting to all compiler crates,
increasing consistency. If any new attribute line is added there is now
only one place it can go -- no need for arbitrary decisions.

Exceptions:
- `rustc_log`, `rustc_next_trait_solver` and `rustc_type_ir_macros`,
  because they have no crate attributes.
- `rustc_codegen_gcc`, because it's quasi-external to rustc (e.g. it's
  ignored in `rustfmt.toml`).
2024-06-12 15:49:10 +10:00
Matthias Krüger
4aceaaa7f3
Rollup merge of #126052 - nnethercote:rustc_parse-more-cleanups, r=spastorino
More `rustc_parse` cleanups

Following on from #125815.

r? `@spastorino`
2024-06-07 20:14:30 +02:00
Matthias Krüger
6e534c73c3
Rollup merge of #124214 - carbotaniuman:parse_unsafe_attrs, r=michaelwoerister
Parse unsafe attributes

Initial parse implementation for #123757

This is the initial work to parse unsafe attributes, which is represented as an extra `unsafety` field in `MetaItem` and `AttrItem`. There's two areas in the code where it appears that parsing is done manually and not using the parser stuff, and I'm not sure how I'm supposed to thread the change there.
2024-06-07 20:14:28 +02:00
bors
1be24d70ce Auto merge of #125918 - oli-obk:const_block_ice, r=compiler-errors
Revert: create const block bodies in typeck via query feeding

as per the discussion in https://github.com/rust-lang/rust/pull/125806#discussion_r1622563948

It was a mistake to try to shoehorn const blocks and some specific anon consts into the same box and feed them during typeck. It turned out not simplifying anything (my hope was that we could feed `type_of` to start avoiding the huge HIR matcher, but that didn't work out), but instead making a few things more fragile.

reverts the const-block-specific parts of https://github.com/rust-lang/rust/pull/124650

`@bors` rollup=never had a small perf impact previously

fixes https://github.com/rust-lang/rust/issues/125846

r? `@compiler-errors`
2024-06-07 09:08:59 +00:00
Oli Scherer
cbee17d502 Revert "Create const block DefIds in typeck instead of ast lowering"
This reverts commit ddc5f9b6c1.
2024-06-07 08:33:58 +00:00
carbotaniuman
87be1bae73 Fix build 2024-06-06 20:27:25 -05:00
carbotaniuman
67f5dd1ef1 Parse unsafe attributes 2024-06-06 20:26:27 -05:00
Rémy Rakic
216424da32 Revert "Rollup merge of #124099 - voidc:disallow-ambiguous-expr-attrs, r=davidtwco"
This reverts commit 57dad1d75e, reversing
changes made to 36316df9fe.
2024-06-06 20:39:54 +00:00
bors
2d28b6384e Auto merge of #124482 - spastorino:unsafe-extern-blocks, r=oli-obk
Unsafe extern blocks

This implements RFC 3484.

Tracking issue #123743 and RFC https://github.com/rust-lang/rfcs/pull/3484

This is better reviewed commit by commit.
2024-06-06 08:14:58 +00:00
Nicholas Nethercote
4c731c2f6b Inline and remove check_builtin_attribute.
It's small and has a single call site.

Also change the second `parse_meta` call to use a simple `match`, like
the first `parse_meta` call, instead of a confusing `map_err`+`ok`
combination.
2024-06-06 08:26:54 +10:00
Nicholas Nethercote
13f2bc9a65 Specialize assert_pred.
It has only two uses, and both use `matches_codepattern`. So just change
it to `assert_matches_codepattern`.
2024-06-06 08:26:54 +10:00
Nicholas Nethercote
95b4c07ef8 Reduce pub exposure. 2024-06-06 08:26:54 +10:00
Nicholas Nethercote
b9037339cb Make top-level rustc_parse functions fallible.
Currently we have an awkward mix of fallible and infallible functions:
```
       new_parser_from_source_str
 maybe_new_parser_from_source_str
       new_parser_from_file
(maybe_new_parser_from_file)        // missing
      (new_parser_from_source_file) // missing
 maybe_new_parser_from_source_file
       source_str_to_stream
 maybe_source_file_to_stream
```
We could add the two missing functions, but instead this commit removes
of all the infallible ones and renames the fallible ones leaving us with
these which are all fallible:
```
new_parser_from_source_str
new_parser_from_file
new_parser_from_source_file
source_str_to_stream
source_file_to_stream
```
This requires making `unwrap_or_emit_fatal` public so callers of
formerly infallible functions can still work.

This does make some of the call sites slightly more verbose, but I think
it's worth it for the simpler API. Also, there are two `catch_unwind`
calls and one `catch_fatal_errors` call in this diff that become
removable thanks this change. (I will do that in a follow-up PR.)
2024-06-05 10:38:03 +10:00
Nicholas Nethercote
264dbe4d81 Inline and remove source_file_to_stream.
It has a single call site.
2024-06-05 10:38:03 +10:00
Nicholas Nethercote
ab192a0c97 Reorder source_str_to_stream arguments.
It's the only one of these functions where `psess` isn't the first
argument.
2024-06-05 10:38:02 +10:00
Nicholas Nethercote
25972aec67 Inline and remove parse_crate{,_attrs}_from_{file,source_str}.
All four functions are simple and have a single call site.

This requires making `Parser::parse_inner_attributes` public, which is
no big deal.
2024-06-05 10:38:02 +10:00
Nicholas Nethercote
8964106e44 Use source_str_to_stream in a test file.
It does exactly what is required.
2024-06-05 10:38:02 +10:00
Nicholas Nethercote
191b76ef31 Rename maybe_source_file_to_parser as maybe_new_parser_from_source_file.
For consistency with `new_parser_from_{file,source_str}` and
`maybe_new_parser_from_source_str`.
2024-06-05 10:38:02 +10:00
Nicholas Nethercote
29e6e2859b Remove low-value comments.
The first one is out-of-date -- there are no longer functions expr,
item, stmt. And I don't know what a "HOF" is.

The second one doesn't really tell you anything.
2024-06-05 10:38:02 +10:00
Nicholas Nethercote
af13b48927 Improve panictry_buffer!.
- Convert it from a macro to a function, which is nicer.
- Rename it as `unwrap_or_emit_fatal`, which is clearer.
- Fix the comment. In particular, `panictry!` no longer exists.
- Remove the unnecessary `use` declaration.
2024-06-05 10:38:02 +10:00
Nicholas Nethercote
3c321b9ea8 Remove stream_to_parser.
It's a zero-value wrapper of `Parser::new`.
2024-06-05 10:37:59 +10:00
Nicholas Nethercote
769ca3f661 Rename maybe_file_to_stream as maybe_source_file_to_stream.
Because it takes an `Lrc<SourceFile>`, and for consistency with
`source_file_to_stream`.
2024-06-05 10:29:16 +10:00
Nicholas Nethercote
f6576249ab Inline and remove error_malformed_cfg_attr_missing.
It has a single call site.

This also means `CFG_ATTR_{GRAMMAR_HELP,NOTE_REF}` can be moved into
`parse_cfg_attr`, now that it's the only function that uses them.
And the commit removes the line break in the URL.
2024-06-05 10:29:16 +10:00
Nicholas Nethercote
d1215da26e Don't use the word "parse" for lexing operations.
Lexing converts source text into a token stream. Parsing converts a
token stream into AST fragments. This commit renames several lexing
operations that have "parse" in the name. I think these names have been
subtly confusing me for years.

This is just a `s/parse/lex/` on function names, with one exception:
`parse_stream_from_source_str` becomes `source_str_to_stream`, to make
it consistent with the existing `source_file_to_stream`. The commit also
moves that function's location in the file to be just above
`source_file_to_stream`.

The commit also cleans up a few comments along the way.
2024-06-05 10:29:16 +10:00
Nicholas Nethercote
e1ae0fa055 UNICODE_ARRAY and ASCII_ARRAY fixes.
- Avoid unnecessary escaping of single quotes within string literals.
- Add a missing blank line between two `UNICODE_ARRAY` sections.
2024-06-05 10:29:16 +10:00
Santiago Pastorino
bac72cf7cf
Add safe/unsafe to static inside extern blocks 2024-06-04 14:19:43 -03:00
Santiago Pastorino
2a377122dd
Handle safety keyword for extern block inner items 2024-06-04 14:19:42 -03:00
Vincenzo Palazzo
36d5fc9a64
Avoid checking the edition as much as possible
Inside #123865, we are adding support for the new semantics
for expr2024, but we have noted a performance issue.

We realized there is a redundant check for each
token regarding an edition. This commit moves the edition
check to the end, avoiding some extra checks that
can slow down compilation time.

Link: https://github.com/rust-lang/rust/pull/123865
Co-Developed-by: @eholk
Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
2024-06-02 09:42:21 +02:00
bors
f67a1acc04 Auto merge of #125863 - fmease:rej-CVarArgs-in-parse_ty_for_where_clause, r=compiler-errors
Reject `CVarArgs` in `parse_ty_for_where_clause`

Fixes #125847. This regressed in #77035 where the `parse_ty` inside `parse_ty_where_predicate` was replaced with the at the time new `parse_ty_for_where_clause` which incorrectly stated it would permit CVarArgs (maybe a copy/paste error).

r? parser
2024-06-01 21:13:52 +00:00
León Orell Valerian Liehr
89386092f1
Reject CVarArgs in parse_ty_for_where_clause 2024-06-01 20:57:15 +02:00
Matthias Krüger
379233242b
Rollup merge of #125635 - fmease:mv-type-binding-assoc-item-constraint, r=compiler-errors
Rename HIR `TypeBinding` to `AssocItemConstraint` and related cleanup

Rename `hir::TypeBinding` and `ast::AssocConstraint` to `AssocItemConstraint` and update all items and locals using the old terminology.

Motivation: The terminology *type binding* is extremely outdated. "Type bindings" not only include constraints on associated *types* but also on associated *constants* (feature `associated_const_equality`) and on RPITITs of associated *functions* (feature `return_type_notation`). Hence the word *item* in the new name. Furthermore, the word *binding* commonly refers to a mapping from a binder/identifier to a "value" for some definition of "value". Its use in "type binding" made sense when equality constraints (e.g., `AssocTy = Ty`) were the only kind of associated item constraint. Nowadays however, we also have *associated type bounds* (e.g., `AssocTy: Bound`) for which the term *binding* doesn't make sense.

---

Old terminology (HIR, rustdoc):

```
`TypeBinding`: (associated) type binding
├── `Constraint`: associated type bound
└── `Equality`: (associated) equality constraint (?)
    ├── `Ty`: (associated) type binding
    └── `Const`: associated const equality (constraint)
```

Old terminology (AST, abbrev.):

```
`AssocConstraint`
├── `Bound`
└── `Equality`
    ├── `Ty`
    └── `Const`
```

New terminology (AST, HIR, rustdoc):

```
`AssocItemConstraint`: associated item constraint
├── `Bound`: associated type bound
└── `Equality`: associated item equality constraint OR associated item binding (for short)
    ├── `Ty`: associated type equality constraint OR associated type binding (for short)
    └── `Const`: associated const equality constraint OR associated const binding (for short)
```

r? compiler-errors
2024-05-31 08:50:22 +02:00
León Orell Valerian Liehr
34c56c45cf
Rename HIR TypeBinding to AssocItemConstraint and related cleanup 2024-05-30 22:52:33 +02:00
Oli Scherer
ddc5f9b6c1 Create const block DefIds in typeck instead of ast lowering 2024-05-28 13:38:43 +00:00
Nicholas Nethercote
bb364fe950 Remove #[macro_use] extern crate tracing from rustc_parse. 2024-05-23 18:02:40 +10:00
León Orell Valerian Liehr
5b485f04de
Rollup merge of #125049 - dtolnay:castbrace, r=compiler-errors
Disallow cast with trailing braced macro in let-else

This fixes an edge case I noticed while porting #118880 and #119062 to syn.

Previously, rustc incorrectly accepted code such as:

```rust
let foo = &std::ptr::null as &'static dyn std::ops::Fn() -> *const primitive! {
    8
} else {
    return;
};
```

even though a right curl brace `}` directly before `else` in a `let...else` statement is not supposed to be valid syntax.
2024-05-22 19:04:44 +02:00
bors
791adf759c Auto merge of #124417 - Xiretza:translate-early-lints, r=fmease
Make early lints translatable

<del>Requires https://github.com/projectfluent/fluent-rs/pull/353.</del> 5134a04eaa

r? diagnostics
2024-05-21 21:36:09 +00:00
Xiretza
98dd6c7e8f Rename buffer_lint_with_diagnostic to buffer_lint 2024-05-21 20:16:39 +00:00
Xiretza
b7abf014ec Convert uses of BuiltinLintDiag::Normal to custom variants
This ensures all diagnostic messages are created at diagnostic emission
time, making them translatable.
2024-05-21 20:16:39 +00:00
Xiretza
c227f35a9c Generate lint diagnostic message from BuiltinLintDiag
Translation of the lint message happens when the actual diagnostic is
created, not when the lint is buffered. Generating the message from
BuiltinLintDiag ensures that all required data to construct the message
is preserved in the LintBuffer, eventually allowing the messages to be
moved to fluent.

Remove the `msg` field from BufferedEarlyLint, it is either generated
from the data in the BuiltinLintDiag or stored inside
BuiltinLintDiag::Normal.
2024-05-21 20:16:39 +00:00
ardi
972633f530 Fix parsing of erroneously placed semicolons 2024-05-20 21:36:20 +02:00
bors
eb1a5c9bb3 Auto merge of #125077 - spastorino:add-new-fnsafety-enum2, r=jackh726
Rename Unsafe to Safety

Alternative to #124455, which is to just have one Safety enum to use everywhere, this opens the posibility of adding `ast::Safety::Safe` that's useful for unsafe extern blocks.

This leaves us today with:

```rust
enum ast::Safety {
    Unsafe(Span),
    Default,
    // Safe (going to be added for unsafe extern blocks)
}

enum hir::Safety {
    Unsafe,
    Safe,
}
```

We would convert from `ast::Safety::Default` into the right Safety level according the context.
2024-05-18 19:35:24 +00:00
Matthias Krüger
f9bf759e83
Rollup merge of #125117 - dev-ardi:improve-parser, r=wesleywiser,fmease
Improve parser

Fixes #124935.

- Add a few more help diagnostics to incorrect semicolons
- Overall improved that function
- Addded a few comments
- Renamed diff_marker fns to git_diff_marker
2024-05-18 18:44:14 +02:00
bors
9b75a43881 Auto merge of #123865 - eholk:expr_2021, r=fmease
Update `expr` matcher for Edition 2024 and add `expr_2021` nonterminal

This commit adds a new nonterminal `expr_2021` in macro patterns, and `expr_fragment_specifier_2024` feature flag.

This change also updates `expr` so that on Edition 2024 it will also match `const { ... }` blocks, while `expr_2021` preserves the current behavior of `expr`, matching expressions without `const` blocks.

Joint work with `@vincenzopalazzo.`

Issue #123742
2024-05-17 21:54:14 +00:00
Santiago Pastorino
6b46a919e1
Rename Unsafe to Safety 2024-05-17 18:33:37 -03:00
Eric Holk
3986ea0ea5
Update compiler/rustc_parse/src/parser/nonterminal.rs
Co-authored-by: León Orell Valerian Liehr <me@fmease.dev>
2024-05-17 11:55:38 -07:00
ardi
f8433a82b4 use signature name for arg 2024-05-17 15:47:24 +02:00
ardi
db5a616405 s/(Ident, ItemKind)/ItemInfo/ 2024-05-17 15:47:21 +02:00
ardi
1f6d271527 Clarify that the diff_marker is talking about version control system
conflicts specifically and a few more improvements.
2024-05-17 15:45:50 +02:00
Vadim Petrochenkov
c30b41012d delegation: Implement list delegation
```rust
reuse prefix::{a, b, c}
```
2024-05-15 02:32:59 +03:00
ardi
8dc6a5d145 improve maybe_consume_incorrect_semicolon 2024-05-14 23:07:40 +02:00
Michael Goulet
1529c661e4 Warn against redundant use<...> 2024-05-13 23:57:56 -04:00
Nicholas Nethercote
95e519ecbf Remove NtIdent and NtLifetime.
The extra span is now recorded in the new `TokenKind::NtIdent` and
`TokenKind::NtLifetime`. These both consist of a single token, and so
there's no operator precedence problems with inserting them directly
into the token stream.

The other way to do this would be to wrap the ident/lifetime in invisible
delimiters, but there's a lot of code that assumes an interpolated
ident/lifetime fits in a single token, and changing all that code to work with
invisible delimiters would have been a pain. (Maybe it could be done in a
follow-up.)

This change might not seem like much of a win, but it's a first step toward the
much bigger and long-desired removal of `Nonterminal` and
`TokenKind::Interpolated`. That change is big and complex enough that it's
worth doing this piece separately. (Indeed, this commit is based on part of a
late commit in #114647, a prior attempt at that big and complex change.)
2024-05-14 08:19:58 +10:00
Vincenzo Palazzo
a55d06323a
Macros: match const { ... } with expr nonterminal in edition 2024
Co-authored-by: Eric Holk <eric@theincredibleholk.org>
Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
2024-05-13 11:55:26 -07:00
Eric Holk
ef6478ba5f
Add expr_2021 nonterminal and feature flag
This commit adds a new nonterminal `expr_2021` in macro patterns, and
`expr_fragment_specifier_2024` feature flag. For now, `expr` and
`expr_2021` are treated the same, but in future PRs we will update
`expr` to match to new grammar.

Co-authored-by: Vincezo Palazzo <vincenzopalazzodev@gmail.com>
2024-05-13 11:27:26 -07:00
David Tolnay
a36b94d088
Disallow cast with trailing braced macro in let-else 2024-05-12 21:50:14 -07:00
Nicholas Nethercote
9a63a42cb7 Remove a Span from TokenKind::Interpolated.
This span records the declaration of the metavariable in the LHS of the macro.
It's used in a couple of error messages. Unfortunately, it gets in the way of
the long-term goal of removing `TokenKind::Interpolated`. So this commit
removes it, which degrades a couple of (obscure) error messages but makes
things simpler and enables the next commit.
2024-05-13 10:30:30 +10:00
David Tolnay
10227eaee7
Add classify::expr_is_complete 2024-05-11 18:18:20 -07:00
David Tolnay
53521faf06
Remove MacCall special cases from Parser::parse_full_stmt
It is impossible for expr here to be a braced macro call. Expr comes
from `parse_stmt_without_recovery`, in which macro calls are parsed by
`parse_stmt_mac`. See this part:

    let kind = if (style == MacStmtStyle::Braces
        && self.token != token::Dot
        && self.token != token::Question)
        || self.token == token::Semi
        || self.token == token::Eof
    {
        StmtKind::MacCall(P(MacCallStmt { mac, style, attrs, tokens: None }))
    } else {
        // Since none of the above applied, this is an expression statement macro.
        let e = self.mk_expr(lo.to(hi), ExprKind::MacCall(mac));
        let e = self.maybe_recover_from_bad_qpath(e)?;
        let e = self.parse_expr_dot_or_call_with(e, lo, attrs)?;
        let e = self.parse_expr_assoc_with(
            0,
            LhsExpr::AlreadyParsed { expr: e, starts_statement: false },
        )?;
        StmtKind::Expr(e)
    };

A braced macro call at the head of a statement is always either extended
into ExprKind::Field / MethodCall / Await / Try / Binary, or else
returned as StmtKind::MacCall. We can never get a StmtKind::Expr
containing ExprKind::MacCall containing brace delimiter.
2024-05-11 15:49:51 -07:00
David Tolnay
aedc1b6ad4
Remove MacCall special case from recovery after missing 'if' after 'else'
The change to the test is a little goofy because the compiler was
guessing "correctly" before that `falsy! {}` is the condition as opposed
to the else body. But I believe this change is fundamentally correct.
Braced macro invocations in statement position are most often item-like
(`thread_local! {...}`) as opposed to parenthesized macro invocations
which are condition-like (`cfg!(...)`).
2024-05-11 15:49:51 -07:00
David Tolnay
728e117166
Document MacCall special case in Parser::parse_arm 2024-05-11 15:49:51 -07:00
David Tolnay
9dbe33d256
Document MacCall special case in Parser::expr_is_complete 2024-05-11 15:49:51 -07:00
David Tolnay
8adcaf5df2
Mark Parser::expr_is_complete call sites 2024-05-11 15:49:51 -07:00
David Tolnay
9e1cf2098d
Macro call with braces does not require semicolon to be statement
This commit by itself is supposed to have no effect on behavior. All of
the call sites are updated to preserve their previous behavior.

The behavior changes are in the commits that follow.
2024-05-11 15:48:59 -07:00
David Tolnay
cbb8714a3f
Mark expr_requires_semi_to_be_stmt call sites
For each of these, we need to decide whether they need to be using
`expr_requires_semi_to_be_stmt`, or `expr_requires_comma_to_be_match_arm`,
which are supposed to be 2 different behaviors. Previously they were
conflated into one, causing either too much or too little
parenthesization.
2024-05-11 15:48:58 -07:00
许杰友 Jieyou Xu (Joe)
e7bb090d0a
Rollup merge of #124930 - compiler-errors:consume-arg, r=petrochenkov
Make sure we consume a generic arg when checking mistyped turbofish

When recovering un-turbofish-ed args in expr position (e.g. `let x = a<T, U>();` in `check_mistyped_turbofish_with_multiple_type_params`, we used `parse_seq_to_before_end` to parse the fake generic args; however, it used `parse_generic_arg` which *optionally* parses a generic arg. If it doesn't end up parsing an arg, it returns `Ok(None)` and consumes no tokens. If we don't find a delimiter after this (`,`), we try parsing *another* element. In this case, we just infinitely loop looking for a subsequent element.

We can fix this by making sure that we either parse a generic arg or error in `parse_seq_to_before_end`'s callback.

Fixes #124897
2024-05-11 01:15:10 +01:00
许杰友 Jieyou Xu (Joe)
69122f1da4
Rollup merge of #124318 - bvanjoi:fix-123911, r=petrochenkov
ignore generics args in attribute paths

Fixes #97006
Fixes #123911
Fixes #123912

This patch ensures that we no longer have to handle invalid generic arguments in attribute paths.

r? `@petrochenkov`
2024-05-11 01:15:08 +01:00
bohan
f70f900036 ignore generics args in attribute paths 2024-05-11 00:13:27 +08:00
Matthias Krüger
f605174ea7
Rollup merge of #124778 - fmease:fix-diag-msg-parse-meta-item, r=nnethercote
Fix parse error message for meta items

Addresses https://github.com/rust-lang/rust/issues/122796#issuecomment-2010803906, cc [``@]Thomasdezeeuw.``

For attrs inside of a macro like `#[doc(alias = $ident)]` or `#[cfg(feature = $ident)]` where `$ident` is a macro metavariable of fragment kind `ident`, we used to say the following when expanded (with `$ident` ⟼ `ident`):

```
error: expected unsuffixed literal or identifier, found `ident`
  --> weird.rs:6:19
   |
6  |      #[cfg(feature = $ident)]
   |                      ^^^^^^
...
11 | m!(id);
   | ------ in this macro invocation
   |
   = note: this error originates in the macro `m` (in Nightly builds, run with -Z macro-backtrace for more info)
```

This was incorrect and caused confusion, justifiably so (see #122796).

In this position, we only accept/expect *unsuffixed literals* which consist of numeric & string literals as well as the boolean literals / the keywords / the reserved identifiers `false` & `true` **but not** arbitrary identifiers.

Furthermore, we used to suggest garbage when encountering unexpected non-identifier tokens:

```
error: expected unsuffixed literal, found `-`
  --> weird.rs:16:17
   |
16 | #[cfg(feature = -1)]
   |                 ^
   |
help: surround the identifier with quotation marks to parse it as a string
   |
16 | #[cfg(feature =" "-1)]
   |                + +
```

Now we no longer do.
2024-05-10 16:10:45 +02:00
León Orell Valerian Liehr
0ad3c5da72
Fix parse error message for meta items 2024-05-10 09:16:27 +02:00
Michael Goulet
dbdef68ddf Make sure we consume a generic arg when checking mistyped turbofish 2024-05-09 10:47:14 -04:00
Nicholas Nethercote
fd91925bce Add ErrorGuaranteed to Recovered::Yes and use it more.
The starting point for this was identical comments on two different
fields, in `ast::VariantData::Struct` and `hir::VariantData::Struct`:
```
    // FIXME: investigate making this a `Option<ErrorGuaranteed>`
    recovered: bool
```
I tried that, and then found that I needed to add an `ErrorGuaranteed`
to `Recovered::Yes`. Then I ended up using `Recovered` instead of
`Option<ErrorGuaranteed>` for these two places and elsewhere, which
required moving `ErrorGuaranteed` from `rustc_parse` to `rustc_ast`.

This makes things more consistent, because `Recovered` is used in more
places, and there are fewer uses of `bool` and
`Option<ErrorGuaranteed>`. And safer, because it's difficult/impossible
to set `recovered` to `Recovered::Yes` without having emitted an error.
2024-05-09 20:12:07 +10:00
Matthias Krüger
d30af5e168
Rollup merge of #123344 - pietroalbini:pa-unused-imports, r=Nilstrieb
Remove braces when fixing a nested use tree into a single item

[Back in 2019](https://github.com/rust-lang/rust/pull/56645) I added rustfix support for the `unused_imports` lint, to automatically remove them when running `cargo fix`. For the most part this worked great, but when removing all but one childs of a nested use tree it turned `use foo::{Unused, Used}` into `use foo::{Used}`. This is slightly annoying, because it then requires you to run `rustfmt` to get `use foo::Used`.

This PR automatically removes braces and the surrouding whitespace when all but one child of a nested use tree are unused. To get it done I had to add the span of the nested use tree to the AST, and refactor a bit the code I wrote back then.

A thing I noticed is, there doesn't seem to be any `//@ run-rustfix` test for fixing the `unused_imports` lint. I created a test in `tests/suggestions` (is that the right directory?) that for now tests just what I added in the PR. I can followup in a separate PR to add more tests for fixing `unused_lints`.

This PR is best reviewed commit-by-commit.
2024-05-08 23:33:24 +02:00
bors
5ce96b1d0f Auto merge of #124779 - workingjubilee:debug-formatting-my-beloved, r=compiler-errors
Improve `rustc_parse::Parser`'s debuggability

The main event is the final commit where I add `Parser::debug_lookahead`. Everything else was basically cleaning up things that bugged me (debugging, as it were) until I felt comfortable enough to actually work on it.

The motivation is that it's annoying as hell to try to figure out how the debug infra works in rustc without having basic queries like `debug!(?parser);` come up "empty". However, Parser has a lot of fields that are mostly irrelevant for most debugging, like the entire ParseSess. I think `Parser::debug_lookahead` with a capped lookahead might be fine as a general-purpose Debug impl, but this adapter version was suggested to allow more choice, and admittedly, it's a refined version of what I was already handrolling just to get some insight going.
2024-05-08 05:11:18 +00:00
Jubilee Young
5e67a3783c compiler: add Parser::debug_lookahead
I tried debugging a parser-related issue but found it annoying to not be
able to easily peek into the Parser's token stream.

Add a convenience fn that offers an opinionated view into the parser,
but one that is useful for answering basic questions about parser state.
2024-05-07 19:10:29 -07:00
Jubilee Young
c70290da0a compiler: derive Debug in parser
It's annoying to debug the parser if you have to stop every five seconds
to add a Debug impl.
2024-05-07 19:09:39 -07:00
Lin Yihai
f9bb5df5a0 narrow down visibilities in rustc_parse::lexer 2024-05-07 11:02:28 +08:00
Jubilee Young
e0192f48c9 compiler: Privatize Parser::current_closure
This was added as pub in 2021 and remains only privately used in 2024!
2024-05-05 16:56:23 -07:00
Nicholas Nethercote
2acbe9c743 Move some tests from rustc_expand to rustc_parse.
There are some test cases involving `parse` and `tokenstream` and
`mut_visit` that are located in `rustc_expand`. Because it used to be
the case that constructing a `ParseSess` required the involvement of
`rustc_expand`. However, since #64197 merged (a long time ago)
`rust_expand` no longer needs to be involved.

This commit moves the tests into `rustc_parse`. This is the optimal
place for the `parse` tests. It's not ideal for the `tokenstream` and
`mut_visit` tests -- they would be better in `rustc_ast` -- but they
still rely on parsing, which is not available in `rustc_ast`. But
`rustc_parse` is lower down in the crate graph and closer to `rustc_ast`
than `rust_expand`, so it's still an improvement for them.

The exact renaming is as follows:

- rustc_expand/src/mut_visit/tests.rs -> rustc_parse/src/parser/mut_visit/tests.rs
- rustc_expand/src/tokenstream/tests.rs -> rustc_parse/src/parser/tokenstream/tests.rs
- rustc_expand/src/tests.rs + rustc_expand/src/parse/tests.rs ->
  compiler/rustc_parse/src/parser/tests.rs

The latter two test files are combined because there's no need for them
to be separate, and having a `rustc_parse::parser::parse` module would
be weird. This also means some `pub(crate)`s can be removed.
2024-05-06 09:06:02 +10:00
Santiago Pastorino
f06e0f7837
Add StaticForeignItem and use it on ForeignItemKind 2024-04-29 13:15:51 -03:00