]> git.lizzy.rs Git - rust.git/blob - src/bin/miri.rs
Address things complained about by clippy
[rust.git] / src / bin / miri.rs
1 #![feature(rustc_private, i128_type)]
2
3 extern crate getopts;
4 extern crate miri;
5 extern crate rustc;
6 extern crate rustc_driver;
7 extern crate rustc_errors;
8 extern crate env_logger;
9 extern crate log_settings;
10 extern crate syntax;
11 extern crate log;
12
13 use rustc::session::Session;
14 use rustc_driver::{Compilation, CompilerCalls, RustcDefaultCalls};
15 use rustc_driver::driver::{CompileState, CompileController};
16 use rustc::session::config::{self, Input, ErrorOutputType};
17 use rustc::hir::{self, itemlikevisit};
18 use rustc::ty::TyCtxt;
19 use syntax::ast::{MetaItemKind, NestedMetaItemKind, self};
20 use std::path::PathBuf;
21
22 struct MiriCompilerCalls(RustcDefaultCalls);
23
24 impl<'a> CompilerCalls<'a> for MiriCompilerCalls {
25     fn early_callback(
26         &mut self,
27         matches: &getopts::Matches,
28         sopts: &config::Options,
29         cfg: &ast::CrateConfig,
30         descriptions: &rustc_errors::registry::Registry,
31         output: ErrorOutputType
32     ) -> Compilation {
33         self.0.early_callback(matches, sopts, cfg, descriptions, output)
34     }
35     fn no_input(
36         &mut self,
37         matches: &getopts::Matches,
38         sopts: &config::Options,
39         cfg: &ast::CrateConfig,
40         odir: &Option<PathBuf>,
41         ofile: &Option<PathBuf>,
42         descriptions: &rustc_errors::registry::Registry
43     ) -> Option<(Input, Option<PathBuf>)> {
44         self.0.no_input(matches, sopts, cfg, odir, ofile, descriptions)
45     }
46     fn late_callback(
47         &mut self,
48         matches: &getopts::Matches,
49         sess: &Session,
50         input: &Input,
51         odir: &Option<PathBuf>,
52         ofile: &Option<PathBuf>
53     ) -> Compilation {
54         self.0.late_callback(matches, sess, input, odir, ofile)
55     }
56     fn build_controller(&mut self, sess: &Session, matches: &getopts::Matches) -> CompileController<'a> {
57         let mut control = self.0.build_controller(sess, matches);
58         control.after_hir_lowering.callback = Box::new(after_hir_lowering);
59         control.after_analysis.callback = Box::new(after_analysis);
60         if std::env::var("MIRI_HOST_TARGET") != Ok("yes".to_owned()) {
61             // only fully compile targets on the host
62             control.after_analysis.stop = Compilation::Stop;
63         }
64         control
65     }
66 }
67
68 fn after_hir_lowering(state: &mut CompileState) {
69     let attr = (String::from("miri"), syntax::feature_gate::AttributeType::Whitelisted);
70     state.session.plugin_attributes.borrow_mut().push(attr);
71 }
72
73 fn after_analysis<'a, 'tcx>(state: &mut CompileState<'a, 'tcx>) {
74     state.session.abort_if_errors();
75
76     let tcx = state.tcx.unwrap();
77     let limits = resource_limits_from_attributes(state);
78
79     if std::env::args().any(|arg| arg == "--test") {
80         struct Visitor<'a, 'tcx: 'a>(miri::ResourceLimits, TyCtxt<'a, 'tcx, 'tcx>, &'a CompileState<'a, 'tcx>);
81         impl<'a, 'tcx: 'a, 'hir> itemlikevisit::ItemLikeVisitor<'hir> for Visitor<'a, 'tcx> {
82             fn visit_item(&mut self, i: &'hir hir::Item) {
83                 if let hir::Item_::ItemFn(_, _, _, _, _, body_id) = i.node {
84                     if i.attrs.iter().any(|attr| attr.name().map_or(false, |n| n == "test")) {
85                         let did = self.1.hir.body_owner_def_id(body_id);
86                         println!("running test: {}", self.1.hir.def_path(did).to_string(self.1));
87                         miri::eval_main(self.1, did, self.0);
88                         self.2.session.abort_if_errors();
89                     }
90                 }
91             }
92             fn visit_trait_item(&mut self, _trait_item: &'hir hir::TraitItem) {}
93             fn visit_impl_item(&mut self, _impl_item: &'hir hir::ImplItem) {}
94         }
95         state.hir_crate.unwrap().visit_all_item_likes(&mut Visitor(limits, tcx, state));
96     } else if let Some((entry_node_id, _)) = *state.session.entry_fn.borrow() {
97         let entry_def_id = tcx.hir.local_def_id(entry_node_id);
98         miri::eval_main(tcx, entry_def_id, limits);
99
100         state.session.abort_if_errors();
101     } else {
102         println!("no main function found, assuming auxiliary build");
103     }
104 }
105
106 fn resource_limits_from_attributes(state: &CompileState) -> miri::ResourceLimits {
107     let mut limits = miri::ResourceLimits::default();
108     let krate = state.hir_crate.as_ref().unwrap();
109     let err_msg = "miri attributes need to be in the form `miri(key = value)`";
110     let extract_int = |lit: &syntax::ast::Lit| -> u128 {
111         match lit.node {
112             syntax::ast::LitKind::Int(i, _) => i,
113             _ => state.session.span_fatal(lit.span, "expected an integer literal"),
114         }
115     };
116
117     for attr in krate.attrs.iter().filter(|a| a.name().map_or(false, |n| n == "miri")) {
118         if let Some(items) = attr.meta_item_list() {
119             for item in items {
120                 if let NestedMetaItemKind::MetaItem(ref inner) = item.node {
121                     if let MetaItemKind::NameValue(ref value) = inner.node {
122                         match &inner.name().as_str()[..] {
123                             "memory_size" => limits.memory_size = extract_int(value) as u64,
124                             "step_limit" => limits.step_limit = extract_int(value) as u64,
125                             "stack_limit" => limits.stack_limit = extract_int(value) as usize,
126                             _ => state.session.span_err(item.span, "unknown miri attribute"),
127                         }
128                     } else {
129                         state.session.span_err(inner.span, err_msg);
130                     }
131                 } else {
132                     state.session.span_err(item.span, err_msg);
133                 }
134             }
135         } else {
136             state.session.span_err(attr.span, err_msg);
137         }
138     }
139     limits
140 }
141
142 fn init_logger() {
143     let format = |record: &log::LogRecord| {
144         if record.level() == log::LogLevel::Trace {
145             // prepend spaces to indent the final string
146             let indentation = log_settings::settings().indentation;
147             format!(
148                 "{lvl}:{module}:{indent:<indentation$} {text}",
149                 lvl = record.level(),
150                 module = record.location().module_path(),
151                 indentation = indentation,
152                 indent = "",
153                 text = record.args(),
154             )
155         } else {
156             format!(
157                 "{lvl}:{module}: {text}",
158                 lvl = record.level(),
159                 module = record.location().module_path(),
160                 text = record.args(),
161             )
162         }
163     };
164
165     let mut builder = env_logger::LogBuilder::new();
166     builder.format(format).filter(None, log::LogLevelFilter::Info);
167
168     if std::env::var("MIRI_LOG").is_ok() {
169         builder.parse(&std::env::var("MIRI_LOG").unwrap());
170     }
171
172     builder.init().unwrap();
173 }
174
175 fn find_sysroot() -> String {
176     // Taken from https://github.com/Manishearth/rust-clippy/pull/911.
177     let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
178     let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
179     match (home, toolchain) {
180         (Some(home), Some(toolchain)) => format!("{}/toolchains/{}", home, toolchain),
181         _ => option_env!("RUST_SYSROOT")
182             .expect("need to specify RUST_SYSROOT env var or use rustup or multirust")
183             .to_owned(),
184     }
185 }
186
187 fn main() {
188     init_logger();
189     let mut args: Vec<String> = std::env::args().collect();
190
191     let sysroot_flag = String::from("--sysroot");
192     if !args.contains(&sysroot_flag) {
193         args.push(sysroot_flag);
194         args.push(find_sysroot());
195     }
196     // we run the optimization passes inside miri
197     // if we ran them twice we'd get funny failures due to borrowck ElaborateDrops only working on
198     // unoptimized MIR
199     // FIXME: add an after-mir-passes hook to rustc driver
200     args.push("-Zmir-opt-level=0".to_owned());
201     // for auxilary builds in unit tests
202     args.push("-Zalways-encode-mir".to_owned());
203
204     rustc_driver::run_compiler(&args, &mut MiriCompilerCalls(RustcDefaultCalls), None, None);
205 }