blob: 90c48e8fe39a9a44e5c27d20ec3c014b81693fbe [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;
Michael Layzell53fc31a2017-06-07 09:21:53 -040030extern crate syn;
David Tolnaycfa5cc02017-11-13 01:05:11 -080031extern crate syntax;
Michael Layzell53fc31a2017-06-07 09:21:53 -040032extern crate walkdir;
Michael Layzell53fc31a2017-06-07 09:21:53 -040033
David Tolnay51382052017-12-27 13:46:21 -050034use rayon::iter::{IntoParallelIterator, ParallelIterator};
David Tolnayd1c31cc2018-08-24 14:47:15 -040035use regex::Regex;
David Tolnaycfa5cc02017-11-13 01:05:11 -080036use syntax::ast;
37use syntax::ptr::P;
Igor Gnatenko951a52b2018-03-12 10:33:33 +010038use walkdir::{DirEntry, WalkDir};
David Tolnayee97dbf2017-11-19 14:24:38 -080039
40use std::fs::File;
41use std::io::Read;
David Tolnay3eaf7d82017-12-17 23:14:52 -080042use std::process;
David Tolnayee97dbf2017-11-19 14:24:38 -080043use std::sync::atomic::{AtomicUsize, Ordering};
Michael Layzell53fc31a2017-06-07 09:21:53 -040044
David Tolnayecd024d2018-07-21 09:07:56 -070045use common::eq::SpanlessEq;
46use common::parse;
Michael Layzell53fc31a2017-06-07 09:21:53 -040047
Michael Layzell53fc31a2017-06-07 09:21:53 -040048#[macro_use]
David Tolnaydd125562017-12-31 02:16:22 -050049mod macros;
50
51#[allow(dead_code)]
Michael Layzell53fc31a2017-06-07 09:21:53 -040052mod common;
53
54/// Test some pre-set expressions chosen by us.
55#[test]
56fn test_simple_precedence() {
57 const EXPRS: &[&str] = &[
58 "1 + 2 * 3 + 4",
59 "1 + 2 * ( 3 + 4 )",
60 "{ for i in r { } *some_ptr += 1; }",
61 "{ loop { break 5; } }",
62 "{ if true { () }.mthd() }",
Nika Layzell3aa0dc72017-12-04 13:41:28 -050063 "{ for i in unsafe { 20 } { } }",
Michael Layzell53fc31a2017-06-07 09:21:53 -040064 ];
65
66 let mut failed = 0;
67
68 for input in EXPRS {
69 let expr = if let Some(expr) = parse::syn_expr(input) {
70 expr
71 } else {
72 failed += 1;
73 continue;
74 };
75
76 let pf = match test_expressions(vec![expr]) {
77 (1, 0) => "passed",
78 (0, 1) => {
79 failed += 1;
80 "failed"
81 }
82 _ => unreachable!(),
83 };
84 errorf!("=== {}: {}\n", input, pf);
85 }
86
87 if failed > 0 {
88 panic!("Failed {} tests", failed);
89 }
90}
91
92/// Test expressions from rustc, like in `test_round_trip`.
93#[test]
94fn test_rustc_precedence() {
Alex Crichton86374772017-07-07 20:39:28 -070095 common::clone_rust();
Michael Layzell53fc31a2017-06-07 09:21:53 -040096 let abort_after = common::abort_after();
97 if abort_after == 0 {
98 panic!("Skipping all precedence tests");
99 }
100
David Tolnayee97dbf2017-11-19 14:24:38 -0800101 let passed = AtomicUsize::new(0);
102 let failed = AtomicUsize::new(0);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400103
David Tolnayd1c31cc2018-08-24 14:47:15 -0400104 // 2018 edition is hard
105 let edition_regex = Regex::new(r"\b(async|try)[!(]").unwrap();
106
David Tolnayee97dbf2017-11-19 14:24:38 -0800107 WalkDir::new("tests/rust")
Igor Gnatenko951a52b2018-03-12 10:33:33 +0100108 .sort_by(|a, b| a.file_name().cmp(b.file_name()))
David Tolnayee97dbf2017-11-19 14:24:38 -0800109 .into_iter()
110 .filter_entry(common::base_dir_filter)
111 .collect::<Result<Vec<DirEntry>, walkdir::Error>>()
112 .unwrap()
113 .into_par_iter()
David Tolnay51382052017-12-27 13:46:21 -0500114 .for_each(|entry| {
115 let path = entry.path();
116 if path.is_dir() {
117 return;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400118 }
David Tolnay51382052017-12-27 13:46:21 -0500119
120 // Our version of `libsyntax` can't parse this tests
David Tolnay65fb5662018-05-20 20:02:28 -0700121 if path
122 .to_str()
David Tolnay51382052017-12-27 13:46:21 -0500123 .unwrap()
124 .ends_with("optional_comma_in_match_arm.rs")
125 {
126 return;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400127 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400128
David Tolnay51382052017-12-27 13:46:21 -0500129 let mut file = File::open(path).unwrap();
130 let mut content = String::new();
131 file.read_to_string(&mut content).unwrap();
David Tolnayd1c31cc2018-08-24 14:47:15 -0400132 let content = edition_regex.replace_all(&content, "_$0");
Michael Layzell53fc31a2017-06-07 09:21:53 -0400133
David Tolnay51382052017-12-27 13:46:21 -0500134 let (l_passed, l_failed) = match syn::parse_file(&content) {
135 Ok(file) => {
136 let exprs = collect_exprs(file);
137 test_expressions(exprs)
138 }
139 Err(msg) => {
140 errorf!("syn failed to parse\n{:?}\n", msg);
141 (0, 1)
142 }
143 };
David Tolnayee97dbf2017-11-19 14:24:38 -0800144
David Tolnay51382052017-12-27 13:46:21 -0500145 errorf!(
146 "=== {}: {} passed | {} failed\n",
147 path.display(),
148 l_passed,
149 l_failed
150 );
151
152 passed.fetch_add(l_passed, Ordering::SeqCst);
153 let prev_failed = failed.fetch_add(l_failed, Ordering::SeqCst);
154
155 if prev_failed + l_failed >= abort_after {
156 process::exit(1);
157 }
158 });
David Tolnayee97dbf2017-11-19 14:24:38 -0800159
160 let passed = passed.load(Ordering::SeqCst);
161 let failed = failed.load(Ordering::SeqCst);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400162
163 errorf!("\n===== Precedence Test Results =====\n");
164 errorf!("{} passed | {} failed\n", passed, failed);
165
Michael Layzell53fc31a2017-06-07 09:21:53 -0400166 if failed > 0 {
167 panic!("{} failures", failed);
168 }
169}
170
David Tolnayee97dbf2017-11-19 14:24:38 -0800171fn test_expressions(exprs: Vec<syn::Expr>) -> (usize, usize) {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400172 let mut passed = 0;
173 let mut failed = 0;
174
David Tolnayeb7d79b2018-03-31 22:52:17 +0200175 syntax::with_globals(|| {
176 for expr in exprs {
177 let raw = quote!(#expr).to_string();
Michael Layzell53fc31a2017-06-07 09:21:53 -0400178
David Tolnayeb7d79b2018-03-31 22:52:17 +0200179 let libsyntax_ast = if let Some(e) = libsyntax_parse_and_rewrite(&raw) {
180 e
181 } else {
182 failed += 1;
183 errorf!("\nFAIL - libsyntax failed to parse raw\n");
184 continue;
185 };
Michael Layzell53fc31a2017-06-07 09:21:53 -0400186
David Tolnayeb7d79b2018-03-31 22:52:17 +0200187 let syn_expr = syn_brackets(expr);
188 let syn_ast = if let Some(e) = parse::libsyntax_expr(&quote!(#syn_expr).to_string()) {
189 e
190 } else {
191 failed += 1;
192 errorf!("\nFAIL - libsyntax failed to parse bracketed\n");
193 continue;
194 };
Michael Layzell53fc31a2017-06-07 09:21:53 -0400195
David Tolnayecd024d2018-07-21 09:07:56 -0700196 if SpanlessEq::eq(&syn_ast, &libsyntax_ast) {
David Tolnayeb7d79b2018-03-31 22:52:17 +0200197 passed += 1;
198 } else {
199 failed += 1;
200 errorf!("\nFAIL\n{:?}\n!=\n{:?}\n", syn_ast, libsyntax_ast);
201 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400202 }
David Tolnay5d1a3ee2018-03-17 19:41:36 -0700203 });
Michael Layzell53fc31a2017-06-07 09:21:53 -0400204
205 (passed, failed)
206}
207
David Tolnaycfa5cc02017-11-13 01:05:11 -0800208fn libsyntax_parse_and_rewrite(input: &str) -> Option<P<ast::Expr>> {
David Tolnay3cede942017-12-26 12:29:24 -0500209 parse::libsyntax_expr(input).and_then(libsyntax_brackets)
Michael Layzell53fc31a2017-06-07 09:21:53 -0400210}
211
212/// Wrap every expression which is not already wrapped in parens with parens, to
David Tolnay0ccb6d12018-08-14 22:43:00 -0700213/// reveal the precidence of the parsed expressions, and produce a stringified
214/// form of the resulting expression.
Michael Layzell53fc31a2017-06-07 09:21:53 -0400215///
David Tolnaycfa5cc02017-11-13 01:05:11 -0800216/// This method operates on libsyntax objects.
217fn libsyntax_brackets(libsyntax_expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
David Tolnayc8659922018-08-14 22:40:50 -0700218 use rustc_data_structures::small_vec::OneVector;
219 use rustc_data_structures::thin_vec::ThinVec;
David Tolnay51382052017-12-27 13:46:21 -0500220 use syntax::ast::{Expr, ExprKind, Field, Mac, Pat, Stmt, StmtKind, Ty};
David Tolnayeb7d79b2018-03-31 22:52:17 +0200221 use syntax::ext::quote::rt::DUMMY_SP;
David Tolnaycfa5cc02017-11-13 01:05:11 -0800222 use syntax::fold::{self, Folder};
Michael Layzell53fc31a2017-06-07 09:21:53 -0400223
Michael Layzell53fc31a2017-06-07 09:21:53 -0400224 struct BracketsFolder {
225 failed: bool,
226 };
227 impl Folder for BracketsFolder {
228 fn fold_expr(&mut self, e: P<Expr>) -> P<Expr> {
David Tolnay5d314dc2018-07-21 16:40:01 -0700229 e.map(|e| match e.node {
230 ExprKind::If(..) | ExprKind::Block(..) | ExprKind::IfLet(..) => {
231 fold::noop_fold_expr(e, self)
232 }
233 _ => Expr {
234 id: ast::DUMMY_NODE_ID,
235 node: ExprKind::Paren(P(fold::noop_fold_expr(e, self))),
236 span: DUMMY_SP,
237 attrs: ThinVec::new(),
David Tolnay51382052017-12-27 13:46:21 -0500238 },
Michael Layzell53fc31a2017-06-07 09:21:53 -0400239 })
240 }
241
242 fn fold_field(&mut self, f: Field) -> Field {
243 Field {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400244 expr: if f.is_shorthand {
245 f.expr.map(|e| fold::noop_fold_expr(e, self))
246 } else {
247 self.fold_expr(f.expr)
248 },
David Tolnaya3174992018-04-06 22:41:59 -0700249 ..f
Michael Layzell53fc31a2017-06-07 09:21:53 -0400250 }
251 }
252
253 // We don't want to look at expressions that might appear in patterns or
254 // types yet. We'll look into comparing those in the future. For now
255 // focus on expressions appearing in other places.
256 fn fold_pat(&mut self, pat: P<Pat>) -> P<Pat> {
257 pat
258 }
259
260 fn fold_ty(&mut self, ty: P<Ty>) -> P<Ty> {
261 ty
262 }
263
David Tolnayc8659922018-08-14 22:40:50 -0700264 fn fold_stmt(&mut self, stmt: Stmt) -> OneVector<Stmt> {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400265 let node = match stmt.node {
266 // Don't wrap toplevel expressions in statements.
David Tolnay51382052017-12-27 13:46:21 -0500267 StmtKind::Expr(e) => StmtKind::Expr(e.map(|e| fold::noop_fold_expr(e, self))),
268 StmtKind::Semi(e) => StmtKind::Semi(e.map(|e| fold::noop_fold_expr(e, self))),
Michael Layzell53fc31a2017-06-07 09:21:53 -0400269 s => s,
270 };
271
David Tolnayd1c31cc2018-08-24 14:47:15 -0400272 OneVector::from_vec(vec![Stmt { node, ..stmt }])
Michael Layzell53fc31a2017-06-07 09:21:53 -0400273 }
274
275 fn fold_mac(&mut self, mac: Mac) -> Mac {
David Tolnaycfa5cc02017-11-13 01:05:11 -0800276 // By default when folding over macros, libsyntax panics. This is
Michael Layzell53fc31a2017-06-07 09:21:53 -0400277 // because it's usually not what you want, you want to run after
278 // macro expansion. We do want to do that (syn doesn't do macro
279 // expansion), so we implement fold_mac to just return the macro
280 // unchanged.
281 mac
282 }
283 }
284
David Tolnay51382052017-12-27 13:46:21 -0500285 let mut folder = BracketsFolder { failed: false };
David Tolnaycfa5cc02017-11-13 01:05:11 -0800286 let e = folder.fold_expr(libsyntax_expr);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400287 if folder.failed {
288 None
289 } else {
290 Some(e)
291 }
292}
293
294/// Wrap every expression which is not already wrapped in parens with parens, to
David Tolnay0ccb6d12018-08-14 22:43:00 -0700295/// reveal the precedence of the parsed expressions, and produce a stringified
296/// form of the resulting expression.
Michael Layzell53fc31a2017-06-07 09:21:53 -0400297fn syn_brackets(syn_expr: syn::Expr) -> syn::Expr {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400298 use syn::fold::*;
David Tolnayeb7d79b2018-03-31 22:52:17 +0200299 use syn::*;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400300
David Tolnayeb752062018-01-06 13:51:42 -0800301 struct ParenthesizeEveryExpr;
302 impl Fold for ParenthesizeEveryExpr {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400303 fn fold_expr(&mut self, expr: Expr) -> Expr {
David Tolnay8c91b882017-12-28 23:04:32 -0500304 match expr {
305 Expr::Group(_) => unreachable!(),
David Tolnay9c119122018-09-01 18:47:02 -0700306 Expr::If(..) | Expr::Unsafe(..) | Expr::Block(..) | Expr::Let(..) => {
David Tolnay3bc597f2017-12-31 02:31:11 -0500307 fold_expr(self, expr)
Michael Layzell53fc31a2017-06-07 09:21:53 -0400308 }
David Tolnay5d314dc2018-07-21 16:40:01 -0700309 node => Expr::Paren(ExprParen {
310 attrs: Vec::new(),
311 expr: Box::new(fold_expr(self, node)),
312 paren_token: token::Paren::default(),
313 }),
David Tolnay8c91b882017-12-28 23:04:32 -0500314 }
Michael Layzell53fc31a2017-06-07 09:21:53 -0400315 }
316
317 fn fold_stmt(&mut self, stmt: Stmt) -> Stmt {
318 match stmt {
319 // Don't wrap toplevel expressions in statements.
David Tolnay1f0b7b82018-01-06 16:07:14 -0800320 Stmt::Expr(e) => Stmt::Expr(fold_expr(self, e)),
321 Stmt::Semi(e, semi) => Stmt::Semi(fold_expr(self, e), semi),
Michael Layzell53fc31a2017-06-07 09:21:53 -0400322 s => s,
323 }
324 }
325
326 // We don't want to look at expressions that might appear in patterns or
327 // types yet. We'll look into comparing those in the future. For now
328 // focus on expressions appearing in other places.
329 fn fold_pat(&mut self, pat: Pat) -> Pat {
330 pat
331 }
332
David Tolnayfd6bf5c2017-11-12 09:41:14 -0800333 fn fold_type(&mut self, ty: Type) -> Type {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400334 ty
335 }
336 }
337
David Tolnayeb752062018-01-06 13:51:42 -0800338 let mut folder = ParenthesizeEveryExpr;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400339 folder.fold_expr(syn_expr)
340}
341
342/// Walk through a crate collecting all expressions we can find in it.
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700343fn collect_exprs(file: syn::File) -> Vec<syn::Expr> {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400344 use syn::fold::*;
David Tolnayf2cfd722017-12-31 18:02:51 -0500345 use syn::punctuated::Punctuated;
David Tolnayeb7d79b2018-03-31 22:52:17 +0200346 use syn::*;
Michael Layzell53fc31a2017-06-07 09:21:53 -0400347
David Tolnayeb752062018-01-06 13:51:42 -0800348 struct CollectExprs(Vec<Expr>);
349 impl Fold for CollectExprs {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400350 fn fold_expr(&mut self, expr: Expr) -> Expr {
351 self.0.push(expr);
352
David Tolnay8c91b882017-12-28 23:04:32 -0500353 Expr::Tuple(ExprTuple {
Michael Layzell53fc31a2017-06-07 09:21:53 -0400354 attrs: vec![],
David Tolnayf2cfd722017-12-31 18:02:51 -0500355 elems: Punctuated::new(),
David Tolnay8c91b882017-12-28 23:04:32 -0500356 paren_token: token::Paren::default(),
357 })
Michael Layzell53fc31a2017-06-07 09:21:53 -0400358 }
359 }
360
David Tolnayeb752062018-01-06 13:51:42 -0800361 let mut folder = CollectExprs(vec![]);
David Tolnayc7a5d3d2017-06-04 12:11:05 -0700362 folder.fold_file(file);
Michael Layzell53fc31a2017-06-07 09:21:53 -0400363 folder.0
364}