1 // Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! This is an NFA-based parser, which calls out to the main rust parser for named nonterminals
12 //! (which it commits to fully when it hits one in a grammar). There's a set of current NFA threads
13 //! and a set of next ones. Instead of NTs, we have a special case for Kleene star. The big-O, in
14 //! pathological cases, is worse than traditional use of NFA or Earley parsing, but it's an easier
15 //! fit for Macro-by-Example-style rules.
17 //! (In order to prevent the pathological case, we'd need to lazily construct the resulting
18 //! `NamedMatch`es at the very end. It'd be a pain, and require more memory to keep around old
19 //! items, but it would also save overhead)
21 //! We don't say this parser uses the Earley algorithm, because it's unnecessarily innacurate.
22 //! The macro parser restricts itself to the features of finite state automata. Earley parsers
23 //! can be described as an extension of NFAs with completion rules, prediction rules, and recursion.
25 //! Quick intro to how the parser works:
27 //! A 'position' is a dot in the middle of a matcher, usually represented as a
28 //! dot. For example `· a $( a )* a b` is a position, as is `a $( · a )* a b`.
30 //! The parser walks through the input a character at a time, maintaining a list
31 //! of threads consistent with the current position in the input string: `cur_items`.
33 //! As it processes them, it fills up `eof_items` with threads that would be valid if
34 //! the macro invocation is now over, `bb_items` with threads that are waiting on
35 //! a Rust nonterminal like `$e:expr`, and `next_items` with threads that are waiting
36 //! on a particular token. Most of the logic concerns moving the · through the
37 //! repetitions indicated by Kleene stars. The rules for moving the · without
38 //! consuming any input are called epsilon transitions. It only advances or calls
39 //! out to the real Rust parser when no `cur_items` threads remain.
44 //! Start parsing a a a a b against [· a $( a )* a b].
46 //! Remaining input: a a a a b
47 //! next: [· a $( a )* a b]
49 //! - - - Advance over an a. - - -
51 //! Remaining input: a a a b
52 //! cur: [a · $( a )* a b]
53 //! Descend/Skip (first item).
54 //! next: [a $( · a )* a b] [a $( a )* · a b].
56 //! - - - Advance over an a. - - -
58 //! Remaining input: a a b
59 //! cur: [a $( a · )* a b] [a $( a )* a · b]
60 //! Follow epsilon transition: Finish/Repeat (first item)
61 //! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b]
63 //! - - - Advance over an a. - - - (this looks exactly like the last step)
65 //! Remaining input: a b
66 //! cur: [a $( a · )* a b] [a $( a )* a · b]
67 //! Follow epsilon transition: Finish/Repeat (first item)
68 //! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b]
70 //! - - - Advance over an a. - - - (this looks exactly like the last step)
72 //! Remaining input: b
73 //! cur: [a $( a · )* a b] [a $( a )* a · b]
74 //! Follow epsilon transition: Finish/Repeat (first item)
75 //! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b]
77 //! - - - Advance over a b. - - -
79 //! Remaining input: ''
80 //! eof: [a $( a )* a b ·]
83 pub use self::NamedMatch::*;
84 pub use self::ParseResult::*;
85 use self::TokenTreeOrTokenTreeVec::*;
88 use syntax_pos::{self, BytePos, Span};
90 use errors::FatalError;
91 use ext::tt::quoted::{self, TokenTree};
92 use parse::{Directory, ParseSess};
93 use parse::parser::{PathStyle, Parser};
94 use parse::token::{self, DocComment, Token, Nonterminal};
97 use tokenstream::TokenStream;
98 use util::small_vector::SmallVector;
102 use std::collections::HashMap;
103 use std::collections::hash_map::Entry::{Vacant, Occupied};
105 // To avoid costly uniqueness checks, we require that `MatchSeq` always has
109 enum TokenTreeOrTokenTreeVec {
111 TtSeq(Vec<TokenTree>),
114 impl TokenTreeOrTokenTreeVec {
115 fn len(&self) -> usize {
117 TtSeq(ref v) => v.len(),
118 Tt(ref tt) => tt.len(),
122 fn get_tt(&self, index: usize) -> TokenTree {
124 TtSeq(ref v) => v[index].clone(),
125 Tt(ref tt) => tt.get_tt(index),
130 /// an unzipping of `TokenTree`s
132 struct MatcherTtFrame {
133 elts: TokenTreeOrTokenTreeVec,
139 stack: Vec<MatcherTtFrame>,
140 top_elts: TokenTreeOrTokenTreeVec,
143 up: Option<Box<MatcherPos>>,
144 matches: Vec<Rc<Vec<NamedMatch>>>,
152 fn push_match(&mut self, idx: usize, m: NamedMatch) {
153 let matches = Rc::make_mut(&mut self.matches[idx]);
158 pub type NamedParseResult = ParseResult<HashMap<Ident, Rc<NamedMatch>>>;
160 pub fn count_names(ms: &[TokenTree]) -> usize {
161 ms.iter().fold(0, |count, elt| {
163 TokenTree::Sequence(_, ref seq) => seq.num_captures,
164 TokenTree::Delimited(_, ref delim) => count_names(&delim.tts),
165 TokenTree::MetaVar(..) => 0,
166 TokenTree::MetaVarDecl(..) => 1,
167 TokenTree::Token(..) => 0,
172 fn initial_matcher_pos(ms: Vec<TokenTree>, lo: BytePos) -> Box<MatcherPos> {
173 let match_idx_hi = count_names(&ms[..]);
174 let matches = create_matches(match_idx_hi);
175 Box::new(MatcherPos {
184 match_hi: match_idx_hi,
189 /// `NamedMatch` is a pattern-match result for a single `token::MATCH_NONTERMINAL`:
190 /// so it is associated with a single ident in a parse, and all
191 /// `MatchedNonterminal`s in the `NamedMatch` have the same nonterminal type
192 /// (expr, item, etc). Each leaf in a single `NamedMatch` corresponds to a
193 /// single `token::MATCH_NONTERMINAL` in the `TokenTree` that produced it.
195 /// The in-memory structure of a particular `NamedMatch` represents the match
196 /// that occurred when a particular subset of a matcher was applied to a
197 /// particular token tree.
199 /// The width of each `MatchedSeq` in the `NamedMatch`, and the identity of
200 /// the `MatchedNonterminal`s, will depend on the token tree it was applied
201 /// to: each `MatchedSeq` corresponds to a single `TTSeq` in the originating
202 /// token tree. The depth of the `NamedMatch` structure will therefore depend
203 /// only on the nesting depth of `ast::TTSeq`s in the originating
204 /// token tree it was derived from.
206 #[derive(Debug, Clone)]
207 pub enum NamedMatch {
208 MatchedSeq(Rc<Vec<NamedMatch>>, syntax_pos::Span),
209 MatchedNonterminal(Rc<Nonterminal>)
212 fn nameize<I: Iterator<Item=NamedMatch>>(sess: &ParseSess, ms: &[TokenTree], mut res: I)
213 -> NamedParseResult {
214 fn n_rec<I: Iterator<Item=NamedMatch>>(sess: &ParseSess, m: &TokenTree, res: &mut I,
215 ret_val: &mut HashMap<Ident, Rc<NamedMatch>>)
216 -> Result<(), (syntax_pos::Span, String)> {
218 TokenTree::Sequence(_, ref seq) => {
219 for next_m in &seq.tts {
220 n_rec(sess, next_m, res.by_ref(), ret_val)?
223 TokenTree::Delimited(_, ref delim) => {
224 for next_m in &delim.tts {
225 n_rec(sess, next_m, res.by_ref(), ret_val)?;
228 TokenTree::MetaVarDecl(span, _, id) if id.name == keywords::Invalid.name() => {
229 if sess.missing_fragment_specifiers.borrow_mut().remove(&span) {
230 return Err((span, "missing fragment specifier".to_string()));
233 TokenTree::MetaVarDecl(sp, bind_name, _) => {
234 match ret_val.entry(bind_name) {
236 // FIXME(simulacrum): Don't construct Rc here
237 spot.insert(Rc::new(res.next().unwrap()));
240 return Err((sp, format!("duplicated bind name: {}", bind_name)))
244 TokenTree::MetaVar(..) | TokenTree::Token(..) => (),
250 let mut ret_val = HashMap::new();
252 match n_rec(sess, m, res.by_ref(), &mut ret_val) {
254 Err((sp, msg)) => return Error(sp, msg),
261 pub enum ParseResult<T> {
263 /// Arm failed to match. If the second parameter is `token::Eof`, it
264 /// indicates an unexpected end of macro invocation. Otherwise, it
265 /// indicates that no rules expected the given token.
266 Failure(syntax_pos::Span, Token),
267 /// Fatal error (malformed macro?). Abort compilation.
268 Error(syntax_pos::Span, String)
271 pub fn parse_failure_msg(tok: Token) -> String {
273 token::Eof => "unexpected end of macro invocation".to_string(),
274 _ => format!("no rules expected the token `{}`", pprust::token_to_string(&tok)),
278 /// Perform a token equality check, ignoring syntax context (that is, an unhygienic comparison)
279 fn token_name_eq(t1 : &Token, t2 : &Token) -> bool {
280 if let (Some(id1), Some(id2)) = (t1.ident(), t2.ident()) {
282 } else if let (&token::Lifetime(id1), &token::Lifetime(id2)) = (t1, t2) {
289 fn create_matches(len: usize) -> Vec<Rc<Vec<NamedMatch>>> {
290 (0..len).into_iter().map(|_| Rc::new(Vec::new())).collect()
293 fn inner_parse_loop(sess: &ParseSess,
294 cur_items: &mut SmallVector<Box<MatcherPos>>,
295 next_items: &mut Vec<Box<MatcherPos>>,
296 eof_items: &mut SmallVector<Box<MatcherPos>>,
297 bb_items: &mut SmallVector<Box<MatcherPos>>,
299 span: syntax_pos::Span)
301 while let Some(mut item) = cur_items.pop() {
302 // When unzipped trees end, remove them
303 while item.idx >= item.top_elts.len() {
304 match item.stack.pop() {
305 Some(MatcherTtFrame { elts, idx }) => {
306 item.top_elts = elts;
314 let len = item.top_elts.len();
316 // at end of sequence
318 // We are repeating iff there is a parent
319 if item.up.is_some() {
320 // Disregarding the separator, add the "up" case to the tokens that should be
322 // (remove this condition to make trailing seps ok)
324 let mut new_pos = item.up.clone().unwrap();
326 // update matches (the MBE "parse tree") by appending
327 // each tree as a subtree.
329 // Only touch the binders we have actually bound
330 for idx in item.match_lo..item.match_hi {
331 let sub = item.matches[idx].clone();
332 new_pos.push_match(idx, MatchedSeq(sub, Span { lo: item.sp_lo, ..span }));
335 new_pos.match_cur = item.match_hi;
337 cur_items.push(new_pos);
340 // Check if we need a separator
341 if idx == len && item.sep.is_some() {
342 // We have a separator, and it is the current token.
343 if item.sep.as_ref().map(|sep| token_name_eq(token, sep)).unwrap_or(false) {
345 next_items.push(item);
347 } else { // we don't need a separator
348 item.match_cur = item.match_lo;
350 cur_items.push(item);
353 // We aren't repeating, so we must be potentially at the end of the input.
354 eof_items.push(item);
357 match item.top_elts.get_tt(idx) {
358 /* need to descend into sequence */
359 TokenTree::Sequence(sp, seq) => {
360 if seq.op == quoted::KleeneOp::ZeroOrMore {
361 // Examine the case where there are 0 matches of this sequence
362 let mut new_item = item.clone();
363 new_item.match_cur += seq.num_captures;
365 for idx in item.match_cur..item.match_cur + seq.num_captures {
366 new_item.push_match(idx, MatchedSeq(Rc::new(vec![]), sp));
368 cur_items.push(new_item);
371 // Examine the case where there is at least one match of this sequence
372 let matches = create_matches(item.matches.len());
373 cur_items.push(Box::new(MatcherPos {
375 sep: seq.separator.clone(),
378 match_lo: item.match_cur,
379 match_cur: item.match_cur,
380 match_hi: item.match_cur + seq.num_captures,
383 top_elts: Tt(TokenTree::Sequence(sp, seq)),
386 TokenTree::MetaVarDecl(span, _, id) if id.name == keywords::Invalid.name() => {
387 if sess.missing_fragment_specifiers.borrow_mut().remove(&span) {
388 return Error(span, "missing fragment specifier".to_string());
391 TokenTree::MetaVarDecl(_, _, id) => {
392 // Built-in nonterminals never start with these tokens,
393 // so we can eliminate them from consideration.
394 if may_begin_with(&*id.name.as_str(), token) {
398 seq @ TokenTree::Delimited(..) | seq @ TokenTree::Token(_, DocComment(..)) => {
399 let lower_elts = mem::replace(&mut item.top_elts, Tt(seq));
401 item.stack.push(MatcherTtFrame {
406 cur_items.push(item);
408 TokenTree::Token(_, ref t) if token_name_eq(t, token) => {
410 next_items.push(item);
412 TokenTree::Token(..) | TokenTree::MetaVar(..) => {}
420 pub fn parse(sess: &ParseSess,
423 directory: Option<Directory>,
424 recurse_into_modules: bool)
425 -> NamedParseResult {
426 let mut parser = Parser::new(sess, tts, directory, recurse_into_modules, true);
427 let mut cur_items = SmallVector::one(initial_matcher_pos(ms.to_owned(), parser.span.lo));
428 let mut next_items = Vec::new(); // or proceed normally
431 let mut bb_items = SmallVector::new(); // black-box parsed by parser.rs
432 let mut eof_items = SmallVector::new();
433 assert!(next_items.is_empty());
435 match inner_parse_loop(sess, &mut cur_items, &mut next_items, &mut eof_items, &mut bb_items,
436 &parser.token, parser.span) {
438 Failure(sp, tok) => return Failure(sp, tok),
439 Error(sp, msg) => return Error(sp, msg),
442 // inner parse loop handled all cur_items, so it's empty
443 assert!(cur_items.is_empty());
445 /* error messages here could be improved with links to orig. rules */
446 if token_name_eq(&parser.token, &token::Eof) {
447 if eof_items.len() == 1 {
448 let matches = eof_items[0].matches.iter_mut().map(|dv| {
449 Rc::make_mut(dv).pop().unwrap()
451 return nameize(sess, ms, matches);
452 } else if eof_items.len() > 1 {
453 return Error(parser.span, "ambiguity: multiple successful parses".to_string());
455 return Failure(parser.span, token::Eof);
457 } else if (!bb_items.is_empty() && !next_items.is_empty()) || bb_items.len() > 1 {
458 let nts = bb_items.iter().map(|item| match item.top_elts.get_tt(item.idx) {
459 TokenTree::MetaVarDecl(_, bind, name) => {
460 format!("{} ('{}')", name, bind)
463 }).collect::<Vec<String>>().join(" or ");
465 return Error(parser.span, format!(
466 "local ambiguity: multiple parsing options: {}",
467 match next_items.len() {
468 0 => format!("built-in NTs {}.", nts),
469 1 => format!("built-in NTs {} or 1 other option.", nts),
470 n => format!("built-in NTs {} or {} other options.", nts, n),
473 } else if bb_items.is_empty() && next_items.is_empty() {
474 return Failure(parser.span, parser.token);
475 } else if !next_items.is_empty() {
476 /* Now process the next token */
477 cur_items.extend(next_items.drain(..));
479 } else /* bb_items.len() == 1 */ {
480 let mut item = bb_items.pop().unwrap();
481 if let TokenTree::MetaVarDecl(span, _, ident) = item.top_elts.get_tt(item.idx) {
482 let match_cur = item.match_cur;
483 item.push_match(match_cur,
484 MatchedNonterminal(Rc::new(parse_nt(&mut parser, span, &ident.name.as_str()))));
490 cur_items.push(item);
493 assert!(!cur_items.is_empty());
497 /// Checks whether a non-terminal may begin with a particular token.
499 /// Returning `false` is a *stability guarantee* that such a matcher will *never* begin with that
500 /// token. Be conservative (return true) if not sure.
501 fn may_begin_with(name: &str, token: &Token) -> bool {
502 /// Checks whether the non-terminal may contain a single (non-keyword) identifier.
503 fn may_be_ident(nt: &token::Nonterminal) -> bool {
505 token::NtItem(_) | token::NtBlock(_) | token::NtVis(_) => false,
511 "expr" => token.can_begin_expr(),
512 "ty" => token.can_begin_type(),
513 "ident" => token.is_ident(),
514 "vis" => match *token { // The follow-set of :vis + "priv" keyword + interpolated
515 Token::Comma | Token::Ident(_) | Token::Interpolated(_) => true,
516 _ => token.can_begin_type(),
518 "block" => match *token {
519 Token::OpenDelim(token::Brace) => true,
520 Token::Interpolated(ref nt) => match nt.0 {
527 token::NtVis(_) => false, // none of these may start with '{'.
532 "path" | "meta" => match *token {
533 Token::ModSep | Token::Ident(_) => true,
534 Token::Interpolated(ref nt) => match nt.0 {
535 token::NtPath(_) | token::NtMeta(_) => true,
536 _ => may_be_ident(&nt.0),
540 "pat" => match *token {
541 Token::Ident(_) | // box, ref, mut, and other identifiers (can stricten)
542 Token::OpenDelim(token::Paren) | // tuple pattern
543 Token::OpenDelim(token::Bracket) | // slice pattern
544 Token::BinOp(token::And) | // reference
545 Token::BinOp(token::Minus) | // negative literal
546 Token::AndAnd | // double reference
547 Token::Literal(..) | // literal
548 Token::DotDot | // range pattern (future compat)
549 Token::DotDotDot | // range pattern (future compat)
550 Token::ModSep | // path
551 Token::Lt | // path (UFCS constant)
552 Token::BinOp(token::Shl) | // path (double UFCS)
553 Token::Underscore => true, // placeholder
554 Token::Interpolated(ref nt) => may_be_ident(&nt.0),
558 token::CloseDelim(_) => false,
564 fn parse_nt<'a>(p: &mut Parser<'a>, sp: Span, name: &str) -> Nonterminal {
566 return token::NtTT(p.parse_token_tree());
568 // check at the beginning and the parser checks after each bump
569 p.process_potential_macro_variable();
571 "item" => match panictry!(p.parse_item()) {
572 Some(i) => token::NtItem(i),
574 p.fatal("expected an item keyword").emit();
578 "block" => token::NtBlock(panictry!(p.parse_block())),
579 "stmt" => match panictry!(p.parse_stmt()) {
580 Some(s) => token::NtStmt(s),
582 p.fatal("expected a statement").emit();
586 "pat" => token::NtPat(panictry!(p.parse_pat())),
587 "expr" => token::NtExpr(panictry!(p.parse_expr())),
588 "ty" => token::NtTy(panictry!(p.parse_ty())),
589 // this could be handled like a token, since it is one
590 "ident" => match p.token {
591 token::Ident(sn) => {
593 token::NtIdent(Spanned::<Ident>{node: sn, span: p.prev_span})
596 let token_str = pprust::token_to_string(&p.token);
597 p.fatal(&format!("expected ident, found {}",
598 &token_str[..])).emit();
603 token::NtPath(panictry!(p.parse_path(PathStyle::Type)))
605 "meta" => token::NtMeta(panictry!(p.parse_meta_item())),
606 "vis" => token::NtVis(panictry!(p.parse_visibility(true))),
607 // this is not supposed to happen, since it has been checked
608 // when compiling the macro.
609 _ => p.span_bug(sp, "invalid fragment specifier")