Debian Codegraph @

.cargo/vendor/syn/benches/rust.rs

raw
1 // $ cargo bench --features full,test --bench rust
2 //
3 // Syn only, useful for profiling:
4 // $ RUSTFLAGS='--cfg syn_only' cargo build --release --features full,test --bench rust
5
6 #![cfg_attr(not(syn_only), feature(rustc_private))]
7 #![recursion_limit = "1024"]
8 #![allow(
9 clippy::arc_with_non_send_sync,
10 clippy::cast_lossless,
11 clippy::elidable_lifetime_names,
12 clippy::let_underscore_untyped,
13 clippy::manual_let_else,
14 clippy::match_like_matches_macro,
15 clippy::needless_lifetimes,
16 clippy::uninlined_format_args,
17 clippy::unnecessary_wraps
18 )]
19
20 #[macro_use]
21 #[path = "../tests/macros/mod.rs"]
22 mod macros;
23
24 #[allow(dead_code)]
25 #[path = "../tests/repo/mod.rs"]
26 mod repo;
27
28 use std::fs;
29 use std::path::Path;
30 use std::time::{Duration, Instant};
31
32 #[cfg(not(syn_only))]
33 mod tokenstream_parse {
34 use proc_macro2::TokenStream;
35 use std::path::Path;
36 use std::str::FromStr;
37
38 pub fn bench(_path: &Path, content: &str) -> Result<(), ()> {
39 TokenStream::from_str(content).map(drop).map_err(drop)
40 }
41 }
42
43 mod syn_parse {
44 use std::path::Path;
45
46 pub fn bench(_path: &Path, content: &str) -> Result<(), ()> {
47 syn::parse_file(content).map(drop).map_err(drop)
48 }
49 }
50
51 #[cfg(not(syn_only))]
52 mod librustc_parse {
53 extern crate rustc_data_structures;
54 extern crate rustc_driver;
55 extern crate rustc_error_messages;
56 extern crate rustc_errors;
57 extern crate rustc_parse;
58 extern crate rustc_session;
59 extern crate rustc_span;
60
61 use crate::repo;
62 use rustc_errors::emitter::Emitter;
63 use rustc_errors::registry::Registry;
64 use rustc_errors::translation::Translator;
65 use rustc_errors::{DiagCtxt, DiagInner};
66 use rustc_parse::lexer::StripTokens;
67 use rustc_session::parse::ParseSess;
68 use rustc_span::source_map::{FilePathMapping, SourceMap};
69 use rustc_span::FileName;
70 use std::path::Path;
71 use std::sync::Arc;
72
73 pub fn bench(path: &Path, content: &str) -> Result<(), ()> {
74 struct SilentEmitter;
75
76 impl Emitter for SilentEmitter {
77 fn emit_diagnostic(&mut self, _diag: DiagInner, _registry: &Registry) {}
78 fn source_map(&self) -> Option<&SourceMap> {
79 None
80 }
81 fn translator(&self) -> &Translator {
82 panic!("silent emitter attempted to translate a diagnostic");
83 }
84 }
85
86 let edition = repo::edition(path).parse().unwrap();
87 rustc_span::create_session_if_not_set_then(edition, |_| {
88 let source_map = Arc::new(SourceMap::new(FilePathMapping::empty()));
89 let emitter = Box::new(SilentEmitter);
90 let handler = DiagCtxt::new(emitter);
91 let sess = ParseSess::with_dcx(handler, source_map);
92 let name = FileName::Custom("bench".to_owned());
93 let mut parser = rustc_parse::new_parser_from_source_str(
94 &sess,
95 name,
96 content.to_owned(),
97 StripTokens::ShebangAndFrontmatter,
98 )
99 .unwrap();
100 if let Err(diagnostic) = parser.parse_crate_mod() {
101 diagnostic.cancel();
102 return Err(());
103 }
104 Ok(())
105 })
106 }
107 }
108
109 #[cfg(not(syn_only))]
110 mod read_from_disk {
111 use std::path::Path;
112
113 pub fn bench(_path: &Path, content: &str) -> Result<(), ()> {
114 let _ = content;
115 Ok(())
116 }
117 }
118
119 fn exec(mut codepath: impl FnMut(&Path, &str) -> Result<(), ()>) -> Duration {
120 let begin = Instant::now();
121 let mut success = 0;
122 let mut total = 0;
123
124 ["tests/rust/compiler", "tests/rust/library"]
125 .iter()
126 .flat_map(|dir| {
127 walkdir::WalkDir::new(dir)
128 .into_iter()
129 .filter_entry(repo::base_dir_filter)
130 })
131 .for_each(|entry| {
132 let entry = entry.unwrap();
133 let path = entry.path();
134 if path.is_dir() {
135 return;
136 }
137 let content = fs::read_to_string(path).unwrap();
138 let ok = codepath(path, &content).is_ok();
139 success += ok as usize;
140 total += 1;
141 if !ok {
142 eprintln!("FAIL {}", path.display());
143 }
144 });
145
146 assert_eq!(success, total);
147 begin.elapsed()
148 }
149
150 fn main() {
151 repo::clone_rust();
152
153 macro_rules! testcases {
154 ($($(#[$cfg:meta])* $name:ident,)*) => {
155 [
156 $(
157 $(#[$cfg])*
158 (stringify!($name), $name::bench as fn(&Path, &str) -> Result<(), ()>),
159 )*
160 ]
161 };
162 }
163
164 #[cfg(not(syn_only))]
165 {
166 let mut lines = 0;
167 let mut files = 0;
168 exec(|_path, content| {
169 lines += content.lines().count();
170 files += 1;
171 Ok(())
172 });
173 eprintln!("\n{} lines in {} files", lines, files);
174 }
175
176 for (name, f) in testcases!(
177 #[cfg(not(syn_only))]
178 read_from_disk,
179 #[cfg(not(syn_only))]
180 tokenstream_parse,
181 syn_parse,
182 #[cfg(not(syn_only))]
183 librustc_parse,
184 ) {
185 eprint!("{:20}", format!("{}:", name));
186 let elapsed = exec(f);
187 eprintln!(
188 "elapsed={}.{:03}s",
189 elapsed.as_secs(),
190 elapsed.subsec_millis(),
191 );
192 }
193 eprintln!();
194 }