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 { kind: token::OpenDelim(delim), span: delim_span.entire() },
185                            );
186                        }
187                    } else {
188                        match delim {
189                            Delimiter::Brace => {
190                                // The delimiter is `{`. This indicates the beginning
191                                // of a meta-variable expression (e.g. `${count(ident)}`).
192                                // Try to parse the meta-variable expression.
193                                match MetaVarExpr::parse(tts, delim_span.entire(), &sess.psess) {
194                                    Err(err) => {
195                                        err.emit();
196                                        // Returns early the same read `$` to avoid spanning
197                                        // unrelated diagnostics that could be performed afterwards
198                                        return TokenTree::token(token::Dollar, dollar_span);
199                                    }
200                                    Ok(elem) => {
201                                        if let MetaVarExpr::Concat(_) = elem {
202                                            maybe_emit_macro_metavar_expr_concat_feature(
203                                                features,
204                                                sess,
205                                                delim_span.entire(),
206                                            );
207                                        } else {
208                                            maybe_emit_macro_metavar_expr_feature(
209                                                features,
210                                                sess,
211                                                delim_span.entire(),
212                                            );
213                                        }
214                                        return TokenTree::MetaVarExpr(delim_span, elem);
215                                    }
216                                }
217                            }
218                            Delimiter::Parenthesis => {}
219                            _ => {
220                                let token = pprust::token_kind_to_string(&token::OpenDelim(delim));
221                                sess.dcx().emit_err(errors::ExpectedParenOrBrace {
222                                    span: delim_span.entire(),
223                                    token,
224                                });
225                            }
226                        }
227                    }
228                    // If we didn't find a metavar expression above, then we must have a
229                    // repetition sequence in the macro (e.g. `$(pat)*`). Parse the
230                    // contents of the sequence itself
231                    let sequence = parse(tts, parsing_patterns, sess, node_id, features, edition);
232                    // Get the Kleene operator and optional separator
233                    let (separator, kleene) =
234                        parse_sep_and_kleene_op(&mut iter, delim_span.entire(), sess);
235                    // Count the number of captured "names" (i.e., named metavars)
236                    let num_captures =
237                        if parsing_patterns { count_metavar_decls(&sequence) } else { 0 };
238                    TokenTree::Sequence(
239                        delim_span,
240                        SequenceRepetition { tts: sequence, separator, kleene, num_captures },
241                    )
242                }
243
244                // `tree` is followed by an `ident`. This could be `$meta_var` or the `$crate`
245                // special metavariable that names the crate of the invocation.
246                Some(tokenstream::TokenTree::Token(token, _)) if token.is_ident() => {
247                    let (ident, is_raw) = token.ident().unwrap();
248                    let span = ident.span.with_lo(dollar_span.lo());
249                    if ident.name == kw::Crate && matches!(is_raw, IdentIsRaw::No) {
250                        TokenTree::token(token::Ident(kw::DollarCrate, is_raw), span)
251                    } else {
252                        TokenTree::MetaVar(span, ident)
253                    }
254                }
255
256                // `tree` is followed by another `$`. This is an escaped `$`.
257                Some(&tokenstream::TokenTree::Token(
258                    Token { kind: token::Dollar, span: dollar_span2 },
259                    _,
260                )) => {
261                    if parsing_patterns {
262                        span_dollar_dollar_or_metavar_in_the_lhs_err(
263                            sess,
264                            &Token { kind: token::Dollar, span: dollar_span2 },
265                        );
266                    } else {
267                        maybe_emit_macro_metavar_expr_feature(features, sess, dollar_span2);
268                    }
269                    TokenTree::token(token::Dollar, dollar_span2)
270                }
271
272                // `tree` is followed by some other token. This is an error.
273                Some(tokenstream::TokenTree::Token(token, _)) => {
274                    let msg =
275                        format!("expected identifier, found `{}`", pprust::token_to_string(token),);
276                    sess.dcx().span_err(token.span, msg);
277                    TokenTree::MetaVar(token.span, Ident::empty())
278                }
279
280                // There are no more tokens. Just return the `$` we already have.
281                None => TokenTree::token(token::Dollar, dollar_span),
282            }
283        }
284
285        // `tree` is an arbitrary token. Keep it.
286        tokenstream::TokenTree::Token(token, _) => TokenTree::Token(token.clone()),
287
288        // `tree` is the beginning of a delimited set of tokens (e.g., `(` or `{`). We need to
289        // descend into the delimited set and further parse it.
290        &tokenstream::TokenTree::Delimited(span, spacing, delim, ref tts) => TokenTree::Delimited(
291            span,
292            spacing,
293            Delimited {
294                delim,
295                tts: parse(tts, parsing_patterns, sess, node_id, features, edition),
296            },
297        ),
298    }
299}
300
301/// Takes a token and returns `Some(KleeneOp)` if the token is `+` `*` or `?`. Otherwise, return
302/// `None`.
303fn kleene_op(token: &Token) -> Option<KleeneOp> {
304    match token.kind {
305        token::BinOp(token::Star) => Some(KleeneOp::ZeroOrMore),
306        token::BinOp(token::Plus) => Some(KleeneOp::OneOrMore),
307        token::Question => Some(KleeneOp::ZeroOrOne),
308        _ => None,
309    }
310}
311
312/// Parse the next token tree of the input looking for a KleeneOp. Returns
313///
314/// - Ok(Ok((op, span))) if the next token tree is a KleeneOp
315/// - Ok(Err(tok, span)) if the next token tree is a token but not a KleeneOp
316/// - Err(span) if the next token tree is not a token
317fn parse_kleene_op(
318    iter: &mut TokenStreamIter<'_>,
319    span: Span,
320) -> Result<Result<(KleeneOp, Span), Token>, Span> {
321    match iter.next() {
322        Some(tokenstream::TokenTree::Token(token, _)) => match kleene_op(token) {
323            Some(op) => Ok(Ok((op, token.span))),
324            None => Ok(Err(token.clone())),
325        },
326        tree => Err(tree.map_or(span, tokenstream::TokenTree::span)),
327    }
328}
329
330/// Attempt to parse a single Kleene star, possibly with a separator.
331///
332/// For example, in a pattern such as `$(a),*`, `a` is the pattern to be repeated, `,` is the
333/// separator, and `*` is the Kleene operator. This function is specifically concerned with parsing
334/// the last two tokens of such a pattern: namely, the optional separator and the Kleene operator
335/// itself. Note that here we are parsing the _macro_ itself, rather than trying to match some
336/// stream of tokens in an invocation of a macro.
337///
338/// This function will take some input iterator `iter` corresponding to `span` and a parsing
339/// session `sess`. If the next one (or possibly two) tokens in `iter` correspond to a Kleene
340/// operator and separator, then a tuple with `(separator, KleeneOp)` is returned. Otherwise, an
341/// error with the appropriate span is emitted to `sess` and a dummy value is returned.
342fn parse_sep_and_kleene_op(
343    iter: &mut TokenStreamIter<'_>,
344    span: Span,
345    sess: &Session,
346) -> (Option<Token>, KleeneToken) {
347    // We basically look at two token trees here, denoted as #1 and #2 below
348    let span = match parse_kleene_op(iter, span) {
349        // #1 is a `?`, `+`, or `*` KleeneOp
350        Ok(Ok((op, span))) => return (None, KleeneToken::new(op, span)),
351
352        // #1 is a separator followed by #2, a KleeneOp
353        Ok(Err(token)) => match parse_kleene_op(iter, token.span) {
354            // #2 is the `?` Kleene op, which does not take a separator (error)
355            Ok(Ok((KleeneOp::ZeroOrOne, span))) => {
356                // Error!
357                sess.dcx().span_err(
358                    token.span,
359                    "the `?` macro repetition operator does not take a separator",
360                );
361
362                // Return a dummy
363                return (None, KleeneToken::new(KleeneOp::ZeroOrMore, span));
364            }
365
366            // #2 is a KleeneOp :D
367            Ok(Ok((op, span))) => return (Some(token), KleeneToken::new(op, span)),
368
369            // #2 is a random token or not a token at all :(
370            Ok(Err(Token { span, .. })) | Err(span) => span,
371        },
372
373        // #1 is not a token
374        Err(span) => span,
375    };
376
377    // If we ever get to this point, we have experienced an "unexpected token" error
378    sess.dcx().span_err(span, "expected one of: `*`, `+`, or `?`");
379
380    // Return a dummy
381    (None, KleeneToken::new(KleeneOp::ZeroOrMore, span))
382}
383
384// `$$` or a meta-variable is the lhs of a macro but shouldn't.
385//
386// For example, `macro_rules! foo { ( ${len()} ) => {} }`
387fn span_dollar_dollar_or_metavar_in_the_lhs_err(sess: &Session, token: &Token) {
388    sess.dcx()
389        .span_err(token.span, format!("unexpected token: {}", pprust::token_to_string(token)));
390    sess.dcx().span_note(
391        token.span,
392        "`$$` and meta-variable expressions are not allowed inside macro parameter definitions",
393    );
394}