]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/tt/macro_rules.rs
d25339a78f43c1f56bd243b6dabf6326c264f4e0
[rust.git] / src / libsyntax / ext / tt / macro_rules.rs
1 use crate::{ast, attr};
2 use crate::edition::Edition;
3 use crate::ext::base::{DummyResult, ExtCtxt, MacResult, SyntaxExtension};
4 use crate::ext::base::{NormalTT, TTMacroExpander};
5 use crate::ext::expand::{AstFragment, AstFragmentKind};
6 use crate::ext::tt::macro_parser::{Success, Error, Failure};
7 use crate::ext::tt::macro_parser::{MatchedSeq, MatchedNonterminal};
8 use crate::ext::tt::macro_parser::{parse, parse_failure_msg};
9 use crate::ext::tt::quoted;
10 use crate::ext::tt::transcribe::transcribe;
11 use crate::feature_gate::Features;
12 use crate::parse::{Directory, ParseSess};
13 use crate::parse::parser::Parser;
14 use crate::parse::token::{self, Token, NtTT};
15 use crate::parse::token::TokenKind::*;
16 use crate::symbol::{Symbol, kw, sym};
17 use crate::tokenstream::{DelimSpan, TokenStream, TokenTree};
18
19 use errors::FatalError;
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 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, &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, None);
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(token, msg) => if token.span.lo() >= best_fail_spot.lo() {
194                 best_fail_spot = token.span;
195                 best_fail_tok = Some(token.kind);
196                 best_fail_text = Some(msg);
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::from_str("lhs").gensym();
256     let rhs_nm = ast::Ident::from_str("rhs").gensym();
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(token::FatArrow, DUMMY_SP),
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(token::Semi, DUMMY_SP)],
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(token, msg) => {
292             let s = parse_failure_msg(token.kind);
293             let sp = token.span.substitute_dummy(def.span);
294             let mut err = sess.span_diagnostic.struct_span_fatal(sp, &s);
295             err.span_label(sp, msg);
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, sym::allow_internal_unstable)
380             .map(|attr| attr
381                 .meta_item_list()
382                 .map(|list| list.iter()
383                     .filter_map(|it| {
384                         let name = it.ident().map(|ident| ident.name);
385                         if name.is_none() {
386                             sess.span_diagnostic.span_err(it.span(),
387                                 "allow internal unstable expects feature names")
388                         }
389                         name
390                     })
391                     .collect::<Vec<Symbol>>().into()
392                 )
393                 .unwrap_or_else(|| {
394                     sess.span_diagnostic.span_warn(
395                         attr.span, "allow_internal_unstable expects list of feature names. In the \
396                         future this will become a hard error. Please use `allow_internal_unstable(\
397                         foo, bar)` to only allow the `foo` and `bar` features",
398                     );
399                     vec![sym::allow_internal_unstable_backcompat_hack].into()
400                 })
401             );
402         let allow_internal_unsafe = attr::contains_name(&def.attrs, sym::allow_internal_unsafe);
403         let mut local_inner_macros = false;
404         if let Some(macro_export) = attr::find_by_name(&def.attrs, sym::macro_export) {
405             if let Some(l) = macro_export.meta_item_list() {
406                 local_inner_macros = attr::list_contains_name(&l, sym::local_inner_macros);
407             }
408         }
409
410         let unstable_feature = attr::find_stability(&sess,
411                                                     &def.attrs, def.span).and_then(|stability| {
412             if let attr::StabilityLevel::Unstable { issue, .. } = stability.level {
413                 Some((stability.feature, issue))
414             } else {
415                 None
416             }
417         });
418
419         NormalTT {
420             expander,
421             def_info: Some((def.id, def.span)),
422             allow_internal_unstable,
423             allow_internal_unsafe,
424             local_inner_macros,
425             unstable_feature,
426             edition,
427         }
428     } else {
429         let is_transparent = attr::contains_name(&def.attrs, sym::rustc_transparent_macro);
430
431         SyntaxExtension::DeclMacro {
432             expander,
433             def_info: Some((def.id, def.span)),
434             is_transparent,
435             edition,
436         }
437     }
438 }
439
440 fn check_lhs_nt_follows(sess: &ParseSess,
441                         features: &Features,
442                         attrs: &[ast::Attribute],
443                         lhs: &quoted::TokenTree) -> bool {
444     // lhs is going to be like TokenTree::Delimited(...), where the
445     // entire lhs is those tts. Or, it can be a "bare sequence", not wrapped in parens.
446     if let quoted::TokenTree::Delimited(_, ref tts) = *lhs {
447         check_matcher(sess, features, attrs, &tts.tts)
448     } else {
449         let msg = "invalid macro matcher; matchers must be contained in balanced delimiters";
450         sess.span_diagnostic.span_err(lhs.span(), msg);
451         false
452     }
453     // we don't abort on errors on rejection, the driver will do that for us
454     // after parsing/expansion. we can report every error in every macro this way.
455 }
456
457 /// Checks that the lhs contains no repetition which could match an empty token
458 /// tree, because then the matcher would hang indefinitely.
459 fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[quoted::TokenTree]) -> bool {
460     use quoted::TokenTree;
461     for tt in tts {
462         match *tt {
463             TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => (),
464             TokenTree::Delimited(_, ref del) => if !check_lhs_no_empty_seq(sess, &del.tts) {
465                 return false;
466             },
467             TokenTree::Sequence(span, ref seq) => {
468                 if seq.separator.is_none() && seq.tts.iter().all(|seq_tt| {
469                     match *seq_tt {
470                         TokenTree::MetaVarDecl(_, _, id) => id.name == sym::vis,
471                         TokenTree::Sequence(_, ref sub_seq) =>
472                             sub_seq.op == quoted::KleeneOp::ZeroOrMore
473                             || sub_seq.op == quoted::KleeneOp::ZeroOrOne,
474                         _ => false,
475                     }
476                 }) {
477                     let sp = span.entire();
478                     sess.span_diagnostic.span_err(sp, "repetition matches empty token tree");
479                     return false;
480                 }
481                 if !check_lhs_no_empty_seq(sess, &seq.tts) {
482                     return false;
483                 }
484             }
485         }
486     }
487
488     true
489 }
490
491 /// Check that the LHS contains no duplicate matcher bindings. e.g. `$a:expr, $a:expr` would be
492 /// illegal, since it would be ambiguous which `$a` to use if we ever needed to.
493 fn check_lhs_duplicate_matcher_bindings(
494     sess: &ParseSess,
495     tts: &[quoted::TokenTree],
496     metavar_names: &mut FxHashMap<Ident, Span>,
497     node_id: ast::NodeId,
498 ) -> bool {
499     use self::quoted::TokenTree;
500     for tt in tts {
501         match *tt {
502             TokenTree::MetaVarDecl(span, name, _kind) => {
503                 if let Some(&prev_span) = metavar_names.get(&name) {
504                     sess.span_diagnostic
505                         .struct_span_err(span, "duplicate matcher binding")
506                         .span_note(prev_span, "previous declaration was here")
507                         .emit();
508                     return false;
509                 } else {
510                     metavar_names.insert(name, span);
511                 }
512             }
513             TokenTree::Delimited(_, ref del) => {
514                 if !check_lhs_duplicate_matcher_bindings(sess, &del.tts, metavar_names, node_id) {
515                     return false;
516                 }
517             },
518             TokenTree::Sequence(_, ref seq) => {
519                 if !check_lhs_duplicate_matcher_bindings(sess, &seq.tts, metavar_names, node_id) {
520                     return false;
521                 }
522             }
523             _ => {}
524         }
525     }
526
527     true
528 }
529
530 fn check_rhs(sess: &ParseSess, rhs: &quoted::TokenTree) -> bool {
531     match *rhs {
532         quoted::TokenTree::Delimited(..) => return true,
533         _ => sess.span_diagnostic.span_err(rhs.span(), "macro rhs must be delimited")
534     }
535     false
536 }
537
538 fn check_matcher(sess: &ParseSess,
539                  features: &Features,
540                  attrs: &[ast::Attribute],
541                  matcher: &[quoted::TokenTree]) -> bool {
542     let first_sets = FirstSets::new(matcher);
543     let empty_suffix = TokenSet::empty();
544     let err = sess.span_diagnostic.err_count();
545     check_matcher_core(sess, features, attrs, &first_sets, matcher, &empty_suffix);
546     err == sess.span_diagnostic.err_count()
547 }
548
549 // `The FirstSets` for a matcher is a mapping from subsequences in the
550 // matcher to the FIRST set for that subsequence.
551 //
552 // This mapping is partially precomputed via a backwards scan over the
553 // token trees of the matcher, which provides a mapping from each
554 // repetition sequence to its *first* set.
555 //
556 // (Hypothetically, sequences should be uniquely identifiable via their
557 // spans, though perhaps that is false, e.g., for macro-generated macros
558 // that do not try to inject artificial span information. My plan is
559 // to try to catch such cases ahead of time and not include them in
560 // the precomputed mapping.)
561 struct FirstSets {
562     // this maps each TokenTree::Sequence `$(tt ...) SEP OP` that is uniquely identified by its
563     // span in the original matcher to the First set for the inner sequence `tt ...`.
564     //
565     // If two sequences have the same span in a matcher, then map that
566     // span to None (invalidating the mapping here and forcing the code to
567     // use a slow path).
568     first: FxHashMap<Span, Option<TokenSet>>,
569 }
570
571 impl FirstSets {
572     fn new(tts: &[quoted::TokenTree]) -> FirstSets {
573         use quoted::TokenTree;
574
575         let mut sets = FirstSets { first: FxHashMap::default() };
576         build_recur(&mut sets, tts);
577         return sets;
578
579         // walks backward over `tts`, returning the FIRST for `tts`
580         // and updating `sets` at the same time for all sequence
581         // substructure we find within `tts`.
582         fn build_recur(sets: &mut FirstSets, tts: &[TokenTree]) -> TokenSet {
583             let mut first = TokenSet::empty();
584             for tt in tts.iter().rev() {
585                 match *tt {
586                     TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
587                         first.replace_with(tt.clone());
588                     }
589                     TokenTree::Delimited(span, ref delimited) => {
590                         build_recur(sets, &delimited.tts[..]);
591                         first.replace_with(delimited.open_tt(span.open));
592                     }
593                     TokenTree::Sequence(sp, ref seq_rep) => {
594                         let subfirst = build_recur(sets, &seq_rep.tts[..]);
595
596                         match sets.first.entry(sp.entire()) {
597                             Entry::Vacant(vac) => {
598                                 vac.insert(Some(subfirst.clone()));
599                             }
600                             Entry::Occupied(mut occ) => {
601                                 // if there is already an entry, then a span must have collided.
602                                 // This should not happen with typical macro_rules macros,
603                                 // but syntax extensions need not maintain distinct spans,
604                                 // so distinct syntax trees can be assigned the same span.
605                                 // In such a case, the map cannot be trusted; so mark this
606                                 // entry as unusable.
607                                 occ.insert(None);
608                             }
609                         }
610
611                         // If the sequence contents can be empty, then the first
612                         // token could be the separator token itself.
613
614                         if let (Some(ref sep), true) = (seq_rep.separator.clone(),
615                                                         subfirst.maybe_empty) {
616                             first.add_one_maybe(TokenTree::token(sep.clone(), sp.entire()));
617                         }
618
619                         // Reverse scan: Sequence comes before `first`.
620                         if subfirst.maybe_empty
621                            || seq_rep.op == quoted::KleeneOp::ZeroOrMore
622                            || seq_rep.op == quoted::KleeneOp::ZeroOrOne
623                         {
624                             // If sequence is potentially empty, then
625                             // union them (preserving first emptiness).
626                             first.add_all(&TokenSet { maybe_empty: true, ..subfirst });
627                         } else {
628                             // Otherwise, sequence guaranteed
629                             // non-empty; replace first.
630                             first = subfirst;
631                         }
632                     }
633                 }
634             }
635
636             first
637         }
638     }
639
640     // walks forward over `tts` until all potential FIRST tokens are
641     // identified.
642     fn first(&self, tts: &[quoted::TokenTree]) -> TokenSet {
643         use quoted::TokenTree;
644
645         let mut first = TokenSet::empty();
646         for tt in tts.iter() {
647             assert!(first.maybe_empty);
648             match *tt {
649                 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
650                     first.add_one(tt.clone());
651                     return first;
652                 }
653                 TokenTree::Delimited(span, ref delimited) => {
654                     first.add_one(delimited.open_tt(span.open));
655                     return first;
656                 }
657                 TokenTree::Sequence(sp, ref seq_rep) => {
658                     match self.first.get(&sp.entire()) {
659                         Some(&Some(ref subfirst)) => {
660
661                             // If the sequence contents can be empty, then the first
662                             // token could be the separator token itself.
663
664                             if let (Some(ref sep), true) = (seq_rep.separator.clone(),
665                                                             subfirst.maybe_empty) {
666                                 first.add_one_maybe(TokenTree::token(sep.clone(), sp.entire()));
667                             }
668
669                             assert!(first.maybe_empty);
670                             first.add_all(subfirst);
671                             if subfirst.maybe_empty
672                                || seq_rep.op == quoted::KleeneOp::ZeroOrMore
673                                || seq_rep.op == quoted::KleeneOp::ZeroOrOne
674                             {
675                                 // continue scanning for more first
676                                 // tokens, but also make sure we
677                                 // restore empty-tracking state
678                                 first.maybe_empty = true;
679                                 continue;
680                             } else {
681                                 return first;
682                             }
683                         }
684
685                         Some(&None) => {
686                             panic!("assume all sequences have (unique) spans for now");
687                         }
688
689                         None => {
690                             panic!("We missed a sequence during FirstSets construction");
691                         }
692                     }
693                 }
694             }
695         }
696
697         // we only exit the loop if `tts` was empty or if every
698         // element of `tts` matches the empty sequence.
699         assert!(first.maybe_empty);
700         first
701     }
702 }
703
704 // A set of `quoted::TokenTree`s, which may include `TokenTree::Match`s
705 // (for macro-by-example syntactic variables). It also carries the
706 // `maybe_empty` flag; that is true if and only if the matcher can
707 // match an empty token sequence.
708 //
709 // The First set is computed on submatchers like `$($a:expr b),* $(c)* d`,
710 // which has corresponding FIRST = {$a:expr, c, d}.
711 // Likewise, `$($a:expr b),* $(c)+ d` has FIRST = {$a:expr, c}.
712 //
713 // (Notably, we must allow for *-op to occur zero times.)
714 #[derive(Clone, Debug)]
715 struct TokenSet {
716     tokens: Vec<quoted::TokenTree>,
717     maybe_empty: bool,
718 }
719
720 impl TokenSet {
721     // Returns a set for the empty sequence.
722     fn empty() -> Self { TokenSet { tokens: Vec::new(), maybe_empty: true } }
723
724     // Returns the set `{ tok }` for the single-token (and thus
725     // non-empty) sequence [tok].
726     fn singleton(tok: quoted::TokenTree) -> Self {
727         TokenSet { tokens: vec![tok], maybe_empty: false }
728     }
729
730     // Changes self to be the set `{ tok }`.
731     // Since `tok` is always present, marks self as non-empty.
732     fn replace_with(&mut self, tok: quoted::TokenTree) {
733         self.tokens.clear();
734         self.tokens.push(tok);
735         self.maybe_empty = false;
736     }
737
738     // Changes self to be the empty set `{}`; meant for use when
739     // the particular token does not matter, but we want to
740     // record that it occurs.
741     fn replace_with_irrelevant(&mut self) {
742         self.tokens.clear();
743         self.maybe_empty = false;
744     }
745
746     // Adds `tok` to the set for `self`, marking sequence as non-empy.
747     fn add_one(&mut self, tok: quoted::TokenTree) {
748         if !self.tokens.contains(&tok) {
749             self.tokens.push(tok);
750         }
751         self.maybe_empty = false;
752     }
753
754     // Adds `tok` to the set for `self`. (Leaves `maybe_empty` flag alone.)
755     fn add_one_maybe(&mut self, tok: quoted::TokenTree) {
756         if !self.tokens.contains(&tok) {
757             self.tokens.push(tok);
758         }
759     }
760
761     // Adds all elements of `other` to this.
762     //
763     // (Since this is a set, we filter out duplicates.)
764     //
765     // If `other` is potentially empty, then preserves the previous
766     // setting of the empty flag of `self`. If `other` is guaranteed
767     // non-empty, then `self` is marked non-empty.
768     fn add_all(&mut self, other: &Self) {
769         for tok in &other.tokens {
770             if !self.tokens.contains(tok) {
771                 self.tokens.push(tok.clone());
772             }
773         }
774         if !other.maybe_empty {
775             self.maybe_empty = false;
776         }
777     }
778 }
779
780 // Checks that `matcher` is internally consistent and that it
781 // can legally by followed by a token N, for all N in `follow`.
782 // (If `follow` is empty, then it imposes no constraint on
783 // the `matcher`.)
784 //
785 // Returns the set of NT tokens that could possibly come last in
786 // `matcher`. (If `matcher` matches the empty sequence, then
787 // `maybe_empty` will be set to true.)
788 //
789 // Requires that `first_sets` is pre-computed for `matcher`;
790 // see `FirstSets::new`.
791 fn check_matcher_core(sess: &ParseSess,
792                       features: &Features,
793                       attrs: &[ast::Attribute],
794                       first_sets: &FirstSets,
795                       matcher: &[quoted::TokenTree],
796                       follow: &TokenSet) -> TokenSet {
797     use quoted::TokenTree;
798
799     let mut last = TokenSet::empty();
800
801     // 2. For each token and suffix  [T, SUFFIX] in M:
802     // ensure that T can be followed by SUFFIX, and if SUFFIX may be empty,
803     // then ensure T can also be followed by any element of FOLLOW.
804     'each_token: for i in 0..matcher.len() {
805         let token = &matcher[i];
806         let suffix = &matcher[i+1..];
807
808         let build_suffix_first = || {
809             let mut s = first_sets.first(suffix);
810             if s.maybe_empty { s.add_all(follow); }
811             s
812         };
813
814         // (we build `suffix_first` on demand below; you can tell
815         // which cases are supposed to fall through by looking for the
816         // initialization of this variable.)
817         let suffix_first;
818
819         // First, update `last` so that it corresponds to the set
820         // of NT tokens that might end the sequence `... token`.
821         match *token {
822             TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
823                 let can_be_followed_by_any;
824                 if let Err(bad_frag) = has_legal_fragment_specifier(sess, features, attrs, token) {
825                     let msg = format!("invalid fragment specifier `{}`", bad_frag);
826                     sess.span_diagnostic.struct_span_err(token.span(), &msg)
827                         .help(VALID_FRAGMENT_NAMES_MSG)
828                         .emit();
829                     // (This eliminates false positives and duplicates
830                     // from error messages.)
831                     can_be_followed_by_any = true;
832                 } else {
833                     can_be_followed_by_any = token_can_be_followed_by_any(token);
834                 }
835
836                 if can_be_followed_by_any {
837                     // don't need to track tokens that work with any,
838                     last.replace_with_irrelevant();
839                     // ... and don't need to check tokens that can be
840                     // followed by anything against SUFFIX.
841                     continue 'each_token;
842                 } else {
843                     last.replace_with(token.clone());
844                     suffix_first = build_suffix_first();
845                 }
846             }
847             TokenTree::Delimited(span, ref d) => {
848                 let my_suffix = TokenSet::singleton(d.close_tt(span.close));
849                 check_matcher_core(sess, features, attrs, first_sets, &d.tts, &my_suffix);
850                 // don't track non NT tokens
851                 last.replace_with_irrelevant();
852
853                 // also, we don't need to check delimited sequences
854                 // against SUFFIX
855                 continue 'each_token;
856             }
857             TokenTree::Sequence(sp, ref seq_rep) => {
858                 suffix_first = build_suffix_first();
859                 // The trick here: when we check the interior, we want
860                 // to include the separator (if any) as a potential
861                 // (but not guaranteed) element of FOLLOW. So in that
862                 // case, we make a temp copy of suffix and stuff
863                 // delimiter in there.
864                 //
865                 // FIXME: Should I first scan suffix_first to see if
866                 // delimiter is already in it before I go through the
867                 // work of cloning it? But then again, this way I may
868                 // get a "tighter" span?
869                 let mut new;
870                 let my_suffix = if let Some(ref u) = seq_rep.separator {
871                     new = suffix_first.clone();
872                     new.add_one_maybe(TokenTree::token(u.clone(), sp.entire()));
873                     &new
874                 } else {
875                     &suffix_first
876                 };
877
878                 // At this point, `suffix_first` is built, and
879                 // `my_suffix` is some TokenSet that we can use
880                 // for checking the interior of `seq_rep`.
881                 let next = check_matcher_core(sess,
882                                               features,
883                                               attrs,
884                                               first_sets,
885                                               &seq_rep.tts,
886                                               my_suffix);
887                 if next.maybe_empty {
888                     last.add_all(&next);
889                 } else {
890                     last = next;
891                 }
892
893                 // the recursive call to check_matcher_core already ran the 'each_last
894                 // check below, so we can just keep going forward here.
895                 continue 'each_token;
896             }
897         }
898
899         // (`suffix_first` guaranteed initialized once reaching here.)
900
901         // Now `last` holds the complete set of NT tokens that could
902         // end the sequence before SUFFIX. Check that every one works with `suffix`.
903         'each_last: for token in &last.tokens {
904             if let TokenTree::MetaVarDecl(_, ref name, ref frag_spec) = *token {
905                 for next_token in &suffix_first.tokens {
906                     match is_in_follow(next_token, &frag_spec.as_str()) {
907                         IsInFollow::Invalid(msg, help) => {
908                             sess.span_diagnostic.struct_span_err(next_token.span(), &msg)
909                                 .help(help).emit();
910                             // don't bother reporting every source of
911                             // conflict for a particular element of `last`.
912                             continue 'each_last;
913                         }
914                         IsInFollow::Yes => {}
915                         IsInFollow::No(ref possible) => {
916                             let may_be = if last.tokens.len() == 1 &&
917                                 suffix_first.tokens.len() == 1
918                             {
919                                 "is"
920                             } else {
921                                 "may be"
922                             };
923
924                             let sp = next_token.span();
925                             let mut err = sess.span_diagnostic.struct_span_err(
926                                 sp,
927                                 &format!("`${name}:{frag}` {may_be} followed by `{next}`, which \
928                                           is not allowed for `{frag}` fragments",
929                                          name=name,
930                                          frag=frag_spec,
931                                          next=quoted_tt_to_string(next_token),
932                                          may_be=may_be),
933                             );
934                             err.span_label(
935                                 sp,
936                                 format!("not allowed after `{}` fragments", frag_spec),
937                             );
938                             let msg = "allowed there are: ";
939                             match &possible[..] {
940                                 &[] => {}
941                                 &[t] => {
942                                     err.note(&format!(
943                                         "only {} is allowed after `{}` fragments",
944                                         t,
945                                         frag_spec,
946                                     ));
947                                 }
948                                 ts => {
949                                     err.note(&format!(
950                                         "{}{} or {}",
951                                         msg,
952                                         ts[..ts.len() - 1].iter().map(|s| *s)
953                                             .collect::<Vec<_>>().join(", "),
954                                         ts[ts.len() - 1],
955                                     ));
956                                 }
957                             }
958                             err.emit();
959                         }
960                     }
961                 }
962             }
963         }
964     }
965     last
966 }
967
968 fn token_can_be_followed_by_any(tok: &quoted::TokenTree) -> bool {
969     if let quoted::TokenTree::MetaVarDecl(_, _, frag_spec) = *tok {
970         frag_can_be_followed_by_any(&frag_spec.as_str())
971     } else {
972         // (Non NT's can always be followed by anthing in matchers.)
973         true
974     }
975 }
976
977 /// Returns `true` if a fragment of type `frag` can be followed by any sort of
978 /// token. We use this (among other things) as a useful approximation
979 /// for when `frag` can be followed by a repetition like `$(...)*` or
980 /// `$(...)+`. In general, these can be a bit tricky to reason about,
981 /// so we adopt a conservative position that says that any fragment
982 /// specifier which consumes at most one token tree can be followed by
983 /// a fragment specifier (indeed, these fragments can be followed by
984 /// ANYTHING without fear of future compatibility hazards).
985 fn frag_can_be_followed_by_any(frag: &str) -> bool {
986     match frag {
987         "item"     | // always terminated by `}` or `;`
988         "block"    | // exactly one token tree
989         "ident"    | // exactly one token tree
990         "literal"  | // exactly one token tree
991         "meta"     | // exactly one token tree
992         "lifetime" | // exactly one token tree
993         "tt" =>   // exactly one token tree
994             true,
995
996         _ =>
997             false,
998     }
999 }
1000
1001 enum IsInFollow {
1002     Yes,
1003     No(Vec<&'static str>),
1004     Invalid(String, &'static str),
1005 }
1006
1007 /// Returns `true` if `frag` can legally be followed by the token `tok`. For
1008 /// fragments that can consume an unbounded number of tokens, `tok`
1009 /// must be within a well-defined follow set. This is intended to
1010 /// guarantee future compatibility: for example, without this rule, if
1011 /// we expanded `expr` to include a new binary operator, we might
1012 /// break macros that were relying on that binary operator as a
1013 /// separator.
1014 // when changing this do not forget to update doc/book/macros.md!
1015 fn is_in_follow(tok: &quoted::TokenTree, frag: &str) -> IsInFollow {
1016     use quoted::TokenTree;
1017
1018     if let TokenTree::Token(Token { kind: token::CloseDelim(_), .. }) = *tok {
1019         // closing a token tree can never be matched by any fragment;
1020         // iow, we always require that `(` and `)` match, etc.
1021         IsInFollow::Yes
1022     } else {
1023         match frag {
1024             "item" => {
1025                 // since items *must* be followed by either a `;` or a `}`, we can
1026                 // accept anything after them
1027                 IsInFollow::Yes
1028             },
1029             "block" => {
1030                 // anything can follow block, the braces provide an easy boundary to
1031                 // maintain
1032                 IsInFollow::Yes
1033             },
1034             "stmt" | "expr"  => {
1035                 let tokens = vec!["`=>`", "`,`", "`;`"];
1036                 match tok {
1037                     TokenTree::Token(token) => match token.kind {
1038                         FatArrow | Comma | Semi => IsInFollow::Yes,
1039                         _ => IsInFollow::No(tokens),
1040                     },
1041                     _ => IsInFollow::No(tokens),
1042                 }
1043             },
1044             "pat" => {
1045                 let tokens = vec!["`=>`", "`,`", "`=`", "`|`", "`if`", "`in`"];
1046                 match tok {
1047                     TokenTree::Token(token) => match token.kind {
1048                         FatArrow | Comma | Eq | BinOp(token::Or) => IsInFollow::Yes,
1049                         Ident(name, false) if name == kw::If || name == kw::In => IsInFollow::Yes,
1050                         _ => IsInFollow::No(tokens),
1051                     },
1052                     _ => IsInFollow::No(tokens),
1053                 }
1054             },
1055             "path" | "ty" => {
1056                 let tokens = vec![
1057                     "`{`", "`[`", "`=>`", "`,`", "`>`","`=`", "`:`", "`;`", "`|`", "`as`",
1058                     "`where`",
1059                 ];
1060                 match tok {
1061                     TokenTree::Token(token) => match token.kind {
1062                         OpenDelim(token::DelimToken::Brace) |
1063                         OpenDelim(token::DelimToken::Bracket) |
1064                         Comma | FatArrow | Colon | Eq | Gt | BinOp(token::Shr) | Semi |
1065                         BinOp(token::Or) => IsInFollow::Yes,
1066                         Ident(name, false) if name == kw::As ||
1067                                               name == kw::Where => IsInFollow::Yes,
1068                         _ => IsInFollow::No(tokens),
1069                     },
1070                     TokenTree::MetaVarDecl(_, _, frag) if frag.name == sym::block =>
1071                         IsInFollow::Yes,
1072                     _ => IsInFollow::No(tokens),
1073                 }
1074             },
1075             "ident" | "lifetime" => {
1076                 // being a single token, idents and lifetimes are harmless
1077                 IsInFollow::Yes
1078             },
1079             "literal" => {
1080                 // literals may be of a single token, or two tokens (negative numbers)
1081                 IsInFollow::Yes
1082             },
1083             "meta" | "tt" => {
1084                 // being either a single token or a delimited sequence, tt is
1085                 // harmless
1086                 IsInFollow::Yes
1087             },
1088             "vis" => {
1089                 // Explicitly disallow `priv`, on the off chance it comes back.
1090                 let tokens = vec!["`,`", "an ident", "a type"];
1091                 match tok {
1092                     TokenTree::Token(token) => match token.kind {
1093                         Comma => IsInFollow::Yes,
1094                         Ident(name, is_raw) if is_raw || name != kw::Priv => IsInFollow::Yes,
1095                         _ => if token.can_begin_type() {
1096                             IsInFollow::Yes
1097                         } else {
1098                             IsInFollow::No(tokens)
1099                         }
1100                     },
1101                     TokenTree::MetaVarDecl(_, _, frag) if frag.name == sym::ident
1102                                                        || frag.name == sym::ty
1103                                                        || frag.name == sym::path =>
1104                         IsInFollow::Yes,
1105                     _ => IsInFollow::No(tokens),
1106                 }
1107             },
1108             "" => IsInFollow::Yes, // kw::Invalid
1109             _ => IsInFollow::Invalid(format!("invalid fragment specifier `{}`", frag),
1110                                      VALID_FRAGMENT_NAMES_MSG),
1111         }
1112     }
1113 }
1114
1115 fn has_legal_fragment_specifier(sess: &ParseSess,
1116                                 features: &Features,
1117                                 attrs: &[ast::Attribute],
1118                                 tok: &quoted::TokenTree) -> Result<(), String> {
1119     debug!("has_legal_fragment_specifier({:?})", tok);
1120     if let quoted::TokenTree::MetaVarDecl(_, _, ref frag_spec) = *tok {
1121         let frag_name = frag_spec.as_str();
1122         let frag_span = tok.span();
1123         if !is_legal_fragment_specifier(sess, features, attrs, &frag_name, frag_span) {
1124             return Err(frag_name.to_string());
1125         }
1126     }
1127     Ok(())
1128 }
1129
1130 fn is_legal_fragment_specifier(_sess: &ParseSess,
1131                                _features: &Features,
1132                                _attrs: &[ast::Attribute],
1133                                frag_name: &str,
1134                                _frag_span: Span) -> bool {
1135     /*
1136      * If new fragment specifiers are invented in nightly, `_sess`,
1137      * `_features`, `_attrs`, and `_frag_span` will be useful here
1138      * for checking against feature gates. See past versions of
1139      * this function.
1140      */
1141     match frag_name {
1142         "item" | "block" | "stmt" | "expr" | "pat" | "lifetime" |
1143         "path" | "ty" | "ident" | "meta" | "tt" | "vis" | "literal" |
1144         "" => true,
1145         _ => false,
1146     }
1147 }
1148
1149 fn quoted_tt_to_string(tt: &quoted::TokenTree) -> String {
1150     match *tt {
1151         quoted::TokenTree::Token(ref token) => crate::print::pprust::token_to_string(&token),
1152         quoted::TokenTree::MetaVar(_, name) => format!("${}", name),
1153         quoted::TokenTree::MetaVarDecl(_, name, kind) => format!("${}:{}", name, kind),
1154         _ => panic!("unexpected quoted::TokenTree::{{Sequence or Delimited}} \
1155                      in follow set checker"),
1156     }
1157 }