]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/tt/macro_parser.rs
auto merge of #14832 : alexcrichton/rust/no-rpath, r=brson
[rust.git] / src / libsyntax / ext / tt / macro_parser.rs
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.
4 //
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.
10
11 // Earley-like parser for macros.
12
13 use ast;
14 use ast::{Matcher, MatchTok, MatchSeq, MatchNonterminal, Ident};
15 use codemap::{BytePos, mk_sp};
16 use codemap;
17 use parse::lexer::*; //resolve bug?
18 use parse::ParseSess;
19 use parse::attr::ParserAttr;
20 use parse::parser::{LifetimeAndTypesWithoutColons, Parser};
21 use parse::token::{Token, EOF, Nonterminal};
22 use parse::token;
23
24 use std::rc::Rc;
25 use std::gc::GC;
26 use std::collections::HashMap;
27
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
39 overhead)*/
40
41 /* Quick intro to how the parser works:
42
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`.
45
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`.
48
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
55
56 Example: Start parsing `a a a a b` against [· a $( a )* a b].
57
58 Remaining input: `a a a a b`
59 next_eis: [· a $( a )* a b]
60
61 - - - Advance over an `a`. - - -
62
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].
67
68 - - - Advance over an `a`. - - -
69
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]
74
75 - - - Advance over an `a`. - - - (this looks exactly like the last step)
76
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]
81
82 - - - Advance over an `a`. - - - (this looks exactly like the last step)
83
84 Remaining input: `b`
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]
88
89 - - - Advance over a `b`. - - -
90
91 Remaining input: ``
92 eof: [a $( a )* a b ·]
93
94  */
95
96
97 /* to avoid costly uniqueness checks, we require that `MatchSeq` always has a
98 nonempty body. */
99
100
101 #[deriving(Clone)]
102 pub struct MatcherPos {
103     elts: Vec<ast::Matcher> , // maybe should be <'>? Need to understand regions.
104     sep: Option<Token>,
105     idx: uint,
106     up: Option<Box<MatcherPos>>,
107     matches: Vec<Vec<Rc<NamedMatch>>>,
108     match_lo: uint, match_hi: uint,
109     sp_lo: BytePos,
110 }
111
112 pub fn count_names(ms: &[Matcher]) -> uint {
113     ms.iter().fold(0, |ct, m| {
114         ct + match m.node {
115             MatchTok(_) => 0u,
116             MatchSeq(ref more_ms, _, _, _, _) => {
117                 count_names(more_ms.as_slice())
118             }
119             MatchNonterminal(_, _, _) => 1u
120         }})
121 }
122
123 pub fn initial_matcher_pos(ms: Vec<Matcher> , sep: Option<Token>, lo: BytePos)
124                            -> Box<MatcherPos> {
125     let mut match_idx_hi = 0u;
126     for elt in ms.iter() {
127         match elt.node {
128             MatchTok(_) => (),
129             MatchSeq(_,_,_,_,hi) => {
130                 match_idx_hi = hi;       // it is monotonic...
131             }
132             MatchNonterminal(_,_,pos) => {
133                 match_idx_hi = pos+1u;  // ...so latest is highest
134             }
135         }
136     }
137     let matches = Vec::from_fn(count_names(ms.as_slice()), |_i| Vec::new());
138     box MatcherPos {
139         elts: ms,
140         sep: sep,
141         idx: 0u,
142         up: None,
143         matches: matches,
144         match_lo: 0u,
145         match_hi: match_idx_hi,
146         sp_lo: lo
147     }
148 }
149
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.
155 //
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.
161 //
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.
168
169 pub enum NamedMatch {
170     MatchedSeq(Vec<Rc<NamedMatch>>, codemap::Span),
171     MatchedNonterminal(Nonterminal)
172 }
173
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>>) {
178         match *m {
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)
183             };
184           }
185           codemap::Spanned {
186                 node: MatchNonterminal(bind_name, _, idx),
187                 span
188           } => {
189             if ret_val.contains_key(&bind_name) {
190                 let string = token::get_ident(bind_name);
191                 p_s.span_diagnostic
192                    .span_fatal(span,
193                                format!("duplicated bind name: {}",
194                                        string.get()).as_slice())
195             }
196             ret_val.insert(bind_name, res[idx].clone());
197           }
198         }
199     }
200     let mut ret_val = HashMap::new();
201     for m in ms.iter() { n_rec(p_s, m, res, &mut ret_val) }
202     ret_val
203 }
204
205 pub enum ParseResult {
206     Success(HashMap<Ident, Rc<NamedMatch>>),
207     Failure(codemap::Span, String),
208     Error(codemap::Span, String)
209 }
210
211 pub fn parse_or_else(sess: &ParseSess,
212                      cfg: ast::CrateConfig,
213                      rdr: TtReader,
214                      ms: Vec<Matcher> )
215                      -> HashMap<Ident, Rc<NamedMatch>> {
216     match parse(sess, cfg, rdr, ms.as_slice()) {
217         Success(m) => m,
218         Failure(sp, str) => {
219             sess.span_diagnostic.span_fatal(sp, str.as_slice())
220         }
221         Error(sp, str) => {
222             sess.span_diagnostic.span_fatal(sp, str.as_slice())
223         }
224     }
225 }
226
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 {
229     match (t1,t2) {
230         (&token::IDENT(id1,_),&token::IDENT(id2,_))
231         | (&token::LIFETIME(id1),&token::LIFETIME(id2)) =>
232             id1.name == id2.name,
233         _ => *t1 == *t2
234     }
235 }
236
237 pub fn parse(sess: &ParseSess,
238              cfg: ast::CrateConfig,
239              mut rdr: TtReader,
240              ms: &[Matcher])
241              -> ParseResult {
242     let mut cur_eis = Vec::new();
243     cur_eis.push(initial_matcher_pos(ms.iter()
244                                        .map(|x| (*x).clone())
245                                        .collect(),
246                                      None,
247                                      rdr.peek().sp.lo));
248
249     loop {
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();
253
254         let TokenAndSpan {tok: tok, sp: sp} = rdr.peek();
255
256         /* we append new items to this while we go */
257         loop {
258             let ei = match cur_eis.pop() {
259                 None => break, /* for each Earley Item */
260                 Some(ei) => ei,
261             };
262
263             let idx = ei.idx;
264             let len = ei.elts.len();
265
266             /* at end of sequence */
267             if idx >= len {
268                 // can't move out of `match`es, so:
269                 if ei.up.is_some() {
270                     // hack: a matcher sequence is repeating iff it has a
271                     // parent (the top level is just a container)
272
273
274                     // disregard separator, try to go up
275                     // (remove this condition to make trailing seps ok)
276                     if idx == len {
277                         // pop from the matcher position
278
279                         let mut new_pos = ei.up.clone().unwrap();
280
281                         // update matches (the MBE "parse tree") by appending
282                         // each tree as a subtree.
283
284                         // I bet this is a perf problem: we're preemptively
285                         // doing a lot of array work that will get thrown away
286                         // most of the time.
287
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();
291                             new_pos.matches
292                                    .get_mut(idx)
293                                    .push(Rc::new(MatchedSeq(sub, mk_sp(ei.sp_lo,
294                                                                        sp.hi))));
295                         }
296
297                         new_pos.idx += 1;
298                         cur_eis.push(new_pos);
299                     }
300
301                     // can we go around again?
302
303                     // the *_t vars are workarounds for the lack of unary move
304                     match ei.sep {
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();
311                             ei_t.idx += 1;
312                             next_eis.push(ei_t);
313                         }
314                       }
315                       _ => { // we don't need a separator
316                         let mut ei_t = ei;
317                         ei_t.idx = 0;
318                         cur_eis.push(ei_t);
319                       }
320                     }
321                 } else {
322                     eof_eis.push(ei);
323                 }
324             } else {
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) => {
329                     if zero_ok {
330                         let mut new_ei = ei.clone();
331                         new_ei.idx += 1u;
332                         //we specifically matched zero repeats.
333                         for idx in range(match_idx_lo, match_idx_hi) {
334                             new_ei.matches
335                                   .get_mut(idx)
336                                   .push(Rc::new(MatchedSeq(Vec::new(), sp)));
337                         }
338
339                         cur_eis.push(new_ei);
340                     }
341
342                     let matches = Vec::from_elem(ei.matches.len(), Vec::new());
343                     let ei_t = ei;
344                     cur_eis.push(box MatcherPos {
345                         elts: (*matchers).clone(),
346                         sep: (*sep).clone(),
347                         idx: 0u,
348                         up: Some(ei_t),
349                         matches: matches,
350                         match_lo: match_idx_lo, match_hi: match_idx_hi,
351                         sp_lo: sp.lo
352                     });
353                   }
354                   MatchNonterminal(_,_,_) => { bb_eis.push(ei) }
355                   MatchTok(ref t) => {
356                     let mut ei_t = ei.clone();
357                     //if (token_name_eq(t,&tok)) {
358                     if token::mtwt_token_eq(t,&tok) {
359                         ei_t.idx += 1;
360                         next_eis.push(ei_t);
361                     }
362                   }
363                 }
364             }
365         }
366
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());
373                 }
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());
377             } else {
378                 return Failure(sp, "unexpected end of macro invocation".to_string());
379             }
380         } else {
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()
389                       }
390                       _ => fail!()
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_string(&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());
403                 }
404                 rdr.next_token();
405             } else /* bb_eis.len() == 1 */ {
406                 let mut rust_parser = Parser::new(sess, cfg.clone(), box rdr.clone());
407
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()))));
414                     ei.idx += 1u;
415                   }
416                   _ => fail!()
417                 }
418                 cur_eis.push(ei);
419
420                 for _ in range(0, rust_parser.tokens_consumed) {
421                     let _ = rdr.next_token();
422                 }
423             }
424         }
425
426         assert!(cur_eis.len() > 0u);
427     }
428 }
429
430 pub fn parse_nt(p: &mut Parser, name: &str) -> Nonterminal {
431     match name {
432       "item" => match p.parse_item(Vec::new()) {
433         Some(i) => token::NtItem(i),
434         None => p.fatal("expected an item keyword")
435       },
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) }
444         _ => {
445             let token_str = token::to_string(&p.token);
446             p.fatal((format!("expected ident, found {}",
447                              token_str.as_slice())).as_slice())
448         }
449       },
450       "path" => {
451         token::NtPath(box p.parse_path(LifetimeAndTypesWithoutColons).path)
452       }
453       "meta" => token::NtMeta(p.parse_meta_item()),
454       "tt" => {
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());
457         p.quote_depth -= 1u;
458         res
459       }
460       "matchers" => token::NtMatchers(p.parse_matchers()),
461       _ => {
462           p.fatal(format!("unsupported builtin nonterminal parser: {}",
463                           name).as_slice())
464       }
465     }
466 }