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