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 a `self::TokenTree` with a `Span` corresponding to the opening delimiter.
27 pub fn open_tt(&self, span: Span) -> TokenTree {
28 let open_span = if span.is_dummy() {
31 span.with_lo(span.lo() + BytePos(self.delim.len() as u32))
33 TokenTree::token(token::OpenDelim(self.delim), open_span)
36 /// Returns a `self::TokenTree` with a `Span` corresponding to the closing delimiter.
37 pub fn close_tt(&self, span: Span) -> TokenTree {
38 let close_span = if span.is_dummy() {
41 span.with_lo(span.hi() - BytePos(self.delim.len() as u32))
43 TokenTree::token(token::CloseDelim(self.delim), close_span)
47 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
48 pub struct SequenceRepetition {
49 /// The sequence of token trees
50 pub tts: Vec<TokenTree>,
51 /// The optional separator
52 pub separator: Option<Token>,
53 /// Whether the sequence can be repeated zero (*), or one or more times (+)
55 /// The number of `Match`s that appear in the sequence (and subsequences)
56 pub num_captures: usize,
59 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
60 /// for token sequences.
61 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
63 /// Kleene star (`*`) for zero or more repetitions
65 /// Kleene plus (`+`) for one or more repetitions
67 /// Kleene optional (`?`) for zero or one reptitions
71 /// Similar to `tokenstream::TokenTree`, except that `$i`, `$i:ident`, and `$(...)`
72 /// are "first-class" token trees. Useful for parsing macros.
73 #[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable)]
76 Delimited(DelimSpan, Lrc<Delimited>),
77 /// A kleene-style repetition sequence
78 Sequence(DelimSpan, Lrc<SequenceRepetition>),
80 MetaVar(Span, ast::Ident),
81 /// e.g., `$var:expr`. This is only used in the left hand side of MBE macros.
84 ast::Ident, /* name to bind */
85 ast::Ident, /* kind of nonterminal */
90 /// Return the number of tokens in the tree.
91 pub fn len(&self) -> usize {
93 TokenTree::Delimited(_, ref delimed) => match delimed.delim {
94 token::NoDelim => delimed.tts.len(),
95 _ => delimed.tts.len() + 2,
97 TokenTree::Sequence(_, ref seq) => seq.tts.len(),
102 /// Returns `true` if the given token tree contains no other tokens. This is vacuously true for
103 /// single tokens or metavar/decls, but may be false for delimited trees or sequences.
104 pub fn is_empty(&self) -> bool {
106 TokenTree::Delimited(_, ref delimed) => match delimed.delim {
107 token::NoDelim => delimed.tts.is_empty(),
110 TokenTree::Sequence(_, ref seq) => seq.tts.is_empty(),
115 /// Gets the `index`-th sub-token-tree. This only makes sense for delimited trees and sequences.
116 pub fn get_tt(&self, index: usize) -> TokenTree {
117 match (self, index) {
118 (&TokenTree::Delimited(_, ref delimed), _) if delimed.delim == token::NoDelim => {
119 delimed.tts[index].clone()
121 (&TokenTree::Delimited(span, ref delimed), _) => {
123 return delimed.open_tt(span.open);
125 if index == delimed.tts.len() + 1 {
126 return delimed.close_tt(span.close);
128 delimed.tts[index - 1].clone()
130 (&TokenTree::Sequence(_, ref seq), _) => seq.tts[index].clone(),
131 _ => panic!("Cannot expand a token tree"),
135 /// Retrieves the `TokenTree`'s span.
136 pub fn span(&self) -> Span {
138 TokenTree::Token(Token { span, .. })
139 | TokenTree::MetaVar(span, _)
140 | TokenTree::MetaVarDecl(span, _, _) => span,
141 TokenTree::Delimited(span, _)
142 | TokenTree::Sequence(span, _) => span.entire(),
146 crate fn token(kind: TokenKind, span: Span) -> TokenTree {
147 TokenTree::Token(Token::new(kind, span))
151 /// Takes a `tokenstream::TokenStream` and returns a `Vec<self::TokenTree>`. Specifically, this
152 /// takes a generic `TokenStream`, such as is used in the rest of the compiler, and returns a
153 /// collection of `TokenTree` for use in parsing a macro.
157 /// - `input`: a token stream to read from, the contents of which we are parsing.
158 /// - `expect_matchers`: `parse` can be used to parse either the "patterns" or the "body" of a
159 /// macro. Both take roughly the same form _except_ that in a pattern, metavars are declared with
160 /// their "matcher" type. For example `$var:expr` or `$id:ident`. In this example, `expr` and
161 /// `ident` are "matchers". They are not present in the body of a macro rule -- just in the
162 /// pattern, so we pass a parameter to indicate whether to expect them or not.
163 /// - `sess`: the parsing session. Any errors will be emitted to this session.
164 /// - `features`, `attrs`: language feature flags and attributes so that we know whether to use
165 /// unstable features or not.
166 /// - `edition`: which edition are we in.
167 /// - `macro_node_id`: the NodeId of the macro we are parsing.
171 /// A collection of `self::TokenTree`. There may also be some errors emitted to `sess`.
173 input: tokenstream::TokenStream,
174 expect_matchers: bool,
177 attrs: &[ast::Attribute],
179 macro_node_id: NodeId,
180 ) -> Vec<TokenTree> {
181 // Will contain the final collection of `self::TokenTree`
182 let mut result = Vec::new();
184 // For each token tree in `input`, parse the token into a `self::TokenTree`, consuming
185 // additional trees if need be.
186 let mut trees = input.trees().peekable();
187 while let Some(tree) = trees.next() {
188 // Given the parsed tree, if there is a metavar and we are expecting matchers, actually
189 // parse out the matcher (i.e., in `$id:ident` this would parse the `:` and `ident`).
190 let tree = parse_tree(
201 TokenTree::MetaVar(start_sp, ident) if expect_matchers => {
202 let span = match trees.next() {
203 Some(tokenstream::TokenTree::Token(Token { kind: token::Colon, span })) =>
205 Some(tokenstream::TokenTree::Token(token)) => match token.ident() {
207 let span = token.span.with_lo(start_sp.lo());
208 result.push(TokenTree::MetaVarDecl(span, ident, kind));
215 .map(tokenstream::TokenTree::span)
220 .map(tokenstream::TokenTree::span)
221 .unwrap_or(start_sp),
223 sess.missing_fragment_specifiers.borrow_mut().insert(span);
224 result.push(TokenTree::MetaVarDecl(
227 ast::Ident::invalid(),
231 // Not a metavar or no matchers allowed, so just return the tree
232 _ => result.push(tree),
238 /// Takes a `tokenstream::TokenTree` and returns a `self::TokenTree`. Specifically, this takes a
239 /// generic `TokenTree`, such as is used in the rest of the compiler, and returns a `TokenTree`
240 /// for use in parsing a macro.
242 /// Converting the given tree may involve reading more tokens.
246 /// - `tree`: the tree we wish to convert.
247 /// - `trees`: an iterator over trees. We may need to read more tokens from it in order to finish
248 /// converting `tree`
249 /// - `expect_matchers`: same as for `parse` (see above).
250 /// - `sess`: the parsing session. Any errors will be emitted to this session.
251 /// - `features`, `attrs`: language feature flags and attributes so that we know whether to use
252 /// unstable features or not.
254 tree: tokenstream::TokenTree,
255 trees: &mut Peekable<I>,
256 expect_matchers: bool,
259 attrs: &[ast::Attribute],
261 macro_node_id: NodeId,
264 I: Iterator<Item = tokenstream::TokenTree>,
266 // Depending on what `tree` is, we could be parsing different parts of a macro
268 // `tree` is a `$` token. Look at the next token in `trees`
269 tokenstream::TokenTree::Token(Token { kind: token::Dollar, span }) => match trees.next() {
270 // `tree` is followed by a delimited set of token trees. This indicates the beginning
271 // of a repetition sequence in the macro (e.g. `$(pat)*`).
272 Some(tokenstream::TokenTree::Delimited(span, delim, tts)) => {
273 // Must have `(` not `{` or `[`
274 if delim != token::Paren {
275 let tok = pprust::token_kind_to_string(&token::OpenDelim(delim));
276 let msg = format!("expected `(`, found `{}`", tok);
277 sess.span_diagnostic.span_err(span.entire(), &msg);
279 // Parse the contents of the sequence itself
280 let sequence = parse(
289 // Get the Kleene operator and optional separator
290 let (separator, op) =
291 parse_sep_and_kleene_op(
300 // Count the number of captured "names" (i.e., named metavars)
301 let name_captures = macro_parser::count_names(&sequence);
304 Lrc::new(SequenceRepetition {
308 num_captures: name_captures,
313 // `tree` is followed by an `ident`. This could be `$meta_var` or the `$crate` special
314 // metavariable that names the crate of the invocation.
315 Some(tokenstream::TokenTree::Token(token)) if token.is_ident() => {
316 let (ident, is_raw) = token.ident().unwrap();
317 let span = ident.span.with_lo(span.lo());
318 if ident.name == kw::Crate && !is_raw {
319 TokenTree::token(token::Ident(kw::DollarCrate, is_raw), span)
321 TokenTree::MetaVar(span, ident)
325 // `tree` is followed by a random token. This is an error.
326 Some(tokenstream::TokenTree::Token(token)) => {
328 "expected identifier, found `{}`",
329 pprust::token_to_string(&token),
331 sess.span_diagnostic.span_err(token.span, &msg);
332 TokenTree::MetaVar(token.span, ast::Ident::invalid())
335 // There are no more tokens. Just return the `$` we already have.
336 None => TokenTree::token(token::Dollar, span),
339 // `tree` is an arbitrary token. Keep it.
340 tokenstream::TokenTree::Token(token) => TokenTree::Token(token),
342 // `tree` is the beginning of a delimited set of tokens (e.g., `(` or `{`). We need to
343 // descend into the delimited set and further parse it.
344 tokenstream::TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited(
362 /// Takes a token and returns `Some(KleeneOp)` if the token is `+` `*` or `?`. Otherwise, return
364 fn kleene_op(token: &Token) -> Option<KleeneOp> {
366 token::BinOp(token::Star) => Some(KleeneOp::ZeroOrMore),
367 token::BinOp(token::Plus) => Some(KleeneOp::OneOrMore),
368 token::Question => Some(KleeneOp::ZeroOrOne),
373 /// Parse the next token tree of the input looking for a KleeneOp. Returns
375 /// - Ok(Ok((op, span))) if the next token tree is a KleeneOp
376 /// - Ok(Err(tok, span)) if the next token tree is a token but not a KleeneOp
377 /// - Err(span) if the next token tree is not a token
378 fn parse_kleene_op<I>(input: &mut I, span: Span) -> Result<Result<(KleeneOp, Span), Token>, Span>
380 I: Iterator<Item = tokenstream::TokenTree>,
383 Some(tokenstream::TokenTree::Token(token)) => match kleene_op(&token) {
384 Some(op) => Ok(Ok((op, token.span))),
385 None => Ok(Err(token)),
389 .map(tokenstream::TokenTree::span)
394 /// Attempt to parse a single Kleene star, possibly with a separator.
396 /// For example, in a pattern such as `$(a),*`, `a` is the pattern to be repeated, `,` is the
397 /// separator, and `*` is the Kleene operator. This function is specifically concerned with parsing
398 /// the last two tokens of such a pattern: namely, the optional separator and the Kleene operator
399 /// itself. Note that here we are parsing the _macro_ itself, rather than trying to match some
400 /// stream of tokens in an invocation of a macro.
402 /// This function will take some input iterator `input` corresponding to `span` and a parsing
403 /// session `sess`. If the next one (or possibly two) tokens in `input` correspond to a Kleene
404 /// operator and separator, then a tuple with `(separator, KleeneOp)` is returned. Otherwise, an
405 /// error with the appropriate span is emitted to `sess` and a dummy value is returned.
407 /// N.B., in the 2015 edition, `*` and `+` are the only Kleene operators, and `?` is a separator.
408 /// In the 2018 edition however, `?` is a Kleene operator, and not a separator.
409 fn parse_sep_and_kleene_op<I>(
410 input: &mut Peekable<I>,
414 attrs: &[ast::Attribute],
416 macro_node_id: NodeId,
417 ) -> (Option<Token>, KleeneOp)
419 I: Iterator<Item = tokenstream::TokenTree>,
422 Edition::Edition2015 => parse_sep_and_kleene_op_2015(
430 Edition::Edition2018 => parse_sep_and_kleene_op_2018(input, span, sess, features, attrs),
434 // `?` is a separator (with a migration warning) and never a KleeneOp.
435 fn parse_sep_and_kleene_op_2015<I>(
436 input: &mut Peekable<I>,
439 _features: &Features,
440 _attrs: &[ast::Attribute],
441 macro_node_id: NodeId,
442 ) -> (Option<Token>, KleeneOp)
444 I: Iterator<Item = tokenstream::TokenTree>,
446 // We basically look at two token trees here, denoted as #1 and #2 below
447 let span = match parse_kleene_op(input, span) {
448 // #1 is a `+` or `*` KleeneOp
450 // `?` is ambiguous: it could be a separator (warning) or a Kleene::ZeroOrOne (error), so
451 // we need to look ahead one more token to be sure.
452 Ok(Ok((op, _))) if op != KleeneOp::ZeroOrOne => return (None, op),
454 // #1 is `?` token, but it could be a Kleene::ZeroOrOne (error in 2015) without a separator
455 // or it could be a `?` separator followed by any Kleene operator. We need to look ahead 1
456 // token to find out which.
457 Ok(Ok((op, op1_span))) => {
458 assert_eq!(op, KleeneOp::ZeroOrOne);
460 // Lookahead at #2. If it is a KleenOp, then #1 is a separator.
461 let is_1_sep = if let Some(tokenstream::TokenTree::Token(tok2)) = input.peek() {
462 kleene_op(tok2).is_some()
468 // #1 is a separator and #2 should be a KleepeOp.
469 // (N.B. We need to advance the input iterator.)
470 match parse_kleene_op(input, span) {
471 // #2 is `?`, which is not allowed as a Kleene op in 2015 edition,
472 // but is allowed in the 2018 edition.
473 Ok(Ok((op, op2_span))) if op == KleeneOp::ZeroOrOne => {
475 .struct_span_err(op2_span, "expected `*` or `+`")
476 .note("`?` is not a macro repetition operator in the 2015 edition, \
477 but is accepted in the 2018 edition")
481 return (None, KleeneOp::ZeroOrMore);
484 // #2 is a Kleene op, which is the only valid option
486 // Warn that `?` as a separator will be deprecated
488 BufferedEarlyLintId::QuestionMarkMacroSep,
491 "using `?` as a separator is deprecated and will be \
492 a hard error in an upcoming edition",
495 return (Some(Token::new(token::Question, op1_span)), op);
498 // #2 is a random token (this is an error) :(
499 Ok(Err(_)) => op1_span,
501 // #2 is not even a token at all :(
505 // `?` is not allowed as a Kleene op in 2015,
506 // but is allowed in the 2018 edition
508 .struct_span_err(op1_span, "expected `*` or `+`")
509 .note("`?` is not a macro repetition operator in the 2015 edition, \
510 but is accepted in the 2018 edition")
514 return (None, KleeneOp::ZeroOrMore);
518 // #1 is a separator followed by #2, a KleeneOp
519 Ok(Err(token)) => match parse_kleene_op(input, token.span) {
520 // #2 is a `?`, which is not allowed as a Kleene op in 2015 edition,
521 // but is allowed in the 2018 edition
522 Ok(Ok((op, op2_span))) if op == KleeneOp::ZeroOrOne => {
524 .struct_span_err(op2_span, "expected `*` or `+`")
525 .note("`?` is not a macro repetition operator in the 2015 edition, \
526 but is accepted in the 2018 edition")
530 return (None, KleeneOp::ZeroOrMore);
533 // #2 is a KleeneOp :D
534 Ok(Ok((op, _))) => return (Some(token), op),
536 // #2 is a random token :(
537 Ok(Err(token)) => token.span,
539 // #2 is not a token at all :(
547 sess.span_diagnostic.span_err(span, "expected `*` or `+`");
550 (None, KleeneOp::ZeroOrMore)
553 // `?` is a Kleene op, not a separator
554 fn parse_sep_and_kleene_op_2018<I>(
555 input: &mut Peekable<I>,
558 _features: &Features,
559 _attrs: &[ast::Attribute],
560 ) -> (Option<Token>, KleeneOp)
562 I: Iterator<Item = tokenstream::TokenTree>,
564 // We basically look at two token trees here, denoted as #1 and #2 below
565 let span = match parse_kleene_op(input, span) {
566 // #1 is a `?` (needs feature gate)
567 Ok(Ok((op, _op1_span))) if op == KleeneOp::ZeroOrOne => {
571 // #1 is a `+` or `*` KleeneOp
572 Ok(Ok((op, _))) => return (None, op),
574 // #1 is a separator followed by #2, a KleeneOp
575 Ok(Err(token)) => match parse_kleene_op(input, token.span) {
576 // #2 is the `?` Kleene op, which does not take a separator (error)
577 Ok(Ok((op, _op2_span))) if op == KleeneOp::ZeroOrOne => {
579 sess.span_diagnostic.span_err(
581 "the `?` macro repetition operator does not take a separator",
585 return (None, KleeneOp::ZeroOrMore);
588 // #2 is a KleeneOp :D
589 Ok(Ok((op, _))) => return (Some(token), op),
591 // #2 is a random token :(
592 Ok(Err(token)) => token.span,
594 // #2 is not a token at all :(
602 // If we ever get to this point, we have experienced an "unexpected token" error
604 .span_err(span, "expected one of: `*`, `+`, or `?`");
607 (None, KleeneOp::ZeroOrMore)