1 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
2 #![feature(result_map_or)]
3 #![feature(rustc_private)]
5 // FIXME: switch to something more ergonomic here, once available.
6 // (Currently there is no way to opt into sysroot crates without `extern crate`.)
7 #[allow(unused_extern_crates)]
9 #[allow(unused_extern_crates)]
10 extern crate rustc_driver;
11 #[allow(unused_extern_crates)]
12 extern crate rustc_errors;
13 #[allow(unused_extern_crates)]
14 extern crate rustc_interface;
16 use rustc::ty::TyCtxt;
17 use rustc_interface::interface;
18 use rustc_tools_util::*;
20 use lazy_static::lazy_static;
23 use std::path::{Path, PathBuf};
24 use std::process::{exit, Command};
28 /// If a command-line option matches `find_arg`, then apply the predicate `pred` on its value. If
29 /// true, then return it. The parameter is assumed to be either `--arg=value` or `--arg value`.
31 args: impl IntoIterator<Item = &'a String>,
33 pred: impl Fn(&str) -> bool,
34 ) -> Option<&'a str> {
35 let mut args = args.into_iter().map(String::as_str);
37 while let Some(arg) = args.next() {
38 let arg: Vec<_> = arg.splitn(2, '=').collect();
39 if arg.get(0) != Some(&find_arg) {
43 let value = arg.get(1).cloned().or_else(|| args.next());
44 if value.as_ref().map_or(false, |p| pred(p)) {
53 let args: Vec<_> = ["--bar=bar", "--foobar", "123", "--foo"]
55 .map(std::string::ToString::to_string)
58 assert_eq!(arg_value(None, "--foobar", |_| true), None);
59 assert_eq!(arg_value(&args, "--bar", |_| false), None);
60 assert_eq!(arg_value(&args, "--bar", |_| true), Some("bar"));
61 assert_eq!(arg_value(&args, "--bar", |p| p == "bar"), Some("bar"));
62 assert_eq!(arg_value(&args, "--bar", |p| p == "foo"), None);
63 assert_eq!(arg_value(&args, "--foobar", |p| p == "foo"), None);
64 assert_eq!(arg_value(&args, "--foobar", |p| p == "123"), Some("123"));
65 assert_eq!(arg_value(&args, "--foo", |_| true), None);
68 #[allow(clippy::too_many_lines)]
70 struct ClippyCallbacks;
72 impl rustc_driver::Callbacks for ClippyCallbacks {
73 fn config(&mut self, config: &mut interface::Config) {
74 let previous = config.register_lints.take();
75 config.register_lints = Some(Box::new(move |sess, mut lint_store| {
76 // technically we're ~guaranteed that this is none but might as well call anything that
77 // is there already. Certainly it can't hurt.
78 if let Some(previous) = &previous {
79 (previous)(sess, lint_store);
82 let conf = clippy_lints::read_conf(&[], &sess);
83 clippy_lints::register_plugins(&mut lint_store, &sess, &conf);
84 clippy_lints::register_pre_expansion_lints(&mut lint_store, &conf);
85 clippy_lints::register_renamed(&mut lint_store);
88 // FIXME: #4825; This is required, because Clippy lints that are based on MIR have to be
89 // run on the unoptimized MIR. On the other hand this results in some false negatives. If
90 // MIR passes can be enabled / disabled separately, we should figure out, what passes to
92 config.opts.debugging_opts.mir_opt_level = 0;
96 #[allow(clippy::find_map, clippy::filter_map)]
99 use std::collections::HashSet;
103 Available lint options:
104 -W <foo> Warn about <foo>
107 -F <foo> Forbid <foo> (deny <foo> and all attempts to override)
112 let lint_level = |lint: &Lint| {
115 .find(|level_mapping| level_mapping.0 == lint.group)
116 .map(|(_, level)| match level {
117 Level::Allow => "allow",
118 Level::Warn => "warn",
119 Level::Deny => "deny",
124 let mut lints: Vec<_> = ALL_LINTS.iter().collect();
125 // The sort doesn't case-fold but it's doubtful we care.
126 lints.sort_by_cached_key(|x: &&Lint| (lint_level(x), x.name));
128 let max_lint_name_len = lints
130 .map(|lint| lint.name.len())
131 .map(|len| len + "clippy::".len())
135 let padded = |x: &str| {
136 let mut s = " ".repeat(max_lint_name_len - x.chars().count());
141 let scoped = |x: &str| format!("clippy::{}", x);
143 let lint_groups: HashSet<_> = lints.iter().map(|lint| lint.group).collect();
145 println!("Lint checks provided by clippy:\n");
146 println!(" {} {:7.7} meaning", padded("name"), "default");
147 println!(" {} {:7.7} -------", padded("----"), "-------");
149 let print_lints = |lints: &[&Lint]| {
151 let name = lint.name.replace("_", "-");
154 padded(&scoped(&name)),
164 let max_group_name_len = std::cmp::max(
168 .map(|group| group.len())
169 .map(|len| len + "clippy::".len())
174 let padded_group = |x: &str| {
175 let mut s = " ".repeat(max_group_name_len - x.chars().count());
180 println!("Lint groups provided by clippy:\n");
181 println!(" {} sub-lints", padded_group("name"));
182 println!(" {} ---------", padded_group("----"));
183 println!(" {} the set of all clippy lints", padded_group("clippy::all"));
185 let print_lint_groups = || {
186 for group in lint_groups {
187 let name = group.to_lowercase().replace("_", "-");
190 .filter(|&lint| lint.group == group)
191 .map(|lint| lint.name)
192 .map(|name| name.replace("_", "-"))
193 .collect::<Vec<String>>()
195 println!(" {} {}", padded_group(&scoped(&name)), desc);
206 Checks a package to catch common mistakes and improve your Rust code.
209 cargo clippy [options] [--] [<opts>...]
212 -h, --help Print this message
213 -V, --version Print version info and exit
215 Other options are the same as `cargo check`.
217 To allow or deny a lint from the command line you can use `cargo clippy --`
220 -W --warn OPT Set lint warnings
221 -A --allow OPT Set lint allowed
222 -D --deny OPT Set lint denied
223 -F --forbid OPT Set lint forbidden
225 You can use tool lints to allow or deny lints from your code, eg.:
227 #[allow(clippy::needless_lifetimes)]
232 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust-clippy/issues/new";
235 static ref ICE_HOOK: Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static> = {
236 let hook = panic::take_hook();
237 panic::set_hook(Box::new(|info| report_clippy_ice(info, BUG_REPORT_URL)));
242 fn report_clippy_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
243 // Invoke our ICE handler, which prints the actual panic message and optionally a backtrace
246 // Separate the output with an empty line
249 let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
250 rustc_errors::ColorConfig::Auto,
257 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
259 // a .span_bug or .bug call has already printed what
260 // it wants to print.
261 if !info.payload().is::<rustc_errors::ExplicitBug>() {
262 let d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
263 handler.emit_diagnostic(&d);
264 handler.abort_if_errors_and_should_abort();
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 = std::env::var_os("RUST_BACKTRACE").map(|x| &x != "0").unwrap_or(false);
283 TyCtxt::try_print_query_stack();
288 rustc_driver::init_rustc_env_logger();
289 lazy_static::initialize(&ICE_HOOK);
291 rustc_driver::catch_fatal_errors(move || {
294 if std::env::args().any(|a| a == "--version" || a == "-V") {
295 let version_info = rustc_tools_util::get_version_info!();
296 println!("{}", version_info);
300 let mut orig_args: Vec<String> = env::args().collect();
302 // Get the sysroot, looking from most specific to this invocation to the least:
304 // - runtime environment
306 // - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
307 // - sysroot from rustc in the path
308 // - compile-time environment
309 let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
310 let have_sys_root_arg = sys_root_arg.is_some();
311 let sys_root = sys_root_arg
313 .or_else(|| std::env::var("SYSROOT").ok().map(PathBuf::from))
315 let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
316 let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
317 home.and_then(|home| {
318 toolchain.map(|toolchain| {
319 let mut path = PathBuf::from(home);
320 path.push("toolchains");
321 path.push(toolchain);
327 Command::new("rustc")
332 .and_then(|out| String::from_utf8(out.stdout).ok())
333 .map(|s| PathBuf::from(s.trim()))
335 .or_else(|| option_env!("SYSROOT").map(PathBuf::from))
336 .map(|pb| pb.to_string_lossy().to_string())
337 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
339 // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
340 // We're invoking the compiler programmatically, so we ignore this/
341 let wrapper_mode = orig_args.get(1).map(Path::new).and_then(Path::file_stem) == Some("rustc".as_ref());
344 // we still want to be able to invoke it normally though
348 if !wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
353 let should_describe_lints = || {
354 let args: Vec<_> = std::env::args().collect();
355 args.windows(2).any(|args| {
357 && match args[0].as_str() {
358 "-W" | "-A" | "-D" | "-F" => true,
364 if !wrapper_mode && should_describe_lints() {
369 // this conditional check for the --sysroot flag is there so users can call
370 // `clippy_driver` directly
371 // without having to pass --sysroot or anything
372 let mut args: Vec<String> = if have_sys_root_arg {
378 .chain(Some("--sysroot".to_owned()))
379 .chain(Some(sys_root))
383 // this check ensures that dependencies are built but not linted and the final
384 // crate is linted but not built
385 let clippy_enabled = env::var("CLIPPY_TESTS").map_or(false, |val| val == "true")
386 || arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_none();
389 args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
390 if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
391 args.extend(extra_args.split("__CLIPPY_HACKERY__").filter_map(|s| {
401 let mut clippy = ClippyCallbacks;
402 let mut default = rustc_driver::DefaultCallbacks;
403 let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
404 if clippy_enabled { &mut clippy } else { &mut default };
406 rustc_driver::run_compiler(&args, callbacks, None, None)
408 .and_then(|result| result)