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 // Parse the macro_rules! invocation
166 let body = match def.node {
167 ast::ItemKind::MacroDef(ref body) => body,
171 // The pattern that macro_rules matches.
172 // The grammar for macro_rules! is:
173 // $( $lhs:tt => $rhs:tt );+
174 // ...quasiquoting this would be nice.
175 // These spans won't matter, anyways
176 let argument_gram = vec![
177 quoted::TokenTree::Sequence(DUMMY_SP, Rc::new(quoted::SequenceRepetition {
179 quoted::TokenTree::MetaVarDecl(DUMMY_SP, lhs_nm, ast::Ident::from_str("tt")),
180 quoted::TokenTree::Token(DUMMY_SP, token::FatArrow),
181 quoted::TokenTree::MetaVarDecl(DUMMY_SP, rhs_nm, ast::Ident::from_str("tt")),
183 separator: Some(if body.legacy { token::Semi } else { token::Comma }),
184 op: quoted::KleeneOp::OneOrMore,
187 // to phase into semicolon-termination instead of semicolon-separation
188 quoted::TokenTree::Sequence(DUMMY_SP, Rc::new(quoted::SequenceRepetition {
189 tts: vec![quoted::TokenTree::Token(DUMMY_SP, token::Semi)],
191 op: quoted::KleeneOp::ZeroOrMore,
196 let argument_map = match parse(sess, body.stream(), &argument_gram, None, true) {
198 Failure(sp, tok) => {
199 let s = parse_failure_msg(tok);
200 panic!(sess.span_diagnostic.span_fatal(sp.substitute_dummy(def.span), &s));
203 panic!(sess.span_diagnostic.span_fatal(sp.substitute_dummy(def.span), &s));
207 let mut valid = true;
209 // Extract the arguments:
210 let lhses = match *argument_map[&lhs_nm] {
211 MatchedSeq(ref s, _) => {
213 if let MatchedNonterminal(ref nt) = **m {
214 if let NtTT(ref tt) = **nt {
215 let tt = quoted::parse(tt.clone().into(), true, sess).pop().unwrap();
216 valid &= check_lhs_nt_follows(sess, features, &tt);
220 sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
221 }).collect::<Vec<quoted::TokenTree>>()
223 _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
226 let rhses = match *argument_map[&rhs_nm] {
227 MatchedSeq(ref s, _) => {
229 if let MatchedNonterminal(ref nt) = **m {
230 if let NtTT(ref tt) = **nt {
231 return quoted::parse(tt.clone().into(), false, sess).pop().unwrap();
234 sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
235 }).collect::<Vec<quoted::TokenTree>>()
237 _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured rhs")
241 valid &= check_rhs(sess, rhs);
244 // don't abort iteration early, so that errors for multiple lhses can be reported
246 valid &= check_lhs_no_empty_seq(sess, &[lhs.clone()])
249 let exp: Box<_> = Box::new(MacroRulesMacroExpander {
257 Some((def.id, def.span)),
258 attr::contains_name(&def.attrs, "allow_internal_unstable"))
261 fn check_lhs_nt_follows(sess: &ParseSess,
262 features: &RefCell<Features>,
263 lhs: "ed::TokenTree) -> bool {
264 // lhs is going to be like TokenTree::Delimited(...), where the
265 // entire lhs is those tts. Or, it can be a "bare sequence", not wrapped in parens.
266 if let quoted::TokenTree::Delimited(_, ref tts) = *lhs {
267 check_matcher(sess, features, &tts.tts)
269 let msg = "invalid macro matcher; matchers must be contained in balanced delimiters";
270 sess.span_diagnostic.span_err(lhs.span(), msg);
273 // we don't abort on errors on rejection, the driver will do that for us
274 // after parsing/expansion. we can report every error in every macro this way.
277 /// Check that the lhs contains no repetition which could match an empty token
278 /// tree, because then the matcher would hang indefinitely.
279 fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[quoted::TokenTree]) -> bool {
280 use self::quoted::TokenTree;
283 TokenTree::Token(..) | TokenTree::MetaVarDecl(..) => (),
284 TokenTree::Delimited(_, ref del) => if !check_lhs_no_empty_seq(sess, &del.tts) {
287 TokenTree::Sequence(span, ref seq) => {
288 if seq.separator.is_none() && seq.tts.iter().all(|seq_tt| {
290 TokenTree::Sequence(_, ref sub_seq) =>
291 sub_seq.op == quoted::KleeneOp::ZeroOrMore,
295 sess.span_diagnostic.span_err(span, "repetition matches empty token tree");
298 if !check_lhs_no_empty_seq(sess, &seq.tts) {
308 fn check_rhs(sess: &ParseSess, rhs: "ed::TokenTree) -> bool {
310 quoted::TokenTree::Delimited(..) => return true,
311 _ => sess.span_diagnostic.span_err(rhs.span(), "macro rhs must be delimited")
316 fn check_matcher(sess: &ParseSess,
317 features: &RefCell<Features>,
318 matcher: &[quoted::TokenTree]) -> bool {
319 let first_sets = FirstSets::new(matcher);
320 let empty_suffix = TokenSet::empty();
321 let err = sess.span_diagnostic.err_count();
322 check_matcher_core(sess, features, &first_sets, matcher, &empty_suffix);
323 err == sess.span_diagnostic.err_count()
326 // The FirstSets for a matcher is a mapping from subsequences in the
327 // matcher to the FIRST set for that subsequence.
329 // This mapping is partially precomputed via a backwards scan over the
330 // token trees of the matcher, which provides a mapping from each
331 // repetition sequence to its FIRST set.
333 // (Hypothetically sequences should be uniquely identifiable via their
334 // spans, though perhaps that is false e.g. for macro-generated macros
335 // that do not try to inject artificial span information. My plan is
336 // to try to catch such cases ahead of time and not include them in
337 // the precomputed mapping.)
339 // this maps each TokenTree::Sequence `$(tt ...) SEP OP` that is uniquely identified by its
340 // span in the original matcher to the First set for the inner sequence `tt ...`.
342 // If two sequences have the same span in a matcher, then map that
343 // span to None (invalidating the mapping here and forcing the code to
345 first: HashMap<Span, Option<TokenSet>>,
349 fn new(tts: &[quoted::TokenTree]) -> FirstSets {
350 use self::quoted::TokenTree;
352 let mut sets = FirstSets { first: HashMap::new() };
353 build_recur(&mut sets, tts);
356 // walks backward over `tts`, returning the FIRST for `tts`
357 // and updating `sets` at the same time for all sequence
358 // substructure we find within `tts`.
359 fn build_recur(sets: &mut FirstSets, tts: &[TokenTree]) -> TokenSet {
360 let mut first = TokenSet::empty();
361 for tt in tts.iter().rev() {
363 TokenTree::Token(..) | TokenTree::MetaVarDecl(..) => {
364 first.replace_with(tt.clone());
366 TokenTree::Delimited(span, ref delimited) => {
367 build_recur(sets, &delimited.tts[..]);
368 first.replace_with(delimited.open_tt(span));
370 TokenTree::Sequence(sp, ref seq_rep) => {
371 let subfirst = build_recur(sets, &seq_rep.tts[..]);
373 match sets.first.entry(sp) {
374 Entry::Vacant(vac) => {
375 vac.insert(Some(subfirst.clone()));
377 Entry::Occupied(mut occ) => {
378 // if there is already an entry, then a span must have collided.
379 // This should not happen with typical macro_rules macros,
380 // but syntax extensions need not maintain distinct spans,
381 // so distinct syntax trees can be assigned the same span.
382 // In such a case, the map cannot be trusted; so mark this
383 // entry as unusable.
388 // If the sequence contents can be empty, then the first
389 // token could be the separator token itself.
391 if let (Some(ref sep), true) = (seq_rep.separator.clone(),
392 subfirst.maybe_empty) {
393 first.add_one_maybe(TokenTree::Token(sp, sep.clone()));
396 // Reverse scan: Sequence comes before `first`.
397 if subfirst.maybe_empty || seq_rep.op == quoted::KleeneOp::ZeroOrMore {
398 // If sequence is potentially empty, then
399 // union them (preserving first emptiness).
400 first.add_all(&TokenSet { maybe_empty: true, ..subfirst });
402 // Otherwise, sequence guaranteed
403 // non-empty; replace first.
414 // walks forward over `tts` until all potential FIRST tokens are
416 fn first(&self, tts: &[quoted::TokenTree]) -> TokenSet {
417 use self::quoted::TokenTree;
419 let mut first = TokenSet::empty();
420 for tt in tts.iter() {
421 assert!(first.maybe_empty);
423 TokenTree::Token(..) | TokenTree::MetaVarDecl(..) => {
424 first.add_one(tt.clone());
427 TokenTree::Delimited(span, ref delimited) => {
428 first.add_one(delimited.open_tt(span));
431 TokenTree::Sequence(sp, ref seq_rep) => {
432 match self.first.get(&sp) {
433 Some(&Some(ref subfirst)) => {
435 // If the sequence contents can be empty, then the first
436 // token could be the separator token itself.
438 if let (Some(ref sep), true) = (seq_rep.separator.clone(),
439 subfirst.maybe_empty) {
440 first.add_one_maybe(TokenTree::Token(sp, sep.clone()));
443 assert!(first.maybe_empty);
444 first.add_all(subfirst);
445 if subfirst.maybe_empty ||
446 seq_rep.op == quoted::KleeneOp::ZeroOrMore {
447 // continue scanning for more first
448 // tokens, but also make sure we
449 // restore empty-tracking state
450 first.maybe_empty = true;
458 panic!("assume all sequences have (unique) spans for now");
462 panic!("We missed a sequence during FirstSets construction");
469 // we only exit the loop if `tts` was empty or if every
470 // element of `tts` matches the empty sequence.
471 assert!(first.maybe_empty);
476 // A set of `quoted::TokenTree`s, which may include `TokenTree::Match`s
477 // (for macro-by-example syntactic variables). It also carries the
478 // `maybe_empty` flag; that is true if and only if the matcher can
479 // match an empty token sequence.
481 // The First set is computed on submatchers like `$($a:expr b),* $(c)* d`,
482 // which has corresponding FIRST = {$a:expr, c, d}.
483 // Likewise, `$($a:expr b),* $(c)+ d` has FIRST = {$a:expr, c}.
485 // (Notably, we must allow for *-op to occur zero times.)
486 #[derive(Clone, Debug)]
488 tokens: Vec<quoted::TokenTree>,
493 // Returns a set for the empty sequence.
494 fn empty() -> Self { TokenSet { tokens: Vec::new(), maybe_empty: true } }
496 // Returns the set `{ tok }` for the single-token (and thus
497 // non-empty) sequence [tok].
498 fn singleton(tok: quoted::TokenTree) -> Self {
499 TokenSet { tokens: vec![tok], maybe_empty: false }
502 // Changes self to be the set `{ tok }`.
503 // Since `tok` is always present, marks self as non-empty.
504 fn replace_with(&mut self, tok: quoted::TokenTree) {
506 self.tokens.push(tok);
507 self.maybe_empty = false;
510 // Changes self to be the empty set `{}`; meant for use when
511 // the particular token does not matter, but we want to
512 // record that it occurs.
513 fn replace_with_irrelevant(&mut self) {
515 self.maybe_empty = false;
518 // Adds `tok` to the set for `self`, marking sequence as non-empy.
519 fn add_one(&mut self, tok: quoted::TokenTree) {
520 if !self.tokens.contains(&tok) {
521 self.tokens.push(tok);
523 self.maybe_empty = false;
526 // Adds `tok` to the set for `self`. (Leaves `maybe_empty` flag alone.)
527 fn add_one_maybe(&mut self, tok: quoted::TokenTree) {
528 if !self.tokens.contains(&tok) {
529 self.tokens.push(tok);
533 // Adds all elements of `other` to this.
535 // (Since this is a set, we filter out duplicates.)
537 // If `other` is potentially empty, then preserves the previous
538 // setting of the empty flag of `self`. If `other` is guaranteed
539 // non-empty, then `self` is marked non-empty.
540 fn add_all(&mut self, other: &Self) {
541 for tok in &other.tokens {
542 if !self.tokens.contains(tok) {
543 self.tokens.push(tok.clone());
546 if !other.maybe_empty {
547 self.maybe_empty = false;
552 // Checks that `matcher` is internally consistent and that it
553 // can legally by followed by a token N, for all N in `follow`.
554 // (If `follow` is empty, then it imposes no constraint on
557 // Returns the set of NT tokens that could possibly come last in
558 // `matcher`. (If `matcher` matches the empty sequence, then
559 // `maybe_empty` will be set to true.)
561 // Requires that `first_sets` is pre-computed for `matcher`;
562 // see `FirstSets::new`.
563 fn check_matcher_core(sess: &ParseSess,
564 features: &RefCell<Features>,
565 first_sets: &FirstSets,
566 matcher: &[quoted::TokenTree],
567 follow: &TokenSet) -> TokenSet {
568 use self::quoted::TokenTree;
570 let mut last = TokenSet::empty();
572 // 2. For each token and suffix [T, SUFFIX] in M:
573 // ensure that T can be followed by SUFFIX, and if SUFFIX may be empty,
574 // then ensure T can also be followed by any element of FOLLOW.
575 'each_token: for i in 0..matcher.len() {
576 let token = &matcher[i];
577 let suffix = &matcher[i+1..];
579 let build_suffix_first = || {
580 let mut s = first_sets.first(suffix);
581 if s.maybe_empty { s.add_all(follow); }
585 // (we build `suffix_first` on demand below; you can tell
586 // which cases are supposed to fall through by looking for the
587 // initialization of this variable.)
590 // First, update `last` so that it corresponds to the set
591 // of NT tokens that might end the sequence `... token`.
593 TokenTree::Token(..) | TokenTree::MetaVarDecl(..) => {
594 let can_be_followed_by_any;
595 if let Err(bad_frag) = has_legal_fragment_specifier(sess, features, token) {
596 let msg = format!("invalid fragment specifier `{}`", bad_frag);
597 sess.span_diagnostic.struct_span_err(token.span(), &msg)
598 .help("valid fragment specifiers are `ident`, `block`, `stmt`, `expr`, \
599 `pat`, `ty`, `path`, `meta`, `tt`, `item` and `vis`")
601 // (This eliminates false positives and duplicates
602 // from error messages.)
603 can_be_followed_by_any = true;
605 can_be_followed_by_any = token_can_be_followed_by_any(token);
608 if can_be_followed_by_any {
609 // don't need to track tokens that work with any,
610 last.replace_with_irrelevant();
611 // ... and don't need to check tokens that can be
612 // followed by anything against SUFFIX.
613 continue 'each_token;
615 last.replace_with(token.clone());
616 suffix_first = build_suffix_first();
619 TokenTree::Delimited(span, ref d) => {
620 let my_suffix = TokenSet::singleton(d.close_tt(span));
621 check_matcher_core(sess, features, first_sets, &d.tts, &my_suffix);
622 // don't track non NT tokens
623 last.replace_with_irrelevant();
625 // also, we don't need to check delimited sequences
627 continue 'each_token;
629 TokenTree::Sequence(sp, ref seq_rep) => {
630 suffix_first = build_suffix_first();
631 // The trick here: when we check the interior, we want
632 // to include the separator (if any) as a potential
633 // (but not guaranteed) element of FOLLOW. So in that
634 // case, we make a temp copy of suffix and stuff
635 // delimiter in there.
637 // FIXME: Should I first scan suffix_first to see if
638 // delimiter is already in it before I go through the
639 // work of cloning it? But then again, this way I may
640 // get a "tighter" span?
642 let my_suffix = if let Some(ref u) = seq_rep.separator {
643 new = suffix_first.clone();
644 new.add_one_maybe(TokenTree::Token(sp, u.clone()));
650 // At this point, `suffix_first` is built, and
651 // `my_suffix` is some TokenSet that we can use
652 // for checking the interior of `seq_rep`.
653 let next = check_matcher_core(sess, features, first_sets, &seq_rep.tts, my_suffix);
654 if next.maybe_empty {
660 // the recursive call to check_matcher_core already ran the 'each_last
661 // check below, so we can just keep going forward here.
662 continue 'each_token;
666 // (`suffix_first` guaranteed initialized once reaching here.)
668 // Now `last` holds the complete set of NT tokens that could
669 // end the sequence before SUFFIX. Check that every one works with `suffix`.
670 'each_last: for token in &last.tokens {
671 if let TokenTree::MetaVarDecl(_, ref name, ref frag_spec) = *token {
672 for next_token in &suffix_first.tokens {
673 match is_in_follow(next_token, &frag_spec.name.as_str()) {
674 Err((msg, help)) => {
675 sess.span_diagnostic.struct_span_err(next_token.span(), &msg)
677 // don't bother reporting every source of
678 // conflict for a particular element of `last`.
683 let may_be = if last.tokens.len() == 1 &&
684 suffix_first.tokens.len() == 1
691 sess.span_diagnostic.span_err(
693 &format!("`${name}:{frag}` {may_be} followed by `{next}`, which \
694 is not allowed for `{frag}` fragments",
697 next=quoted_tt_to_string(next_token),
709 fn token_can_be_followed_by_any(tok: "ed::TokenTree) -> bool {
710 if let quoted::TokenTree::MetaVarDecl(_, _, frag_spec) = *tok {
711 frag_can_be_followed_by_any(&frag_spec.name.as_str())
713 // (Non NT's can always be followed by anthing in matchers.)
718 /// True if a fragment of type `frag` can be followed by any sort of
719 /// token. We use this (among other things) as a useful approximation
720 /// for when `frag` can be followed by a repetition like `$(...)*` or
721 /// `$(...)+`. In general, these can be a bit tricky to reason about,
722 /// so we adopt a conservative position that says that any fragment
723 /// specifier which consumes at most one token tree can be followed by
724 /// a fragment specifier (indeed, these fragments can be followed by
725 /// ANYTHING without fear of future compatibility hazards).
726 fn frag_can_be_followed_by_any(frag: &str) -> bool {
728 "item" | // always terminated by `}` or `;`
729 "block" | // exactly one token tree
730 "ident" | // exactly one token tree
731 "meta" | // exactly one token tree
732 "tt" => // exactly one token tree
740 /// True if `frag` can legally be followed by the token `tok`. For
741 /// fragments that can consume an unbounded number of tokens, `tok`
742 /// must be within a well-defined follow set. This is intended to
743 /// guarantee future compatibility: for example, without this rule, if
744 /// we expanded `expr` to include a new binary operator, we might
745 /// break macros that were relying on that binary operator as a
747 // when changing this do not forget to update doc/book/macros.md!
748 fn is_in_follow(tok: "ed::TokenTree, frag: &str) -> Result<bool, (String, &'static str)> {
749 use self::quoted::TokenTree;
751 if let TokenTree::Token(_, token::CloseDelim(_)) = *tok {
752 // closing a token tree can never be matched by any fragment;
753 // iow, we always require that `(` and `)` match, etc.
758 // since items *must* be followed by either a `;` or a `}`, we can
759 // accept anything after them
763 // anything can follow block, the braces provide an easy boundary to
767 "stmt" | "expr" => match *tok {
768 TokenTree::Token(_, ref tok) => match *tok {
769 FatArrow | Comma | Semi => Ok(true),
774 "pat" => match *tok {
775 TokenTree::Token(_, ref tok) => match *tok {
776 FatArrow | Comma | Eq | BinOp(token::Or) => Ok(true),
777 Ident(i) if i.name == "if" || i.name == "in" => Ok(true),
782 "path" | "ty" => match *tok {
783 TokenTree::Token(_, ref tok) => match *tok {
784 OpenDelim(token::DelimToken::Brace) | OpenDelim(token::DelimToken::Bracket) |
785 Comma | FatArrow | Colon | Eq | Gt | Semi | BinOp(token::Or) => Ok(true),
786 Ident(i) if i.name == "as" || i.name == "where" => Ok(true),
789 TokenTree::MetaVarDecl(_, _, frag) if frag.name == "block" => Ok(true),
793 // being a single token, idents are harmless
797 // being either a single token or a delimited sequence, tt is
802 // Explicitly disallow `priv`, on the off chance it comes back.
804 TokenTree::Token(_, ref tok) => match *tok {
806 Ident(i) if i.name != "priv" => Ok(true),
807 ref tok => Ok(tok.can_begin_type())
809 TokenTree::MetaVarDecl(_, _, frag) if frag.name == "ident"
811 || frag.name == "path" => Ok(true),
815 "" => Ok(true), // keywords::Invalid
816 _ => Err((format!("invalid fragment specifier `{}`", frag),
817 "valid fragment specifiers are `ident`, `block`, \
818 `stmt`, `expr`, `pat`, `ty`, `path`, `meta`, `tt`, \
824 fn has_legal_fragment_specifier(sess: &ParseSess,
825 features: &RefCell<Features>,
826 tok: "ed::TokenTree) -> Result<(), String> {
827 debug!("has_legal_fragment_specifier({:?})", tok);
828 if let quoted::TokenTree::MetaVarDecl(_, _, ref frag_spec) = *tok {
829 let frag_name = frag_spec.name.as_str();
830 let frag_span = tok.span();
831 if !is_legal_fragment_specifier(sess, features, &frag_name, frag_span) {
832 return Err(frag_name.to_string());
838 fn is_legal_fragment_specifier(sess: &ParseSess,
839 features: &RefCell<Features>,
841 frag_span: Span) -> bool {
843 "item" | "block" | "stmt" | "expr" | "pat" |
844 "path" | "ty" | "ident" | "meta" | "tt" | "" => true,
846 if !features.borrow().macro_vis_matcher {
847 let explain = feature_gate::EXPLAIN_VIS_MATCHER;
848 emit_feature_err(sess,
860 fn quoted_tt_to_string(tt: "ed::TokenTree) -> String {
862 quoted::TokenTree::Token(_, ref tok) => ::print::pprust::token_to_string(tok),
863 quoted::TokenTree::MetaVarDecl(_, name, kind) => format!("${}:{}", name, kind),
864 _ => panic!("unexpected quoted::TokenTree::{{Sequence or Delimited}} \
865 in follow set checker"),