]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/tt/quoted.rs
Support ? Kleene operator in 2015.
[rust.git] / src / libsyntax / ext / tt / quoted.rs
1 use crate::ast::NodeId;
2 use crate::ext::tt::macro_parser;
3 use crate::feature_gate::Features;
4 use crate::parse::token::{self, Token, TokenKind};
5 use crate::parse::ParseSess;
6 use crate::print::pprust;
7 use crate::tokenstream::{self, DelimSpan};
8 use crate::ast;
9 use crate::symbol::kw;
10
11 use syntax_pos::{edition::Edition, BytePos, Span};
12
13 use rustc_data_structures::sync::Lrc;
14 use std::iter::Peekable;
15
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>,
22 }
23
24 impl Delimited {
25     /// Returns a `self::TokenTree` with a `Span` corresponding to the opening delimiter.
26     pub fn open_tt(&self, span: Span) -> TokenTree {
27         let open_span = if span.is_dummy() {
28             span
29         } else {
30             span.with_lo(span.lo() + BytePos(self.delim.len() as u32))
31         };
32         TokenTree::token(token::OpenDelim(self.delim), open_span)
33     }
34
35     /// Returns a `self::TokenTree` with a `Span` corresponding to the closing delimiter.
36     pub fn close_tt(&self, span: Span) -> TokenTree {
37         let close_span = if span.is_dummy() {
38             span
39         } else {
40             span.with_lo(span.hi() - BytePos(self.delim.len() as u32))
41         };
42         TokenTree::token(token::CloseDelim(self.delim), close_span)
43     }
44 }
45
46 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
47 pub struct SequenceRepetition {
48     /// The sequence of token trees
49     pub tts: Vec<TokenTree>,
50     /// The optional separator
51     pub separator: Option<Token>,
52     /// Whether the sequence can be repeated zero (*), or one or more times (+)
53     pub op: KleeneOp,
54     /// The number of `Match`s that appear in the sequence (and subsequences)
55     pub num_captures: usize,
56 }
57
58 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
59 /// for token sequences.
60 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
61 pub enum KleeneOp {
62     /// Kleene star (`*`) for zero or more repetitions
63     ZeroOrMore,
64     /// Kleene plus (`+`) for one or more repetitions
65     OneOrMore,
66     /// Kleene optional (`?`) for zero or one reptitions
67     ZeroOrOne,
68 }
69
70 /// Similar to `tokenstream::TokenTree`, except that `$i`, `$i:ident`, and `$(...)`
71 /// are "first-class" token trees. Useful for parsing macros.
72 #[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable)]
73 pub enum TokenTree {
74     Token(Token),
75     Delimited(DelimSpan, Lrc<Delimited>),
76     /// A kleene-style repetition sequence
77     Sequence(DelimSpan, Lrc<SequenceRepetition>),
78     /// e.g., `$var`
79     MetaVar(Span, ast::Ident),
80     /// e.g., `$var:expr`. This is only used in the left hand side of MBE macros.
81     MetaVarDecl(
82         Span,
83         ast::Ident, /* name to bind */
84         ast::Ident, /* kind of nonterminal */
85     ),
86 }
87
88 impl TokenTree {
89     /// Return the number of tokens in the tree.
90     pub fn len(&self) -> usize {
91         match *self {
92             TokenTree::Delimited(_, ref delimed) => match delimed.delim {
93                 token::NoDelim => delimed.tts.len(),
94                 _ => delimed.tts.len() + 2,
95             },
96             TokenTree::Sequence(_, ref seq) => seq.tts.len(),
97             _ => 0,
98         }
99     }
100
101     /// Returns `true` if the given token tree contains no other tokens. This is vacuously true for
102     /// single tokens or metavar/decls, but may be false for delimited trees or sequences.
103     pub fn is_empty(&self) -> bool {
104         match *self {
105             TokenTree::Delimited(_, ref delimed) => match delimed.delim {
106                 token::NoDelim => delimed.tts.is_empty(),
107                 _ => false,
108             },
109             TokenTree::Sequence(_, ref seq) => seq.tts.is_empty(),
110             _ => true,
111         }
112     }
113
114     /// Gets the `index`-th sub-token-tree. This only makes sense for delimited trees and sequences.
115     pub fn get_tt(&self, index: usize) -> TokenTree {
116         match (self, index) {
117             (&TokenTree::Delimited(_, ref delimed), _) if delimed.delim == token::NoDelim => {
118                 delimed.tts[index].clone()
119             }
120             (&TokenTree::Delimited(span, ref delimed), _) => {
121                 if index == 0 {
122                     return delimed.open_tt(span.open);
123                 }
124                 if index == delimed.tts.len() + 1 {
125                     return delimed.close_tt(span.close);
126                 }
127                 delimed.tts[index - 1].clone()
128             }
129             (&TokenTree::Sequence(_, ref seq), _) => seq.tts[index].clone(),
130             _ => panic!("Cannot expand a token tree"),
131         }
132     }
133
134     /// Retrieves the `TokenTree`'s span.
135     pub fn span(&self) -> Span {
136         match *self {
137             TokenTree::Token(Token { span, .. })
138             | TokenTree::MetaVar(span, _)
139             | TokenTree::MetaVarDecl(span, _, _) => span,
140             TokenTree::Delimited(span, _)
141             | TokenTree::Sequence(span, _) => span.entire(),
142         }
143     }
144
145     crate fn token(kind: TokenKind, span: Span) -> TokenTree {
146         TokenTree::Token(Token::new(kind, span))
147     }
148 }
149
150 /// Takes a `tokenstream::TokenStream` and returns a `Vec<self::TokenTree>`. Specifically, this
151 /// takes a generic `TokenStream`, such as is used in the rest of the compiler, and returns a
152 /// collection of `TokenTree` for use in parsing a macro.
153 ///
154 /// # Parameters
155 ///
156 /// - `input`: a token stream to read from, the contents of which we are parsing.
157 /// - `expect_matchers`: `parse` can be used to parse either the "patterns" or the "body" of a
158 ///   macro. Both take roughly the same form _except_ that in a pattern, metavars are declared with
159 ///   their "matcher" type. For example `$var:expr` or `$id:ident`. In this example, `expr` and
160 ///   `ident` are "matchers". They are not present in the body of a macro rule -- just in the
161 ///   pattern, so we pass a parameter to indicate whether to expect them or not.
162 /// - `sess`: the parsing session. Any errors will be emitted to this session.
163 /// - `features`, `attrs`: language feature flags and attributes so that we know whether to use
164 ///   unstable features or not.
165 /// - `edition`: which edition are we in.
166 /// - `macro_node_id`: the NodeId of the macro we are parsing.
167 ///
168 /// # Returns
169 ///
170 /// A collection of `self::TokenTree`. There may also be some errors emitted to `sess`.
171 pub fn parse(
172     input: tokenstream::TokenStream,
173     expect_matchers: bool,
174     sess: &ParseSess,
175     features: &Features,
176     attrs: &[ast::Attribute],
177     edition: Edition,
178     macro_node_id: NodeId,
179 ) -> Vec<TokenTree> {
180     // Will contain the final collection of `self::TokenTree`
181     let mut result = Vec::new();
182
183     // For each token tree in `input`, parse the token into a `self::TokenTree`, consuming
184     // additional trees if need be.
185     let mut trees = input.trees().peekable();
186     while let Some(tree) = trees.next() {
187         // Given the parsed tree, if there is a metavar and we are expecting matchers, actually
188         // parse out the matcher (i.e., in `$id:ident` this would parse the `:` and `ident`).
189         let tree = parse_tree(
190             tree,
191             &mut trees,
192             expect_matchers,
193             sess,
194             features,
195             attrs,
196             edition,
197             macro_node_id,
198         );
199         match tree {
200             TokenTree::MetaVar(start_sp, ident) if expect_matchers => {
201                 let span = match trees.next() {
202                     Some(tokenstream::TokenTree::Token(Token { kind: token::Colon, span })) =>
203                         match trees.next() {
204                             Some(tokenstream::TokenTree::Token(token)) => match token.ident() {
205                                 Some((kind, _)) => {
206                                     let span = token.span.with_lo(start_sp.lo());
207                                     result.push(TokenTree::MetaVarDecl(span, ident, kind));
208                                     continue;
209                                 }
210                                 _ => token.span,
211                             },
212                             tree => tree
213                                 .as_ref()
214                                 .map(tokenstream::TokenTree::span)
215                                 .unwrap_or(span),
216                         },
217                     tree => tree
218                         .as_ref()
219                         .map(tokenstream::TokenTree::span)
220                         .unwrap_or(start_sp),
221                 };
222                 sess.missing_fragment_specifiers.borrow_mut().insert(span);
223                 result.push(TokenTree::MetaVarDecl(
224                     span,
225                     ident,
226                     ast::Ident::invalid(),
227                 ));
228             }
229
230             // Not a metavar or no matchers allowed, so just return the tree
231             _ => result.push(tree),
232         }
233     }
234     result
235 }
236
237 /// Takes a `tokenstream::TokenTree` and returns a `self::TokenTree`. Specifically, this takes a
238 /// generic `TokenTree`, such as is used in the rest of the compiler, and returns a `TokenTree`
239 /// for use in parsing a macro.
240 ///
241 /// Converting the given tree may involve reading more tokens.
242 ///
243 /// # Parameters
244 ///
245 /// - `tree`: the tree we wish to convert.
246 /// - `trees`: an iterator over trees. We may need to read more tokens from it in order to finish
247 ///   converting `tree`
248 /// - `expect_matchers`: same as for `parse` (see above).
249 /// - `sess`: the parsing session. Any errors will be emitted to this session.
250 /// - `features`, `attrs`: language feature flags and attributes so that we know whether to use
251 ///   unstable features or not.
252 fn parse_tree<I>(
253     tree: tokenstream::TokenTree,
254     trees: &mut Peekable<I>,
255     expect_matchers: bool,
256     sess: &ParseSess,
257     features: &Features,
258     attrs: &[ast::Attribute],
259     edition: Edition,
260     macro_node_id: NodeId,
261 ) -> TokenTree
262 where
263     I: Iterator<Item = tokenstream::TokenTree>,
264 {
265     // Depending on what `tree` is, we could be parsing different parts of a macro
266     match tree {
267         // `tree` is a `$` token. Look at the next token in `trees`
268         tokenstream::TokenTree::Token(Token { kind: token::Dollar, span }) => match trees.next() {
269             // `tree` is followed by a delimited set of token trees. This indicates the beginning
270             // of a repetition sequence in the macro (e.g. `$(pat)*`).
271             Some(tokenstream::TokenTree::Delimited(span, delim, tts)) => {
272                 // Must have `(` not `{` or `[`
273                 if delim != token::Paren {
274                     let tok = pprust::token_kind_to_string(&token::OpenDelim(delim));
275                     let msg = format!("expected `(`, found `{}`", tok);
276                     sess.span_diagnostic.span_err(span.entire(), &msg);
277                 }
278                 // Parse the contents of the sequence itself
279                 let sequence = parse(
280                     tts.into(),
281                     expect_matchers,
282                     sess,
283                     features,
284                     attrs,
285                     edition,
286                     macro_node_id,
287                 );
288                 // Get the Kleene operator and optional separator
289                 let (separator, op) = parse_sep_and_kleene_op(trees, span.entire(), sess);
290                 // Count the number of captured "names" (i.e., named metavars)
291                 let name_captures = macro_parser::count_names(&sequence);
292                 TokenTree::Sequence(
293                     span,
294                     Lrc::new(SequenceRepetition {
295                         tts: sequence,
296                         separator,
297                         op,
298                         num_captures: name_captures,
299                     }),
300                 )
301             }
302
303             // `tree` is followed by an `ident`. This could be `$meta_var` or the `$crate` special
304             // metavariable that names the crate of the invocation.
305             Some(tokenstream::TokenTree::Token(token)) if token.is_ident() => {
306                 let (ident, is_raw) = token.ident().unwrap();
307                 let span = ident.span.with_lo(span.lo());
308                 if ident.name == kw::Crate && !is_raw {
309                     TokenTree::token(token::Ident(kw::DollarCrate, is_raw), span)
310                 } else {
311                     TokenTree::MetaVar(span, ident)
312                 }
313             }
314
315             // `tree` is followed by a random token. This is an error.
316             Some(tokenstream::TokenTree::Token(token)) => {
317                 let msg = format!(
318                     "expected identifier, found `{}`",
319                     pprust::token_to_string(&token),
320                 );
321                 sess.span_diagnostic.span_err(token.span, &msg);
322                 TokenTree::MetaVar(token.span, ast::Ident::invalid())
323             }
324
325             // There are no more tokens. Just return the `$` we already have.
326             None => TokenTree::token(token::Dollar, span),
327         },
328
329         // `tree` is an arbitrary token. Keep it.
330         tokenstream::TokenTree::Token(token) => TokenTree::Token(token),
331
332         // `tree` is the beginning of a delimited set of tokens (e.g., `(` or `{`). We need to
333         // descend into the delimited set and further parse it.
334         tokenstream::TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited(
335             span,
336             Lrc::new(Delimited {
337                 delim: delim,
338                 tts: parse(
339                     tts.into(),
340                     expect_matchers,
341                     sess,
342                     features,
343                     attrs,
344                     edition,
345                     macro_node_id,
346                 ),
347             }),
348         ),
349     }
350 }
351
352 /// Takes a token and returns `Some(KleeneOp)` if the token is `+` `*` or `?`. Otherwise, return
353 /// `None`.
354 fn kleene_op(token: &Token) -> Option<KleeneOp> {
355     match token.kind {
356         token::BinOp(token::Star) => Some(KleeneOp::ZeroOrMore),
357         token::BinOp(token::Plus) => Some(KleeneOp::OneOrMore),
358         token::Question => Some(KleeneOp::ZeroOrOne),
359         _ => None,
360     }
361 }
362
363 /// Parse the next token tree of the input looking for a KleeneOp. Returns
364 ///
365 /// - Ok(Ok((op, span))) if the next token tree is a KleeneOp
366 /// - Ok(Err(tok, span)) if the next token tree is a token but not a KleeneOp
367 /// - Err(span) if the next token tree is not a token
368 fn parse_kleene_op<I>(input: &mut I, span: Span) -> Result<Result<(KleeneOp, Span), Token>, Span>
369 where
370     I: Iterator<Item = tokenstream::TokenTree>,
371 {
372     match input.next() {
373         Some(tokenstream::TokenTree::Token(token)) => match kleene_op(&token) {
374             Some(op) => Ok(Ok((op, token.span))),
375             None => Ok(Err(token)),
376         },
377         tree => Err(tree
378             .as_ref()
379             .map(tokenstream::TokenTree::span)
380             .unwrap_or(span)),
381     }
382 }
383
384 /// Attempt to parse a single Kleene star, possibly with a separator.
385 ///
386 /// For example, in a pattern such as `$(a),*`, `a` is the pattern to be repeated, `,` is the
387 /// separator, and `*` is the Kleene operator. This function is specifically concerned with parsing
388 /// the last two tokens of such a pattern: namely, the optional separator and the Kleene operator
389 /// itself. Note that here we are parsing the _macro_ itself, rather than trying to match some
390 /// stream of tokens in an invocation of a macro.
391 ///
392 /// This function will take some input iterator `input` corresponding to `span` and a parsing
393 /// session `sess`. If the next one (or possibly two) tokens in `input` correspond to a Kleene
394 /// operator and separator, then a tuple with `(separator, KleeneOp)` is returned. Otherwise, an
395 /// error with the appropriate span is emitted to `sess` and a dummy value is returned.
396 fn parse_sep_and_kleene_op(
397     input: &mut Peekable<impl Iterator<Item = tokenstream::TokenTree>>,
398     span: Span,
399     sess: &ParseSess,
400 ) -> (Option<Token>, KleeneOp) {
401     // We basically look at two token trees here, denoted as #1 and #2 below
402     let span = match parse_kleene_op(input, span) {
403         // #1 is a `?` (needs feature gate)
404         Ok(Ok((op, _op1_span))) if op == KleeneOp::ZeroOrOne => {
405             return (None, op);
406         }
407
408         // #1 is a `+` or `*` KleeneOp
409         Ok(Ok((op, _))) => return (None, op),
410
411         // #1 is a separator followed by #2, a KleeneOp
412         Ok(Err(token)) => match parse_kleene_op(input, token.span) {
413             // #2 is the `?` Kleene op, which does not take a separator (error)
414             Ok(Ok((op, _op2_span))) if op == KleeneOp::ZeroOrOne => {
415                 // Error!
416                 sess.span_diagnostic.span_err(
417                     token.span,
418                     "the `?` macro repetition operator does not take a separator",
419                 );
420
421                 // Return a dummy
422                 return (None, KleeneOp::ZeroOrMore);
423             }
424
425             // #2 is a KleeneOp :D
426             Ok(Ok((op, _))) => return (Some(token), op),
427
428             // #2 is a random token :(
429             Ok(Err(token)) => token.span,
430
431             // #2 is not a token at all :(
432             Err(span) => span,
433         },
434
435         // #1 is not a token
436         Err(span) => span,
437     };
438
439     // If we ever get to this point, we have experienced an "unexpected token" error
440     sess.span_diagnostic
441         .span_err(span, "expected one of: `*`, `+`, or `?`");
442
443     // Return a dummy
444     (None, KleeneOp::ZeroOrMore)
445 }