]> git.lizzy.rs Git - rust.git/blob - src/main.rs
Run rustfmt
[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 = match (home, toolchain) {
119         (Some(home), Some(toolchain)) => format!("{}/toolchains/{}", home, toolchain),
120         _ => {
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
134     if let Some("clippy") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
135         let mut metadata = cargo::metadata().expect("could not obtain cargo metadata");
136         assert_eq!(metadata.version, 1);
137         for target in metadata.packages.remove(0).targets {
138             let args = std::env::args().skip(2);
139             if let Some(first) = target.kind.get(0) {
140                 if target.kind.len() > 1 || first.ends_with("lib") {
141                     if let Err(code) = process(std::iter::once("--lib".to_owned()).chain(args), &dep_path, &sys_root) {
142                         std::process::exit(code);
143                     }
144                 } else if first == "bin" {
145                     if let Err(code) = process(vec!["--bin".to_owned(), target.name].into_iter().chain(args), &dep_path, &sys_root) {
146                         std::process::exit(code);
147                     }
148                 }
149             } else {
150                 panic!("badly formatted cargo metadata: target::kind is an empty array");
151             }
152         }
153     } else {
154         let mut args: Vec<String> = if env::args().any(|s| s == "--sysroot") {
155             env::args().collect()
156         } else {
157             env::args().chain(Some("--sysroot".to_owned())).chain(Some(sys_root)).collect()
158         };
159
160         args.extend_from_slice(&["--cfg".to_owned(), r#"feature="clippy""#.to_owned()]);
161
162         let (result, _) = rustc_driver::run_compiler(&args, &mut ClippyCompilerCalls::new());
163
164         if let Err(err_count) = result {
165             if err_count > 0 {
166                 std::process::exit(1);
167             }
168         }
169     }
170 }
171
172 fn process<P, I>(old_args: I, dep_path: P, sysroot: &str) -> Result<(), i32>
173     where P: AsRef<Path>,
174           I: Iterator<Item = String>
175 {
176
177     let mut args = vec!["rustc".to_owned()];
178
179     let mut found_dashes = false;
180     for arg in old_args {
181         found_dashes |= arg == "--";
182         args.push(arg);
183     }
184     if !found_dashes {
185         args.push("--".to_owned());
186     }
187     args.push("-L".to_owned());
188     args.push(dep_path.as_ref().to_string_lossy().into_owned());
189     args.push(String::from("--sysroot"));
190     args.push(sysroot.to_owned());
191     args.push("-Zno-trans".to_owned());
192     args.push("--cfg".to_owned());
193     args.push(r#"feature="clippy""#.to_owned());
194
195     let path = std::env::current_exe().expect("current executable path invalid");
196     let exit_status = std::process::Command::new("cargo")
197         .args(&args)
198         .env("RUSTC", path)
199         .spawn().expect("could not run cargo")
200         .wait().expect("failed to wait for cargo?");
201
202     if exit_status.success() {
203         Ok(())
204     } else {
205         Err(exit_status.code().unwrap_or(-1))
206     }
207 }