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-2.0.119 / tests / test_round_trip.rs

225 lines · 7140 bytes Raw Blame History
1#![cfg(not(syn_disable_nightly_tests))]
2#![cfg(not(miri))]
3#![recursion_limit = "1024"]
4#![feature(rustc_private)]
5#![allow(
6 clippy::blocks_in_conditions,
7 clippy::elidable_lifetime_names,
8 clippy::manual_assert,
9 clippy::manual_let_else,
10 clippy::match_like_matches_macro,
11 clippy::needless_lifetimes,
12 clippy::uninlined_format_args
13)]
14#![allow(mismatched_lifetime_syntaxes)]
15
16extern crate rustc_ast;
17extern crate rustc_ast_pretty;
18extern crate rustc_data_structures;
19extern crate rustc_driver;
20extern crate rustc_error_messages;
21extern crate rustc_errors;
22extern crate rustc_expand;
23extern crate rustc_parse;
24extern crate rustc_session;
25extern crate rustc_span;
26
27use crate::common::eq::SpanlessEq;
28use quote::quote;
29use rustc_ast::ast::{
30 AngleBracketedArg, Crate, GenericArg, GenericArgs, GenericParamKind, Generics,
31};
32use rustc_ast::mut_visit::{self, MutVisitor};
33use rustc_ast_pretty::pprust;
34use rustc_data_structures::flat_map_in_place::FlatMapInPlace;
35use rustc_error_messages::DiagMessage;
36use rustc_errors::{Diag, PResult};
37use rustc_parse::lexer::StripTokens;
38use rustc_session::parse::ParseSess;
39use rustc_span::FileName;
40use std::borrow::Cow;
41use std::fs;
42use std::panic;
43use std::path::Path;
44use std::process;
45use std::sync::atomic::{AtomicUsize, Ordering};
46use std::time::Instant;
47
48#[macro_use]
49mod macros;
50
51mod common;
52mod repo;
53
54#[test]
55fn test_round_trip() {
56 repo::rayon_init();
57 repo::clone_rust();
58 let abort_after = repo::abort_after();
59 if abort_after == 0 {
60 panic!("skipping all round_trip tests");
61 }
62
63 let failed = AtomicUsize::new(0);
64
65 repo::for_each_rust_file(|path| test(path, &failed, abort_after));
66
67 let failed = failed.into_inner();
68 if failed > 0 {
69 panic!("{} failures", failed);
70 }
71}
72
73fn test(path: &Path, failed: &AtomicUsize, abort_after: usize) {
74 let failed = || {
75 let prev_failed = failed.fetch_add(1, Ordering::Relaxed);
76 if prev_failed + 1 >= abort_after {
77 process::exit(1);
78 }
79 };
80
81 let content = fs::read_to_string(path).unwrap();
82
83 let (back, elapsed) = match panic::catch_unwind(|| {
84 let start = Instant::now();
85 let result = syn::parse_file(&content);
86 let elapsed = start.elapsed();
87 result.map(|krate| (quote!(#krate).to_string(), elapsed))
88 }) {
89 Err(_) => {
90 errorf!("=== {}: syn panic\n", path.display());
91 failed();
92 return;
93 }
94 Ok(Err(msg)) => {
95 errorf!("=== {}: syn failed to parse\n{:?}\n", path.display(), msg);
96 failed();
97 return;
98 }
99 Ok(Ok(result)) => result,
100 };
101
102 let edition = repo::edition(path).parse().unwrap();
103
104 rustc_span::create_session_if_not_set_then(edition, |_| {
105 let equal = match panic::catch_unwind(|| {
106 let sess = ParseSess::new();
107 let before = match librustc_parse(content, &sess) {
108 Ok(before) => before,
109 Err(diagnostic) => {
110 errorf!(
111 "=== {}: ignore - librustc failed to parse original content: {}\n",
112 path.display(),
113 translate_message(&diagnostic),
114 );
115 diagnostic.cancel();
116 return Err(true);
117 }
118 };
119 let after = match librustc_parse(back, &sess) {
120 Ok(after) => after,
121 Err(diagnostic) => {
122 errorf!("=== {}: librustc failed to parse", path.display());
123 diagnostic.emit();
124 return Err(false);
125 }
126 };
127 Ok((before, after))
128 }) {
129 Err(_) => {
130 errorf!("=== {}: ignoring librustc panic\n", path.display());
131 true
132 }
133 Ok(Err(equal)) => equal,
134 Ok(Ok((mut before, mut after))) => {
135 normalize(&mut before);
136 normalize(&mut after);
137 if SpanlessEq::eq(&before, &after) {
138 errorf!(
139 "=== {}: pass in {}ms\n",
140 path.display(),
141 elapsed.as_secs() * 1000 + u64::from(elapsed.subsec_nanos()) / 1_000_000
142 );
143 true
144 } else {
145 errorf!(
146 "=== {}: FAIL\n{}\n!=\n{}\n",
147 path.display(),
148 pprust::crate_to_string_for_macros(&before),
149 pprust::crate_to_string_for_macros(&after),
150 );
151 false
152 }
153 }
154 };
155 if !equal {
156 failed();
157 }
158 });
159}
160
161fn librustc_parse(content: String, sess: &ParseSess) -> PResult<Crate> {
162 static COUNTER: AtomicUsize = AtomicUsize::new(0);
163 let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
164 let name = FileName::Custom(format!("test_round_trip{}", counter));
165 let mut parser = rustc_parse::new_parser_from_source_str(
166 sess,
167 name,
168 content,
169 StripTokens::ShebangAndFrontmatter,
170 )
171 .unwrap();
172 parser.parse_crate_mod()
173}
174
175fn translate_message(diagnostic: &Diag) -> Cow<'static, str> {
176 match &diagnostic.messages[0].0 {
177 DiagMessage::Str(msg) | DiagMessage::Inline(msg) => msg.clone(),
178 }
179}
180
181fn normalize(krate: &mut Crate) {
182 struct NormalizeVisitor;
183
184 impl MutVisitor for NormalizeVisitor {
185 fn visit_generic_args(&mut self, e: &mut GenericArgs) {
186 if let GenericArgs::AngleBracketed(e) = e {
187 #[derive(Ord, PartialOrd, Eq, PartialEq)]
188 enum Group {
189 Lifetimes,
190 TypesAndConsts,
191 Constraints,
192 }
193 e.args.sort_by_key(|arg| match arg {
194 AngleBracketedArg::Arg(arg) => match arg {
195 GenericArg::Lifetime(_) => Group::Lifetimes,
196 GenericArg::Type(_) | GenericArg::Const(_) => Group::TypesAndConsts,
197 },
198 AngleBracketedArg::Constraint(_) => Group::Constraints,
199 });
200 }
201 mut_visit::walk_generic_args(self, e);
202 }
203
204 fn visit_generics(&mut self, e: &mut Generics) {
205 #[derive(Ord, PartialOrd, Eq, PartialEq)]
206 enum Group {
207 Lifetimes,
208 TypesAndConsts,
209 }
210 e.params.sort_by_key(|param| match param.kind {
211 GenericParamKind::Lifetime => Group::Lifetimes,
212 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
213 Group::TypesAndConsts
214 }
215 });
216 e.params
217 .flat_map_in_place(|param| self.flat_map_generic_param(param));
218 if e.where_clause.predicates.is_empty() {
219 e.where_clause.has_where_token = false;
220 }
221 }
222 }
223
224 NormalizeVisitor.visit_crate(krate);
225}