]> git.lizzy.rs Git - rust.git/blob - src/main.rs
cf57926440bd887014a19f16159d90bcb54a5a0b
[rust.git] / src / main.rs
1 // error-pattern:yummy
2 #![feature(box_syntax)]
3 #![feature(rustc_private)]
4
5 extern crate rustc_driver;
6 extern crate getopts;
7 extern crate rustc;
8 extern crate syntax;
9 extern crate rustc_plugin;
10 extern crate clippy_lints;
11
12 use rustc_driver::{driver, CompilerCalls, RustcDefaultCalls, Compilation};
13 use rustc::session::{config, Session};
14 use rustc::session::config::{Input, ErrorOutputType};
15 use syntax::diagnostics;
16 use std::path::PathBuf;
17 use std::process::Command;
18
19 use clippy_lints::utils::cargo;
20
21 struct ClippyCompilerCalls(RustcDefaultCalls);
22
23 impl std::default::Default for ClippyCompilerCalls {
24     fn default() -> Self {
25         Self::new()
26     }
27 }
28
29 impl ClippyCompilerCalls {
30     fn new() -> Self {
31         ClippyCompilerCalls(RustcDefaultCalls)
32     }
33 }
34
35 impl<'a> CompilerCalls<'a> for ClippyCompilerCalls {
36     fn early_callback(&mut self,
37                       matches: &getopts::Matches,
38                       sopts: &config::Options,
39                       descriptions: &diagnostics::registry::Registry,
40                       output: ErrorOutputType)
41                       -> Compilation {
42         self.0.early_callback(matches, sopts, descriptions, output)
43     }
44     fn no_input(&mut self,
45                 matches: &getopts::Matches,
46                 sopts: &config::Options,
47                 odir: &Option<PathBuf>,
48                 ofile: &Option<PathBuf>,
49                 descriptions: &diagnostics::registry::Registry)
50                 -> Option<(Input, Option<PathBuf>)> {
51         self.0.no_input(matches, sopts, odir, ofile, descriptions)
52     }
53     fn late_callback(&mut self,
54                      matches: &getopts::Matches,
55                      sess: &Session,
56                      input: &Input,
57                      odir: &Option<PathBuf>,
58                      ofile: &Option<PathBuf>)
59                      -> Compilation {
60         self.0.late_callback(matches, sess, input, odir, ofile)
61     }
62     fn build_controller(&mut self, sess: &Session, matches: &getopts::Matches) -> driver::CompileController<'a> {
63         let mut control = self.0.build_controller(sess, matches);
64
65         let old = std::mem::replace(&mut control.after_parse.callback, box |_| {});
66         control.after_parse.callback = Box::new(move |state| {
67             {
68                 let mut registry = rustc_plugin::registry::Registry::new(state.session, state.krate.as_ref().expect("at this compilation stage the krate must be parsed"));
69                 registry.args_hidden = Some(Vec::new());
70                 clippy_lints::register_plugins(&mut registry);
71
72                 let rustc_plugin::registry::Registry { early_lint_passes,
73                                                        late_lint_passes,
74                                                        lint_groups,
75                                                        llvm_passes,
76                                                        attributes,
77                                                        mir_passes,
78                                                        .. } = registry;
79                 let sess = &state.session;
80                 let mut ls = sess.lint_store.borrow_mut();
81                 for pass in early_lint_passes {
82                     ls.register_early_pass(Some(sess), true, pass);
83                 }
84                 for pass in late_lint_passes {
85                     ls.register_late_pass(Some(sess), true, pass);
86                 }
87
88                 for (name, to) in lint_groups {
89                     ls.register_group(Some(sess), true, name, to);
90                 }
91
92                 sess.plugin_llvm_passes.borrow_mut().extend(llvm_passes);
93                 sess.mir_passes.borrow_mut().extend(mir_passes);
94                 sess.plugin_attributes.borrow_mut().extend(attributes);
95             }
96             old(state);
97         });
98
99         control
100     }
101 }
102
103 use std::path::Path;
104
105 pub fn main() {
106     use std::env;
107
108     if env::var("CLIPPY_DOGFOOD").map(|_| true).unwrap_or(false) {
109         panic!("yummy");
110     }
111
112     let dep_path = env::current_dir().expect("current dir is not readable").join("target").join("debug").join("deps");
113
114     let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
115     let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
116     let sys_root = if let (Some(home), Some(toolchain)) = (home, toolchain) {
117         format!("{}/toolchains/{}", home, toolchain)
118     } else {
119         option_env!("SYSROOT")
120             .map(|s| s.to_owned())
121             .or(Command::new("rustc")
122                 .arg("--print")
123                 .arg("sysroot")
124                 .output()
125                 .ok()
126                 .and_then(|out| String::from_utf8(out.stdout).ok())
127                 .map(|s| s.trim().to_owned()))
128             .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust")
129     };
130
131     if let Some("clippy") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
132         let manifest_path = std::env::args().skip(2).find(|val| val.starts_with("--manifest-path="));
133         let mut metadata = cargo::metadata(manifest_path).expect("could not obtain cargo metadata");
134         assert_eq!(metadata.version, 1);
135         for target in metadata.packages.remove(0).targets {
136             let args = std::env::args().skip(2);
137             if let Some(first) = target.kind.get(0) {
138                 if target.kind.len() > 1 || first.ends_with("lib") {
139                     if let Err(code) = process(std::iter::once("--lib".to_owned()).chain(args), &dep_path, &sys_root) {
140                         std::process::exit(code);
141                     }
142                 } else if first == "bin" {
143                     if let Err(code) = process(vec!["--bin".to_owned(), target.name].into_iter().chain(args), &dep_path, &sys_root) {
144                         std::process::exit(code);
145                     }
146                 }
147             } else {
148                 panic!("badly formatted cargo metadata: target::kind is an empty array");
149             }
150         }
151     } else {
152         let mut args: Vec<String> = if env::args().any(|s| s == "--sysroot") {
153             env::args().collect()
154         } else {
155             env::args().chain(Some("--sysroot".to_owned())).chain(Some(sys_root)).collect()
156         };
157
158         args.extend_from_slice(&["--cfg".to_owned(), r#"feature="clippy""#.to_owned()]);
159
160         let (result, _) = rustc_driver::run_compiler(&args, &mut ClippyCompilerCalls::new());
161
162         if let Err(err_count) = result {
163             if err_count > 0 {
164                 std::process::exit(1);
165             }
166         }
167     }
168 }
169
170 fn process<P, I>(old_args: I, dep_path: P, sysroot: &str) -> Result<(), i32>
171     where P: AsRef<Path>,
172           I: Iterator<Item = String>
173 {
174
175     let mut args = vec!["rustc".to_owned()];
176
177     let mut found_dashes = false;
178     for arg in old_args {
179         found_dashes |= arg == "--";
180         args.push(arg);
181     }
182     if !found_dashes {
183         args.push("--".to_owned());
184     }
185     args.push("-L".to_owned());
186     args.push(dep_path.as_ref().to_string_lossy().into_owned());
187     args.push(String::from("--sysroot"));
188     args.push(sysroot.to_owned());
189     args.push("-Zno-trans".to_owned());
190     args.push("--cfg".to_owned());
191     args.push(r#"feature="clippy""#.to_owned());
192
193     let path = std::env::current_exe().expect("current executable path invalid");
194     let exit_status = std::process::Command::new("cargo")
195         .args(&args)
196         .env("RUSTC", path)
197         .spawn().expect("could not run cargo")
198         .wait().expect("failed to wait for cargo?");
199
200     if exit_status.success() {
201         Ok(())
202     } else {
203         Err(exit_status.code().unwrap_or(-1))
204     }
205 }