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