blob: d9cd744c061a5b8c438081758a15c0574ba88b95 [file] [log] [blame]
David Tolnay55535012018-01-05 16:39:23 -08001// Copyright 2018 Syn Developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
Michael Layzell53fc31a2017-06-07 09:21:53 -04009#![cfg(all(feature = "full", feature = "fold"))]
Nika Layzella2a1a4a2017-11-19 11:33:17 -050010#![feature(rustc_private)]
11
Michael Layzell53fc31a2017-06-07 09:21:53 -040012//! The tests in this module do the following:
13//!
David Tolnaycfa5cc02017-11-13 01:05:11 -080014//! 1. Parse a given expression in both `syn` and `libsyntax`.
Michael Layzell53fc31a2017-06-07 09:21:53 -040015//! 2. Fold over the expression adding brackets around each subexpression (with
David Tolnaycfa5cc02017-11-13 01:05:11 -080016//! some complications - see the `syn_brackets` and `libsyntax_brackets`
Michael Layzell53fc31a2017-06-07 09:21:53 -040017//! methods).
18//! 3. Serialize the `syn` expression back into a string, and re-parse it with
David Tolnaycfa5cc02017-11-13 01:05:11 -080019//! `libsyntax`.
Michael Layzell53fc31a2017-06-07 09:21:53 -040020//! 4. Respan all of the expressions, replacing the spans with the default spans.
21//! 5. Compare the expressions with one another, if they are not equal fail.
22
23#[macro_use]
24extern crate quote;
David Tolnayee97dbf2017-11-19 14:24:38 -080025extern crate rayon;
Michael Layzell53fc31a2017-06-07 09:21:53 -040026extern crate syn;
David Tolnaycfa5cc02017-11-13 01:05:11 -080027extern crate syntax;
Michael Layzell53fc31a2017-06-07 09:21:53 -040028extern crate walkdir;
Michael Layzell53fc31a2017-06-07 09:21:53 -040029
David Tolnay51382052017-12-27 13:46:21 -050030use rayon::iter::{IntoParallelIterator, ParallelIterator};
David Tolnaycfa5cc02017-11-13 01:05:11 -080031use syntax::ast;
32use syntax::ptr::P;
David Tolnay51382052017-12-27 13:46:21 -050033use walkdir::{DirEntry, WalkDir, WalkDirIterator};
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 Tolnay51382052017-12-27 13:46:21 -050040use common::{parse, respan};
Michael Layzell53fc31a2017-06-07 09:21:53 -040041
Michael Layzell53fc31a2017-06-07 09:21:53 -040042#[macro_use]
David Tolnaydd125562017-12-31 02:16:22 -050043mod macros;
44
45#[allow(dead_code)]
Michael Layzell53fc31a2017-06-07 09:21:53 -040046mod common;
47
48/// Test some pre-set expressions chosen by us.
49#[test]
50fn test_simple_precedence() {
51 const EXPRS: &[&str] = &[
52 "1 + 2 * 3 + 4",
53 "1 + 2 * ( 3 + 4 )",
54 "{ for i in r { } *some_ptr += 1; }",
55 "{ loop { break 5; } }",
56 "{ if true { () }.mthd() }",
Nika Layzell3aa0dc72017-12-04 13:41:28 -050057 "{ for i in unsafe { 20 } { } }",
Michael Layzell53fc31a2017-06-07 09:21:53 -040058 ];
59
60 let mut failed = 0;
61
62 for input in EXPRS {
63 let expr = if let Some(expr) = parse::syn_expr(input) {
64 expr
65 } else {
66 failed += 1;
67 continue;
68 };
69
70 let pf = match test_expressions(vec![expr]) {
71 (1, 0) => "passed",
72 (0, 1) => {
73 failed += 1;
74 "failed"
75 }
76 _ => unreachable!(),
77 };
78 errorf!("=== {}: {}\n", input, pf);
79 }
80
81 if failed > 0 {
82 panic!("Failed {} tests", failed);
83 }
84}
85
86/// Test expressions from rustc, like in `test_round_trip`.
87#[test]
88fn test_rustc_precedence() {
Michael Layzell53fc31a2017-06-07 09:21:53 -040089 common::check_min_stack();
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 Tolnayee97dbf2017-11-19 14:24:38 -080099 WalkDir::new("tests/rust")
100 .sort_by(|a, b| a.cmp(b))
101 .into_iter()
102 .filter_entry(common::base_dir_filter)
103 .collect::<Result<Vec<DirEntry>, walkdir::Error>>()
104 .unwrap()
105 .into_par_iter()
David Tolnay51382052017-12-27 13:46:21 -0500106 .for_each(|entry| {
107 let path = entry.path();
108 if path.is_dir() {
109 return;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400110 }
David Tolnay51382052017-12-27 13:46:21 -0500111
112 // Our version of `libsyntax` can't parse this tests
113 if path.to_str()
114 .unwrap()
115 .ends_with("optional_comma_in_match_arm.rs")
116 {
117 return;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400118 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400119
David Tolnay51382052017-12-27 13:46:21 -0500120 let mut file = File::open(path).unwrap();
121 let mut content = String::new();
122 file.read_to_string(&mut content).unwrap();
Michael Layzell53fc31a2017-06-07 09:21:53 -0400123
David Tolnay51382052017-12-27 13:46:21 -0500124 let (l_passed, l_failed) = match syn::parse_file(&content) {
125 Ok(file) => {
126 let exprs = collect_exprs(file);
127 test_expressions(exprs)
128 }
129 Err(msg) => {
130 errorf!("syn failed to parse\n{:?}\n", msg);
131 (0, 1)
132 }
133 };
David Tolnayee97dbf2017-11-19 14:24:38 -0800134
David Tolnay51382052017-12-27 13:46:21 -0500135 errorf!(
136 "=== {}: {} passed | {} failed\n",
137 path.display(),
138 l_passed,
139 l_failed
140 );
141
142 passed.fetch_add(l_passed, Ordering::SeqCst);
143 let prev_failed = failed.fetch_add(l_failed, Ordering::SeqCst);
144
145 if prev_failed + l_failed >= abort_after {
146 process::exit(1);
147 }
148 });
David Tolnayee97dbf2017-11-19 14:24:38 -0800149
150 let passed = passed.load(Ordering::SeqCst);
151 let failed = failed.load(Ordering::SeqCst);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400152
153 errorf!("\n===== Precedence Test Results =====\n");
154 errorf!("{} passed | {} failed\n", passed, failed);
155
Michael Layzell53fc31a2017-06-07 09:21:53 -0400156 if failed > 0 {
157 panic!("{} failures", failed);
158 }
159}
160
David Tolnayee97dbf2017-11-19 14:24:38 -0800161fn test_expressions(exprs: Vec<syn::Expr>) -> (usize, usize) {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400162 let mut passed = 0;
163 let mut failed = 0;
164
165 for expr in exprs {
166 let raw = quote!(#expr).to_string();
167
David Tolnaycfa5cc02017-11-13 01:05:11 -0800168 let libsyntax_ast = if let Some(e) = libsyntax_parse_and_rewrite(&raw) {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400169 e
170 } else {
171 failed += 1;
David Tolnaycfa5cc02017-11-13 01:05:11 -0800172 errorf!("\nFAIL - libsyntax failed to parse raw\n");
Michael Layzell53fc31a2017-06-07 09:21:53 -0400173 continue;
174 };
175
176 let syn_expr = syn_brackets(expr);
David Tolnaycfa5cc02017-11-13 01:05:11 -0800177 let syn_ast = if let Some(e) = parse::libsyntax_expr(&quote!(#syn_expr).to_string()) {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400178 e
179 } else {
180 failed += 1;
David Tolnaycfa5cc02017-11-13 01:05:11 -0800181 errorf!("\nFAIL - libsyntax failed to parse bracketed\n");
Michael Layzell53fc31a2017-06-07 09:21:53 -0400182 continue;
183 };
184
185 let syn_ast = respan::respan_expr(syn_ast);
David Tolnaycfa5cc02017-11-13 01:05:11 -0800186 let libsyntax_ast = respan::respan_expr(libsyntax_ast);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400187
David Tolnaycfa5cc02017-11-13 01:05:11 -0800188 if syn_ast == libsyntax_ast {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400189 passed += 1;
190 } else {
191 failed += 1;
David Tolnaycfa5cc02017-11-13 01:05:11 -0800192 errorf!("\nFAIL\n{:?}\n!=\n{:?}\n", syn_ast, libsyntax_ast);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400193 }
194 }
195
196 (passed, failed)
197}
198
David Tolnaycfa5cc02017-11-13 01:05:11 -0800199fn libsyntax_parse_and_rewrite(input: &str) -> Option<P<ast::Expr>> {
David Tolnay3cede942017-12-26 12:29:24 -0500200 parse::libsyntax_expr(input).and_then(libsyntax_brackets)
Michael Layzell53fc31a2017-06-07 09:21:53 -0400201}
202
203/// Wrap every expression which is not already wrapped in parens with parens, to
204/// reveal the precidence of the parsed expressions, and produce a stringified form
205/// of the resulting expression.
206///
David Tolnaycfa5cc02017-11-13 01:05:11 -0800207/// This method operates on libsyntax objects.
208fn libsyntax_brackets(libsyntax_expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
David Tolnay51382052017-12-27 13:46:21 -0500209 use syntax::ast::{Expr, ExprKind, Field, Mac, Pat, Stmt, StmtKind, Ty};
David Tolnaycfa5cc02017-11-13 01:05:11 -0800210 use syntax::fold::{self, Folder};
211 use syntax::util::ThinVec;
212 use syntax::util::small_vector::SmallVector;
213 use syntax::ext::quote::rt::DUMMY_SP;
214 use syntax::codemap;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400215
216 fn expr(node: ExprKind) -> P<Expr> {
217 P(Expr {
218 id: ast::DUMMY_NODE_ID,
219 node: node,
220 span: DUMMY_SP,
221 attrs: ThinVec::new(),
222 })
223 }
224
225 struct BracketsFolder {
226 failed: bool,
227 };
228 impl Folder for BracketsFolder {
229 fn fold_expr(&mut self, e: P<Expr>) -> P<Expr> {
David Tolnay51382052017-12-27 13:46:21 -0500230 e.map(|e| Expr {
231 node: match e.node {
232 ExprKind::Paren(inner) => {
233 ExprKind::Paren(inner.map(|e| fold::noop_fold_expr(e, self)))
234 }
235 ExprKind::If(..) | ExprKind::Block(..) | ExprKind::IfLet(..) => {
236 return fold::noop_fold_expr(e, self);
237 }
238 node => ExprKind::Paren(expr(node).map(|e| fold::noop_fold_expr(e, self))),
239 },
240 ..e
Michael Layzell53fc31a2017-06-07 09:21:53 -0400241 })
242 }
243
244 fn fold_field(&mut self, f: Field) -> Field {
245 Field {
246 ident: codemap::respan(f.ident.span, self.fold_ident(f.ident.node)),
247 expr: if f.is_shorthand {
248 f.expr.map(|e| fold::noop_fold_expr(e, self))
249 } else {
250 self.fold_expr(f.expr)
251 },
252 span: self.new_span(f.span),
253 is_shorthand: f.is_shorthand,
254 attrs: fold::fold_thin_attrs(f.attrs, self),
255 }
256 }
257
258 // We don't want to look at expressions that might appear in patterns or
259 // types yet. We'll look into comparing those in the future. For now
260 // focus on expressions appearing in other places.
261 fn fold_pat(&mut self, pat: P<Pat>) -> P<Pat> {
262 pat
263 }
264
265 fn fold_ty(&mut self, ty: P<Ty>) -> P<Ty> {
266 ty
267 }
268
269 fn fold_stmt(&mut self, stmt: Stmt) -> SmallVector<Stmt> {
270 let node = match stmt.node {
271 // Don't wrap toplevel expressions in statements.
David Tolnay51382052017-12-27 13:46:21 -0500272 StmtKind::Expr(e) => StmtKind::Expr(e.map(|e| fold::noop_fold_expr(e, self))),
273 StmtKind::Semi(e) => StmtKind::Semi(e.map(|e| fold::noop_fold_expr(e, self))),
Michael Layzell53fc31a2017-06-07 09:21:53 -0400274 s => s,
275 };
276
David Tolnay51382052017-12-27 13:46:21 -0500277 SmallVector::one(Stmt { node: node, ..stmt })
Michael Layzell53fc31a2017-06-07 09:21:53 -0400278 }
279
280 fn fold_mac(&mut self, mac: Mac) -> Mac {
David Tolnaycfa5cc02017-11-13 01:05:11 -0800281 // By default when folding over macros, libsyntax panics. This is
Michael Layzell53fc31a2017-06-07 09:21:53 -0400282 // because it's usually not what you want, you want to run after
283 // macro expansion. We do want to do that (syn doesn't do macro
284 // expansion), so we implement fold_mac to just return the macro
285 // unchanged.
286 mac
287 }
288 }
289
David Tolnay51382052017-12-27 13:46:21 -0500290 let mut folder = BracketsFolder { failed: false };
David Tolnaycfa5cc02017-11-13 01:05:11 -0800291 let e = folder.fold_expr(libsyntax_expr);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400292 if folder.failed {
293 None
294 } else {
295 Some(e)
296 }
297}
298
299/// Wrap every expression which is not already wrapped in parens with parens, to
David Tolnayeb752062018-01-06 13:51:42 -0800300/// reveal the precedence of the parsed expressions, and produce a stringified form
Michael Layzell53fc31a2017-06-07 09:21:53 -0400301/// of the resulting expression.
302fn syn_brackets(syn_expr: syn::Expr) -> syn::Expr {
303 use syn::*;
304 use syn::fold::*;
305
David Tolnayeb752062018-01-06 13:51:42 -0800306 fn paren(folder: &mut ParenthesizeEveryExpr, mut node: Expr) -> Expr {
David Tolnay2ae520a2017-12-29 11:19:50 -0500307 let attrs = node.replace_attrs(Vec::new());
David Tolnay8c91b882017-12-28 23:04:32 -0500308 Expr::Paren(ExprParen {
309 attrs: attrs,
David Tolnay61037c62018-01-05 16:21:03 -0800310 expr: Box::new(fold_expr(folder, node)),
David Tolnay42eaae12017-12-26 23:05:18 -0500311 paren_token: token::Paren::default(),
Michael Layzell53fc31a2017-06-07 09:21:53 -0400312 })
313 }
314
David Tolnayeb752062018-01-06 13:51:42 -0800315 struct ParenthesizeEveryExpr;
316 impl Fold for ParenthesizeEveryExpr {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400317 fn fold_expr(&mut self, expr: Expr) -> Expr {
David Tolnay8c91b882017-12-28 23:04:32 -0500318 match expr {
319 Expr::Group(_) => unreachable!(),
320 Expr::Paren(p) => paren(self, *p.expr),
David Tolnay61037c62018-01-05 16:21:03 -0800321 Expr::If(..) | Expr::Unsafe(..) | Expr::Block(..) | Expr::IfLet(..) => {
David Tolnay3bc597f2017-12-31 02:31:11 -0500322 fold_expr(self, expr)
Michael Layzell53fc31a2017-06-07 09:21:53 -0400323 }
324 node => paren(self, node),
David Tolnay8c91b882017-12-28 23:04:32 -0500325 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400326 }
327
328 fn fold_stmt(&mut self, stmt: Stmt) -> Stmt {
329 match stmt {
330 // Don't wrap toplevel expressions in statements.
David Tolnay51382052017-12-27 13:46:21 -0500331 Stmt::Expr(e) => Stmt::Expr(Box::new(fold_expr(self, *e))),
332 Stmt::Semi(e, semi) => Stmt::Semi(Box::new(fold_expr(self, *e)), semi),
Michael Layzell53fc31a2017-06-07 09:21:53 -0400333 s => s,
334 }
335 }
336
337 // We don't want to look at expressions that might appear in patterns or
338 // types yet. We'll look into comparing those in the future. For now
339 // focus on expressions appearing in other places.
340 fn fold_pat(&mut self, pat: Pat) -> Pat {
341 pat
342 }
343
David Tolnayfd6bf5c2017-11-12 09:41:14 -0800344 fn fold_type(&mut self, ty: Type) -> Type {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400345 ty
346 }
347 }
348
David Tolnayeb752062018-01-06 13:51:42 -0800349 let mut folder = ParenthesizeEveryExpr;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400350 folder.fold_expr(syn_expr)
351}
352
353/// Walk through a crate collecting all expressions we can find in it.
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700354fn collect_exprs(file: syn::File) -> Vec<syn::Expr> {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400355 use syn::*;
356 use syn::fold::*;
David Tolnayf2cfd722017-12-31 18:02:51 -0500357 use syn::punctuated::Punctuated;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400358
David Tolnayeb752062018-01-06 13:51:42 -0800359 struct CollectExprs(Vec<Expr>);
360 impl Fold for CollectExprs {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400361 fn fold_expr(&mut self, expr: Expr) -> Expr {
362 self.0.push(expr);
363
David Tolnay8c91b882017-12-28 23:04:32 -0500364 Expr::Tuple(ExprTuple {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400365 attrs: vec![],
David Tolnayf2cfd722017-12-31 18:02:51 -0500366 elems: Punctuated::new(),
David Tolnay8c91b882017-12-28 23:04:32 -0500367 paren_token: token::Paren::default(),
368 })
Michael Layzell53fc31a2017-06-07 09:21:53 -0400369 }
370 }
371
David Tolnayeb752062018-01-06 13:51:42 -0800372 let mut folder = CollectExprs(vec![]);
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700373 folder.fold_file(file);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400374 folder.0
375}