1 use crate::ast::NodeId;
2 use crate::ext::tt::macro_parser;
3 use crate::feature_gate::Features;
4 use crate::parse::token::{self, Token, TokenKind};
5 use crate::parse::ParseSess;
6 use crate::print::pprust;
7 use crate::tokenstream::{self, DelimSpan};
11 use syntax_pos::{edition::Edition, BytePos, Span};
13 use rustc_data_structures::sync::Lrc;
14 use std::iter::Peekable;
16 /// Contains the sub-token-trees of a "delimited" token tree, such as the contents of `(`. Note
17 /// that the delimiter itself might be `NoDelim`.
18 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
19 pub struct Delimited {
20 pub delim: token::DelimToken,
21 pub tts: Vec<TokenTree>,
25 /// Returns a `self::TokenTree` with a `Span` corresponding to the opening delimiter.
26 pub fn open_tt(&self, span: Span) -> TokenTree {
27 let open_span = if span.is_dummy() {
30 span.with_lo(span.lo() + BytePos(self.delim.len() as u32))
32 TokenTree::token(token::OpenDelim(self.delim), open_span)
35 /// Returns a `self::TokenTree` with a `Span` corresponding to the closing delimiter.
36 pub fn close_tt(&self, span: Span) -> TokenTree {
37 let close_span = if span.is_dummy() {
40 span.with_lo(span.hi() - BytePos(self.delim.len() as u32))
42 TokenTree::token(token::CloseDelim(self.delim), close_span)
46 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
47 pub struct SequenceRepetition {
48 /// The sequence of token trees
49 pub tts: Vec<TokenTree>,
50 /// The optional separator
51 pub separator: Option<Token>,
52 /// Whether the sequence can be repeated zero (*), or one or more times (+)
54 /// The number of `Match`s that appear in the sequence (and subsequences)
55 pub num_captures: usize,
58 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
59 /// for token sequences.
60 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
62 /// Kleene star (`*`) for zero or more repetitions
64 /// Kleene plus (`+`) for one or more repetitions
66 /// Kleene optional (`?`) for zero or one reptitions
70 /// Similar to `tokenstream::TokenTree`, except that `$i`, `$i:ident`, and `$(...)`
71 /// are "first-class" token trees. Useful for parsing macros.
72 #[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable)]
75 Delimited(DelimSpan, Lrc<Delimited>),
76 /// A kleene-style repetition sequence
77 Sequence(DelimSpan, Lrc<SequenceRepetition>),
79 MetaVar(Span, ast::Ident),
80 /// e.g., `$var:expr`. This is only used in the left hand side of MBE macros.
83 ast::Ident, /* name to bind */
84 ast::Ident, /* kind of nonterminal */
89 /// Return the number of tokens in the tree.
90 pub fn len(&self) -> usize {
92 TokenTree::Delimited(_, ref delimed) => match delimed.delim {
93 token::NoDelim => delimed.tts.len(),
94 _ => delimed.tts.len() + 2,
96 TokenTree::Sequence(_, ref seq) => seq.tts.len(),
101 /// Returns `true` if the given token tree contains no other tokens. This is vacuously true for
102 /// single tokens or metavar/decls, but may be false for delimited trees or sequences.
103 pub fn is_empty(&self) -> bool {
105 TokenTree::Delimited(_, ref delimed) => match delimed.delim {
106 token::NoDelim => delimed.tts.is_empty(),
109 TokenTree::Sequence(_, ref seq) => seq.tts.is_empty(),
114 /// Gets the `index`-th sub-token-tree. This only makes sense for delimited trees and sequences.
115 pub fn get_tt(&self, index: usize) -> TokenTree {
116 match (self, index) {
117 (&TokenTree::Delimited(_, ref delimed), _) if delimed.delim == token::NoDelim => {
118 delimed.tts[index].clone()
120 (&TokenTree::Delimited(span, ref delimed), _) => {
122 return delimed.open_tt(span.open);
124 if index == delimed.tts.len() + 1 {
125 return delimed.close_tt(span.close);
127 delimed.tts[index - 1].clone()
129 (&TokenTree::Sequence(_, ref seq), _) => seq.tts[index].clone(),
130 _ => panic!("Cannot expand a token tree"),
134 /// Retrieves the `TokenTree`'s span.
135 pub fn span(&self) -> Span {
137 TokenTree::Token(Token { span, .. })
138 | TokenTree::MetaVar(span, _)
139 | TokenTree::MetaVarDecl(span, _, _) => span,
140 TokenTree::Delimited(span, _)
141 | TokenTree::Sequence(span, _) => span.entire(),
145 crate fn token(kind: TokenKind, span: Span) -> TokenTree {
146 TokenTree::Token(Token::new(kind, span))
150 /// Takes a `tokenstream::TokenStream` and returns a `Vec<self::TokenTree>`. Specifically, this
151 /// takes a generic `TokenStream`, such as is used in the rest of the compiler, and returns a
152 /// collection of `TokenTree` for use in parsing a macro.
156 /// - `input`: a token stream to read from, the contents of which we are parsing.
157 /// - `expect_matchers`: `parse` can be used to parse either the "patterns" or the "body" of a
158 /// macro. Both take roughly the same form _except_ that in a pattern, metavars are declared with
159 /// their "matcher" type. For example `$var:expr` or `$id:ident`. In this example, `expr` and
160 /// `ident` are "matchers". They are not present in the body of a macro rule -- just in the
161 /// pattern, so we pass a parameter to indicate whether to expect them or not.
162 /// - `sess`: the parsing session. Any errors will be emitted to this session.
163 /// - `features`, `attrs`: language feature flags and attributes so that we know whether to use
164 /// unstable features or not.
165 /// - `edition`: which edition are we in.
166 /// - `macro_node_id`: the NodeId of the macro we are parsing.
170 /// A collection of `self::TokenTree`. There may also be some errors emitted to `sess`.
172 input: tokenstream::TokenStream,
173 expect_matchers: bool,
176 attrs: &[ast::Attribute],
178 macro_node_id: NodeId,
179 ) -> Vec<TokenTree> {
180 // Will contain the final collection of `self::TokenTree`
181 let mut result = Vec::new();
183 // For each token tree in `input`, parse the token into a `self::TokenTree`, consuming
184 // additional trees if need be.
185 let mut trees = input.trees().peekable();
186 while let Some(tree) = trees.next() {
187 // Given the parsed tree, if there is a metavar and we are expecting matchers, actually
188 // parse out the matcher (i.e., in `$id:ident` this would parse the `:` and `ident`).
189 let tree = parse_tree(
200 TokenTree::MetaVar(start_sp, ident) if expect_matchers => {
201 let span = match trees.next() {
202 Some(tokenstream::TokenTree::Token(Token { kind: token::Colon, span })) =>
204 Some(tokenstream::TokenTree::Token(token)) => match token.ident() {
206 let span = token.span.with_lo(start_sp.lo());
207 result.push(TokenTree::MetaVarDecl(span, ident, kind));
214 .map(tokenstream::TokenTree::span)
219 .map(tokenstream::TokenTree::span)
220 .unwrap_or(start_sp),
222 sess.missing_fragment_specifiers.borrow_mut().insert(span);
223 result.push(TokenTree::MetaVarDecl(
226 ast::Ident::invalid(),
230 // Not a metavar or no matchers allowed, so just return the tree
231 _ => result.push(tree),
237 /// Takes a `tokenstream::TokenTree` and returns a `self::TokenTree`. Specifically, this takes a
238 /// generic `TokenTree`, such as is used in the rest of the compiler, and returns a `TokenTree`
239 /// for use in parsing a macro.
241 /// Converting the given tree may involve reading more tokens.
245 /// - `tree`: the tree we wish to convert.
246 /// - `trees`: an iterator over trees. We may need to read more tokens from it in order to finish
247 /// converting `tree`
248 /// - `expect_matchers`: same as for `parse` (see above).
249 /// - `sess`: the parsing session. Any errors will be emitted to this session.
250 /// - `features`, `attrs`: language feature flags and attributes so that we know whether to use
251 /// unstable features or not.
253 tree: tokenstream::TokenTree,
254 trees: &mut Peekable<I>,
255 expect_matchers: bool,
258 attrs: &[ast::Attribute],
260 macro_node_id: NodeId,
263 I: Iterator<Item = tokenstream::TokenTree>,
265 // Depending on what `tree` is, we could be parsing different parts of a macro
267 // `tree` is a `$` token. Look at the next token in `trees`
268 tokenstream::TokenTree::Token(Token { kind: token::Dollar, span }) => match trees.next() {
269 // `tree` is followed by a delimited set of token trees. This indicates the beginning
270 // of a repetition sequence in the macro (e.g. `$(pat)*`).
271 Some(tokenstream::TokenTree::Delimited(span, delim, tts)) => {
272 // Must have `(` not `{` or `[`
273 if delim != token::Paren {
274 let tok = pprust::token_kind_to_string(&token::OpenDelim(delim));
275 let msg = format!("expected `(`, found `{}`", tok);
276 sess.span_diagnostic.span_err(span.entire(), &msg);
278 // Parse the contents of the sequence itself
279 let sequence = parse(
288 // Get the Kleene operator and optional separator
289 let (separator, op) = parse_sep_and_kleene_op(trees, span.entire(), sess);
290 // Count the number of captured "names" (i.e., named metavars)
291 let name_captures = macro_parser::count_names(&sequence);
294 Lrc::new(SequenceRepetition {
298 num_captures: name_captures,
303 // `tree` is followed by an `ident`. This could be `$meta_var` or the `$crate` special
304 // metavariable that names the crate of the invocation.
305 Some(tokenstream::TokenTree::Token(token)) if token.is_ident() => {
306 let (ident, is_raw) = token.ident().unwrap();
307 let span = ident.span.with_lo(span.lo());
308 if ident.name == kw::Crate && !is_raw {
309 TokenTree::token(token::Ident(kw::DollarCrate, is_raw), span)
311 TokenTree::MetaVar(span, ident)
315 // `tree` is followed by a random token. This is an error.
316 Some(tokenstream::TokenTree::Token(token)) => {
318 "expected identifier, found `{}`",
319 pprust::token_to_string(&token),
321 sess.span_diagnostic.span_err(token.span, &msg);
322 TokenTree::MetaVar(token.span, ast::Ident::invalid())
325 // There are no more tokens. Just return the `$` we already have.
326 None => TokenTree::token(token::Dollar, span),
329 // `tree` is an arbitrary token. Keep it.
330 tokenstream::TokenTree::Token(token) => TokenTree::Token(token),
332 // `tree` is the beginning of a delimited set of tokens (e.g., `(` or `{`). We need to
333 // descend into the delimited set and further parse it.
334 tokenstream::TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited(
352 /// Takes a token and returns `Some(KleeneOp)` if the token is `+` `*` or `?`. Otherwise, return
354 fn kleene_op(token: &Token) -> Option<KleeneOp> {
356 token::BinOp(token::Star) => Some(KleeneOp::ZeroOrMore),
357 token::BinOp(token::Plus) => Some(KleeneOp::OneOrMore),
358 token::Question => Some(KleeneOp::ZeroOrOne),
363 /// Parse the next token tree of the input looking for a KleeneOp. Returns
365 /// - Ok(Ok((op, span))) if the next token tree is a KleeneOp
366 /// - Ok(Err(tok, span)) if the next token tree is a token but not a KleeneOp
367 /// - Err(span) if the next token tree is not a token
368 fn parse_kleene_op<I>(input: &mut I, span: Span) -> Result<Result<(KleeneOp, Span), Token>, Span>
370 I: Iterator<Item = tokenstream::TokenTree>,
373 Some(tokenstream::TokenTree::Token(token)) => match kleene_op(&token) {
374 Some(op) => Ok(Ok((op, token.span))),
375 None => Ok(Err(token)),
379 .map(tokenstream::TokenTree::span)
384 /// Attempt to parse a single Kleene star, possibly with a separator.
386 /// For example, in a pattern such as `$(a),*`, `a` is the pattern to be repeated, `,` is the
387 /// separator, and `*` is the Kleene operator. This function is specifically concerned with parsing
388 /// the last two tokens of such a pattern: namely, the optional separator and the Kleene operator
389 /// itself. Note that here we are parsing the _macro_ itself, rather than trying to match some
390 /// stream of tokens in an invocation of a macro.
392 /// This function will take some input iterator `input` corresponding to `span` and a parsing
393 /// session `sess`. If the next one (or possibly two) tokens in `input` correspond to a Kleene
394 /// operator and separator, then a tuple with `(separator, KleeneOp)` is returned. Otherwise, an
395 /// error with the appropriate span is emitted to `sess` and a dummy value is returned.
396 fn parse_sep_and_kleene_op(
397 input: &mut Peekable<impl Iterator<Item = tokenstream::TokenTree>>,
400 ) -> (Option<Token>, KleeneOp) {
401 // We basically look at two token trees here, denoted as #1 and #2 below
402 let span = match parse_kleene_op(input, span) {
403 // #1 is a `?` (needs feature gate)
404 Ok(Ok((op, _op1_span))) if op == KleeneOp::ZeroOrOne => {
408 // #1 is a `+` or `*` KleeneOp
409 Ok(Ok((op, _))) => return (None, op),
411 // #1 is a separator followed by #2, a KleeneOp
412 Ok(Err(token)) => match parse_kleene_op(input, token.span) {
413 // #2 is the `?` Kleene op, which does not take a separator (error)
414 Ok(Ok((op, _op2_span))) if op == KleeneOp::ZeroOrOne => {
416 sess.span_diagnostic.span_err(
418 "the `?` macro repetition operator does not take a separator",
422 return (None, KleeneOp::ZeroOrMore);
425 // #2 is a KleeneOp :D
426 Ok(Ok((op, _))) => return (Some(token), op),
428 // #2 is a random token :(
429 Ok(Err(token)) => token.span,
431 // #2 is not a token at all :(
439 // If we ever get to this point, we have experienced an "unexpected token" error
441 .span_err(span, "expected one of: `*`, `+`, or `?`");
444 (None, KleeneOp::ZeroOrMore)