blob: 71017b6e544b9d0524be63ea5fd41e5ec1754a98 [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.
David Tolnay176838f2019-02-07 17:28:37 +0100214fn libsyntax_brackets(mut 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 Tolnay176838f2019-02-07 17:28:37 +0100217 use std::mem;
David Tolnay51382052017-12-27 13:46:21 -0500218 use syntax::ast::{Expr, ExprKind, Field, Mac, Pat, Stmt, StmtKind, Ty};
David Tolnay176838f2019-02-07 17:28:37 +0100219 use syntax::mut_visit::{self, MutVisitor};
David Tolnayfcd4a672019-01-24 20:56:54 -0800220 use syntax_pos::DUMMY_SP;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400221
David Tolnay176838f2019-02-07 17:28:37 +0100222 struct BracketsVisitor {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400223 failed: bool,
224 };
David Tolnay176838f2019-02-07 17:28:37 +0100225 impl MutVisitor for BracketsVisitor {
226 fn visit_expr(&mut self, e: &mut P<Expr>) {
227 mut_visit::noop_visit_expr(e, self);
228 match e.node {
229 ExprKind::If(..) | ExprKind::Block(..) | ExprKind::IfLet(..) => {}
230 _ => {
231 let inner = mem::replace(
232 e,
233 P(Expr {
234 id: ast::DUMMY_NODE_ID,
235 node: ExprKind::Err,
236 span: DUMMY_SP,
237 attrs: ThinVec::new(),
238 }),
239 );
240 e.node = ExprKind::Paren(inner);
David Tolnay5d314dc2018-07-21 16:40:01 -0700241 }
David Tolnay176838f2019-02-07 17:28:37 +0100242 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400243 }
244
David Tolnay176838f2019-02-07 17:28:37 +0100245 fn visit_field(&mut self, f: &mut Field) {
246 if f.is_shorthand {
247 mut_visit::noop_visit_expr(&mut f.expr, self);
248 } else {
249 self.visit_expr(&mut f.expr);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400250 }
251 }
252
253 // We don't want to look at expressions that might appear in patterns or
254 // types yet. We'll look into comparing those in the future. For now
255 // focus on expressions appearing in other places.
David Tolnay176838f2019-02-07 17:28:37 +0100256 fn visit_pat(&mut self, pat: &mut P<Pat>) {
257 let _ = pat;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400258 }
259
David Tolnay176838f2019-02-07 17:28:37 +0100260 fn visit_ty(&mut self, ty: &mut P<Ty>) {
261 let _ = ty;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400262 }
263
David Tolnay176838f2019-02-07 17:28:37 +0100264 fn flat_map_stmt(&mut self, stmt: Stmt) -> SmallVec<[Stmt; 1]> {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400265 let node = match stmt.node {
266 // Don't wrap toplevel expressions in statements.
David Tolnay176838f2019-02-07 17:28:37 +0100267 StmtKind::Expr(mut e) => {
268 mut_visit::noop_visit_expr(&mut e, self);
269 StmtKind::Expr(e)
270 }
271 StmtKind::Semi(mut e) => {
272 mut_visit::noop_visit_expr(&mut e, self);
273 StmtKind::Semi(e)
274 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400275 s => s,
276 };
277
David Tolnay0eab7d92018-09-26 22:10:40 -0700278 smallvec![Stmt { node, ..stmt }]
Michael Layzell53fc31a2017-06-07 09:21:53 -0400279 }
280
David Tolnay176838f2019-02-07 17:28:37 +0100281 fn visit_mac(&mut self, mac: &mut Mac) {
David Tolnaycfa5cc02017-11-13 01:05:11 -0800282 // By default when folding over macros, libsyntax panics. This is
Michael Layzell53fc31a2017-06-07 09:21:53 -0400283 // because it's usually not what you want, you want to run after
284 // macro expansion. We do want to do that (syn doesn't do macro
David Tolnay176838f2019-02-07 17:28:37 +0100285 // expansion), so we implement visit_mac to just return the macro
Michael Layzell53fc31a2017-06-07 09:21:53 -0400286 // unchanged.
David Tolnay176838f2019-02-07 17:28:37 +0100287 let _ = mac;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400288 }
289 }
290
David Tolnay176838f2019-02-07 17:28:37 +0100291 let mut folder = BracketsVisitor { failed: false };
292 folder.visit_expr(&mut libsyntax_expr);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400293 if folder.failed {
294 None
295 } else {
David Tolnay176838f2019-02-07 17:28:37 +0100296 Some(libsyntax_expr)
Michael Layzell53fc31a2017-06-07 09:21:53 -0400297 }
298}
299
300/// Wrap every expression which is not already wrapped in parens with parens, to
David Tolnay0ccb6d12018-08-14 22:43:00 -0700301/// reveal the precedence of the parsed expressions, and produce a stringified
302/// form of the resulting expression.
Michael Layzell53fc31a2017-06-07 09:21:53 -0400303fn syn_brackets(syn_expr: syn::Expr) -> syn::Expr {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400304 use syn::fold::*;
David Tolnayeb7d79b2018-03-31 22:52:17 +0200305 use syn::*;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400306
David Tolnayeb752062018-01-06 13:51:42 -0800307 struct ParenthesizeEveryExpr;
308 impl Fold for ParenthesizeEveryExpr {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400309 fn fold_expr(&mut self, expr: Expr) -> Expr {
David Tolnay8c91b882017-12-28 23:04:32 -0500310 match expr {
311 Expr::Group(_) => unreachable!(),
David Tolnay9c119122018-09-01 18:47:02 -0700312 Expr::If(..) | Expr::Unsafe(..) | Expr::Block(..) | Expr::Let(..) => {
David Tolnay3bc597f2017-12-31 02:31:11 -0500313 fold_expr(self, expr)
Michael Layzell53fc31a2017-06-07 09:21:53 -0400314 }
David Tolnay5d314dc2018-07-21 16:40:01 -0700315 node => Expr::Paren(ExprParen {
316 attrs: Vec::new(),
317 expr: Box::new(fold_expr(self, node)),
318 paren_token: token::Paren::default(),
319 }),
David Tolnay8c91b882017-12-28 23:04:32 -0500320 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400321 }
322
323 fn fold_stmt(&mut self, stmt: Stmt) -> Stmt {
324 match stmt {
325 // Don't wrap toplevel expressions in statements.
David Tolnay1f0b7b82018-01-06 16:07:14 -0800326 Stmt::Expr(e) => Stmt::Expr(fold_expr(self, e)),
327 Stmt::Semi(e, semi) => Stmt::Semi(fold_expr(self, e), semi),
Michael Layzell53fc31a2017-06-07 09:21:53 -0400328 s => s,
329 }
330 }
331
332 // We don't want to look at expressions that might appear in patterns or
333 // types yet. We'll look into comparing those in the future. For now
334 // focus on expressions appearing in other places.
335 fn fold_pat(&mut self, pat: Pat) -> Pat {
336 pat
337 }
338
David Tolnayfd6bf5c2017-11-12 09:41:14 -0800339 fn fold_type(&mut self, ty: Type) -> Type {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400340 ty
341 }
342 }
343
David Tolnayeb752062018-01-06 13:51:42 -0800344 let mut folder = ParenthesizeEveryExpr;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400345 folder.fold_expr(syn_expr)
346}
347
348/// Walk through a crate collecting all expressions we can find in it.
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700349fn collect_exprs(file: syn::File) -> Vec<syn::Expr> {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400350 use syn::fold::*;
David Tolnayf2cfd722017-12-31 18:02:51 -0500351 use syn::punctuated::Punctuated;
David Tolnayeb7d79b2018-03-31 22:52:17 +0200352 use syn::*;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400353
David Tolnayeb752062018-01-06 13:51:42 -0800354 struct CollectExprs(Vec<Expr>);
355 impl Fold for CollectExprs {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400356 fn fold_expr(&mut self, expr: Expr) -> Expr {
357 self.0.push(expr);
358
David Tolnay8c91b882017-12-28 23:04:32 -0500359 Expr::Tuple(ExprTuple {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400360 attrs: vec![],
David Tolnayf2cfd722017-12-31 18:02:51 -0500361 elems: Punctuated::new(),
David Tolnay8c91b882017-12-28 23:04:32 -0500362 paren_token: token::Paren::default(),
363 })
Michael Layzell53fc31a2017-06-07 09:21:53 -0400364 }
365 }
366
David Tolnayeb752062018-01-06 13:51:42 -0800367 let mut folder = CollectExprs(vec![]);
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700368 folder.fold_file(file);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400369 folder.0
370}