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