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