2 #![feature(box_syntax)]
3 #![feature(rustc_private)]
5 #![allow(unknown_lints, missing_docs_in_private_items)]
7 extern crate clippy_lints;
10 extern crate rustc_driver;
11 extern crate rustc_errors;
12 extern crate rustc_plugin;
15 use rustc_driver::{driver, CompilerCalls, RustcDefaultCalls, Compilation};
16 use rustc::session::{config, Session, CompileIncomplete};
17 use rustc::session::config::{Input, ErrorOutputType};
18 use std::collections::HashMap;
19 use std::path::PathBuf;
20 use std::process::{self, Command};
22 use std::io::{self, Write};
24 extern crate cargo_metadata;
26 struct ClippyCompilerCalls {
27 default: RustcDefaultCalls,
31 impl ClippyCompilerCalls {
32 fn new(run_lints: bool) -> Self {
34 default: RustcDefaultCalls,
40 impl<'a> CompilerCalls<'a> for ClippyCompilerCalls {
43 matches: &getopts::Matches,
44 sopts: &config::Options,
45 cfg: &ast::CrateConfig,
46 descriptions: &rustc_errors::registry::Registry,
47 output: ErrorOutputType,
50 .early_callback(matches, sopts, cfg, descriptions, output)
54 matches: &getopts::Matches,
55 sopts: &config::Options,
56 cfg: &ast::CrateConfig,
57 odir: &Option<PathBuf>,
58 ofile: &Option<PathBuf>,
59 descriptions: &rustc_errors::registry::Registry,
60 ) -> Option<(Input, Option<PathBuf>)> {
62 .no_input(matches, sopts, cfg, odir, ofile, descriptions)
66 matches: &getopts::Matches,
69 odir: &Option<PathBuf>,
70 ofile: &Option<PathBuf>,
73 .late_callback(matches, sess, 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(state.session,
86 .expect("at this compilation stage \
87 the krate must be parsed")
89 registry.args_hidden = Some(Vec::new());
90 clippy_lints::register_plugins(&mut registry);
92 let rustc_plugin::registry::Registry {
100 let sess = &state.session;
101 let mut ls = sess.lint_store.borrow_mut();
102 for pass in early_lint_passes {
103 ls.register_early_pass(Some(sess), true, pass);
105 for pass in late_lint_passes {
106 ls.register_late_pass(Some(sess), true, pass);
109 for (name, to) in lint_groups {
110 ls.register_group(Some(sess), true, name, to);
113 sess.plugin_llvm_passes.borrow_mut().extend(llvm_passes);
114 sess.plugin_attributes.borrow_mut().extend(attributes);
126 const CARGO_CLIPPY_HELP: &str = r#"Checks a package to catch common mistakes and improve your Rust code.
129 cargo clippy [options] [--] [<opts>...]
132 -h, --help Print this message
133 --features Features to compile for the package
134 -V, --version Print version info and exit
136 Other options are the same as `cargo rustc`.
138 To allow or deny a lint from the command line you can use `cargo clippy --`
141 -W --warn OPT Set lint warnings
142 -A --allow OPT Set lint allowed
143 -D --deny OPT Set lint denied
144 -F --forbid OPT Set lint forbidden
146 The feature `cargo-clippy` is automatically defined for convenience. You can use
147 it to allow or deny lints from the code, eg.:
149 #[cfg_attr(feature = "cargo-clippy", allow(needless_lifetimes))]
152 #[allow(print_stdout)]
154 println!("{}", CARGO_CLIPPY_HELP);
157 #[allow(print_stdout)]
159 println!("{}", env!("CARGO_PKG_VERSION"));
165 if env::var("CLIPPY_DOGFOOD").map(|_| true).unwrap_or(false) {
169 // Check for version and help flags even when invoked as 'cargo-clippy'
170 if std::env::args().any(|a| a == "--help" || a == "-h") {
174 if std::env::args().any(|a| a == "--version" || a == "-V") {
179 if let Some("clippy") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
180 // this arm is executed on the initial call to `cargo clippy`
182 let manifest_path_arg = std::env::args()
184 .find(|val| val.starts_with("--manifest-path="));
187 if let Ok(metadata) = cargo_metadata::metadata(manifest_path_arg.as_ref().map(AsRef::as_ref)) {
190 let _ = io::stderr().write_fmt(format_args!("error: Could not obtain cargo metadata.\n"));
194 let manifest_path = manifest_path_arg.map(|arg| PathBuf::from(Path::new(&arg["--manifest-path=".len()..])));
196 let package_index = {
197 if let Some(ref manifest_path) = manifest_path {
198 metadata.packages.iter().position(|package| {
199 let package_manifest_path = Path::new(&package.manifest_path);
200 package_manifest_path == manifest_path
203 let package_manifest_paths: HashMap<_, _> =
204 metadata.packages.iter()
206 .map(|(i, package)| {
207 let package_manifest_path = Path::new(&package.manifest_path)
209 .expect("could not find parent directory of package manifest")
211 .expect("package directory cannot be canonicalized");
212 (package_manifest_path, i)
216 let current_dir = std::env::current_dir()
217 .expect("could not read current directory")
219 .expect("current directory cannot be canonicalized");
221 let mut current_path: &Path = ¤t_dir;
223 // This gets the most-recent parent (the one that takes the fewest `cd ..`s to
226 if let Some(&package_index) = package_manifest_paths.get(current_path) {
227 break Some(package_index);
230 // We'll never reach the filesystem root, because to get to this point in the code
231 // the call to `cargo_metadata::metadata` must have succeeded. So it's okay to
232 // unwrap the current path's parent.
233 current_path = current_path
235 .unwrap_or_else(|| panic!("could not find parent of path {}", current_path.display()));
240 .expect("could not find matching package");
242 let package = metadata.packages.remove(package_index);
243 for target in package.targets {
244 let args = std::env::args().skip(2);
245 if let Some(first) = target.kind.get(0) {
246 if target.kind.len() > 1 || first.ends_with("lib") {
247 if let Err(code) = process(std::iter::once("--lib".to_owned()).chain(args)) {
248 std::process::exit(code);
250 } else if ["bin", "example", "test", "bench"].contains(&&**first) {
251 if let Err(code) = process(vec![format!("--{}", first), target.name]
254 std::process::exit(code);
258 panic!("badly formatted cargo metadata: target::kind is an empty array");
262 // this arm is executed when cargo-clippy runs `cargo rustc` with the `RUSTC`
263 // env var set to itself
265 let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
266 let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
267 let sys_root = if let (Some(home), Some(toolchain)) = (home, toolchain) {
268 format!("{}/toolchains/{}", home, toolchain)
270 option_env!("SYSROOT")
271 .map(|s| s.to_owned())
273 Command::new("rustc")
278 .and_then(|out| String::from_utf8(out.stdout).ok())
279 .map(|s| s.trim().to_owned())
281 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust")
284 rustc_driver::in_rustc_thread(|| {
285 // this conditional check for the --sysroot flag is there so users can call
286 // `cargo-clippy` directly
287 // without having to pass --sysroot or anything
288 let mut args: Vec<String> = if env::args().any(|s| s == "--sysroot") {
289 env::args().collect()
292 .chain(Some("--sysroot".to_owned()))
293 .chain(Some(sys_root))
297 // this check ensures that dependencies are built but not linted and the final
299 // linted but not built
300 let clippy_enabled = env::args().any(|s| s == "--emit=metadata");
303 args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
306 let mut ccc = ClippyCompilerCalls::new(clippy_enabled);
307 let (result, _) = rustc_driver::run_compiler(&args, &mut ccc, None, None);
308 if let Err(CompileIncomplete::Errored(_)) = result {
309 std::process::exit(1);
312 .expect("rustc_thread failed");
316 fn process<I>(old_args: I) -> Result<(), i32>
317 where I: Iterator<Item = String>
320 let mut args = vec!["rustc".to_owned()];
322 let mut found_dashes = false;
323 for arg in old_args {
324 found_dashes |= arg == "--";
328 args.push("--".to_owned());
330 args.push("--emit=metadata".to_owned());
331 args.push("--cfg".to_owned());
332 args.push(r#"feature="cargo-clippy""#.to_owned());
334 let path = std::env::current_exe().expect("current executable path invalid");
335 let exit_status = std::process::Command::new("cargo")
339 .expect("could not run cargo")
341 .expect("failed to wait for cargo?");
343 if exit_status.success() {
346 Err(exit_status.code().unwrap_or(-1))