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<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<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(tt.clone().into(), true, sess, features, &def.attrs)
245 valid &= check_lhs_nt_follows(sess, features, &def.attrs, &tt);
249 sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
250 }).collect::<Vec<quoted::TokenTree>>()
252 _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
255 let rhses = match *argument_map[&rhs_nm] {
256 MatchedSeq(ref s, _) => {
258 if let MatchedNonterminal(ref nt) = *m {
259 if let NtTT(ref tt) = **nt {
260 return quoted::parse(tt.clone().into(), false, sess, features, &def.attrs)
264 sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
265 }).collect::<Vec<quoted::TokenTree>>()
267 _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured rhs")
271 valid &= check_rhs(sess, rhs);
274 // don't abort iteration early, so that errors for multiple lhses can be reported
276 valid &= check_lhs_no_empty_seq(sess, &[lhs.clone()])
279 let expander: Box<_> = Box::new(MacroRulesMacroExpander {
287 let allow_internal_unstable = attr::contains_name(&def.attrs, "allow_internal_unstable");
288 let allow_internal_unsafe = attr::contains_name(&def.attrs, "allow_internal_unsafe");
289 let mut local_inner_macros = false;
290 if let Some(macro_export) = attr::find_by_name(&def.attrs, "macro_export") {
291 if let Some(l) = macro_export.meta_item_list() {
292 local_inner_macros = attr::list_contains_name(&l, "local_inner_macros");
296 let unstable_feature = attr::find_stability(&sess.span_diagnostic,
297 &def.attrs, def.span).and_then(|stability| {
298 if let attr::StabilityLevel::Unstable { issue, .. } = stability.level {
299 Some((stability.feature, issue))
307 def_info: Some((def.id, def.span)),
308 allow_internal_unstable,
309 allow_internal_unsafe,
315 let is_transparent = attr::contains_name(&def.attrs, "rustc_transparent_macro");
317 SyntaxExtension::DeclMacro {
319 def_info: Some((def.id, def.span)),
326 fn check_lhs_nt_follows(sess: &ParseSess,
328 attrs: &[ast::Attribute],
329 lhs: "ed::TokenTree) -> bool {
330 // lhs is going to be like TokenTree::Delimited(...), where the
331 // entire lhs is those tts. Or, it can be a "bare sequence", not wrapped in parens.
332 if let quoted::TokenTree::Delimited(_, ref tts) = *lhs {
333 check_matcher(sess, features, attrs, &tts.tts)
335 let msg = "invalid macro matcher; matchers must be contained in balanced delimiters";
336 sess.span_diagnostic.span_err(lhs.span(), msg);
339 // we don't abort on errors on rejection, the driver will do that for us
340 // after parsing/expansion. we can report every error in every macro this way.
343 /// Check that the lhs contains no repetition which could match an empty token
344 /// tree, because then the matcher would hang indefinitely.
345 fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[quoted::TokenTree]) -> bool {
346 use self::quoted::TokenTree;
349 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => (),
350 TokenTree::Delimited(_, ref del) => if !check_lhs_no_empty_seq(sess, &del.tts) {
353 TokenTree::Sequence(span, ref seq) => {
354 if seq.separator.is_none() && seq.tts.iter().all(|seq_tt| {
356 TokenTree::MetaVarDecl(_, _, id) => id.name == "vis",
357 TokenTree::Sequence(_, ref sub_seq) =>
358 sub_seq.op == quoted::KleeneOp::ZeroOrMore,
362 sess.span_diagnostic.span_err(span, "repetition matches empty token tree");
365 if !check_lhs_no_empty_seq(sess, &seq.tts) {
375 fn check_rhs(sess: &ParseSess, rhs: "ed::TokenTree) -> bool {
377 quoted::TokenTree::Delimited(..) => return true,
378 _ => sess.span_diagnostic.span_err(rhs.span(), "macro rhs must be delimited")
383 fn check_matcher(sess: &ParseSess,
385 attrs: &[ast::Attribute],
386 matcher: &[quoted::TokenTree]) -> bool {
387 let first_sets = FirstSets::new(matcher);
388 let empty_suffix = TokenSet::empty();
389 let err = sess.span_diagnostic.err_count();
390 check_matcher_core(sess, features, attrs, &first_sets, matcher, &empty_suffix);
391 err == sess.span_diagnostic.err_count()
394 // The FirstSets for a matcher is a mapping from subsequences in the
395 // matcher to the FIRST set for that subsequence.
397 // This mapping is partially precomputed via a backwards scan over the
398 // token trees of the matcher, which provides a mapping from each
399 // repetition sequence to its FIRST set.
401 // (Hypothetically sequences should be uniquely identifiable via their
402 // spans, though perhaps that is false e.g. for macro-generated macros
403 // that do not try to inject artificial span information. My plan is
404 // to try to catch such cases ahead of time and not include them in
405 // the precomputed mapping.)
407 // this maps each TokenTree::Sequence `$(tt ...) SEP OP` that is uniquely identified by its
408 // span in the original matcher to the First set for the inner sequence `tt ...`.
410 // If two sequences have the same span in a matcher, then map that
411 // span to None (invalidating the mapping here and forcing the code to
413 first: HashMap<Span, Option<TokenSet>>,
417 fn new(tts: &[quoted::TokenTree]) -> FirstSets {
418 use self::quoted::TokenTree;
420 let mut sets = FirstSets { first: HashMap::new() };
421 build_recur(&mut sets, tts);
424 // walks backward over `tts`, returning the FIRST for `tts`
425 // and updating `sets` at the same time for all sequence
426 // substructure we find within `tts`.
427 fn build_recur(sets: &mut FirstSets, tts: &[TokenTree]) -> TokenSet {
428 let mut first = TokenSet::empty();
429 for tt in tts.iter().rev() {
431 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
432 first.replace_with(tt.clone());
434 TokenTree::Delimited(span, ref delimited) => {
435 build_recur(sets, &delimited.tts[..]);
436 first.replace_with(delimited.open_tt(span));
438 TokenTree::Sequence(sp, ref seq_rep) => {
439 let subfirst = build_recur(sets, &seq_rep.tts[..]);
441 match sets.first.entry(sp) {
442 Entry::Vacant(vac) => {
443 vac.insert(Some(subfirst.clone()));
445 Entry::Occupied(mut occ) => {
446 // if there is already an entry, then a span must have collided.
447 // This should not happen with typical macro_rules macros,
448 // but syntax extensions need not maintain distinct spans,
449 // so distinct syntax trees can be assigned the same span.
450 // In such a case, the map cannot be trusted; so mark this
451 // entry as unusable.
456 // If the sequence contents can be empty, then the first
457 // token could be the separator token itself.
459 if let (Some(ref sep), true) = (seq_rep.separator.clone(),
460 subfirst.maybe_empty) {
461 first.add_one_maybe(TokenTree::Token(sp, sep.clone()));
464 // Reverse scan: Sequence comes before `first`.
465 if subfirst.maybe_empty || seq_rep.op == quoted::KleeneOp::ZeroOrMore {
466 // If sequence is potentially empty, then
467 // union them (preserving first emptiness).
468 first.add_all(&TokenSet { maybe_empty: true, ..subfirst });
470 // Otherwise, sequence guaranteed
471 // non-empty; replace first.
482 // walks forward over `tts` until all potential FIRST tokens are
484 fn first(&self, tts: &[quoted::TokenTree]) -> TokenSet {
485 use self::quoted::TokenTree;
487 let mut first = TokenSet::empty();
488 for tt in tts.iter() {
489 assert!(first.maybe_empty);
491 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
492 first.add_one(tt.clone());
495 TokenTree::Delimited(span, ref delimited) => {
496 first.add_one(delimited.open_tt(span));
499 TokenTree::Sequence(sp, ref seq_rep) => {
500 match self.first.get(&sp) {
501 Some(&Some(ref subfirst)) => {
503 // If the sequence contents can be empty, then the first
504 // token could be the separator token itself.
506 if let (Some(ref sep), true) = (seq_rep.separator.clone(),
507 subfirst.maybe_empty) {
508 first.add_one_maybe(TokenTree::Token(sp, sep.clone()));
511 assert!(first.maybe_empty);
512 first.add_all(subfirst);
513 if subfirst.maybe_empty ||
514 seq_rep.op == quoted::KleeneOp::ZeroOrMore {
515 // continue scanning for more first
516 // tokens, but also make sure we
517 // restore empty-tracking state
518 first.maybe_empty = true;
526 panic!("assume all sequences have (unique) spans for now");
530 panic!("We missed a sequence during FirstSets construction");
537 // we only exit the loop if `tts` was empty or if every
538 // element of `tts` matches the empty sequence.
539 assert!(first.maybe_empty);
544 // A set of `quoted::TokenTree`s, which may include `TokenTree::Match`s
545 // (for macro-by-example syntactic variables). It also carries the
546 // `maybe_empty` flag; that is true if and only if the matcher can
547 // match an empty token sequence.
549 // The First set is computed on submatchers like `$($a:expr b),* $(c)* d`,
550 // which has corresponding FIRST = {$a:expr, c, d}.
551 // Likewise, `$($a:expr b),* $(c)+ d` has FIRST = {$a:expr, c}.
553 // (Notably, we must allow for *-op to occur zero times.)
554 #[derive(Clone, Debug)]
556 tokens: Vec<quoted::TokenTree>,
561 // Returns a set for the empty sequence.
562 fn empty() -> Self { TokenSet { tokens: Vec::new(), maybe_empty: true } }
564 // Returns the set `{ tok }` for the single-token (and thus
565 // non-empty) sequence [tok].
566 fn singleton(tok: quoted::TokenTree) -> Self {
567 TokenSet { tokens: vec![tok], maybe_empty: false }
570 // Changes self to be the set `{ tok }`.
571 // Since `tok` is always present, marks self as non-empty.
572 fn replace_with(&mut self, tok: quoted::TokenTree) {
574 self.tokens.push(tok);
575 self.maybe_empty = false;
578 // Changes self to be the empty set `{}`; meant for use when
579 // the particular token does not matter, but we want to
580 // record that it occurs.
581 fn replace_with_irrelevant(&mut self) {
583 self.maybe_empty = false;
586 // Adds `tok` to the set for `self`, marking sequence as non-empy.
587 fn add_one(&mut self, tok: quoted::TokenTree) {
588 if !self.tokens.contains(&tok) {
589 self.tokens.push(tok);
591 self.maybe_empty = false;
594 // Adds `tok` to the set for `self`. (Leaves `maybe_empty` flag alone.)
595 fn add_one_maybe(&mut self, tok: quoted::TokenTree) {
596 if !self.tokens.contains(&tok) {
597 self.tokens.push(tok);
601 // Adds all elements of `other` to this.
603 // (Since this is a set, we filter out duplicates.)
605 // If `other` is potentially empty, then preserves the previous
606 // setting of the empty flag of `self`. If `other` is guaranteed
607 // non-empty, then `self` is marked non-empty.
608 fn add_all(&mut self, other: &Self) {
609 for tok in &other.tokens {
610 if !self.tokens.contains(tok) {
611 self.tokens.push(tok.clone());
614 if !other.maybe_empty {
615 self.maybe_empty = false;
620 // Checks that `matcher` is internally consistent and that it
621 // can legally by followed by a token N, for all N in `follow`.
622 // (If `follow` is empty, then it imposes no constraint on
625 // Returns the set of NT tokens that could possibly come last in
626 // `matcher`. (If `matcher` matches the empty sequence, then
627 // `maybe_empty` will be set to true.)
629 // Requires that `first_sets` is pre-computed for `matcher`;
630 // see `FirstSets::new`.
631 fn check_matcher_core(sess: &ParseSess,
633 attrs: &[ast::Attribute],
634 first_sets: &FirstSets,
635 matcher: &[quoted::TokenTree],
636 follow: &TokenSet) -> TokenSet {
637 use self::quoted::TokenTree;
639 let mut last = TokenSet::empty();
641 // 2. For each token and suffix [T, SUFFIX] in M:
642 // ensure that T can be followed by SUFFIX, and if SUFFIX may be empty,
643 // then ensure T can also be followed by any element of FOLLOW.
644 'each_token: for i in 0..matcher.len() {
645 let token = &matcher[i];
646 let suffix = &matcher[i+1..];
648 let build_suffix_first = || {
649 let mut s = first_sets.first(suffix);
650 if s.maybe_empty { s.add_all(follow); }
654 // (we build `suffix_first` on demand below; you can tell
655 // which cases are supposed to fall through by looking for the
656 // initialization of this variable.)
659 // First, update `last` so that it corresponds to the set
660 // of NT tokens that might end the sequence `... token`.
662 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
663 let can_be_followed_by_any;
664 if let Err(bad_frag) = has_legal_fragment_specifier(sess, features, attrs, token) {
665 let msg = format!("invalid fragment specifier `{}`", bad_frag);
666 sess.span_diagnostic.struct_span_err(token.span(), &msg)
667 .help("valid fragment specifiers are `ident`, `block`, `stmt`, `expr`, \
668 `pat`, `ty`, `literal`, `path`, `meta`, `tt`, `item` and `vis`")
670 // (This eliminates false positives and duplicates
671 // from error messages.)
672 can_be_followed_by_any = true;
674 can_be_followed_by_any = token_can_be_followed_by_any(token);
677 if can_be_followed_by_any {
678 // don't need to track tokens that work with any,
679 last.replace_with_irrelevant();
680 // ... and don't need to check tokens that can be
681 // followed by anything against SUFFIX.
682 continue 'each_token;
684 last.replace_with(token.clone());
685 suffix_first = build_suffix_first();
688 TokenTree::Delimited(span, ref d) => {
689 let my_suffix = TokenSet::singleton(d.close_tt(span));
690 check_matcher_core(sess, features, attrs, first_sets, &d.tts, &my_suffix);
691 // don't track non NT tokens
692 last.replace_with_irrelevant();
694 // also, we don't need to check delimited sequences
696 continue 'each_token;
698 TokenTree::Sequence(sp, ref seq_rep) => {
699 suffix_first = build_suffix_first();
700 // The trick here: when we check the interior, we want
701 // to include the separator (if any) as a potential
702 // (but not guaranteed) element of FOLLOW. So in that
703 // case, we make a temp copy of suffix and stuff
704 // delimiter in there.
706 // FIXME: Should I first scan suffix_first to see if
707 // delimiter is already in it before I go through the
708 // work of cloning it? But then again, this way I may
709 // get a "tighter" span?
711 let my_suffix = if let Some(ref u) = seq_rep.separator {
712 new = suffix_first.clone();
713 new.add_one_maybe(TokenTree::Token(sp, u.clone()));
719 // At this point, `suffix_first` is built, and
720 // `my_suffix` is some TokenSet that we can use
721 // for checking the interior of `seq_rep`.
722 let next = check_matcher_core(sess,
728 if next.maybe_empty {
734 // the recursive call to check_matcher_core already ran the 'each_last
735 // check below, so we can just keep going forward here.
736 continue 'each_token;
740 // (`suffix_first` guaranteed initialized once reaching here.)
742 // Now `last` holds the complete set of NT tokens that could
743 // end the sequence before SUFFIX. Check that every one works with `suffix`.
744 'each_last: for token in &last.tokens {
745 if let TokenTree::MetaVarDecl(_, ref name, ref frag_spec) = *token {
746 for next_token in &suffix_first.tokens {
747 match is_in_follow(next_token, &frag_spec.as_str()) {
748 Err((msg, help)) => {
749 sess.span_diagnostic.struct_span_err(next_token.span(), &msg)
751 // don't bother reporting every source of
752 // conflict for a particular element of `last`.
757 let may_be = if last.tokens.len() == 1 &&
758 suffix_first.tokens.len() == 1
765 sess.span_diagnostic.span_err(
767 &format!("`${name}:{frag}` {may_be} followed by `{next}`, which \
768 is not allowed for `{frag}` fragments",
771 next=quoted_tt_to_string(next_token),
783 fn token_can_be_followed_by_any(tok: "ed::TokenTree) -> bool {
784 if let quoted::TokenTree::MetaVarDecl(_, _, frag_spec) = *tok {
785 frag_can_be_followed_by_any(&frag_spec.as_str())
787 // (Non NT's can always be followed by anthing in matchers.)
792 /// True if a fragment of type `frag` can be followed by any sort of
793 /// token. We use this (among other things) as a useful approximation
794 /// for when `frag` can be followed by a repetition like `$(...)*` or
795 /// `$(...)+`. In general, these can be a bit tricky to reason about,
796 /// so we adopt a conservative position that says that any fragment
797 /// specifier which consumes at most one token tree can be followed by
798 /// a fragment specifier (indeed, these fragments can be followed by
799 /// ANYTHING without fear of future compatibility hazards).
800 fn frag_can_be_followed_by_any(frag: &str) -> bool {
802 "item" | // always terminated by `}` or `;`
803 "block" | // exactly one token tree
804 "ident" | // exactly one token tree
805 "literal" | // exactly one token tree
806 "meta" | // exactly one token tree
807 "lifetime" | // exactly one token tree
808 "tt" => // exactly one token tree
816 /// True if `frag` can legally be followed by the token `tok`. For
817 /// fragments that can consume an unbounded number of tokens, `tok`
818 /// must be within a well-defined follow set. This is intended to
819 /// guarantee future compatibility: for example, without this rule, if
820 /// we expanded `expr` to include a new binary operator, we might
821 /// break macros that were relying on that binary operator as a
823 // when changing this do not forget to update doc/book/macros.md!
824 fn is_in_follow(tok: "ed::TokenTree, frag: &str) -> Result<bool, (String, &'static str)> {
825 use self::quoted::TokenTree;
827 if let TokenTree::Token(_, token::CloseDelim(_)) = *tok {
828 // closing a token tree can never be matched by any fragment;
829 // iow, we always require that `(` and `)` match, etc.
834 // since items *must* be followed by either a `;` or a `}`, we can
835 // accept anything after them
839 // anything can follow block, the braces provide an easy boundary to
843 "stmt" | "expr" => match *tok {
844 TokenTree::Token(_, ref tok) => match *tok {
845 FatArrow | Comma | Semi => Ok(true),
850 "pat" => match *tok {
851 TokenTree::Token(_, ref tok) => match *tok {
852 FatArrow | Comma | Eq | BinOp(token::Or) => Ok(true),
853 Ident(i, false) if i.name == "if" || i.name == "in" => Ok(true),
858 "path" | "ty" => match *tok {
859 TokenTree::Token(_, ref tok) => match *tok {
860 OpenDelim(token::DelimToken::Brace) | OpenDelim(token::DelimToken::Bracket) |
861 Comma | FatArrow | Colon | Eq | Gt | Semi | BinOp(token::Or) => Ok(true),
862 Ident(i, false) if i.name == "as" || i.name == "where" => Ok(true),
865 TokenTree::MetaVarDecl(_, _, frag) if frag.name == "block" => Ok(true),
868 "ident" | "lifetime" => {
869 // being a single token, idents and lifetimes are harmless
873 // literals may be of a single token, or two tokens (negative numbers)
877 // being either a single token or a delimited sequence, tt is
882 // Explicitly disallow `priv`, on the off chance it comes back.
884 TokenTree::Token(_, ref tok) => match *tok {
886 Ident(i, is_raw) if is_raw || i.name != "priv" => Ok(true),
887 ref tok => Ok(tok.can_begin_type())
889 TokenTree::MetaVarDecl(_, _, frag) if frag.name == "ident"
891 || frag.name == "path" => Ok(true),
895 "" => Ok(true), // keywords::Invalid
896 _ => Err((format!("invalid fragment specifier `{}`", frag),
897 "valid fragment specifiers are `ident`, `block`, \
898 `stmt`, `expr`, `pat`, `ty`, `path`, `meta`, `tt`, \
899 `literal`, `item` and `vis`"))
904 fn has_legal_fragment_specifier(sess: &ParseSess,
906 attrs: &[ast::Attribute],
907 tok: "ed::TokenTree) -> Result<(), String> {
908 debug!("has_legal_fragment_specifier({:?})", tok);
909 if let quoted::TokenTree::MetaVarDecl(_, _, ref frag_spec) = *tok {
910 let frag_name = frag_spec.as_str();
911 let frag_span = tok.span();
912 if !is_legal_fragment_specifier(sess, features, attrs, &frag_name, frag_span) {
913 return Err(frag_name.to_string());
919 fn is_legal_fragment_specifier(sess: &ParseSess,
921 attrs: &[ast::Attribute],
923 frag_span: Span) -> bool {
925 "item" | "block" | "stmt" | "expr" | "pat" | "lifetime" |
926 "path" | "ty" | "ident" | "meta" | "tt" | "" => true,
928 if !features.macro_literal_matcher &&
929 !attr::contains_name(attrs, "allow_internal_unstable") {
930 let explain = feature_gate::EXPLAIN_LITERAL_MATCHER;
931 emit_feature_err(sess,
932 "macro_literal_matcher",
940 if !features.macro_vis_matcher &&
941 !attr::contains_name(attrs, "allow_internal_unstable") {
942 let explain = feature_gate::EXPLAIN_VIS_MATCHER;
943 emit_feature_err(sess,
955 fn quoted_tt_to_string(tt: "ed::TokenTree) -> String {
957 quoted::TokenTree::Token(_, ref tok) => ::print::pprust::token_to_string(tok),
958 quoted::TokenTree::MetaVar(_, name) => format!("${}", name),
959 quoted::TokenTree::MetaVarDecl(_, name, kind) => format!("${}:{}", name, kind),
960 _ => panic!("unexpected quoted::TokenTree::{{Sequence or Delimited}} \
961 in follow set checker"),