1 #![feature(rustc_private)]
3 // FIXME: switch to something more ergonomic here, once available.
4 // (Currently there is no way to opt into sysroot crates without `extern crate`.)
5 #[allow(unused_extern_crates)]
6 extern crate rustc_driver;
7 #[allow(unused_extern_crates)]
8 extern crate rustc_interface;
9 #[allow(unused_extern_crates)]
10 extern crate rustc_plugin;
12 use rustc_interface::interface;
13 use rustc_tools_util::*;
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 after_parsing(&mut self, compiler: &interface::Compiler) -> bool {
66 let sess = compiler.session();
67 let mut registry = rustc_plugin::registry::Registry::new(
72 "at this compilation stage \
73 the crate must be parsed",
78 registry.args_hidden = Some(Vec::new());
80 let conf = clippy_lints::read_conf(®istry);
81 clippy_lints::register_plugins(&mut registry, &conf);
83 let rustc_plugin::registry::Registry {
91 let mut ls = sess.lint_store.borrow_mut();
92 for pass in early_lint_passes {
93 ls.register_early_pass(Some(sess), true, false, pass);
95 for pass in late_lint_passes {
96 ls.register_late_pass(Some(sess), true, false, false, pass);
99 for (name, (to, deprecated_name)) in lint_groups {
100 ls.register_group(Some(sess), true, name, deprecated_name, to);
102 clippy_lints::register_pre_expansion_lints(sess, &mut ls, &conf);
103 clippy_lints::register_renamed(&mut ls);
105 sess.plugin_llvm_passes.borrow_mut().extend(llvm_passes);
106 sess.plugin_attributes.borrow_mut().extend(attributes);
108 // Continue execution
113 #[allow(clippy::find_map, clippy::filter_map)]
114 fn describe_lints() {
116 use std::collections::HashSet;
120 Available lint options:
121 -W <foo> Warn about <foo>
124 -F <foo> Forbid <foo> (deny <foo> and all attempts to override)
129 let lint_level = |lint: &Lint| {
132 .find(|level_mapping| level_mapping.0 == lint.group)
133 .map(|(_, level)| match level {
134 Level::Allow => "allow",
135 Level::Warn => "warn",
136 Level::Deny => "deny",
141 let mut lints: Vec<_> = ALL_LINTS.iter().collect();
142 // The sort doesn't case-fold but it's doubtful we care.
143 lints.sort_by_cached_key(|x: &&Lint| (lint_level(x), x.name));
145 let max_lint_name_len = lints
147 .map(|lint| lint.name.len())
148 .map(|len| len + "clippy::".len())
152 let padded = |x: &str| {
153 let mut s = " ".repeat(max_lint_name_len - x.chars().count());
158 let scoped = |x: &str| format!("clippy::{}", x);
160 let lint_groups: HashSet<_> = lints.iter().map(|lint| lint.group).collect();
162 println!("Lint checks provided by clippy:\n");
163 println!(" {} {:7.7} meaning", padded("name"), "default");
164 println!(" {} {:7.7} -------", padded("----"), "-------");
166 let print_lints = |lints: &[&Lint]| {
168 let name = lint.name.replace("_", "-");
171 padded(&scoped(&name)),
181 let max_group_name_len = std::cmp::max(
185 .map(|group| group.len())
186 .map(|len| len + "clippy::".len())
191 let padded_group = |x: &str| {
192 let mut s = " ".repeat(max_group_name_len - x.chars().count());
197 println!("Lint groups provided by clippy:\n");
198 println!(" {} sub-lints", padded_group("name"));
199 println!(" {} ---------", padded_group("----"));
200 println!(" {} the set of all clippy lints", padded_group("clippy::all"));
202 let print_lint_groups = || {
203 for group in lint_groups {
204 let name = group.to_lowercase().replace("_", "-");
207 .filter(|&lint| lint.group == group)
208 .map(|lint| lint.name)
209 .map(|name| name.replace("_", "-"))
210 .collect::<Vec<String>>()
212 println!(" {} {}", padded_group(&scoped(&name)), desc);
223 Checks a package to catch common mistakes and improve your Rust code.
226 cargo clippy [options] [--] [<opts>...]
229 -h, --help Print this message
230 -V, --version Print version info and exit
232 Other options are the same as `cargo check`.
234 To allow or deny a lint from the command line you can use `cargo clippy --`
237 -W --warn OPT Set lint warnings
238 -A --allow OPT Set lint allowed
239 -D --deny OPT Set lint denied
240 -F --forbid OPT Set lint forbidden
242 You can use tool lints to allow or deny lints from your code, eg.:
244 #[allow(clippy::needless_lifetimes)]
250 rustc_driver::init_rustc_env_logger();
252 rustc_driver::report_ices_to_stderr_if_any(move || {
255 if std::env::args().any(|a| a == "--version" || a == "-V") {
256 let version_info = rustc_tools_util::get_version_info!();
257 println!("{}", version_info);
261 let mut orig_args: Vec<String> = env::args().collect();
263 // Get the sysroot, looking from most specific to this invocation to the least:
265 // - runtime environment
267 // - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
268 // - sysroot from rustc in the path
269 // - compile-time environment
270 let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
271 let have_sys_root_arg = sys_root_arg.is_some();
272 let sys_root = sys_root_arg
273 .map(std::string::ToString::to_string)
274 .or_else(|| std::env::var("SYSROOT").ok())
276 let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
277 let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
278 home.and_then(|home| toolchain.map(|toolchain| format!("{}/toolchains/{}", home, toolchain)))
281 Command::new("rustc")
286 .and_then(|out| String::from_utf8(out.stdout).ok())
287 .map(|s| s.trim().to_owned())
289 .or_else(|| option_env!("SYSROOT").map(String::from))
290 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
292 // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
293 // We're invoking the compiler programmatically, so we ignore this/
294 let wrapper_mode = Path::new(&orig_args[1]).file_stem() == Some("rustc".as_ref());
297 // we still want to be able to invoke it normally though
301 if !wrapper_mode && std::env::args().any(|a| a == "--help" || a == "-h") {
306 let should_describe_lints = || {
307 let args: Vec<_> = std::env::args().collect();
308 args.windows(2).any(|args| {
310 && match args[0].as_str() {
311 "-W" | "-A" | "-D" | "-F" => true,
317 if !wrapper_mode && should_describe_lints() {
322 // this conditional check for the --sysroot flag is there so users can call
323 // `clippy_driver` directly
324 // without having to pass --sysroot or anything
325 let mut args: Vec<String> = if have_sys_root_arg {
331 .chain(Some("--sysroot".to_owned()))
332 .chain(Some(sys_root))
336 // this check ensures that dependencies are built but not linted and the final
338 // linted but not built
339 let clippy_enabled = env::var("CLIPPY_TESTS").ok().map_or(false, |val| val == "true")
340 || arg_value(&orig_args, "--emit", |val| val.split(',').any(|e| e == "metadata")).is_some();
343 args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
344 if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
345 args.extend(extra_args.split("__CLIPPY_HACKERY__").filter_map(|s| {
355 let mut clippy = ClippyCallbacks;
356 let mut default = rustc_driver::DefaultCallbacks;
357 let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
358 if clippy_enabled { &mut clippy } else { &mut default };
360 rustc_driver::run_compiler(&args, callbacks, None, None)
362 .and_then(|result| result)