Commit graph

252 commits

Author SHA1 Message Date
Vadim Petrochenkov
4a88165124 ast: Keep expansion status for out-of-line module items
Also remove `ast::Mod` which is mostly redundant now
2021-02-18 13:07:49 +03:00
Vadim Petrochenkov
eb65f15c78 ast: Stop using Mod in Crate
Crate root is sufficiently different from `mod` items, at least at syntactic level.

Also remove customization point for "`mod` item or crate root" from AST visitors.
2021-02-18 13:07:49 +03:00
Matthias Krüger
ec50a2086a avoid converting types into themselves (clippy::useless_conversion) 2021-02-17 20:37:09 +01:00
mark
aee1e59e6f Simplify pattern grammar by allowing nested leading vert
Along the way, we also implement a handful of diagnostics improvements
and fixes, particularly with respect to the special handling of `||` in
place of `|` and when there are leading verts in function params, which
don't allow top-level or-patterns anyway.
2021-02-15 12:07:54 -06:00
bors
9503ea19ed Auto merge of #82103 - Dylan-DPC:rollup-5wv8rid, r=Dylan-DPC
Rollup of 11 pull requests

Successful merges:

 - #80523 (#[doc(inline)] sym_generated)
 - #80920 (Visit more targets when validating attributes)
 - #81720 (Updated smallvec version due to RUSTSEC-2021-0003)
 - #81891 ([rustdoc-json] Make `header` a vec of modifiers, and FunctionPointer consistent)
 - #81912 (Implement the precise analysis pass for lint `disjoint_capture_drop_reorder`)
 - #81914 (Fixing bad suggestion for `_` in `const` type when a function #81885)
 - #81919 (BTreeMap: fix internal comments)
 - #81927 (Add a regression test for #32498)
 - #81965 (Fix MIR pretty printer for non-local DefIds)
 - #82029 (Use debug log level for developer oriented logs)
 - #82056 (fix ice (#82032))

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2021-02-14 22:26:21 +00:00
klensy
93c8ebe022 bumped smallvec deps 2021-02-14 18:03:11 +03:00
Aaron Hill
3321d70161
Address review comments 2021-02-13 13:04:54 -05:00
Aaron Hill
0b411f56e1
Require passing an AttrWrapper to collect_tokens_trailing_token
This is a pure refactoring split out from #80689.
It represents the most invasive part of that PR, requiring changes in
every caller of `parse_outer_attributes`

In order to eagerly expand `#[cfg]` attributes while preserving the
original `TokenStream`, we need to know the range of tokens that
corresponds to every attribute target. This is accomplished by making
`parse_outer_attributes` return an opaque `AttrWrapper` struct. An
`AttrWrapper` must be converted to a plain `AttrVec` by passing it to
`collect_tokens_trailing_token`. This makes it difficult to accidentally
construct an AST node with attributes without calling `collect_tokens_trailing_token`,
since AST nodes store an `AttrVec`, not an `AttrWrapper`.

As a result, we now call `collect_tokens_trailing_token` for attribute
targets which only support inert attributes, such as generic arguments
and struct fields. Currently, the constructed `LazyTokenStream` is
simply discarded. Future PRs will record the token range corresponding
to the attribute target, allowing those tokens to be removed from an
enclosing `collect_tokens_trailing_token` call if necessary.
2021-02-13 12:07:15 -05:00
Ömer Sinan Ağacan
6eb1bd4c3e parser: Fix panic in 'const impl' recovery
The panic happens when in recovery parsing a full `impl`
(`parse_item_impl`) fails and we drop the `DiagnosticBuilder` for the
recovery suggestion and return the `parse_item_impl` error.

We now raise the original error "expected identifier found `impl`" when
parsing the `impl` fails.

Note that the regression test is slightly simplified version of the
original repro in #81806, to make the error output smaller and more
resilient to unrelated changes in parser error messages.

Fixes #81806
2021-02-08 10:46:19 +03:00
Vadim Petrochenkov
dbdbd30bf2 expand/resolve: Turn #[derive] into a regular macro attribute 2021-02-07 20:08:45 +03:00
Smitty
c6cb014ad6 Clarify error message wording 2021-02-07 11:02:53 -05:00
Smitty
651d289405 Add note about encoding when null bytes found 2021-02-06 19:17:14 -05:00
Mara Bos
8d49ca11a2
Rollup merge of #81307 - estebank:invalid-byte-str-span, r=petrochenkov
Handle `Span`s for byte and raw strings and add more detail

