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