]> git.proxmox.com Git - rustc.git/blob - src/tools/clippy/src/driver.rs
New upstream version 1.23.0+dfsg1
[rustc.git] / src / tools / clippy / src / driver.rs
1 // error-pattern:yummy
2 #![feature(box_syntax)]
3 #![feature(rustc_private)]
4 #![allow(unknown_lints, missing_docs_in_private_items)]
5
6 extern crate clippy_lints;
7 extern crate getopts;
8 extern crate rustc;
9 extern crate rustc_driver;
10 extern crate rustc_errors;
11 extern crate rustc_plugin;
12 extern crate syntax;
13
14 use rustc_driver::{driver, Compilation, CompilerCalls, RustcDefaultCalls};
15 use rustc::session::{config, CompileIncomplete, Session};
16 use rustc::session::config::{ErrorOutputType, Input};
17 use std::path::PathBuf;
18 use std::process::Command;
19 use syntax::ast;
20
21 struct ClippyCompilerCalls {
22 default: RustcDefaultCalls,
23 run_lints: bool,
24 }
25
26 impl ClippyCompilerCalls {
27 fn new(run_lints: bool) -> Self {
28 Self {
29 default: RustcDefaultCalls,
30 run_lints: run_lints,
31 }
32 }
33 }
34
35 impl<'a> CompilerCalls<'a> for ClippyCompilerCalls {
36 fn early_callback(
37 &mut self,
38 matches: &getopts::Matches,
39 sopts: &config::Options,
40 cfg: &ast::CrateConfig,
41 descriptions: &rustc_errors::registry::Registry,
42 output: ErrorOutputType,
43 ) -> Compilation {
44 self.default
45 .early_callback(matches, sopts, cfg, descriptions, output)
46 }
47 fn no_input(
48 &mut self,
49 matches: &getopts::Matches,
50 sopts: &config::Options,
51 cfg: &ast::CrateConfig,
52 odir: &Option<PathBuf>,
53 ofile: &Option<PathBuf>,
54 descriptions: &rustc_errors::registry::Registry,
55 ) -> Option<(Input, Option<PathBuf>)> {
56 self.default
57 .no_input(matches, sopts, cfg, odir, ofile, descriptions)
58 }
59 fn late_callback(
60 &mut self,
61 matches: &getopts::Matches,
62 sess: &Session,
63 crate_stores: &rustc::middle::cstore::CrateStore,
64 input: &Input,
65 odir: &Option<PathBuf>,
66 ofile: &Option<PathBuf>,
67 ) -> Compilation {
68 self.default
69 .late_callback(matches, sess, crate_stores, 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(
79 state.session,
80 state
81 .krate
82 .as_ref()
83 .expect(
84 "at this compilation stage \
85 the crate must be parsed",
86 )
87 .span,
88 );
89 registry.args_hidden = Some(Vec::new());
90 clippy_lints::register_plugins(&mut registry);
91
92 let rustc_plugin::registry::Registry {
93 early_lint_passes,
94 late_lint_passes,
95 lint_groups,
96 llvm_passes,
97 attributes,
98 ..
99 } = registry;
100 let sess = &state.session;
101 let mut ls = sess.lint_store.borrow_mut();
102 for pass in early_lint_passes {
103 ls.register_early_pass(Some(sess), true, pass);
104 }
105 for pass in late_lint_passes {
106 ls.register_late_pass(Some(sess), true, pass);
107 }
108
109 for (name, to) in lint_groups {
110 ls.register_group(Some(sess), true, name, to);
111 }
112
113 sess.plugin_llvm_passes.borrow_mut().extend(llvm_passes);
114 sess.plugin_attributes.borrow_mut().extend(attributes);
115 }
116 old(state);
117 });
118 }
119
120 control
121 }
122 }
123
124 #[allow(print_stdout)]
125 fn show_version() {
126 println!("{}", env!("CARGO_PKG_VERSION"));
127 }
128
129 pub fn main() {
130 use std::env;
131
132 if std::env::args().any(|a| a == "--version" || a == "-V") {
133 show_version();
134 return;
135 }
136
137 let sys_root = option_env!("SYSROOT")
138 .map(String::from)
139 .or_else(|| std::env::var("SYSROOT").ok())
140 .or_else(|| {
141 let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
142 let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
143 home.and_then(|home| toolchain.map(|toolchain| format!("{}/toolchains/{}", home, toolchain)))
144 })
145 .or_else(|| {
146 Command::new("rustc")
147 .arg("--print")
148 .arg("sysroot")
149 .output()
150 .ok()
151 .and_then(|out| String::from_utf8(out.stdout).ok())
152 .map(|s| s.trim().to_owned())
153 })
154 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
155
156 rustc_driver::in_rustc_thread(|| {
157 // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
158 // We're invoking the compiler programmatically, so we ignore this/
159 let mut orig_args: Vec<String> = env::args().collect();
160 if orig_args.len() <= 1 {
161 std::process::exit(1);
162 }
163 if orig_args[1] == "rustc" {
164 // we still want to be able to invoke it normally though
165 orig_args.remove(1);
166 }
167 // this conditional check for the --sysroot flag is there so users can call
168 // `clippy_driver` directly
169 // without having to pass --sysroot or anything
170 let mut args: Vec<String> = if orig_args.iter().any(|s| s == "--sysroot") {
171 orig_args.clone()
172 } else {
173 orig_args
174 .clone()
175 .into_iter()
176 .chain(Some("--sysroot".to_owned()))
177 .chain(Some(sys_root))
178 .collect()
179 };
180
181 // this check ensures that dependencies are built but not linted and the final
182 // crate is
183 // linted but not built
184 let clippy_enabled = env::var("CLIPPY_TESTS")
185 .ok()
186 .map_or(false, |val| val == "true")
187 || orig_args.iter().any(|s| s == "--emit=metadata");
188
189 if clippy_enabled {
190 args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
191 }
192
193 let mut ccc = ClippyCompilerCalls::new(clippy_enabled);
194 let (result, _) = rustc_driver::run_compiler(&args, &mut ccc, None, None);
195 if let Err(CompileIncomplete::Errored(_)) = result {
196 std::process::exit(1);
197 }
198 }).expect("rustc_thread failed");
199 }