2 use crate::attr::{self, TransparencyError};
3 use crate::edition::Edition;
4 use crate::ext::base::{DummyResult, ExtCtxt, MacResult, TTMacroExpander};
5 use crate::ext::base::{SyntaxExtension, SyntaxExtensionKind};
6 use crate::ext::expand::{AstFragment, AstFragmentKind};
8 use crate::ext::mbe::macro_check;
9 use crate::ext::mbe::macro_parser::parse;
10 use crate::ext::mbe::macro_parser::{Error, Failure, Success};
11 use crate::ext::mbe::macro_parser::{MatchedNonterminal, MatchedSeq, NamedParseResult};
12 use crate::ext::mbe::transcribe::transcribe;
13 use crate::feature_gate::Features;
14 use crate::parse::parser::Parser;
15 use crate::parse::token::TokenKind::*;
16 use crate::parse::token::{self, NtTT, Token};
17 use crate::parse::{Directory, ParseSess};
18 use crate::print::pprust;
19 use crate::symbol::{kw, sym, Symbol};
20 use crate::tokenstream::{DelimSpan, TokenStream, TokenTree};
22 use errors::{DiagnosticBuilder, FatalError};
24 use syntax_pos::hygiene::Transparency;
27 use rustc_data_structures::fx::FxHashMap;
29 use std::collections::hash_map::Entry;
32 use errors::Applicability;
33 use rustc_data_structures::sync::Lrc;
35 const VALID_FRAGMENT_NAMES_MSG: &str = "valid fragment specifiers are \
36 `ident`, `block`, `stmt`, `expr`, `pat`, `ty`, `lifetime`, \
37 `literal`, `path`, `meta`, `tt`, `item` and `vis`";
39 crate struct ParserAnyMacro<'a> {
42 /// Span of the expansion site of the macro this parser is for
44 /// The ident of the macro we're parsing
45 macro_ident: ast::Ident,
49 crate fn annotate_err_with_kind(
50 err: &mut DiagnosticBuilder<'_>,
51 kind: AstFragmentKind,
55 AstFragmentKind::Ty => {
56 err.span_label(span, "this macro call doesn't expand to a type");
58 AstFragmentKind::Pat => {
59 err.span_label(span, "this macro call doesn't expand to a pattern");
65 impl<'a> ParserAnyMacro<'a> {
66 crate fn make(mut self: Box<ParserAnyMacro<'a>>, kind: AstFragmentKind) -> AstFragment {
67 let ParserAnyMacro { site_span, macro_ident, ref mut parser, arm_span } = *self;
68 let fragment = panictry!(parser.parse_ast_fragment(kind, true).map_err(|mut e| {
69 if parser.token == token::Eof && e.message().ends_with(", found `<eof>`") {
70 if !e.span.is_dummy() {
71 // early end of macro arm (#52866)
72 e.replace_span_with(parser.sess.source_map().next_point(parser.token.span));
74 let msg = &e.message[0];
77 "macro expansion ends with an incomplete expression: {}",
78 msg.0.replace(", found `<eof>`", ""),
83 if e.span.is_dummy() {
84 // Get around lack of span in error (#30128)
85 e.replace_span_with(site_span);
86 if parser.sess.source_map().span_to_filename(arm_span).is_real() {
87 e.span_label(arm_span, "in this macro arm");
89 } else if !parser.sess.source_map().span_to_filename(parser.token.span).is_real() {
90 e.span_label(site_span, "in this macro invocation");
93 AstFragmentKind::Pat if macro_ident.name == sym::vec => {
94 let mut suggestion = None;
95 if let Ok(code) = parser.sess.source_map().span_to_snippet(site_span) {
96 if let Some(bang) = code.find('!') {
97 suggestion = Some(code[bang + 1..].to_string());
100 if let Some(suggestion) = suggestion {
103 "use a slice pattern here instead",
105 Applicability::MachineApplicable,
110 "use a slice pattern here instead",
113 e.help("for more information, see https://doc.rust-lang.org/edition-guide/\
114 rust-2018/slice-patterns.html");
116 _ => annotate_err_with_kind(&mut e, kind, site_span),
121 // We allow semicolons at the end of expressions -- e.g., the semicolon in
122 // `macro_rules! m { () => { panic!(); } }` isn't parsed by `.parse_expr()`,
123 // but `m!()` is allowed in expression positions (cf. issue #34706).
124 if kind == AstFragmentKind::Expr && parser.token == token::Semi {
128 // Make sure we don't have any tokens left to parse so we don't silently drop anything.
129 let path = ast::Path::from_ident(macro_ident.with_span_pos(site_span));
130 parser.ensure_complete_parse(&path, kind.name(), site_span);
135 struct MacroRulesMacroExpander {
138 transparency: Transparency,
139 lhses: Vec<mbe::TokenTree>,
140 rhses: Vec<mbe::TokenTree>,
144 impl TTMacroExpander for MacroRulesMacroExpander {
147 cx: &'cx mut ExtCtxt<'_>,
150 ) -> Box<dyn MacResult + 'cx> {
152 return DummyResult::any(sp);
155 cx, sp, self.span, self.name, self.transparency, input, &self.lhses, &self.rhses
160 fn trace_macros_note(cx: &mut ExtCtxt<'_>, sp: Span, message: String) {
161 let sp = sp.macro_backtrace().last().map(|trace| trace.call_site).unwrap_or(sp);
162 cx.expansions.entry(sp).or_default().push(message);
165 /// Given `lhses` and `rhses`, this is the new macro we create
166 fn generic_extension<'cx>(
167 cx: &'cx mut ExtCtxt<'_>,
171 transparency: Transparency,
173 lhses: &[mbe::TokenTree],
174 rhses: &[mbe::TokenTree],
175 ) -> Box<dyn MacResult + 'cx> {
176 if cx.trace_macros() {
177 trace_macros_note(cx, sp, format!("expanding `{}! {{ {} }}`", name, arg));
180 // Which arm's failure should we report? (the one furthest along)
181 let mut best_failure: Option<(Token, &str)> = None;
183 for (i, lhs) in lhses.iter().enumerate() {
184 // try each arm's matchers
185 let lhs_tt = match *lhs {
186 mbe::TokenTree::Delimited(_, ref delim) => &delim.tts[..],
187 _ => cx.span_bug(sp, "malformed macro lhs"),
190 match TokenTree::parse(cx, lhs_tt, arg.clone()) {
191 Success(named_matches) => {
192 let rhs = match rhses[i] {
194 mbe::TokenTree::Delimited(_, ref delimed) => delimed.tts.clone(),
195 _ => cx.span_bug(sp, "malformed macro rhs"),
197 let arm_span = rhses[i].span();
199 let rhs_spans = rhs.iter().map(|t| t.span()).collect::<Vec<_>>();
200 // rhs has holes ( `$id` and `$(...)` that need filled)
201 let mut tts = transcribe(cx, &named_matches, rhs, transparency);
203 // Replace all the tokens for the corresponding positions in the macro, to maintain
204 // proper positions in error reporting, while maintaining the macro_backtrace.
205 if rhs_spans.len() == tts.len() {
206 tts = tts.map_enumerated(|i, mut tt| {
207 let mut sp = rhs_spans[i];
208 sp = sp.with_ctxt(tt.span().ctxt());
214 if cx.trace_macros() {
215 trace_macros_note(cx, sp, format!("to `{}`", tts));
218 let directory = Directory {
219 path: Cow::from(cx.current_expansion.module.directory.as_path()),
220 ownership: cx.current_expansion.directory_ownership,
222 let mut p = Parser::new(cx.parse_sess(), tts, Some(directory), true, false, None);
224 cx.current_expansion.module.mod_path.last().map(|id| id.as_str().to_string());
225 p.last_type_ascription = cx.current_expansion.prior_type_ascription;
227 p.process_potential_macro_variable();
228 // Let the context choose how to interpret the result.
229 // Weird, but useful for X-macros.
230 return Box::new(ParserAnyMacro {
233 // Pass along the original expansion site and the name of the macro
234 // so we can print a useful error message if the parse of the expanded
235 // macro leaves unparsed tokens.
241 Failure(token, msg) => match best_failure {
242 Some((ref best_token, _)) if best_token.span.lo() >= token.span.lo() => {}
243 _ => best_failure = Some((token, msg)),
245 Error(err_sp, ref msg) => cx.span_fatal(err_sp.substitute_dummy(sp), &msg[..]),
249 let (token, label) = best_failure.expect("ran no matchers");
250 let span = token.span.substitute_dummy(sp);
251 let mut err = cx.struct_span_err(span, &parse_failure_msg(&token));
252 err.span_label(span, label);
253 if !def_span.is_dummy() && cx.source_map().span_to_filename(def_span).is_real() {
254 err.span_label(cx.source_map().def_span(def_span), "when calling this macro");
257 // Check whether there's a missing comma in this macro call, like `println!("{}" a);`
258 if let Some((arg, comma_span)) = arg.add_comma() {
260 // try each arm's matchers
261 let lhs_tt = match *lhs {
262 mbe::TokenTree::Delimited(_, ref delim) => &delim.tts[..],
265 match TokenTree::parse(cx, lhs_tt, arg.clone()) {
267 if comma_span.is_dummy() {
268 err.note("you might be missing a comma");
270 err.span_suggestion_short(
272 "missing comma here",
274 Applicability::MachineApplicable,
283 cx.trace_macros_diag();
287 // Note that macro-by-example's input is also matched against a token tree:
288 // $( $lhs:tt => $rhs:tt );+
290 // Holy self-referential!
292 /// Converts a macro item into a syntax extension.
293 pub fn compile_declarative_macro(
298 ) -> SyntaxExtension {
299 let diag = &sess.span_diagnostic;
300 let lhs_nm = ast::Ident::new(sym::lhs, def.span);
301 let rhs_nm = ast::Ident::new(sym::rhs, def.span);
302 let tt_spec = ast::Ident::new(sym::tt, def.span);
304 // Parse the macro_rules! invocation
305 let body = match def.node {
306 ast::ItemKind::MacroDef(ref body) => body,
310 // The pattern that macro_rules matches.
311 // The grammar for macro_rules! is:
312 // $( $lhs:tt => $rhs:tt );+
313 // ...quasiquoting this would be nice.
314 // These spans won't matter, anyways
315 let argument_gram = vec![
316 mbe::TokenTree::Sequence(
318 Lrc::new(mbe::SequenceRepetition {
320 mbe::TokenTree::MetaVarDecl(def.span, lhs_nm, tt_spec),
321 mbe::TokenTree::token(token::FatArrow, def.span),
322 mbe::TokenTree::MetaVarDecl(def.span, rhs_nm, tt_spec),
324 separator: Some(Token::new(
325 if body.legacy { token::Semi } else { token::Comma },
328 kleene: mbe::KleeneToken::new(mbe::KleeneOp::OneOrMore, def.span),
332 // to phase into semicolon-termination instead of semicolon-separation
333 mbe::TokenTree::Sequence(
335 Lrc::new(mbe::SequenceRepetition {
336 tts: vec![mbe::TokenTree::token(
337 if body.legacy { token::Semi } else { token::Comma },
341 kleene: mbe::KleeneToken::new(mbe::KleeneOp::ZeroOrMore, def.span),
347 let argument_map = match parse(sess, body.stream(), &argument_gram, None, true) {
349 Failure(token, msg) => {
350 let s = parse_failure_msg(&token);
351 let sp = token.span.substitute_dummy(def.span);
352 let mut err = sess.span_diagnostic.struct_span_fatal(sp, &s);
353 err.span_label(sp, msg);
358 sess.span_diagnostic.span_fatal(sp.substitute_dummy(def.span), &s).raise();
362 let mut valid = true;
364 // Extract the arguments:
365 let lhses = match argument_map[&lhs_nm] {
366 MatchedSeq(ref s, _) => s
369 if let MatchedNonterminal(ref nt) = *m {
370 if let NtTT(ref tt) = **nt {
371 let tt = mbe::quoted::parse(
378 valid &= check_lhs_nt_follows(sess, features, &def.attrs, &tt);
382 sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
384 .collect::<Vec<mbe::TokenTree>>(),
385 _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs"),
388 let rhses = match argument_map[&rhs_nm] {
389 MatchedSeq(ref s, _) => s
392 if let MatchedNonterminal(ref nt) = *m {
393 if let NtTT(ref tt) = **nt {
394 return mbe::quoted::parse(
403 sess.span_diagnostic.span_bug(def.span, "wrong-structured lhs")
405 .collect::<Vec<mbe::TokenTree>>(),
406 _ => sess.span_diagnostic.span_bug(def.span, "wrong-structured rhs"),
410 valid &= check_rhs(sess, rhs);
413 // don't abort iteration early, so that errors for multiple lhses can be reported
415 valid &= check_lhs_no_empty_seq(sess, slice::from_ref(lhs));
418 // We use CRATE_NODE_ID instead of `def.id` otherwise we may emit buffered lints for a node id
419 // that is not lint-checked and trigger the "failed to process buffered lint here" bug.
420 valid &= macro_check::check_meta_variables(sess, ast::CRATE_NODE_ID, def.span, &lhses, &rhses);
422 let (transparency, transparency_error) = attr::find_transparency(&def.attrs, body.legacy);
423 match transparency_error {
424 Some(TransparencyError::UnknownTransparency(value, span)) =>
425 diag.span_err(span, &format!("unknown macro transparency: `{}`", value)),
426 Some(TransparencyError::MultipleTransparencyAttrs(old_span, new_span)) =>
427 diag.span_err(vec![old_span, new_span], "multiple macro transparency attributes"),
431 let expander: Box<_> = Box::new(MacroRulesMacroExpander {
432 name: def.ident, span: def.span, transparency, lhses, rhses, valid
435 SyntaxExtension::new(
437 SyntaxExtensionKind::LegacyBang(expander),
446 fn check_lhs_nt_follows(
449 attrs: &[ast::Attribute],
450 lhs: &mbe::TokenTree,
452 // lhs is going to be like TokenTree::Delimited(...), where the
453 // entire lhs is those tts. Or, it can be a "bare sequence", not wrapped in parens.
454 if let mbe::TokenTree::Delimited(_, ref tts) = *lhs {
455 check_matcher(sess, features, attrs, &tts.tts)
457 let msg = "invalid macro matcher; matchers must be contained in balanced delimiters";
458 sess.span_diagnostic.span_err(lhs.span(), msg);
461 // we don't abort on errors on rejection, the driver will do that for us
462 // after parsing/expansion. we can report every error in every macro this way.
465 /// Checks that the lhs contains no repetition which could match an empty token
466 /// tree, because then the matcher would hang indefinitely.
467 fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[mbe::TokenTree]) -> bool {
471 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => (),
472 TokenTree::Delimited(_, ref del) => {
473 if !check_lhs_no_empty_seq(sess, &del.tts) {
477 TokenTree::Sequence(span, ref seq) => {
478 if seq.separator.is_none()
479 && seq.tts.iter().all(|seq_tt| match *seq_tt {
480 TokenTree::MetaVarDecl(_, _, id) => id.name == sym::vis,
481 TokenTree::Sequence(_, ref sub_seq) => {
482 sub_seq.kleene.op == mbe::KleeneOp::ZeroOrMore
483 || sub_seq.kleene.op == mbe::KleeneOp::ZeroOrOne
488 let sp = span.entire();
489 sess.span_diagnostic.span_err(sp, "repetition matches empty token tree");
492 if !check_lhs_no_empty_seq(sess, &seq.tts) {
502 fn check_rhs(sess: &ParseSess, rhs: &mbe::TokenTree) -> bool {
504 mbe::TokenTree::Delimited(..) => return true,
505 _ => sess.span_diagnostic.span_err(rhs.span(), "macro rhs must be delimited"),
513 attrs: &[ast::Attribute],
514 matcher: &[mbe::TokenTree],
516 let first_sets = FirstSets::new(matcher);
517 let empty_suffix = TokenSet::empty();
518 let err = sess.span_diagnostic.err_count();
519 check_matcher_core(sess, features, attrs, &first_sets, matcher, &empty_suffix);
520 err == sess.span_diagnostic.err_count()
523 // `The FirstSets` for a matcher is a mapping from subsequences in the
524 // matcher to the FIRST set for that subsequence.
526 // This mapping is partially precomputed via a backwards scan over the
527 // token trees of the matcher, which provides a mapping from each
528 // repetition sequence to its *first* set.
530 // (Hypothetically, sequences should be uniquely identifiable via their
531 // spans, though perhaps that is false, e.g., for macro-generated macros
532 // that do not try to inject artificial span information. My plan is
533 // to try to catch such cases ahead of time and not include them in
534 // the precomputed mapping.)
536 // this maps each TokenTree::Sequence `$(tt ...) SEP OP` that is uniquely identified by its
537 // span in the original matcher to the First set for the inner sequence `tt ...`.
539 // If two sequences have the same span in a matcher, then map that
540 // span to None (invalidating the mapping here and forcing the code to
542 first: FxHashMap<Span, Option<TokenSet>>,
546 fn new(tts: &[mbe::TokenTree]) -> FirstSets {
549 let mut sets = FirstSets { first: FxHashMap::default() };
550 build_recur(&mut sets, tts);
553 // walks backward over `tts`, returning the FIRST for `tts`
554 // and updating `sets` at the same time for all sequence
555 // substructure we find within `tts`.
556 fn build_recur(sets: &mut FirstSets, tts: &[TokenTree]) -> TokenSet {
557 let mut first = TokenSet::empty();
558 for tt in tts.iter().rev() {
560 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
561 first.replace_with(tt.clone());
563 TokenTree::Delimited(span, ref delimited) => {
564 build_recur(sets, &delimited.tts[..]);
565 first.replace_with(delimited.open_tt(span.open));
567 TokenTree::Sequence(sp, ref seq_rep) => {
568 let subfirst = build_recur(sets, &seq_rep.tts[..]);
570 match sets.first.entry(sp.entire()) {
571 Entry::Vacant(vac) => {
572 vac.insert(Some(subfirst.clone()));
574 Entry::Occupied(mut occ) => {
575 // if there is already an entry, then a span must have collided.
576 // This should not happen with typical macro_rules macros,
577 // but syntax extensions need not maintain distinct spans,
578 // so distinct syntax trees can be assigned the same span.
579 // In such a case, the map cannot be trusted; so mark this
580 // entry as unusable.
585 // If the sequence contents can be empty, then the first
586 // token could be the separator token itself.
588 if let (Some(sep), true) = (&seq_rep.separator, subfirst.maybe_empty) {
589 first.add_one_maybe(TokenTree::Token(sep.clone()));
592 // Reverse scan: Sequence comes before `first`.
593 if subfirst.maybe_empty
594 || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrMore
595 || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrOne
597 // If sequence is potentially empty, then
598 // union them (preserving first emptiness).
599 first.add_all(&TokenSet { maybe_empty: true, ..subfirst });
601 // Otherwise, sequence guaranteed
602 // non-empty; replace first.
613 // walks forward over `tts` until all potential FIRST tokens are
615 fn first(&self, tts: &[mbe::TokenTree]) -> TokenSet {
618 let mut first = TokenSet::empty();
619 for tt in tts.iter() {
620 assert!(first.maybe_empty);
622 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
623 first.add_one(tt.clone());
626 TokenTree::Delimited(span, ref delimited) => {
627 first.add_one(delimited.open_tt(span.open));
630 TokenTree::Sequence(sp, ref seq_rep) => {
632 let subfirst = match self.first.get(&sp.entire()) {
633 Some(&Some(ref subfirst)) => subfirst,
635 subfirst_owned = self.first(&seq_rep.tts[..]);
639 panic!("We missed a sequence during FirstSets construction");
643 // If the sequence contents can be empty, then the first
644 // token could be the separator token itself.
645 if let (Some(sep), true) = (&seq_rep.separator, subfirst.maybe_empty) {
646 first.add_one_maybe(TokenTree::Token(sep.clone()));
649 assert!(first.maybe_empty);
650 first.add_all(subfirst);
651 if subfirst.maybe_empty
652 || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrMore
653 || seq_rep.kleene.op == mbe::KleeneOp::ZeroOrOne
655 // Continue scanning for more first
656 // tokens, but also make sure we
657 // restore empty-tracking state.
658 first.maybe_empty = true;
667 // we only exit the loop if `tts` was empty or if every
668 // element of `tts` matches the empty sequence.
669 assert!(first.maybe_empty);
674 // A set of `mbe::TokenTree`s, which may include `TokenTree::Match`s
675 // (for macro-by-example syntactic variables). It also carries the
676 // `maybe_empty` flag; that is true if and only if the matcher can
677 // match an empty token sequence.
679 // The First set is computed on submatchers like `$($a:expr b),* $(c)* d`,
680 // which has corresponding FIRST = {$a:expr, c, d}.
681 // Likewise, `$($a:expr b),* $(c)+ d` has FIRST = {$a:expr, c}.
683 // (Notably, we must allow for *-op to occur zero times.)
684 #[derive(Clone, Debug)]
686 tokens: Vec<mbe::TokenTree>,
691 // Returns a set for the empty sequence.
693 TokenSet { tokens: Vec::new(), maybe_empty: true }
696 // Returns the set `{ tok }` for the single-token (and thus
697 // non-empty) sequence [tok].
698 fn singleton(tok: mbe::TokenTree) -> Self {
699 TokenSet { tokens: vec![tok], maybe_empty: false }
702 // Changes self to be the set `{ tok }`.
703 // Since `tok` is always present, marks self as non-empty.
704 fn replace_with(&mut self, tok: mbe::TokenTree) {
706 self.tokens.push(tok);
707 self.maybe_empty = false;
710 // Changes self to be the empty set `{}`; meant for use when
711 // the particular token does not matter, but we want to
712 // record that it occurs.
713 fn replace_with_irrelevant(&mut self) {
715 self.maybe_empty = false;
718 // Adds `tok` to the set for `self`, marking sequence as non-empy.
719 fn add_one(&mut self, tok: mbe::TokenTree) {
720 if !self.tokens.contains(&tok) {
721 self.tokens.push(tok);
723 self.maybe_empty = false;
726 // Adds `tok` to the set for `self`. (Leaves `maybe_empty` flag alone.)
727 fn add_one_maybe(&mut self, tok: mbe::TokenTree) {
728 if !self.tokens.contains(&tok) {
729 self.tokens.push(tok);
733 // Adds all elements of `other` to this.
735 // (Since this is a set, we filter out duplicates.)
737 // If `other` is potentially empty, then preserves the previous
738 // setting of the empty flag of `self`. If `other` is guaranteed
739 // non-empty, then `self` is marked non-empty.
740 fn add_all(&mut self, other: &Self) {
741 for tok in &other.tokens {
742 if !self.tokens.contains(tok) {
743 self.tokens.push(tok.clone());
746 if !other.maybe_empty {
747 self.maybe_empty = false;
752 // Checks that `matcher` is internally consistent and that it
753 // can legally be followed by a token `N`, for all `N` in `follow`.
754 // (If `follow` is empty, then it imposes no constraint on
757 // Returns the set of NT tokens that could possibly come last in
758 // `matcher`. (If `matcher` matches the empty sequence, then
759 // `maybe_empty` will be set to true.)
761 // Requires that `first_sets` is pre-computed for `matcher`;
762 // see `FirstSets::new`.
763 fn check_matcher_core(
766 attrs: &[ast::Attribute],
767 first_sets: &FirstSets,
768 matcher: &[mbe::TokenTree],
773 let mut last = TokenSet::empty();
775 // 2. For each token and suffix [T, SUFFIX] in M:
776 // ensure that T can be followed by SUFFIX, and if SUFFIX may be empty,
777 // then ensure T can also be followed by any element of FOLLOW.
778 'each_token: for i in 0..matcher.len() {
779 let token = &matcher[i];
780 let suffix = &matcher[i + 1..];
782 let build_suffix_first = || {
783 let mut s = first_sets.first(suffix);
790 // (we build `suffix_first` on demand below; you can tell
791 // which cases are supposed to fall through by looking for the
792 // initialization of this variable.)
795 // First, update `last` so that it corresponds to the set
796 // of NT tokens that might end the sequence `... token`.
798 TokenTree::Token(..) | TokenTree::MetaVar(..) | TokenTree::MetaVarDecl(..) => {
799 let can_be_followed_by_any;
800 if let Err(bad_frag) = has_legal_fragment_specifier(sess, features, attrs, token) {
801 let msg = format!("invalid fragment specifier `{}`", bad_frag);
803 .struct_span_err(token.span(), &msg)
804 .help(VALID_FRAGMENT_NAMES_MSG)
806 // (This eliminates false positives and duplicates
807 // from error messages.)
808 can_be_followed_by_any = true;
810 can_be_followed_by_any = token_can_be_followed_by_any(token);
813 if can_be_followed_by_any {
814 // don't need to track tokens that work with any,
815 last.replace_with_irrelevant();
816 // ... and don't need to check tokens that can be
817 // followed by anything against SUFFIX.
818 continue 'each_token;
820 last.replace_with(token.clone());
821 suffix_first = build_suffix_first();
824 TokenTree::Delimited(span, ref d) => {
825 let my_suffix = TokenSet::singleton(d.close_tt(span.close));
826 check_matcher_core(sess, features, attrs, first_sets, &d.tts, &my_suffix);
827 // don't track non NT tokens
828 last.replace_with_irrelevant();
830 // also, we don't need to check delimited sequences
832 continue 'each_token;
834 TokenTree::Sequence(_, ref seq_rep) => {
835 suffix_first = build_suffix_first();
836 // The trick here: when we check the interior, we want
837 // to include the separator (if any) as a potential
838 // (but not guaranteed) element of FOLLOW. So in that
839 // case, we make a temp copy of suffix and stuff
840 // delimiter in there.
842 // FIXME: Should I first scan suffix_first to see if
843 // delimiter is already in it before I go through the
844 // work of cloning it? But then again, this way I may
845 // get a "tighter" span?
847 let my_suffix = if let Some(sep) = &seq_rep.separator {
848 new = suffix_first.clone();
849 new.add_one_maybe(TokenTree::Token(sep.clone()));
855 // At this point, `suffix_first` is built, and
856 // `my_suffix` is some TokenSet that we can use
857 // for checking the interior of `seq_rep`.
859 check_matcher_core(sess, features, attrs, first_sets, &seq_rep.tts, my_suffix);
860 if next.maybe_empty {
866 // the recursive call to check_matcher_core already ran the 'each_last
867 // check below, so we can just keep going forward here.
868 continue 'each_token;
872 // (`suffix_first` guaranteed initialized once reaching here.)
874 // Now `last` holds the complete set of NT tokens that could
875 // end the sequence before SUFFIX. Check that every one works with `suffix`.
876 'each_last: for token in &last.tokens {
877 if let TokenTree::MetaVarDecl(_, name, frag_spec) = *token {
878 for next_token in &suffix_first.tokens {
879 match is_in_follow(next_token, frag_spec.name) {
880 IsInFollow::Invalid(msg, help) => {
882 .struct_span_err(next_token.span(), &msg)
885 // don't bother reporting every source of
886 // conflict for a particular element of `last`.
889 IsInFollow::Yes => {}
890 IsInFollow::No(possible) => {
891 let may_be = if last.tokens.len() == 1 && suffix_first.tokens.len() == 1
898 let sp = next_token.span();
899 let mut err = sess.span_diagnostic.struct_span_err(
902 "`${name}:{frag}` {may_be} followed by `{next}`, which \
903 is not allowed for `{frag}` fragments",
906 next = quoted_tt_to_string(next_token),
912 format!("not allowed after `{}` fragments", frag_spec),
914 let msg = "allowed there are: ";
919 "only {} is allowed after `{}` fragments",
946 fn token_can_be_followed_by_any(tok: &mbe::TokenTree) -> bool {
947 if let mbe::TokenTree::MetaVarDecl(_, _, frag_spec) = *tok {
948 frag_can_be_followed_by_any(frag_spec.name)
950 // (Non NT's can always be followed by anthing in matchers.)
955 /// Returns `true` if a fragment of type `frag` can be followed by any sort of
956 /// token. We use this (among other things) as a useful approximation
957 /// for when `frag` can be followed by a repetition like `$(...)*` or
958 /// `$(...)+`. In general, these can be a bit tricky to reason about,
959 /// so we adopt a conservative position that says that any fragment
960 /// specifier which consumes at most one token tree can be followed by
961 /// a fragment specifier (indeed, these fragments can be followed by
962 /// ANYTHING without fear of future compatibility hazards).
963 fn frag_can_be_followed_by_any(frag: Symbol) -> bool {
965 sym::item | // always terminated by `}` or `;`
966 sym::block | // exactly one token tree
967 sym::ident | // exactly one token tree
968 sym::literal | // exactly one token tree
969 sym::meta | // exactly one token tree
970 sym::lifetime | // exactly one token tree
971 sym::tt => // exactly one token tree
981 No(&'static [&'static str]),
982 Invalid(String, &'static str),
985 /// Returns `true` if `frag` can legally be followed by the token `tok`. For
986 /// fragments that can consume an unbounded number of tokens, `tok`
987 /// must be within a well-defined follow set. This is intended to
988 /// guarantee future compatibility: for example, without this rule, if
989 /// we expanded `expr` to include a new binary operator, we might
990 /// break macros that were relying on that binary operator as a
992 // when changing this do not forget to update doc/book/macros.md!
993 fn is_in_follow(tok: &mbe::TokenTree, frag: Symbol) -> IsInFollow {
996 if let TokenTree::Token(Token { kind: token::CloseDelim(_), .. }) = *tok {
997 // closing a token tree can never be matched by any fragment;
998 // iow, we always require that `(` and `)` match, etc.
1003 // since items *must* be followed by either a `;` or a `}`, we can
1004 // accept anything after them
1008 // anything can follow block, the braces provide an easy boundary to
1012 sym::stmt | sym::expr => {
1013 const TOKENS: &[&str] = &["`=>`", "`,`", "`;`"];
1015 TokenTree::Token(token) => match token.kind {
1016 FatArrow | Comma | Semi => IsInFollow::Yes,
1017 _ => IsInFollow::No(TOKENS),
1019 _ => IsInFollow::No(TOKENS),
1023 const TOKENS: &[&str] = &["`=>`", "`,`", "`=`", "`|`", "`if`", "`in`"];
1025 TokenTree::Token(token) => match token.kind {
1026 FatArrow | Comma | Eq | BinOp(token::Or) => IsInFollow::Yes,
1027 Ident(name, false) if name == kw::If || name == kw::In => IsInFollow::Yes,
1028 _ => IsInFollow::No(TOKENS),
1030 _ => IsInFollow::No(TOKENS),
1033 sym::path | sym::ty => {
1034 const TOKENS: &[&str] = &[
1035 "`{`", "`[`", "`=>`", "`,`", "`>`", "`=`", "`:`", "`;`", "`|`", "`as`",
1039 TokenTree::Token(token) => match token.kind {
1040 OpenDelim(token::DelimToken::Brace)
1041 | OpenDelim(token::DelimToken::Bracket)
1049 | BinOp(token::Or) => IsInFollow::Yes,
1050 Ident(name, false) if name == kw::As || name == kw::Where => {
1053 _ => IsInFollow::No(TOKENS),
1055 TokenTree::MetaVarDecl(_, _, frag) if frag.name == sym::block => {
1058 _ => IsInFollow::No(TOKENS),
1061 sym::ident | sym::lifetime => {
1062 // being a single token, idents and lifetimes are harmless
1066 // literals may be of a single token, or two tokens (negative numbers)
1069 sym::meta | sym::tt => {
1070 // being either a single token or a delimited sequence, tt is
1075 // Explicitly disallow `priv`, on the off chance it comes back.
1076 const TOKENS: &[&str] = &["`,`", "an ident", "a type"];
1078 TokenTree::Token(token) => match token.kind {
1079 Comma => IsInFollow::Yes,
1080 Ident(name, is_raw) if is_raw || name != kw::Priv => IsInFollow::Yes,
1082 if token.can_begin_type() {
1085 IsInFollow::No(TOKENS)
1089 TokenTree::MetaVarDecl(_, _, frag)
1090 if frag.name == sym::ident
1091 || frag.name == sym::ty
1092 || frag.name == sym::path =>
1096 _ => IsInFollow::No(TOKENS),
1099 kw::Invalid => IsInFollow::Yes,
1100 _ => IsInFollow::Invalid(
1101 format!("invalid fragment specifier `{}`", frag),
1102 VALID_FRAGMENT_NAMES_MSG,
1108 fn has_legal_fragment_specifier(
1110 features: &Features,
1111 attrs: &[ast::Attribute],
1112 tok: &mbe::TokenTree,
1113 ) -> Result<(), String> {
1114 debug!("has_legal_fragment_specifier({:?})", tok);
1115 if let mbe::TokenTree::MetaVarDecl(_, _, ref frag_spec) = *tok {
1116 let frag_span = tok.span();
1117 if !is_legal_fragment_specifier(sess, features, attrs, frag_spec.name, frag_span) {
1118 return Err(frag_spec.to_string());
1124 fn is_legal_fragment_specifier(
1126 _features: &Features,
1127 _attrs: &[ast::Attribute],
1132 * If new fragment specifiers are invented in nightly, `_sess`,
1133 * `_features`, `_attrs`, and `_frag_span` will be useful here
1134 * for checking against feature gates. See past versions of
1151 | kw::Invalid => true,
1156 fn quoted_tt_to_string(tt: &mbe::TokenTree) -> String {
1158 mbe::TokenTree::Token(ref token) => crate::print::pprust::token_to_string(&token),
1159 mbe::TokenTree::MetaVar(_, name) => format!("${}", name),
1160 mbe::TokenTree::MetaVarDecl(_, name, kind) => format!("${}:{}", name, kind),
1162 "unexpected mbe::TokenTree::{{Sequence or Delimited}} \
1163 in follow set checker"
1169 /// Use this token tree as a matcher to parse given tts.
1170 fn parse(cx: &ExtCtxt<'_>, mtch: &[mbe::TokenTree], tts: TokenStream)
1171 -> NamedParseResult {
1172 // `None` is because we're not interpolating
1173 let directory = Directory {
1174 path: Cow::from(cx.current_expansion.module.directory.as_path()),
1175 ownership: cx.current_expansion.directory_ownership,
1177 parse(cx.parse_sess(), tts, mtch, Some(directory), true)
1181 /// Generates an appropriate parsing failure message. For EOF, this is "unexpected end...". For
1182 /// other tokens, this is "unexpected token...".
1183 fn parse_failure_msg(tok: &Token) -> String {
1185 token::Eof => "unexpected end of macro invocation".to_string(),
1187 "no rules expected the token `{}`",
1188 pprust::token_to_string(tok),