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_feature::Features;
6use rustc_session::Session;
7use rustc_session::parse::feature_err;
8use rustc_span::edition::Edition;
9use rustc_span::{Ident, Span, kw, sym};
10
11use crate::errors;
12use crate::mbe::macro_parser::count_metavar_decls;
13use crate::mbe::{Delimited, KleeneOp, KleeneToken, MetaVarExpr, SequenceRepetition, TokenTree};
14
15pub(crate) const VALID_FRAGMENT_NAMES_MSG: &str = "valid fragment specifiers are \
16    `ident`, `block`, `stmt`, `expr`, `pat`, `ty`, `lifetime`, `literal`, `path`, \
17    `meta`, `tt`, `item` and `vis`, along with `expr_2021` and `pat_param` for edition compatibility";
18
19/// Takes a `tokenstream::TokenStream` and returns a `Vec<self::TokenTree>`. Specifically, this
20/// takes a generic `TokenStream`, such as is used in the rest of the compiler, and returns a
21/// collection of `TokenTree` for use in parsing a macro.
22///
23/// # Parameters
24///
25/// - `input`: a token stream to read from, the contents of which we are parsing.
26/// - `parsing_patterns`: `parse` can be used to parse either the "patterns" or the "body" of a
27///   macro. Both take roughly the same form _except_ that:
28///   - In a pattern, metavars are declared with their "matcher" type. For example `$var:expr` or
29///     `$id:ident`. In this example, `expr` and `ident` are "matchers". They are not present in the
30///     body of a macro rule -- just in the pattern.
31///   - Metavariable expressions are only valid in the "body", not the "pattern".
32/// - `sess`: the parsing session. Any errors will be emitted to this session.
33/// - `node_id`: the NodeId of the macro we are parsing.
34/// - `features`: language features so we can do feature gating.
35///
36/// # Returns
37///
38/// A collection of `self::TokenTree`. There may also be some errors emitted to `sess`.
39pub(super) fn parse(
40    input: &tokenstream::TokenStream,
41    parsing_patterns: bool,
42    sess: &Session,
43    node_id: NodeId,
44    features: &Features,
45    edition: Edition,
46) -> Vec<TokenTree> {
47    // Will contain the final collection of `self::TokenTree`
48    let mut result = Vec::new();
49
50    // For each token tree in `input`, parse the token into a `self::TokenTree`, consuming
51    // additional trees if need be.
52    let mut iter = input.iter();
53    while let Some(tree) = iter.next() {
54        // Given the parsed tree, if there is a metavar and we are expecting matchers, actually
55        // parse out the matcher (i.e., in `$id:ident` this would parse the `:` and `ident`).
56        let tree = parse_tree(tree, &mut iter, parsing_patterns, sess, node_id, features, edition);
57
58        if !parsing_patterns {
59            // No matchers allowed, nothing to process here
60            result.push(tree);
61            continue;
62        }
63
64        let TokenTree::MetaVar(start_sp, ident) = tree else {
65            // Not a metavariable, just return the tree
66            result.push(tree);
67            continue;
68        };
69
70        // Push a metavariable with no fragment specifier at the given span
71        let mut missing_fragment_specifier = |span| {
72            sess.dcx().emit_err(errors::MissingFragmentSpecifier {
73                span,
74                add_span: span.shrink_to_hi(),
75                valid: VALID_FRAGMENT_NAMES_MSG,
76            });
77
78            // Fall back to a `TokenTree` since that will match anything if we continue expanding.
79            result.push(TokenTree::MetaVarDecl { span, name: ident, kind: NonterminalKind::TT });
80        };
81
82        // Not consuming the next token immediately, as it may not be a colon
83        if let Some(peek) = iter.peek()
84            && let tokenstream::TokenTree::Token(token, _spacing) = peek
85            && let Token { kind: token::Colon, span: colon_span } = token
86        {
87            // Next token is a colon; consume it
88            iter.next();
89
90            // It's ok to consume the next tree no matter how,
91            // since if it's not a token then it will be an invalid declaration.
92            let Some(tokenstream::TokenTree::Token(token, _)) = iter.next() else {
93                // Invalid, return a nice source location as `var:`
94                missing_fragment_specifier(colon_span.with_lo(start_sp.lo()));
95                continue;
96            };
97
98            let Some((fragment, _)) = token.ident() else {
99                // No identifier for the fragment specifier;
100                missing_fragment_specifier(token.span);
101                continue;
102            };
103
104            let span = token.span.with_lo(start_sp.lo());
105            let edition = || {
106                // FIXME(#85708) - once we properly decode a foreign
107                // crate's `SyntaxContext::root`, then we can replace
108                // this with just `span.edition()`. A
109                // `SyntaxContext::root()` from the current crate will
110                // have the edition of the current crate, and a
111                // `SyntaxContext::root()` from a foreign crate will
112                // have the edition of that crate (which we manually
113                // retrieve via the `edition` parameter).
114                if !span.from_expansion() { edition } else { span.edition() }
115            };
116            let kind = NonterminalKind::from_symbol(fragment.name, edition).unwrap_or_else(|| {
117                sess.dcx().emit_err(errors::InvalidFragmentSpecifier {
118                    span,
119                    fragment,
120                    help: VALID_FRAGMENT_NAMES_MSG,
121                });
122                NonterminalKind::TT
123            });
124            result.push(TokenTree::MetaVarDecl { span, name: ident, kind });
125        } else {
126            // Whether it's none or some other tree, it doesn't belong to
127            // the current meta variable, returning the original span.
128            missing_fragment_specifier(start_sp);
129        }
130    }
131    result
132}
133
134/// Asks for the `macro_metavar_expr` feature if it is not enabled
135fn maybe_emit_macro_metavar_expr_feature(features: &Features, sess: &Session, span: Span) {
136    if !features.macro_metavar_expr() {
137        let msg = "meta-variable expressions are unstable";
138        feature_err(sess, sym::macro_metavar_expr, span, msg).emit();
139    }
140}
141
142fn maybe_emit_macro_metavar_expr_concat_feature(features: &Features, sess: &Session, span: Span) {
143    if !features.macro_metavar_expr_concat() {
144        let msg = "the `concat` meta-variable expression is unstable";
145        feature_err(sess, sym::macro_metavar_expr_concat, span, msg).emit();
146    }
147}
148
149/// Takes a `tokenstream::TokenTree` and returns a `self::TokenTree`. Specifically, this takes a
150/// generic `TokenTree`, such as is used in the rest of the compiler, and returns a `TokenTree`
151/// for use in parsing a macro.
152///
153/// Converting the given tree may involve reading more tokens.
154///
155/// # Parameters
156///
157/// - `tree`: the tree we wish to convert.
158/// - `outer_iter`: an iterator over trees. We may need to read more tokens from it in order to finish
159///   converting `tree`
160/// - `parsing_patterns`: same as [parse].
161/// - `sess`: the parsing session. Any errors will be emitted to this session.
162/// - `features`: language features so we can do feature gating.
163fn parse_tree<'a>(
164    tree: &'a tokenstream::TokenTree,
165    outer_iter: &mut TokenStreamIter<'a>,
166    parsing_patterns: bool,
167    sess: &Session,
168    node_id: NodeId,
169    features: &Features,
170    edition: Edition,
171) -> TokenTree {
172    // Depending on what `tree` is, we could be parsing different parts of a macro
173    match tree {
174        // `tree` is a `$` token. Look at the next token in `trees`
175        &tokenstream::TokenTree::Token(Token { kind: token::Dollar, span: dollar_span }, _) => {
176            // FIXME: Handle `Invisible`-delimited groups in a more systematic way
177            // during parsing.
178            let mut next = outer_iter.next();
179            let mut iter_storage;
180            let mut iter: &mut TokenStreamIter<'_> = match next {
181                Some(tokenstream::TokenTree::Delimited(.., delim, tts)) if delim.skip() => {
182                    iter_storage = tts.iter();
183                    next = iter_storage.next();
184                    &mut iter_storage
185                }
186                _ => outer_iter,
187            };
188
189            match next {
190                // `tree` is followed by a delimited set of token trees.
191                Some(&tokenstream::TokenTree::Delimited(delim_span, _, delim, ref tts)) => {
192                    if parsing_patterns {
193                        if delim != Delimiter::Parenthesis {
194                            span_dollar_dollar_or_metavar_in_the_lhs_err(
195                                sess,
196                                &Token {
197                                    kind: delim.as_open_token_kind(),
198                                    span: delim_span.entire(),
199                                },
200                            );
201                        }
202                    } else {
203                        match delim {
204                            Delimiter::Brace => {
205                                // The delimiter is `{`. This indicates the beginning
206                                // of a meta-variable expression (e.g. `${count(ident)}`).
207                                // Try to parse the meta-variable expression.
208                                match MetaVarExpr::parse(tts, delim_span.entire(), &sess.psess) {
209                                    Err(err) => {
210                                        err.emit();
211                                        // Returns early the same read `$` to avoid spanning
212                                        // unrelated diagnostics that could be performed afterwards
213                                        return TokenTree::token(token::Dollar, dollar_span);
214                                    }
215                                    Ok(elem) => {
216                                        if let MetaVarExpr::Concat(_) = elem {
217                                            maybe_emit_macro_metavar_expr_concat_feature(
218                                                features,
219                                                sess,
220                                                delim_span.entire(),
221                                            );
222                                        } else {
223                                            maybe_emit_macro_metavar_expr_feature(
224                                                features,
225                                                sess,
226                                                delim_span.entire(),
227                                            );
228                                        }
229                                        return TokenTree::MetaVarExpr(delim_span, elem);
230                                    }
231                                }
232                            }
233                            Delimiter::Parenthesis => {}
234                            _ => {
235                                let token =
236                                    pprust::token_kind_to_string(&delim.as_open_token_kind());
237                                sess.dcx().emit_err(errors::ExpectedParenOrBrace {
238                                    span: delim_span.entire(),
239                                    token,
240                                });
241                            }
242                        }
243                    }
244                    // If we didn't find a metavar expression above, then we must have a
245                    // repetition sequence in the macro (e.g. `$(pat)*`). Parse the
246                    // contents of the sequence itself
247                    let sequence = parse(tts, parsing_patterns, sess, node_id, features, edition);
248                    // Get the Kleene operator and optional separator
249                    let (separator, kleene) =
250                        parse_sep_and_kleene_op(&mut iter, delim_span.entire(), sess);
251                    // Count the number of captured "names" (i.e., named metavars)
252                    let num_captures =
253                        if parsing_patterns { count_metavar_decls(&sequence) } else { 0 };
254                    TokenTree::Sequence(
255                        delim_span,
256                        SequenceRepetition { tts: sequence, separator, kleene, num_captures },
257                    )
258                }
259
260                // `tree` is followed by an `ident`. This could be `$meta_var` or the `$crate`
261                // special metavariable that names the crate of the invocation.
262                Some(tokenstream::TokenTree::Token(token, _)) if token.is_ident() => {
263                    let (ident, is_raw) = token.ident().unwrap();
264                    let span = ident.span.with_lo(dollar_span.lo());
265                    if ident.name == kw::Crate && matches!(is_raw, IdentIsRaw::No) {
266                        TokenTree::token(token::Ident(kw::DollarCrate, is_raw), span)
267                    } else {
268                        TokenTree::MetaVar(span, ident)
269                    }
270                }
271
272                // `tree` is followed by another `$`. This is an escaped `$`.
273                Some(&tokenstream::TokenTree::Token(
274                    Token { kind: token::Dollar, span: dollar_span2 },
275                    _,
276                )) => {
277                    if parsing_patterns {
278                        span_dollar_dollar_or_metavar_in_the_lhs_err(
279                            sess,
280                            &Token { kind: token::Dollar, span: dollar_span2 },
281                        );
282                    } else {
283                        maybe_emit_macro_metavar_expr_feature(features, sess, dollar_span2);
284                    }
285                    TokenTree::token(token::Dollar, dollar_span2)
286                }
287
288                // `tree` is followed by some other token. This is an error.
289                Some(tokenstream::TokenTree::Token(token, _)) => {
290                    let msg =
291                        format!("expected identifier, found `{}`", pprust::token_to_string(token),);
292                    sess.dcx().span_err(token.span, msg);
293                    TokenTree::MetaVar(token.span, Ident::dummy())
294                }
295
296                // There are no more tokens. Just return the `$` we already have.
297                None => TokenTree::token(token::Dollar, dollar_span),
298            }
299        }
300
301        // `tree` is an arbitrary token. Keep it.
302        tokenstream::TokenTree::Token(token, _) => TokenTree::Token(*token),
303
304        // `tree` is the beginning of a delimited set of tokens (e.g., `(` or `{`). We need to
305        // descend into the delimited set and further parse it.
306        &tokenstream::TokenTree::Delimited(span, spacing, delim, ref tts) => TokenTree::Delimited(
307            span,
308            spacing,
309            Delimited {
310                delim,
311                tts: parse(tts, parsing_patterns, sess, node_id, features, edition),
312            },
313        ),
314    }
315}
316
317/// Takes a token and returns `Some(KleeneOp)` if the token is `+` `*` or `?`. Otherwise, return
318/// `None`.
319fn kleene_op(token: &Token) -> Option<KleeneOp> {
320    match token.kind {
321        token::Star => Some(KleeneOp::ZeroOrMore),
322        token::Plus => Some(KleeneOp::OneOrMore),
323        token::Question => Some(KleeneOp::ZeroOrOne),
324        _ => None,
325    }
326}
327
328/// Parse the next token tree of the input looking for a KleeneOp. Returns
329///
330/// - Ok(Ok((op, span))) if the next token tree is a KleeneOp
331/// - Ok(Err(tok, span)) if the next token tree is a token but not a KleeneOp
332/// - Err(span) if the next token tree is not a token
333fn parse_kleene_op(
334    iter: &mut TokenStreamIter<'_>,
335    span: Span,
336) -> Result<Result<(KleeneOp, Span), Token>, Span> {
337    match iter.next() {
338        Some(tokenstream::TokenTree::Token(token, _)) => match kleene_op(token) {
339            Some(op) => Ok(Ok((op, token.span))),
340            None => Ok(Err(*token)),
341        },
342        tree => Err(tree.map_or(span, tokenstream::TokenTree::span)),
343    }
344}
345
346/// Attempt to parse a single Kleene star, possibly with a separator.
347///
348/// For example, in a pattern such as `$(a),*`, `a` is the pattern to be repeated, `,` is the
349/// separator, and `*` is the Kleene operator. This function is specifically concerned with parsing
350/// the last two tokens of such a pattern: namely, the optional separator and the Kleene operator
351/// itself. Note that here we are parsing the _macro_ itself, rather than trying to match some
352/// stream of tokens in an invocation of a macro.
353///
354/// This function will take some input iterator `iter` corresponding to `span` and a parsing
355/// session `sess`. If the next one (or possibly two) tokens in `iter` correspond to a Kleene
356/// operator and separator, then a tuple with `(separator, KleeneOp)` is returned. Otherwise, an
357/// error with the appropriate span is emitted to `sess` and a dummy value is returned.
358fn parse_sep_and_kleene_op(
359    iter: &mut TokenStreamIter<'_>,
360    span: Span,
361    sess: &Session,
362) -> (Option<Token>, KleeneToken) {
363    // We basically look at two token trees here, denoted as #1 and #2 below
364    let span = match parse_kleene_op(iter, span) {
365        // #1 is a `?`, `+`, or `*` KleeneOp
366        Ok(Ok((op, span))) => return (None, KleeneToken::new(op, span)),
367
368        // #1 is a separator followed by #2, a KleeneOp
369        Ok(Err(token)) => match parse_kleene_op(iter, token.span) {
370            // #2 is the `?` Kleene op, which does not take a separator (error)
371            Ok(Ok((KleeneOp::ZeroOrOne, span))) => {
372                // Error!
373                sess.dcx().span_err(
374                    token.span,
375                    "the `?` macro repetition operator does not take a separator",
376                );
377
378                // Return a dummy
379                return (None, KleeneToken::new(KleeneOp::ZeroOrMore, span));
380            }
381
382            // #2 is a KleeneOp :D
383            Ok(Ok((op, span))) => return (Some(token), KleeneToken::new(op, span)),
384
385            // #2 is a random token or not a token at all :(
386            Ok(Err(Token { span, .. })) | Err(span) => span,
387        },
388
389        // #1 is not a token
390        Err(span) => span,
391    };
392
393    // If we ever get to this point, we have experienced an "unexpected token" error
394    sess.dcx().span_err(span, "expected one of: `*`, `+`, or `?`");
395
396    // Return a dummy
397    (None, KleeneToken::new(KleeneOp::ZeroOrMore, span))
398}
399
400// `$$` or a meta-variable is the lhs of a macro but shouldn't.
401//
402// For example, `macro_rules! foo { ( ${len()} ) => {} }`
403fn span_dollar_dollar_or_metavar_in_the_lhs_err(sess: &Session, token: &Token) {
404    sess.dcx()
405        .span_err(token.span, format!("unexpected token: {}", pprust::token_to_string(token)));
406    sess.dcx().span_note(
407        token.span,
408        "`$$` and meta-variable expressions are not allowed inside macro parameter definitions",
409    );
410}