1 // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! The Rust compiler.
15 //! This API is completely unstable and subject to change.
17 #![crate_name = "rustc_driver"]
18 #![unstable(feature = "rustc_private", issue = "27812")]
19 #![crate_type = "dylib"]
20 #![crate_type = "rlib"]
21 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
22 html_favicon_url
= "https://doc.rust-lang.org/favicon.ico",
23 html_root_url
= "https://doc.rust-lang.org/nightly/")]
24 #![cfg_attr(not(stage0), deny(warnings))]
26 #![feature(box_syntax)]
27 #![cfg_attr(stage0, feature(dotdot_in_tuple_patterns))]
30 #![feature(rustc_diagnostic_macros)]
31 #![feature(rustc_private)]
32 #![feature(set_stdio)]
33 #![feature(staged_api)]
34 #![cfg_attr(stage0, feature(question_mark))]
39 extern crate graphviz
;
42 extern crate rustc_back
;
43 extern crate rustc_borrowck
;
44 extern crate rustc_const_eval
;
45 extern crate rustc_data_structures
;
46 extern crate rustc_errors
as errors
;
47 extern crate rustc_passes
;
48 extern crate rustc_lint
;
49 extern crate rustc_plugin
;
50 extern crate rustc_privacy
;
51 extern crate rustc_incremental
;
52 extern crate rustc_metadata
;
53 extern crate rustc_mir
;
54 extern crate rustc_resolve
;
55 extern crate rustc_save_analysis
;
56 extern crate rustc_trans
;
57 extern crate rustc_typeck
;
58 extern crate serialize
;
59 extern crate rustc_llvm
as llvm
;
64 extern crate syntax_ext
;
65 extern crate syntax_pos
;
67 use driver
::CompileController
;
68 use pretty
::{PpMode, UserIdentifiedItem}
;
70 use rustc_resolve
as resolve
;
71 use rustc_save_analysis
as save
;
72 use rustc_trans
::back
::link
;
73 use rustc_trans
::back
::write
::{create_target_machine, RELOC_MODEL_ARGS, CODE_GEN_MODEL_ARGS}
;
74 use rustc
::dep_graph
::DepGraph
;
75 use rustc
::session
::{self, config, Session, build_session, CompileResult}
;
76 use rustc
::session
::config
::{Input, PrintRequest, OutputType, ErrorOutputType}
;
77 use rustc
::session
::config
::nightly_options
;
78 use rustc
::session
::early_error
;
79 use rustc
::lint
::Lint
;
81 use rustc_metadata
::locator
;
82 use rustc_metadata
::cstore
::CStore
;
83 use rustc
::util
::common
::time
;
86 use std
::cmp
::Ordering
::Equal
;
87 use std
::default::Default
;
89 use std
::io
::{self, Read, Write}
;
90 use std
::iter
::repeat
;
91 use std
::path
::PathBuf
;
95 use std
::sync
::{Arc, Mutex}
;
98 use syntax
::{ast, json}
;
99 use syntax
::codemap
::{CodeMap, FileLoader, RealFileLoader}
;
100 use syntax
::feature_gate
::{GatedCfg, UnstableFeatures}
;
101 use syntax
::parse
::{self, PResult}
;
102 use syntax_pos
::MultiSpan
;
103 use errors
::emitter
::Emitter
;
110 pub mod target_features
;
111 mod derive_registrar
;
113 const BUG_REPORT_URL
: &'
static str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
117 fn abort_msg(err_count
: usize) -> String
{
119 0 => "aborting with no errors (maybe a bug?)".to_owned(),
120 1 => "aborting due to previous error".to_owned(),
121 e
=> format
!("aborting due to {} previous errors", e
),
125 pub fn abort_on_err
<T
>(result
: Result
<T
, usize>, sess
: &Session
) -> T
{
128 sess
.fatal(&abort_msg(err_count
));
134 pub fn run
<F
>(run_compiler
: F
) -> isize
135 where F
: FnOnce() -> (CompileResult
, Option
<Session
>) + Send
+ '
static
138 let (result
, session
) = run_compiler();
139 if let Err(err_count
) = result
{
142 Some(sess
) => sess
.fatal(&abort_msg(err_count
)),
145 errors
::emitter
::EmitterWriter
::stderr(errors
::ColorConfig
::Auto
, None
);
146 let handler
= errors
::Handler
::with_emitter(true, false, Box
::new(emitter
));
147 handler
.emit(&MultiSpan
::new(),
148 &abort_msg(err_count
),
149 errors
::Level
::Fatal
);
159 // Parse args and run the compiler. This is the primary entry point for rustc.
160 // See comments on CompilerCalls below for details about the callbacks argument.
161 // The FileLoader provides a way to load files from sources other than the file system.
162 pub fn run_compiler
<'a
>(args
: &[String
],
163 callbacks
: &mut CompilerCalls
<'a
>,
164 file_loader
: Option
<Box
<FileLoader
+ '
static>>,
165 emitter_dest
: Option
<Box
<Write
+ Send
>>)
166 -> (CompileResult
, Option
<Session
>)
168 macro_rules
! do_or_return
{($expr
: expr
, $sess
: expr
) => {
170 Compilation
::Stop
=> return (Ok(()), $sess
),
171 Compilation
::Continue
=> {}
175 let matches
= match handle_options(args
) {
176 Some(matches
) => matches
,
177 None
=> return (Ok(()), None
),
180 let (sopts
, cfg
) = config
::build_session_options_and_crate_config(&matches
);
182 if sopts
.debugging_opts
.debug_llvm
{
183 unsafe { llvm::LLVMRustSetDebug(1); }
186 let descriptions
= diagnostics_registry();
188 do_or_return
!(callbacks
.early_callback(&matches
,
195 let (odir
, ofile
) = make_output(&matches
);
196 let (input
, input_file_path
) = match make_input(&matches
.free
) {
197 Some((input
, input_file_path
)) => callbacks
.some_input(input
, input_file_path
),
198 None
=> match callbacks
.no_input(&matches
, &sopts
, &cfg
, &odir
, &ofile
, &descriptions
) {
199 Some((input
, input_file_path
)) => (input
, input_file_path
),
200 None
=> return (Ok(()), None
),
204 let dep_graph
= DepGraph
::new(sopts
.build_dep_graph());
205 let cstore
= Rc
::new(CStore
::new(&dep_graph
));
207 let loader
= file_loader
.unwrap_or(box RealFileLoader
);
208 let codemap
= Rc
::new(CodeMap
::with_file_loader(loader
));
209 let mut sess
= session
::build_session_with_codemap(
210 sopts
, &dep_graph
, input_file_path
, descriptions
, cstore
.clone(), codemap
, emitter_dest
,
212 rustc_lint
::register_builtins(&mut sess
.lint_store
.borrow_mut(), Some(&sess
));
214 let mut cfg
= config
::build_configuration(&sess
, cfg
);
215 target_features
::add_configuration(&mut cfg
, &sess
);
216 sess
.parse_sess
.config
= cfg
;
218 do_or_return
!(callbacks
.late_callback(&matches
, &sess
, &input
, &odir
, &ofile
), Some(sess
));
220 let plugins
= sess
.opts
.debugging_opts
.extra_plugins
.clone();
221 let control
= callbacks
.build_controller(&sess
, &matches
);
222 (driver
::compile_input(&sess
, &cstore
, &input
, &odir
, &ofile
, Some(plugins
), &control
),
226 // Extract output directory and file from matches.
227 fn make_output(matches
: &getopts
::Matches
) -> (Option
<PathBuf
>, Option
<PathBuf
>) {
228 let odir
= matches
.opt_str("out-dir").map(|o
| PathBuf
::from(&o
));
229 let ofile
= matches
.opt_str("o").map(|o
| PathBuf
::from(&o
));
233 // Extract input (string or file and optional path) from matches.
234 fn make_input(free_matches
: &[String
]) -> Option
<(Input
, Option
<PathBuf
>)> {
235 if free_matches
.len() == 1 {
236 let ifile
= &free_matches
[0][..];
238 let mut src
= String
::new();
239 io
::stdin().read_to_string(&mut src
).unwrap();
240 Some((Input
::Str { name: driver::anon_src(), input: src }
,
243 Some((Input
::File(PathBuf
::from(ifile
)),
244 Some(PathBuf
::from(ifile
))))
251 fn parse_pretty(sess
: &Session
,
252 matches
: &getopts
::Matches
)
253 -> Option
<(PpMode
, Option
<UserIdentifiedItem
>)> {
254 let pretty
= if sess
.opts
.debugging_opts
.unstable_options
{
255 matches
.opt_default("pretty", "normal").map(|a
| {
256 // stable pretty-print variants only
257 pretty
::parse_pretty(sess
, &a
, false)
262 if pretty
.is_none() && sess
.unstable_options() {
263 matches
.opt_str("unpretty").map(|a
| {
264 // extended with unstable pretty-print variants
265 pretty
::parse_pretty(sess
, &a
, true)
272 // Whether to stop or continue compilation.
273 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
274 pub enum Compilation
{
280 pub fn and_then
<F
: FnOnce() -> Compilation
>(self, next
: F
) -> Compilation
{
282 Compilation
::Stop
=> Compilation
::Stop
,
283 Compilation
::Continue
=> next(),
288 // A trait for customising the compilation process. Offers a number of hooks for
289 // executing custom code or customising input.
290 pub trait CompilerCalls
<'a
> {
291 // Hook for a callback early in the process of handling arguments. This will
292 // be called straight after options have been parsed but before anything
293 // else (e.g., selecting input and output).
294 fn early_callback(&mut self,
295 _
: &getopts
::Matches
,
297 _
: &ast
::CrateConfig
,
298 _
: &errors
::registry
::Registry
,
301 Compilation
::Continue
304 // Hook for a callback late in the process of handling arguments. This will
305 // be called just before actual compilation starts (and before build_controller
306 // is called), after all arguments etc. have been completely handled.
307 fn late_callback(&mut self,
308 _
: &getopts
::Matches
,
314 Compilation
::Continue
317 // Called after we extract the input from the arguments. Gives the implementer
318 // an opportunity to change the inputs or to add some custom input handling.
319 // The default behaviour is to simply pass through the inputs.
320 fn some_input(&mut self,
322 input_path
: Option
<PathBuf
>)
323 -> (Input
, Option
<PathBuf
>) {
327 // Called after we extract the input from the arguments if there is no valid
328 // input. Gives the implementer an opportunity to supply alternate input (by
329 // returning a Some value) or to add custom behaviour for this error such as
330 // emitting error messages. Returning None will cause compilation to stop
332 fn no_input(&mut self,
333 _
: &getopts
::Matches
,
335 _
: &ast
::CrateConfig
,
338 _
: &errors
::registry
::Registry
)
339 -> Option
<(Input
, Option
<PathBuf
>)> {
343 // Create a CompilController struct for controlling the behaviour of
345 fn build_controller(&mut self, &Session
, &getopts
::Matches
) -> CompileController
<'a
>;
348 // CompilerCalls instance for a regular rustc build.
349 #[derive(Copy, Clone)]
350 pub struct RustcDefaultCalls
;
352 fn handle_explain(code
: &str,
353 descriptions
: &errors
::registry
::Registry
,
354 output
: ErrorOutputType
) {
355 let normalised
= if code
.starts_with("E") {
358 format
!("E{0:0>4}", code
)
360 match descriptions
.find_description(&normalised
) {
361 Some(ref description
) => {
362 // Slice off the leading newline and print.
363 print
!("{}", &(&description
[1..]).split("\n").map(|x
| {
364 format
!("{}\n", if x
.starts_with("```") {
369 }).collect
::<String
>());
372 early_error(output
, &format
!("no extended information for {}", code
));
377 fn check_cfg(cfg
: &ast
::CrateConfig
,
378 output
: ErrorOutputType
) {
379 let emitter
: Box
<Emitter
> = match output
{
380 config
::ErrorOutputType
::HumanReadable(color_config
) => {
381 Box
::new(errors
::emitter
::EmitterWriter
::stderr(color_config
, None
))
383 config
::ErrorOutputType
::Json
=> Box
::new(json
::JsonEmitter
::basic()),
385 let handler
= errors
::Handler
::with_emitter(true, false, emitter
);
387 let mut saw_invalid_predicate
= false;
388 for item
in cfg
.iter() {
389 if item
.is_meta_item_list() {
390 saw_invalid_predicate
= true;
391 handler
.emit(&MultiSpan
::new(),
392 &format
!("invalid predicate in --cfg command line argument: `{}`",
394 errors
::Level
::Fatal
);
398 if saw_invalid_predicate
{
399 panic
!(errors
::FatalError
);
403 impl<'a
> CompilerCalls
<'a
> for RustcDefaultCalls
{
404 fn early_callback(&mut self,
405 matches
: &getopts
::Matches
,
407 cfg
: &ast
::CrateConfig
,
408 descriptions
: &errors
::registry
::Registry
,
409 output
: ErrorOutputType
)
411 if let Some(ref code
) = matches
.opt_str("explain") {
412 handle_explain(code
, descriptions
, output
);
413 return Compilation
::Stop
;
416 check_cfg(cfg
, output
);
417 Compilation
::Continue
420 fn no_input(&mut self,
421 matches
: &getopts
::Matches
,
422 sopts
: &config
::Options
,
423 cfg
: &ast
::CrateConfig
,
424 odir
: &Option
<PathBuf
>,
425 ofile
: &Option
<PathBuf
>,
426 descriptions
: &errors
::registry
::Registry
)
427 -> Option
<(Input
, Option
<PathBuf
>)> {
428 match matches
.free
.len() {
430 if sopts
.describe_lints
{
431 let mut ls
= lint
::LintStore
::new();
432 rustc_lint
::register_builtins(&mut ls
, None
);
433 describe_lints(&ls
, false);
436 let dep_graph
= DepGraph
::new(sopts
.build_dep_graph());
437 let cstore
= Rc
::new(CStore
::new(&dep_graph
));
438 let mut sess
= build_session(sopts
.clone(),
441 descriptions
.clone(),
443 rustc_lint
::register_builtins(&mut sess
.lint_store
.borrow_mut(), Some(&sess
));
444 let mut cfg
= config
::build_configuration(&sess
, cfg
.clone());
445 target_features
::add_configuration(&mut cfg
, &sess
);
446 sess
.parse_sess
.config
= cfg
;
448 RustcDefaultCalls
::print_crate_info(&sess
, None
, odir
, ofile
);
450 if should_stop
== Compilation
::Stop
{
453 early_error(sopts
.error_format
, "no input filename given");
455 1 => panic
!("make_input should have provided valid inputs"),
456 _
=> early_error(sopts
.error_format
, "multiple input filenames provided"),
462 fn late_callback(&mut self,
463 matches
: &getopts
::Matches
,
466 odir
: &Option
<PathBuf
>,
467 ofile
: &Option
<PathBuf
>)
469 RustcDefaultCalls
::print_crate_info(sess
, Some(input
), odir
, ofile
)
470 .and_then(|| RustcDefaultCalls
::list_metadata(sess
, matches
, input
))
473 fn build_controller(&mut self,
475 matches
: &getopts
::Matches
)
476 -> CompileController
<'a
> {
477 let mut control
= CompileController
::basic();
479 if let Some((ppm
, opt_uii
)) = parse_pretty(sess
, matches
) {
480 if ppm
.needs_ast_map(&opt_uii
) {
481 control
.after_hir_lowering
.stop
= Compilation
::Stop
;
483 control
.after_parse
.callback
= box move |state
| {
484 state
.krate
= Some(pretty
::fold_crate(state
.krate
.take().unwrap(), ppm
));
486 control
.after_hir_lowering
.callback
= box move |state
| {
487 pretty
::print_after_hir_lowering(state
.session
,
488 state
.ast_map
.unwrap(),
489 state
.analysis
.unwrap(),
490 state
.resolutions
.unwrap(),
492 &state
.expanded_crate
.take().unwrap(),
493 state
.crate_name
.unwrap(),
495 state
.arenas
.unwrap(),
500 control
.after_parse
.stop
= Compilation
::Stop
;
502 control
.after_parse
.callback
= box move |state
| {
503 let krate
= pretty
::fold_crate(state
.krate
.take().unwrap(), ppm
);
504 pretty
::print_after_parsing(state
.session
,
515 if sess
.opts
.debugging_opts
.parse_only
||
516 sess
.opts
.debugging_opts
.show_span
.is_some() ||
517 sess
.opts
.debugging_opts
.ast_json_noexpand
{
518 control
.after_parse
.stop
= Compilation
::Stop
;
521 if sess
.opts
.debugging_opts
.no_analysis
||
522 sess
.opts
.debugging_opts
.ast_json
{
523 control
.after_hir_lowering
.stop
= Compilation
::Stop
;
526 if !sess
.opts
.output_types
.keys().any(|&i
| i
== OutputType
::Exe
) {
527 control
.after_llvm
.stop
= Compilation
::Stop
;
530 if save_analysis(sess
) {
531 control
.after_analysis
.callback
= box |state
| {
532 time(state
.session
.time_passes(), "save analysis", || {
533 save
::process_crate(state
.tcx
.unwrap(),
534 state
.expanded_crate
.unwrap(),
535 state
.analysis
.unwrap(),
536 state
.crate_name
.unwrap(),
538 save_analysis_format(state
.session
))
541 control
.after_analysis
.run_callback_on_error
= true;
542 control
.make_glob_map
= resolve
::MakeGlobMap
::Yes
;
549 fn save_analysis(sess
: &Session
) -> bool
{
550 sess
.opts
.debugging_opts
.save_analysis
||
551 sess
.opts
.debugging_opts
.save_analysis_csv
||
552 sess
.opts
.debugging_opts
.save_analysis_api
555 fn save_analysis_format(sess
: &Session
) -> save
::Format
{
556 if sess
.opts
.debugging_opts
.save_analysis
{
558 } else if sess
.opts
.debugging_opts
.save_analysis_csv
{
560 } else if sess
.opts
.debugging_opts
.save_analysis_api
{
561 save
::Format
::JsonApi
567 impl RustcDefaultCalls
{
568 pub fn list_metadata(sess
: &Session
, matches
: &getopts
::Matches
, input
: &Input
) -> Compilation
{
569 let r
= matches
.opt_strs("Z");
570 if r
.contains(&("ls".to_string())) {
572 &Input
::File(ref ifile
) => {
573 let path
= &(*ifile
);
574 let mut v
= Vec
::new();
575 locator
::list_file_metadata(&sess
.target
.target
, path
, &mut v
).unwrap();
576 println
!("{}", String
::from_utf8(v
).unwrap());
578 &Input
::Str { .. }
=> {
579 early_error(ErrorOutputType
::default(), "cannot list metadata for stdin");
582 return Compilation
::Stop
;
585 return Compilation
::Continue
;
589 fn print_crate_info(sess
: &Session
,
590 input
: Option
<&Input
>,
591 odir
: &Option
<PathBuf
>,
592 ofile
: &Option
<PathBuf
>)
594 if sess
.opts
.prints
.is_empty() {
595 return Compilation
::Continue
;
598 let attrs
= match input
{
601 let result
= parse_crate_attrs(sess
, input
);
603 Ok(attrs
) => Some(attrs
),
604 Err(mut parse_error
) => {
606 return Compilation
::Stop
;
611 for req
in &sess
.opts
.prints
{
613 PrintRequest
::TargetList
=> {
614 let mut targets
= rustc_back
::target
::get_targets().collect
::<Vec
<String
>>();
616 println
!("{}", targets
.join("\n"));
618 PrintRequest
::Sysroot
=> println
!("{}", sess
.sysroot().display()),
619 PrintRequest
::FileNames
|
620 PrintRequest
::CrateName
=> {
621 let input
= match input
{
622 Some(input
) => input
,
623 None
=> early_error(ErrorOutputType
::default(), "no input file provided"),
625 let attrs
= attrs
.as_ref().unwrap();
626 let t_outputs
= driver
::build_output_filenames(input
, odir
, ofile
, attrs
, sess
);
627 let id
= link
::find_crate_name(Some(sess
), attrs
, input
);
628 if *req
== PrintRequest
::CrateName
{
632 let crate_types
= driver
::collect_crate_types(sess
, attrs
);
633 for &style
in &crate_types
{
634 let fname
= link
::filename_for_input(sess
, style
, &id
, &t_outputs
);
641 PrintRequest
::Cfg
=> {
642 let allow_unstable_cfg
= UnstableFeatures
::from_environment()
645 for cfg
in &sess
.parse_sess
.config
{
646 if !allow_unstable_cfg
&& GatedCfg
::gate(cfg
).is_some() {
651 println
!("{}", cfg
.name());
652 } else if let Some(s
) = cfg
.value_str() {
653 println
!("{}=\"{}\"", cfg
.name(), s
);
654 } else if cfg
.is_meta_item_list() {
655 // Right now there are not and should not be any
656 // MetaItemKind::List items in the configuration returned by
657 // `build_configuration`.
658 panic
!("Found an unexpected list in cfg attribute '{}'!", cfg
.name())
660 // There also shouldn't be literals.
661 panic
!("Found an unexpected literal in cfg attribute '{}'!", cfg
.name())
665 PrintRequest
::TargetCPUs
=> {
666 let tm
= create_target_machine(sess
);
667 unsafe { llvm::LLVMRustPrintTargetCPUs(tm); }
669 PrintRequest
::TargetFeatures
=> {
670 let tm
= create_target_machine(sess
);
671 unsafe { llvm::LLVMRustPrintTargetFeatures(tm); }
673 PrintRequest
::RelocationModels
=> {
674 println
!("Available relocation models:");
675 for &(name
, _
) in RELOC_MODEL_ARGS
.iter() {
676 println
!(" {}", name
);
680 PrintRequest
::CodeModels
=> {
681 println
!("Available code models:");
682 for &(name
, _
) in CODE_GEN_MODEL_ARGS
.iter(){
683 println
!(" {}", name
);
689 return Compilation
::Stop
;
693 /// Returns a version string such as "0.12.0-dev".
694 pub fn release_str() -> Option
<&'
static str> {
695 option_env
!("CFG_RELEASE")
698 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
699 pub fn commit_hash_str() -> Option
<&'
static str> {
700 option_env
!("CFG_VER_HASH")
703 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
704 pub fn commit_date_str() -> Option
<&'
static str> {
705 option_env
!("CFG_VER_DATE")
708 /// Prints version information
709 pub fn version(binary
: &str, matches
: &getopts
::Matches
) {
710 let verbose
= matches
.opt_present("verbose");
714 option_env
!("CFG_VERSION").unwrap_or("unknown version"));
716 fn unw(x
: Option
<&str>) -> &str {
717 x
.unwrap_or("unknown")
719 println
!("binary: {}", binary
);
720 println
!("commit-hash: {}", unw(commit_hash_str()));
721 println
!("commit-date: {}", unw(commit_date_str()));
722 println
!("host: {}", config
::host_triple());
723 println
!("release: {}", unw(release_str()));
725 println
!("LLVM version: {}.{}",
726 llvm
::LLVMRustVersionMajor(), llvm
::LLVMRustVersionMinor());
731 fn usage(verbose
: bool
, include_unstable_options
: bool
) {
732 let groups
= if verbose
{
733 config
::rustc_optgroups()
735 config
::rustc_short_optgroups()
737 let groups
: Vec
<_
> = groups
.into_iter()
738 .filter(|x
| include_unstable_options
|| x
.is_stable())
739 .map(|x
| x
.opt_group
)
741 let message
= format
!("Usage: rustc [OPTIONS] INPUT");
742 let extra_help
= if verbose
{
745 "\n --help -v Print the full set of options rustc accepts"
747 println
!("{}\nAdditional help:
748 -C help Print codegen options
750 Print 'lint' options and default settings
751 -Z help Print internal \
752 options for debugging rustc{}\n",
753 getopts
::usage(&message
, &groups
),
757 fn describe_lints(lint_store
: &lint
::LintStore
, loaded_plugins
: bool
) {
759 Available lint options:
760 -W <foo> Warn about <foo>
764 -F <foo> Forbid <foo> \
765 (deny, and deny all overrides)
769 fn sort_lints(lints
: Vec
<(&'
static Lint
, bool
)>) -> Vec
<&'
static Lint
> {
770 let mut lints
: Vec
<_
> = lints
.into_iter().map(|(x
, _
)| x
).collect();
771 lints
.sort_by(|x
: &&Lint
, y
: &&Lint
| {
772 match x
.default_level
.cmp(&y
.default_level
) {
773 // The sort doesn't case-fold but it's doubtful we care.
774 Equal
=> x
.name
.cmp(y
.name
),
781 fn sort_lint_groups(lints
: Vec
<(&'
static str, Vec
<lint
::LintId
>, bool
)>)
782 -> Vec
<(&'
static str, Vec
<lint
::LintId
>)> {
783 let mut lints
: Vec
<_
> = lints
.into_iter().map(|(x
, y
, _
)| (x
, y
)).collect();
784 lints
.sort_by(|&(x
, _
): &(&'
static str, Vec
<lint
::LintId
>),
785 &(y
, _
): &(&'
static str, Vec
<lint
::LintId
>)| {
791 let (plugin
, builtin
): (Vec
<_
>, _
) = lint_store
.get_lints()
794 .partition(|&(_
, p
)| p
);
795 let plugin
= sort_lints(plugin
);
796 let builtin
= sort_lints(builtin
);
798 let (plugin_groups
, builtin_groups
): (Vec
<_
>, _
) = lint_store
.get_lint_groups()
801 .partition(|&(.., p
)| p
);
802 let plugin_groups
= sort_lint_groups(plugin_groups
);
803 let builtin_groups
= sort_lint_groups(builtin_groups
);
805 let max_name_len
= plugin
.iter()
807 .map(|&s
| s
.name
.chars().count())
810 let padded
= |x
: &str| {
811 let mut s
= repeat(" ")
812 .take(max_name_len
- x
.chars().count())
813 .collect
::<String
>();
818 println
!("Lint checks provided by rustc:\n");
819 println
!(" {} {:7.7} {}", padded("name"), "default", "meaning");
820 println
!(" {} {:7.7} {}", padded("----"), "-------", "-------");
822 let print_lints
= |lints
: Vec
<&Lint
>| {
824 let name
= lint
.name_lower().replace("_", "-");
825 println
!(" {} {:7.7} {}",
827 lint
.default_level
.as_str(),
833 print_lints(builtin
);
837 let max_name_len
= max("warnings".len(),
839 .chain(&builtin_groups
)
840 .map(|&(s
, _
)| s
.chars().count())
844 let padded
= |x
: &str| {
845 let mut s
= repeat(" ")
846 .take(max_name_len
- x
.chars().count())
847 .collect
::<String
>();
852 println
!("Lint groups provided by rustc:\n");
853 println
!(" {} {}", padded("name"), "sub-lints");
854 println
!(" {} {}", padded("----"), "---------");
855 println
!(" {} {}", padded("warnings"), "all built-in lints");
857 let print_lint_groups
= |lints
: Vec
<(&'
static str, Vec
<lint
::LintId
>)>| {
858 for (name
, to
) in lints
{
859 let name
= name
.to_lowercase().replace("_", "-");
860 let desc
= to
.into_iter()
861 .map(|x
| x
.to_string().replace("_", "-"))
862 .collect
::<Vec
<String
>>()
864 println
!(" {} {}", padded(&name
[..]), desc
);
869 print_lint_groups(builtin_groups
);
871 match (loaded_plugins
, plugin
.len(), plugin_groups
.len()) {
872 (false, 0, _
) | (false, _
, 0) => {
873 println
!("Compiler plugins can provide additional lints and lint groups. To see a \
874 listing of these, re-run `rustc -W help` with a crate filename.");
876 (false, ..) => panic
!("didn't load lint plugins but got them anyway!"),
877 (true, 0, 0) => println
!("This crate does not load any lint plugins or lint groups."),
880 println
!("Lint checks provided by plugins loaded by this crate:\n");
884 println
!("Lint groups provided by plugins loaded by this crate:\n");
885 print_lint_groups(plugin_groups
);
891 fn describe_debug_flags() {
892 println
!("\nAvailable debug options:\n");
893 print_flag_list("-Z", config
::DB_OPTIONS
);
896 fn describe_codegen_flags() {
897 println
!("\nAvailable codegen options:\n");
898 print_flag_list("-C", config
::CG_OPTIONS
);
901 fn print_flag_list
<T
>(cmdline_opt
: &str,
902 flag_list
: &[(&'
static str, T
, Option
<&'
static str>, &'
static str)]) {
903 let max_len
= flag_list
.iter()
904 .map(|&(name
, _
, opt_type_desc
, _
)| {
905 let extra_len
= match opt_type_desc
{
909 name
.chars().count() + extra_len
914 for &(name
, _
, opt_type_desc
, desc
) in flag_list
{
915 let (width
, extra
) = match opt_type_desc
{
916 Some(..) => (max_len
- 4, "=val"),
917 None
=> (max_len
, ""),
919 println
!(" {} {:>width$}{} -- {}",
921 name
.replace("_", "-"),
928 /// Process command line options. Emits messages as appropriate. If compilation
929 /// should continue, returns a getopts::Matches object parsed from args,
930 /// otherwise returns None.
932 /// The compiler's handling of options is a little complication as it ties into
933 /// our stability story, and it's even *more* complicated by historical
934 /// accidents. The current intention of each compiler option is to have one of
937 /// 1. An option is stable and can be used everywhere.
938 /// 2. An option is unstable, but was historically allowed on the stable
940 /// 3. An option is unstable, and can only be used on nightly.
942 /// Like unstable library and language features, however, unstable options have
943 /// always required a form of "opt in" to indicate that you're using them. This
944 /// provides the easy ability to scan a code base to check to see if anything
945 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
947 /// All options behind `-Z` are considered unstable by default. Other top-level
948 /// options can also be considered unstable, and they were unlocked through the
949 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
950 /// instability in both cases, though.
952 /// So with all that in mind, the comments below have some more detail about the
953 /// contortions done here to get things to work out correctly.
954 pub fn handle_options(args
: &[String
]) -> Option
<getopts
::Matches
> {
955 // Throw away the first argument, the name of the binary
956 let args
= &args
[1..];
959 // user did not write `-v` nor `-Z unstable-options`, so do not
960 // include that extra information.
965 // Parse with *all* options defined in the compiler, we don't worry about
966 // option stability here we just want to parse as much as possible.
967 let all_groups
: Vec
<getopts
::OptGroup
> = config
::rustc_optgroups()
969 .map(|x
| x
.opt_group
)
971 let matches
= match getopts
::getopts(&args
[..], &all_groups
) {
973 Err(f
) => early_error(ErrorOutputType
::default(), &f
.to_string()),
976 // For all options we just parsed, we check a few aspects:
978 // * If the option is stable, we're all good
979 // * If the option wasn't passed, we're all good
980 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
981 // ourselves), then we require the `-Z unstable-options` flag to unlock
982 // this option that was passed.
983 // * If we're a nightly compiler, then unstable options are now unlocked, so
985 // * Otherwise, if we're a truly unstable option then we generate an error
986 // (unstable option being used on stable)
987 // * If we're a historically stable-but-should-be-unstable option then we
988 // emit a warning that we're going to turn this into an error soon.
989 nightly_options
::check_nightly_options(&matches
, &config
::rustc_optgroups());
991 if matches
.opt_present("h") || matches
.opt_present("help") {
992 // Only show unstable options in --help if we *really* accept unstable
993 // options, which catches the case where we got `-Z unstable-options` on
994 // the stable channel of Rust which was accidentally allowed
996 usage(matches
.opt_present("verbose"),
997 nightly_options
::is_unstable_enabled(&matches
));
1001 // Don't handle -W help here, because we might first load plugins.
1002 let r
= matches
.opt_strs("Z");
1003 if r
.iter().any(|x
| *x
== "help") {
1004 describe_debug_flags();
1008 let cg_flags
= matches
.opt_strs("C");
1009 if cg_flags
.iter().any(|x
| *x
== "help") {
1010 describe_codegen_flags();
1014 if cg_flags
.contains(&"passes=list".to_string()) {
1016 ::llvm
::LLVMRustPrintPasses();
1021 if matches
.opt_present("version") {
1022 version("rustc", &matches
);
1029 fn parse_crate_attrs
<'a
>(sess
: &'a Session
, input
: &Input
) -> PResult
<'a
, Vec
<ast
::Attribute
>> {
1031 Input
::File(ref ifile
) => {
1032 parse
::parse_crate_attrs_from_file(ifile
, &sess
.parse_sess
)
1034 Input
::Str { ref name, ref input }
=> {
1035 parse
::parse_crate_attrs_from_source_str(name
.clone(), input
.clone(), &sess
.parse_sess
)
1040 /// Run a procedure which will detect panics in the compiler and print nicer
1041 /// error messages rather than just failing the test.
1043 /// The diagnostic emitter yielded to the procedure should be used for reporting
1044 /// errors of the compiler.
1045 pub fn monitor
<F
: FnOnce() + Send
+ '
static>(f
: F
) {
1046 // Temporarily have stack size set to 16MB to deal with nom-using crates failing
1047 const STACK_SIZE
: usize = 16 * 1024 * 1024; // 16MB
1049 struct Sink(Arc
<Mutex
<Vec
<u8>>>);
1050 impl Write
for Sink
{
1051 fn write(&mut self, data
: &[u8]) -> io
::Result
<usize> {
1052 Write
::write(&mut *self.0.lock().unwrap(), data
)
1054 fn flush(&mut self) -> io
::Result
<()> {
1059 let data
= Arc
::new(Mutex
::new(Vec
::new()));
1060 let err
= Sink(data
.clone());
1062 let mut cfg
= thread
::Builder
::new().name("rustc".to_string());
1064 // FIXME: Hacks on hacks. If the env is trying to override the stack size
1065 // then *don't* set it explicitly.
1066 if env
::var_os("RUST_MIN_STACK").is_none() {
1067 cfg
= cfg
.stack_size(STACK_SIZE
);
1070 let thread
= cfg
.spawn(move || {
1071 io
::set_panic(Some(box err
));
1075 if let Err(value
) = thread
.unwrap().join() {
1076 // Thread panicked without emitting a fatal diagnostic
1077 if !value
.is
::<errors
::FatalError
>() {
1079 Box
::new(errors
::emitter
::EmitterWriter
::stderr(errors
::ColorConfig
::Auto
, None
));
1080 let handler
= errors
::Handler
::with_emitter(true, false, emitter
);
1082 // a .span_bug or .bug call has already printed what
1083 // it wants to print.
1084 if !value
.is
::<errors
::ExplicitBug
>() {
1085 handler
.emit(&MultiSpan
::new(),
1087 errors
::Level
::Bug
);
1090 let xs
= ["the compiler unexpectedly panicked. this is a bug.".to_string(),
1091 format
!("we would appreciate a bug report: {}", BUG_REPORT_URL
)];
1093 handler
.emit(&MultiSpan
::new(),
1095 errors
::Level
::Note
);
1097 if match env
::var_os("RUST_BACKTRACE") {
1098 Some(val
) => &val
!= "0",
1101 handler
.emit(&MultiSpan
::new(),
1102 "run with `RUST_BACKTRACE=1` for a backtrace",
1103 errors
::Level
::Note
);
1106 writeln
!(io
::stderr(), "{}", str::from_utf8(&data
.lock().unwrap()).unwrap()).unwrap();
1113 fn exit_on_err() -> ! {
1114 // Panic so the process returns a failure code, but don't pollute the
1115 // output with some unnecessary panic messages, we've already
1116 // printed everything that we needed to.
1117 io
::set_panic(Some(box io
::sink()));
1121 pub fn diagnostics_registry() -> errors
::registry
::Registry
{
1122 use errors
::registry
::Registry
;
1124 let mut all_errors
= Vec
::new();
1125 all_errors
.extend_from_slice(&rustc
::DIAGNOSTICS
);
1126 all_errors
.extend_from_slice(&rustc_typeck
::DIAGNOSTICS
);
1127 all_errors
.extend_from_slice(&rustc_borrowck
::DIAGNOSTICS
);
1128 all_errors
.extend_from_slice(&rustc_resolve
::DIAGNOSTICS
);
1129 all_errors
.extend_from_slice(&rustc_privacy
::DIAGNOSTICS
);
1130 all_errors
.extend_from_slice(&rustc_trans
::DIAGNOSTICS
);
1131 all_errors
.extend_from_slice(&rustc_const_eval
::DIAGNOSTICS
);
1132 all_errors
.extend_from_slice(&rustc_metadata
::DIAGNOSTICS
);
1134 Registry
::new(&all_errors
)
1138 let result
= run(|| run_compiler(&env
::args().collect
::<Vec
<_
>>(),
1139 &mut RustcDefaultCalls
,
1142 process
::exit(result
as i32);