2 #![feature(box_syntax)]
3 #![feature(rustc_private)]
4 #![allow(clippy::missing_docs_in_private_items)]
6 // FIXME: switch to something more ergonomic here, once available.
7 // (currently there is no way to opt into sysroot crates w/o `extern crate`)
8 #[allow(unused_extern_crates)]
9 extern crate rustc_driver;
10 #[allow(unused_extern_crates)]
11 extern crate rustc_interface;
12 #[allow(unused_extern_crates)]
13 extern crate rustc_plugin;
15 use rustc_interface::interface;
17 use std::process::{exit, Command};
20 println!(env!("CARGO_PKG_VERSION"));
23 /// If a command-line option matches `find_arg`, then apply the predicate `pred` on its value. If
24 /// true, then return it. The parameter is assumed to be either `--arg=value` or `--arg value`.
26 args: impl IntoIterator<Item = &'a String>,
28 pred: impl Fn(&str) -> bool,
29 ) -> Option<&'a str> {
30 let mut args = args.into_iter().map(String::as_str);
32 while let Some(arg) = args.next() {
33 let arg: Vec<_> = arg.splitn(2, '=').collect();
34 if arg.get(0) != Some(&find_arg) {
38 let value = arg.get(1).cloned().or_else(|| args.next());
39 if value.as_ref().map_or(false, |p| pred(p)) {
48 let args: Vec<_> = ["--bar=bar", "--foobar", "123", "--foo"]
50 .map(std::string::ToString::to_string)
53 assert_eq!(arg_value(None, "--foobar", |_| true), None);
54 assert_eq!(arg_value(&args, "--bar", |_| false), None);
55 assert_eq!(arg_value(&args, "--bar", |_| true), Some("bar"));
56 assert_eq!(arg_value(&args, "--bar", |p| p == "bar"), Some("bar"));
57 assert_eq!(arg_value(&args, "--bar", |p| p == "foo"), None);
58 assert_eq!(arg_value(&args, "--foobar", |p| p == "foo"), None);
59 assert_eq!(arg_value(&args, "--foobar", |p| p == "123"), Some("123"));
60 assert_eq!(arg_value(&args, "--foo", |_| true), None);
63 #[allow(clippy::too_many_lines)]
65 struct ClippyCallbacks;
67 impl rustc_driver::Callbacks for ClippyCallbacks {
68 fn after_parsing(&mut self, compiler: &interface::Compiler) -> bool {
69 let sess = compiler.session();
70 let mut registry = rustc_plugin::registry::Registry::new(
75 "at this compilation stage \
76 the crate must be parsed",
81 registry.args_hidden = Some(Vec::new());
83 let conf = clippy_lints::read_conf(®istry);
84 clippy_lints::register_plugins(&mut registry, &conf);
86 let rustc_plugin::registry::Registry {
94 let mut ls = sess.lint_store.borrow_mut();
95 for pass in early_lint_passes {
96 ls.register_early_pass(Some(sess), true, false, pass);
98 for pass in late_lint_passes {
99 ls.register_late_pass(Some(sess), true, pass);
102 for (name, (to, deprecated_name)) in lint_groups {
103 ls.register_group(Some(sess), true, name, deprecated_name, to);
105 clippy_lints::register_pre_expansion_lints(sess, &mut ls, &conf);
106 clippy_lints::register_renamed(&mut ls);
108 sess.plugin_llvm_passes.borrow_mut().extend(llvm_passes);
109 sess.plugin_attributes.borrow_mut().extend(attributes);
111 // Continue execution
117 rustc_driver::init_rustc_env_logger();
119 rustc_driver::report_ices_to_stderr_if_any(move || {
122 if std::env::args().any(|a| a == "--version" || a == "-V") {
127 let mut orig_args: Vec<String> = env::args().collect();
129 // Get the sysroot, looking from most specific to this invocation to the least:
131 // - runtime environment
133 // - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
134 // - sysroot from rustc in the path
135 // - compile-time environment
136 let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
137 let have_sys_root_arg = sys_root_arg.is_some();
138 let sys_root = sys_root_arg
139 .map(std::string::ToString::to_string)
140 .or_else(|| std::env::var("SYSROOT").ok())
142 let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
143 let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
144 home.and_then(|home| toolchain.map(|toolchain| format!("{}/toolchains/{}", home, toolchain)))
147 Command::new("rustc")
152 .and_then(|out| String::from_utf8(out.stdout).ok())
153 .map(|s| s.trim().to_owned())
155 .or_else(|| option_env!("SYSROOT").map(String::from))
156 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
158 // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
159 // We're invoking the compiler programmatically, so we ignore this/
160 if orig_args.len() <= 1 {
161 std::process::exit(1);
163 if Path::new(&orig_args[1]).file_stem() == Some("rustc".as_ref()) {
164 // we still want to be able to invoke it normally though
167 // this conditional check for the --sysroot flag is there so users can call
168 // `clippy_driver` directly
169 // without having to pass --sysroot or anything
170 let mut args: Vec<String> = if have_sys_root_arg {
176 .chain(Some("--sysroot".to_owned()))
177 .chain(Some(sys_root))
181 // this check ensures that dependencies are built but not linted and the final
183 // linted but not built
184 let clippy_enabled = env::var("CLIPPY_TESTS").ok().map_or(false, |val| val == "true")
185 || arg_value(&orig_args, "--emit", |val| val.split(',').any(|e| e == "metadata")).is_some();
188 args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
189 if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
190 args.extend(extra_args.split("__CLIPPY_HACKERY__").filter_map(|s| {
200 let mut clippy = ClippyCallbacks;
201 let mut default = rustc_driver::DefaultCallbacks;
202 let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
203 if clippy_enabled { &mut clippy } else { &mut default };
205 rustc_driver::run_compiler(&args, callbacks, None, None)
207 .and_then(|result| result)