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