]> git.lizzy.rs Git - rust.git/blob - src/driver.rs
Merge pull request #3294 from mikerite/fix-3276
[rust.git] / src / driver.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10
11 // error-pattern:yummy
12 #![feature(box_syntax)]
13 #![feature(rustc_private)]
14 #![feature(tool_lints)]
15 #![feature(try_from)]
16 #![allow(unknown_lints, clippy::missing_docs_in_private_items)]
17
18 // FIXME: switch to something more ergonomic here, once available.
19 // (currently there is no way to opt into sysroot crates w/o `extern crate`)
20 #[allow(unused_extern_crates)]
21 extern crate rustc_driver;
22 #[allow(unused_extern_crates)]
23 extern crate rustc_plugin;
24 use self::rustc_driver::{driver::CompileController, Compilation};
25
26 use std::convert::TryInto;
27 use std::path::Path;
28 use std::process::{exit, Command};
29
30 #[allow(clippy::print_stdout)]
31 fn show_version() {
32     println!(env!("CARGO_PKG_VERSION"));
33 }
34
35 pub fn main() {
36     rustc_driver::init_rustc_env_logger();
37     exit(rustc_driver::run(move || {
38         use std::env;
39
40         if std::env::args().any(|a| a == "--version" || a == "-V") {
41             show_version();
42             exit(0);
43         }
44
45         let sys_root = option_env!("SYSROOT")
46             .map(String::from)
47             .or_else(|| std::env::var("SYSROOT").ok())
48             .or_else(|| {
49                 let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
50                 let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
51                 home.and_then(|home| toolchain.map(|toolchain| format!("{}/toolchains/{}", home, toolchain)))
52             })
53             .or_else(|| {
54                 Command::new("rustc")
55                     .arg("--print")
56                     .arg("sysroot")
57                     .output()
58                     .ok()
59                     .and_then(|out| String::from_utf8(out.stdout).ok())
60                     .map(|s| s.trim().to_owned())
61             })
62             .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
63
64         // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
65         // We're invoking the compiler programmatically, so we ignore this/
66         let mut orig_args: Vec<String> = env::args().collect();
67         if orig_args.len() <= 1 {
68             std::process::exit(1);
69         }
70         if Path::new(&orig_args[1]).file_stem() == Some("rustc".as_ref()) {
71             // we still want to be able to invoke it normally though
72             orig_args.remove(1);
73         }
74         // this conditional check for the --sysroot flag is there so users can call
75         // `clippy_driver` directly
76         // without having to pass --sysroot or anything
77         let mut args: Vec<String> = if orig_args.iter().any(|s| s == "--sysroot") {
78             orig_args.clone()
79         } else {
80             orig_args
81                 .clone()
82                 .into_iter()
83                 .chain(Some("--sysroot".to_owned()))
84                 .chain(Some(sys_root))
85                 .collect()
86         };
87
88         // this check ensures that dependencies are built but not linted and the final
89         // crate is
90         // linted but not built
91         let clippy_enabled = env::var("CLIPPY_TESTS").ok().map_or(false, |val| val == "true")
92             || orig_args.iter().any(|s| s == "--emit=dep-info,metadata");
93
94         if clippy_enabled {
95             args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
96             if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
97                 args.extend(
98                     extra_args
99                         .split("__CLIPPY_HACKERY__")
100                         .filter_map(|s| if s.is_empty() {
101                             None
102                         } else {
103                             Some(s.to_string())
104                         })
105                 );
106             }
107         }
108
109         let mut controller = CompileController::basic();
110         if clippy_enabled {
111             controller.after_parse.callback = Box::new(move |state| {
112                 let mut registry = rustc_plugin::registry::Registry::new(
113                     state.session,
114                     state
115                         .krate
116                         .as_ref()
117                         .expect(
118                             "at this compilation stage \
119                             the crate must be parsed",
120                         )
121                         .span,
122                 );
123                 registry.args_hidden = Some(Vec::new());
124
125                 let conf = clippy_lints::read_conf(&registry);
126                 clippy_lints::register_plugins(&mut registry, &conf);
127
128                 let rustc_plugin::registry::Registry {
129                     early_lint_passes,
130                     late_lint_passes,
131                     lint_groups,
132                     llvm_passes,
133                     attributes,
134                     ..
135                 } = registry;
136                 let sess = &state.session;
137                 let mut ls = sess.lint_store.borrow_mut();
138                 for pass in early_lint_passes {
139                     ls.register_early_pass(Some(sess), true, pass);
140                 }
141                 for pass in late_lint_passes {
142                     ls.register_late_pass(Some(sess), true, pass);
143                 }
144
145                 for (name, (to, deprecated_name)) in lint_groups {
146                     ls.register_group(Some(sess), true, name, deprecated_name, to);
147                 }
148                 clippy_lints::register_pre_expansion_lints(sess, &mut ls, &conf);
149
150                 sess.plugin_llvm_passes.borrow_mut().extend(llvm_passes);
151                 sess.plugin_attributes.borrow_mut().extend(attributes);
152             });
153         }
154         controller.compilation_done.stop = Compilation::Stop;
155
156         let args = args;
157         rustc_driver::run_compiler(&args, Box::new(controller), None, None)
158     }).try_into().expect("exit code too large"))
159 }