CC #81208.
2021-02-05 12:25:53 +01:00
Esteban Küber
3b5d018ebb Handle Spans for byte and raw strings and add more detail 2021-02-03 13:34:28 -08:00
bors
3182375e06 Auto merge of #81405 - bugadani:ast, r=cjgillot
Box the biggest ast::ItemKind variants

This PR is a different approach on https://github.com/rust-lang/rust/pull/81400, aiming to save memory in humongous ASTs.

The three affected item kind enums are:
 - `ast::ItemKind` (208 -> 112 bytes)
 - `ast::AssocItemKind` (176 -> 72 bytes)
 - `ast::ForeignItemKind` (176 -> 72 bytes)
2021-02-02 17:34:08 +00:00
bors
b81f5811f9 Auto merge of #80843 - Mark-Simulacrum:fmt-bump, r=petrochenkov
Bump rustfmt version
2021-02-02 14:52:53 +00:00
Mark Rousskov
d5b760ba62 Bump rustfmt version
Also switches on formatting of the mir build module
2021-02-02 09:09:52 -05:00
Jonas Schievink
255e0764c0
Rollup merge of #81608 - Aaron1011:macro-res-parse-err, r=davidtwco
Improve handling of spans around macro result parse errors

Fixes #81543

After we expand a macro, we try to parse the resulting tokens as a AST
node. This commit makes several improvements to how we handle spans when
an error occurs:

* Only ovewrite the original `Span` if it's a dummy span. This preserves
  a more-specific span if one is available.
* Use `self.prev_token` instead of `self.token` when emitting an error
  message after encountering EOF, since an EOF token always has a dummy
  span
* Make `SourceMap::next_point` leave dummy spans unused. A dummy span
  does not have a logical 'next point', since it's a zero-length span.
  Re-using the span span preserves its 'dummy-ness' for other checks
2021-02-02 12:15:02 +01:00
Dániel Buga
b87e1ecdf0 Box the biggest ast::ItemKind variants 2021-02-01 09:23:39 +01:00
Aaron Hill
6c14aad58e
Improve handling of spans around macro result parse errors
Fixes #81543

After we expand a macro, we try to parse the resulting tokens as a AST
node. This commit makes several improvements to how we handle spans when
an error occurs:

* Only ovewrite the original `Span` if it's a dummy span. This preserves
  a more-specific span if one is available.
* Use `self.prev_token` instead of `self.token` when emitting an error
  message after encountering EOF, since an EOF token always has a dummy
  span
* Make `SourceMap::next_point` leave dummy spans unused. A dummy span
  does not have a logical 'next point', since it's a zero-length span.
  Re-using the span span preserves its 'dummy-ness' for other checks
2021-01-31 15:24:34 -05:00
Jonas Schievink
3e8ae5dcba
Rollup merge of #81472 - Aaron1011:fix/revert-cursor-clone, r=petrochenkov
Clone entire `TokenCursor` when collecting tokens

Reverts PR #80830
Fixes taiki-e/pin-project#312

We can have an arbitrary number of `None`-delimited group frames pushed
on the stack due to proc-macro invocations, which can legally be exited.
Attempting to account for this would add a lot of complexity for a tiny
performance gain, so let's just use the original strategy.
2021-01-31 01:47:34 +01:00
Ikko Ashimine
718398ccaf
Fix typo in pat.rs
parentesized -> parenthesized
2021-01-29 23:30:55 +09:00
Aaron Hill
5d739180cd
Clone entire TokenCursor when collecting tokens
Reverts PR #80830
Fixes taiki-e/pin-project#312

We can have an arbitrary number of `None`-delimited group frames pushed
on the stack due to proc-macro invocations, which can legally be exited.
Attempting to account for this would add a lot of complexity for a tiny
performance gain, so let's just use the original strategy.
2021-01-28 09:47:59 -05:00
Esteban Küber
2e846d6f61 Point only at generic arguments when they are unexpected 2021-01-26 15:59:43 -08:00
Vadim Petrochenkov
bd07165690 parser: Collect tokens for values in key-value attributes 2021-01-24 17:11:56 +03:00
bors
1986b58c64 Auto merge of #80065 - b-naber:parse-angle-arg-diagnostics, r=petrochenkov
Improve diagnostics when parsing angle args

