]> git.lizzy.rs Git - rust.git/blob - src/librustc_expand/mbe/macro_rules.rs
Add comment about the lack of `ExpnData` serialization for proc-macro crates
[rust.git] / src / librustc_expand / mbe / macro_rules.rs
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};
4 use crate::mbe;
5 use crate::mbe::macro_check;
6 use crate::mbe::macro_parser::parse_tt;
7 use crate::mbe::macro_parser::{Error, ErrorReported, Failure, Success};
8 use crate::mbe::macro_parser::{MatchedNonterminal, MatchedSeq};
9 use crate::mbe::transcribe::transcribe;
10
11 use rustc_ast::ast;
12 use rustc_ast::token::{self, NonterminalKind, NtTT, Token, TokenKind::*};
13 use rustc_ast::tokenstream::{DelimSpan, TokenStream};
14 use rustc_ast_pretty::pprust;
15 use rustc_attr::{self as attr, TransparencyError};
16 use rustc_data_structures::fx::FxHashMap;
17 use rustc_data_structures::sync::Lrc;
18 use rustc_errors::{Applicability, DiagnosticBuilder};
19 use rustc_feature::Features;
20 use rustc_parse::parser::Parser;
21 use rustc_session::parse::ParseSess;
22 use rustc_span::edition::Edition;
23 use rustc_span::hygiene::Transparency;
24 use rustc_span::symbol::{kw, sym, Ident, MacroRulesNormalizedIdent};
25 use rustc_span::Span;
26
27 use log::debug;
28 use std::borrow::Cow;
29 use std::collections::hash_map::Entry;
30 use std::{mem, slice};
31
32 crate struct ParserAnyMacro<'a> {
33     parser: Parser<'a>,
34
35     /// Span of the expansion site of the macro this parser is for
36     site_span: Span,
37     /// The ident of the macro we're parsing
38     macro_ident: Ident,
39     arm_span: Span,
40 }
41
42 crate fn annotate_err_with_kind(
43     err: &mut DiagnosticBuilder<'_>,
44     kind: AstFragmentKind,
45     span: Span,
46 ) {
47     match kind {
48         AstFragmentKind::Ty => {
49             err.span_label(span, "this macro call doesn't expand to a type");
50         }
51         AstFragmentKind::Pat => {
52             err.span_label(span, "this macro call doesn't expand to a pattern");
53         }
54         _ => {}
55     };
56 }
57
58 /// Instead of e.g. `vec![a, b, c]` in a pattern context, suggest `[a, b, c]`.
59 fn suggest_slice_pat(e: &mut DiagnosticBuilder<'_>, site_span: Span, parser: &Parser<'_>) {
60     let mut suggestion = None;
61     if let Ok(code) = parser.sess.source_map().span_to_snippet(site_span) {
62         if let Some(bang) = code.find('!') {
63             suggestion = Some(code[bang + 1..].to_string());
64         }
65     }
66     if let Some(suggestion) = suggestion {
67         e.span_suggestion(
68             site_span,
69             "use a slice pattern here instead",
70             suggestion,
71             Applicability::MachineApplicable,
72         );
73     } else {
74         e.span_label(site_span, "use a slice pattern here instead");
75     }
76     e.help(
77         "for more information, see https://doc.rust-lang.org/edition-guide/\
78         rust-2018/slice-patterns.html",
79     );
80 }
81
82 fn emit_frag_parse_err(
83     mut e: DiagnosticBuilder<'_>,
84     parser: &Parser<'_>,
85     orig_parser: &mut Parser<'_>,
86     site_span: Span,
87     macro_ident: Ident,
88     arm_span: Span,
89     kind: AstFragmentKind,
90 ) {
91     if parser.token == token::Eof && e.message().ends_with(", found `<eof>`") {
92         if !e.span.is_dummy() {
93             // early end of macro arm (#52866)
94             e.replace_span_with(parser.sess.source_map().next_point(parser.token.span));
95         }
96         let msg = &e.message[0];
97         e.message[0] = (
98             format!(
99                 "macro expansion ends with an incomplete expression: {}",
100                 msg.0.replace(", found `<eof>`", ""),
101             ),
102             msg.1,
103         );
104     }
105     if e.span.is_dummy() {
106         // Get around lack of span in error (#30128)
107         e.replace_span_with(site_span);
108         if !parser.sess.source_map().is_imported(arm_span) {
109             e.span_label(arm_span, "in this macro arm");
110         }
111     } else if parser.sess.source_map().is_imported(parser.token.span) {
112         e.span_label(site_span, "in this macro invocation");
113     }
114     match kind {
115         AstFragmentKind::Pat if macro_ident.name == sym::vec => {
116             suggest_slice_pat(&mut e, site_span, parser);
117         }
118         // Try a statement if an expression is wanted but failed and suggest adding `;` to call.
119         AstFragmentKind::Expr => match parse_ast_fragment(orig_parser, AstFragmentKind::Stmts) {
120             Err(mut err) => err.cancel(),
121             Ok(_) => {
122                 e.note(
123                     "the macro call doesn't expand to an expression, but it can expand to a statement",
124                 );
125                 e.span_suggestion_verbose(
126                     site_span.shrink_to_hi(),
127                     "add `;` to interpret the expansion as a statement",
128                     ";".to_string(),
129                     Applicability::MaybeIncorrect,
130                 );
131             }
132         },
133         _ => annotate_err_with_kind(&mut e, kind, site_span),
134     };
135     e.emit();
136 }
137
138 impl<'a> ParserAnyMacro<'a> {
139     crate fn make(mut self: Box<ParserAnyMacro<'a>>, kind: AstFragmentKind) -> AstFragment {
140         let ParserAnyMacro { site_span, macro_ident, ref mut parser, arm_span } = *self;
141         let snapshot = &mut parser.clone();
142         let fragment = match parse_ast_fragment(parser, kind) {
143             Ok(f) => f,
144             Err(err) => {
145                 emit_frag_parse_err(err, parser, snapshot, site_span, macro_ident, arm_span, kind);
146                 return kind.dummy(site_span);
147             }
148         };
149
150         // We allow semicolons at the end of expressions -- e.g., the semicolon in
151         // `macro_rules! m { () => { panic!(); } }` isn't parsed by `.parse_expr()`,
152         // but `m!()` is allowed in expression positions (cf. issue #34706).
153         if kind == AstFragmentKind::Expr && parser.token == token::Semi {
154             parser.bump();
155         }
156
157         // Make sure we don't have any tokens left to parse so we don't silently drop anything.
158         let path = ast::Path::from_ident(macro_ident.with_span_pos(site_span));
159         ensure_complete_parse(parser, &path, kind.name(), site_span);
160         fragment
161     }
162 }
163
164 struct MacroRulesMacroExpander {
165     name: Ident,
166     span: Span,
167     transparency: Transparency,
168     lhses: Vec<mbe::TokenTree>,
169     rhses: Vec<mbe::TokenTree>,
170     valid: bool,
171 }
172
173 impl TTMacroExpander for MacroRulesMacroExpander {
174     fn expand<'cx>(
175         &self,
176         cx: &'cx mut ExtCtxt<'_>,
177         sp: Span,
178         input: TokenStream,
179     ) -> Box<dyn MacResult + 'cx> {
180         if !self.valid {
181             return DummyResult::any(sp);
182         }
183         generic_extension(
184             cx,
185             sp,
186             self.span,
187             self.name,
188             self.transparency,
189             input,
190             &self.lhses,
191             &self.rhses,
192         )
193     }
194 }
195
196 fn macro_rules_dummy_expander<'cx>(
197     _: &'cx mut ExtCtxt<'_>,
198     span: Span,
199     _: TokenStream,
200 ) -> Box<dyn MacResult + 'cx> {
201     DummyResult::any(span)
202 }
203
204 fn trace_macros_note(cx_expansions: &mut FxHashMap<Span, Vec<String>>, sp: Span, message: String) {
205     let sp = sp.macro_backtrace().last().map(|trace| trace.call_site).unwrap_or(sp);
206     cx_expansions.entry(sp).or_default().push(message);
207 }
208
209 /// Given `lhses` and `rhses`, this is the new macro we create
210 fn generic_extension<'cx>(
211     cx: &'cx mut ExtCtxt<'_>,
212     sp: Span,
213     def_span: Span,
214     name: Ident,
215     transparency: Transparency,
216     arg: TokenStream,
217     lhses: &[mbe::TokenTree],
218     rhses: &[mbe::TokenTree],
219 ) -> Box<dyn MacResult + 'cx> {
220     let sess = cx.parse_sess;
221
222     if cx.trace_macros() {
223         let msg = format!("expanding `{}! {{ {} }}`", name, pprust::tts_to_string(&arg));
224         trace_macros_note(&mut cx.expansions, sp, msg);
225     }
226
227     // Which arm's failure should we report? (the one furthest along)
228     let mut best_failure: Option<(Token, &str)> = None;
229
230     // We create a base parser that can be used for the "black box" parts.
231     // Every iteration needs a fresh copy of that parser. However, the parser
232     // is not mutated on many of the iterations, particularly when dealing with
233     // macros like this:
234     //
235     // macro_rules! foo {
236     //     ("a") => (A);
237     //     ("b") => (B);
238     //     ("c") => (C);
239     //     // ... etc. (maybe hundreds more)
240     // }
241     //
242     // as seen in the `html5ever` benchmark. We use a `Cow` so that the base
243     // parser is only cloned when necessary (upon mutation). Furthermore, we
244     // reinitialize the `Cow` with the base parser at the start of every
245     // iteration, so that any mutated parsers are not reused. This is all quite
246     // hacky, but speeds up the `html5ever` benchmark significantly. (Issue
247     // 68836 suggests a more comprehensive but more complex change to deal with
248     // this situation.)
249     let parser = parser_from_cx(sess, arg.clone());
250
251     for (i, lhs) in lhses.iter().enumerate() {
252         // try each arm's matchers
253         let lhs_tt = match *lhs {
254             mbe::TokenTree::Delimited(_, ref delim) => &delim.tts[..],
255             _ => cx.span_bug(sp, "malformed macro lhs"),
256         };
257
258         // Take a snapshot of the state of pre-expansion gating at this point.
259         // This is used so that if a matcher is not `Success(..)`ful,
260         // then the spans which became gated when parsing the unsuccessful matcher
261         // are not recorded. On the first `Success(..)`ful matcher, the spans are merged.
262         let mut gated_spans_snapshot = mem::take(&mut *sess.gated_spans.spans.borrow_mut());
263
264         match parse_tt(&mut Cow::Borrowed(&parser), lhs_tt) {
265             Success(named_matches) => {
266                 // The matcher was `Success(..)`ful.
267                 // Merge the gated spans from parsing the matcher with the pre-existing ones.
268                 sess.gated_spans.merge(gated_spans_snapshot);
269
270                 let rhs = match rhses[i] {
271                     // ignore delimiters
272                     mbe::TokenTree::Delimited(_, ref delimed) => delimed.tts.clone(),
273                     _ => cx.span_bug(sp, "malformed macro rhs"),
274                 };
275                 let arm_span = rhses[i].span();
276
277                 let rhs_spans = rhs.iter().map(|t| t.span()).collect::<Vec<_>>();
278                 // rhs has holes ( `$id` and `$(...)` that need filled)
279                 let mut tts = match transcribe(cx, &named_matches, rhs, transparency) {
280                     Ok(tts) => tts,
281                     Err(mut err) => {
282                         err.emit();
283                         return DummyResult::any(arm_span);
284                     }
285                 };
286
287                 // Replace all the tokens for the corresponding positions in the macro, to maintain
288                 // proper positions in error reporting, while maintaining the macro_backtrace.
289                 if rhs_spans.len() == tts.len() {
290                     tts = tts.map_enumerated(|i, mut tt| {
291                         let mut sp = rhs_spans[i];
292                         sp = sp.with_ctxt(tt.span().ctxt());
293                         tt.set_span(sp);
294                         tt
295                     });
296                 }
297
298                 if cx.trace_macros() {
299                     let msg = format!("to `{}`", pprust::tts_to_string(&tts));
300                     trace_macros_note(&mut cx.expansions, sp, msg);
301                 }
302
303                 let mut p = Parser::new(sess, tts, false, None);
304                 p.last_type_ascription = cx.current_expansion.prior_type_ascription;
305
306                 // Let the context choose how to interpret the result.
307                 // Weird, but useful for X-macros.
308                 return Box::new(ParserAnyMacro {
309                     parser: p,
310
311                     // Pass along the original expansion site and the name of the macro
312                     // so we can print a useful error message if the parse of the expanded
313                     // macro leaves unparsed tokens.
314                     site_span: sp,
315                     macro_ident: name,
316                     arm_span,
317                 });
318             }
319             Failure(token, msg) => match best_failure {
320                 Some((ref best_token, _)) if best_token.span.lo() >= token.span.lo() => {}
321                 _ => best_failure = Some((token, msg)),
322             },
323             Error(err_sp, ref msg) => {
324                 let span = err_sp.substitute_dummy(sp);
325                 cx.struct_span_err(span, &msg).emit();
326                 return DummyResult::any(span);
327             }
328             ErrorReported => return DummyResult::any(sp),
329         }
330
331         // The matcher was not `Success(..)`ful.
332         // Restore to the state before snapshotting and maybe try again.
333         mem::swap(&mut gated_spans_snapshot, &mut sess.gated_spans.spans.borrow_mut());
334     }
335     drop(parser);
336
337     let (token, label) = best_failure.expect("ran no matchers");
338     let span = token.span.substitute_dummy(sp);
339     let mut err = cx.struct_span_err(span, &parse_failure_msg(&token));
340     err.span_label(span, label);
341     if !def_span.is_dummy() && !cx.source_map().is_imported(def_span) {
342         err.span_label(cx.source_map().guess_head_span(def_span), "when calling this macro");
343     }
344
345     // Check whether there's a missing comma in this macro call, like `println!("{}" a);`
346     if let Some((arg, comma_span)) = arg.add_comma() {
347         for lhs in lhses {
348             // try each arm's matchers
349             let lhs_tt = match *lhs {
350                 mbe::TokenTree::Delimited(_, ref delim) => &delim.tts[..],
351                 _ => continue,
352             };
353             if let Success(_) =
354                 parse_tt(&mut Cow::Borrowed(&parser_from_cx(sess, arg.clone())), lhs_tt)
355             {
356                 if comma_span.is_dummy() {
357                     err.note("you might be missing a comma");
358                 } else {
359                     err.span_suggestion_short(
360                         comma_span,
361                         "missing comma here",
362                         ", ".to_string(),
363                         Applicability::MachineApplicable,
364                     );
365                 }
366             }
367         }
368     }
369     err.emit();
370     cx.trace_macros_diag();
371     DummyResult::any(sp)
372 }
373
374 // Note that macro-by-example's input is also matched against a token tree:
375 //                   $( $lhs:tt => $rhs:tt );+
376 //
377 // Holy self-referential!
378
379 /// Converts a macro item into a syntax extension.
380 pub fn compile_declarative_macro(
381     sess: &ParseSess,
382     features: &Features,
383     def: &ast::Item,
384     edition: Edition,
385 ) -> SyntaxExtension {
386     debug!("compile_declarative_macro: {:?}", def);
387     let mk_syn_ext = |expander| {
388         SyntaxExtension::new(
389             sess,
390             SyntaxExtensionKind::LegacyBang(expander),
391             def.span,
392             Vec::new(),
393             edition,
394             def.ident.name,
395             &def.attrs,
396         )
397     };
398
399     let diag = &sess.span_diagnostic;
400     let lhs_nm = Ident::new(sym::lhs, def.span);
401     let rhs_nm = Ident::new(sym::rhs, def.span);
402     let tt_spec = Some(NonterminalKind::TT);
403
404     // Parse the macro_rules! invocation
405     let (macro_rules, body) = match &def.kind {
406         ast::ItemKind::MacroDef(def) => (def.macro_rules, def.body.inner_tokens()),
407         _ => unreachable!(),
408     };
409
410     // The pattern that macro_rules matches.
411     // The grammar for macro_rules! is:
412     // $( $lhs:tt => $rhs:tt );+
413     // ...quasiquoting this would be nice.
414     // These spans won't matter, anyways
415     let argument_gram = vec![
416         mbe::TokenTree::Sequence(
417             DelimSpan::dummy(),
418             Lrc::new(mbe::SequenceRepetition {
419                 tts: vec![
420                     mbe::TokenTree::MetaVarDecl(def.span, lhs_nm, tt_spec),
421                     mbe::TokenTree::token(token::FatArrow, def.span),
422                     mbe::TokenTree::MetaVarDecl(def.span, rhs_nm, tt_spec),
423                 ],
424                 separator: Some(Token::new(
425                     if macro_rules { token::Semi } else { token::Comma },
426                     def.span,
427                 )),
428                 kleene: mbe::KleeneToken::new(mbe::KleeneOp::OneOrMore, def.span),
429                 num_captures: 2,
430             }),
431         ),
432         // to phase into semicolon-termination instead of semicolon-separation
433         mbe::TokenTree::Sequence(
434             DelimSpan::dummy(),
435             Lrc::new(mbe::SequenceRepetition {
436                 tts: vec![mbe::TokenTree::token(
437                     if macro_rules { token::Semi } else { token::Comma },
438                     def.span,
439                 )],
440                 separator: None,
441                 kleene: mbe::KleeneToken::new(mbe::KleeneOp::ZeroOrMore, def.span),
442                 num_captures: 0,
443             }),
444         ),
445     ];
446
447     let parser = Parser::new(sess, body, true, rustc_parse::MACRO_ARGUMENTS);
448     let argument_map = match parse_tt(&mut Cow::Borrowed(&parser), &argument_gram) {
449         Success(m) => m,
450         Failure(token, msg) => {
451             let s = parse_failure_msg(&token);
452             let sp = token.span.substitute_dummy(def.span);
453             sess.span_diagnostic.struct_span_err(sp, &s).span_label(sp, msg).emit();
454             return mk_syn_ext(Box::new(macro_rules_dummy_expander));
455         }
456         Error(sp, msg) => {
457             sess.span_diagnostic.struct_span_err(sp.substitute_dummy(def.span), &msg).emit();
458             return mk_syn_ext(Box::new(macro_rules_dummy_expander));
459         }
460         ErrorReported => {
461             return mk_syn_ext(Box::new(macro_rules_dummy_expander));
462         }
463     };
464
465     let mut valid = true;
466
467     // Extract the arguments:
468     let lhses = match argument_map[&MacroRulesNormalizedIdent::new(lhs_nm)] {
469         MatchedSeq(ref s) => s
470             .iter()
471             .map(|m| {
472                 if let MatchedNonterminal(ref nt) = *m {
473                     if let NtTT(ref tt) = **nt {
474                         let tt = mbe::quoted::parse(tt.clone().into(), true, sess, def.id)
475                             .pop()
476                             .unwrap();
477                         valid &= check_lhs_nt_follows(sess, features, &def.attrs, &tt);
478                         return tt;
479                     }
480                 }
481                 sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
482             })
483             .collect::<Vec<mbe::TokenTree>>(),
484         _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs"),
485     };
486
487     let rhses = match argument_map[&MacroRulesNormalizedIdent::new(rhs_nm)] {
488         MatchedSeq(ref s) => s
489             .iter()
490             .map(|m| {
491                 if let MatchedNonterminal(ref nt) = *m {
492                     if let NtTT(ref tt) = **nt {
493                         return mbe::quoted::parse(tt.clone().into(), false, sess, def.id)
494                             .pop()
495                             .unwrap();
496                     }
497                 }
498                 sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
499             })
500             .collect::<Vec<mbe::TokenTree>>(),
501         _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured rhs"),
502     };
503
504     for rhs in &rhses {
505         valid &= check_rhs(sess, rhs);
506     }
507
508     // don't abort iteration early, so that errors for multiple lhses can be reported
509     for lhs in &lhses {
510         valid &= check_lhs_no_empty_seq(sess, slice::from_ref(lhs));
511     }
512
513     valid &= macro_check::check_meta_variables(sess, def.id, def.span, &lhses, &rhses);
514
515     let (transparency, transparency_error) = attr::find_transparency(&def.attrs, macro_rules);
516     match transparency_error {
517         Some(TransparencyError::UnknownTransparency(value, span)) => {
518             diag.span_err(span, &format!("unknown macro transparency: `{}`", value))
519         }
520         Some(TransparencyError::MultipleTransparencyAttrs(old_span, new_span)) => {
521             diag.span_err(vec![old_span, new_span], "multiple macro transparency attributes")
522         }
523         None => {}
524     }
525
526     mk_syn_ext(Box::new(MacroRulesMacroExpander {
527         name: def.ident,
528         span: def.span,
529         transparency,
530         lhses,
531         rhses,
532         valid,
533     }))
534 }
535
536 fn check_lhs_nt_follows(
537     sess: &ParseSess,
538     features: &Features,
539     attrs: &[ast::Attribute],
540     lhs: &mbe::TokenTree,
541 ) -> bool {
542     // lhs is going to be like TokenTree::Delimited(...), where the
543     // entire lhs is those tts. Or, it can be a "bare sequence", not wrapped in parens.
544     if let mbe::TokenTree::Delimited(_, ref tts) = *lhs {
545         check_matcher(sess, features, attrs, &tts.tts)
546     } else {
547         let msg = "invalid macro matcher; matchers must be contained in balanced delimiters";
548         sess.span_diagnostic.span_err(lhs.span(), msg);
549         false
550     }
551     // we don't abort on errors on rejection, the driver will do that for us
552     // after parsing/expansion. we can report every error in every macro this way.
553 }
554
555 /// Checks that the lhs contains no repetition which could match an empty token
556 /// tree, because then the matcher would hang indefinitely.
557 fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[mbe::TokenTree]) -> bool {
558     use mbe::TokenTree;
559     for tt in tts {
560         match *tt {
561             TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => (),
562             TokenTree::Delimited(_, ref del) => {
563                 if !check_lhs_no_empty_seq(sess, &del.tts) {
564                     return false;
565                 }
566             }
567             TokenTree::Sequence(span, ref seq) => {
568                 if seq.separator.is_none()
569                     && seq.tts.iter().all(|seq_tt| match *seq_tt {
570                         TokenTree::MetaVarDecl(_, _, Some(NonterminalKind::Vis)) => true,
571                         TokenTree::Sequence(_, ref sub_seq) => {
572                             sub_seq.kleene.op == mbe::KleeneOp::ZeroOrMore
573                                 || sub_seq.kleene.op == mbe::KleeneOp::ZeroOrOne
574                         }
575                         _ => false,
576                     })
577                 {
578                     let sp = span.entire();
579                     sess.span_diagnostic.span_err(sp, "repetition matches empty token tree");
580                     return false;
581                 }
582                 if !check_lhs_no_empty_seq(sess, &seq.tts) {
583                     return false;
584                 }
585             }
586         }
587     }
588
589     true
590 }
591
592 fn check_rhs(sess: &ParseSess, rhs: &mbe::TokenTree) -> bool {
593     match *rhs {
594         mbe::TokenTree::Delimited(..) => return true,
595         _ => sess.span_diagnostic.span_err(rhs.span(), "macro rhs must be delimited"),
596     }
597     false
598 }
599
600 fn check_matcher(
601     sess: &ParseSess,
602     features: &Features,
603     attrs: &[ast::Attribute],
604     matcher: &[mbe::TokenTree],
605 ) -> bool {
606     let first_sets = FirstSets::new(matcher);
607     let empty_suffix = TokenSet::empty();
608     let err = sess.span_diagnostic.err_count();
609     check_matcher_core(sess, features, attrs, &first_sets, matcher, &empty_suffix);
610     err == sess.span_diagnostic.err_count()
611 }
612
613 // `The FirstSets` for a matcher is a mapping from subsequences in the
614 // matcher to the FIRST set for that subsequence.
615 //
616 // This mapping is partially precomputed via a backwards scan over the
617 // token trees of the matcher, which provides a mapping from each
618 // repetition sequence to its *first* set.
619 //
620 // (Hypothetically, sequences should be uniquely identifiable via their
621 // spans, though perhaps that is false, e.g., for macro-generated macros
622 // that do not try to inject artificial span information. My plan is
623 // to try to catch such cases ahead of time and not include them in
624 // the precomputed mapping.)
625 struct FirstSets {
626     // this maps each TokenTree::Sequence `$(tt ...) SEP OP` that is uniquely identified by its
627     // span in the original matcher to the First set for the inner sequence `tt ...`.
628     //
629     // If two sequences have the same span in a matcher, then map that
630     // span to None (invalidating the mapping here and forcing the code to
631     // use a slow path).
632     first: FxHashMap<Span, Option<TokenSet>>,
633 }
634
635 impl FirstSets {
636     fn new(tts: &[mbe::TokenTree]) -> FirstSets {
637         use mbe::TokenTree;
638
639         let mut sets = FirstSets { first: FxHashMap::default() };
640         build_recur(&mut sets, tts);
641         return sets;
642
643         // walks backward over `tts`, returning the FIRST for `tts`
644         // and updating `sets` at the same time for all sequence
645         // substructure we find within `tts`.
646         fn build_recur(sets: &mut FirstSets, tts: &[TokenTree]) -> TokenSet {
647             let mut first = TokenSet::empty();
648             for tt in tts.iter().rev() {
649                 match *tt {
650                     TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
651                         first.replace_with(tt.clone());
652                     }
653                     TokenTree::Delimited(span, ref delimited) => {
654                         build_recur(sets, &delimited.tts[..]);
655                         first.replace_with(delimited.open_tt(span));
656                     }
657                     TokenTree::Sequence(sp, ref seq_rep) => {
658                         let subfirst = build_recur(sets, &seq_rep.tts[..]);
659
660                         match sets.first.entry(sp.entire()) {
661                             Entry::Vacant(vac) => {
662                                 vac.insert(Some(subfirst.clone()));
663                             }
664                             Entry::Occupied(mut occ) => {
665                                 // if there is already an entry, then a span must have collided.
666                                 // This should not happen with typical macro_rules macros,
667                                 // but syntax extensions need not maintain distinct spans,
668                                 // so distinct syntax trees can be assigned the same span.
669                                 // In such a case, the map cannot be trusted; so mark this
670                                 // entry as unusable.
671                                 occ.insert(None);
672                             }
673                         }
674
675                         // If the sequence contents can be empty, then the first
676                         // token could be the separator token itself.
677
678                         if let (Some(sep), true) = (&seq_rep.separator, subfirst.maybe_empty) {
679                             first.add_one_maybe(TokenTree::Token(sep.clone()));
680                         }
681
682                         // Reverse scan: Sequence comes before `first`.
683                         if subfirst.maybe_empty
684                             || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrMore
685                             || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrOne
686                         {
687                             // If sequence is potentially empty, then
688                             // union them (preserving first emptiness).
689                             first.add_all(&TokenSet { maybe_empty: true, ..subfirst });
690                         } else {
691                             // Otherwise, sequence guaranteed
692                             // non-empty; replace first.
693                             first = subfirst;
694                         }
695                     }
696                 }
697             }
698
699             first
700         }
701     }
702
703     // walks forward over `tts` until all potential FIRST tokens are
704     // identified.
705     fn first(&self, tts: &[mbe::TokenTree]) -> TokenSet {
706         use mbe::TokenTree;
707
708         let mut first = TokenSet::empty();
709         for tt in tts.iter() {
710             assert!(first.maybe_empty);
711             match *tt {
712                 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
713                     first.add_one(tt.clone());
714                     return first;
715                 }
716                 TokenTree::Delimited(span, ref delimited) => {
717                     first.add_one(delimited.open_tt(span));
718                     return first;
719                 }
720                 TokenTree::Sequence(sp, ref seq_rep) => {
721                     let subfirst_owned;
722                     let subfirst = match self.first.get(&sp.entire()) {
723                         Some(&Some(ref subfirst)) => subfirst,
724                         Some(&None) => {
725                             subfirst_owned = self.first(&seq_rep.tts[..]);
726                             &subfirst_owned
727                         }
728                         None => {
729                             panic!("We missed a sequence during FirstSets construction");
730                         }
731                     };
732
733                     // If the sequence contents can be empty, then the first
734                     // token could be the separator token itself.
735                     if let (Some(sep), true) = (&seq_rep.separator, subfirst.maybe_empty) {
736                         first.add_one_maybe(TokenTree::Token(sep.clone()));
737                     }
738
739                     assert!(first.maybe_empty);
740                     first.add_all(subfirst);
741                     if subfirst.maybe_empty
742                         || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrMore
743                         || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrOne
744                     {
745                         // Continue scanning for more first
746                         // tokens, but also make sure we
747                         // restore empty-tracking state.
748                         first.maybe_empty = true;
749                         continue;
750                     } else {
751                         return first;
752                     }
753                 }
754             }
755         }
756
757         // we only exit the loop if `tts` was empty or if every
758         // element of `tts` matches the empty sequence.
759         assert!(first.maybe_empty);
760         first
761     }
762 }
763
764 // A set of `mbe::TokenTree`s, which may include `TokenTree::Match`s
765 // (for macro-by-example syntactic variables). It also carries the
766 // `maybe_empty` flag; that is true if and only if the matcher can
767 // match an empty token sequence.
768 //
769 // The First set is computed on submatchers like `$($a:expr b),* $(c)* d`,
770 // which has corresponding FIRST = {$a:expr, c, d}.
771 // Likewise, `$($a:expr b),* $(c)+ d` has FIRST = {$a:expr, c}.
772 //
773 // (Notably, we must allow for *-op to occur zero times.)
774 #[derive(Clone, Debug)]
775 struct TokenSet {
776     tokens: Vec<mbe::TokenTree>,
777     maybe_empty: bool,
778 }
779
780 impl TokenSet {
781     // Returns a set for the empty sequence.
782     fn empty() -> Self {
783         TokenSet { tokens: Vec::new(), maybe_empty: true }
784     }
785
786     // Returns the set `{ tok }` for the single-token (and thus
787     // non-empty) sequence [tok].
788     fn singleton(tok: mbe::TokenTree) -> Self {
789         TokenSet { tokens: vec![tok], maybe_empty: false }
790     }
791
792     // Changes self to be the set `{ tok }`.
793     // Since `tok` is always present, marks self as non-empty.
794     fn replace_with(&mut self, tok: mbe::TokenTree) {
795         self.tokens.clear();
796         self.tokens.push(tok);
797         self.maybe_empty = false;
798     }
799
800     // Changes self to be the empty set `{}`; meant for use when
801     // the particular token does not matter, but we want to
802     // record that it occurs.
803     fn replace_with_irrelevant(&mut self) {
804         self.tokens.clear();
805         self.maybe_empty = false;
806     }
807
808     // Adds `tok` to the set for `self`, marking sequence as non-empy.
809     fn add_one(&mut self, tok: mbe::TokenTree) {
810         if !self.tokens.contains(&tok) {
811             self.tokens.push(tok);
812         }
813         self.maybe_empty = false;
814     }
815
816     // Adds `tok` to the set for `self`. (Leaves `maybe_empty` flag alone.)
817     fn add_one_maybe(&mut self, tok: mbe::TokenTree) {
818         if !self.tokens.contains(&tok) {
819             self.tokens.push(tok);
820         }
821     }
822
823     // Adds all elements of `other` to this.
824     //
825     // (Since this is a set, we filter out duplicates.)
826     //
827     // If `other` is potentially empty, then preserves the previous
828     // setting of the empty flag of `self`. If `other` is guaranteed
829     // non-empty, then `self` is marked non-empty.
830     fn add_all(&mut self, other: &Self) {
831         for tok in &other.tokens {
832             if !self.tokens.contains(tok) {
833                 self.tokens.push(tok.clone());
834             }
835         }
836         if !other.maybe_empty {
837             self.maybe_empty = false;
838         }
839     }
840 }
841
842 // Checks that `matcher` is internally consistent and that it
843 // can legally be followed by a token `N`, for all `N` in `follow`.
844 // (If `follow` is empty, then it imposes no constraint on
845 // the `matcher`.)
846 //
847 // Returns the set of NT tokens that could possibly come last in
848 // `matcher`. (If `matcher` matches the empty sequence, then
849 // `maybe_empty` will be set to true.)
850 //
851 // Requires that `first_sets` is pre-computed for `matcher`;
852 // see `FirstSets::new`.
853 fn check_matcher_core(
854     sess: &ParseSess,
855     features: &Features,
856     attrs: &[ast::Attribute],
857     first_sets: &FirstSets,
858     matcher: &[mbe::TokenTree],
859     follow: &TokenSet,
860 ) -> TokenSet {
861     use mbe::TokenTree;
862
863     let mut last = TokenSet::empty();
864
865     // 2. For each token and suffix  [T, SUFFIX] in M:
866     // ensure that T can be followed by SUFFIX, and if SUFFIX may be empty,
867     // then ensure T can also be followed by any element of FOLLOW.
868     'each_token: for i in 0..matcher.len() {
869         let token = &matcher[i];
870         let suffix = &matcher[i + 1..];
871
872         let build_suffix_first = || {
873             let mut s = first_sets.first(suffix);
874             if s.maybe_empty {
875                 s.add_all(follow);
876             }
877             s
878         };
879
880         // (we build `suffix_first` on demand below; you can tell
881         // which cases are supposed to fall through by looking for the
882         // initialization of this variable.)
883         let suffix_first;
884
885         // First, update `last` so that it corresponds to the set
886         // of NT tokens that might end the sequence `... token`.
887         match *token {
888             TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
889                 if token_can_be_followed_by_any(token) {
890                     // don't need to track tokens that work with any,
891                     last.replace_with_irrelevant();
892                     // ... and don't need to check tokens that can be
893                     // followed by anything against SUFFIX.
894                     continue 'each_token;
895                 } else {
896                     last.replace_with(token.clone());
897                     suffix_first = build_suffix_first();
898                 }
899             }
900             TokenTree::Delimited(span, ref d) => {
901                 let my_suffix = TokenSet::singleton(d.close_tt(span));
902                 check_matcher_core(sess, features, attrs, first_sets, &d.tts, &my_suffix);
903                 // don't track non NT tokens
904                 last.replace_with_irrelevant();
905
906                 // also, we don't need to check delimited sequences
907                 // against SUFFIX
908                 continue 'each_token;
909             }
910             TokenTree::Sequence(_, ref seq_rep) => {
911                 suffix_first = build_suffix_first();
912                 // The trick here: when we check the interior, we want
913                 // to include the separator (if any) as a potential
914                 // (but not guaranteed) element of FOLLOW. So in that
915                 // case, we make a temp copy of suffix and stuff
916                 // delimiter in there.
917                 //
918                 // FIXME: Should I first scan suffix_first to see if
919                 // delimiter is already in it before I go through the
920                 // work of cloning it? But then again, this way I may
921                 // get a "tighter" span?
922                 let mut new;
923                 let my_suffix = if let Some(sep) = &seq_rep.separator {
924                     new = suffix_first.clone();
925                     new.add_one_maybe(TokenTree::Token(sep.clone()));
926                     &new
927                 } else {
928                     &suffix_first
929                 };
930
931                 // At this point, `suffix_first` is built, and
932                 // `my_suffix` is some TokenSet that we can use
933                 // for checking the interior of `seq_rep`.
934                 let next =
935                     check_matcher_core(sess, features, attrs, first_sets, &seq_rep.tts, my_suffix);
936                 if next.maybe_empty {
937                     last.add_all(&next);
938                 } else {
939                     last = next;
940                 }
941
942                 // the recursive call to check_matcher_core already ran the 'each_last
943                 // check below, so we can just keep going forward here.
944                 continue 'each_token;
945             }
946         }
947
948         // (`suffix_first` guaranteed initialized once reaching here.)
949
950         // Now `last` holds the complete set of NT tokens that could
951         // end the sequence before SUFFIX. Check that every one works with `suffix`.
952         for token in &last.tokens {
953             if let TokenTree::MetaVarDecl(_, name, Some(kind)) = *token {
954                 for next_token in &suffix_first.tokens {
955                     match is_in_follow(next_token, kind) {
956                         IsInFollow::Yes => {}
957                         IsInFollow::No(possible) => {
958                             let may_be = if last.tokens.len() == 1 && suffix_first.tokens.len() == 1
959                             {
960                                 "is"
961                             } else {
962                                 "may be"
963                             };
964
965                             let sp = next_token.span();
966                             let mut err = sess.span_diagnostic.struct_span_err(
967                                 sp,
968                                 &format!(
969                                     "`${name}:{frag}` {may_be} followed by `{next}`, which \
970                                      is not allowed for `{frag}` fragments",
971                                     name = name,
972                                     frag = kind,
973                                     next = quoted_tt_to_string(next_token),
974                                     may_be = may_be
975                                 ),
976                             );
977                             err.span_label(sp, format!("not allowed after `{}` fragments", kind));
978                             let msg = "allowed there are: ";
979                             match possible {
980                                 &[] => {}
981                                 &[t] => {
982                                     err.note(&format!(
983                                         "only {} is allowed after `{}` fragments",
984                                         t, kind,
985                                     ));
986                                 }
987                                 ts => {
988                                     err.note(&format!(
989                                         "{}{} or {}",
990                                         msg,
991                                         ts[..ts.len() - 1]
992                                             .iter()
993                                             .copied()
994                                             .collect::<Vec<_>>()
995                                             .join(", "),
996                                         ts[ts.len() - 1],
997                                     ));
998                                 }
999                             }
1000                             err.emit();
1001                         }
1002                     }
1003                 }
1004             }
1005         }
1006     }
1007     last
1008 }
1009
1010 fn token_can_be_followed_by_any(tok: &mbe::TokenTree) -> bool {
1011     if let mbe::TokenTree::MetaVarDecl(_, _, Some(kind)) = *tok {
1012         frag_can_be_followed_by_any(kind)
1013     } else {
1014         // (Non NT's can always be followed by anything in matchers.)
1015         true
1016     }
1017 }
1018
1019 /// Returns `true` if a fragment of type `frag` can be followed by any sort of
1020 /// token. We use this (among other things) as a useful approximation
1021 /// for when `frag` can be followed by a repetition like `$(...)*` or
1022 /// `$(...)+`. In general, these can be a bit tricky to reason about,
1023 /// so we adopt a conservative position that says that any fragment
1024 /// specifier which consumes at most one token tree can be followed by
1025 /// a fragment specifier (indeed, these fragments can be followed by
1026 /// ANYTHING without fear of future compatibility hazards).
1027 fn frag_can_be_followed_by_any(kind: NonterminalKind) -> bool {
1028     match kind {
1029         NonterminalKind::Item           // always terminated by `}` or `;`
1030         | NonterminalKind::Block        // exactly one token tree
1031         | NonterminalKind::Ident        // exactly one token tree
1032         | NonterminalKind::Literal      // exactly one token tree
1033         | NonterminalKind::Meta         // exactly one token tree
1034         | NonterminalKind::Lifetime     // exactly one token tree
1035         | NonterminalKind::TT => true,  // exactly one token tree
1036
1037         _ => false,
1038     }
1039 }
1040
1041 enum IsInFollow {
1042     Yes,
1043     No(&'static [&'static str]),
1044 }
1045
1046 /// Returns `true` if `frag` can legally be followed by the token `tok`. For
1047 /// fragments that can consume an unbounded number of tokens, `tok`
1048 /// must be within a well-defined follow set. This is intended to
1049 /// guarantee future compatibility: for example, without this rule, if
1050 /// we expanded `expr` to include a new binary operator, we might
1051 /// break macros that were relying on that binary operator as a
1052 /// separator.
1053 // when changing this do not forget to update doc/book/macros.md!
1054 fn is_in_follow(tok: &mbe::TokenTree, kind: NonterminalKind) -> IsInFollow {
1055     use mbe::TokenTree;
1056
1057     if let TokenTree::Token(Token { kind: token::CloseDelim(_), .. }) = *tok {
1058         // closing a token tree can never be matched by any fragment;
1059         // iow, we always require that `(` and `)` match, etc.
1060         IsInFollow::Yes
1061     } else {
1062         match kind {
1063             NonterminalKind::Item => {
1064                 // since items *must* be followed by either a `;` or a `}`, we can
1065                 // accept anything after them
1066                 IsInFollow::Yes
1067             }
1068             NonterminalKind::Block => {
1069                 // anything can follow block, the braces provide an easy boundary to
1070                 // maintain
1071                 IsInFollow::Yes
1072             }
1073             NonterminalKind::Stmt | NonterminalKind::Expr => {
1074                 const TOKENS: &[&str] = &["`=>`", "`,`", "`;`"];
1075                 match tok {
1076                     TokenTree::Token(token) => match token.kind {
1077                         FatArrow | Comma | Semi => IsInFollow::Yes,
1078                         _ => IsInFollow::No(TOKENS),
1079                     },
1080                     _ => IsInFollow::No(TOKENS),
1081                 }
1082             }
1083             NonterminalKind::Pat => {
1084                 const TOKENS: &[&str] = &["`=>`", "`,`", "`=`", "`|`", "`if`", "`in`"];
1085                 match tok {
1086                     TokenTree::Token(token) => match token.kind {
1087                         FatArrow | Comma | Eq | BinOp(token::Or) => IsInFollow::Yes,
1088                         Ident(name, false) if name == kw::If || name == kw::In => IsInFollow::Yes,
1089                         _ => IsInFollow::No(TOKENS),
1090                     },
1091                     _ => IsInFollow::No(TOKENS),
1092                 }
1093             }
1094             NonterminalKind::Path | NonterminalKind::Ty => {
1095                 const TOKENS: &[&str] = &[
1096                     "`{`", "`[`", "`=>`", "`,`", "`>`", "`=`", "`:`", "`;`", "`|`", "`as`",
1097                     "`where`",
1098                 ];
1099                 match tok {
1100                     TokenTree::Token(token) => match token.kind {
1101                         OpenDelim(token::DelimToken::Brace)
1102                         | OpenDelim(token::DelimToken::Bracket)
1103                         | Comma
1104                         | FatArrow
1105                         | Colon
1106                         | Eq
1107                         | Gt
1108                         | BinOp(token::Shr)
1109                         | Semi
1110                         | BinOp(token::Or) => IsInFollow::Yes,
1111                         Ident(name, false) if name == kw::As || name == kw::Where => {
1112                             IsInFollow::Yes
1113                         }
1114                         _ => IsInFollow::No(TOKENS),
1115                     },
1116                     TokenTree::MetaVarDecl(_, _, Some(NonterminalKind::Block)) => IsInFollow::Yes,
1117                     _ => IsInFollow::No(TOKENS),
1118                 }
1119             }
1120             NonterminalKind::Ident | NonterminalKind::Lifetime => {
1121                 // being a single token, idents and lifetimes are harmless
1122                 IsInFollow::Yes
1123             }
1124             NonterminalKind::Literal => {
1125                 // literals may be of a single token, or two tokens (negative numbers)
1126                 IsInFollow::Yes
1127             }
1128             NonterminalKind::Meta | NonterminalKind::TT => {
1129                 // being either a single token or a delimited sequence, tt is
1130                 // harmless
1131                 IsInFollow::Yes
1132             }
1133             NonterminalKind::Vis => {
1134                 // Explicitly disallow `priv`, on the off chance it comes back.
1135                 const TOKENS: &[&str] = &["`,`", "an ident", "a type"];
1136                 match tok {
1137                     TokenTree::Token(token) => match token.kind {
1138                         Comma => IsInFollow::Yes,
1139                         Ident(name, is_raw) if is_raw || name != kw::Priv => IsInFollow::Yes,
1140                         _ => {
1141                             if token.can_begin_type() {
1142                                 IsInFollow::Yes
1143                             } else {
1144                                 IsInFollow::No(TOKENS)
1145                             }
1146                         }
1147                     },
1148                     TokenTree::MetaVarDecl(
1149                         _,
1150                         _,
1151                         Some(NonterminalKind::Ident | NonterminalKind::Ty | NonterminalKind::Path),
1152                     ) => IsInFollow::Yes,
1153                     _ => IsInFollow::No(TOKENS),
1154                 }
1155             }
1156         }
1157     }
1158 }
1159
1160 fn quoted_tt_to_string(tt: &mbe::TokenTree) -> String {
1161     match *tt {
1162         mbe::TokenTree::Token(ref token) => pprust::token_to_string(&token),
1163         mbe::TokenTree::MetaVar(_, name) => format!("${}", name),
1164         mbe::TokenTree::MetaVarDecl(_, name, Some(kind)) => format!("${}:{}", name, kind),
1165         mbe::TokenTree::MetaVarDecl(_, name, None) => format!("${}:", name),
1166         _ => panic!(
1167             "unexpected mbe::TokenTree::{{Sequence or Delimited}} \
1168              in follow set checker"
1169         ),
1170     }
1171 }
1172
1173 fn parser_from_cx(sess: &ParseSess, tts: TokenStream) -> Parser<'_> {
1174     Parser::new(sess, tts, true, rustc_parse::MACRO_ARGUMENTS)
1175 }
1176
1177 /// Generates an appropriate parsing failure message. For EOF, this is "unexpected end...". For
1178 /// other tokens, this is "unexpected token...".
1179 fn parse_failure_msg(tok: &Token) -> String {
1180     match tok.kind {
1181         token::Eof => "unexpected end of macro invocation".to_string(),
1182         _ => format!("no rules expected the token `{}`", pprust::token_to_string(tok),),
1183     }
1184 }