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