Commit Graph

502 Commits

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