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