]> git.lizzy.rs Git - rust.git/blob - src/driver.rs
Auto merge of #4922 - oli-cosmian:patch-1, r=flip1995
[rust.git] / src / driver.rs
1 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
2 #![feature(rustc_private)]
3
4 // FIXME: switch to something more ergonomic here, once available.
5 // (Currently there is no way to opt into sysroot crates without `extern crate`.)
6 #[allow(unused_extern_crates)]
7 extern crate rustc;
8 #[allow(unused_extern_crates)]
9 extern crate rustc_driver;
10 #[allow(unused_extern_crates)]
11 extern crate rustc_errors;
12 #[allow(unused_extern_crates)]
13 extern crate rustc_interface;
14
15 use rustc::ty::TyCtxt;
16 use rustc_interface::interface;
17 use rustc_tools_util::*;
18
19 use lazy_static::lazy_static;
20 use std::borrow::Cow;
21 use std::panic;
22 use std::path::{Path, PathBuf};
23 use std::process::{exit, Command};
24
25 mod lintlist;
26
27 /// If a command-line option matches `find_arg`, then apply the predicate `pred` on its value. If
28 /// true, then return it. The parameter is assumed to be either `--arg=value` or `--arg value`.
29 fn arg_value<'a>(
30     args: impl IntoIterator<Item = &'a String>,
31     find_arg: &str,
32     pred: impl Fn(&str) -> bool,
33 ) -> Option<&'a str> {
34     let mut args = args.into_iter().map(String::as_str);
35
36     while let Some(arg) = args.next() {
37         let arg: Vec<_> = arg.splitn(2, '=').collect();
38         if arg.get(0) != Some(&find_arg) {
39             continue;
40         }
41
42         let value = arg.get(1).cloned().or_else(|| args.next());
43         if value.as_ref().map_or(false, |p| pred(p)) {
44             return value;
45         }
46     }
47     None
48 }
49
50 #[test]
51 fn test_arg_value() {
52     let args: Vec<_> = ["--bar=bar", "--foobar", "123", "--foo"]
53         .iter()
54         .map(std::string::ToString::to_string)
55         .collect();
56
57     assert_eq!(arg_value(None, "--foobar", |_| true), None);
58     assert_eq!(arg_value(&args, "--bar", |_| false), None);
59     assert_eq!(arg_value(&args, "--bar", |_| true), Some("bar"));
60     assert_eq!(arg_value(&args, "--bar", |p| p == "bar"), Some("bar"));
61     assert_eq!(arg_value(&args, "--bar", |p| p == "foo"), None);
62     assert_eq!(arg_value(&args, "--foobar", |p| p == "foo"), None);
63     assert_eq!(arg_value(&args, "--foobar", |p| p == "123"), Some("123"));
64     assert_eq!(arg_value(&args, "--foo", |_| true), None);
65 }
66
67 #[allow(clippy::too_many_lines)]
68
69 struct ClippyCallbacks;
70
71 impl rustc_driver::Callbacks for ClippyCallbacks {
72     fn config(&mut self, config: &mut interface::Config) {
73         let previous = config.register_lints.take();
74         config.register_lints = Some(Box::new(move |sess, mut lint_store| {
75             // technically we're ~guaranteed that this is none but might as well call anything that
76             // is there already. Certainly it can't hurt.
77             if let Some(previous) = &previous {
78                 (previous)(sess, lint_store);
79             }
80
81             let conf = clippy_lints::read_conf(&[], &sess);
82             clippy_lints::register_plugins(&mut lint_store, &sess, &conf);
83             clippy_lints::register_pre_expansion_lints(&mut lint_store, &conf);
84             clippy_lints::register_renamed(&mut lint_store);
85         }));
86
87         // FIXME: #4825; This is required, because Clippy lints that are based on MIR have to be
88         // run on the unoptimized MIR. On the other hand this results in some false negatives. If
89         // MIR passes can be enabled / disabled separately, we should figure out, what passes to
90         // use for Clippy.
91         config.opts.debugging_opts.mir_opt_level = 0;
92     }
93 }
94
95 #[allow(clippy::find_map, clippy::filter_map)]
96 fn describe_lints() {
97     use lintlist::*;
98     use std::collections::HashSet;
99
100     println!(
101         "
102 Available lint options:
103     -W <foo>           Warn about <foo>
104     -A <foo>           Allow <foo>
105     -D <foo>           Deny <foo>
106     -F <foo>           Forbid <foo> (deny <foo> and all attempts to override)
107
108 "
109     );
110
111     let lint_level = |lint: &Lint| {
112         LINT_LEVELS
113             .iter()
114             .find(|level_mapping| level_mapping.0 == lint.group)
115             .map(|(_, level)| match level {
116                 Level::Allow => "allow",
117                 Level::Warn => "warn",
118                 Level::Deny => "deny",
119             })
120             .unwrap()
121     };
122
123     let mut lints: Vec<_> = ALL_LINTS.iter().collect();
124     // The sort doesn't case-fold but it's doubtful we care.
125     lints.sort_by_cached_key(|x: &&Lint| (lint_level(x), x.name));
126
127     let max_lint_name_len = lints
128         .iter()
129         .map(|lint| lint.name.len())
130         .map(|len| len + "clippy::".len())
131         .max()
132         .unwrap_or(0);
133
134     let padded = |x: &str| {
135         let mut s = " ".repeat(max_lint_name_len - x.chars().count());
136         s.push_str(x);
137         s
138     };
139
140     let scoped = |x: &str| format!("clippy::{}", x);
141
142     let lint_groups: HashSet<_> = lints.iter().map(|lint| lint.group).collect();
143
144     println!("Lint checks provided by clippy:\n");
145     println!("    {}  {:7.7}  meaning", padded("name"), "default");
146     println!("    {}  {:7.7}  -------", padded("----"), "-------");
147
148     let print_lints = |lints: &[&Lint]| {
149         for lint in lints {
150             let name = lint.name.replace("_", "-");
151             println!(
152                 "    {}  {:7.7}  {}",
153                 padded(&scoped(&name)),
154                 lint_level(lint),
155                 lint.desc
156             );
157         }
158         println!("\n");
159     };
160
161     print_lints(&lints);
162
163     let max_group_name_len = std::cmp::max(
164         "clippy::all".len(),
165         lint_groups
166             .iter()
167             .map(|group| group.len())
168             .map(|len| len + "clippy::".len())
169             .max()
170             .unwrap_or(0),
171     );
172
173     let padded_group = |x: &str| {
174         let mut s = " ".repeat(max_group_name_len - x.chars().count());
175         s.push_str(x);
176         s
177     };
178
179     println!("Lint groups provided by clippy:\n");
180     println!("    {}  sub-lints", padded_group("name"));
181     println!("    {}  ---------", padded_group("----"));
182     println!("    {}  the set of all clippy lints", padded_group("clippy::all"));
183
184     let print_lint_groups = || {
185         for group in lint_groups {
186             let name = group.to_lowercase().replace("_", "-");
187             let desc = lints
188                 .iter()
189                 .filter(|&lint| lint.group == group)
190                 .map(|lint| lint.name)
191                 .map(|name| name.replace("_", "-"))
192                 .collect::<Vec<String>>()
193                 .join(", ");
194             println!("    {}  {}", padded_group(&scoped(&name)), desc);
195         }
196         println!("\n");
197     };
198
199     print_lint_groups();
200 }
201
202 fn display_help() {
203     println!(
204         "\
205 Checks a package to catch common mistakes and improve your Rust code.
206
207 Usage:
208     cargo clippy [options] [--] [<opts>...]
209
210 Common options:
211     -h, --help               Print this message
212     -V, --version            Print version info and exit
213
214 Other options are the same as `cargo check`.
215
216 To allow or deny a lint from the command line you can use `cargo clippy --`
217 with:
218
219     -W --warn OPT       Set lint warnings
220     -A --allow OPT      Set lint allowed
221     -D --deny OPT       Set lint denied
222     -F --forbid OPT     Set lint forbidden
223
224 You can use tool lints to allow or deny lints from your code, eg.:
225
226     #[allow(clippy::needless_lifetimes)]
227 "
228     );
229 }
230
231 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust-clippy/issues/new";
232
233 lazy_static! {
234     static ref ICE_HOOK: Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static> = {
235         let hook = panic::take_hook();
236         panic::set_hook(Box::new(|info| report_clippy_ice(info, BUG_REPORT_URL)));
237         hook
238     };
239 }
240
241 fn report_clippy_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
242     // Invoke our ICE handler, which prints the actual panic message and optionally a backtrace
243     (*ICE_HOOK)(info);
244
245     // Separate the output with an empty line
246     eprintln!();
247
248     let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
249         rustc_errors::ColorConfig::Auto,
250         None,
251         false,
252         false,
253         None,
254         false,
255     ));
256     let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
257
258     // a .span_bug or .bug call has already printed what
259     // it wants to print.
260     if !info.payload().is::<rustc_errors::ExplicitBug>() {
261         let d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
262         handler.emit_diagnostic(&d);
263         handler.abort_if_errors_and_should_abort();
264     }
265
266     let version_info = rustc_tools_util::get_version_info!();
267
268     let xs: Vec<Cow<'static, str>> = vec![
269         "the compiler unexpectedly panicked. this is a bug.".into(),
270         format!("we would appreciate a bug report: {}", bug_report_url).into(),
271         format!("Clippy version: {}", version_info).into(),
272     ];
273
274     for note in &xs {
275         handler.note_without_error(&note);
276     }
277
278     // If backtraces are enabled, also print the query stack
279     let backtrace = std::env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
280
281     if backtrace {
282         TyCtxt::try_print_query_stack(&handler);
283     }
284 }
285
286 pub fn main() {
287     rustc_driver::init_rustc_env_logger();
288     lazy_static::initialize(&ICE_HOOK);
289     exit(
290         rustc_driver::catch_fatal_errors(move || {
291             use std::env;
292
293             if std::env::args().any(|a| a == "--version" || a == "-V") {
294                 let version_info = rustc_tools_util::get_version_info!();
295                 println!("{}", version_info);
296                 exit(0);
297             }
298
299             let mut orig_args: Vec<String> = env::args().collect();
300
301             // Get the sysroot, looking from most specific to this invocation to the least:
302             // - command line
303             // - runtime environment
304             //    - SYSROOT
305             //    - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
306             // - sysroot from rustc in the path
307             // - compile-time environment
308             let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
309             let have_sys_root_arg = sys_root_arg.is_some();
310             let sys_root = sys_root_arg
311                 .map(PathBuf::from)
312                 .or_else(|| std::env::var("SYSROOT").ok().map(PathBuf::from))
313                 .or_else(|| {
314                     let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
315                     let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
316                     home.and_then(|home| {
317                         toolchain.map(|toolchain| {
318                             let mut path = PathBuf::from(home);
319                             path.push("toolchains");
320                             path.push(toolchain);
321                             path
322                         })
323                     })
324                 })
325                 .or_else(|| {
326                     Command::new("rustc")
327                         .arg("--print")
328                         .arg("sysroot")
329                         .output()
330                         .ok()
331                         .and_then(|out| String::from_utf8(out.stdout).ok())
332                         .map(|s| PathBuf::from(s.trim()))
333                 })
334                 .or_else(|| option_env!("SYSROOT").map(PathBuf::from))
335                 .map(|pb| pb.to_string_lossy().to_string())
336                 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
337
338             // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
339             // We're invoking the compiler programmatically, so we ignore this/
340             let wrapper_mode = orig_args.get(1).map(Path::new).and_then(Path::file_stem) == Some("rustc".as_ref());
341
342             if wrapper_mode {
343                 // we still want to be able to invoke it normally though
344                 orig_args.remove(1);
345             }
346
347             if !wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
348                 display_help();
349                 exit(0);
350             }
351
352             let should_describe_lints = || {
353                 let args: Vec<_> = std::env::args().collect();
354                 args.windows(2).any(|args| {
355                     args[1] == "help"
356                         && match args[0].as_str() {
357                             "-W" | "-A" | "-D" | "-F" => true,
358                             _ => false,
359                         }
360                 })
361             };
362
363             if !wrapper_mode && should_describe_lints() {
364                 describe_lints();
365                 exit(0);
366             }
367
368             // this conditional check for the --sysroot flag is there so users can call
369             // `clippy_driver` directly
370             // without having to pass --sysroot or anything
371             let mut args: Vec<String> = if have_sys_root_arg {
372                 orig_args.clone()
373             } else {
374                 orig_args
375                     .clone()
376                     .into_iter()
377                     .chain(Some("--sysroot".to_owned()))
378                     .chain(Some(sys_root))
379                     .collect()
380             };
381
382             // this check ensures that dependencies are built but not linted and the final
383             // crate is linted but not built
384             let clippy_enabled = env::var("CLIPPY_TESTS").map_or(false, |val| val == "true")
385                 || arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_none();
386
387             if clippy_enabled {
388                 args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
389                 if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
390                     args.extend(extra_args.split("__CLIPPY_HACKERY__").filter_map(|s| {
391                         if s.is_empty() {
392                             None
393                         } else {
394                             Some(s.to_string())
395                         }
396                     }));
397                 }
398             }
399
400             let mut clippy = ClippyCallbacks;
401             let mut default = rustc_driver::DefaultCallbacks;
402             let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
403                 if clippy_enabled { &mut clippy } else { &mut default };
404             let args = args;
405             rustc_driver::run_compiler(&args, callbacks, None, None)
406         })
407         .and_then(|result| result)
408         .is_err() as i32,
409     )
410 }