]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_expand/src/mbe/macro_parser.rs
Bless NLL test
[rust.git] / compiler / rustc_expand / src / mbe / macro_parser.rs
1 //! This is an NFA-based parser, which calls out to the main rust parser for named non-terminals
2 //! (which it commits to fully when it hits one in a grammar). There's a set of current NFA threads
3 //! and a set of next ones. Instead of NTs, we have a special case for Kleene star. The big-O, in
4 //! pathological cases, is worse than traditional use of NFA or Earley parsing, but it's an easier
5 //! fit for Macro-by-Example-style rules.
6 //!
7 //! (In order to prevent the pathological case, we'd need to lazily construct the resulting
8 //! `NamedMatch`es at the very end. It'd be a pain, and require more memory to keep around old
9 //! items, but it would also save overhead)
10 //!
11 //! We don't say this parser uses the Earley algorithm, because it's unnecessarily inaccurate.
12 //! The macro parser restricts itself to the features of finite state automata. Earley parsers
13 //! can be described as an extension of NFAs with completion rules, prediction rules, and recursion.
14 //!
15 //! Quick intro to how the parser works:
16 //!
17 //! A 'position' is a dot in the middle of a matcher, usually represented as a
18 //! dot. For example `· a $( a )* a b` is a position, as is `a $( · a )* a b`.
19 //!
20 //! The parser walks through the input a character at a time, maintaining a list
21 //! of threads consistent with the current position in the input string: `cur_items`.
22 //!
23 //! As it processes them, it fills up `eof_items` with threads that would be valid if
24 //! the macro invocation is now over, `bb_items` with threads that are waiting on
25 //! a Rust non-terminal like `$e:expr`, and `next_items` with threads that are waiting
26 //! on a particular token. Most of the logic concerns moving the · through the
27 //! repetitions indicated by Kleene stars. The rules for moving the · without
28 //! consuming any input are called epsilon transitions. It only advances or calls
29 //! out to the real Rust parser when no `cur_items` threads remain.
30 //!
31 //! Example:
32 //!
33 //! ```text, ignore
34 //! Start parsing a a a a b against [· a $( a )* a b].
35 //!
36 //! Remaining input: a a a a b
37 //! next: [· a $( a )* a b]
38 //!
39 //! - - - Advance over an a. - - -
40 //!
41 //! Remaining input: a a a b
42 //! cur: [a · $( a )* a b]
43 //! Descend/Skip (first item).
44 //! next: [a $( · a )* a b]  [a $( a )* · a b].
45 //!
46 //! - - - Advance over an a. - - -
47 //!
48 //! Remaining input: a a b
49 //! cur: [a $( a · )* a b]  [a $( a )* a · b]
50 //! Follow epsilon transition: Finish/Repeat (first item)
51 //! next: [a $( a )* · a b]  [a $( · a )* a b]  [a $( a )* a · b]
52 //!
53 //! - - - Advance over an a. - - - (this looks exactly like the last step)
54 //!
55 //! Remaining input: a b
56 //! cur: [a $( a · )* a b]  [a $( a )* a · b]
57 //! Follow epsilon transition: Finish/Repeat (first item)
58 //! next: [a $( a )* · a b]  [a $( · a )* a b]  [a $( a )* a · b]
59 //!
60 //! - - - Advance over an a. - - - (this looks exactly like the last step)
61 //!
62 //! Remaining input: b
63 //! cur: [a $( a · )* a b]  [a $( a )* a · b]
64 //! Follow epsilon transition: Finish/Repeat (first item)
65 //! next: [a $( a )* · a b]  [a $( · a )* a b]  [a $( a )* a · b]
66 //!
67 //! - - - Advance over a b. - - -
68 //!
69 //! Remaining input: ''
70 //! eof: [a $( a )* a b ·]
71 //! ```
72
73 crate use NamedMatch::*;
74 crate use ParseResult::*;
75 use TokenTreeOrTokenTreeSlice::*;
76
77 use crate::mbe::{self, TokenTree};
78
79 use rustc_ast::token::{self, DocComment, Nonterminal, Token};
80 use rustc_parse::parser::Parser;
81 use rustc_session::parse::ParseSess;
82 use rustc_span::symbol::MacroRulesNormalizedIdent;
83
84 use smallvec::{smallvec, SmallVec};
85
86 use rustc_data_structures::fx::FxHashMap;
87 use rustc_data_structures::sync::Lrc;
88 use std::borrow::Cow;
89 use std::collections::hash_map::Entry::{Occupied, Vacant};
90 use std::mem;
91 use std::ops::{Deref, DerefMut};
92
93 // To avoid costly uniqueness checks, we require that `MatchSeq` always has a nonempty body.
94
95 /// Either a sequence of token trees or a single one. This is used as the representation of the
96 /// sequence of tokens that make up a matcher.
97 #[derive(Clone)]
98 enum TokenTreeOrTokenTreeSlice<'tt> {
99     Tt(TokenTree),
100     TtSeq(&'tt [TokenTree]),
101 }
102
103 impl<'tt> TokenTreeOrTokenTreeSlice<'tt> {
104     /// Returns the number of constituent top-level token trees of `self` (top-level in that it
105     /// will not recursively descend into subtrees).
106     fn len(&self) -> usize {
107         match *self {
108             TtSeq(ref v) => v.len(),
109             Tt(ref tt) => tt.len(),
110         }
111     }
112
113     /// The `index`-th token tree of `self`.
114     fn get_tt(&self, index: usize) -> TokenTree {
115         match *self {
116             TtSeq(ref v) => v[index].clone(),
117             Tt(ref tt) => tt.get_tt(index),
118         }
119     }
120 }
121
122 /// An unzipping of `TokenTree`s... see the `stack` field of `MatcherPos`.
123 ///
124 /// This is used by `inner_parse_loop` to keep track of delimited submatchers that we have
125 /// descended into.
126 #[derive(Clone)]
127 struct MatcherTtFrame<'tt> {
128     /// The "parent" matcher that we are descending into.
129     elts: TokenTreeOrTokenTreeSlice<'tt>,
130     /// The position of the "dot" in `elts` at the time we descended.
131     idx: usize,
132 }
133
134 type NamedMatchVec = SmallVec<[NamedMatch; 4]>;
135
136 /// Represents a single "position" (aka "matcher position", aka "item"), as
137 /// described in the module documentation.
138 ///
139 /// Here:
140 ///
141 /// - `'root` represents the lifetime of the stack slot that holds the root
142 ///   `MatcherPos`. As described in `MatcherPosHandle`, the root `MatcherPos`
143 ///   structure is stored on the stack, but subsequent instances are put into
144 ///   the heap.
145 /// - `'tt` represents the lifetime of the token trees that this matcher
146 ///   position refers to.
147 ///
148 /// It is important to distinguish these two lifetimes because we have a
149 /// `SmallVec<TokenTreeOrTokenTreeSlice<'tt>>` below, and the destructor of
150 /// that is considered to possibly access the data from its elements (it lacks
151 /// a `#[may_dangle]` attribute). As a result, the compiler needs to know that
152 /// all the elements in that `SmallVec` strictly outlive the root stack slot
153 /// lifetime. By separating `'tt` from `'root`, we can show that.
154 #[derive(Clone)]
155 struct MatcherPos<'root, 'tt> {
156     /// The token or sequence of tokens that make up the matcher
157     top_elts: TokenTreeOrTokenTreeSlice<'tt>,
158
159     /// The position of the "dot" in this matcher
160     idx: usize,
161
162     /// For each named metavar in the matcher, we keep track of token trees matched against the
163     /// metavar by the black box parser. In particular, there may be more than one match per
164     /// metavar if we are in a repetition (each repetition matches each of the variables).
165     /// Moreover, matchers and repetitions can be nested; the `matches` field is shared (hence the
166     /// `Rc`) among all "nested" matchers. `match_lo`, `match_cur`, and `match_hi` keep track of
167     /// the current position of the `self` matcher position in the shared `matches` list.
168     ///
169     /// Also, note that while we are descending into a sequence, matchers are given their own
170     /// `matches` vector. Only once we reach the end of a full repetition of the sequence do we add
171     /// all bound matches from the submatcher into the shared top-level `matches` vector. If `sep`
172     /// and `up` are `Some`, then `matches` is _not_ the shared top-level list. Instead, if one
173     /// wants the shared `matches`, one should use `up.matches`.
174     matches: Box<[Lrc<NamedMatchVec>]>,
175     /// The position in `matches` corresponding to the first metavar in this matcher's sequence of
176     /// token trees. In other words, the first metavar in the first token of `top_elts` corresponds
177     /// to `matches[match_lo]`.
178     match_lo: usize,
179     /// The position in `matches` corresponding to the metavar we are currently trying to match
180     /// against the source token stream. `match_lo <= match_cur <= match_hi`.
181     match_cur: usize,
182     /// Similar to `match_lo` except `match_hi` is the position in `matches` of the _last_ metavar
183     /// in this matcher.
184     match_hi: usize,
185
186     // The following fields are used if we are matching a repetition. If we aren't, they should be
187     // `None`.
188     /// The KleeneOp of this sequence if we are in a repetition.
189     seq_op: Option<mbe::KleeneOp>,
190
191     /// The separator if we are in a repetition.
192     sep: Option<Token>,
193
194     /// The "parent" matcher position if we are in a repetition. That is, the matcher position just
195     /// before we enter the sequence.
196     up: Option<MatcherPosHandle<'root, 'tt>>,
197
198     /// Specifically used to "unzip" token trees. By "unzip", we mean to unwrap the delimiters from
199     /// a delimited token tree (e.g., something wrapped in `(` `)`) or to get the contents of a doc
200     /// comment...
201     ///
202     /// When matching against matchers with nested delimited submatchers (e.g., `pat ( pat ( .. )
203     /// pat ) pat`), we need to keep track of the matchers we are descending into. This stack does
204     /// that where the bottom of the stack is the outermost matcher.
205     /// Also, throughout the comments, this "descent" is often referred to as "unzipping"...
206     stack: SmallVec<[MatcherTtFrame<'tt>; 1]>,
207 }
208
209 impl<'root, 'tt> MatcherPos<'root, 'tt> {
210     /// Adds `m` as a named match for the `idx`-th metavar.
211     fn push_match(&mut self, idx: usize, m: NamedMatch) {
212         let matches = Lrc::make_mut(&mut self.matches[idx]);
213         matches.push(m);
214     }
215 }
216
217 // Lots of MatcherPos instances are created at runtime. Allocating them on the
218 // heap is slow. Furthermore, using SmallVec<MatcherPos> to allocate them all
219 // on the stack is also slow, because MatcherPos is quite a large type and
220 // instances get moved around a lot between vectors, which requires lots of
221 // slow memcpy calls.
222 //
223 // Therefore, the initial MatcherPos is always allocated on the stack,
224 // subsequent ones (of which there aren't that many) are allocated on the heap,
225 // and this type is used to encapsulate both cases.
226 enum MatcherPosHandle<'root, 'tt> {
227     Ref(&'root mut MatcherPos<'root, 'tt>),
228     Box(Box<MatcherPos<'root, 'tt>>),
229 }
230
231 impl<'root, 'tt> Clone for MatcherPosHandle<'root, 'tt> {
232     // This always produces a new Box.
233     fn clone(&self) -> Self {
234         MatcherPosHandle::Box(match *self {
235             MatcherPosHandle::Ref(ref r) => Box::new((**r).clone()),
236             MatcherPosHandle::Box(ref b) => b.clone(),
237         })
238     }
239 }
240
241 impl<'root, 'tt> Deref for MatcherPosHandle<'root, 'tt> {
242     type Target = MatcherPos<'root, 'tt>;
243     fn deref(&self) -> &Self::Target {
244         match *self {
245             MatcherPosHandle::Ref(ref r) => r,
246             MatcherPosHandle::Box(ref b) => b,
247         }
248     }
249 }
250
251 impl<'root, 'tt> DerefMut for MatcherPosHandle<'root, 'tt> {
252     fn deref_mut(&mut self) -> &mut MatcherPos<'root, 'tt> {
253         match *self {
254             MatcherPosHandle::Ref(ref mut r) => r,
255             MatcherPosHandle::Box(ref mut b) => b,
256         }
257     }
258 }
259
260 /// Represents the possible results of an attempted parse.
261 crate enum ParseResult<T> {
262     /// Parsed successfully.
263     Success(T),
264     /// Arm failed to match. If the second parameter is `token::Eof`, it indicates an unexpected
265     /// end of macro invocation. Otherwise, it indicates that no rules expected the given token.
266     Failure(Token, &'static str),
267     /// Fatal error (malformed macro?). Abort compilation.
268     Error(rustc_span::Span, String),
269     ErrorReported,
270 }
271
272 /// A `ParseResult` where the `Success` variant contains a mapping of
273 /// `MacroRulesNormalizedIdent`s to `NamedMatch`es. This represents the mapping
274 /// of metavars to the token trees they bind to.
275 crate type NamedParseResult = ParseResult<FxHashMap<MacroRulesNormalizedIdent, NamedMatch>>;
276
277 /// Count how many metavars are named in the given matcher `ms`.
278 pub(super) fn count_names(ms: &[TokenTree]) -> usize {
279     ms.iter().fold(0, |count, elt| {
280         count
281             + match *elt {
282                 TokenTree::Sequence(_, ref seq) => seq.num_captures,
283                 TokenTree::Delimited(_, ref delim) => count_names(&delim.tts),
284                 TokenTree::MetaVar(..) => 0,
285                 TokenTree::MetaVarDecl(..) => 1,
286                 TokenTree::Token(..) => 0,
287             }
288     })
289 }
290
291 /// `len` `Vec`s (initially shared and empty) that will store matches of metavars.
292 fn create_matches(len: usize) -> Box<[Lrc<NamedMatchVec>]> {
293     if len == 0 {
294         vec![]
295     } else {
296         let empty_matches = Lrc::new(SmallVec::new());
297         vec![empty_matches; len]
298     }
299     .into_boxed_slice()
300 }
301
302 /// Generates the top-level matcher position in which the "dot" is before the first token of the
303 /// matcher `ms`.
304 fn initial_matcher_pos<'root, 'tt>(ms: &'tt [TokenTree]) -> MatcherPos<'root, 'tt> {
305     let match_idx_hi = count_names(ms);
306     let matches = create_matches(match_idx_hi);
307     MatcherPos {
308         // Start with the top level matcher given to us
309         top_elts: TtSeq(ms), // "elts" is an abbr. for "elements"
310         // The "dot" is before the first token of the matcher
311         idx: 0,
312
313         // Initialize `matches` to a bunch of empty `Vec`s -- one for each metavar in `top_elts`.
314         // `match_lo` for `top_elts` is 0 and `match_hi` is `matches.len()`. `match_cur` is 0 since
315         // we haven't actually matched anything yet.
316         matches,
317         match_lo: 0,
318         match_cur: 0,
319         match_hi: match_idx_hi,
320
321         // Haven't descended into any delimiters, so empty stack
322         stack: smallvec![],
323
324         // Haven't descended into any sequences, so both of these are `None`.
325         seq_op: None,
326         sep: None,
327         up: None,
328     }
329 }
330
331 /// `NamedMatch` is a pattern-match result for a single `token::MATCH_NONTERMINAL`:
332 /// so it is associated with a single ident in a parse, and all
333 /// `MatchedNonterminal`s in the `NamedMatch` have the same non-terminal type
334 /// (expr, item, etc). Each leaf in a single `NamedMatch` corresponds to a
335 /// single `token::MATCH_NONTERMINAL` in the `TokenTree` that produced it.
336 ///
337 /// The in-memory structure of a particular `NamedMatch` represents the match
338 /// that occurred when a particular subset of a matcher was applied to a
339 /// particular token tree.
340 ///
341 /// The width of each `MatchedSeq` in the `NamedMatch`, and the identity of
342 /// the `MatchedNonterminal`s, will depend on the token tree it was applied
343 /// to: each `MatchedSeq` corresponds to a single `TTSeq` in the originating
344 /// token tree. The depth of the `NamedMatch` structure will therefore depend
345 /// only on the nesting depth of `ast::TTSeq`s in the originating
346 /// token tree it was derived from.
347 #[derive(Debug, Clone)]
348 crate enum NamedMatch {
349     MatchedSeq(Lrc<NamedMatchVec>),
350     MatchedNonterminal(Lrc<Nonterminal>),
351 }
352
353 /// Takes a sequence of token trees `ms` representing a matcher which successfully matched input
354 /// and an iterator of items that matched input and produces a `NamedParseResult`.
355 fn nameize<I: Iterator<Item = NamedMatch>>(
356     sess: &ParseSess,
357     ms: &[TokenTree],
358     mut res: I,
359 ) -> NamedParseResult {
360     // Recursively descend into each type of matcher (e.g., sequences, delimited, metavars) and make
361     // sure that each metavar has _exactly one_ binding. If a metavar does not have exactly one
362     // binding, then there is an error. If it does, then we insert the binding into the
363     // `NamedParseResult`.
364     fn n_rec<I: Iterator<Item = NamedMatch>>(
365         sess: &ParseSess,
366         m: &TokenTree,
367         res: &mut I,
368         ret_val: &mut FxHashMap<MacroRulesNormalizedIdent, NamedMatch>,
369     ) -> Result<(), (rustc_span::Span, String)> {
370         match *m {
371             TokenTree::Sequence(_, ref seq) => {
372                 for next_m in &seq.tts {
373                     n_rec(sess, next_m, res.by_ref(), ret_val)?
374                 }
375             }
376             TokenTree::Delimited(_, ref delim) => {
377                 for next_m in &delim.tts {
378                     n_rec(sess, next_m, res.by_ref(), ret_val)?;
379                 }
380             }
381             TokenTree::MetaVarDecl(sp, bind_name, _) => match ret_val
382                 .entry(MacroRulesNormalizedIdent::new(bind_name))
383             {
384                 Vacant(spot) => {
385                     spot.insert(res.next().unwrap());
386                 }
387                 Occupied(..) => return Err((sp, format!("duplicated bind name: {}", bind_name))),
388             },
389             TokenTree::MetaVar(..) | TokenTree::Token(..) => (),
390         }
391
392         Ok(())
393     }
394
395     let mut ret_val = FxHashMap::default();
396     for m in ms {
397         match n_rec(sess, m, res.by_ref(), &mut ret_val) {
398             Ok(_) => {}
399             Err((sp, msg)) => return Error(sp, msg),
400         }
401     }
402
403     Success(ret_val)
404 }
405
406 /// Performs a token equality check, ignoring syntax context (that is, an unhygienic comparison)
407 fn token_name_eq(t1: &Token, t2: &Token) -> bool {
408     if let (Some((ident1, is_raw1)), Some((ident2, is_raw2))) = (t1.ident(), t2.ident()) {
409         ident1.name == ident2.name && is_raw1 == is_raw2
410     } else if let (Some(ident1), Some(ident2)) = (t1.lifetime(), t2.lifetime()) {
411         ident1.name == ident2.name
412     } else {
413         t1.kind == t2.kind
414     }
415 }
416
417 /// Process the matcher positions of `cur_items` until it is empty. In the process, this will
418 /// produce more items in `next_items`, `eof_items`, and `bb_items`.
419 ///
420 /// For more info about the how this happens, see the module-level doc comments and the inline
421 /// comments of this function.
422 ///
423 /// # Parameters
424 ///
425 /// - `sess`: the parsing session into which errors are emitted.
426 /// - `cur_items`: the set of current items to be processed. This should be empty by the end of a
427 ///   successful execution of this function.
428 /// - `next_items`: the set of newly generated items. These are used to replenish `cur_items` in
429 ///   the function `parse`.
430 /// - `eof_items`: the set of items that would be valid if this was the EOF.
431 /// - `bb_items`: the set of items that are waiting for the black-box parser.
432 /// - `token`: the current token of the parser.
433 /// - `span`: the `Span` in the source code corresponding to the token trees we are trying to match
434 ///   against the matcher positions in `cur_items`.
435 ///
436 /// # Returns
437 ///
438 /// A `ParseResult`. Note that matches are kept track of through the items generated.
439 fn inner_parse_loop<'root, 'tt>(
440     cur_items: &mut SmallVec<[MatcherPosHandle<'root, 'tt>; 1]>,
441     next_items: &mut Vec<MatcherPosHandle<'root, 'tt>>,
442     eof_items: &mut SmallVec<[MatcherPosHandle<'root, 'tt>; 1]>,
443     bb_items: &mut SmallVec<[MatcherPosHandle<'root, 'tt>; 1]>,
444     token: &Token,
445 ) -> ParseResult<()> {
446     // Pop items from `cur_items` until it is empty.
447     while let Some(mut item) = cur_items.pop() {
448         // When unzipped trees end, remove them. This corresponds to backtracking out of a
449         // delimited submatcher into which we already descended. In backtracking out again, we need
450         // to advance the "dot" past the delimiters in the outer matcher.
451         while item.idx >= item.top_elts.len() {
452             match item.stack.pop() {
453                 Some(MatcherTtFrame { elts, idx }) => {
454                     item.top_elts = elts;
455                     item.idx = idx + 1;
456                 }
457                 None => break,
458             }
459         }
460
461         // Get the current position of the "dot" (`idx`) in `item` and the number of token trees in
462         // the matcher (`len`).
463         let idx = item.idx;
464         let len = item.top_elts.len();
465
466         // If `idx >= len`, then we are at or past the end of the matcher of `item`.
467         if idx >= len {
468             // We are repeating iff there is a parent. If the matcher is inside of a repetition,
469             // then we could be at the end of a sequence or at the beginning of the next
470             // repetition.
471             if item.up.is_some() {
472                 // At this point, regardless of whether there is a separator, we should add all
473                 // matches from the complete repetition of the sequence to the shared, top-level
474                 // `matches` list (actually, `up.matches`, which could itself not be the top-level,
475                 // but anyway...). Moreover, we add another item to `cur_items` in which the "dot"
476                 // is at the end of the `up` matcher. This ensures that the "dot" in the `up`
477                 // matcher is also advanced sufficiently.
478                 //
479                 // NOTE: removing the condition `idx == len` allows trailing separators.
480                 if idx == len {
481                     // Get the `up` matcher
482                     let mut new_pos = item.up.clone().unwrap();
483
484                     // Add matches from this repetition to the `matches` of `up`
485                     for idx in item.match_lo..item.match_hi {
486                         let sub = item.matches[idx].clone();
487                         new_pos.push_match(idx, MatchedSeq(sub));
488                     }
489
490                     // Move the "dot" past the repetition in `up`
491                     new_pos.match_cur = item.match_hi;
492                     new_pos.idx += 1;
493                     cur_items.push(new_pos);
494                 }
495
496                 // Check if we need a separator.
497                 if idx == len && item.sep.is_some() {
498                     // We have a separator, and it is the current token. We can advance past the
499                     // separator token.
500                     if item.sep.as_ref().map(|sep| token_name_eq(token, sep)).unwrap_or(false) {
501                         item.idx += 1;
502                         next_items.push(item);
503                     }
504                 }
505                 // We don't need a separator. Move the "dot" back to the beginning of the matcher
506                 // and try to match again UNLESS we are only allowed to have _one_ repetition.
507                 else if item.seq_op != Some(mbe::KleeneOp::ZeroOrOne) {
508                     item.match_cur = item.match_lo;
509                     item.idx = 0;
510                     cur_items.push(item);
511                 }
512             }
513             // If we are not in a repetition, then being at the end of a matcher means that we have
514             // reached the potential end of the input.
515             else {
516                 eof_items.push(item);
517             }
518         }
519         // We are in the middle of a matcher.
520         else {
521             // Look at what token in the matcher we are trying to match the current token (`token`)
522             // against. Depending on that, we may generate new items.
523             match item.top_elts.get_tt(idx) {
524                 // Need to descend into a sequence
525                 TokenTree::Sequence(sp, seq) => {
526                     // Examine the case where there are 0 matches of this sequence. We are
527                     // implicitly disallowing OneOrMore from having 0 matches here. Thus, that will
528                     // result in a "no rules expected token" error by virtue of this matcher not
529                     // working.
530                     if seq.kleene.op == mbe::KleeneOp::ZeroOrMore
531                         || seq.kleene.op == mbe::KleeneOp::ZeroOrOne
532                     {
533                         let mut new_item = item.clone();
534                         new_item.match_cur += seq.num_captures;
535                         new_item.idx += 1;
536                         for idx in item.match_cur..item.match_cur + seq.num_captures {
537                             new_item.push_match(idx, MatchedSeq(Lrc::new(smallvec![])));
538                         }
539                         cur_items.push(new_item);
540                     }
541
542                     let matches = create_matches(item.matches.len());
543                     cur_items.push(MatcherPosHandle::Box(Box::new(MatcherPos {
544                         stack: smallvec![],
545                         sep: seq.separator.clone(),
546                         seq_op: Some(seq.kleene.op),
547                         idx: 0,
548                         matches,
549                         match_lo: item.match_cur,
550                         match_cur: item.match_cur,
551                         match_hi: item.match_cur + seq.num_captures,
552                         up: Some(item),
553                         top_elts: Tt(TokenTree::Sequence(sp, seq)),
554                     })));
555                 }
556
557                 // We need to match a metavar with a valid ident... call out to the black-box
558                 // parser by adding an item to `bb_items`.
559                 TokenTree::MetaVarDecl(_, _, kind) => {
560                     // Built-in nonterminals never start with these tokens,
561                     // so we can eliminate them from consideration.
562                     if Parser::nonterminal_may_begin_with(kind, token) {
563                         bb_items.push(item);
564                     }
565                 }
566
567                 // We need to descend into a delimited submatcher or a doc comment. To do this, we
568                 // push the current matcher onto a stack and push a new item containing the
569                 // submatcher onto `cur_items`.
570                 //
571                 // At the beginning of the loop, if we reach the end of the delimited submatcher,
572                 // we pop the stack to backtrack out of the descent.
573                 seq
574                 @
575                 (TokenTree::Delimited(..)
576                 | TokenTree::Token(Token { kind: DocComment(..), .. })) => {
577                     let lower_elts = mem::replace(&mut item.top_elts, Tt(seq));
578                     let idx = item.idx;
579                     item.stack.push(MatcherTtFrame { elts: lower_elts, idx });
580                     item.idx = 0;
581                     cur_items.push(item);
582                 }
583
584                 // We just matched a normal token. We can just advance the parser.
585                 TokenTree::Token(t) if token_name_eq(&t, token) => {
586                     item.idx += 1;
587                     next_items.push(item);
588                 }
589
590                 // There was another token that was not `token`... This means we can't add any
591                 // rules. NOTE that this is not necessarily an error unless _all_ items in
592                 // `cur_items` end up doing this. There may still be some other matchers that do
593                 // end up working out.
594                 TokenTree::Token(..) | TokenTree::MetaVar(..) => {}
595             }
596         }
597     }
598
599     // Yay a successful parse (so far)!
600     Success(())
601 }
602
603 /// Use the given sequence of token trees (`ms`) as a matcher. Match the token
604 /// stream from the given `parser` against it and return the match.
605 pub(super) fn parse_tt(parser: &mut Cow<'_, Parser<'_>>, ms: &[TokenTree]) -> NamedParseResult {
606     // A queue of possible matcher positions. We initialize it with the matcher position in which
607     // the "dot" is before the first token of the first token tree in `ms`. `inner_parse_loop` then
608     // processes all of these possible matcher positions and produces possible next positions into
609     // `next_items`. After some post-processing, the contents of `next_items` replenish `cur_items`
610     // and we start over again.
611     //
612     // This MatcherPos instance is allocated on the stack. All others -- and
613     // there are frequently *no* others! -- are allocated on the heap.
614     let mut initial = initial_matcher_pos(ms);
615     let mut cur_items = smallvec![MatcherPosHandle::Ref(&mut initial)];
616     let mut next_items = Vec::new();
617
618     loop {
619         // Matcher positions black-box parsed by parser.rs (`parser`)
620         let mut bb_items = SmallVec::new();
621
622         // Matcher positions that would be valid if the macro invocation was over now
623         let mut eof_items = SmallVec::new();
624         assert!(next_items.is_empty());
625
626         // Process `cur_items` until either we have finished the input or we need to get some
627         // parsing from the black-box parser done. The result is that `next_items` will contain a
628         // bunch of possible next matcher positions in `next_items`.
629         match inner_parse_loop(
630             &mut cur_items,
631             &mut next_items,
632             &mut eof_items,
633             &mut bb_items,
634             &parser.token,
635         ) {
636             Success(_) => {}
637             Failure(token, msg) => return Failure(token, msg),
638             Error(sp, msg) => return Error(sp, msg),
639             ErrorReported => return ErrorReported,
640         }
641
642         // inner parse loop handled all cur_items, so it's empty
643         assert!(cur_items.is_empty());
644
645         // We need to do some post processing after the `inner_parser_loop`.
646         //
647         // Error messages here could be improved with links to original rules.
648
649         // If we reached the EOF, check that there is EXACTLY ONE possible matcher. Otherwise,
650         // either the parse is ambiguous (which should never happen) or there is a syntax error.
651         if parser.token == token::Eof {
652             if eof_items.len() == 1 {
653                 let matches =
654                     eof_items[0].matches.iter_mut().map(|dv| Lrc::make_mut(dv).pop().unwrap());
655                 return nameize(parser.sess, ms, matches);
656             } else if eof_items.len() > 1 {
657                 return Error(
658                     parser.token.span,
659                     "ambiguity: multiple successful parses".to_string(),
660                 );
661             } else {
662                 return Failure(
663                     Token::new(
664                         token::Eof,
665                         if parser.token.span.is_dummy() {
666                             parser.token.span
667                         } else {
668                             parser.token.span.shrink_to_hi()
669                         },
670                     ),
671                     "missing tokens in macro arguments",
672                 );
673             }
674         }
675         // Performance hack: eof_items may share matchers via Rc with other things that we want
676         // to modify. Dropping eof_items now may drop these refcounts to 1, preventing an
677         // unnecessary implicit clone later in Rc::make_mut.
678         drop(eof_items);
679
680         // If there are no possible next positions AND we aren't waiting for the black-box parser,
681         // then there is a syntax error.
682         if bb_items.is_empty() && next_items.is_empty() {
683             return Failure(parser.token.clone(), "no rules expected this token in macro call");
684         }
685         // Another possibility is that we need to call out to parse some rust nonterminal
686         // (black-box) parser. However, if there is not EXACTLY ONE of these, something is wrong.
687         else if (!bb_items.is_empty() && !next_items.is_empty()) || bb_items.len() > 1 {
688             let nts = bb_items
689                 .iter()
690                 .map(|item| match item.top_elts.get_tt(item.idx) {
691                     TokenTree::MetaVarDecl(_, bind, kind) => format!("{} ('{}')", kind, bind),
692                     _ => panic!(),
693                 })
694                 .collect::<Vec<String>>()
695                 .join(" or ");
696
697             return Error(
698                 parser.token.span,
699                 format!(
700                     "local ambiguity: multiple parsing options: {}",
701                     match next_items.len() {
702                         0 => format!("built-in NTs {}.", nts),
703                         1 => format!("built-in NTs {} or 1 other option.", nts),
704                         n => format!("built-in NTs {} or {} other options.", nts, n),
705                     }
706                 ),
707             );
708         }
709         // Dump all possible `next_items` into `cur_items` for the next iteration.
710         else if !next_items.is_empty() {
711             // Now process the next token
712             cur_items.extend(next_items.drain(..));
713             parser.to_mut().bump();
714         }
715         // Finally, we have the case where we need to call the black-box parser to get some
716         // nonterminal.
717         else {
718             assert_eq!(bb_items.len(), 1);
719
720             let mut item = bb_items.pop().unwrap();
721             if let TokenTree::MetaVarDecl(span, _, kind) = item.top_elts.get_tt(item.idx) {
722                 let match_cur = item.match_cur;
723                 let nt = match parser.to_mut().parse_nonterminal(kind) {
724                     Err(mut err) => {
725                         err.span_label(
726                             span,
727                             format!("while parsing argument for this `{}` macro fragment", kind),
728                         )
729                         .emit();
730                         return ErrorReported;
731                     }
732                     Ok(nt) => nt,
733                 };
734                 item.push_match(match_cur, MatchedNonterminal(Lrc::new(nt)));
735                 item.idx += 1;
736                 item.match_cur += 1;
737             } else {
738                 unreachable!()
739             }
740             cur_items.push(item);
741         }
742
743         assert!(!cur_items.is_empty());
744     }
745 }