blob: d86e66a849834706c381b617ff8b3ad05d908faf [file] [log] [blame]
David Tolnayecd024d2018-07-21 09:07:56 -07001#![recursion_limit = "1024"]
Nika Layzella2a1a4a2017-11-19 11:33:17 -05002#![feature(rustc_private)]
3
Michael Layzell53fc31a2017-06-07 09:21:53 -04004//! The tests in this module do the following:
5//!
David Tolnaycfa5cc02017-11-13 01:05:11 -08006//! 1. Parse a given expression in both `syn` and `libsyntax`.
Michael Layzell53fc31a2017-06-07 09:21:53 -04007//! 2. Fold over the expression adding brackets around each subexpression (with
David Tolnaycfa5cc02017-11-13 01:05:11 -08008//! some complications - see the `syn_brackets` and `libsyntax_brackets`
Michael Layzell53fc31a2017-06-07 09:21:53 -04009//! methods).
10//! 3. Serialize the `syn` expression back into a string, and re-parse it with
David Tolnaycfa5cc02017-11-13 01:05:11 -080011//! `libsyntax`.
David Tolnay0ccb6d12018-08-14 22:43:00 -070012//! 4. Respan all of the expressions, replacing the spans with the default
13//! spans.
Michael Layzell53fc31a2017-06-07 09:21:53 -040014//! 5. Compare the expressions with one another, if they are not equal fail.
15
16#[macro_use]
17extern crate quote;
David Tolnayee97dbf2017-11-19 14:24:38 -080018extern crate rayon;
David Tolnayd1c31cc2018-08-24 14:47:15 -040019extern crate regex;
David Tolnayc8659922018-08-14 22:40:50 -070020extern crate rustc_data_structures;
David Tolnay0eab7d92018-09-26 22:10:40 -070021#[macro_use]
22extern crate smallvec;
Michael Layzell53fc31a2017-06-07 09:21:53 -040023extern crate syn;
David Tolnaycfa5cc02017-11-13 01:05:11 -080024extern crate syntax;
Michael Layzell53fc31a2017-06-07 09:21:53 -040025extern crate walkdir;
Michael Layzell53fc31a2017-06-07 09:21:53 -040026
David Tolnayc3f98562018-11-02 08:55:05 -070027mod features;
28
David Tolnay51382052017-12-27 13:46:21 -050029use rayon::iter::{IntoParallelIterator, ParallelIterator};
David Tolnayd1c31cc2018-08-24 14:47:15 -040030use regex::Regex;
David Tolnaycfa5cc02017-11-13 01:05:11 -080031use syntax::ast;
32use syntax::ptr::P;
Igor Gnatenko951a52b2018-03-12 10:33:33 +010033use walkdir::{DirEntry, WalkDir};
David Tolnayee97dbf2017-11-19 14:24:38 -080034
35use std::fs::File;
36use std::io::Read;
David Tolnay3eaf7d82017-12-17 23:14:52 -080037use std::process;
David Tolnayee97dbf2017-11-19 14:24:38 -080038use std::sync::atomic::{AtomicUsize, Ordering};
Michael Layzell53fc31a2017-06-07 09:21:53 -040039
David Tolnayecd024d2018-07-21 09:07:56 -070040use common::eq::SpanlessEq;
41use common::parse;
Michael Layzell53fc31a2017-06-07 09:21:53 -040042
Michael Layzell53fc31a2017-06-07 09:21:53 -040043#[macro_use]
David Tolnaydd125562017-12-31 02:16:22 -050044mod macros;
45
46#[allow(dead_code)]
Michael Layzell53fc31a2017-06-07 09:21:53 -040047mod common;
48
49/// Test some pre-set expressions chosen by us.
50#[test]
51fn test_simple_precedence() {
52 const EXPRS: &[&str] = &[
53 "1 + 2 * 3 + 4",
54 "1 + 2 * ( 3 + 4 )",
55 "{ for i in r { } *some_ptr += 1; }",
56 "{ loop { break 5; } }",
57 "{ if true { () }.mthd() }",
Nika Layzell3aa0dc72017-12-04 13:41:28 -050058 "{ for i in unsafe { 20 } { } }",
Michael Layzell53fc31a2017-06-07 09:21:53 -040059 ];
60
61 let mut failed = 0;
62
63 for input in EXPRS {
64 let expr = if let Some(expr) = parse::syn_expr(input) {
65 expr
66 } else {
67 failed += 1;
68 continue;
69 };
70
71 let pf = match test_expressions(vec![expr]) {
72 (1, 0) => "passed",
73 (0, 1) => {
74 failed += 1;
75 "failed"
76 }
77 _ => unreachable!(),
78 };
79 errorf!("=== {}: {}\n", input, pf);
80 }
81
82 if failed > 0 {
83 panic!("Failed {} tests", failed);
84 }
85}
86
87/// Test expressions from rustc, like in `test_round_trip`.
88#[test]
89fn test_rustc_precedence() {
Alex Crichton86374772017-07-07 20:39:28 -070090 common::clone_rust();
Michael Layzell53fc31a2017-06-07 09:21:53 -040091 let abort_after = common::abort_after();
92 if abort_after == 0 {
93 panic!("Skipping all precedence tests");
94 }
95
David Tolnayee97dbf2017-11-19 14:24:38 -080096 let passed = AtomicUsize::new(0);
97 let failed = AtomicUsize::new(0);
Michael Layzell53fc31a2017-06-07 09:21:53 -040098
David Tolnayd1c31cc2018-08-24 14:47:15 -040099 // 2018 edition is hard
100 let edition_regex = Regex::new(r"\b(async|try)[!(]").unwrap();
101
David Tolnayee97dbf2017-11-19 14:24:38 -0800102 WalkDir::new("tests/rust")
Igor Gnatenko951a52b2018-03-12 10:33:33 +0100103 .sort_by(|a, b| a.file_name().cmp(b.file_name()))
David Tolnayee97dbf2017-11-19 14:24:38 -0800104 .into_iter()
105 .filter_entry(common::base_dir_filter)
106 .collect::<Result<Vec<DirEntry>, walkdir::Error>>()
107 .unwrap()
108 .into_par_iter()
David Tolnay51382052017-12-27 13:46:21 -0500109 .for_each(|entry| {
110 let path = entry.path();
111 if path.is_dir() {
112 return;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400113 }
David Tolnay51382052017-12-27 13:46:21 -0500114
115 // Our version of `libsyntax` can't parse this tests
David Tolnay65fb5662018-05-20 20:02:28 -0700116 if path
117 .to_str()
David Tolnay51382052017-12-27 13:46:21 -0500118 .unwrap()
119 .ends_with("optional_comma_in_match_arm.rs")
120 {
121 return;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400122 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400123
David Tolnay51382052017-12-27 13:46:21 -0500124 let mut file = File::open(path).unwrap();
125 let mut content = String::new();
126 file.read_to_string(&mut content).unwrap();
David Tolnayd1c31cc2018-08-24 14:47:15 -0400127 let content = edition_regex.replace_all(&content, "_$0");
Michael Layzell53fc31a2017-06-07 09:21:53 -0400128
David Tolnay51382052017-12-27 13:46:21 -0500129 let (l_passed, l_failed) = match syn::parse_file(&content) {
130 Ok(file) => {
131 let exprs = collect_exprs(file);
132 test_expressions(exprs)
133 }
134 Err(msg) => {
135 errorf!("syn failed to parse\n{:?}\n", msg);
136 (0, 1)
137 }
138 };
David Tolnayee97dbf2017-11-19 14:24:38 -0800139
David Tolnay51382052017-12-27 13:46:21 -0500140 errorf!(
141 "=== {}: {} passed | {} failed\n",
142 path.display(),
143 l_passed,
144 l_failed
145 );
146
147 passed.fetch_add(l_passed, Ordering::SeqCst);
148 let prev_failed = failed.fetch_add(l_failed, Ordering::SeqCst);
149
150 if prev_failed + l_failed >= abort_after {
151 process::exit(1);
152 }
153 });
David Tolnayee97dbf2017-11-19 14:24:38 -0800154
155 let passed = passed.load(Ordering::SeqCst);
156 let failed = failed.load(Ordering::SeqCst);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400157
158 errorf!("\n===== Precedence Test Results =====\n");
159 errorf!("{} passed | {} failed\n", passed, failed);
160
Michael Layzell53fc31a2017-06-07 09:21:53 -0400161 if failed > 0 {
162 panic!("{} failures", failed);
163 }
164}
165
David Tolnayee97dbf2017-11-19 14:24:38 -0800166fn test_expressions(exprs: Vec<syn::Expr>) -> (usize, usize) {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400167 let mut passed = 0;
168 let mut failed = 0;
169
David Tolnayeb7d79b2018-03-31 22:52:17 +0200170 syntax::with_globals(|| {
171 for expr in exprs {
172 let raw = quote!(#expr).to_string();
Michael Layzell53fc31a2017-06-07 09:21:53 -0400173
David Tolnayeb7d79b2018-03-31 22:52:17 +0200174 let libsyntax_ast = if let Some(e) = libsyntax_parse_and_rewrite(&raw) {
175 e
176 } else {
177 failed += 1;
178 errorf!("\nFAIL - libsyntax failed to parse raw\n");
179 continue;
180 };
Michael Layzell53fc31a2017-06-07 09:21:53 -0400181
David Tolnayeb7d79b2018-03-31 22:52:17 +0200182 let syn_expr = syn_brackets(expr);
183 let syn_ast = if let Some(e) = parse::libsyntax_expr(&quote!(#syn_expr).to_string()) {
184 e
185 } else {
186 failed += 1;
187 errorf!("\nFAIL - libsyntax failed to parse bracketed\n");
188 continue;
189 };
Michael Layzell53fc31a2017-06-07 09:21:53 -0400190
David Tolnayecd024d2018-07-21 09:07:56 -0700191 if SpanlessEq::eq(&syn_ast, &libsyntax_ast) {
David Tolnayeb7d79b2018-03-31 22:52:17 +0200192 passed += 1;
193 } else {
194 failed += 1;
195 errorf!("\nFAIL\n{:?}\n!=\n{:?}\n", syn_ast, libsyntax_ast);
196 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400197 }
David Tolnay5d1a3ee2018-03-17 19:41:36 -0700198 });
Michael Layzell53fc31a2017-06-07 09:21:53 -0400199
200 (passed, failed)
201}
202
David Tolnaycfa5cc02017-11-13 01:05:11 -0800203fn libsyntax_parse_and_rewrite(input: &str) -> Option<P<ast::Expr>> {
David Tolnay3cede942017-12-26 12:29:24 -0500204 parse::libsyntax_expr(input).and_then(libsyntax_brackets)
Michael Layzell53fc31a2017-06-07 09:21:53 -0400205}
206
207/// Wrap every expression which is not already wrapped in parens with parens, to
David Tolnay0ccb6d12018-08-14 22:43:00 -0700208/// reveal the precidence of the parsed expressions, and produce a stringified
209/// form of the resulting expression.
Michael Layzell53fc31a2017-06-07 09:21:53 -0400210///
David Tolnaycfa5cc02017-11-13 01:05:11 -0800211/// This method operates on libsyntax objects.
212fn libsyntax_brackets(libsyntax_expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
David Tolnayc8659922018-08-14 22:40:50 -0700213 use rustc_data_structures::thin_vec::ThinVec;
David Tolnay0eab7d92018-09-26 22:10:40 -0700214 use smallvec::SmallVec;
David Tolnay51382052017-12-27 13:46:21 -0500215 use syntax::ast::{Expr, ExprKind, Field, Mac, Pat, Stmt, StmtKind, Ty};
David Tolnayeb7d79b2018-03-31 22:52:17 +0200216 use syntax::ext::quote::rt::DUMMY_SP;
David Tolnaycfa5cc02017-11-13 01:05:11 -0800217 use syntax::fold::{self, Folder};
Michael Layzell53fc31a2017-06-07 09:21:53 -0400218
Michael Layzell53fc31a2017-06-07 09:21:53 -0400219 struct BracketsFolder {
220 failed: bool,
221 };
222 impl Folder for BracketsFolder {
223 fn fold_expr(&mut self, e: P<Expr>) -> P<Expr> {
David Tolnay5d314dc2018-07-21 16:40:01 -0700224 e.map(|e| match e.node {
225 ExprKind::If(..) | ExprKind::Block(..) | ExprKind::IfLet(..) => {
226 fold::noop_fold_expr(e, self)
227 }
228 _ => Expr {
229 id: ast::DUMMY_NODE_ID,
230 node: ExprKind::Paren(P(fold::noop_fold_expr(e, self))),
231 span: DUMMY_SP,
232 attrs: ThinVec::new(),
David Tolnay51382052017-12-27 13:46:21 -0500233 },
Michael Layzell53fc31a2017-06-07 09:21:53 -0400234 })
235 }
236
237 fn fold_field(&mut self, f: Field) -> Field {
238 Field {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400239 expr: if f.is_shorthand {
240 f.expr.map(|e| fold::noop_fold_expr(e, self))
241 } else {
242 self.fold_expr(f.expr)
243 },
David Tolnaya3174992018-04-06 22:41:59 -0700244 ..f
Michael Layzell53fc31a2017-06-07 09:21:53 -0400245 }
246 }
247
248 // We don't want to look at expressions that might appear in patterns or
249 // types yet. We'll look into comparing those in the future. For now
250 // focus on expressions appearing in other places.
251 fn fold_pat(&mut self, pat: P<Pat>) -> P<Pat> {
252 pat
253 }
254
255 fn fold_ty(&mut self, ty: P<Ty>) -> P<Ty> {
256 ty
257 }
258
David Tolnay0eab7d92018-09-26 22:10:40 -0700259 fn fold_stmt(&mut self, stmt: Stmt) -> SmallVec<[Stmt; 1]> {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400260 let node = match stmt.node {
261 // Don't wrap toplevel expressions in statements.
David Tolnay51382052017-12-27 13:46:21 -0500262 StmtKind::Expr(e) => StmtKind::Expr(e.map(|e| fold::noop_fold_expr(e, self))),
263 StmtKind::Semi(e) => StmtKind::Semi(e.map(|e| fold::noop_fold_expr(e, self))),
Michael Layzell53fc31a2017-06-07 09:21:53 -0400264 s => s,
265 };
266
David Tolnay0eab7d92018-09-26 22:10:40 -0700267 smallvec![Stmt { node, ..stmt }]
Michael Layzell53fc31a2017-06-07 09:21:53 -0400268 }
269
270 fn fold_mac(&mut self, mac: Mac) -> Mac {
David Tolnaycfa5cc02017-11-13 01:05:11 -0800271 // By default when folding over macros, libsyntax panics. This is
Michael Layzell53fc31a2017-06-07 09:21:53 -0400272 // because it's usually not what you want, you want to run after
273 // macro expansion. We do want to do that (syn doesn't do macro
274 // expansion), so we implement fold_mac to just return the macro
275 // unchanged.
276 mac
277 }
278 }
279
David Tolnay51382052017-12-27 13:46:21 -0500280 let mut folder = BracketsFolder { failed: false };
David Tolnaycfa5cc02017-11-13 01:05:11 -0800281 let e = folder.fold_expr(libsyntax_expr);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400282 if folder.failed {
283 None
284 } else {
285 Some(e)
286 }
287}
288
289/// Wrap every expression which is not already wrapped in parens with parens, to
David Tolnay0ccb6d12018-08-14 22:43:00 -0700290/// reveal the precedence of the parsed expressions, and produce a stringified
291/// form of the resulting expression.
Michael Layzell53fc31a2017-06-07 09:21:53 -0400292fn syn_brackets(syn_expr: syn::Expr) -> syn::Expr {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400293 use syn::fold::*;
David Tolnayeb7d79b2018-03-31 22:52:17 +0200294 use syn::*;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400295
David Tolnayeb752062018-01-06 13:51:42 -0800296 struct ParenthesizeEveryExpr;
297 impl Fold for ParenthesizeEveryExpr {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400298 fn fold_expr(&mut self, expr: Expr) -> Expr {
David Tolnay8c91b882017-12-28 23:04:32 -0500299 match expr {
300 Expr::Group(_) => unreachable!(),
David Tolnay9c119122018-09-01 18:47:02 -0700301 Expr::If(..) | Expr::Unsafe(..) | Expr::Block(..) | Expr::Let(..) => {
David Tolnay3bc597f2017-12-31 02:31:11 -0500302 fold_expr(self, expr)
Michael Layzell53fc31a2017-06-07 09:21:53 -0400303 }
David Tolnay5d314dc2018-07-21 16:40:01 -0700304 node => Expr::Paren(ExprParen {
305 attrs: Vec::new(),
306 expr: Box::new(fold_expr(self, node)),
307 paren_token: token::Paren::default(),
308 }),
David Tolnay8c91b882017-12-28 23:04:32 -0500309 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400310 }
311
312 fn fold_stmt(&mut self, stmt: Stmt) -> Stmt {
313 match stmt {
314 // Don't wrap toplevel expressions in statements.
David Tolnay1f0b7b82018-01-06 16:07:14 -0800315 Stmt::Expr(e) => Stmt::Expr(fold_expr(self, e)),
316 Stmt::Semi(e, semi) => Stmt::Semi(fold_expr(self, e), semi),
Michael Layzell53fc31a2017-06-07 09:21:53 -0400317 s => s,
318 }
319 }
320
321 // We don't want to look at expressions that might appear in patterns or
322 // types yet. We'll look into comparing those in the future. For now
323 // focus on expressions appearing in other places.
324 fn fold_pat(&mut self, pat: Pat) -> Pat {
325 pat
326 }
327
David Tolnayfd6bf5c2017-11-12 09:41:14 -0800328 fn fold_type(&mut self, ty: Type) -> Type {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400329 ty
330 }
331 }
332
David Tolnayeb752062018-01-06 13:51:42 -0800333 let mut folder = ParenthesizeEveryExpr;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400334 folder.fold_expr(syn_expr)
335}
336
337/// Walk through a crate collecting all expressions we can find in it.
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700338fn collect_exprs(file: syn::File) -> Vec<syn::Expr> {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400339 use syn::fold::*;
David Tolnayf2cfd722017-12-31 18:02:51 -0500340 use syn::punctuated::Punctuated;
David Tolnayeb7d79b2018-03-31 22:52:17 +0200341 use syn::*;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400342
David Tolnayeb752062018-01-06 13:51:42 -0800343 struct CollectExprs(Vec<Expr>);
344 impl Fold for CollectExprs {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400345 fn fold_expr(&mut self, expr: Expr) -> Expr {
346 self.0.push(expr);
347
David Tolnay8c91b882017-12-28 23:04:32 -0500348 Expr::Tuple(ExprTuple {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400349 attrs: vec![],
David Tolnayf2cfd722017-12-31 18:02:51 -0500350 elems: Punctuated::new(),
David Tolnay8c91b882017-12-28 23:04:32 -0500351 paren_token: token::Paren::default(),
352 })
Michael Layzell53fc31a2017-06-07 09:21:53 -0400353 }
354 }
355
David Tolnayeb752062018-01-06 13:51:42 -0800356 let mut folder = CollectExprs(vec![]);
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700357 folder.fold_file(file);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400358 folder.0
359}