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