blob: a3c39cd6f8a0086a40f12848553a764a3445c300 [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;
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 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")
Igor Gnatenko951a52b2018-03-12 10:33:33 +0100100 .sort_by(|a, b| a.file_name().cmp(b.file_name()))
David Tolnayee97dbf2017-11-19 14:24:38 -0800101 .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
David Tolnayeb7d79b2018-03-31 22:52:17 +0200165 syntax::with_globals(|| {
166 for expr in exprs {
167 let raw = quote!(#expr).to_string();
Michael Layzell53fc31a2017-06-07 09:21:53 -0400168
David Tolnayeb7d79b2018-03-31 22:52:17 +0200169 let libsyntax_ast = if let Some(e) = libsyntax_parse_and_rewrite(&raw) {
170 e
171 } else {
172 failed += 1;
173 errorf!("\nFAIL - libsyntax failed to parse raw\n");
174 continue;
175 };
Michael Layzell53fc31a2017-06-07 09:21:53 -0400176
David Tolnayeb7d79b2018-03-31 22:52:17 +0200177 let syn_expr = syn_brackets(expr);
178 let syn_ast = if let Some(e) = parse::libsyntax_expr(&quote!(#syn_expr).to_string()) {
179 e
180 } else {
181 failed += 1;
182 errorf!("\nFAIL - libsyntax failed to parse bracketed\n");
183 continue;
184 };
Michael Layzell53fc31a2017-06-07 09:21:53 -0400185
David Tolnayeb7d79b2018-03-31 22:52:17 +0200186 let syn_ast = respan::respan_expr(syn_ast);
187 let libsyntax_ast = respan::respan_expr(libsyntax_ast);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400188
David Tolnayeb7d79b2018-03-31 22:52:17 +0200189 if syn_ast == libsyntax_ast {
190 passed += 1;
191 } else {
192 failed += 1;
193 errorf!("\nFAIL\n{:?}\n!=\n{:?}\n", syn_ast, libsyntax_ast);
194 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400195 }
David Tolnay5d1a3ee2018-03-17 19:41:36 -0700196 });
Michael Layzell53fc31a2017-06-07 09:21:53 -0400197
198 (passed, failed)
199}
200
David Tolnaycfa5cc02017-11-13 01:05:11 -0800201fn libsyntax_parse_and_rewrite(input: &str) -> Option<P<ast::Expr>> {
David Tolnay3cede942017-12-26 12:29:24 -0500202 parse::libsyntax_expr(input).and_then(libsyntax_brackets)
Michael Layzell53fc31a2017-06-07 09:21:53 -0400203}
204
205/// Wrap every expression which is not already wrapped in parens with parens, to
206/// reveal the precidence of the parsed expressions, and produce a stringified form
207/// of the resulting expression.
208///
David Tolnaycfa5cc02017-11-13 01:05:11 -0800209/// This method operates on libsyntax objects.
210fn libsyntax_brackets(libsyntax_expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
David Tolnay51382052017-12-27 13:46:21 -0500211 use syntax::ast::{Expr, ExprKind, Field, Mac, Pat, Stmt, StmtKind, Ty};
David Tolnayeb7d79b2018-03-31 22:52:17 +0200212 use syntax::ext::quote::rt::DUMMY_SP;
David Tolnaycfa5cc02017-11-13 01:05:11 -0800213 use syntax::fold::{self, Folder};
214 use syntax::util::ThinVec;
215 use syntax::util::small_vector::SmallVector;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400216
217 fn expr(node: ExprKind) -> P<Expr> {
218 P(Expr {
219 id: ast::DUMMY_NODE_ID,
David Tolnay54bdb4f2018-03-17 13:00:42 -0700220 node,
Michael Layzell53fc31a2017-06-07 09:21:53 -0400221 span: DUMMY_SP,
222 attrs: ThinVec::new(),
223 })
224 }
225
226 struct BracketsFolder {
227 failed: bool,
228 };
229 impl Folder for BracketsFolder {
230 fn fold_expr(&mut self, e: P<Expr>) -> P<Expr> {
David Tolnay51382052017-12-27 13:46:21 -0500231 e.map(|e| Expr {
232 node: match e.node {
233 ExprKind::Paren(inner) => {
234 ExprKind::Paren(inner.map(|e| fold::noop_fold_expr(e, self)))
235 }
236 ExprKind::If(..) | ExprKind::Block(..) | ExprKind::IfLet(..) => {
237 return fold::noop_fold_expr(e, self);
238 }
239 node => ExprKind::Paren(expr(node).map(|e| fold::noop_fold_expr(e, self))),
240 },
241 ..e
Michael Layzell53fc31a2017-06-07 09:21:53 -0400242 })
243 }
244
245 fn fold_field(&mut self, f: Field) -> Field {
246 Field {
David Tolnayffc86762018-04-06 22:13:41 -0700247 ident: self.fold_ident(f.ident),
Michael Layzell53fc31a2017-06-07 09:21:53 -0400248 expr: if f.is_shorthand {
249 f.expr.map(|e| fold::noop_fold_expr(e, self))
250 } else {
251 self.fold_expr(f.expr)
252 },
253 span: self.new_span(f.span),
254 is_shorthand: f.is_shorthand,
255 attrs: fold::fold_thin_attrs(f.attrs, self),
256 }
257 }
258
259 // We don't want to look at expressions that might appear in patterns or
260 // types yet. We'll look into comparing those in the future. For now
261 // focus on expressions appearing in other places.
262 fn fold_pat(&mut self, pat: P<Pat>) -> P<Pat> {
263 pat
264 }
265
266 fn fold_ty(&mut self, ty: P<Ty>) -> P<Ty> {
267 ty
268 }
269
270 fn fold_stmt(&mut self, stmt: Stmt) -> SmallVector<Stmt> {
271 let node = match stmt.node {
272 // Don't wrap toplevel expressions in statements.
David Tolnay51382052017-12-27 13:46:21 -0500273 StmtKind::Expr(e) => StmtKind::Expr(e.map(|e| fold::noop_fold_expr(e, self))),
274 StmtKind::Semi(e) => StmtKind::Semi(e.map(|e| fold::noop_fold_expr(e, self))),
Michael Layzell53fc31a2017-06-07 09:21:53 -0400275 s => s,
276 };
277
David Tolnay54bdb4f2018-03-17 13:00:42 -0700278 SmallVector::one(Stmt { node, ..stmt })
Michael Layzell53fc31a2017-06-07 09:21:53 -0400279 }
280
281 fn fold_mac(&mut self, mac: Mac) -> 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
285 // expansion), so we implement fold_mac to just return the macro
286 // unchanged.
287 mac
288 }
289 }
290
David Tolnay51382052017-12-27 13:46:21 -0500291 let mut folder = BracketsFolder { failed: false };
David Tolnaycfa5cc02017-11-13 01:05:11 -0800292 let e = folder.fold_expr(libsyntax_expr);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400293 if folder.failed {
294 None
295 } else {
296 Some(e)
297 }
298}
299
300/// Wrap every expression which is not already wrapped in parens with parens, to
David Tolnayeb752062018-01-06 13:51:42 -0800301/// reveal the precedence of the parsed expressions, and produce a stringified form
Michael Layzell53fc31a2017-06-07 09:21:53 -0400302/// of the resulting expression.
303fn 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 fn paren(folder: &mut ParenthesizeEveryExpr, mut node: Expr) -> Expr {
David Tolnay2ae520a2017-12-29 11:19:50 -0500308 let attrs = node.replace_attrs(Vec::new());
David Tolnay8c91b882017-12-28 23:04:32 -0500309 Expr::Paren(ExprParen {
David Tolnay54bdb4f2018-03-17 13:00:42 -0700310 attrs,
David Tolnay61037c62018-01-05 16:21:03 -0800311 expr: Box::new(fold_expr(folder, node)),
David Tolnay42eaae12017-12-26 23:05:18 -0500312 paren_token: token::Paren::default(),
Michael Layzell53fc31a2017-06-07 09:21:53 -0400313 })
314 }
315
David Tolnayeb752062018-01-06 13:51:42 -0800316 struct ParenthesizeEveryExpr;
317 impl Fold for ParenthesizeEveryExpr {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400318 fn fold_expr(&mut self, expr: Expr) -> Expr {
David Tolnay8c91b882017-12-28 23:04:32 -0500319 match expr {
320 Expr::Group(_) => unreachable!(),
321 Expr::Paren(p) => paren(self, *p.expr),
David Tolnay61037c62018-01-05 16:21:03 -0800322 Expr::If(..) | Expr::Unsafe(..) | Expr::Block(..) | Expr::IfLet(..) => {
David Tolnay3bc597f2017-12-31 02:31:11 -0500323 fold_expr(self, expr)
Michael Layzell53fc31a2017-06-07 09:21:53 -0400324 }
325 node => paren(self, node),
David Tolnay8c91b882017-12-28 23:04:32 -0500326 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400327 }
328
329 fn fold_stmt(&mut self, stmt: Stmt) -> Stmt {
330 match stmt {
331 // Don't wrap toplevel expressions in statements.
David Tolnay1f0b7b82018-01-06 16:07:14 -0800332 Stmt::Expr(e) => Stmt::Expr(fold_expr(self, e)),
333 Stmt::Semi(e, semi) => Stmt::Semi(fold_expr(self, e), semi),
Michael Layzell53fc31a2017-06-07 09:21:53 -0400334 s => s,
335 }
336 }
337
338 // We don't want to look at expressions that might appear in patterns or
339 // types yet. We'll look into comparing those in the future. For now
340 // focus on expressions appearing in other places.
341 fn fold_pat(&mut self, pat: Pat) -> Pat {
342 pat
343 }
344
David Tolnayfd6bf5c2017-11-12 09:41:14 -0800345 fn fold_type(&mut self, ty: Type) -> Type {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400346 ty
347 }
348 }
349
David Tolnayeb752062018-01-06 13:51:42 -0800350 let mut folder = ParenthesizeEveryExpr;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400351 folder.fold_expr(syn_expr)
352}
353
354/// Walk through a crate collecting all expressions we can find in it.
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700355fn collect_exprs(file: syn::File) -> Vec<syn::Expr> {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400356 use syn::fold::*;
David Tolnayf2cfd722017-12-31 18:02:51 -0500357 use syn::punctuated::Punctuated;
David Tolnayeb7d79b2018-03-31 22:52:17 +0200358 use syn::*;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400359
David Tolnayeb752062018-01-06 13:51:42 -0800360 struct CollectExprs(Vec<Expr>);
361 impl Fold for CollectExprs {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400362 fn fold_expr(&mut self, expr: Expr) -> Expr {
363 self.0.push(expr);
364
David Tolnay8c91b882017-12-28 23:04:32 -0500365 Expr::Tuple(ExprTuple {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400366 attrs: vec![],
David Tolnayf2cfd722017-12-31 18:02:51 -0500367 elems: Punctuated::new(),
David Tolnay8c91b882017-12-28 23:04:32 -0500368 paren_token: token::Paren::default(),
369 })
Michael Layzell53fc31a2017-06-07 09:21:53 -0400370 }
371 }
372
David Tolnayeb752062018-01-06 13:51:42 -0800373 let mut folder = CollectExprs(vec![]);
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700374 folder.fold_file(file);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400375 folder.0
376}