]> git.lizzy.rs Git - rust.git/blob - src/driver.rs
Auto merge of #4175 - yaahallo:master, r=oli-obk
[rust.git] / src / driver.rs
1 #![feature(rustc_private)]
2
3 // FIXME: switch to something more ergonomic here, once available.
4 // (Currently there is no way to opt into sysroot crates without `extern crate`.)
5 #[allow(unused_extern_crates)]
6 extern crate rustc_driver;
7 #[allow(unused_extern_crates)]
8 extern crate rustc_interface;
9 #[allow(unused_extern_crates)]
10 extern crate rustc_plugin;
11
12 use rustc_interface::interface;
13 use rustc_tools_util::*;
14
15 use std::path::Path;
16 use std::process::{exit, Command};
17
18 mod lintlist;
19
20 /// If a command-line option matches `find_arg`, then apply the predicate `pred` on its value. If
21 /// true, then return it. The parameter is assumed to be either `--arg=value` or `--arg value`.
22 fn arg_value<'a>(
23     args: impl IntoIterator<Item = &'a String>,
24     find_arg: &str,
25     pred: impl Fn(&str) -> bool,
26 ) -> Option<&'a str> {
27     let mut args = args.into_iter().map(String::as_str);
28
29     while let Some(arg) = args.next() {
30         let arg: Vec<_> = arg.splitn(2, '=').collect();
31         if arg.get(0) != Some(&find_arg) {
32             continue;
33         }
34
35         let value = arg.get(1).cloned().or_else(|| args.next());
36         if value.as_ref().map_or(false, |p| pred(p)) {
37             return value;
38         }
39     }
40     None
41 }
42
43 #[test]
44 fn test_arg_value() {
45     let args: Vec<_> = ["--bar=bar", "--foobar", "123", "--foo"]
46         .iter()
47         .map(std::string::ToString::to_string)
48         .collect();
49
50     assert_eq!(arg_value(None, "--foobar", |_| true), None);
51     assert_eq!(arg_value(&args, "--bar", |_| false), None);
52     assert_eq!(arg_value(&args, "--bar", |_| true), Some("bar"));
53     assert_eq!(arg_value(&args, "--bar", |p| p == "bar"), Some("bar"));
54     assert_eq!(arg_value(&args, "--bar", |p| p == "foo"), None);
55     assert_eq!(arg_value(&args, "--foobar", |p| p == "foo"), None);
56     assert_eq!(arg_value(&args, "--foobar", |p| p == "123"), Some("123"));
57     assert_eq!(arg_value(&args, "--foo", |_| true), None);
58 }
59
60 #[allow(clippy::too_many_lines)]
61
62 struct ClippyCallbacks;
63
64 impl rustc_driver::Callbacks for ClippyCallbacks {
65     fn after_parsing(&mut self, compiler: &interface::Compiler) -> bool {
66         let sess = compiler.session();
67         let mut registry = rustc_plugin::registry::Registry::new(
68             sess,
69             compiler
70                 .parse()
71                 .expect(
72                     "at this compilation stage \
73                      the crate must be parsed",
74                 )
75                 .peek()
76                 .span,
77         );
78         registry.args_hidden = Some(Vec::new());
79
80         let conf = clippy_lints::read_conf(&registry);
81         clippy_lints::register_plugins(&mut registry, &conf);
82
83         let rustc_plugin::registry::Registry {
84             early_lint_passes,
85             late_lint_passes,
86             lint_groups,
87             llvm_passes,
88             attributes,
89             ..
90         } = registry;
91         let mut ls = sess.lint_store.borrow_mut();
92         for pass in early_lint_passes {
93             ls.register_early_pass(Some(sess), true, false, pass);
94         }
95         for pass in late_lint_passes {
96             ls.register_late_pass(Some(sess), true, false, false, pass);
97         }
98
99         for (name, (to, deprecated_name)) in lint_groups {
100             ls.register_group(Some(sess), true, name, deprecated_name, to);
101         }
102         clippy_lints::register_pre_expansion_lints(sess, &mut ls, &conf);
103         clippy_lints::register_renamed(&mut ls);
104
105         sess.plugin_llvm_passes.borrow_mut().extend(llvm_passes);
106         sess.plugin_attributes.borrow_mut().extend(attributes);
107
108         // Continue execution
109         true
110     }
111 }
112
113 #[allow(clippy::find_map, clippy::filter_map)]
114 fn describe_lints() {
115     use lintlist::*;
116     use std::collections::HashSet;
117
118     println!(
119         "
120 Available lint options:
121     -W <foo>           Warn about <foo>
122     -A <foo>           Allow <foo>
123     -D <foo>           Deny <foo>
124     -F <foo>           Forbid <foo> (deny <foo> and all attempts to override)
125
126 "
127     );
128
129     let lint_level = |lint: &Lint| {
130         LINT_LEVELS
131             .iter()
132             .find(|level_mapping| level_mapping.0 == lint.group)
133             .map(|(_, level)| match level {
134                 Level::Allow => "allow",
135                 Level::Warn => "warn",
136                 Level::Deny => "deny",
137             })
138             .unwrap()
139     };
140
141     let mut lints: Vec<_> = ALL_LINTS.iter().collect();
142     // The sort doesn't case-fold but it's doubtful we care.
143     lints.sort_by_cached_key(|x: &&Lint| (lint_level(x), x.name));
144
145     let max_lint_name_len = lints
146         .iter()
147         .map(|lint| lint.name.len())
148         .map(|len| len + "clippy::".len())
149         .max()
150         .unwrap_or(0);
151
152     let padded = |x: &str| {
153         let mut s = " ".repeat(max_lint_name_len - x.chars().count());
154         s.push_str(x);
155         s
156     };
157
158     let scoped = |x: &str| format!("clippy::{}", x);
159
160     let lint_groups: HashSet<_> = lints.iter().map(|lint| lint.group).collect();
161
162     println!("Lint checks provided by clippy:\n");
163     println!("    {}  {:7.7}  meaning", padded("name"), "default");
164     println!("    {}  {:7.7}  -------", padded("----"), "-------");
165
166     let print_lints = |lints: &[&Lint]| {
167         for lint in lints {
168             let name = lint.name.replace("_", "-");
169             println!(
170                 "    {}  {:7.7}  {}",
171                 padded(&scoped(&name)),
172                 lint_level(lint),
173                 lint.desc
174             );
175         }
176         println!("\n");
177     };
178
179     print_lints(&lints);
180
181     let max_group_name_len = std::cmp::max(
182         "clippy::all".len(),
183         lint_groups
184             .iter()
185             .map(|group| group.len())
186             .map(|len| len + "clippy::".len())
187             .max()
188             .unwrap_or(0),
189     );
190
191     let padded_group = |x: &str| {
192         let mut s = " ".repeat(max_group_name_len - x.chars().count());
193         s.push_str(x);
194         s
195     };
196
197     println!("Lint groups provided by clippy:\n");
198     println!("    {}  sub-lints", padded_group("name"));
199     println!("    {}  ---------", padded_group("----"));
200     println!("    {}  the set of all clippy lints", padded_group("clippy::all"));
201
202     let print_lint_groups = || {
203         for group in lint_groups {
204             let name = group.to_lowercase().replace("_", "-");
205             let desc = lints
206                 .iter()
207                 .filter(|&lint| lint.group == group)
208                 .map(|lint| lint.name)
209                 .map(|name| name.replace("_", "-"))
210                 .collect::<Vec<String>>()
211                 .join(", ");
212             println!("    {}  {}", padded_group(&scoped(&name)), desc);
213         }
214         println!("\n");
215     };
216
217     print_lint_groups();
218 }
219
220 fn display_help() {
221     println!(
222         "\
223 Checks a package to catch common mistakes and improve your Rust code.
224
225 Usage:
226     cargo clippy [options] [--] [<opts>...]
227
228 Common options:
229     -h, --help               Print this message
230     -V, --version            Print version info and exit
231
232 Other options are the same as `cargo check`.
233
234 To allow or deny a lint from the command line you can use `cargo clippy --`
235 with:
236
237     -W --warn OPT       Set lint warnings
238     -A --allow OPT      Set lint allowed
239     -D --deny OPT       Set lint denied
240     -F --forbid OPT     Set lint forbidden
241
242 You can use tool lints to allow or deny lints from your code, eg.:
243
244     #[allow(clippy::needless_lifetimes)]
245 "
246     );
247 }
248
249 pub fn main() {
250     rustc_driver::init_rustc_env_logger();
251     exit(
252         rustc_driver::report_ices_to_stderr_if_any(move || {
253             use std::env;
254
255             if std::env::args().any(|a| a == "--version" || a == "-V") {
256                 let version_info = rustc_tools_util::get_version_info!();
257                 println!("{}", version_info);
258                 exit(0);
259             }
260
261             let mut orig_args: Vec<String> = env::args().collect();
262
263             // Get the sysroot, looking from most specific to this invocation to the least:
264             // - command line
265             // - runtime environment
266             //    - SYSROOT
267             //    - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
268             // - sysroot from rustc in the path
269             // - compile-time environment
270             let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
271             let have_sys_root_arg = sys_root_arg.is_some();
272             let sys_root = sys_root_arg
273                 .map(std::string::ToString::to_string)
274                 .or_else(|| std::env::var("SYSROOT").ok())
275                 .or_else(|| {
276                     let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
277                     let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
278                     home.and_then(|home| toolchain.map(|toolchain| format!("{}/toolchains/{}", home, toolchain)))
279                 })
280                 .or_else(|| {
281                     Command::new("rustc")
282                         .arg("--print")
283                         .arg("sysroot")
284                         .output()
285                         .ok()
286                         .and_then(|out| String::from_utf8(out.stdout).ok())
287                         .map(|s| s.trim().to_owned())
288                 })
289                 .or_else(|| option_env!("SYSROOT").map(String::from))
290                 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
291
292             // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
293             // We're invoking the compiler programmatically, so we ignore this/
294             let wrapper_mode = Path::new(&orig_args[1]).file_stem() == Some("rustc".as_ref());
295
296             if wrapper_mode {
297                 // we still want to be able to invoke it normally though
298                 orig_args.remove(1);
299             }
300
301             if !wrapper_mode && std::env::args().any(|a| a == "--help" || a == "-h") {
302                 display_help();
303                 exit(0);
304             }
305
306             let should_describe_lints = || {
307                 let args: Vec<_> = std::env::args().collect();
308                 args.windows(2).any(|args| {
309                     args[1] == "help"
310                         && match args[0].as_str() {
311                             "-W" | "-A" | "-D" | "-F" => true,
312                             _ => false,
313                         }
314                 })
315             };
316
317             if !wrapper_mode && should_describe_lints() {
318                 describe_lints();
319                 exit(0);
320             }
321
322             // this conditional check for the --sysroot flag is there so users can call
323             // `clippy_driver` directly
324             // without having to pass --sysroot or anything
325             let mut args: Vec<String> = if have_sys_root_arg {
326                 orig_args.clone()
327             } else {
328                 orig_args
329                     .clone()
330                     .into_iter()
331                     .chain(Some("--sysroot".to_owned()))
332                     .chain(Some(sys_root))
333                     .collect()
334             };
335
336             // this check ensures that dependencies are built but not linted and the final
337             // crate is
338             // linted but not built
339             let clippy_enabled = env::var("CLIPPY_TESTS").ok().map_or(false, |val| val == "true")
340                 || arg_value(&orig_args, "--emit", |val| val.split(',').any(|e| e == "metadata")).is_some();
341
342             if clippy_enabled {
343                 args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
344                 if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
345                     args.extend(extra_args.split("__CLIPPY_HACKERY__").filter_map(|s| {
346                         if s.is_empty() {
347                             None
348                         } else {
349                             Some(s.to_string())
350                         }
351                     }));
352                 }
353             }
354
355             let mut clippy = ClippyCallbacks;
356             let mut default = rustc_driver::DefaultCallbacks;
357             let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
358                 if clippy_enabled { &mut clippy } else { &mut default };
359             let args = args;
360             rustc_driver::run_compiler(&args, callbacks, None, None)
361         })
362         .and_then(|result| result)
363         .is_err() as i32,
364     )
365 }