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, 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 the opening delimiter (possibly `NoDelim`).
26 pub fn open_token(&self) -> token::TokenKind {
27 token::OpenDelim(self.delim)
30 /// Returns the closing delimiter (possibly `NoDelim`).
31 pub fn close_token(&self) -> token::TokenKind {
32 token::CloseDelim(self.delim)
35 /// Returns a `self::TokenTree` with a `Span` corresponding to the opening delimiter.
36 pub fn open_tt(&self, span: Span) -> TokenTree {
37 let open_span = if span.is_dummy() {
40 span.with_lo(span.lo() + BytePos(self.delim.len() as u32))
42 TokenTree::Token(open_span, self.open_token())
45 /// Returns a `self::TokenTree` with a `Span` corresponding to the closing delimiter.
46 pub fn close_tt(&self, span: Span) -> TokenTree {
47 let close_span = if span.is_dummy() {
50 span.with_lo(span.hi() - BytePos(self.delim.len() as u32))
52 TokenTree::Token(close_span, self.close_token())
56 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
57 pub struct SequenceRepetition {
58 /// The sequence of token trees
59 pub tts: Vec<TokenTree>,
60 /// The optional separator
61 pub separator: Option<token::TokenKind>,
62 /// Whether the sequence can be repeated zero (*), or one or more times (+)
64 /// The number of `Match`s that appear in the sequence (and subsequences)
65 pub num_captures: usize,
68 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
69 /// for token sequences.
70 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
72 /// Kleene star (`*`) for zero or more repetitions
74 /// Kleene plus (`+`) for one or more repetitions
76 /// Kleene optional (`?`) for zero or one reptitions
80 /// Similar to `tokenstream::TokenTree`, except that `$i`, `$i:ident`, and `$(...)`
81 /// are "first-class" token trees. Useful for parsing macros.
82 #[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable)]
84 Token(Span, token::TokenKind),
85 Delimited(DelimSpan, Lrc<Delimited>),
86 /// A kleene-style repetition sequence
87 Sequence(DelimSpan, Lrc<SequenceRepetition>),
89 MetaVar(Span, ast::Ident),
90 /// e.g., `$var:expr`. This is only used in the left hand side of MBE macros.
93 ast::Ident, /* name to bind */
94 ast::Ident, /* kind of nonterminal */
99 /// Return the number of tokens in the tree.
100 pub fn len(&self) -> usize {
102 TokenTree::Delimited(_, ref delimed) => match delimed.delim {
103 token::NoDelim => delimed.tts.len(),
104 _ => delimed.tts.len() + 2,
106 TokenTree::Sequence(_, ref seq) => seq.tts.len(),
111 /// Returns `true` if the given token tree contains no other tokens. This is vacuously true for
112 /// single tokens or metavar/decls, but may be false for delimited trees or sequences.
113 pub fn is_empty(&self) -> bool {
115 TokenTree::Delimited(_, ref delimed) => match delimed.delim {
116 token::NoDelim => delimed.tts.is_empty(),
119 TokenTree::Sequence(_, ref seq) => seq.tts.is_empty(),
124 /// Gets the `index`-th sub-token-tree. This only makes sense for delimited trees and sequences.
125 pub fn get_tt(&self, index: usize) -> TokenTree {
126 match (self, index) {
127 (&TokenTree::Delimited(_, ref delimed), _) if delimed.delim == token::NoDelim => {
128 delimed.tts[index].clone()
130 (&TokenTree::Delimited(span, ref delimed), _) => {
132 return delimed.open_tt(span.open);
134 if index == delimed.tts.len() + 1 {
135 return delimed.close_tt(span.close);
137 delimed.tts[index - 1].clone()
139 (&TokenTree::Sequence(_, ref seq), _) => seq.tts[index].clone(),
140 _ => panic!("Cannot expand a token tree"),
144 /// Retrieves the `TokenTree`'s span.
145 pub fn span(&self) -> Span {
147 TokenTree::Token(sp, _)
148 | TokenTree::MetaVar(sp, _)
149 | TokenTree::MetaVarDecl(sp, _, _) => sp,
150 TokenTree::Delimited(sp, _)
151 | TokenTree::Sequence(sp, _) => sp.entire(),
156 /// Takes a `tokenstream::TokenStream` and returns a `Vec<self::TokenTree>`. Specifically, this
157 /// takes a generic `TokenStream`, such as is used in the rest of the compiler, and returns a
158 /// collection of `TokenTree` for use in parsing a macro.
162 /// - `input`: a token stream to read from, the contents of which we are parsing.
163 /// - `expect_matchers`: `parse` can be used to parse either the "patterns" or the "body" of a
164 /// macro. Both take roughly the same form _except_ that in a pattern, metavars are declared with
165 /// their "matcher" type. For example `$var:expr` or `$id:ident`. In this example, `expr` and
166 /// `ident` are "matchers". They are not present in the body of a macro rule -- just in the
167 /// pattern, so we pass a parameter to indicate whether to expect them or not.
168 /// - `sess`: the parsing session. Any errors will be emitted to this session.
169 /// - `features`, `attrs`: language feature flags and attributes so that we know whether to use
170 /// unstable features or not.
171 /// - `edition`: which edition are we in.
172 /// - `macro_node_id`: the NodeId of the macro we are parsing.
176 /// A collection of `self::TokenTree`. There may also be some errors emitted to `sess`.
178 input: tokenstream::TokenStream,
179 expect_matchers: bool,
182 attrs: &[ast::Attribute],
184 macro_node_id: NodeId,
185 ) -> Vec<TokenTree> {
186 // Will contain the final collection of `self::TokenTree`
187 let mut result = Vec::new();
189 // For each token tree in `input`, parse the token into a `self::TokenTree`, consuming
190 // additional trees if need be.
191 let mut trees = input.trees().peekable();
192 while let Some(tree) = trees.next() {
193 // Given the parsed tree, if there is a metavar and we are expecting matchers, actually
194 // parse out the matcher (i.e., in `$id:ident` this would parse the `:` and `ident`).
195 let tree = parse_tree(
206 TokenTree::MetaVar(start_sp, ident) if expect_matchers => {
207 let span = match trees.next() {
208 Some(tokenstream::TokenTree::Token(span, token::Colon)) => match trees.next() {
209 Some(tokenstream::TokenTree::Token(end_sp, ref tok)) => match tok.ident() {
211 let span = end_sp.with_lo(start_sp.lo());
212 result.push(TokenTree::MetaVarDecl(span, ident, kind));
219 .map(tokenstream::TokenTree::span)
224 .map(tokenstream::TokenTree::span)
225 .unwrap_or(start_sp),
227 sess.missing_fragment_specifiers.borrow_mut().insert(span);
228 result.push(TokenTree::MetaVarDecl(
231 ast::Ident::invalid(),
235 // Not a metavar or no matchers allowed, so just return the tree
236 _ => result.push(tree),
242 /// Takes a `tokenstream::TokenTree` and returns a `self::TokenTree`. Specifically, this takes a
243 /// generic `TokenTree`, such as is used in the rest of the compiler, and returns a `TokenTree`
244 /// for use in parsing a macro.
246 /// Converting the given tree may involve reading more tokens.
250 /// - `tree`: the tree we wish to convert.
251 /// - `trees`: an iterator over trees. We may need to read more tokens from it in order to finish
252 /// converting `tree`
253 /// - `expect_matchers`: same as for `parse` (see above).
254 /// - `sess`: the parsing session. Any errors will be emitted to this session.
255 /// - `features`, `attrs`: language feature flags and attributes so that we know whether to use
256 /// unstable features or not.
258 tree: tokenstream::TokenTree,
259 trees: &mut Peekable<I>,
260 expect_matchers: bool,
263 attrs: &[ast::Attribute],
265 macro_node_id: NodeId,
268 I: Iterator<Item = tokenstream::TokenTree>,
270 // Depending on what `tree` is, we could be parsing different parts of a macro
272 // `tree` is a `$` token. Look at the next token in `trees`
273 tokenstream::TokenTree::Token(span, token::Dollar) => match trees.next() {
274 // `tree` is followed by a delimited set of token trees. This indicates the beginning
275 // of a repetition sequence in the macro (e.g. `$(pat)*`).
276 Some(tokenstream::TokenTree::Delimited(span, delim, tts)) => {
277 // Must have `(` not `{` or `[`
278 if delim != token::Paren {
279 let tok = pprust::token_to_string(&token::OpenDelim(delim));
280 let msg = format!("expected `(`, found `{}`", tok);
281 sess.span_diagnostic.span_err(span.entire(), &msg);
283 // Parse the contents of the sequence itself
284 let sequence = parse(
293 // Get the Kleene operator and optional separator
294 let (separator, op) =
295 parse_sep_and_kleene_op(
304 // Count the number of captured "names" (i.e., named metavars)
305 let name_captures = macro_parser::count_names(&sequence);
308 Lrc::new(SequenceRepetition {
312 num_captures: name_captures,
317 // `tree` is followed by an `ident`. This could be `$meta_var` or the `$crate` special
318 // metavariable that names the crate of the invocation.
319 Some(tokenstream::TokenTree::Token(ident_span, ref token)) if token.is_ident() => {
320 let (ident, is_raw) = token.ident().unwrap();
321 let span = ident_span.with_lo(span.lo());
322 if ident.name == kw::Crate && !is_raw {
323 let ident = ast::Ident::new(kw::DollarCrate, ident.span);
324 TokenTree::Token(span, token::Ident(ident, is_raw))
326 TokenTree::MetaVar(span, ident)
330 // `tree` is followed by a random token. This is an error.
331 Some(tokenstream::TokenTree::Token(span, tok)) => {
333 "expected identifier, found `{}`",
334 pprust::token_to_string(&tok)
336 sess.span_diagnostic.span_err(span, &msg);
337 TokenTree::MetaVar(span, ast::Ident::invalid())
340 // There are no more tokens. Just return the `$` we already have.
341 None => TokenTree::Token(span, token::Dollar),
344 // `tree` is an arbitrary token. Keep it.
345 tokenstream::TokenTree::Token(span, tok) => TokenTree::Token(span, tok),
347 // `tree` is the beginning of a delimited set of tokens (e.g., `(` or `{`). We need to
348 // descend into the delimited set and further parse it.
349 tokenstream::TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited(
367 /// Takes a token and returns `Some(KleeneOp)` if the token is `+` `*` or `?`. Otherwise, return
369 fn kleene_op(token: &token::TokenKind) -> Option<KleeneOp> {
371 token::BinOp(token::Star) => Some(KleeneOp::ZeroOrMore),
372 token::BinOp(token::Plus) => Some(KleeneOp::OneOrMore),
373 token::Question => Some(KleeneOp::ZeroOrOne),
378 /// Parse the next token tree of the input looking for a KleeneOp. Returns
380 /// - Ok(Ok((op, span))) if the next token tree is a KleeneOp
381 /// - Ok(Err(tok, span)) if the next token tree is a token but not a KleeneOp
382 /// - Err(span) if the next token tree is not a token
383 fn parse_kleene_op<I>(
386 ) -> Result<Result<(KleeneOp, Span), (token::TokenKind, Span)>, Span>
388 I: Iterator<Item = tokenstream::TokenTree>,
391 Some(tokenstream::TokenTree::Token(span, tok)) => match kleene_op(&tok) {
392 Some(op) => Ok(Ok((op, span))),
393 None => Ok(Err((tok, span))),
397 .map(tokenstream::TokenTree::span)
402 /// Attempt to parse a single Kleene star, possibly with a separator.
404 /// For example, in a pattern such as `$(a),*`, `a` is the pattern to be repeated, `,` is the
405 /// separator, and `*` is the Kleene operator. This function is specifically concerned with parsing
406 /// the last two tokens of such a pattern: namely, the optional separator and the Kleene operator
407 /// itself. Note that here we are parsing the _macro_ itself, rather than trying to match some
408 /// stream of tokens in an invocation of a macro.
410 /// This function will take some input iterator `input` corresponding to `span` and a parsing
411 /// session `sess`. If the next one (or possibly two) tokens in `input` correspond to a Kleene
412 /// operator and separator, then a tuple with `(separator, KleeneOp)` is returned. Otherwise, an
413 /// error with the appropriate span is emitted to `sess` and a dummy value is returned.
415 /// N.B., in the 2015 edition, `*` and `+` are the only Kleene operators, and `?` is a separator.
416 /// In the 2018 edition however, `?` is a Kleene operator, and not a separator.
417 fn parse_sep_and_kleene_op<I>(
418 input: &mut Peekable<I>,
422 attrs: &[ast::Attribute],
424 macro_node_id: NodeId,
425 ) -> (Option<token::TokenKind>, KleeneOp)
427 I: Iterator<Item = tokenstream::TokenTree>,
430 Edition::Edition2015 => parse_sep_and_kleene_op_2015(
438 Edition::Edition2018 => parse_sep_and_kleene_op_2018(input, span, sess, features, attrs),
442 // `?` is a separator (with a migration warning) and never a KleeneOp.
443 fn parse_sep_and_kleene_op_2015<I>(
444 input: &mut Peekable<I>,
447 _features: &Features,
448 _attrs: &[ast::Attribute],
449 macro_node_id: NodeId,
450 ) -> (Option<token::TokenKind>, KleeneOp)
452 I: Iterator<Item = tokenstream::TokenTree>,
454 // We basically look at two token trees here, denoted as #1 and #2 below
455 let span = match parse_kleene_op(input, span) {
456 // #1 is a `+` or `*` KleeneOp
458 // `?` is ambiguous: it could be a separator (warning) or a Kleene::ZeroOrOne (error), so
459 // we need to look ahead one more token to be sure.
460 Ok(Ok((op, _))) if op != KleeneOp::ZeroOrOne => return (None, op),
462 // #1 is `?` token, but it could be a Kleene::ZeroOrOne (error in 2015) without a separator
463 // or it could be a `?` separator followed by any Kleene operator. We need to look ahead 1
464 // token to find out which.
465 Ok(Ok((op, op1_span))) => {
466 assert_eq!(op, KleeneOp::ZeroOrOne);
468 // Lookahead at #2. If it is a KleenOp, then #1 is a separator.
469 let is_1_sep = if let Some(&tokenstream::TokenTree::Token(_, ref tok2)) = input.peek() {
470 kleene_op(tok2).is_some()
476 // #1 is a separator and #2 should be a KleepeOp.
477 // (N.B. We need to advance the input iterator.)
478 match parse_kleene_op(input, span) {
479 // #2 is `?`, which is not allowed as a Kleene op in 2015 edition,
480 // but is allowed in the 2018 edition.
481 Ok(Ok((op, op2_span))) if op == KleeneOp::ZeroOrOne => {
483 .struct_span_err(op2_span, "expected `*` or `+`")
484 .note("`?` is not a macro repetition operator in the 2015 edition, \
485 but is accepted in the 2018 edition")
489 return (None, KleeneOp::ZeroOrMore);
492 // #2 is a Kleene op, which is the only valid option
494 // Warn that `?` as a separator will be deprecated
496 BufferedEarlyLintId::QuestionMarkMacroSep,
499 "using `?` as a separator is deprecated and will be \
500 a hard error in an upcoming edition",
503 return (Some(token::Question), op);
506 // #2 is a random token (this is an error) :(
507 Ok(Err((_, _))) => op1_span,
509 // #2 is not even a token at all :(
513 // `?` is not allowed as a Kleene op in 2015,
514 // but is allowed in the 2018 edition
516 .struct_span_err(op1_span, "expected `*` or `+`")
517 .note("`?` is not a macro repetition operator in the 2015 edition, \
518 but is accepted in the 2018 edition")
522 return (None, KleeneOp::ZeroOrMore);
526 // #1 is a separator followed by #2, a KleeneOp
527 Ok(Err((tok, span))) => match parse_kleene_op(input, span) {
528 // #2 is a `?`, which is not allowed as a Kleene op in 2015 edition,
529 // but is allowed in the 2018 edition
530 Ok(Ok((op, op2_span))) if op == KleeneOp::ZeroOrOne => {
532 .struct_span_err(op2_span, "expected `*` or `+`")
533 .note("`?` is not a macro repetition operator in the 2015 edition, \
534 but is accepted in the 2018 edition")
538 return (None, KleeneOp::ZeroOrMore);
541 // #2 is a KleeneOp :D
542 Ok(Ok((op, _))) => return (Some(tok), op),
544 // #2 is a random token :(
545 Ok(Err((_, span))) => span,
547 // #2 is not a token at all :(
555 sess.span_diagnostic.span_err(span, "expected `*` or `+`");
558 (None, KleeneOp::ZeroOrMore)
561 // `?` is a Kleene op, not a separator
562 fn parse_sep_and_kleene_op_2018<I>(
563 input: &mut Peekable<I>,
566 _features: &Features,
567 _attrs: &[ast::Attribute],
568 ) -> (Option<token::TokenKind>, KleeneOp)
570 I: Iterator<Item = tokenstream::TokenTree>,
572 // We basically look at two token trees here, denoted as #1 and #2 below
573 let span = match parse_kleene_op(input, span) {
574 // #1 is a `?` (needs feature gate)
575 Ok(Ok((op, _op1_span))) if op == KleeneOp::ZeroOrOne => {
579 // #1 is a `+` or `*` KleeneOp
580 Ok(Ok((op, _))) => return (None, op),
582 // #1 is a separator followed by #2, a KleeneOp
583 Ok(Err((tok, span))) => match parse_kleene_op(input, span) {
584 // #2 is the `?` Kleene op, which does not take a separator (error)
585 Ok(Ok((op, _op2_span))) if op == KleeneOp::ZeroOrOne => {
587 sess.span_diagnostic.span_err(
589 "the `?` macro repetition operator does not take a separator",
593 return (None, KleeneOp::ZeroOrMore);
596 // #2 is a KleeneOp :D
597 Ok(Ok((op, _))) => return (Some(tok), op),
599 // #2 is a random token :(
600 Ok(Err((_, span))) => span,
602 // #2 is not a token at all :(
610 // If we ever get to this point, we have experienced an "unexpected token" error
612 .span_err(span, "expected one of: `*`, `+`, or `?`");
615 (None, KleeneOp::ZeroOrMore)