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 cx.expansions.entry(sp).or_default().push(message);
94 /// Given `lhses` and `rhses`, this is the new macro we create
95 fn generic_extension<'cx>(cx: &'cx mut ExtCtxt,
99 lhses: &[quoted::TokenTree],
100 rhses: &[quoted::TokenTree])
101 -> Box<dyn MacResult+'cx> {
102 if cx.trace_macros() {
103 trace_macros_note(cx, sp, format!("expanding `{}! {{ {} }}`", name, arg));
106 // Which arm's failure should we report? (the one furthest along)
107 let mut best_fail_spot = DUMMY_SP;
108 let mut best_fail_tok = None;
110 for (i, lhs) in lhses.iter().enumerate() { // try each arm's matchers
111 let lhs_tt = match *lhs {
112 quoted::TokenTree::Delimited(_, ref delim) => &delim.tts[..],
113 _ => cx.span_bug(sp, "malformed macro lhs")
116 match TokenTree::parse(cx, lhs_tt, arg.clone()) {
117 Success(named_matches) => {
118 let rhs = match rhses[i] {
120 quoted::TokenTree::Delimited(_, ref delimed) => delimed.tts.clone(),
121 _ => cx.span_bug(sp, "malformed macro rhs"),
124 let rhs_spans = rhs.iter().map(|t| t.span()).collect::<Vec<_>>();
125 // rhs has holes ( `$id` and `$(...)` that need filled)
126 let mut tts = transcribe(cx, Some(named_matches), rhs);
128 // Replace all the tokens for the corresponding positions in the macro, to maintain
129 // proper positions in error reporting, while maintaining the macro_backtrace.
130 if rhs_spans.len() == tts.len() {
131 tts = tts.map_enumerated(|i, tt| {
132 let mut tt = tt.clone();
133 let mut sp = rhs_spans[i];
134 sp = sp.with_ctxt(tt.span().ctxt());
140 if cx.trace_macros() {
141 trace_macros_note(cx, sp, format!("to `{}`", tts));
144 let directory = Directory {
145 path: Cow::from(cx.current_expansion.module.directory.as_path()),
146 ownership: cx.current_expansion.directory_ownership,
148 let mut p = Parser::new(cx.parse_sess(), tts, Some(directory), true, false);
149 p.root_module_name = cx.current_expansion.module.mod_path.last()
150 .map(|id| id.as_str().to_string());
152 p.process_potential_macro_variable();
153 // Let the context choose how to interpret the result.
154 // Weird, but useful for X-macros.
155 return Box::new(ParserAnyMacro {
158 // Pass along the original expansion site and the name of the macro
159 // so we can print a useful error message if the parse of the expanded
160 // macro leaves unparsed tokens.
165 Failure(sp, tok) => if sp.lo() >= best_fail_spot.lo() {
167 best_fail_tok = Some(tok);
169 Error(err_sp, ref msg) => {
170 cx.span_fatal(err_sp.substitute_dummy(sp), &msg[..])
175 let best_fail_msg = parse_failure_msg(best_fail_tok.expect("ran no matchers"));
176 let mut err = cx.struct_span_err(best_fail_spot.substitute_dummy(sp), &best_fail_msg);
178 // Check whether there's a missing comma in this macro call, like `println!("{}" a);`
179 if let Some((arg, comma_span)) = arg.add_comma() {
180 for lhs in lhses { // try each arm's matchers
181 let lhs_tt = match *lhs {
182 quoted::TokenTree::Delimited(_, ref delim) => &delim.tts[..],
185 match TokenTree::parse(cx, lhs_tt, arg.clone()) {
187 if comma_span == DUMMY_SP {
188 err.note("you might be missing a comma");
190 err.span_suggestion_short(
192 "missing comma here",
202 cx.trace_macros_diag();
206 // Note that macro-by-example's input is also matched against a token tree:
207 // $( $lhs:tt => $rhs:tt );+
209 // Holy self-referential!
211 /// Converts a `macro_rules!` invocation into a syntax extension.
212 pub fn compile(sess: &ParseSess, features: &Features, def: &ast::Item, edition: Edition)
214 let lhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("lhs"));
215 let rhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("rhs"));
217 // Parse the macro_rules! invocation
218 let body = match def.node {
219 ast::ItemKind::MacroDef(ref body) => body,
223 // The pattern that macro_rules matches.
224 // The grammar for macro_rules! is:
225 // $( $lhs:tt => $rhs:tt );+
226 // ...quasiquoting this would be nice.
227 // These spans won't matter, anyways
228 let argument_gram = vec![
229 quoted::TokenTree::Sequence(DUMMY_SP, Lrc::new(quoted::SequenceRepetition {
231 quoted::TokenTree::MetaVarDecl(DUMMY_SP, lhs_nm, ast::Ident::from_str("tt")),
232 quoted::TokenTree::Token(DUMMY_SP, token::FatArrow),
233 quoted::TokenTree::MetaVarDecl(DUMMY_SP, rhs_nm, ast::Ident::from_str("tt")),
235 separator: Some(if body.legacy { token::Semi } else { token::Comma }),
236 op: quoted::KleeneOp::OneOrMore,
239 // to phase into semicolon-termination instead of semicolon-separation
240 quoted::TokenTree::Sequence(DUMMY_SP, Lrc::new(quoted::SequenceRepetition {
241 tts: vec![quoted::TokenTree::Token(DUMMY_SP, token::Semi)],
243 op: quoted::KleeneOp::ZeroOrMore,
248 let argument_map = match parse(sess, body.stream(), &argument_gram, None, true) {
250 Failure(sp, tok) => {
251 let s = parse_failure_msg(tok);
252 sess.span_diagnostic.span_fatal(sp.substitute_dummy(def.span), &s).raise();
255 sess.span_diagnostic.span_fatal(sp.substitute_dummy(def.span), &s).raise();
259 let mut valid = true;
261 // Extract the arguments:
262 let lhses = match *argument_map[&lhs_nm] {
263 MatchedSeq(ref s, _) => {
265 if let MatchedNonterminal(ref nt) = *m {
266 if let NtTT(ref tt) = **nt {
267 let tt = quoted::parse(
278 valid &= check_lhs_nt_follows(sess, features, &def.attrs, &tt);
282 sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
283 }).collect::<Vec<quoted::TokenTree>>()
285 _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
288 let rhses = match *argument_map[&rhs_nm] {
289 MatchedSeq(ref s, _) => {
291 if let MatchedNonterminal(ref nt) = *m {
292 if let NtTT(ref tt) = **nt {
293 return quoted::parse(
305 sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
306 }).collect::<Vec<quoted::TokenTree>>()
308 _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured rhs")
312 valid &= check_rhs(sess, rhs);
315 // don't abort iteration early, so that errors for multiple lhses can be reported
317 valid &= check_lhs_no_empty_seq(sess, &[lhs.clone()])
320 let expander: Box<_> = Box::new(MacroRulesMacroExpander {
328 let allow_internal_unstable = attr::contains_name(&def.attrs, "allow_internal_unstable");
329 let allow_internal_unsafe = attr::contains_name(&def.attrs, "allow_internal_unsafe");
330 let mut local_inner_macros = false;
331 if let Some(macro_export) = attr::find_by_name(&def.attrs, "macro_export") {
332 if let Some(l) = macro_export.meta_item_list() {
333 local_inner_macros = attr::list_contains_name(&l, "local_inner_macros");
337 let unstable_feature = attr::find_stability(&sess.span_diagnostic,
338 &def.attrs, def.span).and_then(|stability| {
339 if let attr::StabilityLevel::Unstable { issue, .. } = stability.level {
340 Some((stability.feature, issue))
348 def_info: Some((def.id, def.span)),
349 allow_internal_unstable,
350 allow_internal_unsafe,
356 let is_transparent = attr::contains_name(&def.attrs, "rustc_transparent_macro");
358 SyntaxExtension::DeclMacro {
360 def_info: Some((def.id, def.span)),
367 fn check_lhs_nt_follows(sess: &ParseSess,
369 attrs: &[ast::Attribute],
370 lhs: "ed::TokenTree) -> bool {
371 // lhs is going to be like TokenTree::Delimited(...), where the
372 // entire lhs is those tts. Or, it can be a "bare sequence", not wrapped in parens.
373 if let quoted::TokenTree::Delimited(_, ref tts) = *lhs {
374 check_matcher(sess, features, attrs, &tts.tts)
376 let msg = "invalid macro matcher; matchers must be contained in balanced delimiters";
377 sess.span_diagnostic.span_err(lhs.span(), msg);
380 // we don't abort on errors on rejection, the driver will do that for us
381 // after parsing/expansion. we can report every error in every macro this way.
384 /// Check that the lhs contains no repetition which could match an empty token
385 /// tree, because then the matcher would hang indefinitely.
386 fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[quoted::TokenTree]) -> bool {
387 use self::quoted::TokenTree;
390 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => (),
391 TokenTree::Delimited(_, ref del) => if !check_lhs_no_empty_seq(sess, &del.tts) {
394 TokenTree::Sequence(span, ref seq) => {
395 if seq.separator.is_none() && seq.tts.iter().all(|seq_tt| {
397 TokenTree::MetaVarDecl(_, _, id) => id.name == "vis",
398 TokenTree::Sequence(_, ref sub_seq) =>
399 sub_seq.op == quoted::KleeneOp::ZeroOrMore,
403 sess.span_diagnostic.span_err(span, "repetition matches empty token tree");
406 if !check_lhs_no_empty_seq(sess, &seq.tts) {
416 fn check_rhs(sess: &ParseSess, rhs: "ed::TokenTree) -> bool {
418 quoted::TokenTree::Delimited(..) => return true,
419 _ => sess.span_diagnostic.span_err(rhs.span(), "macro rhs must be delimited")
424 fn check_matcher(sess: &ParseSess,
426 attrs: &[ast::Attribute],
427 matcher: &[quoted::TokenTree]) -> bool {
428 let first_sets = FirstSets::new(matcher);
429 let empty_suffix = TokenSet::empty();
430 let err = sess.span_diagnostic.err_count();
431 check_matcher_core(sess, features, attrs, &first_sets, matcher, &empty_suffix);
432 err == sess.span_diagnostic.err_count()
435 // The FirstSets for a matcher is a mapping from subsequences in the
436 // matcher to the FIRST set for that subsequence.
438 // This mapping is partially precomputed via a backwards scan over the
439 // token trees of the matcher, which provides a mapping from each
440 // repetition sequence to its FIRST set.
442 // (Hypothetically sequences should be uniquely identifiable via their
443 // spans, though perhaps that is false e.g. for macro-generated macros
444 // that do not try to inject artificial span information. My plan is
445 // to try to catch such cases ahead of time and not include them in
446 // the precomputed mapping.)
448 // this maps each TokenTree::Sequence `$(tt ...) SEP OP` that is uniquely identified by its
449 // span in the original matcher to the First set for the inner sequence `tt ...`.
451 // If two sequences have the same span in a matcher, then map that
452 // span to None (invalidating the mapping here and forcing the code to
454 first: HashMap<Span, Option<TokenSet>>,
458 fn new(tts: &[quoted::TokenTree]) -> FirstSets {
459 use self::quoted::TokenTree;
461 let mut sets = FirstSets { first: HashMap::new() };
462 build_recur(&mut sets, tts);
465 // walks backward over `tts`, returning the FIRST for `tts`
466 // and updating `sets` at the same time for all sequence
467 // substructure we find within `tts`.
468 fn build_recur(sets: &mut FirstSets, tts: &[TokenTree]) -> TokenSet {
469 let mut first = TokenSet::empty();
470 for tt in tts.iter().rev() {
472 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
473 first.replace_with(tt.clone());
475 TokenTree::Delimited(span, ref delimited) => {
476 build_recur(sets, &delimited.tts[..]);
477 first.replace_with(delimited.open_tt(span));
479 TokenTree::Sequence(sp, ref seq_rep) => {
480 let subfirst = build_recur(sets, &seq_rep.tts[..]);
482 match sets.first.entry(sp) {
483 Entry::Vacant(vac) => {
484 vac.insert(Some(subfirst.clone()));
486 Entry::Occupied(mut occ) => {
487 // if there is already an entry, then a span must have collided.
488 // This should not happen with typical macro_rules macros,
489 // but syntax extensions need not maintain distinct spans,
490 // so distinct syntax trees can be assigned the same span.
491 // In such a case, the map cannot be trusted; so mark this
492 // entry as unusable.
497 // If the sequence contents can be empty, then the first
498 // token could be the separator token itself.
500 if let (Some(ref sep), true) = (seq_rep.separator.clone(),
501 subfirst.maybe_empty) {
502 first.add_one_maybe(TokenTree::Token(sp, sep.clone()));
505 // Reverse scan: Sequence comes before `first`.
506 if subfirst.maybe_empty || seq_rep.op == quoted::KleeneOp::ZeroOrMore {
507 // If sequence is potentially empty, then
508 // union them (preserving first emptiness).
509 first.add_all(&TokenSet { maybe_empty: true, ..subfirst });
511 // Otherwise, sequence guaranteed
512 // non-empty; replace first.
523 // walks forward over `tts` until all potential FIRST tokens are
525 fn first(&self, tts: &[quoted::TokenTree]) -> TokenSet {
526 use self::quoted::TokenTree;
528 let mut first = TokenSet::empty();
529 for tt in tts.iter() {
530 assert!(first.maybe_empty);
532 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
533 first.add_one(tt.clone());
536 TokenTree::Delimited(span, ref delimited) => {
537 first.add_one(delimited.open_tt(span));
540 TokenTree::Sequence(sp, ref seq_rep) => {
541 match self.first.get(&sp) {
542 Some(&Some(ref subfirst)) => {
544 // If the sequence contents can be empty, then the first
545 // token could be the separator token itself.
547 if let (Some(ref sep), true) = (seq_rep.separator.clone(),
548 subfirst.maybe_empty) {
549 first.add_one_maybe(TokenTree::Token(sp, sep.clone()));
552 assert!(first.maybe_empty);
553 first.add_all(subfirst);
554 if subfirst.maybe_empty ||
555 seq_rep.op == quoted::KleeneOp::ZeroOrMore {
556 // continue scanning for more first
557 // tokens, but also make sure we
558 // restore empty-tracking state
559 first.maybe_empty = true;
567 panic!("assume all sequences have (unique) spans for now");
571 panic!("We missed a sequence during FirstSets construction");
578 // we only exit the loop if `tts` was empty or if every
579 // element of `tts` matches the empty sequence.
580 assert!(first.maybe_empty);
585 // A set of `quoted::TokenTree`s, which may include `TokenTree::Match`s
586 // (for macro-by-example syntactic variables). It also carries the
587 // `maybe_empty` flag; that is true if and only if the matcher can
588 // match an empty token sequence.
590 // The First set is computed on submatchers like `$($a:expr b),* $(c)* d`,
591 // which has corresponding FIRST = {$a:expr, c, d}.
592 // Likewise, `$($a:expr b),* $(c)+ d` has FIRST = {$a:expr, c}.
594 // (Notably, we must allow for *-op to occur zero times.)
595 #[derive(Clone, Debug)]
597 tokens: Vec<quoted::TokenTree>,
602 // Returns a set for the empty sequence.
603 fn empty() -> Self { TokenSet { tokens: Vec::new(), maybe_empty: true } }
605 // Returns the set `{ tok }` for the single-token (and thus
606 // non-empty) sequence [tok].
607 fn singleton(tok: quoted::TokenTree) -> Self {
608 TokenSet { tokens: vec![tok], maybe_empty: false }
611 // Changes self to be the set `{ tok }`.
612 // Since `tok` is always present, marks self as non-empty.
613 fn replace_with(&mut self, tok: quoted::TokenTree) {
615 self.tokens.push(tok);
616 self.maybe_empty = false;
619 // Changes self to be the empty set `{}`; meant for use when
620 // the particular token does not matter, but we want to
621 // record that it occurs.
622 fn replace_with_irrelevant(&mut self) {
624 self.maybe_empty = false;
627 // Adds `tok` to the set for `self`, marking sequence as non-empy.
628 fn add_one(&mut self, tok: quoted::TokenTree) {
629 if !self.tokens.contains(&tok) {
630 self.tokens.push(tok);
632 self.maybe_empty = false;
635 // Adds `tok` to the set for `self`. (Leaves `maybe_empty` flag alone.)
636 fn add_one_maybe(&mut self, tok: quoted::TokenTree) {
637 if !self.tokens.contains(&tok) {
638 self.tokens.push(tok);
642 // Adds all elements of `other` to this.
644 // (Since this is a set, we filter out duplicates.)
646 // If `other` is potentially empty, then preserves the previous
647 // setting of the empty flag of `self`. If `other` is guaranteed
648 // non-empty, then `self` is marked non-empty.
649 fn add_all(&mut self, other: &Self) {
650 for tok in &other.tokens {
651 if !self.tokens.contains(tok) {
652 self.tokens.push(tok.clone());
655 if !other.maybe_empty {
656 self.maybe_empty = false;
661 // Checks that `matcher` is internally consistent and that it
662 // can legally by followed by a token N, for all N in `follow`.
663 // (If `follow` is empty, then it imposes no constraint on
666 // Returns the set of NT tokens that could possibly come last in
667 // `matcher`. (If `matcher` matches the empty sequence, then
668 // `maybe_empty` will be set to true.)
670 // Requires that `first_sets` is pre-computed for `matcher`;
671 // see `FirstSets::new`.
672 fn check_matcher_core(sess: &ParseSess,
674 attrs: &[ast::Attribute],
675 first_sets: &FirstSets,
676 matcher: &[quoted::TokenTree],
677 follow: &TokenSet) -> TokenSet {
678 use self::quoted::TokenTree;
680 let mut last = TokenSet::empty();
682 // 2. For each token and suffix [T, SUFFIX] in M:
683 // ensure that T can be followed by SUFFIX, and if SUFFIX may be empty,
684 // then ensure T can also be followed by any element of FOLLOW.
685 'each_token: for i in 0..matcher.len() {
686 let token = &matcher[i];
687 let suffix = &matcher[i+1..];
689 let build_suffix_first = || {
690 let mut s = first_sets.first(suffix);
691 if s.maybe_empty { s.add_all(follow); }
695 // (we build `suffix_first` on demand below; you can tell
696 // which cases are supposed to fall through by looking for the
697 // initialization of this variable.)
700 // First, update `last` so that it corresponds to the set
701 // of NT tokens that might end the sequence `... token`.
703 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
704 let can_be_followed_by_any;
705 if let Err(bad_frag) = has_legal_fragment_specifier(sess, features, attrs, token) {
706 let msg = format!("invalid fragment specifier `{}`", bad_frag);
707 sess.span_diagnostic.struct_span_err(token.span(), &msg)
708 .help("valid fragment specifiers are `ident`, `block`, `stmt`, `expr`, \
709 `pat`, `ty`, `literal`, `path`, `meta`, `tt`, `item` and `vis`")
711 // (This eliminates false positives and duplicates
712 // from error messages.)
713 can_be_followed_by_any = true;
715 can_be_followed_by_any = token_can_be_followed_by_any(token);
718 if can_be_followed_by_any {
719 // don't need to track tokens that work with any,
720 last.replace_with_irrelevant();
721 // ... and don't need to check tokens that can be
722 // followed by anything against SUFFIX.
723 continue 'each_token;
725 last.replace_with(token.clone());
726 suffix_first = build_suffix_first();
729 TokenTree::Delimited(span, ref d) => {
730 let my_suffix = TokenSet::singleton(d.close_tt(span));
731 check_matcher_core(sess, features, attrs, first_sets, &d.tts, &my_suffix);
732 // don't track non NT tokens
733 last.replace_with_irrelevant();
735 // also, we don't need to check delimited sequences
737 continue 'each_token;
739 TokenTree::Sequence(sp, ref seq_rep) => {
740 suffix_first = build_suffix_first();
741 // The trick here: when we check the interior, we want
742 // to include the separator (if any) as a potential
743 // (but not guaranteed) element of FOLLOW. So in that
744 // case, we make a temp copy of suffix and stuff
745 // delimiter in there.
747 // FIXME: Should I first scan suffix_first to see if
748 // delimiter is already in it before I go through the
749 // work of cloning it? But then again, this way I may
750 // get a "tighter" span?
752 let my_suffix = if let Some(ref u) = seq_rep.separator {
753 new = suffix_first.clone();
754 new.add_one_maybe(TokenTree::Token(sp, u.clone()));
760 // At this point, `suffix_first` is built, and
761 // `my_suffix` is some TokenSet that we can use
762 // for checking the interior of `seq_rep`.
763 let next = check_matcher_core(sess,
769 if next.maybe_empty {
775 // the recursive call to check_matcher_core already ran the 'each_last
776 // check below, so we can just keep going forward here.
777 continue 'each_token;
781 // (`suffix_first` guaranteed initialized once reaching here.)
783 // Now `last` holds the complete set of NT tokens that could
784 // end the sequence before SUFFIX. Check that every one works with `suffix`.
785 'each_last: for token in &last.tokens {
786 if let TokenTree::MetaVarDecl(_, ref name, ref frag_spec) = *token {
787 for next_token in &suffix_first.tokens {
788 match is_in_follow(next_token, &frag_spec.as_str()) {
789 Err((msg, help)) => {
790 sess.span_diagnostic.struct_span_err(next_token.span(), &msg)
792 // don't bother reporting every source of
793 // conflict for a particular element of `last`.
798 let may_be = if last.tokens.len() == 1 &&
799 suffix_first.tokens.len() == 1
806 sess.span_diagnostic.span_err(
808 &format!("`${name}:{frag}` {may_be} followed by `{next}`, which \
809 is not allowed for `{frag}` fragments",
812 next=quoted_tt_to_string(next_token),
824 fn token_can_be_followed_by_any(tok: "ed::TokenTree) -> bool {
825 if let quoted::TokenTree::MetaVarDecl(_, _, frag_spec) = *tok {
826 frag_can_be_followed_by_any(&frag_spec.as_str())
828 // (Non NT's can always be followed by anthing in matchers.)
833 /// True if a fragment of type `frag` can be followed by any sort of
834 /// token. We use this (among other things) as a useful approximation
835 /// for when `frag` can be followed by a repetition like `$(...)*` or
836 /// `$(...)+`. In general, these can be a bit tricky to reason about,
837 /// so we adopt a conservative position that says that any fragment
838 /// specifier which consumes at most one token tree can be followed by
839 /// a fragment specifier (indeed, these fragments can be followed by
840 /// ANYTHING without fear of future compatibility hazards).
841 fn frag_can_be_followed_by_any(frag: &str) -> bool {
843 "item" | // always terminated by `}` or `;`
844 "block" | // exactly one token tree
845 "ident" | // exactly one token tree
846 "literal" | // exactly one token tree
847 "meta" | // exactly one token tree
848 "lifetime" | // exactly one token tree
849 "tt" => // exactly one token tree
857 /// True if `frag` can legally be followed by the token `tok`. For
858 /// fragments that can consume an unbounded number of tokens, `tok`
859 /// must be within a well-defined follow set. This is intended to
860 /// guarantee future compatibility: for example, without this rule, if
861 /// we expanded `expr` to include a new binary operator, we might
862 /// break macros that were relying on that binary operator as a
864 // when changing this do not forget to update doc/book/macros.md!
865 fn is_in_follow(tok: "ed::TokenTree, frag: &str) -> Result<bool, (String, &'static str)> {
866 use self::quoted::TokenTree;
868 if let TokenTree::Token(_, token::CloseDelim(_)) = *tok {
869 // closing a token tree can never be matched by any fragment;
870 // iow, we always require that `(` and `)` match, etc.
875 // since items *must* be followed by either a `;` or a `}`, we can
876 // accept anything after them
880 // anything can follow block, the braces provide an easy boundary to
884 "stmt" | "expr" => match *tok {
885 TokenTree::Token(_, ref tok) => match *tok {
886 FatArrow | Comma | Semi => Ok(true),
891 "pat" => match *tok {
892 TokenTree::Token(_, ref tok) => match *tok {
893 FatArrow | Comma | Eq | BinOp(token::Or) => Ok(true),
894 Ident(i, false) if i.name == "if" || i.name == "in" => Ok(true),
899 "path" | "ty" => match *tok {
900 TokenTree::Token(_, ref tok) => match *tok {
901 OpenDelim(token::DelimToken::Brace) | OpenDelim(token::DelimToken::Bracket) |
902 Comma | FatArrow | Colon | Eq | Gt | Semi | BinOp(token::Or) => Ok(true),
903 Ident(i, false) if i.name == "as" || i.name == "where" => Ok(true),
906 TokenTree::MetaVarDecl(_, _, frag) if frag.name == "block" => Ok(true),
909 "ident" | "lifetime" => {
910 // being a single token, idents and lifetimes are harmless
914 // literals may be of a single token, or two tokens (negative numbers)
918 // being either a single token or a delimited sequence, tt is
923 // Explicitly disallow `priv`, on the off chance it comes back.
925 TokenTree::Token(_, ref tok) => match *tok {
927 Ident(i, is_raw) if is_raw || i.name != "priv" => Ok(true),
928 ref tok => Ok(tok.can_begin_type())
930 TokenTree::MetaVarDecl(_, _, frag) if frag.name == "ident"
932 || frag.name == "path" => Ok(true),
936 "" => Ok(true), // keywords::Invalid
937 _ => Err((format!("invalid fragment specifier `{}`", frag),
938 "valid fragment specifiers are `ident`, `block`, \
939 `stmt`, `expr`, `pat`, `ty`, `path`, `meta`, `tt`, \
940 `literal`, `item` and `vis`"))
945 fn has_legal_fragment_specifier(sess: &ParseSess,
947 attrs: &[ast::Attribute],
948 tok: "ed::TokenTree) -> Result<(), String> {
949 debug!("has_legal_fragment_specifier({:?})", tok);
950 if let quoted::TokenTree::MetaVarDecl(_, _, ref frag_spec) = *tok {
951 let frag_name = frag_spec.as_str();
952 let frag_span = tok.span();
953 if !is_legal_fragment_specifier(sess, features, attrs, &frag_name, frag_span) {
954 return Err(frag_name.to_string());
960 fn is_legal_fragment_specifier(sess: &ParseSess,
962 attrs: &[ast::Attribute],
964 frag_span: Span) -> bool {
966 "item" | "block" | "stmt" | "expr" | "pat" | "lifetime" |
967 "path" | "ty" | "ident" | "meta" | "tt" | "" => true,
969 if !features.macro_literal_matcher &&
970 !attr::contains_name(attrs, "allow_internal_unstable") {
971 let explain = feature_gate::EXPLAIN_LITERAL_MATCHER;
972 emit_feature_err(sess,
973 "macro_literal_matcher",
981 if !features.macro_vis_matcher &&
982 !attr::contains_name(attrs, "allow_internal_unstable") {
983 let explain = feature_gate::EXPLAIN_VIS_MATCHER;
984 emit_feature_err(sess,
996 fn quoted_tt_to_string(tt: "ed::TokenTree) -> String {
998 quoted::TokenTree::Token(_, ref tok) => ::print::pprust::token_to_string(tok),
999 quoted::TokenTree::MetaVar(_, name) => format!("${}", name),
1000 quoted::TokenTree::MetaVarDecl(_, name, kind) => format!("${}:{}", name, kind),
1001 _ => panic!("unexpected quoted::TokenTree::{{Sequence or Delimited}} \
1002 in follow set checker"),