2 #![feature(box_syntax)]
3 #![feature(rustc_private)]
4 #![allow(unknown_lints, missing_docs_in_private_items)]
6 extern crate clippy_lints;
9 extern crate rustc_driver;
10 extern crate rustc_errors;
11 extern crate rustc_plugin;
14 use rustc_driver::{driver, Compilation, CompilerCalls, RustcDefaultCalls};
15 use rustc::session::{config, CompileIncomplete, Session};
16 use rustc::session::config::{ErrorOutputType, Input};
17 use std::collections::HashMap;
18 use std::path::PathBuf;
19 use std::process::{self, Command};
21 use std::io::{self, Write};
23 extern crate cargo_metadata;
25 struct ClippyCompilerCalls {
26 default: RustcDefaultCalls,
30 impl ClippyCompilerCalls {
31 fn new(run_lints: bool) -> Self {
33 default: RustcDefaultCalls,
39 impl<'a> CompilerCalls<'a> for ClippyCompilerCalls {
42 matches: &getopts::Matches,
43 sopts: &config::Options,
44 cfg: &ast::CrateConfig,
45 descriptions: &rustc_errors::registry::Registry,
46 output: ErrorOutputType,
48 self.default.early_callback(
58 matches: &getopts::Matches,
59 sopts: &config::Options,
60 cfg: &ast::CrateConfig,
61 odir: &Option<PathBuf>,
62 ofile: &Option<PathBuf>,
63 descriptions: &rustc_errors::registry::Registry,
64 ) -> Option<(Input, Option<PathBuf>)> {
65 self.default.no_input(
76 matches: &getopts::Matches,
79 odir: &Option<PathBuf>,
80 ofile: &Option<PathBuf>,
82 self.default.late_callback(
90 fn build_controller(&mut self, sess: &Session, matches: &getopts::Matches) -> driver::CompileController<'a> {
91 let mut control = self.default.build_controller(sess, matches);
94 let old = std::mem::replace(&mut control.after_parse.callback, box |_| {});
95 control.after_parse.callback = Box::new(move |state| {
97 let mut registry = rustc_plugin::registry::Registry::new(
103 "at this compilation stage \
104 the krate must be parsed",
108 registry.args_hidden = Some(Vec::new());
109 clippy_lints::register_plugins(&mut registry);
111 let rustc_plugin::registry::Registry {
119 let sess = &state.session;
120 let mut ls = sess.lint_store.borrow_mut();
121 for pass in early_lint_passes {
122 ls.register_early_pass(Some(sess), true, pass);
124 for pass in late_lint_passes {
125 ls.register_late_pass(Some(sess), true, pass);
128 for (name, to) in lint_groups {
129 ls.register_group(Some(sess), true, name, to);
132 sess.plugin_llvm_passes.borrow_mut().extend(llvm_passes);
133 sess.plugin_attributes.borrow_mut().extend(attributes);
145 const CARGO_CLIPPY_HELP: &str = r#"Checks a package to catch common mistakes and improve your Rust code.
148 cargo clippy [options] [--] [<opts>...]
151 -h, --help Print this message
152 --features Features to compile for the package
153 -V, --version Print version info and exit
154 --all Run over all packages in the current workspace
156 Other options are the same as `cargo rustc`.
158 To allow or deny a lint from the command line you can use `cargo clippy --`
161 -W --warn OPT Set lint warnings
162 -A --allow OPT Set lint allowed
163 -D --deny OPT Set lint denied
164 -F --forbid OPT Set lint forbidden
166 The feature `cargo-clippy` is automatically defined for convenience. You can use
167 it to allow or deny lints from the code, eg.:
169 #[cfg_attr(feature = "cargo-clippy", allow(needless_lifetimes))]
172 #[allow(print_stdout)]
174 println!("{}", CARGO_CLIPPY_HELP);
177 #[allow(print_stdout)]
179 println!("{}", env!("CARGO_PKG_VERSION"));
185 if env::var("CLIPPY_DOGFOOD").map(|_| true).unwrap_or(false) {
189 // Check for version and help flags even when invoked as 'cargo-clippy'
190 if std::env::args().any(|a| a == "--help" || a == "-h") {
194 if std::env::args().any(|a| a == "--version" || a == "-V") {
199 if let Some("clippy") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
200 // this arm is executed on the initial call to `cargo clippy`
202 let manifest_path_arg = std::env::args()
204 .find(|val| val.starts_with("--manifest-path="));
207 if let Ok(metadata) = cargo_metadata::metadata(manifest_path_arg.as_ref().map(AsRef::as_ref)) {
210 let _ = io::stderr().write_fmt(format_args!("error: Could not obtain cargo metadata.\n"));
214 let manifest_path = manifest_path_arg.map(|arg| {
215 Path::new(&arg["--manifest-path=".len()..])
217 .expect("manifest path could not be canonicalized")
220 let packages = if std::env::args().any(|a| a == "--all") {
223 let package_index = {
224 if let Some(manifest_path) = manifest_path {
225 metadata.packages.iter().position(|package| {
226 let package_manifest_path = Path::new(&package.manifest_path)
228 .expect("package manifest path could not be canonicalized");
229 package_manifest_path == manifest_path
232 let package_manifest_paths: HashMap<_, _> = metadata
236 .map(|(i, package)| {
237 let package_manifest_path = Path::new(&package.manifest_path)
239 .expect("could not find parent directory of package manifest")
241 .expect("package directory cannot be canonicalized");
242 (package_manifest_path, i)
246 let current_dir = std::env::current_dir()
247 .expect("could not read current directory")
249 .expect("current directory cannot be canonicalized");
251 let mut current_path: &Path = ¤t_dir;
253 // This gets the most-recent parent (the one that takes the fewest `cd ..`s to
256 if let Some(&package_index) = package_manifest_paths.get(current_path) {
257 break Some(package_index);
259 // We'll never reach the filesystem root, because to get to this point in the
261 // the call to `cargo_metadata::metadata` must have succeeded. So it's okay to
262 // unwrap the current path's parent.
263 current_path = current_path
265 .unwrap_or_else(|| panic!("could not find parent of path {}", current_path.display()));
269 }.expect("could not find matching package");
271 vec![metadata.packages.remove(package_index)]
274 for package in packages {
275 let manifest_path = package.manifest_path;
277 for target in package.targets {
278 let args = std::env::args()
280 .filter(|a| a != "--all" && !a.starts_with("--manifest-path="));
282 let args = std::iter::once(format!("--manifest-path={}", manifest_path)).chain(args);
283 if let Some(first) = target.kind.get(0) {
284 if target.kind.len() > 1 || first.ends_with("lib") {
285 if let Err(code) = process(std::iter::once("--lib".to_owned()).chain(args)) {
286 std::process::exit(code);
288 } else if ["bin", "example", "test", "bench"].contains(&&**first) {
289 if let Err(code) = process(
290 vec![format!("--{}", first), target.name]
294 std::process::exit(code);
298 panic!("badly formatted cargo metadata: target::kind is an empty array");
303 // this arm is executed when cargo-clippy runs `cargo rustc` with the `RUSTC`
304 // env var set to itself
306 let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
307 let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
308 let sys_root = if let (Some(home), Some(toolchain)) = (home, toolchain) {
309 format!("{}/toolchains/{}", home, toolchain)
311 option_env!("SYSROOT")
312 .map(|s| s.to_owned())
314 Command::new("rustc")
319 .and_then(|out| String::from_utf8(out.stdout).ok())
320 .map(|s| s.trim().to_owned())
323 "need to specify SYSROOT env var during clippy compilation, or use rustup or multirust",
327 rustc_driver::in_rustc_thread(|| {
328 // this conditional check for the --sysroot flag is there so users can call
329 // `cargo-clippy` directly
330 // without having to pass --sysroot or anything
331 let mut args: Vec<String> = if env::args().any(|s| s == "--sysroot") {
332 env::args().collect()
335 .chain(Some("--sysroot".to_owned()))
336 .chain(Some(sys_root))
340 // this check ensures that dependencies are built but not linted and the final
342 // linted but not built
343 let clippy_enabled = env::args().any(|s| s == "--emit=metadata");
346 args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
349 let mut ccc = ClippyCompilerCalls::new(clippy_enabled);
350 let (result, _) = rustc_driver::run_compiler(&args, &mut ccc, None, None);
351 if let Err(CompileIncomplete::Errored(_)) = result {
352 std::process::exit(1);
354 }).expect("rustc_thread failed");
358 fn process<I>(old_args: I) -> Result<(), i32>
360 I: Iterator<Item = String>,
363 let mut args = vec!["rustc".to_owned()];
365 let mut found_dashes = false;
366 for arg in old_args {
367 found_dashes |= arg == "--";
371 args.push("--".to_owned());
373 args.push("--emit=metadata".to_owned());
374 args.push("--cfg".to_owned());
375 args.push(r#"feature="cargo-clippy""#.to_owned());
377 let path = std::env::current_exe().expect("current executable path invalid");
378 let exit_status = std::process::Command::new("cargo")
382 .expect("could not run cargo")
384 .expect("failed to wait for cargo?");
386 if exit_status.success() {
389 Err(exit_status.code().unwrap_or(-1))