1 use crate::ast::NodeId;
2 use crate::early_buffered_lints::BufferedEarlyLintId;
3 use crate::ext::tt::macro_parser;
4 use crate::feature_gate::Features;
5 use crate::parse::token::{self, Token, TokenKind};
6 use crate::parse::ParseSess;
7 use crate::print::pprust;
8 use crate::tokenstream::{self, DelimSpan};
10 use crate::symbol::kw;
12 use syntax_pos::{edition::Edition, BytePos, Span};
14 use rustc_data_structures::sync::Lrc;
15 use std::iter::Peekable;
17 /// Contains the sub-token-trees of a "delimited" token tree, such as the contents of `(`. Note
18 /// that the delimiter itself might be `NoDelim`.
19 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
20 pub struct Delimited {
21 pub delim: token::DelimToken,
22 pub tts: Vec<TokenTree>,
26 /// Returns the opening delimiter (possibly `NoDelim`).
27 pub fn open_token(&self) -> TokenKind {
28 token::OpenDelim(self.delim)
31 /// Returns the closing delimiter (possibly `NoDelim`).
32 pub fn close_token(&self) -> TokenKind {
33 token::CloseDelim(self.delim)
36 /// Returns a `self::TokenTree` with a `Span` corresponding to the opening delimiter.
37 pub fn open_tt(&self, span: Span) -> TokenTree {
38 let open_span = if span.is_dummy() {
41 span.with_lo(span.lo() + BytePos(self.delim.len() as u32))
43 TokenTree::token(self.open_token(), open_span)
46 /// Returns a `self::TokenTree` with a `Span` corresponding to the closing delimiter.
47 pub fn close_tt(&self, span: Span) -> TokenTree {
48 let close_span = if span.is_dummy() {
51 span.with_lo(span.hi() - BytePos(self.delim.len() as u32))
53 TokenTree::token(self.close_token(), close_span)
57 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
58 pub struct SequenceRepetition {
59 /// The sequence of token trees
60 pub tts: Vec<TokenTree>,
61 /// The optional separator
62 pub separator: Option<TokenKind>,
63 /// Whether the sequence can be repeated zero (*), or one or more times (+)
65 /// The number of `Match`s that appear in the sequence (and subsequences)
66 pub num_captures: usize,
69 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
70 /// for token sequences.
71 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
73 /// Kleene star (`*`) for zero or more repetitions
75 /// Kleene plus (`+`) for one or more repetitions
77 /// Kleene optional (`?`) for zero or one reptitions
81 /// Similar to `tokenstream::TokenTree`, except that `$i`, `$i:ident`, and `$(...)`
82 /// are "first-class" token trees. Useful for parsing macros.
83 #[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable)]
86 Delimited(DelimSpan, Lrc<Delimited>),
87 /// A kleene-style repetition sequence
88 Sequence(DelimSpan, Lrc<SequenceRepetition>),
90 MetaVar(Span, ast::Ident),
91 /// e.g., `$var:expr`. This is only used in the left hand side of MBE macros.
94 ast::Ident, /* name to bind */
95 ast::Ident, /* kind of nonterminal */
100 /// Return the number of tokens in the tree.
101 pub fn len(&self) -> usize {
103 TokenTree::Delimited(_, ref delimed) => match delimed.delim {
104 token::NoDelim => delimed.tts.len(),
105 _ => delimed.tts.len() + 2,
107 TokenTree::Sequence(_, ref seq) => seq.tts.len(),
112 /// Returns `true` if the given token tree contains no other tokens. This is vacuously true for
113 /// single tokens or metavar/decls, but may be false for delimited trees or sequences.
114 pub fn is_empty(&self) -> bool {
116 TokenTree::Delimited(_, ref delimed) => match delimed.delim {
117 token::NoDelim => delimed.tts.is_empty(),
120 TokenTree::Sequence(_, ref seq) => seq.tts.is_empty(),
125 /// Gets the `index`-th sub-token-tree. This only makes sense for delimited trees and sequences.
126 pub fn get_tt(&self, index: usize) -> TokenTree {
127 match (self, index) {
128 (&TokenTree::Delimited(_, ref delimed), _) if delimed.delim == token::NoDelim => {
129 delimed.tts[index].clone()
131 (&TokenTree::Delimited(span, ref delimed), _) => {
133 return delimed.open_tt(span.open);
135 if index == delimed.tts.len() + 1 {
136 return delimed.close_tt(span.close);
138 delimed.tts[index - 1].clone()
140 (&TokenTree::Sequence(_, ref seq), _) => seq.tts[index].clone(),
141 _ => panic!("Cannot expand a token tree"),
145 /// Retrieves the `TokenTree`'s span.
146 pub fn span(&self) -> Span {
148 TokenTree::Token(Token { span, .. })
149 | TokenTree::MetaVar(span, _)
150 | TokenTree::MetaVarDecl(span, _, _) => span,
151 TokenTree::Delimited(span, _)
152 | TokenTree::Sequence(span, _) => span.entire(),
156 crate fn token(kind: TokenKind, span: Span) -> TokenTree {
157 TokenTree::Token(Token::new(kind, span))
161 /// Takes a `tokenstream::TokenStream` and returns a `Vec<self::TokenTree>`. Specifically, this
162 /// takes a generic `TokenStream`, such as is used in the rest of the compiler, and returns a
163 /// collection of `TokenTree` for use in parsing a macro.
167 /// - `input`: a token stream to read from, the contents of which we are parsing.
168 /// - `expect_matchers`: `parse` can be used to parse either the "patterns" or the "body" of a
169 /// macro. Both take roughly the same form _except_ that in a pattern, metavars are declared with
170 /// their "matcher" type. For example `$var:expr` or `$id:ident`. In this example, `expr` and
171 /// `ident` are "matchers". They are not present in the body of a macro rule -- just in the
172 /// pattern, so we pass a parameter to indicate whether to expect them or not.
173 /// - `sess`: the parsing session. Any errors will be emitted to this session.
174 /// - `features`, `attrs`: language feature flags and attributes so that we know whether to use
175 /// unstable features or not.
176 /// - `edition`: which edition are we in.
177 /// - `macro_node_id`: the NodeId of the macro we are parsing.
181 /// A collection of `self::TokenTree`. There may also be some errors emitted to `sess`.
183 input: tokenstream::TokenStream,
184 expect_matchers: bool,
187 attrs: &[ast::Attribute],
189 macro_node_id: NodeId,
190 ) -> Vec<TokenTree> {
191 // Will contain the final collection of `self::TokenTree`
192 let mut result = Vec::new();
194 // For each token tree in `input`, parse the token into a `self::TokenTree`, consuming
195 // additional trees if need be.
196 let mut trees = input.trees().peekable();
197 while let Some(tree) = trees.next() {
198 // Given the parsed tree, if there is a metavar and we are expecting matchers, actually
199 // parse out the matcher (i.e., in `$id:ident` this would parse the `:` and `ident`).
200 let tree = parse_tree(
211 TokenTree::MetaVar(start_sp, ident) if expect_matchers => {
212 let span = match trees.next() {
213 Some(tokenstream::TokenTree::Token(Token { kind: token::Colon, span })) =>
215 Some(tokenstream::TokenTree::Token(token)) => match token.ident() {
217 let span = token.span.with_lo(start_sp.lo());
218 result.push(TokenTree::MetaVarDecl(span, ident, kind));
225 .map(tokenstream::TokenTree::span)
230 .map(tokenstream::TokenTree::span)
231 .unwrap_or(start_sp),
233 sess.missing_fragment_specifiers.borrow_mut().insert(span);
234 result.push(TokenTree::MetaVarDecl(
237 ast::Ident::invalid(),
241 // Not a metavar or no matchers allowed, so just return the tree
242 _ => result.push(tree),
248 /// Takes a `tokenstream::TokenTree` and returns a `self::TokenTree`. Specifically, this takes a
249 /// generic `TokenTree`, such as is used in the rest of the compiler, and returns a `TokenTree`
250 /// for use in parsing a macro.
252 /// Converting the given tree may involve reading more tokens.
256 /// - `tree`: the tree we wish to convert.
257 /// - `trees`: an iterator over trees. We may need to read more tokens from it in order to finish
258 /// converting `tree`
259 /// - `expect_matchers`: same as for `parse` (see above).
260 /// - `sess`: the parsing session. Any errors will be emitted to this session.
261 /// - `features`, `attrs`: language feature flags and attributes so that we know whether to use
262 /// unstable features or not.
264 tree: tokenstream::TokenTree,
265 trees: &mut Peekable<I>,
266 expect_matchers: bool,
269 attrs: &[ast::Attribute],
271 macro_node_id: NodeId,
274 I: Iterator<Item = tokenstream::TokenTree>,
276 // Depending on what `tree` is, we could be parsing different parts of a macro
278 // `tree` is a `$` token. Look at the next token in `trees`
279 tokenstream::TokenTree::Token(Token { kind: token::Dollar, span }) => match trees.next() {
280 // `tree` is followed by a delimited set of token trees. This indicates the beginning
281 // of a repetition sequence in the macro (e.g. `$(pat)*`).
282 Some(tokenstream::TokenTree::Delimited(span, delim, tts)) => {
283 // Must have `(` not `{` or `[`
284 if delim != token::Paren {
285 let tok = pprust::token_to_string(&token::OpenDelim(delim));
286 let msg = format!("expected `(`, found `{}`", tok);
287 sess.span_diagnostic.span_err(span.entire(), &msg);
289 // Parse the contents of the sequence itself
290 let sequence = parse(
299 // Get the Kleene operator and optional separator
300 let (separator, op) =
301 parse_sep_and_kleene_op(
310 // Count the number of captured "names" (i.e., named metavars)
311 let name_captures = macro_parser::count_names(&sequence);
314 Lrc::new(SequenceRepetition {
318 num_captures: name_captures,
323 // `tree` is followed by an `ident`. This could be `$meta_var` or the `$crate` special
324 // metavariable that names the crate of the invocation.
325 Some(tokenstream::TokenTree::Token(token)) if token.is_ident() => {
326 let (ident, is_raw) = token.ident().unwrap();
327 let span = ident.span.with_lo(span.lo());
328 if ident.name == kw::Crate && !is_raw {
329 TokenTree::token(token::Ident(kw::DollarCrate, is_raw), span)
331 TokenTree::MetaVar(span, ident)
335 // `tree` is followed by a random token. This is an error.
336 Some(tokenstream::TokenTree::Token(token)) => {
338 "expected identifier, found `{}`",
339 pprust::token_to_string(&token),
341 sess.span_diagnostic.span_err(token.span, &msg);
342 TokenTree::MetaVar(token.span, ast::Ident::invalid())
345 // There are no more tokens. Just return the `$` we already have.
346 None => TokenTree::token(token::Dollar, span),
349 // `tree` is an arbitrary token. Keep it.
350 tokenstream::TokenTree::Token(token) => TokenTree::Token(token),
352 // `tree` is the beginning of a delimited set of tokens (e.g., `(` or `{`). We need to
353 // descend into the delimited set and further parse it.
354 tokenstream::TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited(
372 /// Takes a token and returns `Some(KleeneOp)` if the token is `+` `*` or `?`. Otherwise, return
374 fn kleene_op(token: &TokenKind) -> Option<KleeneOp> {
376 token::BinOp(token::Star) => Some(KleeneOp::ZeroOrMore),
377 token::BinOp(token::Plus) => Some(KleeneOp::OneOrMore),
378 token::Question => Some(KleeneOp::ZeroOrOne),
383 /// Parse the next token tree of the input looking for a KleeneOp. Returns
385 /// - Ok(Ok((op, span))) if the next token tree is a KleeneOp
386 /// - Ok(Err(tok, span)) if the next token tree is a token but not a KleeneOp
387 /// - Err(span) if the next token tree is not a token
388 fn parse_kleene_op<I>(input: &mut I, span: Span) -> Result<Result<(KleeneOp, Span), Token>, Span>
390 I: Iterator<Item = tokenstream::TokenTree>,
393 Some(tokenstream::TokenTree::Token(token)) => match kleene_op(&token) {
394 Some(op) => Ok(Ok((op, token.span))),
395 None => Ok(Err(token)),
399 .map(tokenstream::TokenTree::span)
404 /// Attempt to parse a single Kleene star, possibly with a separator.
406 /// For example, in a pattern such as `$(a),*`, `a` is the pattern to be repeated, `,` is the
407 /// separator, and `*` is the Kleene operator. This function is specifically concerned with parsing
408 /// the last two tokens of such a pattern: namely, the optional separator and the Kleene operator
409 /// itself. Note that here we are parsing the _macro_ itself, rather than trying to match some
410 /// stream of tokens in an invocation of a macro.
412 /// This function will take some input iterator `input` corresponding to `span` and a parsing
413 /// session `sess`. If the next one (or possibly two) tokens in `input` correspond to a Kleene
414 /// operator and separator, then a tuple with `(separator, KleeneOp)` is returned. Otherwise, an
415 /// error with the appropriate span is emitted to `sess` and a dummy value is returned.
417 /// N.B., in the 2015 edition, `*` and `+` are the only Kleene operators, and `?` is a separator.
418 /// In the 2018 edition however, `?` is a Kleene operator, and not a separator.
419 fn parse_sep_and_kleene_op<I>(
420 input: &mut Peekable<I>,
424 attrs: &[ast::Attribute],
426 macro_node_id: NodeId,
427 ) -> (Option<TokenKind>, KleeneOp)
429 I: Iterator<Item = tokenstream::TokenTree>,
432 Edition::Edition2015 => parse_sep_and_kleene_op_2015(
440 Edition::Edition2018 => parse_sep_and_kleene_op_2018(input, span, sess, features, attrs),
444 // `?` is a separator (with a migration warning) and never a KleeneOp.
445 fn parse_sep_and_kleene_op_2015<I>(
446 input: &mut Peekable<I>,
449 _features: &Features,
450 _attrs: &[ast::Attribute],
451 macro_node_id: NodeId,
452 ) -> (Option<TokenKind>, KleeneOp)
454 I: Iterator<Item = tokenstream::TokenTree>,
456 // We basically look at two token trees here, denoted as #1 and #2 below
457 let span = match parse_kleene_op(input, span) {
458 // #1 is a `+` or `*` KleeneOp
460 // `?` is ambiguous: it could be a separator (warning) or a Kleene::ZeroOrOne (error), so
461 // we need to look ahead one more token to be sure.
462 Ok(Ok((op, _))) if op != KleeneOp::ZeroOrOne => return (None, op),
464 // #1 is `?` token, but it could be a Kleene::ZeroOrOne (error in 2015) without a separator
465 // or it could be a `?` separator followed by any Kleene operator. We need to look ahead 1
466 // token to find out which.
467 Ok(Ok((op, op1_span))) => {
468 assert_eq!(op, KleeneOp::ZeroOrOne);
470 // Lookahead at #2. If it is a KleenOp, then #1 is a separator.
471 let is_1_sep = if let Some(tokenstream::TokenTree::Token(tok2)) = input.peek() {
472 kleene_op(tok2).is_some()
478 // #1 is a separator and #2 should be a KleepeOp.
479 // (N.B. We need to advance the input iterator.)
480 match parse_kleene_op(input, span) {
481 // #2 is `?`, which is not allowed as a Kleene op in 2015 edition,
482 // but is allowed in the 2018 edition.
483 Ok(Ok((op, op2_span))) if op == KleeneOp::ZeroOrOne => {
485 .struct_span_err(op2_span, "expected `*` or `+`")
486 .note("`?` is not a macro repetition operator in the 2015 edition, \
487 but is accepted in the 2018 edition")
491 return (None, KleeneOp::ZeroOrMore);
494 // #2 is a Kleene op, which is the only valid option
496 // Warn that `?` as a separator will be deprecated
498 BufferedEarlyLintId::QuestionMarkMacroSep,
501 "using `?` as a separator is deprecated and will be \
502 a hard error in an upcoming edition",
505 return (Some(token::Question), op);
508 // #2 is a random token (this is an error) :(
509 Ok(Err(_)) => op1_span,
511 // #2 is not even a token at all :(
515 // `?` is not allowed as a Kleene op in 2015,
516 // but is allowed in the 2018 edition
518 .struct_span_err(op1_span, "expected `*` or `+`")
519 .note("`?` is not a macro repetition operator in the 2015 edition, \
520 but is accepted in the 2018 edition")
524 return (None, KleeneOp::ZeroOrMore);
528 // #1 is a separator followed by #2, a KleeneOp
529 Ok(Err(token)) => match parse_kleene_op(input, token.span) {
530 // #2 is a `?`, which is not allowed as a Kleene op in 2015 edition,
531 // but is allowed in the 2018 edition
532 Ok(Ok((op, op2_span))) if op == KleeneOp::ZeroOrOne => {
534 .struct_span_err(op2_span, "expected `*` or `+`")
535 .note("`?` is not a macro repetition operator in the 2015 edition, \
536 but is accepted in the 2018 edition")
540 return (None, KleeneOp::ZeroOrMore);
543 // #2 is a KleeneOp :D
544 Ok(Ok((op, _))) => return (Some(token.kind), op),
546 // #2 is a random token :(
547 Ok(Err(token)) => token.span,
549 // #2 is not a token at all :(
557 sess.span_diagnostic.span_err(span, "expected `*` or `+`");
560 (None, KleeneOp::ZeroOrMore)
563 // `?` is a Kleene op, not a separator
564 fn parse_sep_and_kleene_op_2018<I>(
565 input: &mut Peekable<I>,
568 _features: &Features,
569 _attrs: &[ast::Attribute],
570 ) -> (Option<TokenKind>, KleeneOp)
572 I: Iterator<Item = tokenstream::TokenTree>,
574 // We basically look at two token trees here, denoted as #1 and #2 below
575 let span = match parse_kleene_op(input, span) {
576 // #1 is a `?` (needs feature gate)
577 Ok(Ok((op, _op1_span))) if op == KleeneOp::ZeroOrOne => {
581 // #1 is a `+` or `*` KleeneOp
582 Ok(Ok((op, _))) => return (None, op),
584 // #1 is a separator followed by #2, a KleeneOp
585 Ok(Err(token)) => match parse_kleene_op(input, token.span) {
586 // #2 is the `?` Kleene op, which does not take a separator (error)
587 Ok(Ok((op, _op2_span))) if op == KleeneOp::ZeroOrOne => {
589 sess.span_diagnostic.span_err(
591 "the `?` macro repetition operator does not take a separator",
595 return (None, KleeneOp::ZeroOrMore);
598 // #2 is a KleeneOp :D
599 Ok(Ok((op, _))) => return (Some(token.kind), op),
601 // #2 is a random token :(
602 Ok(Err(token)) => token.span,
604 // #2 is not a token at all :(
612 // If we ever get to this point, we have experienced an "unexpected token" error
614 .span_err(span, "expected one of: `*`, `+`, or `?`");
617 (None, KleeneOp::ZeroOrMore)