1 #![feature(rustc_private)]
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;
12 use rustc_interface::interface;
14 use std::process::{exit, Command};
17 println!(env!("CARGO_PKG_VERSION"));
20 /// If a command-line option matches `find_arg`, then apply the predicate `pred` on its value. If
21 /// true, then return it. The parameter is assumed to be either `--arg=value` or `--arg value`.
23 args: impl IntoIterator<Item = &'a String>,
25 pred: impl Fn(&str) -> bool,
26 ) -> Option<&'a str> {
27 let mut args = args.into_iter().map(String::as_str);
29 while let Some(arg) = args.next() {
30 let arg: Vec<_> = arg.splitn(2, '=').collect();
31 if arg.get(0) != Some(&find_arg) {
35 let value = arg.get(1).cloned().or_else(|| args.next());
36 if value.as_ref().map_or(false, |p| pred(p)) {
45 let args: Vec<_> = ["--bar=bar", "--foobar", "123", "--foo"]
47 .map(std::string::ToString::to_string)
50 assert_eq!(arg_value(None, "--foobar", |_| true), None);
51 assert_eq!(arg_value(&args, "--bar", |_| false), None);
52 assert_eq!(arg_value(&args, "--bar", |_| true), Some("bar"));
53 assert_eq!(arg_value(&args, "--bar", |p| p == "bar"), Some("bar"));
54 assert_eq!(arg_value(&args, "--bar", |p| p == "foo"), None);
55 assert_eq!(arg_value(&args, "--foobar", |p| p == "foo"), None);
56 assert_eq!(arg_value(&args, "--foobar", |p| p == "123"), Some("123"));
57 assert_eq!(arg_value(&args, "--foo", |_| true), None);
60 #[allow(clippy::too_many_lines)]
62 struct ClippyCallbacks;
64 impl rustc_driver::Callbacks for ClippyCallbacks {
65 fn after_parsing(&mut self, compiler: &interface::Compiler) -> bool {
66 let sess = compiler.session();
67 let mut registry = rustc_plugin::registry::Registry::new(
72 "at this compilation stage \
73 the crate must be parsed",
78 registry.args_hidden = Some(Vec::new());
80 let conf = clippy_lints::read_conf(®istry);
81 clippy_lints::register_plugins(&mut registry, &conf);
83 let rustc_plugin::registry::Registry {
91 let mut ls = sess.lint_store.borrow_mut();
92 for pass in early_lint_passes {
93 ls.register_early_pass(Some(sess), true, false, pass);
95 for pass in late_lint_passes {
96 ls.register_late_pass(Some(sess), true, false, false, pass);
99 for (name, (to, deprecated_name)) in lint_groups {
100 ls.register_group(Some(sess), true, name, deprecated_name, to);
102 clippy_lints::register_pre_expansion_lints(sess, &mut ls, &conf);
103 clippy_lints::register_renamed(&mut ls);
105 sess.plugin_llvm_passes.borrow_mut().extend(llvm_passes);
106 sess.plugin_attributes.borrow_mut().extend(attributes);
108 // Continue execution
114 rustc_driver::init_rustc_env_logger();
116 rustc_driver::report_ices_to_stderr_if_any(move || {
119 if std::env::args().any(|a| a == "--version" || a == "-V") {
124 let mut orig_args: Vec<String> = env::args().collect();
126 // Get the sysroot, looking from most specific to this invocation to the least:
128 // - runtime environment
130 // - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
131 // - sysroot from rustc in the path
132 // - compile-time environment
133 let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
134 let have_sys_root_arg = sys_root_arg.is_some();
135 let sys_root = sys_root_arg
136 .map(std::string::ToString::to_string)
137 .or_else(|| std::env::var("SYSROOT").ok())
139 let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
140 let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
141 home.and_then(|home| toolchain.map(|toolchain| format!("{}/toolchains/{}", home, toolchain)))
144 Command::new("rustc")
149 .and_then(|out| String::from_utf8(out.stdout).ok())
150 .map(|s| s.trim().to_owned())
152 .or_else(|| option_env!("SYSROOT").map(String::from))
153 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
155 // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
156 // We're invoking the compiler programmatically, so we ignore this/
157 if orig_args.len() <= 1 {
158 std::process::exit(1);
160 if Path::new(&orig_args[1]).file_stem() == Some("rustc".as_ref()) {
161 // we still want to be able to invoke it normally though
164 // this conditional check for the --sysroot flag is there so users can call
165 // `clippy_driver` directly
166 // without having to pass --sysroot or anything
167 let mut args: Vec<String> = if have_sys_root_arg {
173 .chain(Some("--sysroot".to_owned()))
174 .chain(Some(sys_root))
178 // this check ensures that dependencies are built but not linted and the final
180 // linted but not built
181 let clippy_enabled = env::var("CLIPPY_TESTS").ok().map_or(false, |val| val == "true")
182 || arg_value(&orig_args, "--emit", |val| val.split(',').any(|e| e == "metadata")).is_some();
185 args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
186 if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
187 args.extend(extra_args.split("__CLIPPY_HACKERY__").filter_map(|s| {
197 let mut clippy = ClippyCallbacks;
198 let mut default = rustc_driver::DefaultCallbacks;
199 let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
200 if clippy_enabled { &mut clippy } else { &mut default };
202 rustc_driver::run_compiler(&args, callbacks, None, None)
204 .and_then(|result| result)