Commit Graph

1083 Commits

Author SHA1 Message Date
Nicholas Nethercote 53fe37de2e Remove unused `Span` from the `set` function in `State::Active`. 2023-10-05 10:18:29 +11:00
Camille GILLOT 717dc1ce21 Enable incremental-relative-spans by default. 2023-09-07 20:21:13 +00:00
Mark Rousskov 0a916062aa Bump cfg(bootstrap) 2023-08-23 20:05:14 -04:00
bors ee5cb9e3a6 Auto merge of #114915 - nnethercote:Nonterminal-cleanups, r=petrochenkov
`Nonterminal`-related cleanups

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

r? `@petrochenkov`
2023-08-18 16:07:40 +00:00
Nicholas Nethercote 9e22351c74 Rename `NtOrTt` as `ParseNtResult`.
It's more descriptive, and future-proofs it if/when additional variants
get added.
2023-08-18 16:50:41 +10:00
Caio 6395dc2cde [RFC-3086] Restrict the parsing of `count` 2023-08-17 08:52:37 -03:00
Nicholas Nethercote acd3a5e35f Remove unnecessary braces on `PatWithOr` patterns. 2023-08-17 09:04:54 +10:00
Nicholas Nethercote 9de696b39f Remove some unnecessary (and badly named) local variables. 2023-08-17 08:26:55 +10:00
Vadim Petrochenkov 7353c96be8 rustc: Move `features` from `Session` to `GlobalCtxt`
Removes two pieces of mutable state.
Follow up to #114622.
2023-08-11 16:51:50 +08:00
bors fe896efa97 Auto merge of #114104 - oli-obk:syn2, r=compiler-errors
Lots of tiny incremental simplifications of `EmitterWriter` internals

ignore the first commit, it's https://github.com/rust-lang/rust/pull/114088 squashed and rebased, but it's needed to use to use `derive_setters`, as they need a newer `syn` version.

Then this PR starts out with removing many arguments that are almost always defaulted to `None` or `false` and replace them with builder methods that can set these fields in the few cases that want to set them.

After that it's one commit after the other that removes or merges things until everything becomes some very simple trait objects
2023-08-04 18:46:19 +00:00
Nilstrieb 5830ca216d Add `internal_features` lint
It lints against features that are inteded to be internal to the
compiler and standard library. Implements MCP #596.

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

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

We always pass `-Ainternal_features` in the testsuite
About 400 UI tests and several other tests use internal features.
Instead of throwing the attribute on each one, just always allow them.
There's nothing wrong with testing internal features^^
2023-08-03 14:50:50 +02:00
Nicholas Nethercote d75ee2a6bc Remove `MacDelimiter`.
It's the same as `Delimiter`, minus the `Invisible` variant. I'm
generally in favour of using types to make impossible states
unrepresentable, but this one feels very low-value, and the conversions
between the two types are annoying and confusing.

Look at the change in `src/tools/rustfmt/src/expr.rs` for an example:
the old code converted from `MacDelimiter` to `Delimiter` and back
again, for no good reason. This suggests the author was confused about
the types.
2023-08-03 09:03:30 +10:00
bors d12c6e947c Auto merge of #114273 - nnethercote:move-doc-comment-desugaring, r=petrochenkov
Move doc comment desugaring out of `TokenCursor`.

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

r? `@petrochenkov`
2023-08-01 21:27:48 +00:00
Oli Scherer 51c22154f5 Remove a `bool` for color in favor of the `WriteColor` trait wrapping colored and uncolored printing 2023-07-31 09:34:36 +00:00
Oli Scherer 0e7ec9683d Use builder pattern instead of lots of arguments for `EmitterWriter::new` 2023-07-31 09:34:30 +00:00
Nicholas Nethercote 2e6ce68fba Remove `desugar_doc_comments` arg from `Parser::new()`.
It's only true at one call site; do the desugaring there instead.
2023-07-31 14:47:08 +10:00
Nicholas Nethercote c70c8b7196 No need to desugar doc comments when parsing decl macro definitions. 2023-07-31 11:21:30 +10:00
Nicholas Nethercote a8909b059f Reflow an overlong comment. 2023-07-31 11:21:24 +10:00
Nicholas Nethercote d16b1f4a8c Remove more unnecessary `return` keywords. 2023-07-31 11:14:39 +10:00
Matthias Krüger 23815467a2 inline format!() args up to and including rustc_middle 2023-07-30 13:18:33 +02:00
León Orell Valerian Liehr afd009a8d8
Parse generic const items 2023-07-28 22:21:33 +02:00
bors 0699d99516 Auto merge of #114115 - nnethercote:less-token-tree-cloning, r=petrochenkov
Less `TokenTree` cloning

`TokenTreeCursor` has this comment on it:
```
// FIXME: Many uses of this can be replaced with by-reference iterator to avoid clones.
```
This PR completes that FIXME. It doesn't have much perf effect, but at least we now know that.

r? `@petrochenkov`
2023-07-28 01:21:27 +00:00
Nicholas Nethercote 4ebf2be8bb Remove `Iterator` impl for `TokenTreeCursor`.
This is surprising, but the new comment explains why. It's a logical
conclusion in the drive to avoid `TokenTree` clones.

`TokenTreeCursor` is now only used within `Parser`. It's still needed
due to `replace_prev_and_rewind`.
2023-07-27 11:59:03 +10:00
Nicholas Nethercote d2f7f67921 Avoid some token tree cloning in decl macro parsing.
By changing `into_trees` into `trees`. Some of the subsequent paths
require explicit clones, but not all.
2023-07-27 11:58:42 +10:00
Nicholas Nethercote a9d8459299 Replace `into_trees` with `trees` in a test.
There's no need for token tree cloning here.
2023-07-27 10:40:39 +10:00
Nicholas Nethercote 53379a7b65 Simplify the `ttdelim_span` test.
The existing code is a very complex and inefficient way to the get the
span of the last token.
2023-07-27 09:41:49 +10:00
Eric Huss 9914ae3292 Squelch a noisy rustc_expand unittest 2023-07-26 08:12:08 -07:00
Oli Scherer 2b444672e1 Use a builder instead of boolean/option arguments 2023-07-25 13:51:15 +00:00
Oli Scherer d97ec97b94 Don't translate compiler-internal bug messages 2023-07-20 09:51:47 +00:00
bors a6cdd81eff Auto merge of #108714 - estebank:ice_dump, r=oli-obk
On nightly, dump ICE backtraces to disk

Implement rust-lang/compiler-team#578.

When an ICE is encountered on nightly releases, the new rustc panic handler will also write the contents of the backtrace to disk. If any `delay_span_bug`s are encountered, their backtrace is also added to the file. The platform and rustc version will also be collected.

<img width="1032" alt="Screenshot 2023-03-03 at 2 13 25 PM" src="https://user-images.githubusercontent.com/1606434/222842420-8e039740-4042-4563-b31d-599677171acf.png">

The current behavior will *always* write to disk on nightly builds, regardless of whether the backtrace is printed to the terminal, unless the environment variable `RUSTC_ICE_DISK_DUMP` is set to `0`. This is a compromise and can be changed.
2023-07-20 01:29:17 +00:00
Michael Goulet 846cc63e38 Make it clearer that edition functions are >=, not == 2023-07-19 16:38:35 +00:00
Esteban Küber 8eb5843a59 On nightly, dump ICE backtraces to disk
Implement rust-lang/compiler-team#578.

When an ICE is encountered on nightly releases, the new rustc panic
handler will also write the contents of the backtrace to disk. If any
`delay_span_bug`s are encountered, their backtrace is also added to the
file. The platform and rustc version will also be collected.
2023-07-19 14:10:07 +00:00
Mark Rousskov cc907f80b9 Re-format let-else per rustfmt update 2023-07-12 21:49:27 -04:00
The 8472 14e57d7c13 perform TokenStream replacement in-place when possible in expand_macro 2023-07-03 13:29:15 +02:00
Dylan DPC fa56e01b35
Rollup merge of #111571 - jhpratt:proc-macro-span, r=m-ou-se
Implement proposed API for `proc_macro_span`

