1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use early_buffered_lints::BufferedEarlyLintId;
13 use ext::tt::macro_parser;
14 use feature_gate::Features;
15 use parse::{token, ParseSess};
18 use syntax_pos::{edition::Edition, BytePos, Span};
19 use tokenstream::{self, DelimSpan};
22 use rustc_data_structures::sync::Lrc;
23 use std::iter::Peekable;
25 /// Contains the sub-token-trees of a "delimited" token tree, such as the contents of `(`. Note
26 /// that the delimiter itself might be `NoDelim`.
27 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
28 pub struct Delimited {
29 pub delim: token::DelimToken,
30 pub tts: Vec<TokenTree>,
34 /// Return the opening delimiter (possibly `NoDelim`).
35 pub fn open_token(&self) -> token::Token {
36 token::OpenDelim(self.delim)
39 /// Return the closing delimiter (possibly `NoDelim`).
40 pub fn close_token(&self) -> token::Token {
41 token::CloseDelim(self.delim)
44 /// Return a `self::TokenTree` with a `Span` corresponding to the opening delimiter.
45 pub fn open_tt(&self, span: Span) -> TokenTree {
46 let open_span = if span.is_dummy() {
49 span.with_lo(span.lo() + BytePos(self.delim.len() as u32))
51 TokenTree::Token(open_span, self.open_token())
54 /// Return a `self::TokenTree` with a `Span` corresponding to the closing delimiter.
55 pub fn close_tt(&self, span: Span) -> TokenTree {
56 let close_span = if span.is_dummy() {
59 span.with_lo(span.hi() - BytePos(self.delim.len() as u32))
61 TokenTree::Token(close_span, self.close_token())
65 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
66 pub struct SequenceRepetition {
67 /// The sequence of token trees
68 pub tts: Vec<TokenTree>,
69 /// The optional separator
70 pub separator: Option<token::Token>,
71 /// Whether the sequence can be repeated zero (*), or one or more times (+)
73 /// The number of `Match`s that appear in the sequence (and subsequences)
74 pub num_captures: usize,
77 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
78 /// for token sequences.
79 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
81 /// Kleene star (`*`) for zero or more repetitions
83 /// Kleene plus (`+`) for one or more repetitions
88 /// Similar to `tokenstream::TokenTree`, except that `$i`, `$i:ident`, and `$(...)`
89 /// are "first-class" token trees. Useful for parsing macros.
90 #[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable)]
92 Token(Span, token::Token),
93 Delimited(DelimSpan, Lrc<Delimited>),
94 /// A kleene-style repetition sequence
95 Sequence(DelimSpan, Lrc<SequenceRepetition>),
97 MetaVar(Span, ast::Ident),
98 /// e.g., `$var:expr`. This is only used in the left hand side of MBE macros.
101 ast::Ident, /* name to bind */
102 ast::Ident, /* kind of nonterminal */
107 /// Return the number of tokens in the tree.
108 pub fn len(&self) -> usize {
110 TokenTree::Delimited(_, ref delimed) => match delimed.delim {
111 token::NoDelim => delimed.tts.len(),
112 _ => delimed.tts.len() + 2,
114 TokenTree::Sequence(_, ref seq) => seq.tts.len(),
119 /// Returns true if the given token tree contains no other tokens. This is vacuously true for
120 /// single tokens or metavar/decls, but may be false for delimited trees or sequences.
121 pub fn is_empty(&self) -> bool {
123 TokenTree::Delimited(_, ref delimed) => match delimed.delim {
124 token::NoDelim => delimed.tts.is_empty(),
127 TokenTree::Sequence(_, ref seq) => seq.tts.is_empty(),
132 /// Get the `index`-th sub-token-tree. This only makes sense for delimited trees and sequences.
133 pub fn get_tt(&self, index: usize) -> TokenTree {
134 match (self, index) {
135 (&TokenTree::Delimited(_, ref delimed), _) if delimed.delim == token::NoDelim => {
136 delimed.tts[index].clone()
138 (&TokenTree::Delimited(span, ref delimed), _) => {
140 return delimed.open_tt(span.open);
142 if index == delimed.tts.len() + 1 {
143 return delimed.close_tt(span.close);
145 delimed.tts[index - 1].clone()
147 (&TokenTree::Sequence(_, ref seq), _) => seq.tts[index].clone(),
148 _ => panic!("Cannot expand a token tree"),
152 /// Retrieve the `TokenTree`'s span.
153 pub fn span(&self) -> Span {
155 TokenTree::Token(sp, _)
156 | TokenTree::MetaVar(sp, _)
157 | TokenTree::MetaVarDecl(sp, _, _) => sp,
158 TokenTree::Delimited(sp, _)
159 | TokenTree::Sequence(sp, _) => sp.entire(),
164 /// Takes a `tokenstream::TokenStream` and returns a `Vec<self::TokenTree>`. Specifically, this
165 /// takes a generic `TokenStream`, such as is used in the rest of the compiler, and returns a
166 /// collection of `TokenTree` for use in parsing a macro.
170 /// - `input`: a token stream to read from, the contents of which we are parsing.
171 /// - `expect_matchers`: `parse` can be used to parse either the "patterns" or the "body" of a
172 /// macro. Both take roughly the same form _except_ that in a pattern, metavars are declared with
173 /// their "matcher" type. For example `$var:expr` or `$id:ident`. In this example, `expr` and
174 /// `ident` are "matchers". They are not present in the body of a macro rule -- just in the
175 /// pattern, so we pass a parameter to indicate whether to expect them or not.
176 /// - `sess`: the parsing session. Any errors will be emitted to this session.
177 /// - `features`, `attrs`: language feature flags and attributes so that we know whether to use
178 /// unstable features or not.
179 /// - `edition`: which edition are we in.
180 /// - `macro_node_id`: the NodeId of the macro we are parsing.
184 /// A collection of `self::TokenTree`. There may also be some errors emitted to `sess`.
186 input: tokenstream::TokenStream,
187 expect_matchers: bool,
190 attrs: &[ast::Attribute],
192 macro_node_id: NodeId,
193 ) -> Vec<TokenTree> {
194 // Will contain the final collection of `self::TokenTree`
195 let mut result = Vec::new();
197 // For each token tree in `input`, parse the token into a `self::TokenTree`, consuming
198 // additional trees if need be.
199 let mut trees = input.trees().peekable();
200 while let Some(tree) = trees.next() {
201 // Given the parsed tree, if there is a metavar and we are expecting matchers, actually
202 // parse out the matcher (i.e., in `$id:ident` this would parse the `:` and `ident`).
203 let tree = parse_tree(
214 TokenTree::MetaVar(start_sp, ident) if expect_matchers => {
215 let span = match trees.next() {
216 Some(tokenstream::TokenTree::Token(span, token::Colon)) => match trees.next() {
217 Some(tokenstream::TokenTree::Token(end_sp, ref tok)) => match tok.ident() {
219 let span = end_sp.with_lo(start_sp.lo());
220 result.push(TokenTree::MetaVarDecl(span, ident, kind));
227 .map(tokenstream::TokenTree::span)
232 .map(tokenstream::TokenTree::span)
233 .unwrap_or(start_sp),
235 sess.missing_fragment_specifiers.borrow_mut().insert(span);
236 result.push(TokenTree::MetaVarDecl(
239 keywords::Invalid.ident(),
243 // Not a metavar or no matchers allowed, so just return the tree
244 _ => result.push(tree),
250 /// Takes a `tokenstream::TokenTree` and returns a `self::TokenTree`. Specifically, this takes a
251 /// generic `TokenTree`, such as is used in the rest of the compiler, and returns a `TokenTree`
252 /// for use in parsing a macro.
254 /// Converting the given tree may involve reading more tokens.
258 /// - `tree`: the tree we wish to convert.
259 /// - `trees`: an iterator over trees. We may need to read more tokens from it in order to finish
260 /// converting `tree`
261 /// - `expect_matchers`: same as for `parse` (see above).
262 /// - `sess`: the parsing session. Any errors will be emitted to this session.
263 /// - `features`, `attrs`: language feature flags and attributes so that we know whether to use
264 /// unstable features or not.
266 tree: tokenstream::TokenTree,
267 trees: &mut Peekable<I>,
268 expect_matchers: bool,
271 attrs: &[ast::Attribute],
273 macro_node_id: NodeId,
276 I: Iterator<Item = tokenstream::TokenTree>,
278 // Depending on what `tree` is, we could be parsing different parts of a macro
280 // `tree` is a `$` token. Look at the next token in `trees`
281 tokenstream::TokenTree::Token(span, token::Dollar) => match trees.next() {
282 // `tree` is followed by a delimited set of token trees. This indicates the beginning
283 // of a repetition sequence in the macro (e.g., `$(pat)*`).
284 Some(tokenstream::TokenTree::Delimited(span, delimited)) => {
285 // Must have `(` not `{` or `[`
286 if delimited.delim != token::Paren {
287 let tok = pprust::token_to_string(&token::OpenDelim(delimited.delim));
288 let msg = format!("expected `(`, found `{}`", tok);
289 sess.span_diagnostic.span_err(span.entire(), &msg);
291 // Parse the contents of the sequence itself
292 let sequence = parse(
293 delimited.tts.into(),
301 // Get the Kleene operator and optional separator
302 let (separator, op) =
303 parse_sep_and_kleene_op(
312 // Count the number of captured "names" (i.e., named metavars)
313 let name_captures = macro_parser::count_names(&sequence);
316 Lrc::new(SequenceRepetition {
320 num_captures: name_captures,
325 // `tree` is followed by an `ident`. This could be `$meta_var` or the `$crate` special
326 // metavariable that names the crate of the invocation.
327 Some(tokenstream::TokenTree::Token(ident_span, ref token)) if token.is_ident() => {
328 let (ident, is_raw) = token.ident().unwrap();
329 let span = ident_span.with_lo(span.lo());
330 if ident.name == keywords::Crate.name() && !is_raw {
331 let ident = ast::Ident::new(keywords::DollarCrate.name(), ident.span);
332 TokenTree::Token(span, token::Ident(ident, is_raw))
334 TokenTree::MetaVar(span, ident)
338 // `tree` is followed by a random token. This is an error.
339 Some(tokenstream::TokenTree::Token(span, tok)) => {
341 "expected identifier, found `{}`",
342 pprust::token_to_string(&tok)
344 sess.span_diagnostic.span_err(span, &msg);
345 TokenTree::MetaVar(span, keywords::Invalid.ident())
348 // There are no more tokens. Just return the `$` we already have.
349 None => TokenTree::Token(span, token::Dollar),
352 // `tree` is an arbitrary token. Keep it.
353 tokenstream::TokenTree::Token(span, tok) => TokenTree::Token(span, tok),
355 // `tree` is the beginning of a delimited set of tokens (e.g., `(` or `{`). We need to
356 // descend into the delimited set and further parse it.
357 tokenstream::TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
360 delim: delimited.delim,
362 delimited.tts.into(),
375 /// Takes a token and returns `Some(KleeneOp)` if the token is `+` `*` or `?`. Otherwise, return
377 fn kleene_op(token: &token::Token) -> Option<KleeneOp> {
379 token::BinOp(token::Star) => Some(KleeneOp::ZeroOrMore),
380 token::BinOp(token::Plus) => Some(KleeneOp::OneOrMore),
381 token::Question => Some(KleeneOp::ZeroOrOne),
386 /// Parse the next token tree of the input looking for a KleeneOp. Returns
388 /// - Ok(Ok((op, span))) if the next token tree is a KleeneOp
389 /// - Ok(Err(tok, span)) if the next token tree is a token but not a KleeneOp
390 /// - Err(span) if the next token tree is not a token
391 fn parse_kleene_op<I>(
394 ) -> Result<Result<(KleeneOp, Span), (token::Token, Span)>, Span>
396 I: Iterator<Item = tokenstream::TokenTree>,
399 Some(tokenstream::TokenTree::Token(span, tok)) => match kleene_op(&tok) {
400 Some(op) => Ok(Ok((op, span))),
401 None => Ok(Err((tok, span))),
405 .map(tokenstream::TokenTree::span)
410 /// Attempt to parse a single Kleene star, possibly with a separator.
412 /// For example, in a pattern such as `$(a),*`, `a` is the pattern to be repeated, `,` is the
413 /// separator, and `*` is the Kleene operator. This function is specifically concerned with parsing
414 /// the last two tokens of such a pattern: namely, the optional separator and the Kleene operator
415 /// itself. Note that here we are parsing the _macro_ itself, rather than trying to match some
416 /// stream of tokens in an invocation of a macro.
418 /// This function will take some input iterator `input` corresponding to `span` and a parsing
419 /// session `sess`. If the next one (or possibly two) tokens in `input` correspond to a Kleene
420 /// operator and separator, then a tuple with `(separator, KleeneOp)` is returned. Otherwise, an
421 /// error with the appropriate span is emitted to `sess` and a dummy value is returned.
423 /// NOTE: In 2015 edition, * and + are the only Kleene operators and `?` is a separator. In 2018,
424 /// `?` is a Kleene op and not a separator.
425 fn parse_sep_and_kleene_op<I>(
426 input: &mut Peekable<I>,
430 attrs: &[ast::Attribute],
432 macro_node_id: NodeId,
433 ) -> (Option<token::Token>, KleeneOp)
435 I: Iterator<Item = tokenstream::TokenTree>,
438 Edition::Edition2015 => parse_sep_and_kleene_op_2015(
446 Edition::Edition2018 => parse_sep_and_kleene_op_2018(input, span, sess, features, attrs),
450 // `?` is a separator (with a migration warning) and never a KleeneOp.
451 fn parse_sep_and_kleene_op_2015<I>(
452 input: &mut Peekable<I>,
455 _features: &Features,
456 _attrs: &[ast::Attribute],
457 macro_node_id: NodeId,
458 ) -> (Option<token::Token>, KleeneOp)
460 I: Iterator<Item = tokenstream::TokenTree>,
462 // We basically look at two token trees here, denoted as #1 and #2 below
463 let span = match parse_kleene_op(input, span) {
464 // #1 is a `+` or `*` KleeneOp
466 // `?` is ambiguous: it could be a separator (warning) or a Kleene::ZeroOrOne (error), so
467 // we need to look ahead one more token to be sure.
468 Ok(Ok((op, _))) if op != KleeneOp::ZeroOrOne => return (None, op),
470 // #1 is `?` token, but it could be a Kleene::ZeroOrOne (error in 2015) without a separator
471 // or it could be a `?` separator followed by any Kleene operator. We need to look ahead 1
472 // token to find out which.
473 Ok(Ok((op, op1_span))) => {
474 assert_eq!(op, KleeneOp::ZeroOrOne);
476 // Lookahead at #2. If it is a KleenOp, then #1 is a separator.
477 let is_1_sep = if let Some(&tokenstream::TokenTree::Token(_, ref tok2)) = input.peek() {
478 kleene_op(tok2).is_some()
484 // #1 is a separator and #2 should be a KleepeOp.
485 // (N.B. We need to advance the input iterator.)
486 match parse_kleene_op(input, span) {
487 // #2 is `?`, which is not allowed as a Kleene op in 2015 edition.
488 Ok(Ok((op, op2_span))) if op == KleeneOp::ZeroOrOne => {
490 .struct_span_err(op2_span, "expected `*` or `+`")
491 .note("`?` is not a macro repetition operator")
495 return (None, KleeneOp::ZeroOrMore);
498 // #2 is a Kleene op, which is the only valid option
500 // Warn that `?` as a separator will be deprecated
502 BufferedEarlyLintId::QuestionMarkMacroSep,
505 "using `?` as a separator is deprecated and will be \
506 a hard error in an upcoming edition",
509 return (Some(token::Question), op);
512 // #2 is a random token (this is an error) :(
513 Ok(Err((_, _))) => op1_span,
515 // #2 is not even a token at all :(
519 // `?` is not allowed as a Kleene op in 2015
521 .struct_span_err(op1_span, "expected `*` or `+`")
522 .note("`?` is not a macro repetition operator")
526 return (None, KleeneOp::ZeroOrMore);
530 // #1 is a separator followed by #2, a KleeneOp
531 Ok(Err((tok, span))) => match parse_kleene_op(input, span) {
532 // #2 is a `?`, which is not allowed as a Kleene op in 2015 edition.
533 Ok(Ok((op, op2_span))) if op == KleeneOp::ZeroOrOne => {
535 .struct_span_err(op2_span, "expected `*` or `+`")
536 .note("`?` is not a macro repetition operator")
540 return (None, KleeneOp::ZeroOrMore);
543 // #2 is a KleeneOp :D
544 Ok(Ok((op, _))) => return (Some(tok), op),
546 // #2 is a random token :(
547 Ok(Err((_, span))) => 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<token::Token>, 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((tok, span))) => match parse_kleene_op(input, 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(tok), op),
601 // #2 is a random token :(
602 Ok(Err((_, span))) => 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)