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.
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.
12 use syntax_pos::{Span, DUMMY_SP};
13 use ext::base::{DummyResult, ExtCtxt, MacResult, SyntaxExtension};
14 use ext::base::{NormalTT, TTMacroExpander};
15 use ext::expand::{Expansion, ExpansionKind};
16 use ext::tt::macro_parser::{Success, Error, Failure};
17 use ext::tt::macro_parser::{MatchedSeq, MatchedNonterminal};
18 use ext::tt::macro_parser::{parse, parse_failure_msg};
20 use ext::tt::transcribe::transcribe;
21 use feature_gate::{self, emit_feature_err, Features, GateIssue};
22 use parse::{Directory, ParseSess};
23 use parse::parser::Parser;
24 use parse::token::{self, NtTT};
25 use parse::token::Token::*;
27 use tokenstream::{TokenStream, TokenTree};
29 use std::cell::RefCell;
30 use std::collections::HashMap;
31 use std::collections::hash_map::Entry;
34 pub struct ParserAnyMacro<'a> {
37 /// Span of the expansion site of the macro this parser is for
39 /// The ident of the macro we're parsing
40 macro_ident: ast::Ident
43 impl<'a> ParserAnyMacro<'a> {
44 pub fn make(mut self: Box<ParserAnyMacro<'a>>, kind: ExpansionKind) -> Expansion {
45 let ParserAnyMacro { site_span, macro_ident, ref mut parser } = *self;
46 let expansion = panictry!(parser.parse_expansion(kind, true));
48 // We allow semicolons at the end of expressions -- e.g. the semicolon in
49 // `macro_rules! m { () => { panic!(); } }` isn't parsed by `.parse_expr()`,
50 // but `m!()` is allowed in expression positions (c.f. issue #34706).
51 if kind == ExpansionKind::Expr && parser.token == token::Semi {
55 // Make sure we don't have any tokens left to parse so we don't silently drop anything.
56 let path = ast::Path::from_ident(site_span, macro_ident);
57 parser.ensure_complete_parse(&path, kind.name(), site_span);
62 struct MacroRulesMacroExpander {
64 lhses: Vec<quoted::TokenTree>,
65 rhses: Vec<quoted::TokenTree>,
69 impl TTMacroExpander for MacroRulesMacroExpander {
74 -> Box<MacResult+'cx> {
76 return DummyResult::any(sp);
87 fn trace_macros_note(cx: &mut ExtCtxt, sp: Span, message: String) {
88 let sp = sp.macro_backtrace().last().map(|trace| trace.call_site).unwrap_or(sp);
89 let mut values: &mut Vec<String> = cx.expansions.entry(sp).or_insert_with(Vec::new);
93 /// Given `lhses` and `rhses`, this is the new macro we create
94 fn generic_extension<'cx>(cx: &'cx mut ExtCtxt,
98 lhses: &[quoted::TokenTree],
99 rhses: &[quoted::TokenTree])
100 -> Box<MacResult+'cx> {
101 if cx.trace_macros() {
102 trace_macros_note(cx, sp, format!("expanding `{}! {{ {} }}`", name, arg));
105 // Which arm's failure should we report? (the one furthest along)
106 let mut best_fail_spot = DUMMY_SP;
107 let mut best_fail_tok = None;
109 for (i, lhs) in lhses.iter().enumerate() { // try each arm's matchers
110 let lhs_tt = match *lhs {
111 quoted::TokenTree::Delimited(_, ref delim) => &delim.tts[..],
112 _ => cx.span_bug(sp, "malformed macro lhs")
115 match TokenTree::parse(cx, lhs_tt, arg.clone()) {
116 Success(named_matches) => {
117 let rhs = match rhses[i] {
119 quoted::TokenTree::Delimited(_, ref delimed) => delimed.tts.clone(),
120 _ => cx.span_bug(sp, "malformed macro rhs"),
122 // rhs has holes ( `$id` and `$(...)` that need filled)
123 let tts = transcribe(&cx.parse_sess.span_diagnostic, Some(named_matches), rhs);
125 if cx.trace_macros() {
126 trace_macros_note(cx, sp, format!("to `{}`", tts));
129 let directory = Directory {
130 path: cx.current_expansion.module.directory.clone(),
131 ownership: cx.current_expansion.directory_ownership,
133 let mut p = Parser::new(cx.parse_sess(), tts, Some(directory), true, false);
134 p.root_module_name = cx.current_expansion.module.mod_path.last()
135 .map(|id| id.name.as_str().to_string());
137 p.process_potential_macro_variable();
138 // Let the context choose how to interpret the result.
139 // Weird, but useful for X-macros.
140 return Box::new(ParserAnyMacro {
143 // Pass along the original expansion site and the name of the macro
144 // so we can print a useful error message if the parse of the expanded
145 // macro leaves unparsed tokens.
150 Failure(sp, tok) => if sp.lo >= best_fail_spot.lo {
152 best_fail_tok = Some(tok);
154 Error(err_sp, ref msg) => {
155 cx.span_fatal(err_sp.substitute_dummy(sp), &msg[..])
160 let best_fail_msg = parse_failure_msg(best_fail_tok.expect("ran no matchers"));
161 cx.span_fatal(best_fail_spot.substitute_dummy(sp), &best_fail_msg);
164 // Note that macro-by-example's input is also matched against a token tree:
165 // $( $lhs:tt => $rhs:tt );+
167 // Holy self-referential!
169 /// Converts a `macro_rules!` invocation into a syntax extension.
170 pub fn compile(sess: &ParseSess, features: &RefCell<Features>, def: &ast::Item) -> SyntaxExtension {
171 let lhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("lhs"));
172 let rhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("rhs"));
174 // Parse the macro_rules! invocation
175 let body = match def.node {
176 ast::ItemKind::MacroDef(ref body) => body,
180 // The pattern that macro_rules matches.
181 // The grammar for macro_rules! is:
182 // $( $lhs:tt => $rhs:tt );+
183 // ...quasiquoting this would be nice.
184 // These spans won't matter, anyways
185 let argument_gram = vec![
186 quoted::TokenTree::Sequence(DUMMY_SP, Rc::new(quoted::SequenceRepetition {
188 quoted::TokenTree::MetaVarDecl(DUMMY_SP, lhs_nm, ast::Ident::from_str("tt")),
189 quoted::TokenTree::Token(DUMMY_SP, token::FatArrow),
190 quoted::TokenTree::MetaVarDecl(DUMMY_SP, rhs_nm, ast::Ident::from_str("tt")),
192 separator: Some(if body.legacy { token::Semi } else { token::Comma }),
193 op: quoted::KleeneOp::OneOrMore,
196 // to phase into semicolon-termination instead of semicolon-separation
197 quoted::TokenTree::Sequence(DUMMY_SP, Rc::new(quoted::SequenceRepetition {
198 tts: vec![quoted::TokenTree::Token(DUMMY_SP, token::Semi)],
200 op: quoted::KleeneOp::ZeroOrMore,
205 let argument_map = match parse(sess, body.stream(), &argument_gram, None, true) {
207 Failure(sp, tok) => {
208 let s = parse_failure_msg(tok);
209 panic!(sess.span_diagnostic.span_fatal(sp.substitute_dummy(def.span), &s));
212 panic!(sess.span_diagnostic.span_fatal(sp.substitute_dummy(def.span), &s));
216 let mut valid = true;
218 // Extract the arguments:
219 let lhses = match *argument_map[&lhs_nm] {
220 MatchedSeq(ref s, _) => {
222 if let MatchedNonterminal(ref nt) = **m {
223 if let NtTT(ref tt) = **nt {
224 let tt = quoted::parse(tt.clone().into(), true, sess).pop().unwrap();
225 valid &= check_lhs_nt_follows(sess, features, &tt);
229 sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
230 }).collect::<Vec<quoted::TokenTree>>()
232 _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
235 let rhses = match *argument_map[&rhs_nm] {
236 MatchedSeq(ref s, _) => {
238 if let MatchedNonterminal(ref nt) = **m {
239 if let NtTT(ref tt) = **nt {
240 return quoted::parse(tt.clone().into(), false, sess).pop().unwrap();
243 sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
244 }).collect::<Vec<quoted::TokenTree>>()
246 _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured rhs")
250 valid &= check_rhs(sess, rhs);
253 // don't abort iteration early, so that errors for multiple lhses can be reported
255 valid &= check_lhs_no_empty_seq(sess, &[lhs.clone()])
258 let exp: Box<_> = Box::new(MacroRulesMacroExpander {
266 let allow_internal_unstable = attr::contains_name(&def.attrs, "allow_internal_unstable");
267 NormalTT(exp, Some((def.id, def.span)), allow_internal_unstable)
269 SyntaxExtension::DeclMacro(exp, Some(def.span))
273 fn check_lhs_nt_follows(sess: &ParseSess,
274 features: &RefCell<Features>,
275 lhs: "ed::TokenTree) -> bool {
276 // lhs is going to be like TokenTree::Delimited(...), where the
277 // entire lhs is those tts. Or, it can be a "bare sequence", not wrapped in parens.
278 if let quoted::TokenTree::Delimited(_, ref tts) = *lhs {
279 check_matcher(sess, features, &tts.tts)
281 let msg = "invalid macro matcher; matchers must be contained in balanced delimiters";
282 sess.span_diagnostic.span_err(lhs.span(), msg);
285 // we don't abort on errors on rejection, the driver will do that for us
286 // after parsing/expansion. we can report every error in every macro this way.
289 /// Check that the lhs contains no repetition which could match an empty token
290 /// tree, because then the matcher would hang indefinitely.
291 fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[quoted::TokenTree]) -> bool {
292 use self::quoted::TokenTree;
295 TokenTree::Token(..) | TokenTree::MetaVarDecl(..) => (),
296 TokenTree::Delimited(_, ref del) => if !check_lhs_no_empty_seq(sess, &del.tts) {
299 TokenTree::Sequence(span, ref seq) => {
300 if seq.separator.is_none() && seq.tts.iter().all(|seq_tt| {
302 TokenTree::Sequence(_, ref sub_seq) =>
303 sub_seq.op == quoted::KleeneOp::ZeroOrMore,
307 sess.span_diagnostic.span_err(span, "repetition matches empty token tree");
310 if !check_lhs_no_empty_seq(sess, &seq.tts) {
320 fn check_rhs(sess: &ParseSess, rhs: "ed::TokenTree) -> bool {
322 quoted::TokenTree::Delimited(..) => return true,
323 _ => sess.span_diagnostic.span_err(rhs.span(), "macro rhs must be delimited")
328 fn check_matcher(sess: &ParseSess,
329 features: &RefCell<Features>,
330 matcher: &[quoted::TokenTree]) -> bool {
331 let first_sets = FirstSets::new(matcher);
332 let empty_suffix = TokenSet::empty();
333 let err = sess.span_diagnostic.err_count();
334 check_matcher_core(sess, features, &first_sets, matcher, &empty_suffix);
335 err == sess.span_diagnostic.err_count()
338 // The FirstSets for a matcher is a mapping from subsequences in the
339 // matcher to the FIRST set for that subsequence.
341 // This mapping is partially precomputed via a backwards scan over the
342 // token trees of the matcher, which provides a mapping from each
343 // repetition sequence to its FIRST set.
345 // (Hypothetically sequences should be uniquely identifiable via their
346 // spans, though perhaps that is false e.g. for macro-generated macros
347 // that do not try to inject artificial span information. My plan is
348 // to try to catch such cases ahead of time and not include them in
349 // the precomputed mapping.)
351 // this maps each TokenTree::Sequence `$(tt ...) SEP OP` that is uniquely identified by its
352 // span in the original matcher to the First set for the inner sequence `tt ...`.
354 // If two sequences have the same span in a matcher, then map that
355 // span to None (invalidating the mapping here and forcing the code to
357 first: HashMap<Span, Option<TokenSet>>,
361 fn new(tts: &[quoted::TokenTree]) -> FirstSets {
362 use self::quoted::TokenTree;
364 let mut sets = FirstSets { first: HashMap::new() };
365 build_recur(&mut sets, tts);
368 // walks backward over `tts`, returning the FIRST for `tts`
369 // and updating `sets` at the same time for all sequence
370 // substructure we find within `tts`.
371 fn build_recur(sets: &mut FirstSets, tts: &[TokenTree]) -> TokenSet {
372 let mut first = TokenSet::empty();
373 for tt in tts.iter().rev() {
375 TokenTree::Token(..) | TokenTree::MetaVarDecl(..) => {
376 first.replace_with(tt.clone());
378 TokenTree::Delimited(span, ref delimited) => {
379 build_recur(sets, &delimited.tts[..]);
380 first.replace_with(delimited.open_tt(span));
382 TokenTree::Sequence(sp, ref seq_rep) => {
383 let subfirst = build_recur(sets, &seq_rep.tts[..]);
385 match sets.first.entry(sp) {
386 Entry::Vacant(vac) => {
387 vac.insert(Some(subfirst.clone()));
389 Entry::Occupied(mut occ) => {
390 // if there is already an entry, then a span must have collided.
391 // This should not happen with typical macro_rules macros,
392 // but syntax extensions need not maintain distinct spans,
393 // so distinct syntax trees can be assigned the same span.
394 // In such a case, the map cannot be trusted; so mark this
395 // entry as unusable.
400 // If the sequence contents can be empty, then the first
401 // token could be the separator token itself.
403 if let (Some(ref sep), true) = (seq_rep.separator.clone(),
404 subfirst.maybe_empty) {
405 first.add_one_maybe(TokenTree::Token(sp, sep.clone()));
408 // Reverse scan: Sequence comes before `first`.
409 if subfirst.maybe_empty || seq_rep.op == quoted::KleeneOp::ZeroOrMore {
410 // If sequence is potentially empty, then
411 // union them (preserving first emptiness).
412 first.add_all(&TokenSet { maybe_empty: true, ..subfirst });
414 // Otherwise, sequence guaranteed
415 // non-empty; replace first.
426 // walks forward over `tts` until all potential FIRST tokens are
428 fn first(&self, tts: &[quoted::TokenTree]) -> TokenSet {
429 use self::quoted::TokenTree;
431 let mut first = TokenSet::empty();
432 for tt in tts.iter() {
433 assert!(first.maybe_empty);
435 TokenTree::Token(..) | TokenTree::MetaVarDecl(..) => {
436 first.add_one(tt.clone());
439 TokenTree::Delimited(span, ref delimited) => {
440 first.add_one(delimited.open_tt(span));
443 TokenTree::Sequence(sp, ref seq_rep) => {
444 match self.first.get(&sp) {
445 Some(&Some(ref subfirst)) => {
447 // If the sequence contents can be empty, then the first
448 // token could be the separator token itself.
450 if let (Some(ref sep), true) = (seq_rep.separator.clone(),
451 subfirst.maybe_empty) {
452 first.add_one_maybe(TokenTree::Token(sp, sep.clone()));
455 assert!(first.maybe_empty);
456 first.add_all(subfirst);
457 if subfirst.maybe_empty ||
458 seq_rep.op == quoted::KleeneOp::ZeroOrMore {
459 // continue scanning for more first
460 // tokens, but also make sure we
461 // restore empty-tracking state
462 first.maybe_empty = true;
470 panic!("assume all sequences have (unique) spans for now");
474 panic!("We missed a sequence during FirstSets construction");
481 // we only exit the loop if `tts` was empty or if every
482 // element of `tts` matches the empty sequence.
483 assert!(first.maybe_empty);
488 // A set of `quoted::TokenTree`s, which may include `TokenTree::Match`s
489 // (for macro-by-example syntactic variables). It also carries the
490 // `maybe_empty` flag; that is true if and only if the matcher can
491 // match an empty token sequence.
493 // The First set is computed on submatchers like `$($a:expr b),* $(c)* d`,
494 // which has corresponding FIRST = {$a:expr, c, d}.
495 // Likewise, `$($a:expr b),* $(c)+ d` has FIRST = {$a:expr, c}.
497 // (Notably, we must allow for *-op to occur zero times.)
498 #[derive(Clone, Debug)]
500 tokens: Vec<quoted::TokenTree>,
505 // Returns a set for the empty sequence.
506 fn empty() -> Self { TokenSet { tokens: Vec::new(), maybe_empty: true } }
508 // Returns the set `{ tok }` for the single-token (and thus
509 // non-empty) sequence [tok].
510 fn singleton(tok: quoted::TokenTree) -> Self {
511 TokenSet { tokens: vec![tok], maybe_empty: false }
514 // Changes self to be the set `{ tok }`.
515 // Since `tok` is always present, marks self as non-empty.
516 fn replace_with(&mut self, tok: quoted::TokenTree) {
518 self.tokens.push(tok);
519 self.maybe_empty = false;
522 // Changes self to be the empty set `{}`; meant for use when
523 // the particular token does not matter, but we want to
524 // record that it occurs.
525 fn replace_with_irrelevant(&mut self) {
527 self.maybe_empty = false;
530 // Adds `tok` to the set for `self`, marking sequence as non-empy.
531 fn add_one(&mut self, tok: quoted::TokenTree) {
532 if !self.tokens.contains(&tok) {
533 self.tokens.push(tok);
535 self.maybe_empty = false;
538 // Adds `tok` to the set for `self`. (Leaves `maybe_empty` flag alone.)
539 fn add_one_maybe(&mut self, tok: quoted::TokenTree) {
540 if !self.tokens.contains(&tok) {
541 self.tokens.push(tok);
545 // Adds all elements of `other` to this.
547 // (Since this is a set, we filter out duplicates.)
549 // If `other` is potentially empty, then preserves the previous
550 // setting of the empty flag of `self`. If `other` is guaranteed
551 // non-empty, then `self` is marked non-empty.
552 fn add_all(&mut self, other: &Self) {
553 for tok in &other.tokens {
554 if !self.tokens.contains(tok) {
555 self.tokens.push(tok.clone());
558 if !other.maybe_empty {
559 self.maybe_empty = false;
564 // Checks that `matcher` is internally consistent and that it
565 // can legally by followed by a token N, for all N in `follow`.
566 // (If `follow` is empty, then it imposes no constraint on
569 // Returns the set of NT tokens that could possibly come last in
570 // `matcher`. (If `matcher` matches the empty sequence, then
571 // `maybe_empty` will be set to true.)
573 // Requires that `first_sets` is pre-computed for `matcher`;
574 // see `FirstSets::new`.
575 fn check_matcher_core(sess: &ParseSess,
576 features: &RefCell<Features>,
577 first_sets: &FirstSets,
578 matcher: &[quoted::TokenTree],
579 follow: &TokenSet) -> TokenSet {
580 use self::quoted::TokenTree;
582 let mut last = TokenSet::empty();
584 // 2. For each token and suffix [T, SUFFIX] in M:
585 // ensure that T can be followed by SUFFIX, and if SUFFIX may be empty,
586 // then ensure T can also be followed by any element of FOLLOW.
587 'each_token: for i in 0..matcher.len() {
588 let token = &matcher[i];
589 let suffix = &matcher[i+1..];
591 let build_suffix_first = || {
592 let mut s = first_sets.first(suffix);
593 if s.maybe_empty { s.add_all(follow); }
597 // (we build `suffix_first` on demand below; you can tell
598 // which cases are supposed to fall through by looking for the
599 // initialization of this variable.)
602 // First, update `last` so that it corresponds to the set
603 // of NT tokens that might end the sequence `... token`.
605 TokenTree::Token(..) | TokenTree::MetaVarDecl(..) => {
606 let can_be_followed_by_any;
607 if let Err(bad_frag) = has_legal_fragment_specifier(sess, features, token) {
608 let msg = format!("invalid fragment specifier `{}`", bad_frag);
609 sess.span_diagnostic.struct_span_err(token.span(), &msg)
610 .help("valid fragment specifiers are `ident`, `block`, `stmt`, `expr`, \
611 `pat`, `ty`, `path`, `meta`, `tt`, `item` and `vis`")
613 // (This eliminates false positives and duplicates
614 // from error messages.)
615 can_be_followed_by_any = true;
617 can_be_followed_by_any = token_can_be_followed_by_any(token);
620 if can_be_followed_by_any {
621 // don't need to track tokens that work with any,
622 last.replace_with_irrelevant();
623 // ... and don't need to check tokens that can be
624 // followed by anything against SUFFIX.
625 continue 'each_token;
627 last.replace_with(token.clone());
628 suffix_first = build_suffix_first();
631 TokenTree::Delimited(span, ref d) => {
632 let my_suffix = TokenSet::singleton(d.close_tt(span));
633 check_matcher_core(sess, features, first_sets, &d.tts, &my_suffix);
634 // don't track non NT tokens
635 last.replace_with_irrelevant();
637 // also, we don't need to check delimited sequences
639 continue 'each_token;
641 TokenTree::Sequence(sp, ref seq_rep) => {
642 suffix_first = build_suffix_first();
643 // The trick here: when we check the interior, we want
644 // to include the separator (if any) as a potential
645 // (but not guaranteed) element of FOLLOW. So in that
646 // case, we make a temp copy of suffix and stuff
647 // delimiter in there.
649 // FIXME: Should I first scan suffix_first to see if
650 // delimiter is already in it before I go through the
651 // work of cloning it? But then again, this way I may
652 // get a "tighter" span?
654 let my_suffix = if let Some(ref u) = seq_rep.separator {
655 new = suffix_first.clone();
656 new.add_one_maybe(TokenTree::Token(sp, u.clone()));
662 // At this point, `suffix_first` is built, and
663 // `my_suffix` is some TokenSet that we can use
664 // for checking the interior of `seq_rep`.
665 let next = check_matcher_core(sess, features, first_sets, &seq_rep.tts, my_suffix);
666 if next.maybe_empty {
672 // the recursive call to check_matcher_core already ran the 'each_last
673 // check below, so we can just keep going forward here.
674 continue 'each_token;
678 // (`suffix_first` guaranteed initialized once reaching here.)
680 // Now `last` holds the complete set of NT tokens that could
681 // end the sequence before SUFFIX. Check that every one works with `suffix`.
682 'each_last: for token in &last.tokens {
683 if let TokenTree::MetaVarDecl(_, ref name, ref frag_spec) = *token {
684 for next_token in &suffix_first.tokens {
685 match is_in_follow(next_token, &frag_spec.name.as_str()) {
686 Err((msg, help)) => {
687 sess.span_diagnostic.struct_span_err(next_token.span(), &msg)
689 // don't bother reporting every source of
690 // conflict for a particular element of `last`.
695 let may_be = if last.tokens.len() == 1 &&
696 suffix_first.tokens.len() == 1
703 sess.span_diagnostic.span_err(
705 &format!("`${name}:{frag}` {may_be} followed by `{next}`, which \
706 is not allowed for `{frag}` fragments",
709 next=quoted_tt_to_string(next_token),
721 fn token_can_be_followed_by_any(tok: "ed::TokenTree) -> bool {
722 if let quoted::TokenTree::MetaVarDecl(_, _, frag_spec) = *tok {
723 frag_can_be_followed_by_any(&frag_spec.name.as_str())
725 // (Non NT's can always be followed by anthing in matchers.)
730 /// True if a fragment of type `frag` can be followed by any sort of
731 /// token. We use this (among other things) as a useful approximation
732 /// for when `frag` can be followed by a repetition like `$(...)*` or
733 /// `$(...)+`. In general, these can be a bit tricky to reason about,
734 /// so we adopt a conservative position that says that any fragment
735 /// specifier which consumes at most one token tree can be followed by
736 /// a fragment specifier (indeed, these fragments can be followed by
737 /// ANYTHING without fear of future compatibility hazards).
738 fn frag_can_be_followed_by_any(frag: &str) -> bool {
740 "item" | // always terminated by `}` or `;`
741 "block" | // exactly one token tree
742 "ident" | // exactly one token tree
743 "meta" | // exactly one token tree
744 "tt" => // exactly one token tree
752 /// True if `frag` can legally be followed by the token `tok`. For
753 /// fragments that can consume an unbounded number of tokens, `tok`
754 /// must be within a well-defined follow set. This is intended to
755 /// guarantee future compatibility: for example, without this rule, if
756 /// we expanded `expr` to include a new binary operator, we might
757 /// break macros that were relying on that binary operator as a
759 // when changing this do not forget to update doc/book/macros.md!
760 fn is_in_follow(tok: "ed::TokenTree, frag: &str) -> Result<bool, (String, &'static str)> {
761 use self::quoted::TokenTree;
763 if let TokenTree::Token(_, token::CloseDelim(_)) = *tok {
764 // closing a token tree can never be matched by any fragment;
765 // iow, we always require that `(` and `)` match, etc.
770 // since items *must* be followed by either a `;` or a `}`, we can
771 // accept anything after them
775 // anything can follow block, the braces provide an easy boundary to
779 "stmt" | "expr" => match *tok {
780 TokenTree::Token(_, ref tok) => match *tok {
781 FatArrow | Comma | Semi => Ok(true),
786 "pat" => match *tok {
787 TokenTree::Token(_, ref tok) => match *tok {
788 FatArrow | Comma | Eq | BinOp(token::Or) => Ok(true),
789 Ident(i) if i.name == "if" || i.name == "in" => Ok(true),
794 "path" | "ty" => match *tok {
795 TokenTree::Token(_, ref tok) => match *tok {
796 OpenDelim(token::DelimToken::Brace) | OpenDelim(token::DelimToken::Bracket) |
797 Comma | FatArrow | Colon | Eq | Gt | Semi | BinOp(token::Or) => Ok(true),
798 Ident(i) if i.name == "as" || i.name == "where" => Ok(true),
801 TokenTree::MetaVarDecl(_, _, frag) if frag.name == "block" => Ok(true),
805 // being a single token, idents are harmless
809 // being either a single token or a delimited sequence, tt is
814 // Explicitly disallow `priv`, on the off chance it comes back.
816 TokenTree::Token(_, ref tok) => match *tok {
818 Ident(i) if i.name != "priv" => Ok(true),
819 ref tok => Ok(tok.can_begin_type())
821 TokenTree::MetaVarDecl(_, _, frag) if frag.name == "ident"
823 || frag.name == "path" => Ok(true),
827 "" => Ok(true), // keywords::Invalid
828 _ => Err((format!("invalid fragment specifier `{}`", frag),
829 "valid fragment specifiers are `ident`, `block`, \
830 `stmt`, `expr`, `pat`, `ty`, `path`, `meta`, `tt`, \
836 fn has_legal_fragment_specifier(sess: &ParseSess,
837 features: &RefCell<Features>,
838 tok: "ed::TokenTree) -> Result<(), String> {
839 debug!("has_legal_fragment_specifier({:?})", tok);
840 if let quoted::TokenTree::MetaVarDecl(_, _, ref frag_spec) = *tok {
841 let frag_name = frag_spec.name.as_str();
842 let frag_span = tok.span();
843 if !is_legal_fragment_specifier(sess, features, &frag_name, frag_span) {
844 return Err(frag_name.to_string());
850 fn is_legal_fragment_specifier(sess: &ParseSess,
851 features: &RefCell<Features>,
853 frag_span: Span) -> bool {
855 "item" | "block" | "stmt" | "expr" | "pat" |
856 "path" | "ty" | "ident" | "meta" | "tt" | "" => true,
858 if !features.borrow().macro_vis_matcher {
859 let explain = feature_gate::EXPLAIN_VIS_MATCHER;
860 emit_feature_err(sess,
872 fn quoted_tt_to_string(tt: "ed::TokenTree) -> String {
874 quoted::TokenTree::Token(_, ref tok) => ::print::pprust::token_to_string(tok),
875 quoted::TokenTree::MetaVarDecl(_, name, kind) => format!("${}:{}", name, kind),
876 _ => panic!("unexpected quoted::TokenTree::{{Sequence or Delimited}} \
877 in follow set checker"),