1 // Copyright 2012-2014 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 Earley-like parser, without support for in-grammar nonterminals,
12 //! only by calling out to the main rust parser for named nonterminals (which it
13 //! commits to fully when it hits one in a grammar). This means that there are no
14 //! completer or predictor rules, and therefore no need to store one column per
15 //! token: instead, there's a set of current Earley items and a set of next
16 //! ones. Instead of NTs, we have a special case for Kleene star. The big-O, in
17 //! pathological cases, is worse than traditional Earley parsing, but it's an
18 //! easier fit for Macro-by-Example-style rules, and I think the overhead is
19 //! lower. (In order to prevent the pathological case, we'd need to lazily
20 //! construct the resulting `NamedMatch`es at the very end. It'd be a pain,
21 //! and require more memory to keep around old items, but it would also save
24 //! Quick intro to how the parser works:
26 //! A 'position' is a dot in the middle of a matcher, usually represented as a
27 //! dot. For example `· a $( a )* a b` is a position, as is `a $( · a )* a b`.
29 //! The parser walks through the input a character at a time, maintaining a list
30 //! of items consistent with the current position in the input string: `cur_eis`.
32 //! As it processes them, it fills up `eof_eis` with items that would be valid if
33 //! the macro invocation is now over, `bb_eis` with items that are waiting on
34 //! a Rust nonterminal like `$e:expr`, and `next_eis` with items that are waiting
35 //! on the a particular token. Most of the logic concerns moving the · through the
36 //! repetitions indicated by Kleene stars. It only advances or calls out to the
37 //! real Rust parser when no `cur_eis` items remain
39 //! Example: Start parsing `a a a a b` against [· a $( a )* a b].
41 //! Remaining input: `a a a a b`
42 //! next_eis: [· a $( a )* a b]
44 //! - - - Advance over an `a`. - - -
46 //! Remaining input: `a a a b`
47 //! cur: [a · $( a )* a b]
48 //! Descend/Skip (first item).
49 //! next: [a $( · a )* a b] [a $( a )* · a b].
51 //! - - - Advance over an `a`. - - -
53 //! Remaining input: `a a b`
54 //! cur: [a $( a · )* a b] next: [a $( a )* a · b]
55 //! Finish/Repeat (first item)
56 //! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b]
58 //! - - - Advance over an `a`. - - - (this looks exactly like the last step)
60 //! Remaining input: `a b`
61 //! cur: [a $( a · )* a b] next: [a $( a )* a · b]
62 //! Finish/Repeat (first item)
63 //! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b]
65 //! - - - Advance over an `a`. - - - (this looks exactly like the last step)
67 //! Remaining input: `b`
68 //! cur: [a $( a · )* a b] next: [a $( a )* a · b]
69 //! Finish/Repeat (first item)
70 //! next: [a $( a )* · a b] [a $( · a )* a b]
72 //! - - - Advance over a `b`. - - -
74 //! Remaining input: ``
75 //! eof: [a $( a )* a b ·]
79 use ast::{Matcher, MatchTok, MatchSeq, MatchNonterminal, Ident};
80 use codemap::{BytePos, mk_sp};
82 use parse::lexer::*; //resolve bug?
84 use parse::attr::ParserAttr;
85 use parse::parser::{LifetimeAndTypesWithoutColons, Parser};
86 use parse::token::{Token, EOF, Nonterminal};
91 use std::collections::HashMap;
93 /* to avoid costly uniqueness checks, we require that `MatchSeq` always has a
98 pub struct MatcherPos {
99 elts: Vec<ast::Matcher> , // maybe should be <'>? Need to understand regions.
102 up: Option<Box<MatcherPos>>,
103 matches: Vec<Vec<Rc<NamedMatch>>>,
104 match_lo: uint, match_hi: uint,
108 pub fn count_names(ms: &[Matcher]) -> uint {
109 ms.iter().fold(0, |ct, m| {
112 MatchSeq(ref more_ms, _, _, _, _) => {
113 count_names(more_ms.as_slice())
115 MatchNonterminal(_, _, _) => 1u
119 pub fn initial_matcher_pos(ms: Vec<Matcher> , sep: Option<Token>, lo: BytePos)
121 let mut match_idx_hi = 0u;
122 for elt in ms.iter() {
125 MatchSeq(_,_,_,_,hi) => {
126 match_idx_hi = hi; // it is monotonic...
128 MatchNonterminal(_,_,pos) => {
129 match_idx_hi = pos+1u; // ...so latest is highest
133 let matches = Vec::from_fn(count_names(ms.as_slice()), |_i| Vec::new());
141 match_hi: match_idx_hi,
146 /// NamedMatch is a pattern-match result for a single ast::MatchNonterminal:
147 /// so it is associated with a single ident in a parse, and all
148 /// MatchedNonterminal's in the NamedMatch have the same nonterminal type
149 /// (expr, item, etc). All the leaves in a single NamedMatch correspond to a
150 /// single matcher_nonterminal in the ast::Matcher that produced it.
152 /// It should probably be renamed, it has more or less exact correspondence to
153 /// ast::match nodes, and the in-memory structure of a particular NamedMatch
154 /// represents the match that occurred when a particular subset of an
155 /// ast::match -- those ast::Matcher nodes leading to a single
156 /// MatchNonterminal -- was applied to a particular token tree.
158 /// The width of each MatchedSeq in the NamedMatch, and the identity of the
159 /// MatchedNonterminal's, will depend on the token tree it was applied to: each
160 /// MatchedSeq corresponds to a single MatchSeq in the originating
161 /// ast::Matcher. The depth of the NamedMatch structure will therefore depend
162 /// only on the nesting depth of ast::MatchSeq's in the originating
163 /// ast::Matcher it was derived from.
165 pub enum NamedMatch {
166 MatchedSeq(Vec<Rc<NamedMatch>>, codemap::Span),
167 MatchedNonterminal(Nonterminal)
170 pub fn nameize(p_s: &ParseSess, ms: &[Matcher], res: &[Rc<NamedMatch>])
171 -> HashMap<Ident, Rc<NamedMatch>> {
172 fn n_rec(p_s: &ParseSess, m: &Matcher, res: &[Rc<NamedMatch>],
173 ret_val: &mut HashMap<Ident, Rc<NamedMatch>>) {
175 codemap::Spanned {node: MatchTok(_), .. } => (),
176 codemap::Spanned {node: MatchSeq(ref more_ms, _, _, _, _), .. } => {
177 for next_m in more_ms.iter() {
178 n_rec(p_s, next_m, res, ret_val)
182 node: MatchNonterminal(bind_name, _, idx),
185 if ret_val.contains_key(&bind_name) {
186 let string = token::get_ident(bind_name);
189 format!("duplicated bind name: {}",
190 string.get()).as_slice())
192 ret_val.insert(bind_name, res[idx].clone());
196 let mut ret_val = HashMap::new();
197 for m in ms.iter() { n_rec(p_s, m, res, &mut ret_val) }
201 pub enum ParseResult {
202 Success(HashMap<Ident, Rc<NamedMatch>>),
203 Failure(codemap::Span, String),
204 Error(codemap::Span, String)
207 pub fn parse_or_else(sess: &ParseSess,
208 cfg: ast::CrateConfig,
211 -> HashMap<Ident, Rc<NamedMatch>> {
212 match parse(sess, cfg, rdr, ms.as_slice()) {
214 Failure(sp, str) => {
215 sess.span_diagnostic.span_fatal(sp, str.as_slice())
218 sess.span_diagnostic.span_fatal(sp, str.as_slice())
223 /// Perform a token equality check, ignoring syntax context (that is, an
224 /// unhygienic comparison)
225 pub fn token_name_eq(t1 : &Token, t2 : &Token) -> bool {
227 (&token::IDENT(id1,_),&token::IDENT(id2,_))
228 | (&token::LIFETIME(id1),&token::LIFETIME(id2)) =>
229 id1.name == id2.name,
234 pub fn parse(sess: &ParseSess,
235 cfg: ast::CrateConfig,
239 let mut cur_eis = Vec::new();
240 cur_eis.push(initial_matcher_pos(ms.iter()
241 .map(|x| (*x).clone())
247 let mut bb_eis = Vec::new(); // black-box parsed by parser.rs
248 let mut next_eis = Vec::new(); // or proceed normally
249 let mut eof_eis = Vec::new();
251 let TokenAndSpan {tok: tok, sp: sp} = rdr.peek();
253 /* we append new items to this while we go */
255 let ei = match cur_eis.pop() {
256 None => break, /* for each Earley Item */
261 let len = ei.elts.len();
263 /* at end of sequence */
265 // can't move out of `match`es, so:
267 // hack: a matcher sequence is repeating iff it has a
268 // parent (the top level is just a container)
271 // disregard separator, try to go up
272 // (remove this condition to make trailing seps ok)
274 // pop from the matcher position
276 let mut new_pos = ei.up.clone().unwrap();
278 // update matches (the MBE "parse tree") by appending
279 // each tree as a subtree.
281 // I bet this is a perf problem: we're preemptively
282 // doing a lot of array work that will get thrown away
285 // Only touch the binders we have actually bound
286 for idx in range(ei.match_lo, ei.match_hi) {
287 let sub = (*ei.matches.get(idx)).clone();
290 .push(Rc::new(MatchedSeq(sub, mk_sp(ei.sp_lo,
295 cur_eis.push(new_pos);
298 // can we go around again?
300 // the *_t vars are workarounds for the lack of unary move
302 Some(ref t) if idx == len => { // we need a separator
303 // i'm conflicted about whether this should be hygienic....
304 // though in this case, if the separators are never legal
305 // idents, it shouldn't matter.
306 if token_name_eq(&tok, t) { //pass the separator
307 let mut ei_t = ei.clone();
312 _ => { // we don't need a separator
322 match ei.elts.get(idx).node.clone() {
323 /* need to descend into sequence */
324 MatchSeq(ref matchers, ref sep, zero_ok,
325 match_idx_lo, match_idx_hi) => {
327 let mut new_ei = ei.clone();
329 //we specifically matched zero repeats.
330 for idx in range(match_idx_lo, match_idx_hi) {
333 .push(Rc::new(MatchedSeq(Vec::new(), sp)));
336 cur_eis.push(new_ei);
339 let matches = Vec::from_elem(ei.matches.len(), Vec::new());
341 cur_eis.push(box MatcherPos {
342 elts: (*matchers).clone(),
347 match_lo: match_idx_lo, match_hi: match_idx_hi,
351 MatchNonterminal(_,_,_) => { bb_eis.push(ei) }
353 let mut ei_t = ei.clone();
354 if token_name_eq(t,&tok) {
363 /* error messages here could be improved with links to orig. rules */
364 if token_name_eq(&tok, &EOF) {
365 if eof_eis.len() == 1u {
366 let mut v = Vec::new();
367 for dv in eof_eis.get_mut(0).matches.mut_iter() {
368 v.push(dv.pop().unwrap());
370 return Success(nameize(sess, ms, v.as_slice()));
371 } else if eof_eis.len() > 1u {
372 return Error(sp, "ambiguity: multiple successful parses".to_string());
374 return Failure(sp, "unexpected end of macro invocation".to_string());
377 if (bb_eis.len() > 0u && next_eis.len() > 0u)
378 || bb_eis.len() > 1u {
379 let nts = bb_eis.iter().map(|ei| {
380 match ei.elts.get(ei.idx).node {
381 MatchNonterminal(bind, name, _) => {
382 (format!("{} ('{}')",
383 token::get_ident(name),
384 token::get_ident(bind))).to_string()
387 } }).collect::<Vec<String>>().connect(" or ");
388 return Error(sp, format!(
389 "local ambiguity: multiple parsing options: \
390 built-in NTs {} or {} other options.",
391 nts, next_eis.len()).to_string());
392 } else if bb_eis.len() == 0u && next_eis.len() == 0u {
393 return Failure(sp, format!("no rules expected the token `{}`",
394 token::to_string(&tok)).to_string());
395 } else if next_eis.len() > 0u {
396 /* Now process the next token */
397 while next_eis.len() > 0u {
398 cur_eis.push(next_eis.pop().unwrap());
401 } else /* bb_eis.len() == 1 */ {
402 let mut rust_parser = Parser::new(sess, cfg.clone(), box rdr.clone());
404 let mut ei = bb_eis.pop().unwrap();
405 match ei.elts.get(ei.idx).node {
406 MatchNonterminal(_, name, idx) => {
407 let name_string = token::get_ident(name);
408 ei.matches.get_mut(idx).push(Rc::new(MatchedNonterminal(
409 parse_nt(&mut rust_parser, name_string.get()))));
416 for _ in range(0, rust_parser.tokens_consumed) {
417 let _ = rdr.next_token();
422 assert!(cur_eis.len() > 0u);
426 pub fn parse_nt(p: &mut Parser, name: &str) -> Nonterminal {
428 "item" => match p.parse_item(Vec::new()) {
429 Some(i) => token::NtItem(i),
430 None => p.fatal("expected an item keyword")
432 "block" => token::NtBlock(p.parse_block()),
433 "stmt" => token::NtStmt(p.parse_stmt(Vec::new())),
434 "pat" => token::NtPat(p.parse_pat()),
435 "expr" => token::NtExpr(p.parse_expr()),
436 "ty" => token::NtTy(p.parse_ty(false /* no need to disambiguate*/)),
437 // this could be handled like a token, since it is one
438 "ident" => match p.token {
439 token::IDENT(sn,b) => { p.bump(); token::NtIdent(box sn,b) }
441 let token_str = token::to_string(&p.token);
442 p.fatal((format!("expected ident, found {}",
443 token_str.as_slice())).as_slice())
447 token::NtPath(box p.parse_path(LifetimeAndTypesWithoutColons).path)
449 "meta" => token::NtMeta(p.parse_meta_item()),
451 p.quote_depth += 1u; //but in theory, non-quoted tts might be useful
452 let res = token::NtTT(box(GC) p.parse_token_tree());
456 "matchers" => token::NtMatchers(p.parse_matchers()),
458 p.fatal(format!("unsupported builtin nonterminal parser: {}",