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 ext::tt::macro_parser;
13 use feature_gate::{self, emit_feature_err, Features, GateIssue};
14 use parse::{token, ParseSess};
17 use syntax_pos::{BytePos, Span, DUMMY_SP};
20 use std::cell::RefCell;
21 use std::iter::Peekable;
22 use rustc_data_structures::sync::Lrc;
24 /// Contains the sub-token-trees of a "delimited" token tree, such as the contents of `(`. Note
25 /// that the delimiter itself might be `NoDelim`.
26 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
27 pub struct Delimited {
28 pub delim: token::DelimToken,
29 pub tts: Vec<TokenTree>,
33 /// Return the opening delimiter (possibly `NoDelim`).
34 pub fn open_token(&self) -> token::Token {
35 token::OpenDelim(self.delim)
38 /// Return the closing delimiter (possibly `NoDelim`).
39 pub fn close_token(&self) -> token::Token {
40 token::CloseDelim(self.delim)
43 /// Return a `self::TokenTree` with a `Span` corresponding to the opening delimiter.
44 pub fn open_tt(&self, span: Span) -> TokenTree {
45 let open_span = if span == DUMMY_SP {
48 span.with_lo(span.lo() + BytePos(self.delim.len() as u32))
50 TokenTree::Token(open_span, self.open_token())
53 /// Return a `self::TokenTree` with a `Span` corresponding to the closing delimiter.
54 pub fn close_tt(&self, span: Span) -> TokenTree {
55 let close_span = if span == DUMMY_SP {
58 span.with_lo(span.hi() - BytePos(self.delim.len() as u32))
60 TokenTree::Token(close_span, self.close_token())
64 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
65 pub struct SequenceRepetition {
66 /// The sequence of token trees
67 pub tts: Vec<TokenTree>,
68 /// The optional separator
69 pub separator: Option<token::Token>,
70 /// Whether the sequence can be repeated zero (*), or one or more times (+)
72 /// The number of `Match`s that appear in the sequence (and subsequences)
73 pub num_captures: usize,
76 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
77 /// for token sequences.
78 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
80 /// Kleene star (`*`) for zero or more repetitions
82 /// Kleene plus (`+`) for one or more repetitions
87 /// Similar to `tokenstream::TokenTree`, except that `$i`, `$i:ident`, and `$(...)`
88 /// are "first-class" token trees. Useful for parsing macros.
89 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
91 Token(Span, token::Token),
92 Delimited(Span, Lrc<Delimited>),
93 /// A kleene-style repetition sequence
94 Sequence(Span, Lrc<SequenceRepetition>),
96 MetaVar(Span, ast::Ident),
97 /// E.g. `$var:expr`. This is only used in the left hand side of MBE macros.
100 ast::Ident, /* name to bind */
101 ast::Ident, /* kind of nonterminal */
106 /// Return the number of tokens in the tree.
107 pub fn len(&self) -> usize {
109 TokenTree::Delimited(_, ref delimed) => match delimed.delim {
110 token::NoDelim => delimed.tts.len(),
111 _ => delimed.tts.len() + 2,
113 TokenTree::Sequence(_, ref seq) => seq.tts.len(),
118 /// Returns true if the given token tree contains no other tokens. This is vacuously true for
119 /// single tokens or metavar/decls, but may be false for delimited trees or sequences.
120 pub fn is_empty(&self) -> bool {
122 TokenTree::Delimited(_, ref delimed) => match delimed.delim {
123 token::NoDelim => delimed.tts.is_empty(),
126 TokenTree::Sequence(_, ref seq) => seq.tts.is_empty(),
131 /// Get the `index`-th sub-token-tree. This only makes sense for delimited trees and sequences.
132 pub fn get_tt(&self, index: usize) -> TokenTree {
133 match (self, index) {
134 (&TokenTree::Delimited(_, ref delimed), _) if delimed.delim == token::NoDelim => {
135 delimed.tts[index].clone()
137 (&TokenTree::Delimited(span, ref delimed), _) => {
139 return delimed.open_tt(span);
141 if index == delimed.tts.len() + 1 {
142 return delimed.close_tt(span);
144 delimed.tts[index - 1].clone()
146 (&TokenTree::Sequence(_, ref seq), _) => seq.tts[index].clone(),
147 _ => panic!("Cannot expand a token tree"),
151 /// Retrieve the `TokenTree`'s span.
152 pub fn span(&self) -> Span {
154 TokenTree::Token(sp, _)
155 | TokenTree::MetaVar(sp, _)
156 | TokenTree::MetaVarDecl(sp, _, _)
157 | TokenTree::Delimited(sp, _)
158 | TokenTree::Sequence(sp, _) => sp,
163 /// Takes a `tokenstream::TokenStream` and returns a `Vec<self::TokenTree>`. Specifically, this
164 /// takes a generic `TokenStream`, such as is used in the rest of the compiler, and returns a
165 /// collection of `TokenTree` for use in parsing a macro.
169 /// - `input`: a token stream to read from, the contents of which we are parsing.
170 /// - `expect_matchers`: `parse` can be used to parse either the "patterns" or the "body" of a
171 /// macro. Both take roughly the same form _except_ that in a pattern, metavars are declared with
172 /// their "matcher" type. For example `$var:expr` or `$id:ident`. In this example, `expr` and
173 /// `ident` are "matchers". They are not present in the body of a macro rule -- just in the
174 /// pattern, so we pass a parameter to indicate whether to expect them or not.
175 /// - `sess`: the parsing session. Any errors will be emitted to this session.
176 /// - `features`, `attrs`: language feature flags and attributes so that we know whether to use
177 /// unstable features or not.
181 /// A collection of `self::TokenTree`. There may also be some errors emitted to `sess`.
183 input: tokenstream::TokenStream,
184 expect_matchers: bool,
186 features: &RefCell<Features>,
187 attrs: &[ast::Attribute],
188 ) -> Vec<TokenTree> {
189 // Will contain the final collection of `self::TokenTree`
190 let mut result = Vec::new();
192 // For each token tree in `input`, parse the token into a `self::TokenTree`, consuming
193 // additional trees if need be.
194 let mut trees = input.trees().peekable();
195 while let Some(tree) = trees.next() {
196 // Given the parsed tree, if there is a metavar and we are expecting matchers, actually
197 // parse out the matcher (i.e. in `$id:ident` this would parse the `:` and `ident`).
198 let tree = parse_tree(tree, &mut trees, expect_matchers, sess, features, attrs);
200 TokenTree::MetaVar(start_sp, ident) if expect_matchers => {
201 let span = match trees.next() {
202 Some(tokenstream::TokenTree::Token(span, token::Colon)) => match trees.next() {
203 Some(tokenstream::TokenTree::Token(end_sp, ref tok)) => match tok.ident() {
205 let span = end_sp.with_lo(start_sp.lo());
206 result.push(TokenTree::MetaVarDecl(span, ident, kind));
211 tree => tree.as_ref()
212 .map(tokenstream::TokenTree::span)
215 tree => tree.as_ref()
216 .map(tokenstream::TokenTree::span)
217 .unwrap_or(start_sp),
219 sess.missing_fragment_specifiers.borrow_mut().insert(span);
220 result.push(TokenTree::MetaVarDecl(
223 keywords::Invalid.ident(),
227 // Not a metavar or no matchers allowed, so just return the tree
228 _ => result.push(tree),
234 /// Takes a `tokenstream::TokenTree` and returns a `self::TokenTree`. Specifically, this takes a
235 /// generic `TokenTree`, such as is used in the rest of the compiler, and returns a `TokenTree`
236 /// for use in parsing a macro.
238 /// Converting the given tree may involve reading more tokens.
242 /// - `tree`: the tree we wish to convert.
243 /// - `trees`: an iterator over trees. We may need to read more tokens from it in order to finish
244 /// converting `tree`
245 /// - `expect_matchers`: same as for `parse` (see above).
246 /// - `sess`: the parsing session. Any errors will be emitted to this session.
247 /// - `features`, `attrs`: language feature flags and attributes so that we know whether to use
248 /// unstable features or not.
250 tree: tokenstream::TokenTree,
251 trees: &mut Peekable<I>,
252 expect_matchers: bool,
254 features: &RefCell<Features>,
255 attrs: &[ast::Attribute],
258 I: Iterator<Item = tokenstream::TokenTree>,
260 // Depending on what `tree` is, we could be parsing different parts of a macro
262 // `tree` is a `$` token. Look at the next token in `trees`
263 tokenstream::TokenTree::Token(span, token::Dollar) => match trees.next() {
264 // `tree` is followed by a delimited set of token trees. This indicates the beginning
265 // of a repetition sequence in the macro (e.g. `$(pat)*`).
266 Some(tokenstream::TokenTree::Delimited(span, delimited)) => {
267 // Must have `(` not `{` or `[`
268 if delimited.delim != token::Paren {
269 let tok = pprust::token_to_string(&token::OpenDelim(delimited.delim));
270 let msg = format!("expected `(`, found `{}`", tok);
271 sess.span_diagnostic.span_err(span, &msg);
273 // Parse the contents of the sequence itself
274 let sequence = parse(delimited.tts.into(), expect_matchers, sess, features, attrs);
275 // Get the Kleene operator and optional separator
276 let (separator, op) = parse_sep_and_kleene_op(trees, span, sess, features, attrs);
277 // Count the number of captured "names" (i.e. named metavars)
278 let name_captures = macro_parser::count_names(&sequence);
281 Lrc::new(SequenceRepetition {
285 num_captures: name_captures,
290 // `tree` is followed by an `ident`. This could be `$meta_var` or the `$crate` special
291 // metavariable that names the crate of the invokation.
292 Some(tokenstream::TokenTree::Token(ident_span, ref token)) if token.is_ident() => {
293 let ident = token.ident().unwrap();
294 let span = ident_span.with_lo(span.lo());
295 if ident.name == keywords::Crate.name() {
296 let ident = ast::Ident {
297 name: keywords::DollarCrate.name(),
300 TokenTree::Token(span, token::Ident(ident))
302 TokenTree::MetaVar(span, ident)
306 // `tree` is followed by a random token. This is an error.
307 Some(tokenstream::TokenTree::Token(span, tok)) => {
309 "expected identifier, found `{}`",
310 pprust::token_to_string(&tok)
312 sess.span_diagnostic.span_err(span, &msg);
313 TokenTree::MetaVar(span, keywords::Invalid.ident())
316 // There are no more tokens. Just return the `$` we already have.
317 None => TokenTree::Token(span, token::Dollar),
320 // `tree` is an arbitrary token. Keep it.
321 tokenstream::TokenTree::Token(span, tok) => TokenTree::Token(span, tok),
323 // `tree` is the beginning of a delimited set of tokens (e.g. `(` or `{`). We need to
324 // descend into the delimited set and further parse it.
325 tokenstream::TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
328 delim: delimited.delim,
329 tts: parse(delimited.tts.into(), expect_matchers, sess, features, attrs),
335 /// Takes a token and returns `Some(KleeneOp)` if the token is `+` `*` or `?`. Otherwise, return
337 fn kleene_op(token: &token::Token) -> Option<KleeneOp> {
339 token::BinOp(token::Star) => Some(KleeneOp::ZeroOrMore),
340 token::BinOp(token::Plus) => Some(KleeneOp::OneOrMore),
341 token::Question => Some(KleeneOp::ZeroOrOne),
346 /// Parse the next token tree of the input looking for a KleeneOp. Returns
348 /// - Ok(Ok(op)) if the next token tree is a KleeneOp
349 /// - Ok(Err(tok, span)) if the next token tree is a token but not a KleeneOp
350 /// - Err(span) if the next token tree is not a token
351 fn parse_kleene_op<I>(
354 ) -> Result<Result<KleeneOp, (token::Token, Span)>, Span>
356 I: Iterator<Item = tokenstream::TokenTree>,
359 Some(tokenstream::TokenTree::Token(span, tok)) => match kleene_op(&tok) {
360 Some(op) => Ok(Ok(op)),
361 None => Ok(Err((tok, span))),
363 tree => Err(tree.as_ref()
364 .map(tokenstream::TokenTree::span)
369 /// Attempt to parse a single Kleene star, possibly with a separator.
371 /// For example, in a pattern such as `$(a),*`, `a` is the pattern to be repeated, `,` is the
372 /// separator, and `*` is the Kleene operator. This function is specifically concerned with parsing
373 /// the last two tokens of such a pattern: namely, the optional separator and the Kleene operator
374 /// itself. Note that here we are parsing the _macro_ itself, rather than trying to match some
375 /// stream of tokens in an invocation of a macro.
377 /// This function will take some input iterator `input` corresponding to `span` and a parsing
378 /// session `sess`. If the next one (or possibly two) tokens in `input` correspond to a Kleene
379 /// operator and separator, then a tuple with `(separator, KleeneOp)` is returned. Otherwise, an
380 /// error with the appropriate span is emitted to `sess` and a dummy value is returned.
381 fn parse_sep_and_kleene_op<I>(
382 input: &mut Peekable<I>,
385 features: &RefCell<Features>,
386 attrs: &[ast::Attribute],
387 ) -> (Option<token::Token>, KleeneOp)
389 I: Iterator<Item = tokenstream::TokenTree>,
391 // We basically look at two token trees here, denoted as #1 and #2 below
392 let span = match parse_kleene_op(input, span) {
393 // #1 is a `+` or `*` KleeneOp
395 // `?` is ambiguous: it could be a separator or a Kleene::ZeroOrOne, so we need to look
396 // ahead one more token to be sure.
397 Ok(Ok(op)) if op != KleeneOp::ZeroOrOne => return (None, op),
399 // #1 is `?` token, but it could be a Kleene::ZeroOrOne without a separator or it could
400 // be a `?` separator followed by any Kleene operator. We need to look ahead 1 token to
403 assert_eq!(op, KleeneOp::ZeroOrOne);
405 // Lookahead at #2. If it is a KleenOp, then #1 is a separator.
406 let is_1_sep = if let Some(&tokenstream::TokenTree::Token(_, ref tok2)) = input.peek() {
407 kleene_op(tok2).is_some()
413 // #1 is a separator and #2 should be a KleepeOp::*
414 // (N.B. We need to advance the input iterator.)
415 match parse_kleene_op(input, span) {
416 // #2 is a KleeneOp (this is the only valid option) :)
417 Ok(Ok(op)) if op == KleeneOp::ZeroOrOne => {
418 if !features.borrow().macro_at_most_once_rep
419 && !attr::contains_name(attrs, "allow_internal_unstable")
421 let explain = feature_gate::EXPLAIN_MACRO_AT_MOST_ONCE_REP;
424 "macro_at_most_once_rep",
430 return (Some(token::Question), op);
432 Ok(Ok(op)) => return (Some(token::Question), op),
434 // #2 is a random token (this is an error) :(
435 Ok(Err((_, span))) => span,
437 // #2 is not even a token at all :(
441 if !features.borrow().macro_at_most_once_rep
442 && !attr::contains_name(attrs, "allow_internal_unstable")
444 let explain = feature_gate::EXPLAIN_MACRO_AT_MOST_ONCE_REP;
447 "macro_at_most_once_rep",
454 // #2 is a random tree and #1 is KleeneOp::ZeroOrOne
459 // #1 is a separator followed by #2, a KleeneOp
460 Ok(Err((tok, span))) => match parse_kleene_op(input, span) {
461 // #2 is a KleeneOp :D
462 Ok(Ok(op)) if op == KleeneOp::ZeroOrOne => {
463 if !features.borrow().macro_at_most_once_rep
464 && !attr::contains_name(attrs, "allow_internal_unstable")
466 let explain = feature_gate::EXPLAIN_MACRO_AT_MOST_ONCE_REP;
469 "macro_at_most_once_rep",
475 return (Some(tok), op);
477 Ok(Ok(op)) => return (Some(tok), op),
479 // #2 is a random token :(
480 Ok(Err((_, span))) => span,
482 // #2 is not a token at all :(
490 if !features.borrow().macro_at_most_once_rep
491 && !attr::contains_name(attrs, "allow_internal_unstable")
494 .span_err(span, "expected one of: `*`, `+`, or `?`");
496 sess.span_diagnostic.span_err(span, "expected `*` or `+`");
498 (None, KleeneOp::ZeroOrMore)