1 use crate::mbe::macro_parser;
2 use crate::mbe::{Delimited, KleeneOp, KleeneToken, SequenceRepetition, TokenTree};
4 use rustc_ast::token::{self, Token};
5 use rustc_ast::tokenstream;
6 use rustc_ast::{NodeId, DUMMY_NODE_ID};
7 use rustc_ast_pretty::pprust;
8 use rustc_feature::Features;
9 use rustc_session::parse::ParseSess;
10 use rustc_span::symbol::{kw, Ident};
12 use rustc_span::edition::Edition;
13 use rustc_span::{Span, SyntaxContext};
15 use rustc_data_structures::sync::Lrc;
17 const VALID_FRAGMENT_NAMES_MSG: &str = "valid fragment specifiers are \
18 `ident`, `block`, `stmt`, `expr`, `pat`, `ty`, `lifetime`, \
19 `literal`, `path`, `meta`, `tt`, `item` and `vis`";
21 /// Takes a `tokenstream::TokenStream` and returns a `Vec<self::TokenTree>`. Specifically, this
22 /// takes a generic `TokenStream`, such as is used in the rest of the compiler, and returns a
23 /// collection of `TokenTree` for use in parsing a macro.
27 /// - `input`: a token stream to read from, the contents of which we are parsing.
28 /// - `expect_matchers`: `parse` can be used to parse either the "patterns" or the "body" of a
29 /// macro. Both take roughly the same form _except_ that in a pattern, metavars are declared with
30 /// their "matcher" type. For example `$var:expr` or `$id:ident`. In this example, `expr` and
31 /// `ident` are "matchers". They are not present in the body of a macro rule -- just in the
32 /// pattern, so we pass a parameter to indicate whether to expect them or not.
33 /// - `sess`: the parsing session. Any errors will be emitted to this session.
34 /// - `node_id`: the NodeId of the macro we are parsing.
35 /// - `features`: language features so we can do feature gating.
36 /// - `edition`: the edition of the crate defining the macro
40 /// A collection of `self::TokenTree`. There may also be some errors emitted to `sess`.
42 input: tokenstream::TokenStream,
43 expect_matchers: bool,
49 // Will contain the final collection of `self::TokenTree`
50 let mut result = Vec::new();
52 // For each token tree in `input`, parse the token into a `self::TokenTree`, consuming
53 // additional trees if need be.
54 let mut trees = input.trees();
55 while let Some(tree) = trees.next() {
56 // Given the parsed tree, if there is a metavar and we are expecting matchers, actually
57 // parse out the matcher (i.e., in `$id:ident` this would parse the `:` and `ident`).
58 let tree = parse_tree(tree, &mut trees, expect_matchers, sess, node_id, features, edition);
60 TokenTree::MetaVar(start_sp, ident) if expect_matchers => {
61 let span = match trees.next() {
62 Some(tokenstream::TokenTree::Token(Token { kind: token::Colon, span })) => {
64 Some(tokenstream::TokenTree::Token(token)) => match token.ident() {
66 let span = token.span.with_lo(start_sp.lo());
69 token::NonterminalKind::from_symbol(frag.name, || {
70 // FIXME(#85708) - once we properly decode a foreign
71 // crate's `SyntaxContext::root`, then we can replace
72 // this with just `span.edition()`. A
73 // `SyntaxContext::root()` from the current crate will
74 // have the edition of the current crate, and a
75 // `SyntaxxContext::root()` from a foreign crate will
76 // have the edition of that crate (which we manually
77 // retrieve via the `edition` parameter).
78 if span.ctxt() == SyntaxContext::root() {
87 "invalid fragment specifier `{}`",
91 .struct_span_err(span, &msg)
92 .help(VALID_FRAGMENT_NAMES_MSG)
94 token::NonterminalKind::Ident
97 result.push(TokenTree::MetaVarDecl(span, ident, Some(kind)));
102 tree => tree.as_ref().map_or(span, tokenstream::TokenTree::span),
105 tree => tree.as_ref().map_or(start_sp, tokenstream::TokenTree::span),
107 if node_id != DUMMY_NODE_ID {
108 // Macros loaded from other crates have dummy node ids.
109 sess.missing_fragment_specifiers.borrow_mut().insert(span, node_id);
111 result.push(TokenTree::MetaVarDecl(span, ident, None));
114 // Not a metavar or no matchers allowed, so just return the tree
115 _ => result.push(tree),
121 /// Takes a `tokenstream::TokenTree` and returns a `self::TokenTree`. Specifically, this takes a
122 /// generic `TokenTree`, such as is used in the rest of the compiler, and returns a `TokenTree`
123 /// for use in parsing a macro.
125 /// Converting the given tree may involve reading more tokens.
129 /// - `tree`: the tree we wish to convert.
130 /// - `outer_trees`: an iterator over trees. We may need to read more tokens from it in order to finish
131 /// converting `tree`
132 /// - `expect_matchers`: same as for `parse` (see above).
133 /// - `sess`: the parsing session. Any errors will be emitted to this session.
134 /// - `features`: language features so we can do feature gating.
135 /// - `edition` - the edition of the crate defining the macro
137 tree: tokenstream::TokenTree,
138 outer_trees: &mut impl Iterator<Item = tokenstream::TokenTree>,
139 expect_matchers: bool,
145 // Depending on what `tree` is, we could be parsing different parts of a macro
147 // `tree` is a `$` token. Look at the next token in `trees`
148 tokenstream::TokenTree::Token(Token { kind: token::Dollar, span }) => {
149 // FIXME: Handle `None`-delimited groups in a more systematic way
151 let mut next = outer_trees.next();
152 let mut trees: Box<dyn Iterator<Item = tokenstream::TokenTree>>;
153 if let Some(tokenstream::TokenTree::Delimited(_, token::NoDelim, tts)) = next {
154 trees = Box::new(tts.into_trees());
157 trees = Box::new(outer_trees);
161 // `tree` is followed by a delimited set of token trees. This indicates the beginning
162 // of a repetition sequence in the macro (e.g. `$(pat)*`).
163 Some(tokenstream::TokenTree::Delimited(span, delim, tts)) => {
164 // Must have `(` not `{` or `[`
165 if delim != token::Paren {
166 let tok = pprust::token_kind_to_string(&token::OpenDelim(delim));
167 let msg = format!("expected `(`, found `{}`", tok);
168 sess.span_diagnostic.span_err(span.entire(), &msg);
170 // Parse the contents of the sequence itself
171 let sequence = parse(tts, expect_matchers, sess, node_id, features, edition);
172 // Get the Kleene operator and optional separator
173 let (separator, kleene) =
174 parse_sep_and_kleene_op(&mut trees, span.entire(), sess);
175 // Count the number of captured "names" (i.e., named metavars)
176 let name_captures = macro_parser::count_names(&sequence);
179 Lrc::new(SequenceRepetition {
183 num_captures: name_captures,
188 // `tree` is followed by an `ident`. This could be `$meta_var` or the `$crate` special
189 // metavariable that names the crate of the invocation.
190 Some(tokenstream::TokenTree::Token(token)) if token.is_ident() => {
191 let (ident, is_raw) = token.ident().unwrap();
192 let span = ident.span.with_lo(span.lo());
193 if ident.name == kw::Crate && !is_raw {
194 TokenTree::token(token::Ident(kw::DollarCrate, is_raw), span)
196 TokenTree::MetaVar(span, ident)
200 // `tree` is followed by a random token. This is an error.
201 Some(tokenstream::TokenTree::Token(token)) => {
203 "expected identifier, found `{}`",
204 pprust::token_to_string(&token),
206 sess.span_diagnostic.span_err(token.span, &msg);
207 TokenTree::MetaVar(token.span, Ident::invalid())
210 // There are no more tokens. Just return the `$` we already have.
211 None => TokenTree::token(token::Dollar, span),
215 // `tree` is an arbitrary token. Keep it.
216 tokenstream::TokenTree::Token(token) => TokenTree::Token(token),
218 // `tree` is the beginning of a delimited set of tokens (e.g., `(` or `{`). We need to
219 // descend into the delimited set and further parse it.
220 tokenstream::TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited(
224 tts: parse(tts, expect_matchers, sess, node_id, features, edition),
230 /// Takes a token and returns `Some(KleeneOp)` if the token is `+` `*` or `?`. Otherwise, return
232 fn kleene_op(token: &Token) -> Option<KleeneOp> {
234 token::BinOp(token::Star) => Some(KleeneOp::ZeroOrMore),
235 token::BinOp(token::Plus) => Some(KleeneOp::OneOrMore),
236 token::Question => Some(KleeneOp::ZeroOrOne),
241 /// Parse the next token tree of the input looking for a KleeneOp. Returns
243 /// - Ok(Ok((op, span))) if the next token tree is a KleeneOp
244 /// - Ok(Err(tok, span)) if the next token tree is a token but not a KleeneOp
245 /// - Err(span) if the next token tree is not a token
247 input: &mut impl Iterator<Item = tokenstream::TokenTree>,
249 ) -> Result<Result<(KleeneOp, Span), Token>, Span> {
251 Some(tokenstream::TokenTree::Token(token)) => match kleene_op(&token) {
252 Some(op) => Ok(Ok((op, token.span))),
253 None => Ok(Err(token)),
255 tree => Err(tree.as_ref().map_or(span, tokenstream::TokenTree::span)),
259 /// Attempt to parse a single Kleene star, possibly with a separator.
261 /// For example, in a pattern such as `$(a),*`, `a` is the pattern to be repeated, `,` is the
262 /// separator, and `*` is the Kleene operator. This function is specifically concerned with parsing
263 /// the last two tokens of such a pattern: namely, the optional separator and the Kleene operator
264 /// itself. Note that here we are parsing the _macro_ itself, rather than trying to match some
265 /// stream of tokens in an invocation of a macro.
267 /// This function will take some input iterator `input` corresponding to `span` and a parsing
268 /// session `sess`. If the next one (or possibly two) tokens in `input` correspond to a Kleene
269 /// operator and separator, then a tuple with `(separator, KleeneOp)` is returned. Otherwise, an
270 /// error with the appropriate span is emitted to `sess` and a dummy value is returned.
271 fn parse_sep_and_kleene_op(
272 input: &mut impl Iterator<Item = tokenstream::TokenTree>,
275 ) -> (Option<Token>, KleeneToken) {
276 // We basically look at two token trees here, denoted as #1 and #2 below
277 let span = match parse_kleene_op(input, span) {
278 // #1 is a `?`, `+`, or `*` KleeneOp
279 Ok(Ok((op, span))) => return (None, KleeneToken::new(op, span)),
281 // #1 is a separator followed by #2, a KleeneOp
282 Ok(Err(token)) => match parse_kleene_op(input, token.span) {
283 // #2 is the `?` Kleene op, which does not take a separator (error)
284 Ok(Ok((KleeneOp::ZeroOrOne, span))) => {
286 sess.span_diagnostic.span_err(
288 "the `?` macro repetition operator does not take a separator",
292 return (None, KleeneToken::new(KleeneOp::ZeroOrMore, span));
295 // #2 is a KleeneOp :D
296 Ok(Ok((op, span))) => return (Some(token), KleeneToken::new(op, span)),
298 // #2 is a random token or not a token at all :(
299 Ok(Err(Token { span, .. })) | Err(span) => span,
306 // If we ever get to this point, we have experienced an "unexpected token" error
307 sess.span_diagnostic.span_err(span, "expected one of: `*`, `+`, or `?`");
310 (None, KleeneToken::new(KleeneOp::ZeroOrMore, span))