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};
17 use rustc::session::config::{Input, ErrorOutputType};
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(matches, sopts, cfg, descriptions, output)
52 matches: &getopts::Matches,
53 sopts: &config::Options,
54 cfg: &ast::CrateConfig,
55 odir: &Option<PathBuf>,
56 ofile: &Option<PathBuf>,
57 descriptions: &rustc_errors::registry::Registry
58 ) -> Option<(Input, Option<PathBuf>)> {
59 self.default.no_input(matches, sopts, cfg, odir, ofile, descriptions)
63 matches: &getopts::Matches,
66 odir: &Option<PathBuf>,
67 ofile: &Option<PathBuf>
69 self.default.late_callback(matches, sess, input, odir, ofile)
71 fn build_controller(&mut self, sess: &Session, matches: &getopts::Matches) -> driver::CompileController<'a> {
72 let mut control = self.default.build_controller(sess, matches);
75 let old = std::mem::replace(&mut control.after_parse.callback, box |_| {});
76 control.after_parse.callback = Box::new(move |state| {
78 let mut registry = rustc_plugin::registry::Registry::new(state.session,
81 .expect("at this compilation stage \
82 the krate must be parsed")
84 registry.args_hidden = Some(Vec::new());
85 clippy_lints::register_plugins(&mut registry);
87 let rustc_plugin::registry::Registry { early_lint_passes,
94 let sess = &state.session;
95 let mut ls = sess.lint_store.borrow_mut();
96 for pass in early_lint_passes {
97 ls.register_early_pass(Some(sess), true, pass);
99 for pass in late_lint_passes {
100 ls.register_late_pass(Some(sess), true, pass);
103 for (name, to) in lint_groups {
104 ls.register_group(Some(sess), true, name, to);
107 sess.plugin_llvm_passes.borrow_mut().extend(llvm_passes);
108 sess.mir_passes.borrow_mut().extend(mir_passes);
109 sess.plugin_attributes.borrow_mut().extend(attributes);
121 const CARGO_CLIPPY_HELP: &str = r#"Checks a package to catch common mistakes and improve your Rust code.
124 cargo clippy [options] [--] [<opts>...]
127 -h, --help Print this message
128 --features Features to compile for the package
129 -V, --version Print version info and exit
131 Other options are the same as `cargo rustc`.
133 To allow or deny a lint from the command line you can use `cargo clippy --`
136 -W --warn OPT Set lint warnings
137 -A --allow OPT Set lint allowed
138 -D --deny OPT Set lint denied
139 -F --forbid OPT Set lint forbidden
141 The feature `cargo-clippy` is automatically defined for convenience. You can use
142 it to allow or deny lints from the code, eg.:
144 #[cfg_attr(feature = "cargo-clippy", allow(needless_lifetimes))]
147 #[allow(print_stdout)]
149 println!("{}", CARGO_CLIPPY_HELP);
152 #[allow(print_stdout)]
154 println!("{}", env!("CARGO_PKG_VERSION"));
160 if env::var("CLIPPY_DOGFOOD").map(|_| true).unwrap_or(false) {
164 // Check for version and help flags even when invoked as 'cargo-clippy'
165 if std::env::args().any(|a| a == "--help" || a == "-h") {
169 if std::env::args().any(|a| a == "--version" || a == "-V") {
174 let dep_path = env::current_dir().expect("current dir is not readable").join("target").join("debug").join("deps");
176 if let Some("clippy") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
177 // this arm is executed on the initial call to `cargo clippy`
179 let manifest_path_arg = std::env::args().skip(2).find(|val| val.starts_with("--manifest-path="));
181 let mut metadata = if let Ok(metadata) = cargo_metadata::metadata(manifest_path_arg.as_ref()
182 .map(AsRef::as_ref)) {
185 let _ = io::stderr().write_fmt(format_args!("error: Could not obtain cargo metadata."));
189 let manifest_path = manifest_path_arg.map(|arg| PathBuf::from(Path::new(&arg["--manifest-path=".len()..])));
191 let current_dir = std::env::current_dir();
193 let package_index = metadata.packages
195 .position(|package| {
196 let package_manifest_path = Path::new(&package.manifest_path);
197 if let Some(ref manifest_path) = manifest_path {
198 package_manifest_path == manifest_path
200 let current_dir = current_dir.as_ref().expect("could not read current directory");
201 let package_manifest_directory = package_manifest_path.parent()
202 .expect("could not find parent directory of package manifest");
203 package_manifest_directory == current_dir
206 .expect("could not find matching package");
207 let package = metadata.packages.remove(package_index);
208 for target in package.targets {
209 let args = std::env::args().skip(2);
210 if let Some(first) = target.kind.get(0) {
211 if target.kind.len() > 1 || first.ends_with("lib") {
212 if let Err(code) = process(std::iter::once("--lib".to_owned()).chain(args), &dep_path) {
213 std::process::exit(code);
215 } else if ["bin", "example", "test", "bench"].contains(&&**first) {
216 if let Err(code) = process(vec![format!("--{}", first), target.name].into_iter().chain(args),
218 std::process::exit(code);
222 panic!("badly formatted cargo metadata: target::kind is an empty array");
226 // this arm is executed when cargo-clippy runs `cargo rustc` with the `RUSTC` env var set to itself
228 let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
229 let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
230 let sys_root = if let (Some(home), Some(toolchain)) = (home, toolchain) {
231 format!("{}/toolchains/{}", home, toolchain)
233 option_env!("SYSROOT")
234 .map(|s| s.to_owned())
236 Command::new("rustc")
241 .and_then(|out| String::from_utf8(out.stdout).ok())
242 .map(|s| s.trim().to_owned())
244 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust")
247 // this conditional check for the --sysroot flag is there so users can call `cargo-clippy` directly
248 // without having to pass --sysroot or anything
249 let mut args: Vec<String> = if env::args().any(|s| s == "--sysroot") {
250 env::args().collect()
252 env::args().chain(Some("--sysroot".to_owned())).chain(Some(sys_root)).collect()
255 // this check ensures that dependencies are built but not linted and the final crate is
256 // linted but not built
257 let clippy_enabled = env::args().any(|s| s == "-Zno-trans");
260 args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
263 let mut ccc = ClippyCompilerCalls::new(clippy_enabled);
264 let (result, _) = rustc_driver::run_compiler(&args, &mut ccc, None, None);
266 if let Err(err_count) = result {
268 std::process::exit(1);
274 fn process<P, I>(old_args: I, dep_path: P) -> Result<(), i32>
275 where P: AsRef<Path>,
276 I: Iterator<Item = String>
279 let mut args = vec!["rustc".to_owned()];
281 let mut found_dashes = false;
282 for arg in old_args {
283 found_dashes |= arg == "--";
287 args.push("--".to_owned());
289 args.push("-L".to_owned());
290 args.push(dep_path.as_ref().to_string_lossy().into_owned());
291 args.push("-Zno-trans".to_owned());
292 args.push("--cfg".to_owned());
293 args.push(r#"feature="cargo-clippy""#.to_owned());
295 let path = std::env::current_exe().expect("current executable path invalid");
296 let exit_status = std::process::Command::new("cargo")
300 .expect("could not run cargo")
302 .expect("failed to wait for cargo?");
304 if exit_status.success() {
307 Err(exit_status.code().unwrap_or(-1))