1use rustc_ast::token::{self, Delimiter, IdentIsRaw, NonterminalKind, Token};
2use rustc_ast::tokenstream::TokenStreamIter;
3use rustc_ast::{NodeId, tokenstream};
4use rustc_ast_pretty::pprust;
5use rustc_errors::Applicability;
6use rustc_feature::Features;
7use rustc_session::Session;
8use rustc_session::parse::feature_err;
9use rustc_span::edition::Edition;
10use rustc_span::{Ident, Span, kw, sym};
1112use crate::errors;
13use crate::mbe::macro_parser::count_metavar_decls;
14use crate::mbe::{Delimited, KleeneOp, KleeneToken, MetaVarExpr, SequenceRepetition, TokenTree};
1516pub(crate) const VALID_FRAGMENT_NAMES_MSG: &str = "valid fragment specifiers are \
17 `ident`, `block`, `stmt`, `expr`, `pat`, `ty`, `lifetime`, `literal`, `path`, \
18 `meta`, `tt`, `item` and `vis`, along with `expr_2021` and `pat_param` for edition compatibility";
1920/// Which part of a macro rule we're parsing
21#[derive(#[automatically_derived]
impl ::core::marker::Copy for RulePart { }Copy, #[automatically_derived]
impl ::core::clone::Clone for RulePart {
#[inline]
fn clone(&self) -> RulePart { *self }
}Clone)]
22pub(crate) enum RulePart {
23/// The left-hand side, with patterns and metavar definitions with types
24Pattern,
25/// The right-hand side body, with metavar references and metavar expressions
26Body,
27}
2829impl RulePart {
30#[inline(always)]
31fn is_pattern(&self) -> bool {
32#[allow(non_exhaustive_omitted_patterns)] match self {
Self::Pattern => true,
_ => false,
}matches!(self, Self::Pattern)33 }
3435#[inline(always)]
36fn is_body(&self) -> bool {
37#[allow(non_exhaustive_omitted_patterns)] match self {
Self::Body => true,
_ => false,
}matches!(self, Self::Body)38 }
39}
4041/// Takes a `tokenstream::TokenStream` and returns a `Vec<self::TokenTree>`. Specifically, this
42/// takes a generic `TokenStream`, such as is used in the rest of the compiler, and returns a
43/// collection of `TokenTree` for use in parsing a macro.
44///
45/// # Parameters
46///
47/// - `input`: a token stream to read from, the contents of which we are parsing.
48/// - `part`: whether we're parsing the patterns or the body of a macro. Both take roughly the same
49/// form _except_ that:
50/// - In a pattern, metavars are declared with their "matcher" type. For example `$var:expr` or
51/// `$id:ident`. In this example, `expr` and `ident` are "matchers". They are not present in the
52/// body of a macro rule -- just in the pattern.
53/// - Metavariable expressions are only valid in the "body", not the "pattern".
54/// - `sess`: the parsing session. Any errors will be emitted to this session.
55/// - `node_id`: the NodeId of the macro we are parsing.
56/// - `features`: language features so we can do feature gating.
57///
58/// # Returns
59///
60/// A collection of `self::TokenTree`. There may also be some errors emitted to `sess`.
61fn parse(
62 input: &tokenstream::TokenStream,
63 part: RulePart,
64 sess: &Session,
65 node_id: NodeId,
66 features: &Features,
67 edition: Edition,
68) -> Vec<TokenTree> {
69// Will contain the final collection of `self::TokenTree`
70let mut result = Vec::new();
7172// For each token tree in `input`, parse the token into a `self::TokenTree`, consuming
73 // additional trees if need be.
74let mut iter = input.iter();
75while let Some(tree) = iter.next() {
76// Given the parsed tree, if there is a metavar and we are expecting matchers, actually
77 // parse out the matcher (i.e., in `$id:ident` this would parse the `:` and `ident`).
78let tree = parse_tree(tree, &mut iter, part, sess, node_id, features, edition);
7980if part.is_body() {
81// No matchers allowed, nothing to process here
82result.push(tree);
83continue;
84 }
8586let TokenTree::MetaVar(start_sp, ident) = tree else {
87// Not a metavariable, just return the tree
88result.push(tree);
89continue;
90 };
9192let fallback_metavar_decl =
93 |span| TokenTree::MetaVarDecl { span, name: ident, kind: NonterminalKind::TT };
94// Emit a missing-fragment diagnostic and return a `TokenTree` fallback so parsing can
95 // continue.
96let missing_fragment_specifier = |span, add_span| {
97 sess.dcx().emit_err(errors::MissingFragmentSpecifier {
98 span,
99 add_span,
100 valid: VALID_FRAGMENT_NAMES_MSG,
101 });
102 fallback_metavar_decl(span)
103 };
104105// Not consuming the next token immediately, as it may not be a colon
106if let Some(peek) = iter.peek()
107 && let tokenstream::TokenTree::Token(token, _spacing) = peek
108 && let Token { kind: token::Colon, span: colon_span } = token
109 {
110// Next token is a colon; consume it
111iter.next();
112113// It's ok to consume the next tree no matter how,
114 // since if it's not a token then it will be an invalid declaration.
115let Some(tokenstream::TokenTree::Token(token, _)) = iter.next() else {
116// Invalid, return a nice source location as `var:`
117result.push(missing_fragment_specifier(
118 colon_span.with_lo(start_sp.lo()),
119 colon_span.shrink_to_hi(),
120 ));
121continue;
122 };
123124let Some((fragment, _)) = token.ident() else {
125// No identifier for the fragment specifier;
126if token.kind == token::Dollar
127 && iter.peek().is_some_and(|next| {
128#[allow(non_exhaustive_omitted_patterns)] match next {
tokenstream::TokenTree::Token(next_token, _) if
next_token.ident().is_some() => true,
_ => false,
}matches!(
129 next,
130 tokenstream::TokenTree::Token(next_token, _)
131if next_token.ident().is_some()
132 )133 })
134 {
135let mut err =
136 sess.dcx().struct_span_err(token.span, "missing fragment specifier");
137 err.note("fragment specifiers must be provided");
138 err.help(VALID_FRAGMENT_NAMES_MSG);
139 err.span_suggestion_verbose(
140 token.span,
141"fragment specifiers should not be prefixed with `$`",
142"",
143 Applicability::MaybeIncorrect,
144 );
145 err.emit();
146 result.push(fallback_metavar_decl(token.span));
147 } else {
148 result.push(missing_fragment_specifier(token.span, token.span.shrink_to_hi()));
149 }
150continue;
151 };
152153let span = token.span.with_lo(start_sp.lo());
154let edition = || {
155// FIXME(#85708) - once we properly decode a foreign
156 // crate's `SyntaxContext::root`, then we can replace
157 // this with just `span.edition()`. A
158 // `SyntaxContext::root()` from the current crate will
159 // have the edition of the current crate, and a
160 // `SyntaxContext::root()` from a foreign crate will
161 // have the edition of that crate (which we manually
162 // retrieve via the `edition` parameter).
163if !span.from_expansion() { edition } else { span.edition() }
164 };
165let kind = NonterminalKind::from_symbol(fragment.name, edition).unwrap_or_else(|| {
166 sess.dcx().emit_err(errors::InvalidFragmentSpecifier {
167 span,
168 fragment,
169 help: VALID_FRAGMENT_NAMES_MSG,
170 });
171 NonterminalKind::TT
172 });
173 result.push(TokenTree::MetaVarDecl { span, name: ident, kind });
174 } else {
175// Whether it's none or some other tree, it doesn't belong to
176 // the current meta variable, returning the original span.
177result.push(missing_fragment_specifier(start_sp, start_sp.shrink_to_hi()));
178 }
179 }
180result181}
182183/// Takes a `tokenstream::TokenTree` and returns a `self::TokenTree`. Like `parse`, but for a
184/// single token tree. Emits errors to `sess` if needed.
185#[inline]
186pub(super) fn parse_one_tt(
187 input: tokenstream::TokenTree,
188 part: RulePart,
189 sess: &Session,
190 node_id: NodeId,
191 features: &Features,
192 edition: Edition,
193) -> TokenTree {
194parse(&tokenstream::TokenStream::new(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[input]))vec![input]), part, sess, node_id, features, edition)
195 .pop()
196 .unwrap()
197}
198199/// Asks for the `macro_metavar_expr` feature if it is not enabled
200fn maybe_emit_macro_metavar_expr_feature(features: &Features, sess: &Session, span: Span) {
201if !features.macro_metavar_expr() {
202let msg = "meta-variable expressions are unstable";
203feature_err(sess, sym::macro_metavar_expr, span, msg).emit();
204 }
205}
206207fn maybe_emit_macro_metavar_expr_concat_feature(features: &Features, sess: &Session, span: Span) {
208if !features.macro_metavar_expr_concat() {
209let msg = "the `concat` meta-variable expression is unstable";
210feature_err(sess, sym::macro_metavar_expr_concat, span, msg).emit();
211 }
212}
213214/// Takes a `tokenstream::TokenTree` and returns a `self::TokenTree`. Specifically, this takes a
215/// generic `TokenTree`, such as is used in the rest of the compiler, and returns a `TokenTree`
216/// for use in parsing a macro.
217///
218/// Converting the given tree may involve reading more tokens.
219///
220/// # Parameters
221///
222/// - `tree`: the tree we wish to convert.
223/// - `outer_iter`: an iterator over trees. We may need to read more tokens from it in order to finish
224/// converting `tree`
225/// - `part`: same as [parse].
226/// - `sess`: the parsing session. Any errors will be emitted to this session.
227/// - `features`: language features so we can do feature gating.
228fn parse_tree<'a>(
229 tree: &'a tokenstream::TokenTree,
230 outer_iter: &mut TokenStreamIter<'a>,
231 part: RulePart,
232 sess: &Session,
233 node_id: NodeId,
234 features: &Features,
235 edition: Edition,
236) -> TokenTree {
237// Depending on what `tree` is, we could be parsing different parts of a macro
238match tree {
239// `tree` is a `$` token. Look at the next token in `trees`
240&tokenstream::TokenTree::Token(Token { kind: token::Dollar, span: dollar_span }, _) => {
241// FIXME: Handle `Invisible`-delimited groups in a more systematic way
242 // during parsing.
243let mut next = outer_iter.next();
244let mut iter_storage;
245let iter: &mut TokenStreamIter<'_> = match next {
246Some(tokenstream::TokenTree::Delimited(.., delim, tts)) if delim.skip() => {
247iter_storage = tts.iter();
248next = iter_storage.next();
249&mut iter_storage250 }
251_ => outer_iter,
252 };
253254match next {
255// `tree` is followed by a delimited set of token trees.
256Some(&tokenstream::TokenTree::Delimited(delim_span, _, delim, ref tts)) => {
257if part.is_pattern() {
258if delim != Delimiter::Parenthesis {
259span_dollar_dollar_or_metavar_in_the_lhs_err(
260sess,
261&Token {
262 kind: delim.as_open_token_kind(),
263 span: delim_span.entire(),
264 },
265 );
266 }
267 } else {
268match delim {
269 Delimiter::Brace => {
270// The delimiter is `{`. This indicates the beginning
271 // of a meta-variable expression (e.g. `${count(ident)}`).
272 // Try to parse the meta-variable expression.
273match MetaVarExpr::parse(tts, delim_span.entire(), &sess.psess) {
274Err(err) => {
275err.emit();
276// Returns early the same read `$` to avoid spanning
277 // unrelated diagnostics that could be performed afterwards
278return TokenTree::token(token::Dollar, dollar_span);
279 }
280Ok(elem) => {
281if let MetaVarExpr::Concat(_) = elem {
282maybe_emit_macro_metavar_expr_concat_feature(
283features,
284sess,
285delim_span.entire(),
286 );
287 } else {
288maybe_emit_macro_metavar_expr_feature(
289features,
290sess,
291delim_span.entire(),
292 );
293 }
294return TokenTree::MetaVarExpr(delim_span, elem);
295 }
296 }
297 }
298 Delimiter::Parenthesis => {}
299_ => {
300let token =
301 pprust::token_kind_to_string(&delim.as_open_token_kind());
302sess.dcx().emit_err(errors::ExpectedParenOrBrace {
303 span: delim_span.entire(),
304token,
305 });
306 }
307 }
308 }
309// If we didn't find a metavar expression above, then we must have a
310 // repetition sequence in the macro (e.g. `$(pat)*`). Parse the
311 // contents of the sequence itself
312let sequence = parse(tts, part, sess, node_id, features, edition);
313// Get the Kleene operator and optional separator
314let (separator, kleene) =
315parse_sep_and_kleene_op(iter, delim_span.entire(), sess);
316// Count the number of captured "names" (i.e., named metavars)
317let num_captures =
318if part.is_pattern() { count_metavar_decls(&sequence) } else { 0 };
319 TokenTree::Sequence(
320delim_span,
321SequenceRepetition { tts: sequence, separator, kleene, num_captures },
322 )
323 }
324325// `tree` is followed by an `ident`. This could be `$meta_var` or the `$crate`
326 // special metavariable that names the crate of the invocation.
327Some(tokenstream::TokenTree::Token(token, _)) if token.is_ident() => {
328let (ident, is_raw) = token.ident().unwrap();
329let span = ident.span.with_lo(dollar_span.lo());
330if ident.name == kw::Crate && #[allow(non_exhaustive_omitted_patterns)] match is_raw {
IdentIsRaw::No => true,
_ => false,
}matches!(is_raw, IdentIsRaw::No) {
331TokenTree::token(token::Ident(kw::DollarCrate, is_raw), span)
332 } else {
333 TokenTree::MetaVar(span, ident)
334 }
335 }
336337// `tree` is followed by another `$`. This is an escaped `$`.
338Some(&tokenstream::TokenTree::Token(
339Token { kind: token::Dollar, span: dollar_span2 },
340_,
341 )) => {
342if part.is_pattern() {
343span_dollar_dollar_or_metavar_in_the_lhs_err(
344sess,
345&Token { kind: token::Dollar, span: dollar_span2 },
346 );
347 } else {
348maybe_emit_macro_metavar_expr_feature(features, sess, dollar_span2);
349 }
350TokenTree::token(token::Dollar, dollar_span2)
351 }
352353// `tree` is followed by some other token. This is an error.
354Some(tokenstream::TokenTree::Token(token, _)) => {
355let msg =
356::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected identifier, found `{0}`",
pprust::token_to_string(token)))
})format!("expected identifier, found `{}`", pprust::token_to_string(token),);
357sess.dcx().span_err(token.span, msg);
358 TokenTree::MetaVar(token.span, Ident::dummy())
359 }
360361// There are no more tokens. Just return the `$` we already have.
362None => TokenTree::token(token::Dollar, dollar_span),
363 }
364 }
365366// `tree` is an arbitrary token. Keep it.
367tokenstream::TokenTree::Token(token, _) => TokenTree::Token(*token),
368369// `tree` is the beginning of a delimited set of tokens (e.g., `(` or `{`). We need to
370 // descend into the delimited set and further parse it.
371&tokenstream::TokenTree::Delimited(span, spacing, delim, ref tts) => TokenTree::Delimited(
372span,
373spacing,
374Delimited { delim, tts: parse(tts, part, sess, node_id, features, edition) },
375 ),
376 }
377}
378379/// Takes a token and returns `Some(KleeneOp)` if the token is `+` `*` or `?`. Otherwise, return
380/// `None`.
381fn kleene_op(token: &Token) -> Option<KleeneOp> {
382match token.kind {
383 token::Star => Some(KleeneOp::ZeroOrMore),
384 token::Plus => Some(KleeneOp::OneOrMore),
385 token::Question => Some(KleeneOp::ZeroOrOne),
386_ => None,
387 }
388}
389390/// Parse the next token tree of the input looking for a KleeneOp. Returns
391///
392/// - Ok(Ok((op, span))) if the next token tree is a KleeneOp
393/// - Ok(Err(tok, span)) if the next token tree is a token but not a KleeneOp
394/// - Err(span) if the next token tree is not a token
395fn parse_kleene_op(
396 iter: &mut TokenStreamIter<'_>,
397 span: Span,
398) -> Result<Result<(KleeneOp, Span), Token>, Span> {
399match iter.next() {
400Some(tokenstream::TokenTree::Token(token, _)) => match kleene_op(token) {
401Some(op) => Ok(Ok((op, token.span))),
402None => Ok(Err(*token)),
403 },
404 tree => Err(tree.map_or(span, tokenstream::TokenTree::span)),
405 }
406}
407408/// Attempt to parse a single Kleene star, possibly with a separator.
409///
410/// For example, in a pattern such as `$(a),*`, `a` is the pattern to be repeated, `,` is the
411/// separator, and `*` is the Kleene operator. This function is specifically concerned with parsing
412/// the last two tokens of such a pattern: namely, the optional separator and the Kleene operator
413/// itself. Note that here we are parsing the _macro_ itself, rather than trying to match some
414/// stream of tokens in an invocation of a macro.
415///
416/// This function will take some input iterator `iter` corresponding to `span` and a parsing
417/// session `sess`. If the next one (or possibly two) tokens in `iter` correspond to a Kleene
418/// operator and separator, then a tuple with `(separator, KleeneOp)` is returned. Otherwise, an
419/// error with the appropriate span is emitted to `sess` and a dummy value is returned.
420fn parse_sep_and_kleene_op(
421 iter: &mut TokenStreamIter<'_>,
422 span: Span,
423 sess: &Session,
424) -> (Option<Token>, KleeneToken) {
425// We basically look at two token trees here, denoted as #1 and #2 below
426let span = match parse_kleene_op(iter, span) {
427// #1 is a `?`, `+`, or `*` KleeneOp
428Ok(Ok((op, span))) => return (None, KleeneToken::new(op, span)),
429430// #1 is a separator followed by #2, a KleeneOp
431Ok(Err(token)) => match parse_kleene_op(iter, token.span) {
432// #2 is the `?` Kleene op, which does not take a separator (error)
433Ok(Ok((KleeneOp::ZeroOrOne, span))) => {
434// Error!
435sess.dcx().span_err(
436token.span,
437"the `?` macro repetition operator does not take a separator",
438 );
439440// Return a dummy
441return (None, KleeneToken::new(KleeneOp::ZeroOrMore, span));
442 }
443444// #2 is a KleeneOp :D
445Ok(Ok((op, span))) => return (Some(token), KleeneToken::new(op, span)),
446447// #2 is a random token or not a token at all :(
448Ok(Err(Token { span, .. })) | Err(span) => span,
449 },
450451// #1 is not a token
452Err(span) => span,
453 };
454455// If we ever get to this point, we have experienced an "unexpected token" error
456sess.dcx().span_err(span, "expected one of: `*`, `+`, or `?`");
457458// Return a dummy
459(None, KleeneToken::new(KleeneOp::ZeroOrMore, span))
460}
461462// `$$` or a meta-variable is the lhs of a macro but shouldn't.
463//
464// For example, `macro_rules! foo { ( ${len()} ) => {} }`
465fn span_dollar_dollar_or_metavar_in_the_lhs_err(sess: &Session, token: &Token) {
466sess.dcx()
467 .span_err(token.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unexpected token: {0}",
pprust::token_to_string(token)))
})format!("unexpected token: {}", pprust::token_to_string(token)));
468sess.dcx().span_note(
469token.span,
470"`$$` and meta-variable expressions are not allowed inside macro parameter definitions",
471 );
472}