]> git.lizzy.rs Git - rust.git/blob - src/driver.rs
Auto merge of #6805 - matthiaskrgr:uca_nopub_6803, r=flip1995
[rust.git] / 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 #![deny(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::Session;
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::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 #[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, "--foo", |_| true), None);
64 }
65
66 fn track_clippy_args(sess: &Session, args_env_var: &Option<String>) {
67     sess.parse_sess.env_depinfo.borrow_mut().insert((
68         Symbol::intern("CLIPPY_ARGS"),
69         args_env_var.as_deref().map(Symbol::intern),
70     ));
71 }
72
73 struct DefaultCallbacks;
74 impl rustc_driver::Callbacks for DefaultCallbacks {}
75
76 /// This is different from `DefaultCallbacks` that it will inform Cargo to track the value of
77 /// `CLIPPY_ARGS` environment variable.
78 struct RustcCallbacks {
79     clippy_args_var: Option<String>,
80 }
81
82 impl rustc_driver::Callbacks for RustcCallbacks {
83     fn config(&mut self, config: &mut interface::Config) {
84         let previous = config.register_lints.take();
85         let clippy_args_var = self.clippy_args_var.take();
86         config.register_lints = Some(Box::new(move |sess, lint_store| {
87             if let Some(ref previous) = previous {
88                 (previous)(sess, lint_store);
89             }
90
91             track_clippy_args(sess, &clippy_args_var);
92         }));
93     }
94 }
95
96 struct ClippyCallbacks {
97     clippy_args_var: Option<String>,
98 }
99
100 impl rustc_driver::Callbacks for ClippyCallbacks {
101     fn config(&mut self, config: &mut interface::Config) {
102         let previous = config.register_lints.take();
103         let clippy_args_var = self.clippy_args_var.take();
104         config.register_lints = Some(Box::new(move |sess, mut lint_store| {
105             // technically we're ~guaranteed that this is none but might as well call anything that
106             // is there already. Certainly it can't hurt.
107             if let Some(previous) = &previous {
108                 (previous)(sess, lint_store);
109             }
110
111             track_clippy_args(sess, &clippy_args_var);
112
113             let conf = clippy_lints::read_conf(&[], &sess);
114             clippy_lints::register_plugins(&mut lint_store, &sess, &conf);
115             clippy_lints::register_pre_expansion_lints(&mut lint_store);
116             clippy_lints::register_renamed(&mut lint_store);
117         }));
118
119         // FIXME: #4825; This is required, because Clippy lints that are based on MIR have to be
120         // run on the unoptimized MIR. On the other hand this results in some false negatives. If
121         // MIR passes can be enabled / disabled separately, we should figure out, what passes to
122         // use for Clippy.
123         config.opts.debugging_opts.mir_opt_level = Some(0);
124     }
125 }
126
127 fn display_help() {
128     println!(
129         "\
130 Checks a package to catch common mistakes and improve your Rust code.
131
132 Usage:
133     cargo clippy [options] [--] [<opts>...]
134
135 Common options:
136     -h, --help               Print this message
137         --rustc              Pass all args to rustc
138     -V, --version            Print version info and exit
139
140 Other options are the same as `cargo check`.
141
142 To allow or deny a lint from the command line you can use `cargo clippy --`
143 with:
144
145     -W --warn OPT       Set lint warnings
146     -A --allow OPT      Set lint allowed
147     -D --deny OPT       Set lint denied
148     -F --forbid OPT     Set lint forbidden
149
150 You can use tool lints to allow or deny lints from your code, eg.:
151
152     #[allow(clippy::needless_lifetimes)]
153 "
154     );
155 }
156
157 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust-clippy/issues/new";
158
159 static ICE_HOOK: SyncLazy<Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static>> = SyncLazy::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 emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
173         rustc_errors::ColorConfig::Auto,
174         None,
175         false,
176         false,
177         None,
178         false,
179     ));
180     let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
181
182     // a .span_bug or .bug call has already printed what
183     // it wants to print.
184     if !info.payload().is::<rustc_errors::ExplicitBug>() {
185         let d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
186         handler.emit_diagnostic(&d);
187     }
188
189     let version_info = rustc_tools_util::get_version_info!();
190
191     let xs: Vec<Cow<'static, str>> = vec![
192         "the compiler unexpectedly panicked. this is a bug.".into(),
193         format!("we would appreciate a bug report: {}", bug_report_url).into(),
194         format!("Clippy version: {}", version_info).into(),
195     ];
196
197     for note in &xs {
198         handler.note_without_error(&note);
199     }
200
201     // If backtraces are enabled, also print the query stack
202     let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
203
204     let num_frames = if backtrace { None } else { Some(2) };
205
206     interface::try_print_query_stack(&handler, num_frames);
207 }
208
209 fn toolchain_path(home: Option<String>, toolchain: Option<String>) -> Option<PathBuf> {
210     home.and_then(|home| {
211         toolchain.map(|toolchain| {
212             let mut path = PathBuf::from(home);
213             path.push("toolchains");
214             path.push(toolchain);
215             path
216         })
217     })
218 }
219
220 #[allow(clippy::too_many_lines)]
221 pub fn main() {
222     rustc_driver::init_rustc_env_logger();
223     SyncLazy::force(&ICE_HOOK);
224     exit(rustc_driver::catch_with_exit_code(move || {
225         let mut orig_args: Vec<String> = env::args().collect();
226
227         // Get the sysroot, looking from most specific to this invocation to the least:
228         // - command line
229         // - runtime environment
230         //    - SYSROOT
231         //    - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
232         // - sysroot from rustc in the path
233         // - compile-time environment
234         //    - SYSROOT
235         //    - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
236         let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
237         let have_sys_root_arg = sys_root_arg.is_some();
238         let sys_root = sys_root_arg
239             .map(PathBuf::from)
240             .or_else(|| std::env::var("SYSROOT").ok().map(PathBuf::from))
241             .or_else(|| {
242                 let home = std::env::var("RUSTUP_HOME")
243                     .or_else(|_| std::env::var("MULTIRUST_HOME"))
244                     .ok();
245                 let toolchain = std::env::var("RUSTUP_TOOLCHAIN")
246                     .or_else(|_| std::env::var("MULTIRUST_TOOLCHAIN"))
247                     .ok();
248                 toolchain_path(home, toolchain)
249             })
250             .or_else(|| {
251                 Command::new("rustc")
252                     .arg("--print")
253                     .arg("sysroot")
254                     .output()
255                     .ok()
256                     .and_then(|out| String::from_utf8(out.stdout).ok())
257                     .map(|s| PathBuf::from(s.trim()))
258             })
259             .or_else(|| option_env!("SYSROOT").map(PathBuf::from))
260             .or_else(|| {
261                 let home = option_env!("RUSTUP_HOME")
262                     .or(option_env!("MULTIRUST_HOME"))
263                     .map(ToString::to_string);
264                 let toolchain = option_env!("RUSTUP_TOOLCHAIN")
265                     .or(option_env!("MULTIRUST_TOOLCHAIN"))
266                     .map(ToString::to_string);
267                 toolchain_path(home, toolchain)
268             })
269             .map(|pb| pb.to_string_lossy().to_string())
270             .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
271
272         // make "clippy-driver --rustc" work like a subcommand that passes further args to "rustc"
273         // for example `clippy-driver --rustc --version` will print the rustc version that clippy-driver
274         // uses
275         if let Some(pos) = orig_args.iter().position(|arg| arg == "--rustc") {
276             orig_args.remove(pos);
277             orig_args[0] = "rustc".to_string();
278
279             // if we call "rustc", we need to pass --sysroot here as well
280             let mut args: Vec<String> = orig_args.clone();
281             if !have_sys_root_arg {
282                 args.extend(vec!["--sysroot".into(), sys_root]);
283             };
284
285             return rustc_driver::RunCompiler::new(&args, &mut DefaultCallbacks).run();
286         }
287
288         if orig_args.iter().any(|a| a == "--version" || a == "-V") {
289             let version_info = rustc_tools_util::get_version_info!();
290             println!("{}", version_info);
291             exit(0);
292         }
293
294         // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
295         // We're invoking the compiler programmatically, so we ignore this/
296         let wrapper_mode = orig_args.get(1).map(Path::new).and_then(Path::file_stem) == Some("rustc".as_ref());
297
298         if wrapper_mode {
299             // we still want to be able to invoke it normally though
300             orig_args.remove(1);
301         }
302
303         if !wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
304             display_help();
305             exit(0);
306         }
307
308         // this conditional check for the --sysroot flag is there so users can call
309         // `clippy_driver` directly
310         // without having to pass --sysroot or anything
311         let mut args: Vec<String> = orig_args.clone();
312         if !have_sys_root_arg {
313             args.extend(vec!["--sysroot".into(), sys_root]);
314         };
315
316         let mut no_deps = false;
317         let clippy_args_var = env::var("CLIPPY_ARGS").ok();
318         let clippy_args = clippy_args_var
319             .as_deref()
320             .unwrap_or_default()
321             .split("__CLIPPY_HACKERY__")
322             .filter_map(|s| match s {
323                 "" => None,
324                 "--no-deps" => {
325                     no_deps = true;
326                     None
327                 },
328                 _ => Some(s.to_string()),
329             })
330             .chain(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()])
331             .collect::<Vec<String>>();
332
333         // We enable Clippy if one of the following conditions is met
334         // - IF Clippy is run on its test suite OR
335         // - IF Clippy is run on the main crate, not on deps (`!cap_lints_allow`) THEN
336         //    - IF `--no-deps` is not set (`!no_deps`) OR
337         //    - IF `--no-deps` is set and Clippy is run on the specified primary package
338         let clippy_tests_set = env::var("__CLIPPY_INTERNAL_TESTS").map_or(false, |val| val == "true");
339         let cap_lints_allow = arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_some();
340         let in_primary_package = env::var("CARGO_PRIMARY_PACKAGE").is_ok();
341
342         let clippy_enabled = clippy_tests_set || (!cap_lints_allow && (!no_deps || in_primary_package));
343         if clippy_enabled {
344             args.extend(clippy_args);
345         }
346
347         if clippy_enabled {
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 }