]> git.lizzy.rs Git - rust.git/blob - src/main.rs
fixed #1331
[rust.git] / src / main.rs
1 // error-pattern:yummy
2 #![feature(box_syntax)]
3 #![feature(rustc_private)]
4 #![feature(static_in_const)]
5
6 #![allow(unknown_lints, missing_docs_in_private_items)]
7
8 extern crate clippy_lints;
9 extern crate getopts;
10 extern crate rustc;
11 extern crate rustc_driver;
12 extern crate rustc_errors;
13 extern crate rustc_plugin;
14 extern crate syntax;
15
16 use rustc_driver::{driver, CompilerCalls, RustcDefaultCalls, Compilation};
17 use rustc::session::{config, Session};
18 use rustc::session::config::{Input, ErrorOutputType};
19 use std::path::PathBuf;
20 use std::process::Command;
21 use syntax::ast;
22
23 use clippy_lints::utils::cargo;
24
25 struct ClippyCompilerCalls {
26     default: RustcDefaultCalls,
27     run_lints: bool,
28 }
29
30 impl ClippyCompilerCalls {
31     fn new(run_lints: bool) -> Self {
32         ClippyCompilerCalls {
33             default: RustcDefaultCalls,
34             run_lints: run_lints,
35         }
36     }
37 }
38
39 impl<'a> CompilerCalls<'a> for ClippyCompilerCalls {
40     fn early_callback(&mut self,
41                       matches: &getopts::Matches,
42                       sopts: &config::Options,
43                       cfg: &ast::CrateConfig,
44                       descriptions: &rustc_errors::registry::Registry,
45                       output: ErrorOutputType)
46                       -> Compilation {
47         self.default.early_callback(matches, sopts, cfg, descriptions, output)
48     }
49     fn no_input(&mut self,
50                 matches: &getopts::Matches,
51                 sopts: &config::Options,
52                 cfg: &ast::CrateConfig,
53                 odir: &Option<PathBuf>,
54                 ofile: &Option<PathBuf>,
55                 descriptions: &rustc_errors::registry::Registry)
56                 -> Option<(Input, Option<PathBuf>)> {
57         self.default.no_input(matches, sopts, cfg, odir, ofile, descriptions)
58     }
59     fn late_callback(&mut self,
60                      matches: &getopts::Matches,
61                      sess: &Session,
62                      input: &Input,
63                      odir: &Option<PathBuf>,
64                      ofile: &Option<PathBuf>)
65                      -> Compilation {
66         self.default.late_callback(matches, sess, input, odir, ofile)
67     }
68     fn build_controller(&mut self, sess: &Session, matches: &getopts::Matches) -> driver::CompileController<'a> {
69         let mut control = self.default.build_controller(sess, matches);
70
71         if self.run_lints {
72             let old = std::mem::replace(&mut control.after_parse.callback, box |_| {});
73             control.after_parse.callback = Box::new(move |state| {
74                 {
75                     let mut registry = rustc_plugin::registry::Registry::new(state.session, state.krate.as_ref().expect("at this compilation stage the krate must be parsed").span);
76                     registry.args_hidden = Some(Vec::new());
77                     clippy_lints::register_plugins(&mut registry);
78
79                     let rustc_plugin::registry::Registry { early_lint_passes,
80                                                            late_lint_passes,
81                                                            lint_groups,
82                                                            llvm_passes,
83                                                            attributes,
84                                                            mir_passes,
85                                                            .. } = registry;
86                     let sess = &state.session;
87                     let mut ls = sess.lint_store.borrow_mut();
88                     for pass in early_lint_passes {
89                         ls.register_early_pass(Some(sess), true, pass);
90                     }
91                     for pass in late_lint_passes {
92                         ls.register_late_pass(Some(sess), true, pass);
93                     }
94
95                     for (name, to) in lint_groups {
96                         ls.register_group(Some(sess), true, name, to);
97                     }
98
99                     sess.plugin_llvm_passes.borrow_mut().extend(llvm_passes);
100                     sess.mir_passes.borrow_mut().extend(mir_passes);
101                     sess.plugin_attributes.borrow_mut().extend(attributes);
102                 }
103                 old(state);
104             });
105         }
106
107         control
108     }
109 }
110
111 use std::path::Path;
112
113 const CARGO_CLIPPY_HELP: &str = r#"Checks a package to catch common mistakes and improve your Rust code.
114
115 Usage:
116     cargo clippy [options] [--] [<opts>...]
117
118 Common options:
119     -h, --help               Print this message
120     --features               Features to compile for the package
121
122 Other options are the same as `cargo rustc`.
123
124 To allow or deny a lint from the command line you can use `cargo clippy --`
125 with:
126
127     -W --warn OPT       Set lint warnings
128     -A --allow OPT      Set lint allowed
129     -D --deny OPT       Set lint denied
130     -F --forbid OPT     Set lint forbidden
131
132 The feature `cargo-clippy` is automatically defined for convenience. You can use
133 it to allow or deny lints from the code, eg.:
134
135     #[cfg_attr(feature = "cargo-clippy", allow(needless_lifetimes))]
136 "#;
137
138 #[allow(print_stdout)]
139 fn show_help() {
140     println!("{}", CARGO_CLIPPY_HELP);
141 }
142
143 pub fn main() {
144     use std::env;
145
146     if env::var("CLIPPY_DOGFOOD").map(|_| true).unwrap_or(false) {
147         panic!("yummy");
148     }
149
150     let dep_path = env::current_dir().expect("current dir is not readable").join("target").join("debug").join("deps");
151
152     if let Some("clippy") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
153         // this arm is executed on the initial call to `cargo clippy`
154
155         if std::env::args().any(|a| a == "--help" || a == "-h") {
156             show_help();
157             return;
158         }
159
160         let manifest_path_arg = std::env::args().skip(2).find(|val| val.starts_with("--manifest-path="));
161
162         let mut metadata = cargo::metadata(manifest_path_arg.as_ref().map(AsRef::as_ref)).expect("could not obtain cargo metadata");
163
164         assert_eq!(metadata.version, 1);
165
166         let manifest_path = manifest_path_arg.map(|arg| PathBuf::from(Path::new(&arg["--manifest-path=".len()..])));
167
168         let current_dir = std::env::current_dir();
169
170         let package_index = metadata.packages.iter()
171             .position(|package| {
172                 let package_manifest_path = Path::new(&package.manifest_path);
173                 if let Some(ref manifest_path) = manifest_path {
174                     package_manifest_path == manifest_path
175                 } else {
176                     let current_dir = current_dir.as_ref().expect("could not read current directory");
177                     let package_manifest_directory = package_manifest_path.parent().expect("could not find parent directory of package manifest");
178                     package_manifest_directory == current_dir
179                 }
180             })
181             .expect("could not find matching package");
182         let package = metadata.packages.remove(package_index);
183         for target in package.targets {
184             let args = std::env::args().skip(2);
185             if let Some(first) = target.kind.get(0) {
186                 if target.kind.len() > 1 || first.ends_with("lib") {
187                     if let Err(code) = process(std::iter::once("--lib".to_owned()).chain(args), &dep_path) {
188                         std::process::exit(code);
189                     }
190                 } else if ["bin", "example", "test", "bench"].contains(&&**first) {
191                     if let Err(code) = process(vec![format!("--{}", first), target.name].into_iter().chain(args), &dep_path) {
192                         std::process::exit(code);
193                     }
194                 }
195             } else {
196                 panic!("badly formatted cargo metadata: target::kind is an empty array");
197             }
198         }
199     } else {
200         // this arm is executed when cargo-clippy runs `cargo rustc` with the `RUSTC` env var set to itself
201
202         let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
203         let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
204         let sys_root = if let (Some(home), Some(toolchain)) = (home, toolchain) {
205             format!("{}/toolchains/{}", home, toolchain)
206         } else {
207             option_env!("SYSROOT")
208                 .map(|s| s.to_owned())
209                 .or(Command::new("rustc")
210                     .arg("--print")
211                     .arg("sysroot")
212                     .output()
213                     .ok()
214                     .and_then(|out| String::from_utf8(out.stdout).ok())
215                     .map(|s| s.trim().to_owned()))
216                 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust")
217         };
218
219         // this conditional check for the --sysroot flag is there so users can call `cargo-clippy` directly
220         // without having to pass --sysroot or anything
221         let mut args: Vec<String> = if env::args().any(|s| s == "--sysroot") {
222             env::args().collect()
223         } else {
224             env::args().chain(Some("--sysroot".to_owned())).chain(Some(sys_root)).collect()
225         };
226
227         // this check ensures that dependencies are built but not linted and the final crate is
228         // linted but not built
229         let clippy_enabled = env::args().any(|s| s == "-Zno-trans");
230
231         if clippy_enabled {
232             args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
233         }
234
235         let mut ccc = ClippyCompilerCalls::new(clippy_enabled);
236         let (result, _) = rustc_driver::run_compiler(&args, &mut ccc, None, None);
237
238         if let Err(err_count) = result {
239             if err_count > 0 {
240                 std::process::exit(1);
241             }
242         }
243     }
244 }
245
246 fn process<P, I>(old_args: I, dep_path: P) -> Result<(), i32>
247     where P: AsRef<Path>,
248           I: Iterator<Item = String>
249 {
250
251     let mut args = vec!["rustc".to_owned()];
252
253     let mut found_dashes = false;
254     for arg in old_args {
255         found_dashes |= arg == "--";
256         args.push(arg);
257     }
258     if !found_dashes {
259         args.push("--".to_owned());
260     }
261     args.push("-L".to_owned());
262     args.push(dep_path.as_ref().to_string_lossy().into_owned());
263     args.push("-Zno-trans".to_owned());
264     args.push("--cfg".to_owned());
265     args.push(r#"feature="cargo-clippy""#.to_owned());
266
267     let path = std::env::current_exe().expect("current executable path invalid");
268     let exit_status = std::process::Command::new("cargo")
269         .args(&args)
270         .env("RUSTC", path)
271         .spawn().expect("could not run cargo")
272         .wait().expect("failed to wait for cargo?");
273
274     if exit_status.success() {
275         Ok(())
276     } else {
277         Err(exit_status.code().unwrap_or(-1))
278     }
279 }