Commit Graph

731 Commits

Author SHA1 Message Date
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