]> git.lizzy.rs Git - rust.git/blob - src/main.rs
Revert "Revert "Automatically defines the `clippy` feature""
[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                      cfg: &ast::CrateConfig,
63                      input: &Input,
64                      odir: &Option<PathBuf>,
65                      ofile: &Option<PathBuf>)
66                      -> Compilation {
67         self.default.late_callback(matches, sess, cfg, 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
123 Other options are the same as `cargo rustc`.
124
125 To allow or deny a lint from the command line you can use `cargo clippy --` with
126 one of:
127
128     -W --warn OPT       Set lint warnings
129     -A --allow OPT      Set lint allowed
130     -D --deny OPT       Set lint denied
131     -F --forbid OPT     Set lint forbidden
132
133 The feature `cargo-clippy` is automatically defined for convinence. You can use
134 it to allow or deny lints, eg.:
135
136     #[cfg_attr(feature = "cargo-clippy", allow(needless_lifetimes))]
137 "#;
138
139 pub fn main() {
140     use std::env;
141
142     if env::var("CLIPPY_DOGFOOD").map(|_| true).unwrap_or(false) {
143         panic!("yummy");
144     }
145
146     let dep_path = env::current_dir().expect("current dir is not readable").join("target").join("debug").join("deps");
147
148     let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
149     let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
150     let sys_root = if let (Some(home), Some(toolchain)) = (home, toolchain) {
151         format!("{}/toolchains/{}", home, toolchain)
152     } else {
153         option_env!("SYSROOT")
154             .map(|s| s.to_owned())
155             .or(Command::new("rustc")
156                 .arg("--print")
157                 .arg("sysroot")
158                 .output()
159                 .ok()
160                 .and_then(|out| String::from_utf8(out.stdout).ok())
161                 .map(|s| s.trim().to_owned()))
162             .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust")
163     };
164
165     if let Some("clippy") = std::env::args().nth(1).as_ref().map(AsRef::as_ref) {
166         // this arm is executed on the initial call to `cargo clippy`
167
168         match std::env::args().nth(2).as_ref().map(AsRef::as_ref) {
169             Some("--help") | Some("-h") => {
170                 println!("{}", CARGO_CLIPPY_HELP);
171                 return;
172             }
173             _ => (),
174         }
175
176         let manifest_path_arg = std::env::args().skip(2).find(|val| val.starts_with("--manifest-path="));
177
178         let mut metadata = cargo::metadata(manifest_path_arg.as_ref().map(AsRef::as_ref)).expect("could not obtain cargo metadata");
179
180         assert_eq!(metadata.version, 1);
181
182         let manifest_path = manifest_path_arg.map(|arg| PathBuf::from(Path::new(&arg["--manifest-path=".len()..])));
183
184         let current_dir = std::env::current_dir();
185
186         let package_index = metadata.packages.iter()
187             .position(|package| {
188                 let package_manifest_path = Path::new(&package.manifest_path);
189                 if let Some(ref manifest_path) = manifest_path {
190                     package_manifest_path == manifest_path
191                 } else {
192                     let current_dir = current_dir.as_ref().expect("could not read current directory");
193                     let package_manifest_directory = package_manifest_path.parent().expect("could not find parent directory of package manifest");
194                     package_manifest_directory == current_dir
195                 }
196             })
197             .expect("could not find matching package");
198         let package = metadata.packages.remove(package_index);
199         for target in package.targets {
200             let args = std::env::args().skip(2);
201             if let Some(first) = target.kind.get(0) {
202                 if target.kind.len() > 1 || first.ends_with("lib") {
203                     if let Err(code) = process(std::iter::once("--lib".to_owned()).chain(args), &dep_path, &sys_root) {
204                         std::process::exit(code);
205                     }
206                 } else if ["bin", "example", "test", "bench"].contains(&&**first) {
207                     if let Err(code) = process(vec![format!("--{}", first), target.name].into_iter().chain(args), &dep_path, &sys_root) {
208                         std::process::exit(code);
209                     }
210                 }
211             } else {
212                 panic!("badly formatted cargo metadata: target::kind is an empty array");
213             }
214         }
215     } else {
216         // this arm is executed when cargo-clippy runs `cargo rustc` with the `RUSTC` env var set to itself
217
218         // this conditional check for the --sysroot flag is there so users can call `cargo-clippy` directly
219         // without having to pass --sysroot or anything
220         let mut args: Vec<String> = if env::args().any(|s| s == "--sysroot") {
221             env::args().collect()
222         } else {
223             env::args().chain(Some("--sysroot".to_owned())).chain(Some(sys_root)).collect()
224         };
225
226         // this check ensures that dependencies are built but not linted and the final crate is
227         // linted but not built
228         args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
229
230         let mut ccc = ClippyCompilerCalls::new(env::args().any(|s| s == "-Zno-trans"));
231         let (result, _) = rustc_driver::run_compiler(&args, &mut ccc, None, None);
232
233         if let Err(err_count) = result {
234             if err_count > 0 {
235                 std::process::exit(1);
236             }
237         }
238     }
239 }
240
241 fn process<P, I>(old_args: I, dep_path: P, sysroot: &str) -> Result<(), i32>
242     where P: AsRef<Path>,
243           I: Iterator<Item = String>
244 {
245
246     let mut args = vec!["rustc".to_owned()];
247
248     let mut found_dashes = false;
249     for arg in old_args {
250         found_dashes |= arg == "--";
251         args.push(arg);
252     }
253     if !found_dashes {
254         args.push("--".to_owned());
255     }
256     args.push("-L".to_owned());
257     args.push(dep_path.as_ref().to_string_lossy().into_owned());
258     args.push(String::from("--sysroot"));
259     args.push(sysroot.to_owned());
260     args.push("-Zno-trans".to_owned());
261     args.push("--cfg".to_owned());
262     args.push(r#"feature="cargo-clippy""#.to_owned());
263
264     let path = std::env::current_exe().expect("current executable path invalid");
265     let exit_status = std::process::Command::new("cargo")
266         .args(&args)
267         .env("RUSTC", path)
268         .spawn().expect("could not run cargo")
269         .wait().expect("failed to wait for cargo?");
270
271     if exit_status.success() {
272         Ok(())
273     } else {
274         Err(exit_status.code().unwrap_or(-1))
275     }
276 }