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};
14 use ext::base::{DummyResult, ExtCtxt, MacResult, SyntaxExtension};
15 use ext::base::{NormalTT, TTMacroExpander};
16 use ext::expand::{AstFragment, AstFragmentKind};
17 use ext::tt::macro_parser::{Success, Error, Failure};
18 use ext::tt::macro_parser::{MatchedSeq, MatchedNonterminal};
19 use ext::tt::macro_parser::{parse, parse_failure_msg};
21 use ext::tt::transcribe::transcribe;
22 use feature_gate::{self, emit_feature_err, Features, GateIssue};
23 use parse::{Directory, ParseSess};
24 use parse::parser::Parser;
25 use parse::token::{self, NtTT};
26 use parse::token::Token::*;
28 use tokenstream::{TokenStream, TokenTree};
31 use std::collections::HashMap;
32 use std::collections::hash_map::Entry;
34 use rustc_data_structures::sync::Lrc;
36 pub struct ParserAnyMacro<'a> {
39 /// Span of the expansion site of the macro this parser is for
41 /// The ident of the macro we're parsing
42 macro_ident: ast::Ident
45 impl<'a> ParserAnyMacro<'a> {
46 pub fn make(mut self: Box<ParserAnyMacro<'a>>, kind: AstFragmentKind) -> AstFragment {
47 let ParserAnyMacro { site_span, macro_ident, ref mut parser } = *self;
48 let fragment = panictry!(parser.parse_ast_fragment(kind, true));
50 // We allow semicolons at the end of expressions -- e.g. the semicolon in
51 // `macro_rules! m { () => { panic!(); } }` isn't parsed by `.parse_expr()`,
52 // but `m!()` is allowed in expression positions (c.f. issue #34706).
53 if kind == AstFragmentKind::Expr && parser.token == token::Semi {
57 // Make sure we don't have any tokens left to parse so we don't silently drop anything.
58 let path = ast::Path::from_ident(macro_ident.with_span_pos(site_span));
59 parser.ensure_complete_parse(&path, kind.name(), site_span);
64 struct MacroRulesMacroExpander {
66 lhses: Vec<quoted::TokenTree>,
67 rhses: Vec<quoted::TokenTree>,
71 impl TTMacroExpander for MacroRulesMacroExpander {
76 -> Box<dyn MacResult+'cx> {
78 return DummyResult::any(sp);
89 fn trace_macros_note(cx: &mut ExtCtxt, sp: Span, message: String) {
90 let sp = sp.macro_backtrace().last().map(|trace| trace.call_site).unwrap_or(sp);
91 let values: &mut Vec<String> = cx.expansions.entry(sp).or_insert_with(Vec::new);
95 /// Given `lhses` and `rhses`, this is the new macro we create
96 fn generic_extension<'cx>(cx: &'cx mut ExtCtxt,
100 lhses: &[quoted::TokenTree],
101 rhses: &[quoted::TokenTree])
102 -> Box<dyn MacResult+'cx> {
103 if cx.trace_macros() {
104 trace_macros_note(cx, sp, format!("expanding `{}! {{ {} }}`", name, arg));
107 // Which arm's failure should we report? (the one furthest along)
108 let mut best_fail_spot = DUMMY_SP;
109 let mut best_fail_tok = None;
111 for (i, lhs) in lhses.iter().enumerate() { // try each arm's matchers
112 let lhs_tt = match *lhs {
113 quoted::TokenTree::Delimited(_, ref delim) => &delim.tts[..],
114 _ => cx.span_bug(sp, "malformed macro lhs")
117 match TokenTree::parse(cx, lhs_tt, arg.clone()) {
118 Success(named_matches) => {
119 let rhs = match rhses[i] {
121 quoted::TokenTree::Delimited(_, ref delimed) => delimed.tts.clone(),
122 _ => cx.span_bug(sp, "malformed macro rhs"),
125 let rhs_spans = rhs.iter().map(|t| t.span()).collect::<Vec<_>>();
126 // rhs has holes ( `$id` and `$(...)` that need filled)
127 let mut tts = transcribe(cx, Some(named_matches), rhs);
129 // Replace all the tokens for the corresponding positions in the macro, to maintain
130 // proper positions in error reporting, while maintaining the macro_backtrace.
131 if rhs_spans.len() == tts.len() {
132 tts = tts.map_enumerated(|i, tt| {
133 let mut tt = tt.clone();
134 let mut sp = rhs_spans[i];
135 sp = sp.with_ctxt(tt.span().ctxt());
141 if cx.trace_macros() {
142 trace_macros_note(cx, sp, format!("to `{}`", tts));
145 let directory = Directory {
146 path: Cow::from(cx.current_expansion.module.directory.as_path()),
147 ownership: cx.current_expansion.directory_ownership,
149 let mut p = Parser::new(cx.parse_sess(), tts, Some(directory), true, false);
150 p.root_module_name = cx.current_expansion.module.mod_path.last()
151 .map(|id| id.as_str().to_string());
153 p.process_potential_macro_variable();
154 // Let the context choose how to interpret the result.
155 // Weird, but useful for X-macros.
156 return Box::new(ParserAnyMacro {
159 // Pass along the original expansion site and the name of the macro
160 // so we can print a useful error message if the parse of the expanded
161 // macro leaves unparsed tokens.
166 Failure(sp, tok) => if sp.lo() >= best_fail_spot.lo() {
168 best_fail_tok = Some(tok);
170 Error(err_sp, ref msg) => {
171 cx.span_fatal(err_sp.substitute_dummy(sp), &msg[..])
176 let best_fail_msg = parse_failure_msg(best_fail_tok.expect("ran no matchers"));
177 cx.span_err(best_fail_spot.substitute_dummy(sp), &best_fail_msg);
178 cx.trace_macros_diag();
182 // Note that macro-by-example's input is also matched against a token tree:
183 // $( $lhs:tt => $rhs:tt );+
185 // Holy self-referential!
187 /// Converts a `macro_rules!` invocation into a syntax extension.
188 pub fn compile(sess: &ParseSess, features: &Features, def: &ast::Item, edition: Edition)
190 let lhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("lhs"));
191 let rhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("rhs"));
193 // Parse the macro_rules! invocation
194 let body = match def.node {
195 ast::ItemKind::MacroDef(ref body) => body,
199 // The pattern that macro_rules matches.
200 // The grammar for macro_rules! is:
201 // $( $lhs:tt => $rhs:tt );+
202 // ...quasiquoting this would be nice.
203 // These spans won't matter, anyways
204 let argument_gram = vec![
205 quoted::TokenTree::Sequence(DUMMY_SP, Lrc::new(quoted::SequenceRepetition {
207 quoted::TokenTree::MetaVarDecl(DUMMY_SP, lhs_nm, ast::Ident::from_str("tt")),
208 quoted::TokenTree::Token(DUMMY_SP, token::FatArrow),
209 quoted::TokenTree::MetaVarDecl(DUMMY_SP, rhs_nm, ast::Ident::from_str("tt")),
211 separator: Some(if body.legacy { token::Semi } else { token::Comma }),
212 op: quoted::KleeneOp::OneOrMore,
215 // to phase into semicolon-termination instead of semicolon-separation
216 quoted::TokenTree::Sequence(DUMMY_SP, Lrc::new(quoted::SequenceRepetition {
217 tts: vec![quoted::TokenTree::Token(DUMMY_SP, token::Semi)],
219 op: quoted::KleeneOp::ZeroOrMore,
224 let argument_map = match parse(sess, body.stream(), &argument_gram, None, true) {
226 Failure(sp, tok) => {
227 let s = parse_failure_msg(tok);
228 sess.span_diagnostic.span_fatal(sp.substitute_dummy(def.span), &s).raise();
231 sess.span_diagnostic.span_fatal(sp.substitute_dummy(def.span), &s).raise();
235 let mut valid = true;
237 // Extract the arguments:
238 let lhses = match *argument_map[&lhs_nm] {
239 MatchedSeq(ref s, _) => {
241 if let MatchedNonterminal(ref nt) = *m {
242 if let NtTT(ref tt) = **nt {
243 let tt = quoted::parse(
254 valid &= check_lhs_nt_follows(sess, features, &def.attrs, &tt);
258 sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
259 }).collect::<Vec<quoted::TokenTree>>()
261 _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
264 let rhses = match *argument_map[&rhs_nm] {
265 MatchedSeq(ref s, _) => {
267 if let MatchedNonterminal(ref nt) = *m {
268 if let NtTT(ref tt) = **nt {
269 return quoted::parse(
281 sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
282 }).collect::<Vec<quoted::TokenTree>>()
284 _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured rhs")
288 valid &= check_rhs(sess, rhs);
291 // don't abort iteration early, so that errors for multiple lhses can be reported
293 valid &= check_lhs_no_empty_seq(sess, &[lhs.clone()])
296 let expander: Box<_> = Box::new(MacroRulesMacroExpander {
304 let allow_internal_unstable = attr::contains_name(&def.attrs, "allow_internal_unstable");
305 let allow_internal_unsafe = attr::contains_name(&def.attrs, "allow_internal_unsafe");
306 let mut local_inner_macros = false;
307 if let Some(macro_export) = attr::find_by_name(&def.attrs, "macro_export") {
308 if let Some(l) = macro_export.meta_item_list() {
309 local_inner_macros = attr::list_contains_name(&l, "local_inner_macros");
313 let unstable_feature = attr::find_stability(&sess.span_diagnostic,
314 &def.attrs, def.span).and_then(|stability| {
315 if let attr::StabilityLevel::Unstable { issue, .. } = stability.level {
316 Some((stability.feature, issue))
324 def_info: Some((def.id, def.span)),
325 allow_internal_unstable,
326 allow_internal_unsafe,
332 let is_transparent = attr::contains_name(&def.attrs, "rustc_transparent_macro");
334 SyntaxExtension::DeclMacro {
336 def_info: Some((def.id, def.span)),
343 fn check_lhs_nt_follows(sess: &ParseSess,
345 attrs: &[ast::Attribute],
346 lhs: "ed::TokenTree) -> bool {
347 // lhs is going to be like TokenTree::Delimited(...), where the
348 // entire lhs is those tts. Or, it can be a "bare sequence", not wrapped in parens.
349 if let quoted::TokenTree::Delimited(_, ref tts) = *lhs {
350 check_matcher(sess, features, attrs, &tts.tts)
352 let msg = "invalid macro matcher; matchers must be contained in balanced delimiters";
353 sess.span_diagnostic.span_err(lhs.span(), msg);
356 // we don't abort on errors on rejection, the driver will do that for us
357 // after parsing/expansion. we can report every error in every macro this way.
360 /// Check that the lhs contains no repetition which could match an empty token
361 /// tree, because then the matcher would hang indefinitely.
362 fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[quoted::TokenTree]) -> bool {
363 use self::quoted::TokenTree;
366 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => (),
367 TokenTree::Delimited(_, ref del) => if !check_lhs_no_empty_seq(sess, &del.tts) {
370 TokenTree::Sequence(span, ref seq) => {
371 if seq.separator.is_none() && seq.tts.iter().all(|seq_tt| {
373 TokenTree::MetaVarDecl(_, _, id) => id.name == "vis",
374 TokenTree::Sequence(_, ref sub_seq) =>
375 sub_seq.op == quoted::KleeneOp::ZeroOrMore,
379 sess.span_diagnostic.span_err(span, "repetition matches empty token tree");
382 if !check_lhs_no_empty_seq(sess, &seq.tts) {
392 fn check_rhs(sess: &ParseSess, rhs: "ed::TokenTree) -> bool {
394 quoted::TokenTree::Delimited(..) => return true,
395 _ => sess.span_diagnostic.span_err(rhs.span(), "macro rhs must be delimited")
400 fn check_matcher(sess: &ParseSess,
402 attrs: &[ast::Attribute],
403 matcher: &[quoted::TokenTree]) -> bool {
404 let first_sets = FirstSets::new(matcher);
405 let empty_suffix = TokenSet::empty();
406 let err = sess.span_diagnostic.err_count();
407 check_matcher_core(sess, features, attrs, &first_sets, matcher, &empty_suffix);
408 err == sess.span_diagnostic.err_count()
411 // The FirstSets for a matcher is a mapping from subsequences in the
412 // matcher to the FIRST set for that subsequence.
414 // This mapping is partially precomputed via a backwards scan over the
415 // token trees of the matcher, which provides a mapping from each
416 // repetition sequence to its FIRST set.
418 // (Hypothetically sequences should be uniquely identifiable via their
419 // spans, though perhaps that is false e.g. for macro-generated macros
420 // that do not try to inject artificial span information. My plan is
421 // to try to catch such cases ahead of time and not include them in
422 // the precomputed mapping.)
424 // this maps each TokenTree::Sequence `$(tt ...) SEP OP` that is uniquely identified by its
425 // span in the original matcher to the First set for the inner sequence `tt ...`.
427 // If two sequences have the same span in a matcher, then map that
428 // span to None (invalidating the mapping here and forcing the code to
430 first: HashMap<Span, Option<TokenSet>>,
434 fn new(tts: &[quoted::TokenTree]) -> FirstSets {
435 use self::quoted::TokenTree;
437 let mut sets = FirstSets { first: HashMap::new() };
438 build_recur(&mut sets, tts);
441 // walks backward over `tts`, returning the FIRST for `tts`
442 // and updating `sets` at the same time for all sequence
443 // substructure we find within `tts`.
444 fn build_recur(sets: &mut FirstSets, tts: &[TokenTree]) -> TokenSet {
445 let mut first = TokenSet::empty();
446 for tt in tts.iter().rev() {
448 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
449 first.replace_with(tt.clone());
451 TokenTree::Delimited(span, ref delimited) => {
452 build_recur(sets, &delimited.tts[..]);
453 first.replace_with(delimited.open_tt(span));
455 TokenTree::Sequence(sp, ref seq_rep) => {
456 let subfirst = build_recur(sets, &seq_rep.tts[..]);
458 match sets.first.entry(sp) {
459 Entry::Vacant(vac) => {
460 vac.insert(Some(subfirst.clone()));
462 Entry::Occupied(mut occ) => {
463 // if there is already an entry, then a span must have collided.
464 // This should not happen with typical macro_rules macros,
465 // but syntax extensions need not maintain distinct spans,
466 // so distinct syntax trees can be assigned the same span.
467 // In such a case, the map cannot be trusted; so mark this
468 // entry as unusable.
473 // If the sequence contents can be empty, then the first
474 // token could be the separator token itself.
476 if let (Some(ref sep), true) = (seq_rep.separator.clone(),
477 subfirst.maybe_empty) {
478 first.add_one_maybe(TokenTree::Token(sp, sep.clone()));
481 // Reverse scan: Sequence comes before `first`.
482 if subfirst.maybe_empty || seq_rep.op == quoted::KleeneOp::ZeroOrMore {
483 // If sequence is potentially empty, then
484 // union them (preserving first emptiness).
485 first.add_all(&TokenSet { maybe_empty: true, ..subfirst });
487 // Otherwise, sequence guaranteed
488 // non-empty; replace first.
499 // walks forward over `tts` until all potential FIRST tokens are
501 fn first(&self, tts: &[quoted::TokenTree]) -> TokenSet {
502 use self::quoted::TokenTree;
504 let mut first = TokenSet::empty();
505 for tt in tts.iter() {
506 assert!(first.maybe_empty);
508 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
509 first.add_one(tt.clone());
512 TokenTree::Delimited(span, ref delimited) => {
513 first.add_one(delimited.open_tt(span));
516 TokenTree::Sequence(sp, ref seq_rep) => {
517 match self.first.get(&sp) {
518 Some(&Some(ref subfirst)) => {
520 // If the sequence contents can be empty, then the first
521 // token could be the separator token itself.
523 if let (Some(ref sep), true) = (seq_rep.separator.clone(),
524 subfirst.maybe_empty) {
525 first.add_one_maybe(TokenTree::Token(sp, sep.clone()));
528 assert!(first.maybe_empty);
529 first.add_all(subfirst);
530 if subfirst.maybe_empty ||
531 seq_rep.op == quoted::KleeneOp::ZeroOrMore {
532 // continue scanning for more first
533 // tokens, but also make sure we
534 // restore empty-tracking state
535 first.maybe_empty = true;
543 panic!("assume all sequences have (unique) spans for now");
547 panic!("We missed a sequence during FirstSets construction");
554 // we only exit the loop if `tts` was empty or if every
555 // element of `tts` matches the empty sequence.
556 assert!(first.maybe_empty);
561 // A set of `quoted::TokenTree`s, which may include `TokenTree::Match`s
562 // (for macro-by-example syntactic variables). It also carries the
563 // `maybe_empty` flag; that is true if and only if the matcher can
564 // match an empty token sequence.
566 // The First set is computed on submatchers like `$($a:expr b),* $(c)* d`,
567 // which has corresponding FIRST = {$a:expr, c, d}.
568 // Likewise, `$($a:expr b),* $(c)+ d` has FIRST = {$a:expr, c}.
570 // (Notably, we must allow for *-op to occur zero times.)
571 #[derive(Clone, Debug)]
573 tokens: Vec<quoted::TokenTree>,
578 // Returns a set for the empty sequence.
579 fn empty() -> Self { TokenSet { tokens: Vec::new(), maybe_empty: true } }
581 // Returns the set `{ tok }` for the single-token (and thus
582 // non-empty) sequence [tok].
583 fn singleton(tok: quoted::TokenTree) -> Self {
584 TokenSet { tokens: vec![tok], maybe_empty: false }
587 // Changes self to be the set `{ tok }`.
588 // Since `tok` is always present, marks self as non-empty.
589 fn replace_with(&mut self, tok: quoted::TokenTree) {
591 self.tokens.push(tok);
592 self.maybe_empty = false;
595 // Changes self to be the empty set `{}`; meant for use when
596 // the particular token does not matter, but we want to
597 // record that it occurs.
598 fn replace_with_irrelevant(&mut self) {
600 self.maybe_empty = false;
603 // Adds `tok` to the set for `self`, marking sequence as non-empy.
604 fn add_one(&mut self, tok: quoted::TokenTree) {
605 if !self.tokens.contains(&tok) {
606 self.tokens.push(tok);
608 self.maybe_empty = false;
611 // Adds `tok` to the set for `self`. (Leaves `maybe_empty` flag alone.)
612 fn add_one_maybe(&mut self, tok: quoted::TokenTree) {
613 if !self.tokens.contains(&tok) {
614 self.tokens.push(tok);
618 // Adds all elements of `other` to this.
620 // (Since this is a set, we filter out duplicates.)
622 // If `other` is potentially empty, then preserves the previous
623 // setting of the empty flag of `self`. If `other` is guaranteed
624 // non-empty, then `self` is marked non-empty.
625 fn add_all(&mut self, other: &Self) {
626 for tok in &other.tokens {
627 if !self.tokens.contains(tok) {
628 self.tokens.push(tok.clone());
631 if !other.maybe_empty {
632 self.maybe_empty = false;
637 // Checks that `matcher` is internally consistent and that it
638 // can legally by followed by a token N, for all N in `follow`.
639 // (If `follow` is empty, then it imposes no constraint on
642 // Returns the set of NT tokens that could possibly come last in
643 // `matcher`. (If `matcher` matches the empty sequence, then
644 // `maybe_empty` will be set to true.)
646 // Requires that `first_sets` is pre-computed for `matcher`;
647 // see `FirstSets::new`.
648 fn check_matcher_core(sess: &ParseSess,
650 attrs: &[ast::Attribute],
651 first_sets: &FirstSets,
652 matcher: &[quoted::TokenTree],
653 follow: &TokenSet) -> TokenSet {
654 use self::quoted::TokenTree;
656 let mut last = TokenSet::empty();
658 // 2. For each token and suffix [T, SUFFIX] in M:
659 // ensure that T can be followed by SUFFIX, and if SUFFIX may be empty,
660 // then ensure T can also be followed by any element of FOLLOW.
661 'each_token: for i in 0..matcher.len() {
662 let token = &matcher[i];
663 let suffix = &matcher[i+1..];
665 let build_suffix_first = || {
666 let mut s = first_sets.first(suffix);
667 if s.maybe_empty { s.add_all(follow); }
671 // (we build `suffix_first` on demand below; you can tell
672 // which cases are supposed to fall through by looking for the
673 // initialization of this variable.)
676 // First, update `last` so that it corresponds to the set
677 // of NT tokens that might end the sequence `... token`.
679 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
680 let can_be_followed_by_any;
681 if let Err(bad_frag) = has_legal_fragment_specifier(sess, features, attrs, token) {
682 let msg = format!("invalid fragment specifier `{}`", bad_frag);
683 sess.span_diagnostic.struct_span_err(token.span(), &msg)
684 .help("valid fragment specifiers are `ident`, `block`, `stmt`, `expr`, \
685 `pat`, `ty`, `literal`, `path`, `meta`, `tt`, `item` and `vis`")
687 // (This eliminates false positives and duplicates
688 // from error messages.)
689 can_be_followed_by_any = true;
691 can_be_followed_by_any = token_can_be_followed_by_any(token);
694 if can_be_followed_by_any {
695 // don't need to track tokens that work with any,
696 last.replace_with_irrelevant();
697 // ... and don't need to check tokens that can be
698 // followed by anything against SUFFIX.
699 continue 'each_token;
701 last.replace_with(token.clone());
702 suffix_first = build_suffix_first();
705 TokenTree::Delimited(span, ref d) => {
706 let my_suffix = TokenSet::singleton(d.close_tt(span));
707 check_matcher_core(sess, features, attrs, first_sets, &d.tts, &my_suffix);
708 // don't track non NT tokens
709 last.replace_with_irrelevant();
711 // also, we don't need to check delimited sequences
713 continue 'each_token;
715 TokenTree::Sequence(sp, ref seq_rep) => {
716 suffix_first = build_suffix_first();
717 // The trick here: when we check the interior, we want
718 // to include the separator (if any) as a potential
719 // (but not guaranteed) element of FOLLOW. So in that
720 // case, we make a temp copy of suffix and stuff
721 // delimiter in there.
723 // FIXME: Should I first scan suffix_first to see if
724 // delimiter is already in it before I go through the
725 // work of cloning it? But then again, this way I may
726 // get a "tighter" span?
728 let my_suffix = if let Some(ref u) = seq_rep.separator {
729 new = suffix_first.clone();
730 new.add_one_maybe(TokenTree::Token(sp, u.clone()));
736 // At this point, `suffix_first` is built, and
737 // `my_suffix` is some TokenSet that we can use
738 // for checking the interior of `seq_rep`.
739 let next = check_matcher_core(sess,
745 if next.maybe_empty {
751 // the recursive call to check_matcher_core already ran the 'each_last
752 // check below, so we can just keep going forward here.
753 continue 'each_token;
757 // (`suffix_first` guaranteed initialized once reaching here.)
759 // Now `last` holds the complete set of NT tokens that could
760 // end the sequence before SUFFIX. Check that every one works with `suffix`.
761 'each_last: for token in &last.tokens {
762 if let TokenTree::MetaVarDecl(_, ref name, ref frag_spec) = *token {
763 for next_token in &suffix_first.tokens {
764 match is_in_follow(next_token, &frag_spec.as_str()) {
765 Err((msg, help)) => {
766 sess.span_diagnostic.struct_span_err(next_token.span(), &msg)
768 // don't bother reporting every source of
769 // conflict for a particular element of `last`.
774 let may_be = if last.tokens.len() == 1 &&
775 suffix_first.tokens.len() == 1
782 sess.span_diagnostic.span_err(
784 &format!("`${name}:{frag}` {may_be} followed by `{next}`, which \
785 is not allowed for `{frag}` fragments",
788 next=quoted_tt_to_string(next_token),
800 fn token_can_be_followed_by_any(tok: "ed::TokenTree) -> bool {
801 if let quoted::TokenTree::MetaVarDecl(_, _, frag_spec) = *tok {
802 frag_can_be_followed_by_any(&frag_spec.as_str())
804 // (Non NT's can always be followed by anthing in matchers.)
809 /// True if a fragment of type `frag` can be followed by any sort of
810 /// token. We use this (among other things) as a useful approximation
811 /// for when `frag` can be followed by a repetition like `$(...)*` or
812 /// `$(...)+`. In general, these can be a bit tricky to reason about,
813 /// so we adopt a conservative position that says that any fragment
814 /// specifier which consumes at most one token tree can be followed by
815 /// a fragment specifier (indeed, these fragments can be followed by
816 /// ANYTHING without fear of future compatibility hazards).
817 fn frag_can_be_followed_by_any(frag: &str) -> bool {
819 "item" | // always terminated by `}` or `;`
820 "block" | // exactly one token tree
821 "ident" | // exactly one token tree
822 "literal" | // exactly one token tree
823 "meta" | // exactly one token tree
824 "lifetime" | // exactly one token tree
825 "tt" => // exactly one token tree
833 /// True if `frag` can legally be followed by the token `tok`. For
834 /// fragments that can consume an unbounded number of tokens, `tok`
835 /// must be within a well-defined follow set. This is intended to
836 /// guarantee future compatibility: for example, without this rule, if
837 /// we expanded `expr` to include a new binary operator, we might
838 /// break macros that were relying on that binary operator as a
840 // when changing this do not forget to update doc/book/macros.md!
841 fn is_in_follow(tok: "ed::TokenTree, frag: &str) -> Result<bool, (String, &'static str)> {
842 use self::quoted::TokenTree;
844 if let TokenTree::Token(_, token::CloseDelim(_)) = *tok {
845 // closing a token tree can never be matched by any fragment;
846 // iow, we always require that `(` and `)` match, etc.
851 // since items *must* be followed by either a `;` or a `}`, we can
852 // accept anything after them
856 // anything can follow block, the braces provide an easy boundary to
860 "stmt" | "expr" => match *tok {
861 TokenTree::Token(_, ref tok) => match *tok {
862 FatArrow | Comma | Semi => Ok(true),
867 "pat" => match *tok {
868 TokenTree::Token(_, ref tok) => match *tok {
869 FatArrow | Comma | Eq | BinOp(token::Or) => Ok(true),
870 Ident(i, false) if i.name == "if" || i.name == "in" => Ok(true),
875 "path" | "ty" => match *tok {
876 TokenTree::Token(_, ref tok) => match *tok {
877 OpenDelim(token::DelimToken::Brace) | OpenDelim(token::DelimToken::Bracket) |
878 Comma | FatArrow | Colon | Eq | Gt | Semi | BinOp(token::Or) => Ok(true),
879 Ident(i, false) if i.name == "as" || i.name == "where" => Ok(true),
882 TokenTree::MetaVarDecl(_, _, frag) if frag.name == "block" => Ok(true),
885 "ident" | "lifetime" => {
886 // being a single token, idents and lifetimes are harmless
890 // literals may be of a single token, or two tokens (negative numbers)
894 // being either a single token or a delimited sequence, tt is
899 // Explicitly disallow `priv`, on the off chance it comes back.
901 TokenTree::Token(_, ref tok) => match *tok {
903 Ident(i, is_raw) if is_raw || i.name != "priv" => Ok(true),
904 ref tok => Ok(tok.can_begin_type())
906 TokenTree::MetaVarDecl(_, _, frag) if frag.name == "ident"
908 || frag.name == "path" => Ok(true),
912 "" => Ok(true), // keywords::Invalid
913 _ => Err((format!("invalid fragment specifier `{}`", frag),
914 "valid fragment specifiers are `ident`, `block`, \
915 `stmt`, `expr`, `pat`, `ty`, `path`, `meta`, `tt`, \
916 `literal`, `item` and `vis`"))
921 fn has_legal_fragment_specifier(sess: &ParseSess,
923 attrs: &[ast::Attribute],
924 tok: "ed::TokenTree) -> Result<(), String> {
925 debug!("has_legal_fragment_specifier({:?})", tok);
926 if let quoted::TokenTree::MetaVarDecl(_, _, ref frag_spec) = *tok {
927 let frag_name = frag_spec.as_str();
928 let frag_span = tok.span();
929 if !is_legal_fragment_specifier(sess, features, attrs, &frag_name, frag_span) {
930 return Err(frag_name.to_string());
936 fn is_legal_fragment_specifier(sess: &ParseSess,
938 attrs: &[ast::Attribute],
940 frag_span: Span) -> bool {
942 "item" | "block" | "stmt" | "expr" | "pat" | "lifetime" |
943 "path" | "ty" | "ident" | "meta" | "tt" | "" => true,
945 if !features.macro_literal_matcher &&
946 !attr::contains_name(attrs, "allow_internal_unstable") {
947 let explain = feature_gate::EXPLAIN_LITERAL_MATCHER;
948 emit_feature_err(sess,
949 "macro_literal_matcher",
957 if !features.macro_vis_matcher &&
958 !attr::contains_name(attrs, "allow_internal_unstable") {
959 let explain = feature_gate::EXPLAIN_VIS_MATCHER;
960 emit_feature_err(sess,
972 fn quoted_tt_to_string(tt: "ed::TokenTree) -> String {
974 quoted::TokenTree::Token(_, ref tok) => ::print::pprust::token_to_string(tok),
975 quoted::TokenTree::MetaVar(_, name) => format!("${}", name),
976 quoted::TokenTree::MetaVarDecl(_, name, kind) => format!("${}:{}", name, kind),
977 _ => panic!("unexpected quoted::TokenTree::{{Sequence or Delimited}} \
978 in follow set checker"),