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 // Earley-like parser for macros.
14 use ast::{Matcher, MatchTok, MatchSeq, MatchNonterminal, Ident};
15 use codemap::{BytePos, mk_sp};
17 use parse::lexer::*; //resolve bug?
19 use parse::attr::ParserAttr;
20 use parse::parser::{LifetimeAndTypesWithoutColons, Parser};
21 use parse::token::{Token, EOF, Nonterminal};
26 use std::collections::HashMap;
28 /* This is an Earley-like parser, without support for in-grammar nonterminals,
29 only by calling out to the main rust parser for named nonterminals (which it
30 commits to fully when it hits one in a grammar). This means that there are no
31 completer or predictor rules, and therefore no need to store one column per
32 token: instead, there's a set of current Earley items and a set of next
33 ones. Instead of NTs, we have a special case for Kleene star. The big-O, in
34 pathological cases, is worse than traditional Earley parsing, but it's an
35 easier fit for Macro-by-Example-style rules, and I think the overhead is
36 lower. (In order to prevent the pathological case, we'd need to lazily
37 construct the resulting `NamedMatch`es at the very end. It'd be a pain,
38 and require more memory to keep around old items, but it would also save
41 /* Quick intro to how the parser works:
43 A 'position' is a dot in the middle of a matcher, usually represented as a
44 dot. For example `· a $( a )* a b` is a position, as is `a $( · a )* a b`.
46 The parser walks through the input a character at a time, maintaining a list
47 of items consistent with the current position in the input string: `cur_eis`.
49 As it processes them, it fills up `eof_eis` with items that would be valid if
50 the macro invocation is now over, `bb_eis` with items that are waiting on
51 a Rust nonterminal like `$e:expr`, and `next_eis` with items that are waiting
52 on the a particular token. Most of the logic concerns moving the · through the
53 repetitions indicated by Kleene stars. It only advances or calls out to the
54 real Rust parser when no `cur_eis` items remain
56 Example: Start parsing `a a a a b` against [· a $( a )* a b].
58 Remaining input: `a a a a b`
59 next_eis: [· a $( a )* a b]
61 - - - Advance over an `a`. - - -
63 Remaining input: `a a a b`
64 cur: [a · $( a )* a b]
65 Descend/Skip (first item).
66 next: [a $( · a )* a b] [a $( a )* · a b].
68 - - - Advance over an `a`. - - -
70 Remaining input: `a a b`
71 cur: [a $( a · )* a b] next: [a $( a )* a · b]
72 Finish/Repeat (first item)
73 next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b]
75 - - - Advance over an `a`. - - - (this looks exactly like the last step)
77 Remaining input: `a b`
78 cur: [a $( a · )* a b] next: [a $( a )* a · b]
79 Finish/Repeat (first item)
80 next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b]
82 - - - Advance over an `a`. - - - (this looks exactly like the last step)
85 cur: [a $( a · )* a b] next: [a $( a )* a · b]
86 Finish/Repeat (first item)
87 next: [a $( a )* · a b] [a $( · a )* a b]
89 - - - Advance over a `b`. - - -
92 eof: [a $( a )* a b ·]
97 /* to avoid costly uniqueness checks, we require that `MatchSeq` always has a
102 pub struct MatcherPos {
103 elts: Vec<ast::Matcher> , // maybe should be <'>? Need to understand regions.
106 up: Option<Box<MatcherPos>>,
107 matches: Vec<Vec<Rc<NamedMatch>>>,
108 match_lo: uint, match_hi: uint,
112 pub fn count_names(ms: &[Matcher]) -> uint {
113 ms.iter().fold(0, |ct, m| {
116 MatchSeq(ref more_ms, _, _, _, _) => {
117 count_names(more_ms.as_slice())
119 MatchNonterminal(_, _, _) => 1u
123 pub fn initial_matcher_pos(ms: Vec<Matcher> , sep: Option<Token>, lo: BytePos)
125 let mut match_idx_hi = 0u;
126 for elt in ms.iter() {
129 MatchSeq(_,_,_,_,hi) => {
130 match_idx_hi = hi; // it is monotonic...
132 MatchNonterminal(_,_,pos) => {
133 match_idx_hi = pos+1u; // ...so latest is highest
137 let matches = Vec::from_fn(count_names(ms.as_slice()), |_i| Vec::new());
145 match_hi: match_idx_hi,
150 // NamedMatch is a pattern-match result for a single ast::MatchNonterminal:
151 // so it is associated with a single ident in a parse, and all
152 // MatchedNonterminal's in the NamedMatch have the same nonterminal type
153 // (expr, item, etc). All the leaves in a single NamedMatch correspond to a
154 // single matcher_nonterminal in the ast::Matcher that produced it.
156 // It should probably be renamed, it has more or less exact correspondence to
157 // ast::match nodes, and the in-memory structure of a particular NamedMatch
158 // represents the match that occurred when a particular subset of an
159 // ast::match -- those ast::Matcher nodes leading to a single
160 // MatchNonterminal -- was applied to a particular token tree.
162 // The width of each MatchedSeq in the NamedMatch, and the identity of the
163 // MatchedNonterminal's, will depend on the token tree it was applied to: each
164 // MatchedSeq corresponds to a single MatchSeq in the originating
165 // ast::Matcher. The depth of the NamedMatch structure will therefore depend
166 // only on the nesting depth of ast::MatchSeq's in the originating
167 // ast::Matcher it was derived from.
169 pub enum NamedMatch {
170 MatchedSeq(Vec<Rc<NamedMatch>>, codemap::Span),
171 MatchedNonterminal(Nonterminal)
174 pub fn nameize(p_s: &ParseSess, ms: &[Matcher], res: &[Rc<NamedMatch>])
175 -> HashMap<Ident, Rc<NamedMatch>> {
176 fn n_rec(p_s: &ParseSess, m: &Matcher, res: &[Rc<NamedMatch>],
177 ret_val: &mut HashMap<Ident, Rc<NamedMatch>>) {
179 codemap::Spanned {node: MatchTok(_), .. } => (),
180 codemap::Spanned {node: MatchSeq(ref more_ms, _, _, _, _), .. } => {
181 for next_m in more_ms.iter() {
182 n_rec(p_s, next_m, res, ret_val)
186 node: MatchNonterminal(bind_name, _, idx),
189 if ret_val.contains_key(&bind_name) {
190 let string = token::get_ident(bind_name);
193 format!("duplicated bind name: {}",
194 string.get()).as_slice())
196 ret_val.insert(bind_name, res[idx].clone());
200 let mut ret_val = HashMap::new();
201 for m in ms.iter() { n_rec(p_s, m, res, &mut ret_val) }
205 pub enum ParseResult {
206 Success(HashMap<Ident, Rc<NamedMatch>>),
207 Failure(codemap::Span, String),
208 Error(codemap::Span, String)
211 pub fn parse_or_else(sess: &ParseSess,
212 cfg: ast::CrateConfig,
215 -> HashMap<Ident, Rc<NamedMatch>> {
216 match parse(sess, cfg, rdr, ms.as_slice()) {
218 Failure(sp, str) => {
219 sess.span_diagnostic.span_fatal(sp, str.as_slice())
222 sess.span_diagnostic.span_fatal(sp, str.as_slice())
227 // perform a token equality check, ignoring syntax context (that is, an unhygienic comparison)
228 pub fn token_name_eq(t1 : &Token, t2 : &Token) -> bool {
230 (&token::IDENT(id1,_),&token::IDENT(id2,_))
231 | (&token::LIFETIME(id1),&token::LIFETIME(id2)) =>
232 id1.name == id2.name,
237 pub fn parse(sess: &ParseSess,
238 cfg: ast::CrateConfig,
242 let mut cur_eis = Vec::new();
243 cur_eis.push(initial_matcher_pos(ms.iter()
244 .map(|x| (*x).clone())
250 let mut bb_eis = Vec::new(); // black-box parsed by parser.rs
251 let mut next_eis = Vec::new(); // or proceed normally
252 let mut eof_eis = Vec::new();
254 let TokenAndSpan {tok: tok, sp: sp} = rdr.peek();
256 /* we append new items to this while we go */
258 let ei = match cur_eis.pop() {
259 None => break, /* for each Earley Item */
264 let len = ei.elts.len();
266 /* at end of sequence */
268 // can't move out of `match`es, so:
270 // hack: a matcher sequence is repeating iff it has a
271 // parent (the top level is just a container)
274 // disregard separator, try to go up
275 // (remove this condition to make trailing seps ok)
277 // pop from the matcher position
279 let mut new_pos = ei.up.clone().unwrap();
281 // update matches (the MBE "parse tree") by appending
282 // each tree as a subtree.
284 // I bet this is a perf problem: we're preemptively
285 // doing a lot of array work that will get thrown away
288 // Only touch the binders we have actually bound
289 for idx in range(ei.match_lo, ei.match_hi) {
290 let sub = (*ei.matches.get(idx)).clone();
293 .push(Rc::new(MatchedSeq(sub, mk_sp(ei.sp_lo,
298 cur_eis.push(new_pos);
301 // can we go around again?
303 // the *_t vars are workarounds for the lack of unary move
305 Some(ref t) if idx == len => { // we need a separator
306 // i'm conflicted about whether this should be hygienic....
307 // though in this case, if the separators are never legal
308 // idents, it shouldn't matter.
309 if token_name_eq(&tok, t) { //pass the separator
310 let mut ei_t = ei.clone();
315 _ => { // we don't need a separator
325 match ei.elts.get(idx).node.clone() {
326 /* need to descend into sequence */
327 MatchSeq(ref matchers, ref sep, zero_ok,
328 match_idx_lo, match_idx_hi) => {
330 let mut new_ei = ei.clone();
332 //we specifically matched zero repeats.
333 for idx in range(match_idx_lo, match_idx_hi) {
336 .push(Rc::new(MatchedSeq(Vec::new(), sp)));
339 cur_eis.push(new_ei);
342 let matches = Vec::from_elem(ei.matches.len(), Vec::new());
344 cur_eis.push(box MatcherPos {
345 elts: (*matchers).clone(),
350 match_lo: match_idx_lo, match_hi: match_idx_hi,
354 MatchNonterminal(_,_,_) => { bb_eis.push(ei) }
356 let mut ei_t = ei.clone();
357 //if (token_name_eq(t,&tok)) {
358 if token::mtwt_token_eq(t,&tok) {
367 /* error messages here could be improved with links to orig. rules */
368 if token_name_eq(&tok, &EOF) {
369 if eof_eis.len() == 1u {
370 let mut v = Vec::new();
371 for dv in eof_eis.get_mut(0).matches.mut_iter() {
372 v.push(dv.pop().unwrap());
374 return Success(nameize(sess, ms, v.as_slice()));
375 } else if eof_eis.len() > 1u {
376 return Error(sp, "ambiguity: multiple successful parses".to_string());
378 return Failure(sp, "unexpected end of macro invocation".to_string());
381 if (bb_eis.len() > 0u && next_eis.len() > 0u)
382 || bb_eis.len() > 1u {
383 let nts = bb_eis.iter().map(|ei| {
384 match ei.elts.get(ei.idx).node {
385 MatchNonterminal(bind, name, _) => {
386 (format!("{} ('{}')",
387 token::get_ident(name),
388 token::get_ident(bind))).to_string()
391 } }).collect::<Vec<String>>().connect(" or ");
392 return Error(sp, format!(
393 "local ambiguity: multiple parsing options: \
394 built-in NTs {} or {} other options.",
395 nts, next_eis.len()).to_string());
396 } else if bb_eis.len() == 0u && next_eis.len() == 0u {
397 return Failure(sp, format!("no rules expected the token `{}`",
398 token::to_str(&tok)).to_string());
399 } else if next_eis.len() > 0u {
400 /* Now process the next token */
401 while next_eis.len() > 0u {
402 cur_eis.push(next_eis.pop().unwrap());
405 } else /* bb_eis.len() == 1 */ {
406 let mut rust_parser = Parser::new(sess, cfg.clone(), box rdr.clone());
408 let mut ei = bb_eis.pop().unwrap();
409 match ei.elts.get(ei.idx).node {
410 MatchNonterminal(_, name, idx) => {
411 let name_string = token::get_ident(name);
412 ei.matches.get_mut(idx).push(Rc::new(MatchedNonterminal(
413 parse_nt(&mut rust_parser, name_string.get()))));
420 for _ in range(0, rust_parser.tokens_consumed) {
421 let _ = rdr.next_token();
426 assert!(cur_eis.len() > 0u);
430 pub fn parse_nt(p: &mut Parser, name: &str) -> Nonterminal {
432 "item" => match p.parse_item(Vec::new()) {
433 Some(i) => token::NtItem(i),
434 None => p.fatal("expected an item keyword")
436 "block" => token::NtBlock(p.parse_block()),
437 "stmt" => token::NtStmt(p.parse_stmt(Vec::new())),
438 "pat" => token::NtPat(p.parse_pat()),
439 "expr" => token::NtExpr(p.parse_expr()),
440 "ty" => token::NtTy(p.parse_ty(false /* no need to disambiguate*/)),
441 // this could be handled like a token, since it is one
442 "ident" => match p.token {
443 token::IDENT(sn,b) => { p.bump(); token::NtIdent(box sn,b) }
445 let token_str = token::to_str(&p.token);
446 p.fatal((format!("expected ident, found {}",
447 token_str.as_slice())).as_slice())
451 token::NtPath(box p.parse_path(LifetimeAndTypesWithoutColons).path)
453 "meta" => token::NtMeta(p.parse_meta_item()),
455 p.quote_depth += 1u; //but in theory, non-quoted tts might be useful
456 let res = token::NtTT(box(GC) p.parse_token_tree());
460 "matchers" => token::NtMatchers(p.parse_matchers()),
462 p.fatal(format!("unsupported builtin nonterminal parser: {}",