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_data_structures;
12 #[allow(unused_extern_crates)]
13 extern crate rustc_driver;
14 #[allow(unused_extern_crates)]
15 extern crate rustc_errors;
16 #[allow(unused_extern_crates)]
17 extern crate rustc_interface;
18 #[allow(unused_extern_crates)]
19 extern crate rustc_middle;
21 use rustc_interface::interface;
22 use rustc_middle::ty::TyCtxt;
23 use rustc_tools_util::VersionInfo;
25 use lazy_static::lazy_static;
30 use std::path::{Path, PathBuf};
31 use std::process::{exit, Command};
35 /// If a command-line option matches `find_arg`, then apply the predicate `pred` on its value. If
36 /// true, then return it. The parameter is assumed to be either `--arg=value` or `--arg value`.
37 fn arg_value<'a, T: Deref<Target = str>>(
40 pred: impl Fn(&str) -> bool,
41 ) -> Option<&'a str> {
42 let mut args = args.iter().map(Deref::deref);
43 while let Some(arg) = args.next() {
44 let mut arg = arg.splitn(2, '=');
45 if arg.next() != Some(find_arg) {
49 match arg.next().or_else(|| args.next()) {
50 Some(v) if pred(v) => return Some(v),
59 let args = &["--bar=bar", "--foobar", "123", "--foo"];
61 assert_eq!(arg_value(&[] as &[&str], "--foobar", |_| true), None);
62 assert_eq!(arg_value(args, "--bar", |_| false), None);
63 assert_eq!(arg_value(args, "--bar", |_| true), Some("bar"));
64 assert_eq!(arg_value(args, "--bar", |p| p == "bar"), Some("bar"));
65 assert_eq!(arg_value(args, "--bar", |p| p == "foo"), None);
66 assert_eq!(arg_value(args, "--foobar", |p| p == "foo"), None);
67 assert_eq!(arg_value(args, "--foobar", |p| p == "123"), Some("123"));
68 assert_eq!(arg_value(args, "--foo", |_| true), None);
71 struct DefaultCallbacks;
72 impl rustc_driver::Callbacks for DefaultCallbacks {}
74 struct ClippyCallbacks;
75 impl rustc_driver::Callbacks for ClippyCallbacks {
76 fn config(&mut self, config: &mut interface::Config) {
77 let previous = config.register_lints.take();
78 config.register_lints = Some(Box::new(move |sess, mut lint_store| {
79 // technically we're ~guaranteed that this is none but might as well call anything that
80 // is there already. Certainly it can't hurt.
81 if let Some(previous) = &previous {
82 (previous)(sess, lint_store);
85 let conf = clippy_lints::read_conf(&[], &sess);
86 clippy_lints::register_plugins(&mut lint_store, &sess, &conf);
87 clippy_lints::register_pre_expansion_lints(&mut lint_store);
88 clippy_lints::register_renamed(&mut lint_store);
91 // FIXME: #4825; This is required, because Clippy lints that are based on MIR have to be
92 // run on the unoptimized MIR. On the other hand this results in some false negatives. If
93 // MIR passes can be enabled / disabled separately, we should figure out, what passes to
95 config.opts.debugging_opts.mir_opt_level = 0;
99 #[allow(clippy::find_map, clippy::filter_map)]
100 fn describe_lints() {
101 use lintlist::{Level, Lint, ALL_LINTS, LINT_LEVELS};
102 use rustc_data_structures::fx::FxHashSet;
106 Available lint options:
107 -W <foo> Warn about <foo>
110 -F <foo> Forbid <foo> (deny <foo> and all attempts to override)
115 let lint_level = |lint: &Lint| {
118 .find(|level_mapping| level_mapping.0 == lint.group)
119 .map(|(_, level)| match level {
120 Level::Allow => "allow",
121 Level::Warn => "warn",
122 Level::Deny => "deny",
127 let mut lints: Vec<_> = ALL_LINTS.iter().collect();
128 // The sort doesn't case-fold but it's doubtful we care.
129 lints.sort_by_cached_key(|x: &&Lint| (lint_level(x), x.name));
131 let max_lint_name_len = lints
133 .map(|lint| lint.name.len())
134 .map(|len| len + "clippy::".len())
138 let padded = |x: &str| {
139 let mut s = " ".repeat(max_lint_name_len - x.chars().count());
144 let scoped = |x: &str| format!("clippy::{}", x);
146 let lint_groups: FxHashSet<_> = lints.iter().map(|lint| lint.group).collect();
148 println!("Lint checks provided by clippy:\n");
149 println!(" {} {:7.7} meaning", padded("name"), "default");
150 println!(" {} {:7.7} -------", padded("----"), "-------");
152 let print_lints = |lints: &[&Lint]| {
154 let name = lint.name.replace("_", "-");
157 padded(&scoped(&name)),
167 let max_group_name_len = std::cmp::max(
171 .map(|group| group.len())
172 .map(|len| len + "clippy::".len())
177 let padded_group = |x: &str| {
178 let mut s = " ".repeat(max_group_name_len - x.chars().count());
183 println!("Lint groups provided by clippy:\n");
184 println!(" {} sub-lints", padded_group("name"));
185 println!(" {} ---------", padded_group("----"));
186 println!(" {} the set of all clippy lints", padded_group("clippy::all"));
188 let print_lint_groups = || {
189 for group in lint_groups {
190 let name = group.to_lowercase().replace("_", "-");
193 .filter(|&lint| lint.group == group)
194 .map(|lint| lint.name)
195 .map(|name| name.replace("_", "-"))
196 .collect::<Vec<String>>()
198 println!(" {} {}", padded_group(&scoped(&name)), desc);
209 Checks a package to catch common mistakes and improve your Rust code.
212 cargo clippy [options] [--] [<opts>...]
215 -h, --help Print this message
216 --rustc Pass all args to rustc
217 -V, --version Print version info and exit
219 Other options are the same as `cargo check`.
221 To allow or deny a lint from the command line you can use `cargo clippy --`
224 -W --warn OPT Set lint warnings
225 -A --allow OPT Set lint allowed
226 -D --deny OPT Set lint denied
227 -F --forbid OPT Set lint forbidden
229 You can use tool lints to allow or deny lints from your code, eg.:
231 #[allow(clippy::needless_lifetimes)]
236 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust-clippy/issues/new";
239 static ref ICE_HOOK: Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static> = {
240 let hook = panic::take_hook();
241 panic::set_hook(Box::new(|info| report_clippy_ice(info, BUG_REPORT_URL)));
246 fn report_clippy_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
247 // Invoke our ICE handler, which prints the actual panic message and optionally a backtrace
250 // Separate the output with an empty line
253 let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
254 rustc_errors::ColorConfig::Auto,
261 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
263 // a .span_bug or .bug call has already printed what
264 // it wants to print.
265 if !info.payload().is::<rustc_errors::ExplicitBug>() {
266 let d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
267 handler.emit_diagnostic(&d);
270 let version_info = rustc_tools_util::get_version_info!();
272 let xs: Vec<Cow<'static, str>> = vec![
273 "the compiler unexpectedly panicked. this is a bug.".into(),
274 format!("we would appreciate a bug report: {}", bug_report_url).into(),
275 format!("Clippy version: {}", version_info).into(),
279 handler.note_without_error(¬e);
282 // If backtraces are enabled, also print the query stack
283 let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
286 TyCtxt::try_print_query_stack(&handler);
290 fn toolchain_path(home: Option<String>, toolchain: Option<String>) -> Option<PathBuf> {
291 home.and_then(|home| {
292 toolchain.map(|toolchain| {
293 let mut path = PathBuf::from(home);
294 path.push("toolchains");
295 path.push(toolchain);
302 rustc_driver::init_rustc_env_logger();
303 lazy_static::initialize(&ICE_HOOK);
304 exit(rustc_driver::catch_with_exit_code(move || {
305 let mut orig_args: Vec<String> = env::args().collect();
307 // Get the sysroot, looking from most specific to this invocation to the least:
309 // - runtime environment
311 // - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
312 // - sysroot from rustc in the path
313 // - compile-time environment
315 // - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
316 let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
317 let have_sys_root_arg = sys_root_arg.is_some();
318 let sys_root = sys_root_arg
320 .or_else(|| std::env::var("SYSROOT").ok().map(PathBuf::from))
322 let home = std::env::var("RUSTUP_HOME")
323 .or_else(|_| std::env::var("MULTIRUST_HOME"))
325 let toolchain = std::env::var("RUSTUP_TOOLCHAIN")
326 .or_else(|_| std::env::var("MULTIRUST_TOOLCHAIN"))
328 toolchain_path(home, toolchain)
331 Command::new("rustc")
336 .and_then(|out| String::from_utf8(out.stdout).ok())
337 .map(|s| PathBuf::from(s.trim()))
339 .or_else(|| option_env!("SYSROOT").map(PathBuf::from))
341 let home = option_env!("RUSTUP_HOME")
342 .or(option_env!("MULTIRUST_HOME"))
343 .map(ToString::to_string);
344 let toolchain = option_env!("RUSTUP_TOOLCHAIN")
345 .or(option_env!("MULTIRUST_TOOLCHAIN"))
346 .map(ToString::to_string);
347 toolchain_path(home, toolchain)
349 .map(|pb| pb.to_string_lossy().to_string())
350 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
352 // make "clippy-driver --rustc" work like a subcommand that passes further args to "rustc"
353 // for example `clippy-driver --rustc --version` will print the rustc version that clippy-driver
355 if let Some(pos) = orig_args.iter().position(|arg| arg == "--rustc") {
356 orig_args.remove(pos);
357 orig_args[0] = "rustc".to_string();
359 // if we call "rustc", we need to pass --sysroot here as well
360 let mut args: Vec<String> = orig_args.clone();
361 if !have_sys_root_arg {
362 args.extend(vec!["--sysroot".into(), sys_root]);
365 return rustc_driver::run_compiler(&args, &mut DefaultCallbacks, None, None);
368 if orig_args.iter().any(|a| a == "--version" || a == "-V") {
369 let version_info = rustc_tools_util::get_version_info!();
370 println!("{}", version_info);
374 // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
375 // We're invoking the compiler programmatically, so we ignore this/
376 let wrapper_mode = orig_args.get(1).map(Path::new).and_then(Path::file_stem) == Some("rustc".as_ref());
379 // we still want to be able to invoke it normally though
383 if !wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
388 let should_describe_lints = || {
389 let args: Vec<_> = env::args().collect();
390 args.windows(2).any(|args| {
392 && match args[0].as_str() {
393 "-W" | "-A" | "-D" | "-F" => true,
399 if !wrapper_mode && should_describe_lints() {
404 // this conditional check for the --sysroot flag is there so users can call
405 // `clippy_driver` directly
406 // without having to pass --sysroot or anything
407 let mut args: Vec<String> = orig_args.clone();
408 if !have_sys_root_arg {
409 args.extend(vec!["--sysroot".into(), sys_root]);
412 // this check ensures that dependencies are built but not linted and the final
413 // crate is linted but not built
414 let clippy_enabled = env::var("CLIPPY_TESTS").map_or(false, |val| val == "true")
415 || arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_none();
418 args.extend(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()]);
419 if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
420 args.extend(extra_args.split("__CLIPPY_HACKERY__").filter_map(|s| {
429 let mut clippy = ClippyCallbacks;
430 let mut default = DefaultCallbacks;
431 let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
432 if clippy_enabled { &mut clippy } else { &mut default };
433 rustc_driver::run_compiler(&args, callbacks, None, None)