]> git.lizzy.rs Git - rust.git/blob - src/driver.rs
f4a656722b9d067ef657d23d3029f9701427b0fd
[rust.git] / src / driver.rs
1 #![feature(rustc_private)]
2
3 // FIXME: switch to something more ergonomic here, once available.
4 // (Currently there is no way to opt into sysroot crates without `extern crate`.)
5 #[allow(unused_extern_crates)]
6 extern crate rustc_driver;
7 #[allow(unused_extern_crates)]
8 extern crate rustc_interface;
9 #[allow(unused_extern_crates)]
10 extern crate rustc_plugin;
11
12 use rustc_interface::interface;
13 use rustc_tools_util::*;
14
15 use std::path::Path;
16 use std::process::{exit, Command};
17
18 /// If a command-line option matches `find_arg`, then apply the predicate `pred` on its value. If
19 /// true, then return it. The parameter is assumed to be either `--arg=value` or `--arg value`.
20 fn arg_value<'a>(
21     args: impl IntoIterator<Item = &'a String>,
22     find_arg: &str,
23     pred: impl Fn(&str) -> bool,
24 ) -> Option<&'a str> {
25     let mut args = args.into_iter().map(String::as_str);
26
27     while let Some(arg) = args.next() {
28         let arg: Vec<_> = arg.splitn(2, '=').collect();
29         if arg.get(0) != Some(&find_arg) {
30             continue;
31         }
32
33         let value = arg.get(1).cloned().or_else(|| args.next());
34         if value.as_ref().map_or(false, |p| pred(p)) {
35             return value;
36         }
37     }
38     None
39 }
40
41 #[test]
42 fn test_arg_value() {
43     let args: Vec<_> = ["--bar=bar", "--foobar", "123", "--foo"]
44         .iter()
45         .map(std::string::ToString::to_string)
46         .collect();
47
48     assert_eq!(arg_value(None, "--foobar", |_| true), None);
49     assert_eq!(arg_value(&args, "--bar", |_| false), None);
50     assert_eq!(arg_value(&args, "--bar", |_| true), Some("bar"));
51     assert_eq!(arg_value(&args, "--bar", |p| p == "bar"), Some("bar"));
52     assert_eq!(arg_value(&args, "--bar", |p| p == "foo"), None);
53     assert_eq!(arg_value(&args, "--foobar", |p| p == "foo"), None);
54     assert_eq!(arg_value(&args, "--foobar", |p| p == "123"), Some("123"));
55     assert_eq!(arg_value(&args, "--foo", |_| true), None);
56 }
57
58 #[allow(clippy::too_many_lines)]
59
60 struct ClippyCallbacks;
61
62 impl rustc_driver::Callbacks for ClippyCallbacks {
63     fn after_parsing(&mut self, compiler: &interface::Compiler) -> bool {
64         let sess = compiler.session();
65         let mut registry = rustc_plugin::registry::Registry::new(
66             sess,
67             compiler
68                 .parse()
69                 .expect(
70                     "at this compilation stage \
71                      the crate must be parsed",
72                 )
73                 .peek()
74                 .span,
75         );
76         registry.args_hidden = Some(Vec::new());
77
78         let conf = clippy_lints::read_conf(&registry);
79         clippy_lints::register_plugins(&mut registry, &conf);
80
81         let rustc_plugin::registry::Registry {
82             early_lint_passes,
83             late_lint_passes,
84             lint_groups,
85             llvm_passes,
86             attributes,
87             ..
88         } = registry;
89         let mut ls = sess.lint_store.borrow_mut();
90         for pass in early_lint_passes {
91             ls.register_early_pass(Some(sess), true, false, pass);
92         }
93         for pass in late_lint_passes {
94             ls.register_late_pass(Some(sess), true, false, false, pass);
95         }
96
97         for (name, (to, deprecated_name)) in lint_groups {
98             ls.register_group(Some(sess), true, name, deprecated_name, to);
99         }
100         clippy_lints::register_pre_expansion_lints(sess, &mut ls, &conf);
101         clippy_lints::register_renamed(&mut ls);
102
103         sess.plugin_llvm_passes.borrow_mut().extend(llvm_passes);
104         sess.plugin_attributes.borrow_mut().extend(attributes);
105
106         // Continue execution
107         true
108     }
109 }
110
111 pub fn main() {
112     rustc_driver::init_rustc_env_logger();
113     exit(
114         rustc_driver::report_ices_to_stderr_if_any(move || {
115             use std::env;
116
117             if std::env::args().any(|a| a == "--version" || a == "-V") {
118                 let version_info = rustc_tools_util::get_version_info!();
119                 println!("{}", version_info);
120                 exit(0);
121             }
122
123             let mut orig_args: Vec<String> = env::args().collect();
124
125             // Get the sysroot, looking from most specific to this invocation to the least:
126             // - command line
127             // - runtime environment
128             //    - SYSROOT
129             //    - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
130             // - sysroot from rustc in the path
131             // - compile-time environment
132             let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
133             let have_sys_root_arg = sys_root_arg.is_some();
134             let sys_root = sys_root_arg
135                 .map(std::string::ToString::to_string)
136                 .or_else(|| std::env::var("SYSROOT").ok())
137                 .or_else(|| {
138                     let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
139                     let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
140                     home.and_then(|home| toolchain.map(|toolchain| format!("{}/toolchains/{}", home, toolchain)))
141                 })
142                 .or_else(|| {
143                     Command::new("rustc")
144                         .arg("--print")
145                         .arg("sysroot")
146                         .output()
147                         .ok()
148                         .and_then(|out| String::from_utf8(out.stdout).ok())
149                         .map(|s| s.trim().to_owned())
150                 })
151                 .or_else(|| option_env!("SYSROOT").map(String::from))
152                 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
153
154             // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
155             // We're invoking the compiler programmatically, so we ignore this/
156             if orig_args.len() <= 1 {
157                 std::process::exit(1);
158             }
159             if Path::new(&orig_args[1]).file_stem() == Some("rustc".as_ref()) {
160                 // we still want to be able to invoke it normally though
161                 orig_args.remove(1);
162             }
163             // this conditional check for the --sysroot flag is there so users can call
164             // `clippy_driver` directly
165             // without having to pass --sysroot or anything
166             let mut args: Vec<String> = if have_sys_root_arg {
167                 orig_args.clone()
168             } else {
169                 orig_args
170                     .clone()
171                     .into_iter()
172                     .chain(Some("--sysroot".to_owned()))
173                     .chain(Some(sys_root))
174                     .collect()
175             };
176
177             // this check ensures that dependencies are built but not linted and the final
178             // crate is
179             // linted but not built
180             let clippy_enabled = env::var("CLIPPY_TESTS").ok().map_or(false, |val| val == "true")
181                 || arg_value(&orig_args, "--emit", |val| val.split(',').any(|e| e == "metadata")).is_some();
182
183             if clippy_enabled {
184                 args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
185                 if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
186                     args.extend(extra_args.split("__CLIPPY_HACKERY__").filter_map(|s| {
187                         if s.is_empty() {
188                             None
189                         } else {
190                             Some(s.to_string())
191                         }
192                     }));
193                 }
194             }
195
196             let mut clippy = ClippyCallbacks;
197             let mut default = rustc_driver::DefaultCallbacks;
198             let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
199                 if clippy_enabled { &mut clippy } else { &mut default };
200             let args = args;
201             rustc_driver::run_compiler(&args, callbacks, None, None)
202         })
203         .and_then(|result| result)
204         .is_err() as i32,
205     )
206 }