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