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