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