1 #![feature(rustc_private)]
3 #![feature(bool_to_option)]
4 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
5 // warn on lints, that are included in `rust-lang/rust`s bootstrap
6 #![warn(rust_2018_idioms, unused_lifetimes)]
7 // warn on rustc internal lints
8 #![deny(rustc::internal)]
10 // FIXME: switch to something more ergonomic here, once available.
11 // (Currently there is no way to opt into sysroot crates without `extern crate`.)
12 extern crate rustc_driver;
13 extern crate rustc_errors;
14 extern crate rustc_interface;
15 extern crate rustc_middle;
17 use rustc_interface::interface;
18 use rustc_middle::ty::TyCtxt;
19 use rustc_tools_util::VersionInfo;
24 use std::lazy::SyncLazy;
27 use std::path::{Path, PathBuf};
28 use std::process::{exit, Command};
30 /// If a command-line option matches `find_arg`, then apply the predicate `pred` on its value. If
31 /// true, then return it. The parameter is assumed to be either `--arg=value` or `--arg value`.
32 fn arg_value<'a, T: Deref<Target = str>>(
35 pred: impl Fn(&str) -> bool,
36 ) -> Option<&'a str> {
37 let mut args = args.iter().map(Deref::deref);
38 while let Some(arg) = args.next() {
39 let mut arg = arg.splitn(2, '=');
40 if arg.next() != Some(find_arg) {
44 match arg.next().or_else(|| args.next()) {
45 Some(v) if pred(v) => return Some(v),
52 struct DefaultCallbacks;
53 impl rustc_driver::Callbacks for DefaultCallbacks {}
55 struct ClippyCallbacks;
56 impl rustc_driver::Callbacks for ClippyCallbacks {
57 fn config(&mut self, config: &mut interface::Config) {
58 let previous = config.register_lints.take();
59 config.register_lints = Some(Box::new(move |sess, mut lint_store| {
60 // technically we're ~guaranteed that this is none but might as well call anything that
61 // is there already. Certainly it can't hurt.
62 if let Some(previous) = &previous {
63 (previous)(sess, lint_store);
66 let conf = clippy_lints::read_conf(&[], &sess);
67 clippy_lints::register_plugins(&mut lint_store, &sess, &conf);
68 clippy_lints::register_pre_expansion_lints(&mut lint_store);
69 clippy_lints::register_renamed(&mut lint_store);
72 // FIXME: #4825; This is required, because Clippy lints that are based on MIR have to be
73 // run on the unoptimized MIR. On the other hand this results in some false negatives. If
74 // MIR passes can be enabled / disabled separately, we should figure out, what passes to
76 config.opts.debugging_opts.mir_opt_level = 0;
83 Checks a package to catch common mistakes and improve your Rust code.
86 cargo clippy [options] [--] [<opts>...]
89 -h, --help Print this message
90 --rustc Pass all args to rustc
91 -V, --version Print version info and exit
93 Other options are the same as `cargo check`.
95 To allow or deny a lint from the command line you can use `cargo clippy --`
98 -W --warn OPT Set lint warnings
99 -A --allow OPT Set lint allowed
100 -D --deny OPT Set lint denied
101 -F --forbid OPT Set lint forbidden
103 You can use tool lints to allow or deny lints from your code, eg.:
105 #[allow(clippy::needless_lifetimes)]
110 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust-clippy/issues/new";
112 static ICE_HOOK: SyncLazy<Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static>> = SyncLazy::new(|| {
113 let hook = panic::take_hook();
114 panic::set_hook(Box::new(|info| report_clippy_ice(info, BUG_REPORT_URL)));
118 fn report_clippy_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
119 // Invoke our ICE handler, which prints the actual panic message and optionally a backtrace
122 // Separate the output with an empty line
125 let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
126 rustc_errors::ColorConfig::Auto,
133 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
135 // a .span_bug or .bug call has already printed what
136 // it wants to print.
137 if !info.payload().is::<rustc_errors::ExplicitBug>() {
138 let d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
139 handler.emit_diagnostic(&d);
142 let version_info = rustc_tools_util::get_version_info!();
144 let xs: Vec<Cow<'static, str>> = vec![
145 "the compiler unexpectedly panicked. this is a bug.".into(),
146 format!("we would appreciate a bug report: {}", bug_report_url).into(),
147 format!("Clippy version: {}", version_info).into(),
151 handler.note_without_error(¬e);
154 // If backtraces are enabled, also print the query stack
155 let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
157 let num_frames = if backtrace { None } else { Some(2) };
159 TyCtxt::try_print_query_stack(&handler, num_frames);
162 fn toolchain_path(home: Option<String>, toolchain: Option<String>) -> Option<PathBuf> {
163 home.and_then(|home| {
164 toolchain.map(|toolchain| {
165 let mut path = PathBuf::from(home);
166 path.push("toolchains");
167 path.push(toolchain);
173 fn remove_clippy_args<'a, T, U, I>(args: &mut Vec<T>, clippy_args: I)
176 U: AsRef<str> + ?Sized + 'a,
177 I: Iterator<Item = &'a U> + Clone,
179 let args_iter = clippy_args.map(AsRef::as_ref);
180 let args_count = args_iter.clone().count();
183 if let Some(start) = args.windows(args_count).enumerate().find_map(|(current, window)| {
187 .eq(args_iter.clone())
190 args.drain(start..start + args_count);
195 #[allow(clippy::too_many_lines)]
197 rustc_driver::init_rustc_env_logger();
198 SyncLazy::force(&ICE_HOOK);
199 exit(rustc_driver::catch_with_exit_code(move || {
200 let mut orig_args: Vec<String> = env::args().collect();
202 // Get the sysroot, looking from most specific to this invocation to the least:
204 // - runtime environment
206 // - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
207 // - sysroot from rustc in the path
208 // - compile-time environment
210 // - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
211 let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
212 let have_sys_root_arg = sys_root_arg.is_some();
213 let sys_root = sys_root_arg
215 .or_else(|| std::env::var("SYSROOT").ok().map(PathBuf::from))
217 let home = std::env::var("RUSTUP_HOME")
218 .or_else(|_| std::env::var("MULTIRUST_HOME"))
220 let toolchain = std::env::var("RUSTUP_TOOLCHAIN")
221 .or_else(|_| std::env::var("MULTIRUST_TOOLCHAIN"))
223 toolchain_path(home, toolchain)
226 Command::new("rustc")
231 .and_then(|out| String::from_utf8(out.stdout).ok())
232 .map(|s| PathBuf::from(s.trim()))
234 .or_else(|| option_env!("SYSROOT").map(PathBuf::from))
236 let home = option_env!("RUSTUP_HOME")
237 .or(option_env!("MULTIRUST_HOME"))
238 .map(ToString::to_string);
239 let toolchain = option_env!("RUSTUP_TOOLCHAIN")
240 .or(option_env!("MULTIRUST_TOOLCHAIN"))
241 .map(ToString::to_string);
242 toolchain_path(home, toolchain)
244 .map(|pb| pb.to_string_lossy().to_string())
245 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
247 // make "clippy-driver --rustc" work like a subcommand that passes further args to "rustc"
248 // for example `clippy-driver --rustc --version` will print the rustc version that clippy-driver
250 if let Some(pos) = orig_args.iter().position(|arg| arg == "--rustc") {
251 orig_args.remove(pos);
252 orig_args[0] = "rustc".to_string();
254 // if we call "rustc", we need to pass --sysroot here as well
255 let mut args: Vec<String> = orig_args.clone();
256 if !have_sys_root_arg {
257 args.extend(vec!["--sysroot".into(), sys_root]);
260 return rustc_driver::RunCompiler::new(&args, &mut DefaultCallbacks).run();
263 if orig_args.iter().any(|a| a == "--version" || a == "-V") {
264 let version_info = rustc_tools_util::get_version_info!();
265 println!("{}", version_info);
269 // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
270 // We're invoking the compiler programmatically, so we ignore this/
271 let wrapper_mode = orig_args.get(1).map(Path::new).and_then(Path::file_stem) == Some("rustc".as_ref());
274 // we still want to be able to invoke it normally though
278 if !wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
283 // this conditional check for the --sysroot flag is there so users can call
284 // `clippy_driver` directly
285 // without having to pass --sysroot or anything
286 let mut args: Vec<String> = orig_args.clone();
287 if !have_sys_root_arg {
288 args.extend(vec!["--sysroot".into(), sys_root]);
291 let clippy_args = env::var("CLIPPY_ARGS").unwrap_or_default();
292 let clippy_args = clippy_args.split_whitespace();
293 let no_deps = clippy_args.clone().any(|flag| flag == "--no-deps");
295 // We enable Clippy if one of the following conditions is met
296 // - IF Clippy is run on its test suite OR
297 // - IF Clippy is run on the main crate, not on deps (`!cap_lints_allow`) THEN
298 // - IF `--no-deps` is not set (`!no_deps`) OR
299 // - IF `--no-deps` is set and Clippy is run on the specified primary package
300 let clippy_tests_set = env::var("CLIPPY_TESTS").map_or(false, |val| val == "true");
301 let cap_lints_allow = arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_some();
302 let in_primary_package = env::var("CARGO_PRIMARY_PACKAGE").is_ok();
304 let clippy_enabled = clippy_tests_set || (!cap_lints_allow && (!no_deps || in_primary_package));
306 remove_clippy_args(&mut args, iter::once("--no-deps"));
307 args.extend(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()]);
309 // Remove all flags passed through RUSTFLAGS if Clippy is not enabled.
310 remove_clippy_args(&mut args, clippy_args);
313 let mut clippy = ClippyCallbacks;
314 let mut default = DefaultCallbacks;
315 let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
316 if clippy_enabled { &mut clippy } else { &mut default };
318 rustc_driver::RunCompiler::new(&args, callbacks).run()
327 fn test_arg_value() {
328 let args = &["--bar=bar", "--foobar", "123", "--foo"];
330 assert_eq!(arg_value(&[] as &[&str], "--foobar", |_| true), None);
331 assert_eq!(arg_value(args, "--bar", |_| false), None);
332 assert_eq!(arg_value(args, "--bar", |_| true), Some("bar"));
333 assert_eq!(arg_value(args, "--bar", |p| p == "bar"), Some("bar"));
334 assert_eq!(arg_value(args, "--bar", |p| p == "foo"), None);
335 assert_eq!(arg_value(args, "--foobar", |p| p == "foo"), None);
336 assert_eq!(arg_value(args, "--foobar", |p| p == "123"), Some("123"));
337 assert_eq!(arg_value(args, "--foo", |_| true), None);
341 fn removes_clippy_args_from_start() {
342 let mut args = vec!["-D", "clippy::await_holding_lock", "--cfg", r#"feature="some_feat""#];
343 let clippy_args = ["-D", "clippy::await_holding_lock"].iter();
345 remove_clippy_args(&mut args, clippy_args);
346 assert_eq!(args, &["--cfg", r#"feature="some_feat""#]);
350 fn removes_clippy_args_from_end() {
351 let mut args = vec!["-Zui-testing", "-A", "clippy::empty_loop", "--no-deps"];
352 let clippy_args = ["-A", "clippy::empty_loop", "--no-deps"].iter();
354 remove_clippy_args(&mut args, clippy_args);
355 assert_eq!(args, &["-Zui-testing"]);
359 fn removes_clippy_args_from_middle() {
360 let mut args = vec!["-Zui-testing", "-W", "clippy::filter_map", "-L", "serde"];
361 let clippy_args = ["-W", "clippy::filter_map"].iter();
363 remove_clippy_args(&mut args, clippy_args);
364 assert_eq!(args, &["-Zui-testing", "-L", "serde"]);
368 fn no_clippy_args_to_remove() {
369 let mut args = vec!["-Zui-testing", "-L", "serde"];
370 let clippy_args: [&str; 0] = [];
372 remove_clippy_args(&mut args, clippy_args.iter());
373 assert_eq!(args, &["-Zui-testing", "-L", "serde"]);