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