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