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