]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/src/driver.rs
Rollup merge of #103488 - oli-obk:impl_trait_for_tait, r=lcnr
[rust.git] / src / tools / clippy / src / driver.rs
1 #![feature(rustc_private)]
2 #![feature(let_chains)]
3 #![feature(once_cell)]
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)]
9
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;
17
18 use rustc_interface::interface;
19 use rustc_session::parse::ParseSess;
20 use rustc_span::symbol::Symbol;
21 use rustc_tools_util::VersionInfo;
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     if cfg!(debug_assertions) {
94         if let Ok(current_exe) = env::current_exe()
95             && let Some(current_exe) = current_exe.to_str()
96         {
97             file_depinfo.insert(Symbol::intern(current_exe));
98         }
99     }
100 }
101
102 struct DefaultCallbacks;
103 impl rustc_driver::Callbacks for DefaultCallbacks {}
104
105 /// This is different from `DefaultCallbacks` that it will inform Cargo to track the value of
106 /// `CLIPPY_ARGS` environment variable.
107 struct RustcCallbacks {
108     clippy_args_var: Option<String>,
109 }
110
111 impl rustc_driver::Callbacks for RustcCallbacks {
112     fn config(&mut self, config: &mut interface::Config) {
113         let clippy_args_var = self.clippy_args_var.take();
114         config.parse_sess_created = Some(Box::new(move |parse_sess| {
115             track_clippy_args(parse_sess, &clippy_args_var);
116         }));
117     }
118 }
119
120 struct ClippyCallbacks {
121     clippy_args_var: Option<String>,
122 }
123
124 impl rustc_driver::Callbacks for ClippyCallbacks {
125     // JUSTIFICATION: necessary in clippy driver to set `mir_opt_level`
126     #[allow(rustc::bad_opt_access)]
127     fn config(&mut self, config: &mut interface::Config) {
128         let conf_path = clippy_lints::lookup_conf_file();
129         let conf_path_string = if let Ok(Some(path)) = &conf_path {
130             path.to_str().map(String::from)
131         } else {
132             None
133         };
134
135         let previous = config.register_lints.take();
136         let clippy_args_var = self.clippy_args_var.take();
137         config.parse_sess_created = Some(Box::new(move |parse_sess| {
138             track_clippy_args(parse_sess, &clippy_args_var);
139             track_files(parse_sess, conf_path_string);
140         }));
141         config.register_lints = Some(Box::new(move |sess, lint_store| {
142             // technically we're ~guaranteed that this is none but might as well call anything that
143             // is there already. Certainly it can't hurt.
144             if let Some(previous) = &previous {
145                 (previous)(sess, lint_store);
146             }
147
148             let conf = clippy_lints::read_conf(sess, &conf_path);
149             clippy_lints::register_plugins(lint_store, sess, &conf);
150             clippy_lints::register_pre_expansion_lints(lint_store, sess, &conf);
151             clippy_lints::register_renamed(lint_store);
152         }));
153
154         // FIXME: #4825; This is required, because Clippy lints that are based on MIR have to be
155         // run on the unoptimized MIR. On the other hand this results in some false negatives. If
156         // MIR passes can be enabled / disabled separately, we should figure out, what passes to
157         // use for Clippy.
158         config.opts.unstable_opts.mir_opt_level = Some(0);
159     }
160 }
161
162 fn display_help() {
163     println!(
164         "\
165 Checks a package to catch common mistakes and improve your Rust code.
166
167 Usage:
168     cargo clippy [options] [--] [<opts>...]
169
170 Common options:
171     -h, --help               Print this message
172         --rustc              Pass all args to rustc
173     -V, --version            Print version info and exit
174
175 Other options are the same as `cargo check`.
176
177 To allow or deny a lint from the command line you can use `cargo clippy --`
178 with:
179
180     -W --warn OPT       Set lint warnings
181     -A --allow OPT      Set lint allowed
182     -D --deny OPT       Set lint denied
183     -F --forbid OPT     Set lint forbidden
184
185 You can use tool lints to allow or deny lints from your code, eg.:
186
187     #[allow(clippy::needless_lifetimes)]
188 "
189     );
190 }
191
192 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust-clippy/issues/new";
193
194 type PanicCallback = dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static;
195 static ICE_HOOK: LazyLock<Box<PanicCallback>> = LazyLock::new(|| {
196     let hook = panic::take_hook();
197     panic::set_hook(Box::new(|info| report_clippy_ice(info, BUG_REPORT_URL)));
198     hook
199 });
200
201 fn report_clippy_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
202     // Invoke our ICE handler, which prints the actual panic message and optionally a backtrace
203     (*ICE_HOOK)(info);
204
205     // Separate the output with an empty line
206     eprintln!();
207
208     let fallback_bundle = rustc_errors::fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false);
209     let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
210         rustc_errors::ColorConfig::Auto,
211         None,
212         None,
213         fallback_bundle,
214         false,
215         false,
216         None,
217         false,
218         false,
219     ));
220     let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
221
222     // a .span_bug or .bug call has already printed what
223     // it wants to print.
224     if !info.payload().is::<rustc_errors::ExplicitBug>() {
225         let mut d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
226         handler.emit_diagnostic(&mut d);
227     }
228
229     let version_info = rustc_tools_util::get_version_info!();
230
231     let xs: Vec<Cow<'static, str>> = vec![
232         "the compiler unexpectedly panicked. this is a bug.".into(),
233         format!("we would appreciate a bug report: {bug_report_url}").into(),
234         format!("Clippy version: {version_info}").into(),
235     ];
236
237     for note in &xs {
238         handler.note_without_error(note.as_ref());
239     }
240
241     // If backtraces are enabled, also print the query stack
242     let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
243
244     let num_frames = if backtrace { None } else { Some(2) };
245
246     interface::try_print_query_stack(&handler, num_frames);
247 }
248
249 #[allow(clippy::too_many_lines)]
250 pub fn main() {
251     rustc_driver::init_rustc_env_logger();
252     LazyLock::force(&ICE_HOOK);
253     exit(rustc_driver::catch_with_exit_code(move || {
254         let mut orig_args: Vec<String> = env::args().collect();
255
256         let sys_root_env = std::env::var("SYSROOT").ok();
257         let pass_sysroot_env_if_given = |args: &mut Vec<String>, sys_root_env| {
258             if let Some(sys_root) = sys_root_env {
259                 args.extend(vec!["--sysroot".into(), sys_root]);
260             };
261         };
262
263         // make "clippy-driver --rustc" work like a subcommand that passes further args to "rustc"
264         // for example `clippy-driver --rustc --version` will print the rustc version that clippy-driver
265         // uses
266         if let Some(pos) = orig_args.iter().position(|arg| arg == "--rustc") {
267             orig_args.remove(pos);
268             orig_args[0] = "rustc".to_string();
269
270             let mut args: Vec<String> = orig_args.clone();
271             pass_sysroot_env_if_given(&mut args, sys_root_env);
272
273             return rustc_driver::RunCompiler::new(&args, &mut DefaultCallbacks).run();
274         }
275
276         if orig_args.iter().any(|a| a == "--version" || a == "-V") {
277             let version_info = rustc_tools_util::get_version_info!();
278             println!("{version_info}");
279             exit(0);
280         }
281
282         // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
283         // We're invoking the compiler programmatically, so we ignore this/
284         let wrapper_mode = orig_args.get(1).map(Path::new).and_then(Path::file_stem) == Some("rustc".as_ref());
285
286         if wrapper_mode {
287             // we still want to be able to invoke it normally though
288             orig_args.remove(1);
289         }
290
291         if !wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
292             display_help();
293             exit(0);
294         }
295
296         let mut args: Vec<String> = orig_args.clone();
297         pass_sysroot_env_if_given(&mut args, sys_root_env);
298
299         let mut no_deps = false;
300         let clippy_args_var = env::var("CLIPPY_ARGS").ok();
301         let clippy_args = clippy_args_var
302             .as_deref()
303             .unwrap_or_default()
304             .split("__CLIPPY_HACKERY__")
305             .filter_map(|s| match s {
306                 "" => None,
307                 "--no-deps" => {
308                     no_deps = true;
309                     None
310                 },
311                 _ => Some(s.to_string()),
312             })
313             .chain(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()])
314             .collect::<Vec<String>>();
315
316         // We enable Clippy if one of the following conditions is met
317         // - IF Clippy is run on its test suite OR
318         // - IF Clippy is run on the main crate, not on deps (`!cap_lints_allow`) THEN
319         //    - IF `--no-deps` is not set (`!no_deps`) OR
320         //    - IF `--no-deps` is set and Clippy is run on the specified primary package
321         let cap_lints_allow = arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_some()
322             && arg_value(&orig_args, "--force-warn", |val| val.contains("clippy::")).is_none();
323         let in_primary_package = env::var("CARGO_PRIMARY_PACKAGE").is_ok();
324
325         let clippy_enabled = !cap_lints_allow && (!no_deps || in_primary_package);
326         if clippy_enabled {
327             args.extend(clippy_args);
328             rustc_driver::RunCompiler::new(&args, &mut ClippyCallbacks { clippy_args_var }).run()
329         } else {
330             rustc_driver::RunCompiler::new(&args, &mut RustcCallbacks { clippy_args_var }).run()
331         }
332     }))
333 }