]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/src/driver.rs
Auto merge of #77671 - flip1995:lint_list_always_plugins, r=oli-obk,Manishearth
[rust.git] / src / tools / clippy / src / driver.rs
1 #![feature(rustc_private)]
2 #![feature(once_cell)]
3 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
4 // warn on lints, that are included in `rust-lang/rust`s bootstrap
5 #![warn(rust_2018_idioms, unused_lifetimes)]
6 // warn on rustc internal lints
7 #![deny(rustc::internal)]
8
9 // FIXME: switch to something more ergonomic here, once available.
10 // (Currently there is no way to opt into sysroot crates without `extern crate`.)
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 std::borrow::Cow;
21 use std::env;
22 use std::lazy::SyncLazy;
23 use std::ops::Deref;
24 use std::panic;
25 use std::path::{Path, PathBuf};
26 use std::process::{exit, Command};
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, T: Deref<Target = str>>(
31     args: &'a [T],
32     find_arg: &str,
33     pred: impl Fn(&str) -> bool,
34 ) -> Option<&'a str> {
35     let mut args = args.iter().map(Deref::deref);
36     while let Some(arg) = args.next() {
37         let mut arg = arg.splitn(2, '=');
38         if arg.next() != Some(find_arg) {
39             continue;
40         }
41
42         match arg.next().or_else(|| args.next()) {
43             Some(v) if pred(v) => return Some(v),
44             _ => {},
45         }
46     }
47     None
48 }
49
50 #[test]
51 fn test_arg_value() {
52     let args = &["--bar=bar", "--foobar", "123", "--foo"];
53
54     assert_eq!(arg_value(&[] as &[&str], "--foobar", |_| true), None);
55     assert_eq!(arg_value(args, "--bar", |_| false), None);
56     assert_eq!(arg_value(args, "--bar", |_| true), Some("bar"));
57     assert_eq!(arg_value(args, "--bar", |p| p == "bar"), Some("bar"));
58     assert_eq!(arg_value(args, "--bar", |p| p == "foo"), None);
59     assert_eq!(arg_value(args, "--foobar", |p| p == "foo"), None);
60     assert_eq!(arg_value(args, "--foobar", |p| p == "123"), Some("123"));
61     assert_eq!(arg_value(args, "--foo", |_| true), None);
62 }
63
64 struct DefaultCallbacks;
65 impl rustc_driver::Callbacks for DefaultCallbacks {}
66
67 struct ClippyCallbacks;
68 impl rustc_driver::Callbacks for ClippyCallbacks {
69     fn config(&mut self, config: &mut interface::Config) {
70         let previous = config.register_lints.take();
71         config.register_lints = Some(Box::new(move |sess, mut lint_store| {
72             // technically we're ~guaranteed that this is none but might as well call anything that
73             // is there already. Certainly it can't hurt.
74             if let Some(previous) = &previous {
75                 (previous)(sess, lint_store);
76             }
77
78             let conf = clippy_lints::read_conf(&[], &sess);
79             clippy_lints::register_plugins(&mut lint_store, &sess, &conf);
80             clippy_lints::register_pre_expansion_lints(&mut lint_store);
81             clippy_lints::register_renamed(&mut lint_store);
82         }));
83
84         // FIXME: #4825; This is required, because Clippy lints that are based on MIR have to be
85         // run on the unoptimized MIR. On the other hand this results in some false negatives. If
86         // MIR passes can be enabled / disabled separately, we should figure out, what passes to
87         // use for Clippy.
88         config.opts.debugging_opts.mir_opt_level = 0;
89     }
90 }
91
92 fn display_help() {
93     println!(
94         "\
95 Checks a package to catch common mistakes and improve your Rust code.
96
97 Usage:
98     cargo clippy [options] [--] [<opts>...]
99
100 Common options:
101     -h, --help               Print this message
102         --rustc              Pass all args to rustc
103     -V, --version            Print version info and exit
104
105 Other options are the same as `cargo check`.
106
107 To allow or deny a lint from the command line you can use `cargo clippy --`
108 with:
109
110     -W --warn OPT       Set lint warnings
111     -A --allow OPT      Set lint allowed
112     -D --deny OPT       Set lint denied
113     -F --forbid OPT     Set lint forbidden
114
115 You can use tool lints to allow or deny lints from your code, eg.:
116
117     #[allow(clippy::needless_lifetimes)]
118 "
119     );
120 }
121
122 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust-clippy/issues/new";
123
124 static ICE_HOOK: SyncLazy<Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static>> = SyncLazy::new(|| {
125     let hook = panic::take_hook();
126     panic::set_hook(Box::new(|info| report_clippy_ice(info, BUG_REPORT_URL)));
127     hook
128 });
129
130 fn report_clippy_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
131     // Invoke our ICE handler, which prints the actual panic message and optionally a backtrace
132     (*ICE_HOOK)(info);
133
134     // Separate the output with an empty line
135     eprintln!();
136
137     let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
138         rustc_errors::ColorConfig::Auto,
139         None,
140         false,
141         false,
142         None,
143         false,
144     ));
145     let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
146
147     // a .span_bug or .bug call has already printed what
148     // it wants to print.
149     if !info.payload().is::<rustc_errors::ExplicitBug>() {
150         let d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic");
151         handler.emit_diagnostic(&d);
152     }
153
154     let version_info = rustc_tools_util::get_version_info!();
155
156     let xs: Vec<Cow<'static, str>> = vec![
157         "the compiler unexpectedly panicked. this is a bug.".into(),
158         format!("we would appreciate a bug report: {}", bug_report_url).into(),
159         format!("Clippy version: {}", version_info).into(),
160     ];
161
162     for note in &xs {
163         handler.note_without_error(&note);
164     }
165
166     // If backtraces are enabled, also print the query stack
167     let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
168
169     let num_frames = if backtrace { None } else { Some(2) };
170
171     TyCtxt::try_print_query_stack(&handler, num_frames);
172 }
173
174 fn toolchain_path(home: Option<String>, toolchain: Option<String>) -> Option<PathBuf> {
175     home.and_then(|home| {
176         toolchain.map(|toolchain| {
177             let mut path = PathBuf::from(home);
178             path.push("toolchains");
179             path.push(toolchain);
180             path
181         })
182     })
183 }
184
185 pub fn main() {
186     rustc_driver::init_rustc_env_logger();
187     SyncLazy::force(&ICE_HOOK);
188     exit(rustc_driver::catch_with_exit_code(move || {
189         let mut orig_args: Vec<String> = env::args().collect();
190
191         // Get the sysroot, looking from most specific to this invocation to the least:
192         // - command line
193         // - runtime environment
194         //    - SYSROOT
195         //    - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
196         // - sysroot from rustc in the path
197         // - compile-time environment
198         //    - SYSROOT
199         //    - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
200         let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
201         let have_sys_root_arg = sys_root_arg.is_some();
202         let sys_root = sys_root_arg
203             .map(PathBuf::from)
204             .or_else(|| std::env::var("SYSROOT").ok().map(PathBuf::from))
205             .or_else(|| {
206                 let home = std::env::var("RUSTUP_HOME")
207                     .or_else(|_| std::env::var("MULTIRUST_HOME"))
208                     .ok();
209                 let toolchain = std::env::var("RUSTUP_TOOLCHAIN")
210                     .or_else(|_| std::env::var("MULTIRUST_TOOLCHAIN"))
211                     .ok();
212                 toolchain_path(home, toolchain)
213             })
214             .or_else(|| {
215                 Command::new("rustc")
216                     .arg("--print")
217                     .arg("sysroot")
218                     .output()
219                     .ok()
220                     .and_then(|out| String::from_utf8(out.stdout).ok())
221                     .map(|s| PathBuf::from(s.trim()))
222             })
223             .or_else(|| option_env!("SYSROOT").map(PathBuf::from))
224             .or_else(|| {
225                 let home = option_env!("RUSTUP_HOME")
226                     .or(option_env!("MULTIRUST_HOME"))
227                     .map(ToString::to_string);
228                 let toolchain = option_env!("RUSTUP_TOOLCHAIN")
229                     .or(option_env!("MULTIRUST_TOOLCHAIN"))
230                     .map(ToString::to_string);
231                 toolchain_path(home, toolchain)
232             })
233             .map(|pb| pb.to_string_lossy().to_string())
234             .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
235
236         // make "clippy-driver --rustc" work like a subcommand that passes further args to "rustc"
237         // for example `clippy-driver --rustc --version` will print the rustc version that clippy-driver
238         // uses
239         if let Some(pos) = orig_args.iter().position(|arg| arg == "--rustc") {
240             orig_args.remove(pos);
241             orig_args[0] = "rustc".to_string();
242
243             // if we call "rustc", we need to pass --sysroot here as well
244             let mut args: Vec<String> = orig_args.clone();
245             if !have_sys_root_arg {
246                 args.extend(vec!["--sysroot".into(), sys_root]);
247             };
248
249             return rustc_driver::RunCompiler::new(&args, &mut DefaultCallbacks).run();
250         }
251
252         if orig_args.iter().any(|a| a == "--version" || a == "-V") {
253             let version_info = rustc_tools_util::get_version_info!();
254             println!("{}", version_info);
255             exit(0);
256         }
257
258         // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
259         // We're invoking the compiler programmatically, so we ignore this/
260         let wrapper_mode = orig_args.get(1).map(Path::new).and_then(Path::file_stem) == Some("rustc".as_ref());
261
262         if wrapper_mode {
263             // we still want to be able to invoke it normally though
264             orig_args.remove(1);
265         }
266
267         if !wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
268             display_help();
269             exit(0);
270         }
271
272         // this conditional check for the --sysroot flag is there so users can call
273         // `clippy_driver` directly
274         // without having to pass --sysroot or anything
275         let mut args: Vec<String> = orig_args.clone();
276         if !have_sys_root_arg {
277             args.extend(vec!["--sysroot".into(), sys_root]);
278         };
279
280         // this check ensures that dependencies are built but not linted and the final
281         // crate is linted but not built
282         let clippy_enabled = env::var("CLIPPY_TESTS").map_or(false, |val| val == "true")
283             || arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_none();
284
285         if clippy_enabled {
286             args.extend(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()]);
287             if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
288                 args.extend(extra_args.split("__CLIPPY_HACKERY__").filter_map(|s| {
289                     if s.is_empty() {
290                         None
291                     } else {
292                         Some(s.to_string())
293                     }
294                 }));
295             }
296         }
297         let mut clippy = ClippyCallbacks;
298         let mut default = DefaultCallbacks;
299         let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
300             if clippy_enabled { &mut clippy } else { &mut default };
301         rustc_driver::RunCompiler::new(&args, callbacks).run()
302     }))
303 }