]> git.lizzy.rs Git - rust.git/blob - src/main.rs
Allow cargo-clippy to work in subdirectories
[rust.git] / src / main.rs
1 // error-pattern:yummy
2 #![feature(box_syntax)]
3 #![feature(rustc_private)]
4
5 #![allow(unknown_lints, missing_docs_in_private_items)]
6
7 extern crate clippy_lints;
8 extern crate getopts;
9 extern crate rustc;
10 extern crate rustc_driver;
11 extern crate rustc_errors;
12 extern crate rustc_plugin;
13 extern crate syntax;
14
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};
20 use syntax::ast;
21 use std::io::{self, Write};
22
23 extern crate cargo_metadata;
24
25 struct ClippyCompilerCalls {
26     default: RustcDefaultCalls,
27     run_lints: bool,
28 }
29
30 impl ClippyCompilerCalls {
31     fn new(run_lints: bool) -> Self {
32         ClippyCompilerCalls {
33             default: RustcDefaultCalls,
34             run_lints: run_lints,
35         }
36     }
37 }
38
39 impl<'a> CompilerCalls<'a> for ClippyCompilerCalls {
40     fn early_callback(
41         &mut self,
42         matches: &getopts::Matches,
43         sopts: &config::Options,
44         cfg: &ast::CrateConfig,
45         descriptions: &rustc_errors::registry::Registry,
46         output: ErrorOutputType,
47     ) -> Compilation {
48         self.default
49             .early_callback(matches, sopts, cfg, descriptions, output)
50     }
51     fn no_input(
52         &mut self,
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>)> {
60         self.default
61             .no_input(matches, sopts, cfg, odir, ofile, descriptions)
62     }
63     fn late_callback(
64         &mut self,
65         matches: &getopts::Matches,
66         sess: &Session,
67         input: &Input,
68         odir: &Option<PathBuf>,
69         ofile: &Option<PathBuf>,
70     ) -> Compilation {
71         self.default
72             .late_callback(matches, sess, input, odir, ofile)
73     }
74     fn build_controller(&mut self, sess: &Session, matches: &getopts::Matches) -> driver::CompileController<'a> {
75         let mut control = self.default.build_controller(sess, matches);
76
77         if self.run_lints {
78             let old = std::mem::replace(&mut control.after_parse.callback, box |_| {});
79             control.after_parse.callback = Box::new(move |state| {
80                 {
81                     let mut registry = rustc_plugin::registry::Registry::new(state.session,
82                                                                              state
83                                                                                  .krate
84                                                                                  .as_ref()
85                                                                                  .expect("at this compilation stage \
86                                                                                           the krate must be parsed")
87                                                                                  .span);
88                     registry.args_hidden = Some(Vec::new());
89                     clippy_lints::register_plugins(&mut registry);
90
91                     let rustc_plugin::registry::Registry {
92                         early_lint_passes,
93                         late_lint_passes,
94                         lint_groups,
95                         llvm_passes,
96                         attributes,
97                         ..
98                     } = 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);
103                     }
104                     for pass in late_lint_passes {
105                         ls.register_late_pass(Some(sess), true, pass);
106                     }
107
108                     for (name, to) in lint_groups {
109                         ls.register_group(Some(sess), true, name, to);
110                     }
111
112                     sess.plugin_llvm_passes.borrow_mut().extend(llvm_passes);
113                     sess.plugin_attributes.borrow_mut().extend(attributes);
114                 }
115                 old(state);
116             });
117         }
118
119         control
120     }
121 }
122
123 use std::path::Path;
124
125 const CARGO_CLIPPY_HELP: &str = r#"Checks a package to catch common mistakes and improve your Rust code.
126
127 Usage:
128     cargo clippy [options] [--] [<opts>...]
129
130 Common options:
131     -h, --help               Print this message
132     --features               Features to compile for the package
133     -V, --version            Print version info and exit
134
135 Other options are the same as `cargo rustc`.
136
137 To allow or deny a lint from the command line you can use `cargo clippy --`
138 with:
139
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
144
145 The feature `cargo-clippy` is automatically defined for convenience. You can use
146 it to allow or deny lints from the code, eg.:
147
148     #[cfg_attr(feature = "cargo-clippy", allow(needless_lifetimes))]
149 "#;
150
151 #[allow(print_stdout)]
152 fn show_help() {
153     println!("{}", CARGO_CLIPPY_HELP);
154 }
155
156 #[allow(print_stdout)]
157 fn show_version() {
158     println!("{}", env!("CARGO_PKG_VERSION"));
159 }
160
161 fn has_prefix<'a, T: PartialEq, I: Iterator<Item = &'a T>>(v: &'a [T], itr: I) -> bool {
162     v.iter().zip(itr).all(|(a, b)| a == b)
163 }
164
165 pub fn main() {
166     use std::env;
167
168     if env::var("CLIPPY_DOGFOOD").map(|_| true).unwrap_or(false) {
169         panic!("yummy");
170     }
171
172     // Check for version and help flags even when invoked as 'cargo-clippy'
173     if std::env::args().any(|a| a == "--help" || a == "-h") {
174         show_help();
175         return;
176     }
177     if std::env::args().any(|a| a == "--version" || a == "-V") {
178         show_version();
179         return;
180     }
181
182     if let Some("clippy") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
183         // this arm is executed on the initial call to `cargo clippy`
184
185         let manifest_path_arg = std::env::args()
186             .skip(2)
187             .find(|val| val.starts_with("--manifest-path="));
188
189         let mut metadata =
190             if let Ok(metadata) = cargo_metadata::metadata(manifest_path_arg.as_ref().map(AsRef::as_ref)) {
191                 metadata
192             } else {
193                 let _ = io::stderr().write_fmt(format_args!("error: Could not obtain cargo metadata.\n"));
194                 process::exit(101);
195             };
196
197         let manifest_path = manifest_path_arg.map(|arg| PathBuf::from(Path::new(&arg["--manifest-path=".len()..])));
198
199         let package_index = {
200                 let mut iterator = metadata.packages.iter();
201
202                 if let Some(ref manifest_path) = manifest_path {
203                     iterator.position(|package| {
204                         let package_manifest_path = Path::new(&package.manifest_path);
205                         package_manifest_path == manifest_path
206                     })
207                 } else {
208                     let current_dir = std::env::current_dir()
209                         .expect("could not read current directory")
210                         .canonicalize()
211                         .expect("current directory cannot be canonicalized");
212                     let current_dir_components = current_dir.components().collect::<Vec<_>>();
213
214                     // This gets the most-recent parent (the one that takes the fewest `cd ..`s to
215                     // reach).
216                     iterator
217                         .enumerate()
218                         .filter_map(|(i, package)| {
219                             let package_manifest_path = Path::new(&package.manifest_path);
220                             let canonical_path = package_manifest_path
221                                 .parent()
222                                 .expect("could not find parent directory of package manifest")
223                                 .canonicalize()
224                                 .expect("package directory cannot be canonicalized");
225
226                             // TODO: We can do this in `O(1)` by combining the `len` and the
227                             //       iteration.
228                             let components = canonical_path.components().collect::<Vec<_>>();
229                             if has_prefix(&current_dir_components, components.iter()) {
230                                 Some((i, components.len()))
231                             } else {
232                                 None
233                             }
234                         })
235                         .max_by_key(|&(_, length)| length)
236                         .map(|(i, _)| i)
237                 }
238             }
239             .expect("could not find matching package");
240
241         let package = metadata.packages.remove(package_index);
242         for target in package.targets {
243             let args = std::env::args().skip(2);
244             if let Some(first) = target.kind.get(0) {
245                 if target.kind.len() > 1 || first.ends_with("lib") {
246                     if let Err(code) = process(std::iter::once("--lib".to_owned()).chain(args)) {
247                         std::process::exit(code);
248                     }
249                 } else if ["bin", "example", "test", "bench"].contains(&&**first) {
250                     if let Err(code) = process(vec![format!("--{}", first), target.name]
251                                                    .into_iter()
252                                                    .chain(args)) {
253                         std::process::exit(code);
254                     }
255                 }
256             } else {
257                 panic!("badly formatted cargo metadata: target::kind is an empty array");
258             }
259         }
260     } else {
261         // this arm is executed when cargo-clippy runs `cargo rustc` with the `RUSTC`
262         // env var set to itself
263
264         let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
265         let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
266         let sys_root = if let (Some(home), Some(toolchain)) = (home, toolchain) {
267             format!("{}/toolchains/{}", home, toolchain)
268         } else {
269             option_env!("SYSROOT")
270                 .map(|s| s.to_owned())
271                 .or_else(|| {
272                     Command::new("rustc")
273                         .arg("--print")
274                         .arg("sysroot")
275                         .output()
276                         .ok()
277                         .and_then(|out| String::from_utf8(out.stdout).ok())
278                         .map(|s| s.trim().to_owned())
279                 })
280                 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust")
281         };
282
283         rustc_driver::in_rustc_thread(|| {
284             // this conditional check for the --sysroot flag is there so users can call
285             // `cargo-clippy` directly
286             // without having to pass --sysroot or anything
287             let mut args: Vec<String> = if env::args().any(|s| s == "--sysroot") {
288                 env::args().collect()
289             } else {
290                 env::args()
291                     .chain(Some("--sysroot".to_owned()))
292                     .chain(Some(sys_root))
293                     .collect()
294             };
295
296             // this check ensures that dependencies are built but not linted and the final
297             // crate is
298             // linted but not built
299             let clippy_enabled = env::args().any(|s| s == "-Zno-trans");
300
301             if clippy_enabled {
302                 args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
303             }
304
305             let mut ccc = ClippyCompilerCalls::new(clippy_enabled);
306             let (result, _) = rustc_driver::run_compiler(&args, &mut ccc, None, None);
307             if let Err(err_count) = result {
308                 if err_count > 0 {
309                     std::process::exit(1);
310                 }
311             }
312         })
313                 .expect("rustc_thread failed");
314     }
315 }
316
317 fn process<I>(old_args: I) -> Result<(), i32>
318     where I: Iterator<Item = String>
319 {
320
321     let mut args = vec!["rustc".to_owned()];
322
323     let mut found_dashes = false;
324     for arg in old_args {
325         found_dashes |= arg == "--";
326         args.push(arg);
327     }
328     if !found_dashes {
329         args.push("--".to_owned());
330     }
331     args.push("-Zno-trans".to_owned());
332     args.push("--cfg".to_owned());
333     args.push(r#"feature="cargo-clippy""#.to_owned());
334
335     let path = std::env::current_exe().expect("current executable path invalid");
336     let exit_status = std::process::Command::new("cargo")
337         .args(&args)
338         .env("RUSTC", path)
339         .spawn()
340         .expect("could not run cargo")
341         .wait()
342         .expect("failed to wait for cargo?");
343
344     if exit_status.success() {
345         Ok(())
346     } else {
347         Err(exit_status.code().unwrap_or(-1))
348     }
349 }