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 #![warn(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_session;
15 extern crate rustc_span;
17 use rustc_interface::interface;
18 use rustc_session::parse::ParseSess;
19 use rustc_span::symbol::Symbol;
20 use rustc_tools_util::VersionInfo;
24 use std::lazy::SyncLazy;
27 use std::path::{Path, PathBuf};
28 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 fn track_clippy_args(parse_sess: &mut ParseSess, args_env_var: &Option<String>) {
67 parse_sess.env_depinfo.get_mut().insert((
68 Symbol::intern("CLIPPY_ARGS"),
69 args_env_var.as_deref().map(Symbol::intern),
73 struct DefaultCallbacks;
74 impl rustc_driver::Callbacks for DefaultCallbacks {}
76 /// This is different from `DefaultCallbacks` that it will inform Cargo to track the value of
77 /// `CLIPPY_ARGS` environment variable.
78 struct RustcCallbacks {
79 clippy_args_var: Option<String>,
82 impl rustc_driver::Callbacks for RustcCallbacks {
83 fn config(&mut self, config: &mut interface::Config) {
84 let clippy_args_var = self.clippy_args_var.take();
85 config.parse_sess_created = Some(Box::new(move |parse_sess| {
86 track_clippy_args(parse_sess, &clippy_args_var);
91 struct ClippyCallbacks {
92 clippy_args_var: Option<String>,
95 impl rustc_driver::Callbacks for ClippyCallbacks {
96 fn config(&mut self, config: &mut interface::Config) {
97 let previous = config.register_lints.take();
98 let clippy_args_var = self.clippy_args_var.take();
99 config.parse_sess_created = Some(Box::new(move |parse_sess| {
100 track_clippy_args(parse_sess, &clippy_args_var);
102 config.register_lints = Some(Box::new(move |sess, lint_store| {
103 // technically we're ~guaranteed that this is none but might as well call anything that
104 // is there already. Certainly it can't hurt.
105 if let Some(previous) = &previous {
106 (previous)(sess, lint_store);
109 let conf = clippy_lints::read_conf(sess);
110 clippy_lints::register_plugins(lint_store, sess, &conf);
111 clippy_lints::register_pre_expansion_lints(lint_store, sess, &conf);
112 clippy_lints::register_renamed(lint_store);
115 // FIXME: #4825; This is required, because Clippy lints that are based on MIR have to be
116 // run on the unoptimized MIR. On the other hand this results in some false negatives. If
117 // MIR passes can be enabled / disabled separately, we should figure out, what passes to
119 config.opts.debugging_opts.mir_opt_level = Some(0);
126 Checks a package to catch common mistakes and improve your Rust code.
129 cargo clippy [options] [--] [<opts>...]
132 -h, --help Print this message
133 --rustc Pass all args to rustc
134 -V, --version Print version info and exit
136 Other options are the same as `cargo check`.
138 To allow or deny a lint from the command line you can use `cargo clippy --`
141 -W --warn OPT Set lint warnings
142 -A --allow OPT Set lint allowed
143 -D --deny OPT Set lint denied
144 -F --forbid OPT Set lint forbidden
146 You can use tool lints to allow or deny lints from your code, eg.:
148 #[allow(clippy::needless_lifetimes)]
153 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust-clippy/issues/new";
155 static ICE_HOOK: SyncLazy<Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static>> = SyncLazy::new(|| {
156 let hook = panic::take_hook();
157 panic::set_hook(Box::new(|info| report_clippy_ice(info, BUG_REPORT_URL)));
161 fn report_clippy_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
162 // Invoke our ICE handler, which prints the actual panic message and optionally a backtrace
165 // Separate the output with an empty line
168 let fallback_bundle = rustc_errors::fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false);
169 let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
170 rustc_errors::ColorConfig::Auto,
179 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
181 // a .span_bug or .bug call has already printed what
182 // it wants to print.
183 if !info.payload().is::<rustc_errors::ExplicitBug>() {
184 let mut d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
185 handler.emit_diagnostic(&mut d);
188 let version_info = rustc_tools_util::get_version_info!();
190 let xs: Vec<Cow<'static, str>> = vec![
191 "the compiler unexpectedly panicked. this is a bug.".into(),
192 format!("we would appreciate a bug report: {}", bug_report_url).into(),
193 format!("Clippy version: {}", version_info).into(),
197 handler.note_without_error(note.as_ref());
200 // If backtraces are enabled, also print the query stack
201 let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
203 let num_frames = if backtrace { None } else { Some(2) };
205 interface::try_print_query_stack(&handler, num_frames);
208 fn toolchain_path(home: Option<String>, toolchain: Option<String>) -> Option<PathBuf> {
209 home.and_then(|home| {
210 toolchain.map(|toolchain| {
211 let mut path = PathBuf::from(home);
212 path.push("toolchains");
213 path.push(toolchain);
219 #[allow(clippy::too_many_lines)]
221 rustc_driver::init_rustc_env_logger();
222 SyncLazy::force(&ICE_HOOK);
223 exit(rustc_driver::catch_with_exit_code(move || {
224 let mut orig_args: Vec<String> = env::args().collect();
226 // Get the sysroot, looking from most specific to this invocation to the least:
228 // - runtime environment
230 // - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
231 // - sysroot from rustc in the path
232 // - compile-time environment
234 // - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
235 let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
236 let have_sys_root_arg = sys_root_arg.is_some();
237 let sys_root = sys_root_arg
239 .or_else(|| std::env::var("SYSROOT").ok().map(PathBuf::from))
241 let home = std::env::var("RUSTUP_HOME")
242 .or_else(|_| std::env::var("MULTIRUST_HOME"))
244 let toolchain = std::env::var("RUSTUP_TOOLCHAIN")
245 .or_else(|_| std::env::var("MULTIRUST_TOOLCHAIN"))
247 toolchain_path(home, toolchain)
250 Command::new("rustc")
255 .and_then(|out| String::from_utf8(out.stdout).ok())
256 .map(|s| PathBuf::from(s.trim()))
258 .or_else(|| option_env!("SYSROOT").map(PathBuf::from))
260 let home = option_env!("RUSTUP_HOME")
261 .or(option_env!("MULTIRUST_HOME"))
262 .map(ToString::to_string);
263 let toolchain = option_env!("RUSTUP_TOOLCHAIN")
264 .or(option_env!("MULTIRUST_TOOLCHAIN"))
265 .map(ToString::to_string);
266 toolchain_path(home, toolchain)
268 .map(|pb| pb.to_string_lossy().to_string())
269 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
271 // make "clippy-driver --rustc" work like a subcommand that passes further args to "rustc"
272 // for example `clippy-driver --rustc --version` will print the rustc version that clippy-driver
274 if let Some(pos) = orig_args.iter().position(|arg| arg == "--rustc") {
275 orig_args.remove(pos);
276 orig_args[0] = "rustc".to_string();
278 // if we call "rustc", we need to pass --sysroot here as well
279 let mut args: Vec<String> = orig_args.clone();
280 if !have_sys_root_arg {
281 args.extend(vec!["--sysroot".into(), sys_root]);
284 return rustc_driver::RunCompiler::new(&args, &mut DefaultCallbacks).run();
287 if orig_args.iter().any(|a| a == "--version" || a == "-V") {
288 let version_info = rustc_tools_util::get_version_info!();
289 println!("{}", version_info);
293 // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
294 // We're invoking the compiler programmatically, so we ignore this/
295 let wrapper_mode = orig_args.get(1).map(Path::new).and_then(Path::file_stem) == Some("rustc".as_ref());
298 // we still want to be able to invoke it normally though
302 if !wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
307 // this conditional check for the --sysroot flag is there so users can call
308 // `clippy_driver` directly
309 // without having to pass --sysroot or anything
310 let mut args: Vec<String> = orig_args.clone();
311 if !have_sys_root_arg {
312 args.extend(vec!["--sysroot".into(), sys_root]);
315 let mut no_deps = false;
316 let clippy_args_var = env::var("CLIPPY_ARGS").ok();
317 let clippy_args = clippy_args_var
320 .split("__CLIPPY_HACKERY__")
321 .filter_map(|s| match s {
327 _ => Some(s.to_string()),
329 .chain(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()])
330 .collect::<Vec<String>>();
332 // We enable Clippy if one of the following conditions is met
333 // - IF Clippy is run on its test suite OR
334 // - IF Clippy is run on the main crate, not on deps (`!cap_lints_allow`) THEN
335 // - IF `--no-deps` is not set (`!no_deps`) OR
336 // - IF `--no-deps` is set and Clippy is run on the specified primary package
337 let cap_lints_allow = arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_some();
338 let in_primary_package = env::var("CARGO_PRIMARY_PACKAGE").is_ok();
340 let clippy_enabled = !cap_lints_allow && (!no_deps || in_primary_package);
342 args.extend(clippy_args);
346 rustc_driver::RunCompiler::new(&args, &mut ClippyCallbacks { clippy_args_var }).run()
348 rustc_driver::RunCompiler::new(&args, &mut RustcCallbacks { clippy_args_var }).run()