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