]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/util/parser_testing.rs
rollup merge of #21438: taralx/kill-racycell
[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;
12 use parse::{new_parse_sess};
13 use parse::{ParseSess,string_to_filemap,filemap_to_tts};
14 use parse::{new_parser_from_source_str};
15 use parse::parser::Parser;
16 use parse::token;
17 use ptr::P;
18
19 /// Map a string to tts, using a made-up filename:
20 pub fn string_to_tts(source_str: String) -> Vec<ast::TokenTree> {
21     let ps = new_parse_sess();
22     filemap_to_tts(&ps,
23                    string_to_filemap(&ps, source_str, "bogofile".to_string()))
24 }
25
26 /// Map string to parser (via tts)
27 pub fn string_to_parser<'a>(ps: &'a ParseSess, source_str: String) -> Parser<'a> {
28     new_parser_from_source_str(ps,
29                                Vec::new(),
30                                "bogofile".to_string(),
31                                source_str)
32 }
33
34 fn with_error_checking_parse<T, F>(s: String, f: F) -> T where
35     F: FnOnce(&mut Parser) -> T,
36 {
37     let ps = new_parse_sess();
38     let mut p = string_to_parser(&ps, s);
39     let x = f(&mut p);
40     p.abort_if_errors();
41     x
42 }
43
44 /// Parse a string, return a crate.
45 pub fn string_to_crate (source_str : String) -> ast::Crate {
46     with_error_checking_parse(source_str, |p| {
47         p.parse_crate_mod()
48     })
49 }
50
51 /// Parse a string, return an expr
52 pub fn string_to_expr (source_str : String) -> P<ast::Expr> {
53     with_error_checking_parse(source_str, |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     with_error_checking_parse(source_str, |p| {
61         p.parse_item(Vec::new())
62     })
63 }
64
65 /// Parse a string, return a stmt
66 pub fn string_to_stmt(source_str : String) -> P<ast::Stmt> {
67     with_error_checking_parse(source_str, |p| {
68         p.parse_stmt(Vec::new())
69     })
70 }
71
72 /// Parse a string, return a view item
73 pub fn string_to_view_item (source_str : String) -> ast::ViewItem {
74     with_error_checking_parse(source_str, |p| {
75         p.parse_view_item(Vec::new())
76     })
77 }
78
79 /// Parse a string, return a pat. Uses "irrefutable"... which doesn't
80 /// (currently) affect parsing.
81 pub fn string_to_pat(source_str: String) -> P<ast::Pat> {
82     string_to_parser(&new_parse_sess(), source_str).parse_pat()
83 }
84
85 /// Convert a vector of strings to a vector of ast::Ident's
86 pub fn strs_to_idents(ids: Vec<&str> ) -> Vec<ast::Ident> {
87     ids.iter().map(|u| token::str_to_ident(*u)).collect()
88 }
89
90 /// Does the given string match the pattern? whitespace in the first string
91 /// may be deleted or replaced with other whitespace to match the pattern.
92 /// this function is Unicode-ignorant; fortunately, the careful design of
93 /// UTF-8 mitigates this ignorance.  In particular, this function only collapses
94 /// sequences of \n, \r, ' ', and \t, but it should otherwise tolerate Unicode
95 /// chars. Unsurprisingly, it doesn't do NKF-normalization(?).
96 pub fn matches_codepattern(a : &str, b : &str) -> bool {
97     let mut idx_a = 0;
98     let mut idx_b = 0;
99     loop {
100         if idx_a == a.len() && idx_b == b.len() {
101             return true;
102         }
103         else if idx_a == a.len() {return false;}
104         else if idx_b == b.len() {
105             // maybe the stuff left in a is all ws?
106             if is_whitespace(a.char_at(idx_a)) {
107                 return scan_for_non_ws_or_end(a,idx_a) == a.len();
108             } else {
109                 return false;
110             }
111         }
112         // ws in both given and pattern:
113         else if is_whitespace(a.char_at(idx_a))
114            && is_whitespace(b.char_at(idx_b)) {
115             idx_a = scan_for_non_ws_or_end(a,idx_a);
116             idx_b = scan_for_non_ws_or_end(b,idx_b);
117         }
118         // ws in given only:
119         else if is_whitespace(a.char_at(idx_a)) {
120             idx_a = scan_for_non_ws_or_end(a,idx_a);
121         }
122         // *don't* silently eat ws in expected only.
123         else if a.char_at(idx_a) == b.char_at(idx_b) {
124             idx_a += 1;
125             idx_b += 1;
126         }
127         else {
128             return false;
129         }
130     }
131 }
132
133 /// Given a string and an index, return the first usize >= idx
134 /// that is a non-ws-char or is outside of the legal range of
135 /// the string.
136 fn scan_for_non_ws_or_end(a : &str, idx: usize) -> usize {
137     let mut i = idx;
138     let len = a.len();
139     while (i < len) && (is_whitespace(a.char_at(i))) {
140         i += 1;
141     }
142     i
143 }
144
145 /// Copied from lexer.
146 pub fn is_whitespace(c: char) -> bool {
147     return c == ' ' || c == '\t' || c == '\r' || c == '\n';
148 }
149
150 #[cfg(test)]
151 mod test {
152     use super::*;
153
154     #[test] fn eqmodws() {
155         assert_eq!(matches_codepattern("",""),true);
156         assert_eq!(matches_codepattern("","a"),false);
157         assert_eq!(matches_codepattern("a",""),false);
158         assert_eq!(matches_codepattern("a","a"),true);
159         assert_eq!(matches_codepattern("a b","a   \n\t\r  b"),true);
160         assert_eq!(matches_codepattern("a b ","a   \n\t\r  b"),true);
161         assert_eq!(matches_codepattern("a b","a   \n\t\r  b "),false);
162         assert_eq!(matches_codepattern("a   b","a b"),true);
163         assert_eq!(matches_codepattern("ab","a b"),false);
164         assert_eq!(matches_codepattern("a   b","ab"),true);
165     }
166 }