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