]> git.lizzy.rs Git - rust.git/blob - src/driver.rs
Auto merge of #6697 - camsteffen:vec-init-push-fp, 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_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>> = SyncLazy::new(|| {
125     let hook = panic::take_hook();
126     panic::set_hook(Box::new(|info| report_clippy_ice(info, BUG_REPORT_URL)));
127     hook
128 });
129
130 fn report_clippy_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
131     // Invoke our ICE handler, which prints the actual panic message and optionally a backtrace
132     (*ICE_HOOK)(info);
133
134     // Separate the output with an empty line
135     eprintln!();
136
137     let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
138         rustc_errors::ColorConfig::Auto,
139         None,
140         false,
141         false,
142         None,
143         false,
144     ));
145     let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
146
147     // a .span_bug or .bug call has already printed what
148     // it wants to print.
149     if !info.payload().is::<rustc_errors::ExplicitBug>() {
150         let d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
151         handler.emit_diagnostic(&d);
152     }
153
154     let version_info = rustc_tools_util::get_version_info!();
155
156     let xs: Vec<Cow<'static, str>> = vec![
157         "the compiler unexpectedly panicked. this is a bug.".into(),
158         format!("we would appreciate a bug report: {}", bug_report_url).into(),
159         format!("Clippy version: {}", version_info).into(),
160     ];
161
162     for note in &xs {
163         handler.note_without_error(&note);
164     }
165
166     // If backtraces are enabled, also print the query stack
167     let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
168
169     let num_frames = if backtrace { None } else { Some(2) };
170
171     TyCtxt::try_print_query_stack(&handler, num_frames);
172 }
173
174 fn toolchain_path(home: Option<String>, toolchain: Option<String>) -> Option<PathBuf> {
175     home.and_then(|home| {
176         toolchain.map(|toolchain| {
177             let mut path = PathBuf::from(home);
178             path.push("toolchains");
179             path.push(toolchain);
180             path
181         })
182     })
183 }
184
185 #[allow(clippy::too_many_lines)]
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 = orig_args.get(1).map(Path::new).and_then(Path::file_stem) == Some("rustc".as_ref());
262
263         if wrapper_mode {
264             // we still want to be able to invoke it normally though
265             orig_args.remove(1);
266         }
267
268         if !wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
269             display_help();
270             exit(0);
271         }
272
273         // this conditional check for the --sysroot flag is there so users can call
274         // `clippy_driver` directly
275         // without having to pass --sysroot or anything
276         let mut args: Vec<String> = orig_args.clone();
277         if !have_sys_root_arg {
278             args.extend(vec!["--sysroot".into(), sys_root]);
279         };
280
281         let mut no_deps = false;
282         let clippy_args = env::var("CLIPPY_ARGS")
283             .unwrap_or_default()
284             .split("__CLIPPY_HACKERY__")
285             .filter_map(|s| match s {
286                 "" => None,
287                 "--no-deps" => {
288                     no_deps = true;
289                     None
290                 },
291                 _ => Some(s.to_string()),
292             })
293             .chain(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()])
294             .collect::<Vec<String>>();
295
296         // We enable Clippy if one of the following conditions is met
297         // - IF Clippy is run on its test suite OR
298         // - IF Clippy is run on the main crate, not on deps (`!cap_lints_allow`) THEN
299         //    - IF `--no-deps` is not set (`!no_deps`) OR
300         //    - IF `--no-deps` is set and Clippy is run on the specified primary package
301         let clippy_tests_set = env::var("__CLIPPY_INTERNAL_TESTS").map_or(false, |val| val == "true");
302         let cap_lints_allow = arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_some();
303         let in_primary_package = env::var("CARGO_PRIMARY_PACKAGE").is_ok();
304
305         let clippy_enabled = clippy_tests_set || (!cap_lints_allow && (!no_deps || in_primary_package));
306         if clippy_enabled {
307             args.extend(clippy_args);
308         }
309
310         let mut clippy = ClippyCallbacks;
311         let mut default = DefaultCallbacks;
312         let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
313             if clippy_enabled { &mut clippy } else { &mut default };
314
315         rustc_driver::RunCompiler::new(&args, callbacks).run()
316     }))
317 }