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