blob: 2b67094c5aec52f992a2a66212d4baf096b8da53 [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"))]
David Tolnayecd024d2018-07-21 09:07:56 -070010#![recursion_limit = "1024"]
Nika Layzella2a1a4a2017-11-19 11:33:17 -050011#![feature(rustc_private)]
12
Michael Layzell53fc31a2017-06-07 09:21:53 -040013//! The tests in this module do the following:
14//!
David Tolnaycfa5cc02017-11-13 01:05:11 -080015//! 1. Parse a given expression in both `syn` and `libsyntax`.
Michael Layzell53fc31a2017-06-07 09:21:53 -040016//! 2. Fold over the expression adding brackets around each subexpression (with
David Tolnaycfa5cc02017-11-13 01:05:11 -080017//! some complications - see the `syn_brackets` and `libsyntax_brackets`
Michael Layzell53fc31a2017-06-07 09:21:53 -040018//! methods).
19//! 3. Serialize the `syn` expression back into a string, and re-parse it with
David Tolnaycfa5cc02017-11-13 01:05:11 -080020//! `libsyntax`.
David Tolnay0ccb6d12018-08-14 22:43:00 -070021//! 4. Respan all of the expressions, replacing the spans with the default
22//! spans.
Michael Layzell53fc31a2017-06-07 09:21:53 -040023//! 5. Compare the expressions with one another, if they are not equal fail.
24
25#[macro_use]
26extern crate quote;
David Tolnayee97dbf2017-11-19 14:24:38 -080027extern crate rayon;
David Tolnayc8659922018-08-14 22:40:50 -070028extern crate rustc_data_structures;
Michael Layzell53fc31a2017-06-07 09:21:53 -040029extern crate syn;
David Tolnaycfa5cc02017-11-13 01:05:11 -080030extern crate syntax;
Michael Layzell53fc31a2017-06-07 09:21:53 -040031extern crate walkdir;
Michael Layzell53fc31a2017-06-07 09:21:53 -040032
David Tolnay51382052017-12-27 13:46:21 -050033use rayon::iter::{IntoParallelIterator, ParallelIterator};
David Tolnaycfa5cc02017-11-13 01:05:11 -080034use syntax::ast;
35use syntax::ptr::P;
Igor Gnatenko951a52b2018-03-12 10:33:33 +010036use walkdir::{DirEntry, WalkDir};
David Tolnayee97dbf2017-11-19 14:24:38 -080037
38use std::fs::File;
39use std::io::Read;
David Tolnay3eaf7d82017-12-17 23:14:52 -080040use std::process;
David Tolnayee97dbf2017-11-19 14:24:38 -080041use std::sync::atomic::{AtomicUsize, Ordering};
Michael Layzell53fc31a2017-06-07 09:21:53 -040042
David Tolnayecd024d2018-07-21 09:07:56 -070043use common::eq::SpanlessEq;
44use common::parse;
Michael Layzell53fc31a2017-06-07 09:21:53 -040045
Michael Layzell53fc31a2017-06-07 09:21:53 -040046#[macro_use]
David Tolnaydd125562017-12-31 02:16:22 -050047mod macros;
48
49#[allow(dead_code)]
Michael Layzell53fc31a2017-06-07 09:21:53 -040050mod common;
51
52/// Test some pre-set expressions chosen by us.
53#[test]
54fn test_simple_precedence() {
55 const EXPRS: &[&str] = &[
56 "1 + 2 * 3 + 4",
57 "1 + 2 * ( 3 + 4 )",
58 "{ for i in r { } *some_ptr += 1; }",
59 "{ loop { break 5; } }",
60 "{ if true { () }.mthd() }",
Nika Layzell3aa0dc72017-12-04 13:41:28 -050061 "{ for i in unsafe { 20 } { } }",
Michael Layzell53fc31a2017-06-07 09:21:53 -040062 ];
63
64 let mut failed = 0;
65
66 for input in EXPRS {
67 let expr = if let Some(expr) = parse::syn_expr(input) {
68 expr
69 } else {
70 failed += 1;
71 continue;
72 };
73
74 let pf = match test_expressions(vec![expr]) {
75 (1, 0) => "passed",
76 (0, 1) => {
77 failed += 1;
78 "failed"
79 }
80 _ => unreachable!(),
81 };
82 errorf!("=== {}: {}\n", input, pf);
83 }
84
85 if failed > 0 {
86 panic!("Failed {} tests", failed);
87 }
88}
89
90/// Test expressions from rustc, like in `test_round_trip`.
91#[test]
92fn test_rustc_precedence() {
Michael Layzell53fc31a2017-06-07 09:21:53 -040093 common::check_min_stack();
Alex Crichton86374772017-07-07 20:39:28 -070094 common::clone_rust();
Michael Layzell53fc31a2017-06-07 09:21:53 -040095 let abort_after = common::abort_after();
96 if abort_after == 0 {
97 panic!("Skipping all precedence tests");
98 }
99
David Tolnayee97dbf2017-11-19 14:24:38 -0800100 let passed = AtomicUsize::new(0);
101 let failed = AtomicUsize::new(0);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400102
David Tolnayee97dbf2017-11-19 14:24:38 -0800103 WalkDir::new("tests/rust")
Igor Gnatenko951a52b2018-03-12 10:33:33 +0100104 .sort_by(|a, b| a.file_name().cmp(b.file_name()))
David Tolnayee97dbf2017-11-19 14:24:38 -0800105 .into_iter()
106 .filter_entry(common::base_dir_filter)
107 .collect::<Result<Vec<DirEntry>, walkdir::Error>>()
108 .unwrap()
109 .into_par_iter()
David Tolnay51382052017-12-27 13:46:21 -0500110 .for_each(|entry| {
111 let path = entry.path();
112 if path.is_dir() {
113 return;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400114 }
David Tolnay51382052017-12-27 13:46:21 -0500115
116 // Our version of `libsyntax` can't parse this tests
David Tolnay65fb5662018-05-20 20:02:28 -0700117 if path
118 .to_str()
David Tolnay51382052017-12-27 13:46:21 -0500119 .unwrap()
120 .ends_with("optional_comma_in_match_arm.rs")
121 {
122 return;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400123 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400124
David Tolnay51382052017-12-27 13:46:21 -0500125 let mut file = File::open(path).unwrap();
126 let mut content = String::new();
127 file.read_to_string(&mut content).unwrap();
Michael Layzell53fc31a2017-06-07 09:21:53 -0400128
David Tolnay51382052017-12-27 13:46:21 -0500129 let (l_passed, l_failed) = match syn::parse_file(&content) {
130 Ok(file) => {
131 let exprs = collect_exprs(file);
132 test_expressions(exprs)
133 }
134 Err(msg) => {
135 errorf!("syn failed to parse\n{:?}\n", msg);
136 (0, 1)
137 }
138 };
David Tolnayee97dbf2017-11-19 14:24:38 -0800139
David Tolnay51382052017-12-27 13:46:21 -0500140 errorf!(
141 "=== {}: {} passed | {} failed\n",
142 path.display(),
143 l_passed,
144 l_failed
145 );
146
147 passed.fetch_add(l_passed, Ordering::SeqCst);
148 let prev_failed = failed.fetch_add(l_failed, Ordering::SeqCst);
149
150 if prev_failed + l_failed >= abort_after {
151 process::exit(1);
152 }
153 });
David Tolnayee97dbf2017-11-19 14:24:38 -0800154
155 let passed = passed.load(Ordering::SeqCst);
156 let failed = failed.load(Ordering::SeqCst);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400157
158 errorf!("\n===== Precedence Test Results =====\n");
159 errorf!("{} passed | {} failed\n", passed, failed);
160
Michael Layzell53fc31a2017-06-07 09:21:53 -0400161 if failed > 0 {
162 panic!("{} failures", failed);
163 }
164}
165
David Tolnayee97dbf2017-11-19 14:24:38 -0800166fn test_expressions(exprs: Vec<syn::Expr>) -> (usize, usize) {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400167 let mut passed = 0;
168 let mut failed = 0;
169
David Tolnayeb7d79b2018-03-31 22:52:17 +0200170 syntax::with_globals(|| {
171 for expr in exprs {
172 let raw = quote!(#expr).to_string();
Michael Layzell53fc31a2017-06-07 09:21:53 -0400173
David Tolnayeb7d79b2018-03-31 22:52:17 +0200174 let libsyntax_ast = if let Some(e) = libsyntax_parse_and_rewrite(&raw) {
175 e
176 } else {
177 failed += 1;
178 errorf!("\nFAIL - libsyntax failed to parse raw\n");
179 continue;
180 };
Michael Layzell53fc31a2017-06-07 09:21:53 -0400181
David Tolnayeb7d79b2018-03-31 22:52:17 +0200182 let syn_expr = syn_brackets(expr);
183 let syn_ast = if let Some(e) = parse::libsyntax_expr(&quote!(#syn_expr).to_string()) {
184 e
185 } else {
186 failed += 1;
187 errorf!("\nFAIL - libsyntax failed to parse bracketed\n");
188 continue;
189 };
Michael Layzell53fc31a2017-06-07 09:21:53 -0400190
David Tolnayecd024d2018-07-21 09:07:56 -0700191 if SpanlessEq::eq(&syn_ast, &libsyntax_ast) {
David Tolnayeb7d79b2018-03-31 22:52:17 +0200192 passed += 1;
193 } else {
194 failed += 1;
195 errorf!("\nFAIL\n{:?}\n!=\n{:?}\n", syn_ast, libsyntax_ast);
196 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400197 }
David Tolnay5d1a3ee2018-03-17 19:41:36 -0700198 });
Michael Layzell53fc31a2017-06-07 09:21:53 -0400199
200 (passed, failed)
201}
202
David Tolnaycfa5cc02017-11-13 01:05:11 -0800203fn libsyntax_parse_and_rewrite(input: &str) -> Option<P<ast::Expr>> {
David Tolnay3cede942017-12-26 12:29:24 -0500204 parse::libsyntax_expr(input).and_then(libsyntax_brackets)
Michael Layzell53fc31a2017-06-07 09:21:53 -0400205}
206
207/// Wrap every expression which is not already wrapped in parens with parens, to
David Tolnay0ccb6d12018-08-14 22:43:00 -0700208/// reveal the precidence of the parsed expressions, and produce a stringified
209/// form of the resulting expression.
Michael Layzell53fc31a2017-06-07 09:21:53 -0400210///
David Tolnaycfa5cc02017-11-13 01:05:11 -0800211/// This method operates on libsyntax objects.
212fn libsyntax_brackets(libsyntax_expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
David Tolnayc8659922018-08-14 22:40:50 -0700213 use rustc_data_structures::small_vec::OneVector;
214 use rustc_data_structures::thin_vec::ThinVec;
David Tolnay51382052017-12-27 13:46:21 -0500215 use syntax::ast::{Expr, ExprKind, Field, Mac, Pat, Stmt, StmtKind, Ty};
David Tolnayeb7d79b2018-03-31 22:52:17 +0200216 use syntax::ext::quote::rt::DUMMY_SP;
David Tolnaycfa5cc02017-11-13 01:05:11 -0800217 use syntax::fold::{self, Folder};
Michael Layzell53fc31a2017-06-07 09:21:53 -0400218
Michael Layzell53fc31a2017-06-07 09:21:53 -0400219 struct BracketsFolder {
220 failed: bool,
221 };
222 impl Folder for BracketsFolder {
223 fn fold_expr(&mut self, e: P<Expr>) -> P<Expr> {
David Tolnay5d314dc2018-07-21 16:40:01 -0700224 e.map(|e| match e.node {
David Tolnay61e15e52018-08-01 00:28:36 -0700225 ExprKind::Block(_, label) if label.is_some() => Expr {
226 id: ast::DUMMY_NODE_ID,
227 node: ExprKind::Paren(P(e)),
228 span: DUMMY_SP,
229 attrs: ThinVec::new(),
230 },
David Tolnay5d314dc2018-07-21 16:40:01 -0700231 ExprKind::If(..) | ExprKind::Block(..) | ExprKind::IfLet(..) => {
232 fold::noop_fold_expr(e, self)
233 }
234 _ => Expr {
235 id: ast::DUMMY_NODE_ID,
236 node: ExprKind::Paren(P(fold::noop_fold_expr(e, self))),
237 span: DUMMY_SP,
238 attrs: ThinVec::new(),
David Tolnay51382052017-12-27 13:46:21 -0500239 },
Michael Layzell53fc31a2017-06-07 09:21:53 -0400240 })
241 }
242
243 fn fold_field(&mut self, f: Field) -> Field {
244 Field {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400245 expr: if f.is_shorthand {
246 f.expr.map(|e| fold::noop_fold_expr(e, self))
247 } else {
248 self.fold_expr(f.expr)
249 },
David Tolnaya3174992018-04-06 22:41:59 -0700250 ..f
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.
257 fn fold_pat(&mut self, pat: P<Pat>) -> P<Pat> {
258 pat
259 }
260
261 fn fold_ty(&mut self, ty: P<Ty>) -> P<Ty> {
262 ty
263 }
264
David Tolnayc8659922018-08-14 22:40:50 -0700265 fn fold_stmt(&mut self, stmt: Stmt) -> OneVector<Stmt> {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400266 let node = match stmt.node {
267 // Don't wrap toplevel expressions in statements.
David Tolnay51382052017-12-27 13:46:21 -0500268 StmtKind::Expr(e) => StmtKind::Expr(e.map(|e| fold::noop_fold_expr(e, self))),
269 StmtKind::Semi(e) => StmtKind::Semi(e.map(|e| fold::noop_fold_expr(e, self))),
Michael Layzell53fc31a2017-06-07 09:21:53 -0400270 s => s,
271 };
272
David Tolnayc8659922018-08-14 22:40:50 -0700273 OneVector::one(Stmt { node, ..stmt })
Michael Layzell53fc31a2017-06-07 09:21:53 -0400274 }
275
276 fn fold_mac(&mut self, mac: Mac) -> Mac {
David Tolnaycfa5cc02017-11-13 01:05:11 -0800277 // By default when folding over macros, libsyntax panics. This is
Michael Layzell53fc31a2017-06-07 09:21:53 -0400278 // because it's usually not what you want, you want to run after
279 // macro expansion. We do want to do that (syn doesn't do macro
280 // expansion), so we implement fold_mac to just return the macro
281 // unchanged.
282 mac
283 }
284 }
285
David Tolnay51382052017-12-27 13:46:21 -0500286 let mut folder = BracketsFolder { failed: false };
David Tolnaycfa5cc02017-11-13 01:05:11 -0800287 let e = folder.fold_expr(libsyntax_expr);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400288 if folder.failed {
289 None
290 } else {
291 Some(e)
292 }
293}
294
295/// Wrap every expression which is not already wrapped in parens with parens, to
David Tolnay0ccb6d12018-08-14 22:43:00 -0700296/// reveal the precedence of the parsed expressions, and produce a stringified
297/// form of the resulting expression.
Michael Layzell53fc31a2017-06-07 09:21:53 -0400298fn syn_brackets(syn_expr: syn::Expr) -> syn::Expr {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400299 use syn::fold::*;
David Tolnayeb7d79b2018-03-31 22:52:17 +0200300 use syn::*;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400301
David Tolnayeb752062018-01-06 13:51:42 -0800302 struct ParenthesizeEveryExpr;
303 impl Fold for ParenthesizeEveryExpr {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400304 fn fold_expr(&mut self, expr: Expr) -> Expr {
David Tolnay8c91b882017-12-28 23:04:32 -0500305 match expr {
306 Expr::Group(_) => unreachable!(),
David Tolnay61037c62018-01-05 16:21:03 -0800307 Expr::If(..) | Expr::Unsafe(..) | Expr::Block(..) | Expr::IfLet(..) => {
David Tolnay3bc597f2017-12-31 02:31:11 -0500308 fold_expr(self, expr)
Michael Layzell53fc31a2017-06-07 09:21:53 -0400309 }
David Tolnay5d314dc2018-07-21 16:40:01 -0700310 node => Expr::Paren(ExprParen {
311 attrs: Vec::new(),
312 expr: Box::new(fold_expr(self, node)),
313 paren_token: token::Paren::default(),
314 }),
David Tolnay8c91b882017-12-28 23:04:32 -0500315 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400316 }
317
318 fn fold_stmt(&mut self, stmt: Stmt) -> Stmt {
319 match stmt {
320 // Don't wrap toplevel expressions in statements.
David Tolnay1f0b7b82018-01-06 16:07:14 -0800321 Stmt::Expr(e) => Stmt::Expr(fold_expr(self, e)),
322 Stmt::Semi(e, semi) => Stmt::Semi(fold_expr(self, e), semi),
Michael Layzell53fc31a2017-06-07 09:21:53 -0400323 s => s,
324 }
325 }
326
327 // We don't want to look at expressions that might appear in patterns or
328 // types yet. We'll look into comparing those in the future. For now
329 // focus on expressions appearing in other places.
330 fn fold_pat(&mut self, pat: Pat) -> Pat {
331 pat
332 }
333
David Tolnayfd6bf5c2017-11-12 09:41:14 -0800334 fn fold_type(&mut self, ty: Type) -> Type {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400335 ty
336 }
337 }
338
David Tolnayeb752062018-01-06 13:51:42 -0800339 let mut folder = ParenthesizeEveryExpr;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400340 folder.fold_expr(syn_expr)
341}
342
343/// Walk through a crate collecting all expressions we can find in it.
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700344fn collect_exprs(file: syn::File) -> Vec<syn::Expr> {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400345 use syn::fold::*;
David Tolnayf2cfd722017-12-31 18:02:51 -0500346 use syn::punctuated::Punctuated;
David Tolnayeb7d79b2018-03-31 22:52:17 +0200347 use syn::*;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400348
David Tolnayeb752062018-01-06 13:51:42 -0800349 struct CollectExprs(Vec<Expr>);
350 impl Fold for CollectExprs {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400351 fn fold_expr(&mut self, expr: Expr) -> Expr {
352 self.0.push(expr);
353
David Tolnay8c91b882017-12-28 23:04:32 -0500354 Expr::Tuple(ExprTuple {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400355 attrs: vec![],
David Tolnayf2cfd722017-12-31 18:02:51 -0500356 elems: Punctuated::new(),
David Tolnay8c91b882017-12-28 23:04:32 -0500357 paren_token: token::Paren::default(),
358 })
Michael Layzell53fc31a2017-06-07 09:21:53 -0400359 }
360 }
361
David Tolnayeb752062018-01-06 13:51:42 -0800362 let mut folder = CollectExprs(vec![]);
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700363 folder.fold_file(file);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400364 folder.0
365}