1 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
2 #![feature(result_map_or)]
3 #![feature(rustc_private)]
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_driver;
9 #[allow(unused_extern_crates)]
10 extern crate rustc_interface;
12 use rustc_interface::interface;
13 use rustc_tools_util::*;
15 use std::path::{Path, PathBuf};
16 use std::process::{exit, Command};
20 /// If a command-line option matches `find_arg`, then apply the predicate `pred` on its value. If
21 /// true, then return it. The parameter is assumed to be either `--arg=value` or `--arg value`.
23 args: impl IntoIterator<Item = &'a String>,
25 pred: impl Fn(&str) -> bool,
26 ) -> Option<&'a str> {
27 let mut args = args.into_iter().map(String::as_str);
29 while let Some(arg) = args.next() {
30 let arg: Vec<_> = arg.splitn(2, '=').collect();
31 if arg.get(0) != Some(&find_arg) {
35 let value = arg.get(1).cloned().or_else(|| args.next());
36 if value.as_ref().map_or(false, |p| pred(p)) {
45 let args: Vec<_> = ["--bar=bar", "--foobar", "123", "--foo"]
47 .map(std::string::ToString::to_string)
50 assert_eq!(arg_value(None, "--foobar", |_| true), None);
51 assert_eq!(arg_value(&args, "--bar", |_| false), None);
52 assert_eq!(arg_value(&args, "--bar", |_| true), Some("bar"));
53 assert_eq!(arg_value(&args, "--bar", |p| p == "bar"), Some("bar"));
54 assert_eq!(arg_value(&args, "--bar", |p| p == "foo"), None);
55 assert_eq!(arg_value(&args, "--foobar", |p| p == "foo"), None);
56 assert_eq!(arg_value(&args, "--foobar", |p| p == "123"), Some("123"));
57 assert_eq!(arg_value(&args, "--foo", |_| true), None);
60 #[allow(clippy::too_many_lines)]
62 struct ClippyCallbacks;
64 impl rustc_driver::Callbacks for ClippyCallbacks {
65 fn config(&mut self, config: &mut interface::Config) {
66 let previous = config.register_lints.take();
67 config.register_lints = Some(Box::new(move |sess, mut lint_store| {
68 // technically we're ~guaranteed that this is none but might as well call anything that
69 // is there already. Certainly it can't hurt.
70 if let Some(previous) = &previous {
71 (previous)(sess, lint_store);
74 let conf = clippy_lints::read_conf(&[], &sess);
75 clippy_lints::register_plugins(&mut lint_store, &sess, &conf);
76 clippy_lints::register_pre_expansion_lints(&mut lint_store, &conf);
77 clippy_lints::register_renamed(&mut lint_store);
80 // FIXME: #4825; This is required, because Clippy lints that are based on MIR have to be
81 // run on the unoptimized MIR. On the other hand this results in some false negatives. If
82 // MIR passes can be enabled / disabled separately, we should figure out, what passes to
84 config.opts.debugging_opts.mir_opt_level = 0;
88 #[allow(clippy::find_map, clippy::filter_map)]
91 use std::collections::HashSet;
95 Available lint options:
96 -W <foo> Warn about <foo>
99 -F <foo> Forbid <foo> (deny <foo> and all attempts to override)
104 let lint_level = |lint: &Lint| {
107 .find(|level_mapping| level_mapping.0 == lint.group)
108 .map(|(_, level)| match level {
109 Level::Allow => "allow",
110 Level::Warn => "warn",
111 Level::Deny => "deny",
116 let mut lints: Vec<_> = ALL_LINTS.iter().collect();
117 // The sort doesn't case-fold but it's doubtful we care.
118 lints.sort_by_cached_key(|x: &&Lint| (lint_level(x), x.name));
120 let max_lint_name_len = lints
122 .map(|lint| lint.name.len())
123 .map(|len| len + "clippy::".len())
127 let padded = |x: &str| {
128 let mut s = " ".repeat(max_lint_name_len - x.chars().count());
133 let scoped = |x: &str| format!("clippy::{}", x);
135 let lint_groups: HashSet<_> = lints.iter().map(|lint| lint.group).collect();
137 println!("Lint checks provided by clippy:\n");
138 println!(" {} {:7.7} meaning", padded("name"), "default");
139 println!(" {} {:7.7} -------", padded("----"), "-------");
141 let print_lints = |lints: &[&Lint]| {
143 let name = lint.name.replace("_", "-");
146 padded(&scoped(&name)),
156 let max_group_name_len = std::cmp::max(
160 .map(|group| group.len())
161 .map(|len| len + "clippy::".len())
166 let padded_group = |x: &str| {
167 let mut s = " ".repeat(max_group_name_len - x.chars().count());
172 println!("Lint groups provided by clippy:\n");
173 println!(" {} sub-lints", padded_group("name"));
174 println!(" {} ---------", padded_group("----"));
175 println!(" {} the set of all clippy lints", padded_group("clippy::all"));
177 let print_lint_groups = || {
178 for group in lint_groups {
179 let name = group.to_lowercase().replace("_", "-");
182 .filter(|&lint| lint.group == group)
183 .map(|lint| lint.name)
184 .map(|name| name.replace("_", "-"))
185 .collect::<Vec<String>>()
187 println!(" {} {}", padded_group(&scoped(&name)), desc);
198 Checks a package to catch common mistakes and improve your Rust code.
201 cargo clippy [options] [--] [<opts>...]
204 -h, --help Print this message
205 -V, --version Print version info and exit
207 Other options are the same as `cargo check`.
209 To allow or deny a lint from the command line you can use `cargo clippy --`
212 -W --warn OPT Set lint warnings
213 -A --allow OPT Set lint allowed
214 -D --deny OPT Set lint denied
215 -F --forbid OPT Set lint forbidden
217 You can use tool lints to allow or deny lints from your code, eg.:
219 #[allow(clippy::needless_lifetimes)]
225 rustc_driver::init_rustc_env_logger();
226 rustc_driver::install_ice_hook();
228 rustc_driver::catch_fatal_errors(move || {
231 if std::env::args().any(|a| a == "--version" || a == "-V") {
232 let version_info = rustc_tools_util::get_version_info!();
233 println!("{}", version_info);
237 let mut orig_args: Vec<String> = env::args().collect();
239 // Get the sysroot, looking from most specific to this invocation to the least:
241 // - runtime environment
243 // - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
244 // - sysroot from rustc in the path
245 // - compile-time environment
246 let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
247 let have_sys_root_arg = sys_root_arg.is_some();
248 let sys_root = sys_root_arg
250 .or_else(|| std::env::var("SYSROOT").ok().map(PathBuf::from))
252 let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
253 let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
254 home.and_then(|home| {
255 toolchain.map(|toolchain| {
256 let mut path = PathBuf::from(home);
257 path.push("toolchains");
258 path.push(toolchain);
264 Command::new("rustc")
269 .and_then(|out| String::from_utf8(out.stdout).ok())
270 .map(|s| PathBuf::from(s.trim()))
272 .or_else(|| option_env!("SYSROOT").map(PathBuf::from))
273 .map(|pb| pb.to_string_lossy().to_string())
274 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
276 // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
277 // We're invoking the compiler programmatically, so we ignore this/
278 let wrapper_mode = orig_args.get(1).map(Path::new).and_then(Path::file_stem) == Some("rustc".as_ref());
281 // we still want to be able to invoke it normally though
285 if !wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
290 let should_describe_lints = || {
291 let args: Vec<_> = std::env::args().collect();
292 args.windows(2).any(|args| {
294 && match args[0].as_str() {
295 "-W" | "-A" | "-D" | "-F" => true,
301 if !wrapper_mode && should_describe_lints() {
306 // this conditional check for the --sysroot flag is there so users can call
307 // `clippy_driver` directly
308 // without having to pass --sysroot or anything
309 let mut args: Vec<String> = if have_sys_root_arg {
315 .chain(Some("--sysroot".to_owned()))
316 .chain(Some(sys_root))
320 // this check ensures that dependencies are built but not linted and the final
322 // linted but not built
323 let clippy_enabled = env::var("CLIPPY_TESTS").map_or(false, |val| val == "true")
324 || arg_value(&orig_args, "--emit", |val| val.split(',').any(|e| e == "metadata")).is_some();
327 args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
328 if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
329 args.extend(extra_args.split("__CLIPPY_HACKERY__").filter_map(|s| {
339 let mut clippy = ClippyCallbacks;
340 let mut default = rustc_driver::DefaultCallbacks;
341 let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
342 if clippy_enabled { &mut clippy } else { &mut default };
344 rustc_driver::run_compiler(&args, callbacks, None, None)
346 .and_then(|result| result)