As proposed in [#54725 (comment)](https://github.com/rust-lang/rust/issues/54725#issuecomment-1546918161). I have omitted the byte-level API as it's already available as [`Span::byte_range`](https://doc.rust-lang.org/nightly/proc_macro/struct.Span.html#method.byte_range).

`@rustbot` label +A-proc-macros

r? `@m-ou-se`
2023-06-28 18:28:46 +05:30
Matthias Krüger d505582ce2
Rollup merge of #113084 - WaffleLapkin:less_map_or, r=Nilstrieb
Simplify some conditions

r? `@Nilstrieb`

Some things taken out of my `is_none_or` pr.
2023-06-27 22:10:15 +02:00
Maybe Waffle ef05533c39 Simplify some conditions 2023-06-27 07:40:47 +00:00
Raminder Singh 91aef00e51 Fix msg passed to span_bug 2023-06-21 16:54:54 +05:30
Jacob Pratt a1cd8c3a28
Add `Span::{line, column}` 2023-06-20 19:40:25 -04:00
Jacob Pratt 87ec0738ab
`Span::{before, after}` → `Span::{start, end}` 2023-06-20 19:40:25 -04:00
Jacob Pratt dc76991d2f
Remove `LineColumn`, `Span::start`, `Span::end` 2023-06-20 19:40:24 -04:00
Maybe Waffle 73c5c97de7 Add `SyntaxContext::is_root` 2023-06-16 13:47:42 +00:00
Vadim Petrochenkov 46becfdf9c expand: Change how `#![cfg(FALSE)]` behaves on crate root
Previously it removed all other attributes from the crate root.
Now it removes only attributes below itself.

So it becomes possible to configure some global crate properties even for fully unconfigured crates.
2023-06-10 00:35:21 +03:00
Guillaume Gomez b3d1a83311
Rollup merge of #112396 - WaffleLapkin:track_more_diagnostics, r=compiler-errors
Track more diagnostics in `rustc_expand`

I wish we could lint this somehow...
2023-06-08 10:15:13 +02:00
Maybe Waffle c38d80ee9f Track more diagnostics in `rustc_expand` 2023-06-07 19:08:50 +00:00
bors a97c36dd2e Auto merge of #109005 - Nilstrieb:dont-forgor-too-much-from-cfg, r=petrochenkov
Remember names of `cfg`-ed out items to mention them in diagnostics

# Examples

## `serde::Deserialize` without the `derive` feature (a classic beginner mistake)

I had to slightly modify serde so that it uses explicit re-exports instead of a glob re-export. (Update: a serde PR was merged that adds the manual re-exports)

```
error[E0433]: failed to resolve: could not find `Serialize` in `serde`
   --> src/main.rs:1:17
    |
1   | #[derive(serde::Serialize)]
    |                 ^^^^^^^^^ could not find `Serialize` in `serde`
    |
note: crate `serde` has an item named `Serialize` but it is inactive because its cfg predicate evaluated to false
   --> /home/gh-Nilstrieb/.cargo/registry/src/index.crates.io-6f17d22bba15001f/serde-1.0.160/src/lib.rs:343:1
    |
343 | #[cfg(feature = "serde_derive")]
    | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
344 | pub use serde_derive::{Deserialize, Serialize};
    |                                     ^^^^^^^^^
    = note: the item is gated behind the `serde_derive` feature
    = note: see https://doc.rust-lang.org/cargo/reference/features.html for how to activate a crate's feature
```
(the suggestion is not ideal but that's serde's fault)

I already tested the metadata size impact locally by compiling the `windows` crate without any features. `800k`  -> `809k`

r? `@ghost`
2023-06-07 17:38:57 +00:00
bohan 5eafab30ba feat(expand): emit note for doc comment in macro matcher 2023-06-07 10:20:36 +08:00
bohan c927743b7b fix(expand): prevent infinity loop in macro containing only "///" 2023-06-06 23:11:08 +08:00
Nilstrieb a647ba250a Remember names of `cfg`-ed out items to mention them in diagnostics
`#[cfg]`s are frequently used to gate crate content behind cargo
features. This can lead to very confusing errors when features are
missing. For example, `serde` doesn't have the `derive` feature by
default. Therefore, `serde::Serialize` fails to resolve with a generic
error, even though the macro is present in the docs.

This commit adds a list of all stripped item names to metadata. This is
filled during macro expansion and then, through a fed query, persisted
in metadata. The downstream resolver can then access the metadata to
look at possible candidates for mentioning in the errors.

This slightly increases metadata (800k->809k for the feature-heavy
windows crate), but not enough to really matter.
2023-06-01 19:17:19 +02:00
Nicholas Nethercote 781111ef35 Use `Cow` in `{D,Subd}iagnosticMessage`.
Each of `{D,Subd}iagnosticMessage::{Str,Eager}` has a comment:
```
// FIXME(davidtwco): can a `Cow<'static, str>` be used here?
```
This commit answers that question in the affirmative. It's not the most
compelling change ever, but it might be worth merging.

This requires changing the `impl<'a> From<&'a str>` impls to `impl
From<&'static str>`, which involves a bunch of knock-on changes that
require/result in call sites being a little more precise about exactly
what kind of string they use to create errors, and not just `&str`. This
will result in fewer unnecessary allocations, though this will not have
any notable perf effects given that these are error paths.

Note that I was lazy within Clippy, using `to_string` in a few places to
preserve the existing string imprecision. I could have used `impl
Into<{D,Subd}iagnosticMessage>` in various places as is done in the
compiler, but that would have required changes to *many* call sites
(mostly changing `&format("...")` to `format!("...")`) which didn't seem
worthwhile.
2023-05-29 09:23:43 +10:00
clubby789 f97fddab91 Ensure Fluent messages are in alphabetical order 2023-05-25 23:49:35 +00:00
Maybe Waffle fb0f74a8c9 Use `Option::is_some_and` and `Result::is_ok_and` in the compiler 2023-05-24 14:20:41 +00:00
bohan 990b2899ad fix: emit error when fragment is `MethodReceiverExpr` and items is empty 2023-05-19 21:21:05 +08:00
Nicholas Nethercote 01e33a3600 Avoid `&format("...")` calls in error message code.
Error message all end up passing into a function as an `impl
Into<{D,Subd}iagnosticMessage>`. If an error message is creatd as
`&format("...")` that means we allocate a string (in the `format!`
call), then take a reference, and then clone (allocating again) the
reference to produce the `{D,Subd}iagnosticMessage`, which is silly.

This commit removes the leading `&` from a lot of these cases. This
means the original `String` is moved into the
`{D,Subd}iagnosticMessage`, avoiding the double allocations. This
requires changing some function argument types from `&str` to `String`
(when all arguments are `String`) or `impl
Into<{D,Subd}iagnosticMessage>` (when some arguments are `String` and
some are `&str`).
2023-05-16 17:59:56 +10:00
SparrowLii b9746ce039 introduce `DynSend` and `DynSync` auto trait 2023-05-06 09:34:18 +08:00
Dylan DPC 4891f02cff
Rollup merge of #108801 - fee1-dead-contrib:c-str, r=compiler-errors
Implement RFC 3348, `c"foo"` literals

RFC: https://github.com/rust-lang/rfcs/pull/3348
Tracking issue: #105723
2023-05-05 18:40:33 +05:30
bors 74c4821045 Auto merge of #111014 - klensy:no-rc, r=WaffleLapkin
try to downgrade Arc -> Lrc -> Rc -> no-Rc in few places

Expecting this be not slower on non-parallel compiler and probably faster on parallel (checked that this PR builds on it).
2023-05-04 20:49:23 +00:00
Nicholas Nethercote 6b62f37402 Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.

This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.

As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-05-03 08:44:39 +10:00
Deadbeef a49570fd20 fix TODO comments 2023-05-02 10:32:07 +00:00
Deadbeef 8ff3903643 initial step towards implementing C string literals 2023-05-02 10:30:09 +00:00
Nilstrieb c63b6a437e Rip it out
My type ascription
Oh rip it out
Ah
If you think we live too much then
You can sacrifice diagnostics
Don't mix your garbage
Into my syntax
So many weird hacks keep diagnostics alive
Yet I don't even step outside
So many bad diagnostics keep tyasc alive
Yet tyasc doesn't even bother to survive!
2023-05-01 16:15:13 +08:00
klensy 07266362c6 Lrc -> Rc 2023-04-30 13:24:10 +03:00
clubby789 0138513635 Fix static string lints 2023-04-25 18:59:55 +01:00
bors 1151ea6006 Auto merge of #109002 - michaelvanstraten:master, r=petrochenkov
Added byte position range for `proc_macro::Span`

Currently, the [`Debug`](https://doc.rust-lang.org/beta/proc_macro/struct.Span.html#impl-Debug-for-Span) implementation for [`proc_macro::Span`](https://doc.rust-lang.org/beta/proc_macro/struct.Span.html#) calls the debug function implemented in the trait implementation of `server::Span` for the type `Rustc` in the `rustc-expand` crate.

The current implementation, of the referenced function, looks something like this:
```rust
fn debug(&mut self, span: Self::Span) -> String {
    if self.ecx.ecfg.span_debug {
        format!("{:?}", span)
    } else {
        format!("{:?} bytes({}..{})", span.ctxt(), span.lo().0, span.hi().0)
    }
}
```

It returns the byte position of the [`Span`](https://doc.rust-lang.org/beta/proc_macro/struct.Span.html#) as an interpolated string.

Because this is currently the only way to get a spans position in the file, I might lead someone, who is interested in this information, to parsing this interpolated string back into a range of bytes, which I think is a very non-rusty way.

The proposed `position()`, method implemented in this PR, gives the ability to directly get this info.
It returns a [`std::ops::Range`](https://doc.rust-lang.org/std/ops/struct.Range.html#) wrapping the lowest and highest byte of the [`Span`](https://doc.rust-lang.org/beta/proc_macro/struct.Span.html#).

I put it behind the `proc_macro_span` feature flag because many of the other functions that have a similar footprint also are annotated with it, I don't actually know if this is right.

It would be great if somebody could take a look at this, thank you very much in advanced.
2023-04-21 10:47:27 +00:00
Michael van Straten 342c5fb6c5 Fixed bad formating 2023-04-19 13:04:01 +02:00
Michael van Straten 3d49cc1198 Translated absolute byte offset to relative 2023-04-19 13:02:30 +02:00
bors d7f9e81650 Auto merge of #110407 - Nilstrieb:fluent-macro, r=davidtwco
Add `rustc_fluent_macro` to decouple fluent from `rustc_macros`

Fluent, with all the icu4x it brings in, takes quite some time to compile. `fluent_messages!` is only needed in further downstream rustc crates, but is blocking more upstream crates like `rustc_index`. By splitting it out, we allow `rustc_macros` to be compiled earlier, which speeds up `x check compiler` by about 5 seconds (and even more after the needless dependency on `serde_json` is removed from `rustc_data_structures`).
2023-04-19 08:26:47 +00:00
Nilstrieb b5d3d970fa Add `rustc_fluent_macro` to decouple fluent from `rustc_macros`
Fluent, with all the icu4x it brings in, takes quite some time to
compile. `fluent_messages!` is only needed in further downstream rustc
crates, but is blocking more upstream crates like `rustc_index`. By
splitting it out, we allow `rustc_macros` to be compiled earlier, which
speeds up `x check compiler` by about 5 seconds (and even more after the
needless dependency on `serde_json` is removed from
`rustc_data_structures`).
2023-04-18 18:56:22 +00:00
Josh Soref e09d0d2a29 Spelling - compiler
* account
* achieved
* advising
* always
* ambiguous
* analysis
* annotations
* appropriate
* build
* candidates
* cascading
* category
* character
* clarification
* compound
* conceptually
* constituent
* consts
* convenience
* corresponds
* debruijn
* debug
* debugable
* debuggable
* deterministic
* discriminant
* display
* documentation
* doesn't
* ellipsis
* erroneous
* evaluability
* evaluate
* evaluation
* explicitly
* fallible
* fulfill
* getting
* has
* highlighting
* illustrative
* imported
* incompatible
* infringing
* initialized
* into
* intrinsic
* introduced
* javascript
* liveness
* metadata
* monomorphization
* nonexistent
* nontrivial
* obligation
* obligations
* offset
* opaque
* opportunities
* opt-in
* outlive
* overlapping
* paragraph
* parentheses
* poisson
* precisely
* predecessors
* predicates
* preexisting
* propagated
* really
* reentrant
* referent
* responsibility
* rustonomicon
* shortcircuit
* simplifiable
* simplifications
* specify
* stabilized
* structurally
* suggestibility
* translatable
* transmuting
* two
* unclosed
* uninhabited
* visibility
* volatile
* workaround

Signed-off-by: Josh Soref <2119212+jsoref@users.noreply.github.com>
2023-04-17 16:09:18 -04:00
Matthias Krüger d54a8ac8e2
Rollup merge of #110222 - lovelymono:rustc-expand-mbe-diagnostic, r=davidtwco
Improve the error message when forwarding a matched fragment to another macro

Adds a link to [Forwarding a matched fragment](https://doc.rust-lang.org/nightly/reference/macros-by-example.html#forwarding-a-matched-fragment) section of the Rust Reference, and suggests a possible fix (using `:tt` instead in the macro definition).

Also removes typos from the original message, it should be `:lifetime` instead of `$lifetime`.

## Motivation

When trying to write a macro which uses a literal in the matcher from the outer macro, like the following one, using a fragment specified that isn't one of `:ident`, `:lifetime`, or `:tt` currently results in a hard to understand message.

```rs
macro_rules! make_t_for_all_tokens {
    ($($name:literal as $variant:expr,)*) => {
        macro_rules! t {
            $(
                ($name) => {
                    $variant
                };
            )*
        }
    };
}

make_t_for_all_tokens! {
    "fn" as Token::Fn,
    "return" as Token::Return,
    "let" as Token::Let,
}

// This creates
//
// macro_rules! t {
//     ("fn") => {
//         Token::Fn
//     };
//     ("return") => {
//         Token::Return
//     };
//     ("let") => {
//         Token::Let
//     };
// }

t!["fn"];
```

### Before

```
error: no rules expected the token `"fn"`
   --> src/main.rs:103:10
    |
32  |         macro_rules! t {
    |         -------------- when calling this macro
...
103 |     t!["fn"];
    |        ^^^^ no rules expected this token in macro call
    |
note: while trying to match `"fn"`
   --> src/main.rs:34:6
    |
34  |                   ($name) => {
    |                    ^^^^^
...
58  | / make_t_for_all_tokens! {
59  | |     "fn" as Token::Fn,
60  | |     "return" as Token::Return,
61  | |     "let" as Token::Let,
62  | | }
    | |_- in this macro invocation
    = note: captured metavariables except for `$tt`, `$ident` and `$lifetime` cannot be compared to other tokens
    = note: this error originates in the macro `make_t_for_all_tokens` (in Nightly builds, run with -Z macro-backtrace for more info)
```

### After

```
error: no rules expected the token `"fn"`
   --> src/main.rs:103:10
    |
32  |         macro_rules! t {
    |         -------------- when calling this macro
...
103 |     t!["fn"];
    |        ^^^^ no rules expected this token in macro call
    |
note: while trying to match `"fn"`
   --> src/main.rs:34:6
    |
34  |                   ($name) => {
    |                    ^^^^^
...
58  | / make_t_for_all_tokens! {
59  | |     "fn" as Token::Fn,
60  | |     "return" as Token::Return,
61  | |     "let" as Token::Let,
62  | | }
    | |_- in this macro invocation
    = note: captured metavariables except for `:tt`, `:ident` and `:lifetime` cannot be compared to other tokens
    = note: see https://doc.rust-lang.org/nightly/reference/macros-by-example.html#forwarding-a-matched-fragment for more information
    = help: try using `:tt` instead in the macro definition
    = note: this error originates in the macro `make_t_for_all_tokens` (in Nightly builds, run with -Z macro-backtrace for more info)
```

## Unresolved questions

- Preferrably the suggestion should be attached to the `$name:literal` part of the outer macro, instead of being in the notes section at the end. But I'm not familiar with how the compiler works at all, and I have no idea how to approach this kind of solution.
- `@Nilstrieb` raised a question that the suggestion of adding `:tt` isn't accurate when there's more than `tt` being matched, for example when the input is an `item`.
2023-04-12 20:56:24 +02:00
Lena Milizé 04f20d4ac8 compiler: print the suggestion only for local macros
And wrap the link in the diagnostic in angle brackets.

Signed-off-by: Lena Milizé <me@lvmn.org>
2023-04-12 15:43:50 +02:00
Lena Milizé 4b456cb683 compiler: improve captured metavariables diagnostic
Adds a link to the relevant part of The Rust Reference in the eror
message, and suggests a possible fix (replacing the fragment specifier
with :tt in the macro definition).

Fixes typos in the original message.

Signed-off-by: Lena Milizé <me@lvmn.org>
2023-04-12 11:32:25 +02:00
DaniPopes 677357d32b
Fix typos in compiler 2023-04-10 22:02:52 +02:00
Nilstrieb 81c320ea77 Fix some clippy::complexity 2023-04-09 23:22:14 +02:00
Oli Scherer 373807a95c Rename `ast::Static` to `ast::StaticItem` to match `ast::ConstItem` 2023-04-04 15:34:40 +00:00
Oli Scherer 4bebdd7104 box a bunch of large types 2023-04-04 13:58:50 +00:00
Oli Scherer ec74653652 Split out ast::ItemKind::Const into its own struct 2023-04-04 09:44:50 +00:00
Oli Scherer e3828777a6 rust-analyzer guided tuple field to named field 2023-04-04 09:44:50 +00:00
Oli Scherer b08a557f80 rust-analyzer guided enum variant structification 2023-04-04 09:44:45 +00:00
bors 5e1d3299a2 Auto merge of #109824 - GuillaumeGomez:rollup-i5r4uts, r=GuillaumeGomez
Rollup of 7 pull requests

Successful merges:

 - #109104 (rustdoc: Fix invalid suggestions on ambiguous intra doc links v2)
 - #109443 (Move `doc(primitive)` future incompat warning to `invalid_doc_attributes`)
 - #109680 (Fix subslice capture in closure)
 - #109798 (fluent_messages macro: don't emit the OS error in a note)
 - #109805 (Source map cleanups)
 - #109818 (rustdoc: Add GUI test for jump to collapsed item)
 - #109820 (rustdoc-search: update docs for comma in `?` help popover)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2023-03-31 20:38:06 +00:00
Nicholas Nethercote f049d5df10 Remove an unnecessary use of `with_session_globals`.
We can easily pass in the source map.
2023-03-31 15:34:00 +11:00
Michael Goulet 8b592db27a Add `(..)` syntax for RTN 2023-03-28 01:14:28 +00:00
Camille GILLOT 5f9c004d35 Separate find_*_stability. 2023-03-23 19:52:27 +00:00
Vadim Petrochenkov aca1b1e0b3 rustc_interface: Add a new query `pre_configure`
It partially expands crate attributes before the main expansion pass (without modifying the crate), and the produced preliminary crate attribute list is used for querying a few attributes that are required very early.

Crate-level cfg attributes are then expanded normally during the main expansion pass, like attributes on any other nodes.
2023-03-23 14:22:48 +04:00
Vadim Petrochenkov 6cc33b7691 expand: Pass `ast::Crate` by reference to AST transforming passes
Also some more attributes are passed by reference.
2023-03-23 14:20:55 +04:00
Vadim Petrochenkov 67a2c5bec8 rustc: Remove unused `Session` argument from some attribute functions 2023-03-22 13:55:55 +04:00
Mu42 550e3087d1 Suggest surrounding the macro with `{}` to interpret as a statement 2023-03-17 14:36:22 +08:00
gimbles e5a5b90afc unequal → not equal 2023-03-15 23:55:48 +05:30
est31 7e2ecb3cd8 Simplify message paths
This makes it easier to open the messages file while developing on features.

The commit was the result of automatted changes:

for p in compiler/rustc_*; do mv $p/locales/en-US.ftl $p/messages.ftl; rmdir $p/locales; done

for p in compiler/rustc_*; do sed -i "s#\.\./locales/en-US.ftl#../messages.ftl#" $p/src/lib.rs; done
2023-03-11 22:51:57 +01:00
bors 8a73f50d87 Auto merge of #109019 - matthiaskrgr:rollup-ihjntil, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #104363 (Make `unused_allocation` lint against `Box::new` too)
 - #106633 (Stabilize `nonzero_min_max`)
 - #106844 (allow negative numeric literals in `concat!`)
 - #108071 (Implement goal caching with the new solver)
 - #108542 (Force parentheses around `match` expression in binary expression)
 - #108690 (Place size limits on query keys and values)
 - #108708 (Prevent overflow through Arc::downgrade)
 - #108739 (Prevent the `start_bx` basic block in codegen from having two `Builder`s at the same time)
 - #108806 (Querify register_tools and post-expansion early lints)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2023-03-11 18:15:53 +00:00
Matthias Krüger df50001c7d
Rollup merge of #108806 - cjgillot:query-lints, r=davidtwco
Querify register_tools and post-expansion early lints

The 2 extra queries correspond to code that happen before and after macro expansion, and don't need the resolver to exist.
2023-03-11 15:43:15 +01:00
Michael van Straten c67ae04aca Renamed to byte_range and changed Range generics [skip ci] 2023-03-11 12:15:19 +01:00
Michael van Straten 3a3ecbfae6 Fixed extra call to lo in end [skip ci] 2023-03-10 23:48:17 +01:00
Michael van Straten b8c6d2211e added byte position range for proc_macro::Span 2023-03-10 21:19:25 +01:00
Nilstrieb 3dee4630ba Add note when matching token with nonterminal
The current error message is _really_ confusing.
2023-03-10 16:59:26 +00:00
Nicholas Nethercote be60bcb28a Rename `MapInPlace` as `FlatMapInPlace`.
After removing the `map_in_place` method, which isn't much use because
modifying every element in a collection such as a `Vec` can be done
trivially with iteration.
2023-03-08 15:53:56 +11:00
Camille GILLOT b7e2b049f3 Querify registered_tools. 2023-03-06 10:56:23 +00:00
Tshepang Mbambo 7fe4f0701c rustc_expand: make proc-macro derive error translatable 2023-03-04 07:54:29 +02:00
est31 ef658907a5 Match end user facing unmatched backticks in compiler/ 2023-03-03 08:39:36 +01:00
Matthias Krüger 371904bba6
Rollup merge of #108297 - chenyukang:yukang/delim-error-exit, r=petrochenkov
Exit when there are unmatched delims to avoid noisy diagnostics

From https://github.com/rust-lang/rust/pull/104012#issuecomment-1311764832
r? ``@petrochenkov``
2023-03-01 01:20:22 +01:00
yukang 88de2e1115 no need to return unmatched_delims from tokentrees 2023-02-28 07:57:17 +00:00
Tshepang Mbambo dca52ac835 make "proc macro panicked" translatable 2023-02-24 23:37:10 +02:00
David Wood 26255186e2 various: translation resources from cg backend
Extend `CodegenBackend` trait with a function returning the translation
resources from the codegen backend, which can be added to the complete
list of resources provided to the emitter.

Signed-off-by: David Wood <david.wood@huawei.com>
2023-02-22 09:15:54 +00:00
David Wood d1fcf61117 errors: generate typed identifiers in each crate
Instead of loading the Fluent resources for every crate in
`rustc_error_messages`, each crate generates typed identifiers for its
own diagnostics and creates a static which are pulled together in the
`rustc_driver` crate and provided to the diagnostic emitter.

Signed-off-by: David Wood <david.wood@huawei.com>
2023-02-22 09:15:53 +00:00
bors 3fee48c161 Auto merge of #104754 - nnethercote:more-ThinVec-in-ast, r=the8472
Use `ThinVec` more in the AST

r? `@ghost`
2023-02-21 07:02:57 +00:00
bors 2deff71719 Auto merge of #105462 - oli-obk:feeding_full, r=cjgillot,petrochenkov
give the resolver access to TyCtxt

The resolver is now created after TyCtxt is created. Then macro expansion and name resolution are run and the results fed into queries just like before this PR.

Since the resolver had (before this PR) mutable access to the `CStore` and the source span table, these two datastructures are now behind a `RwLock`. To ensure that these are not mutated anymore after the resolver is done, a read lock to them is leaked right after the resolver finishes.

### PRs split out of this one and leading up to it:

* https://github.com/rust-lang/rust/pull/105423
* https://github.com/rust-lang/rust/pull/105357
* https://github.com/rust-lang/rust/pull/105603
* https://github.com/rust-lang/rust/pull/106776
* https://github.com/rust-lang/rust/pull/106810
* https://github.com/rust-lang/rust/pull/106812
* https://github.com/rust-lang/rust/pull/108032
2023-02-21 01:19:25 +00:00
Nicholas Nethercote 7e855d5f31 Use `ThinVec` in a few more AST types. 2023-02-21 11:51:56 +11:00
Nicholas Nethercote 549f1c60af Use `ThinVec` in `ast::ExprKind::Match`. 2023-02-21 11:51:56 +11:00
Nicholas Nethercote 912b825002 Use `ThinVec` in `ast::PatKind::Struct`. 2023-02-21 11:51:56 +11:00
Nicholas Nethercote b14b7ba5dd Use `ThinVec` in `ast::Block`. 2023-02-21 11:51:56 +11:00
Nicholas Nethercote 4143b101f9 Use `ThinVec` in various AST types.
This commit changes the sequence parsers to produce `ThinVec`, which
triggers numerous conversions.
2023-02-21 11:51:56 +11:00
Nicholas Nethercote dd7aff5cc5 Use `ThinVec` in `ast::Generics` and related types. 2023-02-21 11:51:55 +11:00
Nicholas Nethercote 06228d6e93 Upgrade `thin-vec` from 0.2.9 to 0.2.12.
Because 0.2.10 added supports for `ThinVec::splice`, and 0.2.12 is the
latest release.
2023-02-21 11:51:55 +11:00
Oli Scherer 9fb91b8742 Remove a redundant function argument 2023-02-20 15:28:58 +00:00
Patrik Kårlin 0fd2a70b90
create dummy placeholder crate to prevent compiler 2023-02-20 10:20:57 +01:00
Maybe Waffle 5bf6a46032 Replace some `then`s with some `then_some`s 2023-02-16 15:26:03 +00:00
Maybe Waffle 8751fa1a9a `if $c:expr { Some($r:expr) } else { None }` =>> `$c.then(|| $r)` 2023-02-16 15:26:00 +00:00
Matthias Krüger 780beae7bd
Rollup merge of #107838 - estebank:terminal_hyperlinks, r=nagisa
Introduce `-Zterminal-urls` to use OSC8 for error codes

Terminals supporting the OSC8 Hyperlink Extension can support inline anchors where the text is user defineable but clicking on it opens a browser to a specified URLs, just like `<a href="URL">` does in HTML.

https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda
2023-02-13 11:34:57 +01:00
Esteban Küber a576514e13 Introduce `-Zterminal-urls` to use OSC8 for error codes
Terminals supporting the OSC8 Hyperlink Extension can support inline
anchors where the text is user defineable but clicking on it opens a
browser to a specified URLs, just like `<a href="URL">` does in HTML.

https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda
2023-02-09 14:52:54 +00:00
Michael Goulet 7a4505900d Add ~const bounds trait bounds when using derive_const 2023-02-07 21:00:12 +00:00
est31 60e82aef64 rustc_expand: remove huge error imports 2023-02-05 03:47:22 +01:00
Nicholas Nethercote a86fc727fa Rename `Cursor`/`CursorRef` as `TokenTreeCursor`/`RefTokenTreeCursor`.
This makes it clear they return token trees, and makes for a nice
comparison against `TokenCursor` which returns tokens.
2023-02-03 10:06:52 +11:00
Matthias Krüger 150b9d753b
Rollup merge of #107488 - nnethercote:fix-PartialEq-syntax, r=RalfJung
Fix syntax in `-Zunpretty-expanded` output for derived `PartialEq`.

If you do `derive(PartialEq)` on a packed struct, the output shown by `-Zunpretty=expanded` includes expressions like this:
```
{ self.x } == { other.x }
```
This is invalid syntax. This doesn't break compilation, because the AST nodes are constructed within the compiler. But it does mean anyone using `-Zunpretty=expanded` output as a guide for hand-written impls could get a nasty surprise.

This commit fixes things by instead using this form:
```
({ self.x }) == ({ other.x })
```

r? ``@RalfJung``
2023-02-02 06:52:14 +01:00
Nicholas Nethercote 75e87d1f81 Fix syntax in `-Zunpretty-expanded` output for derived `PartialEq`.
If you do `derive(PartialEq)` on a packed struct, the output shown by
`-Zunpretty=expanded` includes expressions like this:
```
{ self.x } == { other.x }
```
This is invalid syntax. This doesn't break compilation, because the AST
nodes are constructed within the compiler. But it does mean anyone using
`-Zunpretty=expanded` output as a guide for hand-written impls could get
a nasty surprise.

This commit fixes things by instead using this form:
```
({ self.x }) == ({ other.x })
```
2023-02-01 15:14:05 +11:00
Guillaume Gomez 53bb6322db
Rollup merge of #107467 - WaffleLapkin:uneq, r=oli-obk
Improve enum checks

Some light refactoring.
2023-01-31 23:38:52 +01:00
David Wood 2575b1abc9 session: diagnostic migration lint on more fns
Apply the diagnostic migration lint to more functions on `Session`.

Signed-off-by: David Wood <david.wood@huawei.com>
2023-01-30 17:11:35 +00:00
Maybe Waffle f1d273cbfb Replace some `_ == _ || _ == _`s with `matches!(_, _ | _)`s 2023-01-30 12:26:26 +00:00
Lukas Markeffsky 31443c63b5 preserve delim spans during `macro_rules!` expansion if able 2023-01-20 20:16:37 +01:00
bors 56ee85274e Auto merge of #106090 - WaffleLapkin:dereffffffffff, r=Nilstrieb
Remove some `ref` patterns from the compiler

Previous PR: https://github.com/rust-lang/rust/pull/105368

r? `@Nilstrieb`
2023-01-20 04:52:28 +00:00
Matthias Krüger 68f12338af
Rollup merge of #104505 - WaffleLapkin:no-double-spaces-in-comments, r=jackh726
Remove double spaces after dots in comments

Most of the comments do not have double spaces, so I assume these are typos.
2023-01-17 20:21:25 +01:00
Maybe Waffle 6a28fb42a8 Remove double spaces after dots in comments 2023-01-17 08:09:33 +00:00
Maybe Waffle bddbf38af2 `rustc_expand`: remove `ref` patterns 2023-01-17 07:48:19 +00:00
Tim Neumann 496edf97c5 Update `rental` hack to work with remapped paths. 2023-01-13 20:36:03 +00:00
Deadbeef 4fb10c0ce4 parse const closures 2023-01-12 02:28:37 +00:00
Nilstrieb 5112f0281d Shrink `ParseResult` in the hot path.
A recent PR increased the size, which caused regressions. This uses the
existing generic infrastructure to differentiate between the hot path
and the diagnostics path.
2023-01-05 20:42:26 +01:00
bors fb9dfa8cef Auto merge of #84762 - cjgillot:resolve-span-opt, r=petrochenkov
Encode spans relative to the enclosing item -- enable on nightly

Follow-up to #84373 with the flag `-Zincremental-relative-spans` set by default.

This PR seeks to remove one of the main shortcomings of incremental: the handling of spans.
Changing the contents of a function may require redoing part of the compilation process for another function in another file because of span information is changed.
Within one file: all the spans in HIR change, so typechecking had to be re-done.
Between files: spans of associated types/consts/functions change, so type-based resolution needs to be re-done (hygiene information is stored in the span).

The flag `-Zincremental-relative-spans` encodes local spans relative to the span of an item, stored inside the `source_span` query.

Trap: stashed diagnostics are referenced by the "raw" span, so stealing them requires to remove the span's parent.

In order to avoid too much traffic in the span interner, span encoding uses the `ctxt_or_tag` field to encode:
- the parent when the `SyntaxContext` is 0;
- the `SyntaxContext` when the parent is `None`.
Even with this, the PR creates a lot of traffic to the Span interner, when a Span has both a LocalDefId parent and a non-root SyntaxContext. They appear in lowering, when we add a parent to all spans, including those which come from macros, and during inlining when we mark inlined spans.

The last commit changes how queries of `LocalDefId` manage their cache. I can put this in a separate PR if required.

Possible future directions:
- validate that all spans are marked in HIR validation;
- mark macro-expanded spans relative to the def-site and not the use-site.
2023-01-02 13:10:16 +00:00
Esteban Küber 5bfcfeee2a Merge multiple mutable borrows of immutable binding errors
Fix #53466.
2023-01-01 10:09:26 -08:00
Matthias Krüger c610aeb592
Rollup merge of #106221 - Nilstrieb:rptr-more-like-ref-actually, r=compiler-errors
Rename `Rptr` to `Ref` in AST and HIR

The name makes a lot more sense, and `ty::TyKind` calls it `Ref` already as well.
2022-12-29 13:16:04 +01:00
Matthias Krüger c52d58f346
Rollup merge of #105570 - Nilstrieb:actual-best-failure, r=compiler-errors
Properly calculate best failure in macro matching

Previously, we used spans. This was not good. Sometimes, the span of the token that failed to match may come from a position later in the file which has been transcribed into a token stream way earlier in the file. If precisely this token fails to match, we think that it was the best match because its span is so high, even though other arms might have gotten further in the token stream.

We now try to properly use the location in the token stream.

This needs a little cleanup as the `best_failure` field is getting out of hand but it should be mostly good to go. I hope I didn't violate too many abstraction boundaries..
2022-12-28 22:22:19 +01:00
Nilstrieb 9067e4417e Rename `Rptr` to `Ref` in AST and HIR
The name makes a lot more sense, and `ty::TyKind` calls it `Ref` already
as well.
2022-12-28 18:52:36 +01:00
Michael Goulet aff403cf68 Recover `fn` keyword as `Fn` trait in bounds 2022-12-27 06:14:46 +00:00
Camille GILLOT 40c8165395 Only enable relative span hashing on nightly. 2022-12-25 18:48:36 +00:00
Camille GILLOT 65f342daea Enable relative span hashing. 2022-12-25 18:48:31 +00:00
Matthias Krüger d8874f259a fix more clippy::style findings
match_result_ok
obfuscated_if_else
single_char_add
writeln_empty_string
collapsible_match
iter_cloned_collect
unnecessary_mut_passed
2022-12-25 17:32:26 +01:00
Jeremy Stucki 3dde32ca97
rustc: Remove needless lifetimes 2022-12-20 22:10:40 +01:00
Matthias Krüger a108d55ce6 don't restuct references just to reborrow 2022-12-18 17:04:32 +01:00
Nilstrieb d72a0c437b Properly calculate best failure in macro matching
Previously, we used spans. This was not good. Sometimes, the span of the
token that failed to match may come from a position later in the file
which has been transcribed into a token stream way earlier in the file.
If precisely this token fails to match, we think that it was the best
match because its span is so high, even though other arms might have
gotten further in the token stream.

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

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

r? `@petrochenkov`
2022-12-12 05:16:50 +00:00
Matthias Krüger 2daa3bcbc2
Rollup merge of #105537 - kadiwa4:remove_some_imports, r=fee1-dead
compiler: remove unnecessary imports and qualified paths

Some of these imports were necessary before Edition 2021, others were already in the prelude.

I hope it's fine that this PR is so spread-out across files :/
2022-12-11 09:51:57 +01:00
KaDiWa 9bc69925cb
compiler: remove unnecessary imports and qualified paths 2022-12-10 18:45:34 +01:00
nils 2f9f097cb8 Migrate parts of `rustc_expand` to session diagnostics
This migrates everything but the `mbe` and `proc_macro` modules. It also
contains a few cleanups and drive-by/accidental diagnostic improvements
which can be seen in the diff for the UI tests.
2022-12-10 11:02:41 +01:00
Oli Scherer d30848b30a Use `Symbol` for the crate name instead of `String`/`str` 2022-12-07 20:30:02 +00:00
Nicholas Nethercote 568e647047 Remove three uses of `LitKind::synthesize_token_lit`. 2022-12-05 16:33:20 +11:00
Nicholas Nethercote 4ae956f600 Remove `ExtCtxt::expr_lit`. 2022-12-05 14:20:38 +11:00
Matthias Krüger c89bff29e5
Rollup merge of #104199 - SarthakSingh31:issue-97417-1, r=cjgillot
Keep track of the start of the argument block of a closure

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

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

r? `@cjgillot`
2022-12-03 17:37:41 +01:00
Nicholas Nethercote a7f35c42d4 Add `StrStyle` to `ast::LitKind::ByteStr`.
This is required to distinguish between cooked and raw byte string
literals in an `ast::LitKind`, without referring to an adjacent
`token::Lit`. It's a prerequisite for the next commit.
2022-12-02 10:38:58 +11:00
Nicholas Nethercote e658144586 Rename `LitKind::to_token_lit` as `LitKind::synthesize_token_lit`.
This makes it clearer that it's not a lossless conversion, which I find
helpful.
2022-12-02 10:23:44 +11:00
Matthias Krüger 741f8c9166
Rollup merge of #105078 - TaKO8Ki:fix-105011, r=nnethercote
Fix `expr_to_spanned_string` ICE

Fixes #105011
2022-12-01 11:58:59 +01:00
Takayuki Maeda 97f0c58b37 report literal errors when `token_lit` has errors 2022-11-30 13:31:11 +09:00
Nicholas Nethercote ba1751a201 Avoid more `MetaItem`-to-`Attribute` conversions.
There is code for converting `Attribute` (syntactic) to `MetaItem`
(semantic). There is also code for the reverse direction. The reverse
direction isn't really necessary; it's currently only used when
generating attributes, e.g. in `derive` code.

This commit adds some new functions for creating `Attributes`s directly,
without involving `MetaItem`s: `mk_attr_word`, `mk_attr_name_value_str`,
`mk_attr_nested_word`, and
`ExtCtxt::attr_{word,name_value_str,nested_word}`.

These new methods replace the old functions for creating `Attribute`s:
`mk_attr_inner`, `mk_attr_outer`, and `ExtCtxt::attribute`. Those
functions took `MetaItem`s as input, and relied on many other functions
that created `MetaItems`, which are also removed: `mk_name_value_item`,
`mk_list_item`, `mk_word_item`, `mk_nested_word_item`,
`{MetaItem,MetaItemKind,NestedMetaItem}::token_trees`,
`MetaItemKind::attr_args`, `MetaItemLit::{from_lit_kind,to_token}`,
`ExtCtxt::meta_word`.

Overall this cuts more than 100 lines of code and makes thing simpler.
2022-11-29 18:43:53 +11:00
Nicholas Nethercote ac7a7499df Remove an out-of-date comment.
This comment dates back to at least 2013, and is no longer relevant.
(There used to be an `allow` attribute, but that's no longer present.)
2022-11-29 17:13:38 +11:00
Nicholas Nethercote c9ae38c71e Avoid unnecessary `MetaItem`/`Attribute` conversions.
`check_builtin_attribute` calls `parse_meta` to convert an `Attribute`
to a `MetaItem`, which it then checks. However, many callers of
`check_builtin_attribute` start with a `MetaItem`, and then convert it
to an `Attribute` by calling `cx.attribute(meta_item)`. This `MetaItem`
to `Attribute` to `MetaItem` conversion is silly.

This commit adds a new function `check_builtin_meta_item`, which can be
called instead from these call sites. `check_builtin_attribute` also now
calls it. The commit also renames `check_meta` as `check_attr` to better
match its arguments.
2022-11-29 12:08:57 +11:00
Matthias Krüger 63ec33e929
Rollup merge of #104804 - nnethercote:MetaItemLit, r=petrochenkov
Rename `ast::Lit` as `ast::MetaItemLit`.

And some other literal cleanups.

r? `@petrochenkov`
2022-11-28 17:25:46 +01:00
Dylan DPC 79fe15c8b0
Rollup merge of #104795 - estebank:multiline-spans, r=TaKO8Ki
Change multiline span ASCII art visual order

Tweak the ASCII art for nested multiline spans so that we minimize line overlaps.

Partially addresses https://github.com/rust-lang/rust/issues/61017.
2022-11-28 15:42:10 +05:30
Sarthak Singh 8f705e2425 Keep track of the start of the argument block of a closure 2022-11-28 14:09:00 +05:30
Esteban Küber ab04080b56 Change multiline span ASCII art visual order 2022-11-28 00:11:12 -08:00
Nicholas Nethercote e4a9150872 Rename `ast::Lit` as `ast::MetaItemLit`. 2022-11-28 15:18:49 +11:00
Nicholas Nethercote 8cfc8153da Remove `Lit::from_included_bytes`.
`Lit::from_included_bytes` calls `Lit::from_lit_kind`, but the two call
sites only need the resulting `token::Lit`, not the full `ast::Lit`.

This commit changes those call sites to use `LitKind::to_token_lit`,
which means `from_included_bytes` can be removed.
2022-11-28 15:17:45 +11:00
Maybe Waffle 1d42936b18 Prefer doc comments over `//`-comments in compiler 2022-11-27 11:19:04 +00:00
Nicholas Nethercote 2c5d3705ec Clarify `SyntaxExtensionKind::LegacyDerive`. 2022-11-25 09:13:27 +11:00
Manish Goregaokar 9043dfd946
Rollup merge of #104638 - Nilstrieb:macro-diagnostics, r=compiler-errors
Move macro_rules diagnostics to diagnostics module

This will make it easier to add more diagnostics in the future in a centralized place.
2022-11-22 01:26:08 -05:00
Matthias Krüger 589d843bd0
Rollup merge of #104559 - nnethercote:split-MacArgs, r=petrochenkov
Split `MacArgs` in two.

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

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

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

Various other related things are renamed as well.

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

r? `@petrochenkov`
2022-11-22 00:01:09 +01:00
Matthias Krüger 7a3eca690f
Rollup merge of #104416 - clubby789:fix-104414, r=eholk
Fix using `include_bytes` in pattern position

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

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

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

Various other related things are renamed as well.

These changes make the code clearer, avoids several unreachable paths, and
disallows the invalid values.
2022-11-22 09:04:15 +11:00
Nilstrieb a1e5fea136
Move macro_rules diagnostics to diagnostics module 2022-11-20 13:06:44 +01:00
Nilstrieb 825b8db34a
Cleanup macro matching recovery
The retry has been implemented already.
2022-11-19 17:46:04 +01:00
Dylan DPC 3c6fc06906
Rollup merge of #104566 - matthiaskrgr:clippy_perf_nov18, r=oli-obk
couple of clippy::perf fixes
2022-11-19 11:54:46 +05:30
Matthias Krüger e3036df003 couple of clippy::perf fixes 2022-11-18 10:30:47 +01:00
Nicholas Nethercote 67d5cc0462 Use `ThinVec` in `ast::Path`. 2022-11-17 13:56:38 +11:00
Nicholas Nethercote 6b7ca2fcf2 Box `ExprKind::{Closure,MethodCall}`, and `QSelf` in expressions, types, and patterns. 2022-11-17 13:45:59 +11:00
bors bebd57a960 Auto merge of #102944 - nnethercote:ast-Lit-third-time-lucky, r=petrochenkov
Use `token::Lit` in `ast::ExprKind::Lit`.

Instead of `ast::Lit`.

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

r? `@petrochenkov`
2022-11-16 23:03:14 +00:00
Nicholas Nethercote 358a603f11 Use `token::Lit` in `ast::ExprKind::Lit`.
Instead of `ast::Lit`.

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

This commit changes the language very slightly. Some programs that used
to not compile now will compile. This is because some invalid literals
that are removed by `cfg` or attribute macros will no longer trigger
errors. See this comment for more details:
https://github.com/rust-lang/rust/pull/102944#issuecomment-1277476773
2022-11-16 09:41:28 +11:00
Nilstrieb b7b67228f9
Only do parser recovery on retried macro matching
This prevents issues with eager parser recovery during macro matching.
2022-11-15 19:34:35 +01:00
Matthias Krüger 1a6ed3050f
Rollup merge of #103439 - Nilstrieb:help-me-with-my-macro, r=estebank
Show note where the macro failed to match

When feeding the wrong tokens, it used to fail with a very generic error that wasn't very helpful. This change tries to help by noting where specifically the matching went wrong.

```rust
macro_rules! uwu {
    (a a a b) => {};
}
uwu! { a a a c }
```

```diff
error: no rules expected the token `c`
 --> macros.rs:5:14
  |
1 | macro_rules! uwu {
  | ---------------- when calling this macro
...
4 | uwu! { a a a c }
  |              ^ no rules expected this token in macro call
  |
+note: while trying to match `b`
+ --> macros.rs:2:12
+  |
+2 |     (a a a b) => {};
+  |            ^
```
2022-11-15 10:44:07 +01:00
Nilstrieb 7e7c11cf56
Show a note where a macro failed to match
This shows a small note on what the macro matcher was currently
processing to aid with "no rules expected the token X" errors.
2022-11-14 19:59:15 +01:00
clubby789 47eda6b7db Fix using `include_bytes` in pattern position 2022-11-14 17:43:21 +00:00
cui fliter 442f848d74 fix some typos in comments
Signed-off-by: cui fliter <imcusg@gmail.com>
2022-11-13 15:26:17 +08:00
bors 8ef2485bd5 Auto merge of #103812 - clubby789:improve-include-bytes, r=petrochenkov
Delay `include_bytes` to AST lowering

Hopefully addresses #65818.
This PR introduces a new `ExprKind::IncludedBytes` which stores the path and bytes of a file included with `include_bytes!()`. We can then create a literal from the bytes during AST lowering, which means we don't need to escape the bytes into valid UTF8 which is the cause of most of the overhead of embedding large binary blobs.
2022-11-12 14:30:34 +00:00
Dylan DPC 4b0b89827d
Rollup merge of #102049 - fee1-dead-contrib:derive_const, r=oli-obk
Add the `#[derive_const]` attribute

Closes #102371. This is a minimal patchset for the attribute to work. There are no restrictions on what traits this attribute applies to.

r? `````@oli-obk`````
2022-11-12 12:02:50 +05:30
clubby789 b2da155a9a Introduce `ExprKind::IncludedBytes` 2022-11-11 16:31:32 +00:00
nils ebfa2ab68e
Small style improvements 2022-11-04 09:44:59 +01:00
Nilstrieb 1e21b3cfa3
Add some debug logs to macro matching
These were useful while debugging, so I'll leave them here.
2022-11-02 21:09:41 +01:00
Nilstrieb 5f73eac51b
Retry matching with tracking for diagnostics
For now, we only collect the small info for the `best_failure`, but
using this tracker, we can easily extend it in the future to track
things with more performance overhead.

We cannot retry cases where the macro failed with a parser error that
was emitted already, as that would cause us to emit the same error to
the user twice.
2022-11-02 21:05:09 +01:00
Nilstrieb 39584b153b
Factor out matching into `try_match_macro`
This moves out the matching part of expansion into a new function. This
function will try to match the macro and return an error if it failed to
match. A tracker can be used to get more information about the matching.
2022-11-02 21:05:09 +01:00
Nilstrieb 2f8a068cb7
Add `Tracker` to track matching operations
This should allow us to collect detailed information without slowing
down the inital hot path.
2022-11-02 21:05:09 +01:00
Nilstrieb 6c47848c25
Small parser cleanups 2022-11-02 21:05:09 +01:00
Nilstrieb 8d13b2a046
Store `ErrorGuaranteed` in `ErrorReported` 2022-11-02 21:05:09 +01:00
bors 11ebe6512b Auto merge of #103217 - mejrs:track, r=eholk
Track where diagnostics were created.

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

For example, the following code...

```rust
struct A;
struct B;

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

```
error[E0308]: mismatched types
 --> src\main.rs:5:16
  |
5 |     let _: A = B;
  |            -   ^ expected struct `A`, found struct `B`
  |            |
  |            expected due to this
-Ztrack-diagnostics: created at compiler\rustc_infer\src\infer\error_reporting\mod.rs:2275:31
```
2022-11-01 21:09:45 +00:00
Matthias Krüger f9dfb6e32f
Rollup merge of #103544 - Nilstrieb:no-recovery-pls, r=compiler-errors
Add flag to forbid recovery in the parser

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

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

r? `@compiler-errors`
2022-10-27 15:03:58 +02:00
Dylan DPC c9a04cddc0
Rollup merge of #103430 - cjgillot:receiver-attrs, r=petrochenkov
Workaround unstable stmt_expr_attributes for method receiver expressions

Fixes https://github.com/rust-lang/rust/issues/103244

cc ``@Mark-Simulacrum`` ``@ehuss``
2022-10-26 11:29:55 +05:30
Nilstrieb ed14202864
Add flag to forbid recovery in the parser 2022-10-25 22:06:53 +02:00
bors c07a6a9c0c Auto merge of #94063 - Aaron1011:pretty-print-rental, r=lcnr
Only apply `ProceduralMasquerade` hack to older versions of `rental`

The latest version of `rental` (v0.5.6) contains a fix that allows it to
compile without relying on the pretty-print back-compat hack.

Hopefully, there are no longer any crates relying on the affected
versions of the (much less popular) `procedural-masquerade` crate. This
should allow us to target the pretty-print back-compat hack specifically
to older versions of `rental`, and specifically mention upgrading to
`rental` v0.5.6 in the lint message.
2022-10-24 13:35:48 +00:00
Camille GILLOT 74d4eefc13 Workaround unstable stmt_expr_attributes for method receiver expressions. 2022-10-23 09:27:12 +00:00
Nilstrieb c65ebae221
Migrate all diagnostics 2022-10-23 10:09:44 +02:00
Aaron Hill 10dad22b66
Only apply `ProceduralMasquerade` hack to older versions of `rental`
The latest version of `rental` (v0.5.6) contains a fix that allows it to
compile without relying on the pretty-print back-compat hack.

Hopefully, there are no longer any crates relying on the affected
versions of the (much less popular) `procedural-masquerade` crate. This
should allow us to target the pretty-print back-compat hack specifically
to older versions of `rental`, and specifically mention upgrading to
`rental` v0.5.6 in the lint message.
2022-10-21 21:36:00 -05:00
Dylan DPC 0a0e9f73af
Rollup merge of #102922 - kper:bugfix/102902-filtering-json, r=oli-obk
Filtering spans when emitting json

According to the issue #102902, we shouldn't emit spans which have an empty span and no suggested replacement.
2022-10-21 17:29:58 +05:30
Kevin Per 28d0312b7d Implement assertions and fixes to not emit empty spans without suggestions 2022-10-20 08:25:31 +00:00
mejrs 406e1dc8eb Implement -Ztrack-diagnostics 2022-10-19 00:08:20 +02:00
yukang 0af255a5aa Fix the bug of next_point in span 2022-10-18 02:59:38 +08:00
Rageking8 7122abaddf more dupe word typos 2022-10-14 12:57:56 +08:00
bors 2b91cbe2d4 Auto merge of #102692 - nnethercote:TokenStreamBuilder, r=Aaron1011
Remove `TokenStreamBuilder`

`TokenStreamBuilder` is used to combine multiple token streams. It can be removed, leaving the code a little simpler and a little faster.

r? `@Aaron1011`
2022-10-12 03:46:16 +00:00
Takayuki Maeda 68260289b5 fix #102878 2022-10-11 02:43:36 +09:00
Nicholas Nethercote 1e848a564b Remove `TokenStreamBuilder`.
`TokenStreamBuilder` exists to concatenate multiple `TokenStream`s
together. This commit removes it, and moves the concatenation
functionality directly into `TokenStream`, via two new methods
`push_tree` and `push_stream`. This makes things both simpler and
faster.

`push_tree` is particularly important. `TokenStreamBuilder` only had a
single `push` method, which pushed a stream. But in practice most of the
time we push a single token tree rather than a stream, and `push_tree`
avoids the need to build a token stream with a single entry (which
requires two allocations, one for the `Lrc` and one for the `Vec`).

The main `push_tree` use arises from a change to one of the `ToInternal`
impls in `proc_macro_server.rs`. It now returns a `SmallVec` instead of
a `TokenStream`. This return value is then iterated over by
`concat_trees`, which does `push_tree` on each element. Furthermore, the
use of `SmallVec` avoids more allocations, because there is always only
one or two token trees.

Note: the removed `TokenStreamBuilder::push` method had some code to
deal with a quadratic blowup case from #57735. This commit removes the
code. I tried and failed to reproduce the blowup from that PR, before
and after this change. Various other changes have happened to
`TokenStreamBuilder` in the meantime, so I suspect the original problem
is no longer relevant, though I don't have proof of this. Generally
speaking, repeatedly extending a `Vec` without pre-determining its
capacity is *not* quadratic. It's also incredibly common, within rustc
and many other Rust programs, so if there were performance problems
there you'd think it would show up in other places, too.
2022-10-05 12:42:54 +11:00
Nicholas Nethercote 1e8dc45fb5 Rearrange `to_internal`.
`TokenTree::Punct` is handled outside the `match`. This commits moves it
inside the `match`, avoiding the need for the `return`s and making it
easier to read.
2022-10-05 10:36:56 +11:00
Nicholas Nethercote 88dab8d9b3 Improve spans when splitting multi-char operator tokens for proc macros. 2022-10-04 09:08:02 +11:00
Nicholas Nethercote 3be86e6528 Clarify operator splitting.
I found this code hard to read.
2022-10-03 11:41:36 +11:00
Mara Bos 9bec0de397 Rewrite and refactor format_args!() builtin macro. 2022-09-27 13:13:08 +02:00
Pietro Albini 3975d55d98
remove cfg(bootstrap) 2022-09-26 10:14:45 +02:00
Jhonny Bill Mena e52e2344dc FIX - adopt new Diagnostic naming in newly migrated modules
FIX - ambiguous Diagnostic link in docs

UPDATE - rename diagnostic_items to IntoDiagnostic and AddToDiagnostic

[Gardening] FIX - formatting via `x fmt`

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

DELETE - unneeded allow attributes in Handler method

FIX - broken test

FIX - Rebase conflict

UPDATE - rename residual _SessionDiagnostic and fix LintDiag link
2022-09-21 11:43:22 -04:00
Jhonny Bill Mena 5f91719f75 UPDATE - rename SessionSubdiagnostic macro to Subdiagnostic
Also renames:
- sym::AddSubdiagnostic to sym:: Subdiagnostic
- rustc_diagnostic_item = "AddSubdiagnostic" to rustc_diagnostic_item = "Subdiagnostic"
2022-09-21 11:39:53 -04:00
Jhonny Bill Mena a3396b2070 UPDATE - rename DiagnosticHandler macro to Diagnostic 2022-09-21 11:39:53 -04:00
Jhonny Bill Mena 19b348fed4 UPDATE - rename DiagnosticHandler trait to IntoDiagnostic 2022-09-21 11:39:52 -04:00
Jhonny Bill Mena 5b8152807c UPDATE - move SessionDiagnostic from rustc_session to rustc_errors 2022-09-21 11:39:52 -04:00
Deadbeef a052f2cce1 Add the `#[derive_const]` attribute 2022-09-20 11:57:58 +00:00
est31 173eb6f407 Only enable the let_else feature on bootstrap
On later stages, the feature is already stable.

Result of running:

rg -l "feature.let_else" compiler/ src/librustdoc/ library/ | xargs sed -s -i "s#\\[feature.let_else#\\[cfg_attr\\(bootstrap, feature\\(let_else\\)#"
2022-09-15 21:06:45 +02:00
SparrowLii 1a3ecbdb6a make `mk_attr_id` part of `ParseSess` 2022-09-14 08:49:10 +08:00
Dylan DPC db75d7e14b
Rollup merge of #101602 - nnethercote:AttrTokenStream, r=petrochenkov
Streamline `AttrAnnotatedTokenStream`

r? ```@petrochenkov```
2022-09-13 16:51:31 +05:30
Nicholas Nethercote d2df07c425 Rename `{Create,Lazy}TokenStream` as `{To,Lazy}AttrTokenStream`.
`To` is better than `Create` for indicating that this is a non-consuming
conversion, rather than creating something out of nothing.

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

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

PR #99887 did the same thing for `TokenStream`.
2022-09-09 12:00:46 +10:00
David Wood 38958aa8bd ssa: implement `#[collapse_debuginfo]`
Debuginfo line information for macro invocations are collapsed by
default - line information are replaced by the line of the outermost
expansion site. Using `-Zdebug-macros` disables this behaviour.

When the `collapse_debuginfo` feature is enabled, the default behaviour
is reversed so that debuginfo is not collapsed by default. In addition,
the `#[collapse_debuginfo]` attribute is available and can be applied to
macro definitions which will then have their line information collapsed.

Signed-off-by: David Wood <david.wood@huawei.com>
2022-09-07 13:54:51 +01:00
Cameron Steffen 02ba216e3c Refactor and re-use BindingAnnotation 2022-09-02 12:55:05 -05:00
Oli Scherer ee3c835018 Always import all tracing macros for the entire crate instead of piecemeal by module 2022-09-01 14:54:27 +00:00
bors b32223fec1 Auto merge of #100707 - dzvon:fix-typo, r=davidtwco
Fix a bunch of typo

This PR will fix some typos detected by [typos].

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

[typos]: https://github.com/crate-ci/typos
2022-09-01 05:39:58 +00:00
bors 3892b7074d Auto merge of #100210 - mystor:proc_macro_diag_struct, r=eddyb
proc_macro/bridge: send diagnostics over the bridge as a struct

This removes some RPC when creating and emitting diagnostics, and
simplifies the bridge slightly.

After this change, there are no remaining methods which take advantage
of the support for `&mut` references to objects in the store as
arguments, meaning that support for them could technically be removed if
we wanted. The only remaining uses of immutable references into the
store are `TokenStream` and `SourceFile`.

r? `@eddyb`
2022-09-01 00:26:53 +00:00
Dezhi Wu 85fc39c1e3 Fix ci checks 2022-08-31 18:25:00 +08:00
Dezhi Wu b1430fb7ca Fix a bunch of typo
This PR will fix some typos detected by [typos].

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

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

This is the revert against master, the beta revert was already done in #100538.
2022-08-29 19:34:11 +02:00
Nicholas Nethercote 6087dc2054 Remove the symbol from `ast::LitKind::Err`.
Because it's never used meaningfully.
2022-08-23 16:56:24 +10:00
Nicholas Nethercote 619b8abaa6 Use `AttrVec` in more places.
In some places we use `Vec<Attribute>` and some places we use
`ThinVec<Attribute>` (a.k.a. `AttrVec`). This results in various points
where we have to convert between `Vec` and `ThinVec`.

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

Overall, it makes the code a little nicer, and has little effect on
performance. But it is a precursor to removing
`rustc_data_structures::thin_vec::ThinVec` and replacing it with
`thin_vec::ThinVec`, which is implemented more efficiently.
2022-08-22 07:35:33 +10:00
Xiretza 7f3a6fd7f6 Replace #[lint/warning/error] with #[diag] 2022-08-21 09:17:43 +02:00
bors dd01122b5c Auto merge of #100564 - nnethercote:box-ast-MacCall, r=spastorino
Box the `MacCall` in various types.

r? `@spastorino`
2022-08-20 10:26:54 +00:00
Matthias Krüger 3e057d1512
Rollup merge of #100669 - nnethercote:attribute-cleanups, r=spastorino
Attribute cleanups

r? `@ghost`
2022-08-18 05:10:48 +02:00
Matthias Krüger 8b180ed3c0
Rollup merge of #100651 - nidnogg:diagnostics_migration_expand_transcribe, r=davidtwco
Migrations for rustc_expand transcribe.rs

This PR includes some migrations to the new diagnostics API for the `rustc_expand` module.
r? ```@davidtwco```
2022-08-18 05:10:47 +02:00
nidnogg a468f13162 Hotfix for duplicated slug name on VarStillRepeating struct 2022-08-17 13:13:07 -03:00
nidnogg caab20c431 Moved structs to rustc_expand::errors, added several more migrations, fixed slug name 2022-08-17 11:20:37 -03:00
nidnogg c6f9a9c410 Moved structs to rustc_expand::errors, added several more migrations, fixed slug name 2022-08-17 11:18:19 -03:00
Nicholas Nethercote 6cd40d0e51 Remove `attrs` arg from `typaram` and `mk_ty_param`.
Because it's always empty.
2022-08-17 12:33:42 +10:00
nidnogg 72ce216def Previous commit under x.py fmt 2022-08-16 19:19:59 -03:00
Nicholas Nethercote eafd0dfd05 Box the `MacCall` in various types. 2022-08-17 08:10:56 +10:00
nidnogg be18a9bf75 Migrated more diagnostics under transcribe.rs 2022-08-16 19:02:51 -03:00
nidnogg 7e15fbab75 Added first migration for repeated expressions without syntax vars 2022-08-16 18:34:13 -03:00
Nicholas Nethercote 5d3cc1713a Rename some things related to literals.
- Rename `ast::Lit::token` as `ast::Lit::token_lit`, because its type is
  `token::Lit`, which is not a token. (This has been confusing me for a
  long time.)
  reasonable because we have an `ast::token::Lit` inside an `ast::Lit`.
- Rename `LitKind::{from,to}_lit_token` as
  `LitKind::{from,to}_token_lit`, to match the above change and
  `token::Lit`.
2022-08-16 13:41:34 +10:00
Nicholas Nethercote d7a041f607 Make `ExtCtxt::expr_lit` non-`pub`.
By using `expr_str` more and adding `expr_{char,byte_str}`.
2022-08-16 11:17:15 +10:00
Mark Rousskov 154a09dd91 Adjust cfgs 2022-08-12 16:28:15 -04:00
Michael Goulet a2b6744af0 Use &mut Diagnostic instead of &mut DiagnosticBuilder unless needed 2022-08-10 03:45:42 +00:00
Dylan DPC 1dc4858914
Rollup merge of #96478 - WaffleLapkin:rustc_default_body_unstable, r=Aaron1011
Implement `#[rustc_default_body_unstable]`

This PR implements a new stability attribute — `#[rustc_default_body_unstable]`.

`#[rustc_default_body_unstable]` controls the stability of default bodies in traits.
For example:
```rust
pub trait Trait {
    #[rustc_default_body_unstable(feature = "feat", isssue = "none")]
    fn item() {}
}
```
In order to implement `Trait` user needs to either
- implement `item` (even though it has a default implementation)
- enable `#![feature(feat)]`

This is useful in conjunction with [`#[rustc_must_implement_one_of]`](https://github.com/rust-lang/rust/pull/92164), we may want to relax requirements for a trait, for example allowing implementing either of `PartialEq::{eq, ne}`, but do so in a safe way — making implementation of only `PartialEq::ne` unstable.

r? `@Aaron1011`
cc `@nrc` (iirc you were interested in this wrt `read_buf`), `@danielhenrymantilla` (you were interested in the related `#[rustc_must_implement_one_of]`)
P.S. This is my first time working with stability attributes, so I'm not sure if I did everything right 😅
2022-08-09 17:34:50 +05:30
Nika Layzell 1c7c792dda proc_macro/bridge: send diagnostics over the bridge as a struct
This removes some RPC when creating and emitting diagnostics, and
simplifies the bridge slightly.

After this change, there are no remaining methods which take advantage
of the support for `&mut` references to objects in the store as
arguments, meaning that support for them could technically be removed if
we wanted. The only remaining uses of immutable references into the
store are `TokenStream` and `SourceFile`.
2022-08-06 15:49:43 -04:00
bors 1202bbaf48 Auto merge of #99887 - nnethercote:rm-TreeAndSpacing, r=petrochenkov
Remove `TreeAndSpacing`.

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

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

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

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

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

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

r? `@petrochenkov`
2022-07-30 14:50:05 +00:00
Nika Layzell 6d1650fe45 proc_macro: use crossbeam channels for the proc_macro cross-thread bridge
This is done by having the crossbeam dependency inserted into the
proc_macro server code from the server side, to avoid adding a
dependency to proc_macro.

In addition, this introduces a -Z command-line option which will switch
rustc to run proc-macros using this cross-thread executor. With the
changes to the bridge in #98186, #98187, #98188 and #98189, the
performance of the executor should be much closer to same-thread
execution.

In local testing, the crossbeam executor was substantially more
performant than either of the two existing CrossThread strategies, so
they have been removed to keep things simple.
2022-07-29 17:38:12 -04:00
Nicholas Nethercote 332dffb1f9 Remove `TreeAndSpacing`.
A `TokenStream` contains a `Lrc<Vec<(TokenTree, Spacing)>>`. But this is
not quite right. `Spacing` makes sense for `TokenTree::Token`, but does
not make sense for `TokenTree::Delimited`, because a
`TokenTree::Delimited` cannot be joined with another `TokenTree`.

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

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

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

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

These changes also simplifies `Cursor` and `CursorRef`, because they no longer
need to distinguish between `next` and `next_with_spacing`.
2022-07-29 15:52:15 +10:00
Takayuki Maeda 3cbc94427c avoid `Symbol` to `String` conversions 2022-07-28 10:20:55 +09:00
Maybe Waffle 177af47104 Implement `#[rustc_default_body_unstable]`
This attribute allows to mark default body of a trait function as
unstable. This means that implementing the trait without implementing
the function will require enabling unstable feature.

This is useful in conjunction with `#[rustc_must_implement_one_of]`,
we may want to relax requirements for a trait, for example allowing
implementing either of `PartialEq::{eq, ne}`, but do so in a safe way
-- making implementation of only `PartialEq::ne` unstable.
2022-07-26 15:38:03 +04:00
bors 47ba935965 Auto merge of #99320 - NiklasJonsson:84447/rustc_expand, r=compiler-errors
rustc_expand: Switch FxHashMap to FxIndexMap where iteration is used

Relates #84447
2022-07-23 07:59:54 +00:00
Michael Goulet dd109c8c10 better error for bad depth on macro metavar expr 2022-07-19 16:41:32 +00:00
Matthias Krüger 19932a5533
Rollup merge of #99435 - CAD97:revert-dollar-dollar-crate, r=Mark-Simulacrum
Revert "Stabilize $$ in Rust 1.63.0"

This mechanically reverts commit 9edaa76adc, the one commit from #95860.

https://github.com/rust-lang/rust/issues/99035; the behavior of `$$crate` is potentially unexpected and not ready to be stabilized. https://github.com/rust-lang/rust/pull/99193 attempts to forbid `$$crate` without also destabilizing `$$` more generally.

`@rustbot` modify labels +T-compiler +T-lang +P-medium +beta-nominated +relnotes

(applying the labels I think are accurate from the issue and alternative partial revert)

cc `@Mark-Simulacrum`
2022-07-19 13:30:48 +02:00
Christopher Durham c0569f2aa7 Revert "Stabilize $$ in Rust 1.63.0"
This reverts commit 9edaa76adc.
2022-07-18 15:22:01 -04:00
Nika Layzell c4acac6443 proc_macro: Move subspan to be a method on Span in the bridge
This method is still only used for Literal::subspan, however the
implementation only depends on the Span component, so it is simpler and
more efficient for now to pass down only the information that is needed.
In the future, if more information about the Literal is required in the
implementation (e.g. to validate that spans line up as expected with
source text), that extra information can be added back with extra
arguments.
2022-07-18 13:06:51 -04:00
Nika Layzell b34c79f8f1 proc_macro: stop using a remote object handle for Literal
This builds on the symbol infrastructure built for `Ident` to replicate
the `LitKind` and `Lit` structures in rustc within the `proc_macro`
client, allowing literals to be fully created and interacted with from
the client thread. Only parsing and subspan operations still require
sync RPC.
2022-07-18 13:06:51 -04:00
Nika Layzell 491fccfbe3 proc_macro: stop using a remote object handle for Ident
Doing this for all unicode identifiers would require a dependency on
`unicode-normalization` and `rustc_lexer`, which is currently not
possible for `proc_macro` due to it being built concurrently with `std`
and `core`. Instead, ASCII identifiers are validated locally, and an RPC
message is used to validate unicode identifiers when needed.

String values are interned on the both the server and client when
deserializing, to avoid unnecessary copies and keep Ident cheap to copy and
move. This appears to be important for performance.

The client-side interner is based roughly on the one from rustc_span, and uses
an arena inspired by rustc_arena.

RPC messages passing symbols always include the full value. This could
potentially be optimized in the future if it is revealed to be a
performance bottleneck.

Despite now having a relevant implementaion of Display for Ident, ToString is
still specialized, as it is a hot-path for this object.

The symbol infrastructure will also be used for literals in the next
part.
2022-07-18 12:59:14 -04:00
Caio 3266460749 Stabilize `let_chains` 2022-07-16 20:17:58 -03:00
Matthias Krüger 6277ac2fb8
Rollup merge of #99342 - TaKO8Ki:avoid-symbol-to-string-conversions, r=compiler-errors
Avoid some `Symbol` to `String` conversions

This patch removes some Symbol to String conversions.
2022-07-16 22:30:56 +02:00
Takayuki Maeda c54d4ada26 avoid some `Symbol` to `String` conversions 2022-07-17 04:09:20 +09:00
Niklas Jonsson b47a934194 rustc_expand: Switch FxHashMap to FxIndexMap where iteration is used 2022-07-16 13:23:05 +02:00
Dylan DPC 8c5c983e5b
Rollup merge of #98580 - PrestonFrom:issue_98466, r=estebank
Emit warning when named arguments are used positionally in format

Addresses Issue 98466 by emitting an error if a named argument
is used like a position argument (i.e. the name is not used in
the string to be formatted).

Fixes rust-lang#98466
2022-07-14 19:24:03 +05:30
bors f1a8854f9b Auto merge of #99231 - Dylan-DPC:rollup-0tl8c0o, r=Dylan-DPC
Rollup of 5 pull requests

Successful merges:

 - #97720 (Always create elided lifetime parameters for functions)
 - #98315 (Stabilize `core::ffi:c_*` and rexport in `std::ffi`)
 - #98705 (Implement `for<>` lifetime binder for closures)
 - #99126 (remove allow(rustc::potential_query_instability) in rustc_span)
 - #99139 (Give a better error when `x dist` fails for an optional tool)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-07-14 11:00:30 +00:00
Dylan DPC e5a86d7358
Rollup merge of #98705 - WaffleLapkin:closure_binder, r=cjgillot
Implement `for<>` lifetime binder for closures

This PR implements RFC 3216 ([TI](https://github.com/rust-lang/rust/issues/97362)) and allows code like the following:

```rust
let _f = for<'a, 'b> |a: &'a A, b: &'b B| -> &'b C { b.c(a) };
//       ^^^^^^^^^^^--- new!
```

cc ``@Aaron1011`` ``@cjgillot``
2022-07-14 14:14:21 +05:30
Joshua Nelson 3c9765cff1 Rename `debugging_opts` to `unstable_opts`
This is no longer used only for debugging options (e.g. `-Zoutput-width`, `-Zallow-features`).
Rename it to be more clear.
2022-07-13 17:47:06 -05:00
Preston From 1219f72f90 Emit warning when named arguments are used positionally in format
Addresses Issue 98466 by emitting a warning if a named argument
is used like a position argument (i.e. the name is not used in
the string to be formatted).

Fixes rust-lang#98466
2022-07-13 15:34:10 -06:00
Maybe Waffle 40ae7b5b8e Parse closure binders
This is first step in implementing RFC 3216.
- Parse `for<'a>` before closures in ast
  - Error in lowering
- Add `closure_lifetime_binder` feature
2022-07-12 16:25:16 +04:00
Michael Goulet d2e5a929b9 use subdiagnostic for message 2022-07-10 23:43:46 +00:00
Michael Goulet 2a973e2abc explain doc comments in macros a bit 2022-07-10 23:42:50 +00:00
bors 29554c0a12 Auto merge of #98463 - mystor:expand_expr_bool, r=eddyb
proc_macro: Fix expand_expr expansion of bool literals

Previously, the expand_expr method would expand bool literals as a
`Literal` token containing a `LitKind::Bool`, rather than as an `Ident`.
This is not a valid token, and the `LitKind::Bool` case needs to be
handled seperately.

Tests were added to more deeply compare the streams in the expand-expr
test suite to catch mistakes like this in the future.
2022-07-10 14:02:45 +00:00
bors d46c728bcd Auto merge of #98446 - nnethercote:derive-no-match-destructuring, r=scottmcm
Don't use match-destructuring for derived ops on structs.

r? `@scottmcm`
2022-07-04 01:06:54 +00:00
Nicholas Nethercote ecc6e95ed4 Don't use match-destructuring for derived ops on structs.
All derive ops currently use match-destructuring to access fields. This
is reasonable for enums, but sub-optimal for structs. E.g.:
```
fn eq(&self, other: &Point) -> bool {
    match *other {
	Self { x: ref __self_1_0, y: ref __self_1_1 } =>
	    match *self {
		Self { x: ref __self_0_0, y: ref __self_0_1 } =>
		    (*__self_0_0) == (*__self_1_0) &&
			(*__self_0_1) == (*__self_1_1),
	    },
    }
}
```
This commit changes derive ops on structs to use field access instead, e.g.:
```
fn eq(&self, other: &Point) -> bool {
    self.x == other.x && self.y == other.y
}
```
This is faster to compile, results in smaller binaries, and is simpler to
generate. Unfortunately, we have to keep the old pattern generating code around
for `repr(packed)` structs because something like `&self.x` (which doesn't show
up in `PartialEq` ops, but does show up in `Debug` and `Hash` ops) isn't
allowed. But this commit at least changes those cases to use let-destructuring
instead of match-destructuring, e.g.:
```
fn hash<__H: ::core:#️⃣:Hasher>(&self, state: &mut __H) -> () {
    {
	let Self(ref __self_0_0) = *self;
	{ ::core:#️⃣:Hash::hash(&(*__self_0_0), state) }
    }
}
```
There are some unnecessary blocks remaining in the generated code, but I
will fix them in a follow-up PR.
2022-07-04 10:48:15 +10:00
bors ada8c80bed Auto merge of #98673 - pietroalbini:pa-bootstrap-update, r=Mark-Simulacrum
Bump bootstrap compiler

r? `@Mark-Simulacrum`
2022-07-03 06:55:50 +00:00
Pietro Albini 6b2d3d5f3c
update cfg(bootstrap)s 2022-07-01 15:48:23 +02:00
Matthias Krüger d34c4ca9be
Rollup merge of #98668 - TaKO8Ki:avoid-many-&str-to-string-conversions, r=Dylan-DPC
Avoid some `&str` to `String` conversions with `MultiSpan::push_span_label`

This patch removes some`&str` to `String` conversions with `MultiSpan::push_span_label`.
2022-06-29 20:35:07 +02:00
Takayuki Maeda 6212e6b339 avoid many `&str` to `String` conversions with `MultiSpan::push_span_label` 2022-06-29 21:16:43 +09:00
bors 66c83ffca1 Auto merge of #98558 - nnethercote:smallvec-1.8.1, r=lqd
Update `smallvec` to 1.8.1.

This pulls in https://github.com/servo/rust-smallvec/pull/282, which
gives some small wins for rustc.

r? `@lqd`
2022-06-29 09:11:29 +00:00
bors 94e93749ab Auto merge of #98188 - mystor:fast_group_punct, r=eddyb
proc_macro/bridge: stop using a remote object handle for proc_macro Punct and Group

This is the third part of https://github.com/rust-lang/rust/pull/86822, split off as requested in https://github.com/rust-lang/rust/pull/86822#pullrequestreview-1008655452. This patch transforms the `Punct` and `Group` types into structs serialized over IPC rather than handles, making them more efficient to create and manipulate from within proc-macros.
2022-06-28 16:10:30 +00:00
Nika Layzell 64a7d57046 review changes
longer names for RPC generics and reduced dependency on macros in the server.
2022-06-28 09:54:29 -04:00
David Wood ae612241dc various: add `rustc_lint_diagnostics` to diag fns
The `rustc_lint_diagnostics` attribute is used by the diagnostic
translation/struct migration lints to identify calls where
non-translatable diagnostics or diagnostics outwith impls are being
created. Any function used in creating a diagnostic should be annotated
with this attribute so this commit adds the attribute to many more
functions.

Signed-off-by: David Wood <david.wood@huawei.com>
2022-06-27 08:32:06 +01:00
Nika Layzell f28dfdf1c7 proc_macro: stop using a remote object handle for Group
This greatly reduces round-trips to fetch relevant extra information about the
token in proc macro code, and avoids RPC messages to create Group tokens.
2022-06-26 22:20:33 -04:00
Nika Layzell 72bfe618fa proc_macro: stop using a remote object handle for Punct
This greatly reduces round-trips to fetch relevant extra information about the
token in proc macro code, and avoids RPC messages to create Punct tokens.
2022-06-26 22:20:33 -04:00
Nicholas Nethercote 7c40661ddb Update `smallvec` to 1.8.1.
This pulls in https://github.com/servo/rust-smallvec/pull/282, which
gives some small wins for rustc.
2022-06-27 08:48:55 +10:00
bors 3b0d4813ab Auto merge of #98187 - mystor:fast_span_call_site, r=eddyb
proc_macro/bridge: cache static spans in proc_macro's client thread-local state

This is the second part of https://github.com/rust-lang/rust/pull/86822, split off as requested in https://github.com/rust-lang/rust/pull/86822#pullrequestreview-1008655452. This patch removes the RPC calls required for the very common operations of `Span::call_site()`, `Span::def_site()` and `Span::mixed_site()`.

Some notes:

This part is one of the ones I don't love as a final solution from a design standpoint, because I don't like how the spans are serialized immediately at macro invocation. I think a more elegant solution might've been to reserve special IDs for `call_site`, `def_site`, and `mixed_site` at compile time (either starting at 1 or from `u32::MAX`) and making reading a Span handle automatically map these IDs to the relevant values, rather than doing extra serialization.

This would also have an advantage for potential future work to allow `proc_macro` to operate more independently from the compiler (e.g. to reduce the necessity of `proc-macro2`), as methods like `Span::call_site()` could be made to function without access to the compiler backend.

That was unfortunately tricky to do at the time, as this was the first part I wrote of the patches. After the later part (#98188, #98189), the other uses of `InternedStore` are removed meaning that a custom serialization strategy for `Span` is easier to implement.

If we want to go that path, we'll still need the majority of the work to split the bridge object and introduce the `Context` trait for free methods, and it will be easier to do after `Span` is the only user of `InternedStore` (after #98189).
2022-06-26 21:28:24 +00:00
Nika Layzell e32ee19b3a proc_macro: Rename ExpnContext to ExpnGlobals, and unify method on Server trait 2022-06-26 12:48:33 -04:00
bors 788ddedb0d Auto merge of #98190 - nnethercote:optimize-derive-Debug-code, r=scottmcm
Improve `derive(Debug)`

r? `@ghost`
2022-06-26 15:00:04 +00:00
Nika Layzell 2456ff8928 proc_macro: remove Context trait, and put span methods directly on Server 2022-06-25 12:26:21 -04:00
Nika Layzell 55f052d9c9 proc_macro: cache static spans in client's thread-local state
This greatly improves the performance of the very frequently called
`call_site()` macro when running in a cross-thread configuration.
2022-06-25 10:28:11 -04:00
Nika Layzell fb5b7b4af2 proc_macro: Fix expand_expr expansion of bool literals
Previously, the expand_expr method would expand bool literals as a
`Literal` token containing a `LitKind::Bool`, rather than as an `Ident`.
This is not a valid token, and the `LitKind::Bool` case needs to be
handled seperately.

Tests were added to more deeply compare the streams in the expand-expr
test suite to catch mistakes like this in the future.
2022-06-24 13:43:26 -04:00
Nicholas Nethercote 5b54363961 Optimize the code produced by `derive(Debug)`.
This commit adds new methods that combine sequences of existing
formatting methods.
- `Formatter::debug_{tuple,struct}_field[12345]_finish`, equivalent to a
  `Formatter::debug_{tuple,struct}` + N x `Debug{Tuple,Struct}::field` +
  `Debug{Tuple,Struct}::finish` call sequence.
- `Formatter::debug_{tuple,struct}_fields_finish` is similar, but can
  handle any number of fields by using arrays.

These new methods are all marked as `doc(hidden)` and unstable. They are
intended for the compiler's own use.

Special-casing up to 5 fields gives significantly better performance
results than always using arrays (as was tried in #95637).

The commit also changes the `Debug` deriving code to use these new methods. For
example, where the old `Debug` code for a struct with two fields would be like
this:
```
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
    match *self {
	Self {
	    f1: ref __self_0_0,
	    f2: ref __self_0_1,
	} => {
	    let debug_trait_builder = &mut ::core::fmt::Formatter::debug_struct(f, "S2");
	    let _ = ::core::fmt::DebugStruct::field(debug_trait_builder, "f1", &&(*__self_0_0));
	    let _ = ::core::fmt::DebugStruct::field(debug_trait_builder, "f2", &&(*__self_0_1));
	    ::core::fmt::DebugStruct::finish(debug_trait_builder)
	}
    }
}
```
the new code is like this:
```
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
    match *self {
	Self {
	    f1: ref __self_0_0,
	    f2: ref __self_0_1,
	} => ::core::fmt::Formatter::debug_struct_field2_finish(
	    f,
	    "S2",
	    "f1",
	    &&(*__self_0_0),
	    "f2",
	    &&(*__self_0_1),
	),
    }
}
```
This shrinks the code produced for `Debug` instances
considerably, reducing compile times and binary sizes.

Co-authored-by: Scott McMurray <scottmcm@users.noreply.github.com>
2022-06-24 09:40:15 +10:00
Nicholas Nethercote 7586e79af8 Rename some `ExtCtxt` methods.
The new names are more accurate.

Co-authored-by: Scott McMurray <scottmcm@users.noreply.github.com>
2022-06-23 11:10:43 +10:00
beetrees 761c846a07
Add `create_err` and `emit_err` to `ExtCtxt` 2022-06-21 18:56:04 +01:00
Nicholas Nethercote 69f45b7860 Add blank lines between methods in `proc_macro_server.rs`.
Because that's the standard way of doing it.
2022-06-20 13:52:48 +10:00
Nicholas Nethercote f6b57883e0 Remove `TokenStream::from_streams`.
By inlining it into the only non-test call site. The one test call site
is changed to use `TokenStreamBuilder`.
2022-06-20 09:33:08 +10:00
Nicholas Nethercote ccd956aca6 Remove `Cursor::append`.
It's a weird function: it lets you modify the token stream in the middle
of iteration. There is only one call site, and it is only used for the
rare `ProceduralMasquerade` legacy case.
2022-06-20 09:19:10 +10:00
bors 0182fd99af Auto merge of #98186 - mystor:tokenstream_as_vec_tt, r=eddyb
Batch proc_macro RPC for TokenStream iteration and combination operations

This is the first part of #86822, split off as requested in https://github.com/rust-lang/rust/pull/86822#pullrequestreview-1008655452. It reduces the number of RPC calls required for common operations such as iterating over and concatenating TokenStreams.
2022-06-18 07:37:14 +00:00
Nika Layzell df925fda9c review fixups 2022-06-17 22:10:07 -04:00
Nika Layzell 4d45af9e73 Try to reduce codegen complexity of TokenStream's FromIterator and Extend impls
This is an experimental patch to try to reduce the codegen complexity of
TokenStream's FromIterator and Extend implementations for downstream
crates, by moving the core logic into a helper type. This might help
improve build performance of crates which depend on proc_macro as
iterators are used less, and the compiler may take less time to do
things like attempt specializations or other iterator optimizations.

The change intentionally sacrifices some optimization opportunities,
such as using the specializations for collecting iterators derived from
Vec::into_iter() into Vec.

This is one of the simpler potential approaches to reducing the amount
of code generated in crates depending on proc_macro, so it seems worth
trying before other more-involved changes.
2022-06-17 00:42:26 -04:00
Nika Layzell 0a049fd30d proc_macro: reduce the number of messages required to create, extend, and iterate TokenStreams
This significantly reduces the cost of common interactions with TokenStream
when running with the CrossThread execution strategy, by reducing the number of
RPC calls required.
2022-06-17 00:42:26 -04:00
Matthias Krüger 95be954af4
Rollup merge of #97757 - xFrednet:rfc-2383-expect-with-force-warn, r=wesleywiser,flip1995
Support lint expectations for `--force-warn` lints (RFC 2383)

Rustc has a `--force-warn` flag, which overrides lint level attributes and forces the diagnostics to always be warn. This means, that for lint expectations, the diagnostic can't be suppressed as usual. This also means that the expectation would not be fulfilled, even if a lint had been triggered in the expected scope.

This PR now also tracks the expectation ID in the `ForceWarn` level. I've also made some minor adjustments, to possibly catch more bugs and make the whole implementation more robust.

This will probably conflict with https://github.com/rust-lang/rust/pull/97718. That PR should ideally be reviewed and merged first. The conflict itself will be trivial to fix.

---

r? `@wesleywiser`

cc: `@flip1995` since you've helped with the initial review and also discussed this topic with me. 🙃

Follow-up of: https://github.com/rust-lang/rust/pull/87835

Issue: https://github.com/rust-lang/rust/issues/85549

Yeah, and that's it.
2022-06-16 09:10:20 +02:00
xFrednet 8527a3d369
Support lint expectations for `--force-warn` lints (RFC 2383) 2022-06-16 08:16:43 +02:00
Takayuki Maeda 77d6176e69 remove unnecessary `to_string` and `String::new` 2022-06-13 15:48:40 +09:00
bors 1fb9603022 Auto merge of #98020 - TaKO8Ki:use-create-snapshot-for-diagnostic-in-rustc-expand, r=Dylan-DPC
Use `create_snapshot_for_diagnostic` instead of `clone` for `Parser`

Use [`create_snapshot_for_diagnostic`](cd11905716/compiler/rustc_parse/src/parser/diagnostics.rs (L214-L223)) I implemented in https://github.com/rust-lang/rust/pull/94731 instead of `clone` to avoid duplicate unclosed delims errors being emitted when the `Parser` is dropped. I missed this one in #95068.
2022-06-12 23:25:35 +00:00
Takayuki Maeda 84a13a28b7 use `create_snapshot_for_diagnostic` instead of `clone` 2022-06-12 17:27:36 +09:00
bors fa68e73e99 Auto merge of #97903 - est31:unused_macro_rules_compile_error, r=petrochenkov
Never regard macro rules with compile_error! invocations as unused

The very point of compile_error! is to never be reached, and one of
the use cases of the macro, currently also listed as examples in the
documentation of compile_error, is to create nicer errors for wrong
macro invocations. Thus, we should never warn about unused macro arms
that contain invocations of compile_error.

See also https://github.com/rust-lang/rust/pull/96150#issuecomment-1126599107 and the discussion after that.

Furthermore, the PR also contains two commits to silence `unused_macro_rules` when a macro has an invalid rule, and to add a test that `unused_macros` does not behave badly in the same situation.

r? `@petrochenkov` as I've talked to them about this
2022-06-11 08:46:21 +00:00
est31 777e136f4c Suppress the unused_macro_rules lint if malformed rules are encountered
Prior to this commit, if a macro had any malformed rules, all rules would
be reported as unused, regardless of whether they were used or not.
So we just turn off unused rule checking completely for macros with
malformed rules.
2022-06-09 23:34:06 +02:00
est31 eb3c611e1d Never regard macro rules with compile_error! invocations as unused
The very point of compile_error! is to never be reached, and one of
the use cases of the macro, currently also listed as examples in the
documentation of compile_error, is to create nicer errors for wrong
macro invocations. Thus, we shuuld never warn about unused macro arms
that contain invocations of compile_error.
2022-06-09 23:21:06 +02:00
Yuki Okushi afa2edbe42
Rollup merge of #95860 - c410-f3r:stabilize-meta, r=joshtriplett
Stabilize `$$` in Rust 1.63.0

# Stabilization proposal

This PR proposes the stabilization of a subset of `#![feature(macro_metavar_expr)]` or more specifically, the stabilization of dollar-dollar (`$$`).

Tracking issue: #83527
Version: 1.63 (2022-06-28 => beta, 2022-08-11 => stable).

## What is stabilized

```rust
macro_rules! foo {
    () => {
        macro_rules! bar {
            ( $$( $$any:tt )* ) => { $$( $$any )* };
        }
    };
}

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

## Motivation

For more examples, see the [RFC](https://github.com/markbt/rfcs/blob/macro_metavar_expr/text/0000-macro-metavar-expr.md).

Users must currently resort to a tricky and not so well-known hack to declare nested macros with repetitions.

```rust
macro_rules! foo {
    ($dollar:tt) => {
        macro_rules! bar {
            ( $dollar ( $any:tt )* ) => { $dollar ( $any )* };
        }
    };
}
fn main() {
    foo!($);
}
```

As seen above, such hack is fragile and makes work with declarative macros much more unpleasant. Dollar-dollar (`$$`), on the other hand, makes nested macros more intuitive.

## What isn't stabilized

`count`, `ignore`, `index` and `length` are not being stabilized due to the lack of consensus.

## History

* 2021-02-22, [RFC: Declarative macro metavariable expressions](https://github.com/rust-lang/rfcs/pull/3086)
* 2021-03-26, [Tracking Issue for RFC 3086: macro metavariable expressions](https://github.com/rust-lang/rust/issues/83527)
* 2022-02-01, [Implement macro meta-variable expressions](https://github.com/rust-lang/rust/pull/93545)
* 2022-02-25, [[1/2] Implement macro meta-variable expressions](https://github.com/rust-lang/rust/pull/94368)
* 2022-03-11, [[2/2] Implement macro meta-variable expressions](https://github.com/rust-lang/rust/pull/94833)
* 2022-03-12, [Fix remaining meta-variable expression TODOs](https://github.com/rust-lang/rust/pull/94884)
* 2019-03-21, [[macro-metavar-expr] Fix generated tokens hygiene](https://github.com/rust-lang/rust/pull/95188)
* 2022-04-07, [Kickstart the inner usage of macro_metavar_expr](https://github.com/rust-lang/rust/pull/95761)
* 2022-04-07, [[macro_metavar_expr] Add tests to ensure the feature requirement](https://github.com/rust-lang/rust/pull/95764)

## Non-stabilized expressions

https://github.com/rust-lang/rust/issues/83527 lists several concerns about some characteristics of `count`, `index` and `length` that effectively make their stabilization unfeasible. `$$` and `ignore`, however, are not part of any discussion and thus are suitable for stabilization.

It is not in the scope of this PR to detail each concern or suggest any possible converging solution. Such thing should be restrained in this tracking issue.

## Tests

This list is a subset of https://github.com/rust-lang/rust/tree/master/src/test/ui/macros/rfc-3086-metavar-expr

* [Ensures that nested macros have correct behavior](https://github.com/rust-lang/rust/blob/master/src/test/ui/macros/rfc-3086-metavar-expr/dollar-dollar-has-correct-behavior.rs)

* [Compares produced tokens to assert expected outputs](https://github.com/rust-lang/rust/blob/master/src/test/ui/macros/rfc-3086-metavar-expr/feature-gate-macro_metavar_expr.rs)

* [Checks the declarations of the feature](https://github.com/rust-lang/rust/blob/master/src/test/ui/macros/rfc-3086-metavar-expr/required-feature.rs)

* [Verifies all possible errors that can occur due to incorrect user input](https://github.com/rust-lang/rust/blob/master/src/test/ui/macros/rfc-3086-metavar-expr/syntax-errors.rs)

## Possible future work

Once consensus is achieved, other nightly expressions can be stabilized.

Thanks ``@markbt`` for creating the RFC and thanks to ``@petrochenkov`` and ``@mark-i-m`` for reviewing the implementations.
2022-06-09 19:19:55 +09:00
Chayim Refael Friedman f4ba14d290
Fix typo: fo->for 2022-06-08 16:40:02 +03:00
Caio 9edaa76adc Stabilize $$ in Rust 1.63.0 2022-06-07 21:50:45 -03:00
Caio aa115eba12 Basic compiler infra 2022-06-02 09:00:04 -03:00
Michael Goulet f20bbc1fb0
Rollup merge of #97536 - est31:remove_unused_lifetimes, r=compiler-errors
Remove unused lifetimes from expand_macro

The function doesn't need the lifetimes
of the two arguments be bound together.
2022-05-29 16:25:05 -07:00
est31 311aacf0d0 Remove unused lifetimes from expand_macro
The function doesn't need the lifetimes
of the two arguments be bound together.
2022-05-29 23:53:24 +02:00
Guillaume Gomez a777d50b24
Rollup merge of #97478 - JohnTitor:fixme-fn-decl, r=compiler-errors
Remove FIXME on `ExtCtxt::fn_decl()`

`ExtCtxt::fn_decl()` is used like `self.fn_decl(..)` or `self.cx.fn_decl(..)`, coverting it to an assoc fn, for example, makes it inconvenience (e.g. `self.cx.fn_decl(..)` would be longer to represent). Given that, it doesn't seem a "FIXME" thing and unused `self` is okay, I think.
2022-05-29 01:12:30 +02:00
Yuki Okushi 643c508e86
Remove FIXME on `ExtCtxt::fn_decl()` 2022-05-28 18:12:34 +09:00
Eduard-Mihai Burtescu 78a83b0d5f proc_macro: don't pass a client-side function pointer through the server. 2022-05-27 19:29:21 +00:00
Nicholas Nethercote bc70d0db92 Rename `ProcMacroDerive` as `DeriveProcMacro`.
So it matches the existing `AttrProcMacro` and `BangProcMacro` types.
2022-05-27 15:58:35 +10:00
Nicholas Nethercote dbdc7dd0dc Rename `ProcMacro` trait as `BangProcMacro`.
Similar to the existing `AttrProcMacro` trait.
2022-05-27 15:58:35 +10:00
Vadim Petrochenkov 8e8fb4f49e rustc_parse: Move AST -> TokenStream conversion logic to `rustc_ast` 2022-05-22 12:01:07 +03:00
Jacob Pratt 49c82f31a8
Remove `crate` visibility usage in compiler 2022-05-20 20:04:54 -04:00
klensy cc5f3e21ac use `CursorRef` more, to not to clone `Tree`s 2022-05-18 18:43:48 +03:00
est31 e6ccf9b5d8 Use pluralize in one instance 2022-05-13 08:48:35 +02:00
est31 cc3c5d2700 Improve name and documentation of generic_extension
This function doesn't *create* a (rules based) macro, it *expands* it.
Thus, the documentation was wrong.
2022-05-13 08:42:39 +02:00
bors 0cd939e36c Auto merge of #96150 - est31:unused_macro_rules, r=petrochenkov
Implement a lint to warn about unused macro rules

This implements a new lint to warn about unused macro rules (arms/matchers), similar to the `unused_macros` lint added by #41907 that warns about entire macros.

```rust
macro_rules! unused_empty {
    (hello) => { println!("Hello, world!") };
    () => { println!("empty") }; //~ ERROR: 1st rule of macro `unused_empty` is never used
}

fn main() {
    unused_empty!(hello);
}
```

Builds upon #96149 and #96156.

Fixes #73576
2022-05-12 00:08:08 +00:00
Vadim Petrochenkov f2b7fa4847 ast: Introduce some traits to get AST node properties generically
And use them to avoid constructing some artificial `Nonterminal` tokens during expansion
2022-05-11 12:43:27 +03:00
bors 574830f573 Auto merge of #96094 - Elliot-Roberts:fix_doctests, r=compiler-errors
Begin fixing all the broken doctests in `compiler/`

Begins to fix #95994.
All of them pass now but 24 of them I've marked with `ignore HELP (<explanation>)` (asking for help) as I'm unsure how to get them to work / if we should leave them as they are.
There are also a few that I marked `ignore` that could maybe be made to work but seem less important.
Each `ignore` has a rough "reason" for ignoring after it parentheses, with

- `(pseudo-rust)` meaning "mostly rust-like but contains foreign syntax"
- `(illustrative)` a somewhat catchall for either a fragment of rust that doesn't stand on its own (like a lone type), or abbreviated rust with ellipses and undeclared types that would get too cluttered if made compile-worthy.
- `(not-rust)` stuff that isn't rust but benefits from the syntax highlighting, like MIR.
- `(internal)` uses `rustc_*` code which would be difficult to make work with the testing setup.

Those reason notes are a bit inconsistently applied and messy though. If that's important I can go through them again and try a more principled approach. When I run `rg '```ignore \(' .` on the repo, there look to be lots of different conventions other people have used for this sort of thing. I could try unifying them all if that would be helpful.

I'm not sure if there was a better existing way to do this but I wrote my own script to help me run all the doctests and wade through the output. If that would be useful to anyone else, I put it here: https://github.com/Elliot-Roberts/rust_doctest_fixing_tool
2022-05-07 06:30:29 +00:00
est31 0bd2232fe4 Implement the unused_macro_rules lint 2022-05-05 19:13:00 +02:00
bors a7d6768e3b Auto merge of #91779 - ridwanabdillahi:natvis, r=michaelwoerister
Add a new Rust attribute to support embedding debugger visualizers

Implemented [this RFC](https://github.com/rust-lang/rfcs/pull/3191) to add support for embedding debugger visualizers into a PDB.

Added a new attribute `#[debugger_visualizer]` and updated the `CrateMetadata` to store debugger visualizers for crate dependencies.

RFC: https://github.com/rust-lang/rfcs/pull/3191
2022-05-05 12:26:38 +00:00
bors 343889b723 Auto merge of #96683 - nnethercote:speed-up-Token-ident-lifetime, r=petrochenkov
Speed up `Token::{ident,lifetime}`

Some speed and cleanliness improvements.

r? `@petrochenkov`
2022-05-04 15:24:02 +00:00
Nicholas Nethercote bbef9756ea Fix spelling of an identifier. 2022-05-04 06:15:36 +10:00
ridwanabdillahi 175a4eab84 Add support for a new attribute `#[debugger_visualizer]` to support embedding debugger visualizers into a generated PDB.
Cleanup `DebuggerVisualizerFile` type and other minor cleanup of queries.

Merge the queries for debugger visualizers into a single query.

Revert move of `resolve_path` to `rustc_builtin_macros`. Update dependencies in Cargo.toml for `rustc_passes`.

Respond to PR comments. Load visualizer files into opaque bytes `Vec<u8>`. Debugger visualizers for dynamically linked crates should not be embedded in the current crate.

Update the unstable book with the new feature. Add the tracking issue for the debugger_visualizer feature.

Respond to PR comments and minor cleanups.
2022-05-03 10:53:54 -07:00
Elliot Roberts 7907385999 fix most compiler/ doctests 2022-05-02 17:40:30 -07:00
Camille GILLOT 74583852e8 Save colon span to suggest bounds. 2022-04-30 13:55:17 +02:00
David Wood 73fa217bc1 errors: `span_suggestion` takes `impl ToString`
Change `span_suggestion` (and variants) to take `impl ToString` rather
than `String` for the suggested code, as this simplifies the
requirements on the diagnostic derive.

Signed-off-by: David Wood <david.wood@huawei.com>
2022-04-29 02:05:20 +01:00
Vadim Petrochenkov 2733ec1be3 rustc_ast: Harmonize delimiter naming with `proc_macro::Delimiter` 2022-04-28 10:04:29 +03:00
Dylan DPC 4c628bbb1c
Rollup merge of #96471 - BoxyUwU:let_else_considered_harmful, r=lcnr
replace let else with `?`

r? `@oli-obk`
2022-04-28 02:40:36 +02:00