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