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