]> git.lizzy.rs Git - rust.git/blob - src/bin/miri-rustc-tests.rs
Rustup
[rust.git] / src / bin / miri-rustc-tests.rs
1 #![feature(rustc_private)]
2
3 extern crate rustc_middle;
4 extern crate rustc_driver;
5 extern crate rustc_hir;
6 extern crate rustc_interface;
7 extern crate rustc_span;
8
9 use std::io;
10 use std::io::Write;
11 use std::path::Path;
12 use std::sync::{Arc, Mutex};
13
14 use rustc_middle::ty::TyCtxt;
15 use rustc_driver::Compilation;
16 use rustc_hir as hir;
17 use rustc_hir::def_id::LOCAL_CRATE;
18 use rustc_hir::itemlikevisit;
19 use rustc_interface::{interface, Queries};
20
21 struct MiriCompilerCalls {
22     /// whether we are building for the host
23     host_target: bool,
24 }
25
26 impl rustc_driver::Callbacks for MiriCompilerCalls {
27     fn after_analysis<'tcx>(
28         &mut self,
29         compiler: &interface::Compiler,
30         queries: &'tcx Queries<'tcx>,
31     ) -> Compilation {
32         compiler.session().abort_if_errors();
33         queries.global_ctxt().unwrap().peek_mut().enter(|tcx| {
34             if std::env::args().any(|arg| arg == "--test") {
35                 struct Visitor<'tcx>(TyCtxt<'tcx>);
36                 impl<'tcx, 'hir> itemlikevisit::ItemLikeVisitor<'hir> for Visitor<'tcx> {
37                     fn visit_item(&mut self, i: &'hir hir::Item) {
38                         if let hir::ItemKind::Fn(.., body_id) = i.kind {
39                             if i.attrs
40                                 .iter()
41                                 .any(|attr| self.0.sess.check_name(attr, rustc_span::symbol::sym::test))
42                             {
43                                 let config = miri::MiriConfig::default();
44                                 let did = self.0.hir().body_owner_def_id(body_id).to_def_id();
45                                 println!("running test: {}", self.0.def_path_debug_str(did));
46                                 miri::eval_main(self.0, did, config);
47                                 self.0.sess.abort_if_errors();
48                             }
49                         }
50                     }
51                     fn visit_trait_item(&mut self, _trait_item: &'hir hir::TraitItem) {}
52                     fn visit_impl_item(&mut self, _impl_item: &'hir hir::ImplItem) {}
53                 }
54                 tcx.hir().krate().visit_all_item_likes(&mut Visitor(tcx));
55             } else if let Some((entry_def_id, _)) = tcx.entry_fn(LOCAL_CRATE) {
56                 let config = miri::MiriConfig::default();
57                 miri::eval_main(tcx, entry_def_id.to_def_id(), config);
58
59                 compiler.session().abort_if_errors();
60             } else {
61                 println!("no main function found, assuming auxiliary build");
62             }
63         });
64
65         // Continue execution on host target
66         if self.host_target { Compilation::Continue } else { Compilation::Stop }
67     }
68 }
69
70 fn main() {
71     let path = option_env!("MIRI_RUSTC_TEST").map(String::from).unwrap_or_else(|| {
72         std::env::var("MIRI_RUSTC_TEST")
73             .expect("need to set MIRI_RUSTC_TEST to path of rustc tests")
74     });
75
76     let mut mir_not_found = Vec::new();
77     let mut crate_not_found = Vec::new();
78     let mut success = 0;
79     let mut failed = Vec::new();
80     let mut c_abi_fns = Vec::new();
81     let mut abi = Vec::new();
82     let mut unsupported = Vec::new();
83     let mut unimplemented_intrinsic = Vec::new();
84     let mut limits = Vec::new();
85     let mut files: Vec<_> = std::fs::read_dir(path).unwrap().collect();
86     while let Some(file) = files.pop() {
87         let file = file.unwrap();
88         let path = file.path();
89         if file.metadata().unwrap().is_dir() {
90             if !path.to_str().unwrap().ends_with("auxiliary") {
91                 // add subdirs recursively
92                 files.extend(std::fs::read_dir(path).unwrap());
93             }
94             continue;
95         }
96         if !file.metadata().unwrap().is_file() || !path.to_str().unwrap().ends_with(".rs") {
97             continue;
98         }
99         let stderr = std::io::stderr();
100         write!(stderr.lock(), "test [miri-pass] {} ... ", path.display()).unwrap();
101         let mut host_target = false;
102         let mut args: Vec<String> = std::env::args()
103             .filter(|arg| {
104                 if arg == "--miri_host_target" {
105                     host_target = true;
106                     false // remove the flag, rustc doesn't know it
107                 } else {
108                     true
109                 }
110             })
111             .collect();
112         args.splice(1..1, miri::miri_default_args().iter().map(ToString::to_string));
113         // file to process
114         args.push(path.display().to_string());
115
116         let sysroot_flag = String::from("--sysroot");
117         if !args.contains(&sysroot_flag) {
118             args.push(sysroot_flag);
119             args.push(
120                 Path::new(&std::env::var("HOME").unwrap())
121                     .join(".xargo")
122                     .join("HOST")
123                     .display()
124                     .to_string(),
125             );
126         }
127
128         // A threadsafe buffer for writing.
129         #[derive(Default, Clone)]
130         struct BufWriter(Arc<Mutex<Vec<u8>>>);
131
132         impl Write for BufWriter {
133             fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
134                 self.0.lock().unwrap().write(buf)
135             }
136             fn flush(&mut self) -> io::Result<()> {
137                 self.0.lock().unwrap().flush()
138             }
139         }
140         let buf = BufWriter::default();
141         let output = buf.clone();
142         let result = std::panic::catch_unwind(|| {
143             let mut callbacks = MiriCompilerCalls { host_target };
144             let mut run = rustc_driver::RunCompiler::new(&args, &mut callbacks);
145             run.set_emitter(Some(Box::new(buf)));
146             let _ = run.run();
147         });
148
149         match result {
150             Ok(()) => {
151                 success += 1;
152                 writeln!(stderr.lock(), "ok").unwrap()
153             }
154             Err(_) => {
155                 let output = output.0.lock().unwrap();
156                 let output_err = std::str::from_utf8(&output).unwrap();
157                 if let Some(text) = output_err.splitn(2, "no mir for `").nth(1) {
158                     let end = text.find('`').unwrap();
159                     mir_not_found.push(text[..end].to_string());
160                     writeln!(stderr.lock(), "NO MIR FOR `{}`", &text[..end]).unwrap();
161                 } else if let Some(text) = output_err.splitn(2, "can't find crate for `").nth(1) {
162                     let end = text.find('`').unwrap();
163                     crate_not_found.push(text[..end].to_string());
164                     writeln!(stderr.lock(), "CAN'T FIND CRATE FOR `{}`", &text[..end]).unwrap();
165                 } else {
166                     for text in output_err.split("error: ").skip(1) {
167                         let end = text.find('\n').unwrap_or(text.len());
168                         let c_abi = "can't call C ABI function: ";
169                         let unimplemented_intrinsic_s = "unimplemented intrinsic: ";
170                         let unsupported_s = "miri does not support ";
171                         let abi_s = "can't handle function with ";
172                         let limit_s = "reached the configured maximum ";
173                         if text.starts_with(c_abi) {
174                             c_abi_fns.push(text[c_abi.len()..end].to_string());
175                         } else if text.starts_with(unimplemented_intrinsic_s) {
176                             unimplemented_intrinsic
177                                 .push(text[unimplemented_intrinsic_s.len()..end].to_string());
178                         } else if text.starts_with(unsupported_s) {
179                             unsupported.push(text[unsupported_s.len()..end].to_string());
180                         } else if text.starts_with(abi_s) {
181                             abi.push(text[abi_s.len()..end].to_string());
182                         } else if text.starts_with(limit_s) {
183                             limits.push(text[limit_s.len()..end].to_string());
184                         } else if text.find("aborting").is_none() {
185                             failed.push(text[..end].to_string());
186                         }
187                     }
188                     writeln!(stderr.lock(), "stderr: \n {}", output_err).unwrap();
189                 }
190             }
191         }
192     }
193     let stderr = std::io::stderr();
194     let mut stderr = stderr.lock();
195     writeln!(
196         stderr,
197         "{} success, {} no mir, {} crate not found, {} failed, {} C fn, {} ABI, {} unsupported, {} intrinsic",
198         success,
199         mir_not_found.len(),
200         crate_not_found.len(),
201         failed.len(),
202         c_abi_fns.len(),
203         abi.len(),
204         unsupported.len(),
205         unimplemented_intrinsic.len()
206     )
207     .unwrap();
208     writeln!(stderr, "# The \"other reasons\" errors").unwrap();
209     writeln!(stderr, "(sorted, deduplicated)").unwrap();
210     print_vec(&mut stderr, failed);
211
212     writeln!(stderr, "# can't call C ABI function").unwrap();
213     print_vec(&mut stderr, c_abi_fns);
214
215     writeln!(stderr, "# unsupported ABI").unwrap();
216     print_vec(&mut stderr, abi);
217
218     writeln!(stderr, "# unsupported").unwrap();
219     print_vec(&mut stderr, unsupported);
220
221     writeln!(stderr, "# unimplemented intrinsics").unwrap();
222     print_vec(&mut stderr, unimplemented_intrinsic);
223
224     writeln!(stderr, "# mir not found").unwrap();
225     print_vec(&mut stderr, mir_not_found);
226
227     writeln!(stderr, "# crate not found").unwrap();
228     print_vec(&mut stderr, crate_not_found);
229 }
230
231 fn print_vec<W: std::io::Write>(stderr: &mut W, v: Vec<String>) {
232     writeln!(stderr, "```").unwrap();
233     for (n, s) in vec_to_hist(v).into_iter().rev() {
234         writeln!(stderr, "{:4} {}", n, s).unwrap();
235     }
236     writeln!(stderr, "```").unwrap();
237 }
238
239 fn vec_to_hist<T: PartialEq + Ord>(mut v: Vec<T>) -> Vec<(usize, T)> {
240     v.sort();
241     let mut v = v.into_iter();
242     let mut result = Vec::new();
243     let mut current = v.next();
244     'outer: while let Some(current_val) = current {
245         let mut n = 1;
246         for next in &mut v {
247             if next == current_val {
248                 n += 1;
249             } else {
250                 result.push((n, current_val));
251                 current = Some(next);
252                 continue 'outer;
253             }
254         }
255         result.push((n, current_val));
256         break;
257     }
258     result.sort();
259     result
260 }