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