]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/src/driver.rs
Merge commit 'c2c07fa9d095931eb5684a42942a7b573a0c5238' into clippyup
[rust.git] / src / tools / clippy / 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 extern crate rustc_data_structures;
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 lazy_static::lazy_static;
21 use std::borrow::Cow;
22 use std::env;
23 use std::ops::Deref;
24 use std::panic;
25 use std::path::{Path, PathBuf};
26 use std::process::{exit, Command};
27
28 mod lintlist;
29
30 /// If a command-line option matches `find_arg`, then apply the predicate `pred` on its value. If
31 /// true, then return it. The parameter is assumed to be either `--arg=value` or `--arg value`.
32 fn arg_value<'a, T: Deref<Target = str>>(
33     args: &'a [T],
34     find_arg: &str,
35     pred: impl Fn(&str) -> bool,
36 ) -> Option<&'a str> {
37     let mut args = args.iter().map(Deref::deref);
38     while let Some(arg) = args.next() {
39         let mut arg = arg.splitn(2, '=');
40         if arg.next() != Some(find_arg) {
41             continue;
42         }
43
44         match arg.next().or_else(|| args.next()) {
45             Some(v) if pred(v) => return Some(v),
46             _ => {},
47         }
48     }
49     None
50 }
51
52 #[test]
53 fn test_arg_value() {
54     let args = &["--bar=bar", "--foobar", "123", "--foo"];
55
56     assert_eq!(arg_value(&[] as &[&str], "--foobar", |_| true), None);
57     assert_eq!(arg_value(args, "--bar", |_| false), None);
58     assert_eq!(arg_value(args, "--bar", |_| true), Some("bar"));
59     assert_eq!(arg_value(args, "--bar", |p| p == "bar"), Some("bar"));
60     assert_eq!(arg_value(args, "--bar", |p| p == "foo"), None);
61     assert_eq!(arg_value(args, "--foobar", |p| p == "foo"), None);
62     assert_eq!(arg_value(args, "--foobar", |p| p == "123"), Some("123"));
63     assert_eq!(arg_value(args, "--foo", |_| true), None);
64 }
65
66 struct DefaultCallbacks;
67 impl rustc_driver::Callbacks for DefaultCallbacks {}
68
69 struct ClippyCallbacks;
70 impl rustc_driver::Callbacks for ClippyCallbacks {
71     fn config(&mut self, config: &mut interface::Config) {
72         let previous = config.register_lints.take();
73         config.register_lints = Some(Box::new(move |sess, mut lint_store| {
74             // technically we're ~guaranteed that this is none but might as well call anything that
75             // is there already. Certainly it can't hurt.
76             if let Some(previous) = &previous {
77                 (previous)(sess, lint_store);
78             }
79
80             let conf = clippy_lints::read_conf(&[], &sess);
81             clippy_lints::register_plugins(&mut lint_store, &sess, &conf);
82             clippy_lints::register_pre_expansion_lints(&mut lint_store);
83             clippy_lints::register_renamed(&mut lint_store);
84         }));
85
86         // FIXME: #4825; This is required, because Clippy lints that are based on MIR have to be
87         // run on the unoptimized MIR. On the other hand this results in some false negatives. If
88         // MIR passes can be enabled / disabled separately, we should figure out, what passes to
89         // use for Clippy.
90         config.opts.debugging_opts.mir_opt_level = 0;
91     }
92 }
93
94 #[allow(clippy::find_map, clippy::filter_map)]
95 fn describe_lints() {
96     use lintlist::{Level, Lint, ALL_LINTS, LINT_LEVELS};
97     use rustc_data_structures::fx::FxHashSet;
98
99     println!(
100         "
101 Available lint options:
102     -W <foo>           Warn about <foo>
103     -A <foo>           Allow <foo>
104     -D <foo>           Deny <foo>
105     -F <foo>           Forbid <foo> (deny <foo> and all attempts to override)
106
107 "
108     );
109
110     let lint_level = |lint: &Lint| {
111         LINT_LEVELS
112             .iter()
113             .find(|level_mapping| level_mapping.0 == lint.group)
114             .map(|(_, level)| match level {
115                 Level::Allow => "allow",
116                 Level::Warn => "warn",
117                 Level::Deny => "deny",
118             })
119             .unwrap()
120     };
121
122     let mut lints: Vec<_> = ALL_LINTS.iter().collect();
123     // The sort doesn't case-fold but it's doubtful we care.
124     lints.sort_by_cached_key(|x: &&Lint| (lint_level(x), x.name));
125
126     let max_lint_name_len = lints
127         .iter()
128         .map(|lint| lint.name.len())
129         .map(|len| len + "clippy::".len())
130         .max()
131         .unwrap_or(0);
132
133     let padded = |x: &str| {
134         let mut s = " ".repeat(max_lint_name_len - x.chars().count());
135         s.push_str(x);
136         s
137     };
138
139     let scoped = |x: &str| format!("clippy::{}", x);
140
141     let lint_groups: FxHashSet<_> = lints.iter().map(|lint| lint.group).collect();
142
143     println!("Lint checks provided by clippy:\n");
144     println!("    {}  {:7.7}  meaning", padded("name"), "default");
145     println!("    {}  {:7.7}  -------", padded("----"), "-------");
146
147     let print_lints = |lints: &[&Lint]| {
148         for lint in lints {
149             let name = lint.name.replace("_", "-");
150             println!(
151                 "    {}  {:7.7}  {}",
152                 padded(&scoped(&name)),
153                 lint_level(lint),
154                 lint.desc
155             );
156         }
157         println!("\n");
158     };
159
160     print_lints(&lints);
161
162     let max_group_name_len = std::cmp::max(
163         "clippy::all".len(),
164         lint_groups
165             .iter()
166             .map(|group| group.len())
167             .map(|len| len + "clippy::".len())
168             .max()
169             .unwrap_or(0),
170     );
171
172     let padded_group = |x: &str| {
173         let mut s = " ".repeat(max_group_name_len - x.chars().count());
174         s.push_str(x);
175         s
176     };
177
178     println!("Lint groups provided by clippy:\n");
179     println!("    {}  sub-lints", padded_group("name"));
180     println!("    {}  ---------", padded_group("----"));
181     println!("    {}  the set of all clippy lints", padded_group("clippy::all"));
182
183     let print_lint_groups = || {
184         for group in lint_groups {
185             let name = group.to_lowercase().replace("_", "-");
186             let desc = lints
187                 .iter()
188                 .filter(|&lint| lint.group == group)
189                 .map(|lint| lint.name)
190                 .map(|name| name.replace("_", "-"))
191                 .collect::<Vec<String>>()
192                 .join(", ");
193             println!("    {}  {}", padded_group(&scoped(&name)), desc);
194         }
195         println!("\n");
196     };
197
198     print_lint_groups();
199 }
200
201 fn display_help() {
202     println!(
203         "\
204 Checks a package to catch common mistakes and improve your Rust code.
205
206 Usage:
207     cargo clippy [options] [--] [<opts>...]
208
209 Common options:
210     -h, --help               Print this message
211         --rustc              Pass all args to rustc
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     }
264
265     let version_info = rustc_tools_util::get_version_info!();
266
267     let xs: Vec<Cow<'static, str>> = vec![
268         "the compiler unexpectedly panicked. this is a bug.".into(),
269         format!("we would appreciate a bug report: {}", bug_report_url).into(),
270         format!("Clippy version: {}", version_info).into(),
271     ];
272
273     for note in &xs {
274         handler.note_without_error(&note);
275     }
276
277     // If backtraces are enabled, also print the query stack
278     let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
279
280     if backtrace {
281         TyCtxt::try_print_query_stack(&handler);
282     }
283 }
284
285 fn toolchain_path(home: Option<String>, toolchain: Option<String>) -> Option<PathBuf> {
286     home.and_then(|home| {
287         toolchain.map(|toolchain| {
288             let mut path = PathBuf::from(home);
289             path.push("toolchains");
290             path.push(toolchain);
291             path
292         })
293     })
294 }
295
296 pub fn main() {
297     rustc_driver::init_rustc_env_logger();
298     lazy_static::initialize(&ICE_HOOK);
299     exit(rustc_driver::catch_with_exit_code(move || {
300         let mut orig_args: Vec<String> = env::args().collect();
301
302         // Get the sysroot, looking from most specific to this invocation to the least:
303         // - command line
304         // - runtime environment
305         //    - SYSROOT
306         //    - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
307         // - sysroot from rustc in the path
308         // - compile-time environment
309         //    - SYSROOT
310         //    - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
311         let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
312         let have_sys_root_arg = sys_root_arg.is_some();
313         let sys_root = sys_root_arg
314             .map(PathBuf::from)
315             .or_else(|| std::env::var("SYSROOT").ok().map(PathBuf::from))
316             .or_else(|| {
317                 let home = std::env::var("RUSTUP_HOME")
318                     .or_else(|_| std::env::var("MULTIRUST_HOME"))
319                     .ok();
320                 let toolchain = std::env::var("RUSTUP_TOOLCHAIN")
321                     .or_else(|_| std::env::var("MULTIRUST_TOOLCHAIN"))
322                     .ok();
323                 toolchain_path(home, toolchain)
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             .or_else(|| {
336                 let home = option_env!("RUSTUP_HOME")
337                     .or(option_env!("MULTIRUST_HOME"))
338                     .map(ToString::to_string);
339                 let toolchain = option_env!("RUSTUP_TOOLCHAIN")
340                     .or(option_env!("MULTIRUST_TOOLCHAIN"))
341                     .map(ToString::to_string);
342                 toolchain_path(home, toolchain)
343             })
344             .map(|pb| pb.to_string_lossy().to_string())
345             .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
346
347         // make "clippy-driver --rustc" work like a subcommand that passes further args to "rustc"
348         // for example `clippy-driver --rustc --version` will print the rustc version that clippy-driver
349         // uses
350         if let Some(pos) = orig_args.iter().position(|arg| arg == "--rustc") {
351             orig_args.remove(pos);
352             orig_args[0] = "rustc".to_string();
353
354             // if we call "rustc", we need to pass --sysroot here as well
355             let mut args: Vec<String> = orig_args.clone();
356             if !have_sys_root_arg {
357                 args.extend(vec!["--sysroot".into(), sys_root]);
358             };
359
360             return rustc_driver::run_compiler(&args, &mut DefaultCallbacks, None, None);
361         }
362
363         if orig_args.iter().any(|a| a == "--version" || a == "-V") {
364             let version_info = rustc_tools_util::get_version_info!();
365             println!("{}", version_info);
366             exit(0);
367         }
368
369         // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
370         // We're invoking the compiler programmatically, so we ignore this/
371         let wrapper_mode = orig_args.get(1).map(Path::new).and_then(Path::file_stem) == Some("rustc".as_ref());
372
373         if wrapper_mode {
374             // we still want to be able to invoke it normally though
375             orig_args.remove(1);
376         }
377
378         if !wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
379             display_help();
380             exit(0);
381         }
382
383         let should_describe_lints = || {
384             let args: Vec<_> = env::args().collect();
385             args.windows(2).any(|args| {
386                 args[1] == "help"
387                     && match args[0].as_str() {
388                         "-W" | "-A" | "-D" | "-F" => true,
389                         _ => false,
390                     }
391             })
392         };
393
394         if !wrapper_mode && should_describe_lints() {
395             describe_lints();
396             exit(0);
397         }
398
399         // this conditional check for the --sysroot flag is there so users can call
400         // `clippy_driver` directly
401         // without having to pass --sysroot or anything
402         let mut args: Vec<String> = orig_args.clone();
403         if !have_sys_root_arg {
404             args.extend(vec!["--sysroot".into(), sys_root]);
405         };
406
407         // this check ensures that dependencies are built but not linted and the final
408         // crate is linted but not built
409         let clippy_enabled = env::var("CLIPPY_TESTS").map_or(false, |val| val == "true")
410             || arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_none();
411
412         if clippy_enabled {
413             args.extend(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()]);
414             if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
415                 args.extend(extra_args.split("__CLIPPY_HACKERY__").filter_map(|s| {
416                     if s.is_empty() {
417                         None
418                     } else {
419                         Some(s.to_string())
420                     }
421                 }));
422             }
423         }
424         let mut clippy = ClippyCallbacks;
425         let mut default = DefaultCallbacks;
426         let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
427             if clippy_enabled { &mut clippy } else { &mut default };
428         rustc_driver::run_compiler(&args, callbacks, None, None)
429     }))
430 }