1 #![feature(rustc_private)]
2 #![feature(let_chains)]
4 #![feature(lint_reasons)]
5 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
6 // warn on lints, that are included in `rust-lang/rust`s bootstrap
7 #![warn(rust_2018_idioms, unused_lifetimes)]
8 // warn on rustc internal lints
9 #![warn(rustc::internal)]
11 // FIXME: switch to something more ergonomic here, once available.
12 // (Currently there is no way to opt into sysroot crates without `extern crate`.)
13 extern crate rustc_driver;
14 extern crate rustc_errors;
15 extern crate rustc_interface;
16 extern crate rustc_session;
17 extern crate rustc_span;
19 use rustc_interface::interface;
20 use rustc_session::parse::ParseSess;
21 use rustc_span::symbol::Symbol;
28 use std::process::exit;
29 use std::sync::LazyLock;
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, "--foobar", |p| p.contains("12")), Some("123"));
65 assert_eq!(arg_value(args, "--foo", |_| true), None);
68 fn track_clippy_args(parse_sess: &mut ParseSess, args_env_var: &Option<String>) {
69 parse_sess.env_depinfo.get_mut().insert((
70 Symbol::intern("CLIPPY_ARGS"),
71 args_env_var.as_deref().map(Symbol::intern),
75 /// Track files that may be accessed at runtime in `file_depinfo` so that cargo will re-run clippy
76 /// when any of them are modified
77 fn track_files(parse_sess: &mut ParseSess, conf_path_string: Option<String>) {
78 let file_depinfo = parse_sess.file_depinfo.get_mut();
80 // Used by `clippy::cargo` lints and to determine the MSRV. `cargo clippy` executes `clippy-driver`
81 // with the current directory set to `CARGO_MANIFEST_DIR` so a relative path is fine
82 if Path::new("Cargo.toml").exists() {
83 file_depinfo.insert(Symbol::intern("Cargo.toml"));
87 if let Some(path) = conf_path_string {
88 file_depinfo.insert(Symbol::intern(&path));
91 // During development track the `clippy-driver` executable so that cargo will re-run clippy whenever
94 clippy::collapsible_if,
95 reason = "Due to a bug in let_chains this if statement can't be collapsed"
97 if cfg!(debug_assertions) {
98 if let Ok(current_exe) = env::current_exe()
99 && let Some(current_exe) = current_exe.to_str()
101 file_depinfo.insert(Symbol::intern(current_exe));
106 struct DefaultCallbacks;
107 impl rustc_driver::Callbacks for DefaultCallbacks {}
109 /// This is different from `DefaultCallbacks` that it will inform Cargo to track the value of
110 /// `CLIPPY_ARGS` environment variable.
111 struct RustcCallbacks {
112 clippy_args_var: Option<String>,
115 impl rustc_driver::Callbacks for RustcCallbacks {
116 fn config(&mut self, config: &mut interface::Config) {
117 let clippy_args_var = self.clippy_args_var.take();
118 config.parse_sess_created = Some(Box::new(move |parse_sess| {
119 track_clippy_args(parse_sess, &clippy_args_var);
124 struct ClippyCallbacks {
125 clippy_args_var: Option<String>,
128 impl rustc_driver::Callbacks for ClippyCallbacks {
129 // JUSTIFICATION: necessary in clippy driver to set `mir_opt_level`
130 #[allow(rustc::bad_opt_access)]
131 fn config(&mut self, config: &mut interface::Config) {
132 let conf_path = clippy_lints::lookup_conf_file();
133 let conf_path_string = if let Ok(Some(path)) = &conf_path {
134 path.to_str().map(String::from)
139 let previous = config.register_lints.take();
140 let clippy_args_var = self.clippy_args_var.take();
141 config.parse_sess_created = Some(Box::new(move |parse_sess| {
142 track_clippy_args(parse_sess, &clippy_args_var);
143 track_files(parse_sess, conf_path_string);
145 config.register_lints = Some(Box::new(move |sess, lint_store| {
146 // technically we're ~guaranteed that this is none but might as well call anything that
147 // is there already. Certainly it can't hurt.
148 if let Some(previous) = &previous {
149 (previous)(sess, lint_store);
152 let conf = clippy_lints::read_conf(sess, &conf_path);
153 clippy_lints::register_plugins(lint_store, sess, &conf);
154 clippy_lints::register_pre_expansion_lints(lint_store, sess, &conf);
155 clippy_lints::register_renamed(lint_store);
158 // FIXME: #4825; This is required, because Clippy lints that are based on MIR have to be
159 // run on the unoptimized MIR. On the other hand this results in some false negatives. If
160 // MIR passes can be enabled / disabled separately, we should figure out, what passes to
162 config.opts.unstable_opts.mir_opt_level = Some(0);
169 Checks a package to catch common mistakes and improve your Rust code.
172 cargo clippy [options] [--] [<opts>...]
175 -h, --help Print this message
176 --rustc Pass all args to rustc
177 -V, --version Print version info and exit
179 Other options are the same as `cargo check`.
181 To allow or deny a lint from the command line you can use `cargo clippy --`
184 -W --warn OPT Set lint warnings
185 -A --allow OPT Set lint allowed
186 -D --deny OPT Set lint denied
187 -F --forbid OPT Set lint forbidden
189 You can use tool lints to allow or deny lints from your code, eg.:
191 #[allow(clippy::needless_lifetimes)]
196 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust-clippy/issues/new";
198 type PanicCallback = dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static;
199 static ICE_HOOK: LazyLock<Box<PanicCallback>> = LazyLock::new(|| {
200 let hook = panic::take_hook();
201 panic::set_hook(Box::new(|info| report_clippy_ice(info, BUG_REPORT_URL)));
205 fn report_clippy_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
206 // Invoke our ICE handler, which prints the actual panic message and optionally a backtrace
209 // Separate the output with an empty line
212 let fallback_bundle = rustc_errors::fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false);
213 let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
214 rustc_errors::ColorConfig::Auto,
224 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
226 // a .span_bug or .bug call has already printed what
227 // it wants to print.
228 if !info.payload().is::<rustc_errors::ExplicitBug>() {
229 let mut d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
230 handler.emit_diagnostic(&mut d);
233 let version_info = rustc_tools_util::get_version_info!();
235 let xs: Vec<Cow<'static, str>> = vec![
236 "the compiler unexpectedly panicked. this is a bug.".into(),
237 format!("we would appreciate a bug report: {bug_report_url}").into(),
238 format!("Clippy version: {version_info}").into(),
242 handler.note_without_error(note.as_ref());
245 // If backtraces are enabled, also print the query stack
246 let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
248 let num_frames = if backtrace { None } else { Some(2) };
250 interface::try_print_query_stack(&handler, num_frames);
253 #[allow(clippy::too_many_lines)]
255 rustc_driver::init_rustc_env_logger();
256 LazyLock::force(&ICE_HOOK);
257 exit(rustc_driver::catch_with_exit_code(move || {
258 let mut orig_args: Vec<String> = env::args().collect();
260 let sys_root_env = std::env::var("SYSROOT").ok();
261 let pass_sysroot_env_if_given = |args: &mut Vec<String>, sys_root_env| {
262 if let Some(sys_root) = sys_root_env {
263 args.extend(vec!["--sysroot".into(), sys_root]);
267 // make "clippy-driver --rustc" work like a subcommand that passes further args to "rustc"
268 // for example `clippy-driver --rustc --version` will print the rustc version that clippy-driver
270 if let Some(pos) = orig_args.iter().position(|arg| arg == "--rustc") {
271 orig_args.remove(pos);
272 orig_args[0] = "rustc".to_string();
274 let mut args: Vec<String> = orig_args.clone();
275 pass_sysroot_env_if_given(&mut args, sys_root_env);
277 return rustc_driver::RunCompiler::new(&args, &mut DefaultCallbacks).run();
280 if orig_args.iter().any(|a| a == "--version" || a == "-V") {
281 let version_info = rustc_tools_util::get_version_info!();
282 println!("{version_info}");
286 // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
287 // We're invoking the compiler programmatically, so we ignore this/
288 let wrapper_mode = orig_args.get(1).map(Path::new).and_then(Path::file_stem) == Some("rustc".as_ref());
291 // we still want to be able to invoke it normally though
295 if !wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
300 let mut args: Vec<String> = orig_args.clone();
301 pass_sysroot_env_if_given(&mut args, sys_root_env);
303 let mut no_deps = false;
304 let clippy_args_var = env::var("CLIPPY_ARGS").ok();
305 let clippy_args = clippy_args_var
308 .split("__CLIPPY_HACKERY__")
309 .filter_map(|s| match s {
315 _ => Some(s.to_string()),
317 .chain(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()])
318 .collect::<Vec<String>>();
320 // We enable Clippy if one of the following conditions is met
321 // - IF Clippy is run on its test suite OR
322 // - IF Clippy is run on the main crate, not on deps (`!cap_lints_allow`) THEN
323 // - IF `--no-deps` is not set (`!no_deps`) OR
324 // - IF `--no-deps` is set and Clippy is run on the specified primary package
325 let cap_lints_allow = arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_some()
326 && arg_value(&orig_args, "--force-warn", |val| val.contains("clippy::")).is_none();
327 let in_primary_package = env::var("CARGO_PRIMARY_PACKAGE").is_ok();
329 let clippy_enabled = !cap_lints_allow && (!no_deps || in_primary_package);
331 args.extend(clippy_args);
332 rustc_driver::RunCompiler::new(&args, &mut ClippyCallbacks { clippy_args_var }).run()
334 rustc_driver::RunCompiler::new(&args, &mut RustcCallbacks { clippy_args_var }).run()