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