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 parse::{token, ParseSess};
16 use syntax_pos::{BytePos, Span, DUMMY_SP};
21 /// Contains the sub-token-trees of a "delimited" token tree, such as the contents of `(`. Note
22 /// that the delimiter itself might be `NoDelim`.
23 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
24 pub struct Delimited {
25 pub delim: token::DelimToken,
26 pub tts: Vec<TokenTree>,
30 /// Return the opening delimiter (possibly `NoDelim`).
31 pub fn open_token(&self) -> token::Token {
32 token::OpenDelim(self.delim)
35 /// Return the closing delimiter (possibly `NoDelim`).
36 pub fn close_token(&self) -> token::Token {
37 token::CloseDelim(self.delim)
40 /// Return a `self::TokenTree` with a `Span` corresponding to the opening delimiter.
41 pub fn open_tt(&self, span: Span) -> TokenTree {
42 let open_span = if span == DUMMY_SP {
45 span.with_lo(span.lo() + BytePos(self.delim.len() as u32))
47 TokenTree::Token(open_span, self.open_token())
50 /// Return a `self::TokenTree` with a `Span` corresponding to the closing delimiter.
51 pub fn close_tt(&self, span: Span) -> TokenTree {
52 let close_span = if span == DUMMY_SP {
55 span.with_lo(span.hi() - BytePos(self.delim.len() as u32))
57 TokenTree::Token(close_span, self.close_token())
61 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
62 pub struct SequenceRepetition {
63 /// The sequence of token trees
64 pub tts: Vec<TokenTree>,
65 /// The optional separator
66 pub separator: Option<token::Token>,
67 /// Whether the sequence can be repeated zero (*), or one or more times (+)
69 /// The number of `Match`s that appear in the sequence (and subsequences)
70 pub num_captures: usize,
73 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
74 /// for token sequences.
75 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
77 /// Kleene star (`*`) for zero or more repetitions
79 /// Kleene plus (`+`) for one or more repetitions
83 /// Similar to `tokenstream::TokenTree`, except that `$i`, `$i:ident`, and `$(...)`
84 /// are "first-class" token trees. Useful for parsing macros.
85 #[derive(Debug, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)]
87 Token(Span, token::Token),
88 Delimited(Span, Rc<Delimited>),
89 /// A kleene-style repetition sequence
90 Sequence(Span, Rc<SequenceRepetition>),
92 MetaVar(Span, ast::Ident),
93 /// E.g. `$var:expr`. This is only used in the left hand side of MBE macros.
96 ast::Ident, /* name to bind */
97 ast::Ident, /* kind of nonterminal */
102 /// Return the number of tokens in the tree.
103 pub fn len(&self) -> usize {
105 TokenTree::Delimited(_, ref delimed) => match delimed.delim {
106 token::NoDelim => delimed.tts.len(),
107 _ => delimed.tts.len() + 2,
109 TokenTree::Sequence(_, ref seq) => seq.tts.len(),
114 /// Returns true if the given token tree contains no other tokens. This is vacuously true for
115 /// single tokens or metavar/decls, but may be false for delimited trees or sequences.
116 pub fn is_empty(&self) -> bool {
118 TokenTree::Delimited(_, ref delimed) => match delimed.delim {
119 token::NoDelim => delimed.tts.is_empty(),
122 TokenTree::Sequence(_, ref seq) => seq.tts.is_empty(),
127 /// Get the `index`-th sub-token-tree. This only makes sense for delimited trees and sequences.
128 pub fn get_tt(&self, index: usize) -> TokenTree {
129 match (self, index) {
130 (&TokenTree::Delimited(_, ref delimed), _) if delimed.delim == token::NoDelim => {
131 delimed.tts[index].clone()
133 (&TokenTree::Delimited(span, ref delimed), _) => {
135 return delimed.open_tt(span);
137 if index == delimed.tts.len() + 1 {
138 return delimed.close_tt(span);
140 delimed.tts[index - 1].clone()
142 (&TokenTree::Sequence(_, ref seq), _) => seq.tts[index].clone(),
143 _ => panic!("Cannot expand a token tree"),
147 /// Retrieve the `TokenTree`'s span.
148 pub fn span(&self) -> Span {
150 TokenTree::Token(sp, _)
151 | TokenTree::MetaVar(sp, _)
152 | TokenTree::MetaVarDecl(sp, _, _)
153 | TokenTree::Delimited(sp, _)
154 | TokenTree::Sequence(sp, _) => sp,
159 /// Takes a `tokenstream::TokenStream` and returns a `Vec<self::TokenTree>`. Specifically, this
160 /// takes a generic `TokenStream`, such as is used in the rest of the compiler, and returns a
161 /// collection of `TokenTree` for use in parsing a macro.
165 /// - `input`: a token stream to read from, the contents of which we are parsing.
166 /// - `expect_matchers`: `parse` can be used to parse either the "patterns" or the "body" of a
167 /// macro. Both take roughly the same form _except_ that in a pattern, metavars are declared with
168 /// their "matcher" type. For example `$var:expr` or `$id:ident`. In this example, `expr` and
169 /// `ident` are "matchers". They are not present in the body of a macro rule -- just in the
170 /// pattern, so we pass a parameter to indicate whether to expect them or not.
171 /// - `sess`: the parsing session. Any errors will be emitted to this session.
175 /// A collection of `self::TokenTree`. There may also be some errors emitted to `sess`.
177 input: tokenstream::TokenStream,
178 expect_matchers: bool,
180 ) -> Vec<TokenTree> {
181 // Will contain the final collection of `self::TokenTree`
182 let mut result = Vec::new();
184 // For each token tree in `input`, parse the token into a `self::TokenTree`, consuming
185 // additional trees if need be.
186 let mut trees = input.trees();
187 while let Some(tree) = trees.next() {
188 let tree = parse_tree(tree, &mut trees, expect_matchers, sess);
190 // Given the parsed tree, if there is a metavar and we are expecting matchers, actually
191 // parse out the matcher (i.e. in `$id:ident` this would parse the `:` and `ident`).
193 TokenTree::MetaVar(start_sp, ident) if expect_matchers => {
194 let span = match trees.next() {
195 Some(tokenstream::TokenTree::Token(span, token::Colon)) => match trees.next() {
196 Some(tokenstream::TokenTree::Token(end_sp, ref tok)) => match tok.ident() {
198 let span = end_sp.with_lo(start_sp.lo());
199 result.push(TokenTree::MetaVarDecl(span, ident, kind));
204 tree => tree.as_ref()
205 .map(tokenstream::TokenTree::span)
208 tree => tree.as_ref()
209 .map(tokenstream::TokenTree::span)
210 .unwrap_or(start_sp),
212 sess.missing_fragment_specifiers.borrow_mut().insert(span);
213 result.push(TokenTree::MetaVarDecl(
216 keywords::Invalid.ident(),
220 // Not a metavar or no matchers allowed, so just return the tree
221 _ => result.push(tree),
227 /// Takes a `tokenstream::TokenTree` and returns a `self::TokenTree`. Specifically, this takes a
228 /// generic `TokenTree`, such as is used in the rest of the compiler, and returns a `TokenTree`
229 /// for use in parsing a macro.
231 /// Converting the given tree may involve reading more tokens.
235 /// - `tree`: the tree we wish to convert.
236 /// - `trees`: an iterator over trees. We may need to read more tokens from it in order to finish
237 /// converting `tree`
238 /// - `expect_matchers`: same as for `parse` (see above).
239 /// - `sess`: the parsing session. Any errors will be emitted to this session.
241 tree: tokenstream::TokenTree,
243 expect_matchers: bool,
247 I: Iterator<Item = tokenstream::TokenTree>,
249 // Depending on what `tree` is, we could be parsing different parts of a macro
251 // `tree` is a `$` token. Look at the next token in `trees`
252 tokenstream::TokenTree::Token(span, token::Dollar) => match trees.next() {
253 // `tree` is followed by a delimited set of token trees. This indicates the beginning
254 // of a repetition sequence in the macro (e.g. `$(pat)*`).
255 Some(tokenstream::TokenTree::Delimited(span, delimited)) => {
256 // Must have `(` not `{` or `[`
257 if delimited.delim != token::Paren {
258 let tok = pprust::token_to_string(&token::OpenDelim(delimited.delim));
259 let msg = format!("expected `(`, found `{}`", tok);
260 sess.span_diagnostic.span_err(span, &msg);
262 // Parse the contents of the sequence itself
263 let sequence = parse(delimited.tts.into(), expect_matchers, sess);
264 // Get the Kleene operator and optional separator
265 let (separator, op) = parse_sep_and_kleene_op(trees, span, sess);
266 // Count the number of captured "names" (i.e. named metavars)
267 let name_captures = macro_parser::count_names(&sequence);
270 Rc::new(SequenceRepetition {
274 num_captures: name_captures,
279 // `tree` is followed by an `ident`. This could be `$meta_var` or the `$crate` special
280 // metavariable that names the crate of the invokation.
281 Some(tokenstream::TokenTree::Token(ident_span, ref token)) if token.is_ident() => {
282 let ident = token.ident().unwrap();
283 let span = ident_span.with_lo(span.lo());
284 if ident.name == keywords::Crate.name() {
285 let ident = ast::Ident {
286 name: keywords::DollarCrate.name(),
289 TokenTree::Token(span, token::Ident(ident))
291 TokenTree::MetaVar(span, ident)
295 // `tree` is followed by a random token. This is an error.
296 Some(tokenstream::TokenTree::Token(span, tok)) => {
298 "expected identifier, found `{}`",
299 pprust::token_to_string(&tok)
301 sess.span_diagnostic.span_err(span, &msg);
302 TokenTree::MetaVar(span, keywords::Invalid.ident())
305 // There are no more tokens. Just return the `$` we already have.
306 None => TokenTree::Token(span, token::Dollar),
309 // `tree` is an arbitrary token. Keep it.
310 tokenstream::TokenTree::Token(span, tok) => TokenTree::Token(span, tok),
312 // `tree` is the beginning of a delimited set of tokens (e.g. `(` or `{`). We need to
313 // descend into the delimited set and further parse it.
314 tokenstream::TokenTree::Delimited(span, delimited) => TokenTree::Delimited(
317 delim: delimited.delim,
318 tts: parse(delimited.tts.into(), expect_matchers, sess),
324 /// Attempt to parse a single Kleene star, possibly with a separator.
326 /// For example, in a pattern such as `$(a),*`, `a` is the pattern to be repeated, `,` is the
327 /// separator, and `*` is the Kleene operator. This function is specifically concerned with parsing
328 /// the last two tokens of such a pattern: namely, the optional separator and the Kleene operator
329 /// itself. Note that here we are parsing the _macro_ itself, rather than trying to match some
330 /// stream of tokens in an invocation of a macro.
332 /// This function will take some input iterator `input` corresponding to `span` and a parsing
333 /// session `sess`. If the next one (or possibly two) tokens in `input` correspond to a Kleene
334 /// operator and separator, then a tuple with `(separator, KleeneOp)` is returned. Otherwise, an
335 /// error with the appropriate span is emitted to `sess` and a dummy value is returned.
336 fn parse_sep_and_kleene_op<I>(
340 ) -> (Option<token::Token>, KleeneOp)
342 I: Iterator<Item = tokenstream::TokenTree>,
344 fn kleene_op(token: &token::Token) -> Option<KleeneOp> {
346 token::BinOp(token::Star) => Some(KleeneOp::ZeroOrMore),
347 token::BinOp(token::Plus) => Some(KleeneOp::OneOrMore),
352 // We attempt to look at the next two token trees in `input`. I will call the first #1 and the
353 // second #2. If #1 and #2 don't match a valid KleeneOp with/without separator, that is an
354 // error, and we should emit an error on the most specific span possible.
355 let span = match input.next() {
357 Some(tokenstream::TokenTree::Token(span, tok)) => match kleene_op(&tok) {
358 // #1 is a KleeneOp with no separator
359 Some(op) => return (None, op),
361 // #1 is not a KleeneOp, but may be a separator... need to look at #2
362 None => match input.next() {
364 Some(tokenstream::TokenTree::Token(span, tok2)) => match kleene_op(&tok2) {
365 // #2 is a KleeneOp, so #1 must be a separator
366 Some(op) => return (Some(tok), op),
368 // #2 is not a KleeneOp... error
372 // #2 is not a token at all... error
373 tree => tree.as_ref()
374 .map(tokenstream::TokenTree::span)
379 // #1 is not a token at all... error
380 tree => tree.as_ref()
381 .map(tokenstream::TokenTree::span)
386 sess.span_diagnostic.span_err(span, "expected `*` or `+`");
387 (None, KleeneOp::ZeroOrMore)