blob: 93d50a457536cdda09eca4fc2a6726ec451eb07a [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 Tolnayd1c31cc2018-08-24 14:47:15 -040028extern crate regex;
David Tolnayc8659922018-08-14 22:40:50 -070029extern crate rustc_data_structures;
David Tolnay0eab7d92018-09-26 22:10:40 -070030#[macro_use]
31extern crate smallvec;
Michael Layzell53fc31a2017-06-07 09:21:53 -040032extern crate syn;
David Tolnaycfa5cc02017-11-13 01:05:11 -080033extern crate syntax;
Michael Layzell53fc31a2017-06-07 09:21:53 -040034extern crate walkdir;
Michael Layzell53fc31a2017-06-07 09:21:53 -040035
David Tolnay51382052017-12-27 13:46:21 -050036use rayon::iter::{IntoParallelIterator, ParallelIterator};
David Tolnayd1c31cc2018-08-24 14:47:15 -040037use regex::Regex;
David Tolnaycfa5cc02017-11-13 01:05:11 -080038use syntax::ast;
39use syntax::ptr::P;
Igor Gnatenko951a52b2018-03-12 10:33:33 +010040use walkdir::{DirEntry, WalkDir};
David Tolnayee97dbf2017-11-19 14:24:38 -080041
42use std::fs::File;
43use std::io::Read;
David Tolnay3eaf7d82017-12-17 23:14:52 -080044use std::process;
David Tolnayee97dbf2017-11-19 14:24:38 -080045use std::sync::atomic::{AtomicUsize, Ordering};
Michael Layzell53fc31a2017-06-07 09:21:53 -040046
David Tolnayecd024d2018-07-21 09:07:56 -070047use common::eq::SpanlessEq;
48use common::parse;
Michael Layzell53fc31a2017-06-07 09:21:53 -040049
Michael Layzell53fc31a2017-06-07 09:21:53 -040050#[macro_use]
David Tolnaydd125562017-12-31 02:16:22 -050051mod macros;
52
53#[allow(dead_code)]
Michael Layzell53fc31a2017-06-07 09:21:53 -040054mod common;
55
56/// Test some pre-set expressions chosen by us.
57#[test]
58fn test_simple_precedence() {
59 const EXPRS: &[&str] = &[
60 "1 + 2 * 3 + 4",
61 "1 + 2 * ( 3 + 4 )",
62 "{ for i in r { } *some_ptr += 1; }",
63 "{ loop { break 5; } }",
64 "{ if true { () }.mthd() }",
Nika Layzell3aa0dc72017-12-04 13:41:28 -050065 "{ for i in unsafe { 20 } { } }",
Michael Layzell53fc31a2017-06-07 09:21:53 -040066 ];
67
68 let mut failed = 0;
69
70 for input in EXPRS {
71 let expr = if let Some(expr) = parse::syn_expr(input) {
72 expr
73 } else {
74 failed += 1;
75 continue;
76 };
77
78 let pf = match test_expressions(vec![expr]) {
79 (1, 0) => "passed",
80 (0, 1) => {
81 failed += 1;
82 "failed"
83 }
84 _ => unreachable!(),
85 };
86 errorf!("=== {}: {}\n", input, pf);
87 }
88
89 if failed > 0 {
90 panic!("Failed {} tests", failed);
91 }
92}
93
94/// Test expressions from rustc, like in `test_round_trip`.
95#[test]
96fn test_rustc_precedence() {
Alex Crichton86374772017-07-07 20:39:28 -070097 common::clone_rust();
Michael Layzell53fc31a2017-06-07 09:21:53 -040098 let abort_after = common::abort_after();
99 if abort_after == 0 {
100 panic!("Skipping all precedence tests");
101 }
102
David Tolnayee97dbf2017-11-19 14:24:38 -0800103 let passed = AtomicUsize::new(0);
104 let failed = AtomicUsize::new(0);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400105
David Tolnayd1c31cc2018-08-24 14:47:15 -0400106 // 2018 edition is hard
107 let edition_regex = Regex::new(r"\b(async|try)[!(]").unwrap();
108
David Tolnayee97dbf2017-11-19 14:24:38 -0800109 WalkDir::new("tests/rust")
Igor Gnatenko951a52b2018-03-12 10:33:33 +0100110 .sort_by(|a, b| a.file_name().cmp(b.file_name()))
David Tolnayee97dbf2017-11-19 14:24:38 -0800111 .into_iter()
112 .filter_entry(common::base_dir_filter)
113 .collect::<Result<Vec<DirEntry>, walkdir::Error>>()
114 .unwrap()
115 .into_par_iter()
David Tolnay51382052017-12-27 13:46:21 -0500116 .for_each(|entry| {
117 let path = entry.path();
118 if path.is_dir() {
119 return;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400120 }
David Tolnay51382052017-12-27 13:46:21 -0500121
122 // Our version of `libsyntax` can't parse this tests
David Tolnay65fb5662018-05-20 20:02:28 -0700123 if path
124 .to_str()
David Tolnay51382052017-12-27 13:46:21 -0500125 .unwrap()
126 .ends_with("optional_comma_in_match_arm.rs")
127 {
128 return;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400129 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400130
David Tolnay51382052017-12-27 13:46:21 -0500131 let mut file = File::open(path).unwrap();
132 let mut content = String::new();
133 file.read_to_string(&mut content).unwrap();
David Tolnayd1c31cc2018-08-24 14:47:15 -0400134 let content = edition_regex.replace_all(&content, "_$0");
Michael Layzell53fc31a2017-06-07 09:21:53 -0400135
David Tolnay51382052017-12-27 13:46:21 -0500136 let (l_passed, l_failed) = match syn::parse_file(&content) {
137 Ok(file) => {
138 let exprs = collect_exprs(file);
139 test_expressions(exprs)
140 }
141 Err(msg) => {
142 errorf!("syn failed to parse\n{:?}\n", msg);
143 (0, 1)
144 }
145 };
David Tolnayee97dbf2017-11-19 14:24:38 -0800146
David Tolnay51382052017-12-27 13:46:21 -0500147 errorf!(
148 "=== {}: {} passed | {} failed\n",
149 path.display(),
150 l_passed,
151 l_failed
152 );
153
154 passed.fetch_add(l_passed, Ordering::SeqCst);
155 let prev_failed = failed.fetch_add(l_failed, Ordering::SeqCst);
156
157 if prev_failed + l_failed >= abort_after {
158 process::exit(1);
159 }
160 });
David Tolnayee97dbf2017-11-19 14:24:38 -0800161
162 let passed = passed.load(Ordering::SeqCst);
163 let failed = failed.load(Ordering::SeqCst);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400164
165 errorf!("\n===== Precedence Test Results =====\n");
166 errorf!("{} passed | {} failed\n", passed, failed);
167
Michael Layzell53fc31a2017-06-07 09:21:53 -0400168 if failed > 0 {
169 panic!("{} failures", failed);
170 }
171}
172
David Tolnayee97dbf2017-11-19 14:24:38 -0800173fn test_expressions(exprs: Vec<syn::Expr>) -> (usize, usize) {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400174 let mut passed = 0;
175 let mut failed = 0;
176
David Tolnayeb7d79b2018-03-31 22:52:17 +0200177 syntax::with_globals(|| {
178 for expr in exprs {
179 let raw = quote!(#expr).to_string();
Michael Layzell53fc31a2017-06-07 09:21:53 -0400180
David Tolnayeb7d79b2018-03-31 22:52:17 +0200181 let libsyntax_ast = if let Some(e) = libsyntax_parse_and_rewrite(&raw) {
182 e
183 } else {
184 failed += 1;
185 errorf!("\nFAIL - libsyntax failed to parse raw\n");
186 continue;
187 };
Michael Layzell53fc31a2017-06-07 09:21:53 -0400188
David Tolnayeb7d79b2018-03-31 22:52:17 +0200189 let syn_expr = syn_brackets(expr);
190 let syn_ast = if let Some(e) = parse::libsyntax_expr(&quote!(#syn_expr).to_string()) {
191 e
192 } else {
193 failed += 1;
194 errorf!("\nFAIL - libsyntax failed to parse bracketed\n");
195 continue;
196 };
Michael Layzell53fc31a2017-06-07 09:21:53 -0400197
David Tolnayecd024d2018-07-21 09:07:56 -0700198 if SpanlessEq::eq(&syn_ast, &libsyntax_ast) {
David Tolnayeb7d79b2018-03-31 22:52:17 +0200199 passed += 1;
200 } else {
201 failed += 1;
202 errorf!("\nFAIL\n{:?}\n!=\n{:?}\n", syn_ast, libsyntax_ast);
203 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400204 }
David Tolnay5d1a3ee2018-03-17 19:41:36 -0700205 });
Michael Layzell53fc31a2017-06-07 09:21:53 -0400206
207 (passed, failed)
208}
209
David Tolnaycfa5cc02017-11-13 01:05:11 -0800210fn libsyntax_parse_and_rewrite(input: &str) -> Option<P<ast::Expr>> {
David Tolnay3cede942017-12-26 12:29:24 -0500211 parse::libsyntax_expr(input).and_then(libsyntax_brackets)
Michael Layzell53fc31a2017-06-07 09:21:53 -0400212}
213
214/// Wrap every expression which is not already wrapped in parens with parens, to
David Tolnay0ccb6d12018-08-14 22:43:00 -0700215/// reveal the precidence of the parsed expressions, and produce a stringified
216/// form of the resulting expression.
Michael Layzell53fc31a2017-06-07 09:21:53 -0400217///
David Tolnaycfa5cc02017-11-13 01:05:11 -0800218/// This method operates on libsyntax objects.
219fn libsyntax_brackets(libsyntax_expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
David Tolnayc8659922018-08-14 22:40:50 -0700220 use rustc_data_structures::thin_vec::ThinVec;
David Tolnay0eab7d92018-09-26 22:10:40 -0700221 use smallvec::SmallVec;
David Tolnay51382052017-12-27 13:46:21 -0500222 use syntax::ast::{Expr, ExprKind, Field, Mac, Pat, Stmt, StmtKind, Ty};
David Tolnayeb7d79b2018-03-31 22:52:17 +0200223 use syntax::ext::quote::rt::DUMMY_SP;
David Tolnaycfa5cc02017-11-13 01:05:11 -0800224 use syntax::fold::{self, Folder};
Michael Layzell53fc31a2017-06-07 09:21:53 -0400225
Michael Layzell53fc31a2017-06-07 09:21:53 -0400226 struct BracketsFolder {
227 failed: bool,
228 };
229 impl Folder for BracketsFolder {
230 fn fold_expr(&mut self, e: P<Expr>) -> P<Expr> {
David Tolnay5d314dc2018-07-21 16:40:01 -0700231 e.map(|e| match e.node {
232 ExprKind::If(..) | ExprKind::Block(..) | ExprKind::IfLet(..) => {
233 fold::noop_fold_expr(e, self)
234 }
235 _ => Expr {
236 id: ast::DUMMY_NODE_ID,
237 node: ExprKind::Paren(P(fold::noop_fold_expr(e, self))),
238 span: DUMMY_SP,
239 attrs: ThinVec::new(),
David Tolnay51382052017-12-27 13:46:21 -0500240 },
Michael Layzell53fc31a2017-06-07 09:21:53 -0400241 })
242 }
243
244 fn fold_field(&mut self, f: Field) -> Field {
245 Field {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400246 expr: if f.is_shorthand {
247 f.expr.map(|e| fold::noop_fold_expr(e, self))
248 } else {
249 self.fold_expr(f.expr)
250 },
David Tolnaya3174992018-04-06 22:41:59 -0700251 ..f
Michael Layzell53fc31a2017-06-07 09:21:53 -0400252 }
253 }
254
255 // We don't want to look at expressions that might appear in patterns or
256 // types yet. We'll look into comparing those in the future. For now
257 // focus on expressions appearing in other places.
258 fn fold_pat(&mut self, pat: P<Pat>) -> P<Pat> {
259 pat
260 }
261
262 fn fold_ty(&mut self, ty: P<Ty>) -> P<Ty> {
263 ty
264 }
265
David Tolnay0eab7d92018-09-26 22:10:40 -0700266 fn fold_stmt(&mut self, stmt: Stmt) -> SmallVec<[Stmt; 1]> {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400267 let node = match stmt.node {
268 // Don't wrap toplevel expressions in statements.
David Tolnay51382052017-12-27 13:46:21 -0500269 StmtKind::Expr(e) => StmtKind::Expr(e.map(|e| fold::noop_fold_expr(e, self))),
270 StmtKind::Semi(e) => StmtKind::Semi(e.map(|e| fold::noop_fold_expr(e, self))),
Michael Layzell53fc31a2017-06-07 09:21:53 -0400271 s => s,
272 };
273
David Tolnay0eab7d92018-09-26 22:10:40 -0700274 smallvec![Stmt { node, ..stmt }]
Michael Layzell53fc31a2017-06-07 09:21:53 -0400275 }
276
277 fn fold_mac(&mut self, mac: Mac) -> Mac {
David Tolnaycfa5cc02017-11-13 01:05:11 -0800278 // By default when folding over macros, libsyntax panics. This is
Michael Layzell53fc31a2017-06-07 09:21:53 -0400279 // because it's usually not what you want, you want to run after
280 // macro expansion. We do want to do that (syn doesn't do macro
281 // expansion), so we implement fold_mac to just return the macro
282 // unchanged.
283 mac
284 }
285 }
286
David Tolnay51382052017-12-27 13:46:21 -0500287 let mut folder = BracketsFolder { failed: false };
David Tolnaycfa5cc02017-11-13 01:05:11 -0800288 let e = folder.fold_expr(libsyntax_expr);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400289 if folder.failed {
290 None
291 } else {
292 Some(e)
293 }
294}
295
296/// Wrap every expression which is not already wrapped in parens with parens, to
David Tolnay0ccb6d12018-08-14 22:43:00 -0700297/// reveal the precedence of the parsed expressions, and produce a stringified
298/// form of the resulting expression.
Michael Layzell53fc31a2017-06-07 09:21:53 -0400299fn syn_brackets(syn_expr: syn::Expr) -> syn::Expr {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400300 use syn::fold::*;
David Tolnayeb7d79b2018-03-31 22:52:17 +0200301 use syn::*;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400302
David Tolnayeb752062018-01-06 13:51:42 -0800303 struct ParenthesizeEveryExpr;
304 impl Fold for ParenthesizeEveryExpr {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400305 fn fold_expr(&mut self, expr: Expr) -> Expr {
David Tolnay8c91b882017-12-28 23:04:32 -0500306 match expr {
307 Expr::Group(_) => unreachable!(),
David Tolnay9c119122018-09-01 18:47:02 -0700308 Expr::If(..) | Expr::Unsafe(..) | Expr::Block(..) | Expr::Let(..) => {
David Tolnay3bc597f2017-12-31 02:31:11 -0500309 fold_expr(self, expr)
Michael Layzell53fc31a2017-06-07 09:21:53 -0400310 }
David Tolnay5d314dc2018-07-21 16:40:01 -0700311 node => Expr::Paren(ExprParen {
312 attrs: Vec::new(),
313 expr: Box::new(fold_expr(self, node)),
314 paren_token: token::Paren::default(),
315 }),
David Tolnay8c91b882017-12-28 23:04:32 -0500316 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400317 }
318
319 fn fold_stmt(&mut self, stmt: Stmt) -> Stmt {
320 match stmt {
321 // Don't wrap toplevel expressions in statements.
David Tolnay1f0b7b82018-01-06 16:07:14 -0800322 Stmt::Expr(e) => Stmt::Expr(fold_expr(self, e)),
323 Stmt::Semi(e, semi) => Stmt::Semi(fold_expr(self, e), semi),
Michael Layzell53fc31a2017-06-07 09:21:53 -0400324 s => s,
325 }
326 }
327
328 // We don't want to look at expressions that might appear in patterns or
329 // types yet. We'll look into comparing those in the future. For now
330 // focus on expressions appearing in other places.
331 fn fold_pat(&mut self, pat: Pat) -> Pat {
332 pat
333 }
334
David Tolnayfd6bf5c2017-11-12 09:41:14 -0800335 fn fold_type(&mut self, ty: Type) -> Type {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400336 ty
337 }
338 }
339
David Tolnayeb752062018-01-06 13:51:42 -0800340 let mut folder = ParenthesizeEveryExpr;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400341 folder.fold_expr(syn_expr)
342}
343
344/// Walk through a crate collecting all expressions we can find in it.
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700345fn collect_exprs(file: syn::File) -> Vec<syn::Expr> {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400346 use syn::fold::*;
David Tolnayf2cfd722017-12-31 18:02:51 -0500347 use syn::punctuated::Punctuated;
David Tolnayeb7d79b2018-03-31 22:52:17 +0200348 use syn::*;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400349
David Tolnayeb752062018-01-06 13:51:42 -0800350 struct CollectExprs(Vec<Expr>);
351 impl Fold for CollectExprs {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400352 fn fold_expr(&mut self, expr: Expr) -> Expr {
353 self.0.push(expr);
354
David Tolnay8c91b882017-12-28 23:04:32 -0500355 Expr::Tuple(ExprTuple {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400356 attrs: vec![],
David Tolnayf2cfd722017-12-31 18:02:51 -0500357 elems: Punctuated::new(),
David Tolnay8c91b882017-12-28 23:04:32 -0500358 paren_token: token::Paren::default(),
359 })
Michael Layzell53fc31a2017-06-07 09:21:53 -0400360 }
361 }
362
David Tolnayeb752062018-01-06 13:51:42 -0800363 let mut folder = CollectExprs(vec![]);
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700364 folder.fold_file(file);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400365 folder.0
366}