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 after_parsing(&mut self, compiler: &interface::Compiler) -> rustc_driver::Compilation {
65 let sess = compiler.session();
66 let mut registry = rustc_driver::plugin::registry::Registry::new(
71 "at this compilation stage \
72 the crate must be parsed",
77 registry.args_hidden = Some(Vec::new());
79 let conf = clippy_lints::read_conf(®istry);
80 clippy_lints::register_plugins(&mut registry, &conf);
82 let rustc_driver::plugin::registry::Registry {
90 let mut ls = sess.lint_store.borrow_mut();
91 for pass in early_lint_passes {
92 ls.register_early_pass(Some(sess), true, false, pass);
94 for pass in late_lint_passes {
95 ls.register_late_pass(Some(sess), true, false, false, pass);
98 for (name, (to, deprecated_name)) in lint_groups {
99 ls.register_group(Some(sess), true, name, deprecated_name, to);
101 clippy_lints::register_pre_expansion_lints(sess, &mut ls, &conf);
102 clippy_lints::register_renamed(&mut ls);
104 sess.plugin_llvm_passes.borrow_mut().extend(llvm_passes);
105 sess.plugin_attributes.borrow_mut().extend(attributes);
107 // Continue execution
108 rustc_driver::Compilation::Continue
112 #[allow(clippy::find_map, clippy::filter_map)]
113 fn describe_lints() {
115 use std::collections::HashSet;
119 Available lint options:
120 -W <foo> Warn about <foo>
123 -F <foo> Forbid <foo> (deny <foo> and all attempts to override)
128 let lint_level = |lint: &Lint| {
131 .find(|level_mapping| level_mapping.0 == lint.group)
132 .map(|(_, level)| match level {
133 Level::Allow => "allow",
134 Level::Warn => "warn",
135 Level::Deny => "deny",
140 let mut lints: Vec<_> = ALL_LINTS.iter().collect();
141 // The sort doesn't case-fold but it's doubtful we care.
142 lints.sort_by_cached_key(|x: &&Lint| (lint_level(x), x.name));
144 let max_lint_name_len = lints
146 .map(|lint| lint.name.len())
147 .map(|len| len + "clippy::".len())
151 let padded = |x: &str| {
152 let mut s = " ".repeat(max_lint_name_len - x.chars().count());
157 let scoped = |x: &str| format!("clippy::{}", x);
159 let lint_groups: HashSet<_> = lints.iter().map(|lint| lint.group).collect();
161 println!("Lint checks provided by clippy:\n");
162 println!(" {} {:7.7} meaning", padded("name"), "default");
163 println!(" {} {:7.7} -------", padded("----"), "-------");
165 let print_lints = |lints: &[&Lint]| {
167 let name = lint.name.replace("_", "-");
170 padded(&scoped(&name)),
180 let max_group_name_len = std::cmp::max(
184 .map(|group| group.len())
185 .map(|len| len + "clippy::".len())
190 let padded_group = |x: &str| {
191 let mut s = " ".repeat(max_group_name_len - x.chars().count());
196 println!("Lint groups provided by clippy:\n");
197 println!(" {} sub-lints", padded_group("name"));
198 println!(" {} ---------", padded_group("----"));
199 println!(" {} the set of all clippy lints", padded_group("clippy::all"));
201 let print_lint_groups = || {
202 for group in lint_groups {
203 let name = group.to_lowercase().replace("_", "-");
206 .filter(|&lint| lint.group == group)
207 .map(|lint| lint.name)
208 .map(|name| name.replace("_", "-"))
209 .collect::<Vec<String>>()
211 println!(" {} {}", padded_group(&scoped(&name)), desc);
222 Checks a package to catch common mistakes and improve your Rust code.
225 cargo clippy [options] [--] [<opts>...]
228 -h, --help Print this message
229 -V, --version Print version info and exit
231 Other options are the same as `cargo check`.
233 To allow or deny a lint from the command line you can use `cargo clippy --`
236 -W --warn OPT Set lint warnings
237 -A --allow OPT Set lint allowed
238 -D --deny OPT Set lint denied
239 -F --forbid OPT Set lint forbidden
241 You can use tool lints to allow or deny lints from your code, eg.:
243 #[allow(clippy::needless_lifetimes)]
249 rustc_driver::init_rustc_env_logger();
251 rustc_driver::report_ices_to_stderr_if_any(move || {
254 if std::env::args().any(|a| a == "--version" || a == "-V") {
255 let version_info = rustc_tools_util::get_version_info!();
256 println!("{}", version_info);
260 let mut orig_args: Vec<String> = env::args().collect();
262 // Get the sysroot, looking from most specific to this invocation to the least:
264 // - runtime environment
266 // - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
267 // - sysroot from rustc in the path
268 // - compile-time environment
269 let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
270 let have_sys_root_arg = sys_root_arg.is_some();
271 let sys_root = sys_root_arg
273 .or_else(|| std::env::var("SYSROOT").ok().map(PathBuf::from))
275 let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
276 let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
277 home.and_then(|home| {
278 toolchain.map(|toolchain| {
279 let mut path = PathBuf::from(home);
280 path.push("toolchains");
281 path.push(toolchain);
287 Command::new("rustc")
292 .and_then(|out| String::from_utf8(out.stdout).ok())
293 .map(|s| PathBuf::from(s.trim()))
295 .or_else(|| option_env!("SYSROOT").map(PathBuf::from))
296 .map(|pb| pb.to_string_lossy().to_string())
297 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
299 // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
300 // We're invoking the compiler programmatically, so we ignore this/
301 let wrapper_mode = Path::new(&orig_args[1]).file_stem() == Some("rustc".as_ref());
304 // we still want to be able to invoke it normally though
308 if !wrapper_mode && std::env::args().any(|a| a == "--help" || a == "-h") {
313 let should_describe_lints = || {
314 let args: Vec<_> = std::env::args().collect();
315 args.windows(2).any(|args| {
317 && match args[0].as_str() {
318 "-W" | "-A" | "-D" | "-F" => true,
324 if !wrapper_mode && should_describe_lints() {
329 // this conditional check for the --sysroot flag is there so users can call
330 // `clippy_driver` directly
331 // without having to pass --sysroot or anything
332 let mut args: Vec<String> = if have_sys_root_arg {
338 .chain(Some("--sysroot".to_owned()))
339 .chain(Some(sys_root))
343 // this check ensures that dependencies are built but not linted and the final
345 // linted but not built
346 let clippy_enabled = env::var("CLIPPY_TESTS").ok().map_or(false, |val| val == "true")
347 || arg_value(&orig_args, "--emit", |val| val.split(',').any(|e| e == "metadata")).is_some();
350 args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
351 if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
352 args.extend(extra_args.split("__CLIPPY_HACKERY__").filter_map(|s| {
362 let mut clippy = ClippyCallbacks;
363 let mut default = rustc_driver::DefaultCallbacks;
364 let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
365 if clippy_enabled { &mut clippy } else { &mut default };
367 rustc_driver::run_compiler(&args, callbacks, None, None)
369 .and_then(|result| result)