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