]> git.lizzy.rs Git - rust.git/blob - src/driver.rs
Rollup merge of #5716 - bugadani:patch-1, r=matthiaskrgr
[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         --rustc              Pass all args to rustc
217     -V, --version            Print version info and exit
218
219 Other options are the same as `cargo check`.
220
221 To allow or deny a lint from the command line you can use `cargo clippy --`
222 with:
223
224     -W --warn OPT       Set lint warnings
225     -A --allow OPT      Set lint allowed
226     -D --deny OPT       Set lint denied
227     -F --forbid OPT     Set lint forbidden
228
229 You can use tool lints to allow or deny lints from your code, eg.:
230
231     #[allow(clippy::needless_lifetimes)]
232 "
233     );
234 }
235
236 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust-clippy/issues/new";
237
238 lazy_static! {
239     static ref ICE_HOOK: Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static> = {
240         let hook = panic::take_hook();
241         panic::set_hook(Box::new(|info| report_clippy_ice(info, BUG_REPORT_URL)));
242         hook
243     };
244 }
245
246 fn report_clippy_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
247     // Invoke our ICE handler, which prints the actual panic message and optionally a backtrace
248     (*ICE_HOOK)(info);
249
250     // Separate the output with an empty line
251     eprintln!();
252
253     let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
254         rustc_errors::ColorConfig::Auto,
255         None,
256         false,
257         false,
258         None,
259         false,
260     ));
261     let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
262
263     // a .span_bug or .bug call has already printed what
264     // it wants to print.
265     if !info.payload().is::<rustc_errors::ExplicitBug>() {
266         let d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
267         handler.emit_diagnostic(&d);
268     }
269
270     let version_info = rustc_tools_util::get_version_info!();
271
272     let xs: Vec<Cow<'static, str>> = vec![
273         "the compiler unexpectedly panicked. this is a bug.".into(),
274         format!("we would appreciate a bug report: {}", bug_report_url).into(),
275         format!("Clippy version: {}", version_info).into(),
276     ];
277
278     for note in &xs {
279         handler.note_without_error(&note);
280     }
281
282     // If backtraces are enabled, also print the query stack
283     let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
284
285     if backtrace {
286         TyCtxt::try_print_query_stack(&handler);
287     }
288 }
289
290 fn toolchain_path(home: Option<String>, toolchain: Option<String>) -> Option<PathBuf> {
291     home.and_then(|home| {
292         toolchain.map(|toolchain| {
293             let mut path = PathBuf::from(home);
294             path.push("toolchains");
295             path.push(toolchain);
296             path
297         })
298     })
299 }
300
301 pub fn main() {
302     rustc_driver::init_rustc_env_logger();
303     lazy_static::initialize(&ICE_HOOK);
304     exit(rustc_driver::catch_with_exit_code(move || {
305         let mut orig_args: Vec<String> = env::args().collect();
306
307         // Get the sysroot, looking from most specific to this invocation to the least:
308         // - command line
309         // - runtime environment
310         //    - SYSROOT
311         //    - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
312         // - sysroot from rustc in the path
313         // - compile-time environment
314         //    - SYSROOT
315         //    - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
316         let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
317         let have_sys_root_arg = sys_root_arg.is_some();
318         let sys_root = sys_root_arg
319             .map(PathBuf::from)
320             .or_else(|| std::env::var("SYSROOT").ok().map(PathBuf::from))
321             .or_else(|| {
322                 let home = std::env::var("RUSTUP_HOME")
323                     .or_else(|_| std::env::var("MULTIRUST_HOME"))
324                     .ok();
325                 let toolchain = std::env::var("RUSTUP_TOOLCHAIN")
326                     .or_else(|_| std::env::var("MULTIRUST_TOOLCHAIN"))
327                     .ok();
328                 toolchain_path(home, toolchain)
329             })
330             .or_else(|| {
331                 Command::new("rustc")
332                     .arg("--print")
333                     .arg("sysroot")
334                     .output()
335                     .ok()
336                     .and_then(|out| String::from_utf8(out.stdout).ok())
337                     .map(|s| PathBuf::from(s.trim()))
338             })
339             .or_else(|| option_env!("SYSROOT").map(PathBuf::from))
340             .or_else(|| {
341                 let home = option_env!("RUSTUP_HOME")
342                     .or(option_env!("MULTIRUST_HOME"))
343                     .map(ToString::to_string);
344                 let toolchain = option_env!("RUSTUP_TOOLCHAIN")
345                     .or(option_env!("MULTIRUST_TOOLCHAIN"))
346                     .map(ToString::to_string);
347                 toolchain_path(home, toolchain)
348             })
349             .map(|pb| pb.to_string_lossy().to_string())
350             .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
351
352         // make "clippy-driver --rustc" work like a subcommand that passes further args to "rustc"
353         // for example `clippy-driver --rustc --version` will print the rustc version that clippy-driver
354         // uses
355         if let Some(pos) = orig_args.iter().position(|arg| arg == "--rustc") {
356             orig_args.remove(pos);
357             orig_args[0] = "rustc".to_string();
358
359             // if we call "rustc", we need to pass --sysroot here as well
360             let mut args: Vec<String> = orig_args.clone();
361             if !have_sys_root_arg {
362                 args.extend(vec!["--sysroot".into(), sys_root]);
363             };
364
365             return rustc_driver::run_compiler(&args, &mut DefaultCallbacks, None, None);
366         }
367
368         if orig_args.iter().any(|a| a == "--version" || a == "-V") {
369             let version_info = rustc_tools_util::get_version_info!();
370             println!("{}", version_info);
371             exit(0);
372         }
373
374         // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
375         // We're invoking the compiler programmatically, so we ignore this/
376         let wrapper_mode = orig_args.get(1).map(Path::new).and_then(Path::file_stem) == Some("rustc".as_ref());
377
378         if wrapper_mode {
379             // we still want to be able to invoke it normally though
380             orig_args.remove(1);
381         }
382
383         if !wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
384             display_help();
385             exit(0);
386         }
387
388         let should_describe_lints = || {
389             let args: Vec<_> = env::args().collect();
390             args.windows(2).any(|args| {
391                 args[1] == "help"
392                     && match args[0].as_str() {
393                         "-W" | "-A" | "-D" | "-F" => true,
394                         _ => false,
395                     }
396             })
397         };
398
399         if !wrapper_mode && should_describe_lints() {
400             describe_lints();
401             exit(0);
402         }
403
404         // this conditional check for the --sysroot flag is there so users can call
405         // `clippy_driver` directly
406         // without having to pass --sysroot or anything
407         let mut args: Vec<String> = orig_args.clone();
408         if !have_sys_root_arg {
409             args.extend(vec!["--sysroot".into(), sys_root]);
410         };
411
412         // this check ensures that dependencies are built but not linted and the final
413         // crate is linted but not built
414         let clippy_enabled = env::var("CLIPPY_TESTS").map_or(false, |val| val == "true")
415             || arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_none();
416
417         if clippy_enabled {
418             args.extend(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()]);
419             if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
420                 args.extend(extra_args.split("__CLIPPY_HACKERY__").filter_map(|s| {
421                     if s.is_empty() {
422                         None
423                     } else {
424                         Some(s.to_string())
425                     }
426                 }));
427             }
428         }
429         let mut clippy = ClippyCallbacks;
430         let mut default = DefaultCallbacks;
431         let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
432             if clippy_enabled { &mut clippy } else { &mut default };
433         rustc_driver::run_compiler(&args, callbacks, None, None)
434     }))
435 }