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