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);
81 #[allow(clippy::find_map, clippy::filter_map)]
84 use std::collections::HashSet;
88 Available lint options:
89 -W <foo> Warn about <foo>
92 -F <foo> Forbid <foo> (deny <foo> and all attempts to override)
97 let lint_level = |lint: &Lint| {
100 .find(|level_mapping| level_mapping.0 == lint.group)
101 .map(|(_, level)| match level {
102 Level::Allow => "allow",
103 Level::Warn => "warn",
104 Level::Deny => "deny",
109 let mut lints: Vec<_> = ALL_LINTS.iter().collect();
110 // The sort doesn't case-fold but it's doubtful we care.
111 lints.sort_by_cached_key(|x: &&Lint| (lint_level(x), x.name));
113 let max_lint_name_len = lints
115 .map(|lint| lint.name.len())
116 .map(|len| len + "clippy::".len())
120 let padded = |x: &str| {
121 let mut s = " ".repeat(max_lint_name_len - x.chars().count());
126 let scoped = |x: &str| format!("clippy::{}", x);
128 let lint_groups: HashSet<_> = lints.iter().map(|lint| lint.group).collect();
130 println!("Lint checks provided by clippy:\n");
131 println!(" {} {:7.7} meaning", padded("name"), "default");
132 println!(" {} {:7.7} -------", padded("----"), "-------");
134 let print_lints = |lints: &[&Lint]| {
136 let name = lint.name.replace("_", "-");
139 padded(&scoped(&name)),
149 let max_group_name_len = std::cmp::max(
153 .map(|group| group.len())
154 .map(|len| len + "clippy::".len())
159 let padded_group = |x: &str| {
160 let mut s = " ".repeat(max_group_name_len - x.chars().count());
165 println!("Lint groups provided by clippy:\n");
166 println!(" {} sub-lints", padded_group("name"));
167 println!(" {} ---------", padded_group("----"));
168 println!(" {} the set of all clippy lints", padded_group("clippy::all"));
170 let print_lint_groups = || {
171 for group in lint_groups {
172 let name = group.to_lowercase().replace("_", "-");
175 .filter(|&lint| lint.group == group)
176 .map(|lint| lint.name)
177 .map(|name| name.replace("_", "-"))
178 .collect::<Vec<String>>()
180 println!(" {} {}", padded_group(&scoped(&name)), desc);
191 Checks a package to catch common mistakes and improve your Rust code.
194 cargo clippy [options] [--] [<opts>...]
197 -h, --help Print this message
198 -V, --version Print version info and exit
200 Other options are the same as `cargo check`.
202 To allow or deny a lint from the command line you can use `cargo clippy --`
205 -W --warn OPT Set lint warnings
206 -A --allow OPT Set lint allowed
207 -D --deny OPT Set lint denied
208 -F --forbid OPT Set lint forbidden
210 You can use tool lints to allow or deny lints from your code, eg.:
212 #[allow(clippy::needless_lifetimes)]
218 rustc_driver::init_rustc_env_logger();
219 rustc_driver::install_ice_hook();
221 rustc_driver::catch_fatal_errors(move || {
224 if std::env::args().any(|a| a == "--version" || a == "-V") {
225 let version_info = rustc_tools_util::get_version_info!();
226 println!("{}", version_info);
230 let mut orig_args: Vec<String> = env::args().collect();
232 // Get the sysroot, looking from most specific to this invocation to the least:
234 // - runtime environment
236 // - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
237 // - sysroot from rustc in the path
238 // - compile-time environment
239 let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
240 let have_sys_root_arg = sys_root_arg.is_some();
241 let sys_root = sys_root_arg
243 .or_else(|| std::env::var("SYSROOT").ok().map(PathBuf::from))
245 let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
246 let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
247 home.and_then(|home| {
248 toolchain.map(|toolchain| {
249 let mut path = PathBuf::from(home);
250 path.push("toolchains");
251 path.push(toolchain);
257 Command::new("rustc")
262 .and_then(|out| String::from_utf8(out.stdout).ok())
263 .map(|s| PathBuf::from(s.trim()))
265 .or_else(|| option_env!("SYSROOT").map(PathBuf::from))
266 .map(|pb| pb.to_string_lossy().to_string())
267 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
269 // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
270 // We're invoking the compiler programmatically, so we ignore this/
271 let wrapper_mode = Path::new(&orig_args[1]).file_stem() == Some("rustc".as_ref());
274 // we still want to be able to invoke it normally though
278 if !wrapper_mode && std::env::args().any(|a| a == "--help" || a == "-h") {
283 let should_describe_lints = || {
284 let args: Vec<_> = std::env::args().collect();
285 args.windows(2).any(|args| {
287 && match args[0].as_str() {
288 "-W" | "-A" | "-D" | "-F" => true,
294 if !wrapper_mode && should_describe_lints() {
299 // this conditional check for the --sysroot flag is there so users can call
300 // `clippy_driver` directly
301 // without having to pass --sysroot or anything
302 let mut args: Vec<String> = if have_sys_root_arg {
308 .chain(Some("--sysroot".to_owned()))
309 .chain(Some(sys_root))
313 // this check ensures that dependencies are built but not linted and the final
315 // linted but not built
316 let clippy_enabled = env::var("CLIPPY_TESTS").ok().map_or(false, |val| val == "true")
317 || arg_value(&orig_args, "--emit", |val| val.split(',').any(|e| e == "metadata")).is_some();
320 args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
321 if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
322 args.extend(extra_args.split("__CLIPPY_HACKERY__").filter_map(|s| {
332 let mut clippy = ClippyCallbacks;
333 let mut default = rustc_driver::DefaultCallbacks;
334 let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
335 if clippy_enabled { &mut clippy } else { &mut default };
337 rustc_driver::run_compiler(&args, callbacks, None, None)
339 .and_then(|result| result)