]> git.lizzy.rs Git - rust.git/blob - src/main.rs
Merge remote-tracking branch 'origin/master' into sugg
[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
19 use clippy_lints::utils::cargo;
20
21 struct ClippyCompilerCalls {
22     default: RustcDefaultCalls,
23     run_lints: bool,
24 }
25
26 impl ClippyCompilerCalls {
27     fn new(run_lints: bool) -> Self {
28         ClippyCompilerCalls {
29             default: RustcDefaultCalls,
30             run_lints: run_lints,
31         }
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: &rustc_errors::registry::Registry,
40                       output: ErrorOutputType)
41                       -> Compilation {
42         self.default.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: &rustc_errors::registry::Registry)
50                 -> Option<(Input, Option<PathBuf>)> {
51         self.default.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.default.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.default.build_controller(sess, matches);
64
65         if self.run_lints {
66             let old = std::mem::replace(&mut control.after_parse.callback, box |_| {});
67             control.after_parse.callback = Box::new(move |state| {
68                 {
69                     let mut registry = rustc_plugin::registry::Registry::new(state.session, state.krate.as_ref().expect("at this compilation stage the krate must be parsed"));
70                     registry.args_hidden = Some(Vec::new());
71                     clippy_lints::register_plugins(&mut registry);
72
73                     let rustc_plugin::registry::Registry { early_lint_passes,
74                                                            late_lint_passes,
75                                                            lint_groups,
76                                                            llvm_passes,
77                                                            attributes,
78                                                            mir_passes,
79                                                            .. } = registry;
80                     let sess = &state.session;
81                     let mut ls = sess.lint_store.borrow_mut();
82                     for pass in early_lint_passes {
83                         ls.register_early_pass(Some(sess), true, pass);
84                     }
85                     for pass in late_lint_passes {
86                         ls.register_late_pass(Some(sess), true, pass);
87                     }
88
89                     for (name, to) in lint_groups {
90                         ls.register_group(Some(sess), true, name, to);
91                     }
92
93                     sess.plugin_llvm_passes.borrow_mut().extend(llvm_passes);
94                     sess.mir_passes.borrow_mut().extend(mir_passes);
95                     sess.plugin_attributes.borrow_mut().extend(attributes);
96                 }
97                 old(state);
98             });
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         // this arm is executed on the initial call to `cargo clippy`
135         let manifest_path = std::env::args().skip(2).find(|val| val.starts_with("--manifest-path="));
136         let mut metadata = cargo::metadata(manifest_path).expect("could not obtain cargo metadata");
137         assert_eq!(metadata.version, 1);
138         for target in metadata.packages.remove(0).targets {
139             let args = std::env::args().skip(2);
140             if let Some(first) = target.kind.get(0) {
141                 if target.kind.len() > 1 || first.ends_with("lib") {
142                     if let Err(code) = process(std::iter::once("--lib".to_owned()).chain(args), &dep_path, &sys_root) {
143                         std::process::exit(code);
144                     }
145                 } else if first == "bin" {
146                     if let Err(code) = process(vec!["--bin".to_owned(), target.name].into_iter().chain(args), &dep_path, &sys_root) {
147                         std::process::exit(code);
148                     }
149                 }
150             } else {
151                 panic!("badly formatted cargo metadata: target::kind is an empty array");
152             }
153         }
154     } else {
155         // this arm is executed when cargo-clippy runs `cargo rustc` with the `RUSTC` env var set to itself
156
157         // this conditional check for the --sysroot flag is there so users can call `cargo-clippy` directly
158         // without having to pass --sysroot or anything
159         let args: Vec<String> = if env::args().any(|s| s == "--sysroot") {
160             env::args().collect()
161         } else {
162             env::args().chain(Some("--sysroot".to_owned())).chain(Some(sys_root)).collect()
163         };
164         // this check ensures that dependencies are built but not linted and the final crate is
165         // linted but not built
166         let mut ccc = ClippyCompilerCalls::new(env::args().any(|s| s == "-Zno-trans"));
167         let (result, _) = rustc_driver::run_compiler(&args, &mut ccc);
168
169         if let Err(err_count) = result {
170             if err_count > 0 {
171                 std::process::exit(1);
172             }
173         }
174     }
175 }
176
177 fn process<P, I>(old_args: I, dep_path: P, sysroot: &str) -> Result<(), i32>
178     where P: AsRef<Path>,
179           I: Iterator<Item = String>
180 {
181
182     let mut args = vec!["rustc".to_owned()];
183
184     let mut found_dashes = false;
185     for arg in old_args {
186         found_dashes |= arg == "--";
187         args.push(arg);
188     }
189     if !found_dashes {
190         args.push("--".to_owned());
191     }
192     args.push("-L".to_owned());
193     args.push(dep_path.as_ref().to_string_lossy().into_owned());
194     args.push(String::from("--sysroot"));
195     args.push(sysroot.to_owned());
196     args.push("-Zno-trans".to_owned());
197
198     let path = std::env::current_exe().expect("current executable path invalid");
199     let exit_status = std::process::Command::new("cargo")
200         .args(&args)
201         .env("RUSTC", path)
202         .spawn().expect("could not run cargo")
203         .wait().expect("failed to wait for cargo?");
204
205     if exit_status.success() {
206         Ok(())
207     } else {
208         Err(exit_status.code().unwrap_or(-1))
209     }
210 }