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