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.
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)
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.
15 //! Quick intro to how the parser works:
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`.
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`.
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.
34 //! Start parsing a a a a b against [· a $( a )* a b].
36 //! Remaining input: a a a a b
37 //! next: [· a $( a )* a b]
39 //! - - - Advance over an a. - - -
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].
46 //! - - - Advance over an a. - - -
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]
53 //! - - - Advance over an a. - - - (this looks exactly like the last step)
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]
60 //! - - - Advance over an a. - - - (this looks exactly like the last step)
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]
67 //! - - - Advance over a b. - - -
69 //! Remaining input: ''
70 //! eof: [a $( a )* a b ·]
73 crate use NamedMatch::*;
74 crate use ParseResult::*;
75 use TokenTreeOrTokenTreeSlice::*;
77 use crate::mbe::{self, TokenTree};
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;
84 use smallvec::{smallvec, SmallVec};
86 use rustc_data_structures::fx::FxHashMap;
87 use rustc_data_structures::sync::Lrc;
88 use rustc_span::symbol::Ident;
90 use std::collections::hash_map::Entry::{Occupied, Vacant};
92 use std::ops::{Deref, DerefMut};
94 // To avoid costly uniqueness checks, we require that `MatchSeq` always has a nonempty body.
96 /// Either a sequence of token trees or a single one. This is used as the representation of the
97 /// sequence of tokens that make up a matcher.
99 enum TokenTreeOrTokenTreeSlice<'tt> {
101 TtSeq(&'tt [TokenTree]),
104 impl<'tt> TokenTreeOrTokenTreeSlice<'tt> {
105 /// Returns the number of constituent top-level token trees of `self` (top-level in that it
106 /// will not recursively descend into subtrees).
107 fn len(&self) -> usize {
109 TtSeq(ref v) => v.len(),
110 Tt(ref tt) => tt.len(),
114 /// The `index`-th token tree of `self`.
115 fn get_tt(&self, index: usize) -> TokenTree {
117 TtSeq(ref v) => v[index].clone(),
118 Tt(ref tt) => tt.get_tt(index),
123 /// An unzipping of `TokenTree`s... see the `stack` field of `MatcherPos`.
125 /// This is used by `inner_parse_loop` to keep track of delimited submatchers that we have
128 struct MatcherTtFrame<'tt> {
129 /// The "parent" matcher that we are descending into.
130 elts: TokenTreeOrTokenTreeSlice<'tt>,
131 /// The position of the "dot" in `elts` at the time we descended.
135 type NamedMatchVec = SmallVec<[NamedMatch; 4]>;
137 /// Represents a single "position" (aka "matcher position", aka "item"), as
138 /// described in the module documentation.
142 /// - `'root` represents the lifetime of the stack slot that holds the root
143 /// `MatcherPos`. As described in `MatcherPosHandle`, the root `MatcherPos`
144 /// structure is stored on the stack, but subsequent instances are put into
146 /// - `'tt` represents the lifetime of the token trees that this matcher
147 /// position refers to.
149 /// It is important to distinguish these two lifetimes because we have a
150 /// `SmallVec<TokenTreeOrTokenTreeSlice<'tt>>` below, and the destructor of
151 /// that is considered to possibly access the data from its elements (it lacks
152 /// a `#[may_dangle]` attribute). As a result, the compiler needs to know that
153 /// all the elements in that `SmallVec` strictly outlive the root stack slot
154 /// lifetime. By separating `'tt` from `'root`, we can show that.
156 struct MatcherPos<'root, 'tt> {
157 /// The token or sequence of tokens that make up the matcher
158 top_elts: TokenTreeOrTokenTreeSlice<'tt>,
160 /// The position of the "dot" in this matcher
163 /// For each named metavar in the matcher, we keep track of token trees matched against the
164 /// metavar by the black box parser. In particular, there may be more than one match per
165 /// metavar if we are in a repetition (each repetition matches each of the variables).
166 /// Moreover, matchers and repetitions can be nested; the `matches` field is shared (hence the
167 /// `Rc`) among all "nested" matchers. `match_lo`, `match_cur`, and `match_hi` keep track of
168 /// the current position of the `self` matcher position in the shared `matches` list.
170 /// Also, note that while we are descending into a sequence, matchers are given their own
171 /// `matches` vector. Only once we reach the end of a full repetition of the sequence do we add
172 /// all bound matches from the submatcher into the shared top-level `matches` vector. If `sep`
173 /// and `up` are `Some`, then `matches` is _not_ the shared top-level list. Instead, if one
174 /// wants the shared `matches`, one should use `up.matches`.
175 matches: Box<[Lrc<NamedMatchVec>]>,
176 /// The position in `matches` corresponding to the first metavar in this matcher's sequence of
177 /// token trees. In other words, the first metavar in the first token of `top_elts` corresponds
178 /// to `matches[match_lo]`.
180 /// The position in `matches` corresponding to the metavar we are currently trying to match
181 /// against the source token stream. `match_lo <= match_cur <= match_hi`.
183 /// Similar to `match_lo` except `match_hi` is the position in `matches` of the _last_ metavar
187 // The following fields are used if we are matching a repetition. If we aren't, they should be
189 /// The KleeneOp of this sequence if we are in a repetition.
190 seq_op: Option<mbe::KleeneOp>,
192 /// The separator if we are in a repetition.
195 /// The "parent" matcher position if we are in a repetition. That is, the matcher position just
196 /// before we enter the sequence.
197 up: Option<MatcherPosHandle<'root, 'tt>>,
199 /// Specifically used to "unzip" token trees. By "unzip", we mean to unwrap the delimiters from
200 /// a delimited token tree (e.g., something wrapped in `(` `)`) or to get the contents of a doc
203 /// When matching against matchers with nested delimited submatchers (e.g., `pat ( pat ( .. )
204 /// pat ) pat`), we need to keep track of the matchers we are descending into. This stack does
205 /// that where the bottom of the stack is the outermost matcher.
206 /// Also, throughout the comments, this "descent" is often referred to as "unzipping"...
207 stack: SmallVec<[MatcherTtFrame<'tt>; 1]>,
210 impl<'root, 'tt> MatcherPos<'root, 'tt> {
211 /// Adds `m` as a named match for the `idx`-th metavar.
212 fn push_match(&mut self, idx: usize, m: NamedMatch) {
213 let matches = Lrc::make_mut(&mut self.matches[idx]);
218 // Lots of MatcherPos instances are created at runtime. Allocating them on the
219 // heap is slow. Furthermore, using SmallVec<MatcherPos> to allocate them all
220 // on the stack is also slow, because MatcherPos is quite a large type and
221 // instances get moved around a lot between vectors, which requires lots of
222 // slow memcpy calls.
224 // Therefore, the initial MatcherPos is always allocated on the stack,
225 // subsequent ones (of which there aren't that many) are allocated on the heap,
226 // and this type is used to encapsulate both cases.
227 enum MatcherPosHandle<'root, 'tt> {
228 Ref(&'root mut MatcherPos<'root, 'tt>),
229 Box(Box<MatcherPos<'root, 'tt>>),
232 impl<'root, 'tt> Clone for MatcherPosHandle<'root, 'tt> {
233 // This always produces a new Box.
234 fn clone(&self) -> Self {
235 MatcherPosHandle::Box(match *self {
236 MatcherPosHandle::Ref(ref r) => Box::new((**r).clone()),
237 MatcherPosHandle::Box(ref b) => b.clone(),
242 impl<'root, 'tt> Deref for MatcherPosHandle<'root, 'tt> {
243 type Target = MatcherPos<'root, 'tt>;
244 fn deref(&self) -> &Self::Target {
246 MatcherPosHandle::Ref(ref r) => r,
247 MatcherPosHandle::Box(ref b) => b,
252 impl<'root, 'tt> DerefMut for MatcherPosHandle<'root, 'tt> {
253 fn deref_mut(&mut self) -> &mut MatcherPos<'root, 'tt> {
255 MatcherPosHandle::Ref(ref mut r) => r,
256 MatcherPosHandle::Box(ref mut b) => b,
261 /// Represents the possible results of an attempted parse.
262 crate enum ParseResult<T> {
263 /// Parsed successfully.
265 /// Arm failed to match. If the second parameter is `token::Eof`, it indicates an unexpected
266 /// end of macro invocation. Otherwise, it indicates that no rules expected the given token.
267 Failure(Token, &'static str),
268 /// Fatal error (malformed macro?). Abort compilation.
269 Error(rustc_span::Span, String),
273 /// A `ParseResult` where the `Success` variant contains a mapping of
274 /// `MacroRulesNormalizedIdent`s to `NamedMatch`es. This represents the mapping
275 /// of metavars to the token trees they bind to.
276 crate type NamedParseResult = ParseResult<FxHashMap<MacroRulesNormalizedIdent, NamedMatch>>;
278 /// Count how many metavars are named in the given matcher `ms`.
279 pub(super) fn count_names(ms: &[TokenTree]) -> usize {
280 ms.iter().fold(0, |count, elt| {
283 TokenTree::Sequence(_, ref seq) => seq.num_captures,
284 TokenTree::Delimited(_, ref delim) => count_names(&delim.tts),
285 TokenTree::MetaVar(..) => 0,
286 TokenTree::MetaVarDecl(..) => 1,
287 TokenTree::Token(..) => 0,
292 /// `len` `Vec`s (initially shared and empty) that will store matches of metavars.
293 fn create_matches(len: usize) -> Box<[Lrc<NamedMatchVec>]> {
297 let empty_matches = Lrc::new(SmallVec::new());
298 vec![empty_matches; len]
303 /// Generates the top-level matcher position in which the "dot" is before the first token of the
305 fn initial_matcher_pos<'root, 'tt>(ms: &'tt [TokenTree]) -> MatcherPos<'root, 'tt> {
306 let match_idx_hi = count_names(ms);
307 let matches = create_matches(match_idx_hi);
309 // Start with the top level matcher given to us
310 top_elts: TtSeq(ms), // "elts" is an abbr. for "elements"
311 // The "dot" is before the first token of the matcher
314 // Initialize `matches` to a bunch of empty `Vec`s -- one for each metavar in `top_elts`.
315 // `match_lo` for `top_elts` is 0 and `match_hi` is `matches.len()`. `match_cur` is 0 since
316 // we haven't actually matched anything yet.
320 match_hi: match_idx_hi,
322 // Haven't descended into any delimiters, so empty stack
325 // Haven't descended into any sequences, so both of these are `None`.
332 /// `NamedMatch` is a pattern-match result for a single `token::MATCH_NONTERMINAL`:
333 /// so it is associated with a single ident in a parse, and all
334 /// `MatchedNonterminal`s in the `NamedMatch` have the same non-terminal type
335 /// (expr, item, etc). Each leaf in a single `NamedMatch` corresponds to a
336 /// single `token::MATCH_NONTERMINAL` in the `TokenTree` that produced it.
338 /// The in-memory structure of a particular `NamedMatch` represents the match
339 /// that occurred when a particular subset of a matcher was applied to a
340 /// particular token tree.
342 /// The width of each `MatchedSeq` in the `NamedMatch`, and the identity of
343 /// the `MatchedNonterminal`s, will depend on the token tree it was applied
344 /// to: each `MatchedSeq` corresponds to a single `TTSeq` in the originating
345 /// token tree. The depth of the `NamedMatch` structure will therefore depend
346 /// only on the nesting depth of `ast::TTSeq`s in the originating
347 /// token tree it was derived from.
349 /// In layman's terms: `NamedMatch` will form a tree representing nested matches of a particular
350 /// meta variable. For example, if we are matching the following macro against the following
354 /// macro_rules! foo {
355 /// ($($($x:ident),+);+) => {}
358 /// foo!(a, b, c, d; a, b, c, d, e);
361 /// Then, the tree will have the following shape:
366 /// MatchedNonterminal(a),
367 /// MatchedNonterminal(b),
368 /// MatchedNonterminal(c),
369 /// MatchedNonterminal(d),
372 /// MatchedNonterminal(a),
373 /// MatchedNonterminal(b),
374 /// MatchedNonterminal(c),
375 /// MatchedNonterminal(d),
376 /// MatchedNonterminal(e),
380 #[derive(Debug, Clone)]
381 crate enum NamedMatch {
382 MatchedSeq(Lrc<NamedMatchVec>),
383 MatchedNonterminal(Lrc<Nonterminal>),
386 /// Takes a sequence of token trees `ms` representing a matcher which successfully matched input
387 /// and an iterator of items that matched input and produces a `NamedParseResult`.
388 fn nameize<I: Iterator<Item = NamedMatch>>(
392 ) -> NamedParseResult {
393 // Recursively descend into each type of matcher (e.g., sequences, delimited, metavars) and make
394 // sure that each metavar has _exactly one_ binding. If a metavar does not have exactly one
395 // binding, then there is an error. If it does, then we insert the binding into the
396 // `NamedParseResult`.
397 fn n_rec<I: Iterator<Item = NamedMatch>>(
401 ret_val: &mut FxHashMap<MacroRulesNormalizedIdent, NamedMatch>,
402 ) -> Result<(), (rustc_span::Span, String)> {
404 TokenTree::Sequence(_, ref seq) => {
405 for next_m in &seq.tts {
406 n_rec(sess, next_m, res.by_ref(), ret_val)?
409 TokenTree::Delimited(_, ref delim) => {
410 for next_m in &delim.tts {
411 n_rec(sess, next_m, res.by_ref(), ret_val)?;
414 TokenTree::MetaVarDecl(span, _, None) => {
415 if sess.missing_fragment_specifiers.borrow_mut().remove(&span).is_some() {
416 return Err((span, "missing fragment specifier".to_string()));
419 TokenTree::MetaVarDecl(sp, bind_name, _) => match ret_val
420 .entry(MacroRulesNormalizedIdent::new(bind_name))
423 spot.insert(res.next().unwrap());
425 Occupied(..) => return Err((sp, format!("duplicated bind name: {}", bind_name))),
427 TokenTree::MetaVar(..) | TokenTree::Token(..) => (),
433 let mut ret_val = FxHashMap::default();
435 match n_rec(sess, m, res.by_ref(), &mut ret_val) {
437 Err((sp, msg)) => return Error(sp, msg),
444 /// Performs a token equality check, ignoring syntax context (that is, an unhygienic comparison)
445 fn token_name_eq(t1: &Token, t2: &Token) -> bool {
446 if let (Some((ident1, is_raw1)), Some((ident2, is_raw2))) = (t1.ident(), t2.ident()) {
447 ident1.name == ident2.name && is_raw1 == is_raw2
448 } else if let (Some(ident1), Some(ident2)) = (t1.lifetime(), t2.lifetime()) {
449 ident1.name == ident2.name
455 /// Process the matcher positions of `cur_items` until it is empty. In the process, this will
456 /// produce more items in `next_items`, `eof_items`, and `bb_items`.
458 /// For more info about the how this happens, see the module-level doc comments and the inline
459 /// comments of this function.
463 /// - `cur_items`: the set of current items to be processed. This should be empty by the end of a
464 /// successful execution of this function.
465 /// - `next_items`: the set of newly generated items. These are used to replenish `cur_items` in
466 /// the function `parse`.
467 /// - `eof_items`: the set of items that would be valid if this was the EOF.
468 /// - `bb_items`: the set of items that are waiting for the black-box parser.
469 /// - `token`: the current token of the parser.
473 /// A `ParseResult`. Note that matches are kept track of through the items generated.
474 fn inner_parse_loop<'root, 'tt>(
476 cur_items: &mut SmallVec<[MatcherPosHandle<'root, 'tt>; 1]>,
477 next_items: &mut Vec<MatcherPosHandle<'root, 'tt>>,
478 eof_items: &mut SmallVec<[MatcherPosHandle<'root, 'tt>; 1]>,
479 bb_items: &mut SmallVec<[MatcherPosHandle<'root, 'tt>; 1]>,
481 ) -> ParseResult<()> {
482 // Pop items from `cur_items` until it is empty.
483 while let Some(mut item) = cur_items.pop() {
484 // When unzipped trees end, remove them. This corresponds to backtracking out of a
485 // delimited submatcher into which we already descended. In backtracking out again, we need
486 // to advance the "dot" past the delimiters in the outer matcher.
487 while item.idx >= item.top_elts.len() {
488 match item.stack.pop() {
489 Some(MatcherTtFrame { elts, idx }) => {
490 item.top_elts = elts;
497 // Get the current position of the "dot" (`idx`) in `item` and the number of token trees in
498 // the matcher (`len`).
500 let len = item.top_elts.len();
502 // If `idx >= len`, then we are at or past the end of the matcher of `item`.
504 // We are repeating iff there is a parent. If the matcher is inside of a repetition,
505 // then we could be at the end of a sequence or at the beginning of the next
507 if item.up.is_some() {
508 // At this point, regardless of whether there is a separator, we should add all
509 // matches from the complete repetition of the sequence to the shared, top-level
510 // `matches` list (actually, `up.matches`, which could itself not be the top-level,
511 // but anyway...). Moreover, we add another item to `cur_items` in which the "dot"
512 // is at the end of the `up` matcher. This ensures that the "dot" in the `up`
513 // matcher is also advanced sufficiently.
515 // NOTE: removing the condition `idx == len` allows trailing separators.
517 // Get the `up` matcher
518 let mut new_pos = item.up.clone().unwrap();
520 // Add matches from this repetition to the `matches` of `up`
521 for idx in item.match_lo..item.match_hi {
522 let sub = item.matches[idx].clone();
523 new_pos.push_match(idx, MatchedSeq(sub));
526 // Move the "dot" past the repetition in `up`
527 new_pos.match_cur = item.match_hi;
529 cur_items.push(new_pos);
532 // Check if we need a separator.
533 if idx == len && item.sep.is_some() {
534 // We have a separator, and it is the current token. We can advance past the
536 if item.sep.as_ref().map_or(false, |sep| token_name_eq(token, sep)) {
538 next_items.push(item);
541 // We don't need a separator. Move the "dot" back to the beginning of the matcher
542 // and try to match again UNLESS we are only allowed to have _one_ repetition.
543 else if item.seq_op != Some(mbe::KleeneOp::ZeroOrOne) {
544 item.match_cur = item.match_lo;
546 cur_items.push(item);
549 // If we are not in a repetition, then being at the end of a matcher means that we have
550 // reached the potential end of the input.
552 eof_items.push(item);
555 // We are in the middle of a matcher.
557 // Look at what token in the matcher we are trying to match the current token (`token`)
558 // against. Depending on that, we may generate new items.
559 match item.top_elts.get_tt(idx) {
560 // Need to descend into a sequence
561 TokenTree::Sequence(sp, seq) => {
562 // Examine the case where there are 0 matches of this sequence. We are
563 // implicitly disallowing OneOrMore from having 0 matches here. Thus, that will
564 // result in a "no rules expected token" error by virtue of this matcher not
566 if seq.kleene.op == mbe::KleeneOp::ZeroOrMore
567 || seq.kleene.op == mbe::KleeneOp::ZeroOrOne
569 let mut new_item = item.clone();
570 new_item.match_cur += seq.num_captures;
572 for idx in item.match_cur..item.match_cur + seq.num_captures {
573 new_item.push_match(idx, MatchedSeq(Lrc::new(smallvec![])));
575 cur_items.push(new_item);
578 let matches = create_matches(item.matches.len());
579 cur_items.push(MatcherPosHandle::Box(Box::new(MatcherPos {
581 sep: seq.separator.clone(),
582 seq_op: Some(seq.kleene.op),
585 match_lo: item.match_cur,
586 match_cur: item.match_cur,
587 match_hi: item.match_cur + seq.num_captures,
589 top_elts: Tt(TokenTree::Sequence(sp, seq)),
593 // We need to match a metavar (but the identifier is invalid)... this is an error
594 TokenTree::MetaVarDecl(span, _, None) => {
595 if sess.missing_fragment_specifiers.borrow_mut().remove(&span).is_some() {
596 return Error(span, "missing fragment specifier".to_string());
600 // We need to match a metavar with a valid ident... call out to the black-box
601 // parser by adding an item to `bb_items`.
602 TokenTree::MetaVarDecl(_, _, Some(kind)) => {
603 // Built-in nonterminals never start with these tokens, so we can eliminate
604 // them from consideration.
606 // We use the span of the metavariable declaration to determine any
607 // edition-specific matching behavior for non-terminals.
608 if Parser::nonterminal_may_begin_with(kind, token) {
613 // We need to descend into a delimited submatcher or a doc comment. To do this, we
614 // push the current matcher onto a stack and push a new item containing the
615 // submatcher onto `cur_items`.
617 // At the beginning of the loop, if we reach the end of the delimited submatcher,
618 // we pop the stack to backtrack out of the descent.
619 seq @ (TokenTree::Delimited(..)
620 | TokenTree::Token(Token { kind: DocComment(..), .. })) => {
621 let lower_elts = mem::replace(&mut item.top_elts, Tt(seq));
623 item.stack.push(MatcherTtFrame { elts: lower_elts, idx });
625 cur_items.push(item);
628 // We just matched a normal token. We can just advance the parser.
629 TokenTree::Token(t) if token_name_eq(&t, token) => {
631 next_items.push(item);
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(..) => {}
643 // Yay a successful parse (so far)!
647 /// Use the given sequence of token trees (`ms`) as a matcher. Match the token
648 /// stream from the given `parser` against it and return the match.
649 pub(super) fn parse_tt(
650 parser: &mut Cow<'_, Parser<'_>>,
653 ) -> NamedParseResult {
654 // A queue of possible matcher positions. We initialize it with the matcher position in which
655 // the "dot" is before the first token of the first token tree in `ms`. `inner_parse_loop` then
656 // processes all of these possible matcher positions and produces possible next positions into
657 // `next_items`. After some post-processing, the contents of `next_items` replenish `cur_items`
658 // and we start over again.
660 // This MatcherPos instance is allocated on the stack. All others -- and
661 // there are frequently *no* others! -- are allocated on the heap.
662 let mut initial = initial_matcher_pos(ms);
663 let mut cur_items = smallvec![MatcherPosHandle::Ref(&mut initial)];
664 let mut next_items = Vec::new();
667 // Matcher positions black-box parsed by parser.rs (`parser`)
668 let mut bb_items = SmallVec::new();
670 // Matcher positions that would be valid if the macro invocation was over now
671 let mut eof_items = SmallVec::new();
672 assert!(next_items.is_empty());
674 // Process `cur_items` until either we have finished the input or we need to get some
675 // parsing from the black-box parser done. The result is that `next_items` will contain a
676 // bunch of possible next matcher positions in `next_items`.
677 match inner_parse_loop(
686 Failure(token, msg) => return Failure(token, msg),
687 Error(sp, msg) => return Error(sp, msg),
688 ErrorReported => return ErrorReported,
691 // inner parse loop handled all cur_items, so it's empty
692 assert!(cur_items.is_empty());
694 // We need to do some post processing after the `inner_parser_loop`.
696 // Error messages here could be improved with links to original rules.
698 // If we reached the EOF, check that there is EXACTLY ONE possible matcher. Otherwise,
699 // either the parse is ambiguous (which should never happen) or there is a syntax error.
700 if parser.token == token::Eof {
701 if eof_items.len() == 1 {
703 eof_items[0].matches.iter_mut().map(|dv| Lrc::make_mut(dv).pop().unwrap());
704 return nameize(parser.sess, ms, matches);
705 } else if eof_items.len() > 1 {
708 "ambiguity: multiple successful parses".to_string(),
714 if parser.token.span.is_dummy() {
717 parser.token.span.shrink_to_hi()
720 "missing tokens in macro arguments",
724 // Performance hack: eof_items may share matchers via Rc with other things that we want
725 // to modify. Dropping eof_items now may drop these refcounts to 1, preventing an
726 // unnecessary implicit clone later in Rc::make_mut.
729 // If there are no possible next positions AND we aren't waiting for the black-box parser,
730 // then there is a syntax error.
731 if bb_items.is_empty() && next_items.is_empty() {
732 return Failure(parser.token.clone(), "no rules expected this token in macro call");
734 // Another possibility is that we need to call out to parse some rust nonterminal
735 // (black-box) parser. However, if there is not EXACTLY ONE of these, something is wrong.
736 else if (!bb_items.is_empty() && !next_items.is_empty()) || bb_items.len() > 1 {
739 .map(|item| match item.top_elts.get_tt(item.idx) {
740 TokenTree::MetaVarDecl(_, bind, Some(kind)) => format!("{} ('{}')", kind, bind),
743 .collect::<Vec<String>>()
749 "local ambiguity when calling macro `{macro_name}`: multiple parsing options: {}",
750 match next_items.len() {
751 0 => format!("built-in NTs {}.", nts),
752 1 => format!("built-in NTs {} or 1 other option.", nts),
753 n => format!("built-in NTs {} or {} other options.", nts, n),
758 // Dump all possible `next_items` into `cur_items` for the next iteration.
759 else if !next_items.is_empty() {
760 // Now process the next token
761 cur_items.extend(next_items.drain(..));
762 parser.to_mut().bump();
764 // Finally, we have the case where we need to call the black-box parser to get some
767 assert_eq!(bb_items.len(), 1);
769 let mut item = bb_items.pop().unwrap();
770 if let TokenTree::MetaVarDecl(span, _, Some(kind)) = item.top_elts.get_tt(item.idx) {
771 let match_cur = item.match_cur;
772 // We use the span of the metavariable declaration to determine any
773 // edition-specific matching behavior for non-terminals.
774 let nt = match parser.to_mut().parse_nonterminal(kind) {
778 format!("while parsing argument for this `{}` macro fragment", kind),
781 return ErrorReported;
785 item.push_match(match_cur, MatchedNonterminal(Lrc::new(nt)));
791 cur_items.push(item);
794 assert!(!cur_items.is_empty());