]> git.lizzy.rs Git - rust.git/blob - src/driver.rs
Merge commit '4911ab124c481430672a3833b37075e6435ec34d' into clippyup
[rust.git] / src / driver.rs
1 #![feature(rustc_private)]
2 #![feature(once_cell)]
3 #![feature(bool_to_option)]
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 #![deny(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_middle;
16
17 use rustc_interface::interface;
18 use rustc_middle::ty::TyCtxt;
19 use rustc_tools_util::VersionInfo;
20
21 use std::borrow::Cow;
22 use std::env;
23 use std::iter;
24 use std::lazy::SyncLazy;
25 use std::ops::Deref;
26 use std::panic;
27 use std::path::{Path, PathBuf};
28 use std::process::{exit, Command};
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 struct DefaultCallbacks;
53 impl rustc_driver::Callbacks for DefaultCallbacks {}
54
55 struct ClippyCallbacks;
56 impl rustc_driver::Callbacks for ClippyCallbacks {
57     fn config(&mut self, config: &mut interface::Config) {
58         let previous = config.register_lints.take();
59         config.register_lints = Some(Box::new(move |sess, mut lint_store| {
60             // technically we're ~guaranteed that this is none but might as well call anything that
61             // is there already. Certainly it can't hurt.
62             if let Some(previous) = &previous {
63                 (previous)(sess, lint_store);
64             }
65
66             let conf = clippy_lints::read_conf(&[], &sess);
67             clippy_lints::register_plugins(&mut lint_store, &sess, &conf);
68             clippy_lints::register_pre_expansion_lints(&mut lint_store);
69             clippy_lints::register_renamed(&mut lint_store);
70         }));
71
72         // FIXME: #4825; This is required, because Clippy lints that are based on MIR have to be
73         // run on the unoptimized MIR. On the other hand this results in some false negatives. If
74         // MIR passes can be enabled / disabled separately, we should figure out, what passes to
75         // use for Clippy.
76         config.opts.debugging_opts.mir_opt_level = 0;
77     }
78 }
79
80 fn display_help() {
81     println!(
82         "\
83 Checks a package to catch common mistakes and improve your Rust code.
84
85 Usage:
86     cargo clippy [options] [--] [<opts>...]
87
88 Common options:
89     -h, --help               Print this message
90         --rustc              Pass all args to rustc
91     -V, --version            Print version info and exit
92
93 Other options are the same as `cargo check`.
94
95 To allow or deny a lint from the command line you can use `cargo clippy --`
96 with:
97
98     -W --warn OPT       Set lint warnings
99     -A --allow OPT      Set lint allowed
100     -D --deny OPT       Set lint denied
101     -F --forbid OPT     Set lint forbidden
102
103 You can use tool lints to allow or deny lints from your code, eg.:
104
105     #[allow(clippy::needless_lifetimes)]
106 "
107     );
108 }
109
110 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust-clippy/issues/new";
111
112 static ICE_HOOK: SyncLazy<Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static>> = SyncLazy::new(|| {
113     let hook = panic::take_hook();
114     panic::set_hook(Box::new(|info| report_clippy_ice(info, BUG_REPORT_URL)));
115     hook
116 });
117
118 fn report_clippy_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
119     // Invoke our ICE handler, which prints the actual panic message and optionally a backtrace
120     (*ICE_HOOK)(info);
121
122     // Separate the output with an empty line
123     eprintln!();
124
125     let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
126         rustc_errors::ColorConfig::Auto,
127         None,
128         false,
129         false,
130         None,
131         false,
132     ));
133     let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
134
135     // a .span_bug or .bug call has already printed what
136     // it wants to print.
137     if !info.payload().is::<rustc_errors::ExplicitBug>() {
138         let d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
139         handler.emit_diagnostic(&d);
140     }
141
142     let version_info = rustc_tools_util::get_version_info!();
143
144     let xs: Vec<Cow<'static, str>> = vec![
145         "the compiler unexpectedly panicked. this is a bug.".into(),
146         format!("we would appreciate a bug report: {}", bug_report_url).into(),
147         format!("Clippy version: {}", version_info).into(),
148     ];
149
150     for note in &xs {
151         handler.note_without_error(&note);
152     }
153
154     // If backtraces are enabled, also print the query stack
155     let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
156
157     let num_frames = if backtrace { None } else { Some(2) };
158
159     TyCtxt::try_print_query_stack(&handler, num_frames);
160 }
161
162 fn toolchain_path(home: Option<String>, toolchain: Option<String>) -> Option<PathBuf> {
163     home.and_then(|home| {
164         toolchain.map(|toolchain| {
165             let mut path = PathBuf::from(home);
166             path.push("toolchains");
167             path.push(toolchain);
168             path
169         })
170     })
171 }
172
173 fn remove_clippy_args<'a, T, U, I>(args: &mut Vec<T>, clippy_args: I)
174 where
175     T: AsRef<str>,
176     U: AsRef<str> + ?Sized + 'a,
177     I: Iterator<Item = &'a U> + Clone,
178 {
179     let args_iter = clippy_args.map(AsRef::as_ref);
180     let args_count = args_iter.clone().count();
181
182     if args_count > 0 {
183         if let Some(start) = args.windows(args_count).enumerate().find_map(|(current, window)| {
184             window
185                 .iter()
186                 .map(AsRef::as_ref)
187                 .eq(args_iter.clone())
188                 .then_some(current)
189         }) {
190             args.drain(start..start + args_count);
191         }
192     }
193 }
194
195 #[allow(clippy::too_many_lines)]
196 pub fn main() {
197     rustc_driver::init_rustc_env_logger();
198     SyncLazy::force(&ICE_HOOK);
199     exit(rustc_driver::catch_with_exit_code(move || {
200         let mut orig_args: Vec<String> = env::args().collect();
201
202         // Get the sysroot, looking from most specific to this invocation to the least:
203         // - command line
204         // - runtime environment
205         //    - SYSROOT
206         //    - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
207         // - sysroot from rustc in the path
208         // - compile-time environment
209         //    - SYSROOT
210         //    - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
211         let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
212         let have_sys_root_arg = sys_root_arg.is_some();
213         let sys_root = sys_root_arg
214             .map(PathBuf::from)
215             .or_else(|| std::env::var("SYSROOT").ok().map(PathBuf::from))
216             .or_else(|| {
217                 let home = std::env::var("RUSTUP_HOME")
218                     .or_else(|_| std::env::var("MULTIRUST_HOME"))
219                     .ok();
220                 let toolchain = std::env::var("RUSTUP_TOOLCHAIN")
221                     .or_else(|_| std::env::var("MULTIRUST_TOOLCHAIN"))
222                     .ok();
223                 toolchain_path(home, toolchain)
224             })
225             .or_else(|| {
226                 Command::new("rustc")
227                     .arg("--print")
228                     .arg("sysroot")
229                     .output()
230                     .ok()
231                     .and_then(|out| String::from_utf8(out.stdout).ok())
232                     .map(|s| PathBuf::from(s.trim()))
233             })
234             .or_else(|| option_env!("SYSROOT").map(PathBuf::from))
235             .or_else(|| {
236                 let home = option_env!("RUSTUP_HOME")
237                     .or(option_env!("MULTIRUST_HOME"))
238                     .map(ToString::to_string);
239                 let toolchain = option_env!("RUSTUP_TOOLCHAIN")
240                     .or(option_env!("MULTIRUST_TOOLCHAIN"))
241                     .map(ToString::to_string);
242                 toolchain_path(home, toolchain)
243             })
244             .map(|pb| pb.to_string_lossy().to_string())
245             .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
246
247         // make "clippy-driver --rustc" work like a subcommand that passes further args to "rustc"
248         // for example `clippy-driver --rustc --version` will print the rustc version that clippy-driver
249         // uses
250         if let Some(pos) = orig_args.iter().position(|arg| arg == "--rustc") {
251             orig_args.remove(pos);
252             orig_args[0] = "rustc".to_string();
253
254             // if we call "rustc", we need to pass --sysroot here as well
255             let mut args: Vec<String> = orig_args.clone();
256             if !have_sys_root_arg {
257                 args.extend(vec!["--sysroot".into(), sys_root]);
258             };
259
260             return rustc_driver::RunCompiler::new(&args, &mut DefaultCallbacks).run();
261         }
262
263         if orig_args.iter().any(|a| a == "--version" || a == "-V") {
264             let version_info = rustc_tools_util::get_version_info!();
265             println!("{}", version_info);
266             exit(0);
267         }
268
269         // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
270         // We're invoking the compiler programmatically, so we ignore this/
271         let wrapper_mode = orig_args.get(1).map(Path::new).and_then(Path::file_stem) == Some("rustc".as_ref());
272
273         if wrapper_mode {
274             // we still want to be able to invoke it normally though
275             orig_args.remove(1);
276         }
277
278         if !wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
279             display_help();
280             exit(0);
281         }
282
283         // this conditional check for the --sysroot flag is there so users can call
284         // `clippy_driver` directly
285         // without having to pass --sysroot or anything
286         let mut args: Vec<String> = orig_args.clone();
287         if !have_sys_root_arg {
288             args.extend(vec!["--sysroot".into(), sys_root]);
289         };
290
291         let clippy_args = env::var("CLIPPY_ARGS").unwrap_or_default();
292         let clippy_args = clippy_args.split_whitespace();
293         let no_deps = clippy_args.clone().any(|flag| flag == "--no-deps");
294
295         // We enable Clippy if one of the following conditions is met
296         // - IF Clippy is run on its test suite OR
297         // - IF Clippy is run on the main crate, not on deps (`!cap_lints_allow`) THEN
298         //    - IF `--no-deps` is not set (`!no_deps`) OR
299         //    - IF `--no-deps` is set and Clippy is run on the specified primary package
300         let clippy_tests_set = env::var("CLIPPY_TESTS").map_or(false, |val| val == "true");
301         let cap_lints_allow = arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_some();
302         let in_primary_package = env::var("CARGO_PRIMARY_PACKAGE").is_ok();
303
304         let clippy_enabled = clippy_tests_set || (!cap_lints_allow && (!no_deps || in_primary_package));
305         if clippy_enabled {
306             remove_clippy_args(&mut args, iter::once("--no-deps"));
307             args.extend(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()]);
308         } else {
309             // Remove all flags passed through RUSTFLAGS if Clippy is not enabled.
310             remove_clippy_args(&mut args, clippy_args);
311         }
312
313         let mut clippy = ClippyCallbacks;
314         let mut default = DefaultCallbacks;
315         let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
316             if clippy_enabled { &mut clippy } else { &mut default };
317
318         rustc_driver::RunCompiler::new(&args, callbacks).run()
319     }))
320 }
321
322 #[cfg(test)]
323 mod tests {
324     use super::*;
325
326     #[test]
327     fn test_arg_value() {
328         let args = &["--bar=bar", "--foobar", "123", "--foo"];
329
330         assert_eq!(arg_value(&[] as &[&str], "--foobar", |_| true), None);
331         assert_eq!(arg_value(args, "--bar", |_| false), None);
332         assert_eq!(arg_value(args, "--bar", |_| true), Some("bar"));
333         assert_eq!(arg_value(args, "--bar", |p| p == "bar"), Some("bar"));
334         assert_eq!(arg_value(args, "--bar", |p| p == "foo"), None);
335         assert_eq!(arg_value(args, "--foobar", |p| p == "foo"), None);
336         assert_eq!(arg_value(args, "--foobar", |p| p == "123"), Some("123"));
337         assert_eq!(arg_value(args, "--foo", |_| true), None);
338     }
339
340     #[test]
341     fn removes_clippy_args_from_start() {
342         let mut args = vec!["-D", "clippy::await_holding_lock", "--cfg", r#"feature="some_feat""#];
343         let clippy_args = ["-D", "clippy::await_holding_lock"].iter();
344
345         remove_clippy_args(&mut args, clippy_args);
346         assert_eq!(args, &["--cfg", r#"feature="some_feat""#]);
347     }
348
349     #[test]
350     fn removes_clippy_args_from_end() {
351         let mut args = vec!["-Zui-testing", "-A", "clippy::empty_loop", "--no-deps"];
352         let clippy_args = ["-A", "clippy::empty_loop", "--no-deps"].iter();
353
354         remove_clippy_args(&mut args, clippy_args);
355         assert_eq!(args, &["-Zui-testing"]);
356     }
357
358     #[test]
359     fn removes_clippy_args_from_middle() {
360         let mut args = vec!["-Zui-testing", "-W", "clippy::filter_map", "-L", "serde"];
361         let clippy_args = ["-W", "clippy::filter_map"].iter();
362
363         remove_clippy_args(&mut args, clippy_args);
364         assert_eq!(args, &["-Zui-testing", "-L", "serde"]);
365     }
366
367     #[test]
368     fn no_clippy_args_to_remove() {
369         let mut args = vec!["-Zui-testing", "-L", "serde"];
370         let clippy_args: [&str; 0] = [];
371
372         remove_clippy_args(&mut args, clippy_args.iter());
373         assert_eq!(args, &["-Zui-testing", "-L", "serde"]);
374     }
375 }