1 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
2 #![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;
25 use std::path::{Path, PathBuf};
26 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),
54 let args = &["--bar=bar", "--foobar", "123", "--foo"];
56 assert_eq!(arg_value(&[] as &[&str], "--foobar", |_| true), None);
57 assert_eq!(arg_value(args, "--bar", |_| false), None);
58 assert_eq!(arg_value(args, "--bar", |_| true), Some("bar"));
59 assert_eq!(arg_value(args, "--bar", |p| p == "bar"), Some("bar"));
60 assert_eq!(arg_value(args, "--bar", |p| p == "foo"), None);
61 assert_eq!(arg_value(args, "--foobar", |p| p == "foo"), None);
62 assert_eq!(arg_value(args, "--foobar", |p| p == "123"), Some("123"));
63 assert_eq!(arg_value(args, "--foo", |_| true), None);
66 #[allow(clippy::too_many_lines)]
68 struct ClippyCallbacks;
70 impl rustc_driver::Callbacks for ClippyCallbacks {
71 fn config(&mut self, config: &mut interface::Config) {
72 let previous = config.register_lints.take();
73 config.register_lints = Some(Box::new(move |sess, mut lint_store| {
74 // technically we're ~guaranteed that this is none but might as well call anything that
75 // is there already. Certainly it can't hurt.
76 if let Some(previous) = &previous {
77 (previous)(sess, lint_store);
80 let conf = clippy_lints::read_conf(&[], &sess);
81 clippy_lints::register_plugins(&mut lint_store, &sess, &conf);
82 clippy_lints::register_pre_expansion_lints(&mut lint_store, &conf);
83 clippy_lints::register_renamed(&mut lint_store);
86 // FIXME: #4825; This is required, because Clippy lints that are based on MIR have to be
87 // run on the unoptimized MIR. On the other hand this results in some false negatives. If
88 // MIR passes can be enabled / disabled separately, we should figure out, what passes to
90 config.opts.debugging_opts.mir_opt_level = 0;
94 #[allow(clippy::find_map, clippy::filter_map)]
97 use std::collections::HashSet;
101 Available lint options:
102 -W <foo> Warn about <foo>
105 -F <foo> Forbid <foo> (deny <foo> and all attempts to override)
110 let lint_level = |lint: &Lint| {
113 .find(|level_mapping| level_mapping.0 == lint.group)
114 .map(|(_, level)| match level {
115 Level::Allow => "allow",
116 Level::Warn => "warn",
117 Level::Deny => "deny",
122 let mut lints: Vec<_> = ALL_LINTS.iter().collect();
123 // The sort doesn't case-fold but it's doubtful we care.
124 lints.sort_by_cached_key(|x: &&Lint| (lint_level(x), x.name));
126 let max_lint_name_len = lints
128 .map(|lint| lint.name.len())
129 .map(|len| len + "clippy::".len())
133 let padded = |x: &str| {
134 let mut s = " ".repeat(max_lint_name_len - x.chars().count());
139 let scoped = |x: &str| format!("clippy::{}", x);
141 let lint_groups: HashSet<_> = lints.iter().map(|lint| lint.group).collect();
143 println!("Lint checks provided by clippy:\n");
144 println!(" {} {:7.7} meaning", padded("name"), "default");
145 println!(" {} {:7.7} -------", padded("----"), "-------");
147 let print_lints = |lints: &[&Lint]| {
149 let name = lint.name.replace("_", "-");
152 padded(&scoped(&name)),
162 let max_group_name_len = std::cmp::max(
166 .map(|group| group.len())
167 .map(|len| len + "clippy::".len())
172 let padded_group = |x: &str| {
173 let mut s = " ".repeat(max_group_name_len - x.chars().count());
178 println!("Lint groups provided by clippy:\n");
179 println!(" {} sub-lints", padded_group("name"));
180 println!(" {} ---------", padded_group("----"));
181 println!(" {} the set of all clippy lints", padded_group("clippy::all"));
183 let print_lint_groups = || {
184 for group in lint_groups {
185 let name = group.to_lowercase().replace("_", "-");
188 .filter(|&lint| lint.group == group)
189 .map(|lint| lint.name)
190 .map(|name| name.replace("_", "-"))
191 .collect::<Vec<String>>()
193 println!(" {} {}", padded_group(&scoped(&name)), desc);
204 Checks a package to catch common mistakes and improve your Rust code.
207 cargo clippy [options] [--] [<opts>...]
210 -h, --help Print this message
211 -V, --version Print version info and exit
213 Other options are the same as `cargo check`.
215 To allow or deny a lint from the command line you can use `cargo clippy --`
218 -W --warn OPT Set lint warnings
219 -A --allow OPT Set lint allowed
220 -D --deny OPT Set lint denied
221 -F --forbid OPT Set lint forbidden
223 You can use tool lints to allow or deny lints from your code, eg.:
225 #[allow(clippy::needless_lifetimes)]
230 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust-clippy/issues/new";
233 static ref ICE_HOOK: Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static> = {
234 let hook = panic::take_hook();
235 panic::set_hook(Box::new(|info| report_clippy_ice(info, BUG_REPORT_URL)));
240 fn report_clippy_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
241 // Invoke our ICE handler, which prints the actual panic message and optionally a backtrace
244 // Separate the output with an empty line
247 let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
248 rustc_errors::ColorConfig::Auto,
255 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
257 // a .span_bug or .bug call has already printed what
258 // it wants to print.
259 if !info.payload().is::<rustc_errors::ExplicitBug>() {
260 let d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
261 handler.emit_diagnostic(&d);
264 let version_info = rustc_tools_util::get_version_info!();
266 let xs: Vec<Cow<'static, str>> = vec![
267 "the compiler unexpectedly panicked. this is a bug.".into(),
268 format!("we would appreciate a bug report: {}", bug_report_url).into(),
269 format!("Clippy version: {}", version_info).into(),
273 handler.note_without_error(¬e);
276 // If backtraces are enabled, also print the query stack
277 let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
280 TyCtxt::try_print_query_stack(&handler);
285 rustc_driver::init_rustc_env_logger();
286 lazy_static::initialize(&ICE_HOOK);
288 rustc_driver::catch_fatal_errors(move || {
289 let mut orig_args: Vec<String> = env::args().collect();
291 if orig_args.iter().any(|a| a == "--version" || a == "-V") {
292 let version_info = rustc_tools_util::get_version_info!();
293 println!("{}", version_info);
297 // Get the sysroot, looking from most specific to this invocation to the least:
299 // - runtime environment
301 // - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
302 // - sysroot from rustc in the path
303 // - compile-time environment
304 let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
305 let have_sys_root_arg = sys_root_arg.is_some();
306 let sys_root = sys_root_arg
308 .or_else(|| std::env::var("SYSROOT").ok().map(PathBuf::from))
310 let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
311 let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
312 home.and_then(|home| {
313 toolchain.map(|toolchain| {
314 let mut path = PathBuf::from(home);
315 path.push("toolchains");
316 path.push(toolchain);
322 Command::new("rustc")
327 .and_then(|out| String::from_utf8(out.stdout).ok())
328 .map(|s| PathBuf::from(s.trim()))
330 .or_else(|| option_env!("SYSROOT").map(PathBuf::from))
331 .map(|pb| pb.to_string_lossy().to_string())
332 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
334 // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
335 // We're invoking the compiler programmatically, so we ignore this/
336 let wrapper_mode = orig_args.get(1).map(Path::new).and_then(Path::file_stem) == Some("rustc".as_ref());
339 // we still want to be able to invoke it normally though
343 if !wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
348 let should_describe_lints = || {
349 let args: Vec<_> = env::args().collect();
350 args.windows(2).any(|args| {
352 && match args[0].as_str() {
353 "-W" | "-A" | "-D" | "-F" => true,
359 if !wrapper_mode && should_describe_lints() {
364 // this conditional check for the --sysroot flag is there so users can call
365 // `clippy_driver` directly
366 // without having to pass --sysroot or anything
367 let mut args: Vec<String> = orig_args.clone();
368 if !have_sys_root_arg {
369 args.extend(vec!["--sysroot".into(), sys_root]);
372 // this check ensures that dependencies are built but not linted and the final
373 // crate is linted but not built
374 let clippy_enabled = env::var("CLIPPY_TESTS").map_or(false, |val| val == "true")
375 || arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_none();
378 args.extend(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()]);
379 if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
380 args.extend(extra_args.split("__CLIPPY_HACKERY__").filter_map(|s| {
389 let mut clippy = ClippyCallbacks;
390 let mut default = rustc_driver::DefaultCallbacks;
391 let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
392 if clippy_enabled { &mut clippy } else { &mut default };
393 rustc_driver::run_compiler(&args, callbacks, None, None)
395 .and_then(|result| result)