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