1 #![feature(rustc_private)]
2 #![feature(let_chains)]
4 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
5 // warn on lints, that are included in `rust-lang/rust`s bootstrap
6 #![warn(rust_2018_idioms, unused_lifetimes)]
7 // warn on rustc internal lints
8 #![warn(rustc::internal)]
10 // FIXME: switch to something more ergonomic here, once available.
11 // (Currently there is no way to opt into sysroot crates without `extern crate`.)
12 extern crate rustc_driver;
13 extern crate rustc_errors;
14 extern crate rustc_interface;
15 extern crate rustc_session;
16 extern crate rustc_span;
18 use rustc_interface::interface;
19 use rustc_session::parse::ParseSess;
20 use rustc_span::symbol::Symbol;
21 use rustc_tools_util::VersionInfo;
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
93 if cfg!(debug_assertions)
94 && let Ok(current_exe) = env::current_exe()
95 && let Some(current_exe) = current_exe.to_str()
97 file_depinfo.insert(Symbol::intern(current_exe));
101 struct DefaultCallbacks;
102 impl rustc_driver::Callbacks for DefaultCallbacks {}
104 /// This is different from `DefaultCallbacks` that it will inform Cargo to track the value of
105 /// `CLIPPY_ARGS` environment variable.
106 struct RustcCallbacks {
107 clippy_args_var: Option<String>,
110 impl rustc_driver::Callbacks for RustcCallbacks {
111 fn config(&mut self, config: &mut interface::Config) {
112 let clippy_args_var = self.clippy_args_var.take();
113 config.parse_sess_created = Some(Box::new(move |parse_sess| {
114 track_clippy_args(parse_sess, &clippy_args_var);
119 struct ClippyCallbacks {
120 clippy_args_var: Option<String>,
123 impl rustc_driver::Callbacks for ClippyCallbacks {
124 // JUSTIFICATION: necessary in clippy driver to set `mir_opt_level`
125 #[allow(rustc::bad_opt_access)]
126 fn config(&mut self, config: &mut interface::Config) {
127 let conf_path = clippy_lints::lookup_conf_file();
128 let conf_path_string = if let Ok(Some(path)) = &conf_path {
129 path.to_str().map(String::from)
134 let previous = config.register_lints.take();
135 let clippy_args_var = self.clippy_args_var.take();
136 config.parse_sess_created = Some(Box::new(move |parse_sess| {
137 track_clippy_args(parse_sess, &clippy_args_var);
138 track_files(parse_sess, conf_path_string);
140 config.register_lints = Some(Box::new(move |sess, lint_store| {
141 // technically we're ~guaranteed that this is none but might as well call anything that
142 // is there already. Certainly it can't hurt.
143 if let Some(previous) = &previous {
144 (previous)(sess, lint_store);
147 let conf = clippy_lints::read_conf(sess, &conf_path);
148 clippy_lints::register_plugins(lint_store, sess, &conf);
149 clippy_lints::register_pre_expansion_lints(lint_store, sess, &conf);
150 clippy_lints::register_renamed(lint_store);
153 // FIXME: #4825; This is required, because Clippy lints that are based on MIR have to be
154 // run on the unoptimized MIR. On the other hand this results in some false negatives. If
155 // MIR passes can be enabled / disabled separately, we should figure out, what passes to
157 config.opts.unstable_opts.mir_opt_level = Some(0);
164 Checks a package to catch common mistakes and improve your Rust code.
167 cargo clippy [options] [--] [<opts>...]
170 -h, --help Print this message
171 --rustc Pass all args to rustc
172 -V, --version Print version info and exit
174 Other options are the same as `cargo check`.
176 To allow or deny a lint from the command line you can use `cargo clippy --`
179 -W --warn OPT Set lint warnings
180 -A --allow OPT Set lint allowed
181 -D --deny OPT Set lint denied
182 -F --forbid OPT Set lint forbidden
184 You can use tool lints to allow or deny lints from your code, eg.:
186 #[allow(clippy::needless_lifetimes)]
191 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust-clippy/issues/new";
193 type PanicCallback = dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static;
194 static ICE_HOOK: LazyLock<Box<PanicCallback>> = LazyLock::new(|| {
195 let hook = panic::take_hook();
196 panic::set_hook(Box::new(|info| report_clippy_ice(info, BUG_REPORT_URL)));
200 fn report_clippy_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
201 // Invoke our ICE handler, which prints the actual panic message and optionally a backtrace
204 // Separate the output with an empty line
207 let fallback_bundle = rustc_errors::fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false);
208 let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
209 rustc_errors::ColorConfig::Auto,
219 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
221 // a .span_bug or .bug call has already printed what
222 // it wants to print.
223 if !info.payload().is::<rustc_errors::ExplicitBug>() {
224 let mut d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
225 handler.emit_diagnostic(&mut d);
228 let version_info = rustc_tools_util::get_version_info!();
230 let xs: Vec<Cow<'static, str>> = vec![
231 "the compiler unexpectedly panicked. this is a bug.".into(),
232 format!("we would appreciate a bug report: {bug_report_url}").into(),
233 format!("Clippy version: {version_info}").into(),
237 handler.note_without_error(note.as_ref());
240 // If backtraces are enabled, also print the query stack
241 let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
243 let num_frames = if backtrace { None } else { Some(2) };
245 interface::try_print_query_stack(&handler, num_frames);
248 #[allow(clippy::too_many_lines)]
250 rustc_driver::init_rustc_env_logger();
251 LazyLock::force(&ICE_HOOK);
252 exit(rustc_driver::catch_with_exit_code(move || {
253 let mut orig_args: Vec<String> = env::args().collect();
255 let sys_root_env = std::env::var("SYSROOT").ok();
256 let pass_sysroot_env_if_given = |args: &mut Vec<String>, sys_root_env| {
257 if let Some(sys_root) = sys_root_env {
258 args.extend(vec!["--sysroot".into(), sys_root]);
262 // make "clippy-driver --rustc" work like a subcommand that passes further args to "rustc"
263 // for example `clippy-driver --rustc --version` will print the rustc version that clippy-driver
265 if let Some(pos) = orig_args.iter().position(|arg| arg == "--rustc") {
266 orig_args.remove(pos);
267 orig_args[0] = "rustc".to_string();
269 let mut args: Vec<String> = orig_args.clone();
270 pass_sysroot_env_if_given(&mut args, sys_root_env);
272 return rustc_driver::RunCompiler::new(&args, &mut DefaultCallbacks).run();
275 if orig_args.iter().any(|a| a == "--version" || a == "-V") {
276 let version_info = rustc_tools_util::get_version_info!();
277 println!("{version_info}");
281 // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
282 // We're invoking the compiler programmatically, so we ignore this/
283 let wrapper_mode = orig_args.get(1).map(Path::new).and_then(Path::file_stem) == Some("rustc".as_ref());
286 // we still want to be able to invoke it normally though
290 if !wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
295 let mut args: Vec<String> = orig_args.clone();
296 pass_sysroot_env_if_given(&mut args, sys_root_env);
298 let mut no_deps = false;
299 let clippy_args_var = env::var("CLIPPY_ARGS").ok();
300 let clippy_args = clippy_args_var
303 .split("__CLIPPY_HACKERY__")
304 .filter_map(|s| match s {
310 _ => Some(s.to_string()),
312 .chain(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()])
313 .collect::<Vec<String>>();
315 // We enable Clippy if one of the following conditions is met
316 // - IF Clippy is run on its test suite OR
317 // - IF Clippy is run on the main crate, not on deps (`!cap_lints_allow`) THEN
318 // - IF `--no-deps` is not set (`!no_deps`) OR
319 // - IF `--no-deps` is set and Clippy is run on the specified primary package
320 let cap_lints_allow = arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_some()
321 && arg_value(&orig_args, "--force-warn", |val| val.contains("clippy::")).is_none();
322 let in_primary_package = env::var("CARGO_PRIMARY_PACKAGE").is_ok();
324 let clippy_enabled = !cap_lints_allow && (!no_deps || in_primary_package);
326 args.extend(clippy_args);
327 rustc_driver::RunCompiler::new(&args, &mut ClippyCallbacks { clippy_args_var }).run()
329 rustc_driver::RunCompiler::new(&args, &mut RustcCallbacks { clippy_args_var }).run()