blob: 12b6a448e3017141ab6e6ea877fa348cb9feef15 [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;
David Tolnayfcd4a672019-01-24 20:56:54 -080025extern crate syntax_pos;
Michael Layzell53fc31a2017-06-07 09:21:53 -040026extern crate walkdir;
Michael Layzell53fc31a2017-06-07 09:21:53 -040027
David Tolnayc3f98562018-11-02 08:55:05 -070028mod features;
29
David Tolnay51382052017-12-27 13:46:21 -050030use rayon::iter::{IntoParallelIterator, ParallelIterator};
David Tolnayd1c31cc2018-08-24 14:47:15 -040031use regex::Regex;
David Tolnaycfa5cc02017-11-13 01:05:11 -080032use syntax::ast;
33use syntax::ptr::P;
Igor Gnatenko951a52b2018-03-12 10:33:33 +010034use walkdir::{DirEntry, WalkDir};
David Tolnayee97dbf2017-11-19 14:24:38 -080035
36use std::fs::File;
37use std::io::Read;
David Tolnay3eaf7d82017-12-17 23:14:52 -080038use std::process;
David Tolnayee97dbf2017-11-19 14:24:38 -080039use std::sync::atomic::{AtomicUsize, Ordering};
Michael Layzell53fc31a2017-06-07 09:21:53 -040040
David Tolnayecd024d2018-07-21 09:07:56 -070041use common::eq::SpanlessEq;
42use common::parse;
Michael Layzell53fc31a2017-06-07 09:21:53 -040043
Michael Layzell53fc31a2017-06-07 09:21:53 -040044#[macro_use]
David Tolnaydd125562017-12-31 02:16:22 -050045mod macros;
46
47#[allow(dead_code)]
Michael Layzell53fc31a2017-06-07 09:21:53 -040048mod common;
49
50/// Test some pre-set expressions chosen by us.
51#[test]
52fn test_simple_precedence() {
53 const EXPRS: &[&str] = &[
54 "1 + 2 * 3 + 4",
55 "1 + 2 * ( 3 + 4 )",
56 "{ for i in r { } *some_ptr += 1; }",
57 "{ loop { break 5; } }",
58 "{ if true { () }.mthd() }",
Nika Layzell3aa0dc72017-12-04 13:41:28 -050059 "{ for i in unsafe { 20 } { } }",
Michael Layzell53fc31a2017-06-07 09:21:53 -040060 ];
61
62 let mut failed = 0;
63
64 for input in EXPRS {
65 let expr = if let Some(expr) = parse::syn_expr(input) {
66 expr
67 } else {
68 failed += 1;
69 continue;
70 };
71
72 let pf = match test_expressions(vec![expr]) {
73 (1, 0) => "passed",
74 (0, 1) => {
75 failed += 1;
76 "failed"
77 }
78 _ => unreachable!(),
79 };
80 errorf!("=== {}: {}\n", input, pf);
81 }
82
83 if failed > 0 {
84 panic!("Failed {} tests", failed);
85 }
86}
87
88/// Test expressions from rustc, like in `test_round_trip`.
89#[test]
cad97286b19f2019-01-23 23:08:25 -050090#[cfg_attr(target_os = "windows", ignore = "requires nix .sh")]
Michael Layzell53fc31a2017-06-07 09:21:53 -040091fn test_rustc_precedence() {
Alex Crichton86374772017-07-07 20:39:28 -070092 common::clone_rust();
Michael Layzell53fc31a2017-06-07 09:21:53 -040093 let abort_after = common::abort_after();
94 if abort_after == 0 {
95 panic!("Skipping all precedence tests");
96 }
97
David Tolnayee97dbf2017-11-19 14:24:38 -080098 let passed = AtomicUsize::new(0);
99 let failed = AtomicUsize::new(0);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400100
David Tolnayd1c31cc2018-08-24 14:47:15 -0400101 // 2018 edition is hard
102 let edition_regex = Regex::new(r"\b(async|try)[!(]").unwrap();
103
David Tolnayee97dbf2017-11-19 14:24:38 -0800104 WalkDir::new("tests/rust")
Igor Gnatenko951a52b2018-03-12 10:33:33 +0100105 .sort_by(|a, b| a.file_name().cmp(b.file_name()))
David Tolnayee97dbf2017-11-19 14:24:38 -0800106 .into_iter()
107 .filter_entry(common::base_dir_filter)
108 .collect::<Result<Vec<DirEntry>, walkdir::Error>>()
109 .unwrap()
110 .into_par_iter()
David Tolnay51382052017-12-27 13:46:21 -0500111 .for_each(|entry| {
112 let path = entry.path();
113 if path.is_dir() {
114 return;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400115 }
David Tolnay51382052017-12-27 13:46:21 -0500116
117 // Our version of `libsyntax` can't parse this tests
David Tolnay65fb5662018-05-20 20:02:28 -0700118 if path
119 .to_str()
David Tolnay51382052017-12-27 13:46:21 -0500120 .unwrap()
121 .ends_with("optional_comma_in_match_arm.rs")
122 {
123 return;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400124 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400125
David Tolnay51382052017-12-27 13:46:21 -0500126 let mut file = File::open(path).unwrap();
127 let mut content = String::new();
128 file.read_to_string(&mut content).unwrap();
David Tolnayd1c31cc2018-08-24 14:47:15 -0400129 let content = edition_regex.replace_all(&content, "_$0");
Michael Layzell53fc31a2017-06-07 09:21:53 -0400130
David Tolnay51382052017-12-27 13:46:21 -0500131 let (l_passed, l_failed) = match syn::parse_file(&content) {
132 Ok(file) => {
133 let exprs = collect_exprs(file);
134 test_expressions(exprs)
135 }
136 Err(msg) => {
137 errorf!("syn failed to parse\n{:?}\n", msg);
138 (0, 1)
139 }
140 };
David Tolnayee97dbf2017-11-19 14:24:38 -0800141
David Tolnay51382052017-12-27 13:46:21 -0500142 errorf!(
143 "=== {}: {} passed | {} failed\n",
144 path.display(),
145 l_passed,
146 l_failed
147 );
148
149 passed.fetch_add(l_passed, Ordering::SeqCst);
150 let prev_failed = failed.fetch_add(l_failed, Ordering::SeqCst);
151
152 if prev_failed + l_failed >= abort_after {
153 process::exit(1);
154 }
155 });
David Tolnayee97dbf2017-11-19 14:24:38 -0800156
157 let passed = passed.load(Ordering::SeqCst);
158 let failed = failed.load(Ordering::SeqCst);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400159
160 errorf!("\n===== Precedence Test Results =====\n");
161 errorf!("{} passed | {} failed\n", passed, failed);
162
Michael Layzell53fc31a2017-06-07 09:21:53 -0400163 if failed > 0 {
164 panic!("{} failures", failed);
165 }
166}
167
David Tolnayee97dbf2017-11-19 14:24:38 -0800168fn test_expressions(exprs: Vec<syn::Expr>) -> (usize, usize) {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400169 let mut passed = 0;
170 let mut failed = 0;
171
David Tolnayeb7d79b2018-03-31 22:52:17 +0200172 syntax::with_globals(|| {
173 for expr in exprs {
174 let raw = quote!(#expr).to_string();
Michael Layzell53fc31a2017-06-07 09:21:53 -0400175
David Tolnayeb7d79b2018-03-31 22:52:17 +0200176 let libsyntax_ast = if let Some(e) = libsyntax_parse_and_rewrite(&raw) {
177 e
178 } else {
179 failed += 1;
180 errorf!("\nFAIL - libsyntax failed to parse raw\n");
181 continue;
182 };
Michael Layzell53fc31a2017-06-07 09:21:53 -0400183
David Tolnayeb7d79b2018-03-31 22:52:17 +0200184 let syn_expr = syn_brackets(expr);
185 let syn_ast = if let Some(e) = parse::libsyntax_expr(&quote!(#syn_expr).to_string()) {
186 e
187 } else {
188 failed += 1;
189 errorf!("\nFAIL - libsyntax failed to parse bracketed\n");
190 continue;
191 };
Michael Layzell53fc31a2017-06-07 09:21:53 -0400192
David Tolnayecd024d2018-07-21 09:07:56 -0700193 if SpanlessEq::eq(&syn_ast, &libsyntax_ast) {
David Tolnayeb7d79b2018-03-31 22:52:17 +0200194 passed += 1;
195 } else {
196 failed += 1;
197 errorf!("\nFAIL\n{:?}\n!=\n{:?}\n", syn_ast, libsyntax_ast);
198 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400199 }
David Tolnay5d1a3ee2018-03-17 19:41:36 -0700200 });
Michael Layzell53fc31a2017-06-07 09:21:53 -0400201
202 (passed, failed)
203}
204
David Tolnaycfa5cc02017-11-13 01:05:11 -0800205fn libsyntax_parse_and_rewrite(input: &str) -> Option<P<ast::Expr>> {
David Tolnay3cede942017-12-26 12:29:24 -0500206 parse::libsyntax_expr(input).and_then(libsyntax_brackets)
Michael Layzell53fc31a2017-06-07 09:21:53 -0400207}
208
209/// Wrap every expression which is not already wrapped in parens with parens, to
David Tolnay0ccb6d12018-08-14 22:43:00 -0700210/// reveal the precidence of the parsed expressions, and produce a stringified
211/// form of the resulting expression.
Michael Layzell53fc31a2017-06-07 09:21:53 -0400212///
David Tolnaycfa5cc02017-11-13 01:05:11 -0800213/// This method operates on libsyntax objects.
214fn libsyntax_brackets(libsyntax_expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
David Tolnayc8659922018-08-14 22:40:50 -0700215 use rustc_data_structures::thin_vec::ThinVec;
David Tolnay0eab7d92018-09-26 22:10:40 -0700216 use smallvec::SmallVec;
David Tolnay51382052017-12-27 13:46:21 -0500217 use syntax::ast::{Expr, ExprKind, Field, Mac, Pat, Stmt, StmtKind, Ty};
David Tolnaycfa5cc02017-11-13 01:05:11 -0800218 use syntax::fold::{self, Folder};
David Tolnayfcd4a672019-01-24 20:56:54 -0800219 use syntax_pos::DUMMY_SP;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400220
Michael Layzell53fc31a2017-06-07 09:21:53 -0400221 struct BracketsFolder {
222 failed: bool,
223 };
224 impl Folder for BracketsFolder {
225 fn fold_expr(&mut self, e: P<Expr>) -> P<Expr> {
David Tolnay5d314dc2018-07-21 16:40:01 -0700226 e.map(|e| match e.node {
227 ExprKind::If(..) | ExprKind::Block(..) | ExprKind::IfLet(..) => {
228 fold::noop_fold_expr(e, self)
229 }
230 _ => Expr {
231 id: ast::DUMMY_NODE_ID,
232 node: ExprKind::Paren(P(fold::noop_fold_expr(e, self))),
233 span: DUMMY_SP,
234 attrs: ThinVec::new(),
David Tolnay51382052017-12-27 13:46:21 -0500235 },
Michael Layzell53fc31a2017-06-07 09:21:53 -0400236 })
237 }
238
239 fn fold_field(&mut self, f: Field) -> Field {
240 Field {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400241 expr: if f.is_shorthand {
242 f.expr.map(|e| fold::noop_fold_expr(e, self))
243 } else {
244 self.fold_expr(f.expr)
245 },
David Tolnaya3174992018-04-06 22:41:59 -0700246 ..f
Michael Layzell53fc31a2017-06-07 09:21:53 -0400247 }
248 }
249
250 // We don't want to look at expressions that might appear in patterns or
251 // types yet. We'll look into comparing those in the future. For now
252 // focus on expressions appearing in other places.
253 fn fold_pat(&mut self, pat: P<Pat>) -> P<Pat> {
254 pat
255 }
256
257 fn fold_ty(&mut self, ty: P<Ty>) -> P<Ty> {
258 ty
259 }
260
David Tolnay0eab7d92018-09-26 22:10:40 -0700261 fn fold_stmt(&mut self, stmt: Stmt) -> SmallVec<[Stmt; 1]> {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400262 let node = match stmt.node {
263 // Don't wrap toplevel expressions in statements.
David Tolnay51382052017-12-27 13:46:21 -0500264 StmtKind::Expr(e) => StmtKind::Expr(e.map(|e| fold::noop_fold_expr(e, self))),
265 StmtKind::Semi(e) => StmtKind::Semi(e.map(|e| fold::noop_fold_expr(e, self))),
Michael Layzell53fc31a2017-06-07 09:21:53 -0400266 s => s,
267 };
268
David Tolnay0eab7d92018-09-26 22:10:40 -0700269 smallvec![Stmt { node, ..stmt }]
Michael Layzell53fc31a2017-06-07 09:21:53 -0400270 }
271
272 fn fold_mac(&mut self, mac: Mac) -> Mac {
David Tolnaycfa5cc02017-11-13 01:05:11 -0800273 // By default when folding over macros, libsyntax panics. This is
Michael Layzell53fc31a2017-06-07 09:21:53 -0400274 // because it's usually not what you want, you want to run after
275 // macro expansion. We do want to do that (syn doesn't do macro
276 // expansion), so we implement fold_mac to just return the macro
277 // unchanged.
278 mac
279 }
280 }
281
David Tolnay51382052017-12-27 13:46:21 -0500282 let mut folder = BracketsFolder { failed: false };
David Tolnaycfa5cc02017-11-13 01:05:11 -0800283 let e = folder.fold_expr(libsyntax_expr);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400284 if folder.failed {
285 None
286 } else {
287 Some(e)
288 }
289}
290
291/// Wrap every expression which is not already wrapped in parens with parens, to
David Tolnay0ccb6d12018-08-14 22:43:00 -0700292/// reveal the precedence of the parsed expressions, and produce a stringified
293/// form of the resulting expression.
Michael Layzell53fc31a2017-06-07 09:21:53 -0400294fn syn_brackets(syn_expr: syn::Expr) -> syn::Expr {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400295 use syn::fold::*;
David Tolnayeb7d79b2018-03-31 22:52:17 +0200296 use syn::*;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400297
David Tolnayeb752062018-01-06 13:51:42 -0800298 struct ParenthesizeEveryExpr;
299 impl Fold for ParenthesizeEveryExpr {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400300 fn fold_expr(&mut self, expr: Expr) -> Expr {
David Tolnay8c91b882017-12-28 23:04:32 -0500301 match expr {
302 Expr::Group(_) => unreachable!(),
David Tolnay9c119122018-09-01 18:47:02 -0700303 Expr::If(..) | Expr::Unsafe(..) | Expr::Block(..) | Expr::Let(..) => {
David Tolnay3bc597f2017-12-31 02:31:11 -0500304 fold_expr(self, expr)
Michael Layzell53fc31a2017-06-07 09:21:53 -0400305 }
David Tolnay5d314dc2018-07-21 16:40:01 -0700306 node => Expr::Paren(ExprParen {
307 attrs: Vec::new(),
308 expr: Box::new(fold_expr(self, node)),
309 paren_token: token::Paren::default(),
310 }),
David Tolnay8c91b882017-12-28 23:04:32 -0500311 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400312 }
313
314 fn fold_stmt(&mut self, stmt: Stmt) -> Stmt {
315 match stmt {
316 // Don't wrap toplevel expressions in statements.
David Tolnay1f0b7b82018-01-06 16:07:14 -0800317 Stmt::Expr(e) => Stmt::Expr(fold_expr(self, e)),
318 Stmt::Semi(e, semi) => Stmt::Semi(fold_expr(self, e), semi),
Michael Layzell53fc31a2017-06-07 09:21:53 -0400319 s => s,
320 }
321 }
322
323 // We don't want to look at expressions that might appear in patterns or
324 // types yet. We'll look into comparing those in the future. For now
325 // focus on expressions appearing in other places.
326 fn fold_pat(&mut self, pat: Pat) -> Pat {
327 pat
328 }
329
David Tolnayfd6bf5c2017-11-12 09:41:14 -0800330 fn fold_type(&mut self, ty: Type) -> Type {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400331 ty
332 }
333 }
334
David Tolnayeb752062018-01-06 13:51:42 -0800335 let mut folder = ParenthesizeEveryExpr;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400336 folder.fold_expr(syn_expr)
337}
338
339/// Walk through a crate collecting all expressions we can find in it.
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700340fn collect_exprs(file: syn::File) -> Vec<syn::Expr> {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400341 use syn::fold::*;
David Tolnayf2cfd722017-12-31 18:02:51 -0500342 use syn::punctuated::Punctuated;
David Tolnayeb7d79b2018-03-31 22:52:17 +0200343 use syn::*;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400344
David Tolnayeb752062018-01-06 13:51:42 -0800345 struct CollectExprs(Vec<Expr>);
346 impl Fold for CollectExprs {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400347 fn fold_expr(&mut self, expr: Expr) -> Expr {
348 self.0.push(expr);
349
David Tolnay8c91b882017-12-28 23:04:32 -0500350 Expr::Tuple(ExprTuple {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400351 attrs: vec![],
David Tolnayf2cfd722017-12-31 18:02:51 -0500352 elems: Punctuated::new(),
David Tolnay8c91b882017-12-28 23:04:32 -0500353 paren_token: token::Paren::default(),
354 })
Michael Layzell53fc31a2017-06-07 09:21:53 -0400355 }
356 }
357
David Tolnayeb752062018-01-06 13:51:42 -0800358 let mut folder = CollectExprs(vec![]);
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700359 folder.fold_file(file);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400360 folder.0
361}