]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/src/driver.rs
Rollup merge of #103104 - SUPERCILEX:sep-ref, r=dtolnay
[rust.git] / src / tools / clippy / src / driver.rs
1 #![feature(rustc_private)]
2 #![feature(let_chains)]
3 #![feature(once_cell)]
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)]
10
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;
18
19 use rustc_interface::interface;
20 use rustc_session::parse::ParseSess;
21 use rustc_span::symbol::Symbol;
22
23 use std::borrow::Cow;
24 use std::env;
25 use std::ops::Deref;
26 use std::panic;
27 use std::path::Path;
28 use std::process::exit;
29 use std::sync::LazyLock;
30
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>>(
34     args: &'a [T],
35     find_arg: &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) {
42             continue;
43         }
44
45         match arg.next().or_else(|| args.next()) {
46             Some(v) if pred(v) => return Some(v),
47             _ => {},
48         }
49     }
50     None
51 }
52
53 #[test]
54 fn test_arg_value() {
55     let args = &["--bar=bar", "--foobar", "123", "--foo"];
56
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);
66 }
67
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),
72     ));
73 }
74
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();
79
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"));
84     }
85
86     // `clippy.toml`
87     if let Some(path) = conf_path_string {
88         file_depinfo.insert(Symbol::intern(&path));
89     }
90
91     // During development track the `clippy-driver` executable so that cargo will re-run clippy whenever
92     // it is rebuilt
93     #[expect(
94         clippy::collapsible_if,
95         reason = "Due to a bug in let_chains this if statement can't be collapsed"
96     )]
97     if cfg!(debug_assertions) {
98         if let Ok(current_exe) = env::current_exe()
99             && let Some(current_exe) = current_exe.to_str()
100         {
101             file_depinfo.insert(Symbol::intern(current_exe));
102         }
103     }
104 }
105
106 struct DefaultCallbacks;
107 impl rustc_driver::Callbacks for DefaultCallbacks {}
108
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>,
113 }
114
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);
120         }));
121     }
122 }
123
124 struct ClippyCallbacks {
125     clippy_args_var: Option<String>,
126 }
127
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)
135         } else {
136             None
137         };
138
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);
144         }));
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);
150             }
151
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);
156         }));
157
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
161         // use for Clippy.
162         config.opts.unstable_opts.mir_opt_level = Some(0);
163     }
164 }
165
166 fn display_help() {
167     println!(
168         "\
169 Checks a package to catch common mistakes and improve your Rust code.
170
171 Usage:
172     cargo clippy [options] [--] [<opts>...]
173
174 Common options:
175     -h, --help               Print this message
176         --rustc              Pass all args to rustc
177     -V, --version            Print version info and exit
178
179 Other options are the same as `cargo check`.
180
181 To allow or deny a lint from the command line you can use `cargo clippy --`
182 with:
183
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
188
189 You can use tool lints to allow or deny lints from your code, eg.:
190
191     #[allow(clippy::needless_lifetimes)]
192 "
193     );
194 }
195
196 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust-clippy/issues/new";
197
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)));
202     hook
203 });
204
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
207     (*ICE_HOOK)(info);
208
209     // Separate the output with an empty line
210     eprintln!();
211
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,
215         None,
216         None,
217         fallback_bundle,
218         false,
219         false,
220         None,
221         false,
222         false,
223     ));
224     let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
225
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);
231     }
232
233     let version_info = rustc_tools_util::get_version_info!();
234
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(),
239     ];
240
241     for note in &xs {
242         handler.note_without_error(note.as_ref());
243     }
244
245     // If backtraces are enabled, also print the query stack
246     let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
247
248     let num_frames = if backtrace { None } else { Some(2) };
249
250     interface::try_print_query_stack(&handler, num_frames);
251 }
252
253 #[allow(clippy::too_many_lines)]
254 pub fn main() {
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();
259
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]);
264             };
265         };
266
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
269         // uses
270         if let Some(pos) = orig_args.iter().position(|arg| arg == "--rustc") {
271             orig_args.remove(pos);
272             orig_args[0] = "rustc".to_string();
273
274             let mut args: Vec<String> = orig_args.clone();
275             pass_sysroot_env_if_given(&mut args, sys_root_env);
276
277             return rustc_driver::RunCompiler::new(&args, &mut DefaultCallbacks).run();
278         }
279
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}");
283             exit(0);
284         }
285
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());
289
290         if wrapper_mode {
291             // we still want to be able to invoke it normally though
292             orig_args.remove(1);
293         }
294
295         if !wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
296             display_help();
297             exit(0);
298         }
299
300         let mut args: Vec<String> = orig_args.clone();
301         pass_sysroot_env_if_given(&mut args, sys_root_env);
302
303         let mut no_deps = false;
304         let clippy_args_var = env::var("CLIPPY_ARGS").ok();
305         let clippy_args = clippy_args_var
306             .as_deref()
307             .unwrap_or_default()
308             .split("__CLIPPY_HACKERY__")
309             .filter_map(|s| match s {
310                 "" => None,
311                 "--no-deps" => {
312                     no_deps = true;
313                     None
314                 },
315                 _ => Some(s.to_string()),
316             })
317             .chain(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()])
318             .collect::<Vec<String>>();
319
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();
328
329         let clippy_enabled = !cap_lints_allow && (!no_deps || in_primary_package);
330         if clippy_enabled {
331             args.extend(clippy_args);
332             rustc_driver::RunCompiler::new(&args, &mut ClippyCallbacks { clippy_args_var }).run()
333         } else {
334             rustc_driver::RunCompiler::new(&args, &mut RustcCallbacks { clippy_args_var }).run()
335         }
336     }))
337 }