]>
Commit | Line | Data |
---|---|---|
1a4d82fc JJ |
1 | //! The Rust compiler. |
2 | //! | |
3 | //! # Note | |
4 | //! | |
5 | //! This API is completely unstable and subject to change. | |
6 | ||
9fa01778 | 7 | #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")] |
0bf4aa26 | 8 | #![feature(nll)] |
dfeec247 | 9 | #![recursion_limit = "256"] |
94b46f34 | 10 | |
92a42be0 | 11 | #[macro_use] |
3dfed10e | 12 | extern crate tracing; |
e1599b0c XL |
13 | #[macro_use] |
14 | extern crate lazy_static; | |
15 | ||
16 | pub extern crate rustc_plugin_impl as plugin; | |
1a4d82fc | 17 | |
3dfed10e | 18 | use rustc_ast as ast; |
ba9703b0 | 19 | use rustc_codegen_ssa::{traits::CodegenBackend, CodegenResults}; |
dfeec247 | 20 | use rustc_data_structures::profiling::print_time_passes_entry; |
532ac7d7 | 21 | use rustc_data_structures::sync::SeqCst; |
ba9703b0 XL |
22 | use rustc_errors::registry::{InvalidErrorCode, Registry}; |
23 | use rustc_errors::{ErrorReported, PResult}; | |
60c5eb7d | 24 | use rustc_feature::{find_gated_cfg, UnstableFeatures}; |
dfeec247 | 25 | use rustc_hir::def_id::LOCAL_CRATE; |
74b04a01 | 26 | use rustc_interface::util::{collect_crate_types, get_builtin_codegen_backend}; |
dfeec247 XL |
27 | use rustc_interface::{interface, Queries}; |
28 | use rustc_lint::LintStore; | |
29 | use rustc_metadata::locator; | |
ba9703b0 XL |
30 | use rustc_middle::middle::cstore::MetadataLoader; |
31 | use rustc_middle::ty::TyCtxt; | |
dfeec247 XL |
32 | use rustc_save_analysis as save; |
33 | use rustc_save_analysis::DumpHandler; | |
74b04a01 | 34 | use rustc_serialize::json::{self, ToJson}; |
ba9703b0 XL |
35 | use rustc_session::config::nightly_options; |
36 | use rustc_session::config::{ErrorOutputType, Input, OutputType, PrintRequest}; | |
37 | use rustc_session::getopts; | |
38 | use rustc_session::lint::{Lint, LintId}; | |
39 | use rustc_session::{config, DiagnosticOutput, Session}; | |
40 | use rustc_session::{early_error, early_warn}; | |
41 | use rustc_span::source_map::{FileLoader, FileName}; | |
42 | use rustc_span::symbol::sym; | |
476ff2be | 43 | |
0bf4aa26 | 44 | use std::borrow::Cow; |
2c00a5a8 | 45 | use std::cmp::max; |
9cc50fc6 | 46 | use std::default::Default; |
85aaf69f | 47 | use std::env; |
041b39d2 | 48 | use std::ffi::OsString; |
74b04a01 | 49 | use std::fs; |
c34b1796 | 50 | use std::io::{self, Read, Write}; |
416331ca | 51 | use std::mem; |
532ac7d7 XL |
52 | use std::panic::{self, catch_unwind}; |
53 | use std::path::PathBuf; | |
041b39d2 | 54 | use std::process::{self, Command, Stdio}; |
c34b1796 | 55 | use std::str; |
416331ca | 56 | use std::time::Instant; |
1a4d82fc | 57 | |
e1599b0c | 58 | mod args; |
dfeec247 | 59 | pub mod pretty; |
2c00a5a8 | 60 | |
8faf50e0 | 61 | /// Exit status code used for successful compilation and help output. |
532ac7d7 | 62 | pub const EXIT_SUCCESS: i32 = 0; |
8faf50e0 | 63 | |
416331ca | 64 | /// Exit status code used for compilation failures and invalid flags. |
532ac7d7 | 65 | pub const EXIT_FAILURE: i32 = 1; |
8faf50e0 | 66 | |
3dfed10e XL |
67 | const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/issues/new\ |
68 | ?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md"; | |
0bf4aa26 XL |
69 | |
70 | const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["Z", "C", "crate-type"]; | |
71 | ||
72 | const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"]; | |
73 | ||
74 | const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"]; | |
0531ce1d | 75 | |
532ac7d7 | 76 | pub fn abort_on_err<T>(result: Result<T, ErrorReported>, sess: &Session) -> T { |
7453a54e | 77 | match result { |
532ac7d7 | 78 | Err(..) => { |
041b39d2 XL |
79 | sess.abort_if_errors(); |
80 | panic!("error reported but abort_if_errors didn't abort???"); | |
81 | } | |
7453a54e SL |
82 | Ok(x) => x, |
83 | } | |
84 | } | |
85 | ||
532ac7d7 XL |
86 | pub trait Callbacks { |
87 | /// Called before creating the compiler instance | |
88 | fn config(&mut self, _config: &mut interface::Config) {} | |
416331ca XL |
89 | /// Called after parsing. Return value instructs the compiler whether to |
90 | /// continue the compilation afterwards (defaults to `Compilation::Continue`) | |
60c5eb7d XL |
91 | fn after_parsing<'tcx>( |
92 | &mut self, | |
93 | _compiler: &interface::Compiler, | |
94 | _queries: &'tcx Queries<'tcx>, | |
95 | ) -> Compilation { | |
416331ca | 96 | Compilation::Continue |
8faf50e0 | 97 | } |
416331ca XL |
98 | /// Called after expansion. Return value instructs the compiler whether to |
99 | /// continue the compilation afterwards (defaults to `Compilation::Continue`) | |
60c5eb7d XL |
100 | fn after_expansion<'tcx>( |
101 | &mut self, | |
102 | _compiler: &interface::Compiler, | |
103 | _queries: &'tcx Queries<'tcx>, | |
104 | ) -> Compilation { | |
416331ca XL |
105 | Compilation::Continue |
106 | } | |
107 | /// Called after analysis. Return value instructs the compiler whether to | |
108 | /// continue the compilation afterwards (defaults to `Compilation::Continue`) | |
60c5eb7d XL |
109 | fn after_analysis<'tcx>( |
110 | &mut self, | |
111 | _compiler: &interface::Compiler, | |
112 | _queries: &'tcx Queries<'tcx>, | |
113 | ) -> Compilation { | |
416331ca | 114 | Compilation::Continue |
2c00a5a8 XL |
115 | } |
116 | } | |
3b2f2976 | 117 | |
416331ca XL |
118 | #[derive(Default)] |
119 | pub struct TimePassesCallbacks { | |
120 | time_passes: bool, | |
121 | } | |
122 | ||
123 | impl Callbacks for TimePassesCallbacks { | |
124 | fn config(&mut self, config: &mut interface::Config) { | |
e1599b0c XL |
125 | // If a --prints=... option has been given, we don't print the "total" |
126 | // time because it will mess up the --prints output. See #64339. | |
dfeec247 XL |
127 | self.time_passes = config.opts.prints.is_empty() |
128 | && (config.opts.debugging_opts.time_passes || config.opts.debugging_opts.time); | |
416331ca XL |
129 | } |
130 | } | |
131 | ||
60c5eb7d XL |
132 | pub fn diagnostics_registry() -> Registry { |
133 | Registry::new(&rustc_error_codes::DIAGNOSTICS) | |
134 | } | |
135 | ||
532ac7d7 | 136 | // Parse args and run the compiler. This is the primary entry point for rustc. |
532ac7d7 XL |
137 | // The FileLoader provides a way to load files from sources other than the file system. |
138 | pub fn run_compiler( | |
e1599b0c | 139 | at_args: &[String], |
532ac7d7 XL |
140 | callbacks: &mut (dyn Callbacks + Send), |
141 | file_loader: Option<Box<dyn FileLoader + Send + Sync>>, | |
dfeec247 | 142 | emitter: Option<Box<dyn Write + Send>>, |
532ac7d7 | 143 | ) -> interface::Result<()> { |
e1599b0c XL |
144 | let mut args = Vec::new(); |
145 | for arg in at_args { | |
146 | match args::arg_expand(arg.clone()) { | |
147 | Ok(arg) => args.extend(arg), | |
dfeec247 XL |
148 | Err(err) => early_error( |
149 | ErrorOutputType::default(), | |
150 | &format!("Failed to load argument file: {}", err), | |
151 | ), | |
e1599b0c XL |
152 | } |
153 | } | |
dfeec247 XL |
154 | let diagnostic_output = |
155 | emitter.map(|emitter| DiagnosticOutput::Raw(emitter)).unwrap_or(DiagnosticOutput::Default); | |
e1599b0c | 156 | let matches = match handle_options(&args) { |
532ac7d7 XL |
157 | Some(matches) => matches, |
158 | None => return Ok(()), | |
159 | }; | |
2c00a5a8 | 160 | |
e74abb32 XL |
161 | let sopts = config::build_session_options(&matches); |
162 | let cfg = interface::parse_cfgspecs(matches.opt_strs("cfg")); | |
2c00a5a8 | 163 | |
532ac7d7 XL |
164 | let mut dummy_config = |sopts, cfg, diagnostic_output| { |
165 | let mut config = interface::Config { | |
166 | opts: sopts, | |
167 | crate_cfg: cfg, | |
168 | input: Input::File(PathBuf::new()), | |
169 | input_path: None, | |
170 | output_file: None, | |
171 | output_dir: None, | |
172 | file_loader: None, | |
173 | diagnostic_output, | |
174 | stderr: None, | |
175 | crate_name: None, | |
176 | lint_caps: Default::default(), | |
e74abb32 | 177 | register_lints: None, |
60c5eb7d XL |
178 | override_queries: None, |
179 | registry: diagnostics_registry(), | |
2c00a5a8 | 180 | }; |
532ac7d7 XL |
181 | callbacks.config(&mut config); |
182 | config | |
183 | }; | |
184 | ||
185 | if let Some(ref code) = matches.opt_str("explain") { | |
60c5eb7d | 186 | handle_explain(diagnostics_registry(), code, sopts.error_format); |
532ac7d7 | 187 | return Ok(()); |
2c00a5a8 XL |
188 | } |
189 | ||
532ac7d7 XL |
190 | let (odir, ofile) = make_output(&matches); |
191 | let (input, input_file_path, input_err) = match make_input(&matches.free) { | |
192 | Some(v) => v, | |
dfeec247 XL |
193 | None => match matches.free.len() { |
194 | 0 => { | |
195 | let config = dummy_config(sopts, cfg, diagnostic_output); | |
196 | interface::run_compiler(config, |compiler| { | |
197 | let sopts = &compiler.session().opts; | |
198 | if sopts.describe_lints { | |
199 | let lint_store = rustc_lint::new_lint_store( | |
200 | sopts.debugging_opts.no_interleave_lints, | |
201 | compiler.session().unstable_options(), | |
532ac7d7 | 202 | ); |
dfeec247 XL |
203 | describe_lints(compiler.session(), &lint_store, false); |
204 | return; | |
205 | } | |
206 | let should_stop = RustcDefaultCalls::print_crate_info( | |
207 | &***compiler.codegen_backend(), | |
208 | compiler.session(), | |
209 | None, | |
210 | &odir, | |
211 | &ofile, | |
212 | ); | |
2c00a5a8 | 213 | |
dfeec247 XL |
214 | if should_stop == Compilation::Stop { |
215 | return; | |
216 | } | |
217 | early_error(sopts.error_format, "no input filename given") | |
218 | }); | |
219 | return Ok(()); | |
2c00a5a8 | 220 | } |
dfeec247 XL |
221 | 1 => panic!("make_input should have provided valid inputs"), |
222 | _ => early_error( | |
223 | sopts.error_format, | |
224 | &format!( | |
225 | "multiple input filenames provided (first two filenames are `{}` and `{}`)", | |
226 | matches.free[0], matches.free[1], | |
227 | ), | |
228 | ), | |
229 | }, | |
532ac7d7 XL |
230 | }; |
231 | ||
232 | if let Some(err) = input_err { | |
233 | // Immediately stop compilation if there was an issue reading | |
234 | // the input (for example if the input stream is not UTF-8). | |
235 | interface::run_compiler(dummy_config(sopts, cfg, diagnostic_output), |compiler| { | |
236 | compiler.session().err(&err.to_string()); | |
237 | }); | |
238 | return Err(ErrorReported); | |
2c00a5a8 XL |
239 | } |
240 | ||
532ac7d7 XL |
241 | let mut config = interface::Config { |
242 | opts: sopts, | |
243 | crate_cfg: cfg, | |
244 | input, | |
245 | input_path: input_file_path, | |
246 | output_file: ofile, | |
247 | output_dir: odir, | |
248 | file_loader, | |
249 | diagnostic_output, | |
250 | stderr: None, | |
251 | crate_name: None, | |
252 | lint_caps: Default::default(), | |
e74abb32 | 253 | register_lints: None, |
60c5eb7d XL |
254 | override_queries: None, |
255 | registry: diagnostics_registry(), | |
532ac7d7 XL |
256 | }; |
257 | ||
258 | callbacks.config(&mut config); | |
259 | ||
260 | interface::run_compiler(config, |compiler| { | |
261 | let sess = compiler.session(); | |
262 | let should_stop = RustcDefaultCalls::print_crate_info( | |
263 | &***compiler.codegen_backend(), | |
264 | sess, | |
265 | Some(compiler.input()), | |
266 | compiler.output_dir(), | |
267 | compiler.output_file(), | |
dfeec247 XL |
268 | ) |
269 | .and_then(|| { | |
270 | RustcDefaultCalls::list_metadata( | |
271 | sess, | |
272 | &*compiler.codegen_backend().metadata_loader(), | |
273 | &matches, | |
274 | compiler.input(), | |
275 | ) | |
74b04a01 XL |
276 | }) |
277 | .and_then(|| RustcDefaultCalls::try_process_rlink(sess, compiler)); | |
532ac7d7 XL |
278 | |
279 | if should_stop == Compilation::Stop { | |
280 | return sess.compile_status(); | |
2c00a5a8 XL |
281 | } |
282 | ||
60c5eb7d XL |
283 | let linker = compiler.enter(|queries| { |
284 | let early_exit = || sess.compile_status().map(|_| None); | |
285 | queries.parse()?; | |
286 | ||
287 | if let Some(ppm) = &sess.opts.pretty { | |
288 | if ppm.needs_ast_map() { | |
289 | queries.global_ctxt()?.peek_mut().enter(|tcx| { | |
290 | let expanded_crate = queries.expansion()?.take().0; | |
291 | pretty::print_after_hir_lowering( | |
292 | tcx, | |
293 | compiler.input(), | |
294 | &expanded_crate, | |
295 | *ppm, | |
296 | compiler.output_file().as_ref().map(|p| &**p), | |
297 | ); | |
298 | Ok(()) | |
299 | })?; | |
300 | } else { | |
301 | let krate = queries.parse()?.take(); | |
302 | pretty::print_after_parsing( | |
303 | sess, | |
304 | &compiler.input(), | |
305 | &krate, | |
306 | *ppm, | |
532ac7d7 XL |
307 | compiler.output_file().as_ref().map(|p| &**p), |
308 | ); | |
60c5eb7d | 309 | } |
f035d41b | 310 | trace!("finished pretty-printing"); |
60c5eb7d | 311 | return early_exit(); |
2c00a5a8 | 312 | } |
3b2f2976 | 313 | |
60c5eb7d XL |
314 | if callbacks.after_parsing(compiler, queries) == Compilation::Stop { |
315 | return early_exit(); | |
316 | } | |
94b46f34 | 317 | |
dfeec247 XL |
318 | if sess.opts.debugging_opts.parse_only |
319 | || sess.opts.debugging_opts.show_span.is_some() | |
320 | || sess.opts.debugging_opts.ast_json_noexpand | |
321 | { | |
322 | return early_exit(); | |
60c5eb7d | 323 | } |
94b46f34 | 324 | |
60c5eb7d XL |
325 | { |
326 | let (_, lint_store) = &*queries.register_plugins()?.peek(); | |
0531ce1d | 327 | |
60c5eb7d XL |
328 | // Lint plugins are registered; now we can process command line flags. |
329 | if sess.opts.describe_lints { | |
330 | describe_lints(&sess, &lint_store, true); | |
331 | return early_exit(); | |
332 | } | |
e74abb32 | 333 | } |
1a4d82fc | 334 | |
60c5eb7d XL |
335 | queries.expansion()?; |
336 | if callbacks.after_expansion(compiler, queries) == Compilation::Stop { | |
337 | return early_exit(); | |
338 | } | |
416331ca | 339 | |
60c5eb7d | 340 | queries.prepare_outputs()?; |
85aaf69f | 341 | |
60c5eb7d XL |
342 | if sess.opts.output_types.contains_key(&OutputType::DepInfo) |
343 | && sess.opts.output_types.len() == 1 | |
344 | { | |
345 | return early_exit(); | |
346 | } | |
85aaf69f | 347 | |
60c5eb7d | 348 | queries.global_ctxt()?; |
85aaf69f | 349 | |
f035d41b | 350 | // Drop AST after creating GlobalCtxt to free memory |
3dfed10e XL |
351 | { |
352 | let _timer = sess.prof.generic_activity("drop_ast"); | |
353 | mem::drop(queries.expansion()?.take()); | |
354 | } | |
f035d41b | 355 | |
dfeec247 XL |
356 | if sess.opts.debugging_opts.no_analysis || sess.opts.debugging_opts.ast_json { |
357 | return early_exit(); | |
60c5eb7d | 358 | } |
2c00a5a8 | 359 | |
60c5eb7d | 360 | if sess.opts.debugging_opts.save_analysis { |
60c5eb7d XL |
361 | let crate_name = queries.crate_name()?.peek().clone(); |
362 | queries.global_ctxt()?.peek_mut().enter(|tcx| { | |
363 | let result = tcx.analysis(LOCAL_CRATE); | |
364 | ||
dfeec247 | 365 | sess.time("save_analysis", || { |
60c5eb7d XL |
366 | save::process_crate( |
367 | tcx, | |
60c5eb7d XL |
368 | &crate_name, |
369 | &compiler.input(), | |
370 | None, | |
371 | DumpHandler::new( | |
dfeec247 XL |
372 | compiler.output_dir().as_ref().map(|p| &**p), |
373 | &crate_name, | |
374 | ), | |
60c5eb7d XL |
375 | ) |
376 | }); | |
2c00a5a8 | 377 | |
60c5eb7d | 378 | result |
60c5eb7d | 379 | })?; |
60c5eb7d | 380 | } |
2c00a5a8 | 381 | |
60c5eb7d | 382 | queries.global_ctxt()?.peek_mut().enter(|tcx| tcx.analysis(LOCAL_CRATE))?; |
c30ab7b3 | 383 | |
60c5eb7d XL |
384 | if callbacks.after_analysis(compiler, queries) == Compilation::Stop { |
385 | return early_exit(); | |
386 | } | |
387 | ||
60c5eb7d | 388 | queries.ongoing_codegen()?; |
85aaf69f | 389 | |
60c5eb7d XL |
390 | if sess.opts.debugging_opts.print_type_sizes { |
391 | sess.code_stats.print_type_sizes(); | |
392 | } | |
0531ce1d | 393 | |
60c5eb7d XL |
394 | let linker = queries.linker()?; |
395 | Ok(Some(linker)) | |
396 | })?; | |
0531ce1d | 397 | |
60c5eb7d | 398 | if let Some(linker) = linker { |
dfeec247 | 399 | let _timer = sess.timer("link"); |
60c5eb7d | 400 | linker.link()? |
532ac7d7 | 401 | } |
0531ce1d | 402 | |
532ac7d7 XL |
403 | if sess.opts.debugging_opts.perf_stats { |
404 | sess.print_perf_stats(); | |
405 | } | |
0531ce1d | 406 | |
532ac7d7 | 407 | if sess.print_fuel_crate.is_some() { |
dfeec247 XL |
408 | eprintln!( |
409 | "Fuel used by {}: {}", | |
532ac7d7 | 410 | sess.print_fuel_crate.as_ref().unwrap(), |
dfeec247 XL |
411 | sess.print_fuel.load(SeqCst) |
412 | ); | |
532ac7d7 | 413 | } |
0531ce1d | 414 | |
532ac7d7 XL |
415 | Ok(()) |
416 | }) | |
85aaf69f SL |
417 | } |
418 | ||
83c7162d XL |
419 | #[cfg(unix)] |
420 | pub fn set_sigpipe_handler() { | |
421 | unsafe { | |
422 | // Set the SIGPIPE signal handler, so that an EPIPE | |
423 | // will cause rustc to terminate, as expected. | |
0bf4aa26 | 424 | assert_ne!(libc::signal(libc::SIGPIPE, libc::SIG_DFL), libc::SIG_ERR); |
83c7162d XL |
425 | } |
426 | } | |
427 | ||
428 | #[cfg(windows)] | |
429 | pub fn set_sigpipe_handler() {} | |
430 | ||
85aaf69f | 431 | // Extract output directory and file from matches. |
c34b1796 AL |
432 | fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) { |
433 | let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o)); | |
434 | let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o)); | |
85aaf69f SL |
435 | (odir, ofile) |
436 | } | |
437 | ||
438 | // Extract input (string or file and optional path) from matches. | |
2c00a5a8 | 439 | fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>, Option<io::Error>)> { |
85aaf69f | 440 | if free_matches.len() == 1 { |
cc61c64b | 441 | let ifile = &free_matches[0]; |
85aaf69f | 442 | if ifile == "-" { |
c34b1796 | 443 | let mut src = String::new(); |
2c00a5a8 | 444 | let err = if io::stdin().read_to_string(&mut src).is_err() { |
dfeec247 XL |
445 | Some(io::Error::new( |
446 | io::ErrorKind::InvalidData, | |
447 | "couldn't read from stdin, as it did not contain valid UTF-8", | |
448 | )) | |
2c00a5a8 XL |
449 | } else { |
450 | None | |
451 | }; | |
e1599b0c | 452 | if let Ok(path) = env::var("UNSTABLE_RUSTDOC_TEST_PATH") { |
dfeec247 XL |
453 | let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").expect( |
454 | "when UNSTABLE_RUSTDOC_TEST_PATH is set \ | |
455 | UNSTABLE_RUSTDOC_TEST_LINE also needs to be set", | |
456 | ); | |
457 | let line = isize::from_str_radix(&line, 10) | |
458 | .expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be an number"); | |
e1599b0c XL |
459 | let file_name = FileName::doc_test_source_code(PathBuf::from(path), line); |
460 | return Some((Input::Str { name: file_name, input: src }, None, err)); | |
461 | } | |
dfeec247 | 462 | Some((Input::Str { name: FileName::anon_source_code(&src), input: src }, None, err)) |
85aaf69f | 463 | } else { |
dfeec247 | 464 | Some((Input::File(PathBuf::from(ifile)), Some(PathBuf::from(ifile)), None)) |
1a4d82fc | 465 | } |
85aaf69f SL |
466 | } else { |
467 | None | |
468 | } | |
469 | } | |
470 | ||
471 | // Whether to stop or continue compilation. | |
c34b1796 | 472 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] |
85aaf69f SL |
473 | pub enum Compilation { |
474 | Stop, | |
475 | Continue, | |
476 | } | |
477 | ||
478 | impl Compilation { | |
479 | pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation { | |
480 | match self { | |
481 | Compilation::Stop => Compilation::Stop, | |
92a42be0 | 482 | Compilation::Continue => next(), |
1a4d82fc | 483 | } |
85aaf69f SL |
484 | } |
485 | } | |
1a4d82fc | 486 | |
94b46f34 | 487 | /// CompilerCalls instance for a regular rustc build. |
c34b1796 | 488 | #[derive(Copy, Clone)] |
85aaf69f SL |
489 | pub struct RustcDefaultCalls; |
490 | ||
041b39d2 XL |
491 | // FIXME remove these and use winapi 0.3 instead |
492 | // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs | |
493 | #[cfg(unix)] | |
494 | fn stdout_isatty() -> bool { | |
495 | unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 } | |
496 | } | |
497 | ||
498 | #[cfg(windows)] | |
499 | fn stdout_isatty() -> bool { | |
dfeec247 XL |
500 | use winapi::um::consoleapi::GetConsoleMode; |
501 | use winapi::um::processenv::GetStdHandle; | |
502 | use winapi::um::winbase::STD_OUTPUT_HANDLE; | |
503 | ||
041b39d2 XL |
504 | unsafe { |
505 | let handle = GetStdHandle(STD_OUTPUT_HANDLE); | |
506 | let mut out = 0; | |
507 | GetConsoleMode(handle, &mut out) != 0 | |
508 | } | |
509 | } | |
510 | ||
60c5eb7d | 511 | fn handle_explain(registry: Registry, code: &str, output: ErrorOutputType) { |
dfeec247 | 512 | let normalised = |
74b04a01 XL |
513 | if code.starts_with('E') { code.to_string() } else { format!("E{0:0>4}", code) }; |
514 | match registry.try_find_description(&normalised) { | |
515 | Ok(Some(description)) => { | |
041b39d2 XL |
516 | let mut is_in_code_block = false; |
517 | let mut text = String::new(); | |
7453a54e | 518 | // Slice off the leading newline and print. |
60c5eb7d | 519 | for line in description.lines() { |
dfeec247 XL |
520 | let indent_level = |
521 | line.find(|c: char| !c.is_whitespace()).unwrap_or_else(|| line.len()); | |
041b39d2 XL |
522 | let dedented_line = &line[indent_level..]; |
523 | if dedented_line.starts_with("```") { | |
524 | is_in_code_block = !is_in_code_block; | |
60c5eb7d | 525 | text.push_str(&line[..(indent_level + 3)]); |
041b39d2 XL |
526 | } else if is_in_code_block && dedented_line.starts_with("# ") { |
527 | continue; | |
a7813a04 | 528 | } else { |
041b39d2 XL |
529 | text.push_str(line); |
530 | } | |
531 | text.push('\n'); | |
532 | } | |
041b39d2 XL |
533 | if stdout_isatty() { |
534 | show_content_with_pager(&text); | |
535 | } else { | |
536 | print!("{}", text); | |
537 | } | |
7453a54e | 538 | } |
74b04a01 | 539 | Ok(None) => { |
7453a54e SL |
540 | early_error(output, &format!("no extended information for {}", code)); |
541 | } | |
74b04a01 XL |
542 | Err(InvalidErrorCode) => { |
543 | early_error(output, &format!("{} is not a valid error code", code)); | |
544 | } | |
7453a54e SL |
545 | } |
546 | } | |
547 | ||
041b39d2 | 548 | fn show_content_with_pager(content: &String) { |
dfeec247 XL |
549 | let pager_name = env::var_os("PAGER").unwrap_or_else(|| { |
550 | if cfg!(windows) { OsString::from("more.com") } else { OsString::from("less") } | |
041b39d2 XL |
551 | }); |
552 | ||
553 | let mut fallback_to_println = false; | |
554 | ||
555 | match Command::new(pager_name).stdin(Stdio::piped()).spawn() { | |
556 | Ok(mut pager) => { | |
3b2f2976 | 557 | if let Some(pipe) = pager.stdin.as_mut() { |
041b39d2 XL |
558 | if pipe.write_all(content.as_bytes()).is_err() { |
559 | fallback_to_println = true; | |
560 | } | |
561 | } | |
562 | ||
563 | if pager.wait().is_err() { | |
564 | fallback_to_println = true; | |
565 | } | |
566 | } | |
567 | Err(_) => { | |
568 | fallback_to_println = true; | |
569 | } | |
570 | } | |
571 | ||
572 | // If pager fails for whatever reason, we should still print the content | |
573 | // to standard output | |
574 | if fallback_to_println { | |
575 | print!("{}", content); | |
576 | } | |
577 | } | |
578 | ||
85aaf69f | 579 | impl RustcDefaultCalls { |
74b04a01 XL |
580 | fn process_rlink(sess: &Session, compiler: &interface::Compiler) -> Result<(), ErrorReported> { |
581 | if let Input::File(file) = compiler.input() { | |
582 | // FIXME: #![crate_type] and #![crate_name] support not implemented yet | |
583 | let attrs = vec![]; | |
f9f354fc | 584 | sess.init_crate_types(collect_crate_types(sess, &attrs)); |
74b04a01 XL |
585 | let outputs = compiler.build_output_filenames(&sess, &attrs); |
586 | let rlink_data = fs::read_to_string(file).unwrap_or_else(|err| { | |
587 | sess.fatal(&format!("failed to read rlink file: {}", err)); | |
588 | }); | |
589 | let codegen_results: CodegenResults = json::decode(&rlink_data).unwrap_or_else(|err| { | |
590 | sess.fatal(&format!("failed to decode rlink: {}", err)); | |
591 | }); | |
592 | compiler.codegen_backend().link(&sess, Box::new(codegen_results), &outputs) | |
593 | } else { | |
594 | sess.fatal("rlink must be a file") | |
595 | } | |
596 | } | |
597 | ||
598 | pub fn try_process_rlink(sess: &Session, compiler: &interface::Compiler) -> Compilation { | |
599 | if sess.opts.debugging_opts.link_only { | |
600 | let result = RustcDefaultCalls::process_rlink(sess, compiler); | |
601 | abort_on_err(result, sess); | |
602 | Compilation::Stop | |
603 | } else { | |
604 | Compilation::Continue | |
605 | } | |
606 | } | |
607 | ||
dfeec247 XL |
608 | pub fn list_metadata( |
609 | sess: &Session, | |
610 | metadata_loader: &dyn MetadataLoader, | |
611 | matches: &getopts::Matches, | |
612 | input: &Input, | |
613 | ) -> Compilation { | |
85aaf69f | 614 | let r = matches.opt_strs("Z"); |
0bf4aa26 | 615 | if r.iter().any(|s| *s == "ls") { |
f9f354fc XL |
616 | match *input { |
617 | Input::File(ref ifile) => { | |
85aaf69f | 618 | let path = &(*ifile); |
c34b1796 | 619 | let mut v = Vec::new(); |
dfeec247 XL |
620 | locator::list_file_metadata(&sess.target.target, path, metadata_loader, &mut v) |
621 | .unwrap(); | |
c34b1796 | 622 | println!("{}", String::from_utf8(v).unwrap()); |
85aaf69f | 623 | } |
f9f354fc | 624 | Input::Str { .. } => { |
9cc50fc6 | 625 | early_error(ErrorOutputType::default(), "cannot list metadata for stdin"); |
85aaf69f | 626 | } |
1a4d82fc | 627 | } |
85aaf69f | 628 | return Compilation::Stop; |
1a4d82fc | 629 | } |
85aaf69f | 630 | |
0bf4aa26 | 631 | Compilation::Continue |
1a4d82fc JJ |
632 | } |
633 | ||
dfeec247 XL |
634 | fn print_crate_info( |
635 | codegen_backend: &dyn CodegenBackend, | |
636 | sess: &Session, | |
637 | input: Option<&Input>, | |
638 | odir: &Option<PathBuf>, | |
639 | ofile: &Option<PathBuf>, | |
640 | ) -> Compilation { | |
ba9703b0 | 641 | use rustc_session::config::PrintRequest::*; |
ea8adc8c XL |
642 | // PrintRequest::NativeStaticLibs is special - printed during linking |
643 | // (empty iterator returns true) | |
0bf4aa26 | 644 | if sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) { |
85aaf69f SL |
645 | return Compilation::Continue; |
646 | } | |
647 | ||
54a0048b SL |
648 | let attrs = match input { |
649 | None => None, | |
650 | Some(input) => { | |
651 | let result = parse_crate_attrs(sess, input); | |
652 | match result { | |
653 | Ok(attrs) => Some(attrs), | |
654 | Err(mut parse_error) => { | |
655 | parse_error.emit(); | |
656 | return Compilation::Stop; | |
657 | } | |
658 | } | |
659 | } | |
660 | }; | |
85aaf69f SL |
661 | for req in &sess.opts.prints { |
662 | match *req { | |
2c00a5a8 | 663 | TargetList => { |
83c7162d | 664 | let mut targets = rustc_target::spec::get_targets().collect::<Vec<String>>(); |
7453a54e SL |
665 | targets.sort(); |
666 | println!("{}", targets.join("\n")); | |
dfeec247 | 667 | } |
0731742a | 668 | Sysroot => println!("{}", sess.sysroot.display()), |
74b04a01 XL |
669 | TargetLibdir => println!( |
670 | "{}", | |
671 | sess.target_tlib_path.as_ref().unwrap_or(&sess.host_tlib_path).dir.display() | |
672 | ), | |
2c00a5a8 XL |
673 | TargetSpec => println!("{}", sess.target.target.to_json().pretty()), |
674 | FileNames | CrateName => { | |
dfeec247 XL |
675 | let input = input.unwrap_or_else(|| { |
676 | early_error(ErrorOutputType::default(), "no input file provided") | |
677 | }); | |
85aaf69f | 678 | let attrs = attrs.as_ref().unwrap(); |
532ac7d7 | 679 | let t_outputs = rustc_interface::util::build_output_filenames( |
dfeec247 | 680 | input, odir, ofile, attrs, sess, |
532ac7d7 | 681 | ); |
3dfed10e | 682 | let id = rustc_session::output::find_crate_name(sess, attrs, input); |
85aaf69f SL |
683 | if *req == PrintRequest::CrateName { |
684 | println!("{}", id); | |
92a42be0 | 685 | continue; |
85aaf69f | 686 | } |
74b04a01 | 687 | let crate_types = collect_crate_types(sess, attrs); |
85aaf69f | 688 | for &style in &crate_types { |
ba9703b0 XL |
689 | let fname = |
690 | rustc_session::output::filename_for_input(sess, style, &id, &t_outputs); | |
0bf4aa26 | 691 | println!("{}", fname.file_name().unwrap().to_string_lossy()); |
85aaf69f SL |
692 | } |
693 | } | |
2c00a5a8 | 694 | Cfg => { |
dfeec247 XL |
695 | let allow_unstable_cfg = |
696 | UnstableFeatures::from_environment().is_nightly_build(); | |
697 | ||
698 | let mut cfgs = sess | |
699 | .parse_sess | |
700 | .config | |
701 | .iter() | |
3dfed10e | 702 | .filter_map(|&(name, value)| { |
dfeec247 XL |
703 | // Note that crt-static is a specially recognized cfg |
704 | // directive that's printed out here as part of | |
705 | // rust-lang/rust#37406, but in general the | |
706 | // `target_feature` cfg is gated under | |
707 | // rust-lang/rust#29717. For now this is just | |
708 | // specifically allowing the crt-static cfg and that's | |
709 | // it, this is intended to get into Cargo and then go | |
710 | // through to build scripts. | |
3dfed10e | 711 | if (name != sym::target_feature || value != Some(sym::crt_dash_static)) |
dfeec247 XL |
712 | && !allow_unstable_cfg |
713 | && find_gated_cfg(|cfg_sym| cfg_sym == name).is_some() | |
714 | { | |
715 | return None; | |
716 | } | |
717 | ||
718 | if let Some(value) = value { | |
719 | Some(format!("{}=\"{}\"", name, value)) | |
720 | } else { | |
721 | Some(name.to_string()) | |
722 | } | |
723 | }) | |
724 | .collect::<Vec<String>>(); | |
476ff2be SL |
725 | |
726 | cfgs.sort(); | |
727 | for cfg in cfgs { | |
728 | println!("{}", cfg); | |
7453a54e SL |
729 | } |
730 | } | |
2c00a5a8 | 731 | RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => { |
94b46f34 | 732 | codegen_backend.print(*req, sess); |
7cac9316 | 733 | } |
ff7c6d11 XL |
734 | // Any output here interferes with Cargo's parsing of other printed output |
735 | PrintRequest::NativeStaticLibs => {} | |
85aaf69f SL |
736 | } |
737 | } | |
ba9703b0 | 738 | Compilation::Stop |
1a4d82fc JJ |
739 | } |
740 | } | |
741 | ||
742 | /// Returns a version string such as "0.12.0-dev". | |
3b2f2976 | 743 | fn release_str() -> Option<&'static str> { |
1a4d82fc JJ |
744 | option_env!("CFG_RELEASE") |
745 | } | |
746 | ||
747 | /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built. | |
3b2f2976 | 748 | fn commit_hash_str() -> Option<&'static str> { |
1a4d82fc JJ |
749 | option_env!("CFG_VER_HASH") |
750 | } | |
751 | ||
752 | /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string. | |
3b2f2976 | 753 | fn commit_date_str() -> Option<&'static str> { |
1a4d82fc JJ |
754 | option_env!("CFG_VER_DATE") |
755 | } | |
756 | ||
c1a9b12d | 757 | /// Prints version information |
1a4d82fc JJ |
758 | pub fn version(binary: &str, matches: &getopts::Matches) { |
759 | let verbose = matches.opt_present("verbose"); | |
760 | ||
0bf4aa26 XL |
761 | println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version")); |
762 | ||
1a4d82fc | 763 | if verbose { |
92a42be0 SL |
764 | fn unw(x: Option<&str>) -> &str { |
765 | x.unwrap_or("unknown") | |
766 | } | |
1a4d82fc JJ |
767 | println!("binary: {}", binary); |
768 | println!("commit-hash: {}", unw(commit_hash_str())); | |
769 | println!("commit-date: {}", unw(commit_date_str())); | |
770 | println!("host: {}", config::host_triple()); | |
771 | println!("release: {}", unw(release_str())); | |
60c5eb7d | 772 | get_builtin_codegen_backend("llvm")().print_version(); |
1a4d82fc JJ |
773 | } |
774 | } | |
775 | ||
776 | fn usage(verbose: bool, include_unstable_options: bool) { | |
dfeec247 | 777 | let groups = if verbose { config::rustc_optgroups() } else { config::rustc_short_optgroups() }; |
041b39d2 XL |
778 | let mut options = getopts::Options::new(); |
779 | for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) { | |
780 | (option.apply)(&mut options); | |
781 | } | |
0bf4aa26 | 782 | let message = "Usage: rustc [OPTIONS] INPUT"; |
3b2f2976 | 783 | let nightly_help = if nightly_options::is_nightly_build() { |
48663c56 | 784 | "\n -Z help Print unstable compiler options" |
3b2f2976 XL |
785 | } else { |
786 | "" | |
787 | }; | |
788 | let verbose_help = if verbose { | |
1a4d82fc JJ |
789 | "" |
790 | } else { | |
791 | "\n --help -v Print the full set of options rustc accepts" | |
792 | }; | |
e1599b0c XL |
793 | let at_path = if verbose && nightly_options::is_nightly_build() { |
794 | " @path Read newline separated options from `path`\n" | |
795 | } else { | |
796 | "" | |
797 | }; | |
dfeec247 XL |
798 | println!( |
799 | "{options}{at_path}\nAdditional help: | |
1a4d82fc | 800 | -C help Print codegen options |
92a42be0 | 801 | -W help \ |
e1599b0c | 802 | Print 'lint' options and default settings{nightly}{verbose}\n", |
dfeec247 XL |
803 | options = options.usage(message), |
804 | at_path = at_path, | |
805 | nightly = nightly_help, | |
806 | verbose = verbose_help | |
807 | ); | |
1a4d82fc JJ |
808 | } |
809 | ||
0531ce1d | 810 | fn print_wall_help() { |
dfeec247 XL |
811 | println!( |
812 | " | |
0531ce1d XL |
813 | The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by |
814 | default. Use `rustc -W help` to see all available lints. It's more common to put | |
815 | warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using | |
816 | the command line flag directly. | |
dfeec247 XL |
817 | " |
818 | ); | |
0531ce1d XL |
819 | } |
820 | ||
dfeec247 XL |
821 | fn describe_lints(sess: &Session, lint_store: &LintStore, loaded_plugins: bool) { |
822 | println!( | |
823 | " | |
1a4d82fc JJ |
824 | Available lint options: |
825 | -W <foo> Warn about <foo> | |
92a42be0 SL |
826 | -A <foo> \ |
827 | Allow <foo> | |
1a4d82fc | 828 | -D <foo> Deny <foo> |
92a42be0 | 829 | -F <foo> Forbid <foo> \ |
8bb4bdeb | 830 | (deny <foo> and all attempts to override) |
1a4d82fc | 831 | |
dfeec247 XL |
832 | " |
833 | ); | |
1a4d82fc | 834 | |
e74abb32 | 835 | fn sort_lints(sess: &Session, mut lints: Vec<&'static Lint>) -> Vec<&'static Lint> { |
83c7162d | 836 | // The sort doesn't case-fold but it's doubtful we care. |
60c5eb7d | 837 | lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess.edition()), x.name)); |
1a4d82fc JJ |
838 | lints |
839 | } | |
840 | ||
dfeec247 XL |
841 | fn sort_lint_groups( |
842 | lints: Vec<(&'static str, Vec<LintId>, bool)>, | |
843 | ) -> Vec<(&'static str, Vec<LintId>)> { | |
1a4d82fc | 844 | let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect(); |
8faf50e0 | 845 | lints.sort_by_key(|l| l.0); |
1a4d82fc JJ |
846 | lints |
847 | } | |
848 | ||
dfeec247 XL |
849 | let (plugin, builtin): (Vec<_>, _) = |
850 | lint_store.get_lints().iter().cloned().partition(|&lint| lint.is_plugin); | |
0531ce1d XL |
851 | let plugin = sort_lints(sess, plugin); |
852 | let builtin = sort_lints(sess, builtin); | |
1a4d82fc | 853 | |
dfeec247 XL |
854 | let (plugin_groups, builtin_groups): (Vec<_>, _) = |
855 | lint_store.get_lint_groups().iter().cloned().partition(|&(.., p)| p); | |
1a4d82fc JJ |
856 | let plugin_groups = sort_lint_groups(plugin_groups); |
857 | let builtin_groups = sort_lint_groups(builtin_groups); | |
858 | ||
dfeec247 XL |
859 | let max_name_len = |
860 | plugin.iter().chain(&builtin).map(|&s| s.name.chars().count()).max().unwrap_or(0); | |
85aaf69f | 861 | let padded = |x: &str| { |
8faf50e0 | 862 | let mut s = " ".repeat(max_name_len - x.chars().count()); |
1a4d82fc JJ |
863 | s.push_str(x); |
864 | s | |
865 | }; | |
866 | ||
867 | println!("Lint checks provided by rustc:\n"); | |
868 | println!(" {} {:7.7} {}", padded("name"), "default", "meaning"); | |
869 | println!(" {} {:7.7} {}", padded("----"), "-------", "-------"); | |
870 | ||
85aaf69f SL |
871 | let print_lints = |lints: Vec<&Lint>| { |
872 | for lint in lints { | |
1a4d82fc | 873 | let name = lint.name_lower().replace("_", "-"); |
dfeec247 | 874 | println!(" {} {:7.7} {}", padded(&name), lint.default_level.as_str(), lint.desc); |
1a4d82fc JJ |
875 | } |
876 | println!("\n"); | |
877 | }; | |
878 | ||
879 | print_lints(builtin); | |
880 | ||
dfeec247 XL |
881 | let max_name_len = max( |
882 | "warnings".len(), | |
883 | plugin_groups | |
884 | .iter() | |
885 | .chain(&builtin_groups) | |
886 | .map(|&(s, _)| s.chars().count()) | |
887 | .max() | |
888 | .unwrap_or(0), | |
889 | ); | |
9cc50fc6 | 890 | |
85aaf69f | 891 | let padded = |x: &str| { |
8faf50e0 | 892 | let mut s = " ".repeat(max_name_len - x.chars().count()); |
1a4d82fc JJ |
893 | s.push_str(x); |
894 | s | |
895 | }; | |
896 | ||
897 | println!("Lint groups provided by rustc:\n"); | |
898 | println!(" {} {}", padded("name"), "sub-lints"); | |
899 | println!(" {} {}", padded("----"), "---------"); | |
ff7c6d11 | 900 | println!(" {} {}", padded("warnings"), "all lints that are set to issue warnings"); |
1a4d82fc | 901 | |
dfeec247 | 902 | let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>| { |
85aaf69f | 903 | for (name, to) in lints { |
c34b1796 | 904 | let name = name.to_lowercase().replace("_", "-"); |
dfeec247 XL |
905 | let desc = to |
906 | .into_iter() | |
907 | .map(|x| x.to_string().replace("_", "-")) | |
908 | .collect::<Vec<String>>() | |
909 | .join(", "); | |
cc61c64b | 910 | println!(" {} {}", padded(&name), desc); |
1a4d82fc JJ |
911 | } |
912 | println!("\n"); | |
913 | }; | |
914 | ||
915 | print_lint_groups(builtin_groups); | |
916 | ||
917 | match (loaded_plugins, plugin.len(), plugin_groups.len()) { | |
918 | (false, 0, _) | (false, _, 0) => { | |
dfeec247 XL |
919 | println!( |
920 | "Compiler plugins can provide additional lints and lint groups. To see a \ | |
921 | listing of these, re-run `rustc -W help` with a crate filename." | |
922 | ); | |
1a4d82fc | 923 | } |
9e0c209e | 924 | (false, ..) => panic!("didn't load lint plugins but got them anyway!"), |
1a4d82fc JJ |
925 | (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."), |
926 | (true, l, g) => { | |
927 | if l > 0 { | |
928 | println!("Lint checks provided by plugins loaded by this crate:\n"); | |
929 | print_lints(plugin); | |
930 | } | |
931 | if g > 0 { | |
932 | println!("Lint groups provided by plugins loaded by this crate:\n"); | |
933 | print_lint_groups(plugin_groups); | |
934 | } | |
935 | } | |
936 | } | |
937 | } | |
938 | ||
939 | fn describe_debug_flags() { | |
48663c56 | 940 | println!("\nAvailable options:\n"); |
92a42be0 | 941 | print_flag_list("-Z", config::DB_OPTIONS); |
1a4d82fc JJ |
942 | } |
943 | ||
944 | fn describe_codegen_flags() { | |
945 | println!("\nAvailable codegen options:\n"); | |
92a42be0 SL |
946 | print_flag_list("-C", config::CG_OPTIONS); |
947 | } | |
948 | ||
dfeec247 XL |
949 | fn print_flag_list<T>( |
950 | cmdline_opt: &str, | |
ba9703b0 | 951 | flag_list: &[(&'static str, T, &'static str, &'static str)], |
dfeec247 | 952 | ) { |
ba9703b0 | 953 | let max_len = flag_list.iter().map(|&(name, _, _, _)| name.chars().count()).max().unwrap_or(0); |
92a42be0 | 954 | |
ba9703b0 | 955 | for &(name, _, _, desc) in flag_list { |
dfeec247 | 956 | println!( |
ba9703b0 | 957 | " {} {:>width$}=val -- {}", |
dfeec247 XL |
958 | cmdline_opt, |
959 | name.replace("_", "-"), | |
dfeec247 | 960 | desc, |
ba9703b0 | 961 | width = max_len |
dfeec247 | 962 | ); |
1a4d82fc JJ |
963 | } |
964 | } | |
965 | ||
966 | /// Process command line options. Emits messages as appropriate. If compilation | |
7453a54e | 967 | /// should continue, returns a getopts::Matches object parsed from args, |
9fa01778 | 968 | /// otherwise returns `None`. |
7453a54e | 969 | /// |
32a655c1 | 970 | /// The compiler's handling of options is a little complicated as it ties into |
416331ca XL |
971 | /// our stability story. The current intention of each compiler option is to |
972 | /// have one of two modes: | |
7453a54e SL |
973 | /// |
974 | /// 1. An option is stable and can be used everywhere. | |
416331ca | 975 | /// 2. An option is unstable, and can only be used on nightly. |
7453a54e SL |
976 | /// |
977 | /// Like unstable library and language features, however, unstable options have | |
978 | /// always required a form of "opt in" to indicate that you're using them. This | |
979 | /// provides the easy ability to scan a code base to check to see if anything | |
980 | /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag. | |
981 | /// | |
982 | /// All options behind `-Z` are considered unstable by default. Other top-level | |
983 | /// options can also be considered unstable, and they were unlocked through the | |
984 | /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of | |
985 | /// instability in both cases, though. | |
986 | /// | |
987 | /// So with all that in mind, the comments below have some more detail about the | |
988 | /// contortions done here to get things to work out correctly. | |
54a0048b | 989 | pub fn handle_options(args: &[String]) -> Option<getopts::Matches> { |
1a4d82fc | 990 | // Throw away the first argument, the name of the binary |
54a0048b | 991 | let args = &args[1..]; |
1a4d82fc JJ |
992 | |
993 | if args.is_empty() { | |
994 | // user did not write `-v` nor `-Z unstable-options`, so do not | |
995 | // include that extra information. | |
996 | usage(false, false); | |
997 | return None; | |
998 | } | |
999 | ||
7453a54e SL |
1000 | // Parse with *all* options defined in the compiler, we don't worry about |
1001 | // option stability here we just want to parse as much as possible. | |
041b39d2 XL |
1002 | let mut options = getopts::Options::new(); |
1003 | for option in config::rustc_optgroups() { | |
1004 | (option.apply)(&mut options); | |
1005 | } | |
dfeec247 XL |
1006 | let matches = options |
1007 | .parse(args) | |
1008 | .unwrap_or_else(|f| early_error(ErrorOutputType::default(), &f.to_string())); | |
1a4d82fc | 1009 | |
7453a54e SL |
1010 | // For all options we just parsed, we check a few aspects: |
1011 | // | |
1012 | // * If the option is stable, we're all good | |
1013 | // * If the option wasn't passed, we're all good | |
1014 | // * If `-Z unstable-options` wasn't passed (and we're not a -Z option | |
1015 | // ourselves), then we require the `-Z unstable-options` flag to unlock | |
1016 | // this option that was passed. | |
1017 | // * If we're a nightly compiler, then unstable options are now unlocked, so | |
1018 | // we're good to go. | |
416331ca | 1019 | // * Otherwise, if we're an unstable option then we generate an error |
7453a54e | 1020 | // (unstable option being used on stable) |
54a0048b | 1021 | nightly_options::check_nightly_options(&matches, &config::rustc_optgroups()); |
1a4d82fc JJ |
1022 | |
1023 | if matches.opt_present("h") || matches.opt_present("help") { | |
416331ca XL |
1024 | // Only show unstable options in --help if we accept unstable options. |
1025 | usage(matches.opt_present("verbose"), nightly_options::is_unstable_enabled(&matches)); | |
1a4d82fc JJ |
1026 | return None; |
1027 | } | |
1028 | ||
0531ce1d XL |
1029 | // Handle the special case of -Wall. |
1030 | let wall = matches.opt_strs("W"); | |
1031 | if wall.iter().any(|x| *x == "all") { | |
1032 | print_wall_help(); | |
1033 | return None; | |
1034 | } | |
1035 | ||
1a4d82fc | 1036 | // Don't handle -W help here, because we might first load plugins. |
1a4d82fc JJ |
1037 | let r = matches.opt_strs("Z"); |
1038 | if r.iter().any(|x| *x == "help") { | |
1039 | describe_debug_flags(); | |
1040 | return None; | |
1041 | } | |
1042 | ||
1043 | let cg_flags = matches.opt_strs("C"); | |
0bf4aa26 | 1044 | |
1a4d82fc JJ |
1045 | if cg_flags.iter().any(|x| *x == "help") { |
1046 | describe_codegen_flags(); | |
1047 | return None; | |
1048 | } | |
1049 | ||
476ff2be | 1050 | if cg_flags.iter().any(|x| *x == "no-stack-check") { |
dfeec247 XL |
1051 | early_warn( |
1052 | ErrorOutputType::default(), | |
1053 | "the --no-stack-check flag is deprecated and does nothing", | |
1054 | ); | |
476ff2be SL |
1055 | } |
1056 | ||
0bf4aa26 | 1057 | if cg_flags.iter().any(|x| *x == "passes=list") { |
60c5eb7d | 1058 | get_builtin_codegen_backend("llvm")().print_passes(); |
1a4d82fc JJ |
1059 | return None; |
1060 | } | |
1061 | ||
1062 | if matches.opt_present("version") { | |
1063 | version("rustc", &matches); | |
1064 | return None; | |
1065 | } | |
1066 | ||
1067 | Some(matches) | |
1068 | } | |
1069 | ||
54a0048b | 1070 | fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> { |
60c5eb7d | 1071 | match input { |
dfeec247 XL |
1072 | Input::File(ifile) => rustc_parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess), |
1073 | Input::Str { name, input } => rustc_parse::parse_crate_attrs_from_source_str( | |
1074 | name.clone(), | |
1075 | input.clone(), | |
1076 | &sess.parse_sess, | |
1077 | ), | |
54a0048b | 1078 | } |
1a4d82fc JJ |
1079 | } |
1080 | ||
9fa01778 | 1081 | /// Gets a list of extra command-line flags provided by the user, as strings. |
0531ce1d XL |
1082 | /// |
1083 | /// This function is used during ICEs to show more information useful for | |
1084 | /// debugging, since some ICEs only happens with non-default compiler flags | |
1085 | /// (and the users don't always report them). | |
1086 | fn extra_compiler_flags() -> Option<(Vec<String>, bool)> { | |
8faf50e0 | 1087 | let args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).collect::<Vec<_>>(); |
0531ce1d XL |
1088 | |
1089 | // Avoid printing help because of empty args. This can suggest the compiler | |
1090 | // itself is not the program root (consider RLS). | |
1091 | if args.len() < 2 { | |
1092 | return None; | |
1093 | } | |
1094 | ||
ba9703b0 | 1095 | let matches = handle_options(&args)?; |
0531ce1d XL |
1096 | let mut result = Vec::new(); |
1097 | let mut excluded_cargo_defaults = false; | |
1098 | for flag in ICE_REPORT_COMPILER_FLAGS { | |
1099 | let prefix = if flag.len() == 1 { "-" } else { "--" }; | |
1100 | ||
1101 | for content in &matches.opt_strs(flag) { | |
1102 | // Split always returns the first element | |
dfeec247 | 1103 | let name = if let Some(first) = content.split('=').next() { first } else { &content }; |
0531ce1d | 1104 | |
dfeec247 XL |
1105 | let content = |
1106 | if ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.contains(&name) { name } else { content }; | |
0531ce1d XL |
1107 | |
1108 | if !ICE_REPORT_COMPILER_FLAGS_EXCLUDE.contains(&name) { | |
1109 | result.push(format!("{}{} {}", prefix, flag, content)); | |
1110 | } else { | |
1111 | excluded_cargo_defaults = true; | |
1112 | } | |
1113 | } | |
1114 | } | |
1115 | ||
dfeec247 | 1116 | if !result.is_empty() { Some((result, excluded_cargo_defaults)) } else { None } |
0531ce1d XL |
1117 | } |
1118 | ||
e1599b0c | 1119 | /// Runs a closure and catches unwinds triggered by fatal errors. |
1a4d82fc | 1120 | /// |
e1599b0c XL |
1121 | /// The compiler currently unwinds with a special sentinel value to abort |
1122 | /// compilation on fatal errors. This function catches that sentinel and turns | |
1123 | /// the panic into a `Result` instead. | |
1124 | pub fn catch_fatal_errors<F: FnOnce() -> R, R>(f: F) -> Result<R, ErrorReported> { | |
532ac7d7 | 1125 | catch_unwind(panic::AssertUnwindSafe(f)).map_err(|value| { |
dfeec247 | 1126 | if value.is::<rustc_errors::FatalErrorMarker>() { |
532ac7d7 | 1127 | ErrorReported |
8faf50e0 | 1128 | } else { |
e1599b0c XL |
1129 | panic::resume_unwind(value); |
1130 | } | |
1131 | }) | |
1132 | } | |
1133 | ||
f9f354fc XL |
1134 | /// Variant of `catch_fatal_errors` for the `interface::Result` return type |
1135 | /// that also computes the exit code. | |
1136 | pub fn catch_with_exit_code(f: impl FnOnce() -> interface::Result<()>) -> i32 { | |
1137 | let result = catch_fatal_errors(f).and_then(|result| result); | |
1138 | match result { | |
1139 | Ok(()) => EXIT_SUCCESS, | |
1140 | Err(_) => EXIT_FAILURE, | |
1141 | } | |
1142 | } | |
1143 | ||
e1599b0c XL |
1144 | lazy_static! { |
1145 | static ref DEFAULT_HOOK: Box<dyn Fn(&panic::PanicInfo<'_>) + Sync + Send + 'static> = { | |
1146 | let hook = panic::take_hook(); | |
1147 | panic::set_hook(Box::new(|info| report_ice(info, BUG_REPORT_URL))); | |
1148 | hook | |
1149 | }; | |
1150 | } | |
1151 | ||
1152 | /// Prints the ICE message, including backtrace and query stack. | |
1153 | /// | |
1154 | /// The message will point the user at `bug_report_url` to report the ICE. | |
1155 | /// | |
1156 | /// When `install_ice_hook` is called, this function will be called as the panic | |
1157 | /// hook. | |
1158 | pub fn report_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) { | |
1159 | // Invoke the default handler, which prints the actual panic message and optionally a backtrace | |
1160 | (*DEFAULT_HOOK)(info); | |
1161 | ||
1162 | // Separate the output with an empty line | |
1163 | eprintln!(); | |
1164 | ||
dfeec247 XL |
1165 | let emitter = Box::new(rustc_errors::emitter::EmitterWriter::stderr( |
1166 | rustc_errors::ColorConfig::Auto, | |
e1599b0c XL |
1167 | None, |
1168 | false, | |
1169 | false, | |
1170 | None, | |
1171 | false, | |
1172 | )); | |
dfeec247 | 1173 | let handler = rustc_errors::Handler::with_emitter(true, None, emitter); |
e1599b0c XL |
1174 | |
1175 | // a .span_bug or .bug call has already printed what | |
1176 | // it wants to print. | |
dfeec247 XL |
1177 | if !info.payload().is::<rustc_errors::ExplicitBug>() { |
1178 | let d = rustc_errors::Diagnostic::new(rustc_errors::Level::Bug, "unexpected panic"); | |
e1599b0c | 1179 | handler.emit_diagnostic(&d); |
e1599b0c | 1180 | } |
1a4d82fc | 1181 | |
e1599b0c XL |
1182 | let mut xs: Vec<Cow<'static, str>> = vec![ |
1183 | "the compiler unexpectedly panicked. this is a bug.".into(), | |
1184 | format!("we would appreciate a bug report: {}", bug_report_url).into(), | |
dfeec247 XL |
1185 | format!( |
1186 | "rustc {} running on {}", | |
1187 | option_env!("CFG_VERSION").unwrap_or("unknown_version"), | |
1188 | config::host_triple() | |
1189 | ) | |
1190 | .into(), | |
e1599b0c | 1191 | ]; |
0531ce1d | 1192 | |
e1599b0c XL |
1193 | if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() { |
1194 | xs.push(format!("compiler flags: {}", flags.join(" ")).into()); | |
0531ce1d | 1195 | |
e1599b0c XL |
1196 | if excluded_cargo_defaults { |
1197 | xs.push("some of the compiler flags provided by cargo are hidden".into()); | |
1198 | } | |
1199 | } | |
0531ce1d | 1200 | |
e1599b0c XL |
1201 | for note in &xs { |
1202 | handler.note_without_error(¬e); | |
1203 | } | |
1204 | ||
1205 | // If backtraces are enabled, also print the query stack | |
1206 | let backtrace = env::var_os("RUST_BACKTRACE").map(|x| &x != "0").unwrap_or(false); | |
54a0048b | 1207 | |
e1599b0c | 1208 | if backtrace { |
e74abb32 | 1209 | TyCtxt::try_print_query_stack(&handler); |
e1599b0c XL |
1210 | } |
1211 | ||
1212 | #[cfg(windows)] | |
1213 | unsafe { | |
1214 | if env::var("RUSTC_BREAK_ON_ICE").is_ok() { | |
e1599b0c | 1215 | // Trigger a debugger if we crashed during bootstrap |
dfeec247 | 1216 | winapi::um::debugapi::DebugBreak(); |
8faf50e0 | 1217 | } |
e1599b0c XL |
1218 | } |
1219 | } | |
1220 | ||
1221 | /// Installs a panic hook that will print the ICE message on unexpected panics. | |
1222 | /// | |
1223 | /// A custom rustc driver can skip calling this to set up a custom ICE hook. | |
1224 | pub fn install_ice_hook() { | |
1225 | lazy_static::initialize(&DEFAULT_HOOK); | |
1a4d82fc JJ |
1226 | } |
1227 | ||
0531ce1d | 1228 | /// This allows tools to enable rust logging without having to magically match rustc's |
3dfed10e | 1229 | /// tracing crate version. |
0531ce1d | 1230 | pub fn init_rustc_env_logger() { |
3dfed10e XL |
1231 | init_env_logger("RUSTC_LOG") |
1232 | } | |
1233 | ||
1234 | /// This allows tools to enable rust logging without having to magically match rustc's | |
1235 | /// tracing crate version. In contrast to `init_rustc_env_logger` it allows you to choose an env var | |
1236 | /// other than `RUSTC_LOG`. | |
1237 | pub fn init_env_logger(env: &str) { | |
1238 | // Don't register a dispatcher if there's no filter to print anything | |
1239 | match std::env::var(env) { | |
1240 | Err(_) => return, | |
1241 | Ok(s) if s.is_empty() => return, | |
1242 | Ok(_) => {} | |
1243 | } | |
1244 | let builder = tracing_subscriber::FmtSubscriber::builder(); | |
1245 | ||
1246 | let builder = builder.with_env_filter(tracing_subscriber::EnvFilter::from_env(env)); | |
1247 | ||
1248 | builder.init() | |
0531ce1d XL |
1249 | } |
1250 | ||
f9f354fc | 1251 | pub fn main() -> ! { |
416331ca | 1252 | let start = Instant::now(); |
0531ce1d | 1253 | init_rustc_env_logger(); |
416331ca | 1254 | let mut callbacks = TimePassesCallbacks::default(); |
e1599b0c | 1255 | install_ice_hook(); |
f9f354fc | 1256 | let exit_code = catch_with_exit_code(|| { |
dfeec247 XL |
1257 | let args = env::args_os() |
1258 | .enumerate() | |
1259 | .map(|(i, arg)| { | |
1260 | arg.into_string().unwrap_or_else(|arg| { | |
1261 | early_error( | |
1262 | ErrorOutputType::default(), | |
1263 | &format!("Argument {} is not valid Unicode: {:?}", i, arg), | |
1264 | ) | |
1265 | }) | |
1266 | }) | |
2c00a5a8 | 1267 | .collect::<Vec<_>>(); |
416331ca | 1268 | run_compiler(&args, &mut callbacks, None, None) |
f9f354fc | 1269 | }); |
416331ca | 1270 | // The extra `\t` is necessary to align this label with the others. |
416331ca | 1271 | print_time_passes_entry(callbacks.time_passes, "\ttotal", start.elapsed()); |
f9f354fc | 1272 | process::exit(exit_code) |
1a4d82fc | 1273 | } |