blob: b3f90d2403198d9b77be3b1bb7188b5e4bd70869 [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 {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400247 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 },
David Tolnaya3174992018-04-06 22:41:59 -0700252 ..f
Michael Layzell53fc31a2017-06-07 09:21:53 -0400253 }
254 }
255
256 // We don't want to look at expressions that might appear in patterns or
257 // types yet. We'll look into comparing those in the future. For now
258 // focus on expressions appearing in other places.
259 fn fold_pat(&mut self, pat: P<Pat>) -> P<Pat> {
260 pat
261 }
262
263 fn fold_ty(&mut self, ty: P<Ty>) -> P<Ty> {
264 ty
265 }
266
267 fn fold_stmt(&mut self, stmt: Stmt) -> SmallVector<Stmt> {
268 let node = match stmt.node {
269 // Don't wrap toplevel expressions in statements.
David Tolnay51382052017-12-27 13:46:21 -0500270 StmtKind::Expr(e) => StmtKind::Expr(e.map(|e| fold::noop_fold_expr(e, self))),
271 StmtKind::Semi(e) => StmtKind::Semi(e.map(|e| fold::noop_fold_expr(e, self))),
Michael Layzell53fc31a2017-06-07 09:21:53 -0400272 s => s,
273 };
274
David Tolnay54bdb4f2018-03-17 13:00:42 -0700275 SmallVector::one(Stmt { node, ..stmt })
Michael Layzell53fc31a2017-06-07 09:21:53 -0400276 }
277
278 fn fold_mac(&mut self, mac: Mac) -> Mac {
David Tolnaycfa5cc02017-11-13 01:05:11 -0800279 // By default when folding over macros, libsyntax panics. This is
Michael Layzell53fc31a2017-06-07 09:21:53 -0400280 // because it's usually not what you want, you want to run after
281 // macro expansion. We do want to do that (syn doesn't do macro
282 // expansion), so we implement fold_mac to just return the macro
283 // unchanged.
284 mac
285 }
286 }
287
David Tolnay51382052017-12-27 13:46:21 -0500288 let mut folder = BracketsFolder { failed: false };
David Tolnaycfa5cc02017-11-13 01:05:11 -0800289 let e = folder.fold_expr(libsyntax_expr);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400290 if folder.failed {
291 None
292 } else {
293 Some(e)
294 }
295}
296
297/// Wrap every expression which is not already wrapped in parens with parens, to
David Tolnayeb752062018-01-06 13:51:42 -0800298/// reveal the precedence of the parsed expressions, and produce a stringified form
Michael Layzell53fc31a2017-06-07 09:21:53 -0400299/// of the resulting expression.
300fn syn_brackets(syn_expr: syn::Expr) -> syn::Expr {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400301 use syn::fold::*;
David Tolnayeb7d79b2018-03-31 22:52:17 +0200302 use syn::*;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400303
David Tolnayeb752062018-01-06 13:51:42 -0800304 fn paren(folder: &mut ParenthesizeEveryExpr, mut node: Expr) -> Expr {
David Tolnay2ae520a2017-12-29 11:19:50 -0500305 let attrs = node.replace_attrs(Vec::new());
David Tolnay8c91b882017-12-28 23:04:32 -0500306 Expr::Paren(ExprParen {
David Tolnay54bdb4f2018-03-17 13:00:42 -0700307 attrs,
David Tolnay61037c62018-01-05 16:21:03 -0800308 expr: Box::new(fold_expr(folder, node)),
David Tolnay42eaae12017-12-26 23:05:18 -0500309 paren_token: token::Paren::default(),
Michael Layzell53fc31a2017-06-07 09:21:53 -0400310 })
311 }
312
David Tolnayeb752062018-01-06 13:51:42 -0800313 struct ParenthesizeEveryExpr;
314 impl Fold for ParenthesizeEveryExpr {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400315 fn fold_expr(&mut self, expr: Expr) -> Expr {
David Tolnay8c91b882017-12-28 23:04:32 -0500316 match expr {
317 Expr::Group(_) => unreachable!(),
318 Expr::Paren(p) => paren(self, *p.expr),
David Tolnay61037c62018-01-05 16:21:03 -0800319 Expr::If(..) | Expr::Unsafe(..) | Expr::Block(..) | Expr::IfLet(..) => {
David Tolnay3bc597f2017-12-31 02:31:11 -0500320 fold_expr(self, expr)
Michael Layzell53fc31a2017-06-07 09:21:53 -0400321 }
322 node => paren(self, node),
David Tolnay8c91b882017-12-28 23:04:32 -0500323 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400324 }
325
326 fn fold_stmt(&mut self, stmt: Stmt) -> Stmt {
327 match stmt {
328 // Don't wrap toplevel expressions in statements.
David Tolnay1f0b7b82018-01-06 16:07:14 -0800329 Stmt::Expr(e) => Stmt::Expr(fold_expr(self, e)),
330 Stmt::Semi(e, semi) => Stmt::Semi(fold_expr(self, e), semi),
Michael Layzell53fc31a2017-06-07 09:21:53 -0400331 s => s,
332 }
333 }
334
335 // We don't want to look at expressions that might appear in patterns or
336 // types yet. We'll look into comparing those in the future. For now
337 // focus on expressions appearing in other places.
338 fn fold_pat(&mut self, pat: Pat) -> Pat {
339 pat
340 }
341
David Tolnayfd6bf5c2017-11-12 09:41:14 -0800342 fn fold_type(&mut self, ty: Type) -> Type {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400343 ty
344 }
345 }
346
David Tolnayeb752062018-01-06 13:51:42 -0800347 let mut folder = ParenthesizeEveryExpr;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400348 folder.fold_expr(syn_expr)
349}
350
351/// Walk through a crate collecting all expressions we can find in it.
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700352fn collect_exprs(file: syn::File) -> Vec<syn::Expr> {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400353 use syn::fold::*;
David Tolnayf2cfd722017-12-31 18:02:51 -0500354 use syn::punctuated::Punctuated;
David Tolnayeb7d79b2018-03-31 22:52:17 +0200355 use syn::*;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400356
David Tolnayeb752062018-01-06 13:51:42 -0800357 struct CollectExprs(Vec<Expr>);
358 impl Fold for CollectExprs {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400359 fn fold_expr(&mut self, expr: Expr) -> Expr {
360 self.0.push(expr);
361
David Tolnay8c91b882017-12-28 23:04:32 -0500362 Expr::Tuple(ExprTuple {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400363 attrs: vec![],
David Tolnayf2cfd722017-12-31 18:02:51 -0500364 elems: Punctuated::new(),
David Tolnay8c91b882017-12-28 23:04:32 -0500365 paren_token: token::Paren::default(),
366 })
Michael Layzell53fc31a2017-06-07 09:21:53 -0400367 }
368 }
369
David Tolnayeb752062018-01-06 13:51:42 -0800370 let mut folder = CollectExprs(vec![]);
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700371 folder.fold_file(file);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400372 folder.0
373}