about summary refs log tree commit diff
path: root/compiler/rustc_expand/src
AgeCommit message (Collapse)AuthorLines
2025-07-03Port `#[target_feature]` to the new attribute parsing infrastructureJonathan Brouwer-1/+1
Signed-off-by: Jonathan Brouwer <jonathantbrouwer@gmail.com>
2025-07-02Rollup merge of #143070 - joshtriplett:macro-rules-parse, r=petrochenkovMatthias Krüger-206/+61
Rewrite `macro_rules!` parser to not use the MBE engine itself The `macro_rules!` parser was written to match the series of rules using the macros-by-example (MBE) engine and a hand-written equivalent of the left-hand side of a MBE macro. This was complex to read, difficult to extend, and produced confusing error messages. Because it was using the MBE engine, any parse failure would be reported as if some macro was being applied to the `macro_rules!` invocation itself; for instance, errors would talk about "macro invocation", "macro arguments", and "macro call", when they were actually about the macro *definition*. And in practice, the `macro_rules!` parser only used the MBE engine to extract the left-hand side and right-hand side of each rule as a token tree, and then parsed the rest using a separate parser. Rewrite it to parse the series of rules using a simple loop, instead. This makes it more extensible in the future, and improves error messages. For instance, omitting a semicolon between rules will result in "expected `;`" and "unexpected token", rather than the confusing "no rules expected this token in macro call". This work was greatly aided by pair programming with Vincenzo Palazzo (`@vincenzopalazzo)` and Eric Holk (`@eholk).` For review, I recommend reading the two commits separately.
2025-07-02Rollup merge of #142237 - benschulz:unused-parens-fn, r=fee1-deadMatthias Krüger-0/+1
Detect more cases of unused_parens around types With this change, more unused parentheses around bounds and types nested within bounds are detected.
2025-07-01Detect more cases of unused_parens around typesBenjamin Schulz-0/+1
2025-07-01Auto merge of #143267 - matthiaskrgr:rollup-suvzar6, r=matthiaskrgrbors-60/+70
Rollup of 8 pull requests Successful merges: - rust-lang/rust#143125 (Disable f16 on Aarch64 without neon for llvm < 20.1.1) - rust-lang/rust#143156 (inherit `#[align]` from trait method prototypes) - rust-lang/rust#143178 (rustdoc default faviocon) - rust-lang/rust#143234 (Replace `ItemCtxt::report_placeholder_type_error` match with a call to `TyCtxt::def_descr`) - rust-lang/rust#143245 (mbe: Add tests and restructure metavariable expressions) - rust-lang/rust#143257 (Upgrade dependencies in run-make-support) - rust-lang/rust#143263 (linkify CodeSuggestion in doc comments) - rust-lang/rust#143264 (fix: Emit suggestion filename if primary diagnostic span is dummy) Failed merges: - rust-lang/rust#143251 (bootstrap: add build.tidy-extra-checks option) r? `@ghost` `@rustbot` modify labels: rollup
2025-07-01Rollup merge of #143245 - tgross35:metavariable-expr-organization, ↵Matthias Krüger-60/+70
r=petrochenkov mbe: Add tests and restructure metavariable expressions Add tests that show better diagnostics, and factor `concat` handling to a separate function. Each commit message has further details. This performs the nonfunctional perparation for further changes such as https://github.com/rust-lang/rust/pull/142950 and https://github.com/rust-lang/rust/pull/142975 .
2025-06-30mbe: Move `MetaVarExprConcatElem` closer to where it is usedTrevor Gross-14/+14
Move this structure directly above the `parse_<expr>` functions that return it to keep top-down flow. This is a non-functional change.
2025-06-30mbe: Factor `concat` metavariable handling outTrevor Gross-40/+45
Move the `concat` implementation to a separate function so it is easier to work on. Other metavariable expressions are already split this way. This is a non-functional change.
2025-06-30mbe: Shorten `MetaVarExpr` -> `Mve` in structural diagnosticsTrevor Gross-10/+15
More diagnostic structs related to metavariable expressions will be introduced. Introduce the abbreviation "mve" which is reasonably unambiguous (`rg Mve` and `rg '(\b|_|-)mve(\b|_|-)'` return no results outside of a Thumb target feature) and use it for these diagnostic types. A new module is also created.
2025-06-30Introduce `ByteSymbol`.Nicholas Nethercote-2/+6
It's like `Symbol` but for byte strings. The interner is now used for both `Symbol` and `ByteSymbol`. E.g. if you intern `"dog"` and `b"dog"` you'll get a `Symbol` and a `ByteSymbol` with the same index and the characters will only be stored once. The motivation for this is to eliminate the `Arc`s in `ast::LitKind`, to make `ast::LitKind` impl `Copy`, and to avoid the need to arena-allocate `ast::LitKind` in HIR. The latter change reduces peak memory by a non-trivial amount on literal-heavy benchmarks such as `deep-vector` and `tuple-stress`. `Encoder`, `Decoder`, `SpanEncoder`, and `SpanDecoder` all get some changes so that they can handle normal strings and byte strings. This change does slow down compilation of programs that use `include_bytes!` on large files, because the contents of those files are now interned (hashed). This makes `include_bytes!` more similar to `include_str!`, though `include_bytes!` contents still aren't escaped, and hashing is still much cheaper than escaping.
2025-06-26mbe: Fold calls to `check_meta_variables` into the parser loopJosh Triplett-18/+8
2025-06-26Rewrite `macro_rules!` parser to not use the MBE engine itselfJosh Triplett-188/+53
The `macro_rules!` parser was written to match the series of rules using the macros-by-example (MBE) engine and a hand-written equivalent of the left-hand side of a MBE macro. This was complex to read, difficult to extend, and produced confusing error messages. Because it was using the MBE engine, any parse failure would be reported as if some macro was being applied to the `macro_rules!` invocation itself; for instance, errors would talk about "macro invocation", "macro arguments", and "macro call", when they were actually about the macro *definition*. And in practice, the `macro_rules!` parser only used the MBE engine to extract the left-hand side and right-hand side of each rule as a token tree, and then parsed the rest using a separate parser. Rewrite it to parse the series of rules using a simple loop, instead. This makes it more extensible in the future, and improves error messages. For instance, omitting a semicolon between rules will result in "expected `;`" and "unexpected token", rather than the confusing "no rules expected this token in macro call". This work was greatly aided by pair programming with Vincenzo Palazzo and Eric Holk.
2025-06-25Don't give APITs names with macro expansion placeholder fragments in itMichael Goulet-0/+14
2025-06-24Rollup merge of #142934 - nnethercote:tweak-macro-stats, r=petrochenkovJubilee-18/+10
Tweak `-Zmacro-stats` measurement. It currently reports net size, i.e. size(output) - size(input). After some use I think this is sub-optimal, and it's better to just report size(output). Because for derive macros the input size is always 1, and for attribute macros it's almost always 1. r? ```@petrochenkov```
2025-06-24Rollup merge of #142943 - jieyouxu:no-rustc-version, r=compiler-errorsMatthias Krüger-2/+0
Don't include current rustc version string in feature removed help The version string is difficult to properly normalize out, and removing it isn't a huge deal (the user can query version info easily through `rustc --version` or `cargo --version`). The normalization options were all non-ideal (see https://github.com/rust-lang/rust/pull/142940#issuecomment-2998518450): - Per-test version string normalization is nasty to maintain, and we need to maintain `n` copies of it. See rust-lang/rust#142930 where the regex wasn't robust against different release channels. - Centralized compiletest normalization (with a directive opt-out) is also not ideal, because `cfg(version(..))` tests can't have those accidentally normalized out (and you'd have to remember to opt-out). r? `@workingjubilee` (discussed in rust-lang/rust#142940)
2025-06-24Rollup merge of #142657 - tgross35:nonoptional-fragment-specifiers-cleanup, ↵Matthias Krüger-135/+124
r=petrochenkov mbe: Clean up code with non-optional `NonterminalKind` Since [rust-lang/rust#128425], the fragment specifier is unconditionally required in all editions. This means `NonTerminalKind` no longer needs to be optional, as we can reject this code during the expansion of `macro_rules!` rather than handling it throughout the code. Do this cleanup here. [rust-lang/rust#128425]: https://github.com/rust-lang/rust/pull/128425
2025-06-24Don't include current rustc version string in feature removed helpJieyou Xu-2/+0
The version string is difficult to properly normalize out, and removing it isn't a huge deal (the user can query version info easily through `rustc --version` or `cargo --version`). The normalization options were all non-ideal: - Per-test version string normalization is nasty to maintain, and we need to maintain `n` copies of it. - Centralized compiletest normalization (with a directive opt-out) is also not ideal, because `cfg(version(..))` tests can't have those accidentally normalized out (and you'd have to remember to opt-out).
2025-06-24mbe: Use `TokenTree` as the fallback for invalid fragment specifiersTrevor Gross-3/+3
`tt` should match more, so use this for both missing and invalid fragment specifiers. Also remove one unneeded instance of `String`.
2025-06-24mbe: Clean up code with non-optional `NonterminalKind`Trevor Gross-82/+66
Since [1], the fragment specifier is unconditionally required in all editions. This means `NonTerminalKind` no longer needs to be optional, as we can reject this code during the expansion of `macro_rules!` rather than handling it throughout the code. Do this cleanup here. [1]: https://github.com/rust-lang/rust/pull/128425
2025-06-24mbe: Unnest nested matches with let-else and let chainsTrevor Gross-58/+63
Non-functional change to simplify control flow.
2025-06-24Tweak `-Zmacro-stats` measurement.Nicholas Nethercote-18/+10
It currently reports net size, i.e. size(output) - size(input). After some use I think this is sub-optimal, and it's better to just report size(output). Because for derive macros the input size is always 1, and for attribute macros it's almost always 1.
2025-06-22Auto merge of #142706 - fee1-dead-contrib:push-zsznlqyrzsqo, r=oli-obkbors-8/+8
completely deduplicate `Visitor` and `MutVisitor` r? oli-obk This closes rust-lang/rust#127615. ### Discussion > * Give every `MutVisitor::visit_*` method a corresponding `flat_map_*` method. Not every AST node exists in a location where they can be mapped to multiple instances of themselves. Not every AST node exists in a location where they can be removed from existence (e.g. `filter_map_expr`). I don't think this is doable. > * Give every `MutVisitor::visit_*` method a corresponding `Visitor` method and vice versa The only three remaining method-level asymmetries after this PR are `visit_stmt` and `visit_nested_use_tree` (only on `Visitor`) and `visit_span` (only on `MutVisitor`). `visit_stmt` doesn't seem applicable to `MutVisitor` because `walk_flat_map_stmt_kind` will ask `flat_map_item` / `filter_map_expr` to potentially turn a single `Stmt` to multiple based on what a visitor wants. So only using `flat_map_stmt` seems appropriate. `visit_nested_use_tree` is used for `rustc_resolve` to track stuff. Not useful for `MutVisitor` for now. `visit_span` is currently not used for `MutVisitor` already, it was just kept in case we want to revive rust-lang/rust#127241. cc `@cjgillot` maybe we could remove for now and re-insert later if we find a use-case? It does involve some extra effort to maintain. * Remaining FIXMEs `visit_lifetime` has an extra param for `Visitor` that's not in `MutVisitor`. This is again something only used by `rustc_resolve`. I think we can keep that symmetry for now.
2025-06-21Rollup merge of #142690 - petrochenkov:expnoparam, r=compiler-errorsJana Dönszelmann-46/+46
expand: Remove some unnecessary generic parameters
2025-06-20Auto merge of #142794 - tgross35:rollup-iae7okj, r=tgross35bors-363/+404
Rollup of 9 pull requests Successful merges: - rust-lang/rust#142331 (Add `trim_prefix` and `trim_suffix` methods for both `slice` and `str` types.) - rust-lang/rust#142491 (Rework #[cold] attribute parser) - rust-lang/rust#142494 (Fix missing docs in `rustc_attr_parsing`) - rust-lang/rust#142495 (Better template for `#[repr]` attributes) - rust-lang/rust#142497 (Fix random failure when JS code is executed when the whole file was not read yet) - rust-lang/rust#142575 (Ensure copy* intrinsics also perform the static self-init checks) - rust-lang/rust#142650 (Refactor Translator) - rust-lang/rust#142713 (mbe: Refactor transcription) - rust-lang/rust#142755 (rustdoc: Remove `FormatRenderer::cache`) r? `@ghost` `@rustbot` modify labels: rollup
2025-06-20Use a symbol for `ExpansionConfig::crate_name`.Nicholas Nethercote-7/+7
This avoids some symbol interning and `to_string` conversions.
2025-06-19mbe: Refactor transcriptionTrevor Gross-348/+389
Introduce `MacroTcbCtx` that holds everything relevant to transcription. This allows for the following changes: * Split `transcribe_sequence` and `transcribe_metavar` out of the heavily nested `transcribe` * Split `metavar_expr_concat` out of `transcribe_metavar_expr` This is a nonfunctional change.
2025-06-19mbe: Move `transcribe_metavar_expr` directly after `transcribe`Trevor Gross-96/+96
Be more consistent with the otherwise top-down organization of this file.
2025-06-19completely deduplicate `Visitor` and `MutVisitor`Deadbeef-8/+8
2025-06-18expand: Remove some unnecessary generic parametersVadim Petrochenkov-46/+46
2025-06-17Rollup merge of #142371 - fee1-dead-contrib:push-xqlkumzurkus, r=petrochenkovJacob Pratt-23/+24
avoid `&mut P<T>` in `visit_expr` etc methods trying a different way than rust-lang/rust#141636 r? ghost
2025-06-16Remove an `njn:` comment accidentaly left behind.Nicholas Nethercote-1/+2
2025-06-13Auto merge of #142443 - matthiaskrgr:rollup-l1l6d0v, r=matthiaskrgrbors-19/+6
Rollup of 9 pull requests Successful merges: - rust-lang/rust#128425 (Make `missing_fragment_specifier` an unconditional error) - rust-lang/rust#135927 (retpoline and retpoline-external-thunk flags (target modifiers) to enable retpoline-related target features) - rust-lang/rust#140770 (add `extern "custom"` functions) - rust-lang/rust#142176 (tests: Split dont-shuffle-bswaps along opt-levels and arches) - rust-lang/rust#142248 (Add supported asm types for LoongArch32) - rust-lang/rust#142267 (assert more in release in `rustc_ast_lowering`) - rust-lang/rust#142274 (Update the stdarch submodule) - rust-lang/rust#142276 (Update dependencies in `library/Cargo.lock`) - rust-lang/rust#142308 (Upgrade `object`, `addr2line`, and `unwinding` in the standard library) Failed merges: - rust-lang/rust#140920 (Extract some shared code from codegen backend target feature handling) r? `@ghost` `@rustbot` modify labels: rollup try-job: aarch64-apple try-job: x86_64-msvc-1 try-job: x86_64-gnu try-job: dist-i586-gnu-i586-i686-musl try-job: test-various
2025-06-12Introduce `-Zmacro-stats`.Nicholas Nethercote-46/+322
It collects data about macro expansions and prints them in a table after expansion finishes. It's very useful for detecting macro bloat, especially for proc macros. Details: - It measures code snippets by pretty-printing them and then measuring lines and bytes. This required a bunch of additional pretty-printing plumbing, in `rustc_ast_pretty` and `rustc_expand`. - The measurement is done in `MacroExpander::expand_invoc`. - The measurements are stored in `ExtCtxt::macro_stats`.
2025-06-12avoid `&mut P<T>` in `visit_expr` etc methodsDeadbeef-23/+24
2025-06-12Make `missing_fragment_specifier` an unconditional errorTrevor Gross-19/+6
This was attempted in [1] then reverted in [2] because of fallout. Recently, this was made an edition-dependent error in [3]. Make missing fragment specifiers an unconditional error again. [1]: https://github.com/rust-lang/rust/pull/75516 [2]: https://github.com/rust-lang/rust/pull/80210 [3]: https://github.com/rust-lang/rust/pull/128006
2025-06-09Note the version and PR of removed features when using itxizheyin-0/+15
Signed-off-by: xizheyin <xizheyin@smail.nju.edu.cn>
2025-06-08Remove all unused feature gates from the compilerbjorn3-1/+0
2025-06-06Rollup merge of #141603 - nnethercote:reduce-P, r=fee1-deadGuillaume Gomez-22/+17
Reduce `ast::ptr::P` to a typedef of `Box` As per the MCP at https://github.com/rust-lang/compiler-team/issues/878. r? `@fee1-dead`
2025-05-30Rollup merge of #141430 - fee1-dead-contrib:push-nmzoprvtsvww, r=petrochenkovMatthias Krüger-30/+69
remove `visit_clobber` and move `DummyAstNode` to `rustc_expand` `visit_clobber` is not really useful except for one niche purpose involving generic code. We should just use the replace logic where we can.
2025-05-29Auto merge of #141739 - GuillaumeGomez:rollup-ivboqwd, r=GuillaumeGomezbors-3/+2
Rollup of 11 pull requests Successful merges: - rust-lang/rust#137574 (Make `std/src/num` mirror `core/src/num`) - rust-lang/rust#141384 (Enable review queue tracking) - rust-lang/rust#141448 (A variety of improvements to the codegen backends) - rust-lang/rust#141636 (avoid some usages of `&mut P<T>` in AST visitors) - rust-lang/rust#141676 (float: Disable `total_cmp` sNaN tests for `f16`) - rust-lang/rust#141705 (Add eslint as part of `tidy` run) - rust-lang/rust#141715 (Add `loongarch64` with `d` feature to `f32::midpoint` fast path) - rust-lang/rust#141723 (Provide secrets to try builds with new bors) - rust-lang/rust#141728 (Fix false documentation of FnCtxt::diverges) - rust-lang/rust#141729 (resolve target-libdir directly from rustc) - rust-lang/rust#141732 (creader: Remove extraenous String::clone) r? `@ghost` `@rustbot` modify labels: rollup
2025-05-29Rollup merge of #141636 - fee1-dead-contrib:push-ntqvvxwuvrvx, r=petrochenkovGuillaume Gomez-3/+2
avoid some usages of `&mut P<T>` in AST visitors It's a double indirection, and is also complicating our efforts at rust-lang/rust#127615. r? `@ghost`
2025-05-29Auto merge of #141595 - bjorn3:rustc_no_sysroot_proc_macro, r=onur-ozkanbors-11/+9
Do not get proc_macro from the sysroot in rustc With the stage0 refactor the proc_macro version found in the sysroot will no longer always match the proc_macro version that proc-macros get compiled with by the rustc executable that uses this proc_macro. This will cause problems as soon as the ABI of the bridge gets changed to implement new features or change the way existing features work. To fix this, this commit changes rustc crates to depend directly on the local version of proc_macro which will also be used in the sysroot that rustc will build.
2025-05-29avoid some usages of `&mut P<T>` in AST visitorsDeadbeef-3/+2
2025-05-29remove `visit_clobber` and move `DummyAstNode` to `rustc_expand`Deadbeef-30/+69
`visit_clobber` is not really useful except for one niche purpose involving generic code. We should just use the replace logic where we can.
2025-05-29Rollup merge of #141675 - nnethercote:ItemKind-field-order, r=fee1-deadJacob Pratt-1/+1
Reorder `ast::ItemKind::{Struct,Enum,Union}` fields. So they match the order of the parts in the source code, e.g.: ``` struct Foo<T, U> { t: T, u: U } <-><----> <------------> / | \ ident generics variant_data ``` r? `@fee1-dead`
2025-05-28Rollup merge of #141548 - bvanjoi:issue-141256, r=petrochenkovTrevor Gross-3/+3
consider glob imports in cfg suggestion Fixes rust-lang/rust#141256 r? ```@petrochenkov```
2025-05-28Reorder `ast::ItemKind::{Struct,Enum,Union}` fields.Nicholas Nethercote-1/+1
So they match the order of the parts in the source code, e.g.: ``` struct Foo<T, U> { t: T, u: U } <-><----> <------------> / | \ ident generics variant_data ```
2025-05-28consider glob imports in cfg suggestionbohan-3/+3
2025-05-27Do not get proc_macro from the sysroot in rustcbjorn3-11/+9
With the stage0 refactor the proc_macro version found in the sysroot will no longer always match the proc_macro version that proc-macros get compiled with by the rustc executable that uses this proc_macro. This will cause problems as soon as the ABI of the bridge gets changed to implement new features or change the way existing features work. To fix this, this commit changes rustc crates to depend directly on the local version of proc_macro which will also be used in the sysroot that rustc will build.
2025-05-27Remove out-of-date `noop_*` names.Nicholas Nethercote-1/+1
`mut_visit.rs` has a single function with a `noop_` prefix: `noop_filter_map_expr`. This commit renames as `walk_filter_map_expr` which is consistent with other functions in this file. The commit also removes out-of-date comments that refer to `noop_*` methods.