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,
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,
68 odir: &Option<PathBuf>,
69 ofile: &Option<PathBuf>,
72 .late_callback(matches, sess, input, odir, ofile)
74 fn build_controller(&mut self, sess: &Session, matches: &getopts::Matches) -> driver::CompileController<'a> {
75 let mut control = self.default.build_controller(sess, matches);
78 let old = std::mem::replace(&mut control.after_parse.callback, box |_| {});
79 control.after_parse.callback = Box::new(move |state| {
81 let mut registry = rustc_plugin::registry::Registry::new(state.session,
85 .expect("at this compilation stage \
86 the krate must be parsed")
88 registry.args_hidden = Some(Vec::new());
89 clippy_lints::register_plugins(&mut registry);
91 let rustc_plugin::registry::Registry {
99 let sess = &state.session;
100 let mut ls = sess.lint_store.borrow_mut();
101 for pass in early_lint_passes {
102 ls.register_early_pass(Some(sess), true, pass);
104 for pass in late_lint_passes {
105 ls.register_late_pass(Some(sess), true, pass);
108 for (name, to) in lint_groups {
109 ls.register_group(Some(sess), true, name, to);
112 sess.plugin_llvm_passes.borrow_mut().extend(llvm_passes);
113 sess.plugin_attributes.borrow_mut().extend(attributes);
125 const CARGO_CLIPPY_HELP: &str = r#"Checks a package to catch common mistakes and improve your Rust code.
128 cargo clippy [options] [--] [<opts>...]
131 -h, --help Print this message
132 --features Features to compile for the package
133 -V, --version Print version info and exit
135 Other options are the same as `cargo rustc`.
137 To allow or deny a lint from the command line you can use `cargo clippy --`
140 -W --warn OPT Set lint warnings
141 -A --allow OPT Set lint allowed
142 -D --deny OPT Set lint denied
143 -F --forbid OPT Set lint forbidden
145 The feature `cargo-clippy` is automatically defined for convenience. You can use
146 it to allow or deny lints from the code, eg.:
148 #[cfg_attr(feature = "cargo-clippy", allow(needless_lifetimes))]
151 #[allow(print_stdout)]
153 println!("{}", CARGO_CLIPPY_HELP);
156 #[allow(print_stdout)]
158 println!("{}", env!("CARGO_PKG_VERSION"));
164 if env::var("CLIPPY_DOGFOOD").map(|_| true).unwrap_or(false) {
168 // Check for version and help flags even when invoked as 'cargo-clippy'
169 if std::env::args().any(|a| a == "--help" || a == "-h") {
173 if std::env::args().any(|a| a == "--version" || a == "-V") {
178 if let Some("clippy") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
179 // this arm is executed on the initial call to `cargo clippy`
181 let manifest_path_arg = std::env::args()
183 .find(|val| val.starts_with("--manifest-path="));
186 if let Ok(metadata) = cargo_metadata::metadata(manifest_path_arg.as_ref().map(AsRef::as_ref)) {
189 let _ = io::stderr().write_fmt(format_args!("error: Could not obtain cargo metadata.\n"));
193 let manifest_path = manifest_path_arg.map(|arg| PathBuf::from(Path::new(&arg["--manifest-path=".len()..])));
195 let current_dir = std::env::current_dir();
197 let package_index = metadata
200 .position(|package| {
201 let package_manifest_path = Path::new(&package.manifest_path);
202 if let Some(ref manifest_path) = manifest_path {
203 package_manifest_path == manifest_path
205 let current_dir = current_dir
207 .expect("could not read current directory");
208 let package_manifest_directory = package_manifest_path
210 .expect("could not find parent directory of package manifest");
211 package_manifest_directory == current_dir
214 .expect("could not find matching package");
215 let package = metadata.packages.remove(package_index);
216 for target in package.targets {
217 let args = std::env::args().skip(2);
218 if let Some(first) = target.kind.get(0) {
219 if target.kind.len() > 1 || first.ends_with("lib") {
220 if let Err(code) = process(std::iter::once("--lib".to_owned()).chain(args)) {
221 std::process::exit(code);
223 } else if ["bin", "example", "test", "bench"].contains(&&**first) {
224 if let Err(code) = process(vec![format!("--{}", first), target.name]
227 std::process::exit(code);
231 panic!("badly formatted cargo metadata: target::kind is an empty array");
235 // this arm is executed when cargo-clippy runs `cargo rustc` with the `RUSTC`
236 // env var set to itself
238 let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
239 let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
240 let sys_root = if let (Some(home), Some(toolchain)) = (home, toolchain) {
241 format!("{}/toolchains/{}", home, toolchain)
243 option_env!("SYSROOT")
244 .map(|s| s.to_owned())
246 Command::new("rustc")
251 .and_then(|out| String::from_utf8(out.stdout).ok())
252 .map(|s| s.trim().to_owned())
254 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust")
257 rustc_driver::in_rustc_thread(|| {
258 // this conditional check for the --sysroot flag is there so users can call
259 // `cargo-clippy` directly
260 // without having to pass --sysroot or anything
261 let mut args: Vec<String> = if env::args().any(|s| s == "--sysroot") {
262 env::args().collect()
265 .chain(Some("--sysroot".to_owned()))
266 .chain(Some(sys_root))
270 // this check ensures that dependencies are built but not linted and the final
272 // linted but not built
273 let clippy_enabled = env::args().any(|s| s == "--emit=metadata");
276 args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
279 let mut ccc = ClippyCompilerCalls::new(clippy_enabled);
280 let (result, _) = rustc_driver::run_compiler(&args, &mut ccc, None, None);
281 if let Err(err_count) = result {
283 std::process::exit(1);
287 .expect("rustc_thread failed");
291 fn process<I>(old_args: I) -> Result<(), i32>
292 where I: Iterator<Item = String>
295 let mut args = vec!["rustc".to_owned()];
297 let mut found_dashes = false;
298 for arg in old_args {
299 found_dashes |= arg == "--";
303 args.push("--".to_owned());
305 args.push("--emit=metadata".to_owned());
306 args.push("--cfg".to_owned());
307 args.push(r#"feature="cargo-clippy""#.to_owned());
309 let path = std::env::current_exe().expect("current executable path invalid");
310 let exit_status = std::process::Command::new("cargo")
314 .expect("could not run cargo")
316 .expect("failed to wait for cargo?");
318 if exit_status.success() {
321 Err(exit_status.code().unwrap_or(-1))