1 #![feature(rustc_private)]
3 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
4 // warn on lints, that are included in `rust-lang/rust`s bootstrap
5 #![warn(rust_2018_idioms, unused_lifetimes)]
6 // warn on rustc internal lints
7 #![deny(rustc::internal)]
9 // FIXME: switch to something more ergonomic here, once available.
10 // (Currently there is no way to opt into sysroot crates without `extern crate`.)
11 extern crate rustc_data_structures;
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;
23 use std::lazy::SyncLazy;
26 use std::path::{Path, PathBuf};
27 use std::process::{exit, Command};
31 /// If a command-line option matches `find_arg`, then apply the predicate `pred` on its value. If
32 /// true, then return it. The parameter is assumed to be either `--arg=value` or `--arg value`.
33 fn arg_value<'a, T: Deref<Target = str>>(
36 pred: impl Fn(&str) -> bool,
37 ) -> Option<&'a str> {
38 let mut args = args.iter().map(Deref::deref);
39 while let Some(arg) = args.next() {
40 let mut arg = arg.splitn(2, '=');
41 if arg.next() != Some(find_arg) {
45 match arg.next().or_else(|| args.next()) {
46 Some(v) if pred(v) => return Some(v),
55 let args = &["--bar=bar", "--foobar", "123", "--foo"];
57 assert_eq!(arg_value(&[] as &[&str], "--foobar", |_| true), None);
58 assert_eq!(arg_value(args, "--bar", |_| false), None);
59 assert_eq!(arg_value(args, "--bar", |_| true), Some("bar"));
60 assert_eq!(arg_value(args, "--bar", |p| p == "bar"), Some("bar"));
61 assert_eq!(arg_value(args, "--bar", |p| p == "foo"), None);
62 assert_eq!(arg_value(args, "--foobar", |p| p == "foo"), None);
63 assert_eq!(arg_value(args, "--foobar", |p| p == "123"), Some("123"));
64 assert_eq!(arg_value(args, "--foo", |_| true), None);
67 struct DefaultCallbacks;
68 impl rustc_driver::Callbacks for DefaultCallbacks {}
70 struct ClippyCallbacks;
71 impl rustc_driver::Callbacks for ClippyCallbacks {
72 fn config(&mut self, config: &mut interface::Config) {
73 let previous = config.register_lints.take();
74 config.register_lints = Some(Box::new(move |sess, mut lint_store| {
75 // technically we're ~guaranteed that this is none but might as well call anything that
76 // is there already. Certainly it can't hurt.
77 if let Some(previous) = &previous {
78 (previous)(sess, lint_store);
81 let conf = clippy_lints::read_conf(&[], &sess);
82 clippy_lints::register_plugins(&mut lint_store, &sess, &conf);
83 clippy_lints::register_pre_expansion_lints(&mut lint_store);
84 clippy_lints::register_renamed(&mut lint_store);
87 // FIXME: #4825; This is required, because Clippy lints that are based on MIR have to be
88 // run on the unoptimized MIR. On the other hand this results in some false negatives. If
89 // MIR passes can be enabled / disabled separately, we should figure out, what passes to
91 config.opts.debugging_opts.mir_opt_level = 0;
95 #[allow(clippy::find_map, clippy::filter_map)]
97 use lintlist::{Level, Lint, ALL_LINTS, LINT_LEVELS};
98 use rustc_data_structures::fx::FxHashSet;
102 Available lint options:
103 -W <foo> Warn about <foo>
106 -F <foo> Forbid <foo> (deny <foo> and all attempts to override)
111 let lint_level = |lint: &Lint| {
114 .find(|level_mapping| level_mapping.0 == lint.group)
115 .map(|(_, level)| match level {
116 Level::Allow => "allow",
117 Level::Warn => "warn",
118 Level::Deny => "deny",
123 let mut lints: Vec<_> = ALL_LINTS.iter().collect();
124 // The sort doesn't case-fold but it's doubtful we care.
125 lints.sort_by_cached_key(|x: &&Lint| (lint_level(x), x.name));
127 let max_lint_name_len = lints
129 .map(|lint| lint.name.len())
130 .map(|len| len + "clippy::".len())
134 let padded = |x: &str| {
135 let mut s = " ".repeat(max_lint_name_len - x.chars().count());
140 let scoped = |x: &str| format!("clippy::{}", x);
142 let lint_groups: FxHashSet<_> = lints.iter().map(|lint| lint.group).collect();
144 println!("Lint checks provided by clippy:\n");
145 println!(" {} {:7.7} meaning", padded("name"), "default");
146 println!(" {} {:7.7} -------", padded("----"), "-------");
148 let print_lints = |lints: &[&Lint]| {
150 let name = lint.name.replace("_", "-");
153 padded(&scoped(&name)),
163 let max_group_name_len = std::cmp::max(
167 .map(|group| group.len())
168 .map(|len| len + "clippy::".len())
173 let padded_group = |x: &str| {
174 let mut s = " ".repeat(max_group_name_len - x.chars().count());
179 println!("Lint groups provided by clippy:\n");
180 println!(" {} sub-lints", padded_group("name"));
181 println!(" {} ---------", padded_group("----"));
182 println!(" {} the set of all clippy lints", padded_group("clippy::all"));
184 let print_lint_groups = || {
185 for group in lint_groups {
186 let name = group.to_lowercase().replace("_", "-");
189 .filter(|&lint| lint.group == group)
190 .map(|lint| lint.name)
191 .map(|name| name.replace("_", "-"))
192 .collect::<Vec<String>>()
194 println!(" {} {}", padded_group(&scoped(&name)), desc);
205 Checks a package to catch common mistakes and improve your Rust code.
208 cargo clippy [options] [--] [<opts>...]
211 -h, --help Print this message
212 --rustc Pass all args to rustc
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";
234 static ICE_HOOK: SyncLazy<Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static>> = SyncLazy::new(|| {
235 let hook = panic::take_hook();
236 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");
279 let num_frames = if backtrace { None } else { Some(2) };
281 TyCtxt::try_print_query_stack(&handler, num_frames);
284 fn toolchain_path(home: Option<String>, toolchain: Option<String>) -> Option<PathBuf> {
285 home.and_then(|home| {
286 toolchain.map(|toolchain| {
287 let mut path = PathBuf::from(home);
288 path.push("toolchains");
289 path.push(toolchain);
296 rustc_driver::init_rustc_env_logger();
297 SyncLazy::force(&ICE_HOOK);
298 exit(rustc_driver::catch_with_exit_code(move || {
299 let mut orig_args: Vec<String> = env::args().collect();
301 // Get the sysroot, looking from most specific to this invocation to the least:
303 // - runtime environment
305 // - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
306 // - sysroot from rustc in the path
307 // - compile-time environment
309 // - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
310 let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
311 let have_sys_root_arg = sys_root_arg.is_some();
312 let sys_root = sys_root_arg
314 .or_else(|| std::env::var("SYSROOT").ok().map(PathBuf::from))
316 let home = std::env::var("RUSTUP_HOME")
317 .or_else(|_| std::env::var("MULTIRUST_HOME"))
319 let toolchain = std::env::var("RUSTUP_TOOLCHAIN")
320 .or_else(|_| std::env::var("MULTIRUST_TOOLCHAIN"))
322 toolchain_path(home, toolchain)
325 Command::new("rustc")
330 .and_then(|out| String::from_utf8(out.stdout).ok())
331 .map(|s| PathBuf::from(s.trim()))
333 .or_else(|| option_env!("SYSROOT").map(PathBuf::from))
335 let home = option_env!("RUSTUP_HOME")
336 .or(option_env!("MULTIRUST_HOME"))
337 .map(ToString::to_string);
338 let toolchain = option_env!("RUSTUP_TOOLCHAIN")
339 .or(option_env!("MULTIRUST_TOOLCHAIN"))
340 .map(ToString::to_string);
341 toolchain_path(home, toolchain)
343 .map(|pb| pb.to_string_lossy().to_string())
344 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
346 // make "clippy-driver --rustc" work like a subcommand that passes further args to "rustc"
347 // for example `clippy-driver --rustc --version` will print the rustc version that clippy-driver
349 if let Some(pos) = orig_args.iter().position(|arg| arg == "--rustc") {
350 orig_args.remove(pos);
351 orig_args[0] = "rustc".to_string();
353 // if we call "rustc", we need to pass --sysroot here as well
354 let mut args: Vec<String> = orig_args.clone();
355 if !have_sys_root_arg {
356 args.extend(vec!["--sysroot".into(), sys_root]);
359 return rustc_driver::RunCompiler::new(&args, &mut DefaultCallbacks).run();
362 if orig_args.iter().any(|a| a == "--version" || a == "-V") {
363 let version_info = rustc_tools_util::get_version_info!();
364 println!("{}", version_info);
368 // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
369 // We're invoking the compiler programmatically, so we ignore this/
370 let wrapper_mode = orig_args.get(1).map(Path::new).and_then(Path::file_stem) == Some("rustc".as_ref());
373 // we still want to be able to invoke it normally though
377 if !wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
382 let should_describe_lints = || {
383 let args: Vec<_> = env::args().collect();
385 .any(|args| args[1] == "help" && matches!(args[0].as_str(), "-W" | "-A" | "-D" | "-F"))
388 if !wrapper_mode && should_describe_lints() {
393 // this conditional check for the --sysroot flag is there so users can call
394 // `clippy_driver` directly
395 // without having to pass --sysroot or anything
396 let mut args: Vec<String> = orig_args.clone();
397 if !have_sys_root_arg {
398 args.extend(vec!["--sysroot".into(), sys_root]);
401 // this check ensures that dependencies are built but not linted and the final
402 // crate is linted but not built
403 let clippy_enabled = env::var("CLIPPY_TESTS").map_or(false, |val| val == "true")
404 || arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_none();
407 args.extend(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()]);
408 if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
409 args.extend(extra_args.split("__CLIPPY_HACKERY__").filter_map(|s| {
418 let mut clippy = ClippyCallbacks;
419 let mut default = DefaultCallbacks;
420 let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
421 if clippy_enabled { &mut clippy } else { &mut default };
422 rustc_driver::RunCompiler::new(&args, callbacks).run()