]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/tt/quoted.rs
707fb65bcc52bfb363c18689714a81d449456a92
[rust.git] / src / libsyntax / ext / tt / quoted.rs
1 use crate::ast::NodeId;
2 use crate::early_buffered_lints::BufferedEarlyLintId;
3 use crate::ext::tt::macro_parser;
4 use crate::feature_gate::Features;
5 use crate::parse::token::{self, Token, TokenKind};
6 use crate::parse::ParseSess;
7 use crate::print::pprust;
8 use crate::tokenstream::{self, DelimSpan};
9 use crate::ast;
10 use crate::symbol::kw;
11
12 use syntax_pos::{edition::Edition, BytePos, Span};
13
14 use rustc_data_structures::sync::Lrc;
15 use std::iter::Peekable;
16
17 /// Contains the sub-token-trees of a "delimited" token tree, such as the contents of `(`. Note
18 /// that the delimiter itself might be `NoDelim`.
19 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
20 pub struct Delimited {
21     pub delim: token::DelimToken,
22     pub tts: Vec<TokenTree>,
23 }
24
25 impl Delimited {
26     /// Returns a `self::TokenTree` with a `Span` corresponding to the opening delimiter.
27     pub fn open_tt(&self, span: Span) -> TokenTree {
28         let open_span = if span.is_dummy() {
29             span
30         } else {
31             span.with_lo(span.lo() + BytePos(self.delim.len() as u32))
32         };
33         TokenTree::token(token::OpenDelim(self.delim), open_span)
34     }
35
36     /// Returns a `self::TokenTree` with a `Span` corresponding to the closing delimiter.
37     pub fn close_tt(&self, span: Span) -> TokenTree {
38         let close_span = if span.is_dummy() {
39             span
40         } else {
41             span.with_lo(span.hi() - BytePos(self.delim.len() as u32))
42         };
43         TokenTree::token(token::CloseDelim(self.delim), close_span)
44     }
45 }
46
47 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
48 pub struct SequenceRepetition {
49     /// The sequence of token trees
50     pub tts: Vec<TokenTree>,
51     /// The optional separator
52     pub separator: Option<Token>,
53     /// Whether the sequence can be repeated zero (*), or one or more times (+)
54     pub op: KleeneOp,
55     /// The number of `Match`s that appear in the sequence (and subsequences)
56     pub num_captures: usize,
57 }
58
59 /// A Kleene-style [repetition operator](http://en.wikipedia.org/wiki/Kleene_star)
60 /// for token sequences.
61 #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
62 pub enum KleeneOp {
63     /// Kleene star (`*`) for zero or more repetitions
64     ZeroOrMore,
65     /// Kleene plus (`+`) for one or more repetitions
66     OneOrMore,
67     /// Kleene optional (`?`) for zero or one reptitions
68     ZeroOrOne,
69 }
70
71 /// Similar to `tokenstream::TokenTree`, except that `$i`, `$i:ident`, and `$(...)`
72 /// are "first-class" token trees. Useful for parsing macros.
73 #[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable)]
74 pub enum TokenTree {
75     Token(Token),
76     Delimited(DelimSpan, Lrc<Delimited>),
77     /// A kleene-style repetition sequence
78     Sequence(DelimSpan, Lrc<SequenceRepetition>),
79     /// e.g., `$var`
80     MetaVar(Span, ast::Ident),
81     /// e.g., `$var:expr`. This is only used in the left hand side of MBE macros.
82     MetaVarDecl(
83         Span,
84         ast::Ident, /* name to bind */
85         ast::Ident, /* kind of nonterminal */
86     ),
87 }
88
89 impl TokenTree {
90     /// Return the number of tokens in the tree.
91     pub fn len(&self) -> usize {
92         match *self {
93             TokenTree::Delimited(_, ref delimed) => match delimed.delim {
94                 token::NoDelim => delimed.tts.len(),
95                 _ => delimed.tts.len() + 2,
96             },
97             TokenTree::Sequence(_, ref seq) => seq.tts.len(),
98             _ => 0,
99         }
100     }
101
102     /// Returns `true` if the given token tree contains no other tokens. This is vacuously true for
103     /// single tokens or metavar/decls, but may be false for delimited trees or sequences.
104     pub fn is_empty(&self) -> bool {
105         match *self {
106             TokenTree::Delimited(_, ref delimed) => match delimed.delim {
107                 token::NoDelim => delimed.tts.is_empty(),
108                 _ => false,
109             },
110             TokenTree::Sequence(_, ref seq) => seq.tts.is_empty(),
111             _ => true,
112         }
113     }
114
115     /// Gets the `index`-th sub-token-tree. This only makes sense for delimited trees and sequences.
116     pub fn get_tt(&self, index: usize) -> TokenTree {
117         match (self, index) {
118             (&TokenTree::Delimited(_, ref delimed), _) if delimed.delim == token::NoDelim => {
119                 delimed.tts[index].clone()
120             }
121             (&TokenTree::Delimited(span, ref delimed), _) => {
122                 if index == 0 {
123                     return delimed.open_tt(span.open);
124                 }
125                 if index == delimed.tts.len() + 1 {
126                     return delimed.close_tt(span.close);
127                 }
128                 delimed.tts[index - 1].clone()
129             }
130             (&TokenTree::Sequence(_, ref seq), _) => seq.tts[index].clone(),
131             _ => panic!("Cannot expand a token tree"),
132         }
133     }
134
135     /// Retrieves the `TokenTree`'s span.
136     pub fn span(&self) -> Span {
137         match *self {
138             TokenTree::Token(Token { span, .. })
139             | TokenTree::MetaVar(span, _)
140             | TokenTree::MetaVarDecl(span, _, _) => span,
141             TokenTree::Delimited(span, _)
142             | TokenTree::Sequence(span, _) => span.entire(),
143         }
144     }
145
146     crate fn token(kind: TokenKind, span: Span) -> TokenTree {
147         TokenTree::Token(Token::new(kind, span))
148     }
149 }
150
151 /// Takes a `tokenstream::TokenStream` and returns a `Vec<self::TokenTree>`. Specifically, this
152 /// takes a generic `TokenStream`, such as is used in the rest of the compiler, and returns a
153 /// collection of `TokenTree` for use in parsing a macro.
154 ///
155 /// # Parameters
156 ///
157 /// - `input`: a token stream to read from, the contents of which we are parsing.
158 /// - `expect_matchers`: `parse` can be used to parse either the "patterns" or the "body" of a
159 ///   macro. Both take roughly the same form _except_ that in a pattern, metavars are declared with
160 ///   their "matcher" type. For example `$var:expr` or `$id:ident`. In this example, `expr` and
161 ///   `ident` are "matchers". They are not present in the body of a macro rule -- just in the
162 ///   pattern, so we pass a parameter to indicate whether to expect them or not.
163 /// - `sess`: the parsing session. Any errors will be emitted to this session.
164 /// - `features`, `attrs`: language feature flags and attributes so that we know whether to use
165 ///   unstable features or not.
166 /// - `edition`: which edition are we in.
167 /// - `macro_node_id`: the NodeId of the macro we are parsing.
168 ///
169 /// # Returns
170 ///
171 /// A collection of `self::TokenTree`. There may also be some errors emitted to `sess`.
172 pub fn parse(
173     input: tokenstream::TokenStream,
174     expect_matchers: bool,
175     sess: &ParseSess,
176     features: &Features,
177     attrs: &[ast::Attribute],
178     edition: Edition,
179     macro_node_id: NodeId,
180 ) -> Vec<TokenTree> {
181     // Will contain the final collection of `self::TokenTree`
182     let mut result = Vec::new();
183
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().peekable();
187     while let Some(tree) = trees.next() {
188         // Given the parsed tree, if there is a metavar and we are expecting matchers, actually
189         // parse out the matcher (i.e., in `$id:ident` this would parse the `:` and `ident`).
190         let tree = parse_tree(
191             tree,
192             &mut trees,
193             expect_matchers,
194             sess,
195             features,
196             attrs,
197             edition,
198             macro_node_id,
199         );
200         match tree {
201             TokenTree::MetaVar(start_sp, ident) if expect_matchers => {
202                 let span = match trees.next() {
203                     Some(tokenstream::TokenTree::Token(Token { kind: token::Colon, span })) =>
204                         match trees.next() {
205                             Some(tokenstream::TokenTree::Token(token)) => match token.ident() {
206                                 Some((kind, _)) => {
207                                     let span = token.span.with_lo(start_sp.lo());
208                                     result.push(TokenTree::MetaVarDecl(span, ident, kind));
209                                     continue;
210                                 }
211                                 _ => token.span,
212                             },
213                             tree => tree
214                                 .as_ref()
215                                 .map(tokenstream::TokenTree::span)
216                                 .unwrap_or(span),
217                         },
218                     tree => tree
219                         .as_ref()
220                         .map(tokenstream::TokenTree::span)
221                         .unwrap_or(start_sp),
222                 };
223                 sess.missing_fragment_specifiers.borrow_mut().insert(span);
224                 result.push(TokenTree::MetaVarDecl(
225                     span,
226                     ident,
227                     ast::Ident::invalid(),
228                 ));
229             }
230
231             // Not a metavar or no matchers allowed, so just return the tree
232             _ => result.push(tree),
233         }
234     }
235     result
236 }
237
238 /// Takes a `tokenstream::TokenTree` and returns a `self::TokenTree`. Specifically, this takes a
239 /// generic `TokenTree`, such as is used in the rest of the compiler, and returns a `TokenTree`
240 /// for use in parsing a macro.
241 ///
242 /// Converting the given tree may involve reading more tokens.
243 ///
244 /// # Parameters
245 ///
246 /// - `tree`: the tree we wish to convert.
247 /// - `trees`: an iterator over trees. We may need to read more tokens from it in order to finish
248 ///   converting `tree`
249 /// - `expect_matchers`: same as for `parse` (see above).
250 /// - `sess`: the parsing session. Any errors will be emitted to this session.
251 /// - `features`, `attrs`: language feature flags and attributes so that we know whether to use
252 ///   unstable features or not.
253 fn parse_tree<I>(
254     tree: tokenstream::TokenTree,
255     trees: &mut Peekable<I>,
256     expect_matchers: bool,
257     sess: &ParseSess,
258     features: &Features,
259     attrs: &[ast::Attribute],
260     edition: Edition,
261     macro_node_id: NodeId,
262 ) -> TokenTree
263 where
264     I: Iterator<Item = tokenstream::TokenTree>,
265 {
266     // Depending on what `tree` is, we could be parsing different parts of a macro
267     match tree {
268         // `tree` is a `$` token. Look at the next token in `trees`
269         tokenstream::TokenTree::Token(Token { kind: token::Dollar, span }) => match trees.next() {
270             // `tree` is followed by a delimited set of token trees. This indicates the beginning
271             // of a repetition sequence in the macro (e.g. `$(pat)*`).
272             Some(tokenstream::TokenTree::Delimited(span, delim, tts)) => {
273                 // Must have `(` not `{` or `[`
274                 if delim != token::Paren {
275                     let tok = pprust::token_kind_to_string(&token::OpenDelim(delim));
276                     let msg = format!("expected `(`, found `{}`", tok);
277                     sess.span_diagnostic.span_err(span.entire(), &msg);
278                 }
279                 // Parse the contents of the sequence itself
280                 let sequence = parse(
281                     tts.into(),
282                     expect_matchers,
283                     sess,
284                     features,
285                     attrs,
286                     edition,
287                     macro_node_id,
288                 );
289                 // Get the Kleene operator and optional separator
290                 let (separator, op) =
291                     parse_sep_and_kleene_op(
292                         trees,
293                         span.entire(),
294                         sess,
295                         features,
296                         attrs,
297                         edition,
298                         macro_node_id,
299                     );
300                 // Count the number of captured "names" (i.e., named metavars)
301                 let name_captures = macro_parser::count_names(&sequence);
302                 TokenTree::Sequence(
303                     span,
304                     Lrc::new(SequenceRepetition {
305                         tts: sequence,
306                         separator,
307                         op,
308                         num_captures: name_captures,
309                     }),
310                 )
311             }
312
313             // `tree` is followed by an `ident`. This could be `$meta_var` or the `$crate` special
314             // metavariable that names the crate of the invocation.
315             Some(tokenstream::TokenTree::Token(token)) if token.is_ident() => {
316                 let (ident, is_raw) = token.ident().unwrap();
317                 let span = ident.span.with_lo(span.lo());
318                 if ident.name == kw::Crate && !is_raw {
319                     TokenTree::token(token::Ident(kw::DollarCrate, is_raw), span)
320                 } else {
321                     TokenTree::MetaVar(span, ident)
322                 }
323             }
324
325             // `tree` is followed by a random token. This is an error.
326             Some(tokenstream::TokenTree::Token(token)) => {
327                 let msg = format!(
328                     "expected identifier, found `{}`",
329                     pprust::token_to_string(&token),
330                 );
331                 sess.span_diagnostic.span_err(token.span, &msg);
332                 TokenTree::MetaVar(token.span, ast::Ident::invalid())
333             }
334
335             // There are no more tokens. Just return the `$` we already have.
336             None => TokenTree::token(token::Dollar, span),
337         },
338
339         // `tree` is an arbitrary token. Keep it.
340         tokenstream::TokenTree::Token(token) => TokenTree::Token(token),
341
342         // `tree` is the beginning of a delimited set of tokens (e.g., `(` or `{`). We need to
343         // descend into the delimited set and further parse it.
344         tokenstream::TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited(
345             span,
346             Lrc::new(Delimited {
347                 delim: delim,
348                 tts: parse(
349                     tts.into(),
350                     expect_matchers,
351                     sess,
352                     features,
353                     attrs,
354                     edition,
355                     macro_node_id,
356                 ),
357             }),
358         ),
359     }
360 }
361
362 /// Takes a token and returns `Some(KleeneOp)` if the token is `+` `*` or `?`. Otherwise, return
363 /// `None`.
364 fn kleene_op(token: &Token) -> Option<KleeneOp> {
365     match token.kind {
366         token::BinOp(token::Star) => Some(KleeneOp::ZeroOrMore),
367         token::BinOp(token::Plus) => Some(KleeneOp::OneOrMore),
368         token::Question => Some(KleeneOp::ZeroOrOne),
369         _ => None,
370     }
371 }
372
373 /// Parse the next token tree of the input looking for a KleeneOp. Returns
374 ///
375 /// - Ok(Ok((op, span))) if the next token tree is a KleeneOp
376 /// - Ok(Err(tok, span)) if the next token tree is a token but not a KleeneOp
377 /// - Err(span) if the next token tree is not a token
378 fn parse_kleene_op<I>(input: &mut I, span: Span) -> Result<Result<(KleeneOp, Span), Token>, Span>
379 where
380     I: Iterator<Item = tokenstream::TokenTree>,
381 {
382     match input.next() {
383         Some(tokenstream::TokenTree::Token(token)) => match kleene_op(&token) {
384             Some(op) => Ok(Ok((op, token.span))),
385             None => Ok(Err(token)),
386         },
387         tree => Err(tree
388             .as_ref()
389             .map(tokenstream::TokenTree::span)
390             .unwrap_or(span)),
391     }
392 }
393
394 /// Attempt to parse a single Kleene star, possibly with a separator.
395 ///
396 /// For example, in a pattern such as `$(a),*`, `a` is the pattern to be repeated, `,` is the
397 /// separator, and `*` is the Kleene operator. This function is specifically concerned with parsing
398 /// the last two tokens of such a pattern: namely, the optional separator and the Kleene operator
399 /// itself. Note that here we are parsing the _macro_ itself, rather than trying to match some
400 /// stream of tokens in an invocation of a macro.
401 ///
402 /// This function will take some input iterator `input` corresponding to `span` and a parsing
403 /// session `sess`. If the next one (or possibly two) tokens in `input` correspond to a Kleene
404 /// operator and separator, then a tuple with `(separator, KleeneOp)` is returned. Otherwise, an
405 /// error with the appropriate span is emitted to `sess` and a dummy value is returned.
406 ///
407 /// N.B., in the 2015 edition, `*` and `+` are the only Kleene operators, and `?` is a separator.
408 /// In the 2018 edition however, `?` is a Kleene operator, and not a separator.
409 fn parse_sep_and_kleene_op<I>(
410     input: &mut Peekable<I>,
411     span: Span,
412     sess: &ParseSess,
413     features: &Features,
414     attrs: &[ast::Attribute],
415     edition: Edition,
416     macro_node_id: NodeId,
417 ) -> (Option<Token>, KleeneOp)
418 where
419     I: Iterator<Item = tokenstream::TokenTree>,
420 {
421     match edition {
422         Edition::Edition2015 => parse_sep_and_kleene_op_2015(
423             input,
424             span,
425             sess,
426             features,
427             attrs,
428             macro_node_id,
429         ),
430         Edition::Edition2018 => parse_sep_and_kleene_op_2018(input, span, sess, features, attrs),
431     }
432 }
433
434 // `?` is a separator (with a migration warning) and never a KleeneOp.
435 fn parse_sep_and_kleene_op_2015<I>(
436     input: &mut Peekable<I>,
437     span: Span,
438     sess: &ParseSess,
439     _features: &Features,
440     _attrs: &[ast::Attribute],
441     macro_node_id: NodeId,
442 ) -> (Option<Token>, KleeneOp)
443 where
444     I: Iterator<Item = tokenstream::TokenTree>,
445 {
446     // We basically look at two token trees here, denoted as #1 and #2 below
447     let span = match parse_kleene_op(input, span) {
448         // #1 is a `+` or `*` KleeneOp
449         //
450         // `?` is ambiguous: it could be a separator (warning) or a Kleene::ZeroOrOne (error), so
451         // we need to look ahead one more token to be sure.
452         Ok(Ok((op, _))) if op != KleeneOp::ZeroOrOne => return (None, op),
453
454         // #1 is `?` token, but it could be a Kleene::ZeroOrOne (error in 2015) without a separator
455         // or it could be a `?` separator followed by any Kleene operator. We need to look ahead 1
456         // token to find out which.
457         Ok(Ok((op, op1_span))) => {
458             assert_eq!(op, KleeneOp::ZeroOrOne);
459
460             // Lookahead at #2. If it is a KleenOp, then #1 is a separator.
461             let is_1_sep = if let Some(tokenstream::TokenTree::Token(tok2)) = input.peek() {
462                 kleene_op(tok2).is_some()
463             } else {
464                 false
465             };
466
467             if is_1_sep {
468                 // #1 is a separator and #2 should be a KleepeOp.
469                 // (N.B. We need to advance the input iterator.)
470                 match parse_kleene_op(input, span) {
471                     // #2 is `?`, which is not allowed as a Kleene op in 2015 edition,
472                     // but is allowed in the 2018 edition.
473                     Ok(Ok((op, op2_span))) if op == KleeneOp::ZeroOrOne => {
474                         sess.span_diagnostic
475                             .struct_span_err(op2_span, "expected `*` or `+`")
476                             .note("`?` is not a macro repetition operator in the 2015 edition, \
477                                  but is accepted in the 2018 edition")
478                             .emit();
479
480                         // Return a dummy
481                         return (None, KleeneOp::ZeroOrMore);
482                     }
483
484                     // #2 is a Kleene op, which is the only valid option
485                     Ok(Ok((op, _))) => {
486                         // Warn that `?` as a separator will be deprecated
487                         sess.buffer_lint(
488                             BufferedEarlyLintId::QuestionMarkMacroSep,
489                             op1_span,
490                             macro_node_id,
491                             "using `?` as a separator is deprecated and will be \
492                              a hard error in an upcoming edition",
493                         );
494
495                         return (Some(Token::new(token::Question, op1_span)), op);
496                     }
497
498                     // #2 is a random token (this is an error) :(
499                     Ok(Err(_)) => op1_span,
500
501                     // #2 is not even a token at all :(
502                     Err(_) => op1_span,
503                 }
504             } else {
505                 // `?` is not allowed as a Kleene op in 2015,
506                 // but is allowed in the 2018 edition
507                 sess.span_diagnostic
508                     .struct_span_err(op1_span, "expected `*` or `+`")
509                     .note("`?` is not a macro repetition operator in the 2015 edition, \
510                          but is accepted in the 2018 edition")
511                     .emit();
512
513                 // Return a dummy
514                 return (None, KleeneOp::ZeroOrMore);
515             }
516         }
517
518         // #1 is a separator followed by #2, a KleeneOp
519         Ok(Err(token)) => match parse_kleene_op(input, token.span) {
520             // #2 is a `?`, which is not allowed as a Kleene op in 2015 edition,
521             // but is allowed in the 2018 edition
522             Ok(Ok((op, op2_span))) if op == KleeneOp::ZeroOrOne => {
523                 sess.span_diagnostic
524                     .struct_span_err(op2_span, "expected `*` or `+`")
525                     .note("`?` is not a macro repetition operator in the 2015 edition, \
526                         but is accepted in the 2018 edition")
527                     .emit();
528
529                 // Return a dummy
530                 return (None, KleeneOp::ZeroOrMore);
531             }
532
533             // #2 is a KleeneOp :D
534             Ok(Ok((op, _))) => return (Some(token), op),
535
536             // #2 is a random token :(
537             Ok(Err(token)) => token.span,
538
539             // #2 is not a token at all :(
540             Err(span) => span,
541         },
542
543         // #1 is not a token
544         Err(span) => span,
545     };
546
547     sess.span_diagnostic.span_err(span, "expected `*` or `+`");
548
549     // Return a dummy
550     (None, KleeneOp::ZeroOrMore)
551 }
552
553 // `?` is a Kleene op, not a separator
554 fn parse_sep_and_kleene_op_2018<I>(
555     input: &mut Peekable<I>,
556     span: Span,
557     sess: &ParseSess,
558     _features: &Features,
559     _attrs: &[ast::Attribute],
560 ) -> (Option<Token>, KleeneOp)
561 where
562     I: Iterator<Item = tokenstream::TokenTree>,
563 {
564     // We basically look at two token trees here, denoted as #1 and #2 below
565     let span = match parse_kleene_op(input, span) {
566         // #1 is a `?` (needs feature gate)
567         Ok(Ok((op, _op1_span))) if op == KleeneOp::ZeroOrOne => {
568             return (None, op);
569         }
570
571         // #1 is a `+` or `*` KleeneOp
572         Ok(Ok((op, _))) => return (None, op),
573
574         // #1 is a separator followed by #2, a KleeneOp
575         Ok(Err(token)) => match parse_kleene_op(input, token.span) {
576             // #2 is the `?` Kleene op, which does not take a separator (error)
577             Ok(Ok((op, _op2_span))) if op == KleeneOp::ZeroOrOne => {
578                 // Error!
579                 sess.span_diagnostic.span_err(
580                     token.span,
581                     "the `?` macro repetition operator does not take a separator",
582                 );
583
584                 // Return a dummy
585                 return (None, KleeneOp::ZeroOrMore);
586             }
587
588             // #2 is a KleeneOp :D
589             Ok(Ok((op, _))) => return (Some(token), op),
590
591             // #2 is a random token :(
592             Ok(Err(token)) => token.span,
593
594             // #2 is not a token at all :(
595             Err(span) => span,
596         },
597
598         // #1 is not a token
599         Err(span) => span,
600     };
601
602     // If we ever get to this point, we have experienced an "unexpected token" error
603     sess.span_diagnostic
604         .span_err(span, "expected one of: `*`, `+`, or `?`");
605
606     // Return a dummy
607     (None, KleeneOp::ZeroOrMore)
608 }