https://github.com/rust-lang/rust/pull/79266 introduced parsing of generic arguments in associated type constraints, this however resulted in possibly very confusing error messages in cases in which closing angle brackets were missing such as in `Vec<(u32, _, _) = vec![]`, which outputs an incorrectly parsed equality constraint error, as noted by `@cynecx.`

This PR tries to provide better error messages in such cases.

r? `@petrochenkov`
2021-01-23 06:27:21 +00:00
bors
693ed05bbd Auto merge of #81017 - Aaron1011:collect-trailing-token, r=petrochenkov
Refactor token collection to capture trailing token immediately

Split out from https://github.com/rust-lang/rust/pull/80689 - when we start capturing more information about attribute targets, we'll need to know in advance if we're capturing a trailing token or not.

r? `@ghost`
2021-01-23 00:42:37 +00:00
b-naber
728d257839 improve diagnostics for angle args 2021-01-22 17:07:27 +01:00
Esteban Küber
8c5dafdcb8 Parse loop labels missing a leading '
When encountering the following typo:

```rust
a: loop { break 'a; }
```

provide an appropriate suggestion.
2021-01-21 21:41:47 -08:00
Aaron Hill
ccfc292999
Refactor token collection to capture trailing token immediately 2021-01-22 00:33:03 -05:00
Reese Williams
8a83c8f64f Improve suggestion for tuple struct pattern matching errors.
Currently, when a user uses a struct pattern to pattern match on
a tuple struct, the errors we emit generally suggest adding fields
using their field names, which are numbers. However, numbers are
not valid identifiers, so the suggestions, which use the shorthand
notation, are not valid syntax. This commit changes those errors
to suggest using the actual tuple struct pattern syntax instead,
which is a more actionable suggestion.
2021-01-20 23:06:19 -05:00
Aaron Hill
11b1e37016
Force token collection to run when parsing nonterminals
Fixes #81007

Previously, we would fail to collect tokens in the proper place when
only builtin attributes were present. As a result, we would end up with
attribute tokens in the collected `TokenStream`, leading to duplication
when we attempted to prepend the attributes from the AST node.

We now explicitly track when token collection must be performed due to
nomterminal parsing.
2021-01-20 18:09:32 -05:00
Yuki Okushi
a584d87417
Rollup merge of #80944 - LingMan:map_or, r=nagisa
Use Option::map_or instead of `.map(..).unwrap_or(..)`

``@rustbot`` modify labels +C-cleanup +T-compiler
2021-01-15 18:26:14 +09:00
bors
dcf622eb70 Auto merge of #80993 - Aaron1011:collect-set-tokens, r=petrochenkov
Set tokens on AST node in `collect_tokens`

A new `HasTokens` trait is introduced, which is used to move logic from
the callers of `collect_tokens` into the body of `collect_tokens`.

In addition to reducing duplication, this paves the way for PR #80689,
which needs to perform additional logic during token collection.
2021-01-15 05:36:48 +00:00
LingMan
a56bffb4f9 Use Option::map_or instead of .map(..).unwrap_or(..) 2021-01-14 19:23:59 +01:00
Aaron Hill
a961e6785c
Set tokens on AST node in collect_tokens
A new `HasTokens` trait is introduced, which is used to move logic from
the callers of `collect_tokens` into the body of `collect_tokens`.

