]> git.lizzy.rs Git - rust.git/blob - src/main.rs
Changed signature of cargo::metadata according to review comment.
[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::Command;
20 use syntax::ast;
21
22 use clippy_lints::utils::cargo;
23
24 struct ClippyCompilerCalls {
25     default: RustcDefaultCalls,
26     run_lints: bool,
27 }
28
29 impl ClippyCompilerCalls {
30     fn new(run_lints: bool) -> Self {
31         ClippyCompilerCalls {
32             default: RustcDefaultCalls,
33             run_lints: run_lints,
34         }
35     }
36 }
37
38 impl<'a> CompilerCalls<'a> for ClippyCompilerCalls {
39     fn early_callback(&mut self,
40                       matches: &getopts::Matches,
41                       sopts: &config::Options,
42                       cfg: &ast::CrateConfig,
43                       descriptions: &rustc_errors::registry::Registry,
44                       output: ErrorOutputType)
45                       -> Compilation {
46         self.default.early_callback(matches, sopts, cfg, descriptions, output)
47     }
48     fn no_input(&mut self,
49                 matches: &getopts::Matches,
50                 sopts: &config::Options,
51                 cfg: &ast::CrateConfig,
52                 odir: &Option<PathBuf>,
53                 ofile: &Option<PathBuf>,
54                 descriptions: &rustc_errors::registry::Registry)
55                 -> Option<(Input, Option<PathBuf>)> {
56         self.default.no_input(matches, sopts, cfg, odir, ofile, descriptions)
57     }
58     fn late_callback(&mut self,
59                      matches: &getopts::Matches,
60                      sess: &Session,
61                      cfg: &ast::CrateConfig,
62                      input: &Input,
63                      odir: &Option<PathBuf>,
64                      ofile: &Option<PathBuf>)
65                      -> Compilation {
66         self.default.late_callback(matches, sess, cfg, input, odir, ofile)
67     }
68     fn build_controller(&mut self, sess: &Session, matches: &getopts::Matches) -> driver::CompileController<'a> {
69         let mut control = self.default.build_controller(sess, matches);
70
71         if self.run_lints {
72             let old = std::mem::replace(&mut control.after_parse.callback, box |_| {});
73             control.after_parse.callback = Box::new(move |state| {
74                 {
75                     let mut registry = rustc_plugin::registry::Registry::new(state.session, state.krate.as_ref().expect("at this compilation stage the krate must be parsed").span);
76                     registry.args_hidden = Some(Vec::new());
77                     clippy_lints::register_plugins(&mut registry);
78
79                     let rustc_plugin::registry::Registry { early_lint_passes,
80                                                            late_lint_passes,
81                                                            lint_groups,
82                                                            llvm_passes,
83                                                            attributes,
84                                                            mir_passes,
85                                                            .. } = registry;
86                     let sess = &state.session;
87                     let mut ls = sess.lint_store.borrow_mut();
88                     for pass in early_lint_passes {
89                         ls.register_early_pass(Some(sess), true, pass);
90                     }
91                     for pass in late_lint_passes {
92                         ls.register_late_pass(Some(sess), true, pass);
93                     }
94
95                     for (name, to) in lint_groups {
96                         ls.register_group(Some(sess), true, name, to);
97                     }
98
99                     sess.plugin_llvm_passes.borrow_mut().extend(llvm_passes);
100                     sess.mir_passes.borrow_mut().extend(mir_passes);
101                     sess.plugin_attributes.borrow_mut().extend(attributes);
102                 }
103                 old(state);
104             });
105         }
106
107         control
108     }
109 }
110
111 use std::path::Path;
112
113 pub fn main() {
114     use std::env;
115
116     if env::var("CLIPPY_DOGFOOD").map(|_| true).unwrap_or(false) {
117         panic!("yummy");
118     }
119
120     let dep_path = env::current_dir().expect("current dir is not readable").join("target").join("debug").join("deps");
121
122     let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
123     let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
124     let sys_root = if let (Some(home), Some(toolchain)) = (home, toolchain) {
125         format!("{}/toolchains/{}", home, toolchain)
126     } else {
127         option_env!("SYSROOT")
128             .map(|s| s.to_owned())
129             .or(Command::new("rustc")
130                 .arg("--print")
131                 .arg("sysroot")
132                 .output()
133                 .ok()
134                 .and_then(|out| String::from_utf8(out.stdout).ok())
135                 .map(|s| s.trim().to_owned()))
136             .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust")
137     };
138
139     if let Some("clippy") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
140         // this arm is executed on the initial call to `cargo clippy`
141         let manifest_path_arg = std::env::args().skip(2).find(|val| val.starts_with("--manifest-path="));
142
143         let mut metadata = cargo::metadata(manifest_path_arg.as_ref().map(AsRef::as_ref)).expect("could not obtain cargo metadata");
144         assert_eq!(metadata.version, 1);
145
146         let manifest_path = manifest_path_arg.map(|arg| PathBuf::from(Path::new(&arg["--manifest-path=".len()..])));
147
148         let current_dir = std::env::current_dir();
149
150         let package_index = metadata.packages.iter()
151             .position(|package| {
152                 let package_manifest_path = Path::new(&package.manifest_path);
153                 if let Some(ref manifest_path) = manifest_path {
154                     package_manifest_path == manifest_path
155                 } else if let Ok(ref current_dir) = current_dir {
156                     let package_manifest_directory = package_manifest_path.parent().expect("could not find parent directory of package manifest");
157                     package_manifest_directory == current_dir
158                 } else {
159                     panic!("could not read current directory")
160                 }
161             })
162             .expect("could not find matching package");
163         let package = metadata.packages.remove(package_index);
164         for target in package.targets {
165             let args = std::env::args().skip(2);
166             if let Some(first) = target.kind.get(0) {
167                 if target.kind.len() > 1 || first.ends_with("lib") {
168                     if let Err(code) = process(std::iter::once("--lib".to_owned()).chain(args), &dep_path, &sys_root) {
169                         std::process::exit(code);
170                     }
171                 } else if ["bin", "example", "test", "bench"].contains(&&**first) {
172                     if let Err(code) = process(vec![format!("--{}", first), target.name].into_iter().chain(args), &dep_path, &sys_root) {
173                         std::process::exit(code);
174                     }
175                 }
176             } else {
177                 panic!("badly formatted cargo metadata: target::kind is an empty array");
178             }
179         }
180     } else {
181         // this arm is executed when cargo-clippy runs `cargo rustc` with the `RUSTC` env var set to itself
182
183         // this conditional check for the --sysroot flag is there so users can call `cargo-clippy` directly
184         // without having to pass --sysroot or anything
185         let args: Vec<String> = if env::args().any(|s| s == "--sysroot") {
186             env::args().collect()
187         } else {
188             env::args().chain(Some("--sysroot".to_owned())).chain(Some(sys_root)).collect()
189         };
190         // this check ensures that dependencies are built but not linted and the final crate is
191         // linted but not built
192         let mut ccc = ClippyCompilerCalls::new(env::args().any(|s| s == "-Zno-trans"));
193         let (result, _) = rustc_driver::run_compiler(&args, &mut ccc, None, None);
194
195         if let Err(err_count) = result {
196             if err_count > 0 {
197                 std::process::exit(1);
198             }
199         }
200     }
201 }
202
203 fn process<P, I>(old_args: I, dep_path: P, sysroot: &str) -> Result<(), i32>
204     where P: AsRef<Path>,
205           I: Iterator<Item = String>
206 {
207
208     let mut args = vec!["rustc".to_owned()];
209
210     let mut found_dashes = false;
211     for arg in old_args {
212         found_dashes |= arg == "--";
213         args.push(arg);
214     }
215     if !found_dashes {
216         args.push("--".to_owned());
217     }
218     args.push("-L".to_owned());
219     args.push(dep_path.as_ref().to_string_lossy().into_owned());
220     args.push(String::from("--sysroot"));
221     args.push(sysroot.to_owned());
222     args.push("-Zno-trans".to_owned());
223
224     let path = std::env::current_exe().expect("current executable path invalid");
225     let exit_status = std::process::Command::new("cargo")
226         .args(&args)
227         .env("RUSTC", path)
228         .spawn().expect("could not run cargo")
229         .wait().expect("failed to wait for cargo?");
230
231     if exit_status.success() {
232         Ok(())
233     } else {
234         Err(exit_status.code().unwrap_or(-1))
235     }
236 }