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"),
123 let rhs_spans = rhs.iter().map(|t| t.span()).collect::<Vec<_>>();
124 // rhs has holes ( `$id` and `$(...)` that need filled)
125 let mut tts = transcribe(cx, Some(named_matches), rhs);
127 // Replace all the tokens for the corresponding positions in the macro, to maintain
128 // proper positions in error reporting, while maintaining the macro_backtrace.
129 if rhs_spans.len() == tts.len() {
130 tts = tts.map_enumerated(|i, tt| {
131 let mut tt = tt.clone();
132 let mut sp = rhs_spans[i];
133 sp.ctxt = tt.span().ctxt;
139 if cx.trace_macros() {
140 trace_macros_note(cx, sp, format!("to `{}`", tts));
143 let directory = Directory {
144 path: cx.current_expansion.module.directory.clone(),
145 ownership: cx.current_expansion.directory_ownership,
147 let mut p = Parser::new(cx.parse_sess(), tts, Some(directory), true, false);
148 p.root_module_name = cx.current_expansion.module.mod_path.last()
149 .map(|id| id.name.as_str().to_string());
151 p.process_potential_macro_variable();
152 // Let the context choose how to interpret the result.
153 // Weird, but useful for X-macros.
154 return Box::new(ParserAnyMacro {
157 // Pass along the original expansion site and the name of the macro
158 // so we can print a useful error message if the parse of the expanded
159 // macro leaves unparsed tokens.
164 Failure(sp, tok) => if sp.lo >= best_fail_spot.lo {
166 best_fail_tok = Some(tok);
168 Error(err_sp, ref msg) => {
169 cx.span_fatal(err_sp.substitute_dummy(sp), &msg[..])
174 let best_fail_msg = parse_failure_msg(best_fail_tok.expect("ran no matchers"));
175 cx.span_fatal(best_fail_spot.substitute_dummy(sp), &best_fail_msg);
178 // Note that macro-by-example's input is also matched against a token tree:
179 // $( $lhs:tt => $rhs:tt );+
181 // Holy self-referential!
183 /// Converts a `macro_rules!` invocation into a syntax extension.
184 pub fn compile(sess: &ParseSess, features: &RefCell<Features>, def: &ast::Item) -> SyntaxExtension {
185 let lhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("lhs"));
186 let rhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("rhs"));
188 // Parse the macro_rules! invocation
189 let body = match def.node {
190 ast::ItemKind::MacroDef(ref body) => body,
194 // The pattern that macro_rules matches.
195 // The grammar for macro_rules! is:
196 // $( $lhs:tt => $rhs:tt );+
197 // ...quasiquoting this would be nice.
198 // These spans won't matter, anyways
199 let argument_gram = vec![
200 quoted::TokenTree::Sequence(DUMMY_SP, Rc::new(quoted::SequenceRepetition {
202 quoted::TokenTree::MetaVarDecl(DUMMY_SP, lhs_nm, ast::Ident::from_str("tt")),
203 quoted::TokenTree::Token(DUMMY_SP, token::FatArrow),
204 quoted::TokenTree::MetaVarDecl(DUMMY_SP, rhs_nm, ast::Ident::from_str("tt")),
206 separator: Some(if body.legacy { token::Semi } else { token::Comma }),
207 op: quoted::KleeneOp::OneOrMore,
210 // to phase into semicolon-termination instead of semicolon-separation
211 quoted::TokenTree::Sequence(DUMMY_SP, Rc::new(quoted::SequenceRepetition {
212 tts: vec![quoted::TokenTree::Token(DUMMY_SP, token::Semi)],
214 op: quoted::KleeneOp::ZeroOrMore,
219 let argument_map = match parse(sess, body.stream(), &argument_gram, None, true) {
221 Failure(sp, tok) => {
222 let s = parse_failure_msg(tok);
223 panic!(sess.span_diagnostic.span_fatal(sp.substitute_dummy(def.span), &s));
226 panic!(sess.span_diagnostic.span_fatal(sp.substitute_dummy(def.span), &s));
230 let mut valid = true;
232 // Extract the arguments:
233 let lhses = match *argument_map[&lhs_nm] {
234 MatchedSeq(ref s, _) => {
236 if let MatchedNonterminal(ref nt) = *m {
237 if let NtTT(ref tt) = **nt {
238 let tt = quoted::parse(tt.clone().into(), true, sess).pop().unwrap();
239 valid &= check_lhs_nt_follows(sess, features, &def.attrs, &tt);
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 lhs")
249 let rhses = match *argument_map[&rhs_nm] {
250 MatchedSeq(ref s, _) => {
252 if let MatchedNonterminal(ref nt) = *m {
253 if let NtTT(ref tt) = **nt {
254 return quoted::parse(tt.clone().into(), false, sess).pop().unwrap();
257 sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
258 }).collect::<Vec<quoted::TokenTree>>()
260 _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured rhs")
264 valid &= check_rhs(sess, rhs);
267 // don't abort iteration early, so that errors for multiple lhses can be reported
269 valid &= check_lhs_no_empty_seq(sess, &[lhs.clone()])
272 let exp: Box<_> = Box::new(MacroRulesMacroExpander {
280 let allow_internal_unstable = attr::contains_name(&def.attrs, "allow_internal_unstable");
281 NormalTT(exp, Some((def.id, def.span)), allow_internal_unstable)
283 SyntaxExtension::DeclMacro(exp, Some((def.id, def.span)))
287 fn check_lhs_nt_follows(sess: &ParseSess,
288 features: &RefCell<Features>,
289 attrs: &[ast::Attribute],
290 lhs: "ed::TokenTree) -> bool {
291 // lhs is going to be like TokenTree::Delimited(...), where the
292 // entire lhs is those tts. Or, it can be a "bare sequence", not wrapped in parens.
293 if let quoted::TokenTree::Delimited(_, ref tts) = *lhs {
294 check_matcher(sess, features, attrs, &tts.tts)
296 let msg = "invalid macro matcher; matchers must be contained in balanced delimiters";
297 sess.span_diagnostic.span_err(lhs.span(), msg);
300 // we don't abort on errors on rejection, the driver will do that for us
301 // after parsing/expansion. we can report every error in every macro this way.
304 /// Check that the lhs contains no repetition which could match an empty token
305 /// tree, because then the matcher would hang indefinitely.
306 fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[quoted::TokenTree]) -> bool {
307 use self::quoted::TokenTree;
310 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => (),
311 TokenTree::Delimited(_, ref del) => if !check_lhs_no_empty_seq(sess, &del.tts) {
314 TokenTree::Sequence(span, ref seq) => {
315 if seq.separator.is_none() && seq.tts.iter().all(|seq_tt| {
317 TokenTree::MetaVarDecl(_, _, id) => id.name == "vis",
318 TokenTree::Sequence(_, ref sub_seq) =>
319 sub_seq.op == quoted::KleeneOp::ZeroOrMore,
323 sess.span_diagnostic.span_err(span, "repetition matches empty token tree");
326 if !check_lhs_no_empty_seq(sess, &seq.tts) {
336 fn check_rhs(sess: &ParseSess, rhs: "ed::TokenTree) -> bool {
338 quoted::TokenTree::Delimited(..) => return true,
339 _ => sess.span_diagnostic.span_err(rhs.span(), "macro rhs must be delimited")
344 fn check_matcher(sess: &ParseSess,
345 features: &RefCell<Features>,
346 attrs: &[ast::Attribute],
347 matcher: &[quoted::TokenTree]) -> bool {
348 let first_sets = FirstSets::new(matcher);
349 let empty_suffix = TokenSet::empty();
350 let err = sess.span_diagnostic.err_count();
351 check_matcher_core(sess, features, attrs, &first_sets, matcher, &empty_suffix);
352 err == sess.span_diagnostic.err_count()
355 // The FirstSets for a matcher is a mapping from subsequences in the
356 // matcher to the FIRST set for that subsequence.
358 // This mapping is partially precomputed via a backwards scan over the
359 // token trees of the matcher, which provides a mapping from each
360 // repetition sequence to its FIRST set.
362 // (Hypothetically sequences should be uniquely identifiable via their
363 // spans, though perhaps that is false e.g. for macro-generated macros
364 // that do not try to inject artificial span information. My plan is
365 // to try to catch such cases ahead of time and not include them in
366 // the precomputed mapping.)
368 // this maps each TokenTree::Sequence `$(tt ...) SEP OP` that is uniquely identified by its
369 // span in the original matcher to the First set for the inner sequence `tt ...`.
371 // If two sequences have the same span in a matcher, then map that
372 // span to None (invalidating the mapping here and forcing the code to
374 first: HashMap<Span, Option<TokenSet>>,
378 fn new(tts: &[quoted::TokenTree]) -> FirstSets {
379 use self::quoted::TokenTree;
381 let mut sets = FirstSets { first: HashMap::new() };
382 build_recur(&mut sets, tts);
385 // walks backward over `tts`, returning the FIRST for `tts`
386 // and updating `sets` at the same time for all sequence
387 // substructure we find within `tts`.
388 fn build_recur(sets: &mut FirstSets, tts: &[TokenTree]) -> TokenSet {
389 let mut first = TokenSet::empty();
390 for tt in tts.iter().rev() {
392 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
393 first.replace_with(tt.clone());
395 TokenTree::Delimited(span, ref delimited) => {
396 build_recur(sets, &delimited.tts[..]);
397 first.replace_with(delimited.open_tt(span));
399 TokenTree::Sequence(sp, ref seq_rep) => {
400 let subfirst = build_recur(sets, &seq_rep.tts[..]);
402 match sets.first.entry(sp) {
403 Entry::Vacant(vac) => {
404 vac.insert(Some(subfirst.clone()));
406 Entry::Occupied(mut occ) => {
407 // if there is already an entry, then a span must have collided.
408 // This should not happen with typical macro_rules macros,
409 // but syntax extensions need not maintain distinct spans,
410 // so distinct syntax trees can be assigned the same span.
411 // In such a case, the map cannot be trusted; so mark this
412 // entry as unusable.
417 // If the sequence contents can be empty, then the first
418 // token could be the separator token itself.
420 if let (Some(ref sep), true) = (seq_rep.separator.clone(),
421 subfirst.maybe_empty) {
422 first.add_one_maybe(TokenTree::Token(sp, sep.clone()));
425 // Reverse scan: Sequence comes before `first`.
426 if subfirst.maybe_empty || seq_rep.op == quoted::KleeneOp::ZeroOrMore {
427 // If sequence is potentially empty, then
428 // union them (preserving first emptiness).
429 first.add_all(&TokenSet { maybe_empty: true, ..subfirst });
431 // Otherwise, sequence guaranteed
432 // non-empty; replace first.
443 // walks forward over `tts` until all potential FIRST tokens are
445 fn first(&self, tts: &[quoted::TokenTree]) -> TokenSet {
446 use self::quoted::TokenTree;
448 let mut first = TokenSet::empty();
449 for tt in tts.iter() {
450 assert!(first.maybe_empty);
452 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
453 first.add_one(tt.clone());
456 TokenTree::Delimited(span, ref delimited) => {
457 first.add_one(delimited.open_tt(span));
460 TokenTree::Sequence(sp, ref seq_rep) => {
461 match self.first.get(&sp) {
462 Some(&Some(ref subfirst)) => {
464 // If the sequence contents can be empty, then the first
465 // token could be the separator token itself.
467 if let (Some(ref sep), true) = (seq_rep.separator.clone(),
468 subfirst.maybe_empty) {
469 first.add_one_maybe(TokenTree::Token(sp, sep.clone()));
472 assert!(first.maybe_empty);
473 first.add_all(subfirst);
474 if subfirst.maybe_empty ||
475 seq_rep.op == quoted::KleeneOp::ZeroOrMore {
476 // continue scanning for more first
477 // tokens, but also make sure we
478 // restore empty-tracking state
479 first.maybe_empty = true;
487 panic!("assume all sequences have (unique) spans for now");
491 panic!("We missed a sequence during FirstSets construction");
498 // we only exit the loop if `tts` was empty or if every
499 // element of `tts` matches the empty sequence.
500 assert!(first.maybe_empty);
505 // A set of `quoted::TokenTree`s, which may include `TokenTree::Match`s
506 // (for macro-by-example syntactic variables). It also carries the
507 // `maybe_empty` flag; that is true if and only if the matcher can
508 // match an empty token sequence.
510 // The First set is computed on submatchers like `$($a:expr b),* $(c)* d`,
511 // which has corresponding FIRST = {$a:expr, c, d}.
512 // Likewise, `$($a:expr b),* $(c)+ d` has FIRST = {$a:expr, c}.
514 // (Notably, we must allow for *-op to occur zero times.)
515 #[derive(Clone, Debug)]
517 tokens: Vec<quoted::TokenTree>,
522 // Returns a set for the empty sequence.
523 fn empty() -> Self { TokenSet { tokens: Vec::new(), maybe_empty: true } }
525 // Returns the set `{ tok }` for the single-token (and thus
526 // non-empty) sequence [tok].
527 fn singleton(tok: quoted::TokenTree) -> Self {
528 TokenSet { tokens: vec![tok], maybe_empty: false }
531 // Changes self to be the set `{ tok }`.
532 // Since `tok` is always present, marks self as non-empty.
533 fn replace_with(&mut self, tok: quoted::TokenTree) {
535 self.tokens.push(tok);
536 self.maybe_empty = false;
539 // Changes self to be the empty set `{}`; meant for use when
540 // the particular token does not matter, but we want to
541 // record that it occurs.
542 fn replace_with_irrelevant(&mut self) {
544 self.maybe_empty = false;
547 // Adds `tok` to the set for `self`, marking sequence as non-empy.
548 fn add_one(&mut self, tok: quoted::TokenTree) {
549 if !self.tokens.contains(&tok) {
550 self.tokens.push(tok);
552 self.maybe_empty = false;
555 // Adds `tok` to the set for `self`. (Leaves `maybe_empty` flag alone.)
556 fn add_one_maybe(&mut self, tok: quoted::TokenTree) {
557 if !self.tokens.contains(&tok) {
558 self.tokens.push(tok);
562 // Adds all elements of `other` to this.
564 // (Since this is a set, we filter out duplicates.)
566 // If `other` is potentially empty, then preserves the previous
567 // setting of the empty flag of `self`. If `other` is guaranteed
568 // non-empty, then `self` is marked non-empty.
569 fn add_all(&mut self, other: &Self) {
570 for tok in &other.tokens {
571 if !self.tokens.contains(tok) {
572 self.tokens.push(tok.clone());
575 if !other.maybe_empty {
576 self.maybe_empty = false;
581 // Checks that `matcher` is internally consistent and that it
582 // can legally by followed by a token N, for all N in `follow`.
583 // (If `follow` is empty, then it imposes no constraint on
586 // Returns the set of NT tokens that could possibly come last in
587 // `matcher`. (If `matcher` matches the empty sequence, then
588 // `maybe_empty` will be set to true.)
590 // Requires that `first_sets` is pre-computed for `matcher`;
591 // see `FirstSets::new`.
592 fn check_matcher_core(sess: &ParseSess,
593 features: &RefCell<Features>,
594 attrs: &[ast::Attribute],
595 first_sets: &FirstSets,
596 matcher: &[quoted::TokenTree],
597 follow: &TokenSet) -> TokenSet {
598 use self::quoted::TokenTree;
600 let mut last = TokenSet::empty();
602 // 2. For each token and suffix [T, SUFFIX] in M:
603 // ensure that T can be followed by SUFFIX, and if SUFFIX may be empty,
604 // then ensure T can also be followed by any element of FOLLOW.
605 'each_token: for i in 0..matcher.len() {
606 let token = &matcher[i];
607 let suffix = &matcher[i+1..];
609 let build_suffix_first = || {
610 let mut s = first_sets.first(suffix);
611 if s.maybe_empty { s.add_all(follow); }
615 // (we build `suffix_first` on demand below; you can tell
616 // which cases are supposed to fall through by looking for the
617 // initialization of this variable.)
620 // First, update `last` so that it corresponds to the set
621 // of NT tokens that might end the sequence `... token`.
623 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
624 let can_be_followed_by_any;
625 if let Err(bad_frag) = has_legal_fragment_specifier(sess, features, attrs, token) {
626 let msg = format!("invalid fragment specifier `{}`", bad_frag);
627 sess.span_diagnostic.struct_span_err(token.span(), &msg)
628 .help("valid fragment specifiers are `ident`, `block`, `stmt`, `expr`, \
629 `pat`, `ty`, `path`, `meta`, `tt`, `item` and `vis`")
631 // (This eliminates false positives and duplicates
632 // from error messages.)
633 can_be_followed_by_any = true;
635 can_be_followed_by_any = token_can_be_followed_by_any(token);
638 if can_be_followed_by_any {
639 // don't need to track tokens that work with any,
640 last.replace_with_irrelevant();
641 // ... and don't need to check tokens that can be
642 // followed by anything against SUFFIX.
643 continue 'each_token;
645 last.replace_with(token.clone());
646 suffix_first = build_suffix_first();
649 TokenTree::Delimited(span, ref d) => {
650 let my_suffix = TokenSet::singleton(d.close_tt(span));
651 check_matcher_core(sess, features, attrs, first_sets, &d.tts, &my_suffix);
652 // don't track non NT tokens
653 last.replace_with_irrelevant();
655 // also, we don't need to check delimited sequences
657 continue 'each_token;
659 TokenTree::Sequence(sp, ref seq_rep) => {
660 suffix_first = build_suffix_first();
661 // The trick here: when we check the interior, we want
662 // to include the separator (if any) as a potential
663 // (but not guaranteed) element of FOLLOW. So in that
664 // case, we make a temp copy of suffix and stuff
665 // delimiter in there.
667 // FIXME: Should I first scan suffix_first to see if
668 // delimiter is already in it before I go through the
669 // work of cloning it? But then again, this way I may
670 // get a "tighter" span?
672 let my_suffix = if let Some(ref u) = seq_rep.separator {
673 new = suffix_first.clone();
674 new.add_one_maybe(TokenTree::Token(sp, u.clone()));
680 // At this point, `suffix_first` is built, and
681 // `my_suffix` is some TokenSet that we can use
682 // for checking the interior of `seq_rep`.
683 let next = check_matcher_core(sess,
689 if next.maybe_empty {
695 // the recursive call to check_matcher_core already ran the 'each_last
696 // check below, so we can just keep going forward here.
697 continue 'each_token;
701 // (`suffix_first` guaranteed initialized once reaching here.)
703 // Now `last` holds the complete set of NT tokens that could
704 // end the sequence before SUFFIX. Check that every one works with `suffix`.
705 'each_last: for token in &last.tokens {
706 if let TokenTree::MetaVarDecl(_, ref name, ref frag_spec) = *token {
707 for next_token in &suffix_first.tokens {
708 match is_in_follow(next_token, &frag_spec.name.as_str()) {
709 Err((msg, help)) => {
710 sess.span_diagnostic.struct_span_err(next_token.span(), &msg)
712 // don't bother reporting every source of
713 // conflict for a particular element of `last`.
718 let may_be = if last.tokens.len() == 1 &&
719 suffix_first.tokens.len() == 1
726 sess.span_diagnostic.span_err(
728 &format!("`${name}:{frag}` {may_be} followed by `{next}`, which \
729 is not allowed for `{frag}` fragments",
732 next=quoted_tt_to_string(next_token),
744 fn token_can_be_followed_by_any(tok: "ed::TokenTree) -> bool {
745 if let quoted::TokenTree::MetaVarDecl(_, _, frag_spec) = *tok {
746 frag_can_be_followed_by_any(&frag_spec.name.as_str())
748 // (Non NT's can always be followed by anthing in matchers.)
753 /// True if a fragment of type `frag` can be followed by any sort of
754 /// token. We use this (among other things) as a useful approximation
755 /// for when `frag` can be followed by a repetition like `$(...)*` or
756 /// `$(...)+`. In general, these can be a bit tricky to reason about,
757 /// so we adopt a conservative position that says that any fragment
758 /// specifier which consumes at most one token tree can be followed by
759 /// a fragment specifier (indeed, these fragments can be followed by
760 /// ANYTHING without fear of future compatibility hazards).
761 fn frag_can_be_followed_by_any(frag: &str) -> bool {
763 "item" | // always terminated by `}` or `;`
764 "block" | // exactly one token tree
765 "ident" | // exactly one token tree
766 "meta" | // exactly one token tree
767 "tt" => // exactly one token tree
775 /// True if `frag` can legally be followed by the token `tok`. For
776 /// fragments that can consume an unbounded number of tokens, `tok`
777 /// must be within a well-defined follow set. This is intended to
778 /// guarantee future compatibility: for example, without this rule, if
779 /// we expanded `expr` to include a new binary operator, we might
780 /// break macros that were relying on that binary operator as a
782 // when changing this do not forget to update doc/book/macros.md!
783 fn is_in_follow(tok: "ed::TokenTree, frag: &str) -> Result<bool, (String, &'static str)> {
784 use self::quoted::TokenTree;
786 if let TokenTree::Token(_, token::CloseDelim(_)) = *tok {
787 // closing a token tree can never be matched by any fragment;
788 // iow, we always require that `(` and `)` match, etc.
793 // since items *must* be followed by either a `;` or a `}`, we can
794 // accept anything after them
798 // anything can follow block, the braces provide an easy boundary to
802 "stmt" | "expr" => match *tok {
803 TokenTree::Token(_, ref tok) => match *tok {
804 FatArrow | Comma | Semi => Ok(true),
809 "pat" => match *tok {
810 TokenTree::Token(_, ref tok) => match *tok {
811 FatArrow | Comma | Eq | BinOp(token::Or) => Ok(true),
812 Ident(i) if i.name == "if" || i.name == "in" => Ok(true),
817 "path" | "ty" => match *tok {
818 TokenTree::Token(_, ref tok) => match *tok {
819 OpenDelim(token::DelimToken::Brace) | OpenDelim(token::DelimToken::Bracket) |
820 Comma | FatArrow | Colon | Eq | Gt | Semi | BinOp(token::Or) => Ok(true),
821 Ident(i) if i.name == "as" || i.name == "where" => Ok(true),
824 TokenTree::MetaVarDecl(_, _, frag) if frag.name == "block" => Ok(true),
828 // being a single token, idents are harmless
832 // being either a single token or a delimited sequence, tt is
837 // Explicitly disallow `priv`, on the off chance it comes back.
839 TokenTree::Token(_, ref tok) => match *tok {
841 Ident(i) if i.name != "priv" => Ok(true),
842 ref tok => Ok(tok.can_begin_type())
844 TokenTree::MetaVarDecl(_, _, frag) if frag.name == "ident"
846 || frag.name == "path" => Ok(true),
850 "" => Ok(true), // keywords::Invalid
851 _ => Err((format!("invalid fragment specifier `{}`", frag),
852 "valid fragment specifiers are `ident`, `block`, \
853 `stmt`, `expr`, `pat`, `ty`, `path`, `meta`, `tt`, \
859 fn has_legal_fragment_specifier(sess: &ParseSess,
860 features: &RefCell<Features>,
861 attrs: &[ast::Attribute],
862 tok: "ed::TokenTree) -> Result<(), String> {
863 debug!("has_legal_fragment_specifier({:?})", tok);
864 if let quoted::TokenTree::MetaVarDecl(_, _, ref frag_spec) = *tok {
865 let frag_name = frag_spec.name.as_str();
866 let frag_span = tok.span();
867 if !is_legal_fragment_specifier(sess, features, attrs, &frag_name, frag_span) {
868 return Err(frag_name.to_string());
874 fn is_legal_fragment_specifier(sess: &ParseSess,
875 features: &RefCell<Features>,
876 attrs: &[ast::Attribute],
878 frag_span: Span) -> bool {
880 "item" | "block" | "stmt" | "expr" | "pat" |
881 "path" | "ty" | "ident" | "meta" | "tt" | "" => true,
883 if !features.borrow().macro_vis_matcher
884 && !attr::contains_name(attrs, "allow_internal_unstable") {
885 let explain = feature_gate::EXPLAIN_VIS_MATCHER;
886 emit_feature_err(sess,
898 fn quoted_tt_to_string(tt: "ed::TokenTree) -> String {
900 quoted::TokenTree::Token(_, ref tok) => ::print::pprust::token_to_string(tok),
901 quoted::TokenTree::MetaVar(_, name) => format!("${}", name),
902 quoted::TokenTree::MetaVarDecl(_, name, kind) => format!("${}:{}", name, kind),
903 _ => panic!("unexpected quoted::TokenTree::{{Sequence or Delimited}} \
904 in follow set checker"),