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