In addition to reducing duplication, this paves the way for PR #80689,
which needs to perform additional logic during token collection.
2021-01-13 22:10:36 -05:00
bors
a62a76047e Auto merge of #77524 - Patryk27:fixes/66228, r=estebank
Rework diagnostics for wrong number of generic args (fixes #66228 and #71924)

This PR reworks the `wrong number of {} arguments` message, so that it provides more details and contextual hints.
2021-01-13 20:35:58 +00:00
bors
467f5e99a5 Auto merge of #76580 - rokob:iss76011, r=estebank
Suggest async {} for async || {}

Fixes #76011

This adds support for adding help diagnostics to the feature gating checks and
then uses it for the async_closure gate to add the extra bit of help
information as described in the issue.
2021-01-12 02:56:51 +00:00
bors
080ee6f5d7 Auto merge of #80789 - Aaron1011:fix/stmt-empty, r=petrochenkov
Synthesize a `TokenStream` for `StmtKind::Empty`

Fixes #80760
2021-01-10 17:58:38 +00:00
Patryk Wychowaniec
d2f8e398f1
Rework diagnostics for wrong number of generic args 2021-01-10 13:07:40 +01:00
bors
f30733adb9 Auto merge of #80441 - petrochenkov:kwtok, r=Aaron1011
ast: Remove some indirection layers from values in key-value attributes

Trying to address some perf regressions from https://github.com/rust-lang/rust/pull/78837#issuecomment-745380762.
2021-01-09 22:19:46 +00:00
Aaron Hill
3ed6caae60
Synthesize a TokenStream for StmtKind::Empty
Fixes #80760
2021-01-09 14:54:14 -05:00
Vadim Petrochenkov
71cd6f42a6 ast: Remove some indirection layers from values in key-value attributes 2021-01-09 21:50:39 +03:00
Aaron Hill
7b36408b5f
Use an empty TokenCursorFrame stack when capturing tokens
We will never need to pop  past our starting frame during token
capturing. Using an empty stack allows us to avoid pointless heap
allocations/deallocations.
2021-01-08 18:16:20 -05:00
Yuki Okushi
d063745023 Add a note for * and {} usage on use 2021-01-08 17:36:14 +09:00
Vadim Petrochenkov
f915e3e5cf rustc_ast_pretty: Remove PrintState::insert_extra_parens
It's no longer necessary after #79472
2021-01-08 00:43:38 +03:00
Vadim Petrochenkov
0dab076358 rustc_parse: Better spans for synthesized token streams 2021-01-07 17:48:13 +03:00
Rémy Rakic
942b7ce2c1 make const_generics_defaults use the unstable syntax mechanism
This is important to not accidentally stabilize the parsing of the syntax while it still is experimental and not formally accepted
2021-01-01 11:01:01 +01:00
Julian Knodt
61f33bfd29 first pass at default values for const generics
- Adds optional default values to const generic parameters in the AST
  and HIR
- Parses these optional default values
- Adds a `const_generics_defaults` feature gate
2021-01-01 10:55:10 +01:00
Mara Bos
c574ded57d Consistently call editions "Rust 20xx" in messages. 2020-12-31 19:06:09 +01:00
Mara Bos
f16ef7d7ce Add edition 2021. 2020-12-31 19:06:09 +01:00
bors
44e3daf5ee Auto merge of #80459 - mark-i-m:or-pat-reg, r=petrochenkov
Implement edition-based macro :pat feature

This PR does two things:
1. Fixes the perf regression from https://github.com/rust-lang/rust/pull/80100#issuecomment-750893149
2. Implements `:pat2018` and `:pat2021` matchers, as described by `@joshtriplett`  in https://github.com/rust-lang/rust/issues/54883#issuecomment-745509090 behind the feature gate `edition_macro_pat`.

r? `@petrochenkov`

cc `@Mark-Simulacrum`
2020-12-31 14:52:26 +00:00
Mara Bos
9e8edc8c22
Rollup merge of #80495 - jyn514:rename-empty, r=petrochenkov
Rename kw::Invalid -> kw::Empty

See https://rust-lang.zulipchat.com/#narrow/stream/182449-t-compiler.2Fhelp/topic/Is.20there.20a.20symbol.20for.20the.20empty.20string.3F/near/220054471
for context.

r? `@petrochenkov`
2020-12-30 20:56:58 +00:00
mark
40bf3c0f09 Implement edition-based macro pat feature 2020-12-30 09:57:49 -06:00
Joshua Nelson
edeac1778c Rename kw::Invalid -> kw::Empty
See https://rust-lang.zulipchat.com/#narrow/stream/182449-t-compiler.2Fhelp/topic/Is.20there.20a.20symbol.20for.20the.20empty.20string.3F/near/220054471
for context.
2020-12-30 09:50:02 -05:00
Yuki Okushi
4ae99cc843 Fix ICE when pointing at multi bytes character 2020-12-30 22:33:13 +09:00
Aaron Hill
530a629635
Remove pretty-print/reparse hack, and add derive-specific hack 2020-12-29 09:36:42 -05:00
Dylan DPC
c51172f38a
Rollup merge of #80344 - matthiaskrgr:matches, r=Dylan-DPC
use matches!() macro in more places
2020-12-28 14:13:12 +01:00
Bastian Kauschke
06cc9c26da stabilize min_const_generics 2020-12-26 18:24:10 +01:00
Dylan DPC
299c2fc695
Rollup merge of #80160 - diondokter:move_async_fix, r=davidtwco
Implemented a compiler diagnostic for move async mistake

Fixes #79694

First time contributing, so I hope I'm doing everything right.
(If not, please correct me!)

This code performs a check when a move capture clause is parsed. The check is to detect if the user has reversed the async move keywords and to provide a diagnostic with a suggestion to fix it.

Checked code:
```rust
fn main() {
    move async { };
}
```

Previous output:
```txt
PS C:\Repos\move_async_test> cargo build
   Compiling move_async_test v0.1.0 (C:\Repos\move_async_test)
error: expected one of `|` or `||`, found keyword `async`
 --> src\main.rs:2:10
  |
2 |     move async { };
  |          ^^^^^ expected one of `|` or `||`

error: aborting due to previous error

error: could not compile `move_async_test`
```

New output:
```txt
PS C:\Repos\move_async_test> cargo +dev build
   Compiling move_async_test v0.1.0 (C:\Repos\move_async_test)
error: the order of `move` and `async` is incorrect
 --> src\main.rs:2:13
  |
2 |     let _ = move async { };
  |             ^^^^^^^^^^
  |
help: try switching the order
  |
2 |     let _ = async move { };
  |             ^^^^^^^^^^

error: aborting due to previous error

error: could not compile `move_async_test`
```

Is there a file/module where these kind of things are tested?
Would love some feedback 😄
2020-12-25 03:39:35 +01:00
Matthias Krüger
d12a358673 use matches!() macro in more places 2020-12-24 13:35:12 +01:00
Dion Dokter
a272d621bc Implemented a compiler diagnostic for move async mistake
Ran the tidy check

Following the diagnostic guide better

Diagnostic generation is now relegated to its own function in the diagnostics module.
Added tests

Fixed the ui test
2020-12-21 12:57:08 +01:00
mark
1a7d00a529 implement edition-specific :pat behavior for 2015/18 2020-12-19 07:13:36 -06:00
bors
d1741e59cb Auto merge of #77035 - mibac138:fn-fat-arrow-return, r=davidtwco
Gracefully handle mistyping -> as => in function return type

Fixes #77019
2020-12-19 01:47:05 +00:00
Camelid
d6f1787447 Don't allow const to begin a nonterminal
Thanks to Vadim Petrochenkov who [told me what the fix was][z]!

[z]: https://rust-lang.zulipchat.com/#narrow/stream/182449-t-compiler.2Fhelp/topic/finding.20which.20macro.20rule.20to.20use/near/220240422
2020-12-17 13:58:56 -08:00
mibac138
e916641fd3 Address review comments 2020-12-17 14:12:48 +01:00
bors
803c60218f Auto merge of #79978 - Aaron1011:fix/capture-broken-token, r=petrochenkov
Properly capture trailing 'unglued' token

If we try to capture the `Vec<u8>` in `Option<Vec<u8>>`, we'll
need to capture a `>` token which was 'unglued' from a `>>` token.
The processing of unglueing a token for parsing purposes bypasses the
usual capturing infrastructure, so we currently lose the trailing `>`.
As a result, we fall back to the reparsed `TokenStream`, causing us to
lose spans.

This commit makes token capturing keep track of a trailing 'unglued'
token. Note that we don't need to care about unglueing except at the end
of the captured tokens - if we capture both the first and second unglued
tokens, then we'll end up capturing the full 'glued' token, which
already works correctly.
2020-12-13 19:31:06 +00:00
bors
057937bdda Auto merge of #79668 - coolreader18:recover-const-impl, r=petrochenkov
Recover on `const impl<> X for Y`

`@leonardo-m` mentioned that `const impl Foo for Bar` could be recovered from in #79287.

I'm not sure about the error strings as they are, I think it should probably be something like the error that `expected_one_of_not_found` makes + the suggestion to flip the keywords, but I'm not sure how exactly to do that. Also, I decided not to try to handle `const unsafe impl` or `unsafe const impl` cause I figured that `unsafe impl const` would be pretty rare anyway (if it's even valid?), and it wouldn't be worth making the code more messy.
2020-12-13 10:52:29 +00:00
Aaron Hill
e6fa6334dd
Properly capture trailing 'unglued' token
If we try to capture the `Vec<u8>` in `Option<Vec<u8>>`, we'll
need to capture a `>` token which was 'unglued' from a `>>` token.
The processing of unglueing a token for parsing purposes bypasses the
usual capturing infrastructure, so we currently lose the trailing `>`.
As a result, we fall back to the reparsed `TokenStream`, causing us to
lose spans.

This commit makes token capturing keep track of a trailing 'unglued'
token. Note that we don't need to care about unglueing except at the end
of the captured tokens - if we capture both the first and second unglued
tokens, then we'll end up capturing the full 'glued' token, which
already works correctly.
2020-12-12 16:28:13 -05:00
Noah
1e27b65d8e
Recover on const impl<> X for Y 2020-12-12 14:45:54 -06:00
Vadim Petrochenkov
31d72c2658 Accept arbitrary expressions in key-value attributes at parse time 2020-12-09 21:37:32 +03:00
Ryan Levick
823f64532c A slightly clearer diagnostic when misusing 2020-12-04 11:33:30 +01:00
mibac138
3548be94c0 Gracefully handle confusing -> with : in function return type 2020-12-03 18:19:42 +01:00
bors
f4db9ffb22 Auto merge of #79364 - nico-abram:unstable-or-pat-suggestion, r=matthewjasper
Fixes #79357 unstable or-pat suggestions

Fixes #79357
2020-12-02 20:33:55 +00:00
mibac138
5404deeb64 Gracefully handle mistyping -> as => in function return type 2020-12-01 12:12:48 +01:00
bors
28b86e0860 Auto merge of #79329 - camelid:int-lit-suffix-error, r=davidtwco
Update error to reflect that integer literals can have float suffixes

For example, `1` is parsed as an integer literal, but it can be turned
into a float with the suffix `f32`. Now the error calls them "numeric
literals" and notes that you can add a float suffix since they can be
either integers or floats.
2020-11-30 01:42:14 +00:00
unknown
de3a0bdf05 Fixes #79357 unstable or-pat suggestions 2020-11-29 15:31:45 -03:00
Jonas Schievink
a732c3a369
Rollup merge of #78853 - calebcartwright:fix-const-block-expr-span, r=spastorino
rustc_parse: fix ConstBlock expr span

The span for a ConstBlock expression should presumably run through the end of the block it contains and not stop at the keyword, just like is done with similar block-containing expression kinds, such as a TryBlock
2020-11-28 15:58:15 +01:00
bors
4ae328bef4 Auto merge of #78296 - Aaron1011:fix/stmt-tokens, r=petrochenkov
Properly handle attributes on statements

We now collect tokens for the underlying node wrapped by `StmtKind`
nstead of storing tokens directly in `Stmt`.

`LazyTokenStream` now supports capturing a trailing semicolon after it
is initially constructed. This allows us to avoid refactoring statement
parsing to wrap the parsing of the semicolon in `parse_tokens`.

Attributes on item statements
(e.g. `fn foo() { #[bar] struct MyStruct; }`) are now treated as
item attributes, not statement attributes, which is consistent with how
we handle attributes on other kinds of statements. The feature-gating
code is adjusted so that proc-macro attributes are still allowed on item
statements on stable.

Two built-in macros (`#[global_allocator]` and `#[test]`) needed to be
adjusted to support being passed `Annotatable::Stmt`.
2020-11-28 07:48:56 +00:00
Camelid
a3cde636fc Update error to reflect that integer literals can have float suffixes
For example, `1` is parsed as an integer literal, but it can be turned
into a float with the suffix `f32`. Now the error calls them "numeric
literals" and notes that you can add a float suffix since they can be
either integers or floats.
2020-11-27 19:08:24 -08:00
bors
361543d776 Auto merge of #79433 - calebcartwright:parse-attr-vis, r=petrochenkov
rustc_parse: restore public visibility on parse_attribute

Make `parse_attribute` public as rustfmt is a downstream consumer. Refs https://github.com/rust-lang/rust/pull/78782#discussion_r530658904

r? `@petrochenkov`
2020-11-27 11:23:11 +00:00
bors
cfed9184f4 Auto merge of #79266 - b-naber:gat_trait_path_parser, r=petrochenkov
Generic Associated Types in Trait Paths - Ast part

The Ast part of https://github.com/rust-lang/rust/pull/78978

r? `@petrochenkov`
2020-11-27 00:18:24 +00:00
Aaron Hill
758834d3e2
Only eat semicolons for statements that need them
When parsing a statement (e.g. inside a function body),
we now consider `struct Foo {};` and `$stmt;` to each consist
of two statements: `struct Foo {}` and `;`, and `$stmt` and `;`.

As a result, an attribute macro invoke as
`fn foo() { #[attr] struct Bar{}; }` will see `struct Bar{}` as its
input. Additionally, the 'unused semicolon' lint now fires in more
places.
2020-11-26 17:08:35 -05:00
Aaron Hill
de88bf148b
Properly handle attributes on statements
We now collect tokens for the underlying node wrapped by `StmtKind`
instead of storing tokens directly in `Stmt`.

`LazyTokenStream` now supports capturing a trailing semicolon after it
is initially constructed. This allows us to avoid refactoring statement
parsing to wrap the parsing of the semicolon in `parse_tokens`.

Attributes on item statements
(e.g. `fn foo() { #[bar] struct MyStruct; }`) are now treated as
item attributes, not statement attributes, which is consistent with how
we handle attributes on other kinds of statements. The feature-gating
code is adjusted so that proc-macro attributes are still allowed on item
statements on stable.

Two built-in macros (`#[global_allocator]` and `#[test]`) needed to be
adjusted to support being passed `Annotatable::Stmt`.
2020-11-26 17:08:35 -05:00
bors
cb56a4420c Auto merge of #79338 - Aaron1011:fix/token-reparse-cache, r=petrochenkov
Cache pretty-print/retokenize result to avoid compile time blowup

Fixes #79242

If a `macro_rules!` recursively builds up a nested nonterminal
(passing it to a proc-macro at each step), we will end up repeatedly
pretty-printing/retokenizing the same nonterminals. Unfortunately, the
'probable equality' check we do has a non-trivial cost, which leads to a
blowup in compilation time.

As a workaround, we cache the result of the 'probable equality' check,
which eliminates the compilation time blowup for the linked issue. This
commit only touches a single file (other than adding tests), so it
should be easy to backport.

The proper solution is to remove the pretty-print/retokenize hack
entirely. However, this will almost certainly break a large number of
crates that were relying on hygiene bugs created by using the reparsed
`TokenStream`. As a result, we will definitely not want to backport
such a change.
2020-11-26 22:02:45 +00:00
Caleb Cartwright
5930a8ab12 rustc_parse: restore pub vis on parse_attribute 2020-11-26 12:54:09 -06:00
b-naber
823dbb38e4 ast and parser 2020-11-25 19:55:41 +01:00
Aaron Hill
6e466efa11
Cache pretty-print/retokenize result to avoid compile time blowup
Fixes #79242

If a `macro_rules!` recursively builds up a nested nonterminal
(passing it to a proc-macro at each step), we will end up repeatedly
pretty-printing/retokenizing the same nonterminals. Unfortunately, the
'probable equality' check we do has a non-trivial cost, which leads to a
blowup in compilation time.

As a workaround, we cache the result of the 'probable equality' check,
which eliminates the compilation time blowup for the linked issue. This
commit only touches a single file (other than adding tests), so it
should be easy to backport.

The proper solution is to remove the pretty-print/retokenize hack
entirely. However, this will almost certainly break a large number of
crates that were relying on hygiene bugs created by using the reparsed
`TokenStream`. As a result, we will definitely not want to backport
such a change.
2020-11-23 02:40:57 -05:00
Mara Bos
41c033b2f7
Rollup merge of #79299 - varkor:stabilise-then, r=m-ou-se
Stabilise `then`

Stabilises the lazy variant of https://github.com/rust-lang/rust/issues/64260 now that the FCP [has ended](https://github.com/rust-lang/rust/issues/64260#issuecomment-731636203).

I've kept the original feature gate `bool_to_option` for the strict variant (`then_some`), and created a new insta-stable feature gate `lazy_bool_to_option` for `then`.
2020-11-22 23:01:08 +01:00
varkor
cf32afcf48 Stabilise then 2020-11-22 13:45:14 +00:00
Nicolas
7be6d67f82
Fix typo in doc comment for report_too_many_hashes
"to big" -> "too big"
2020-11-22 07:02:58 -03:00
Dylan DPC
8216b359e5
Rollup merge of #79185 - petrochenkov:derattr2, r=Aaron1011
expand/resolve: Pre-requisites to "Turn `#[derive]` into a regular macro attribute"

Miscellaneous refactorings and error reporting changes extracted from https://github.com/rust-lang/rust/pull/79078.

Unlike https://github.com/rust-lang/rust/pull/79078 this PR doesn't make any observable changes to the language or library.
r? ```@Aaron1011```
2020-11-19 23:58:42 +01:00
Vadim Petrochenkov
dfb690eaa9 resolve/expand: Misc cleanup 2020-11-19 19:25:20 +03:00
varkor
efcbf1b00b Permit standalone generic parameters as const generic arguments in macros 2020-11-18 13:16:35 +00:00
Jonas Schievink
f66af28641
Rollup merge of #79016 - fanzier:underscore-expressions, r=petrochenkov
Make `_` an expression, to discard values in destructuring assignments

This is the third and final step towards implementing destructuring assignment (RFC: rust-lang/rfcs#2909, tracking issue: #71126). This PR is the third and final part of #71156, which was split up to allow for easier review.

With this PR, an underscore `_` is parsed as an expression but is allowed *only* on the left-hand side of a destructuring assignment. There it simply discards a value, similarly to the wildcard `_` in patterns. For instance,
```rust
(a, _) = (1, 2)
```
will simply assign 1 to `a` and discard the 2. Note that for consistency,
```
_ = foo
```
is also allowed and equivalent to just `foo`.

Thanks to ````@varkor```` who helped with the implementation, particularly around pre-expansion gating.

r? ````@petrochenkov````
2020-11-15 13:39:48 +01:00
Fabian Zaiser
8cf3564310 Add underscore expressions for destructuring assignments
Co-authored-by: varkor <github@varkor.com>
2020-11-14 13:53:12 +00:00
bors
50d3c2a3cb Auto merge of #78736 - petrochenkov:lazyenum, r=Aaron1011
rustc_parse: Remove optimization for 0-length streams in `collect_tokens`

The optimization conflates empty token streams with unknown token stream, which is at least suspicious, and doesn't affect performance because 0-length token streams are very rare.

r? `@Aaron1011`
2020-11-14 04:21:56 +00:00
Vadim Petrochenkov
2879ab793e rustc_parse: Remove optimization for 0-length streams in collect_tokens
The optimization conflates empty token streams with unknown token stream, which is at least suspicious, and doesn't affect performance because 0-length token streams are very rare.
2020-11-12 22:00:48 +03:00
Mara Bos
755dd14e00
Rollup merge of #78836 - fanzier:struct-and-slice-destructuring, r=petrochenkov
Implement destructuring assignment for structs and slices

This is the second step towards implementing destructuring assignment (RFC: rust-lang/rfcs#2909, tracking issue: #71126). This PR is the second part of #71156, which was split up to allow for easier review.

Note that the first PR (#78748) is not merged yet, so it is included as the first commit in this one. I thought this would allow the review to start earlier because I have some time this weekend to respond to reviews. If ``@petrochenkov`` prefers to wait until the first PR is merged, I totally understand, of course.

This PR implements destructuring assignment for (tuple) structs and slices. In order to do this, the following *parser change* was necessary: struct expressions are not required to have a base expression, i.e. `Struct { a: 1, .. }` becomes legal (in order to act like a struct pattern).

Unfortunately, this PR slightly regresses the diagnostics implemented in #77283. However, it is only a missing help message in `src/test/ui/issues/issue-77218.rs`. Other instances of this diagnostic are not affected. Since I don't exactly understand how this help message works and how to fix it yet, I was hoping it's OK to regress this temporarily and fix it in a follow-up PR.

Thanks to ``@varkor`` who helped with the implementation, particularly around the struct rest changes.

r? ``@petrochenkov``
2020-11-12 19:46:09 +01:00
bors
5a6a41e784 Auto merge of #78782 - petrochenkov:nodoctok, r=Aaron1011
Do not collect tokens for doc comments

Doc comment is a single token and AST has all the information to re-create it precisely.
Doc comments are also responsible for majority of calls to `collect_tokens` (with `num_calls == 1` and `num_calls == 0`, cc https://github.com/rust-lang/rust/pull/78736).

(I also moved token collection into `fn parse_attribute` to deduplicate code a bit.)

r? `@Aaron1011`
2020-11-12 00:33:55 +00:00