]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/tt/macro_parser.rs
Rollup merge of #41957 - llogiq:clippy-libsyntax, r=petrochenkov
[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 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:
40 //!
41 //! ```text, ignore
42 //! Start parsing a a a a b against [· a $( a )* a b].
43 //!
44 //! Remaining input: a a a a b
45 //! next_eis: [· a $( a )* a b]
46 //!
47 //! - - - Advance over an a. - - -
48 //!
49 //! Remaining input: a a a b
50 //! cur: [a · $( a )* a b]
51 //! Descend/Skip (first item).
52 //! next: [a $( · a )* a b]  [a $( a )* · a b].
53 //!
54 //! - - - Advance over an a. - - -
55 //!
56 //! Remaining input: a a b
57 //! cur: [a $( a · )* a b]  next: [a $( a )* a · b]
58 //! Finish/Repeat (first item)
59 //! next: [a $( a )* · a b]  [a $( · a )* a b]  [a $( a )* a · b]
60 //!
61 //! - - - Advance over an a. - - - (this looks exactly like the last step)
62 //!
63 //! Remaining input: a b
64 //! cur: [a $( a · )* a b]  next: [a $( a )* a · b]
65 //! Finish/Repeat (first item)
66 //! next: [a $( a )* · a b]  [a $( · a )* a b]  [a $( a )* a · b]
67 //!
68 //! - - - Advance over an a. - - - (this looks exactly like the last step)
69 //!
70 //! Remaining input: 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]
74 //!
75 //! - - - Advance over a b. - - -
76 //!
77 //! Remaining input: ''
78 //! eof: [a $( a )* a b ·]
79 //! ```
80
81 pub use self::NamedMatch::*;
82 pub use self::ParseResult::*;
83 use self::TokenTreeOrTokenTreeVec::*;
84
85 use ast::Ident;
86 use syntax_pos::{self, BytePos, Span};
87 use codemap::Spanned;
88 use errors::FatalError;
89 use ext::tt::quoted::{self, TokenTree};
90 use parse::{Directory, ParseSess};
91 use parse::parser::{PathStyle, Parser};
92 use parse::token::{self, DocComment, Token, Nonterminal};
93 use print::pprust;
94 use symbol::keywords;
95 use tokenstream::TokenStream;
96 use util::small_vector::SmallVector;
97
98 use std::mem;
99 use std::rc::Rc;
100 use std::collections::HashMap;
101 use std::collections::hash_map::Entry::{Vacant, Occupied};
102
103 // To avoid costly uniqueness checks, we require that `MatchSeq` always has
104 // a nonempty body.
105
106 #[derive(Clone)]
107 enum TokenTreeOrTokenTreeVec {
108     Tt(TokenTree),
109     TtSeq(Vec<TokenTree>),
110 }
111
112 impl TokenTreeOrTokenTreeVec {
113     fn len(&self) -> usize {
114         match *self {
115             TtSeq(ref v) => v.len(),
116             Tt(ref tt) => tt.len(),
117         }
118     }
119
120     fn get_tt(&self, index: usize) -> TokenTree {
121         match *self {
122             TtSeq(ref v) => v[index].clone(),
123             Tt(ref tt) => tt.get_tt(index),
124         }
125     }
126 }
127
128 /// an unzipping of `TokenTree`s
129 #[derive(Clone)]
130 struct MatcherTtFrame {
131     elts: TokenTreeOrTokenTreeVec,
132     idx: usize,
133 }
134
135 #[derive(Clone)]
136 struct MatcherPos {
137     stack: Vec<MatcherTtFrame>,
138     top_elts: TokenTreeOrTokenTreeVec,
139     sep: Option<Token>,
140     idx: usize,
141     up: Option<Box<MatcherPos>>,
142     matches: Vec<Vec<Rc<NamedMatch>>>,
143     match_lo: usize,
144     match_cur: usize,
145     match_hi: usize,
146     sp_lo: BytePos,
147 }
148
149 pub type NamedParseResult = ParseResult<HashMap<Ident, Rc<NamedMatch>>>;
150
151 pub fn count_names(ms: &[TokenTree]) -> usize {
152     ms.iter().fold(0, |count, elt| {
153         count + match *elt {
154             TokenTree::Sequence(_, ref seq) => {
155                 seq.num_captures
156             }
157             TokenTree::Delimited(_, ref delim) => {
158                 count_names(&delim.tts)
159             }
160             TokenTree::MetaVarDecl(..) => {
161                 1
162             }
163             TokenTree::Token(..) => 0,
164         }
165     })
166 }
167
168 fn initial_matcher_pos(ms: Vec<TokenTree>, lo: BytePos) -> Box<MatcherPos> {
169     let match_idx_hi = count_names(&ms[..]);
170     let matches = create_matches(match_idx_hi);
171     Box::new(MatcherPos {
172         stack: vec![],
173         top_elts: TtSeq(ms),
174         sep: None,
175         idx: 0,
176         up: None,
177         matches: matches,
178         match_lo: 0,
179         match_cur: 0,
180         match_hi: match_idx_hi,
181         sp_lo: lo
182     })
183 }
184
185 /// `NamedMatch` is a pattern-match result for a single `token::MATCH_NONTERMINAL`:
186 /// so it is associated with a single ident in a parse, and all
187 /// `MatchedNonterminal`s in the `NamedMatch` have the same nonterminal type
188 /// (expr, item, etc). Each leaf in a single `NamedMatch` corresponds to a
189 /// single `token::MATCH_NONTERMINAL` in the `TokenTree` that produced it.
190 ///
191 /// The in-memory structure of a particular `NamedMatch` represents the match
192 /// that occurred when a particular subset of a matcher was applied to a
193 /// particular token tree.
194 ///
195 /// The width of each `MatchedSeq` in the `NamedMatch`, and the identity of
196 /// the `MatchedNonterminal`s, will depend on the token tree it was applied
197 /// to: each `MatchedSeq` corresponds to a single `TTSeq` in the originating
198 /// token tree. The depth of the `NamedMatch` structure will therefore depend
199 /// only on the nesting depth of `ast::TTSeq`s in the originating
200 /// token tree it was derived from.
201
202 pub enum NamedMatch {
203     MatchedSeq(Vec<Rc<NamedMatch>>, syntax_pos::Span),
204     MatchedNonterminal(Rc<Nonterminal>)
205 }
206
207 fn nameize<I: Iterator<Item=Rc<NamedMatch>>>(sess: &ParseSess, ms: &[TokenTree], mut res: I)
208                                              -> NamedParseResult {
209     fn n_rec<I: Iterator<Item=Rc<NamedMatch>>>(sess: &ParseSess, m: &TokenTree, mut res: &mut I,
210              ret_val: &mut HashMap<Ident, Rc<NamedMatch>>)
211              -> Result<(), (syntax_pos::Span, String)> {
212         match *m {
213             TokenTree::Sequence(_, ref seq) => {
214                 for next_m in &seq.tts {
215                     n_rec(sess, next_m, res.by_ref(), ret_val)?
216                 }
217             }
218             TokenTree::Delimited(_, ref delim) => {
219                 for next_m in &delim.tts {
220                     n_rec(sess, next_m, res.by_ref(), ret_val)?;
221                 }
222             }
223             TokenTree::MetaVarDecl(span, _, id) if id.name == keywords::Invalid.name() => {
224                 if sess.missing_fragment_specifiers.borrow_mut().remove(&span) {
225                     return Err((span, "missing fragment specifier".to_string()));
226                 }
227             }
228             TokenTree::MetaVarDecl(sp, bind_name, _) => {
229                 match ret_val.entry(bind_name) {
230                     Vacant(spot) => {
231                         spot.insert(res.next().unwrap());
232                     }
233                     Occupied(..) => {
234                         return Err((sp, format!("duplicated bind name: {}", bind_name)))
235                     }
236                 }
237             }
238             TokenTree::Token(..) => (),
239         }
240
241         Ok(())
242     }
243
244     let mut ret_val = HashMap::new();
245     for m in ms {
246         match n_rec(sess, m, res.by_ref(), &mut ret_val) {
247             Ok(_) => {},
248             Err((sp, msg)) => return Error(sp, msg),
249         }
250     }
251
252     Success(ret_val)
253 }
254
255 pub enum ParseResult<T> {
256     Success(T),
257     /// Arm failed to match. If the second parameter is `token::Eof`, it
258     /// indicates an unexpected end of macro invocation. Otherwise, it
259     /// indicates that no rules expected the given token.
260     Failure(syntax_pos::Span, Token),
261     /// Fatal error (malformed macro?). Abort compilation.
262     Error(syntax_pos::Span, String)
263 }
264
265 pub fn parse_failure_msg(tok: Token) -> String {
266     match tok {
267         token::Eof => "unexpected end of macro invocation".to_string(),
268         _ => format!("no rules expected the token `{}`", pprust::token_to_string(&tok)),
269     }
270 }
271
272 /// Perform a token equality check, ignoring syntax context (that is, an unhygienic comparison)
273 fn token_name_eq(t1 : &Token, t2 : &Token) -> bool {
274     if let (Some(id1), Some(id2)) = (t1.ident(), t2.ident()) {
275         id1.name == id2.name
276     } else if let (&token::Lifetime(id1), &token::Lifetime(id2)) = (t1, t2) {
277         id1.name == id2.name
278     } else {
279         *t1 == *t2
280     }
281 }
282
283 fn create_matches(len: usize) -> Vec<Vec<Rc<NamedMatch>>> {
284     (0..len).into_iter().map(|_| Vec::new()).collect()
285 }
286
287 fn inner_parse_loop(sess: &ParseSess,
288                     cur_eis: &mut SmallVector<Box<MatcherPos>>,
289                     next_eis: &mut Vec<Box<MatcherPos>>,
290                     eof_eis: &mut SmallVector<Box<MatcherPos>>,
291                     bb_eis: &mut SmallVector<Box<MatcherPos>>,
292                     token: &Token,
293                     span: syntax_pos::Span)
294                     -> ParseResult<()> {
295     while let Some(mut ei) = cur_eis.pop() {
296         // When unzipped trees end, remove them
297         while ei.idx >= ei.top_elts.len() {
298             match ei.stack.pop() {
299                 Some(MatcherTtFrame { elts, idx }) => {
300                     ei.top_elts = elts;
301                     ei.idx = idx + 1;
302                 }
303                 None => break
304             }
305         }
306
307         let idx = ei.idx;
308         let len = ei.top_elts.len();
309
310         // at end of sequence
311         if idx >= len {
312             // We are repeating iff there is a parent
313             if ei.up.is_some() {
314                 // Disregarding the separator, add the "up" case to the tokens that should be
315                 // examined.
316                 // (remove this condition to make trailing seps ok)
317                 if idx == len {
318                     let mut new_pos = ei.up.clone().unwrap();
319
320                     // update matches (the MBE "parse tree") by appending
321                     // each tree as a subtree.
322
323                     // I bet this is a perf problem: we're preemptively
324                     // doing a lot of array work that will get thrown away
325                     // most of the time.
326
327                     // Only touch the binders we have actually bound
328                     for idx in ei.match_lo..ei.match_hi {
329                         let sub = ei.matches[idx].clone();
330                         new_pos.matches[idx]
331                             .push(Rc::new(MatchedSeq(sub, Span { lo: ei.sp_lo, ..span })));
332                     }
333
334                     new_pos.match_cur = ei.match_hi;
335                     new_pos.idx += 1;
336                     cur_eis.push(new_pos);
337                 }
338
339                 // Check if we need a separator
340                 if idx == len && ei.sep.is_some() {
341                     // We have a separator, and it is the current token.
342                     if ei.sep.as_ref().map(|sep| token_name_eq(token, sep)).unwrap_or(false) {
343                         ei.idx += 1;
344                         next_eis.push(ei);
345                     }
346                 } else { // we don't need a separator
347                     ei.match_cur = ei.match_lo;
348                     ei.idx = 0;
349                     cur_eis.push(ei);
350                 }
351             } else {
352                 // We aren't repeating, so we must be potentially at the end of the input.
353                 eof_eis.push(ei);
354             }
355         } else {
356             match ei.top_elts.get_tt(idx) {
357                 /* need to descend into sequence */
358                 TokenTree::Sequence(sp, seq) => {
359                     if seq.op == quoted::KleeneOp::ZeroOrMore {
360                         // Examine the case where there are 0 matches of this sequence
361                         let mut new_ei = ei.clone();
362                         new_ei.match_cur += seq.num_captures;
363                         new_ei.idx += 1;
364                         for idx in ei.match_cur..ei.match_cur + seq.num_captures {
365                             new_ei.matches[idx].push(Rc::new(MatchedSeq(vec![], sp)));
366                         }
367                         cur_eis.push(new_ei);
368                     }
369
370                     // Examine the case where there is at least one match of this sequence
371                     let matches = create_matches(ei.matches.len());
372                     cur_eis.push(Box::new(MatcherPos {
373                         stack: vec![],
374                         sep: seq.separator.clone(),
375                         idx: 0,
376                         matches: matches,
377                         match_lo: ei.match_cur,
378                         match_cur: ei.match_cur,
379                         match_hi: ei.match_cur + seq.num_captures,
380                         up: Some(ei),
381                         sp_lo: sp.lo,
382                         top_elts: Tt(TokenTree::Sequence(sp, seq)),
383                     }));
384                 }
385                 TokenTree::MetaVarDecl(span, _, id) if id.name == keywords::Invalid.name() => {
386                     if sess.missing_fragment_specifiers.borrow_mut().remove(&span) {
387                         return Error(span, "missing fragment specifier".to_string());
388                     }
389                 }
390                 TokenTree::MetaVarDecl(..) => {
391                     // Built-in nonterminals never start with these tokens,
392                     // so we can eliminate them from consideration.
393                     match *token {
394                         token::CloseDelim(_) => {},
395                         _ => bb_eis.push(ei),
396                     }
397                 }
398                 seq @ TokenTree::Delimited(..) | seq @ TokenTree::Token(_, DocComment(..)) => {
399                     let lower_elts = mem::replace(&mut ei.top_elts, Tt(seq));
400                     let idx = ei.idx;
401                     ei.stack.push(MatcherTtFrame {
402                         elts: lower_elts,
403                         idx: idx,
404                     });
405                     ei.idx = 0;
406                     cur_eis.push(ei);
407                 }
408                 TokenTree::Token(_, ref t) => {
409                     if token_name_eq(t, token) {
410                         ei.idx += 1;
411                         next_eis.push(ei);
412                     }
413                 }
414             }
415         }
416     }
417
418     Success(())
419 }
420
421 pub fn parse(sess: &ParseSess, tts: TokenStream, ms: &[TokenTree], directory: Option<Directory>)
422              -> NamedParseResult {
423     let mut parser = Parser::new(sess, tts, directory, true);
424     let mut cur_eis = SmallVector::one(initial_matcher_pos(ms.to_owned(), parser.span.lo));
425     let mut next_eis = Vec::new(); // or proceed normally
426
427     loop {
428         let mut bb_eis = SmallVector::new(); // black-box parsed by parser.rs
429         let mut eof_eis = SmallVector::new();
430         assert!(next_eis.is_empty());
431
432         match inner_parse_loop(sess, &mut cur_eis, &mut next_eis, &mut eof_eis, &mut bb_eis,
433                                &parser.token, parser.span) {
434             Success(_) => {},
435             Failure(sp, tok) => return Failure(sp, tok),
436             Error(sp, msg) => return Error(sp, msg),
437         }
438
439         // inner parse loop handled all cur_eis, so it's empty
440         assert!(cur_eis.is_empty());
441
442         /* error messages here could be improved with links to orig. rules */
443         if token_name_eq(&parser.token, &token::Eof) {
444             if eof_eis.len() == 1 {
445                 let matches = eof_eis[0].matches.iter_mut().map(|mut dv| dv.pop().unwrap());
446                 return nameize(sess, ms, matches);
447             } else if eof_eis.len() > 1 {
448                 return Error(parser.span, "ambiguity: multiple successful parses".to_string());
449             } else {
450                 return Failure(parser.span, token::Eof);
451             }
452         } else if (!bb_eis.is_empty() && !next_eis.is_empty()) || bb_eis.len() > 1 {
453             let nts = bb_eis.iter().map(|ei| match ei.top_elts.get_tt(ei.idx) {
454                 TokenTree::MetaVarDecl(_, bind, name) => {
455                     format!("{} ('{}')", name, bind)
456                 }
457                 _ => panic!()
458             }).collect::<Vec<String>>().join(" or ");
459
460             return Error(parser.span, format!(
461                 "local ambiguity: multiple parsing options: {}",
462                 match next_eis.len() {
463                     0 => format!("built-in NTs {}.", nts),
464                     1 => format!("built-in NTs {} or 1 other option.", nts),
465                     n => format!("built-in NTs {} or {} other options.", nts, n),
466                 }
467             ));
468         } else if bb_eis.is_empty() && next_eis.is_empty() {
469             return Failure(parser.span, parser.token);
470         } else if !next_eis.is_empty() {
471             /* Now process the next token */
472             cur_eis.extend(next_eis.drain(..));
473             parser.bump();
474         } else /* bb_eis.len() == 1 */ {
475             let mut ei = bb_eis.pop().unwrap();
476             if let TokenTree::MetaVarDecl(span, _, ident) = ei.top_elts.get_tt(ei.idx) {
477                 let match_cur = ei.match_cur;
478                 ei.matches[match_cur].push(Rc::new(MatchedNonterminal(
479                             Rc::new(parse_nt(&mut parser, span, &ident.name.as_str())))));
480                 ei.idx += 1;
481                 ei.match_cur += 1;
482             } else {
483                 unreachable!()
484             }
485             cur_eis.push(ei);
486         }
487
488         assert!(!cur_eis.is_empty());
489     }
490 }
491
492 fn parse_nt<'a>(p: &mut Parser<'a>, sp: Span, name: &str) -> Nonterminal {
493     if name == "tt" {
494         return token::NtTT(p.parse_token_tree());
495     }
496     // check at the beginning and the parser checks after each bump
497     p.process_potential_macro_variable();
498     match name {
499         "item" => match panictry!(p.parse_item()) {
500             Some(i) => token::NtItem(i),
501             None => {
502                 p.fatal("expected an item keyword").emit();
503                 panic!(FatalError);
504             }
505         },
506         "block" => token::NtBlock(panictry!(p.parse_block())),
507         "stmt" => match panictry!(p.parse_stmt()) {
508             Some(s) => token::NtStmt(s),
509             None => {
510                 p.fatal("expected a statement").emit();
511                 panic!(FatalError);
512             }
513         },
514         "pat" => token::NtPat(panictry!(p.parse_pat())),
515         "expr" => token::NtExpr(panictry!(p.parse_expr())),
516         "ty" => token::NtTy(panictry!(p.parse_ty())),
517         // this could be handled like a token, since it is one
518         "ident" => match p.token {
519             token::Ident(sn) => {
520                 p.bump();
521                 token::NtIdent(Spanned::<Ident>{node: sn, span: p.prev_span})
522             }
523             _ => {
524                 let token_str = pprust::token_to_string(&p.token);
525                 p.fatal(&format!("expected ident, found {}",
526                                  &token_str[..])).emit();
527                 panic!(FatalError)
528             }
529         },
530         "path" => {
531             token::NtPath(panictry!(p.parse_path(PathStyle::Type)))
532         },
533         "meta" => token::NtMeta(panictry!(p.parse_meta_item())),
534         "vis" => token::NtVis(panictry!(p.parse_visibility(true))),
535         // this is not supposed to happen, since it has been checked
536         // when compiling the macro.
537         _ => p.span_bug(sp, "invalid fragment specifier")
538     }
539 }