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