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