Skip to main content

rustc_expand/mbe/
quoted.rs

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::errors::feature_err;
9use rustc_span::edition::Edition;
10use rustc_span::{Ident, Span, kw, sym};
11
12use crate::errors;
13use crate::mbe::macro_parser::count_metavar_decls;
14use crate::mbe::{Delimited, KleeneOp, KleeneToken, MetaVarExpr, SequenceRepetition, TokenTree};
15
16pub(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";
19
20/// 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
24    Pattern,
25    /// The right-hand side body, with metavar references and metavar expressions
26    Body,
27}
28
29impl RulePart {
30    #[inline(always)]
31    fn is_pattern(&self) -> bool {
32        #[allow(non_exhaustive_omitted_patterns)] match self {
    Self::Pattern => true,
    _ => false,
}matches!(self, Self::Pattern)
33    }
34
35    #[inline(always)]
36    fn is_body(&self) -> bool {
37        #[allow(non_exhaustive_omitted_patterns)] match self {
    Self::Body => true,
    _ => false,
}matches!(self, Self::Body)
38    }
39}
40
41/// 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`
70    let mut result = Vec::new();
71
72    // For each token tree in `input`, parse the token into a `self::TokenTree`, consuming
73    // additional trees if need be.
74    let mut iter = input.iter();
75    while 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`).
78        let tree = parse_tree(tree, &mut iter, part, sess, node_id, features, edition);
79
80        if part.is_body() {
81            // No matchers allowed, nothing to process here
82            result.push(tree);
83            continue;
84        }
85
86        let TokenTree::MetaVar(start_sp, ident) = tree else {
87            // Not a metavariable, just return the tree
88            result.push(tree);
89            continue;
90        };
91
92        let 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.
96        let 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        };
104
105        // Not consuming the next token immediately, as it may not be a colon
106        if 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
111            iter.next();
112
113            // 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.
115            let Some(tokenstream::TokenTree::Token(token, _)) = iter.next() else {
116                // Invalid, return a nice source location as `var:`
117                result.push(missing_fragment_specifier(
118                    colon_span.with_lo(start_sp.lo()),
119                    colon_span.shrink_to_hi(),
120                ));
121                continue;
122            };
123
124            let Some((fragment, _)) = token.ident() else {
125                // No identifier for the fragment specifier;
126                if 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, _)
131                                if next_token.ident().is_some()
132                        )
133                    })
134                {
135                    let 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                }
150                continue;
151            };
152
153            let span = token.span.with_lo(start_sp.lo());
154            let 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).
163                if !span.from_expansion() { edition } else { span.edition() }
164            };
165            let 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.
177            result.push(missing_fragment_specifier(start_sp, start_sp.shrink_to_hi()));
178        }
179    }
180    result
181}
182
183/// 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 {
194    parse(&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}
198
199/// 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) {
201    if !features.macro_metavar_expr() {
202        let msg = "meta-variable expressions are unstable";
203        feature_err(sess, sym::macro_metavar_expr, span, msg).emit();
204    }
205}
206
207fn maybe_emit_macro_metavar_expr_concat_feature(features: &Features, sess: &Session, span: Span) {
208    if !features.macro_metavar_expr_concat() {
209        let msg = "the `concat` meta-variable expression is unstable";
210        feature_err(sess, sym::macro_metavar_expr_concat, span, msg).emit();
211    }
212}
213
214/// 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
238    match 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.
243            let mut next = outer_iter.next();
244            let mut iter_storage;
245            let iter: &mut TokenStreamIter<'_> = match next {
246                Some(tokenstream::TokenTree::Delimited(.., delim, tts)) if delim.skip() => {
247                    iter_storage = tts.iter();
248                    next = iter_storage.next();
249                    &mut iter_storage
250                }
251                _ => outer_iter,
252            };
253
254            match next {
255                // `tree` is followed by a delimited set of token trees.
256                Some(&tokenstream::TokenTree::Delimited(delim_span, _, delim, ref tts)) => {
257                    if part.is_pattern() {
258                        if delim != Delimiter::Parenthesis {
259                            span_dollar_dollar_or_metavar_in_the_lhs_err(
260                                sess,
261                                &Token {
262                                    kind: delim.as_open_token_kind(),
263                                    span: delim_span.entire(),
264                                },
265                            );
266                        }
267                    } else {
268                        match 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.
273                                match MetaVarExpr::parse(tts, delim_span.entire(), &sess.psess) {
274                                    Err(err) => {
275                                        err.emit();
276                                        // Returns early the same read `$` to avoid spanning
277                                        // unrelated diagnostics that could be performed afterwards
278                                        return TokenTree::token(token::Dollar, dollar_span);
279                                    }
280                                    Ok(elem) => {
281                                        if let MetaVarExpr::Concat(_) = elem {
282                                            maybe_emit_macro_metavar_expr_concat_feature(
283                                                features,
284                                                sess,
285                                                delim_span.entire(),
286                                            );
287                                        } else {
288                                            maybe_emit_macro_metavar_expr_feature(
289                                                features,
290                                                sess,
291                                                delim_span.entire(),
292                                            );
293                                        }
294                                        return TokenTree::MetaVarExpr(delim_span, elem);
295                                    }
296                                }
297                            }
298                            Delimiter::Parenthesis => {}
299                            _ => {
300                                let token =
301                                    pprust::token_kind_to_string(&delim.as_open_token_kind());
302                                sess.dcx().emit_err(errors::ExpectedParenOrBrace {
303                                    span: delim_span.entire(),
304                                    token,
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
312                    let sequence = parse(tts, part, sess, node_id, features, edition);
313                    // Get the Kleene operator and optional separator
314                    let (separator, kleene) =
315                        parse_sep_and_kleene_op(iter, delim_span.entire(), sess);
316                    // Count the number of captured "names" (i.e., named metavars)
317                    let num_captures =
318                        if part.is_pattern() { count_metavar_decls(&sequence) } else { 0 };
319                    TokenTree::Sequence(
320                        delim_span,
321                        SequenceRepetition { tts: sequence, separator, kleene, num_captures },
322                    )
323                }
324
325                // `tree` is followed by an `ident`. This could be `$meta_var` or the `$crate`
326                // special metavariable that names the crate of the invocation.
327                Some(tokenstream::TokenTree::Token(token, _)) if token.is_ident() => {
328                    let (ident, is_raw) = token.ident().unwrap();
329                    let span = ident.span.with_lo(dollar_span.lo());
330                    if ident.name == kw::Crate && #[allow(non_exhaustive_omitted_patterns)] match is_raw {
    IdentIsRaw::No => true,
    _ => false,
}matches!(is_raw, IdentIsRaw::No) {
331                        TokenTree::token(token::Ident(kw::DollarCrate, is_raw), span)
332                    } else {
333                        TokenTree::MetaVar(span, ident)
334                    }
335                }
336
337                // `tree` is followed by another `$`. This is an escaped `$`.
338                Some(&tokenstream::TokenTree::Token(
339                    Token { kind: token::Dollar, span: dollar_span2 },
340                    _,
341                )) => {
342                    if part.is_pattern() {
343                        span_dollar_dollar_or_metavar_in_the_lhs_err(
344                            sess,
345                            &Token { kind: token::Dollar, span: dollar_span2 },
346                        );
347                    } else {
348                        maybe_emit_macro_metavar_expr_feature(features, sess, dollar_span2);
349                    }
350                    TokenTree::token(token::Dollar, dollar_span2)
351                }
352
353                // `tree` is followed by some other token. This is an error.
354                Some(tokenstream::TokenTree::Token(token, _)) => {
355                    let 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),);
357                    sess.dcx().span_err(token.span, msg);
358                    TokenTree::MetaVar(token.span, Ident::dummy())
359                }
360
361                // There are no more tokens. Just return the `$` we already have.
362                None => TokenTree::token(token::Dollar, dollar_span),
363            }
364        }
365
366        // `tree` is an arbitrary token. Keep it.
367        tokenstream::TokenTree::Token(token, _) => TokenTree::Token(*token),
368
369        // `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(
372            span,
373            spacing,
374            Delimited { delim, tts: parse(tts, part, sess, node_id, features, edition) },
375        ),
376    }
377}
378
379/// Takes a token and returns `Some(KleeneOp)` if the token is `+` `*` or `?`. Otherwise, return
380/// `None`.
381fn kleene_op(token: &Token) -> Option<KleeneOp> {
382    match token.kind {
383        token::Star => Some(KleeneOp::ZeroOrMore),
384        token::Plus => Some(KleeneOp::OneOrMore),
385        token::Question => Some(KleeneOp::ZeroOrOne),
386        _ => None,
387    }
388}
389
390/// 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> {
399    match iter.next() {
400        Some(tokenstream::TokenTree::Token(token, _)) => match kleene_op(token) {
401            Some(op) => Ok(Ok((op, token.span))),
402            None => Ok(Err(*token)),
403        },
404        tree => Err(tree.map_or(span, tokenstream::TokenTree::span)),
405    }
406}
407
408/// 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
426    let span = match parse_kleene_op(iter, span) {
427        // #1 is a `?`, `+`, or `*` KleeneOp
428        Ok(Ok((op, span))) => return (None, KleeneToken::new(op, span)),
429
430        // #1 is a separator followed by #2, a KleeneOp
431        Ok(Err(token)) => match parse_kleene_op(iter, token.span) {
432            // #2 is the `?` Kleene op, which does not take a separator (error)
433            Ok(Ok((KleeneOp::ZeroOrOne, span))) => {
434                // Error!
435                sess.dcx().span_err(
436                    token.span,
437                    "the `?` macro repetition operator does not take a separator",
438                );
439
440                // Return a dummy
441                return (None, KleeneToken::new(KleeneOp::ZeroOrMore, span));
442            }
443
444            // #2 is a KleeneOp :D
445            Ok(Ok((op, span))) => return (Some(token), KleeneToken::new(op, span)),
446
447            // #2 is a random token or not a token at all :(
448            Ok(Err(Token { span, .. })) | Err(span) => span,
449        },
450
451        // #1 is not a token
452        Err(span) => span,
453    };
454
455    // If we ever get to this point, we have experienced an "unexpected token" error
456    sess.dcx().span_err(span, "expected one of: `*`, `+`, or `?`");
457
458    // Return a dummy
459    (None, KleeneToken::new(KleeneOp::ZeroOrMore, span))
460}
461
462// `$$` 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) {
466    sess.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)));
468    sess.dcx().span_note(
469        token.span,
470        "`$$` and meta-variable expressions are not allowed inside macro parameter definitions",
471    );
472}