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::{DelimSpan, TokenStream, TokenTree};
30 use rustc_data_structures::fx::FxHashMap;
32 use std::collections::hash_map::Entry;
34 use rustc_data_structures::sync::Lrc;
35 use errors::Applicability;
37 const VALID_FRAGMENT_NAMES_MSG: &str = "valid fragment specifiers are \
38 `ident`, `block`, `stmt`, `expr`, `pat`, `ty`, `lifetime`, `literal`, \
39 `path`, `meta`, `tt`, `item` and `vis`";
41 pub struct ParserAnyMacro<'a> {
44 /// Span of the expansion site of the macro this parser is for
46 /// The ident of the macro we're parsing
47 macro_ident: ast::Ident
50 impl<'a> ParserAnyMacro<'a> {
51 pub fn make(mut self: Box<ParserAnyMacro<'a>>, kind: AstFragmentKind) -> AstFragment {
52 let ParserAnyMacro { site_span, macro_ident, ref mut parser } = *self;
53 let fragment = panictry!(parser.parse_ast_fragment(kind, true).map_err(|mut e| {
54 if e.span.is_dummy() { // Get around lack of span in error (#30128)
55 e.set_span(site_span);
60 // We allow semicolons at the end of expressions -- e.g. the semicolon in
61 // `macro_rules! m { () => { panic!(); } }` isn't parsed by `.parse_expr()`,
62 // but `m!()` is allowed in expression positions (c.f. issue #34706).
63 if kind == AstFragmentKind::Expr && parser.token == token::Semi {
67 // Make sure we don't have any tokens left to parse so we don't silently drop anything.
68 let path = ast::Path::from_ident(macro_ident.with_span_pos(site_span));
69 parser.ensure_complete_parse(&path, kind.name(), site_span);
74 struct MacroRulesMacroExpander {
76 lhses: Vec<quoted::TokenTree>,
77 rhses: Vec<quoted::TokenTree>,
81 impl TTMacroExpander for MacroRulesMacroExpander {
87 def_span: Option<Span>,
88 ) -> Box<dyn MacResult+'cx> {
90 return DummyResult::any(sp);
102 fn trace_macros_note(cx: &mut ExtCtxt, sp: Span, message: String) {
103 let sp = sp.macro_backtrace().last().map(|trace| trace.call_site).unwrap_or(sp);
104 cx.expansions.entry(sp).or_default().push(message);
107 /// Given `lhses` and `rhses`, this is the new macro we create
108 fn generic_extension<'cx>(cx: &'cx mut ExtCtxt,
110 def_span: Option<Span>,
113 lhses: &[quoted::TokenTree],
114 rhses: &[quoted::TokenTree])
115 -> Box<dyn MacResult+'cx> {
116 if cx.trace_macros() {
117 trace_macros_note(cx, sp, format!("expanding `{}! {{ {} }}`", name, arg));
120 // Which arm's failure should we report? (the one furthest along)
121 let mut best_fail_spot = DUMMY_SP;
122 let mut best_fail_tok = None;
124 for (i, lhs) in lhses.iter().enumerate() { // try each arm's matchers
125 let lhs_tt = match *lhs {
126 quoted::TokenTree::Delimited(_, ref delim) => &delim.tts[..],
127 _ => cx.span_bug(sp, "malformed macro lhs")
130 match TokenTree::parse(cx, lhs_tt, arg.clone()) {
131 Success(named_matches) => {
132 let rhs = match rhses[i] {
134 quoted::TokenTree::Delimited(_, ref delimed) => delimed.tts.clone(),
135 _ => cx.span_bug(sp, "malformed macro rhs"),
138 let rhs_spans = rhs.iter().map(|t| t.span()).collect::<Vec<_>>();
139 // rhs has holes ( `$id` and `$(...)` that need filled)
140 let mut tts = transcribe(cx, Some(named_matches), rhs);
142 // Replace all the tokens for the corresponding positions in the macro, to maintain
143 // proper positions in error reporting, while maintaining the macro_backtrace.
144 if rhs_spans.len() == tts.len() {
145 tts = tts.map_enumerated(|i, tt| {
146 let mut tt = tt.clone();
147 let mut sp = rhs_spans[i];
148 sp = sp.with_ctxt(tt.span().ctxt());
154 if cx.trace_macros() {
155 trace_macros_note(cx, sp, format!("to `{}`", tts));
158 let directory = Directory {
159 path: Cow::from(cx.current_expansion.module.directory.as_path()),
160 ownership: cx.current_expansion.directory_ownership,
162 let mut p = Parser::new(cx.parse_sess(), tts, Some(directory), true, false);
163 p.root_module_name = cx.current_expansion.module.mod_path.last()
164 .map(|id| id.as_str().to_string());
166 p.process_potential_macro_variable();
167 // Let the context choose how to interpret the result.
168 // Weird, but useful for X-macros.
169 return Box::new(ParserAnyMacro {
172 // Pass along the original expansion site and the name of the macro
173 // so we can print a useful error message if the parse of the expanded
174 // macro leaves unparsed tokens.
179 Failure(sp, tok) => if sp.lo() >= best_fail_spot.lo() {
181 best_fail_tok = Some(tok);
183 Error(err_sp, ref msg) => {
184 cx.span_fatal(err_sp.substitute_dummy(sp), &msg[..])
189 let best_fail_msg = parse_failure_msg(best_fail_tok.expect("ran no matchers"));
190 let span = best_fail_spot.substitute_dummy(sp);
191 let mut err = cx.struct_span_err(span, &best_fail_msg);
192 err.span_label(span, best_fail_msg);
193 if let Some(sp) = def_span {
194 if cx.source_map().span_to_filename(sp).is_real() && !sp.is_dummy() {
195 err.span_label(cx.source_map().def_span(sp), "when calling this macro");
199 // Check whether there's a missing comma in this macro call, like `println!("{}" a);`
200 if let Some((arg, comma_span)) = arg.add_comma() {
201 for lhs in lhses { // try each arm's matchers
202 let lhs_tt = match *lhs {
203 quoted::TokenTree::Delimited(_, ref delim) => &delim.tts[..],
206 match TokenTree::parse(cx, lhs_tt, arg.clone()) {
208 if comma_span.is_dummy() {
209 err.note("you might be missing a comma");
211 err.span_suggestion_short_with_applicability(
213 "missing comma here",
215 Applicability::MachineApplicable,
224 cx.trace_macros_diag();
228 // Note that macro-by-example's input is also matched against a token tree:
229 // $( $lhs:tt => $rhs:tt );+
231 // Holy self-referential!
233 /// Converts a `macro_rules!` invocation into a syntax extension.
234 pub fn compile(sess: &ParseSess, features: &Features, def: &ast::Item, edition: Edition)
236 let lhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("lhs"));
237 let rhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("rhs"));
239 // Parse the macro_rules! invocation
240 let body = match def.node {
241 ast::ItemKind::MacroDef(ref body) => body,
245 // The pattern that macro_rules matches.
246 // The grammar for macro_rules! is:
247 // $( $lhs:tt => $rhs:tt );+
248 // ...quasiquoting this would be nice.
249 // These spans won't matter, anyways
250 let argument_gram = vec![
251 quoted::TokenTree::Sequence(DelimSpan::dummy(), Lrc::new(quoted::SequenceRepetition {
253 quoted::TokenTree::MetaVarDecl(DUMMY_SP, lhs_nm, ast::Ident::from_str("tt")),
254 quoted::TokenTree::Token(DUMMY_SP, token::FatArrow),
255 quoted::TokenTree::MetaVarDecl(DUMMY_SP, rhs_nm, ast::Ident::from_str("tt")),
257 separator: Some(if body.legacy { token::Semi } else { token::Comma }),
258 op: quoted::KleeneOp::OneOrMore,
261 // to phase into semicolon-termination instead of semicolon-separation
262 quoted::TokenTree::Sequence(DelimSpan::dummy(), Lrc::new(quoted::SequenceRepetition {
263 tts: vec![quoted::TokenTree::Token(DUMMY_SP, token::Semi)],
265 op: quoted::KleeneOp::ZeroOrMore,
270 let argument_map = match parse(sess, body.stream(), &argument_gram, None, true) {
272 Failure(sp, tok) => {
273 let s = parse_failure_msg(tok);
274 sess.span_diagnostic.span_fatal(sp.substitute_dummy(def.span), &s).raise();
277 sess.span_diagnostic.span_fatal(sp.substitute_dummy(def.span), &s).raise();
281 let mut valid = true;
283 // Extract the arguments:
284 let lhses = match *argument_map[&lhs_nm] {
285 MatchedSeq(ref s, _) => {
287 if let MatchedNonterminal(ref nt) = *m {
288 if let NtTT(ref tt) = **nt {
289 let tt = quoted::parse(
300 valid &= check_lhs_nt_follows(sess, features, &def.attrs, &tt);
304 sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
305 }).collect::<Vec<quoted::TokenTree>>()
307 _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
310 let rhses = match *argument_map[&rhs_nm] {
311 MatchedSeq(ref s, _) => {
313 if let MatchedNonterminal(ref nt) = *m {
314 if let NtTT(ref tt) = **nt {
315 return quoted::parse(
327 sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
328 }).collect::<Vec<quoted::TokenTree>>()
330 _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured rhs")
334 valid &= check_rhs(sess, rhs);
337 // don't abort iteration early, so that errors for multiple lhses can be reported
339 valid &= check_lhs_no_empty_seq(sess, &[lhs.clone()])
342 let expander: Box<_> = Box::new(MacroRulesMacroExpander {
350 let allow_internal_unstable = attr::contains_name(&def.attrs, "allow_internal_unstable");
351 let allow_internal_unsafe = attr::contains_name(&def.attrs, "allow_internal_unsafe");
352 let mut local_inner_macros = false;
353 if let Some(macro_export) = attr::find_by_name(&def.attrs, "macro_export") {
354 if let Some(l) = macro_export.meta_item_list() {
355 local_inner_macros = attr::list_contains_name(&l, "local_inner_macros");
359 let unstable_feature = attr::find_stability(&sess.span_diagnostic,
360 &def.attrs, def.span).and_then(|stability| {
361 if let attr::StabilityLevel::Unstable { issue, .. } = stability.level {
362 Some((stability.feature, issue))
370 def_info: Some((def.id, def.span)),
371 allow_internal_unstable,
372 allow_internal_unsafe,
378 let is_transparent = attr::contains_name(&def.attrs, "rustc_transparent_macro");
380 SyntaxExtension::DeclMacro {
382 def_info: Some((def.id, def.span)),
389 fn check_lhs_nt_follows(sess: &ParseSess,
391 attrs: &[ast::Attribute],
392 lhs: "ed::TokenTree) -> bool {
393 // lhs is going to be like TokenTree::Delimited(...), where the
394 // entire lhs is those tts. Or, it can be a "bare sequence", not wrapped in parens.
395 if let quoted::TokenTree::Delimited(_, ref tts) = *lhs {
396 check_matcher(sess, features, attrs, &tts.tts)
398 let msg = "invalid macro matcher; matchers must be contained in balanced delimiters";
399 sess.span_diagnostic.span_err(lhs.span(), msg);
402 // we don't abort on errors on rejection, the driver will do that for us
403 // after parsing/expansion. we can report every error in every macro this way.
406 /// Check that the lhs contains no repetition which could match an empty token
407 /// tree, because then the matcher would hang indefinitely.
408 fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[quoted::TokenTree]) -> bool {
409 use self::quoted::TokenTree;
412 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => (),
413 TokenTree::Delimited(_, ref del) => if !check_lhs_no_empty_seq(sess, &del.tts) {
416 TokenTree::Sequence(span, ref seq) => {
417 if seq.separator.is_none() && seq.tts.iter().all(|seq_tt| {
419 TokenTree::MetaVarDecl(_, _, id) => id.name == "vis",
420 TokenTree::Sequence(_, ref sub_seq) =>
421 sub_seq.op == quoted::KleeneOp::ZeroOrMore,
425 let sp = span.entire();
426 sess.span_diagnostic.span_err(sp, "repetition matches empty token tree");
429 if !check_lhs_no_empty_seq(sess, &seq.tts) {
439 fn check_rhs(sess: &ParseSess, rhs: "ed::TokenTree) -> bool {
441 quoted::TokenTree::Delimited(..) => return true,
442 _ => sess.span_diagnostic.span_err(rhs.span(), "macro rhs must be delimited")
447 fn check_matcher(sess: &ParseSess,
449 attrs: &[ast::Attribute],
450 matcher: &[quoted::TokenTree]) -> bool {
451 let first_sets = FirstSets::new(matcher);
452 let empty_suffix = TokenSet::empty();
453 let err = sess.span_diagnostic.err_count();
454 check_matcher_core(sess, features, attrs, &first_sets, matcher, &empty_suffix);
455 err == sess.span_diagnostic.err_count()
458 // The FirstSets for a matcher is a mapping from subsequences in the
459 // matcher to the FIRST set for that subsequence.
461 // This mapping is partially precomputed via a backwards scan over the
462 // token trees of the matcher, which provides a mapping from each
463 // repetition sequence to its FIRST set.
465 // (Hypothetically sequences should be uniquely identifiable via their
466 // spans, though perhaps that is false e.g. for macro-generated macros
467 // that do not try to inject artificial span information. My plan is
468 // to try to catch such cases ahead of time and not include them in
469 // the precomputed mapping.)
471 // this maps each TokenTree::Sequence `$(tt ...) SEP OP` that is uniquely identified by its
472 // span in the original matcher to the First set for the inner sequence `tt ...`.
474 // If two sequences have the same span in a matcher, then map that
475 // span to None (invalidating the mapping here and forcing the code to
477 first: FxHashMap<Span, Option<TokenSet>>,
481 fn new(tts: &[quoted::TokenTree]) -> FirstSets {
482 use self::quoted::TokenTree;
484 let mut sets = FirstSets { first: FxHashMap::default() };
485 build_recur(&mut sets, tts);
488 // walks backward over `tts`, returning the FIRST for `tts`
489 // and updating `sets` at the same time for all sequence
490 // substructure we find within `tts`.
491 fn build_recur(sets: &mut FirstSets, tts: &[TokenTree]) -> TokenSet {
492 let mut first = TokenSet::empty();
493 for tt in tts.iter().rev() {
495 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
496 first.replace_with(tt.clone());
498 TokenTree::Delimited(span, ref delimited) => {
499 build_recur(sets, &delimited.tts[..]);
500 first.replace_with(delimited.open_tt(span.open));
502 TokenTree::Sequence(sp, ref seq_rep) => {
503 let subfirst = build_recur(sets, &seq_rep.tts[..]);
505 match sets.first.entry(sp.entire()) {
506 Entry::Vacant(vac) => {
507 vac.insert(Some(subfirst.clone()));
509 Entry::Occupied(mut occ) => {
510 // if there is already an entry, then a span must have collided.
511 // This should not happen with typical macro_rules macros,
512 // but syntax extensions need not maintain distinct spans,
513 // so distinct syntax trees can be assigned the same span.
514 // In such a case, the map cannot be trusted; so mark this
515 // entry as unusable.
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.entire(), sep.clone()));
528 // Reverse scan: Sequence comes before `first`.
529 if subfirst.maybe_empty || seq_rep.op == quoted::KleeneOp::ZeroOrMore {
530 // If sequence is potentially empty, then
531 // union them (preserving first emptiness).
532 first.add_all(&TokenSet { maybe_empty: true, ..subfirst });
534 // Otherwise, sequence guaranteed
535 // non-empty; replace first.
546 // walks forward over `tts` until all potential FIRST tokens are
548 fn first(&self, tts: &[quoted::TokenTree]) -> TokenSet {
549 use self::quoted::TokenTree;
551 let mut first = TokenSet::empty();
552 for tt in tts.iter() {
553 assert!(first.maybe_empty);
555 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
556 first.add_one(tt.clone());
559 TokenTree::Delimited(span, ref delimited) => {
560 first.add_one(delimited.open_tt(span.open));
563 TokenTree::Sequence(sp, ref seq_rep) => {
564 match self.first.get(&sp.entire()) {
565 Some(&Some(ref subfirst)) => {
567 // If the sequence contents can be empty, then the first
568 // token could be the separator token itself.
570 if let (Some(ref sep), true) = (seq_rep.separator.clone(),
571 subfirst.maybe_empty) {
572 first.add_one_maybe(TokenTree::Token(sp.entire(), sep.clone()));
575 assert!(first.maybe_empty);
576 first.add_all(subfirst);
577 if subfirst.maybe_empty ||
578 seq_rep.op == quoted::KleeneOp::ZeroOrMore {
579 // continue scanning for more first
580 // tokens, but also make sure we
581 // restore empty-tracking state
582 first.maybe_empty = true;
590 panic!("assume all sequences have (unique) spans for now");
594 panic!("We missed a sequence during FirstSets construction");
601 // we only exit the loop if `tts` was empty or if every
602 // element of `tts` matches the empty sequence.
603 assert!(first.maybe_empty);
608 // A set of `quoted::TokenTree`s, which may include `TokenTree::Match`s
609 // (for macro-by-example syntactic variables). It also carries the
610 // `maybe_empty` flag; that is true if and only if the matcher can
611 // match an empty token sequence.
613 // The First set is computed on submatchers like `$($a:expr b),* $(c)* d`,
614 // which has corresponding FIRST = {$a:expr, c, d}.
615 // Likewise, `$($a:expr b),* $(c)+ d` has FIRST = {$a:expr, c}.
617 // (Notably, we must allow for *-op to occur zero times.)
618 #[derive(Clone, Debug)]
620 tokens: Vec<quoted::TokenTree>,
625 // Returns a set for the empty sequence.
626 fn empty() -> Self { TokenSet { tokens: Vec::new(), maybe_empty: true } }
628 // Returns the set `{ tok }` for the single-token (and thus
629 // non-empty) sequence [tok].
630 fn singleton(tok: quoted::TokenTree) -> Self {
631 TokenSet { tokens: vec![tok], maybe_empty: false }
634 // Changes self to be the set `{ tok }`.
635 // Since `tok` is always present, marks self as non-empty.
636 fn replace_with(&mut self, tok: quoted::TokenTree) {
638 self.tokens.push(tok);
639 self.maybe_empty = false;
642 // Changes self to be the empty set `{}`; meant for use when
643 // the particular token does not matter, but we want to
644 // record that it occurs.
645 fn replace_with_irrelevant(&mut self) {
647 self.maybe_empty = false;
650 // Adds `tok` to the set for `self`, marking sequence as non-empy.
651 fn add_one(&mut self, tok: quoted::TokenTree) {
652 if !self.tokens.contains(&tok) {
653 self.tokens.push(tok);
655 self.maybe_empty = false;
658 // Adds `tok` to the set for `self`. (Leaves `maybe_empty` flag alone.)
659 fn add_one_maybe(&mut self, tok: quoted::TokenTree) {
660 if !self.tokens.contains(&tok) {
661 self.tokens.push(tok);
665 // Adds all elements of `other` to this.
667 // (Since this is a set, we filter out duplicates.)
669 // If `other` is potentially empty, then preserves the previous
670 // setting of the empty flag of `self`. If `other` is guaranteed
671 // non-empty, then `self` is marked non-empty.
672 fn add_all(&mut self, other: &Self) {
673 for tok in &other.tokens {
674 if !self.tokens.contains(tok) {
675 self.tokens.push(tok.clone());
678 if !other.maybe_empty {
679 self.maybe_empty = false;
684 // Checks that `matcher` is internally consistent and that it
685 // can legally by followed by a token N, for all N in `follow`.
686 // (If `follow` is empty, then it imposes no constraint on
689 // Returns the set of NT tokens that could possibly come last in
690 // `matcher`. (If `matcher` matches the empty sequence, then
691 // `maybe_empty` will be set to true.)
693 // Requires that `first_sets` is pre-computed for `matcher`;
694 // see `FirstSets::new`.
695 fn check_matcher_core(sess: &ParseSess,
697 attrs: &[ast::Attribute],
698 first_sets: &FirstSets,
699 matcher: &[quoted::TokenTree],
700 follow: &TokenSet) -> TokenSet {
701 use self::quoted::TokenTree;
703 let mut last = TokenSet::empty();
705 // 2. For each token and suffix [T, SUFFIX] in M:
706 // ensure that T can be followed by SUFFIX, and if SUFFIX may be empty,
707 // then ensure T can also be followed by any element of FOLLOW.
708 'each_token: for i in 0..matcher.len() {
709 let token = &matcher[i];
710 let suffix = &matcher[i+1..];
712 let build_suffix_first = || {
713 let mut s = first_sets.first(suffix);
714 if s.maybe_empty { s.add_all(follow); }
718 // (we build `suffix_first` on demand below; you can tell
719 // which cases are supposed to fall through by looking for the
720 // initialization of this variable.)
723 // First, update `last` so that it corresponds to the set
724 // of NT tokens that might end the sequence `... token`.
726 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
727 let can_be_followed_by_any;
728 if let Err(bad_frag) = has_legal_fragment_specifier(sess, features, attrs, token) {
729 let msg = format!("invalid fragment specifier `{}`", bad_frag);
730 sess.span_diagnostic.struct_span_err(token.span(), &msg)
731 .help(VALID_FRAGMENT_NAMES_MSG)
733 // (This eliminates false positives and duplicates
734 // from error messages.)
735 can_be_followed_by_any = true;
737 can_be_followed_by_any = token_can_be_followed_by_any(token);
740 if can_be_followed_by_any {
741 // don't need to track tokens that work with any,
742 last.replace_with_irrelevant();
743 // ... and don't need to check tokens that can be
744 // followed by anything against SUFFIX.
745 continue 'each_token;
747 last.replace_with(token.clone());
748 suffix_first = build_suffix_first();
751 TokenTree::Delimited(span, ref d) => {
752 let my_suffix = TokenSet::singleton(d.close_tt(span.close));
753 check_matcher_core(sess, features, attrs, first_sets, &d.tts, &my_suffix);
754 // don't track non NT tokens
755 last.replace_with_irrelevant();
757 // also, we don't need to check delimited sequences
759 continue 'each_token;
761 TokenTree::Sequence(sp, ref seq_rep) => {
762 suffix_first = build_suffix_first();
763 // The trick here: when we check the interior, we want
764 // to include the separator (if any) as a potential
765 // (but not guaranteed) element of FOLLOW. So in that
766 // case, we make a temp copy of suffix and stuff
767 // delimiter in there.
769 // FIXME: Should I first scan suffix_first to see if
770 // delimiter is already in it before I go through the
771 // work of cloning it? But then again, this way I may
772 // get a "tighter" span?
774 let my_suffix = if let Some(ref u) = seq_rep.separator {
775 new = suffix_first.clone();
776 new.add_one_maybe(TokenTree::Token(sp.entire(), u.clone()));
782 // At this point, `suffix_first` is built, and
783 // `my_suffix` is some TokenSet that we can use
784 // for checking the interior of `seq_rep`.
785 let next = check_matcher_core(sess,
791 if next.maybe_empty {
797 // the recursive call to check_matcher_core already ran the 'each_last
798 // check below, so we can just keep going forward here.
799 continue 'each_token;
803 // (`suffix_first` guaranteed initialized once reaching here.)
805 // Now `last` holds the complete set of NT tokens that could
806 // end the sequence before SUFFIX. Check that every one works with `suffix`.
807 'each_last: for token in &last.tokens {
808 if let TokenTree::MetaVarDecl(_, ref name, ref frag_spec) = *token {
809 for next_token in &suffix_first.tokens {
810 match is_in_follow(next_token, &frag_spec.as_str()) {
811 IsInFollow::Invalid(msg, help) => {
812 sess.span_diagnostic.struct_span_err(next_token.span(), &msg)
814 // don't bother reporting every source of
815 // conflict for a particular element of `last`.
818 IsInFollow::Yes => {}
819 IsInFollow::No(ref possible) => {
820 let may_be = if last.tokens.len() == 1 &&
821 suffix_first.tokens.len() == 1
828 let sp = next_token.span();
829 let mut err = sess.span_diagnostic.struct_span_err(
831 &format!("`${name}:{frag}` {may_be} followed by `{next}`, which \
832 is not allowed for `{frag}` fragments",
835 next=quoted_tt_to_string(next_token),
840 format!("not allowed after `{}` fragments", frag_spec),
842 let msg = "allowed there are: ";
843 match &possible[..] {
847 "only {} is allowed after `{}` fragments",
856 ts[..ts.len() - 1].iter().map(|s| *s)
857 .collect::<Vec<_>>().join(", "),
872 fn token_can_be_followed_by_any(tok: "ed::TokenTree) -> bool {
873 if let quoted::TokenTree::MetaVarDecl(_, _, frag_spec) = *tok {
874 frag_can_be_followed_by_any(&frag_spec.as_str())
876 // (Non NT's can always be followed by anthing in matchers.)
881 /// True if a fragment of type `frag` can be followed by any sort of
882 /// token. We use this (among other things) as a useful approximation
883 /// for when `frag` can be followed by a repetition like `$(...)*` or
884 /// `$(...)+`. In general, these can be a bit tricky to reason about,
885 /// so we adopt a conservative position that says that any fragment
886 /// specifier which consumes at most one token tree can be followed by
887 /// a fragment specifier (indeed, these fragments can be followed by
888 /// ANYTHING without fear of future compatibility hazards).
889 fn frag_can_be_followed_by_any(frag: &str) -> bool {
891 "item" | // always terminated by `}` or `;`
892 "block" | // exactly one token tree
893 "ident" | // exactly one token tree
894 "literal" | // exactly one token tree
895 "meta" | // exactly one token tree
896 "lifetime" | // exactly one token tree
897 "tt" => // exactly one token tree
907 No(Vec<&'static str>),
908 Invalid(String, &'static str),
911 /// True if `frag` can legally be followed by the token `tok`. For
912 /// fragments that can consume an unbounded number of tokens, `tok`
913 /// must be within a well-defined follow set. This is intended to
914 /// guarantee future compatibility: for example, without this rule, if
915 /// we expanded `expr` to include a new binary operator, we might
916 /// break macros that were relying on that binary operator as a
918 // when changing this do not forget to update doc/book/macros.md!
919 fn is_in_follow(tok: "ed::TokenTree, frag: &str) -> IsInFollow {
920 use self::quoted::TokenTree;
922 if let TokenTree::Token(_, token::CloseDelim(_)) = *tok {
923 // closing a token tree can never be matched by any fragment;
924 // iow, we always require that `(` and `)` match, etc.
929 // since items *must* be followed by either a `;` or a `}`, we can
930 // accept anything after them
934 // anything can follow block, the braces provide an easy boundary to
939 let tokens = vec!["`=>`", "`,`", "`;`"];
941 TokenTree::Token(_, ref tok) => match *tok {
942 FatArrow | Comma | Semi => IsInFollow::Yes,
943 _ => IsInFollow::No(tokens),
945 _ => IsInFollow::No(tokens),
949 let tokens = vec!["`=>`", "`,`", "`=`", "`|`", "`if`", "`in`"];
951 TokenTree::Token(_, ref tok) => match *tok {
952 FatArrow | Comma | Eq | BinOp(token::Or) => IsInFollow::Yes,
953 Ident(i, false) if i.name == "if" || i.name == "in" => IsInFollow::Yes,
954 _ => IsInFollow::No(tokens),
956 _ => IsInFollow::No(tokens),
961 "`{`", "`[`", "`=>`", "`,`", "`>`","`=`", "`:`", "`;`", "`|`", "`as`",
965 TokenTree::Token(_, ref tok) => match *tok {
966 OpenDelim(token::DelimToken::Brace) |
967 OpenDelim(token::DelimToken::Bracket) |
968 Comma | FatArrow | Colon | Eq | Gt | BinOp(token::Shr) | Semi |
969 BinOp(token::Or) => IsInFollow::Yes,
970 Ident(i, false) if i.name == "as" || i.name == "where" => IsInFollow::Yes,
971 _ => IsInFollow::No(tokens),
973 TokenTree::MetaVarDecl(_, _, frag) if frag.name == "block" => IsInFollow::Yes,
974 _ => IsInFollow::No(tokens),
977 "ident" | "lifetime" => {
978 // being a single token, idents and lifetimes are harmless
982 // literals may be of a single token, or two tokens (negative numbers)
986 // being either a single token or a delimited sequence, tt is
991 // Explicitly disallow `priv`, on the off chance it comes back.
992 let tokens = vec!["`,`", "an ident", "a type"];
994 TokenTree::Token(_, ref tok) => match *tok {
995 Comma => IsInFollow::Yes,
996 Ident(i, is_raw) if is_raw || i.name != "priv" => IsInFollow::Yes,
997 ref tok => if tok.can_begin_type() {
1000 IsInFollow::No(tokens)
1003 TokenTree::MetaVarDecl(_, _, frag) if frag.name == "ident"
1004 || frag.name == "ty"
1005 || frag.name == "path" => IsInFollow::Yes,
1006 _ => IsInFollow::No(tokens),
1009 "" => IsInFollow::Yes, // keywords::Invalid
1010 _ => IsInFollow::Invalid(format!("invalid fragment specifier `{}`", frag),
1011 VALID_FRAGMENT_NAMES_MSG),
1016 fn has_legal_fragment_specifier(sess: &ParseSess,
1017 features: &Features,
1018 attrs: &[ast::Attribute],
1019 tok: "ed::TokenTree) -> Result<(), String> {
1020 debug!("has_legal_fragment_specifier({:?})", tok);
1021 if let quoted::TokenTree::MetaVarDecl(_, _, ref frag_spec) = *tok {
1022 let frag_name = frag_spec.as_str();
1023 let frag_span = tok.span();
1024 if !is_legal_fragment_specifier(sess, features, attrs, &frag_name, frag_span) {
1025 return Err(frag_name.to_string());
1031 fn is_legal_fragment_specifier(sess: &ParseSess,
1032 features: &Features,
1033 attrs: &[ast::Attribute],
1035 frag_span: Span) -> bool {
1037 "item" | "block" | "stmt" | "expr" | "pat" | "lifetime" |
1038 "path" | "ty" | "ident" | "meta" | "tt" | "vis" | "" => true,
1040 if !features.macro_literal_matcher &&
1041 !attr::contains_name(attrs, "allow_internal_unstable") {
1042 let explain = feature_gate::EXPLAIN_LITERAL_MATCHER;
1043 emit_feature_err(sess,
1044 "macro_literal_matcher",
1046 GateIssue::Language,
1055 fn quoted_tt_to_string(tt: "ed::TokenTree) -> String {
1057 quoted::TokenTree::Token(_, ref tok) => ::print::pprust::token_to_string(tok),
1058 quoted::TokenTree::MetaVar(_, name) => format!("${}", name),
1059 quoted::TokenTree::MetaVarDecl(_, name, kind) => format!("${}:{}", name, kind),
1060 _ => panic!("unexpected quoted::TokenTree::{{Sequence or Delimited}} \
1061 in follow set checker"),