about summary refs log tree commit diff
path: root/compiler/rustc_expand/src
AgeCommit message (Collapse)AuthorLines
2022-06-29avoid many `&str` to `String` conversions with `MultiSpan::push_span_label`Takayuki Maeda-1/+1
2022-06-28Auto merge of #98188 - mystor:fast_group_punct, r=eddybbors-281/+174
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-28review changesNika Layzell-104/+95
longer names for RPC generics and reduced dependency on macros in the server.
2022-06-27various: add `rustc_lint_diagnostics` to diag fnsDavid Wood-0/+4
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-26proc_macro: stop using a remote object handle for GroupNika Layzell-214/+160
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-26proc_macro: stop using a remote object handle for PunctNika Layzell-60/+16
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-26Auto merge of #98187 - mystor:fast_span_call_site, r=eddybbors-16/+14
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-26proc_macro: Rename ExpnContext to ExpnGlobals, and unify method on Server traitNika Layzell-17/+10
2022-06-26Auto merge of #98190 - nnethercote:optimize-derive-Debug-code, r=scottmcmbors-4/+27
Improve `derive(Debug)` r? `@ghost`
2022-06-25proc_macro: remove Context trait, and put span methods directly on ServerNika Layzell-4/+4
2022-06-25proc_macro: cache static spans in client's thread-local stateNika Layzell-15/+20
This greatly improves the performance of the very frequently called `call_site()` macro when running in a cross-thread configuration.
2022-06-24proc_macro: Fix expand_expr expansion of bool literalsNika Layzell-0/+4
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-24Optimize the code produced by `derive(Debug)`.Nicholas Nethercote-1/+20
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-23Rename some `ExtCtxt` methods.Nicholas Nethercote-3/+7
The new names are more accurate. Co-authored-by: Scott McMurray <scottmcm@users.noreply.github.com>
2022-06-21Add `create_err` and `emit_err` to `ExtCtxt`beetrees-1/+12
2022-06-20Add blank lines between methods in `proc_macro_server.rs`.Nicholas Nethercote-0/+54
Because that's the standard way of doing it.
2022-06-20Remove `TokenStream::from_streams`.Nicholas Nethercote-2/+4
By inlining it into the only non-test call site. The one test call site is changed to use `TokenStreamBuilder`.
2022-06-20Remove `Cursor::append`.Nicholas Nethercote-3/+3
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-18Auto merge of #98186 - mystor:tokenstream_as_vec_tt, r=eddybbors-44/+55
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-17review fixupsNika Layzell-3/+4
2022-06-17Try to reduce codegen complexity of TokenStream's FromIterator and Extend implsNika Layzell-2/+2
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-17proc_macro: reduce the number of messages required to create, extend, and ↵Nika Layzell-44/+54
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-16Rollup merge of #97757 - xFrednet:rfc-2383-expect-with-force-warn, ↵Matthias Krüger-1/+1
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. :upside_down_face: 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-16Support lint expectations for `--force-warn` lints (RFC 2383)xFrednet-1/+1
2022-06-13remove unnecessary `to_string` and `String::new`Takayuki Maeda-6/+6
2022-06-12Auto merge of #98020 - ↵bors-1/+1
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`](https://github.com/rust-lang/rust/blob/cd119057160cedea245aa2679add56723f3dc784/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-12use `create_snapshot_for_diagnostic` instead of `clone`Takayuki Maeda-1/+1
2022-06-11Auto merge of #97903 - est31:unused_macro_rules_compile_error, r=petrochenkovbors-6/+41
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-09Suppress the unused_macro_rules lint if malformed rules are encounteredest31-4/+6
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-09Never regard macro rules with compile_error! invocations as unusedest31-2/+35
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-09Rollup merge of #95860 - c410-f3r:stabilize-meta, r=joshtriplettYuki Okushi-2/+0
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-08Fix typo: fo->forChayim Refael Friedman-1/+1
2022-06-07Stabilize $$ in Rust 1.63.0Caio-2/+0
2022-06-02Basic compiler infraCaio-1/+5
2022-05-29Rollup merge of #97536 - est31:remove_unused_lifetimes, r=compiler-errorsMichael Goulet-3/+3
Remove unused lifetimes from expand_macro The function doesn't need the lifetimes of the two arguments be bound together.
2022-05-29Remove unused lifetimes from expand_macroest31-3/+3
The function doesn't need the lifetimes of the two arguments be bound together.
2022-05-29Rollup merge of #97478 - JohnTitor:fixme-fn-decl, r=compiler-errorsGuillaume Gomez-1/+1
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-28Remove FIXME on `ExtCtxt::fn_decl()`Yuki Okushi-1/+1
2022-05-27proc_macro: don't pass a client-side function pointer through the server.Eduard-Mihai Burtescu-3/+3
2022-05-27Rename `ProcMacroDerive` as `DeriveProcMacro`.Nicholas Nethercote-2/+2
So it matches the existing `AttrProcMacro` and `BangProcMacro` types.
2022-05-27Rename `ProcMacro` trait as `BangProcMacro`.Nicholas Nethercote-4/+4
Similar to the existing `AttrProcMacro` trait.
2022-05-22rustc_parse: Move AST -> TokenStream conversion logic to `rustc_ast`Vadim Petrochenkov-19/+18
2022-05-20Remove `crate` visibility usage in compilerJacob Pratt-33/+32
2022-05-18use `CursorRef` more, to not to clone `Tree`sklensy-18/+20
2022-05-13Use pluralize in one instanceest31-2/+2
2022-05-13Improve name and documentation of generic_extensionest31-3/+4
This function doesn't *create* a (rules based) macro, it *expands* it. Thus, the documentation was wrong.
2022-05-12Auto merge of #96150 - est31:unused_macro_rules, r=petrochenkovbors-12/+30
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-11ast: Introduce some traits to get AST node properties genericallyVadim Petrochenkov-119/+70
And use them to avoid constructing some artificial `Nonterminal` tokens during expansion
2022-05-07Auto merge of #96094 - Elliot-Roberts:fix_doctests, r=compiler-errorsbors-5/+6
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-05Implement the unused_macro_rules lintest31-12/+30