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