1 use crate::{ast, attr};
2 use crate::edition::Edition;
3 use crate::ext::base::{DummyResult, ExtCtxt, MacResult, SyntaxExtension};
4 use crate::ext::base::{NormalTT, TTMacroExpander};
5 use crate::ext::expand::{AstFragment, AstFragmentKind};
6 use crate::ext::tt::macro_parser::{Success, Error, Failure};
7 use crate::ext::tt::macro_parser::{MatchedSeq, MatchedNonterminal};
8 use crate::ext::tt::macro_parser::{parse, parse_failure_msg};
9 use crate::ext::tt::quoted;
10 use crate::ext::tt::transcribe::transcribe;
11 use crate::feature_gate::Features;
12 use crate::parse::{Directory, ParseSess};
13 use crate::parse::parser::Parser;
14 use crate::parse::token::{self, NtTT};
15 use crate::parse::token::Token::*;
16 use crate::symbol::Symbol;
17 use crate::tokenstream::{DelimSpan, TokenStream, TokenTree};
19 use errors::FatalError;
20 use syntax_pos::{Span, DUMMY_SP, symbol::Ident};
23 use rustc_data_structures::fx::{FxHashMap};
25 use std::collections::hash_map::Entry;
27 use rustc_data_structures::sync::Lrc;
28 use errors::Applicability;
30 const VALID_FRAGMENT_NAMES_MSG: &str = "valid fragment specifiers are \
31 `ident`, `block`, `stmt`, `expr`, `pat`, `ty`, `lifetime`, `literal`, \
32 `path`, `meta`, `tt`, `item` and `vis`";
34 pub struct ParserAnyMacro<'a> {
37 /// Span of the expansion site of the macro this parser is for
39 /// The ident of the macro we're parsing
40 macro_ident: ast::Ident,
44 impl<'a> ParserAnyMacro<'a> {
45 pub fn make(mut self: Box<ParserAnyMacro<'a>>, kind: AstFragmentKind) -> AstFragment {
46 let ParserAnyMacro { site_span, macro_ident, ref mut parser, arm_span } = *self;
47 let fragment = panictry!(parser.parse_ast_fragment(kind, true).map_err(|mut e| {
48 if parser.token == token::Eof && e.message().ends_with(", found `<eof>`") {
49 if !e.span.is_dummy() { // early end of macro arm (#52866)
50 e.replace_span_with(parser.sess.source_map().next_point(parser.span));
52 let msg = &e.message[0];
55 "macro expansion ends with an incomplete expression: {}",
56 msg.0.replace(", found `<eof>`", ""),
61 if e.span.is_dummy() { // Get around lack of span in error (#30128)
62 e.replace_span_with(site_span);
63 if parser.sess.source_map().span_to_filename(arm_span).is_real() {
64 e.span_label(arm_span, "in this macro arm");
66 } else if !parser.sess.source_map().span_to_filename(parser.span).is_real() {
67 e.span_label(site_span, "in this macro invocation");
72 // We allow semicolons at the end of expressions -- e.g., the semicolon in
73 // `macro_rules! m { () => { panic!(); } }` isn't parsed by `.parse_expr()`,
74 // but `m!()` is allowed in expression positions (cf. issue #34706).
75 if kind == AstFragmentKind::Expr && parser.token == token::Semi {
79 // Make sure we don't have any tokens left to parse so we don't silently drop anything.
80 let path = ast::Path::from_ident(macro_ident.with_span_pos(site_span));
81 parser.ensure_complete_parse(&path, kind.name(), site_span);
86 struct MacroRulesMacroExpander {
88 lhses: Vec<quoted::TokenTree>,
89 rhses: Vec<quoted::TokenTree>,
93 impl TTMacroExpander for MacroRulesMacroExpander {
96 cx: &'cx mut ExtCtxt<'_>,
99 def_span: Option<Span>,
100 ) -> Box<dyn MacResult+'cx> {
102 return DummyResult::any(sp);
104 generic_extension(cx,
114 fn trace_macros_note(cx: &mut ExtCtxt<'_>, sp: Span, message: String) {
115 let sp = sp.macro_backtrace().last().map(|trace| trace.call_site).unwrap_or(sp);
116 cx.expansions.entry(sp).or_default().push(message);
119 /// Given `lhses` and `rhses`, this is the new macro we create
120 fn generic_extension<'cx>(cx: &'cx mut ExtCtxt<'_>,
122 def_span: Option<Span>,
125 lhses: &[quoted::TokenTree],
126 rhses: &[quoted::TokenTree])
127 -> Box<dyn MacResult+'cx> {
128 if cx.trace_macros() {
129 trace_macros_note(cx, sp, format!("expanding `{}! {{ {} }}`", name, arg));
132 // Which arm's failure should we report? (the one furthest along)
133 let mut best_fail_spot = DUMMY_SP;
134 let mut best_fail_tok = None;
135 let mut best_fail_text = None;
137 for (i, lhs) in lhses.iter().enumerate() { // try each arm's matchers
138 let lhs_tt = match *lhs {
139 quoted::TokenTree::Delimited(_, ref delim) => &delim.tts[..],
140 _ => cx.span_bug(sp, "malformed macro lhs")
143 match TokenTree::parse(cx, lhs_tt, arg.clone()) {
144 Success(named_matches) => {
145 let rhs = match rhses[i] {
147 quoted::TokenTree::Delimited(_, ref delimed) => delimed.tts.clone(),
148 _ => cx.span_bug(sp, "malformed macro rhs"),
150 let arm_span = rhses[i].span();
152 let rhs_spans = rhs.iter().map(|t| t.span()).collect::<Vec<_>>();
153 // rhs has holes ( `$id` and `$(...)` that need filled)
154 let mut tts = transcribe(cx, Some(named_matches), rhs);
156 // Replace all the tokens for the corresponding positions in the macro, to maintain
157 // proper positions in error reporting, while maintaining the macro_backtrace.
158 if rhs_spans.len() == tts.len() {
159 tts = tts.map_enumerated(|i, mut tt| {
160 let mut sp = rhs_spans[i];
161 sp = sp.with_ctxt(tt.span().ctxt());
167 if cx.trace_macros() {
168 trace_macros_note(cx, sp, format!("to `{}`", tts));
171 let directory = Directory {
172 path: Cow::from(cx.current_expansion.module.directory.as_path()),
173 ownership: cx.current_expansion.directory_ownership,
175 let mut p = Parser::new(cx.parse_sess(), tts, Some(directory), true, false);
176 p.root_module_name = cx.current_expansion.module.mod_path.last()
177 .map(|id| id.as_str().to_string());
179 p.process_potential_macro_variable();
180 // Let the context choose how to interpret the result.
181 // Weird, but useful for X-macros.
182 return Box::new(ParserAnyMacro {
185 // Pass along the original expansion site and the name of the macro
186 // so we can print a useful error message if the parse of the expanded
187 // macro leaves unparsed tokens.
193 Failure(sp, tok, t) => if sp.lo() >= best_fail_spot.lo() {
195 best_fail_tok = Some(tok);
196 best_fail_text = Some(t);
198 Error(err_sp, ref msg) => {
199 cx.span_fatal(err_sp.substitute_dummy(sp), &msg[..])
204 let best_fail_msg = parse_failure_msg(best_fail_tok.expect("ran no matchers"));
205 let span = best_fail_spot.substitute_dummy(sp);
206 let mut err = cx.struct_span_err(span, &best_fail_msg);
207 err.span_label(span, best_fail_text.unwrap_or(&best_fail_msg));
208 if let Some(sp) = def_span {
209 if cx.source_map().span_to_filename(sp).is_real() && !sp.is_dummy() {
210 err.span_label(cx.source_map().def_span(sp), "when calling this macro");
214 // Check whether there's a missing comma in this macro call, like `println!("{}" a);`
215 if let Some((arg, comma_span)) = arg.add_comma() {
216 for lhs in lhses { // try each arm's matchers
217 let lhs_tt = match *lhs {
218 quoted::TokenTree::Delimited(_, ref delim) => &delim.tts[..],
221 match TokenTree::parse(cx, lhs_tt, arg.clone()) {
223 if comma_span.is_dummy() {
224 err.note("you might be missing a comma");
226 err.span_suggestion_short(
228 "missing comma here",
230 Applicability::MachineApplicable,
239 cx.trace_macros_diag();
243 // Note that macro-by-example's input is also matched against a token tree:
244 // $( $lhs:tt => $rhs:tt );+
246 // Holy self-referential!
248 /// Converts a `macro_rules!` invocation into a syntax extension.
254 ) -> SyntaxExtension {
255 let lhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("lhs"));
256 let rhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("rhs"));
258 // Parse the macro_rules! invocation
259 let body = match def.node {
260 ast::ItemKind::MacroDef(ref body) => body,
264 // The pattern that macro_rules matches.
265 // The grammar for macro_rules! is:
266 // $( $lhs:tt => $rhs:tt );+
267 // ...quasiquoting this would be nice.
268 // These spans won't matter, anyways
269 let argument_gram = vec![
270 quoted::TokenTree::Sequence(DelimSpan::dummy(), Lrc::new(quoted::SequenceRepetition {
272 quoted::TokenTree::MetaVarDecl(DUMMY_SP, lhs_nm, ast::Ident::from_str("tt")),
273 quoted::TokenTree::Token(DUMMY_SP, token::FatArrow),
274 quoted::TokenTree::MetaVarDecl(DUMMY_SP, rhs_nm, ast::Ident::from_str("tt")),
276 separator: Some(if body.legacy { token::Semi } else { token::Comma }),
277 op: quoted::KleeneOp::OneOrMore,
280 // to phase into semicolon-termination instead of semicolon-separation
281 quoted::TokenTree::Sequence(DelimSpan::dummy(), Lrc::new(quoted::SequenceRepetition {
282 tts: vec![quoted::TokenTree::Token(DUMMY_SP, token::Semi)],
284 op: quoted::KleeneOp::ZeroOrMore,
289 let argument_map = match parse(sess, body.stream(), &argument_gram, None, true) {
291 Failure(sp, tok, t) => {
292 let s = parse_failure_msg(tok);
293 let sp = sp.substitute_dummy(def.span);
294 let mut err = sess.span_diagnostic.struct_span_fatal(sp, &s);
295 err.span_label(sp, t);
300 sess.span_diagnostic.span_fatal(sp.substitute_dummy(def.span), &s).raise();
304 let mut valid = true;
306 // Extract the arguments:
307 let lhses = match *argument_map[&lhs_nm] {
308 MatchedSeq(ref s, _) => {
310 if let MatchedNonterminal(ref nt) = *m {
311 if let NtTT(ref tt) = **nt {
312 let tt = quoted::parse(
323 valid &= check_lhs_nt_follows(sess, features, &def.attrs, &tt);
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 lhs")
333 let rhses = match *argument_map[&rhs_nm] {
334 MatchedSeq(ref s, _) => {
336 if let MatchedNonterminal(ref nt) = *m {
337 if let NtTT(ref tt) = **nt {
338 return quoted::parse(
350 sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
351 }).collect::<Vec<quoted::TokenTree>>()
353 _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured rhs")
357 valid &= check_rhs(sess, rhs);
360 // don't abort iteration early, so that errors for multiple lhses can be reported
362 valid &= check_lhs_no_empty_seq(sess, &[lhs.clone()]);
363 valid &= check_lhs_duplicate_matcher_bindings(
366 &mut FxHashMap::default(),
371 let expander: Box<_> = Box::new(MacroRulesMacroExpander {
379 let allow_internal_unstable = attr::find_by_name(&def.attrs, "allow_internal_unstable")
382 .map(|list| list.iter()
383 .map(|it| it.name().unwrap_or_else(|| sess.span_diagnostic.span_bug(
384 it.span, "allow internal unstable expects feature names",
386 .collect::<Vec<Symbol>>().into()
389 sess.span_diagnostic.span_warn(
390 attr.span, "allow_internal_unstable expects list of feature names. In the \
391 future this will become a hard error. Please use `allow_internal_unstable(\
392 foo, bar)` to only allow the `foo` and `bar` features",
394 vec![Symbol::intern("allow_internal_unstable_backcompat_hack")].into()
397 let allow_internal_unsafe = attr::contains_name(&def.attrs, "allow_internal_unsafe");
398 let mut local_inner_macros = false;
399 if let Some(macro_export) = attr::find_by_name(&def.attrs, "macro_export") {
400 if let Some(l) = macro_export.meta_item_list() {
401 local_inner_macros = attr::list_contains_name(&l, "local_inner_macros");
405 let unstable_feature = attr::find_stability(&sess,
406 &def.attrs, def.span).and_then(|stability| {
407 if let attr::StabilityLevel::Unstable { issue, .. } = stability.level {
408 Some((stability.feature, issue))
416 def_info: Some((def.id, def.span)),
417 allow_internal_unstable,
418 allow_internal_unsafe,
424 let is_transparent = attr::contains_name(&def.attrs, "rustc_transparent_macro");
426 SyntaxExtension::DeclMacro {
428 def_info: Some((def.id, def.span)),
435 fn check_lhs_nt_follows(sess: &ParseSess,
437 attrs: &[ast::Attribute],
438 lhs: "ed::TokenTree) -> bool {
439 // lhs is going to be like TokenTree::Delimited(...), where the
440 // entire lhs is those tts. Or, it can be a "bare sequence", not wrapped in parens.
441 if let quoted::TokenTree::Delimited(_, ref tts) = *lhs {
442 check_matcher(sess, features, attrs, &tts.tts)
444 let msg = "invalid macro matcher; matchers must be contained in balanced delimiters";
445 sess.span_diagnostic.span_err(lhs.span(), msg);
448 // we don't abort on errors on rejection, the driver will do that for us
449 // after parsing/expansion. we can report every error in every macro this way.
452 /// Check that the lhs contains no repetition which could match an empty token
453 /// tree, because then the matcher would hang indefinitely.
454 fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[quoted::TokenTree]) -> bool {
455 use quoted::TokenTree;
458 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => (),
459 TokenTree::Delimited(_, ref del) => if !check_lhs_no_empty_seq(sess, &del.tts) {
462 TokenTree::Sequence(span, ref seq) => {
463 if seq.separator.is_none() && seq.tts.iter().all(|seq_tt| {
465 TokenTree::MetaVarDecl(_, _, id) => id.name == "vis",
466 TokenTree::Sequence(_, ref sub_seq) =>
467 sub_seq.op == quoted::KleeneOp::ZeroOrMore
468 || sub_seq.op == quoted::KleeneOp::ZeroOrOne,
472 let sp = span.entire();
473 sess.span_diagnostic.span_err(sp, "repetition matches empty token tree");
476 if !check_lhs_no_empty_seq(sess, &seq.tts) {
486 /// Check that the LHS contains no duplicate matcher bindings. e.g. `$a:expr, $a:expr` would be
487 /// illegal, since it would be ambiguous which `$a` to use if we ever needed to.
488 fn check_lhs_duplicate_matcher_bindings(
490 tts: &[quoted::TokenTree],
491 metavar_names: &mut FxHashMap<Ident, Span>,
492 node_id: ast::NodeId,
494 use self::quoted::TokenTree;
495 use crate::early_buffered_lints::BufferedEarlyLintId;
498 TokenTree::MetaVarDecl(span, name, _kind) => {
499 if let Some(&prev_span) = metavar_names.get(&name) {
500 // FIXME(mark-i-m): in a few cycles, make this a hard error.
501 // sess.span_diagnostic
502 // .struct_span_err(span, "duplicate matcher binding")
503 // .span_note(prev_span, "previous declaration was here")
506 BufferedEarlyLintId::DuplicateMacroMatcherBindingName,
507 crate::source_map::MultiSpan::from(vec![prev_span, span]),
509 "duplicate matcher binding"
513 metavar_names.insert(name, span);
516 TokenTree::Delimited(_, ref del) => {
517 if !check_lhs_duplicate_matcher_bindings(sess, &del.tts, metavar_names, node_id) {
521 TokenTree::Sequence(_, ref seq) => {
522 if !check_lhs_duplicate_matcher_bindings(sess, &seq.tts, metavar_names, node_id) {
533 fn check_rhs(sess: &ParseSess, rhs: "ed::TokenTree) -> bool {
535 quoted::TokenTree::Delimited(..) => return true,
536 _ => sess.span_diagnostic.span_err(rhs.span(), "macro rhs must be delimited")
541 fn check_matcher(sess: &ParseSess,
543 attrs: &[ast::Attribute],
544 matcher: &[quoted::TokenTree]) -> bool {
545 let first_sets = FirstSets::new(matcher);
546 let empty_suffix = TokenSet::empty();
547 let err = sess.span_diagnostic.err_count();
548 check_matcher_core(sess, features, attrs, &first_sets, matcher, &empty_suffix);
549 err == sess.span_diagnostic.err_count()
552 // `The FirstSets` for a matcher is a mapping from subsequences in the
553 // matcher to the FIRST set for that subsequence.
555 // This mapping is partially precomputed via a backwards scan over the
556 // token trees of the matcher, which provides a mapping from each
557 // repetition sequence to its *first* set.
559 // (Hypothetically, sequences should be uniquely identifiable via their
560 // spans, though perhaps that is false, e.g., for macro-generated macros
561 // that do not try to inject artificial span information. My plan is
562 // to try to catch such cases ahead of time and not include them in
563 // the precomputed mapping.)
565 // this maps each TokenTree::Sequence `$(tt ...) SEP OP` that is uniquely identified by its
566 // span in the original matcher to the First set for the inner sequence `tt ...`.
568 // If two sequences have the same span in a matcher, then map that
569 // span to None (invalidating the mapping here and forcing the code to
571 first: FxHashMap<Span, Option<TokenSet>>,
575 fn new(tts: &[quoted::TokenTree]) -> FirstSets {
576 use quoted::TokenTree;
578 let mut sets = FirstSets { first: FxHashMap::default() };
579 build_recur(&mut sets, tts);
582 // walks backward over `tts`, returning the FIRST for `tts`
583 // and updating `sets` at the same time for all sequence
584 // substructure we find within `tts`.
585 fn build_recur(sets: &mut FirstSets, tts: &[TokenTree]) -> TokenSet {
586 let mut first = TokenSet::empty();
587 for tt in tts.iter().rev() {
589 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
590 first.replace_with(tt.clone());
592 TokenTree::Delimited(span, ref delimited) => {
593 build_recur(sets, &delimited.tts[..]);
594 first.replace_with(delimited.open_tt(span.open));
596 TokenTree::Sequence(sp, ref seq_rep) => {
597 let subfirst = build_recur(sets, &seq_rep.tts[..]);
599 match sets.first.entry(sp.entire()) {
600 Entry::Vacant(vac) => {
601 vac.insert(Some(subfirst.clone()));
603 Entry::Occupied(mut occ) => {
604 // if there is already an entry, then a span must have collided.
605 // This should not happen with typical macro_rules macros,
606 // but syntax extensions need not maintain distinct spans,
607 // so distinct syntax trees can be assigned the same span.
608 // In such a case, the map cannot be trusted; so mark this
609 // entry as unusable.
614 // If the sequence contents can be empty, then the first
615 // token could be the separator token itself.
617 if let (Some(ref sep), true) = (seq_rep.separator.clone(),
618 subfirst.maybe_empty) {
619 first.add_one_maybe(TokenTree::Token(sp.entire(), sep.clone()));
622 // Reverse scan: Sequence comes before `first`.
623 if subfirst.maybe_empty
624 || seq_rep.op == quoted::KleeneOp::ZeroOrMore
625 || seq_rep.op == quoted::KleeneOp::ZeroOrOne
627 // If sequence is potentially empty, then
628 // union them (preserving first emptiness).
629 first.add_all(&TokenSet { maybe_empty: true, ..subfirst });
631 // Otherwise, sequence guaranteed
632 // non-empty; replace first.
643 // walks forward over `tts` until all potential FIRST tokens are
645 fn first(&self, tts: &[quoted::TokenTree]) -> TokenSet {
646 use quoted::TokenTree;
648 let mut first = TokenSet::empty();
649 for tt in tts.iter() {
650 assert!(first.maybe_empty);
652 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
653 first.add_one(tt.clone());
656 TokenTree::Delimited(span, ref delimited) => {
657 first.add_one(delimited.open_tt(span.open));
660 TokenTree::Sequence(sp, ref seq_rep) => {
661 match self.first.get(&sp.entire()) {
662 Some(&Some(ref subfirst)) => {
664 // If the sequence contents can be empty, then the first
665 // token could be the separator token itself.
667 if let (Some(ref sep), true) = (seq_rep.separator.clone(),
668 subfirst.maybe_empty) {
669 first.add_one_maybe(TokenTree::Token(sp.entire(), sep.clone()));
672 assert!(first.maybe_empty);
673 first.add_all(subfirst);
674 if subfirst.maybe_empty
675 || seq_rep.op == quoted::KleeneOp::ZeroOrMore
676 || seq_rep.op == quoted::KleeneOp::ZeroOrOne
678 // continue scanning for more first
679 // tokens, but also make sure we
680 // restore empty-tracking state
681 first.maybe_empty = true;
689 panic!("assume all sequences have (unique) spans for now");
693 panic!("We missed a sequence during FirstSets construction");
700 // we only exit the loop if `tts` was empty or if every
701 // element of `tts` matches the empty sequence.
702 assert!(first.maybe_empty);
707 // A set of `quoted::TokenTree`s, which may include `TokenTree::Match`s
708 // (for macro-by-example syntactic variables). It also carries the
709 // `maybe_empty` flag; that is true if and only if the matcher can
710 // match an empty token sequence.
712 // The First set is computed on submatchers like `$($a:expr b),* $(c)* d`,
713 // which has corresponding FIRST = {$a:expr, c, d}.
714 // Likewise, `$($a:expr b),* $(c)+ d` has FIRST = {$a:expr, c}.
716 // (Notably, we must allow for *-op to occur zero times.)
717 #[derive(Clone, Debug)]
719 tokens: Vec<quoted::TokenTree>,
724 // Returns a set for the empty sequence.
725 fn empty() -> Self { TokenSet { tokens: Vec::new(), maybe_empty: true } }
727 // Returns the set `{ tok }` for the single-token (and thus
728 // non-empty) sequence [tok].
729 fn singleton(tok: quoted::TokenTree) -> Self {
730 TokenSet { tokens: vec![tok], maybe_empty: false }
733 // Changes self to be the set `{ tok }`.
734 // Since `tok` is always present, marks self as non-empty.
735 fn replace_with(&mut self, tok: quoted::TokenTree) {
737 self.tokens.push(tok);
738 self.maybe_empty = false;
741 // Changes self to be the empty set `{}`; meant for use when
742 // the particular token does not matter, but we want to
743 // record that it occurs.
744 fn replace_with_irrelevant(&mut self) {
746 self.maybe_empty = false;
749 // Adds `tok` to the set for `self`, marking sequence as non-empy.
750 fn add_one(&mut self, tok: quoted::TokenTree) {
751 if !self.tokens.contains(&tok) {
752 self.tokens.push(tok);
754 self.maybe_empty = false;
757 // Adds `tok` to the set for `self`. (Leaves `maybe_empty` flag alone.)
758 fn add_one_maybe(&mut self, tok: quoted::TokenTree) {
759 if !self.tokens.contains(&tok) {
760 self.tokens.push(tok);
764 // Adds all elements of `other` to this.
766 // (Since this is a set, we filter out duplicates.)
768 // If `other` is potentially empty, then preserves the previous
769 // setting of the empty flag of `self`. If `other` is guaranteed
770 // non-empty, then `self` is marked non-empty.
771 fn add_all(&mut self, other: &Self) {
772 for tok in &other.tokens {
773 if !self.tokens.contains(tok) {
774 self.tokens.push(tok.clone());
777 if !other.maybe_empty {
778 self.maybe_empty = false;
783 // Checks that `matcher` is internally consistent and that it
784 // can legally by followed by a token N, for all N in `follow`.
785 // (If `follow` is empty, then it imposes no constraint on
788 // Returns the set of NT tokens that could possibly come last in
789 // `matcher`. (If `matcher` matches the empty sequence, then
790 // `maybe_empty` will be set to true.)
792 // Requires that `first_sets` is pre-computed for `matcher`;
793 // see `FirstSets::new`.
794 fn check_matcher_core(sess: &ParseSess,
796 attrs: &[ast::Attribute],
797 first_sets: &FirstSets,
798 matcher: &[quoted::TokenTree],
799 follow: &TokenSet) -> TokenSet {
800 use quoted::TokenTree;
802 let mut last = TokenSet::empty();
804 // 2. For each token and suffix [T, SUFFIX] in M:
805 // ensure that T can be followed by SUFFIX, and if SUFFIX may be empty,
806 // then ensure T can also be followed by any element of FOLLOW.
807 'each_token: for i in 0..matcher.len() {
808 let token = &matcher[i];
809 let suffix = &matcher[i+1..];
811 let build_suffix_first = || {
812 let mut s = first_sets.first(suffix);
813 if s.maybe_empty { s.add_all(follow); }
817 // (we build `suffix_first` on demand below; you can tell
818 // which cases are supposed to fall through by looking for the
819 // initialization of this variable.)
822 // First, update `last` so that it corresponds to the set
823 // of NT tokens that might end the sequence `... token`.
825 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
826 let can_be_followed_by_any;
827 if let Err(bad_frag) = has_legal_fragment_specifier(sess, features, attrs, token) {
828 let msg = format!("invalid fragment specifier `{}`", bad_frag);
829 sess.span_diagnostic.struct_span_err(token.span(), &msg)
830 .help(VALID_FRAGMENT_NAMES_MSG)
832 // (This eliminates false positives and duplicates
833 // from error messages.)
834 can_be_followed_by_any = true;
836 can_be_followed_by_any = token_can_be_followed_by_any(token);
839 if can_be_followed_by_any {
840 // don't need to track tokens that work with any,
841 last.replace_with_irrelevant();
842 // ... and don't need to check tokens that can be
843 // followed by anything against SUFFIX.
844 continue 'each_token;
846 last.replace_with(token.clone());
847 suffix_first = build_suffix_first();
850 TokenTree::Delimited(span, ref d) => {
851 let my_suffix = TokenSet::singleton(d.close_tt(span.close));
852 check_matcher_core(sess, features, attrs, first_sets, &d.tts, &my_suffix);
853 // don't track non NT tokens
854 last.replace_with_irrelevant();
856 // also, we don't need to check delimited sequences
858 continue 'each_token;
860 TokenTree::Sequence(sp, ref seq_rep) => {
861 suffix_first = build_suffix_first();
862 // The trick here: when we check the interior, we want
863 // to include the separator (if any) as a potential
864 // (but not guaranteed) element of FOLLOW. So in that
865 // case, we make a temp copy of suffix and stuff
866 // delimiter in there.
868 // FIXME: Should I first scan suffix_first to see if
869 // delimiter is already in it before I go through the
870 // work of cloning it? But then again, this way I may
871 // get a "tighter" span?
873 let my_suffix = if let Some(ref u) = seq_rep.separator {
874 new = suffix_first.clone();
875 new.add_one_maybe(TokenTree::Token(sp.entire(), u.clone()));
881 // At this point, `suffix_first` is built, and
882 // `my_suffix` is some TokenSet that we can use
883 // for checking the interior of `seq_rep`.
884 let next = check_matcher_core(sess,
890 if next.maybe_empty {
896 // the recursive call to check_matcher_core already ran the 'each_last
897 // check below, so we can just keep going forward here.
898 continue 'each_token;
902 // (`suffix_first` guaranteed initialized once reaching here.)
904 // Now `last` holds the complete set of NT tokens that could
905 // end the sequence before SUFFIX. Check that every one works with `suffix`.
906 'each_last: for token in &last.tokens {
907 if let TokenTree::MetaVarDecl(_, ref name, ref frag_spec) = *token {
908 for next_token in &suffix_first.tokens {
909 match is_in_follow(next_token, &frag_spec.as_str()) {
910 IsInFollow::Invalid(msg, help) => {
911 sess.span_diagnostic.struct_span_err(next_token.span(), &msg)
913 // don't bother reporting every source of
914 // conflict for a particular element of `last`.
917 IsInFollow::Yes => {}
918 IsInFollow::No(ref possible) => {
919 let may_be = if last.tokens.len() == 1 &&
920 suffix_first.tokens.len() == 1
927 let sp = next_token.span();
928 let mut err = sess.span_diagnostic.struct_span_err(
930 &format!("`${name}:{frag}` {may_be} followed by `{next}`, which \
931 is not allowed for `{frag}` fragments",
934 next=quoted_tt_to_string(next_token),
939 format!("not allowed after `{}` fragments", frag_spec),
941 let msg = "allowed there are: ";
942 match &possible[..] {
946 "only {} is allowed after `{}` fragments",
955 ts[..ts.len() - 1].iter().map(|s| *s)
956 .collect::<Vec<_>>().join(", "),
971 fn token_can_be_followed_by_any(tok: "ed::TokenTree) -> bool {
972 if let quoted::TokenTree::MetaVarDecl(_, _, frag_spec) = *tok {
973 frag_can_be_followed_by_any(&frag_spec.as_str())
975 // (Non NT's can always be followed by anthing in matchers.)
980 /// True if a fragment of type `frag` can be followed by any sort of
981 /// token. We use this (among other things) as a useful approximation
982 /// for when `frag` can be followed by a repetition like `$(...)*` or
983 /// `$(...)+`. In general, these can be a bit tricky to reason about,
984 /// so we adopt a conservative position that says that any fragment
985 /// specifier which consumes at most one token tree can be followed by
986 /// a fragment specifier (indeed, these fragments can be followed by
987 /// ANYTHING without fear of future compatibility hazards).
988 fn frag_can_be_followed_by_any(frag: &str) -> bool {
990 "item" | // always terminated by `}` or `;`
991 "block" | // exactly one token tree
992 "ident" | // exactly one token tree
993 "literal" | // exactly one token tree
994 "meta" | // exactly one token tree
995 "lifetime" | // exactly one token tree
996 "tt" => // exactly one token tree
1006 No(Vec<&'static str>),
1007 Invalid(String, &'static str),
1010 /// True if `frag` can legally be followed by the token `tok`. For
1011 /// fragments that can consume an unbounded number of tokens, `tok`
1012 /// must be within a well-defined follow set. This is intended to
1013 /// guarantee future compatibility: for example, without this rule, if
1014 /// we expanded `expr` to include a new binary operator, we might
1015 /// break macros that were relying on that binary operator as a
1017 // when changing this do not forget to update doc/book/macros.md!
1018 fn is_in_follow(tok: "ed::TokenTree, frag: &str) -> IsInFollow {
1019 use quoted::TokenTree;
1021 if let TokenTree::Token(_, token::CloseDelim(_)) = *tok {
1022 // closing a token tree can never be matched by any fragment;
1023 // iow, we always require that `(` and `)` match, etc.
1028 // since items *must* be followed by either a `;` or a `}`, we can
1029 // accept anything after them
1033 // anything can follow block, the braces provide an easy boundary to
1037 "stmt" | "expr" => {
1038 let tokens = vec!["`=>`", "`,`", "`;`"];
1040 TokenTree::Token(_, ref tok) => match *tok {
1041 FatArrow | Comma | Semi => IsInFollow::Yes,
1042 _ => IsInFollow::No(tokens),
1044 _ => IsInFollow::No(tokens),
1048 let tokens = vec!["`=>`", "`,`", "`=`", "`|`", "`if`", "`in`"];
1050 TokenTree::Token(_, ref tok) => match *tok {
1051 FatArrow | Comma | Eq | BinOp(token::Or) => IsInFollow::Yes,
1052 Ident(i, false) if i.name == "if" || i.name == "in" => IsInFollow::Yes,
1053 _ => IsInFollow::No(tokens),
1055 _ => IsInFollow::No(tokens),
1060 "`{`", "`[`", "`=>`", "`,`", "`>`","`=`", "`:`", "`;`", "`|`", "`as`",
1064 TokenTree::Token(_, ref tok) => match *tok {
1065 OpenDelim(token::DelimToken::Brace) |
1066 OpenDelim(token::DelimToken::Bracket) |
1067 Comma | FatArrow | Colon | Eq | Gt | BinOp(token::Shr) | Semi |
1068 BinOp(token::Or) => IsInFollow::Yes,
1069 Ident(i, false) if i.name == "as" || i.name == "where" => IsInFollow::Yes,
1070 _ => IsInFollow::No(tokens),
1072 TokenTree::MetaVarDecl(_, _, frag) if frag.name == "block" => IsInFollow::Yes,
1073 _ => IsInFollow::No(tokens),
1076 "ident" | "lifetime" => {
1077 // being a single token, idents and lifetimes are harmless
1081 // literals may be of a single token, or two tokens (negative numbers)
1085 // being either a single token or a delimited sequence, tt is
1090 // Explicitly disallow `priv`, on the off chance it comes back.
1091 let tokens = vec!["`,`", "an ident", "a type"];
1093 TokenTree::Token(_, ref tok) => match *tok {
1094 Comma => IsInFollow::Yes,
1095 Ident(i, is_raw) if is_raw || i.name != "priv" => IsInFollow::Yes,
1096 ref tok => if tok.can_begin_type() {
1099 IsInFollow::No(tokens)
1102 TokenTree::MetaVarDecl(_, _, frag) if frag.name == "ident"
1103 || frag.name == "ty"
1104 || frag.name == "path" => IsInFollow::Yes,
1105 _ => IsInFollow::No(tokens),
1108 "" => IsInFollow::Yes, // keywords::Invalid
1109 _ => IsInFollow::Invalid(format!("invalid fragment specifier `{}`", frag),
1110 VALID_FRAGMENT_NAMES_MSG),
1115 fn has_legal_fragment_specifier(sess: &ParseSess,
1116 features: &Features,
1117 attrs: &[ast::Attribute],
1118 tok: "ed::TokenTree) -> Result<(), String> {
1119 debug!("has_legal_fragment_specifier({:?})", tok);
1120 if let quoted::TokenTree::MetaVarDecl(_, _, ref frag_spec) = *tok {
1121 let frag_name = frag_spec.as_str();
1122 let frag_span = tok.span();
1123 if !is_legal_fragment_specifier(sess, features, attrs, &frag_name, frag_span) {
1124 return Err(frag_name.to_string());
1130 fn is_legal_fragment_specifier(_sess: &ParseSess,
1131 _features: &Features,
1132 _attrs: &[ast::Attribute],
1134 _frag_span: Span) -> bool {
1136 * If new fragment specifiers are invented in nightly, `_sess`,
1137 * `_features`, `_attrs`, and `_frag_span` will be useful here
1138 * for checking against feature gates. See past versions of
1142 "item" | "block" | "stmt" | "expr" | "pat" | "lifetime" |
1143 "path" | "ty" | "ident" | "meta" | "tt" | "vis" | "literal" |
1149 fn quoted_tt_to_string(tt: "ed::TokenTree) -> String {
1151 quoted::TokenTree::Token(_, ref tok) => crate::print::pprust::token_to_string(tok),
1152 quoted::TokenTree::MetaVar(_, name) => format!("${}", name),
1153 quoted::TokenTree::MetaVarDecl(_, name, kind) => format!("${}:{}", name, kind),
1154 _ => panic!("unexpected quoted::TokenTree::{{Sequence or Delimited}} \
1155 in follow set checker"),