1 #![feature(rustc_private)]
2 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
3 // warn on lints, that are included in `rust-lang/rust`s bootstrap
4 #![warn(rust_2018_idioms, unused_lifetimes)]
5 // warn on rustc internal lints
6 #![deny(rustc::internal)]
8 // FIXME: switch to something more ergonomic here, once available.
9 // (Currently there is no way to opt into sysroot crates without `extern crate`.)
10 #[allow(unused_extern_crates)]
11 extern crate rustc_driver;
12 #[allow(unused_extern_crates)]
13 extern crate rustc_errors;
14 #[allow(unused_extern_crates)]
15 extern crate rustc_interface;
16 #[allow(unused_extern_crates)]
17 extern crate rustc_middle;
19 use rustc_interface::interface;
20 use rustc_middle::ty::TyCtxt;
21 use rustc_tools_util::VersionInfo;
23 use lazy_static::lazy_static;
28 use std::path::{Path, PathBuf};
29 use std::process::{exit, Command};
33 /// If a command-line option matches `find_arg`, then apply the predicate `pred` on its value. If
34 /// true, then return it. The parameter is assumed to be either `--arg=value` or `--arg value`.
35 fn arg_value<'a, T: Deref<Target = str>>(
38 pred: impl Fn(&str) -> bool,
39 ) -> Option<&'a str> {
40 let mut args = args.iter().map(Deref::deref);
41 while let Some(arg) = args.next() {
42 let mut arg = arg.splitn(2, '=');
43 if arg.next() != Some(find_arg) {
47 match arg.next().or_else(|| args.next()) {
48 Some(v) if pred(v) => return Some(v),
57 let args = &["--bar=bar", "--foobar", "123", "--foo"];
59 assert_eq!(arg_value(&[] as &[&str], "--foobar", |_| true), None);
60 assert_eq!(arg_value(args, "--bar", |_| false), None);
61 assert_eq!(arg_value(args, "--bar", |_| true), Some("bar"));
62 assert_eq!(arg_value(args, "--bar", |p| p == "bar"), Some("bar"));
63 assert_eq!(arg_value(args, "--bar", |p| p == "foo"), None);
64 assert_eq!(arg_value(args, "--foobar", |p| p == "foo"), None);
65 assert_eq!(arg_value(args, "--foobar", |p| p == "123"), Some("123"));
66 assert_eq!(arg_value(args, "--foo", |_| true), None);
69 struct DefaultCallbacks;
70 impl rustc_driver::Callbacks for DefaultCallbacks {}
72 struct ClippyCallbacks;
73 impl rustc_driver::Callbacks for ClippyCallbacks {
74 fn config(&mut self, config: &mut interface::Config) {
75 let previous = config.register_lints.take();
76 config.register_lints = Some(Box::new(move |sess, mut lint_store| {
77 // technically we're ~guaranteed that this is none but might as well call anything that
78 // is there already. Certainly it can't hurt.
79 if let Some(previous) = &previous {
80 (previous)(sess, lint_store);
83 let conf = clippy_lints::read_conf(&[], &sess);
84 clippy_lints::register_plugins(&mut lint_store, &sess, &conf);
85 clippy_lints::register_pre_expansion_lints(&mut lint_store);
86 clippy_lints::register_renamed(&mut lint_store);
89 // FIXME: #4825; This is required, because Clippy lints that are based on MIR have to be
90 // run on the unoptimized MIR. On the other hand this results in some false negatives. If
91 // MIR passes can be enabled / disabled separately, we should figure out, what passes to
93 config.opts.debugging_opts.mir_opt_level = 0;
97 #[allow(clippy::find_map, clippy::filter_map)]
99 use lintlist::{Level, Lint, ALL_LINTS, LINT_LEVELS};
100 use std::collections::HashSet;
104 Available lint options:
105 -W <foo> Warn about <foo>
108 -F <foo> Forbid <foo> (deny <foo> and all attempts to override)
113 let lint_level = |lint: &Lint| {
116 .find(|level_mapping| level_mapping.0 == lint.group)
117 .map(|(_, level)| match level {
118 Level::Allow => "allow",
119 Level::Warn => "warn",
120 Level::Deny => "deny",
125 let mut lints: Vec<_> = ALL_LINTS.iter().collect();
126 // The sort doesn't case-fold but it's doubtful we care.
127 lints.sort_by_cached_key(|x: &&Lint| (lint_level(x), x.name));
129 let max_lint_name_len = lints
131 .map(|lint| lint.name.len())
132 .map(|len| len + "clippy::".len())
136 let padded = |x: &str| {
137 let mut s = " ".repeat(max_lint_name_len - x.chars().count());
142 let scoped = |x: &str| format!("clippy::{}", x);
144 let lint_groups: HashSet<_> = lints.iter().map(|lint| lint.group).collect();
146 println!("Lint checks provided by clippy:\n");
147 println!(" {} {:7.7} meaning", padded("name"), "default");
148 println!(" {} {:7.7} -------", padded("----"), "-------");
150 let print_lints = |lints: &[&Lint]| {
152 let name = lint.name.replace("_", "-");
155 padded(&scoped(&name)),
165 let max_group_name_len = std::cmp::max(
169 .map(|group| group.len())
170 .map(|len| len + "clippy::".len())
175 let padded_group = |x: &str| {
176 let mut s = " ".repeat(max_group_name_len - x.chars().count());
181 println!("Lint groups provided by clippy:\n");
182 println!(" {} sub-lints", padded_group("name"));
183 println!(" {} ---------", padded_group("----"));
184 println!(" {} the set of all clippy lints", padded_group("clippy::all"));
186 let print_lint_groups = || {
187 for group in lint_groups {
188 let name = group.to_lowercase().replace("_", "-");
191 .filter(|&lint| lint.group == group)
192 .map(|lint| lint.name)
193 .map(|name| name.replace("_", "-"))
194 .collect::<Vec<String>>()
196 println!(" {} {}", padded_group(&scoped(&name)), desc);
207 Checks a package to catch common mistakes and improve your Rust code.
210 cargo clippy [options] [--] [<opts>...]
213 -h, --help Print this message
214 -V, --version Print version info and exit
216 Other options are the same as `cargo check`.
218 To allow or deny a lint from the command line you can use `cargo clippy --`
221 -W --warn OPT Set lint warnings
222 -A --allow OPT Set lint allowed
223 -D --deny OPT Set lint denied
224 -F --forbid OPT Set lint forbidden
226 You can use tool lints to allow or deny lints from your code, eg.:
228 #[allow(clippy::needless_lifetimes)]
233 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust-clippy/issues/new";
236 static ref ICE_HOOK: Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static> = {
237 let hook = panic::take_hook();
238 panic::set_hook(Box::new(|info| report_clippy_ice(info, BUG_REPORT_URL)));
243 fn report_clippy_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
244 // Invoke our ICE handler, which prints the actual panic message and optionally a backtrace
247 // Separate the output with an empty line
250 let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
251 rustc_errors::ColorConfig::Auto,
258 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
260 // a .span_bug or .bug call has already printed what
261 // it wants to print.
262 if !info.payload().is::<rustc_errors::ExplicitBug>() {
263 let d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
264 handler.emit_diagnostic(&d);
267 let version_info = rustc_tools_util::get_version_info!();
269 let xs: Vec<Cow<'static, str>> = vec![
270 "the compiler unexpectedly panicked. this is a bug.".into(),
271 format!("we would appreciate a bug report: {}", bug_report_url).into(),
272 format!("Clippy version: {}", version_info).into(),
276 handler.note_without_error(¬e);
279 // If backtraces are enabled, also print the query stack
280 let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
283 TyCtxt::try_print_query_stack(&handler);
287 fn toolchain_path(home: Option<String>, toolchain: Option<String>) -> Option<PathBuf> {
288 home.and_then(|home| {
289 toolchain.map(|toolchain| {
290 let mut path = PathBuf::from(home);
291 path.push("toolchains");
292 path.push(toolchain);
299 rustc_driver::init_rustc_env_logger();
300 lazy_static::initialize(&ICE_HOOK);
301 exit(rustc_driver::catch_with_exit_code(move || {
302 let mut orig_args: Vec<String> = env::args().collect();
304 if orig_args.iter().any(|a| a == "--version" || a == "-V") {
305 let version_info = rustc_tools_util::get_version_info!();
306 println!("{}", version_info);
310 // Get the sysroot, looking from most specific to this invocation to the least:
312 // - runtime environment
314 // - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
315 // - sysroot from rustc in the path
316 // - compile-time environment
318 // - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
319 let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
320 let have_sys_root_arg = sys_root_arg.is_some();
321 let sys_root = sys_root_arg
323 .or_else(|| std::env::var("SYSROOT").ok().map(PathBuf::from))
325 let home = std::env::var("RUSTUP_HOME")
326 .or_else(|_| std::env::var("MULTIRUST_HOME"))
328 let toolchain = std::env::var("RUSTUP_TOOLCHAIN")
329 .or_else(|_| std::env::var("MULTIRUST_TOOLCHAIN"))
331 toolchain_path(home, toolchain)
334 Command::new("rustc")
339 .and_then(|out| String::from_utf8(out.stdout).ok())
340 .map(|s| PathBuf::from(s.trim()))
342 .or_else(|| option_env!("SYSROOT").map(PathBuf::from))
344 let home = option_env!("RUSTUP_HOME")
345 .or(option_env!("MULTIRUST_HOME"))
346 .map(ToString::to_string);
347 let toolchain = option_env!("RUSTUP_TOOLCHAIN")
348 .or(option_env!("MULTIRUST_TOOLCHAIN"))
349 .map(ToString::to_string);
350 toolchain_path(home, toolchain)
352 .map(|pb| pb.to_string_lossy().to_string())
353 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
355 // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
356 // We're invoking the compiler programmatically, so we ignore this/
357 let wrapper_mode = orig_args.get(1).map(Path::new).and_then(Path::file_stem) == Some("rustc".as_ref());
360 // we still want to be able to invoke it normally though
364 if !wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
369 let should_describe_lints = || {
370 let args: Vec<_> = env::args().collect();
371 args.windows(2).any(|args| {
373 && match args[0].as_str() {
374 "-W" | "-A" | "-D" | "-F" => true,
380 if !wrapper_mode && should_describe_lints() {
385 // this conditional check for the --sysroot flag is there so users can call
386 // `clippy_driver` directly
387 // without having to pass --sysroot or anything
388 let mut args: Vec<String> = orig_args.clone();
389 if !have_sys_root_arg {
390 args.extend(vec!["--sysroot".into(), sys_root]);
393 // this check ensures that dependencies are built but not linted and the final
394 // crate is linted but not built
395 let clippy_enabled = env::var("CLIPPY_TESTS").map_or(false, |val| val == "true")
396 || arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_none();
399 args.extend(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()]);
400 if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
401 args.extend(extra_args.split("__CLIPPY_HACKERY__").filter_map(|s| {
410 let mut clippy = ClippyCallbacks;
411 let mut default = DefaultCallbacks;
412 let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
413 if clippy_enabled { &mut clippy } else { &mut default };
414 rustc_driver::run_compiler(&args, callbacks, None, None)