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) -> token::TokenKind {
28 token::OpenDelim(self.delim)
31 /// Returns the closing delimiter (possibly `NoDelim`).
32 pub fn close_token(&self) -> token::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(open_span, self.open_token())
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(close_span, self.close_token())
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<token::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(span: Span, kind: TokenKind) -> 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 })) => match trees.next() {
214 Some(tokenstream::TokenTree::Token(token)) => match token.ident() {
216 let span = token.span.with_lo(start_sp.lo());
217 result.push(TokenTree::MetaVarDecl(span, ident, kind));
224 .map(tokenstream::TokenTree::span)
229 .map(tokenstream::TokenTree::span)
230 .unwrap_or(start_sp),
232 sess.missing_fragment_specifiers.borrow_mut().insert(span);
233 result.push(TokenTree::MetaVarDecl(
236 ast::Ident::invalid(),
240 // Not a metavar or no matchers allowed, so just return the tree
241 _ => result.push(tree),
247 /// Takes a `tokenstream::TokenTree` and returns a `self::TokenTree`. Specifically, this takes a
248 /// generic `TokenTree`, such as is used in the rest of the compiler, and returns a `TokenTree`
249 /// for use in parsing a macro.
251 /// Converting the given tree may involve reading more tokens.
255 /// - `tree`: the tree we wish to convert.
256 /// - `trees`: an iterator over trees. We may need to read more tokens from it in order to finish
257 /// converting `tree`
258 /// - `expect_matchers`: same as for `parse` (see above).
259 /// - `sess`: the parsing session. Any errors will be emitted to this session.
260 /// - `features`, `attrs`: language feature flags and attributes so that we know whether to use
261 /// unstable features or not.
263 tree: tokenstream::TokenTree,
264 trees: &mut Peekable<I>,
265 expect_matchers: bool,
268 attrs: &[ast::Attribute],
270 macro_node_id: NodeId,
273 I: Iterator<Item = tokenstream::TokenTree>,
275 // Depending on what `tree` is, we could be parsing different parts of a macro
277 // `tree` is a `$` token. Look at the next token in `trees`
278 tokenstream::TokenTree::Token(Token { kind: token::Dollar, span }) => match trees.next() {
279 // `tree` is followed by a delimited set of token trees. This indicates the beginning
280 // of a repetition sequence in the macro (e.g. `$(pat)*`).
281 Some(tokenstream::TokenTree::Delimited(span, delim, tts)) => {
282 // Must have `(` not `{` or `[`
283 if delim != token::Paren {
284 let tok = pprust::token_to_string(&token::OpenDelim(delim));
285 let msg = format!("expected `(`, found `{}`", tok);
286 sess.span_diagnostic.span_err(span.entire(), &msg);
288 // Parse the contents of the sequence itself
289 let sequence = parse(
298 // Get the Kleene operator and optional separator
299 let (separator, op) =
300 parse_sep_and_kleene_op(
309 // Count the number of captured "names" (i.e., named metavars)
310 let name_captures = macro_parser::count_names(&sequence);
313 Lrc::new(SequenceRepetition {
317 num_captures: name_captures,
322 // `tree` is followed by an `ident`. This could be `$meta_var` or the `$crate` special
323 // metavariable that names the crate of the invocation.
324 Some(tokenstream::TokenTree::Token(token)) if token.is_ident() => {
325 let (ident, is_raw) = token.ident().unwrap();
326 let span = ident.span.with_lo(span.lo());
327 if ident.name == kw::Crate && !is_raw {
328 TokenTree::token(span, token::Ident(kw::DollarCrate, is_raw))
330 TokenTree::MetaVar(span, ident)
334 // `tree` is followed by a random token. This is an error.
335 Some(tokenstream::TokenTree::Token(token)) => {
337 "expected identifier, found `{}`",
338 pprust::token_to_string(&token),
340 sess.span_diagnostic.span_err(token.span, &msg);
341 TokenTree::MetaVar(token.span, ast::Ident::invalid())
344 // There are no more tokens. Just return the `$` we already have.
345 None => TokenTree::token(span, token::Dollar),
348 // `tree` is an arbitrary token. Keep it.
349 tokenstream::TokenTree::Token(token) => TokenTree::Token(token),
351 // `tree` is the beginning of a delimited set of tokens (e.g., `(` or `{`). We need to
352 // descend into the delimited set and further parse it.
353 tokenstream::TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited(
371 /// Takes a token and returns `Some(KleeneOp)` if the token is `+` `*` or `?`. Otherwise, return
373 fn kleene_op(token: &token::TokenKind) -> Option<KleeneOp> {
375 token::BinOp(token::Star) => Some(KleeneOp::ZeroOrMore),
376 token::BinOp(token::Plus) => Some(KleeneOp::OneOrMore),
377 token::Question => Some(KleeneOp::ZeroOrOne),
382 /// Parse the next token tree of the input looking for a KleeneOp. Returns
384 /// - Ok(Ok((op, span))) if the next token tree is a KleeneOp
385 /// - Ok(Err(tok, span)) if the next token tree is a token but not a KleeneOp
386 /// - Err(span) if the next token tree is not a token
387 fn parse_kleene_op<I>(input: &mut I, span: Span) -> Result<Result<(KleeneOp, Span), Token>, Span>
389 I: Iterator<Item = tokenstream::TokenTree>,
392 Some(tokenstream::TokenTree::Token(token)) => match kleene_op(&token) {
393 Some(op) => Ok(Ok((op, token.span))),
394 None => Ok(Err(token)),
398 .map(tokenstream::TokenTree::span)
403 /// Attempt to parse a single Kleene star, possibly with a separator.
405 /// For example, in a pattern such as `$(a),*`, `a` is the pattern to be repeated, `,` is the
406 /// separator, and `*` is the Kleene operator. This function is specifically concerned with parsing
407 /// the last two tokens of such a pattern: namely, the optional separator and the Kleene operator
408 /// itself. Note that here we are parsing the _macro_ itself, rather than trying to match some
409 /// stream of tokens in an invocation of a macro.
411 /// This function will take some input iterator `input` corresponding to `span` and a parsing
412 /// session `sess`. If the next one (or possibly two) tokens in `input` correspond to a Kleene
413 /// operator and separator, then a tuple with `(separator, KleeneOp)` is returned. Otherwise, an
414 /// error with the appropriate span is emitted to `sess` and a dummy value is returned.
416 /// N.B., in the 2015 edition, `*` and `+` are the only Kleene operators, and `?` is a separator.
417 /// In the 2018 edition however, `?` is a Kleene operator, and not a separator.
418 fn parse_sep_and_kleene_op<I>(
419 input: &mut Peekable<I>,
423 attrs: &[ast::Attribute],
425 macro_node_id: NodeId,
426 ) -> (Option<token::TokenKind>, KleeneOp)
428 I: Iterator<Item = tokenstream::TokenTree>,
431 Edition::Edition2015 => parse_sep_and_kleene_op_2015(
439 Edition::Edition2018 => parse_sep_and_kleene_op_2018(input, span, sess, features, attrs),
443 // `?` is a separator (with a migration warning) and never a KleeneOp.
444 fn parse_sep_and_kleene_op_2015<I>(
445 input: &mut Peekable<I>,
448 _features: &Features,
449 _attrs: &[ast::Attribute],
450 macro_node_id: NodeId,
451 ) -> (Option<token::TokenKind>, KleeneOp)
453 I: Iterator<Item = tokenstream::TokenTree>,
455 // We basically look at two token trees here, denoted as #1 and #2 below
456 let span = match parse_kleene_op(input, span) {
457 // #1 is a `+` or `*` KleeneOp
459 // `?` is ambiguous: it could be a separator (warning) or a Kleene::ZeroOrOne (error), so
460 // we need to look ahead one more token to be sure.
461 Ok(Ok((op, _))) if op != KleeneOp::ZeroOrOne => return (None, op),
463 // #1 is `?` token, but it could be a Kleene::ZeroOrOne (error in 2015) without a separator
464 // or it could be a `?` separator followed by any Kleene operator. We need to look ahead 1
465 // token to find out which.
466 Ok(Ok((op, op1_span))) => {
467 assert_eq!(op, KleeneOp::ZeroOrOne);
469 // Lookahead at #2. If it is a KleenOp, then #1 is a separator.
470 let is_1_sep = if let Some(tokenstream::TokenTree::Token(tok2)) = input.peek() {
471 kleene_op(tok2).is_some()
477 // #1 is a separator and #2 should be a KleepeOp.
478 // (N.B. We need to advance the input iterator.)
479 match parse_kleene_op(input, span) {
480 // #2 is `?`, which is not allowed as a Kleene op in 2015 edition,
481 // but is allowed in the 2018 edition.
482 Ok(Ok((op, op2_span))) if op == KleeneOp::ZeroOrOne => {
484 .struct_span_err(op2_span, "expected `*` or `+`")
485 .note("`?` is not a macro repetition operator in the 2015 edition, \
486 but is accepted in the 2018 edition")
490 return (None, KleeneOp::ZeroOrMore);
493 // #2 is a Kleene op, which is the only valid option
495 // Warn that `?` as a separator will be deprecated
497 BufferedEarlyLintId::QuestionMarkMacroSep,
500 "using `?` as a separator is deprecated and will be \
501 a hard error in an upcoming edition",
504 return (Some(token::Question), op);
507 // #2 is a random token (this is an error) :(
508 Ok(Err(_)) => op1_span,
510 // #2 is not even a token at all :(
514 // `?` is not allowed as a Kleene op in 2015,
515 // but is allowed in the 2018 edition
517 .struct_span_err(op1_span, "expected `*` or `+`")
518 .note("`?` is not a macro repetition operator in the 2015 edition, \
519 but is accepted in the 2018 edition")
523 return (None, KleeneOp::ZeroOrMore);
527 // #1 is a separator followed by #2, a KleeneOp
528 Ok(Err(token)) => match parse_kleene_op(input, token.span) {
529 // #2 is a `?`, which is not allowed as a Kleene op in 2015 edition,
530 // but is allowed in the 2018 edition
531 Ok(Ok((op, op2_span))) if op == KleeneOp::ZeroOrOne => {
533 .struct_span_err(op2_span, "expected `*` or `+`")
534 .note("`?` is not a macro repetition operator in the 2015 edition, \
535 but is accepted in the 2018 edition")
539 return (None, KleeneOp::ZeroOrMore);
542 // #2 is a KleeneOp :D
543 Ok(Ok((op, _))) => return (Some(token.kind), op),
545 // #2 is a random token :(
546 Ok(Err(token)) => token.span,
548 // #2 is not a token at all :(
556 sess.span_diagnostic.span_err(span, "expected `*` or `+`");
559 (None, KleeneOp::ZeroOrMore)
562 // `?` is a Kleene op, not a separator
563 fn parse_sep_and_kleene_op_2018<I>(
564 input: &mut Peekable<I>,
567 _features: &Features,
568 _attrs: &[ast::Attribute],
569 ) -> (Option<token::TokenKind>, KleeneOp)
571 I: Iterator<Item = tokenstream::TokenTree>,
573 // We basically look at two token trees here, denoted as #1 and #2 below
574 let span = match parse_kleene_op(input, span) {
575 // #1 is a `?` (needs feature gate)
576 Ok(Ok((op, _op1_span))) if op == KleeneOp::ZeroOrOne => {
580 // #1 is a `+` or `*` KleeneOp
581 Ok(Ok((op, _))) => return (None, op),
583 // #1 is a separator followed by #2, a KleeneOp
584 Ok(Err(token)) => match parse_kleene_op(input, token.span) {
585 // #2 is the `?` Kleene op, which does not take a separator (error)
586 Ok(Ok((op, _op2_span))) if op == KleeneOp::ZeroOrOne => {
588 sess.span_diagnostic.span_err(
590 "the `?` macro repetition operator does not take a separator",
594 return (None, KleeneOp::ZeroOrMore);
597 // #2 is a KleeneOp :D
598 Ok(Ok((op, _))) => return (Some(token.kind), op),
600 // #2 is a random token :(
601 Ok(Err(token)) => token.span,
603 // #2 is not a token at all :(
611 // If we ever get to this point, we have experienced an "unexpected token" error
613 .span_err(span, "expected one of: `*`, `+`, or `?`");
616 (None, KleeneOp::ZeroOrMore)