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 /// Given `lhses` and `rhses`, this is the new macro we create
88 fn generic_extension<'cx>(cx: &'cx mut ExtCtxt,
92 lhses: &[quoted::TokenTree],
93 rhses: &[quoted::TokenTree])
94 -> Box<MacResult+'cx> {
95 if cx.trace_macros() {
96 let sp = sp.macro_backtrace().last().map(|trace| trace.call_site).unwrap_or(sp);
97 let mut values: &mut Vec<String> = cx.expansions.entry(sp).or_insert_with(Vec::new);
98 values.push(format!("expands to `{}! {{ {} }}`", name, arg));
101 // Which arm's failure should we report? (the one furthest along)
102 let mut best_fail_spot = DUMMY_SP;
103 let mut best_fail_tok = None;
105 for (i, lhs) in lhses.iter().enumerate() { // try each arm's matchers
106 let lhs_tt = match *lhs {
107 quoted::TokenTree::Delimited(_, ref delim) => &delim.tts[..],
108 _ => cx.span_bug(sp, "malformed macro lhs")
111 match TokenTree::parse(cx, lhs_tt, arg.clone()) {
112 Success(named_matches) => {
113 let rhs = match rhses[i] {
115 quoted::TokenTree::Delimited(_, ref delimed) => delimed.tts.clone(),
116 _ => cx.span_bug(sp, "malformed macro rhs"),
118 // rhs has holes ( `$id` and `$(...)` that need filled)
119 let tts = transcribe(&cx.parse_sess.span_diagnostic, Some(named_matches), rhs);
120 let directory = Directory {
121 path: cx.current_expansion.module.directory.clone(),
122 ownership: cx.current_expansion.directory_ownership,
124 let mut p = Parser::new(cx.parse_sess(), tts, Some(directory), true, false);
125 p.root_module_name = cx.current_expansion.module.mod_path.last()
126 .map(|id| id.name.as_str().to_string());
128 p.process_potential_macro_variable();
129 // Let the context choose how to interpret the result.
130 // Weird, but useful for X-macros.
131 return Box::new(ParserAnyMacro {
134 // Pass along the original expansion site and the name of the macro
135 // so we can print a useful error message if the parse of the expanded
136 // macro leaves unparsed tokens.
141 Failure(sp, tok) => if sp.lo >= best_fail_spot.lo {
143 best_fail_tok = Some(tok);
145 Error(err_sp, ref msg) => {
146 cx.span_fatal(err_sp.substitute_dummy(sp), &msg[..])
151 let best_fail_msg = parse_failure_msg(best_fail_tok.expect("ran no matchers"));
152 cx.span_fatal(best_fail_spot.substitute_dummy(sp), &best_fail_msg);
155 // Note that macro-by-example's input is also matched against a token tree:
156 // $( $lhs:tt => $rhs:tt );+
158 // Holy self-referential!
160 /// Converts a `macro_rules!` invocation into a syntax extension.
161 pub fn compile(sess: &ParseSess, features: &RefCell<Features>, def: &ast::Item) -> SyntaxExtension {
162 let lhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("lhs"));
163 let rhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("rhs"));
165 // The pattern that macro_rules matches.
166 // The grammar for macro_rules! is:
167 // $( $lhs:tt => $rhs:tt );+
168 // ...quasiquoting this would be nice.
169 // These spans won't matter, anyways
170 let argument_gram = vec![
171 quoted::TokenTree::Sequence(DUMMY_SP, Rc::new(quoted::SequenceRepetition {
173 quoted::TokenTree::MetaVarDecl(DUMMY_SP, lhs_nm, ast::Ident::from_str("tt")),
174 quoted::TokenTree::Token(DUMMY_SP, token::FatArrow),
175 quoted::TokenTree::MetaVarDecl(DUMMY_SP, rhs_nm, ast::Ident::from_str("tt")),
177 separator: Some(token::Semi),
178 op: quoted::KleeneOp::OneOrMore,
181 // to phase into semicolon-termination instead of semicolon-separation
182 quoted::TokenTree::Sequence(DUMMY_SP, Rc::new(quoted::SequenceRepetition {
183 tts: vec![quoted::TokenTree::Token(DUMMY_SP, token::Semi)],
185 op: quoted::KleeneOp::ZeroOrMore,
190 // Parse the macro_rules! invocation
191 let body = match def.node {
192 ast::ItemKind::MacroDef(ref body) => body.stream(),
195 let argument_map = match parse(sess, body, &argument_gram, None, true) {
197 Failure(sp, tok) => {
198 let s = parse_failure_msg(tok);
199 panic!(sess.span_diagnostic.span_fatal(sp.substitute_dummy(def.span), &s));
202 panic!(sess.span_diagnostic.span_fatal(sp.substitute_dummy(def.span), &s));
206 let mut valid = true;
208 // Extract the arguments:
209 let lhses = match *argument_map[&lhs_nm] {
210 MatchedSeq(ref s, _) => {
212 if let MatchedNonterminal(ref nt) = **m {
213 if let NtTT(ref tt) = **nt {
214 let tt = quoted::parse(tt.clone().into(), true, sess).pop().unwrap();
215 valid &= check_lhs_nt_follows(sess, features, &tt);
219 sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
220 }).collect::<Vec<quoted::TokenTree>>()
222 _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
225 let rhses = match *argument_map[&rhs_nm] {
226 MatchedSeq(ref s, _) => {
228 if let MatchedNonterminal(ref nt) = **m {
229 if let NtTT(ref tt) = **nt {
230 return quoted::parse(tt.clone().into(), false, sess).pop().unwrap();
233 sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
234 }).collect::<Vec<quoted::TokenTree>>()
236 _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured rhs")
240 valid &= check_rhs(sess, rhs);
243 // don't abort iteration early, so that errors for multiple lhses can be reported
245 valid &= check_lhs_no_empty_seq(sess, &[lhs.clone()])
248 let exp: Box<_> = Box::new(MacroRulesMacroExpander {
256 Some((def.id, def.span)),
257 attr::contains_name(&def.attrs, "allow_internal_unstable"))
260 fn check_lhs_nt_follows(sess: &ParseSess,
261 features: &RefCell<Features>,
262 lhs: "ed::TokenTree) -> bool {
263 // lhs is going to be like TokenTree::Delimited(...), where the
264 // entire lhs is those tts. Or, it can be a "bare sequence", not wrapped in parens.
265 if let quoted::TokenTree::Delimited(_, ref tts) = *lhs {
266 check_matcher(sess, features, &tts.tts)
268 let msg = "invalid macro matcher; matchers must be contained in balanced delimiters";
269 sess.span_diagnostic.span_err(lhs.span(), msg);
272 // we don't abort on errors on rejection, the driver will do that for us
273 // after parsing/expansion. we can report every error in every macro this way.
276 /// Check that the lhs contains no repetition which could match an empty token
277 /// tree, because then the matcher would hang indefinitely.
278 fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[quoted::TokenTree]) -> bool {
279 use self::quoted::TokenTree;
282 TokenTree::Token(..) | TokenTree::MetaVarDecl(..) => (),
283 TokenTree::Delimited(_, ref del) => if !check_lhs_no_empty_seq(sess, &del.tts) {
286 TokenTree::Sequence(span, ref seq) => {
287 if seq.separator.is_none() && seq.tts.iter().all(|seq_tt| {
289 TokenTree::Sequence(_, ref sub_seq) =>
290 sub_seq.op == quoted::KleeneOp::ZeroOrMore,
294 sess.span_diagnostic.span_err(span, "repetition matches empty token tree");
297 if !check_lhs_no_empty_seq(sess, &seq.tts) {
307 fn check_rhs(sess: &ParseSess, rhs: "ed::TokenTree) -> bool {
309 quoted::TokenTree::Delimited(..) => return true,
310 _ => sess.span_diagnostic.span_err(rhs.span(), "macro rhs must be delimited")
315 fn check_matcher(sess: &ParseSess,
316 features: &RefCell<Features>,
317 matcher: &[quoted::TokenTree]) -> bool {
318 let first_sets = FirstSets::new(matcher);
319 let empty_suffix = TokenSet::empty();
320 let err = sess.span_diagnostic.err_count();
321 check_matcher_core(sess, features, &first_sets, matcher, &empty_suffix);
322 err == sess.span_diagnostic.err_count()
325 // The FirstSets for a matcher is a mapping from subsequences in the
326 // matcher to the FIRST set for that subsequence.
328 // This mapping is partially precomputed via a backwards scan over the
329 // token trees of the matcher, which provides a mapping from each
330 // repetition sequence to its FIRST set.
332 // (Hypothetically sequences should be uniquely identifiable via their
333 // spans, though perhaps that is false e.g. for macro-generated macros
334 // that do not try to inject artificial span information. My plan is
335 // to try to catch such cases ahead of time and not include them in
336 // the precomputed mapping.)
338 // this maps each TokenTree::Sequence `$(tt ...) SEP OP` that is uniquely identified by its
339 // span in the original matcher to the First set for the inner sequence `tt ...`.
341 // If two sequences have the same span in a matcher, then map that
342 // span to None (invalidating the mapping here and forcing the code to
344 first: HashMap<Span, Option<TokenSet>>,
348 fn new(tts: &[quoted::TokenTree]) -> FirstSets {
349 use self::quoted::TokenTree;
351 let mut sets = FirstSets { first: HashMap::new() };
352 build_recur(&mut sets, tts);
355 // walks backward over `tts`, returning the FIRST for `tts`
356 // and updating `sets` at the same time for all sequence
357 // substructure we find within `tts`.
358 fn build_recur(sets: &mut FirstSets, tts: &[TokenTree]) -> TokenSet {
359 let mut first = TokenSet::empty();
360 for tt in tts.iter().rev() {
362 TokenTree::Token(..) | TokenTree::MetaVarDecl(..) => {
363 first.replace_with(tt.clone());
365 TokenTree::Delimited(span, ref delimited) => {
366 build_recur(sets, &delimited.tts[..]);
367 first.replace_with(delimited.open_tt(span));
369 TokenTree::Sequence(sp, ref seq_rep) => {
370 let subfirst = build_recur(sets, &seq_rep.tts[..]);
372 match sets.first.entry(sp) {
373 Entry::Vacant(vac) => {
374 vac.insert(Some(subfirst.clone()));
376 Entry::Occupied(mut occ) => {
377 // if there is already an entry, then a span must have collided.
378 // This should not happen with typical macro_rules macros,
379 // but syntax extensions need not maintain distinct spans,
380 // so distinct syntax trees can be assigned the same span.
381 // In such a case, the map cannot be trusted; so mark this
382 // entry as unusable.
387 // If the sequence contents can be empty, then the first
388 // token could be the separator token itself.
390 if let (Some(ref sep), true) = (seq_rep.separator.clone(),
391 subfirst.maybe_empty) {
392 first.add_one_maybe(TokenTree::Token(sp, sep.clone()));
395 // Reverse scan: Sequence comes before `first`.
396 if subfirst.maybe_empty || seq_rep.op == quoted::KleeneOp::ZeroOrMore {
397 // If sequence is potentially empty, then
398 // union them (preserving first emptiness).
399 first.add_all(&TokenSet { maybe_empty: true, ..subfirst });
401 // Otherwise, sequence guaranteed
402 // non-empty; replace first.
413 // walks forward over `tts` until all potential FIRST tokens are
415 fn first(&self, tts: &[quoted::TokenTree]) -> TokenSet {
416 use self::quoted::TokenTree;
418 let mut first = TokenSet::empty();
419 for tt in tts.iter() {
420 assert!(first.maybe_empty);
422 TokenTree::Token(..) | TokenTree::MetaVarDecl(..) => {
423 first.add_one(tt.clone());
426 TokenTree::Delimited(span, ref delimited) => {
427 first.add_one(delimited.open_tt(span));
430 TokenTree::Sequence(sp, ref seq_rep) => {
431 match self.first.get(&sp) {
432 Some(&Some(ref subfirst)) => {
434 // If the sequence contents can be empty, then the first
435 // token could be the separator token itself.
437 if let (Some(ref sep), true) = (seq_rep.separator.clone(),
438 subfirst.maybe_empty) {
439 first.add_one_maybe(TokenTree::Token(sp, sep.clone()));
442 assert!(first.maybe_empty);
443 first.add_all(subfirst);
444 if subfirst.maybe_empty ||
445 seq_rep.op == quoted::KleeneOp::ZeroOrMore {
446 // continue scanning for more first
447 // tokens, but also make sure we
448 // restore empty-tracking state
449 first.maybe_empty = true;
457 panic!("assume all sequences have (unique) spans for now");
461 panic!("We missed a sequence during FirstSets construction");
468 // we only exit the loop if `tts` was empty or if every
469 // element of `tts` matches the empty sequence.
470 assert!(first.maybe_empty);
475 // A set of `quoted::TokenTree`s, which may include `TokenTree::Match`s
476 // (for macro-by-example syntactic variables). It also carries the
477 // `maybe_empty` flag; that is true if and only if the matcher can
478 // match an empty token sequence.
480 // The First set is computed on submatchers like `$($a:expr b),* $(c)* d`,
481 // which has corresponding FIRST = {$a:expr, c, d}.
482 // Likewise, `$($a:expr b),* $(c)+ d` has FIRST = {$a:expr, c}.
484 // (Notably, we must allow for *-op to occur zero times.)
485 #[derive(Clone, Debug)]
487 tokens: Vec<quoted::TokenTree>,
492 // Returns a set for the empty sequence.
493 fn empty() -> Self { TokenSet { tokens: Vec::new(), maybe_empty: true } }
495 // Returns the set `{ tok }` for the single-token (and thus
496 // non-empty) sequence [tok].
497 fn singleton(tok: quoted::TokenTree) -> Self {
498 TokenSet { tokens: vec![tok], maybe_empty: false }
501 // Changes self to be the set `{ tok }`.
502 // Since `tok` is always present, marks self as non-empty.
503 fn replace_with(&mut self, tok: quoted::TokenTree) {
505 self.tokens.push(tok);
506 self.maybe_empty = false;
509 // Changes self to be the empty set `{}`; meant for use when
510 // the particular token does not matter, but we want to
511 // record that it occurs.
512 fn replace_with_irrelevant(&mut self) {
514 self.maybe_empty = false;
517 // Adds `tok` to the set for `self`, marking sequence as non-empy.
518 fn add_one(&mut self, tok: quoted::TokenTree) {
519 if !self.tokens.contains(&tok) {
520 self.tokens.push(tok);
522 self.maybe_empty = false;
525 // Adds `tok` to the set for `self`. (Leaves `maybe_empty` flag alone.)
526 fn add_one_maybe(&mut self, tok: quoted::TokenTree) {
527 if !self.tokens.contains(&tok) {
528 self.tokens.push(tok);
532 // Adds all elements of `other` to this.
534 // (Since this is a set, we filter out duplicates.)
536 // If `other` is potentially empty, then preserves the previous
537 // setting of the empty flag of `self`. If `other` is guaranteed
538 // non-empty, then `self` is marked non-empty.
539 fn add_all(&mut self, other: &Self) {
540 for tok in &other.tokens {
541 if !self.tokens.contains(tok) {
542 self.tokens.push(tok.clone());
545 if !other.maybe_empty {
546 self.maybe_empty = false;
551 // Checks that `matcher` is internally consistent and that it
552 // can legally by followed by a token N, for all N in `follow`.
553 // (If `follow` is empty, then it imposes no constraint on
556 // Returns the set of NT tokens that could possibly come last in
557 // `matcher`. (If `matcher` matches the empty sequence, then
558 // `maybe_empty` will be set to true.)
560 // Requires that `first_sets` is pre-computed for `matcher`;
561 // see `FirstSets::new`.
562 fn check_matcher_core(sess: &ParseSess,
563 features: &RefCell<Features>,
564 first_sets: &FirstSets,
565 matcher: &[quoted::TokenTree],
566 follow: &TokenSet) -> TokenSet {
567 use self::quoted::TokenTree;
569 let mut last = TokenSet::empty();
571 // 2. For each token and suffix [T, SUFFIX] in M:
572 // ensure that T can be followed by SUFFIX, and if SUFFIX may be empty,
573 // then ensure T can also be followed by any element of FOLLOW.
574 'each_token: for i in 0..matcher.len() {
575 let token = &matcher[i];
576 let suffix = &matcher[i+1..];
578 let build_suffix_first = || {
579 let mut s = first_sets.first(suffix);
580 if s.maybe_empty { s.add_all(follow); }
584 // (we build `suffix_first` on demand below; you can tell
585 // which cases are supposed to fall through by looking for the
586 // initialization of this variable.)
589 // First, update `last` so that it corresponds to the set
590 // of NT tokens that might end the sequence `... token`.
592 TokenTree::Token(..) | TokenTree::MetaVarDecl(..) => {
593 let can_be_followed_by_any;
594 if let Err(bad_frag) = has_legal_fragment_specifier(sess, features, token) {
595 let msg = format!("invalid fragment specifier `{}`", bad_frag);
596 sess.span_diagnostic.struct_span_err(token.span(), &msg)
597 .help("valid fragment specifiers are `ident`, `block`, `stmt`, `expr`, \
598 `pat`, `ty`, `path`, `meta`, `tt`, `item` and `vis`")
600 // (This eliminates false positives and duplicates
601 // from error messages.)
602 can_be_followed_by_any = true;
604 can_be_followed_by_any = token_can_be_followed_by_any(token);
607 if can_be_followed_by_any {
608 // don't need to track tokens that work with any,
609 last.replace_with_irrelevant();
610 // ... and don't need to check tokens that can be
611 // followed by anything against SUFFIX.
612 continue 'each_token;
614 last.replace_with(token.clone());
615 suffix_first = build_suffix_first();
618 TokenTree::Delimited(span, ref d) => {
619 let my_suffix = TokenSet::singleton(d.close_tt(span));
620 check_matcher_core(sess, features, first_sets, &d.tts, &my_suffix);
621 // don't track non NT tokens
622 last.replace_with_irrelevant();
624 // also, we don't need to check delimited sequences
626 continue 'each_token;
628 TokenTree::Sequence(sp, ref seq_rep) => {
629 suffix_first = build_suffix_first();
630 // The trick here: when we check the interior, we want
631 // to include the separator (if any) as a potential
632 // (but not guaranteed) element of FOLLOW. So in that
633 // case, we make a temp copy of suffix and stuff
634 // delimiter in there.
636 // FIXME: Should I first scan suffix_first to see if
637 // delimiter is already in it before I go through the
638 // work of cloning it? But then again, this way I may
639 // get a "tighter" span?
641 let my_suffix = if let Some(ref u) = seq_rep.separator {
642 new = suffix_first.clone();
643 new.add_one_maybe(TokenTree::Token(sp, u.clone()));
649 // At this point, `suffix_first` is built, and
650 // `my_suffix` is some TokenSet that we can use
651 // for checking the interior of `seq_rep`.
652 let next = check_matcher_core(sess, features, first_sets, &seq_rep.tts, my_suffix);
653 if next.maybe_empty {
659 // the recursive call to check_matcher_core already ran the 'each_last
660 // check below, so we can just keep going forward here.
661 continue 'each_token;
665 // (`suffix_first` guaranteed initialized once reaching here.)
667 // Now `last` holds the complete set of NT tokens that could
668 // end the sequence before SUFFIX. Check that every one works with `suffix`.
669 'each_last: for token in &last.tokens {
670 if let TokenTree::MetaVarDecl(_, ref name, ref frag_spec) = *token {
671 for next_token in &suffix_first.tokens {
672 match is_in_follow(next_token, &frag_spec.name.as_str()) {
673 Err((msg, help)) => {
674 sess.span_diagnostic.struct_span_err(next_token.span(), &msg)
676 // don't bother reporting every source of
677 // conflict for a particular element of `last`.
682 let may_be = if last.tokens.len() == 1 &&
683 suffix_first.tokens.len() == 1
690 sess.span_diagnostic.span_err(
692 &format!("`${name}:{frag}` {may_be} followed by `{next}`, which \
693 is not allowed for `{frag}` fragments",
696 next=quoted_tt_to_string(next_token),
708 fn token_can_be_followed_by_any(tok: "ed::TokenTree) -> bool {
709 if let quoted::TokenTree::MetaVarDecl(_, _, frag_spec) = *tok {
710 frag_can_be_followed_by_any(&frag_spec.name.as_str())
712 // (Non NT's can always be followed by anthing in matchers.)
717 /// True if a fragment of type `frag` can be followed by any sort of
718 /// token. We use this (among other things) as a useful approximation
719 /// for when `frag` can be followed by a repetition like `$(...)*` or
720 /// `$(...)+`. In general, these can be a bit tricky to reason about,
721 /// so we adopt a conservative position that says that any fragment
722 /// specifier which consumes at most one token tree can be followed by
723 /// a fragment specifier (indeed, these fragments can be followed by
724 /// ANYTHING without fear of future compatibility hazards).
725 fn frag_can_be_followed_by_any(frag: &str) -> bool {
727 "item" | // always terminated by `}` or `;`
728 "block" | // exactly one token tree
729 "ident" | // exactly one token tree
730 "meta" | // exactly one token tree
731 "tt" => // exactly one token tree
739 /// True if `frag` can legally be followed by the token `tok`. For
740 /// fragments that can consume an unbounded number of tokens, `tok`
741 /// must be within a well-defined follow set. This is intended to
742 /// guarantee future compatibility: for example, without this rule, if
743 /// we expanded `expr` to include a new binary operator, we might
744 /// break macros that were relying on that binary operator as a
746 // when changing this do not forget to update doc/book/macros.md!
747 fn is_in_follow(tok: "ed::TokenTree, frag: &str) -> Result<bool, (String, &'static str)> {
748 use self::quoted::TokenTree;
750 if let TokenTree::Token(_, token::CloseDelim(_)) = *tok {
751 // closing a token tree can never be matched by any fragment;
752 // iow, we always require that `(` and `)` match, etc.
757 // since items *must* be followed by either a `;` or a `}`, we can
758 // accept anything after them
762 // anything can follow block, the braces provide an easy boundary to
766 "stmt" | "expr" => match *tok {
767 TokenTree::Token(_, ref tok) => match *tok {
768 FatArrow | Comma | Semi => Ok(true),
773 "pat" => match *tok {
774 TokenTree::Token(_, ref tok) => match *tok {
775 FatArrow | Comma | Eq | BinOp(token::Or) => Ok(true),
776 Ident(i) if i.name == "if" || i.name == "in" => Ok(true),
781 "path" | "ty" => match *tok {
782 TokenTree::Token(_, ref tok) => match *tok {
783 OpenDelim(token::DelimToken::Brace) | OpenDelim(token::DelimToken::Bracket) |
784 Comma | FatArrow | Colon | Eq | Gt | Semi | BinOp(token::Or) => Ok(true),
785 Ident(i) if i.name == "as" || i.name == "where" => Ok(true),
788 TokenTree::MetaVarDecl(_, _, frag) if frag.name == "block" => Ok(true),
792 // being a single token, idents are harmless
796 // being either a single token or a delimited sequence, tt is
801 // Explicitly disallow `priv`, on the off chance it comes back.
803 TokenTree::Token(_, ref tok) => match *tok {
805 Ident(i) if i.name != "priv" => Ok(true),
806 ref tok => Ok(tok.can_begin_type())
808 TokenTree::MetaVarDecl(_, _, frag) if frag.name == "ident"
810 || frag.name == "path" => Ok(true),
814 "" => Ok(true), // keywords::Invalid
815 _ => Err((format!("invalid fragment specifier `{}`", frag),
816 "valid fragment specifiers are `ident`, `block`, \
817 `stmt`, `expr`, `pat`, `ty`, `path`, `meta`, `tt`, \
823 fn has_legal_fragment_specifier(sess: &ParseSess,
824 features: &RefCell<Features>,
825 tok: "ed::TokenTree) -> Result<(), String> {
826 debug!("has_legal_fragment_specifier({:?})", tok);
827 if let quoted::TokenTree::MetaVarDecl(_, _, ref frag_spec) = *tok {
828 let frag_name = frag_spec.name.as_str();
829 let frag_span = tok.span();
830 if !is_legal_fragment_specifier(sess, features, &frag_name, frag_span) {
831 return Err(frag_name.to_string());
837 fn is_legal_fragment_specifier(sess: &ParseSess,
838 features: &RefCell<Features>,
840 frag_span: Span) -> bool {
842 "item" | "block" | "stmt" | "expr" | "pat" |
843 "path" | "ty" | "ident" | "meta" | "tt" | "" => true,
845 if !features.borrow().macro_vis_matcher {
846 let explain = feature_gate::EXPLAIN_VIS_MATCHER;
847 emit_feature_err(sess,
859 fn quoted_tt_to_string(tt: "ed::TokenTree) -> String {
861 quoted::TokenTree::Token(_, ref tok) => ::print::pprust::token_to_string(tok),
862 quoted::TokenTree::MetaVarDecl(_, name, kind) => format!("${}:{}", name, kind),
863 _ => panic!("unexpected quoted::TokenTree::{{Sequence or Delimited}} \
864 in follow set checker"),