]> git.lizzy.rs Git - rust.git/blob - src/driver.rs
Auto merge of #3820 - mikerite:remove-feature-try-from, r=Manishearth
[rust.git] / src / driver.rs
1 // error-pattern:yummy
2 #![feature(box_syntax)]
3 #![feature(rustc_private)]
4 #![allow(clippy::missing_docs_in_private_items)]
5
6 // FIXME: switch to something more ergonomic here, once available.
7 // (currently there is no way to opt into sysroot crates w/o `extern crate`)
8 #[allow(unused_extern_crates)]
9 extern crate rustc_driver;
10 #[allow(unused_extern_crates)]
11 extern crate rustc_plugin;
12 use self::rustc_driver::{driver::CompileController, Compilation};
13
14 use std::convert::TryInto;
15 use std::path::Path;
16 use std::process::{exit, Command};
17
18 fn show_version() {
19     println!(env!("CARGO_PKG_VERSION"));
20 }
21
22 /// If a command-line option matches `find_arg`, then apply the predicate `pred` on its value. If
23 /// true, then return it. The parameter is assumed to be either `--arg=value` or `--arg value`.
24 fn arg_value<'a>(
25     args: impl IntoIterator<Item = &'a String>,
26     find_arg: &str,
27     pred: impl Fn(&str) -> bool,
28 ) -> Option<&'a str> {
29     let mut args = args.into_iter().map(String::as_str);
30
31     while let Some(arg) = args.next() {
32         let arg: Vec<_> = arg.splitn(2, '=').collect();
33         if arg.get(0) != Some(&find_arg) {
34             continue;
35         }
36
37         let value = arg.get(1).cloned().or_else(|| args.next());
38         if value.as_ref().map_or(false, |p| pred(p)) {
39             return value;
40         }
41     }
42     None
43 }
44
45 #[test]
46 fn test_arg_value() {
47     let args: Vec<_> = ["--bar=bar", "--foobar", "123", "--foo"]
48         .iter()
49         .map(std::string::ToString::to_string)
50         .collect();
51
52     assert_eq!(arg_value(None, "--foobar", |_| true), None);
53     assert_eq!(arg_value(&args, "--bar", |_| false), None);
54     assert_eq!(arg_value(&args, "--bar", |_| true), Some("bar"));
55     assert_eq!(arg_value(&args, "--bar", |p| p == "bar"), Some("bar"));
56     assert_eq!(arg_value(&args, "--bar", |p| p == "foo"), None);
57     assert_eq!(arg_value(&args, "--foobar", |p| p == "foo"), None);
58     assert_eq!(arg_value(&args, "--foobar", |p| p == "123"), Some("123"));
59     assert_eq!(arg_value(&args, "--foo", |_| true), None);
60 }
61
62 #[allow(clippy::too_many_lines)]
63 pub fn main() {
64     rustc_driver::init_rustc_env_logger();
65     exit(
66         rustc_driver::run(move || {
67             use std::env;
68
69             if std::env::args().any(|a| a == "--version" || a == "-V") {
70                 show_version();
71                 exit(0);
72             }
73
74             let mut orig_args: Vec<String> = env::args().collect();
75
76             // Get the sysroot, looking from most specific to this invocation to the least:
77             // - command line
78             // - runtime environment
79             //    - SYSROOT
80             //    - RUSTUP_HOME, MULTIRUST_HOME, RUSTUP_TOOLCHAIN, MULTIRUST_TOOLCHAIN
81             // - sysroot from rustc in the path
82             // - compile-time environment
83             let sys_root_arg = arg_value(&orig_args, "--sysroot", |_| true);
84             let have_sys_root_arg = sys_root_arg.is_some();
85             let sys_root = sys_root_arg
86                 .map(std::string::ToString::to_string)
87                 .or_else(|| std::env::var("SYSROOT").ok())
88                 .or_else(|| {
89                     let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME"));
90                     let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN"));
91                     home.and_then(|home| toolchain.map(|toolchain| format!("{}/toolchains/{}", home, toolchain)))
92                 })
93                 .or_else(|| {
94                     Command::new("rustc")
95                         .arg("--print")
96                         .arg("sysroot")
97                         .output()
98                         .ok()
99                         .and_then(|out| String::from_utf8(out.stdout).ok())
100                         .map(|s| s.trim().to_owned())
101                 })
102                 .or_else(|| option_env!("SYSROOT").map(String::from))
103                 .expect("need to specify SYSROOT env var during clippy compilation, or use rustup or multirust");
104
105             // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument.
106             // We're invoking the compiler programmatically, so we ignore this/
107             if orig_args.len() <= 1 {
108                 std::process::exit(1);
109             }
110             if Path::new(&orig_args[1]).file_stem() == Some("rustc".as_ref()) {
111                 // we still want to be able to invoke it normally though
112                 orig_args.remove(1);
113             }
114             // this conditional check for the --sysroot flag is there so users can call
115             // `clippy_driver` directly
116             // without having to pass --sysroot or anything
117             let mut args: Vec<String> = if have_sys_root_arg {
118                 orig_args.clone()
119             } else {
120                 orig_args
121                     .clone()
122                     .into_iter()
123                     .chain(Some("--sysroot".to_owned()))
124                     .chain(Some(sys_root))
125                     .collect()
126             };
127
128             // this check ensures that dependencies are built but not linted and the final
129             // crate is
130             // linted but not built
131             let clippy_enabled = env::var("CLIPPY_TESTS").ok().map_or(false, |val| val == "true")
132                 || arg_value(&orig_args, "--emit", |val| val.split(',').any(|e| e == "metadata")).is_some();
133
134             if clippy_enabled {
135                 args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
136                 if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
137                     args.extend(extra_args.split("__CLIPPY_HACKERY__").filter_map(|s| {
138                         if s.is_empty() {
139                             None
140                         } else {
141                             Some(s.to_string())
142                         }
143                     }));
144                 }
145             }
146
147             let mut controller = CompileController::basic();
148             if clippy_enabled {
149                 controller.after_parse.callback = Box::new(move |state| {
150                     let mut registry = rustc_plugin::registry::Registry::new(
151                         state.session,
152                         state
153                             .krate
154                             .as_ref()
155                             .expect(
156                                 "at this compilation stage \
157                                  the crate must be parsed",
158                             )
159                             .span,
160                     );
161                     registry.args_hidden = Some(Vec::new());
162
163                     let conf = clippy_lints::read_conf(&registry);
164                     clippy_lints::register_plugins(&mut registry, &conf);
165
166                     let rustc_plugin::registry::Registry {
167                         early_lint_passes,
168                         late_lint_passes,
169                         lint_groups,
170                         llvm_passes,
171                         attributes,
172                         ..
173                     } = registry;
174                     let sess = &state.session;
175                     let mut ls = sess.lint_store.borrow_mut();
176                     for pass in early_lint_passes {
177                         ls.register_early_pass(Some(sess), true, false, pass);
178                     }
179                     for pass in late_lint_passes {
180                         ls.register_late_pass(Some(sess), true, pass);
181                     }
182
183                     for (name, (to, deprecated_name)) in lint_groups {
184                         ls.register_group(Some(sess), true, name, deprecated_name, to);
185                     }
186                     clippy_lints::register_pre_expansion_lints(sess, &mut ls, &conf);
187                     clippy_lints::register_renamed(&mut ls);
188
189                     sess.plugin_llvm_passes.borrow_mut().extend(llvm_passes);
190                     sess.plugin_attributes.borrow_mut().extend(attributes);
191                 });
192             }
193             controller.compilation_done.stop = Compilation::Stop;
194
195             let args = args;
196             rustc_driver::run_compiler(&args, Box::new(controller), None, None)
197         })
198         .try_into()
199         .expect("exit code too large"),
200     )
201 }