]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/util/parser_testing.rs
Provide specific label for patern parsing error
[rust.git] / src / libsyntax / util / parser_testing.rs
1 // Copyright 2013 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 use ast::{self, Ident};
12 use source_map::FilePathMapping;
13 use parse::{ParseSess, PResult, source_file_to_stream};
14 use parse::{lexer, new_parser_from_source_str};
15 use parse::parser::Parser;
16 use ptr::P;
17 use tokenstream::TokenStream;
18 use std::iter::Peekable;
19 use std::path::PathBuf;
20
21 /// Map a string to tts, using a made-up filename:
22 pub fn string_to_stream(source_str: String) -> TokenStream {
23     let ps = ParseSess::new(FilePathMapping::empty());
24     source_file_to_stream(&ps, ps.source_map()
25                              .new_source_file(PathBuf::from("bogofile").into(), source_str), None)
26 }
27
28 /// Map string to parser (via tts)
29 pub fn string_to_parser<'a>(ps: &'a ParseSess, source_str: String) -> Parser<'a> {
30     new_parser_from_source_str(ps, PathBuf::from("bogofile").into(), source_str)
31 }
32
33 fn with_error_checking_parse<'a, T, F>(s: String, ps: &'a ParseSess, f: F) -> T where
34     F: FnOnce(&mut Parser<'a>) -> PResult<'a, T>,
35 {
36     let mut p = string_to_parser(&ps, s);
37     let x = panictry!(f(&mut p));
38     p.abort_if_errors();
39     x
40 }
41
42 /// Parse a string, return a crate.
43 pub fn string_to_crate (source_str : String) -> ast::Crate {
44     let ps = ParseSess::new(FilePathMapping::empty());
45     with_error_checking_parse(source_str, &ps, |p| {
46         p.parse_crate_mod()
47     })
48 }
49
50 /// Parse a string, return an expr
51 pub fn string_to_expr (source_str : String) -> P<ast::Expr> {
52     let ps = ParseSess::new(FilePathMapping::empty());
53     with_error_checking_parse(source_str, &ps, |p| {
54         p.parse_expr()
55     })
56 }
57
58 /// Parse a string, return an item
59 pub fn string_to_item (source_str : String) -> Option<P<ast::Item>> {
60     let ps = ParseSess::new(FilePathMapping::empty());
61     with_error_checking_parse(source_str, &ps, |p| {
62         p.parse_item()
63     })
64 }
65
66 /// Parse a string, return a pat. Uses "irrefutable"... which doesn't
67 /// (currently) affect parsing.
68 pub fn string_to_pat(source_str: String) -> P<ast::Pat> {
69     let ps = ParseSess::new(FilePathMapping::empty());
70     with_error_checking_parse(source_str, &ps, |p| {
71         p.parse_pat(None)
72     })
73 }
74
75 /// Convert a vector of strings to a vector of Ident's
76 pub fn strs_to_idents(ids: Vec<&str> ) -> Vec<Ident> {
77     ids.iter().map(|u| Ident::from_str(*u)).collect()
78 }
79
80 /// Does the given string match the pattern? whitespace in the first string
81 /// may be deleted or replaced with other whitespace to match the pattern.
82 /// This function is relatively Unicode-ignorant; fortunately, the careful design
83 /// of UTF-8 mitigates this ignorance. It doesn't do NKF-normalization(?).
84 pub fn matches_codepattern(a : &str, b : &str) -> bool {
85     let mut a_iter = a.chars().peekable();
86     let mut b_iter = b.chars().peekable();
87
88     loop {
89         let (a, b) = match (a_iter.peek(), b_iter.peek()) {
90             (None, None) => return true,
91             (None, _) => return false,
92             (Some(&a), None) => {
93                 if is_pattern_whitespace(a) {
94                     break // trailing whitespace check is out of loop for borrowck
95                 } else {
96                     return false
97                 }
98             }
99             (Some(&a), Some(&b)) => (a, b)
100         };
101
102         if is_pattern_whitespace(a) && is_pattern_whitespace(b) {
103             // skip whitespace for a and b
104             scan_for_non_ws_or_end(&mut a_iter);
105             scan_for_non_ws_or_end(&mut b_iter);
106         } else if is_pattern_whitespace(a) {
107             // skip whitespace for a
108             scan_for_non_ws_or_end(&mut a_iter);
109         } else if a == b {
110             a_iter.next();
111             b_iter.next();
112         } else {
113             return false
114         }
115     }
116
117     // check if a has *only* trailing whitespace
118     a_iter.all(is_pattern_whitespace)
119 }
120
121 /// Advances the given peekable `Iterator` until it reaches a non-whitespace character
122 fn scan_for_non_ws_or_end<I: Iterator<Item= char>>(iter: &mut Peekable<I>) {
123     while lexer::is_pattern_whitespace(iter.peek().cloned()) {
124         iter.next();
125     }
126 }
127
128 pub fn is_pattern_whitespace(c: char) -> bool {
129     lexer::is_pattern_whitespace(Some(c))
130 }
131
132 #[cfg(test)]
133 mod tests {
134     use super::*;
135
136     #[test]
137     fn eqmodws() {
138         assert_eq!(matches_codepattern("",""),true);
139         assert_eq!(matches_codepattern("","a"),false);
140         assert_eq!(matches_codepattern("a",""),false);
141         assert_eq!(matches_codepattern("a","a"),true);
142         assert_eq!(matches_codepattern("a b","a   \n\t\r  b"),true);
143         assert_eq!(matches_codepattern("a b ","a   \n\t\r  b"),true);
144         assert_eq!(matches_codepattern("a b","a   \n\t\r  b "),false);
145         assert_eq!(matches_codepattern("a   b","a b"),true);
146         assert_eq!(matches_codepattern("ab","a b"),false);
147         assert_eq!(matches_codepattern("a   b","ab"),true);
148         assert_eq!(matches_codepattern(" a   b","ab"),true);
149     }
150
151     #[test]
152     fn pattern_whitespace() {
153         assert_eq!(matches_codepattern("","\x0C"), false);
154         assert_eq!(matches_codepattern("a b ","a   \u{0085}\n\t\r  b"),true);
155         assert_eq!(matches_codepattern("a b","a   \u{0085}\n\t\r  b "),false);
156     }
157
158     #[test]
159     fn non_pattern_whitespace() {
160         // These have the property 'White_Space' but not 'Pattern_White_Space'
161         assert_eq!(matches_codepattern("a b","a\u{2002}b"), false);
162         assert_eq!(matches_codepattern("a   b","a\u{2002}b"), false);
163         assert_eq!(matches_codepattern("\u{205F}a   b","ab"), false);
164         assert_eq!(matches_codepattern("a  \u{3000}b","ab"), false);
165     }
166 }