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 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
18 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
19 html_root_url = "https://doc.rust-lang.org/nightly/")]
22 #![feature(box_syntax)]
23 #![cfg_attr(unix, feature(libc))]
25 #![feature(rustc_diagnostic_macros)]
26 #![feature(set_stdio)]
30 extern crate graphviz;
31 extern crate env_logger;
35 extern crate rustc_allocator;
36 extern crate rustc_back;
37 extern crate rustc_borrowck;
38 extern crate rustc_const_eval;
39 extern crate rustc_data_structures;
40 extern crate rustc_errors as errors;
41 extern crate rustc_passes;
42 extern crate rustc_lint;
43 extern crate rustc_plugin;
44 extern crate rustc_privacy;
45 extern crate rustc_incremental;
46 extern crate rustc_metadata;
47 extern crate rustc_mir;
48 extern crate rustc_resolve;
49 extern crate rustc_save_analysis;
50 #[cfg(feature="llvm")]
51 extern crate rustc_trans;
52 extern crate rustc_trans_utils;
53 extern crate rustc_typeck;
54 extern crate serialize;
58 extern crate syntax_ext;
59 extern crate syntax_pos;
61 use driver::CompileController;
62 use pretty::{PpMode, UserIdentifiedItem};
64 use rustc_resolve as resolve;
65 use rustc_save_analysis as save;
66 use rustc_save_analysis::DumpHandler;
67 use rustc::session::{self, config, Session, build_session, CompileResult};
68 use rustc::session::CompileIncomplete;
69 use rustc::session::config::{Input, PrintRequest, OutputType, ErrorOutputType};
70 use rustc::session::config::nightly_options;
71 use rustc::session::{early_error, early_warn};
72 use rustc::lint::Lint;
74 use rustc::middle::cstore::CrateStore;
75 use rustc_metadata::locator;
76 use rustc_metadata::cstore::CStore;
77 use rustc::util::common::{time, ErrorReported};
79 use serialize::json::ToJson;
83 use std::cmp::Ordering::Equal;
84 use std::default::Default;
86 use std::ffi::OsString;
87 use std::io::{self, Read, Write};
88 use std::iter::repeat;
89 use std::path::PathBuf;
90 use std::process::{self, Command, Stdio};
93 use std::sync::{Arc, Mutex};
97 use syntax::codemap::{CodeMap, FileLoader, RealFileLoader};
98 use syntax::feature_gate::{GatedCfg, UnstableFeatures};
99 use syntax::parse::{self, PResult};
100 use syntax_pos::{DUMMY_SP, MultiSpan};
108 pub mod target_features;
109 mod derive_registrar;
111 const BUG_REPORT_URL: &'static str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
114 pub fn abort_on_err<T>(result: Result<T, CompileIncomplete>, sess: &Session) -> T {
116 Err(CompileIncomplete::Errored(ErrorReported)) => {
117 sess.abort_if_errors();
118 panic!("error reported but abort_if_errors didn't abort???");
120 Err(CompileIncomplete::Stopped) => {
121 sess.fatal("compilation terminated");
127 pub fn run<F>(run_compiler: F) -> isize
128 where F: FnOnce() -> (CompileResult, Option<Session>) + Send + 'static
131 let (result, session) = run_compiler();
132 if let Err(CompileIncomplete::Errored(_)) = result {
135 sess.abort_if_errors();
136 panic!("error reported but abort_if_errors didn't abort???");
140 errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto, None);
141 let handler = errors::Handler::with_emitter(true, false, Box::new(emitter));
142 handler.emit(&MultiSpan::new(),
143 "aborting due to previous error(s)",
144 errors::Level::Fatal);
153 #[cfg(not(feature="llvm"))]
154 pub use no_llvm_metadata_loader::NoLLvmMetadataLoader as MetadataLoader;
155 #[cfg(feature="llvm")]
156 pub use rustc_trans::LlvmMetadataLoader as MetadataLoader;
158 #[cfg(not(feature="llvm"))]
159 mod no_llvm_metadata_loader {
161 extern crate owning_ref;
163 use rustc::middle::cstore::MetadataLoader as MetadataLoaderTrait;
164 use rustc_back::target::Target;
169 use self::ar::Archive;
170 use self::owning_ref::{OwningRef, ErasedBoxRef};
172 pub struct NoLLvmMetadataLoader;
174 impl MetadataLoaderTrait for NoLLvmMetadataLoader {
175 fn get_rlib_metadata(
179 ) -> Result<ErasedBoxRef<[u8]>, String> {
180 let file = File::open(filename).map_err(|e| {
181 format!("metadata file open err: {:?}", e)
183 let mut archive = Archive::new(file);
185 while let Some(entry_result) = archive.next_entry() {
186 let mut entry = entry_result.map_err(|e| {
187 format!("metadata section read err: {:?}", e)
189 if entry.header().identifier() == "rust.metadata.bin" {
190 let mut buf = Vec::new();
191 io::copy(&mut entry, &mut buf).unwrap();
192 let buf: OwningRef<Vec<u8>, [u8]> = OwningRef::new(buf).into();
193 return Ok(buf.map_owner_box().erase_owner());
197 Err("Couldnt find metadata section".to_string())
200 fn get_dylib_metadata(&self,
203 -> Result<ErasedBoxRef<[u8]>, String> {
204 panic!("Dylib metadata loading not supported without LLVM")
209 #[cfg(not(feature="llvm"))]
211 use syntax_pos::symbol::Symbol;
212 use rustc::session::Session;
213 use rustc::session::config::{PrintRequest, OutputFilenames};
214 use rustc::ty::{TyCtxt, CrateAnalysis};
215 use rustc::ty::maps::Providers;
216 use rustc_incremental::IncrementalHashesMap;
218 use self::back::write::OngoingCrateTranslation;
220 pub fn init(_sess: &Session) {}
221 pub fn enable_llvm_debug() {}
222 pub fn provide(_providers: &mut Providers) {}
223 pub fn print_version() {}
224 pub fn print_passes() {}
225 pub fn print(_req: PrintRequest, _sess: &Session) {}
226 pub fn target_features(_sess: &Session) -> Vec<Symbol> { vec![] }
228 pub fn trans_crate<'a, 'tcx>(
229 _tcx: TyCtxt<'a, 'tcx, 'tcx>,
230 _analysis: CrateAnalysis,
231 _incr_hashes_map: IncrementalHashesMap,
232 _output_filenames: &OutputFilenames
233 ) -> OngoingCrateTranslation {
234 OngoingCrateTranslation(())
237 pub struct CrateTranslation(());
241 pub struct OngoingCrateTranslation(pub (in ::rustc_trans) ());
243 pub const RELOC_MODEL_ARGS: [(&'static str, ()); 0] = [];
244 pub const CODE_GEN_MODEL_ARGS: [(&'static str, ()); 0] = [];
248 __build_diagnostic_array! { librustc_trans, DIAGNOSTICS }
251 // Parse args and run the compiler. This is the primary entry point for rustc.
252 // See comments on CompilerCalls below for details about the callbacks argument.
253 // The FileLoader provides a way to load files from sources other than the file system.
254 pub fn run_compiler<'a>(args: &[String],
255 callbacks: &mut CompilerCalls<'a>,
256 file_loader: Option<Box<FileLoader + 'static>>,
257 emitter_dest: Option<Box<Write + Send>>)
258 -> (CompileResult, Option<Session>)
260 macro_rules! do_or_return {($expr: expr, $sess: expr) => {
262 Compilation::Stop => return (Ok(()), $sess),
263 Compilation::Continue => {}
267 let matches = match handle_options(args) {
268 Some(matches) => matches,
269 None => return (Ok(()), None),
272 let (sopts, cfg) = config::build_session_options_and_crate_config(&matches);
274 if sopts.debugging_opts.debug_llvm {
275 rustc_trans::enable_llvm_debug();
278 let descriptions = diagnostics_registry();
280 do_or_return!(callbacks.early_callback(&matches,
287 let (odir, ofile) = make_output(&matches);
288 let (input, input_file_path) = match make_input(&matches.free) {
289 Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
290 None => match callbacks.no_input(&matches, &sopts, &cfg, &odir, &ofile, &descriptions) {
291 Some((input, input_file_path)) => (input, input_file_path),
292 None => return (Ok(()), None),
296 let cstore = Rc::new(CStore::new(box ::MetadataLoader));
298 let loader = file_loader.unwrap_or(box RealFileLoader);
299 let codemap = Rc::new(CodeMap::with_file_loader(loader, sopts.file_path_mapping()));
300 let mut sess = session::build_session_with_codemap(
301 sopts, input_file_path, descriptions, codemap, emitter_dest,
303 rustc_trans::init(&sess);
304 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
306 let mut cfg = config::build_configuration(&sess, cfg);
307 target_features::add_configuration(&mut cfg, &sess);
308 sess.parse_sess.config = cfg;
310 do_or_return!(callbacks.late_callback(&matches,
315 &ofile), Some(sess));
317 let plugins = sess.opts.debugging_opts.extra_plugins.clone();
318 let control = callbacks.build_controller(&sess, &matches);
319 (driver::compile_input(&sess,
329 // Extract output directory and file from matches.
330 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
331 let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
332 let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
336 // Extract input (string or file and optional path) from matches.
337 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
338 if free_matches.len() == 1 {
339 let ifile = &free_matches[0];
341 let mut src = String::new();
342 io::stdin().read_to_string(&mut src).unwrap();
343 Some((Input::Str { name: driver::anon_src(), input: src },
346 Some((Input::File(PathBuf::from(ifile)),
347 Some(PathBuf::from(ifile))))
354 fn parse_pretty(sess: &Session,
355 matches: &getopts::Matches)
356 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
357 let pretty = if sess.opts.debugging_opts.unstable_options {
358 matches.opt_default("pretty", "normal").map(|a| {
359 // stable pretty-print variants only
360 pretty::parse_pretty(sess, &a, false)
365 if pretty.is_none() && sess.unstable_options() {
366 matches.opt_str("unpretty").map(|a| {
367 // extended with unstable pretty-print variants
368 pretty::parse_pretty(sess, &a, true)
375 // Whether to stop or continue compilation.
376 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
377 pub enum Compilation {
383 pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
385 Compilation::Stop => Compilation::Stop,
386 Compilation::Continue => next(),
391 // A trait for customising the compilation process. Offers a number of hooks for
392 // executing custom code or customising input.
393 pub trait CompilerCalls<'a> {
394 // Hook for a callback early in the process of handling arguments. This will
395 // be called straight after options have been parsed but before anything
396 // else (e.g., selecting input and output).
397 fn early_callback(&mut self,
398 _: &getopts::Matches,
400 _: &ast::CrateConfig,
401 _: &errors::registry::Registry,
404 Compilation::Continue
407 // Hook for a callback late in the process of handling arguments. This will
408 // be called just before actual compilation starts (and before build_controller
409 // is called), after all arguments etc. have been completely handled.
410 fn late_callback(&mut self,
411 _: &getopts::Matches,
418 Compilation::Continue
421 // Called after we extract the input from the arguments. Gives the implementer
422 // an opportunity to change the inputs or to add some custom input handling.
423 // The default behaviour is to simply pass through the inputs.
424 fn some_input(&mut self,
426 input_path: Option<PathBuf>)
427 -> (Input, Option<PathBuf>) {
431 // Called after we extract the input from the arguments if there is no valid
432 // input. Gives the implementer an opportunity to supply alternate input (by
433 // returning a Some value) or to add custom behaviour for this error such as
434 // emitting error messages. Returning None will cause compilation to stop
436 fn no_input(&mut self,
437 _: &getopts::Matches,
439 _: &ast::CrateConfig,
442 _: &errors::registry::Registry)
443 -> Option<(Input, Option<PathBuf>)> {
447 // Create a CompilController struct for controlling the behaviour of
449 fn build_controller(&mut self, _: &Session, _: &getopts::Matches) -> CompileController<'a>;
452 // CompilerCalls instance for a regular rustc build.
453 #[derive(Copy, Clone)]
454 pub struct RustcDefaultCalls;
456 // FIXME remove these and use winapi 0.3 instead
457 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
459 fn stdout_isatty() -> bool {
460 unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
464 fn stdout_isatty() -> bool {
467 type HANDLE = *mut u8;
468 type LPDWORD = *mut u32;
469 const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
471 fn GetStdHandle(which: DWORD) -> HANDLE;
472 fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL;
475 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
477 GetConsoleMode(handle, &mut out) != 0
481 fn handle_explain(code: &str,
482 descriptions: &errors::registry::Registry,
483 output: ErrorOutputType) {
484 let normalised = if code.starts_with("E") {
487 format!("E{0:0>4}", code)
489 match descriptions.find_description(&normalised) {
490 Some(ref description) => {
491 let mut is_in_code_block = false;
492 let mut text = String::new();
494 // Slice off the leading newline and print.
495 for line in description[1..].lines() {
496 let indent_level = line.find(|c: char| !c.is_whitespace())
497 .unwrap_or_else(|| line.len());
498 let dedented_line = &line[indent_level..];
499 if dedented_line.starts_with("```") {
500 is_in_code_block = !is_in_code_block;
501 text.push_str(&line[..(indent_level+3)]);
502 } else if is_in_code_block && dedented_line.starts_with("# ") {
511 show_content_with_pager(&text);
517 early_error(output, &format!("no extended information for {}", code));
522 fn show_content_with_pager(content: &String) {
523 let pager_name = env::var_os("PAGER").unwrap_or_else(|| if cfg!(windows) {
524 OsString::from("more.com")
526 OsString::from("less")
529 let mut fallback_to_println = false;
531 match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
533 if let Some(pipe) = pager.stdin.as_mut() {
534 if pipe.write_all(content.as_bytes()).is_err() {
535 fallback_to_println = true;
539 if pager.wait().is_err() {
540 fallback_to_println = true;
544 fallback_to_println = true;
548 // If pager fails for whatever reason, we should still print the content
549 // to standard output
550 if fallback_to_println {
551 print!("{}", content);
555 impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
556 fn early_callback(&mut self,
557 matches: &getopts::Matches,
559 _: &ast::CrateConfig,
560 descriptions: &errors::registry::Registry,
561 output: ErrorOutputType)
563 if let Some(ref code) = matches.opt_str("explain") {
564 handle_explain(code, descriptions, output);
565 return Compilation::Stop;
568 Compilation::Continue
571 fn no_input(&mut self,
572 matches: &getopts::Matches,
573 sopts: &config::Options,
574 cfg: &ast::CrateConfig,
575 odir: &Option<PathBuf>,
576 ofile: &Option<PathBuf>,
577 descriptions: &errors::registry::Registry)
578 -> Option<(Input, Option<PathBuf>)> {
579 match matches.free.len() {
581 if sopts.describe_lints {
582 let mut ls = lint::LintStore::new();
583 rustc_lint::register_builtins(&mut ls, None);
584 describe_lints(&ls, false);
587 let mut sess = build_session(sopts.clone(),
589 descriptions.clone());
590 rustc_trans::init(&sess);
591 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
592 let mut cfg = config::build_configuration(&sess, cfg.clone());
593 target_features::add_configuration(&mut cfg, &sess);
594 sess.parse_sess.config = cfg;
596 RustcDefaultCalls::print_crate_info(&sess, None, odir, ofile);
598 if should_stop == Compilation::Stop {
601 early_error(sopts.error_format, "no input filename given");
603 1 => panic!("make_input should have provided valid inputs"),
604 _ => early_error(sopts.error_format, "multiple input filenames provided"),
608 fn late_callback(&mut self,
609 matches: &getopts::Matches,
613 odir: &Option<PathBuf>,
614 ofile: &Option<PathBuf>)
616 RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile)
617 .and_then(|| RustcDefaultCalls::list_metadata(sess, cstore, matches, input))
620 fn build_controller(&mut self,
622 matches: &getopts::Matches)
623 -> CompileController<'a> {
624 let mut control = CompileController::basic();
626 control.keep_ast = sess.opts.debugging_opts.keep_ast;
627 control.continue_parse_after_error = sess.opts.debugging_opts.continue_parse_after_error;
629 if let Some((ppm, opt_uii)) = parse_pretty(sess, matches) {
630 if ppm.needs_ast_map(&opt_uii) {
631 control.after_hir_lowering.stop = Compilation::Stop;
633 control.after_parse.callback = box move |state| {
634 state.krate = Some(pretty::fold_crate(state.krate.take().unwrap(), ppm));
636 control.after_hir_lowering.callback = box move |state| {
637 pretty::print_after_hir_lowering(state.session,
638 state.cstore.unwrap(),
639 state.hir_map.unwrap(),
640 state.analysis.unwrap(),
641 state.resolutions.unwrap(),
643 &state.expanded_crate.take().unwrap(),
644 state.crate_name.unwrap(),
646 state.arena.unwrap(),
647 state.arenas.unwrap(),
648 state.output_filenames.unwrap(),
653 control.after_parse.stop = Compilation::Stop;
655 control.after_parse.callback = box move |state| {
656 let krate = pretty::fold_crate(state.krate.take().unwrap(), ppm);
657 pretty::print_after_parsing(state.session,
668 if sess.opts.debugging_opts.parse_only ||
669 sess.opts.debugging_opts.show_span.is_some() ||
670 sess.opts.debugging_opts.ast_json_noexpand {
671 control.after_parse.stop = Compilation::Stop;
674 if sess.opts.debugging_opts.no_analysis ||
675 sess.opts.debugging_opts.ast_json {
676 control.after_hir_lowering.stop = Compilation::Stop;
679 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
680 i == OutputType::Metadata) {
681 control.after_llvm.stop = Compilation::Stop;
684 if save_analysis(sess) {
685 enable_save_analysis(&mut control);
688 if sess.print_fuel_crate.is_some() {
689 let old_callback = control.compilation_done.callback;
690 control.compilation_done.callback = box move |state| {
692 let sess = state.session;
693 println!("Fuel used by {}: {}",
694 sess.print_fuel_crate.as_ref().unwrap(),
695 sess.print_fuel.get());
702 pub fn enable_save_analysis(control: &mut CompileController) {
703 control.keep_ast = true;
704 control.after_analysis.callback = box |state| {
705 time(state.session.time_passes(), "save analysis", || {
706 save::process_crate(state.tcx.unwrap(),
707 state.expanded_crate.unwrap(),
708 state.analysis.unwrap(),
709 state.crate_name.unwrap(),
711 DumpHandler::new(state.out_dir,
712 state.crate_name.unwrap()))
715 control.after_analysis.run_callback_on_error = true;
716 control.make_glob_map = resolve::MakeGlobMap::Yes;
719 fn save_analysis(sess: &Session) -> bool {
720 sess.opts.debugging_opts.save_analysis
723 impl RustcDefaultCalls {
724 pub fn list_metadata(sess: &Session,
726 matches: &getopts::Matches,
729 let r = matches.opt_strs("Z");
730 if r.contains(&("ls".to_string())) {
732 &Input::File(ref ifile) => {
733 let path = &(*ifile);
734 let mut v = Vec::new();
735 locator::list_file_metadata(&sess.target.target,
737 cstore.metadata_loader(),
740 println!("{}", String::from_utf8(v).unwrap());
742 &Input::Str { .. } => {
743 early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
746 return Compilation::Stop;
749 return Compilation::Continue;
753 fn print_crate_info(sess: &Session,
754 input: Option<&Input>,
755 odir: &Option<PathBuf>,
756 ofile: &Option<PathBuf>)
758 // PrintRequest::NativeStaticLibs is special - printed during linking
759 // (empty iterator returns true)
760 if sess.opts.prints.iter().all(|&p| p==PrintRequest::NativeStaticLibs) {
761 return Compilation::Continue;
764 let attrs = match input {
767 let result = parse_crate_attrs(sess, input);
769 Ok(attrs) => Some(attrs),
770 Err(mut parse_error) => {
772 return Compilation::Stop;
777 for req in &sess.opts.prints {
779 PrintRequest::TargetList => {
780 let mut targets = rustc_back::target::get_targets().collect::<Vec<String>>();
782 println!("{}", targets.join("\n"));
784 PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
785 PrintRequest::TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
786 PrintRequest::FileNames |
787 PrintRequest::CrateName => {
788 let input = match input {
789 Some(input) => input,
790 None => early_error(ErrorOutputType::default(), "no input file provided"),
792 let attrs = attrs.as_ref().unwrap();
793 let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
794 let id = rustc_trans_utils::link::find_crate_name(Some(sess), attrs, input);
795 if *req == PrintRequest::CrateName {
799 let crate_types = driver::collect_crate_types(sess, attrs);
800 for &style in &crate_types {
801 let fname = rustc_trans_utils::link::filename_for_input(
813 PrintRequest::Cfg => {
814 let allow_unstable_cfg = UnstableFeatures::from_environment()
817 let mut cfgs = Vec::new();
818 for &(name, ref value) in sess.parse_sess.config.iter() {
819 let gated_cfg = GatedCfg::gate(&ast::MetaItem {
821 node: ast::MetaItemKind::Word,
825 // Note that crt-static is a specially recognized cfg
826 // directive that's printed out here as part of
827 // rust-lang/rust#37406, but in general the
828 // `target_feature` cfg is gated under
829 // rust-lang/rust#29717. For now this is just
830 // specifically allowing the crt-static cfg and that's
831 // it, this is intended to get into Cargo and then go
832 // through to build scripts.
833 let value = value.as_ref().map(|s| s.as_str());
834 let value = value.as_ref().map(|s| s.as_ref());
835 if name != "target_feature" || value != Some("crt-static") {
836 if !allow_unstable_cfg && gated_cfg.is_some() {
841 cfgs.push(if let Some(value) = value {
842 format!("{}=\"{}\"", name, value)
853 PrintRequest::RelocationModels => {
854 println!("Available relocation models:");
855 for &(name, _) in rustc_trans::back::write::RELOC_MODEL_ARGS.iter() {
856 println!(" {}", name);
860 PrintRequest::CodeModels => {
861 println!("Available code models:");
862 for &(name, _) in rustc_trans::back::write::CODE_GEN_MODEL_ARGS.iter(){
863 println!(" {}", name);
867 PrintRequest::TargetCPUs | PrintRequest::TargetFeatures => {
868 rustc_trans::print(*req, sess);
870 PrintRequest::NativeStaticLibs => {
871 println!("Native static libs can be printed only during linking");
875 return Compilation::Stop;
879 /// Returns a version string such as "0.12.0-dev".
880 fn release_str() -> Option<&'static str> {
881 option_env!("CFG_RELEASE")
884 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
885 fn commit_hash_str() -> Option<&'static str> {
886 option_env!("CFG_VER_HASH")
889 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
890 fn commit_date_str() -> Option<&'static str> {
891 option_env!("CFG_VER_DATE")
894 /// Prints version information
895 pub fn version(binary: &str, matches: &getopts::Matches) {
896 let verbose = matches.opt_present("verbose");
900 option_env!("CFG_VERSION").unwrap_or("unknown version"));
902 fn unw(x: Option<&str>) -> &str {
903 x.unwrap_or("unknown")
905 println!("binary: {}", binary);
906 println!("commit-hash: {}", unw(commit_hash_str()));
907 println!("commit-date: {}", unw(commit_date_str()));
908 println!("host: {}", config::host_triple());
909 println!("release: {}", unw(release_str()));
910 rustc_trans::print_version();
914 fn usage(verbose: bool, include_unstable_options: bool) {
915 let groups = if verbose {
916 config::rustc_optgroups()
918 config::rustc_short_optgroups()
920 let mut options = getopts::Options::new();
921 for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
922 (option.apply)(&mut options);
924 let message = format!("Usage: rustc [OPTIONS] INPUT");
925 let nightly_help = if nightly_options::is_nightly_build() {
926 "\n -Z help Print internal options for debugging rustc"
930 let verbose_help = if verbose {
933 "\n --help -v Print the full set of options rustc accepts"
935 println!("{}\nAdditional help:
936 -C help Print codegen options
938 Print 'lint' options and default settings{}{}\n",
939 options.usage(&message),
944 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
946 Available lint options:
947 -W <foo> Warn about <foo>
951 -F <foo> Forbid <foo> \
952 (deny <foo> and all attempts to override)
956 fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
957 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
958 lints.sort_by(|x: &&Lint, y: &&Lint| {
959 match x.default_level.cmp(&y.default_level) {
960 // The sort doesn't case-fold but it's doubtful we care.
961 Equal => x.name.cmp(y.name),
968 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
969 -> Vec<(&'static str, Vec<lint::LintId>)> {
970 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
971 lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
972 &(y, _): &(&'static str, Vec<lint::LintId>)| {
978 let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
981 .partition(|&(_, p)| p);
982 let plugin = sort_lints(plugin);
983 let builtin = sort_lints(builtin);
985 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
988 .partition(|&(.., p)| p);
989 let plugin_groups = sort_lint_groups(plugin_groups);
990 let builtin_groups = sort_lint_groups(builtin_groups);
992 let max_name_len = plugin.iter()
994 .map(|&s| s.name.chars().count())
997 let padded = |x: &str| {
998 let mut s = repeat(" ")
999 .take(max_name_len - x.chars().count())
1000 .collect::<String>();
1005 println!("Lint checks provided by rustc:\n");
1006 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
1007 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
1009 let print_lints = |lints: Vec<&Lint>| {
1011 let name = lint.name_lower().replace("_", "-");
1012 println!(" {} {:7.7} {}",
1014 lint.default_level.as_str(),
1020 print_lints(builtin);
1024 let max_name_len = max("warnings".len(),
1025 plugin_groups.iter()
1026 .chain(&builtin_groups)
1027 .map(|&(s, _)| s.chars().count())
1031 let padded = |x: &str| {
1032 let mut s = repeat(" ")
1033 .take(max_name_len - x.chars().count())
1034 .collect::<String>();
1039 println!("Lint groups provided by rustc:\n");
1040 println!(" {} {}", padded("name"), "sub-lints");
1041 println!(" {} {}", padded("----"), "---------");
1042 println!(" {} {}", padded("warnings"), "all built-in lints");
1044 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
1045 for (name, to) in lints {
1046 let name = name.to_lowercase().replace("_", "-");
1047 let desc = to.into_iter()
1048 .map(|x| x.to_string().replace("_", "-"))
1049 .collect::<Vec<String>>()
1051 println!(" {} {}", padded(&name), desc);
1056 print_lint_groups(builtin_groups);
1058 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
1059 (false, 0, _) | (false, _, 0) => {
1060 println!("Compiler plugins can provide additional lints and lint groups. To see a \
1061 listing of these, re-run `rustc -W help` with a crate filename.");
1063 (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
1064 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
1067 println!("Lint checks provided by plugins loaded by this crate:\n");
1068 print_lints(plugin);
1071 println!("Lint groups provided by plugins loaded by this crate:\n");
1072 print_lint_groups(plugin_groups);
1078 fn describe_debug_flags() {
1079 println!("\nAvailable debug options:\n");
1080 print_flag_list("-Z", config::DB_OPTIONS);
1083 fn describe_codegen_flags() {
1084 println!("\nAvailable codegen options:\n");
1085 print_flag_list("-C", config::CG_OPTIONS);
1088 fn print_flag_list<T>(cmdline_opt: &str,
1089 flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
1090 let max_len = flag_list.iter()
1091 .map(|&(name, _, opt_type_desc, _)| {
1092 let extra_len = match opt_type_desc {
1096 name.chars().count() + extra_len
1101 for &(name, _, opt_type_desc, desc) in flag_list {
1102 let (width, extra) = match opt_type_desc {
1103 Some(..) => (max_len - 4, "=val"),
1104 None => (max_len, ""),
1106 println!(" {} {:>width$}{} -- {}",
1108 name.replace("_", "-"),
1115 /// Process command line options. Emits messages as appropriate. If compilation
1116 /// should continue, returns a getopts::Matches object parsed from args,
1117 /// otherwise returns None.
1119 /// The compiler's handling of options is a little complicated as it ties into
1120 /// our stability story, and it's even *more* complicated by historical
1121 /// accidents. The current intention of each compiler option is to have one of
1124 /// 1. An option is stable and can be used everywhere.
1125 /// 2. An option is unstable, but was historically allowed on the stable
1127 /// 3. An option is unstable, and can only be used on nightly.
1129 /// Like unstable library and language features, however, unstable options have
1130 /// always required a form of "opt in" to indicate that you're using them. This
1131 /// provides the easy ability to scan a code base to check to see if anything
1132 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
1134 /// All options behind `-Z` are considered unstable by default. Other top-level
1135 /// options can also be considered unstable, and they were unlocked through the
1136 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
1137 /// instability in both cases, though.
1139 /// So with all that in mind, the comments below have some more detail about the
1140 /// contortions done here to get things to work out correctly.
1141 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
1142 // Throw away the first argument, the name of the binary
1143 let args = &args[1..];
1145 if args.is_empty() {
1146 // user did not write `-v` nor `-Z unstable-options`, so do not
1147 // include that extra information.
1148 usage(false, false);
1152 // Parse with *all* options defined in the compiler, we don't worry about
1153 // option stability here we just want to parse as much as possible.
1154 let mut options = getopts::Options::new();
1155 for option in config::rustc_optgroups() {
1156 (option.apply)(&mut options);
1158 let matches = match options.parse(args) {
1160 Err(f) => early_error(ErrorOutputType::default(), &f.to_string()),
1163 // For all options we just parsed, we check a few aspects:
1165 // * If the option is stable, we're all good
1166 // * If the option wasn't passed, we're all good
1167 // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1168 // ourselves), then we require the `-Z unstable-options` flag to unlock
1169 // this option that was passed.
1170 // * If we're a nightly compiler, then unstable options are now unlocked, so
1171 // we're good to go.
1172 // * Otherwise, if we're a truly unstable option then we generate an error
1173 // (unstable option being used on stable)
1174 // * If we're a historically stable-but-should-be-unstable option then we
1175 // emit a warning that we're going to turn this into an error soon.
1176 nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1178 if matches.opt_present("h") || matches.opt_present("help") {
1179 // Only show unstable options in --help if we *really* accept unstable
1180 // options, which catches the case where we got `-Z unstable-options` on
1181 // the stable channel of Rust which was accidentally allowed
1183 usage(matches.opt_present("verbose"),
1184 nightly_options::is_unstable_enabled(&matches));
1188 // Don't handle -W help here, because we might first load plugins.
1189 let r = matches.opt_strs("Z");
1190 if r.iter().any(|x| *x == "help") {
1191 describe_debug_flags();
1195 let cg_flags = matches.opt_strs("C");
1196 if cg_flags.iter().any(|x| *x == "help") {
1197 describe_codegen_flags();
1201 if cg_flags.iter().any(|x| *x == "no-stack-check") {
1202 early_warn(ErrorOutputType::default(),
1203 "the --no-stack-check flag is deprecated and does nothing");
1206 if cg_flags.contains(&"passes=list".to_string()) {
1207 rustc_trans::print_passes();
1211 if matches.opt_present("version") {
1212 version("rustc", &matches);
1219 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1221 Input::File(ref ifile) => {
1222 parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1224 Input::Str { ref name, ref input } => {
1225 parse::parse_crate_attrs_from_source_str(name.clone(), input.clone(), &sess.parse_sess)
1230 /// Runs `f` in a suitable thread for running `rustc`; returns a
1231 /// `Result` with either the return value of `f` or -- if a panic
1232 /// occurs -- the panic value.
1233 pub fn in_rustc_thread<F, R>(f: F) -> Result<R, Box<Any + Send>>
1234 where F: FnOnce() -> R + Send + 'static,
1237 // Temporarily have stack size set to 16MB to deal with nom-using crates failing
1238 const STACK_SIZE: usize = 16 * 1024 * 1024; // 16MB
1240 let mut cfg = thread::Builder::new().name("rustc".to_string());
1242 // FIXME: Hacks on hacks. If the env is trying to override the stack size
1243 // then *don't* set it explicitly.
1244 if env::var_os("RUST_MIN_STACK").is_none() {
1245 cfg = cfg.stack_size(STACK_SIZE);
1248 let thread = cfg.spawn(f);
1249 thread.unwrap().join()
1252 /// Run a procedure which will detect panics in the compiler and print nicer
1253 /// error messages rather than just failing the test.
1255 /// The diagnostic emitter yielded to the procedure should be used for reporting
1256 /// errors of the compiler.
1257 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) {
1258 struct Sink(Arc<Mutex<Vec<u8>>>);
1259 impl Write for Sink {
1260 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
1261 Write::write(&mut *self.0.lock().unwrap(), data)
1263 fn flush(&mut self) -> io::Result<()> {
1268 let data = Arc::new(Mutex::new(Vec::new()));
1269 let err = Sink(data.clone());
1271 let result = in_rustc_thread(move || {
1272 io::set_panic(Some(box err));
1276 if let Err(value) = result {
1277 // Thread panicked without emitting a fatal diagnostic
1278 if !value.is::<errors::FatalError>() {
1280 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto, None));
1281 let handler = errors::Handler::with_emitter(true, false, emitter);
1283 // a .span_bug or .bug call has already printed what
1284 // it wants to print.
1285 if !value.is::<errors::ExplicitBug>() {
1286 handler.emit(&MultiSpan::new(),
1288 errors::Level::Bug);
1291 let xs = ["the compiler unexpectedly panicked. this is a bug.".to_string(),
1292 format!("we would appreciate a bug report: {}", BUG_REPORT_URL),
1293 format!("rustc {} running on {}",
1294 option_env!("CFG_VERSION").unwrap_or("unknown_version"),
1295 config::host_triple())];
1297 handler.emit(&MultiSpan::new(),
1299 errors::Level::Note);
1301 if match env::var_os("RUST_BACKTRACE") {
1302 Some(val) => &val != "0",
1305 handler.emit(&MultiSpan::new(),
1306 "run with `RUST_BACKTRACE=1` for a backtrace",
1307 errors::Level::Note);
1310 writeln!(io::stderr(), "{}", str::from_utf8(&data.lock().unwrap()).unwrap()).unwrap();
1317 fn exit_on_err() -> ! {
1318 // Panic so the process returns a failure code, but don't pollute the
1319 // output with some unnecessary panic messages, we've already
1320 // printed everything that we needed to.
1321 io::set_panic(Some(box io::sink()));
1325 pub fn diagnostics_registry() -> errors::registry::Registry {
1326 use errors::registry::Registry;
1328 let mut all_errors = Vec::new();
1329 all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
1330 all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
1331 all_errors.extend_from_slice(&rustc_borrowck::DIAGNOSTICS);
1332 all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
1333 all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
1334 all_errors.extend_from_slice(&rustc_trans::DIAGNOSTICS);
1335 all_errors.extend_from_slice(&rustc_const_eval::DIAGNOSTICS);
1336 all_errors.extend_from_slice(&rustc_metadata::DIAGNOSTICS);
1337 all_errors.extend_from_slice(&rustc_passes::DIAGNOSTICS);
1338 all_errors.extend_from_slice(&rustc_plugin::DIAGNOSTICS);
1339 all_errors.extend_from_slice(&rustc_mir::DIAGNOSTICS);
1340 all_errors.extend_from_slice(&syntax::DIAGNOSTICS);
1342 Registry::new(&all_errors)
1345 pub fn get_args() -> Vec<String> {
1346 env::args_os().enumerate()
1347 .map(|(i, arg)| arg.into_string().unwrap_or_else(|arg| {
1348 early_error(ErrorOutputType::default(),
1349 &format!("Argument {} is not valid Unicode: {:?}", i, arg))
1355 env_logger::init().unwrap();
1356 let result = run(|| run_compiler(&get_args(),
1357 &mut RustcDefaultCalls,
1360 process::exit(result as i32);