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