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