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