1 #![feature(rustc_private, i128_type)]
6 extern crate rustc_driver;
7 extern crate rustc_errors;
8 extern crate env_logger;
9 extern crate log_settings;
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;
22 struct MiriCompilerCalls(RustcDefaultCalls);
24 impl<'a> CompilerCalls<'a> for MiriCompilerCalls {
27 matches: &getopts::Matches,
28 sopts: &config::Options,
29 cfg: &ast::CrateConfig,
30 descriptions: &rustc_errors::registry::Registry,
31 output: ErrorOutputType
33 self.0.early_callback(matches, sopts, cfg, descriptions, output)
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)
48 matches: &getopts::Matches,
51 odir: &Option<PathBuf>,
52 ofile: &Option<PathBuf>
54 self.0.late_callback(matches, sess, input, odir, ofile)
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;
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);
73 fn after_analysis<'a, 'tcx>(state: &mut CompileState<'a, 'tcx>) {
74 state.session.abort_if_errors();
76 let tcx = state.tcx.unwrap();
77 let limits = resource_limits_from_attributes(state);
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();
92 fn visit_trait_item(&mut self, _trait_item: &'hir hir::TraitItem) {}
93 fn visit_impl_item(&mut self, _impl_item: &'hir hir::ImplItem) {}
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);
100 state.session.abort_if_errors();
102 println!("no main function found, assuming auxiliary build");
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 {
112 syntax::ast::LitKind::Int(i, _) => i,
113 _ => state.session.span_fatal(lit.span, "expected an integer literal"),
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() {
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"),
129 state.session.span_err(inner.span, err_msg);
132 state.session.span_err(item.span, err_msg);
136 state.session.span_err(attr.span, err_msg);
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;
148 "{lvl}:{module}:{indent:<indentation$} {text}",
149 lvl = record.level(),
150 module = record.location().module_path(),
151 indentation = indentation,
153 text = record.args(),
157 "{lvl}:{module}: {text}",
158 lvl = record.level(),
159 module = record.location().module_path(),
160 text = record.args(),
165 let mut builder = env_logger::LogBuilder::new();
166 builder.format(format).filter(None, log::LogLevelFilter::Info);
168 if std::env::var("MIRI_LOG").is_ok() {
169 builder.parse(&std::env::var("MIRI_LOG").unwrap());
172 builder.init().unwrap();
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")
189 let mut args: Vec<String> = std::env::args().collect();
191 let sysroot_flag = String::from("--sysroot");
192 if !args.contains(&sysroot_flag) {
193 args.push(sysroot_flag);
194 args.push(find_sysroot());
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
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());
204 rustc_driver::run_compiler(&args, &mut MiriCompilerCalls(RustcDefaultCalls), None, None);