1 use crate::base
::{DummyResult, ExtCtxt, MacResult, TTMacroExpander}
;
2 use crate::base
::{SyntaxExtension, SyntaxExtensionKind}
;
3 use crate::expand
::{ensure_complete_parse, parse_ast_fragment, AstFragment, AstFragmentKind}
;
5 use crate::mbe
::macro_check
;
6 use crate::mbe
::macro_parser
::{Error, ErrorReported, Failure, Success, TtParser}
;
7 use crate::mbe
::macro_parser
::{MatchedSeq, MatchedTokenTree, MatcherLoc}
;
8 use crate::mbe
::transcribe
::transcribe
;
11 use rustc_ast
::token
::{self, Delimiter, NonterminalKind, Token, TokenKind, TokenKind::*}
;
12 use rustc_ast
::tokenstream
::{DelimSpan, TokenStream}
;
13 use rustc_ast
::{NodeId, DUMMY_NODE_ID}
;
14 use rustc_ast_pretty
::pprust
;
15 use rustc_attr
::{self as attr, TransparencyError}
;
16 use rustc_data_structures
::fx
::FxHashMap
;
17 use rustc_errors
::{Applicability, Diagnostic, DiagnosticBuilder}
;
18 use rustc_feature
::Features
;
19 use rustc_lint_defs
::builtin
::{
20 RUST_2021_INCOMPATIBLE_OR_PATTERNS
, SEMICOLON_IN_EXPRESSIONS_FROM_MACROS
,
22 use rustc_lint_defs
::BuiltinLintDiagnostics
;
23 use rustc_parse
::parser
::Parser
;
24 use rustc_session
::parse
::ParseSess
;
25 use rustc_session
::Session
;
26 use rustc_span
::edition
::Edition
;
27 use rustc_span
::hygiene
::Transparency
;
28 use rustc_span
::symbol
::{kw, sym, Ident, MacroRulesNormalizedIdent}
;
32 use std
::collections
::hash_map
::Entry
;
33 use std
::{mem, slice}
;
36 pub(crate) struct ParserAnyMacro
<'a
> {
39 /// Span of the expansion site of the macro this parser is for
41 /// The ident of the macro we're parsing
44 is_trailing_mac
: bool
,
46 /// Whether or not this macro is defined in the current crate
50 pub(crate) fn annotate_err_with_kind(err
: &mut Diagnostic
, kind
: AstFragmentKind
, span
: Span
) {
52 AstFragmentKind
::Ty
=> {
53 err
.span_label(span
, "this macro call doesn't expand to a type");
55 AstFragmentKind
::Pat
=> {
56 err
.span_label(span
, "this macro call doesn't expand to a pattern");
62 fn emit_frag_parse_err(
63 mut e
: DiagnosticBuilder
<'_
, rustc_errors
::ErrorGuaranteed
>,
65 orig_parser
: &mut Parser
<'_
>,
68 kind
: AstFragmentKind
,
70 // FIXME(davidtwco): avoid depending on the error message text
71 if parser
.token
== token
::Eof
&& e
.message
[0].0.expect_str().ends_with(", found `<eof>`") {
72 if !e
.span
.is_dummy() {
73 // early end of macro arm (#52866)
74 e
.replace_span_with(parser
.sess
.source_map().next_point(parser
.token
.span
));
76 let msg
= &e
.message
[0];
78 rustc_errors
::DiagnosticMessage
::Str(format
!(
79 "macro expansion ends with an incomplete expression: {}",
80 msg
.0.expect_str().replace(", found `<eof>`", ""),
85 if e
.span
.is_dummy() {
86 // Get around lack of span in error (#30128)
87 e
.replace_span_with(site_span
);
88 if !parser
.sess
.source_map().is_imported(arm_span
) {
89 e
.span_label(arm_span
, "in this macro arm");
91 } else if parser
.sess
.source_map().is_imported(parser
.token
.span
) {
92 e
.span_label(site_span
, "in this macro invocation");
95 // Try a statement if an expression is wanted but failed and suggest adding `;` to call.
96 AstFragmentKind
::Expr
=> match parse_ast_fragment(orig_parser
, AstFragmentKind
::Stmts
) {
97 Err(err
) => err
.cancel(),
100 "the macro call doesn't expand to an expression, but it can expand to a statement",
102 e
.span_suggestion_verbose(
103 site_span
.shrink_to_hi(),
104 "add `;` to interpret the expansion as a statement",
106 Applicability
::MaybeIncorrect
,
110 _
=> annotate_err_with_kind(&mut e
, kind
, site_span
),
115 impl<'a
> ParserAnyMacro
<'a
> {
116 pub(crate) fn make(mut self: Box
<ParserAnyMacro
<'a
>>, kind
: AstFragmentKind
) -> AstFragment
{
126 let snapshot
= &mut parser
.create_snapshot_for_diagnostic();
127 let fragment
= match parse_ast_fragment(parser
, kind
) {
130 emit_frag_parse_err(err
, parser
, snapshot
, site_span
, arm_span
, kind
);
131 return kind
.dummy(site_span
);
135 // We allow semicolons at the end of expressions -- e.g., the semicolon in
136 // `macro_rules! m { () => { panic!(); } }` isn't parsed by `.parse_expr()`,
137 // but `m!()` is allowed in expression positions (cf. issue #34706).
138 if kind
== AstFragmentKind
::Expr
&& parser
.token
== token
::Semi
{
140 parser
.sess
.buffer_lint_with_diagnostic(
141 SEMICOLON_IN_EXPRESSIONS_FROM_MACROS
,
144 "trailing semicolon in macro used in expression position",
145 BuiltinLintDiagnostics
::TrailingMacro(is_trailing_mac
, macro_ident
),
151 // Make sure we don't have any tokens left to parse so we don't silently drop anything.
152 let path
= ast
::Path
::from_ident(macro_ident
.with_span_pos(site_span
));
153 ensure_complete_parse(parser
, &path
, kind
.name(), site_span
);
158 struct MacroRulesMacroExpander
{
162 transparency
: Transparency
,
163 lhses
: Vec
<Vec
<MatcherLoc
>>,
164 rhses
: Vec
<mbe
::TokenTree
>,
168 impl TTMacroExpander
for MacroRulesMacroExpander
{
171 cx
: &'cx
mut ExtCtxt
<'_
>,
174 ) -> Box
<dyn MacResult
+ 'cx
> {
176 return DummyResult
::any(sp
);
192 fn macro_rules_dummy_expander
<'cx
>(
193 _
: &'cx
mut ExtCtxt
<'_
>,
196 ) -> Box
<dyn MacResult
+ 'cx
> {
197 DummyResult
::any(span
)
200 fn trace_macros_note(cx_expansions
: &mut FxHashMap
<Span
, Vec
<String
>>, sp
: Span
, message
: String
) {
201 let sp
= sp
.macro_backtrace().last().map_or(sp
, |trace
| trace
.call_site
);
202 cx_expansions
.entry(sp
).or_default().push(message
);
205 /// Expands the rules based macro defined by `lhses` and `rhses` for a given
207 fn expand_macro
<'cx
>(
208 cx
: &'cx
mut ExtCtxt
<'_
>,
213 transparency
: Transparency
,
215 lhses
: &[Vec
<MatcherLoc
>],
216 rhses
: &[mbe
::TokenTree
],
217 ) -> Box
<dyn MacResult
+ 'cx
> {
218 let sess
= &cx
.sess
.parse_sess
;
219 // Macros defined in the current crate have a real node id,
220 // whereas macros from an external crate have a dummy id.
221 let is_local
= node_id
!= DUMMY_NODE_ID
;
223 if cx
.trace_macros() {
224 let msg
= format
!("expanding `{}! {{ {} }}`", name
, pprust
::tts_to_string(&arg
));
225 trace_macros_note(&mut cx
.expansions
, sp
, msg
);
228 // Which arm's failure should we report? (the one furthest along)
229 let mut best_failure
: Option
<(Token
, &str)> = None
;
231 // We create a base parser that can be used for the "black box" parts.
232 // Every iteration needs a fresh copy of that parser. However, the parser
233 // is not mutated on many of the iterations, particularly when dealing with
236 // macro_rules! foo {
240 // // ... etc. (maybe hundreds more)
243 // as seen in the `html5ever` benchmark. We use a `Cow` so that the base
244 // parser is only cloned when necessary (upon mutation). Furthermore, we
245 // reinitialize the `Cow` with the base parser at the start of every
246 // iteration, so that any mutated parsers are not reused. This is all quite
247 // hacky, but speeds up the `html5ever` benchmark significantly. (Issue
248 // 68836 suggests a more comprehensive but more complex change to deal with
250 let parser
= parser_from_cx(sess
, arg
.clone());
252 // Try each arm's matchers.
253 let mut tt_parser
= TtParser
::new(name
);
254 for (i
, lhs
) in lhses
.iter().enumerate() {
255 // Take a snapshot of the state of pre-expansion gating at this point.
256 // This is used so that if a matcher is not `Success(..)`ful,
257 // then the spans which became gated when parsing the unsuccessful matcher
258 // are not recorded. On the first `Success(..)`ful matcher, the spans are merged.
259 let mut gated_spans_snapshot
= mem
::take(&mut *sess
.gated_spans
.spans
.borrow_mut());
261 match tt_parser
.parse_tt(&mut Cow
::Borrowed(&parser
), lhs
) {
262 Success(named_matches
) => {
263 // The matcher was `Success(..)`ful.
264 // Merge the gated spans from parsing the matcher with the pre-existing ones.
265 sess
.gated_spans
.merge(gated_spans_snapshot
);
267 let (rhs
, rhs_span
): (&mbe
::Delimited
, DelimSpan
) = match &rhses
[i
] {
268 mbe
::TokenTree
::Delimited(span
, delimited
) => (&delimited
, *span
),
269 _
=> cx
.span_bug(sp
, "malformed macro rhs"),
271 let arm_span
= rhses
[i
].span();
273 let rhs_spans
= rhs
.tts
.iter().map(|t
| t
.span()).collect
::<Vec
<_
>>();
274 // rhs has holes ( `$id` and `$(...)` that need filled)
275 let mut tts
= match transcribe(cx
, &named_matches
, &rhs
, rhs_span
, transparency
) {
279 return DummyResult
::any(arm_span
);
283 // Replace all the tokens for the corresponding positions in the macro, to maintain
284 // proper positions in error reporting, while maintaining the macro_backtrace.
285 if rhs_spans
.len() == tts
.len() {
286 tts
= tts
.map_enumerated(|i
, tt
| {
287 let mut tt
= tt
.clone();
288 let mut sp
= rhs_spans
[i
];
289 sp
= sp
.with_ctxt(tt
.span().ctxt());
295 if cx
.trace_macros() {
296 let msg
= format
!("to `{}`", pprust
::tts_to_string(&tts
));
297 trace_macros_note(&mut cx
.expansions
, sp
, msg
);
300 let mut p
= Parser
::new(sess
, tts
, false, None
);
301 p
.last_type_ascription
= cx
.current_expansion
.prior_type_ascription
;
304 cx
.resolver
.record_macro_rule_usage(node_id
, i
);
307 // Let the context choose how to interpret the result.
308 // Weird, but useful for X-macros.
309 return Box
::new(ParserAnyMacro
{
312 // Pass along the original expansion site and the name of the macro
313 // so we can print a useful error message if the parse of the expanded
314 // macro leaves unparsed tokens.
317 lint_node_id
: cx
.current_expansion
.lint_node_id
,
318 is_trailing_mac
: cx
.current_expansion
.is_trailing_mac
,
323 Failure(token
, msg
) => match best_failure
{
324 Some((ref best_token
, _
)) if best_token
.span
.lo() >= token
.span
.lo() => {}
325 _
=> best_failure
= Some((token
, msg
)),
327 Error(err_sp
, ref msg
) => {
328 let span
= err_sp
.substitute_dummy(sp
);
329 cx
.struct_span_err(span
, &msg
).emit();
330 return DummyResult
::any(span
);
332 ErrorReported
=> return DummyResult
::any(sp
),
335 // The matcher was not `Success(..)`ful.
336 // Restore to the state before snapshotting and maybe try again.
337 mem
::swap(&mut gated_spans_snapshot
, &mut sess
.gated_spans
.spans
.borrow_mut());
341 let (token
, label
) = best_failure
.expect("ran no matchers");
342 let span
= token
.span
.substitute_dummy(sp
);
343 let mut err
= cx
.struct_span_err(span
, &parse_failure_msg(&token
));
344 err
.span_label(span
, label
);
345 if !def_span
.is_dummy() && !cx
.source_map().is_imported(def_span
) {
346 err
.span_label(cx
.source_map().guess_head_span(def_span
), "when calling this macro");
349 // Check whether there's a missing comma in this macro call, like `println!("{}" a);`
350 if let Some((arg
, comma_span
)) = arg
.add_comma() {
352 let parser
= parser_from_cx(sess
, arg
.clone());
353 if let Success(_
) = tt_parser
.parse_tt(&mut Cow
::Borrowed(&parser
), lhs
) {
354 if comma_span
.is_dummy() {
355 err
.note("you might be missing a comma");
357 err
.span_suggestion_short(
359 "missing comma here",
361 Applicability
::MachineApplicable
,
368 cx
.trace_macros_diag();
372 // Note that macro-by-example's input is also matched against a token tree:
373 // $( $lhs:tt => $rhs:tt );+
375 // Holy self-referential!
377 /// Converts a macro item into a syntax extension.
378 pub fn compile_declarative_macro(
383 ) -> (SyntaxExtension
, Vec
<(usize, Span
)>) {
384 debug
!("compile_declarative_macro: {:?}", def
);
385 let mk_syn_ext
= |expander
| {
386 SyntaxExtension
::new(
388 SyntaxExtensionKind
::LegacyBang(expander
),
396 let dummy_syn_ext
= || (mk_syn_ext(Box
::new(macro_rules_dummy_expander
)), Vec
::new());
398 let diag
= &sess
.parse_sess
.span_diagnostic
;
399 let lhs_nm
= Ident
::new(sym
::lhs
, def
.span
);
400 let rhs_nm
= Ident
::new(sym
::rhs
, def
.span
);
401 let tt_spec
= Some(NonterminalKind
::TT
);
403 // Parse the macro_rules! invocation
404 let (macro_rules
, body
) = match &def
.kind
{
405 ast
::ItemKind
::MacroDef(def
) => (def
.macro_rules
, def
.body
.inner_tokens()),
409 // The pattern that macro_rules matches.
410 // The grammar for macro_rules! is:
411 // $( $lhs:tt => $rhs:tt );+
412 // ...quasiquoting this would be nice.
413 // These spans won't matter, anyways
414 let argument_gram
= vec
![
415 mbe
::TokenTree
::Sequence(
417 mbe
::SequenceRepetition
{
419 mbe
::TokenTree
::MetaVarDecl(def
.span
, lhs_nm
, tt_spec
),
420 mbe
::TokenTree
::token(token
::FatArrow
, def
.span
),
421 mbe
::TokenTree
::MetaVarDecl(def
.span
, rhs_nm
, tt_spec
),
423 separator
: Some(Token
::new(
424 if macro_rules { token::Semi }
else { token::Comma }
,
427 kleene
: mbe
::KleeneToken
::new(mbe
::KleeneOp
::OneOrMore
, def
.span
),
431 // to phase into semicolon-termination instead of semicolon-separation
432 mbe
::TokenTree
::Sequence(
434 mbe
::SequenceRepetition
{
435 tts
: vec
![mbe
::TokenTree
::token(
436 if macro_rules { token::Semi }
else { token::Comma }
,
440 kleene
: mbe
::KleeneToken
::new(mbe
::KleeneOp
::ZeroOrMore
, def
.span
),
445 // Convert it into `MatcherLoc` form.
446 let argument_gram
= mbe
::macro_parser
::compute_locs(&argument_gram
);
448 let parser
= Parser
::new(&sess
.parse_sess
, body
, true, rustc_parse
::MACRO_ARGUMENTS
);
450 TtParser
::new(Ident
::with_dummy_span(if macro_rules { kw::MacroRules }
else { kw::Macro }
));
451 let argument_map
= match tt_parser
.parse_tt(&mut Cow
::Borrowed(&parser
), &argument_gram
) {
453 Failure(token
, msg
) => {
454 let s
= parse_failure_msg(&token
);
455 let sp
= token
.span
.substitute_dummy(def
.span
);
456 sess
.parse_sess
.span_diagnostic
.struct_span_err(sp
, &s
).span_label(sp
, msg
).emit();
457 return dummy_syn_ext();
462 .struct_span_err(sp
.substitute_dummy(def
.span
), &msg
)
464 return dummy_syn_ext();
467 return dummy_syn_ext();
471 let mut valid
= true;
473 // Extract the arguments:
474 let lhses
= match argument_map
[&MacroRulesNormalizedIdent
::new(lhs_nm
)] {
475 MatchedSeq(ref s
) => s
478 if let MatchedTokenTree(ref tt
) = *m
{
479 let tt
= mbe
::quoted
::parse(
489 valid
&= check_lhs_nt_follows(&sess
.parse_sess
, &def
, &tt
);
492 sess
.parse_sess
.span_diagnostic
.span_bug(def
.span
, "wrong-structured lhs")
494 .collect
::<Vec
<mbe
::TokenTree
>>(),
495 _
=> sess
.parse_sess
.span_diagnostic
.span_bug(def
.span
, "wrong-structured lhs"),
498 let rhses
= match argument_map
[&MacroRulesNormalizedIdent
::new(rhs_nm
)] {
499 MatchedSeq(ref s
) => s
502 if let MatchedTokenTree(ref tt
) = *m
{
503 return mbe
::quoted
::parse(
514 sess
.parse_sess
.span_diagnostic
.span_bug(def
.span
, "wrong-structured lhs")
516 .collect
::<Vec
<mbe
::TokenTree
>>(),
517 _
=> sess
.parse_sess
.span_diagnostic
.span_bug(def
.span
, "wrong-structured rhs"),
521 valid
&= check_rhs(&sess
.parse_sess
, rhs
);
524 // don't abort iteration early, so that errors for multiple lhses can be reported
526 valid
&= check_lhs_no_empty_seq(&sess
.parse_sess
, slice
::from_ref(lhs
));
529 valid
&= macro_check
::check_meta_variables(&sess
.parse_sess
, def
.id
, def
.span
, &lhses
, &rhses
);
531 let (transparency
, transparency_error
) = attr
::find_transparency(&def
.attrs
, macro_rules
);
532 match transparency_error
{
533 Some(TransparencyError
::UnknownTransparency(value
, span
)) => {
534 diag
.span_err(span
, &format
!("unknown macro transparency: `{}`", value
));
536 Some(TransparencyError
::MultipleTransparencyAttrs(old_span
, new_span
)) => {
537 diag
.span_err(vec
![old_span
, new_span
], "multiple macro transparency attributes");
542 // Compute the spans of the macro rules for unused rule linting.
543 // To avoid warning noise, only consider the rules of this
544 // macro for the lint, if all rules are valid.
545 // Also, we are only interested in non-foreign macros.
546 let rule_spans
= if valid
&& def
.id
!= DUMMY_NODE_ID
{
551 // If the rhs contains an invocation like compile_error!,
552 // don't consider the rule for the unused rule lint.
553 .filter(|(_idx
, (_lhs
, rhs
))| !has_compile_error_macro(rhs
))
554 // We only take the span of the lhs here,
555 // so that the spans of created warnings are smaller.
556 .map(|(idx
, (lhs
, _rhs
))| (idx
, lhs
.span()))
562 // Convert the lhses into `MatcherLoc` form, which is better for doing the
563 // actual matching. Unless the matcher is invalid.
564 let lhses
= if valid
{
568 // Ignore the delimiters around the matcher.
570 mbe
::TokenTree
::Delimited(_
, delimited
) => {
571 mbe
::macro_parser
::compute_locs(&delimited
.tts
)
573 _
=> sess
.parse_sess
.span_diagnostic
.span_bug(def
.span
, "malformed macro lhs"),
581 let expander
= Box
::new(MacroRulesMacroExpander
{
590 (mk_syn_ext(expander
), rule_spans
)
593 fn check_lhs_nt_follows(sess
: &ParseSess
, def
: &ast
::Item
, lhs
: &mbe
::TokenTree
) -> bool
{
594 // lhs is going to be like TokenTree::Delimited(...), where the
595 // entire lhs is those tts. Or, it can be a "bare sequence", not wrapped in parens.
596 if let mbe
::TokenTree
::Delimited(_
, delimited
) = lhs
{
597 check_matcher(sess
, def
, &delimited
.tts
)
599 let msg
= "invalid macro matcher; matchers must be contained in balanced delimiters";
600 sess
.span_diagnostic
.span_err(lhs
.span(), msg
);
603 // we don't abort on errors on rejection, the driver will do that for us
604 // after parsing/expansion. we can report every error in every macro this way.
607 /// Checks that the lhs contains no repetition which could match an empty token
608 /// tree, because then the matcher would hang indefinitely.
609 fn check_lhs_no_empty_seq(sess
: &ParseSess
, tts
: &[mbe
::TokenTree
]) -> bool
{
614 | TokenTree
::MetaVar(..)
615 | TokenTree
::MetaVarDecl(..)
616 | TokenTree
::MetaVarExpr(..) => (),
617 TokenTree
::Delimited(_
, ref del
) => {
618 if !check_lhs_no_empty_seq(sess
, &del
.tts
) {
622 TokenTree
::Sequence(span
, ref seq
) => {
623 if seq
.separator
.is_none()
624 && seq
.tts
.iter().all(|seq_tt
| match *seq_tt
{
625 TokenTree
::MetaVarDecl(_
, _
, Some(NonterminalKind
::Vis
)) => true,
626 TokenTree
::Sequence(_
, ref sub_seq
) => {
627 sub_seq
.kleene
.op
== mbe
::KleeneOp
::ZeroOrMore
628 || sub_seq
.kleene
.op
== mbe
::KleeneOp
::ZeroOrOne
633 let sp
= span
.entire();
634 sess
.span_diagnostic
.span_err(sp
, "repetition matches empty token tree");
637 if !check_lhs_no_empty_seq(sess
, &seq
.tts
) {
647 fn check_rhs(sess
: &ParseSess
, rhs
: &mbe
::TokenTree
) -> bool
{
649 mbe
::TokenTree
::Delimited(..) => return true,
651 sess
.span_diagnostic
.span_err(rhs
.span(), "macro rhs must be delimited");
657 fn check_matcher(sess
: &ParseSess
, def
: &ast
::Item
, matcher
: &[mbe
::TokenTree
]) -> bool
{
658 let first_sets
= FirstSets
::new(matcher
);
659 let empty_suffix
= TokenSet
::empty();
660 let err
= sess
.span_diagnostic
.err_count();
661 check_matcher_core(sess
, def
, &first_sets
, matcher
, &empty_suffix
);
662 err
== sess
.span_diagnostic
.err_count()
665 fn has_compile_error_macro(rhs
: &mbe
::TokenTree
) -> bool
{
667 mbe
::TokenTree
::Delimited(_sp
, d
) => {
668 let has_compile_error
= d
.tts
.array_windows
::<3>().any(|[ident
, bang
, args
]| {
669 if let mbe
::TokenTree
::Token(ident
) = ident
&&
670 let TokenKind
::Ident(ident
, _
) = ident
.kind
&&
671 ident
== sym
::compile_error
&&
672 let mbe
::TokenTree
::Token(bang
) = bang
&&
673 let TokenKind
::Not
= bang
.kind
&&
674 let mbe
::TokenTree
::Delimited(_
, del
) = args
&&
675 del
.delim
!= Delimiter
::Invisible
682 if has_compile_error { true }
else { d.tts.iter().any(has_compile_error_macro) }
688 // `The FirstSets` for a matcher is a mapping from subsequences in the
689 // matcher to the FIRST set for that subsequence.
691 // This mapping is partially precomputed via a backwards scan over the
692 // token trees of the matcher, which provides a mapping from each
693 // repetition sequence to its *first* set.
695 // (Hypothetically, sequences should be uniquely identifiable via their
696 // spans, though perhaps that is false, e.g., for macro-generated macros
697 // that do not try to inject artificial span information. My plan is
698 // to try to catch such cases ahead of time and not include them in
699 // the precomputed mapping.)
700 struct FirstSets
<'tt
> {
701 // this maps each TokenTree::Sequence `$(tt ...) SEP OP` that is uniquely identified by its
702 // span in the original matcher to the First set for the inner sequence `tt ...`.
704 // If two sequences have the same span in a matcher, then map that
705 // span to None (invalidating the mapping here and forcing the code to
707 first
: FxHashMap
<Span
, Option
<TokenSet
<'tt
>>>,
710 impl<'tt
> FirstSets
<'tt
> {
711 fn new(tts
: &'tt
[mbe
::TokenTree
]) -> FirstSets
<'tt
> {
714 let mut sets
= FirstSets { first: FxHashMap::default() }
;
715 build_recur(&mut sets
, tts
);
718 // walks backward over `tts`, returning the FIRST for `tts`
719 // and updating `sets` at the same time for all sequence
720 // substructure we find within `tts`.
721 fn build_recur
<'tt
>(sets
: &mut FirstSets
<'tt
>, tts
: &'tt
[TokenTree
]) -> TokenSet
<'tt
> {
722 let mut first
= TokenSet
::empty();
723 for tt
in tts
.iter().rev() {
726 | TokenTree
::MetaVar(..)
727 | TokenTree
::MetaVarDecl(..)
728 | TokenTree
::MetaVarExpr(..) => {
729 first
.replace_with(TtHandle
::TtRef(tt
));
731 TokenTree
::Delimited(span
, ref delimited
) => {
732 build_recur(sets
, &delimited
.tts
);
733 first
.replace_with(TtHandle
::from_token_kind(
734 token
::OpenDelim(delimited
.delim
),
738 TokenTree
::Sequence(sp
, ref seq_rep
) => {
739 let subfirst
= build_recur(sets
, &seq_rep
.tts
);
741 match sets
.first
.entry(sp
.entire()) {
742 Entry
::Vacant(vac
) => {
743 vac
.insert(Some(subfirst
.clone()));
745 Entry
::Occupied(mut occ
) => {
746 // if there is already an entry, then a span must have collided.
747 // This should not happen with typical macro_rules macros,
748 // but syntax extensions need not maintain distinct spans,
749 // so distinct syntax trees can be assigned the same span.
750 // In such a case, the map cannot be trusted; so mark this
751 // entry as unusable.
756 // If the sequence contents can be empty, then the first
757 // token could be the separator token itself.
759 if let (Some(sep
), true) = (&seq_rep
.separator
, subfirst
.maybe_empty
) {
760 first
.add_one_maybe(TtHandle
::from_token(sep
.clone()));
763 // Reverse scan: Sequence comes before `first`.
764 if subfirst
.maybe_empty
765 || seq_rep
.kleene
.op
== mbe
::KleeneOp
::ZeroOrMore
766 || seq_rep
.kleene
.op
== mbe
::KleeneOp
::ZeroOrOne
768 // If sequence is potentially empty, then
769 // union them (preserving first emptiness).
770 first
.add_all(&TokenSet { maybe_empty: true, ..subfirst }
);
772 // Otherwise, sequence guaranteed
773 // non-empty; replace first.
784 // walks forward over `tts` until all potential FIRST tokens are
786 fn first(&self, tts
: &'tt
[mbe
::TokenTree
]) -> TokenSet
<'tt
> {
789 let mut first
= TokenSet
::empty();
790 for tt
in tts
.iter() {
791 assert
!(first
.maybe_empty
);
794 | TokenTree
::MetaVar(..)
795 | TokenTree
::MetaVarDecl(..)
796 | TokenTree
::MetaVarExpr(..) => {
797 first
.add_one(TtHandle
::TtRef(tt
));
800 TokenTree
::Delimited(span
, ref delimited
) => {
801 first
.add_one(TtHandle
::from_token_kind(
802 token
::OpenDelim(delimited
.delim
),
807 TokenTree
::Sequence(sp
, ref seq_rep
) => {
809 let subfirst
= match self.first
.get(&sp
.entire()) {
810 Some(&Some(ref subfirst
)) => subfirst
,
812 subfirst_owned
= self.first(&seq_rep
.tts
);
816 panic
!("We missed a sequence during FirstSets construction");
820 // If the sequence contents can be empty, then the first
821 // token could be the separator token itself.
822 if let (Some(sep
), true) = (&seq_rep
.separator
, subfirst
.maybe_empty
) {
823 first
.add_one_maybe(TtHandle
::from_token(sep
.clone()));
826 assert
!(first
.maybe_empty
);
827 first
.add_all(subfirst
);
828 if subfirst
.maybe_empty
829 || seq_rep
.kleene
.op
== mbe
::KleeneOp
::ZeroOrMore
830 || seq_rep
.kleene
.op
== mbe
::KleeneOp
::ZeroOrOne
832 // Continue scanning for more first
833 // tokens, but also make sure we
834 // restore empty-tracking state.
835 first
.maybe_empty
= true;
844 // we only exit the loop if `tts` was empty or if every
845 // element of `tts` matches the empty sequence.
846 assert
!(first
.maybe_empty
);
851 // Most `mbe::TokenTree`s are pre-existing in the matcher, but some are defined
852 // implicitly, such as opening/closing delimiters and sequence repetition ops.
853 // This type encapsulates both kinds. It implements `Clone` while avoiding the
854 // need for `mbe::TokenTree` to implement `Clone`.
857 /// This is used in most cases.
858 TtRef(&'tt mbe
::TokenTree
),
860 /// This is only used for implicit token trees. The `mbe::TokenTree` *must*
861 /// be `mbe::TokenTree::Token`. No other variants are allowed. We store an
862 /// `mbe::TokenTree` rather than a `Token` so that `get()` can return a
863 /// `&mbe::TokenTree`.
864 Token(mbe
::TokenTree
),
867 impl<'tt
> TtHandle
<'tt
> {
868 fn from_token(tok
: Token
) -> Self {
869 TtHandle
::Token(mbe
::TokenTree
::Token(tok
))
872 fn from_token_kind(kind
: TokenKind
, span
: Span
) -> Self {
873 TtHandle
::from_token(Token
::new(kind
, span
))
876 // Get a reference to a token tree.
877 fn get(&'tt
self) -> &'tt mbe
::TokenTree
{
879 TtHandle
::TtRef(tt
) => tt
,
880 TtHandle
::Token(token_tt
) => &token_tt
,
885 impl<'tt
> PartialEq
for TtHandle
<'tt
> {
886 fn eq(&self, other
: &TtHandle
<'tt
>) -> bool
{
887 self.get() == other
.get()
891 impl<'tt
> Clone
for TtHandle
<'tt
> {
892 fn clone(&self) -> Self {
894 TtHandle
::TtRef(tt
) => TtHandle
::TtRef(tt
),
896 // This variant *must* contain a `mbe::TokenTree::Token`, and not
897 // any other variant of `mbe::TokenTree`.
898 TtHandle
::Token(mbe
::TokenTree
::Token(tok
)) => {
899 TtHandle
::Token(mbe
::TokenTree
::Token(tok
.clone()))
907 // A set of `mbe::TokenTree`s, which may include `TokenTree::Match`s
908 // (for macro-by-example syntactic variables). It also carries the
909 // `maybe_empty` flag; that is true if and only if the matcher can
910 // match an empty token sequence.
912 // The First set is computed on submatchers like `$($a:expr b),* $(c)* d`,
913 // which has corresponding FIRST = {$a:expr, c, d}.
914 // Likewise, `$($a:expr b),* $(c)+ d` has FIRST = {$a:expr, c}.
916 // (Notably, we must allow for *-op to occur zero times.)
917 #[derive(Clone, Debug)]
918 struct TokenSet
<'tt
> {
919 tokens
: Vec
<TtHandle
<'tt
>>,
923 impl<'tt
> TokenSet
<'tt
> {
924 // Returns a set for the empty sequence.
926 TokenSet { tokens: Vec::new(), maybe_empty: true }
929 // Returns the set `{ tok }` for the single-token (and thus
930 // non-empty) sequence [tok].
931 fn singleton(tt
: TtHandle
<'tt
>) -> Self {
932 TokenSet { tokens: vec![tt], maybe_empty: false }
935 // Changes self to be the set `{ tok }`.
936 // Since `tok` is always present, marks self as non-empty.
937 fn replace_with(&mut self, tt
: TtHandle
<'tt
>) {
939 self.tokens
.push(tt
);
940 self.maybe_empty
= false;
943 // Changes self to be the empty set `{}`; meant for use when
944 // the particular token does not matter, but we want to
945 // record that it occurs.
946 fn replace_with_irrelevant(&mut self) {
948 self.maybe_empty
= false;
951 // Adds `tok` to the set for `self`, marking sequence as non-empy.
952 fn add_one(&mut self, tt
: TtHandle
<'tt
>) {
953 if !self.tokens
.contains(&tt
) {
954 self.tokens
.push(tt
);
956 self.maybe_empty
= false;
959 // Adds `tok` to the set for `self`. (Leaves `maybe_empty` flag alone.)
960 fn add_one_maybe(&mut self, tt
: TtHandle
<'tt
>) {
961 if !self.tokens
.contains(&tt
) {
962 self.tokens
.push(tt
);
966 // Adds all elements of `other` to this.
968 // (Since this is a set, we filter out duplicates.)
970 // If `other` is potentially empty, then preserves the previous
971 // setting of the empty flag of `self`. If `other` is guaranteed
972 // non-empty, then `self` is marked non-empty.
973 fn add_all(&mut self, other
: &Self) {
974 for tt
in &other
.tokens
{
975 if !self.tokens
.contains(tt
) {
976 self.tokens
.push(tt
.clone());
979 if !other
.maybe_empty
{
980 self.maybe_empty
= false;
985 // Checks that `matcher` is internally consistent and that it
986 // can legally be followed by a token `N`, for all `N` in `follow`.
987 // (If `follow` is empty, then it imposes no constraint on
990 // Returns the set of NT tokens that could possibly come last in
991 // `matcher`. (If `matcher` matches the empty sequence, then
992 // `maybe_empty` will be set to true.)
994 // Requires that `first_sets` is pre-computed for `matcher`;
995 // see `FirstSets::new`.
996 fn check_matcher_core
<'tt
>(
999 first_sets
: &FirstSets
<'tt
>,
1000 matcher
: &'tt
[mbe
::TokenTree
],
1001 follow
: &TokenSet
<'tt
>,
1002 ) -> TokenSet
<'tt
> {
1005 let mut last
= TokenSet
::empty();
1007 // 2. For each token and suffix [T, SUFFIX] in M:
1008 // ensure that T can be followed by SUFFIX, and if SUFFIX may be empty,
1009 // then ensure T can also be followed by any element of FOLLOW.
1010 'each_token
: for i
in 0..matcher
.len() {
1011 let token
= &matcher
[i
];
1012 let suffix
= &matcher
[i
+ 1..];
1014 let build_suffix_first
= || {
1015 let mut s
= first_sets
.first(suffix
);
1022 // (we build `suffix_first` on demand below; you can tell
1023 // which cases are supposed to fall through by looking for the
1024 // initialization of this variable.)
1027 // First, update `last` so that it corresponds to the set
1028 // of NT tokens that might end the sequence `... token`.
1030 TokenTree
::Token(..)
1031 | TokenTree
::MetaVar(..)
1032 | TokenTree
::MetaVarDecl(..)
1033 | TokenTree
::MetaVarExpr(..) => {
1034 if token_can_be_followed_by_any(token
) {
1035 // don't need to track tokens that work with any,
1036 last
.replace_with_irrelevant();
1037 // ... and don't need to check tokens that can be
1038 // followed by anything against SUFFIX.
1039 continue 'each_token
;
1041 last
.replace_with(TtHandle
::TtRef(token
));
1042 suffix_first
= build_suffix_first();
1045 TokenTree
::Delimited(span
, ref d
) => {
1046 let my_suffix
= TokenSet
::singleton(TtHandle
::from_token_kind(
1047 token
::CloseDelim(d
.delim
),
1050 check_matcher_core(sess
, def
, first_sets
, &d
.tts
, &my_suffix
);
1051 // don't track non NT tokens
1052 last
.replace_with_irrelevant();
1054 // also, we don't need to check delimited sequences
1056 continue 'each_token
;
1058 TokenTree
::Sequence(_
, ref seq_rep
) => {
1059 suffix_first
= build_suffix_first();
1060 // The trick here: when we check the interior, we want
1061 // to include the separator (if any) as a potential
1062 // (but not guaranteed) element of FOLLOW. So in that
1063 // case, we make a temp copy of suffix and stuff
1064 // delimiter in there.
1066 // FIXME: Should I first scan suffix_first to see if
1067 // delimiter is already in it before I go through the
1068 // work of cloning it? But then again, this way I may
1069 // get a "tighter" span?
1071 let my_suffix
= if let Some(sep
) = &seq_rep
.separator
{
1072 new
= suffix_first
.clone();
1073 new
.add_one_maybe(TtHandle
::from_token(sep
.clone()));
1079 // At this point, `suffix_first` is built, and
1080 // `my_suffix` is some TokenSet that we can use
1081 // for checking the interior of `seq_rep`.
1082 let next
= check_matcher_core(sess
, def
, first_sets
, &seq_rep
.tts
, my_suffix
);
1083 if next
.maybe_empty
{
1084 last
.add_all(&next
);
1089 // the recursive call to check_matcher_core already ran the 'each_last
1090 // check below, so we can just keep going forward here.
1091 continue 'each_token
;
1095 // (`suffix_first` guaranteed initialized once reaching here.)
1097 // Now `last` holds the complete set of NT tokens that could
1098 // end the sequence before SUFFIX. Check that every one works with `suffix`.
1099 for tt
in &last
.tokens
{
1100 if let &TokenTree
::MetaVarDecl(span
, name
, Some(kind
)) = tt
.get() {
1101 for next_token
in &suffix_first
.tokens
{
1102 let next_token
= next_token
.get();
1104 // Check if the old pat is used and the next token is `|`
1105 // to warn about incompatibility with Rust 2021.
1106 // We only emit this lint if we're parsing the original
1107 // definition of this macro_rules, not while (re)parsing
1108 // the macro when compiling another crate that is using the
1109 // macro. (See #86567.)
1110 // Macros defined in the current crate have a real node id,
1111 // whereas macros from an external crate have a dummy id.
1112 if def
.id
!= DUMMY_NODE_ID
1113 && matches
!(kind
, NonterminalKind
::PatParam { inferred: true }
)
1114 && matches
!(next_token
, TokenTree
::Token(token
) if token
.kind
== BinOp(token
::BinOpToken
::Or
))
1116 // It is suggestion to use pat_param, for example: $x:pat -> $x:pat_param.
1117 let suggestion
= quoted_tt_to_string(&TokenTree
::MetaVarDecl(
1120 Some(NonterminalKind
::PatParam { inferred: false }
),
1122 sess
.buffer_lint_with_diagnostic(
1123 &RUST_2021_INCOMPATIBLE_OR_PATTERNS
,
1126 "the meaning of the `pat` fragment specifier is changing in Rust 2021, which may affect this macro",
1127 BuiltinLintDiagnostics
::OrPatternsBackCompat(span
, suggestion
),
1130 match is_in_follow(next_token
, kind
) {
1131 IsInFollow
::Yes
=> {}
1132 IsInFollow
::No(possible
) => {
1133 let may_be
= if last
.tokens
.len() == 1 && suffix_first
.tokens
.len() == 1
1140 let sp
= next_token
.span();
1141 let mut err
= sess
.span_diagnostic
.struct_span_err(
1144 "`${name}:{frag}` {may_be} followed by `{next}`, which \
1145 is not allowed for `{frag}` fragments",
1148 next
= quoted_tt_to_string(next_token
),
1152 err
.span_label(sp
, format
!("not allowed after `{}` fragments", kind
));
1154 if kind
== NonterminalKind
::PatWithOr
1155 && sess
.edition
.rust_2021()
1156 && next_token
.is_token(&BinOp(token
::BinOpToken
::Or
))
1158 let suggestion
= quoted_tt_to_string(&TokenTree
::MetaVarDecl(
1161 Some(NonterminalKind
::PatParam { inferred: false }
),
1163 err
.span_suggestion(
1165 "try a `pat_param` fragment specifier instead",
1167 Applicability
::MaybeIncorrect
,
1171 let msg
= "allowed there are: ";
1176 "only {} is allowed after `{}` fragments",
1187 .collect
::<Vec
<_
>>()
1203 fn token_can_be_followed_by_any(tok
: &mbe
::TokenTree
) -> bool
{
1204 if let mbe
::TokenTree
::MetaVarDecl(_
, _
, Some(kind
)) = *tok
{
1205 frag_can_be_followed_by_any(kind
)
1207 // (Non NT's can always be followed by anything in matchers.)
1212 /// Returns `true` if a fragment of type `frag` can be followed by any sort of
1213 /// token. We use this (among other things) as a useful approximation
1214 /// for when `frag` can be followed by a repetition like `$(...)*` or
1215 /// `$(...)+`. In general, these can be a bit tricky to reason about,
1216 /// so we adopt a conservative position that says that any fragment
1217 /// specifier which consumes at most one token tree can be followed by
1218 /// a fragment specifier (indeed, these fragments can be followed by
1219 /// ANYTHING without fear of future compatibility hazards).
1220 fn frag_can_be_followed_by_any(kind
: NonterminalKind
) -> bool
{
1223 NonterminalKind
::Item
// always terminated by `}` or `;`
1224 | NonterminalKind
::Block
// exactly one token tree
1225 | NonterminalKind
::Ident
// exactly one token tree
1226 | NonterminalKind
::Literal
// exactly one token tree
1227 | NonterminalKind
::Meta
// exactly one token tree
1228 | NonterminalKind
::Lifetime
// exactly one token tree
1229 | NonterminalKind
::TT
// exactly one token tree
1235 No(&'
static [&'
static str]),
1238 /// Returns `true` if `frag` can legally be followed by the token `tok`. For
1239 /// fragments that can consume an unbounded number of tokens, `tok`
1240 /// must be within a well-defined follow set. This is intended to
1241 /// guarantee future compatibility: for example, without this rule, if
1242 /// we expanded `expr` to include a new binary operator, we might
1243 /// break macros that were relying on that binary operator as a
1245 // when changing this do not forget to update doc/book/macros.md!
1246 fn is_in_follow(tok
: &mbe
::TokenTree
, kind
: NonterminalKind
) -> IsInFollow
{
1249 if let TokenTree
::Token(Token { kind: token::CloseDelim(_), .. }
) = *tok
{
1250 // closing a token tree can never be matched by any fragment;
1251 // iow, we always require that `(` and `)` match, etc.
1255 NonterminalKind
::Item
=> {
1256 // since items *must* be followed by either a `;` or a `}`, we can
1257 // accept anything after them
1260 NonterminalKind
::Block
=> {
1261 // anything can follow block, the braces provide an easy boundary to
1265 NonterminalKind
::Stmt
| NonterminalKind
::Expr
=> {
1266 const TOKENS
: &[&str] = &["`=>`", "`,`", "`;`"];
1268 TokenTree
::Token(token
) => match token
.kind
{
1269 FatArrow
| Comma
| Semi
=> IsInFollow
::Yes
,
1270 _
=> IsInFollow
::No(TOKENS
),
1272 _
=> IsInFollow
::No(TOKENS
),
1275 NonterminalKind
::PatParam { .. }
=> {
1276 const TOKENS
: &[&str] = &["`=>`", "`,`", "`=`", "`|`", "`if`", "`in`"];
1278 TokenTree
::Token(token
) => match token
.kind
{
1279 FatArrow
| Comma
| Eq
| BinOp(token
::Or
) => IsInFollow
::Yes
,
1280 Ident(name
, false) if name
== kw
::If
|| name
== kw
::In
=> IsInFollow
::Yes
,
1281 _
=> IsInFollow
::No(TOKENS
),
1283 _
=> IsInFollow
::No(TOKENS
),
1286 NonterminalKind
::PatWithOr { .. }
=> {
1287 const TOKENS
: &[&str] = &["`=>`", "`,`", "`=`", "`if`", "`in`"];
1289 TokenTree
::Token(token
) => match token
.kind
{
1290 FatArrow
| Comma
| Eq
=> IsInFollow
::Yes
,
1291 Ident(name
, false) if name
== kw
::If
|| name
== kw
::In
=> IsInFollow
::Yes
,
1292 _
=> IsInFollow
::No(TOKENS
),
1294 _
=> IsInFollow
::No(TOKENS
),
1297 NonterminalKind
::Path
| NonterminalKind
::Ty
=> {
1298 const TOKENS
: &[&str] = &[
1299 "`{`", "`[`", "`=>`", "`,`", "`>`", "`=`", "`:`", "`;`", "`|`", "`as`",
1303 TokenTree
::Token(token
) => match token
.kind
{
1304 OpenDelim(Delimiter
::Brace
)
1305 | OpenDelim(Delimiter
::Bracket
)
1313 | BinOp(token
::Or
) => IsInFollow
::Yes
,
1314 Ident(name
, false) if name
== kw
::As
|| name
== kw
::Where
=> {
1317 _
=> IsInFollow
::No(TOKENS
),
1319 TokenTree
::MetaVarDecl(_
, _
, Some(NonterminalKind
::Block
)) => IsInFollow
::Yes
,
1320 _
=> IsInFollow
::No(TOKENS
),
1323 NonterminalKind
::Ident
| NonterminalKind
::Lifetime
=> {
1324 // being a single token, idents and lifetimes are harmless
1327 NonterminalKind
::Literal
=> {
1328 // literals may be of a single token, or two tokens (negative numbers)
1331 NonterminalKind
::Meta
| NonterminalKind
::TT
=> {
1332 // being either a single token or a delimited sequence, tt is
1336 NonterminalKind
::Vis
=> {
1337 // Explicitly disallow `priv`, on the off chance it comes back.
1338 const TOKENS
: &[&str] = &["`,`", "an ident", "a type"];
1340 TokenTree
::Token(token
) => match token
.kind
{
1341 Comma
=> IsInFollow
::Yes
,
1342 Ident(name
, is_raw
) if is_raw
|| name
!= kw
::Priv
=> IsInFollow
::Yes
,
1344 if token
.can_begin_type() {
1347 IsInFollow
::No(TOKENS
)
1351 TokenTree
::MetaVarDecl(
1354 Some(NonterminalKind
::Ident
| NonterminalKind
::Ty
| NonterminalKind
::Path
),
1355 ) => IsInFollow
::Yes
,
1356 _
=> IsInFollow
::No(TOKENS
),
1363 fn quoted_tt_to_string(tt
: &mbe
::TokenTree
) -> String
{
1365 mbe
::TokenTree
::Token(ref token
) => pprust
::token_to_string(&token
).into(),
1366 mbe
::TokenTree
::MetaVar(_
, name
) => format
!("${}", name
),
1367 mbe
::TokenTree
::MetaVarDecl(_
, name
, Some(kind
)) => format
!("${}:{}", name
, kind
),
1368 mbe
::TokenTree
::MetaVarDecl(_
, name
, None
) => format
!("${}:", name
),
1371 "unexpected mbe::TokenTree::{Sequence or Delimited} \
1372 in follow set checker"
1377 fn parser_from_cx(sess
: &ParseSess
, tts
: TokenStream
) -> Parser
<'_
> {
1378 Parser
::new(sess
, tts
, true, rustc_parse
::MACRO_ARGUMENTS
)
1381 /// Generates an appropriate parsing failure message. For EOF, this is "unexpected end...". For
1382 /// other tokens, this is "unexpected token...".
1383 fn parse_failure_msg(tok
: &Token
) -> String
{
1385 token
::Eof
=> "unexpected end of macro invocation".to_string(),
1386 _
=> format
!("no rules expected the token `{}`", pprust
::token_to_string(tok
),),