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