blob: 41e1f12bfc366f5bc25c59973ef2a94f61c9c6c7 [file] [log] [blame]
David Tolnayf83b6c92019-03-09 22:58:26 -08001#![cfg(not(syn_disable_nightly_tests))]
David Tolnayecd024d2018-07-21 09:07:56 -07002#![recursion_limit = "1024"]
Nika Layzella2a1a4a2017-11-19 11:33:17 -05003#![feature(rustc_private)]
4
Michael Layzell53fc31a2017-06-07 09:21:53 -04005//! The tests in this module do the following:
6//!
David Tolnaycfa5cc02017-11-13 01:05:11 -08007//! 1. Parse a given expression in both `syn` and `libsyntax`.
Michael Layzell53fc31a2017-06-07 09:21:53 -04008//! 2. Fold over the expression adding brackets around each subexpression (with
David Tolnaycfa5cc02017-11-13 01:05:11 -08009//! some complications - see the `syn_brackets` and `libsyntax_brackets`
Michael Layzell53fc31a2017-06-07 09:21:53 -040010//! methods).
11//! 3. Serialize the `syn` expression back into a string, and re-parse it with
David Tolnaycfa5cc02017-11-13 01:05:11 -080012//! `libsyntax`.
David Tolnay0ccb6d12018-08-14 22:43:00 -070013//! 4. Respan all of the expressions, replacing the spans with the default
14//! spans.
Michael Layzell53fc31a2017-06-07 09:21:53 -040015//! 5. Compare the expressions with one another, if they are not equal fail.
16
Michael Layzell53fc31a2017-06-07 09:21:53 -040017extern 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 -070021extern crate smallvec;
Michael Layzell53fc31a2017-06-07 09:21:53 -040022extern crate syn;
David Tolnaycfa5cc02017-11-13 01:05:11 -080023extern crate syntax;
David Tolnayfcd4a672019-01-24 20:56:54 -080024extern crate syntax_pos;
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 Tolnaye9b448f2019-03-10 22:46:38 -070029use quote::quote;
David Tolnay51382052017-12-27 13:46:21 -050030use rayon::iter::{IntoParallelIterator, ParallelIterator};
David Tolnayd1c31cc2018-08-24 14:47:15 -040031use regex::Regex;
David Tolnaye9b448f2019-03-10 22:46:38 -070032use smallvec::smallvec;
David Tolnaycfa5cc02017-11-13 01:05:11 -080033use syntax::ast;
34use syntax::ptr::P;
Igor Gnatenko951a52b2018-03-12 10:33:33 +010035use walkdir::{DirEntry, WalkDir};
David Tolnayee97dbf2017-11-19 14:24:38 -080036
37use std::fs::File;
38use std::io::Read;
David Tolnay3eaf7d82017-12-17 23:14:52 -080039use std::process;
David Tolnayee97dbf2017-11-19 14:24:38 -080040use std::sync::atomic::{AtomicUsize, Ordering};
Michael Layzell53fc31a2017-06-07 09:21:53 -040041
David Tolnayecd024d2018-07-21 09:07:56 -070042use common::eq::SpanlessEq;
43use common::parse;
Michael Layzell53fc31a2017-06-07 09:21:53 -040044
Michael Layzell53fc31a2017-06-07 09:21:53 -040045#[macro_use]
David Tolnaydd125562017-12-31 02:16:22 -050046mod macros;
47
48#[allow(dead_code)]
Michael Layzell53fc31a2017-06-07 09:21:53 -040049mod common;
50
51/// Test some pre-set expressions chosen by us.
52#[test]
53fn test_simple_precedence() {
54 const EXPRS: &[&str] = &[
55 "1 + 2 * 3 + 4",
56 "1 + 2 * ( 3 + 4 )",
57 "{ for i in r { } *some_ptr += 1; }",
58 "{ loop { break 5; } }",
59 "{ if true { () }.mthd() }",
Nika Layzell3aa0dc72017-12-04 13:41:28 -050060 "{ for i in unsafe { 20 } { } }",
Michael Layzell53fc31a2017-06-07 09:21:53 -040061 ];
62
63 let mut failed = 0;
64
65 for input in EXPRS {
66 let expr = if let Some(expr) = parse::syn_expr(input) {
67 expr
68 } else {
69 failed += 1;
70 continue;
71 };
72
73 let pf = match test_expressions(vec![expr]) {
74 (1, 0) => "passed",
75 (0, 1) => {
76 failed += 1;
77 "failed"
78 }
79 _ => unreachable!(),
80 };
81 errorf!("=== {}: {}\n", input, pf);
82 }
83
84 if failed > 0 {
85 panic!("Failed {} tests", failed);
86 }
87}
88
89/// Test expressions from rustc, like in `test_round_trip`.
90#[test]
cad97286b19f2019-01-23 23:08:25 -050091#[cfg_attr(target_os = "windows", ignore = "requires nix .sh")]
Michael Layzell53fc31a2017-06-07 09:21:53 -040092fn test_rustc_precedence() {
Alex Crichton86374772017-07-07 20:39:28 -070093 common::clone_rust();
Michael Layzell53fc31a2017-06-07 09:21:53 -040094 let abort_after = common::abort_after();
95 if abort_after == 0 {
96 panic!("Skipping all precedence tests");
97 }
98
David Tolnayee97dbf2017-11-19 14:24:38 -080099 let passed = AtomicUsize::new(0);
100 let failed = AtomicUsize::new(0);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400101
David Tolnayd1c31cc2018-08-24 14:47:15 -0400102 // 2018 edition is hard
103 let edition_regex = Regex::new(r"\b(async|try)[!(]").unwrap();
104
David Tolnayee97dbf2017-11-19 14:24:38 -0800105 WalkDir::new("tests/rust")
Igor Gnatenko951a52b2018-03-12 10:33:33 +0100106 .sort_by(|a, b| a.file_name().cmp(b.file_name()))
David Tolnayee97dbf2017-11-19 14:24:38 -0800107 .into_iter()
108 .filter_entry(common::base_dir_filter)
109 .collect::<Result<Vec<DirEntry>, walkdir::Error>>()
110 .unwrap()
111 .into_par_iter()
David Tolnay51382052017-12-27 13:46:21 -0500112 .for_each(|entry| {
113 let path = entry.path();
114 if path.is_dir() {
115 return;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400116 }
David Tolnay51382052017-12-27 13:46:21 -0500117
118 // Our version of `libsyntax` can't parse this tests
David Tolnay65fb5662018-05-20 20:02:28 -0700119 if path
120 .to_str()
David Tolnay51382052017-12-27 13:46:21 -0500121 .unwrap()
122 .ends_with("optional_comma_in_match_arm.rs")
123 {
124 return;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400125 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400126
David Tolnay51382052017-12-27 13:46:21 -0500127 let mut file = File::open(path).unwrap();
128 let mut content = String::new();
129 file.read_to_string(&mut content).unwrap();
David Tolnayd1c31cc2018-08-24 14:47:15 -0400130 let content = edition_regex.replace_all(&content, "_$0");
Michael Layzell53fc31a2017-06-07 09:21:53 -0400131
David Tolnay51382052017-12-27 13:46:21 -0500132 let (l_passed, l_failed) = match syn::parse_file(&content) {
133 Ok(file) => {
134 let exprs = collect_exprs(file);
135 test_expressions(exprs)
136 }
137 Err(msg) => {
138 errorf!("syn failed to parse\n{:?}\n", msg);
139 (0, 1)
140 }
141 };
David Tolnayee97dbf2017-11-19 14:24:38 -0800142
David Tolnay51382052017-12-27 13:46:21 -0500143 errorf!(
144 "=== {}: {} passed | {} failed\n",
145 path.display(),
146 l_passed,
147 l_failed
148 );
149
150 passed.fetch_add(l_passed, Ordering::SeqCst);
151 let prev_failed = failed.fetch_add(l_failed, Ordering::SeqCst);
152
153 if prev_failed + l_failed >= abort_after {
154 process::exit(1);
155 }
156 });
David Tolnayee97dbf2017-11-19 14:24:38 -0800157
158 let passed = passed.load(Ordering::SeqCst);
159 let failed = failed.load(Ordering::SeqCst);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400160
161 errorf!("\n===== Precedence Test Results =====\n");
162 errorf!("{} passed | {} failed\n", passed, failed);
163
Michael Layzell53fc31a2017-06-07 09:21:53 -0400164 if failed > 0 {
165 panic!("{} failures", failed);
166 }
167}
168
David Tolnayee97dbf2017-11-19 14:24:38 -0800169fn test_expressions(exprs: Vec<syn::Expr>) -> (usize, usize) {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400170 let mut passed = 0;
171 let mut failed = 0;
172
David Tolnayeb7d79b2018-03-31 22:52:17 +0200173 syntax::with_globals(|| {
174 for expr in exprs {
175 let raw = quote!(#expr).to_string();
Michael Layzell53fc31a2017-06-07 09:21:53 -0400176
David Tolnayeb7d79b2018-03-31 22:52:17 +0200177 let libsyntax_ast = if let Some(e) = libsyntax_parse_and_rewrite(&raw) {
178 e
179 } else {
180 failed += 1;
181 errorf!("\nFAIL - libsyntax failed to parse raw\n");
182 continue;
183 };
Michael Layzell53fc31a2017-06-07 09:21:53 -0400184
David Tolnayeb7d79b2018-03-31 22:52:17 +0200185 let syn_expr = syn_brackets(expr);
186 let syn_ast = if let Some(e) = parse::libsyntax_expr(&quote!(#syn_expr).to_string()) {
187 e
188 } else {
189 failed += 1;
190 errorf!("\nFAIL - libsyntax failed to parse bracketed\n");
191 continue;
192 };
Michael Layzell53fc31a2017-06-07 09:21:53 -0400193
David Tolnayecd024d2018-07-21 09:07:56 -0700194 if SpanlessEq::eq(&syn_ast, &libsyntax_ast) {
David Tolnayeb7d79b2018-03-31 22:52:17 +0200195 passed += 1;
196 } else {
197 failed += 1;
198 errorf!("\nFAIL\n{:?}\n!=\n{:?}\n", syn_ast, libsyntax_ast);
199 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400200 }
David Tolnay5d1a3ee2018-03-17 19:41:36 -0700201 });
Michael Layzell53fc31a2017-06-07 09:21:53 -0400202
203 (passed, failed)
204}
205
David Tolnaycfa5cc02017-11-13 01:05:11 -0800206fn libsyntax_parse_and_rewrite(input: &str) -> Option<P<ast::Expr>> {
David Tolnay3cede942017-12-26 12:29:24 -0500207 parse::libsyntax_expr(input).and_then(libsyntax_brackets)
Michael Layzell53fc31a2017-06-07 09:21:53 -0400208}
209
210/// Wrap every expression which is not already wrapped in parens with parens, to
David Tolnay0ccb6d12018-08-14 22:43:00 -0700211/// reveal the precidence of the parsed expressions, and produce a stringified
212/// form of the resulting expression.
Michael Layzell53fc31a2017-06-07 09:21:53 -0400213///
David Tolnaycfa5cc02017-11-13 01:05:11 -0800214/// This method operates on libsyntax objects.
David Tolnay176838f2019-02-07 17:28:37 +0100215fn libsyntax_brackets(mut libsyntax_expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
David Tolnayc8659922018-08-14 22:40:50 -0700216 use rustc_data_structures::thin_vec::ThinVec;
David Tolnay0eab7d92018-09-26 22:10:40 -0700217 use smallvec::SmallVec;
David Tolnay176838f2019-02-07 17:28:37 +0100218 use std::mem;
David Tolnay51382052017-12-27 13:46:21 -0500219 use syntax::ast::{Expr, ExprKind, Field, Mac, Pat, Stmt, StmtKind, Ty};
David Tolnay176838f2019-02-07 17:28:37 +0100220 use syntax::mut_visit::{self, MutVisitor};
David Tolnayfcd4a672019-01-24 20:56:54 -0800221 use syntax_pos::DUMMY_SP;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400222
David Tolnay176838f2019-02-07 17:28:37 +0100223 struct BracketsVisitor {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400224 failed: bool,
225 };
David Tolnay176838f2019-02-07 17:28:37 +0100226 impl MutVisitor for BracketsVisitor {
227 fn visit_expr(&mut self, e: &mut P<Expr>) {
228 mut_visit::noop_visit_expr(e, self);
229 match e.node {
230 ExprKind::If(..) | ExprKind::Block(..) | ExprKind::IfLet(..) => {}
231 _ => {
232 let inner = mem::replace(
233 e,
234 P(Expr {
235 id: ast::DUMMY_NODE_ID,
236 node: ExprKind::Err,
237 span: DUMMY_SP,
238 attrs: ThinVec::new(),
239 }),
240 );
241 e.node = ExprKind::Paren(inner);
David Tolnay5d314dc2018-07-21 16:40:01 -0700242 }
David Tolnay176838f2019-02-07 17:28:37 +0100243 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400244 }
245
David Tolnay176838f2019-02-07 17:28:37 +0100246 fn visit_field(&mut self, f: &mut Field) {
247 if f.is_shorthand {
248 mut_visit::noop_visit_expr(&mut f.expr, self);
249 } else {
250 self.visit_expr(&mut f.expr);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400251 }
252 }
253
254 // We don't want to look at expressions that might appear in patterns or
255 // types yet. We'll look into comparing those in the future. For now
256 // focus on expressions appearing in other places.
David Tolnay176838f2019-02-07 17:28:37 +0100257 fn visit_pat(&mut self, pat: &mut P<Pat>) {
258 let _ = pat;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400259 }
260
David Tolnay176838f2019-02-07 17:28:37 +0100261 fn visit_ty(&mut self, ty: &mut P<Ty>) {
262 let _ = ty;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400263 }
264
David Tolnay176838f2019-02-07 17:28:37 +0100265 fn flat_map_stmt(&mut self, stmt: Stmt) -> SmallVec<[Stmt; 1]> {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400266 let node = match stmt.node {
267 // Don't wrap toplevel expressions in statements.
David Tolnay176838f2019-02-07 17:28:37 +0100268 StmtKind::Expr(mut e) => {
269 mut_visit::noop_visit_expr(&mut e, self);
270 StmtKind::Expr(e)
271 }
272 StmtKind::Semi(mut e) => {
273 mut_visit::noop_visit_expr(&mut e, self);
274 StmtKind::Semi(e)
275 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400276 s => s,
277 };
278
David Tolnay0eab7d92018-09-26 22:10:40 -0700279 smallvec![Stmt { node, ..stmt }]
Michael Layzell53fc31a2017-06-07 09:21:53 -0400280 }
281
David Tolnay176838f2019-02-07 17:28:37 +0100282 fn visit_mac(&mut self, mac: &mut Mac) {
David Tolnaycfa5cc02017-11-13 01:05:11 -0800283 // By default when folding over macros, libsyntax panics. This is
Michael Layzell53fc31a2017-06-07 09:21:53 -0400284 // because it's usually not what you want, you want to run after
285 // macro expansion. We do want to do that (syn doesn't do macro
David Tolnay176838f2019-02-07 17:28:37 +0100286 // expansion), so we implement visit_mac to just return the macro
Michael Layzell53fc31a2017-06-07 09:21:53 -0400287 // unchanged.
David Tolnay176838f2019-02-07 17:28:37 +0100288 let _ = mac;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400289 }
290 }
291
David Tolnay176838f2019-02-07 17:28:37 +0100292 let mut folder = BracketsVisitor { failed: false };
293 folder.visit_expr(&mut libsyntax_expr);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400294 if folder.failed {
295 None
296 } else {
David Tolnay176838f2019-02-07 17:28:37 +0100297 Some(libsyntax_expr)
Michael Layzell53fc31a2017-06-07 09:21:53 -0400298 }
299}
300
301/// Wrap every expression which is not already wrapped in parens with parens, to
David Tolnay0ccb6d12018-08-14 22:43:00 -0700302/// reveal the precedence of the parsed expressions, and produce a stringified
303/// form of the resulting expression.
Michael Layzell53fc31a2017-06-07 09:21:53 -0400304fn syn_brackets(syn_expr: syn::Expr) -> syn::Expr {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400305 use syn::fold::*;
David Tolnayeb7d79b2018-03-31 22:52:17 +0200306 use syn::*;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400307
David Tolnayeb752062018-01-06 13:51:42 -0800308 struct ParenthesizeEveryExpr;
309 impl Fold for ParenthesizeEveryExpr {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400310 fn fold_expr(&mut self, expr: Expr) -> Expr {
David Tolnay8c91b882017-12-28 23:04:32 -0500311 match expr {
312 Expr::Group(_) => unreachable!(),
David Tolnay9c119122018-09-01 18:47:02 -0700313 Expr::If(..) | Expr::Unsafe(..) | Expr::Block(..) | Expr::Let(..) => {
David Tolnay3bc597f2017-12-31 02:31:11 -0500314 fold_expr(self, expr)
Michael Layzell53fc31a2017-06-07 09:21:53 -0400315 }
David Tolnay5d314dc2018-07-21 16:40:01 -0700316 node => Expr::Paren(ExprParen {
317 attrs: Vec::new(),
318 expr: Box::new(fold_expr(self, node)),
319 paren_token: token::Paren::default(),
320 }),
David Tolnay8c91b882017-12-28 23:04:32 -0500321 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400322 }
323
324 fn fold_stmt(&mut self, stmt: Stmt) -> Stmt {
325 match stmt {
326 // Don't wrap toplevel expressions in statements.
David Tolnay1f0b7b82018-01-06 16:07:14 -0800327 Stmt::Expr(e) => Stmt::Expr(fold_expr(self, e)),
328 Stmt::Semi(e, semi) => Stmt::Semi(fold_expr(self, e), semi),
Michael Layzell53fc31a2017-06-07 09:21:53 -0400329 s => s,
330 }
331 }
332
333 // We don't want to look at expressions that might appear in patterns or
334 // types yet. We'll look into comparing those in the future. For now
335 // focus on expressions appearing in other places.
336 fn fold_pat(&mut self, pat: Pat) -> Pat {
337 pat
338 }
339
David Tolnayfd6bf5c2017-11-12 09:41:14 -0800340 fn fold_type(&mut self, ty: Type) -> Type {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400341 ty
342 }
343 }
344
David Tolnayeb752062018-01-06 13:51:42 -0800345 let mut folder = ParenthesizeEveryExpr;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400346 folder.fold_expr(syn_expr)
347}
348
349/// Walk through a crate collecting all expressions we can find in it.
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700350fn collect_exprs(file: syn::File) -> Vec<syn::Expr> {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400351 use syn::fold::*;
David Tolnayf2cfd722017-12-31 18:02:51 -0500352 use syn::punctuated::Punctuated;
David Tolnayeb7d79b2018-03-31 22:52:17 +0200353 use syn::*;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400354
David Tolnayeb752062018-01-06 13:51:42 -0800355 struct CollectExprs(Vec<Expr>);
356 impl Fold for CollectExprs {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400357 fn fold_expr(&mut self, expr: Expr) -> Expr {
358 self.0.push(expr);
359
David Tolnay8c91b882017-12-28 23:04:32 -0500360 Expr::Tuple(ExprTuple {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400361 attrs: vec![],
David Tolnayf2cfd722017-12-31 18:02:51 -0500362 elems: Punctuated::new(),
David Tolnay8c91b882017-12-28 23:04:32 -0500363 paren_token: token::Paren::default(),
364 })
Michael Layzell53fc31a2017-06-07 09:21:53 -0400365 }
366 }
367
David Tolnayeb752062018-01-06 13:51:42 -0800368 let mut folder = CollectExprs(vec![]);
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700369 folder.fold_file(file);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400370 folder.0
371}