1 #![feature(rustc_private)]
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)]
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;
16 use rustc_interface::interface;
17 use rustc_middle::ty::TyCtxt;
18 use rustc_tools_util::VersionInfo;
22 use std::lazy::SyncLazy;
25 use std::path::{Path, PathBuf};
26 use std::process::{exit, Command};
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>>(
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) {
42 match arg.next().or_else(|| args.next()) {
43 Some(v) if pred(v) => return Some(v),
52 let args = &["--bar=bar", "--foobar", "123", "--foo"];
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);
64 struct DefaultCallbacks;
65 impl rustc_driver::Callbacks for DefaultCallbacks {}
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);
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);
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
88 config.opts.debugging_opts.mir_opt_level = 0;
95 Checks a package to catch common mistakes and improve your Rust code.
98 cargo clippy [options] [--] [<opts>...]
101 -h, --help Print this message
102 --rustc Pass all args to rustc
103 -V, --version Print version info and exit
105 Other options are the same as `cargo check`.
107 To allow or deny a lint from the command line you can use `cargo clippy --`
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
115 You can use tool lints to allow or deny lints from your code, eg.:
117 #[allow(clippy::needless_lifetimes)]
122 const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust-clippy/issues/new";
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)));
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
134 // Separate the output with an empty line
137 let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr(
138 rustc_errors::ColorConfig::Auto,
145 let handler = rustc_errors::Handler::with_emitter(true, None, emitter);
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);
154 let version_info = rustc_tools_util::get_version_info!();
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(),
163 handler.note_without_error(¬e);
166 // If backtraces are enabled, also print the query stack
167 let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
169 let num_frames = if backtrace { None } else { Some(2) };
171 TyCtxt::try_print_query_stack(&handler, num_frames);
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);
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();
191 // Get the sysroot, looking from most specific to this invocation to the least:
193 // - runtime environment
195 // - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
196 // - sysroot from rustc in the path
197 // - compile-time environment
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
204 .or_else(|| std::env::var("SYSROOT").ok().map(PathBuf::from))
206 let home = std::env::var("RUSTUP_HOME")
207 .or_else(|_| std::env::var("MULTIRUST_HOME"))
209 let toolchain = std::env::var("RUSTUP_TOOLCHAIN")
210 .or_else(|_| std::env::var("MULTIRUST_TOOLCHAIN"))
212 toolchain_path(home, toolchain)
215 Command::new("rustc")
220 .and_then(|out| String::from_utf8(out.stdout).ok())
221 .map(|s| PathBuf::from(s.trim()))
223 .or_else(|| option_env!("SYSROOT").map(PathBuf::from))
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)
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");
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
239 if let Some(pos) = orig_args.iter().position(|arg| arg == "--rustc") {
240 orig_args.remove(pos);
241 orig_args[0] = "rustc".to_string();
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]);
249 return rustc_driver::RunCompiler::new(&args, &mut DefaultCallbacks).run();
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);
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());
263 // we still want to be able to invoke it normally though
267 if !wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
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]);
280 let mut no_deps = false;
281 let clippy_args = env::var("CLIPPY_ARGS")
283 .split("__CLIPPY_HACKERY__")
284 .filter_map(|s| match s {
290 _ => Some(s.to_string()),
292 .chain(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()])
293 .collect::<Vec<String>>();
295 // this check ensures that dependencies are built but not linted and the final
296 // crate is linted but not built
297 let clippy_disabled = env::var("CLIPPY_TESTS").map_or(false, |val| val != "true")
298 || arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_some()
299 || no_deps && env::var("CARGO_PRIMARY_PACKAGE").is_err();
301 if !clippy_disabled {
302 args.extend(clippy_args);
304 let mut clippy = ClippyCallbacks;
305 let mut default = DefaultCallbacks;
306 let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
307 if clippy_disabled { &mut default } else { &mut clippy };
308 rustc_driver::RunCompiler::new(&args, callbacks).run()