]> git.lizzy.rs Git - rust.git/blob - src/driver.rs
2579fb4ad4d58a6e19ebea28fe68a4fa87411403
[rust.git] / src / driver.rs
1 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
2 #![feature(result_map_or)]
3 #![feature(rustc_private)]
4
5 // FIXME: switch to something more ergonomic here, once available.
6 // (Currently there is no way to opt into sysroot crates without `extern crate`.)
7 #[allow(unused_extern_crates)]
8 extern crate rustc_driver;
9 #[allow(unused_extern_crates)]
10 extern crate rustc_interface;
11
12 use rustc_interface::interface;
13 use rustc_tools_util::*;
14
15 use std::path::{Path, PathBuf};
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 config(&mut self, config: &mut interface::Config) {
66         let previous = config.register_lints.take();
67         config.register_lints = Some(Box::new(move |sess, mut lint_store| {
68             // technically we're ~guaranteed that this is none but might as well call anything that
69             // is there already. Certainly it can't hurt.
70             if let Some(previous) = &previous {
71                 (previous)(sess, lint_store);
72             }
73
74             let conf = clippy_lints::read_conf(&[], &sess);
75             clippy_lints::register_plugins(&mut lint_store, &sess, &conf);
76             clippy_lints::register_pre_expansion_lints(&mut lint_store, &conf);
77             clippy_lints::register_renamed(&mut lint_store);
78         }));
79
80         // FIXME: #4825; This is required, because Clippy lints that are based on MIR have to be
81         // run on the unoptimized MIR. On the other hand this results in some false negatives. If
82         // MIR passes can be enabled / disabled separately, we should figure out, what passes to
83         // use for Clippy.
84         config.opts.debugging_opts.mir_opt_level = 0;
85     }
86 }
87
88 #[allow(clippy::find_map, clippy::filter_map)]
89 fn describe_lints() {
90     use lintlist::*;
91     use std::collections::HashSet;
92
93     println!(
94         "
95 Available lint options:
96     -W <foo>           Warn about <foo>
97     -A <foo>           Allow <foo>
98     -D <foo>           Deny <foo>
99     -F <foo>           Forbid <foo> (deny <foo> and all attempts to override)
100
101 "
102     );
103
104     let lint_level = |lint: &Lint| {
105         LINT_LEVELS
106             .iter()
107             .find(|level_mapping| level_mapping.0 == lint.group)
108             .map(|(_, level)| match level {
109                 Level::Allow => "allow",
110                 Level::Warn => "warn",
111                 Level::Deny => "deny",
112             })
113             .unwrap()
114     };
115
116     let mut lints: Vec<_> = ALL_LINTS.iter().collect();
117     // The sort doesn't case-fold but it's doubtful we care.
118     lints.sort_by_cached_key(|x: &&Lint| (lint_level(x), x.name));
119
120     let max_lint_name_len = lints
121         .iter()
122         .map(|lint| lint.name.len())
123         .map(|len| len + "clippy::".len())
124         .max()
125         .unwrap_or(0);
126
127     let padded = |x: &str| {
128         let mut s = " ".repeat(max_lint_name_len - x.chars().count());
129         s.push_str(x);
130         s
131     };
132
133     let scoped = |x: &str| format!("clippy::{}", x);
134
135     let lint_groups: HashSet<_> = lints.iter().map(|lint| lint.group).collect();
136
137     println!("Lint checks provided by clippy:\n");
138     println!("    {}  {:7.7}  meaning", padded("name"), "default");
139     println!("    {}  {:7.7}  -------", padded("----"), "-------");
140
141     let print_lints = |lints: &[&Lint]| {
142         for lint in lints {
143             let name = lint.name.replace("_", "-");
144             println!(
145                 "    {}  {:7.7}  {}",
146                 padded(&scoped(&name)),
147                 lint_level(lint),
148                 lint.desc
149             );
150         }
151         println!("\n");
152     };
153
154     print_lints(&lints);
155
156     let max_group_name_len = std::cmp::max(
157         "clippy::all".len(),
158         lint_groups
159             .iter()
160             .map(|group| group.len())
161             .map(|len| len + "clippy::".len())
162             .max()
163             .unwrap_or(0),
164     );
165
166     let padded_group = |x: &str| {
167         let mut s = " ".repeat(max_group_name_len - x.chars().count());
168         s.push_str(x);
169         s
170     };
171
172     println!("Lint groups provided by clippy:\n");
173     println!("    {}  sub-lints", padded_group("name"));
174     println!("    {}  ---------", padded_group("----"));
175     println!("    {}  the set of all clippy lints", padded_group("clippy::all"));
176
177     let print_lint_groups = || {
178         for group in lint_groups {
179             let name = group.to_lowercase().replace("_", "-");
180             let desc = lints
181                 .iter()
182                 .filter(|&lint| lint.group == group)
183                 .map(|lint| lint.name)
184                 .map(|name| name.replace("_", "-"))
185                 .collect::<Vec<String>>()
186                 .join(", ");
187             println!("    {}  {}", padded_group(&scoped(&name)), desc);
188         }
189         println!("\n");
190     };
191
192     print_lint_groups();
193 }
194
195 fn display_help() {
196     println!(
197         "\
198 Checks a package to catch common mistakes and improve your Rust code.
199
200 Usage:
201     cargo clippy [options] [--] [<opts>...]
202
203 Common options:
204     -h, --help               Print this message
205     -V, --version            Print version info and exit
206
207 Other options are the same as `cargo check`.
208
209 To allow or deny a lint from the command line you can use `cargo clippy --`
210 with:
211
212     -W --warn OPT       Set lint warnings
213     -A --allow OPT      Set lint allowed
214     -D --deny OPT       Set lint denied
215     -F --forbid OPT     Set lint forbidden
216
217 You can use tool lints to allow or deny lints from your code, eg.:
218
219     #[allow(clippy::needless_lifetimes)]
220 "
221     );
222 }
223
224 pub fn main() {
225     rustc_driver::init_rustc_env_logger();
226     rustc_driver::install_ice_hook();
227     exit(
228         rustc_driver::catch_fatal_errors(move || {
229             use std::env;
230
231             if std::env::args().any(|a| a == "--version" || a == "-V") {
232                 let version_info = rustc_tools_util::get_version_info!();
233                 println!("{}", version_info);
234                 exit(0);
235             }
236
237             let mut orig_args: Vec<String> = env::args().collect();
238
239             // Get the sysroot, looking from most specific to this invocation to the least:
240             // - command line
241             // - runtime environment
242             //    - SYSROOT
243             //    - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
244             // - sysroot from rustc in the path
245             // - compile-time environment
246             let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
247             let have_sys_root_arg = sys_root_arg.is_some();
248             let sys_root = sys_root_arg
249                 .map(PathBuf::from)
250                 .or_else(|| std::env::var("SYSROOT").ok().map(PathBuf::from))
251                 .or_else(|| {
252                     let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
253                     let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
254                     home.and_then(|home| {
255                         toolchain.map(|toolchain| {
256                             let mut path = PathBuf::from(home);
257                             path.push("toolchains");
258                             path.push(toolchain);
259                             path
260                         })
261                     })
262                 })
263                 .or_else(|| {
264                     Command::new("rustc")
265                         .arg("--print")
266                         .arg("sysroot")
267                         .output()
268                         .ok()
269                         .and_then(|out| String::from_utf8(out.stdout).ok())
270                         .map(|s| PathBuf::from(s.trim()))
271                 })
272                 .or_else(|| option_env!("SYSROOT").map(PathBuf::from))
273                 .map(|pb| pb.to_string_lossy().to_string())
274                 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
275
276             // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
277             // We're invoking the compiler programmatically, so we ignore this/
278             let wrapper_mode = orig_args.get(1).map(Path::new).and_then(Path::file_stem) == Some("rustc".as_ref());
279
280             if wrapper_mode {
281                 // we still want to be able to invoke it normally though
282                 orig_args.remove(1);
283             }
284
285             if !wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) {
286                 display_help();
287                 exit(0);
288             }
289
290             let should_describe_lints = || {
291                 let args: Vec<_> = std::env::args().collect();
292                 args.windows(2).any(|args| {
293                     args[1] == "help"
294                         && match args[0].as_str() {
295                             "-W" | "-A" | "-D" | "-F" => true,
296                             _ => false,
297                         }
298                 })
299             };
300
301             if !wrapper_mode && should_describe_lints() {
302                 describe_lints();
303                 exit(0);
304             }
305
306             // this conditional check for the --sysroot flag is there so users can call
307             // `clippy_driver` directly
308             // without having to pass --sysroot or anything
309             let mut args: Vec<String> = if have_sys_root_arg {
310                 orig_args.clone()
311             } else {
312                 orig_args
313                     .clone()
314                     .into_iter()
315                     .chain(Some("--sysroot".to_owned()))
316                     .chain(Some(sys_root))
317                     .collect()
318             };
319
320             // this check ensures that dependencies are built but not linted and the final
321             // crate is
322             // linted but not built
323             let clippy_enabled = env::var("CLIPPY_TESTS").map_or(false, |val| val == "true")
324                 || arg_value(&orig_args, "--emit", |val| val.split(',').any(|e| e == "metadata")).is_some();
325
326             if clippy_enabled {
327                 args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
328                 if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
329                     args.extend(extra_args.split("__CLIPPY_HACKERY__").filter_map(|s| {
330                         if s.is_empty() {
331                             None
332                         } else {
333                             Some(s.to_string())
334                         }
335                     }));
336                 }
337             }
338
339             let mut clippy = ClippyCallbacks;
340             let mut default = rustc_driver::DefaultCallbacks;
341             let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
342                 if clippy_enabled { &mut clippy } else { &mut default };
343             let args = args;
344             rustc_driver::run_compiler(&args, callbacks, None, None)
345         })
346         .and_then(|result| result)
347         .is_err() as i32,
348     )
349 }