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