]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/tests.rs
Rename `Item.node` to `Item.kind`
[rust.git] / src / libsyntax / parse / tests.rs
1 use super::*;
2
3 use crate::ast::{self, Name, PatKind};
4 use crate::attr::first_attr_value_str_by_name;
5 use crate::parse::{ParseSess, PResult};
6 use crate::parse::new_parser_from_source_str;
7 use crate::parse::token::Token;
8 use crate::print::pprust::item_to_string;
9 use crate::ptr::P;
10 use crate::source_map::FilePathMapping;
11 use crate::symbol::{kw, sym};
12 use crate::tests::{matches_codepattern, string_to_stream, with_error_checking_parse};
13 use crate::tokenstream::{DelimSpan, TokenTree, TokenStream};
14 use crate::with_default_globals;
15 use syntax_pos::{Span, BytePos, Pos};
16
17 use std::path::PathBuf;
18
19 /// Parses an item.
20 ///
21 /// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and `Err`
22 /// when a syntax error occurred.
23 fn parse_item_from_source_str(name: FileName, source: String, sess: &ParseSess)
24                                     -> PResult<'_, Option<P<ast::Item>>> {
25     new_parser_from_source_str(sess, name, source).parse_item()
26 }
27
28 // Produces a `syntax_pos::span`.
29 fn sp(a: u32, b: u32) -> Span {
30     Span::with_root_ctxt(BytePos(a), BytePos(b))
31 }
32
33 /// Parses a string, return an expression.
34 fn string_to_expr(source_str : String) -> P<ast::Expr> {
35     let ps = ParseSess::new(FilePathMapping::empty());
36     with_error_checking_parse(source_str, &ps, |p| {
37         p.parse_expr()
38     })
39 }
40
41 /// Parses a string, returns an item.
42 fn string_to_item(source_str : String) -> Option<P<ast::Item>> {
43     let ps = ParseSess::new(FilePathMapping::empty());
44     with_error_checking_parse(source_str, &ps, |p| {
45         p.parse_item()
46     })
47 }
48
49 #[should_panic]
50 #[test] fn bad_path_expr_1() {
51     with_default_globals(|| {
52         string_to_expr("::abc::def::return".to_string());
53     })
54 }
55
56 // Checks the token-tree-ization of macros.
57 #[test]
58 fn string_to_tts_macro () {
59     with_default_globals(|| {
60         let tts: Vec<_> =
61             string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
62         let tts: &[TokenTree] = &tts[..];
63
64         match tts {
65             [
66                 TokenTree::Token(Token { kind: token::Ident(name_macro_rules, false), .. }),
67                 TokenTree::Token(Token { kind: token::Not, .. }),
68                 TokenTree::Token(Token { kind: token::Ident(name_zip, false), .. }),
69                 TokenTree::Delimited(_, macro_delim,  macro_tts)
70             ]
71             if name_macro_rules == &sym::macro_rules && name_zip.as_str() == "zip" => {
72                 let tts = &macro_tts.trees().collect::<Vec<_>>();
73                 match &tts[..] {
74                     [
75                         TokenTree::Delimited(_, first_delim, first_tts),
76                         TokenTree::Token(Token { kind: token::FatArrow, .. }),
77                         TokenTree::Delimited(_, second_delim, second_tts),
78                     ]
79                     if macro_delim == &token::Paren => {
80                         let tts = &first_tts.trees().collect::<Vec<_>>();
81                         match &tts[..] {
82                             [
83                                 TokenTree::Token(Token { kind: token::Dollar, .. }),
84                                 TokenTree::Token(Token { kind: token::Ident(name, false), .. }),
85                             ]
86                             if first_delim == &token::Paren && name.as_str() == "a" => {},
87                             _ => panic!("value 3: {:?} {:?}", first_delim, first_tts),
88                         }
89                         let tts = &second_tts.trees().collect::<Vec<_>>();
90                         match &tts[..] {
91                             [
92                                 TokenTree::Token(Token { kind: token::Dollar, .. }),
93                                 TokenTree::Token(Token { kind: token::Ident(name, false), .. }),
94                             ]
95                             if second_delim == &token::Paren && name.as_str() == "a" => {},
96                             _ => panic!("value 4: {:?} {:?}", second_delim, second_tts),
97                         }
98                     },
99                     _ => panic!("value 2: {:?} {:?}", macro_delim, macro_tts),
100                 }
101             },
102             _ => panic!("value: {:?}",tts),
103         }
104     })
105 }
106
107 #[test]
108 fn string_to_tts_1() {
109     with_default_globals(|| {
110         let tts = string_to_stream("fn a (b : i32) { b; }".to_string());
111
112         let expected = TokenStream::new(vec![
113             TokenTree::token(token::Ident(kw::Fn, false), sp(0, 2)).into(),
114             TokenTree::token(token::Ident(Name::intern("a"), false), sp(3, 4)).into(),
115             TokenTree::Delimited(
116                 DelimSpan::from_pair(sp(5, 6), sp(13, 14)),
117                 token::DelimToken::Paren,
118                 TokenStream::new(vec![
119                     TokenTree::token(token::Ident(Name::intern("b"), false), sp(6, 7)).into(),
120                     TokenTree::token(token::Colon, sp(8, 9)).into(),
121                     TokenTree::token(token::Ident(sym::i32, false), sp(10, 13)).into(),
122                 ]).into(),
123             ).into(),
124             TokenTree::Delimited(
125                 DelimSpan::from_pair(sp(15, 16), sp(20, 21)),
126                 token::DelimToken::Brace,
127                 TokenStream::new(vec![
128                     TokenTree::token(token::Ident(Name::intern("b"), false), sp(17, 18)).into(),
129                     TokenTree::token(token::Semi, sp(18, 19)).into(),
130                 ]).into(),
131             ).into()
132         ]);
133
134         assert_eq!(tts, expected);
135     })
136 }
137
138 #[test] fn parse_use() {
139     with_default_globals(|| {
140         let use_s = "use foo::bar::baz;";
141         let vitem = string_to_item(use_s.to_string()).unwrap();
142         let vitem_s = item_to_string(&vitem);
143         assert_eq!(&vitem_s[..], use_s);
144
145         let use_s = "use foo::bar as baz;";
146         let vitem = string_to_item(use_s.to_string()).unwrap();
147         let vitem_s = item_to_string(&vitem);
148         assert_eq!(&vitem_s[..], use_s);
149     })
150 }
151
152 #[test] fn parse_extern_crate() {
153     with_default_globals(|| {
154         let ex_s = "extern crate foo;";
155         let vitem = string_to_item(ex_s.to_string()).unwrap();
156         let vitem_s = item_to_string(&vitem);
157         assert_eq!(&vitem_s[..], ex_s);
158
159         let ex_s = "extern crate foo as bar;";
160         let vitem = string_to_item(ex_s.to_string()).unwrap();
161         let vitem_s = item_to_string(&vitem);
162         assert_eq!(&vitem_s[..], ex_s);
163     })
164 }
165
166 fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
167     let item = string_to_item(src.to_string()).unwrap();
168
169     struct PatIdentVisitor {
170         spans: Vec<Span>
171     }
172     impl<'a> crate::visit::Visitor<'a> for PatIdentVisitor {
173         fn visit_pat(&mut self, p: &'a ast::Pat) {
174             match p.kind {
175                 PatKind::Ident(_ , ref ident, _) => {
176                     self.spans.push(ident.span.clone());
177                 }
178                 _ => {
179                     crate::visit::walk_pat(self, p);
180                 }
181             }
182         }
183     }
184     let mut v = PatIdentVisitor { spans: Vec::new() };
185     crate::visit::walk_item(&mut v, &item);
186     return v.spans;
187 }
188
189 #[test] fn span_of_self_arg_pat_idents_are_correct() {
190     with_default_globals(|| {
191
192         let srcs = ["impl z { fn a (&self, &myarg: i32) {} }",
193                     "impl z { fn a (&mut self, &myarg: i32) {} }",
194                     "impl z { fn a (&'a self, &myarg: i32) {} }",
195                     "impl z { fn a (self, &myarg: i32) {} }",
196                     "impl z { fn a (self: Foo, &myarg: i32) {} }",
197                     ];
198
199         for &src in &srcs {
200             let spans = get_spans_of_pat_idents(src);
201             let (lo, hi) = (spans[0].lo(), spans[0].hi());
202             assert!("self" == &src[lo.to_usize()..hi.to_usize()],
203                     "\"{}\" != \"self\". src=\"{}\"",
204                     &src[lo.to_usize()..hi.to_usize()], src)
205         }
206     })
207 }
208
209 #[test] fn parse_exprs () {
210     with_default_globals(|| {
211         // just make sure that they parse....
212         string_to_expr("3 + 4".to_string());
213         string_to_expr("a::z.froob(b,&(987+3))".to_string());
214     })
215 }
216
217 #[test] fn attrs_fix_bug () {
218     with_default_globals(|| {
219         string_to_item("pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
220                 -> Result<Box<Writer>, String> {
221 #[cfg(windows)]
222 fn wb() -> c_int {
223     (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
224 }
225
226 #[cfg(unix)]
227 fn wb() -> c_int { O_WRONLY as c_int }
228
229 let mut fflags: c_int = wb();
230 }".to_string());
231     })
232 }
233
234 #[test] fn crlf_doc_comments() {
235     with_default_globals(|| {
236         let sess = ParseSess::new(FilePathMapping::empty());
237
238         let name_1 = FileName::Custom("crlf_source_1".to_string());
239         let source = "/// doc comment\r\nfn foo() {}".to_string();
240         let item = parse_item_from_source_str(name_1, source, &sess)
241             .unwrap().unwrap();
242         let doc = first_attr_value_str_by_name(&item.attrs, sym::doc).unwrap();
243         assert_eq!(doc.as_str(), "/// doc comment");
244
245         let name_2 = FileName::Custom("crlf_source_2".to_string());
246         let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
247         let item = parse_item_from_source_str(name_2, source, &sess)
248             .unwrap().unwrap();
249         let docs = item.attrs.iter().filter(|a| a.path == sym::doc)
250                     .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
251         let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
252         assert_eq!(&docs[..], b);
253
254         let name_3 = FileName::Custom("clrf_source_3".to_string());
255         let source = "/** doc comment\r\n *  with CRLF */\r\nfn foo() {}".to_string();
256         let item = parse_item_from_source_str(name_3, source, &sess).unwrap().unwrap();
257         let doc = first_attr_value_str_by_name(&item.attrs, sym::doc).unwrap();
258         assert_eq!(doc.as_str(), "/** doc comment\n *  with CRLF */");
259     });
260 }
261
262 #[test]
263 fn ttdelim_span() {
264     fn parse_expr_from_source_str(
265         name: FileName, source: String, sess: &ParseSess
266     ) -> PResult<'_, P<ast::Expr>> {
267         new_parser_from_source_str(sess, name, source).parse_expr()
268     }
269
270     with_default_globals(|| {
271         let sess = ParseSess::new(FilePathMapping::empty());
272         let expr = parse_expr_from_source_str(PathBuf::from("foo").into(),
273             "foo!( fn main() { body } )".to_string(), &sess).unwrap();
274
275         let tts: Vec<_> = match expr.kind {
276             ast::ExprKind::Mac(ref mac) => mac.stream().trees().collect(),
277             _ => panic!("not a macro"),
278         };
279
280         let span = tts.iter().rev().next().unwrap().span();
281
282         match sess.source_map().span_to_snippet(span) {
283             Ok(s) => assert_eq!(&s[..], "{ body }"),
284             Err(_) => panic!("could not get snippet"),
285         }
286     });
287 }
288
289 // This tests that when parsing a string (rather than a file) we don't try
290 // and read in a file for a module declaration and just parse a stub.
291 // See `recurse_into_file_modules` in the parser.
292 #[test]
293 fn out_of_line_mod() {
294     with_default_globals(|| {
295         let sess = ParseSess::new(FilePathMapping::empty());
296         let item = parse_item_from_source_str(
297             PathBuf::from("foo").into(),
298             "mod foo { struct S; mod this_does_not_exist; }".to_owned(),
299             &sess,
300         ).unwrap().unwrap();
301
302         if let ast::ItemKind::Mod(ref m) = item.kind {
303             assert!(m.items.len() == 2);
304         } else {
305             panic!();
306         }
307     });
308 }
309
310 #[test]
311 fn eqmodws() {
312     assert_eq!(matches_codepattern("",""),true);
313     assert_eq!(matches_codepattern("","a"),false);
314     assert_eq!(matches_codepattern("a",""),false);
315     assert_eq!(matches_codepattern("a","a"),true);
316     assert_eq!(matches_codepattern("a b","a   \n\t\r  b"),true);
317     assert_eq!(matches_codepattern("a b ","a   \n\t\r  b"),true);
318     assert_eq!(matches_codepattern("a b","a   \n\t\r  b "),false);
319     assert_eq!(matches_codepattern("a   b","a b"),true);
320     assert_eq!(matches_codepattern("ab","a b"),false);
321     assert_eq!(matches_codepattern("a   b","ab"),true);
322     assert_eq!(matches_codepattern(" a   b","ab"),true);
323 }
324
325 #[test]
326 fn pattern_whitespace() {
327     assert_eq!(matches_codepattern("","\x0C"), false);
328     assert_eq!(matches_codepattern("a b ","a   \u{0085}\n\t\r  b"),true);
329     assert_eq!(matches_codepattern("a b","a   \u{0085}\n\t\r  b "),false);
330 }
331
332 #[test]
333 fn non_pattern_whitespace() {
334     // These have the property 'White_Space' but not 'Pattern_White_Space'
335     assert_eq!(matches_codepattern("a b","a\u{2002}b"), false);
336     assert_eq!(matches_codepattern("a   b","a\u{2002}b"), false);
337     assert_eq!(matches_codepattern("\u{205F}a   b","ab"), false);
338     assert_eq!(matches_codepattern("a  \u{3000}b","ab"), false);
339 }