]> git.proxmox.com Git - rustc.git/blob - src/tools/clippy/src/driver.rs
New upstream version 1.65.0+dfsg1
[rustc.git] / src / tools / clippy / src / driver.rs
1 #![feature(rustc_private)]
2 #![feature(once_cell)]
3 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
4 // warn on lints, that are included in `rust-lang/rust`s bootstrap
5 #![warn(rust_2018_idioms, unused_lifetimes)]
6 // warn on rustc internal lints
7 #![warn(rustc::internal)]
8
9 // FIXME: switch to something more ergonomic here, once available.
10 // (Currently there is no way to opt into sysroot crates without `extern crate`.)
11 extern crate rustc_driver;
12 extern crate rustc_errors;
13 extern crate rustc_interface;
14 extern crate rustc_session;
15 extern crate rustc_span;
16
17 use rustc_interface::interface;
18 use rustc_session::parse::ParseSess;
19 use rustc_span::symbol::Symbol;
20 use rustc_tools_util::VersionInfo;
21
22 use std::borrow::Cow;
23 use std::env;
24 use std::ops::Deref;
25 use std::panic;
26 use std::path::{Path, PathBuf};
27 use std::process::{exit, Command};
28 use std::sync::LazyLock;
29
30 /// If a command-line option matches `find_arg`, then apply the predicate `pred` on its value. If
31 /// true, then return it. The parameter is assumed to be either `--arg=value` or `--arg value`.
32 fn arg_value<'a, T: Deref<Target = str>>(
33 args: &'a [T],
34 find_arg: &str,
35 pred: impl Fn(&str) -> bool,
36 ) -> Option<&'a str> {
37 let mut args = args.iter().map(Deref::deref);
38 while let Some(arg) = args.next() {
39 let mut arg = arg.splitn(2, '=');
40 if arg.next() != Some(find_arg) {
41 continue;
42 }
43
44 match arg.next().or_else(|| args.next()) {
45 Some(v) if pred(v) => return Some(v),
46 _ => {},
47 }
48 }
49 None
50 }
51
52 #[test]
53 fn test_arg_value() {
54 let args = &["--bar=bar", "--foobar", "123", "--foo"];
55
56 assert_eq!(arg_value(&[] as &[&str], "--foobar", |_| true), None);
57 assert_eq!(arg_value(args, "--bar", |_| false), None);
58 assert_eq!(arg_value(args, "--bar", |_| true), Some("bar"));
59 assert_eq!(arg_value(args, "--bar", |p| p == "bar"), Some("bar"));
60 assert_eq!(arg_value(args, "--bar", |p| p == "foo"), None);
61 assert_eq!(arg_value(args, "--foobar", |p| p == "foo"), None);
62 assert_eq!(arg_value(args, "--foobar", |p| p == "123"), Some("123"));
63 assert_eq!(arg_value(args, "--foobar", |p| p.contains("12")), Some("123"));
64 assert_eq!(arg_value(args, "--foo", |_| true), None);
65 }
66
67 fn track_clippy_args(parse_sess: &mut ParseSess, args_env_var: &Option<String>) {
68 parse_sess.env_depinfo.get_mut().insert((
69 Symbol::intern("CLIPPY_ARGS"),
70 args_env_var.as_deref().map(Symbol::intern),
71 ));
72 }
73
74 struct DefaultCallbacks;
75 impl rustc_driver::Callbacks for DefaultCallbacks {}
76
77 /// This is different from `DefaultCallbacks` that it will inform Cargo to track the value of
78 /// `CLIPPY_ARGS` environment variable.
79 struct RustcCallbacks {
80 clippy_args_var: Option<String>,
81 }
82
83 impl rustc_driver::Callbacks for RustcCallbacks {
84 fn config(&mut self, config: &mut interface::Config) {
85 let clippy_args_var = self.clippy_args_var.take();
86 config.parse_sess_created = Some(Box::new(move |parse_sess| {
87 track_clippy_args(parse_sess, &clippy_args_var);
88 }));
89 }
90 }
91
92 struct ClippyCallbacks {
93 clippy_args_var: Option<String>,
94 }
95
96 impl rustc_driver::Callbacks for ClippyCallbacks {
97 // JUSTIFICATION: necessary in clippy driver to set `mir_opt_level`
98 #[allow(rustc::bad_opt_access)]
99 fn config(&mut self, config: &mut interface::Config) {
100 let previous = config.register_lints.take();
101 let clippy_args_var = self.clippy_args_var.take();
102 config.parse_sess_created = Some(Box::new(move |parse_sess| {
103 track_clippy_args(parse_sess, &clippy_args_var);
104 }));
105 config.register_lints = Some(Box::new(move |sess, lint_store| {
106 // technically we're ~guaranteed that this is none but might as well call anything that
107 // is there already. Certainly it can't hurt.
108 if let Some(previous) = &previous {
109 (previous)(sess, lint_store);
110 }
111
112 let conf = clippy_lints::read_conf(sess);
113 clippy_lints::register_plugins(lint_store, sess, &conf);
114 clippy_lints::register_pre_expansion_lints(lint_store, sess, &conf);
115 clippy_lints::register_renamed(lint_store);
116 }));
117
118 // FIXME: #4825; This is required, because Clippy lints that are based on MIR have to be
119 // run on the unoptimized MIR. On the other hand this results in some false negatives. If
120 // MIR passes can be enabled / disabled separately, we should figure out, what passes to
121 // use for Clippy.
122 config.opts.unstable_opts.mir_opt_level = Some(0);
123 }
124 }
125
126 fn display_help() {
127 println!(
128 "\
129 Checks a package to catch common mistakes and improve your Rust code.
130
131 Usage:
132 cargo clippy [options] [--] [<opts>...]
133
134 Common options:
135 -h, --help Print this message
136 --rustc Pass all args to rustc
137 -V, --version Print version info and exit
138
139 Other options are the same as `cargo check`.
140
141 To allow or deny a lint from the command line you can use `cargo clippy --`
142 with:
143
144 -W --warn OPT Set lint warnings
145 -A --allow OPT Set lint allowed
146 -D --deny OPT Set lint denied
147 -F --forbid OPT Set lint forbidden
148
149 You can use tool lints to allow or deny lints from your code, eg.:
150
151 #[allow(clippy::needless_lifetimes)]
152 "
153 );
154 }
155
156 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust-clippy/issues/new";
157
158 type PanicCallback = dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static;
159 static ICE_HOOK: LazyLock<Box<PanicCallback>> = LazyLock::new(|| {
160 let hook = panic::take_hook();
161 panic::set_hook(Box::new(|info| report_clippy_ice(info, BUG_REPORT_URL)));
162 hook
163 });
164
165 fn report_clippy_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
166 // Invoke our ICE handler, which prints the actual panic message and optionally a backtrace
167 (*ICE_HOOK)(info);
168
169 // Separate the output with an empty line
170 eprintln!();
171
172 let fallback_bundle = rustc_errors::fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false);
173 let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
174 rustc_errors::ColorConfig::Auto,
175 None,
176 None,
177 fallback_bundle,
178 false,
179 false,
180 None,
181 false,
182 ));
183 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
184
185 // a .span_bug or .bug call has already printed what
186 // it wants to print.
187 if !info.payload().is::<rustc_errors::ExplicitBug>() {
188 let mut d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
189 handler.emit_diagnostic(&mut d);
190 }
191
192 let version_info = rustc_tools_util::get_version_info!();
193
194 let xs: Vec<Cow<'static, str>> = vec![
195 "the compiler unexpectedly panicked. this is a bug.".into(),
196 format!("we would appreciate a bug report: {}", bug_report_url).into(),
197 format!("Clippy version: {}", version_info).into(),
198 ];
199
200 for note in &xs {
201 handler.note_without_error(note.as_ref());
202 }
203
204 // If backtraces are enabled, also print the query stack
205 let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
206
207 let num_frames = if backtrace { None } else { Some(2) };
208
209 interface::try_print_query_stack(&handler, num_frames);
210 }
211
212 fn toolchain_path(home: Option<String>, toolchain: Option<String>) -> Option<PathBuf> {
213 home.and_then(|home| {
214 toolchain.map(|toolchain| {
215 let mut path = PathBuf::from(home);
216 path.push("toolchains");
217 path.push(toolchain);
218 path
219 })
220 })
221 }
222
223 #[allow(clippy::too_many_lines)]
224 pub fn main() {
225 rustc_driver::init_rustc_env_logger();
226 LazyLock::force(&ICE_HOOK);
227 exit(rustc_driver::catch_with_exit_code(move || {
228 let mut orig_args: Vec<String> = env::args().collect();
229
230 // Get the sysroot, looking from most specific to this invocation to the least:
231 // - command line
232 // - runtime environment
233 // - SYSROOT
234 // - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
235 // - sysroot from rustc in the path
236 // - compile-time environment
237 // - SYSROOT
238 // - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
239 let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
240 let have_sys_root_arg = sys_root_arg.is_some();
241 let sys_root = sys_root_arg
242 .map(PathBuf::from)
243 .or_else(|| std::env::var("SYSROOT").ok().map(PathBuf::from))
244 .or_else(|| {
245 let home = std::env::var("RUSTUP_HOME")
246 .or_else(|_| std::env::var("MULTIRUST_HOME"))
247 .ok();
248 let toolchain = std::env::var("RUSTUP_TOOLCHAIN")
249 .or_else(|_| std::env::var("MULTIRUST_TOOLCHAIN"))
250 .ok();
251 toolchain_path(home, toolchain)
252 })
253 .or_else(|| {
254 Command::new("rustc")
255 .arg("--print")
256 .arg("sysroot")
257 .output()
258 .ok()
259 .and_then(|out| String::from_utf8(out.stdout).ok())
260 .map(|s| PathBuf::from(s.trim()))
261 })
262 .or_else(|| option_env!("SYSROOT").map(PathBuf::from))
263 .or_else(|| {
264 let home = option_env!("RUSTUP_HOME")
265 .or(option_env!("MULTIRUST_HOME"))
266 .map(ToString::to_string);
267 let toolchain = option_env!("RUSTUP_TOOLCHAIN")
268 .or(option_env!("MULTIRUST_TOOLCHAIN"))
269 .map(ToString::to_string);
270 toolchain_path(home, toolchain)
271 })
272 .map(|pb| pb.to_string_lossy().to_string())
273 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
274
275 // make "clippy-driver --rustc" work like a subcommand that passes further args to "rustc"
276 // for example `clippy-driver --rustc --version` will print the rustc version that clippy-driver
277 // uses
278 if let Some(pos) = orig_args.iter().position(|arg| arg == "--rustc") {
279 orig_args.remove(pos);
280 orig_args[0] = "rustc".to_string();
281
282 // if we call "rustc", we need to pass --sysroot here as well
283 let mut args: Vec<String> = orig_args.clone();
284 if !have_sys_root_arg {
285 args.extend(vec!["--sysroot".into(), sys_root]);
286 };
287
288 return rustc_driver::RunCompiler::new(&args, &mut DefaultCallbacks).run();
289 }
290
291 if orig_args.iter().any(|a| a == "--version" || a == "-V") {
292 let version_info = rustc_tools_util::get_version_info!();
293 println!("{}", version_info);
294 exit(0);
295 }
296
297 // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
298 // We're invoking the compiler programmatically, so we ignore this/
299 let wrapper_mode = orig_args.get(1).map(Path::new).and_then(Path::file_stem) == Some("rustc".as_ref());
300
301 if wrapper_mode {
302 // we still want to be able to invoke it normally though
303 orig_args.remove(1);
304 }
305
306 if !wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
307 display_help();
308 exit(0);
309 }
310
311 // this conditional check for the --sysroot flag is there so users can call
312 // `clippy_driver` directly
313 // without having to pass --sysroot or anything
314 let mut args: Vec<String> = orig_args.clone();
315 if !have_sys_root_arg {
316 args.extend(vec!["--sysroot".into(), sys_root]);
317 };
318
319 let mut no_deps = false;
320 let clippy_args_var = env::var("CLIPPY_ARGS").ok();
321 let clippy_args = clippy_args_var
322 .as_deref()
323 .unwrap_or_default()
324 .split("__CLIPPY_HACKERY__")
325 .filter_map(|s| match s {
326 "" => None,
327 "--no-deps" => {
328 no_deps = true;
329 None
330 },
331 _ => Some(s.to_string()),
332 })
333 .chain(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()])
334 .collect::<Vec<String>>();
335
336 // We enable Clippy if one of the following conditions is met
337 // - IF Clippy is run on its test suite OR
338 // - IF Clippy is run on the main crate, not on deps (`!cap_lints_allow`) THEN
339 // - IF `--no-deps` is not set (`!no_deps`) OR
340 // - IF `--no-deps` is set and Clippy is run on the specified primary package
341 let cap_lints_allow = arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_some()
342 && arg_value(&orig_args, "--force-warn", |val| val.contains("clippy::")).is_none();
343 let in_primary_package = env::var("CARGO_PRIMARY_PACKAGE").is_ok();
344
345 let clippy_enabled = !cap_lints_allow && (!no_deps || in_primary_package);
346 if clippy_enabled {
347 args.extend(clippy_args);
348 rustc_driver::RunCompiler::new(&args, &mut ClippyCallbacks { clippy_args_var }).run()
349 } else {
350 rustc_driver::RunCompiler::new(&args, &mut RustcCallbacks { clippy_args_var }).run()
351 }
352 }))
353 }