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