]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/src/driver.rs
Merge commit 'f4850f7292efa33759b4f7f9b7621268979e9914' into clippyup
[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         && 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 struct DefaultCallbacks;
102 impl rustc_driver::Callbacks for DefaultCallbacks {}
103
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>,
108 }
109
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);
115         }));
116     }
117 }
118
119 struct ClippyCallbacks {
120     clippy_args_var: Option<String>,
121 }
122
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)
130         } else {
131             None
132         };
133
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);
139         }));
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);
145             }
146
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);
151         }));
152
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
156         // use for Clippy.
157         config.opts.unstable_opts.mir_opt_level = Some(0);
158     }
159 }
160
161 fn display_help() {
162     println!(
163         "\
164 Checks a package to catch common mistakes and improve your Rust code.
165
166 Usage:
167     cargo clippy [options] [--] [<opts>...]
168
169 Common options:
170     -h, --help               Print this message
171         --rustc              Pass all args to rustc
172     -V, --version            Print version info and exit
173
174 Other options are the same as `cargo check`.
175
176 To allow or deny a lint from the command line you can use `cargo clippy --`
177 with:
178
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
183
184 You can use tool lints to allow or deny lints from your code, eg.:
185
186     #[allow(clippy::needless_lifetimes)]
187 "
188     );
189 }
190
191 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust-clippy/issues/new";
192
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)));
197     hook
198 });
199
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
202     (*ICE_HOOK)(info);
203
204     // Separate the output with an empty line
205     eprintln!();
206
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,
210         None,
211         None,
212         fallback_bundle,
213         false,
214         false,
215         None,
216         false,
217         false,
218     ));
219     let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
220
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);
226     }
227
228     let version_info = rustc_tools_util::get_version_info!();
229
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(),
234     ];
235
236     for note in &xs {
237         handler.note_without_error(note.as_ref());
238     }
239
240     // If backtraces are enabled, also print the query stack
241     let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
242
243     let num_frames = if backtrace { None } else { Some(2) };
244
245     interface::try_print_query_stack(&handler, num_frames);
246 }
247
248 #[allow(clippy::too_many_lines)]
249 pub fn main() {
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();
254
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]);
259             };
260         };
261
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
264         // uses
265         if let Some(pos) = orig_args.iter().position(|arg| arg == "--rustc") {
266             orig_args.remove(pos);
267             orig_args[0] = "rustc".to_string();
268
269             let mut args: Vec<String> = orig_args.clone();
270             pass_sysroot_env_if_given(&mut args, sys_root_env);
271
272             return rustc_driver::RunCompiler::new(&args, &mut DefaultCallbacks).run();
273         }
274
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}");
278             exit(0);
279         }
280
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());
284
285         if wrapper_mode {
286             // we still want to be able to invoke it normally though
287             orig_args.remove(1);
288         }
289
290         if !wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
291             display_help();
292             exit(0);
293         }
294
295         let mut args: Vec<String> = orig_args.clone();
296         pass_sysroot_env_if_given(&mut args, sys_root_env);
297
298         let mut no_deps = false;
299         let clippy_args_var = env::var("CLIPPY_ARGS").ok();
300         let clippy_args = clippy_args_var
301             .as_deref()
302             .unwrap_or_default()
303             .split("__CLIPPY_HACKERY__")
304             .filter_map(|s| match s {
305                 "" => None,
306                 "--no-deps" => {
307                     no_deps = true;
308                     None
309                 },
310                 _ => Some(s.to_string()),
311             })
312             .chain(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()])
313             .collect::<Vec<String>>();
314
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();
323
324         let clippy_enabled = !cap_lints_allow && (!no_deps || in_primary_package);
325         if clippy_enabled {
326             args.extend(clippy_args);
327             rustc_driver::RunCompiler::new(&args, &mut ClippyCallbacks { clippy_args_var }).run()
328         } else {
329             rustc_driver::RunCompiler::new(&args, &mut RustcCallbacks { clippy_args_var }).run()
330         }
331     }))
332 }