]> git.lizzy.rs Git - rust.git/blob - src/main.rs
43483e76a0fda28f000f4c87ea27fe050fe18590
[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, late_lint_passes, lint_groups, llvm_passes, attributes, mir_passes, .. } = registry;
75                 let sess = &state.session;
76                 let mut ls = sess.lint_store.borrow_mut();
77                 for pass in early_lint_passes {
78                     ls.register_early_pass(Some(sess), true, pass);
79                 }
80                 for pass in late_lint_passes {
81                     ls.register_late_pass(Some(sess), true, pass);
82                 }
83
84                 for (name, to) in lint_groups {
85                     ls.register_group(Some(sess), true, name, to);
86                 }
87
88                 sess.plugin_llvm_passes.borrow_mut().extend(llvm_passes);
89                 sess.mir_passes.borrow_mut().extend(mir_passes);
90                 sess.plugin_attributes.borrow_mut().extend(attributes);
91             }
92             old(state);
93         });
94
95         control
96     }
97 }
98
99 use std::path::Path;
100
101 pub fn main() {
102     use std::env;
103
104     if env::var("CLIPPY_DOGFOOD").map(|_| true).unwrap_or(false) {
105         panic!("yummy");
106     }
107
108     let dep_path = env::current_dir().expect("current dir is not readable").join("target").join("debug").join("deps");
109
110     let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
111     let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
112     let sys_root = match (home, toolchain) {
113         (Some(home), Some(toolchain)) => format!("{}/toolchains/{}", home, toolchain),
114         _ => option_env!("SYSROOT").map(|s| s.to_owned())
115                                    .or(Command::new("rustc").arg("--print")
116                                                             .arg("sysroot")
117                                                             .output().ok()
118                                                             .and_then(|out| String::from_utf8(out.stdout).ok())
119                                                             .map(|s| s.trim().to_owned())
120                                                             )
121                 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust"),
122     };
123
124     if let Some("clippy") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
125         let mut metadata = cargo::metadata().expect("could not obtain cargo metadata");
126         assert_eq!(metadata.version, 1);
127         for target in metadata.packages.remove(0).targets {
128             let args = std::env::args().skip(2);
129             if let Some(first) = target.kind.get(0) {
130                 if target.kind.len() > 1 || first.ends_with("lib") {
131                     if let Err(code) = process(std::iter::once("--lib".to_owned()).chain(args), &dep_path, &sys_root) {
132                         std::process::exit(code);
133                     }
134                 } else if first == "bin" {
135                     if let Err(code) = process(vec!["--bin".to_owned(), target.name].into_iter().chain(args), &dep_path, &sys_root) {
136                         std::process::exit(code);
137                     }
138                 }
139             } else {
140                 panic!("badly formatted cargo metadata: target::kind is an empty array");
141             }
142         }
143     } else {
144         let mut args: Vec<String> = if env::args().any(|s| s == "--sysroot") {
145             env::args().collect()
146         } else {
147             env::args().chain(Some("--sysroot".to_owned())).chain(Some(sys_root)).collect()
148         };
149
150         args.extend_from_slice(&["--cfg".to_owned(), r#"feature="clippy""#.to_owned()]);
151
152         let (result, _) = rustc_driver::run_compiler(&args, &mut ClippyCompilerCalls::new());
153
154         if let Err(err_count) = result {
155             if err_count > 0 {
156                 std::process::exit(1);
157             }
158         }
159     }
160 }
161
162 fn process<P, I>(old_args: I, dep_path: P, sysroot: &str) -> Result<(), i32>
163     where P: AsRef<Path>, I: Iterator<Item=String> {
164
165     let mut args = vec!["rustc".to_owned()];
166
167     let mut found_dashes = false;
168     for arg in old_args {
169         found_dashes |= arg == "--";
170         args.push(arg);
171     }
172     if !found_dashes {
173         args.push("--".to_owned());
174     }
175     args.push("-L".to_owned());
176     args.push(dep_path.as_ref().to_string_lossy().into_owned());
177     args.push(String::from("--sysroot"));
178     args.push(sysroot.to_owned());
179     args.push("-Zno-trans".to_owned());
180     args.push("--cfg".to_owned());
181     args.push(r#"feature="clippy""#.to_owned());
182
183     let path = std::env::current_exe().expect("current executable path invalid");
184     let exit_status = std::process::Command::new("cargo")
185         .args(&args)
186         .env("RUSTC", path)
187         .spawn().expect("could not run cargo")
188         .wait().expect("failed to wait for cargo?");
189
190     if exit_status.success() {
191         Ok(())
192     } else {
193         Err(exit_status.code().unwrap_or(-1))
194     }
195 }