Skip to content

Tracking issue (ish) for some declarative macro optimizations #159951

Description

@bal-e

This is sort of like a tracking issue, but specifically for the optimizations I am making (or plan to make) to rustc's macros-by-example implementation. I'm using it to maintain a public list of my ideas on this topic and link together the relevant PRs.

@nnethercote is reviewing these PRs, I'm really grateful for all his help :)

Depth-first traversal for macro parsing (ongoing)

Until now, macro parsing uses a breadth-first traversal strategy for exploring possibly ambiguous parse trees. I believe a depth-first approach would play better with the CPU, e.g. for branch prediction, as well as unlocking bigger optimizations (e.g. it would allow the Rc<Vec<NamedMatch>> in each MatcherPos to be amortized).

Work started 2026-05-22.

Overall results:

  • Nice perf wins, even in preparatory PRs.
  • Made user-visible details (e.g. ordering within error messages) independent of implementation details.
  • Added more internal documentation.
  • Conceptually unified two kinds of ambiguity detection (meta-variables and EOF).
  • Removed some unreachable paths.
  • Moved more diagnostic code to diagnostics.rs.

Others

Note: these are ideas / proposals, and not all of them might pan out.

  • Convert ParseNtResult into TokenStream earlier #159366
  • Reuse existing TokenStream allocations when transcribing meta-variables
  • Introduce a Matcher type to hold and extend &[MatcherLoc]
  • Remove MatcherLoc::Delimited
  • Strip doc-comment MatcherLoc::Tokens when building MatcherLocs (for now)
  • Optimize memory layout of MatcherLoc
  • Propose supporting doc-comment tokens in matchers (might need a FCW)
  • Assign meta-variables fixed IDs across parsing and transcribing
  • Use Vec instead of HashMap in NamedMatches
  • Flatten the recursive Vecs in NamedMatch
  • Amortize MatcherPos::matches
  • Reuse allocations by caching TtParser in thread-local storage
  • Try replacing Cow<Parser<'_>> with an explicit fast path
  • Replace mbe::TokenStream with an auxiliary table
  • Add a pseudo-metavar for $($x:tt)* to speed up tt-munchers
  • Add benchmarks that directly call expand_macro()

Metadata

Metadata

Assignees

Labels

A-macrosArea: All kinds of macros (custom derive, macro_rules!, proc macros, ..)C-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchC-tracking-issueCategory: An issue tracking the progress of sth. like the implementation of an RFC

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions