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 let mut err = cx.struct_span_err(best_fail_spot.substitute_dummy(sp), &best_fail_msg);
179 // Check whether there's a missing comma in this macro call, like `println!("{}" a);`
180 if let Some((arg, comma_span)) = arg.add_comma() {
181 for lhs in lhses { // try each arm's matchers
182 let lhs_tt = match *lhs {
183 quoted::TokenTree::Delimited(_, ref delim) => &delim.tts[..],
184 _ => cx.span_bug(sp, "malformed macro lhs")
186 match TokenTree::parse(cx, lhs_tt, arg.clone()) {
188 if comma_span == DUMMY_SP {
189 err.note("you might be missing a comma");
191 err.span_suggestion_short(
193 "missing comma here",
203 cx.trace_macros_diag();
207 // Note that macro-by-example's input is also matched against a token tree:
208 // $( $lhs:tt => $rhs:tt );+
210 // Holy self-referential!
212 /// Converts a `macro_rules!` invocation into a syntax extension.
213 pub fn compile(sess: &ParseSess, features: &Features, def: &ast::Item, edition: Edition)
215 let lhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("lhs"));
216 let rhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("rhs"));
218 // Parse the macro_rules! invocation
219 let body = match def.node {
220 ast::ItemKind::MacroDef(ref body) => body,
224 // The pattern that macro_rules matches.
225 // The grammar for macro_rules! is:
226 // $( $lhs:tt => $rhs:tt );+
227 // ...quasiquoting this would be nice.
228 // These spans won't matter, anyways
229 let argument_gram = vec![
230 quoted::TokenTree::Sequence(DUMMY_SP, Lrc::new(quoted::SequenceRepetition {
232 quoted::TokenTree::MetaVarDecl(DUMMY_SP, lhs_nm, ast::Ident::from_str("tt")),
233 quoted::TokenTree::Token(DUMMY_SP, token::FatArrow),
234 quoted::TokenTree::MetaVarDecl(DUMMY_SP, rhs_nm, ast::Ident::from_str("tt")),
236 separator: Some(if body.legacy { token::Semi } else { token::Comma }),
237 op: quoted::KleeneOp::OneOrMore,
240 // to phase into semicolon-termination instead of semicolon-separation
241 quoted::TokenTree::Sequence(DUMMY_SP, Lrc::new(quoted::SequenceRepetition {
242 tts: vec![quoted::TokenTree::Token(DUMMY_SP, token::Semi)],
244 op: quoted::KleeneOp::ZeroOrMore,
249 let argument_map = match parse(sess, body.stream(), &argument_gram, None, true) {
251 Failure(sp, tok) => {
252 let s = parse_failure_msg(tok);
253 sess.span_diagnostic.span_fatal(sp.substitute_dummy(def.span), &s).raise();
256 sess.span_diagnostic.span_fatal(sp.substitute_dummy(def.span), &s).raise();
260 let mut valid = true;
262 // Extract the arguments:
263 let lhses = match *argument_map[&lhs_nm] {
264 MatchedSeq(ref s, _) => {
266 if let MatchedNonterminal(ref nt) = *m {
267 if let NtTT(ref tt) = **nt {
268 let tt = quoted::parse(
279 valid &= check_lhs_nt_follows(sess, features, &def.attrs, &tt);
283 sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
284 }).collect::<Vec<quoted::TokenTree>>()
286 _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
289 let rhses = match *argument_map[&rhs_nm] {
290 MatchedSeq(ref s, _) => {
292 if let MatchedNonterminal(ref nt) = *m {
293 if let NtTT(ref tt) = **nt {
294 return quoted::parse(
306 sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
307 }).collect::<Vec<quoted::TokenTree>>()
309 _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured rhs")
313 valid &= check_rhs(sess, rhs);
316 // don't abort iteration early, so that errors for multiple lhses can be reported
318 valid &= check_lhs_no_empty_seq(sess, &[lhs.clone()])
321 let expander: Box<_> = Box::new(MacroRulesMacroExpander {
329 let allow_internal_unstable = attr::contains_name(&def.attrs, "allow_internal_unstable");
330 let allow_internal_unsafe = attr::contains_name(&def.attrs, "allow_internal_unsafe");
331 let mut local_inner_macros = false;
332 if let Some(macro_export) = attr::find_by_name(&def.attrs, "macro_export") {
333 if let Some(l) = macro_export.meta_item_list() {
334 local_inner_macros = attr::list_contains_name(&l, "local_inner_macros");
338 let unstable_feature = attr::find_stability(&sess.span_diagnostic,
339 &def.attrs, def.span).and_then(|stability| {
340 if let attr::StabilityLevel::Unstable { issue, .. } = stability.level {
341 Some((stability.feature, issue))
349 def_info: Some((def.id, def.span)),
350 allow_internal_unstable,
351 allow_internal_unsafe,
357 let is_transparent = attr::contains_name(&def.attrs, "rustc_transparent_macro");
359 SyntaxExtension::DeclMacro {
361 def_info: Some((def.id, def.span)),
368 fn check_lhs_nt_follows(sess: &ParseSess,
370 attrs: &[ast::Attribute],
371 lhs: "ed::TokenTree) -> bool {
372 // lhs is going to be like TokenTree::Delimited(...), where the
373 // entire lhs is those tts. Or, it can be a "bare sequence", not wrapped in parens.
374 if let quoted::TokenTree::Delimited(_, ref tts) = *lhs {
375 check_matcher(sess, features, attrs, &tts.tts)
377 let msg = "invalid macro matcher; matchers must be contained in balanced delimiters";
378 sess.span_diagnostic.span_err(lhs.span(), msg);
381 // we don't abort on errors on rejection, the driver will do that for us
382 // after parsing/expansion. we can report every error in every macro this way.
385 /// Check that the lhs contains no repetition which could match an empty token
386 /// tree, because then the matcher would hang indefinitely.
387 fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[quoted::TokenTree]) -> bool {
388 use self::quoted::TokenTree;
391 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => (),
392 TokenTree::Delimited(_, ref del) => if !check_lhs_no_empty_seq(sess, &del.tts) {
395 TokenTree::Sequence(span, ref seq) => {
396 if seq.separator.is_none() && seq.tts.iter().all(|seq_tt| {
398 TokenTree::MetaVarDecl(_, _, id) => id.name == "vis",
399 TokenTree::Sequence(_, ref sub_seq) =>
400 sub_seq.op == quoted::KleeneOp::ZeroOrMore,
404 sess.span_diagnostic.span_err(span, "repetition matches empty token tree");
407 if !check_lhs_no_empty_seq(sess, &seq.tts) {
417 fn check_rhs(sess: &ParseSess, rhs: "ed::TokenTree) -> bool {
419 quoted::TokenTree::Delimited(..) => return true,
420 _ => sess.span_diagnostic.span_err(rhs.span(), "macro rhs must be delimited")
425 fn check_matcher(sess: &ParseSess,
427 attrs: &[ast::Attribute],
428 matcher: &[quoted::TokenTree]) -> bool {
429 let first_sets = FirstSets::new(matcher);
430 let empty_suffix = TokenSet::empty();
431 let err = sess.span_diagnostic.err_count();
432 check_matcher_core(sess, features, attrs, &first_sets, matcher, &empty_suffix);
433 err == sess.span_diagnostic.err_count()
436 // The FirstSets for a matcher is a mapping from subsequences in the
437 // matcher to the FIRST set for that subsequence.
439 // This mapping is partially precomputed via a backwards scan over the
440 // token trees of the matcher, which provides a mapping from each
441 // repetition sequence to its FIRST set.
443 // (Hypothetically sequences should be uniquely identifiable via their
444 // spans, though perhaps that is false e.g. for macro-generated macros
445 // that do not try to inject artificial span information. My plan is
446 // to try to catch such cases ahead of time and not include them in
447 // the precomputed mapping.)
449 // this maps each TokenTree::Sequence `$(tt ...) SEP OP` that is uniquely identified by its
450 // span in the original matcher to the First set for the inner sequence `tt ...`.
452 // If two sequences have the same span in a matcher, then map that
453 // span to None (invalidating the mapping here and forcing the code to
455 first: HashMap<Span, Option<TokenSet>>,
459 fn new(tts: &[quoted::TokenTree]) -> FirstSets {
460 use self::quoted::TokenTree;
462 let mut sets = FirstSets { first: HashMap::new() };
463 build_recur(&mut sets, tts);
466 // walks backward over `tts`, returning the FIRST for `tts`
467 // and updating `sets` at the same time for all sequence
468 // substructure we find within `tts`.
469 fn build_recur(sets: &mut FirstSets, tts: &[TokenTree]) -> TokenSet {
470 let mut first = TokenSet::empty();
471 for tt in tts.iter().rev() {
473 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
474 first.replace_with(tt.clone());
476 TokenTree::Delimited(span, ref delimited) => {
477 build_recur(sets, &delimited.tts[..]);
478 first.replace_with(delimited.open_tt(span));
480 TokenTree::Sequence(sp, ref seq_rep) => {
481 let subfirst = build_recur(sets, &seq_rep.tts[..]);
483 match sets.first.entry(sp) {
484 Entry::Vacant(vac) => {
485 vac.insert(Some(subfirst.clone()));
487 Entry::Occupied(mut occ) => {
488 // if there is already an entry, then a span must have collided.
489 // This should not happen with typical macro_rules macros,
490 // but syntax extensions need not maintain distinct spans,
491 // so distinct syntax trees can be assigned the same span.
492 // In such a case, the map cannot be trusted; so mark this
493 // entry as unusable.
498 // If the sequence contents can be empty, then the first
499 // token could be the separator token itself.
501 if let (Some(ref sep), true) = (seq_rep.separator.clone(),
502 subfirst.maybe_empty) {
503 first.add_one_maybe(TokenTree::Token(sp, sep.clone()));
506 // Reverse scan: Sequence comes before `first`.
507 if subfirst.maybe_empty || seq_rep.op == quoted::KleeneOp::ZeroOrMore {
508 // If sequence is potentially empty, then
509 // union them (preserving first emptiness).
510 first.add_all(&TokenSet { maybe_empty: true, ..subfirst });
512 // Otherwise, sequence guaranteed
513 // non-empty; replace first.
524 // walks forward over `tts` until all potential FIRST tokens are
526 fn first(&self, tts: &[quoted::TokenTree]) -> TokenSet {
527 use self::quoted::TokenTree;
529 let mut first = TokenSet::empty();
530 for tt in tts.iter() {
531 assert!(first.maybe_empty);
533 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
534 first.add_one(tt.clone());
537 TokenTree::Delimited(span, ref delimited) => {
538 first.add_one(delimited.open_tt(span));
541 TokenTree::Sequence(sp, ref seq_rep) => {
542 match self.first.get(&sp) {
543 Some(&Some(ref subfirst)) => {
545 // If the sequence contents can be empty, then the first
546 // token could be the separator token itself.
548 if let (Some(ref sep), true) = (seq_rep.separator.clone(),
549 subfirst.maybe_empty) {
550 first.add_one_maybe(TokenTree::Token(sp, sep.clone()));
553 assert!(first.maybe_empty);
554 first.add_all(subfirst);
555 if subfirst.maybe_empty ||
556 seq_rep.op == quoted::KleeneOp::ZeroOrMore {
557 // continue scanning for more first
558 // tokens, but also make sure we
559 // restore empty-tracking state
560 first.maybe_empty = true;
568 panic!("assume all sequences have (unique) spans for now");
572 panic!("We missed a sequence during FirstSets construction");
579 // we only exit the loop if `tts` was empty or if every
580 // element of `tts` matches the empty sequence.
581 assert!(first.maybe_empty);
586 // A set of `quoted::TokenTree`s, which may include `TokenTree::Match`s
587 // (for macro-by-example syntactic variables). It also carries the
588 // `maybe_empty` flag; that is true if and only if the matcher can
589 // match an empty token sequence.
591 // The First set is computed on submatchers like `$($a:expr b),* $(c)* d`,
592 // which has corresponding FIRST = {$a:expr, c, d}.
593 // Likewise, `$($a:expr b),* $(c)+ d` has FIRST = {$a:expr, c}.
595 // (Notably, we must allow for *-op to occur zero times.)
596 #[derive(Clone, Debug)]
598 tokens: Vec<quoted::TokenTree>,
603 // Returns a set for the empty sequence.
604 fn empty() -> Self { TokenSet { tokens: Vec::new(), maybe_empty: true } }
606 // Returns the set `{ tok }` for the single-token (and thus
607 // non-empty) sequence [tok].
608 fn singleton(tok: quoted::TokenTree) -> Self {
609 TokenSet { tokens: vec![tok], maybe_empty: false }
612 // Changes self to be the set `{ tok }`.
613 // Since `tok` is always present, marks self as non-empty.
614 fn replace_with(&mut self, tok: quoted::TokenTree) {
616 self.tokens.push(tok);
617 self.maybe_empty = false;
620 // Changes self to be the empty set `{}`; meant for use when
621 // the particular token does not matter, but we want to
622 // record that it occurs.
623 fn replace_with_irrelevant(&mut self) {
625 self.maybe_empty = false;
628 // Adds `tok` to the set for `self`, marking sequence as non-empy.
629 fn add_one(&mut self, tok: quoted::TokenTree) {
630 if !self.tokens.contains(&tok) {
631 self.tokens.push(tok);
633 self.maybe_empty = false;
636 // Adds `tok` to the set for `self`. (Leaves `maybe_empty` flag alone.)
637 fn add_one_maybe(&mut self, tok: quoted::TokenTree) {
638 if !self.tokens.contains(&tok) {
639 self.tokens.push(tok);
643 // Adds all elements of `other` to this.
645 // (Since this is a set, we filter out duplicates.)
647 // If `other` is potentially empty, then preserves the previous
648 // setting of the empty flag of `self`. If `other` is guaranteed
649 // non-empty, then `self` is marked non-empty.
650 fn add_all(&mut self, other: &Self) {
651 for tok in &other.tokens {
652 if !self.tokens.contains(tok) {
653 self.tokens.push(tok.clone());
656 if !other.maybe_empty {
657 self.maybe_empty = false;
662 // Checks that `matcher` is internally consistent and that it
663 // can legally by followed by a token N, for all N in `follow`.
664 // (If `follow` is empty, then it imposes no constraint on
667 // Returns the set of NT tokens that could possibly come last in
668 // `matcher`. (If `matcher` matches the empty sequence, then
669 // `maybe_empty` will be set to true.)
671 // Requires that `first_sets` is pre-computed for `matcher`;
672 // see `FirstSets::new`.
673 fn check_matcher_core(sess: &ParseSess,
675 attrs: &[ast::Attribute],
676 first_sets: &FirstSets,
677 matcher: &[quoted::TokenTree],
678 follow: &TokenSet) -> TokenSet {
679 use self::quoted::TokenTree;
681 let mut last = TokenSet::empty();
683 // 2. For each token and suffix [T, SUFFIX] in M:
684 // ensure that T can be followed by SUFFIX, and if SUFFIX may be empty,
685 // then ensure T can also be followed by any element of FOLLOW.
686 'each_token: for i in 0..matcher.len() {
687 let token = &matcher[i];
688 let suffix = &matcher[i+1..];
690 let build_suffix_first = || {
691 let mut s = first_sets.first(suffix);
692 if s.maybe_empty { s.add_all(follow); }
696 // (we build `suffix_first` on demand below; you can tell
697 // which cases are supposed to fall through by looking for the
698 // initialization of this variable.)
701 // First, update `last` so that it corresponds to the set
702 // of NT tokens that might end the sequence `... token`.
704 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
705 let can_be_followed_by_any;
706 if let Err(bad_frag) = has_legal_fragment_specifier(sess, features, attrs, token) {
707 let msg = format!("invalid fragment specifier `{}`", bad_frag);
708 sess.span_diagnostic.struct_span_err(token.span(), &msg)
709 .help("valid fragment specifiers are `ident`, `block`, `stmt`, `expr`, \
710 `pat`, `ty`, `literal`, `path`, `meta`, `tt`, `item` and `vis`")
712 // (This eliminates false positives and duplicates
713 // from error messages.)
714 can_be_followed_by_any = true;
716 can_be_followed_by_any = token_can_be_followed_by_any(token);
719 if can_be_followed_by_any {
720 // don't need to track tokens that work with any,
721 last.replace_with_irrelevant();
722 // ... and don't need to check tokens that can be
723 // followed by anything against SUFFIX.
724 continue 'each_token;
726 last.replace_with(token.clone());
727 suffix_first = build_suffix_first();
730 TokenTree::Delimited(span, ref d) => {
731 let my_suffix = TokenSet::singleton(d.close_tt(span));
732 check_matcher_core(sess, features, attrs, first_sets, &d.tts, &my_suffix);
733 // don't track non NT tokens
734 last.replace_with_irrelevant();
736 // also, we don't need to check delimited sequences
738 continue 'each_token;
740 TokenTree::Sequence(sp, ref seq_rep) => {
741 suffix_first = build_suffix_first();
742 // The trick here: when we check the interior, we want
743 // to include the separator (if any) as a potential
744 // (but not guaranteed) element of FOLLOW. So in that
745 // case, we make a temp copy of suffix and stuff
746 // delimiter in there.
748 // FIXME: Should I first scan suffix_first to see if
749 // delimiter is already in it before I go through the
750 // work of cloning it? But then again, this way I may
751 // get a "tighter" span?
753 let my_suffix = if let Some(ref u) = seq_rep.separator {
754 new = suffix_first.clone();
755 new.add_one_maybe(TokenTree::Token(sp, u.clone()));
761 // At this point, `suffix_first` is built, and
762 // `my_suffix` is some TokenSet that we can use
763 // for checking the interior of `seq_rep`.
764 let next = check_matcher_core(sess,
770 if next.maybe_empty {
776 // the recursive call to check_matcher_core already ran the 'each_last
777 // check below, so we can just keep going forward here.
778 continue 'each_token;
782 // (`suffix_first` guaranteed initialized once reaching here.)
784 // Now `last` holds the complete set of NT tokens that could
785 // end the sequence before SUFFIX. Check that every one works with `suffix`.
786 'each_last: for token in &last.tokens {
787 if let TokenTree::MetaVarDecl(_, ref name, ref frag_spec) = *token {
788 for next_token in &suffix_first.tokens {
789 match is_in_follow(next_token, &frag_spec.as_str()) {
790 Err((msg, help)) => {
791 sess.span_diagnostic.struct_span_err(next_token.span(), &msg)
793 // don't bother reporting every source of
794 // conflict for a particular element of `last`.
799 let may_be = if last.tokens.len() == 1 &&
800 suffix_first.tokens.len() == 1
807 sess.span_diagnostic.span_err(
809 &format!("`${name}:{frag}` {may_be} followed by `{next}`, which \
810 is not allowed for `{frag}` fragments",
813 next=quoted_tt_to_string(next_token),
825 fn token_can_be_followed_by_any(tok: "ed::TokenTree) -> bool {
826 if let quoted::TokenTree::MetaVarDecl(_, _, frag_spec) = *tok {
827 frag_can_be_followed_by_any(&frag_spec.as_str())
829 // (Non NT's can always be followed by anthing in matchers.)
834 /// True if a fragment of type `frag` can be followed by any sort of
835 /// token. We use this (among other things) as a useful approximation
836 /// for when `frag` can be followed by a repetition like `$(...)*` or
837 /// `$(...)+`. In general, these can be a bit tricky to reason about,
838 /// so we adopt a conservative position that says that any fragment
839 /// specifier which consumes at most one token tree can be followed by
840 /// a fragment specifier (indeed, these fragments can be followed by
841 /// ANYTHING without fear of future compatibility hazards).
842 fn frag_can_be_followed_by_any(frag: &str) -> bool {
844 "item" | // always terminated by `}` or `;`
845 "block" | // exactly one token tree
846 "ident" | // exactly one token tree
847 "literal" | // exactly one token tree
848 "meta" | // exactly one token tree
849 "lifetime" | // exactly one token tree
850 "tt" => // exactly one token tree
858 /// True if `frag` can legally be followed by the token `tok`. For
859 /// fragments that can consume an unbounded number of tokens, `tok`
860 /// must be within a well-defined follow set. This is intended to
861 /// guarantee future compatibility: for example, without this rule, if
862 /// we expanded `expr` to include a new binary operator, we might
863 /// break macros that were relying on that binary operator as a
865 // when changing this do not forget to update doc/book/macros.md!
866 fn is_in_follow(tok: "ed::TokenTree, frag: &str) -> Result<bool, (String, &'static str)> {
867 use self::quoted::TokenTree;
869 if let TokenTree::Token(_, token::CloseDelim(_)) = *tok {
870 // closing a token tree can never be matched by any fragment;
871 // iow, we always require that `(` and `)` match, etc.
876 // since items *must* be followed by either a `;` or a `}`, we can
877 // accept anything after them
881 // anything can follow block, the braces provide an easy boundary to
885 "stmt" | "expr" => match *tok {
886 TokenTree::Token(_, ref tok) => match *tok {
887 FatArrow | Comma | Semi => Ok(true),
892 "pat" => match *tok {
893 TokenTree::Token(_, ref tok) => match *tok {
894 FatArrow | Comma | Eq | BinOp(token::Or) => Ok(true),
895 Ident(i, false) if i.name == "if" || i.name == "in" => Ok(true),
900 "path" | "ty" => match *tok {
901 TokenTree::Token(_, ref tok) => match *tok {
902 OpenDelim(token::DelimToken::Brace) | OpenDelim(token::DelimToken::Bracket) |
903 Comma | FatArrow | Colon | Eq | Gt | Semi | BinOp(token::Or) => Ok(true),
904 Ident(i, false) if i.name == "as" || i.name == "where" => Ok(true),
907 TokenTree::MetaVarDecl(_, _, frag) if frag.name == "block" => Ok(true),
910 "ident" | "lifetime" => {
911 // being a single token, idents and lifetimes are harmless
915 // literals may be of a single token, or two tokens (negative numbers)
919 // being either a single token or a delimited sequence, tt is
924 // Explicitly disallow `priv`, on the off chance it comes back.
926 TokenTree::Token(_, ref tok) => match *tok {
928 Ident(i, is_raw) if is_raw || i.name != "priv" => Ok(true),
929 ref tok => Ok(tok.can_begin_type())
931 TokenTree::MetaVarDecl(_, _, frag) if frag.name == "ident"
933 || frag.name == "path" => Ok(true),
937 "" => Ok(true), // keywords::Invalid
938 _ => Err((format!("invalid fragment specifier `{}`", frag),
939 "valid fragment specifiers are `ident`, `block`, \
940 `stmt`, `expr`, `pat`, `ty`, `path`, `meta`, `tt`, \
941 `literal`, `item` and `vis`"))
946 fn has_legal_fragment_specifier(sess: &ParseSess,
948 attrs: &[ast::Attribute],
949 tok: "ed::TokenTree) -> Result<(), String> {
950 debug!("has_legal_fragment_specifier({:?})", tok);
951 if let quoted::TokenTree::MetaVarDecl(_, _, ref frag_spec) = *tok {
952 let frag_name = frag_spec.as_str();
953 let frag_span = tok.span();
954 if !is_legal_fragment_specifier(sess, features, attrs, &frag_name, frag_span) {
955 return Err(frag_name.to_string());
961 fn is_legal_fragment_specifier(sess: &ParseSess,
963 attrs: &[ast::Attribute],
965 frag_span: Span) -> bool {
967 "item" | "block" | "stmt" | "expr" | "pat" | "lifetime" |
968 "path" | "ty" | "ident" | "meta" | "tt" | "" => true,
970 if !features.macro_literal_matcher &&
971 !attr::contains_name(attrs, "allow_internal_unstable") {
972 let explain = feature_gate::EXPLAIN_LITERAL_MATCHER;
973 emit_feature_err(sess,
974 "macro_literal_matcher",
982 if !features.macro_vis_matcher &&
983 !attr::contains_name(attrs, "allow_internal_unstable") {
984 let explain = feature_gate::EXPLAIN_VIS_MATCHER;
985 emit_feature_err(sess,
997 fn quoted_tt_to_string(tt: "ed::TokenTree) -> String {
999 quoted::TokenTree::Token(_, ref tok) => ::print::pprust::token_to_string(tok),
1000 quoted::TokenTree::MetaVar(_, name) => format!("${}", name),
1001 quoted::TokenTree::MetaVarDecl(_, name, kind) => format!("${}:{}", name, kind),
1002 _ => panic!("unexpected quoted::TokenTree::{{Sequence or Delimited}} \
1003 in follow set checker"),