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::iter::Peekable;
21 use rustc_data_structures::sync::Lrc;
23 /// Contains the sub-token-trees of a "delimited" token tree, such as the contents of `(`. Note
24 /// that the delimiter itself might be `NoDelim`.
25 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
26 pub struct Delimited {
27 pub delim: token::DelimToken,
28 pub tts: Vec<TokenTree>,
32 /// Return the opening delimiter (possibly `NoDelim`).
33 pub fn open_token(&self) -> token::Token {
34 token::OpenDelim(self.delim)
37 /// Return the closing delimiter (possibly `NoDelim`).
38 pub fn close_token(&self) -> token::Token {
39 token::CloseDelim(self.delim)
42 /// Return a `self::TokenTree` with a `Span` corresponding to the opening delimiter.
43 pub fn open_tt(&self, span: Span) -> TokenTree {
44 let open_span = if span == DUMMY_SP {
47 span.with_lo(span.lo() + BytePos(self.delim.len() as u32))
49 TokenTree::Token(open_span, self.open_token())
52 /// Return a `self::TokenTree` with a `Span` corresponding to the closing delimiter.
53 pub fn close_tt(&self, span: Span) -> TokenTree {
54 let close_span = if span == DUMMY_SP {
57 span.with_lo(span.hi() - BytePos(self.delim.len() as u32))
59 TokenTree::Token(close_span, self.close_token())
63 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
64 pub struct SequenceRepetition {
65 /// The sequence of token trees
66 pub tts: Vec<TokenTree>,
67 /// The optional separator
68 pub separator: Option<token::Token>,
69 /// Whether the sequence can be repeated zero (*), or one or more times (+)
71 /// The number of `Match`s that appear in the sequence (and subsequences)
72 pub num_captures: usize,
75 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
76 /// for token sequences.
77 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
79 /// Kleene star (`*`) for zero or more repetitions
81 /// Kleene plus (`+`) for one or more repetitions
86 /// Similar to `tokenstream::TokenTree`, except that `$i`, `$i:ident`, and `$(...)`
87 /// are "first-class" token trees. Useful for parsing macros.
88 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
90 Token(Span, token::Token),
91 Delimited(Span, Lrc<Delimited>),
92 /// A kleene-style repetition sequence
93 Sequence(Span, Lrc<SequenceRepetition>),
95 MetaVar(Span, ast::Ident),
96 /// E.g. `$var:expr`. This is only used in the left hand side of MBE macros.
99 ast::Ident, /* name to bind */
100 ast::Ident, /* kind of nonterminal */
105 /// Return the number of tokens in the tree.
106 pub fn len(&self) -> usize {
108 TokenTree::Delimited(_, ref delimed) => match delimed.delim {
109 token::NoDelim => delimed.tts.len(),
110 _ => delimed.tts.len() + 2,
112 TokenTree::Sequence(_, ref seq) => seq.tts.len(),
117 /// Returns true if the given token tree contains no other tokens. This is vacuously true for
118 /// single tokens or metavar/decls, but may be false for delimited trees or sequences.
119 pub fn is_empty(&self) -> bool {
121 TokenTree::Delimited(_, ref delimed) => match delimed.delim {
122 token::NoDelim => delimed.tts.is_empty(),
125 TokenTree::Sequence(_, ref seq) => seq.tts.is_empty(),
130 /// Get the `index`-th sub-token-tree. This only makes sense for delimited trees and sequences.
131 pub fn get_tt(&self, index: usize) -> TokenTree {
132 match (self, index) {
133 (&TokenTree::Delimited(_, ref delimed), _) if delimed.delim == token::NoDelim => {
134 delimed.tts[index].clone()
136 (&TokenTree::Delimited(span, ref delimed), _) => {
138 return delimed.open_tt(span);
140 if index == delimed.tts.len() + 1 {
141 return delimed.close_tt(span);
143 delimed.tts[index - 1].clone()
145 (&TokenTree::Sequence(_, ref seq), _) => seq.tts[index].clone(),
146 _ => panic!("Cannot expand a token tree"),
150 /// Retrieve the `TokenTree`'s span.
151 pub fn span(&self) -> Span {
153 TokenTree::Token(sp, _)
154 | TokenTree::MetaVar(sp, _)
155 | TokenTree::MetaVarDecl(sp, _, _)
156 | TokenTree::Delimited(sp, _)
157 | TokenTree::Sequence(sp, _) => sp,
162 /// Takes a `tokenstream::TokenStream` and returns a `Vec<self::TokenTree>`. Specifically, this
163 /// takes a generic `TokenStream`, such as is used in the rest of the compiler, and returns a
164 /// collection of `TokenTree` for use in parsing a macro.
168 /// - `input`: a token stream to read from, the contents of which we are parsing.
169 /// - `expect_matchers`: `parse` can be used to parse either the "patterns" or the "body" of a
170 /// macro. Both take roughly the same form _except_ that in a pattern, metavars are declared with
171 /// their "matcher" type. For example `$var:expr` or `$id:ident`. In this example, `expr` and
172 /// `ident` are "matchers". They are not present in the body of a macro rule -- just in the
173 /// pattern, so we pass a parameter to indicate whether to expect them or not.
174 /// - `sess`: the parsing session. Any errors will be emitted to this session.
175 /// - `features`, `attrs`: language feature flags and attributes so that we know whether to use
176 /// unstable features or not.
180 /// A collection of `self::TokenTree`. There may also be some errors emitted to `sess`.
182 input: tokenstream::TokenStream,
183 expect_matchers: bool,
186 attrs: &[ast::Attribute],
187 ) -> Vec<TokenTree> {
188 // Will contain the final collection of `self::TokenTree`
189 let mut result = Vec::new();
191 // For each token tree in `input`, parse the token into a `self::TokenTree`, consuming
192 // additional trees if need be.
193 let mut trees = input.trees().peekable();
194 while let Some(tree) = trees.next() {
195 // Given the parsed tree, if there is a metavar and we are expecting matchers, actually
196 // parse out the matcher (i.e. in `$id:ident` this would parse the `:` and `ident`).
197 let tree = parse_tree(tree, &mut trees, expect_matchers, sess, features, attrs);
199 TokenTree::MetaVar(start_sp, ident) if expect_matchers => {
200 let span = match trees.next() {
201 Some(tokenstream::TokenTree::Token(span, token::Colon)) => match trees.next() {
202 Some(tokenstream::TokenTree::Token(end_sp, ref tok)) => match tok.ident() {
204 let span = end_sp.with_lo(start_sp.lo());
205 result.push(TokenTree::MetaVarDecl(span, ident, kind));
210 tree => tree.as_ref()
211 .map(tokenstream::TokenTree::span)
214 tree => tree.as_ref()
215 .map(tokenstream::TokenTree::span)
216 .unwrap_or(start_sp),
218 sess.missing_fragment_specifiers.borrow_mut().insert(span);
219 result.push(TokenTree::MetaVarDecl(
222 keywords::Invalid.ident(),
226 // Not a metavar or no matchers allowed, so just return the tree
227 _ => result.push(tree),
233 /// Takes a `tokenstream::TokenTree` and returns a `self::TokenTree`. Specifically, this takes a
234 /// generic `TokenTree`, such as is used in the rest of the compiler, and returns a `TokenTree`
235 /// for use in parsing a macro.
237 /// Converting the given tree may involve reading more tokens.
241 /// - `tree`: the tree we wish to convert.
242 /// - `trees`: an iterator over trees. We may need to read more tokens from it in order to finish
243 /// converting `tree`
244 /// - `expect_matchers`: same as for `parse` (see above).
245 /// - `sess`: the parsing session. Any errors will be emitted to this session.
246 /// - `features`, `attrs`: language feature flags and attributes so that we know whether to use
247 /// unstable features or not.
249 tree: tokenstream::TokenTree,
250 trees: &mut Peekable<I>,
251 expect_matchers: bool,
254 attrs: &[ast::Attribute],
257 I: Iterator<Item = tokenstream::TokenTree>,
259 // Depending on what `tree` is, we could be parsing different parts of a macro
261 // `tree` is a `$` token. Look at the next token in `trees`
262 tokenstream::TokenTree::Token(span, token::Dollar) => match trees.next() {
263 // `tree` is followed by a delimited set of token trees. This indicates the beginning
264 // of a repetition sequence in the macro (e.g. `$(pat)*`).
265 Some(tokenstream::TokenTree::Delimited(span, delimited)) => {
266 // Must have `(` not `{` or `[`
267 if delimited.delim != token::Paren {
268 let tok = pprust::token_to_string(&token::OpenDelim(delimited.delim));
269 let msg = format!("expected `(`, found `{}`", tok);
270 sess.span_diagnostic.span_err(span, &msg);
272 // Parse the contents of the sequence itself
273 let sequence = parse(delimited.tts.into(), expect_matchers, sess, features, attrs);
274 // Get the Kleene operator and optional separator
275 let (separator, op) = parse_sep_and_kleene_op(trees, span, sess, features, attrs);
276 // Count the number of captured "names" (i.e. named metavars)
277 let name_captures = macro_parser::count_names(&sequence);
280 Lrc::new(SequenceRepetition {
284 num_captures: name_captures,
289 // `tree` is followed by an `ident`. This could be `$meta_var` or the `$crate` special
290 // metavariable that names the crate of the invokation.
291 Some(tokenstream::TokenTree::Token(ident_span, ref token)) if token.is_ident() => {
292 let (ident, _) = token.ident().unwrap();
293 let span = ident_span.with_lo(span.lo());
294 if ident.name == keywords::Crate.name() {
295 let ident = ast::Ident {
296 name: keywords::DollarCrate.name(),
299 TokenTree::Token(span, token::Ident(ident, false))
301 TokenTree::MetaVar(span, ident)
305 // `tree` is followed by a random token. This is an error.
306 Some(tokenstream::TokenTree::Token(span, tok)) => {
308 "expected identifier, found `{}`",
309 pprust::token_to_string(&tok)
311 sess.span_diagnostic.span_err(span, &msg);
312 TokenTree::MetaVar(span, keywords::Invalid.ident())
315 // There are no more tokens. Just return the `$` we already have.
316 None => TokenTree::Token(span, token::Dollar),
319 // `tree` is an arbitrary token. Keep it.
320 tokenstream::TokenTree::Token(span, tok) => TokenTree::Token(span, tok),
322 // `tree` is the beginning of a delimited set of tokens (e.g. `(` or `{`). We need to
323 // descend into the delimited set and further parse it.
324 tokenstream::TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
327 delim: delimited.delim,
328 tts: parse(delimited.tts.into(), expect_matchers, sess, features, attrs),
334 /// Takes a token and returns `Some(KleeneOp)` if the token is `+` `*` or `?`. Otherwise, return
336 fn kleene_op(token: &token::Token) -> Option<KleeneOp> {
338 token::BinOp(token::Star) => Some(KleeneOp::ZeroOrMore),
339 token::BinOp(token::Plus) => Some(KleeneOp::OneOrMore),
340 token::Question => Some(KleeneOp::ZeroOrOne),
345 /// Parse the next token tree of the input looking for a KleeneOp. Returns
347 /// - Ok(Ok(op)) if the next token tree is a KleeneOp
348 /// - Ok(Err(tok, span)) if the next token tree is a token but not a KleeneOp
349 /// - Err(span) if the next token tree is not a token
350 fn parse_kleene_op<I>(
353 ) -> Result<Result<KleeneOp, (token::Token, Span)>, Span>
355 I: Iterator<Item = tokenstream::TokenTree>,
358 Some(tokenstream::TokenTree::Token(span, tok)) => match kleene_op(&tok) {
359 Some(op) => Ok(Ok(op)),
360 None => Ok(Err((tok, span))),
362 tree => Err(tree.as_ref()
363 .map(tokenstream::TokenTree::span)
368 /// Attempt to parse a single Kleene star, possibly with a separator.
370 /// For example, in a pattern such as `$(a),*`, `a` is the pattern to be repeated, `,` is the
371 /// separator, and `*` is the Kleene operator. This function is specifically concerned with parsing
372 /// the last two tokens of such a pattern: namely, the optional separator and the Kleene operator
373 /// itself. Note that here we are parsing the _macro_ itself, rather than trying to match some
374 /// stream of tokens in an invocation of a macro.
376 /// This function will take some input iterator `input` corresponding to `span` and a parsing
377 /// session `sess`. If the next one (or possibly two) tokens in `input` correspond to a Kleene
378 /// operator and separator, then a tuple with `(separator, KleeneOp)` is returned. Otherwise, an
379 /// error with the appropriate span is emitted to `sess` and a dummy value is returned.
380 fn parse_sep_and_kleene_op<I>(
381 input: &mut Peekable<I>,
385 attrs: &[ast::Attribute],
386 ) -> (Option<token::Token>, KleeneOp)
388 I: Iterator<Item = tokenstream::TokenTree>,
390 // We basically look at two token trees here, denoted as #1 and #2 below
391 let span = match parse_kleene_op(input, span) {
392 // #1 is any KleeneOp (`?`)
393 Ok(Ok(op)) if op == KleeneOp::ZeroOrOne => {
394 if !features.macro_at_most_once_rep
395 && !attr::contains_name(attrs, "allow_internal_unstable")
397 let explain = feature_gate::EXPLAIN_MACRO_AT_MOST_ONCE_REP;
400 "macro_at_most_once_rep",
409 // #1 is any KleeneOp (`+`, `*`)
410 Ok(Ok(op)) => return (None, op),
412 // #1 is a separator followed by #2, a KleeneOp
413 Ok(Err((tok, span))) => match parse_kleene_op(input, span) {
414 // #2 is a KleeneOp :D
415 Ok(Ok(op)) if op == KleeneOp::ZeroOrOne => {
416 if !features.macro_at_most_once_rep
417 && !attr::contains_name(attrs, "allow_internal_unstable")
419 let explain = feature_gate::EXPLAIN_MACRO_AT_MOST_ONCE_REP;
422 "macro_at_most_once_rep",
429 .span_err(span, "`?` macro repetition does not allow a separator");
433 Ok(Ok(op)) => return (Some(tok), op),
435 // #2 is a random token :(
436 Ok(Err((_, span))) => span,
438 // #2 is not a token at all :(
446 if !features.macro_at_most_once_rep && !attr::contains_name(attrs, "allow_internal_unstable") {
448 .span_err(span, "expected one of: `*`, `+`, or `?`");
450 sess.span_diagnostic.span_err(span, "expected `*` or `+`");
452 (None, KleeneOp::ZeroOrMore)