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