]> git.lizzy.rs Git - rust.git/blob - src/main.rs
Fix ICE #1969
[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         Self {
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
156 Other options are the same as `cargo rustc`.
157
158 To allow or deny a lint from the command line you can use `cargo clippy --`
159 with:
160
161     -W --warn OPT       Set lint warnings
162     -A --allow OPT      Set lint allowed
163     -D --deny OPT       Set lint denied
164     -F --forbid OPT     Set lint forbidden
165
166 The feature `cargo-clippy` is automatically defined for convenience. You can use
167 it to allow or deny lints from the code, eg.:
168
169     #[cfg_attr(feature = "cargo-clippy", allow(needless_lifetimes))]
170 "#;
171
172 #[allow(print_stdout)]
173 fn show_help() {
174     println!("{}", CARGO_CLIPPY_HELP);
175 }
176
177 #[allow(print_stdout)]
178 fn show_version() {
179     println!("{}", env!("CARGO_PKG_VERSION"));
180 }
181
182 pub fn main() {
183     use std::env;
184
185     if env::var("CLIPPY_DOGFOOD").map(|_| true).unwrap_or(false) {
186         panic!("yummy");
187     }
188
189     // Check for version and help flags even when invoked as 'cargo-clippy'
190     if std::env::args().any(|a| a == "--help" || a == "-h") {
191         show_help();
192         return;
193     }
194     if std::env::args().any(|a| a == "--version" || a == "-V") {
195         show_version();
196         return;
197     }
198
199     if let Some("clippy") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
200         // this arm is executed on the initial call to `cargo clippy`
201
202         let manifest_path_arg = std::env::args().skip(2).find(|val| {
203             val.starts_with("--manifest-path=")
204         });
205
206         let mut metadata =
207             if let Ok(metadata) = cargo_metadata::metadata(manifest_path_arg.as_ref().map(AsRef::as_ref)) {
208                 metadata
209             } else {
210                 let _ = io::stderr().write_fmt(format_args!("error: Could not obtain cargo metadata.\n"));
211                 process::exit(101);
212             };
213
214         let manifest_path = manifest_path_arg.map(|arg| {
215             Path::new(&arg["--manifest-path=".len()..])
216                 .canonicalize()
217                 .expect("manifest path could not be canonicalized")
218         });
219
220         let package_index = {
221             if let Some(manifest_path) = manifest_path {
222                 metadata.packages.iter().position(|package| {
223                     let package_manifest_path = Path::new(&package.manifest_path).canonicalize().expect(
224                         "package manifest path could not be canonicalized",
225                     );
226                     package_manifest_path == manifest_path
227                 })
228             } else {
229                 let package_manifest_paths: HashMap<_, _> = metadata
230                     .packages
231                     .iter()
232                     .enumerate()
233                     .map(|(i, package)| {
234                         let package_manifest_path = Path::new(&package.manifest_path)
235                             .parent()
236                             .expect("could not find parent directory of package manifest")
237                             .canonicalize()
238                             .expect("package directory cannot be canonicalized");
239                         (package_manifest_path, i)
240                     })
241                     .collect();
242
243                 let current_dir = std::env::current_dir()
244                     .expect("could not read current directory")
245                     .canonicalize()
246                     .expect("current directory cannot be canonicalized");
247
248                 let mut current_path: &Path = &current_dir;
249
250                 // This gets the most-recent parent (the one that takes the fewest `cd ..`s to
251                 // reach).
252                 loop {
253                     if let Some(&package_index) = package_manifest_paths.get(current_path) {
254                         break Some(package_index);
255                     } else {
256                         // We'll never reach the filesystem root, because to get to this point in the
257                         // code
258                         // the call to `cargo_metadata::metadata` must have succeeded. So it's okay to
259                         // unwrap the current path's parent.
260                         current_path = current_path.parent().unwrap_or_else(|| {
261                             panic!("could not find parent of path {}", current_path.display())
262                         });
263                     }
264                 }
265             }
266         }.expect("could not find matching package");
267
268         let package = metadata.packages.remove(package_index);
269         for target in package.targets {
270             let args = std::env::args().skip(2);
271             if let Some(first) = target.kind.get(0) {
272                 if target.kind.len() > 1 || first.ends_with("lib") {
273                     if let Err(code) = process(std::iter::once("--lib".to_owned()).chain(args)) {
274                         std::process::exit(code);
275                     }
276                 } else if ["bin", "example", "test", "bench"].contains(&&**first) {
277                     if let Err(code) = process(
278                         vec![format!("--{}", first), target.name]
279                             .into_iter()
280                             .chain(args),
281                     )
282                     {
283                         std::process::exit(code);
284                     }
285                 }
286             } else {
287                 panic!("badly formatted cargo metadata: target::kind is an empty array");
288             }
289         }
290     } else {
291         // this arm is executed when cargo-clippy runs `cargo rustc` with the `RUSTC`
292         // env var set to itself
293
294         let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
295         let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
296         let sys_root = if let (Some(home), Some(toolchain)) = (home, toolchain) {
297             format!("{}/toolchains/{}", home, toolchain)
298         } else {
299             option_env!("SYSROOT")
300                 .map(|s| s.to_owned())
301                 .or_else(|| {
302                     Command::new("rustc")
303                         .arg("--print")
304                         .arg("sysroot")
305                         .output()
306                         .ok()
307                         .and_then(|out| String::from_utf8(out.stdout).ok())
308                         .map(|s| s.trim().to_owned())
309                 })
310                 .expect(
311                     "need to specify SYSROOT env var during clippy compilation, or use rustup or multirust",
312                 )
313         };
314
315         rustc_driver::in_rustc_thread(|| {
316             // this conditional check for the --sysroot flag is there so users can call
317             // `cargo-clippy` directly
318             // without having to pass --sysroot or anything
319             let mut args: Vec<String> = if env::args().any(|s| s == "--sysroot") {
320                 env::args().collect()
321             } else {
322                 env::args()
323                     .chain(Some("--sysroot".to_owned()))
324                     .chain(Some(sys_root))
325                     .collect()
326             };
327
328             // this check ensures that dependencies are built but not linted and the final
329             // crate is
330             // linted but not built
331             let clippy_enabled = env::args().any(|s| s == "--emit=metadata");
332
333             if clippy_enabled {
334                 args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
335             }
336
337             let mut ccc = ClippyCompilerCalls::new(clippy_enabled);
338             let (result, _) = rustc_driver::run_compiler(&args, &mut ccc, None, None);
339             if let Err(CompileIncomplete::Errored(_)) = result {
340                 std::process::exit(1);
341             }
342         }).expect("rustc_thread failed");
343     }
344 }
345
346 fn process<I>(old_args: I) -> Result<(), i32>
347 where
348     I: Iterator<Item = String>,
349 {
350
351     let mut args = vec!["rustc".to_owned()];
352
353     let mut found_dashes = false;
354     for arg in old_args {
355         found_dashes |= arg == "--";
356         args.push(arg);
357     }
358     if !found_dashes {
359         args.push("--".to_owned());
360     }
361     args.push("--emit=metadata".to_owned());
362     args.push("--cfg".to_owned());
363     args.push(r#"feature="cargo-clippy""#.to_owned());
364
365     let path = std::env::current_exe().expect("current executable path invalid");
366     let exit_status = std::process::Command::new("cargo")
367         .args(&args)
368         .env("RUSTC", path)
369         .spawn()
370         .expect("could not run cargo")
371         .wait()
372         .expect("failed to wait for cargo?");
373
374     if exit_status.success() {
375         Ok(())
376     } else {
377         Err(exit_status.code().unwrap_or(-1))
378     }
379 }