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,
93 let sess = &state.session;
94 let mut ls = sess.lint_store.borrow_mut();
95 for pass in early_lint_passes {
96 ls.register_early_pass(Some(sess), true, pass);
98 for pass in late_lint_passes {
99 ls.register_late_pass(Some(sess), true, pass);
102 for (name, to) in lint_groups {
103 ls.register_group(Some(sess), true, name, to);
106 sess.plugin_llvm_passes.borrow_mut().extend(llvm_passes);
107 sess.plugin_attributes.borrow_mut().extend(attributes);
119 const CARGO_CLIPPY_HELP: &str = r#"Checks a package to catch common mistakes and improve your Rust code.
122 cargo clippy [options] [--] [<opts>...]
125 -h, --help Print this message
126 --features Features to compile for the package
127 -V, --version Print version info and exit
129 Other options are the same as `cargo rustc`.
131 To allow or deny a lint from the command line you can use `cargo clippy --`
134 -W --warn OPT Set lint warnings
135 -A --allow OPT Set lint allowed
136 -D --deny OPT Set lint denied
137 -F --forbid OPT Set lint forbidden
139 The feature `cargo-clippy` is automatically defined for convenience. You can use
140 it to allow or deny lints from the code, eg.:
142 #[cfg_attr(feature = "cargo-clippy", allow(needless_lifetimes))]
145 #[allow(print_stdout)]
147 println!("{}", CARGO_CLIPPY_HELP);
150 #[allow(print_stdout)]
152 println!("{}", env!("CARGO_PKG_VERSION"));
158 if env::var("CLIPPY_DOGFOOD").map(|_| true).unwrap_or(false) {
162 // Check for version and help flags even when invoked as 'cargo-clippy'
163 if std::env::args().any(|a| a == "--help" || a == "-h") {
167 if std::env::args().any(|a| a == "--version" || a == "-V") {
172 let dep_path = env::current_dir().expect("current dir is not readable").join("target").join("debug").join("deps");
174 if let Some("clippy") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
175 // this arm is executed on the initial call to `cargo clippy`
177 let manifest_path_arg = std::env::args().skip(2).find(|val| val.starts_with("--manifest-path="));
179 let mut metadata = if let Ok(metadata) = cargo_metadata::metadata(manifest_path_arg.as_ref()
180 .map(AsRef::as_ref)) {
183 let _ = io::stderr().write_fmt(format_args!("error: Could not obtain cargo metadata.\n"));
187 let manifest_path = manifest_path_arg.map(|arg| PathBuf::from(Path::new(&arg["--manifest-path=".len()..])));
189 let current_dir = std::env::current_dir();
191 let package_index = metadata.packages
193 .position(|package| {
194 let package_manifest_path = Path::new(&package.manifest_path);
195 if let Some(ref manifest_path) = manifest_path {
196 package_manifest_path == manifest_path
198 let current_dir = current_dir.as_ref().expect("could not read current directory");
199 let package_manifest_directory = package_manifest_path.parent()
200 .expect("could not find parent directory of package manifest");
201 package_manifest_directory == current_dir
204 .expect("could not find matching package");
205 let package = metadata.packages.remove(package_index);
206 for target in package.targets {
207 let args = std::env::args().skip(2);
208 if let Some(first) = target.kind.get(0) {
209 if target.kind.len() > 1 || first.ends_with("lib") {
210 if let Err(code) = process(std::iter::once("--lib".to_owned()).chain(args), &dep_path) {
211 std::process::exit(code);
213 } else if ["bin", "example", "test", "bench"].contains(&&**first) {
214 if let Err(code) = process(vec![format!("--{}", first), target.name].into_iter().chain(args),
216 std::process::exit(code);
220 panic!("badly formatted cargo metadata: target::kind is an empty array");
224 // this arm is executed when cargo-clippy runs `cargo rustc` with the `RUSTC` env var set to itself
226 let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
227 let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
228 let sys_root = if let (Some(home), Some(toolchain)) = (home, toolchain) {
229 format!("{}/toolchains/{}", home, toolchain)
231 option_env!("SYSROOT")
232 .map(|s| s.to_owned())
234 Command::new("rustc")
239 .and_then(|out| String::from_utf8(out.stdout).ok())
240 .map(|s| s.trim().to_owned())
242 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust")
245 rustc_driver::in_rustc_thread(|| {
246 // this conditional check for the --sysroot flag is there so users can call `cargo-clippy` directly
247 // without having to pass --sysroot or anything
248 let mut args: Vec<String> = if env::args().any(|s| s == "--sysroot") {
249 env::args().collect()
251 env::args().chain(Some("--sysroot".to_owned())).chain(Some(sys_root)).collect()
254 // this check ensures that dependencies are built but not linted and the final crate is
255 // linted but not built
256 let clippy_enabled = env::args().any(|s| s == "-Zno-trans");
259 args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
262 let mut ccc = ClippyCompilerCalls::new(clippy_enabled);
263 let (result, _) = rustc_driver::run_compiler(&args, &mut ccc, None, None);
264 if let Err(err_count) = result {
266 std::process::exit(1);
270 .expect("rustc_thread failed");
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))