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,
49 .early_callback(matches, sopts, cfg, descriptions, output)
53 matches: &getopts::Matches,
54 sopts: &config::Options,
55 cfg: &ast::CrateConfig,
56 odir: &Option<PathBuf>,
57 ofile: &Option<PathBuf>,
58 descriptions: &rustc_errors::registry::Registry,
59 ) -> Option<(Input, Option<PathBuf>)> {
61 .no_input(matches, sopts, cfg, odir, ofile, descriptions)
65 matches: &getopts::Matches,
67 crate_stores: &rustc::middle::cstore::CrateStore,
69 odir: &Option<PathBuf>,
70 ofile: &Option<PathBuf>,
73 .late_callback(matches, sess, crate_stores, input, odir, ofile)
75 fn build_controller(&mut self, sess: &Session, matches: &getopts::Matches) -> driver::CompileController<'a> {
76 let mut control = self.default.build_controller(sess, matches);
79 let old = std::mem::replace(&mut control.after_parse.callback, box |_| {});
80 control.after_parse.callback = Box::new(move |state| {
82 let mut registry = rustc_plugin::registry::Registry::new(
88 "at this compilation stage \
89 the krate must be parsed",
93 registry.args_hidden = Some(Vec::new());
94 clippy_lints::register_plugins(&mut registry);
96 let rustc_plugin::registry::Registry {
104 let sess = &state.session;
105 let mut ls = sess.lint_store.borrow_mut();
106 for pass in early_lint_passes {
107 ls.register_early_pass(Some(sess), true, pass);
109 for pass in late_lint_passes {
110 ls.register_late_pass(Some(sess), true, pass);
113 for (name, to) in lint_groups {
114 ls.register_group(Some(sess), true, name, to);
117 sess.plugin_llvm_passes.borrow_mut().extend(llvm_passes);
118 sess.plugin_attributes.borrow_mut().extend(attributes);
130 const CARGO_CLIPPY_HELP: &str = r#"Checks a package to catch common mistakes and improve your Rust code.
133 cargo clippy [options] [--] [<opts>...]
136 -h, --help Print this message
137 --features Features to compile for the package
138 -V, --version Print version info and exit
139 --all Run over all packages in the current workspace
141 Other options are the same as `cargo rustc`.
143 To allow or deny a lint from the command line you can use `cargo clippy --`
146 -W --warn OPT Set lint warnings
147 -A --allow OPT Set lint allowed
148 -D --deny OPT Set lint denied
149 -F --forbid OPT Set lint forbidden
151 The feature `cargo-clippy` is automatically defined for convenience. You can use
152 it to allow or deny lints from the code, eg.:
154 #[cfg_attr(feature = "cargo-clippy", allow(needless_lifetimes))]
157 #[allow(print_stdout)]
159 println!("{}", CARGO_CLIPPY_HELP);
162 #[allow(print_stdout)]
164 println!("{}", env!("CARGO_PKG_VERSION"));
170 if env::var("CLIPPY_DOGFOOD").map(|_| true).unwrap_or(false) {
174 // Check for version and help flags even when invoked as 'cargo-clippy'
175 if std::env::args().any(|a| a == "--help" || a == "-h") {
179 if std::env::args().any(|a| a == "--version" || a == "-V") {
184 if let Some("clippy") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
185 // this arm is executed on the initial call to `cargo clippy`
187 let manifest_path_arg = std::env::args()
189 .find(|val| val.starts_with("--manifest-path="));
191 let mut metadata = if let Ok(metadata) = cargo_metadata::metadata(manifest_path_arg.as_ref().map(AsRef::as_ref))
195 let _ = io::stderr().write_fmt(format_args!("error: Could not obtain cargo metadata.\n"));
199 let manifest_path = manifest_path_arg.map(|arg| {
200 Path::new(&arg["--manifest-path=".len()..])
202 .expect("manifest path could not be canonicalized")
205 let packages = if std::env::args().any(|a| a == "--all") {
208 let package_index = {
209 if let Some(manifest_path) = manifest_path {
210 metadata.packages.iter().position(|package| {
211 let package_manifest_path = Path::new(&package.manifest_path)
213 .expect("package manifest path could not be canonicalized");
214 package_manifest_path == manifest_path
217 let package_manifest_paths: HashMap<_, _> = metadata
221 .map(|(i, package)| {
222 let package_manifest_path = Path::new(&package.manifest_path)
224 .expect("could not find parent directory of package manifest")
226 .expect("package directory cannot be canonicalized");
227 (package_manifest_path, i)
231 let current_dir = std::env::current_dir()
232 .expect("could not read current directory")
234 .expect("current directory cannot be canonicalized");
236 let mut current_path: &Path = ¤t_dir;
238 // This gets the most-recent parent (the one that takes the fewest `cd ..`s to
241 if let Some(&package_index) = package_manifest_paths.get(current_path) {
242 break Some(package_index);
244 // We'll never reach the filesystem root, because to get to this point in the
246 // the call to `cargo_metadata::metadata` must have succeeded. So it's okay to
247 // unwrap the current path's parent.
248 current_path = current_path
250 .unwrap_or_else(|| panic!("could not find parent of path {}", current_path.display()));
254 }.expect("could not find matching package");
256 vec![metadata.packages.remove(package_index)]
259 for package in packages {
260 let manifest_path = package.manifest_path;
262 for target in package.targets {
263 let args = std::env::args()
265 .filter(|a| a != "--all" && !a.starts_with("--manifest-path="));
267 let args = std::iter::once(format!("--manifest-path={}", manifest_path)).chain(args);
268 if let Some(first) = target.kind.get(0) {
269 if target.kind.len() > 1 || first.ends_with("lib") {
270 if let Err(code) = process(std::iter::once("--lib".to_owned()).chain(args)) {
271 std::process::exit(code);
273 } else if ["bin", "example", "test", "bench"].contains(&&**first) {
274 if let Err(code) = process(
275 vec![format!("--{}", first), target.name]
279 std::process::exit(code);
283 panic!("badly formatted cargo metadata: target::kind is an empty array");
288 // this arm is executed when cargo-clippy runs `cargo rustc` with the `RUSTC`
289 // env var set to itself
291 let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
292 let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
293 let sys_root = if let (Some(home), Some(toolchain)) = (home, toolchain) {
294 format!("{}/toolchains/{}", home, toolchain)
296 option_env!("SYSROOT")
297 .map(|s| s.to_owned())
299 Command::new("rustc")
304 .and_then(|out| String::from_utf8(out.stdout).ok())
305 .map(|s| s.trim().to_owned())
308 "need to specify SYSROOT env var during clippy compilation, or use rustup or multirust",
312 rustc_driver::in_rustc_thread(|| {
313 // this conditional check for the --sysroot flag is there so users can call
314 // `cargo-clippy` directly
315 // without having to pass --sysroot or anything
316 let mut args: Vec<String> = if env::args().any(|s| s == "--sysroot") {
317 env::args().collect()
320 .chain(Some("--sysroot".to_owned()))
321 .chain(Some(sys_root))
325 // this check ensures that dependencies are built but not linted and the final
327 // linted but not built
328 let clippy_enabled = env::args().any(|s| s == "--emit=metadata");
331 args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
334 let mut ccc = ClippyCompilerCalls::new(clippy_enabled);
335 let (result, _) = rustc_driver::run_compiler(&args, &mut ccc, None, None);
336 if let Err(CompileIncomplete::Errored(_)) = result {
337 std::process::exit(1);
339 }).expect("rustc_thread failed");
343 fn process<I>(old_args: I) -> Result<(), i32>
345 I: Iterator<Item = String>,
347 let mut args = vec!["rustc".to_owned()];
349 let mut found_dashes = false;
350 for arg in old_args {
351 found_dashes |= arg == "--";
355 args.push("--".to_owned());
357 args.push("--emit=metadata".to_owned());
358 args.push("--cfg".to_owned());
359 args.push(r#"feature="cargo-clippy""#.to_owned());
361 let path = std::env::current_exe().expect("current executable path invalid");
362 let exit_status = std::process::Command::new("cargo")
366 .expect("could not run cargo")
368 .expect("failed to wait for cargo?");
370 if exit_status.success() {
373 Err(exit_status.code().unwrap_or(-1))