Debian Codegraph @

third_party/rust/syn/tests/test_precedence.rs

raw
1 // This test does the following for every file in the rust-lang/rust repo:
2 //
3 // 1. Parse the file using syn into a syn::File.
4 // 2. Extract every syn::Expr from the file.
5 // 3. Print each expr to a string of source code.
6 // 4. Parse the source code using librustc_parse into a rustc_ast::Expr.
7 // 5. For both the syn::Expr and rustc_ast::Expr, crawl the syntax tree to
8 // insert parentheses surrounding every subexpression.
9 // 6. Serialize the fully parenthesized syn::Expr to a string of source code.
10 // 7. Parse the fully parenthesized source code using librustc_parse.
11 // 8. Compare the rustc_ast::Expr resulting from parenthesizing using rustc data
12 // structures vs syn data structures, ignoring spans. If they agree, rustc's
13 // parser and syn's parser have identical handling of expression precedence.
14
15 #![cfg(not(syn_disable_nightly_tests))]
16 #![cfg(not(miri))]
17 #![recursion_limit = "1024"]
18 #![feature(rustc_private)]
19 #![allow(
20 clippy::blocks_in_conditions,
21 clippy::doc_markdown,
22 clippy::explicit_deref_methods,
23 clippy::let_underscore_untyped,
24 clippy::manual_assert,
25 clippy::manual_let_else,
26 clippy::match_like_matches_macro,
27 clippy::match_wildcard_for_single_variants,
28 clippy::needless_lifetimes,
29 clippy::too_many_lines,
30 clippy::uninlined_format_args
31 )]
32
33 extern crate rustc_ast;
34 extern crate rustc_ast_pretty;
35 extern crate rustc_data_structures;
36 extern crate rustc_driver;
37 extern crate rustc_span;
38 extern crate smallvec;
39 extern crate thin_vec;
40
41 use crate::common::eq::SpanlessEq;
42 use crate::common::parse;
43 use quote::ToTokens;
44 use rustc_ast::ast;
45 use rustc_ast::ptr::P;
46 use rustc_ast_pretty::pprust;
47 use rustc_span::edition::Edition;
48 use std::fs;
49 use std::path::Path;
50 use std::process;
51 use std::sync::atomic::{AtomicUsize, Ordering};
52 use syn::parse::Parser as _;
53
54 #[macro_use]
55 mod macros;
56
57 mod common;
58 mod repo;
59
60 #[path = "../src/scan_expr.rs"]
61 mod scan_expr;
62
63 #[test]
64 fn test_rustc_precedence() {
65 repo::rayon_init();
66 repo::clone_rust();
67 let abort_after = repo::abort_after();
68 if abort_after == 0 {
69 panic!("skipping all precedence tests");
70 }
71
72 let passed = AtomicUsize::new(0);
73 let failed = AtomicUsize::new(0);
74
75 repo::for_each_rust_file(|path| {
76 let content = fs::read_to_string(path).unwrap();
77
78 let (l_passed, l_failed) = match syn::parse_file(&content) {
79 Ok(file) => {
80 let edition = repo::edition(path).parse().unwrap();
81 let exprs = collect_exprs(file);
82 let (l_passed, l_failed) = test_expressions(path, edition, exprs);
83 errorf!(
84 "=== {}: {} passed | {} failed\n",
85 path.display(),
86 l_passed,
87 l_failed,
88 );
89 (l_passed, l_failed)
90 }
91 Err(msg) => {
92 errorf!("\nFAIL {} - syn failed to parse: {}\n", path.display(), msg);
93 (0, 1)
94 }
95 };
96
97 passed.fetch_add(l_passed, Ordering::Relaxed);
98 let prev_failed = failed.fetch_add(l_failed, Ordering::Relaxed);
99
100 if prev_failed + l_failed >= abort_after {
101 process::exit(1);
102 }
103 });
104
105 let passed = passed.into_inner();
106 let failed = failed.into_inner();
107
108 errorf!("\n===== Precedence Test Results =====\n");
109 errorf!("{} passed | {} failed\n", passed, failed);
110
111 if failed > 0 {
112 panic!("{} failures", failed);
113 }
114 }
115
116 fn test_expressions(path: &Path, edition: Edition, exprs: Vec<syn::Expr>) -> (usize, usize) {
117 let mut passed = 0;
118 let mut failed = 0;
119
120 rustc_span::create_session_if_not_set_then(edition, |_| {
121 for expr in exprs {
122 let expr_tokens = expr.to_token_stream();
123 let source_code = expr_tokens.to_string();
124 let librustc_ast = if let Some(e) = librustc_parse_and_rewrite(&source_code) {
125 e
126 } else {
127 failed += 1;
128 errorf!(
129 "\nFAIL {} - librustc failed to parse original\n",
130 path.display(),
131 );
132 continue;
133 };
134
135 let syn_parenthesized_code =
136 syn_parenthesize(expr.clone()).to_token_stream().to_string();
137 let syn_ast = if let Some(e) = parse::librustc_expr(&syn_parenthesized_code) {
138 e
139 } else {
140 failed += 1;
141 errorf!(
142 "\nFAIL {} - librustc failed to parse parenthesized\n",
143 path.display(),
144 );
145 continue;
146 };
147
148 if !SpanlessEq::eq(&syn_ast, &librustc_ast) {
149 failed += 1;
150 let syn_pretty = pprust::expr_to_string(&syn_ast);
151 let librustc_pretty = pprust::expr_to_string(&librustc_ast);
152 errorf!(
153 "\nFAIL {}\n{}\nsyn != rustc\n{}\n",
154 path.display(),
155 syn_pretty,
156 librustc_pretty,
157 );
158 continue;
159 }
160
161 let expr_invisible = make_parens_invisible(expr);
162 let Ok(reparsed_expr_invisible) = syn::parse2(expr_invisible.to_token_stream()) else {
163 failed += 1;
164 errorf!(
165 "\nFAIL {} - syn failed to parse invisible delimiters\n{}\n",
166 path.display(),
167 source_code,
168 );
169 continue;
170 };
171 if expr_invisible != reparsed_expr_invisible {
172 failed += 1;
173 errorf!(
174 "\nFAIL {} - mismatch after parsing invisible delimiters\n{}\n",
175 path.display(),
176 source_code,
177 );
178 continue;
179 }
180
181 if scan_expr::scan_expr.parse2(expr_tokens).is_err() {
182 failed += 1;
183 errorf!(
184 "\nFAIL {} - failed to scan expr\n{}\n",
185 path.display(),
186 source_code,
187 );
188 continue;
189 }
190
191 passed += 1;
192 }
193 });
194
195 (passed, failed)
196 }
197
198 fn librustc_parse_and_rewrite(input: &str) -> Option<P<ast::Expr>> {
199 parse::librustc_expr(input).map(librustc_parenthesize)
200 }
201
202 fn librustc_parenthesize(mut librustc_expr: P<ast::Expr>) -> P<ast::Expr> {
203 use rustc_ast::ast::{
204 AssocItem, AssocItemKind, Attribute, BinOpKind, Block, BoundConstness, Expr, ExprField,
205 ExprKind, GenericArg, GenericBound, Local, LocalKind, Pat, PolyTraitRef, Stmt, StmtKind,
206 StructExpr, StructRest, TraitBoundModifiers, Ty,
207 };
208 use rustc_ast::mut_visit::{walk_flat_map_item, MutVisitor};
209 use rustc_ast::visit::{AssocCtxt, BoundKind};
210 use rustc_data_structures::flat_map_in_place::FlatMapInPlace;
211 use rustc_span::DUMMY_SP;
212 use smallvec::SmallVec;
213 use std::mem;
214 use std::ops::DerefMut;
215 use thin_vec::ThinVec;
216
217 struct FullyParenthesize;
218
219 fn contains_let_chain(expr: &Expr) -> bool {
220 match &expr.kind {
221 ExprKind::Let(..) => true,
222 ExprKind::Binary(binop, left, right) => {
223 binop.node == BinOpKind::And
224 && (contains_let_chain(left) || contains_let_chain(right))
225 }
226 _ => false,
227 }
228 }
229
230 fn flat_map_field<T: MutVisitor>(mut f: ExprField, vis: &mut T) -> Vec<ExprField> {
231 if f.is_shorthand {
232 noop_visit_expr(&mut f.expr, vis);
233 } else {
234 vis.visit_expr(&mut f.expr);
235 }
236 vec![f]
237 }
238
239 fn flat_map_stmt<T: MutVisitor>(stmt: Stmt, vis: &mut T) -> Vec<Stmt> {
240 let kind = match stmt.kind {
241 // Don't wrap toplevel expressions in statements.
242 StmtKind::Expr(mut e) => {
243 noop_visit_expr(&mut e, vis);
244 StmtKind::Expr(e)
245 }
246 StmtKind::Semi(mut e) => {
247 noop_visit_expr(&mut e, vis);
248 StmtKind::Semi(e)
249 }
250 s => s,
251 };
252
253 vec![Stmt { kind, ..stmt }]
254 }
255
256 fn noop_visit_expr<T: MutVisitor>(e: &mut Expr, vis: &mut T) {
257 match &mut e.kind {
258 ExprKind::Become(..) => {}
259 ExprKind::Struct(expr) => {
260 let StructExpr {
261 qself,
262 path,
263 fields,
264 rest,
265 } = expr.deref_mut();
266 vis.visit_qself(qself);
267 vis.visit_path(path);
268 fields.flat_map_in_place(|field| flat_map_field(field, vis));
269 if let StructRest::Base(rest) = rest {
270 vis.visit_expr(rest);
271 }
272 }
273 _ => rustc_ast::mut_visit::walk_expr(vis, e),
274 }
275 }
276
277 impl MutVisitor for FullyParenthesize {
278 fn visit_expr(&mut self, e: &mut P<Expr>) {
279 noop_visit_expr(e, self);
280 match e.kind {
281 ExprKind::Block(..) | ExprKind::If(..) | ExprKind::Let(..) => {}
282 ExprKind::Binary(..) if contains_let_chain(e) => {}
283 _ => {
284 let inner = mem::replace(
285 e,
286 P(Expr {
287 id: ast::DUMMY_NODE_ID,
288 kind: ExprKind::Dummy,
289 span: DUMMY_SP,
290 attrs: ThinVec::new(),
291 tokens: None,
292 }),
293 );
294 e.kind = ExprKind::Paren(inner);
295 }
296 }
297 }
298
299 fn visit_generic_arg(&mut self, arg: &mut GenericArg) {
300 match arg {
301 GenericArg::Lifetime(_lifetime) => {}
302 GenericArg::Type(arg) => self.visit_ty(arg),
303 // Don't wrap unbraced const generic arg as that's invalid syntax.
304 GenericArg::Const(anon_const) => {
305 if let ExprKind::Block(..) = &mut anon_const.value.kind {
306 noop_visit_expr(&mut anon_const.value, self);
307 }
308 }
309 }
310 }
311
312 fn visit_param_bound(&mut self, bound: &mut GenericBound, _ctxt: BoundKind) {
313 match bound {
314 GenericBound::Trait(PolyTraitRef {
315 modifiers:
316 TraitBoundModifiers {
317 constness: BoundConstness::Maybe(_),
318 ..
319 },
320 ..
321 })
322 | GenericBound::Outlives(..)
323 | GenericBound::Use(..) => {}
324 GenericBound::Trait(ty) => self.visit_poly_trait_ref(ty),
325 }
326 }
327
328 fn visit_block(&mut self, block: &mut P<Block>) {
329 self.visit_id(&mut block.id);
330 block
331 .stmts
332 .flat_map_in_place(|stmt| flat_map_stmt(stmt, self));
333 self.visit_span(&mut block.span);
334 }
335
336 fn visit_local(&mut self, local: &mut P<Local>) {
337 match &mut local.kind {
338 LocalKind::Decl => {}
339 LocalKind::Init(init) => {
340 self.visit_expr(init);
341 }
342 LocalKind::InitElse(init, els) => {
343 self.visit_expr(init);
344 self.visit_block(els);
345 }
346 }
347 }
348
349 fn flat_map_assoc_item(
350 &mut self,
351 item: P<AssocItem>,
352 _ctxt: AssocCtxt,
353 ) -> SmallVec<[P<AssocItem>; 1]> {
354 match &item.kind {
355 AssocItemKind::Const(const_item)
356 if !const_item.generics.params.is_empty()
357 || !const_item.generics.where_clause.predicates.is_empty() =>
358 {
359 SmallVec::from([item])
360 }
361 _ => walk_flat_map_item(self, item),
362 }
363 }
364
365 // We don't want to look at expressions that might appear in patterns or
366 // types yet. We'll look into comparing those in the future. For now
367 // focus on expressions appearing in other places.
368 fn visit_pat(&mut self, pat: &mut P<Pat>) {
369 let _ = pat;
370 }
371
372 fn visit_ty(&mut self, ty: &mut P<Ty>) {
373 let _ = ty;
374 }
375
376 fn visit_attribute(&mut self, attr: &mut Attribute) {
377 let _ = attr;
378 }
379 }
380
381 let mut folder = FullyParenthesize;
382 folder.visit_expr(&mut librustc_expr);
383 librustc_expr
384 }
385
386 fn syn_parenthesize(syn_expr: syn::Expr) -> syn::Expr {
387 use syn::fold::{fold_expr, fold_generic_argument, Fold};
388 use syn::{token, BinOp, Expr, ExprParen, GenericArgument, MetaNameValue, Pat, Stmt, Type};
389
390 struct FullyParenthesize;
391
392 fn parenthesize(expr: Expr) -> Expr {
393 Expr::Paren(ExprParen {
394 attrs: Vec::new(),
395 expr: Box::new(expr),
396 paren_token: token::Paren::default(),
397 })
398 }
399
400 fn needs_paren(expr: &Expr) -> bool {
401 match expr {
402 Expr::Group(_) => unreachable!(),
403 Expr::If(_) | Expr::Unsafe(_) | Expr::Block(_) | Expr::Let(_) => false,
404 Expr::Binary(_) => !contains_let_chain(expr),
405 _ => true,
406 }
407 }
408
409 fn contains_let_chain(expr: &Expr) -> bool {
410 match expr {
411 Expr::Let(_) => true,
412 Expr::Binary(expr) => {
413 matches!(expr.op, BinOp::And(_))
414 && (contains_let_chain(&expr.left) || contains_let_chain(&expr.right))
415 }
416 _ => false,
417 }
418 }
419
420 impl Fold for FullyParenthesize {
421 fn fold_expr(&mut self, expr: Expr) -> Expr {
422 let needs_paren = needs_paren(&expr);
423 let folded = fold_expr(self, expr);
424 if needs_paren {
425 parenthesize(folded)
426 } else {
427 folded
428 }
429 }
430
431 fn fold_generic_argument(&mut self, arg: GenericArgument) -> GenericArgument {
432 match arg {
433 GenericArgument::Const(arg) => GenericArgument::Const(match arg {
434 Expr::Block(_) => fold_expr(self, arg),
435 // Don't wrap unbraced const generic arg as that's invalid syntax.
436 _ => arg,
437 }),
438 _ => fold_generic_argument(self, arg),
439 }
440 }
441
442 fn fold_stmt(&mut self, stmt: Stmt) -> Stmt {
443 match stmt {
444 // Don't wrap toplevel expressions in statements.
445 Stmt::Expr(Expr::Verbatim(_), Some(_)) => stmt,
446 Stmt::Expr(e, semi) => Stmt::Expr(fold_expr(self, e), semi),
447 s => s,
448 }
449 }
450
451 fn fold_meta_name_value(&mut self, meta: MetaNameValue) -> MetaNameValue {
452 // Don't turn #[p = "..."] into #[p = ("...")].
453 meta
454 }
455
456 // We don't want to look at expressions that might appear in patterns or
457 // types yet. We'll look into comparing those in the future. For now
458 // focus on expressions appearing in other places.
459 fn fold_pat(&mut self, pat: Pat) -> Pat {
460 pat
461 }
462
463 fn fold_type(&mut self, ty: Type) -> Type {
464 ty
465 }
466 }
467
468 let mut folder = FullyParenthesize;
469 folder.fold_expr(syn_expr)
470 }
471
472 fn make_parens_invisible(expr: syn::Expr) -> syn::Expr {
473 use syn::fold::{fold_expr, fold_stmt, Fold};
474 use syn::{token, Expr, ExprGroup, ExprParen, Stmt};
475
476 struct MakeParensInvisible;
477
478 impl Fold for MakeParensInvisible {
479 fn fold_expr(&mut self, mut expr: Expr) -> Expr {
480 if let Expr::Paren(paren) = expr {
481 expr = Expr::Group(ExprGroup {
482 attrs: paren.attrs,
483 group_token: token::Group(paren.paren_token.span.join()),
484 expr: paren.expr,
485 });
486 }
487 fold_expr(self, expr)
488 }
489
490 fn fold_stmt(&mut self, stmt: Stmt) -> Stmt {
491 if let Stmt::Expr(expr @ (Expr::Binary(_) | Expr::Call(_) | Expr::Cast(_)), None) = stmt
492 {
493 Stmt::Expr(
494 Expr::Paren(ExprParen {
495 attrs: Vec::new(),
496 paren_token: token::Paren::default(),
497 expr: Box::new(fold_expr(self, expr)),
498 }),
499 None,
500 )
501 } else {
502 fold_stmt(self, stmt)
503 }
504 }
505 }
506
507 let mut folder = MakeParensInvisible;
508 folder.fold_expr(expr)
509 }
510
511 /// Walk through a crate collecting all expressions we can find in it.
512 fn collect_exprs(file: syn::File) -> Vec<syn::Expr> {
513 use syn::fold::Fold;
514 use syn::punctuated::Punctuated;
515 use syn::{token, ConstParam, Expr, ExprTuple, Pat, Path};
516
517 struct CollectExprs(Vec<Expr>);
518 impl Fold for CollectExprs {
519 fn fold_expr(&mut self, expr: Expr) -> Expr {
520 match expr {
521 Expr::Verbatim(_) => {}
522 _ => self.0.push(expr),
523 }
524
525 Expr::Tuple(ExprTuple {
526 attrs: vec![],
527 elems: Punctuated::new(),
528 paren_token: token::Paren::default(),
529 })
530 }
531
532 fn fold_pat(&mut self, pat: Pat) -> Pat {
533 pat
534 }
535
536 fn fold_path(&mut self, path: Path) -> Path {
537 // Skip traversing into const generic path arguments
538 path
539 }
540
541 fn fold_const_param(&mut self, const_param: ConstParam) -> ConstParam {
542 const_param
543 }
544 }
545
546 let mut folder = CollectExprs(vec![]);
547 folder.fold_file(file);
548 folder.0
549 }