]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/tt/macro_parser.rs
Various minor/cosmetic improvements to code
[rust.git] / src / libsyntax / ext / tt / macro_parser.rs
1 // Copyright 2012-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.
4 //
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.
10
11 //! This is an NFA-based parser, which calls out to the main rust parser for named nonterminals
12 //! (which it commits to fully when it hits one in a grammar). There's a set of current NFA threads
13 //! and a set of next ones. Instead of NTs, we have a special case for Kleene star. The big-O, in
14 //! pathological cases, is worse than traditional use of NFA or Earley parsing, but it's an easier
15 //! fit for Macro-by-Example-style rules.
16 //!
17 //! (In order to prevent the pathological case, we'd need to lazily construct the resulting
18 //! `NamedMatch`es at the very end. It'd be a pain, and require more memory to keep around old
19 //! items, but it would also save overhead)
20 //!
21 //! We don't say this parser uses the Earley algorithm, because it's unnecessarily inaccurate.
22 //! The macro parser restricts itself to the features of finite state automata. Earley parsers
23 //! can be described as an extension of NFAs with completion rules, prediction rules, and recursion.
24 //!
25 //! Quick intro to how the parser works:
26 //!
27 //! A 'position' is a dot in the middle of a matcher, usually represented as a
28 //! dot. For example `· a $( a )* a b` is a position, as is `a $( · a )* a b`.
29 //!
30 //! The parser walks through the input a character at a time, maintaining a list
31 //! of threads consistent with the current position in the input string: `cur_items`.
32 //!
33 //! As it processes them, it fills up `eof_items` with threads that would be valid if
34 //! the macro invocation is now over, `bb_items` with threads that are waiting on
35 //! a Rust nonterminal like `$e:expr`, and `next_items` with threads that are waiting
36 //! on a particular token. Most of the logic concerns moving the · through the
37 //! repetitions indicated by Kleene stars. The rules for moving the · without
38 //! consuming any input are called epsilon transitions. It only advances or calls
39 //! out to the real Rust parser when no `cur_items` threads remain.
40 //!
41 //! Example:
42 //!
43 //! ```text, ignore
44 //! Start parsing a a a a b against [· a $( a )* a b].
45 //!
46 //! Remaining input: a a a a b
47 //! next: [· a $( a )* a b]
48 //!
49 //! - - - Advance over an a. - - -
50 //!
51 //! Remaining input: a a a b
52 //! cur: [a · $( a )* a b]
53 //! Descend/Skip (first item).
54 //! next: [a $( · a )* a b]  [a $( a )* · a b].
55 //!
56 //! - - - Advance over an a. - - -
57 //!
58 //! Remaining input: a a b
59 //! cur: [a $( a · )* a b]  [a $( a )* a · b]
60 //! Follow epsilon transition: Finish/Repeat (first item)
61 //! next: [a $( a )* · a b]  [a $( · a )* a b]  [a $( a )* a · b]
62 //!
63 //! - - - Advance over an a. - - - (this looks exactly like the last step)
64 //!
65 //! Remaining input: a b
66 //! cur: [a $( a · )* a b]  [a $( a )* a · b]
67 //! Follow epsilon transition: Finish/Repeat (first item)
68 //! next: [a $( a )* · a b]  [a $( · a )* a b]  [a $( a )* a · b]
69 //!
70 //! - - - Advance over an a. - - - (this looks exactly like the last step)
71 //!
72 //! Remaining input: b
73 //! cur: [a $( a · )* a b]  [a $( a )* a · b]
74 //! Follow epsilon transition: Finish/Repeat (first item)
75 //! next: [a $( a )* · a b]  [a $( · a )* a b]  [a $( a )* a · b]
76 //!
77 //! - - - Advance over a b. - - -
78 //!
79 //! Remaining input: ''
80 //! eof: [a $( a )* a b ·]
81 //! ```
82
83 pub use self::NamedMatch::*;
84 pub use self::ParseResult::*;
85 use self::TokenTreeOrTokenTreeSlice::*;
86
87 use ast::Ident;
88 use syntax_pos::{self, Span};
89 use errors::FatalError;
90 use ext::tt::quoted::{self, TokenTree};
91 use parse::{Directory, ParseSess};
92 use parse::parser::{Parser, PathStyle};
93 use parse::token::{self, DocComment, Nonterminal, Token};
94 use print::pprust;
95 use smallvec::SmallVec;
96 use symbol::keywords;
97 use tokenstream::{DelimSpan, TokenStream};
98
99 use rustc_data_structures::fx::FxHashMap;
100 use std::collections::hash_map::Entry::{Occupied, Vacant};
101 use std::mem;
102 use std::ops::{Deref, DerefMut};
103 use std::rc::Rc;
104
105 // To avoid costly uniqueness checks, we require that `MatchSeq` always has a nonempty body.
106
107 /// Either a sequence of token trees or a single one. This is used as the representation of the
108 /// sequence of tokens that make up a matcher.
109 #[derive(Clone)]
110 enum TokenTreeOrTokenTreeSlice<'tt> {
111     Tt(TokenTree),
112     TtSeq(&'tt [TokenTree]),
113 }
114
115 impl<'tt> TokenTreeOrTokenTreeSlice<'tt> {
116     /// Returns the number of constituent top-level token trees of `self` (top-level in that it
117     /// will not recursively descend into subtrees).
118     fn len(&self) -> usize {
119         match *self {
120             TtSeq(ref v) => v.len(),
121             Tt(ref tt) => tt.len(),
122         }
123     }
124
125     /// The `index`-th token tree of `self`.
126     fn get_tt(&self, index: usize) -> TokenTree {
127         match *self {
128             TtSeq(ref v) => v[index].clone(),
129             Tt(ref tt) => tt.get_tt(index),
130         }
131     }
132 }
133
134 /// An unzipping of `TokenTree`s... see the `stack` field of `MatcherPos`.
135 ///
136 /// This is used by `inner_parse_loop` to keep track of delimited submatchers that we have
137 /// descended into.
138 #[derive(Clone)]
139 struct MatcherTtFrame<'tt> {
140     /// The "parent" matcher that we are descending into.
141     elts: TokenTreeOrTokenTreeSlice<'tt>,
142     /// The position of the "dot" in `elts` at the time we descended.
143     idx: usize,
144 }
145
146 type NamedMatchVec = SmallVec<[NamedMatch; 4]>;
147
148 /// Represents a single "position" (aka "matcher position", aka "item"), as
149 /// described in the module documentation.
150 ///
151 /// Here:
152 ///
153 /// - `'root` represents the lifetime of the stack slot that holds the root
154 ///   `MatcherPos`. As described in `MatcherPosHandle`, the root `MatcherPos`
155 ///   structure is stored on the stack, but subsequent instances are put into
156 ///   the heap.
157 /// - `'tt` represents the lifetime of the token trees that this matcher
158 ///   position refers to.
159 ///
160 /// It is important to distinguish these two lifetimes because we have a
161 /// `SmallVec<TokenTreeOrTokenTreeSlice<'tt>>` below, and the destructor of
162 /// that is considered to possibly access the data from its elements (it lacks
163 /// a `#[may_dangle]` attribute). As a result, the compiler needs to know that
164 /// all the elements in that `SmallVec` strictly outlive the root stack slot
165 /// lifetime. By separating `'tt` from `'root`, we can show that.
166 #[derive(Clone)]
167 struct MatcherPos<'root, 'tt: 'root> {
168     /// The token or sequence of tokens that make up the matcher
169     top_elts: TokenTreeOrTokenTreeSlice<'tt>,
170
171     /// The position of the "dot" in this matcher
172     idx: usize,
173
174     /// The first span of source source that the beginning of this matcher corresponds to. In other
175     /// words, the token in the source whose span is `sp_open` is matched against the first token of
176     /// the matcher.
177     sp_open: Span,
178
179     /// For each named metavar in the matcher, we keep track of token trees matched against the
180     /// metavar by the black box parser. In particular, there may be more than one match per
181     /// metavar if we are in a repetition (each repetition matches each of the variables).
182     /// Moreover, matchers and repetitions can be nested; the `matches` field is shared (hence the
183     /// `Rc`) among all "nested" matchers. `match_lo`, `match_cur`, and `match_hi` keep track of
184     /// the current position of the `self` matcher position in the shared `matches` list.
185     ///
186     /// Also, note that while we are descending into a sequence, matchers are given their own
187     /// `matches` vector. Only once we reach the end of a full repetition of the sequence do we add
188     /// all bound matches from the submatcher into the shared top-level `matches` vector. If `sep`
189     /// and `up` are `Some`, then `matches` is _not_ the shared top-level list. Instead, if one
190     /// wants the shared `matches`, one should use `up.matches`.
191     matches: Box<[Rc<NamedMatchVec>]>,
192     /// The position in `matches` corresponding to the first metavar in this matcher's sequence of
193     /// token trees. In other words, the first metavar in the first token of `top_elts` corresponds
194     /// to `matches[match_lo]`.
195     match_lo: usize,
196     /// The position in `matches` corresponding to the metavar we are currently trying to match
197     /// against the source token stream. `match_lo <= match_cur <= match_hi`.
198     match_cur: usize,
199     /// Similar to `match_lo` except `match_hi` is the position in `matches` of the _last_ metavar
200     /// in this matcher.
201     match_hi: usize,
202
203     // The following fields are used if we are matching a repetition. If we aren't, they should be
204     // `None`.
205
206     /// The KleeneOp of this sequence if we are in a repetition.
207     seq_op: Option<quoted::KleeneOp>,
208
209     /// The separator if we are in a repetition.
210     sep: Option<Token>,
211
212     /// The "parent" matcher position if we are in a repetition. That is, the matcher position just
213     /// before we enter the sequence.
214     up: Option<MatcherPosHandle<'root, 'tt>>,
215
216     /// Specifically used to "unzip" token trees. By "unzip", we mean to unwrap the delimiters from
217     /// a delimited token tree (e.g., something wrapped in `(` `)`) or to get the contents of a doc
218     /// comment...
219     ///
220     /// When matching against matchers with nested delimited submatchers (e.g., `pat ( pat ( .. )
221     /// pat ) pat`), we need to keep track of the matchers we are descending into. This stack does
222     /// that where the bottom of the stack is the outermost matcher.
223     /// Also, throughout the comments, this "descent" is often referred to as "unzipping"...
224     stack: SmallVec<[MatcherTtFrame<'tt>; 1]>,
225 }
226
227 impl<'root, 'tt> MatcherPos<'root, 'tt> {
228     /// Add `m` as a named match for the `idx`-th metavar.
229     fn push_match(&mut self, idx: usize, m: NamedMatch) {
230         let matches = Rc::make_mut(&mut self.matches[idx]);
231         matches.push(m);
232     }
233 }
234
235 // Lots of MatcherPos instances are created at runtime. Allocating them on the
236 // heap is slow. Furthermore, using SmallVec<MatcherPos> to allocate them all
237 // on the stack is also slow, because MatcherPos is quite a large type and
238 // instances get moved around a lot between vectors, which requires lots of
239 // slow memcpy calls.
240 //
241 // Therefore, the initial MatcherPos is always allocated on the stack,
242 // subsequent ones (of which there aren't that many) are allocated on the heap,
243 // and this type is used to encapsulate both cases.
244 enum MatcherPosHandle<'root, 'tt: 'root> {
245     Ref(&'root mut MatcherPos<'root, 'tt>),
246     Box(Box<MatcherPos<'root, 'tt>>),
247 }
248
249 impl<'root, 'tt> Clone for MatcherPosHandle<'root, 'tt> {
250     // This always produces a new Box.
251     fn clone(&self) -> Self {
252         MatcherPosHandle::Box(match *self {
253             MatcherPosHandle::Ref(ref r) => Box::new((**r).clone()),
254             MatcherPosHandle::Box(ref b) => b.clone(),
255         })
256     }
257 }
258
259 impl<'root, 'tt> Deref for MatcherPosHandle<'root, 'tt> {
260     type Target = MatcherPos<'root, 'tt>;
261     fn deref(&self) -> &Self::Target {
262         match *self {
263             MatcherPosHandle::Ref(ref r) => r,
264             MatcherPosHandle::Box(ref b) => b,
265         }
266     }
267 }
268
269 impl<'root, 'tt> DerefMut for MatcherPosHandle<'root, 'tt> {
270     fn deref_mut(&mut self) -> &mut MatcherPos<'root, 'tt> {
271         match *self {
272             MatcherPosHandle::Ref(ref mut r) => r,
273             MatcherPosHandle::Box(ref mut b) => b,
274         }
275     }
276 }
277
278 /// Represents the possible results of an attempted parse.
279 pub enum ParseResult<T> {
280     /// Parsed successfully.
281     Success(T),
282     /// Arm failed to match. If the second parameter is `token::Eof`, it indicates an unexpected
283     /// end of macro invocation. Otherwise, it indicates that no rules expected the given token.
284     Failure(syntax_pos::Span, Token, String),
285     /// Fatal error (malformed macro?). Abort compilation.
286     Error(syntax_pos::Span, String),
287 }
288
289 /// A `ParseResult` where the `Success` variant contains a mapping of `Ident`s to `NamedMatch`es.
290 /// This represents the mapping of metavars to the token trees they bind to.
291 pub type NamedParseResult = ParseResult<FxHashMap<Ident, Rc<NamedMatch>>>;
292
293 /// Count how many metavars are named in the given matcher `ms`.
294 pub fn count_names(ms: &[TokenTree]) -> usize {
295     ms.iter().fold(0, |count, elt| {
296         count + match *elt {
297             TokenTree::Sequence(_, ref seq) => seq.num_captures,
298             TokenTree::Delimited(_, ref delim) => count_names(&delim.tts),
299             TokenTree::MetaVar(..) => 0,
300             TokenTree::MetaVarDecl(..) => 1,
301             TokenTree::Token(..) => 0,
302         }
303     })
304 }
305
306 /// `len` `Vec`s (initially shared and empty) that will store matches of metavars.
307 fn create_matches(len: usize) -> Box<[Rc<NamedMatchVec>]> {
308     if len == 0 {
309         vec![]
310     } else {
311         let empty_matches = Rc::new(SmallVec::new());
312         vec![empty_matches; len]
313     }.into_boxed_slice()
314 }
315
316 /// Generate the top-level matcher position in which the "dot" is before the first token of the
317 /// matcher `ms` and we are going to start matching at the span `open` in the source.
318 fn initial_matcher_pos<'root, 'tt>(ms: &'tt [TokenTree], open: Span) -> MatcherPos<'root, 'tt> {
319     let match_idx_hi = count_names(ms);
320     let matches = create_matches(match_idx_hi);
321     MatcherPos {
322         // Start with the top level matcher given to us
323         top_elts: TtSeq(ms), // "elts" is an abbr. for "elements"
324         // The "dot" is before the first token of the matcher
325         idx: 0,
326         // We start matching at the span `open` in the source code
327         sp_open: open,
328
329         // Initialize `matches` to a bunch of empty `Vec`s -- one for each metavar in `top_elts`.
330         // `match_lo` for `top_elts` is 0 and `match_hi` is `matches.len()`. `match_cur` is 0 since
331         // we haven't actually matched anything yet.
332         matches,
333         match_lo: 0,
334         match_cur: 0,
335         match_hi: match_idx_hi,
336
337         // Haven't descended into any delimiters, so empty stack
338         stack: smallvec![],
339
340         // Haven't descended into any sequences, so both of these are `None`.
341         seq_op: None,
342         sep: None,
343         up: None,
344     }
345 }
346
347 /// `NamedMatch` is a pattern-match result for a single `token::MATCH_NONTERMINAL`:
348 /// so it is associated with a single ident in a parse, and all
349 /// `MatchedNonterminal`s in the `NamedMatch` have the same nonterminal type
350 /// (expr, item, etc). Each leaf in a single `NamedMatch` corresponds to a
351 /// single `token::MATCH_NONTERMINAL` in the `TokenTree` that produced it.
352 ///
353 /// The in-memory structure of a particular `NamedMatch` represents the match
354 /// that occurred when a particular subset of a matcher was applied to a
355 /// particular token tree.
356 ///
357 /// The width of each `MatchedSeq` in the `NamedMatch`, and the identity of
358 /// the `MatchedNonterminal`s, will depend on the token tree it was applied
359 /// to: each `MatchedSeq` corresponds to a single `TTSeq` in the originating
360 /// token tree. The depth of the `NamedMatch` structure will therefore depend
361 /// only on the nesting depth of `ast::TTSeq`s in the originating
362 /// token tree it was derived from.
363 #[derive(Debug, Clone)]
364 pub enum NamedMatch {
365     MatchedSeq(Rc<NamedMatchVec>, DelimSpan),
366     MatchedNonterminal(Rc<Nonterminal>),
367 }
368
369 /// Takes a sequence of token trees `ms` representing a matcher which successfully matched input
370 /// and an iterator of items that matched input and produces a `NamedParseResult`.
371 fn nameize<I: Iterator<Item = NamedMatch>>(
372     sess: &ParseSess,
373     ms: &[TokenTree],
374     mut res: I,
375 ) -> NamedParseResult {
376     // Recursively descend into each type of matcher (e.g., sequences, delimited, metavars) and make
377     // sure that each metavar has _exactly one_ binding. If a metavar does not have exactly one
378     // binding, then there is an error. If it does, then we insert the binding into the
379     // `NamedParseResult`.
380     fn n_rec<I: Iterator<Item = NamedMatch>>(
381         sess: &ParseSess,
382         m: &TokenTree,
383         res: &mut I,
384         ret_val: &mut FxHashMap<Ident, Rc<NamedMatch>>,
385     ) -> Result<(), (syntax_pos::Span, String)> {
386         match *m {
387             TokenTree::Sequence(_, ref seq) => for next_m in &seq.tts {
388                 n_rec(sess, next_m, res.by_ref(), ret_val)?
389             },
390             TokenTree::Delimited(_, ref delim) => for next_m in &delim.tts {
391                 n_rec(sess, next_m, res.by_ref(), ret_val)?;
392             },
393             TokenTree::MetaVarDecl(span, _, id) if id.name == keywords::Invalid.name() => {
394                 if sess.missing_fragment_specifiers.borrow_mut().remove(&span) {
395                     return Err((span, "missing fragment specifier".to_string()));
396                 }
397             }
398             TokenTree::MetaVarDecl(sp, bind_name, _) => {
399                 match ret_val.entry(bind_name) {
400                     Vacant(spot) => {
401                         // FIXME(simulacrum): Don't construct Rc here
402                         spot.insert(Rc::new(res.next().unwrap()));
403                     }
404                     Occupied(..) => {
405                         return Err((sp, format!("duplicated bind name: {}", bind_name)))
406                     }
407                 }
408             }
409             TokenTree::MetaVar(..) | TokenTree::Token(..) => (),
410         }
411
412         Ok(())
413     }
414
415     let mut ret_val = FxHashMap::default();
416     for m in ms {
417         match n_rec(sess, m, res.by_ref(), &mut ret_val) {
418             Ok(_) => {}
419             Err((sp, msg)) => return Error(sp, msg),
420         }
421     }
422
423     Success(ret_val)
424 }
425
426 /// Generate an appropriate parsing failure message. For EOF, this is "unexpected end...". For
427 /// other tokens, this is "unexpected token...".
428 pub fn parse_failure_msg(tok: Token) -> String {
429     match tok {
430         token::Eof => "unexpected end of macro invocation".to_string(),
431         _ => format!(
432             "no rules expected the token `{}`",
433             pprust::token_to_string(&tok)
434         ),
435     }
436 }
437
438 /// Perform a token equality check, ignoring syntax context (that is, an unhygienic comparison)
439 fn token_name_eq(t1: &Token, t2: &Token) -> bool {
440     if let (Some((id1, is_raw1)), Some((id2, is_raw2))) = (t1.ident(), t2.ident()) {
441         id1.name == id2.name && is_raw1 == is_raw2
442     } else if let (Some(id1), Some(id2)) = (t1.lifetime(), t2.lifetime()) {
443         id1.name == id2.name
444     } else {
445         *t1 == *t2
446     }
447 }
448
449 /// Process the matcher positions of `cur_items` until it is empty. In the process, this will
450 /// produce more items in `next_items`, `eof_items`, and `bb_items`.
451 ///
452 /// For more info about the how this happens, see the module-level doc comments and the inline
453 /// comments of this function.
454 ///
455 /// # Parameters
456 ///
457 /// - `sess`: the parsing session into which errors are emitted.
458 /// - `cur_items`: the set of current items to be processed. This should be empty by the end of a
459 ///   successful execution of this function.
460 /// - `next_items`: the set of newly generated items. These are used to replenish `cur_items` in
461 ///   the function `parse`.
462 /// - `eof_items`: the set of items that would be valid if this was the EOF.
463 /// - `bb_items`: the set of items that are waiting for the black-box parser.
464 /// - `token`: the current token of the parser.
465 /// - `span`: the `Span` in the source code corresponding to the token trees we are trying to match
466 ///   against the matcher positions in `cur_items`.
467 ///
468 /// # Returns
469 ///
470 /// A `ParseResult`. Note that matches are kept track of through the items generated.
471 fn inner_parse_loop<'root, 'tt>(
472     sess: &ParseSess,
473     cur_items: &mut SmallVec<[MatcherPosHandle<'root, 'tt>; 1]>,
474     next_items: &mut Vec<MatcherPosHandle<'root, 'tt>>,
475     eof_items: &mut SmallVec<[MatcherPosHandle<'root, 'tt>; 1]>,
476     bb_items: &mut SmallVec<[MatcherPosHandle<'root, 'tt>; 1]>,
477     token: &Token,
478     span: syntax_pos::Span,
479 ) -> ParseResult<()> {
480     // Pop items from `cur_items` until it is empty.
481     while let Some(mut item) = cur_items.pop() {
482         // When unzipped trees end, remove them. This corresponds to backtracking out of a
483         // delimited submatcher into which we already descended. In backtracking out again, we need
484         // to advance the "dot" past the delimiters in the outer matcher.
485         while item.idx >= item.top_elts.len() {
486             match item.stack.pop() {
487                 Some(MatcherTtFrame { elts, idx }) => {
488                     item.top_elts = elts;
489                     item.idx = idx + 1;
490                 }
491                 None => break,
492             }
493         }
494
495         // Get the current position of the "dot" (`idx`) in `item` and the number of token trees in
496         // the matcher (`len`).
497         let idx = item.idx;
498         let len = item.top_elts.len();
499
500         // If `idx >= len`, then we are at or past the end of the matcher of `item`.
501         if idx >= len {
502             // We are repeating iff there is a parent. If the matcher is inside of a repetition,
503             // then we could be at the end of a sequence or at the beginning of the next
504             // repetition.
505             if item.up.is_some() {
506                 // At this point, regardless of whether there is a separator, we should add all
507                 // matches from the complete repetition of the sequence to the shared, top-level
508                 // `matches` list (actually, `up.matches`, which could itself not be the top-level,
509                 // but anyway...). Moreover, we add another item to `cur_items` in which the "dot"
510                 // is at the end of the `up` matcher. This ensures that the "dot" in the `up`
511                 // matcher is also advanced sufficiently.
512                 //
513                 // NOTE: removing the condition `idx == len` allows trailing separators.
514                 if idx == len {
515                     // Get the `up` matcher
516                     let mut new_pos = item.up.clone().unwrap();
517
518                     // Add matches from this repetition to the `matches` of `up`
519                     for idx in item.match_lo..item.match_hi {
520                         let sub = item.matches[idx].clone();
521                         let span = DelimSpan::from_pair(item.sp_open, span);
522                         new_pos.push_match(idx, MatchedSeq(sub, span));
523                     }
524
525                     // Move the "dot" past the repetition in `up`
526                     new_pos.match_cur = item.match_hi;
527                     new_pos.idx += 1;
528                     cur_items.push(new_pos);
529                 }
530
531                 // Check if we need a separator.
532                 if idx == len && item.sep.is_some() {
533                     // We have a separator, and it is the current token. We can advance past the
534                     // separator token.
535                     if item.sep
536                         .as_ref()
537                         .map(|sep| token_name_eq(token, sep))
538                         .unwrap_or(false)
539                     {
540                         item.idx += 1;
541                         next_items.push(item);
542                     }
543                 }
544                 // We don't need a separator. Move the "dot" back to the beginning of the matcher
545                 // and try to match again UNLESS we are only allowed to have _one_ repetition.
546                 else if item.seq_op != Some(quoted::KleeneOp::ZeroOrOne) {
547                     item.match_cur = item.match_lo;
548                     item.idx = 0;
549                     cur_items.push(item);
550                 }
551             }
552             // If we are not in a repetition, then being at the end of a matcher means that we have
553             // reached the potential end of the input.
554             else {
555                 eof_items.push(item);
556             }
557         }
558         // We are in the middle of a matcher.
559         else {
560             // Look at what token in the matcher we are trying to match the current token (`token`)
561             // against. Depending on that, we may generate new items.
562             match item.top_elts.get_tt(idx) {
563                 // Need to descend into a sequence
564                 TokenTree::Sequence(sp, seq) => {
565                     // Examine the case where there are 0 matches of this sequence
566                     if seq.op == quoted::KleeneOp::ZeroOrMore
567                         || seq.op == quoted::KleeneOp::ZeroOrOne
568                     {
569                         let mut new_item = item.clone();
570                         new_item.match_cur += seq.num_captures;
571                         new_item.idx += 1;
572                         for idx in item.match_cur..item.match_cur + seq.num_captures {
573                             new_item.push_match(idx, MatchedSeq(Rc::new(smallvec![]), sp));
574                         }
575                         cur_items.push(new_item);
576                     }
577
578                     let matches = create_matches(item.matches.len());
579                     cur_items.push(MatcherPosHandle::Box(Box::new(MatcherPos {
580                         stack: smallvec![],
581                         sep: seq.separator.clone(),
582                         seq_op: Some(seq.op),
583                         idx: 0,
584                         matches,
585                         match_lo: item.match_cur,
586                         match_cur: item.match_cur,
587                         match_hi: item.match_cur + seq.num_captures,
588                         up: Some(item),
589                         sp_open: sp.open,
590                         top_elts: Tt(TokenTree::Sequence(sp, seq)),
591                     })));
592                 }
593
594                 // We need to match a metavar (but the identifier is invalid)... this is an error
595                 TokenTree::MetaVarDecl(span, _, id) if id.name == keywords::Invalid.name() => {
596                     if sess.missing_fragment_specifiers.borrow_mut().remove(&span) {
597                         return Error(span, "missing fragment specifier".to_string());
598                     }
599                 }
600
601                 // We need to match a metavar with a valid ident... call out to the black-box
602                 // parser by adding an item to `bb_items`.
603                 TokenTree::MetaVarDecl(_, _, id) => {
604                     // Built-in nonterminals never start with these tokens,
605                     // so we can eliminate them from consideration.
606                     if may_begin_with(&*id.as_str(), token) {
607                         bb_items.push(item);
608                     }
609                 }
610
611                 // We need to descend into a delimited submatcher or a doc comment. To do this, we
612                 // push the current matcher onto a stack and push a new item containing the
613                 // submatcher onto `cur_items`.
614                 //
615                 // At the beginning of the loop, if we reach the end of the delimited submatcher,
616                 // we pop the stack to backtrack out of the descent.
617                 seq @ TokenTree::Delimited(..) | seq @ TokenTree::Token(_, DocComment(..)) => {
618                     let lower_elts = mem::replace(&mut item.top_elts, Tt(seq));
619                     let idx = item.idx;
620                     item.stack.push(MatcherTtFrame {
621                         elts: lower_elts,
622                         idx,
623                     });
624                     item.idx = 0;
625                     cur_items.push(item);
626                 }
627
628                 // We just matched a normal token. We can just advance the parser.
629                 TokenTree::Token(_, ref t) if token_name_eq(t, token) => {
630                     item.idx += 1;
631                     next_items.push(item);
632                 }
633
634                 // There was another token that was not `token`... This means we can't add any
635                 // rules. NOTE that this is not necessarily an error unless _all_ items in
636                 // `cur_items` end up doing this. There may still be some other matchers that do
637                 // end up working out.
638                 TokenTree::Token(..) | TokenTree::MetaVar(..) => {}
639             }
640         }
641     }
642
643     // Yay a successful parse (so far)!
644     Success(())
645 }
646
647 /// Use the given sequence of token trees (`ms`) as a matcher. Match the given token stream `tts`
648 /// against it and return the match.
649 ///
650 /// # Parameters
651 ///
652 /// - `sess`: The session into which errors are emitted
653 /// - `tts`: The tokenstream we are matching against the pattern `ms`
654 /// - `ms`: A sequence of token trees representing a pattern against which we are matching
655 /// - `directory`: Information about the file locations (needed for the black-box parser)
656 /// - `recurse_into_modules`: Whether or not to recurse into modules (needed for the black-box
657 ///   parser)
658 pub fn parse(
659     sess: &ParseSess,
660     tts: TokenStream,
661     ms: &[TokenTree],
662     directory: Option<Directory>,
663     recurse_into_modules: bool,
664 ) -> NamedParseResult {
665     // Create a parser that can be used for the "black box" parts.
666     let mut parser = Parser::new(sess, tts, directory, recurse_into_modules, true);
667
668     // A queue of possible matcher positions. We initialize it with the matcher position in which
669     // the "dot" is before the first token of the first token tree in `ms`. `inner_parse_loop` then
670     // processes all of these possible matcher positions and produces possible next positions into
671     // `next_items`. After some post-processing, the contents of `next_items` replenish `cur_items`
672     // and we start over again.
673     //
674     // This MatcherPos instance is allocated on the stack. All others -- and
675     // there are frequently *no* others! -- are allocated on the heap.
676     let mut initial = initial_matcher_pos(ms, parser.span);
677     let mut cur_items = smallvec![MatcherPosHandle::Ref(&mut initial)];
678     let mut next_items = Vec::new();
679
680     loop {
681         // Matcher positions black-box parsed by parser.rs (`parser`)
682         let mut bb_items = SmallVec::new();
683
684         // Matcher positions that would be valid if the macro invocation was over now
685         let mut eof_items = SmallVec::new();
686         assert!(next_items.is_empty());
687
688         // Process `cur_items` until either we have finished the input or we need to get some
689         // parsing from the black-box parser done. The result is that `next_items` will contain a
690         // bunch of possible next matcher positions in `next_items`.
691         match inner_parse_loop(
692             sess,
693             &mut cur_items,
694             &mut next_items,
695             &mut eof_items,
696             &mut bb_items,
697             &parser.token,
698             parser.span,
699         ) {
700             Success(_) => {}
701             Failure(sp, tok, t) => return Failure(sp, tok, t),
702             Error(sp, msg) => return Error(sp, msg),
703         }
704
705         // inner parse loop handled all cur_items, so it's empty
706         assert!(cur_items.is_empty());
707
708         // We need to do some post processing after the `inner_parser_loop`.
709         //
710         // Error messages here could be improved with links to original rules.
711
712         // If we reached the EOF, check that there is EXACTLY ONE possible matcher. Otherwise,
713         // either the parse is ambiguous (which should never happen) or there is a syntax error.
714         if token_name_eq(&parser.token, &token::Eof) {
715             if eof_items.len() == 1 {
716                 let matches = eof_items[0]
717                     .matches
718                     .iter_mut()
719                     .map(|dv| Rc::make_mut(dv).pop().unwrap());
720                 return nameize(sess, ms, matches);
721             } else if eof_items.len() > 1 {
722                 return Error(
723                     parser.span,
724                     "ambiguity: multiple successful parses".to_string(),
725                 );
726             } else {
727                 return Failure(
728                     if parser.span.is_dummy() {
729                         parser.span
730                     } else {
731                         sess.source_map().next_point(parser.span)
732                     },
733                     token::Eof,
734                     "missing tokens in macro arguments".to_string(),
735                 );
736             }
737         }
738         // Performance hack: eof_items may share matchers via Rc with other things that we want
739         // to modify. Dropping eof_items now may drop these refcounts to 1, preventing an
740         // unnecessary implicit clone later in Rc::make_mut.
741         drop(eof_items);
742
743         // Another possibility is that we need to call out to parse some rust nonterminal
744         // (black-box) parser. However, if there is not EXACTLY ONE of these, something is wrong.
745         if (!bb_items.is_empty() && !next_items.is_empty()) || bb_items.len() > 1 {
746             let nts = bb_items
747                 .iter()
748                 .map(|item| match item.top_elts.get_tt(item.idx) {
749                     TokenTree::MetaVarDecl(_, bind, name) => format!("{} ('{}')", name, bind),
750                     _ => panic!(),
751                 })
752                 .collect::<Vec<String>>()
753                 .join(" or ");
754
755             return Error(
756                 parser.span,
757                 format!(
758                     "local ambiguity: multiple parsing options: {}",
759                     match next_items.len() {
760                         0 => format!("built-in NTs {}.", nts),
761                         1 => format!("built-in NTs {} or 1 other option.", nts),
762                         n => format!("built-in NTs {} or {} other options.", nts, n),
763                     }
764                 ),
765             );
766         }
767         // If there are no possible next positions AND we aren't waiting for the black-box parser,
768         // then there is a syntax error.
769         else if bb_items.is_empty() && next_items.is_empty() {
770             return Failure(
771                 parser.span,
772                 parser.token,
773                 "no rules expected this token in macro call".to_string(),
774             );
775         }
776         // Dump all possible `next_items` into `cur_items` for the next iteration.
777         else if !next_items.is_empty() {
778             // Now process the next token
779             cur_items.extend(next_items.drain(..));
780             parser.bump();
781         }
782         // Finally, we have the case where we need to call the black-box parser to get some
783         // nonterminal.
784         else {
785             assert_eq!(bb_items.len(), 1);
786
787             let mut item = bb_items.pop().unwrap();
788             if let TokenTree::MetaVarDecl(span, _, ident) = item.top_elts.get_tt(item.idx) {
789                 let match_cur = item.match_cur;
790                 item.push_match(
791                     match_cur,
792                     MatchedNonterminal(Rc::new(parse_nt(&mut parser, span, &ident.as_str()))),
793                 );
794                 item.idx += 1;
795                 item.match_cur += 1;
796             } else {
797                 unreachable!()
798             }
799             cur_items.push(item);
800         }
801
802         assert!(!cur_items.is_empty());
803     }
804 }
805
806 /// The token is an identifier, but not `_`.
807 /// We prohibit passing `_` to macros expecting `ident` for now.
808 fn get_macro_ident(token: &Token) -> Option<(Ident, bool)> {
809     match *token {
810         token::Ident(ident, is_raw) if ident.name != keywords::Underscore.name() =>
811             Some((ident, is_raw)),
812         _ => None,
813     }
814 }
815
816 /// Checks whether a non-terminal may begin with a particular token.
817 ///
818 /// Returning `false` is a *stability guarantee* that such a matcher will *never* begin with that
819 /// token. Be conservative (return true) if not sure.
820 fn may_begin_with(name: &str, token: &Token) -> bool {
821     /// Checks whether the non-terminal may contain a single (non-keyword) identifier.
822     fn may_be_ident(nt: &token::Nonterminal) -> bool {
823         match *nt {
824             token::NtItem(_) | token::NtBlock(_) | token::NtVis(_) => false,
825             _ => true,
826         }
827     }
828
829     match name {
830         "expr" => token.can_begin_expr(),
831         "ty" => token.can_begin_type(),
832         "ident" => get_macro_ident(token).is_some(),
833         "literal" => token.can_begin_literal_or_bool(),
834         "vis" => match *token {
835             // The follow-set of :vis + "priv" keyword + interpolated
836             Token::Comma | Token::Ident(..) | Token::Interpolated(_) => true,
837             _ => token.can_begin_type(),
838         },
839         "block" => match *token {
840             Token::OpenDelim(token::Brace) => true,
841             Token::Interpolated(ref nt) => match nt.0 {
842                 token::NtItem(_)
843                 | token::NtPat(_)
844                 | token::NtTy(_)
845                 | token::NtIdent(..)
846                 | token::NtMeta(_)
847                 | token::NtPath(_)
848                 | token::NtVis(_) => false, // none of these may start with '{'.
849                 _ => true,
850             },
851             _ => false,
852         },
853         "path" | "meta" => match *token {
854             Token::ModSep | Token::Ident(..) => true,
855             Token::Interpolated(ref nt) => match nt.0 {
856                 token::NtPath(_) | token::NtMeta(_) => true,
857                 _ => may_be_ident(&nt.0),
858             },
859             _ => false,
860         },
861         "pat" => match *token {
862             Token::Ident(..) |               // box, ref, mut, and other identifiers (can stricten)
863             Token::OpenDelim(token::Paren) |    // tuple pattern
864             Token::OpenDelim(token::Bracket) |  // slice pattern
865             Token::BinOp(token::And) |          // reference
866             Token::BinOp(token::Minus) |        // negative literal
867             Token::AndAnd |                     // double reference
868             Token::Literal(..) |                // literal
869             Token::DotDot |                     // range pattern (future compat)
870             Token::DotDotDot |                  // range pattern (future compat)
871             Token::ModSep |                     // path
872             Token::Lt |                         // path (UFCS constant)
873             Token::BinOp(token::Shl) => true,   // path (double UFCS)
874             Token::Interpolated(ref nt) => may_be_ident(&nt.0),
875             _ => false,
876         },
877         "lifetime" => match *token {
878             Token::Lifetime(_) => true,
879             Token::Interpolated(ref nt) => match nt.0 {
880                 token::NtLifetime(_) | token::NtTT(_) => true,
881                 _ => false,
882             },
883             _ => false,
884         },
885         _ => match *token {
886             token::CloseDelim(_) => false,
887             _ => true,
888         },
889     }
890 }
891
892 /// A call to the "black-box" parser to parse some rust nonterminal.
893 ///
894 /// # Parameters
895 ///
896 /// - `p`: the "black-box" parser to use
897 /// - `sp`: the `Span` we want to parse
898 /// - `name`: the name of the metavar _matcher_ we want to match (e.g., `tt`, `ident`, `block`,
899 ///   etc...)
900 ///
901 /// # Returns
902 ///
903 /// The parsed nonterminal.
904 fn parse_nt<'a>(p: &mut Parser<'a>, sp: Span, name: &str) -> Nonterminal {
905     if name == "tt" {
906         return token::NtTT(p.parse_token_tree());
907     }
908     // check at the beginning and the parser checks after each bump
909     p.process_potential_macro_variable();
910     match name {
911         "item" => match panictry!(p.parse_item()) {
912             Some(i) => token::NtItem(i),
913             None => {
914                 p.fatal("expected an item keyword").emit();
915                 FatalError.raise();
916             }
917         },
918         "block" => token::NtBlock(panictry!(p.parse_block())),
919         "stmt" => match panictry!(p.parse_stmt()) {
920             Some(s) => token::NtStmt(s),
921             None => {
922                 p.fatal("expected a statement").emit();
923                 FatalError.raise();
924             }
925         },
926         "pat" => token::NtPat(panictry!(p.parse_pat(None))),
927         "expr" => token::NtExpr(panictry!(p.parse_expr())),
928         "literal" => token::NtLiteral(panictry!(p.parse_literal_maybe_minus())),
929         "ty" => token::NtTy(panictry!(p.parse_ty())),
930         // this could be handled like a token, since it is one
931         "ident" => if let Some((ident, is_raw)) = get_macro_ident(&p.token) {
932             let span = p.span;
933             p.bump();
934             token::NtIdent(Ident::new(ident.name, span), is_raw)
935         } else {
936             let token_str = pprust::token_to_string(&p.token);
937             p.fatal(&format!("expected ident, found {}", &token_str)).emit();
938             FatalError.raise()
939         }
940         "path" => token::NtPath(panictry!(p.parse_path_common(PathStyle::Type, false))),
941         "meta" => token::NtMeta(panictry!(p.parse_meta_item())),
942         "vis" => token::NtVis(panictry!(p.parse_visibility(true))),
943         "lifetime" => if p.check_lifetime() {
944             token::NtLifetime(p.expect_lifetime().ident)
945         } else {
946             let token_str = pprust::token_to_string(&p.token);
947             p.fatal(&format!("expected a lifetime, found `{}`", &token_str)).emit();
948             FatalError.raise();
949         }
950         // this is not supposed to happen, since it has been checked
951         // when compiling the macro.
952         _ => p.span_bug(sp, "invalid fragment specifier"),
953     }
954 }