]> git.lizzy.rs Git - rust.git/blob - src/main.rs
Merge remote-tracking branch 'origin/master' into 1537-drop_copy
[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                                                            .. } = registry;
93                     let sess = &state.session;
94                     let mut ls = sess.lint_store.borrow_mut();
95                     for pass in early_lint_passes {
96                         ls.register_early_pass(Some(sess), true, pass);
97                     }
98                     for pass in late_lint_passes {
99                         ls.register_late_pass(Some(sess), true, pass);
100                     }
101
102                     for (name, to) in lint_groups {
103                         ls.register_group(Some(sess), true, name, to);
104                     }
105
106                     sess.plugin_llvm_passes.borrow_mut().extend(llvm_passes);
107                     sess.plugin_attributes.borrow_mut().extend(attributes);
108                 }
109                 old(state);
110             });
111         }
112
113         control
114     }
115 }
116
117 use std::path::Path;
118
119 const CARGO_CLIPPY_HELP: &str = r#"Checks a package to catch common mistakes and improve your Rust code.
120
121 Usage:
122     cargo clippy [options] [--] [<opts>...]
123
124 Common options:
125     -h, --help               Print this message
126     --features               Features to compile for the package
127     -V, --version            Print version info and exit
128
129 Other options are the same as `cargo rustc`.
130
131 To allow or deny a lint from the command line you can use `cargo clippy --`
132 with:
133
134     -W --warn OPT       Set lint warnings
135     -A --allow OPT      Set lint allowed
136     -D --deny OPT       Set lint denied
137     -F --forbid OPT     Set lint forbidden
138
139 The feature `cargo-clippy` is automatically defined for convenience. You can use
140 it to allow or deny lints from the code, eg.:
141
142     #[cfg_attr(feature = "cargo-clippy", allow(needless_lifetimes))]
143 "#;
144
145 #[allow(print_stdout)]
146 fn show_help() {
147     println!("{}", CARGO_CLIPPY_HELP);
148 }
149
150 #[allow(print_stdout)]
151 fn show_version() {
152     println!("{}", env!("CARGO_PKG_VERSION"));
153 }
154
155 pub fn main() {
156     use std::env;
157
158     if env::var("CLIPPY_DOGFOOD").map(|_| true).unwrap_or(false) {
159         panic!("yummy");
160     }
161
162     // Check for version and help flags even when invoked as 'cargo-clippy'
163     if std::env::args().any(|a| a == "--help" || a == "-h") {
164         show_help();
165         return;
166     }
167     if std::env::args().any(|a| a == "--version" || a == "-V") {
168         show_version();
169         return;
170     }
171
172     let dep_path = env::current_dir().expect("current dir is not readable").join("target").join("debug").join("deps");
173
174     if let Some("clippy") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
175         // this arm is executed on the initial call to `cargo clippy`
176
177         let manifest_path_arg = std::env::args().skip(2).find(|val| val.starts_with("--manifest-path="));
178
179         let mut metadata = if let Ok(metadata) = cargo_metadata::metadata(manifest_path_arg.as_ref()
180             .map(AsRef::as_ref)) {
181             metadata
182         } else {
183             let _ = io::stderr().write_fmt(format_args!("error: Could not obtain cargo metadata.\n"));
184             process::exit(101);
185         };
186
187         let manifest_path = manifest_path_arg.map(|arg| PathBuf::from(Path::new(&arg["--manifest-path=".len()..])));
188
189         let current_dir = std::env::current_dir();
190
191         let package_index = metadata.packages
192             .iter()
193             .position(|package| {
194                 let package_manifest_path = Path::new(&package.manifest_path);
195                 if let Some(ref manifest_path) = manifest_path {
196                     package_manifest_path == manifest_path
197                 } else {
198                     let current_dir = current_dir.as_ref().expect("could not read current directory");
199                     let package_manifest_directory = package_manifest_path.parent()
200                         .expect("could not find parent directory of package manifest");
201                     package_manifest_directory == current_dir
202                 }
203             })
204             .expect("could not find matching package");
205         let package = metadata.packages.remove(package_index);
206         for target in package.targets {
207             let args = std::env::args().skip(2);
208             if let Some(first) = target.kind.get(0) {
209                 if target.kind.len() > 1 || first.ends_with("lib") {
210                     if let Err(code) = process(std::iter::once("--lib".to_owned()).chain(args), &dep_path) {
211                         std::process::exit(code);
212                     }
213                 } else if ["bin", "example", "test", "bench"].contains(&&**first) {
214                     if let Err(code) = process(vec![format!("--{}", first), target.name].into_iter().chain(args),
215                                                &dep_path) {
216                         std::process::exit(code);
217                     }
218                 }
219             } else {
220                 panic!("badly formatted cargo metadata: target::kind is an empty array");
221             }
222         }
223     } else {
224         // this arm is executed when cargo-clippy runs `cargo rustc` with the `RUSTC` env var set to itself
225
226         let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
227         let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
228         let sys_root = if let (Some(home), Some(toolchain)) = (home, toolchain) {
229             format!("{}/toolchains/{}", home, toolchain)
230         } else {
231             option_env!("SYSROOT")
232                 .map(|s| s.to_owned())
233                 .or_else(|| {
234                     Command::new("rustc")
235                         .arg("--print")
236                         .arg("sysroot")
237                         .output()
238                         .ok()
239                         .and_then(|out| String::from_utf8(out.stdout).ok())
240                         .map(|s| s.trim().to_owned())
241                 })
242                 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust")
243         };
244
245         rustc_driver::in_rustc_thread(|| {
246                 // this conditional check for the --sysroot flag is there so users can call `cargo-clippy` directly
247                 // without having to pass --sysroot or anything
248                 let mut args: Vec<String> = if env::args().any(|s| s == "--sysroot") {
249                     env::args().collect()
250                 } else {
251                     env::args().chain(Some("--sysroot".to_owned())).chain(Some(sys_root)).collect()
252                 };
253
254                 // this check ensures that dependencies are built but not linted and the final crate is
255                 // linted but not built
256                 let clippy_enabled = env::args().any(|s| s == "-Zno-trans");
257
258                 if clippy_enabled {
259                     args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
260                 }
261
262                 let mut ccc = ClippyCompilerCalls::new(clippy_enabled);
263                 let (result, _) = rustc_driver::run_compiler(&args, &mut ccc, None, None);
264                 if let Err(err_count) = result {
265                     if err_count > 0 {
266                         std::process::exit(1);
267                     }
268                 }
269             })
270             .expect("rustc_thread failed");
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 }