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