interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / vendor / syn / tests / test_precedence.rs

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