]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/tt/macro_rules.rs
ad09d5837341297105b83532b61916dddc5c1ae5
[rust.git] / src / libsyntax / ext / tt / macro_rules.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use {ast, attr};
12 use syntax_pos::{Span, DUMMY_SP};
13 use ext::base::{DummyResult, ExtCtxt, MacResult, SyntaxExtension};
14 use ext::base::{NormalTT, TTMacroExpander};
15 use ext::expand::{Expansion, ExpansionKind};
16 use ext::tt::macro_parser::{Success, Error, Failure};
17 use ext::tt::macro_parser::{MatchedSeq, MatchedNonterminal};
18 use ext::tt::macro_parser::{parse, parse_failure_msg};
19 use ext::tt::quoted;
20 use ext::tt::transcribe::transcribe;
21 use feature_gate::{self, emit_feature_err, Features, GateIssue};
22 use parse::{Directory, ParseSess};
23 use parse::parser::Parser;
24 use parse::token::{self, NtTT};
25 use parse::token::Token::*;
26 use symbol::Symbol;
27 use tokenstream::{TokenStream, TokenTree};
28
29 use std::cell::RefCell;
30 use std::collections::HashMap;
31 use std::collections::hash_map::Entry;
32 use std::rc::Rc;
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 }
42
43 impl<'a> ParserAnyMacro<'a> {
44     pub fn make(mut self: Box<ParserAnyMacro<'a>>, kind: ExpansionKind) -> Expansion {
45         let ParserAnyMacro { site_span, macro_ident, ref mut parser } = *self;
46         let expansion = panictry!(parser.parse_expansion(kind, true));
47
48         // We allow semicolons at the end of expressions -- e.g. the semicolon in
49         // `macro_rules! m { () => { panic!(); } }` isn't parsed by `.parse_expr()`,
50         // but `m!()` is allowed in expression positions (c.f. issue #34706).
51         if kind == ExpansionKind::Expr && parser.token == token::Semi {
52             parser.bump();
53         }
54
55         // Make sure we don't have any tokens left to parse so we don't silently drop anything.
56         let path = ast::Path::from_ident(site_span, macro_ident);
57         parser.ensure_complete_parse(&path, kind.name(), site_span);
58         expansion
59     }
60 }
61
62 struct MacroRulesMacroExpander {
63     name: ast::Ident,
64     lhses: Vec<quoted::TokenTree>,
65     rhses: Vec<quoted::TokenTree>,
66     valid: bool,
67 }
68
69 impl TTMacroExpander for MacroRulesMacroExpander {
70     fn expand<'cx>(&self,
71                    cx: &'cx mut ExtCtxt,
72                    sp: Span,
73                    input: TokenStream)
74                    -> Box<MacResult+'cx> {
75         if !self.valid {
76             return DummyResult::any(sp);
77         }
78         generic_extension(cx,
79                           sp,
80                           self.name,
81                           input,
82                           &self.lhses,
83                           &self.rhses)
84     }
85 }
86
87 /// Given `lhses` and `rhses`, this is the new macro we create
88 fn generic_extension<'cx>(cx: &'cx mut ExtCtxt,
89                           sp: Span,
90                           name: ast::Ident,
91                           arg: TokenStream,
92                           lhses: &[quoted::TokenTree],
93                           rhses: &[quoted::TokenTree])
94                           -> Box<MacResult+'cx> {
95     if cx.trace_macros() {
96         let sp = sp.macro_backtrace().last().map(|trace| trace.call_site).unwrap_or(sp);
97         let mut values: &mut Vec<String> = cx.expansions.entry(sp).or_insert_with(Vec::new);
98         values.push(format!("expands to `{}! {{ {} }}`", name, arg));
99     }
100
101     // Which arm's failure should we report? (the one furthest along)
102     let mut best_fail_spot = DUMMY_SP;
103     let mut best_fail_tok = None;
104
105     for (i, lhs) in lhses.iter().enumerate() { // try each arm's matchers
106         let lhs_tt = match *lhs {
107             quoted::TokenTree::Delimited(_, ref delim) => &delim.tts[..],
108             _ => cx.span_bug(sp, "malformed macro lhs")
109         };
110
111         match TokenTree::parse(cx, lhs_tt, arg.clone()) {
112             Success(named_matches) => {
113                 let rhs = match rhses[i] {
114                     // ignore delimiters
115                     quoted::TokenTree::Delimited(_, ref delimed) => delimed.tts.clone(),
116                     _ => cx.span_bug(sp, "malformed macro rhs"),
117                 };
118                 // rhs has holes ( `$id` and `$(...)` that need filled)
119                 let tts = transcribe(&cx.parse_sess.span_diagnostic, Some(named_matches), rhs);
120                 let directory = Directory {
121                     path: cx.current_expansion.module.directory.clone(),
122                     ownership: cx.current_expansion.directory_ownership,
123                 };
124                 let mut p = Parser::new(cx.parse_sess(), tts, Some(directory), true, false);
125                 p.root_module_name = cx.current_expansion.module.mod_path.last()
126                     .map(|id| id.name.as_str().to_string());
127
128                 p.process_potential_macro_variable();
129                 // Let the context choose how to interpret the result.
130                 // Weird, but useful for X-macros.
131                 return Box::new(ParserAnyMacro {
132                     parser: p,
133
134                     // Pass along the original expansion site and the name of the macro
135                     // so we can print a useful error message if the parse of the expanded
136                     // macro leaves unparsed tokens.
137                     site_span: sp,
138                     macro_ident: name
139                 })
140             }
141             Failure(sp, tok) => if sp.lo >= best_fail_spot.lo {
142                 best_fail_spot = sp;
143                 best_fail_tok = Some(tok);
144             },
145             Error(err_sp, ref msg) => {
146                 cx.span_fatal(err_sp.substitute_dummy(sp), &msg[..])
147             }
148         }
149     }
150
151     let best_fail_msg = parse_failure_msg(best_fail_tok.expect("ran no matchers"));
152     cx.span_fatal(best_fail_spot.substitute_dummy(sp), &best_fail_msg);
153 }
154
155 // Note that macro-by-example's input is also matched against a token tree:
156 //                   $( $lhs:tt => $rhs:tt );+
157 //
158 // Holy self-referential!
159
160 /// Converts a `macro_rules!` invocation into a syntax extension.
161 pub fn compile(sess: &ParseSess, features: &RefCell<Features>, def: &ast::Item) -> SyntaxExtension {
162     let lhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("lhs"));
163     let rhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("rhs"));
164
165     // Parse the macro_rules! invocation
166     let body = match def.node {
167         ast::ItemKind::MacroDef(ref body) => body,
168         _ => unreachable!(),
169     };
170
171     // The pattern that macro_rules matches.
172     // The grammar for macro_rules! is:
173     // $( $lhs:tt => $rhs:tt );+
174     // ...quasiquoting this would be nice.
175     // These spans won't matter, anyways
176     let argument_gram = vec![
177         quoted::TokenTree::Sequence(DUMMY_SP, Rc::new(quoted::SequenceRepetition {
178             tts: vec![
179                 quoted::TokenTree::MetaVarDecl(DUMMY_SP, lhs_nm, ast::Ident::from_str("tt")),
180                 quoted::TokenTree::Token(DUMMY_SP, token::FatArrow),
181                 quoted::TokenTree::MetaVarDecl(DUMMY_SP, rhs_nm, ast::Ident::from_str("tt")),
182             ],
183             separator: Some(if body.legacy { token::Semi } else { token::Comma }),
184             op: quoted::KleeneOp::OneOrMore,
185             num_captures: 2,
186         })),
187         // to phase into semicolon-termination instead of semicolon-separation
188         quoted::TokenTree::Sequence(DUMMY_SP, Rc::new(quoted::SequenceRepetition {
189             tts: vec![quoted::TokenTree::Token(DUMMY_SP, token::Semi)],
190             separator: None,
191             op: quoted::KleeneOp::ZeroOrMore,
192             num_captures: 0
193         })),
194     ];
195
196     let argument_map = match parse(sess, body.stream(), &argument_gram, None, true) {
197         Success(m) => m,
198         Failure(sp, tok) => {
199             let s = parse_failure_msg(tok);
200             panic!(sess.span_diagnostic.span_fatal(sp.substitute_dummy(def.span), &s));
201         }
202         Error(sp, s) => {
203             panic!(sess.span_diagnostic.span_fatal(sp.substitute_dummy(def.span), &s));
204         }
205     };
206
207     let mut valid = true;
208
209     // Extract the arguments:
210     let lhses = match *argument_map[&lhs_nm] {
211         MatchedSeq(ref s, _) => {
212             s.iter().map(|m| {
213                 if let MatchedNonterminal(ref nt) = **m {
214                     if let NtTT(ref tt) = **nt {
215                         let tt = quoted::parse(tt.clone().into(), true, sess).pop().unwrap();
216                         valid &= check_lhs_nt_follows(sess, features, &tt);
217                         return tt;
218                     }
219                 }
220                 sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
221             }).collect::<Vec<quoted::TokenTree>>()
222         }
223         _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
224     };
225
226     let rhses = match *argument_map[&rhs_nm] {
227         MatchedSeq(ref s, _) => {
228             s.iter().map(|m| {
229                 if let MatchedNonterminal(ref nt) = **m {
230                     if let NtTT(ref tt) = **nt {
231                         return quoted::parse(tt.clone().into(), false, sess).pop().unwrap();
232                     }
233                 }
234                 sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
235             }).collect::<Vec<quoted::TokenTree>>()
236         }
237         _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured rhs")
238     };
239
240     for rhs in &rhses {
241         valid &= check_rhs(sess, rhs);
242     }
243
244     // don't abort iteration early, so that errors for multiple lhses can be reported
245     for lhs in &lhses {
246         valid &= check_lhs_no_empty_seq(sess, &[lhs.clone()])
247     }
248
249     let exp: Box<_> = Box::new(MacroRulesMacroExpander {
250         name: def.ident,
251         lhses: lhses,
252         rhses: rhses,
253         valid: valid,
254     });
255
256     NormalTT(exp,
257              Some((def.id, def.span)),
258              attr::contains_name(&def.attrs, "allow_internal_unstable"))
259 }
260
261 fn check_lhs_nt_follows(sess: &ParseSess,
262                         features: &RefCell<Features>,
263                         lhs: &quoted::TokenTree) -> bool {
264     // lhs is going to be like TokenTree::Delimited(...), where the
265     // entire lhs is those tts. Or, it can be a "bare sequence", not wrapped in parens.
266     if let quoted::TokenTree::Delimited(_, ref tts) = *lhs {
267         check_matcher(sess, features, &tts.tts)
268     } else {
269         let msg = "invalid macro matcher; matchers must be contained in balanced delimiters";
270         sess.span_diagnostic.span_err(lhs.span(), msg);
271         false
272     }
273     // we don't abort on errors on rejection, the driver will do that for us
274     // after parsing/expansion. we can report every error in every macro this way.
275 }
276
277 /// Check that the lhs contains no repetition which could match an empty token
278 /// tree, because then the matcher would hang indefinitely.
279 fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[quoted::TokenTree]) -> bool {
280     use self::quoted::TokenTree;
281     for tt in tts {
282         match *tt {
283             TokenTree::Token(..) | TokenTree::MetaVarDecl(..) => (),
284             TokenTree::Delimited(_, ref del) => if !check_lhs_no_empty_seq(sess, &del.tts) {
285                 return false;
286             },
287             TokenTree::Sequence(span, ref seq) => {
288                 if seq.separator.is_none() && seq.tts.iter().all(|seq_tt| {
289                     match *seq_tt {
290                         TokenTree::Sequence(_, ref sub_seq) =>
291                             sub_seq.op == quoted::KleeneOp::ZeroOrMore,
292                         _ => false,
293                     }
294                 }) {
295                     sess.span_diagnostic.span_err(span, "repetition matches empty token tree");
296                     return false;
297                 }
298                 if !check_lhs_no_empty_seq(sess, &seq.tts) {
299                     return false;
300                 }
301             }
302         }
303     }
304
305     true
306 }
307
308 fn check_rhs(sess: &ParseSess, rhs: &quoted::TokenTree) -> bool {
309     match *rhs {
310         quoted::TokenTree::Delimited(..) => return true,
311         _ => sess.span_diagnostic.span_err(rhs.span(), "macro rhs must be delimited")
312     }
313     false
314 }
315
316 fn check_matcher(sess: &ParseSess,
317                  features: &RefCell<Features>,
318                  matcher: &[quoted::TokenTree]) -> bool {
319     let first_sets = FirstSets::new(matcher);
320     let empty_suffix = TokenSet::empty();
321     let err = sess.span_diagnostic.err_count();
322     check_matcher_core(sess, features, &first_sets, matcher, &empty_suffix);
323     err == sess.span_diagnostic.err_count()
324 }
325
326 // The FirstSets for a matcher is a mapping from subsequences in the
327 // matcher to the FIRST set for that subsequence.
328 //
329 // This mapping is partially precomputed via a backwards scan over the
330 // token trees of the matcher, which provides a mapping from each
331 // repetition sequence to its FIRST set.
332 //
333 // (Hypothetically sequences should be uniquely identifiable via their
334 // spans, though perhaps that is false e.g. for macro-generated macros
335 // that do not try to inject artificial span information. My plan is
336 // to try to catch such cases ahead of time and not include them in
337 // the precomputed mapping.)
338 struct FirstSets {
339     // this maps each TokenTree::Sequence `$(tt ...) SEP OP` that is uniquely identified by its
340     // span in the original matcher to the First set for the inner sequence `tt ...`.
341     //
342     // If two sequences have the same span in a matcher, then map that
343     // span to None (invalidating the mapping here and forcing the code to
344     // use a slow path).
345     first: HashMap<Span, Option<TokenSet>>,
346 }
347
348 impl FirstSets {
349     fn new(tts: &[quoted::TokenTree]) -> FirstSets {
350         use self::quoted::TokenTree;
351
352         let mut sets = FirstSets { first: HashMap::new() };
353         build_recur(&mut sets, tts);
354         return sets;
355
356         // walks backward over `tts`, returning the FIRST for `tts`
357         // and updating `sets` at the same time for all sequence
358         // substructure we find within `tts`.
359         fn build_recur(sets: &mut FirstSets, tts: &[TokenTree]) -> TokenSet {
360             let mut first = TokenSet::empty();
361             for tt in tts.iter().rev() {
362                 match *tt {
363                     TokenTree::Token(..) | TokenTree::MetaVarDecl(..) => {
364                         first.replace_with(tt.clone());
365                     }
366                     TokenTree::Delimited(span, ref delimited) => {
367                         build_recur(sets, &delimited.tts[..]);
368                         first.replace_with(delimited.open_tt(span));
369                     }
370                     TokenTree::Sequence(sp, ref seq_rep) => {
371                         let subfirst = build_recur(sets, &seq_rep.tts[..]);
372
373                         match sets.first.entry(sp) {
374                             Entry::Vacant(vac) => {
375                                 vac.insert(Some(subfirst.clone()));
376                             }
377                             Entry::Occupied(mut occ) => {
378                                 // if there is already an entry, then a span must have collided.
379                                 // This should not happen with typical macro_rules macros,
380                                 // but syntax extensions need not maintain distinct spans,
381                                 // so distinct syntax trees can be assigned the same span.
382                                 // In such a case, the map cannot be trusted; so mark this
383                                 // entry as unusable.
384                                 occ.insert(None);
385                             }
386                         }
387
388                         // If the sequence contents can be empty, then the first
389                         // token could be the separator token itself.
390
391                         if let (Some(ref sep), true) = (seq_rep.separator.clone(),
392                                                         subfirst.maybe_empty) {
393                             first.add_one_maybe(TokenTree::Token(sp, sep.clone()));
394                         }
395
396                         // Reverse scan: Sequence comes before `first`.
397                         if subfirst.maybe_empty || seq_rep.op == quoted::KleeneOp::ZeroOrMore {
398                             // If sequence is potentially empty, then
399                             // union them (preserving first emptiness).
400                             first.add_all(&TokenSet { maybe_empty: true, ..subfirst });
401                         } else {
402                             // Otherwise, sequence guaranteed
403                             // non-empty; replace first.
404                             first = subfirst;
405                         }
406                     }
407                 }
408             }
409
410             first
411         }
412     }
413
414     // walks forward over `tts` until all potential FIRST tokens are
415     // identified.
416     fn first(&self, tts: &[quoted::TokenTree]) -> TokenSet {
417         use self::quoted::TokenTree;
418
419         let mut first = TokenSet::empty();
420         for tt in tts.iter() {
421             assert!(first.maybe_empty);
422             match *tt {
423                 TokenTree::Token(..) | TokenTree::MetaVarDecl(..) => {
424                     first.add_one(tt.clone());
425                     return first;
426                 }
427                 TokenTree::Delimited(span, ref delimited) => {
428                     first.add_one(delimited.open_tt(span));
429                     return first;
430                 }
431                 TokenTree::Sequence(sp, ref seq_rep) => {
432                     match self.first.get(&sp) {
433                         Some(&Some(ref subfirst)) => {
434
435                             // If the sequence contents can be empty, then the first
436                             // token could be the separator token itself.
437
438                             if let (Some(ref sep), true) = (seq_rep.separator.clone(),
439                                                             subfirst.maybe_empty) {
440                                 first.add_one_maybe(TokenTree::Token(sp, sep.clone()));
441                             }
442
443                             assert!(first.maybe_empty);
444                             first.add_all(subfirst);
445                             if subfirst.maybe_empty ||
446                                seq_rep.op == quoted::KleeneOp::ZeroOrMore {
447                                 // continue scanning for more first
448                                 // tokens, but also make sure we
449                                 // restore empty-tracking state
450                                 first.maybe_empty = true;
451                                 continue;
452                             } else {
453                                 return first;
454                             }
455                         }
456
457                         Some(&None) => {
458                             panic!("assume all sequences have (unique) spans for now");
459                         }
460
461                         None => {
462                             panic!("We missed a sequence during FirstSets construction");
463                         }
464                     }
465                 }
466             }
467         }
468
469         // we only exit the loop if `tts` was empty or if every
470         // element of `tts` matches the empty sequence.
471         assert!(first.maybe_empty);
472         first
473     }
474 }
475
476 // A set of `quoted::TokenTree`s, which may include `TokenTree::Match`s
477 // (for macro-by-example syntactic variables). It also carries the
478 // `maybe_empty` flag; that is true if and only if the matcher can
479 // match an empty token sequence.
480 //
481 // The First set is computed on submatchers like `$($a:expr b),* $(c)* d`,
482 // which has corresponding FIRST = {$a:expr, c, d}.
483 // Likewise, `$($a:expr b),* $(c)+ d` has FIRST = {$a:expr, c}.
484 //
485 // (Notably, we must allow for *-op to occur zero times.)
486 #[derive(Clone, Debug)]
487 struct TokenSet {
488     tokens: Vec<quoted::TokenTree>,
489     maybe_empty: bool,
490 }
491
492 impl TokenSet {
493     // Returns a set for the empty sequence.
494     fn empty() -> Self { TokenSet { tokens: Vec::new(), maybe_empty: true } }
495
496     // Returns the set `{ tok }` for the single-token (and thus
497     // non-empty) sequence [tok].
498     fn singleton(tok: quoted::TokenTree) -> Self {
499         TokenSet { tokens: vec![tok], maybe_empty: false }
500     }
501
502     // Changes self to be the set `{ tok }`.
503     // Since `tok` is always present, marks self as non-empty.
504     fn replace_with(&mut self, tok: quoted::TokenTree) {
505         self.tokens.clear();
506         self.tokens.push(tok);
507         self.maybe_empty = false;
508     }
509
510     // Changes self to be the empty set `{}`; meant for use when
511     // the particular token does not matter, but we want to
512     // record that it occurs.
513     fn replace_with_irrelevant(&mut self) {
514         self.tokens.clear();
515         self.maybe_empty = false;
516     }
517
518     // Adds `tok` to the set for `self`, marking sequence as non-empy.
519     fn add_one(&mut self, tok: quoted::TokenTree) {
520         if !self.tokens.contains(&tok) {
521             self.tokens.push(tok);
522         }
523         self.maybe_empty = false;
524     }
525
526     // Adds `tok` to the set for `self`. (Leaves `maybe_empty` flag alone.)
527     fn add_one_maybe(&mut self, tok: quoted::TokenTree) {
528         if !self.tokens.contains(&tok) {
529             self.tokens.push(tok);
530         }
531     }
532
533     // Adds all elements of `other` to this.
534     //
535     // (Since this is a set, we filter out duplicates.)
536     //
537     // If `other` is potentially empty, then preserves the previous
538     // setting of the empty flag of `self`. If `other` is guaranteed
539     // non-empty, then `self` is marked non-empty.
540     fn add_all(&mut self, other: &Self) {
541         for tok in &other.tokens {
542             if !self.tokens.contains(tok) {
543                 self.tokens.push(tok.clone());
544             }
545         }
546         if !other.maybe_empty {
547             self.maybe_empty = false;
548         }
549     }
550 }
551
552 // Checks that `matcher` is internally consistent and that it
553 // can legally by followed by a token N, for all N in `follow`.
554 // (If `follow` is empty, then it imposes no constraint on
555 // the `matcher`.)
556 //
557 // Returns the set of NT tokens that could possibly come last in
558 // `matcher`. (If `matcher` matches the empty sequence, then
559 // `maybe_empty` will be set to true.)
560 //
561 // Requires that `first_sets` is pre-computed for `matcher`;
562 // see `FirstSets::new`.
563 fn check_matcher_core(sess: &ParseSess,
564                       features: &RefCell<Features>,
565                       first_sets: &FirstSets,
566                       matcher: &[quoted::TokenTree],
567                       follow: &TokenSet) -> TokenSet {
568     use self::quoted::TokenTree;
569
570     let mut last = TokenSet::empty();
571
572     // 2. For each token and suffix  [T, SUFFIX] in M:
573     // ensure that T can be followed by SUFFIX, and if SUFFIX may be empty,
574     // then ensure T can also be followed by any element of FOLLOW.
575     'each_token: for i in 0..matcher.len() {
576         let token = &matcher[i];
577         let suffix = &matcher[i+1..];
578
579         let build_suffix_first = || {
580             let mut s = first_sets.first(suffix);
581             if s.maybe_empty { s.add_all(follow); }
582             s
583         };
584
585         // (we build `suffix_first` on demand below; you can tell
586         // which cases are supposed to fall through by looking for the
587         // initialization of this variable.)
588         let suffix_first;
589
590         // First, update `last` so that it corresponds to the set
591         // of NT tokens that might end the sequence `... token`.
592         match *token {
593             TokenTree::Token(..) | TokenTree::MetaVarDecl(..) => {
594                 let can_be_followed_by_any;
595                 if let Err(bad_frag) = has_legal_fragment_specifier(sess, features, token) {
596                     let msg = format!("invalid fragment specifier `{}`", bad_frag);
597                     sess.span_diagnostic.struct_span_err(token.span(), &msg)
598                         .help("valid fragment specifiers are `ident`, `block`, `stmt`, `expr`, \
599                               `pat`, `ty`, `path`, `meta`, `tt`, `item` and `vis`")
600                         .emit();
601                     // (This eliminates false positives and duplicates
602                     // from error messages.)
603                     can_be_followed_by_any = true;
604                 } else {
605                     can_be_followed_by_any = token_can_be_followed_by_any(token);
606                 }
607
608                 if can_be_followed_by_any {
609                     // don't need to track tokens that work with any,
610                     last.replace_with_irrelevant();
611                     // ... and don't need to check tokens that can be
612                     // followed by anything against SUFFIX.
613                     continue 'each_token;
614                 } else {
615                     last.replace_with(token.clone());
616                     suffix_first = build_suffix_first();
617                 }
618             }
619             TokenTree::Delimited(span, ref d) => {
620                 let my_suffix = TokenSet::singleton(d.close_tt(span));
621                 check_matcher_core(sess, features, first_sets, &d.tts, &my_suffix);
622                 // don't track non NT tokens
623                 last.replace_with_irrelevant();
624
625                 // also, we don't need to check delimited sequences
626                 // against SUFFIX
627                 continue 'each_token;
628             }
629             TokenTree::Sequence(sp, ref seq_rep) => {
630                 suffix_first = build_suffix_first();
631                 // The trick here: when we check the interior, we want
632                 // to include the separator (if any) as a potential
633                 // (but not guaranteed) element of FOLLOW. So in that
634                 // case, we make a temp copy of suffix and stuff
635                 // delimiter in there.
636                 //
637                 // FIXME: Should I first scan suffix_first to see if
638                 // delimiter is already in it before I go through the
639                 // work of cloning it? But then again, this way I may
640                 // get a "tighter" span?
641                 let mut new;
642                 let my_suffix = if let Some(ref u) = seq_rep.separator {
643                     new = suffix_first.clone();
644                     new.add_one_maybe(TokenTree::Token(sp, u.clone()));
645                     &new
646                 } else {
647                     &suffix_first
648                 };
649
650                 // At this point, `suffix_first` is built, and
651                 // `my_suffix` is some TokenSet that we can use
652                 // for checking the interior of `seq_rep`.
653                 let next = check_matcher_core(sess, features, first_sets, &seq_rep.tts, my_suffix);
654                 if next.maybe_empty {
655                     last.add_all(&next);
656                 } else {
657                     last = next;
658                 }
659
660                 // the recursive call to check_matcher_core already ran the 'each_last
661                 // check below, so we can just keep going forward here.
662                 continue 'each_token;
663             }
664         }
665
666         // (`suffix_first` guaranteed initialized once reaching here.)
667
668         // Now `last` holds the complete set of NT tokens that could
669         // end the sequence before SUFFIX. Check that every one works with `suffix`.
670         'each_last: for token in &last.tokens {
671             if let TokenTree::MetaVarDecl(_, ref name, ref frag_spec) = *token {
672                 for next_token in &suffix_first.tokens {
673                     match is_in_follow(next_token, &frag_spec.name.as_str()) {
674                         Err((msg, help)) => {
675                             sess.span_diagnostic.struct_span_err(next_token.span(), &msg)
676                                 .help(help).emit();
677                             // don't bother reporting every source of
678                             // conflict for a particular element of `last`.
679                             continue 'each_last;
680                         }
681                         Ok(true) => {}
682                         Ok(false) => {
683                             let may_be = if last.tokens.len() == 1 &&
684                                 suffix_first.tokens.len() == 1
685                             {
686                                 "is"
687                             } else {
688                                 "may be"
689                             };
690
691                             sess.span_diagnostic.span_err(
692                                 next_token.span(),
693                                 &format!("`${name}:{frag}` {may_be} followed by `{next}`, which \
694                                           is not allowed for `{frag}` fragments",
695                                          name=name,
696                                          frag=frag_spec,
697                                          next=quoted_tt_to_string(next_token),
698                                          may_be=may_be)
699                             );
700                         }
701                     }
702                 }
703             }
704         }
705     }
706     last
707 }
708
709 fn token_can_be_followed_by_any(tok: &quoted::TokenTree) -> bool {
710     if let quoted::TokenTree::MetaVarDecl(_, _, frag_spec) = *tok {
711         frag_can_be_followed_by_any(&frag_spec.name.as_str())
712     } else {
713         // (Non NT's can always be followed by anthing in matchers.)
714         true
715     }
716 }
717
718 /// True if a fragment of type `frag` can be followed by any sort of
719 /// token.  We use this (among other things) as a useful approximation
720 /// for when `frag` can be followed by a repetition like `$(...)*` or
721 /// `$(...)+`. In general, these can be a bit tricky to reason about,
722 /// so we adopt a conservative position that says that any fragment
723 /// specifier which consumes at most one token tree can be followed by
724 /// a fragment specifier (indeed, these fragments can be followed by
725 /// ANYTHING without fear of future compatibility hazards).
726 fn frag_can_be_followed_by_any(frag: &str) -> bool {
727     match frag {
728         "item"  | // always terminated by `}` or `;`
729         "block" | // exactly one token tree
730         "ident" | // exactly one token tree
731         "meta"  | // exactly one token tree
732         "tt" =>   // exactly one token tree
733             true,
734
735         _ =>
736             false,
737     }
738 }
739
740 /// True if `frag` can legally be followed by the token `tok`. For
741 /// fragments that can consume an unbounded number of tokens, `tok`
742 /// must be within a well-defined follow set. This is intended to
743 /// guarantee future compatibility: for example, without this rule, if
744 /// we expanded `expr` to include a new binary operator, we might
745 /// break macros that were relying on that binary operator as a
746 /// separator.
747 // when changing this do not forget to update doc/book/macros.md!
748 fn is_in_follow(tok: &quoted::TokenTree, frag: &str) -> Result<bool, (String, &'static str)> {
749     use self::quoted::TokenTree;
750
751     if let TokenTree::Token(_, token::CloseDelim(_)) = *tok {
752         // closing a token tree can never be matched by any fragment;
753         // iow, we always require that `(` and `)` match, etc.
754         Ok(true)
755     } else {
756         match frag {
757             "item" => {
758                 // since items *must* be followed by either a `;` or a `}`, we can
759                 // accept anything after them
760                 Ok(true)
761             },
762             "block" => {
763                 // anything can follow block, the braces provide an easy boundary to
764                 // maintain
765                 Ok(true)
766             },
767             "stmt" | "expr"  => match *tok {
768                 TokenTree::Token(_, ref tok) => match *tok {
769                     FatArrow | Comma | Semi => Ok(true),
770                     _ => Ok(false)
771                 },
772                 _ => Ok(false),
773             },
774             "pat" => match *tok {
775                 TokenTree::Token(_, ref tok) => match *tok {
776                     FatArrow | Comma | Eq | BinOp(token::Or) => Ok(true),
777                     Ident(i) if i.name == "if" || i.name == "in" => Ok(true),
778                     _ => Ok(false)
779                 },
780                 _ => Ok(false),
781             },
782             "path" | "ty" => match *tok {
783                 TokenTree::Token(_, ref tok) => match *tok {
784                     OpenDelim(token::DelimToken::Brace) | OpenDelim(token::DelimToken::Bracket) |
785                     Comma | FatArrow | Colon | Eq | Gt | Semi | BinOp(token::Or) => Ok(true),
786                     Ident(i) if i.name == "as" || i.name == "where" => Ok(true),
787                     _ => Ok(false)
788                 },
789                 TokenTree::MetaVarDecl(_, _, frag) if frag.name == "block" => Ok(true),
790                 _ => Ok(false),
791             },
792             "ident" => {
793                 // being a single token, idents are harmless
794                 Ok(true)
795             },
796             "meta" | "tt" => {
797                 // being either a single token or a delimited sequence, tt is
798                 // harmless
799                 Ok(true)
800             },
801             "vis" => {
802                 // Explicitly disallow `priv`, on the off chance it comes back.
803                 match *tok {
804                     TokenTree::Token(_, ref tok) => match *tok {
805                         Comma => Ok(true),
806                         Ident(i) if i.name != "priv" => Ok(true),
807                         ref tok => Ok(tok.can_begin_type())
808                     },
809                     TokenTree::MetaVarDecl(_, _, frag) if frag.name == "ident"
810                                                        || frag.name == "ty"
811                                                        || frag.name == "path" => Ok(true),
812                     _ => Ok(false)
813                 }
814             },
815             "" => Ok(true), // keywords::Invalid
816             _ => Err((format!("invalid fragment specifier `{}`", frag),
817                      "valid fragment specifiers are `ident`, `block`, \
818                       `stmt`, `expr`, `pat`, `ty`, `path`, `meta`, `tt`, \
819                       `item` and `vis`"))
820         }
821     }
822 }
823
824 fn has_legal_fragment_specifier(sess: &ParseSess,
825                                 features: &RefCell<Features>,
826                                 tok: &quoted::TokenTree) -> Result<(), String> {
827     debug!("has_legal_fragment_specifier({:?})", tok);
828     if let quoted::TokenTree::MetaVarDecl(_, _, ref frag_spec) = *tok {
829         let frag_name = frag_spec.name.as_str();
830         let frag_span = tok.span();
831         if !is_legal_fragment_specifier(sess, features, &frag_name, frag_span) {
832             return Err(frag_name.to_string());
833         }
834     }
835     Ok(())
836 }
837
838 fn is_legal_fragment_specifier(sess: &ParseSess,
839                                features: &RefCell<Features>,
840                                frag_name: &str,
841                                frag_span: Span) -> bool {
842     match frag_name {
843         "item" | "block" | "stmt" | "expr" | "pat" |
844         "path" | "ty" | "ident" | "meta" | "tt" | "" => true,
845         "vis" => {
846             if !features.borrow().macro_vis_matcher {
847                 let explain = feature_gate::EXPLAIN_VIS_MATCHER;
848                 emit_feature_err(sess,
849                                  "macro_vis_matcher",
850                                  frag_span,
851                                  GateIssue::Language,
852                                  explain);
853             }
854             true
855         },
856         _ => false,
857     }
858 }
859
860 fn quoted_tt_to_string(tt: &quoted::TokenTree) -> String {
861     match *tt {
862         quoted::TokenTree::Token(_, ref tok) => ::print::pprust::token_to_string(tok),
863         quoted::TokenTree::MetaVarDecl(_, name, kind) => format!("${}:{}", name, kind),
864         _ => panic!("unexpected quoted::TokenTree::{{Sequence or Delimited}} \
865                      in follow set checker"),
866     }
867 }