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_driver;
12 extern crate rustc_errors;
13 extern crate rustc_interface;
14 extern crate rustc_middle;
16 use rustc_interface::interface;
17 use rustc_middle::ty::TyCtxt;
18 use rustc_tools_util::VersionInfo;
22 use std::lazy::SyncLazy;
25 use std::path::{Path, PathBuf};
26 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`.
30 fn arg_value<'a, T: Deref<Target = str>>(
33 pred: impl Fn(&str) -> bool,
34 ) -> Option<&'a str> {
35 let mut args = args.iter().map(Deref::deref);
36 while let Some(arg) = args.next() {
37 let mut arg = arg.splitn(2, '=');
38 if arg.next() != Some(find_arg) {
42 match arg.next().or_else(|| args.next()) {
43 Some(v) if pred(v) => return Some(v),
52 let args = &["--bar=bar", "--foobar", "123", "--foo"];
54 assert_eq!(arg_value(&[] as &[&str], "--foobar", |_| true), None);
55 assert_eq!(arg_value(args, "--bar", |_| false), None);
56 assert_eq!(arg_value(args, "--bar", |_| true), Some("bar"));
57 assert_eq!(arg_value(args, "--bar", |p| p == "bar"), Some("bar"));
58 assert_eq!(arg_value(args, "--bar", |p| p == "foo"), None);
59 assert_eq!(arg_value(args, "--foobar", |p| p == "foo"), None);
60 assert_eq!(arg_value(args, "--foobar", |p| p == "123"), Some("123"));
61 assert_eq!(arg_value(args, "--foo", |_| true), None);
64 struct DefaultCallbacks;
65 impl rustc_driver::Callbacks for DefaultCallbacks {}
67 struct ClippyCallbacks;
68 impl rustc_driver::Callbacks for ClippyCallbacks {
69 fn config(&mut self, config: &mut interface::Config) {
70 let previous = config.register_lints.take();
71 config.register_lints = Some(Box::new(move |sess, mut lint_store| {
72 // technically we're ~guaranteed that this is none but might as well call anything that
73 // is there already. Certainly it can't hurt.
74 if let Some(previous) = &previous {
75 (previous)(sess, lint_store);
78 let conf = clippy_lints::read_conf(&[], &sess);
79 clippy_lints::register_plugins(&mut lint_store, &sess, &conf);
80 clippy_lints::register_pre_expansion_lints(&mut lint_store);
81 clippy_lints::register_renamed(&mut lint_store);
84 // FIXME: #4825; This is required, because Clippy lints that are based on MIR have to be
85 // run on the unoptimized MIR. On the other hand this results in some false negatives. If
86 // MIR passes can be enabled / disabled separately, we should figure out, what passes to
88 config.opts.debugging_opts.mir_opt_level = 0;
95 Checks a package to catch common mistakes and improve your Rust code.
98 cargo clippy [options] [--] [<opts>...]
101 -h, --help Print this message
102 --rustc Pass all args to rustc
103 -V, --version Print version info and exit
105 Other options are the same as `cargo check`.
107 To allow or deny a lint from the command line you can use `cargo clippy --`
110 -W --warn OPT Set lint warnings
111 -A --allow OPT Set lint allowed
112 -D --deny OPT Set lint denied
113 -F --forbid OPT Set lint forbidden
115 You can use tool lints to allow or deny lints from your code, eg.:
117 #[allow(clippy::needless_lifetimes)]
122 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust-clippy/issues/new";
124 static ICE_HOOK: SyncLazy<Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static>> =
126 let hook = panic::take_hook();
127 panic::set_hook(Box::new(|info| report_clippy_ice(info, BUG_REPORT_URL)));
131 fn report_clippy_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
132 // Invoke our ICE handler, which prints the actual panic message and optionally a backtrace
135 // Separate the output with an empty line
138 let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
139 rustc_errors::ColorConfig::Auto,
146 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
148 // a .span_bug or .bug call has already printed what
149 // it wants to print.
150 if !info.payload().is::<rustc_errors::ExplicitBug>() {
151 let d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
152 handler.emit_diagnostic(&d);
155 let version_info = rustc_tools_util::get_version_info!();
157 let xs: Vec<Cow<'static, str>> = vec![
158 "the compiler unexpectedly panicked. this is a bug.".into(),
159 format!("we would appreciate a bug report: {}", bug_report_url).into(),
160 format!("Clippy version: {}", version_info).into(),
164 handler.note_without_error(¬e);
167 // If backtraces are enabled, also print the query stack
168 let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
170 let num_frames = if backtrace { None } else { Some(2) };
172 TyCtxt::try_print_query_stack(&handler, num_frames);
175 fn toolchain_path(home: Option<String>, toolchain: Option<String>) -> Option<PathBuf> {
176 home.and_then(|home| {
177 toolchain.map(|toolchain| {
178 let mut path = PathBuf::from(home);
179 path.push("toolchains");
180 path.push(toolchain);
187 rustc_driver::init_rustc_env_logger();
188 SyncLazy::force(&ICE_HOOK);
189 exit(rustc_driver::catch_with_exit_code(move || {
190 let mut orig_args: Vec<String> = env::args().collect();
192 // Get the sysroot, looking from most specific to this invocation to the least:
194 // - runtime environment
196 // - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
197 // - sysroot from rustc in the path
198 // - compile-time environment
200 // - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
201 let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
202 let have_sys_root_arg = sys_root_arg.is_some();
203 let sys_root = sys_root_arg
205 .or_else(|| std::env::var("SYSROOT").ok().map(PathBuf::from))
207 let home = std::env::var("RUSTUP_HOME")
208 .or_else(|_| std::env::var("MULTIRUST_HOME"))
210 let toolchain = std::env::var("RUSTUP_TOOLCHAIN")
211 .or_else(|_| std::env::var("MULTIRUST_TOOLCHAIN"))
213 toolchain_path(home, toolchain)
216 Command::new("rustc")
221 .and_then(|out| String::from_utf8(out.stdout).ok())
222 .map(|s| PathBuf::from(s.trim()))
224 .or_else(|| option_env!("SYSROOT").map(PathBuf::from))
226 let home = option_env!("RUSTUP_HOME")
227 .or(option_env!("MULTIRUST_HOME"))
228 .map(ToString::to_string);
229 let toolchain = option_env!("RUSTUP_TOOLCHAIN")
230 .or(option_env!("MULTIRUST_TOOLCHAIN"))
231 .map(ToString::to_string);
232 toolchain_path(home, toolchain)
234 .map(|pb| pb.to_string_lossy().to_string())
235 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
237 // make "clippy-driver --rustc" work like a subcommand that passes further args to "rustc"
238 // for example `clippy-driver --rustc --version` will print the rustc version that clippy-driver
240 if let Some(pos) = orig_args.iter().position(|arg| arg == "--rustc") {
241 orig_args.remove(pos);
242 orig_args[0] = "rustc".to_string();
244 // if we call "rustc", we need to pass --sysroot here as well
245 let mut args: Vec<String> = orig_args.clone();
246 if !have_sys_root_arg {
247 args.extend(vec!["--sysroot".into(), sys_root]);
250 return rustc_driver::RunCompiler::new(&args, &mut DefaultCallbacks).run();
253 if orig_args.iter().any(|a| a == "--version" || a == "-V") {
254 let version_info = rustc_tools_util::get_version_info!();
255 println!("{}", version_info);
259 // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
260 // We're invoking the compiler programmatically, so we ignore this/
262 orig_args.get(1).map(Path::new).and_then(Path::file_stem) == Some("rustc".as_ref());
265 // we still want to be able to invoke it normally though
270 && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1)
276 // this conditional check for the --sysroot flag is there so users can call
277 // `clippy_driver` directly
278 // without having to pass --sysroot or anything
279 let mut args: Vec<String> = orig_args.clone();
280 if !have_sys_root_arg {
281 args.extend(vec!["--sysroot".into(), sys_root]);
284 // this check ensures that dependencies are built but not linted and the final
285 // crate is linted but not built
286 let clippy_enabled = env::var("CLIPPY_TESTS").map_or(false, |val| val == "true")
287 || arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_none();
290 args.extend(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()]);
291 if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
294 .split("__CLIPPY_HACKERY__")
295 .filter_map(|s| if s.is_empty() { None } else { Some(s.to_string()) }),
299 let mut clippy = ClippyCallbacks;
300 let mut default = DefaultCallbacks;
301 let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
302 if clippy_enabled { &mut clippy } else { &mut default };
303 rustc_driver::RunCompiler::new(&args, callbacks).run()