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