1 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
2 #![feature(rustc_private)]
4 // FIXME: switch to something more ergonomic here, once available.
5 // (Currently there is no way to opt into sysroot crates without `extern crate`.)
6 #[allow(unused_extern_crates)]
7 extern crate rustc_driver;
8 #[allow(unused_extern_crates)]
9 extern crate rustc_interface;
11 use rustc_interface::interface;
12 use rustc_tools_util::*;
14 use std::path::{Path, PathBuf};
15 use std::process::{exit, Command};
19 /// If a command-line option matches `find_arg`, then apply the predicate `pred` on its value. If
20 /// true, then return it. The parameter is assumed to be either `--arg=value` or `--arg value`.
22 args: impl IntoIterator<Item = &'a String>,
24 pred: impl Fn(&str) -> bool,
25 ) -> Option<&'a str> {
26 let mut args = args.into_iter().map(String::as_str);
28 while let Some(arg) = args.next() {
29 let arg: Vec<_> = arg.splitn(2, '=').collect();
30 if arg.get(0) != Some(&find_arg) {
34 let value = arg.get(1).cloned().or_else(|| args.next());
35 if value.as_ref().map_or(false, |p| pred(p)) {
44 let args: Vec<_> = ["--bar=bar", "--foobar", "123", "--foo"]
46 .map(std::string::ToString::to_string)
49 assert_eq!(arg_value(None, "--foobar", |_| true), None);
50 assert_eq!(arg_value(&args, "--bar", |_| false), None);
51 assert_eq!(arg_value(&args, "--bar", |_| true), Some("bar"));
52 assert_eq!(arg_value(&args, "--bar", |p| p == "bar"), Some("bar"));
53 assert_eq!(arg_value(&args, "--bar", |p| p == "foo"), None);
54 assert_eq!(arg_value(&args, "--foobar", |p| p == "foo"), None);
55 assert_eq!(arg_value(&args, "--foobar", |p| p == "123"), Some("123"));
56 assert_eq!(arg_value(&args, "--foo", |_| true), None);
59 #[allow(clippy::too_many_lines)]
61 struct ClippyCallbacks;
63 impl rustc_driver::Callbacks for ClippyCallbacks {
64 fn config(&mut self, config: &mut interface::Config) {
65 let previous = config.register_lints.take();
66 config.register_lints = Some(Box::new(move |sess, mut lint_store| {
67 // technically we're ~guaranteed that this is none but might as well call anything that
68 // is there already. Certainly it can't hurt.
69 if let Some(previous) = &previous {
70 (previous)(sess, lint_store);
73 let conf = clippy_lints::read_conf(&[], &sess);
74 clippy_lints::register_plugins(&mut lint_store, &sess, &conf);
75 clippy_lints::register_pre_expansion_lints(&mut lint_store, &conf);
76 clippy_lints::register_renamed(&mut lint_store);
79 // FIXME: #4825; This is required, because Clippy lints that are based on MIR have to be
80 // run on the unoptimized MIR. On the other hand this results in some false negatives. If
81 // MIR passes can be enabled / disabled separately, we should figure out, what passes to
83 config.opts.debugging_opts.mir_opt_level = 0;
87 #[allow(clippy::find_map, clippy::filter_map)]
90 use std::collections::HashSet;
94 Available lint options:
95 -W <foo> Warn about <foo>
98 -F <foo> Forbid <foo> (deny <foo> and all attempts to override)
103 let lint_level = |lint: &Lint| {
106 .find(|level_mapping| level_mapping.0 == lint.group)
107 .map(|(_, level)| match level {
108 Level::Allow => "allow",
109 Level::Warn => "warn",
110 Level::Deny => "deny",
115 let mut lints: Vec<_> = ALL_LINTS.iter().collect();
116 // The sort doesn't case-fold but it's doubtful we care.
117 lints.sort_by_cached_key(|x: &&Lint| (lint_level(x), x.name));
119 let max_lint_name_len = lints
121 .map(|lint| lint.name.len())
122 .map(|len| len + "clippy::".len())
126 let padded = |x: &str| {
127 let mut s = " ".repeat(max_lint_name_len - x.chars().count());
132 let scoped = |x: &str| format!("clippy::{}", x);
134 let lint_groups: HashSet<_> = lints.iter().map(|lint| lint.group).collect();
136 println!("Lint checks provided by clippy:\n");
137 println!(" {} {:7.7} meaning", padded("name"), "default");
138 println!(" {} {:7.7} -------", padded("----"), "-------");
140 let print_lints = |lints: &[&Lint]| {
142 let name = lint.name.replace("_", "-");
145 padded(&scoped(&name)),
155 let max_group_name_len = std::cmp::max(
159 .map(|group| group.len())
160 .map(|len| len + "clippy::".len())
165 let padded_group = |x: &str| {
166 let mut s = " ".repeat(max_group_name_len - x.chars().count());
171 println!("Lint groups provided by clippy:\n");
172 println!(" {} sub-lints", padded_group("name"));
173 println!(" {} ---------", padded_group("----"));
174 println!(" {} the set of all clippy lints", padded_group("clippy::all"));
176 let print_lint_groups = || {
177 for group in lint_groups {
178 let name = group.to_lowercase().replace("_", "-");
181 .filter(|&lint| lint.group == group)
182 .map(|lint| lint.name)
183 .map(|name| name.replace("_", "-"))
184 .collect::<Vec<String>>()
186 println!(" {} {}", padded_group(&scoped(&name)), desc);
197 Checks a package to catch common mistakes and improve your Rust code.
200 cargo clippy [options] [--] [<opts>...]
203 -h, --help Print this message
204 -V, --version Print version info and exit
206 Other options are the same as `cargo check`.
208 To allow or deny a lint from the command line you can use `cargo clippy --`
211 -W --warn OPT Set lint warnings
212 -A --allow OPT Set lint allowed
213 -D --deny OPT Set lint denied
214 -F --forbid OPT Set lint forbidden
216 You can use tool lints to allow or deny lints from your code, eg.:
218 #[allow(clippy::needless_lifetimes)]
224 rustc_driver::init_rustc_env_logger();
225 rustc_driver::install_ice_hook();
227 rustc_driver::catch_fatal_errors(move || {
230 if std::env::args().any(|a| a == "--version" || a == "-V") {
231 let version_info = rustc_tools_util::get_version_info!();
232 println!("{}", version_info);
236 let mut orig_args: Vec<String> = env::args().collect();
238 // Get the sysroot, looking from most specific to this invocation to the least:
240 // - runtime environment
242 // - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
243 // - sysroot from rustc in the path
244 // - compile-time environment
245 let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
246 let have_sys_root_arg = sys_root_arg.is_some();
247 let sys_root = sys_root_arg
249 .or_else(|| std::env::var("SYSROOT").ok().map(PathBuf::from))
251 let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
252 let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
253 home.and_then(|home| {
254 toolchain.map(|toolchain| {
255 let mut path = PathBuf::from(home);
256 path.push("toolchains");
257 path.push(toolchain);
263 Command::new("rustc")
268 .and_then(|out| String::from_utf8(out.stdout).ok())
269 .map(|s| PathBuf::from(s.trim()))
271 .or_else(|| option_env!("SYSROOT").map(PathBuf::from))
272 .map(|pb| pb.to_string_lossy().to_string())
273 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
275 // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
276 // We're invoking the compiler programmatically, so we ignore this/
277 let wrapper_mode = orig_args.get(1).map(Path::new).and_then(Path::file_stem) == Some("rustc".as_ref());
280 // we still want to be able to invoke it normally though
284 if !wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
289 let should_describe_lints = || {
290 let args: Vec<_> = std::env::args().collect();
291 args.windows(2).any(|args| {
293 && match args[0].as_str() {
294 "-W" | "-A" | "-D" | "-F" => true,
300 if !wrapper_mode && should_describe_lints() {
305 // this conditional check for the --sysroot flag is there so users can call
306 // `clippy_driver` directly
307 // without having to pass --sysroot or anything
308 let mut args: Vec<String> = if have_sys_root_arg {
314 .chain(Some("--sysroot".to_owned()))
315 .chain(Some(sys_root))
319 // this check ensures that dependencies are built but not linted and the final
321 // linted but not built
322 let clippy_enabled = env::var("CLIPPY_TESTS").ok().map_or(false, |val| val == "true")
323 || arg_value(&orig_args, "--emit", |val| val.split(',').any(|e| e == "metadata")).is_some();
326 args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
327 if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
328 args.extend(extra_args.split("__CLIPPY_HACKERY__").filter_map(|s| {
338 let mut clippy = ClippyCallbacks;
339 let mut default = rustc_driver::DefaultCallbacks;
340 let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
341 if clippy_enabled { &mut clippy } else { &mut default };
343 rustc_driver::run_compiler(&args, callbacks, None, None)
345 .and_then(|result| result)