]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/lib.rs
Rollup merge of #47247 - estebank:suggest-cast, r=petrochenkov
[rust.git] / src / librustc_driver / lib.rs
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.
4 //
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.
10
11 //! The Rust compiler.
12 //!
13 //! # Note
14 //!
15 //! This API is completely unstable and subject to change.
16
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/")]
20 #![deny(warnings)]
21
22 #![feature(box_syntax)]
23 #![cfg_attr(unix, feature(libc))]
24 #![feature(quote)]
25 #![feature(rustc_diagnostic_macros)]
26 #![feature(set_stdio)]
27
28 extern crate arena;
29 extern crate getopts;
30 extern crate graphviz;
31 extern crate env_logger;
32 #[cfg(unix)]
33 extern crate libc;
34 extern crate rustc;
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 pub extern crate rustc_trans;
52 extern crate rustc_trans_utils;
53 extern crate rustc_typeck;
54 extern crate serialize;
55 #[macro_use]
56 extern crate log;
57 extern crate syntax;
58 extern crate syntax_ext;
59 extern crate syntax_pos;
60
61 use driver::CompileController;
62 use pretty::{PpMode, UserIdentifiedItem};
63
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, ErrorOutputType};
70 use rustc::session::config::nightly_options;
71 use rustc::session::{early_error, early_warn};
72 use rustc::lint::Lint;
73 use rustc::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};
78 use rustc_trans_utils::trans_crate::TransCrate;
79
80 use serialize::json::ToJson;
81
82 use std::any::Any;
83 use std::cmp::max;
84 use std::cmp::Ordering::Equal;
85 use std::default::Default;
86 use std::env;
87 use std::ffi::OsString;
88 use std::io::{self, Read, Write};
89 use std::iter::repeat;
90 use std::path::PathBuf;
91 use std::process::{self, Command, Stdio};
92 use std::rc::Rc;
93 use std::str;
94 use std::sync::{Arc, Mutex};
95 use std::thread;
96
97 use syntax::ast;
98 use syntax::codemap::{CodeMap, FileLoader, RealFileLoader};
99 use syntax::feature_gate::{GatedCfg, UnstableFeatures};
100 use syntax::parse::{self, PResult};
101 use syntax_pos::{DUMMY_SP, MultiSpan, FileName};
102
103 #[cfg(test)]
104 mod test;
105
106 pub mod profile;
107 pub mod driver;
108 pub mod pretty;
109 mod derive_registrar;
110
111 pub mod target_features {
112     use syntax::ast;
113     use syntax::symbol::Symbol;
114     use rustc::session::Session;
115     use rustc_trans_utils::trans_crate::TransCrate;
116
117     /// Add `target_feature = "..."` cfgs for a variety of platform
118     /// specific features (SSE, NEON etc.).
119     ///
120     /// This is performed by checking whether a whitelisted set of
121     /// features is available on the target machine, by querying LLVM.
122     pub fn add_configuration(cfg: &mut ast::CrateConfig, sess: &Session, trans: &TransCrate) {
123         let tf = Symbol::intern("target_feature");
124
125         for feat in trans.target_features(sess) {
126             cfg.insert((tf, Some(feat)));
127         }
128
129         if sess.crt_static_feature() {
130             cfg.insert((tf, Some(Symbol::intern("crt-static"))));
131         }
132     }
133 }
134
135 const BUG_REPORT_URL: &'static str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
136                                       md#bug-reports";
137
138 pub fn abort_on_err<T>(result: Result<T, CompileIncomplete>, sess: &Session) -> T {
139     match result {
140         Err(CompileIncomplete::Errored(ErrorReported)) => {
141             sess.abort_if_errors();
142             panic!("error reported but abort_if_errors didn't abort???");
143         }
144         Err(CompileIncomplete::Stopped) => {
145             sess.fatal("compilation terminated");
146         }
147         Ok(x) => x,
148     }
149 }
150
151 pub fn run<F>(run_compiler: F) -> isize
152     where F: FnOnce() -> (CompileResult, Option<Session>) + Send + 'static
153 {
154     monitor(move || {
155         let (result, session) = run_compiler();
156         if let Err(CompileIncomplete::Errored(_)) = result {
157             match session {
158                 Some(sess) => {
159                     sess.abort_if_errors();
160                     panic!("error reported but abort_if_errors didn't abort???");
161                 }
162                 None => {
163                     let emitter =
164                         errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto,
165                                                                None,
166                                                                true);
167                     let handler = errors::Handler::with_emitter(true, false, Box::new(emitter));
168                     handler.emit(&MultiSpan::new(),
169                                  "aborting due to previous error(s)",
170                                  errors::Level::Fatal);
171                     exit_on_err();
172                 }
173             }
174         }
175     });
176     0
177 }
178
179 #[cfg(not(feature="llvm"))]
180 pub use rustc_trans_utils::trans_crate::MetadataOnlyTransCrate as DefaultTransCrate;
181 #[cfg(feature="llvm")]
182 pub use rustc_trans::LlvmTransCrate as DefaultTransCrate;
183
184 #[cfg(not(feature="llvm"))]
185 pub mod rustc_trans {
186     pub use rustc_trans_utils::trans_crate::MetadataOnlyTransCrate as LlvmTransCrate;
187
188     pub fn print_version() {}
189     pub fn print_passes() {}
190 }
191
192 fn load_backend_from_dylib(sess: &Session, backend_name: &str) -> Box<TransCrate> {
193     use std::path::Path;
194     use rustc_metadata::dynamic_lib::DynamicLibrary;
195
196     match DynamicLibrary::open(Some(Path::new(backend_name))) {
197         Ok(lib) => {
198             unsafe {
199                 let trans = {
200                     let __rustc_codegen_backend: unsafe fn(&Session) -> Box<TransCrate>;
201                     __rustc_codegen_backend = match lib.symbol("__rustc_codegen_backend") {
202                         Ok(f) => ::std::mem::transmute::<*mut u8, _>(f),
203                         Err(e) => sess.fatal(&format!("Couldnt load codegen backend as it\
204                         doesn't export the __rustc_backend_new symbol: {:?}", e)),
205                     };
206                     __rustc_codegen_backend(sess)
207                 };
208                 ::std::mem::forget(lib);
209                 trans
210             }
211         }
212         Err(err) => {
213             sess.fatal(&format!("Couldnt load codegen backend {:?}: {:?}", backend_name, err));
214         }
215     }
216 }
217
218 pub fn get_trans(sess: &Session) -> Box<TransCrate> {
219     let trans_name = sess.opts.debugging_opts.codegen_backend.clone();
220     match trans_name.as_ref().map(|s|&**s) {
221         None => DefaultTransCrate::new(&sess),
222         Some("llvm") => rustc_trans::LlvmTransCrate::new(&sess),
223         Some("metadata_only") => {
224             rustc_trans_utils::trans_crate::MetadataOnlyTransCrate::new(&sess)
225         }
226         Some(filename) if filename.contains(".") => {
227             load_backend_from_dylib(&sess, &filename)
228         }
229         Some(trans_name) => sess.fatal(&format!("Unknown codegen backend {}", trans_name)),
230     }
231 }
232
233 // Parse args and run the compiler. This is the primary entry point for rustc.
234 // See comments on CompilerCalls below for details about the callbacks argument.
235 // The FileLoader provides a way to load files from sources other than the file system.
236 pub fn run_compiler<'a>(args: &[String],
237                         callbacks: &mut CompilerCalls<'a>,
238                         file_loader: Option<Box<FileLoader + 'static>>,
239                         emitter_dest: Option<Box<Write + Send>>)
240                         -> (CompileResult, Option<Session>)
241 {
242     macro_rules! do_or_return {($expr: expr, $sess: expr) => {
243         match $expr {
244             Compilation::Stop => return (Ok(()), $sess),
245             Compilation::Continue => {}
246         }
247     }}
248
249     let matches = match handle_options(args) {
250         Some(matches) => matches,
251         None => return (Ok(()), None),
252     };
253
254     let (sopts, cfg) = config::build_session_options_and_crate_config(&matches);
255
256     let descriptions = diagnostics_registry();
257
258     do_or_return!(callbacks.early_callback(&matches,
259                                            &sopts,
260                                            &cfg,
261                                            &descriptions,
262                                            sopts.error_format),
263                                            None);
264
265     let (odir, ofile) = make_output(&matches);
266     let (input, input_file_path) = match make_input(&matches.free) {
267         Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
268         None => match callbacks.no_input(&matches, &sopts, &cfg, &odir, &ofile, &descriptions) {
269             Some((input, input_file_path)) => (input, input_file_path),
270             None => return (Ok(()), None),
271         },
272     };
273
274     let loader = file_loader.unwrap_or(box RealFileLoader);
275     let codemap = Rc::new(CodeMap::with_file_loader(loader, sopts.file_path_mapping()));
276     let mut sess = session::build_session_with_codemap(
277         sopts, input_file_path.clone(), descriptions, codemap, emitter_dest,
278     );
279
280     let trans = get_trans(&sess);
281
282     rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
283
284     let mut cfg = config::build_configuration(&sess, cfg);
285     target_features::add_configuration(&mut cfg, &sess, &*trans);
286     sess.parse_sess.config = cfg;
287
288     let plugins = sess.opts.debugging_opts.extra_plugins.clone();
289
290     let cstore = CStore::new(trans.metadata_loader());
291
292     do_or_return!(callbacks.late_callback(&*trans,
293                                           &matches,
294                                           &sess,
295                                           &cstore,
296                                           &input,
297                                           &odir,
298                                           &ofile), Some(sess));
299
300     let control = callbacks.build_controller(&sess, &matches);
301
302     (driver::compile_input(trans,
303                            &sess,
304                            &cstore,
305                            &input_file_path,
306                            &input,
307                            &odir,
308                            &ofile,
309                            Some(plugins),
310                            &control),
311      Some(sess))
312 }
313
314 // Extract output directory and file from matches.
315 fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
316     let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
317     let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
318     (odir, ofile)
319 }
320
321 // Extract input (string or file and optional path) from matches.
322 fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
323     if free_matches.len() == 1 {
324         let ifile = &free_matches[0];
325         if ifile == "-" {
326             let mut src = String::new();
327             io::stdin().read_to_string(&mut src).unwrap();
328             Some((Input::Str { name: FileName::Anon, input: src },
329                   None))
330         } else {
331             Some((Input::File(PathBuf::from(ifile)),
332                   Some(PathBuf::from(ifile))))
333         }
334     } else {
335         None
336     }
337 }
338
339 fn parse_pretty(sess: &Session,
340                 matches: &getopts::Matches)
341                 -> Option<(PpMode, Option<UserIdentifiedItem>)> {
342     let pretty = if sess.opts.debugging_opts.unstable_options {
343         matches.opt_default("pretty", "normal").map(|a| {
344             // stable pretty-print variants only
345             pretty::parse_pretty(sess, &a, false)
346         })
347     } else {
348         None
349     };
350     if pretty.is_none() && sess.unstable_options() {
351         matches.opt_str("unpretty").map(|a| {
352             // extended with unstable pretty-print variants
353             pretty::parse_pretty(sess, &a, true)
354         })
355     } else {
356         pretty
357     }
358 }
359
360 // Whether to stop or continue compilation.
361 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
362 pub enum Compilation {
363     Stop,
364     Continue,
365 }
366
367 impl Compilation {
368     pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
369         match self {
370             Compilation::Stop => Compilation::Stop,
371             Compilation::Continue => next(),
372         }
373     }
374 }
375
376 // A trait for customising the compilation process. Offers a number of hooks for
377 // executing custom code or customising input.
378 pub trait CompilerCalls<'a> {
379     // Hook for a callback early in the process of handling arguments. This will
380     // be called straight after options have been parsed but before anything
381     // else (e.g., selecting input and output).
382     fn early_callback(&mut self,
383                       _: &getopts::Matches,
384                       _: &config::Options,
385                       _: &ast::CrateConfig,
386                       _: &errors::registry::Registry,
387                       _: ErrorOutputType)
388                       -> Compilation {
389         Compilation::Continue
390     }
391
392     // Hook for a callback late in the process of handling arguments. This will
393     // be called just before actual compilation starts (and before build_controller
394     // is called), after all arguments etc. have been completely handled.
395     fn late_callback(&mut self,
396                      _: &TransCrate,
397                      _: &getopts::Matches,
398                      _: &Session,
399                      _: &CrateStore,
400                      _: &Input,
401                      _: &Option<PathBuf>,
402                      _: &Option<PathBuf>)
403                      -> Compilation {
404         Compilation::Continue
405     }
406
407     // Called after we extract the input from the arguments. Gives the implementer
408     // an opportunity to change the inputs or to add some custom input handling.
409     // The default behaviour is to simply pass through the inputs.
410     fn some_input(&mut self,
411                   input: Input,
412                   input_path: Option<PathBuf>)
413                   -> (Input, Option<PathBuf>) {
414         (input, input_path)
415     }
416
417     // Called after we extract the input from the arguments if there is no valid
418     // input. Gives the implementer an opportunity to supply alternate input (by
419     // returning a Some value) or to add custom behaviour for this error such as
420     // emitting error messages. Returning None will cause compilation to stop
421     // at this point.
422     fn no_input(&mut self,
423                 _: &getopts::Matches,
424                 _: &config::Options,
425                 _: &ast::CrateConfig,
426                 _: &Option<PathBuf>,
427                 _: &Option<PathBuf>,
428                 _: &errors::registry::Registry)
429                 -> Option<(Input, Option<PathBuf>)> {
430         None
431     }
432
433     // Create a CompilController struct for controlling the behaviour of
434     // compilation.
435     fn build_controller(&mut self, _: &Session, _: &getopts::Matches) -> CompileController<'a>;
436 }
437
438 // CompilerCalls instance for a regular rustc build.
439 #[derive(Copy, Clone)]
440 pub struct RustcDefaultCalls;
441
442 // FIXME remove these and use winapi 0.3 instead
443 // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs
444 #[cfg(unix)]
445 fn stdout_isatty() -> bool {
446     unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 }
447 }
448
449 #[cfg(windows)]
450 fn stdout_isatty() -> bool {
451     type DWORD = u32;
452     type BOOL = i32;
453     type HANDLE = *mut u8;
454     type LPDWORD = *mut u32;
455     const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD;
456     extern "system" {
457         fn GetStdHandle(which: DWORD) -> HANDLE;
458         fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL;
459     }
460     unsafe {
461         let handle = GetStdHandle(STD_OUTPUT_HANDLE);
462         let mut out = 0;
463         GetConsoleMode(handle, &mut out) != 0
464     }
465 }
466
467 fn handle_explain(code: &str,
468                   descriptions: &errors::registry::Registry,
469                   output: ErrorOutputType) {
470     let normalised = if code.starts_with("E") {
471         code.to_string()
472     } else {
473         format!("E{0:0>4}", code)
474     };
475     match descriptions.find_description(&normalised) {
476         Some(ref description) => {
477             let mut is_in_code_block = false;
478             let mut text = String::new();
479
480             // Slice off the leading newline and print.
481             for line in description[1..].lines() {
482                 let indent_level = line.find(|c: char| !c.is_whitespace())
483                     .unwrap_or_else(|| line.len());
484                 let dedented_line = &line[indent_level..];
485                 if dedented_line.starts_with("```") {
486                     is_in_code_block = !is_in_code_block;
487                     text.push_str(&line[..(indent_level+3)]);
488                 } else if is_in_code_block && dedented_line.starts_with("# ") {
489                     continue;
490                 } else {
491                     text.push_str(line);
492                 }
493                 text.push('\n');
494             }
495
496             if stdout_isatty() {
497                 show_content_with_pager(&text);
498             } else {
499                 print!("{}", text);
500             }
501         }
502         None => {
503             early_error(output, &format!("no extended information for {}", code));
504         }
505     }
506 }
507
508 fn show_content_with_pager(content: &String) {
509     let pager_name = env::var_os("PAGER").unwrap_or_else(|| if cfg!(windows) {
510         OsString::from("more.com")
511     } else {
512         OsString::from("less")
513     });
514
515     let mut fallback_to_println = false;
516
517     match Command::new(pager_name).stdin(Stdio::piped()).spawn() {
518         Ok(mut pager) => {
519             if let Some(pipe) = pager.stdin.as_mut() {
520                 if pipe.write_all(content.as_bytes()).is_err() {
521                     fallback_to_println = true;
522                 }
523             }
524
525             if pager.wait().is_err() {
526                 fallback_to_println = true;
527             }
528         }
529         Err(_) => {
530             fallback_to_println = true;
531         }
532     }
533
534     // If pager fails for whatever reason, we should still print the content
535     // to standard output
536     if fallback_to_println {
537         print!("{}", content);
538     }
539 }
540
541 impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
542     fn early_callback(&mut self,
543                       matches: &getopts::Matches,
544                       _: &config::Options,
545                       _: &ast::CrateConfig,
546                       descriptions: &errors::registry::Registry,
547                       output: ErrorOutputType)
548                       -> Compilation {
549         if let Some(ref code) = matches.opt_str("explain") {
550             handle_explain(code, descriptions, output);
551             return Compilation::Stop;
552         }
553
554         Compilation::Continue
555     }
556
557     fn no_input(&mut self,
558                 matches: &getopts::Matches,
559                 sopts: &config::Options,
560                 cfg: &ast::CrateConfig,
561                 odir: &Option<PathBuf>,
562                 ofile: &Option<PathBuf>,
563                 descriptions: &errors::registry::Registry)
564                 -> Option<(Input, Option<PathBuf>)> {
565         match matches.free.len() {
566             0 => {
567                 if sopts.describe_lints {
568                     let mut ls = lint::LintStore::new();
569                     rustc_lint::register_builtins(&mut ls, None);
570                     describe_lints(&ls, false);
571                     return None;
572                 }
573                 let mut sess = build_session(sopts.clone(),
574                     None,
575                     descriptions.clone());
576                 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
577                 let mut cfg = config::build_configuration(&sess, cfg.clone());
578                 let trans = get_trans(&sess);
579                 target_features::add_configuration(&mut cfg, &sess, &*trans);
580                 sess.parse_sess.config = cfg;
581                 let should_stop = RustcDefaultCalls::print_crate_info(
582                     &*trans,
583                     &sess,
584                     None,
585                     odir,
586                     ofile
587                 );
588
589                 if should_stop == Compilation::Stop {
590                     return None;
591                 }
592                 early_error(sopts.error_format, "no input filename given");
593             }
594             1 => panic!("make_input should have provided valid inputs"),
595             _ => early_error(sopts.error_format, "multiple input filenames provided"),
596         }
597     }
598
599     fn late_callback(&mut self,
600                      trans: &TransCrate,
601                      matches: &getopts::Matches,
602                      sess: &Session,
603                      cstore: &CrateStore,
604                      input: &Input,
605                      odir: &Option<PathBuf>,
606                      ofile: &Option<PathBuf>)
607                      -> Compilation {
608         RustcDefaultCalls::print_crate_info(trans, sess, Some(input), odir, ofile)
609             .and_then(|| RustcDefaultCalls::list_metadata(sess, cstore, matches, input))
610     }
611
612     fn build_controller(&mut self,
613                         sess: &Session,
614                         matches: &getopts::Matches)
615                         -> CompileController<'a> {
616         let mut control = CompileController::basic();
617
618         control.keep_ast = sess.opts.debugging_opts.keep_ast;
619         control.continue_parse_after_error = sess.opts.debugging_opts.continue_parse_after_error;
620
621         if let Some((ppm, opt_uii)) = parse_pretty(sess, matches) {
622             if ppm.needs_ast_map(&opt_uii) {
623                 control.after_hir_lowering.stop = Compilation::Stop;
624
625                 control.after_parse.callback = box move |state| {
626                     state.krate = Some(pretty::fold_crate(state.session,
627                                                           state.krate.take().unwrap(),
628                                                           ppm));
629                 };
630                 control.after_hir_lowering.callback = box move |state| {
631                     pretty::print_after_hir_lowering(state.session,
632                                                      state.cstore.unwrap(),
633                                                      state.hir_map.unwrap(),
634                                                      state.analysis.unwrap(),
635                                                      state.resolutions.unwrap(),
636                                                      state.input,
637                                                      &state.expanded_crate.take().unwrap(),
638                                                      state.crate_name.unwrap(),
639                                                      ppm,
640                                                      state.arenas.unwrap(),
641                                                      state.output_filenames.unwrap(),
642                                                      opt_uii.clone(),
643                                                      state.out_file);
644                 };
645             } else {
646                 control.after_parse.stop = Compilation::Stop;
647
648                 control.after_parse.callback = box move |state| {
649                     let krate = pretty::fold_crate(state.session, state.krate.take().unwrap(), ppm);
650                     pretty::print_after_parsing(state.session,
651                                                 state.input,
652                                                 &krate,
653                                                 ppm,
654                                                 state.out_file);
655                 };
656             }
657
658             return control;
659         }
660
661         if sess.opts.debugging_opts.parse_only ||
662            sess.opts.debugging_opts.show_span.is_some() ||
663            sess.opts.debugging_opts.ast_json_noexpand {
664             control.after_parse.stop = Compilation::Stop;
665         }
666
667         if sess.opts.debugging_opts.no_analysis ||
668            sess.opts.debugging_opts.ast_json {
669             control.after_hir_lowering.stop = Compilation::Stop;
670         }
671
672         if save_analysis(sess) {
673             enable_save_analysis(&mut control);
674         }
675
676         if sess.print_fuel_crate.is_some() {
677             let old_callback = control.compilation_done.callback;
678             control.compilation_done.callback = box move |state| {
679                 old_callback(state);
680                 let sess = state.session;
681                 println!("Fuel used by {}: {}",
682                     sess.print_fuel_crate.as_ref().unwrap(),
683                     sess.print_fuel.get());
684             }
685         }
686         control
687     }
688 }
689
690 pub fn enable_save_analysis(control: &mut CompileController) {
691     control.keep_ast = true;
692     control.after_analysis.callback = box |state| {
693         time(state.session.time_passes(), "save analysis", || {
694             save::process_crate(state.tcx.unwrap(),
695                                 state.expanded_crate.unwrap(),
696                                 state.analysis.unwrap(),
697                                 state.crate_name.unwrap(),
698                                 None,
699                                 DumpHandler::new(state.out_dir,
700                                                  state.crate_name.unwrap()))
701         });
702     };
703     control.after_analysis.run_callback_on_error = true;
704     control.make_glob_map = resolve::MakeGlobMap::Yes;
705 }
706
707 fn save_analysis(sess: &Session) -> bool {
708     sess.opts.debugging_opts.save_analysis
709 }
710
711 impl RustcDefaultCalls {
712     pub fn list_metadata(sess: &Session,
713                          cstore: &CrateStore,
714                          matches: &getopts::Matches,
715                          input: &Input)
716                          -> Compilation {
717         let r = matches.opt_strs("Z");
718         if r.contains(&("ls".to_string())) {
719             match input {
720                 &Input::File(ref ifile) => {
721                     let path = &(*ifile);
722                     let mut v = Vec::new();
723                     locator::list_file_metadata(&sess.target.target,
724                                                 path,
725                                                 cstore.metadata_loader(),
726                                                 &mut v)
727                             .unwrap();
728                     println!("{}", String::from_utf8(v).unwrap());
729                 }
730                 &Input::Str { .. } => {
731                     early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
732                 }
733             }
734             return Compilation::Stop;
735         }
736
737         return Compilation::Continue;
738     }
739
740
741     fn print_crate_info(trans: &TransCrate,
742                         sess: &Session,
743                         input: Option<&Input>,
744                         odir: &Option<PathBuf>,
745                         ofile: &Option<PathBuf>)
746                         -> Compilation {
747         use rustc::session::config::PrintRequest::*;
748         // PrintRequest::NativeStaticLibs is special - printed during linking
749         // (empty iterator returns true)
750         if sess.opts.prints.iter().all(|&p| p==PrintRequest::NativeStaticLibs) {
751             return Compilation::Continue;
752         }
753
754         let attrs = match input {
755             None => None,
756             Some(input) => {
757                 let result = parse_crate_attrs(sess, input);
758                 match result {
759                     Ok(attrs) => Some(attrs),
760                     Err(mut parse_error) => {
761                         parse_error.emit();
762                         return Compilation::Stop;
763                     }
764                 }
765             }
766         };
767         for req in &sess.opts.prints {
768             match *req {
769                 TargetList => {
770                     let mut targets = rustc_back::target::get_targets().collect::<Vec<String>>();
771                     targets.sort();
772                     println!("{}", targets.join("\n"));
773                 },
774                 Sysroot => println!("{}", sess.sysroot().display()),
775                 TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
776                 FileNames | CrateName => {
777                     let input = match input {
778                         Some(input) => input,
779                         None => early_error(ErrorOutputType::default(), "no input file provided"),
780                     };
781                     let attrs = attrs.as_ref().unwrap();
782                     let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
783                     let id = rustc_trans_utils::link::find_crate_name(Some(sess), attrs, input);
784                     if *req == PrintRequest::CrateName {
785                         println!("{}", id);
786                         continue;
787                     }
788                     let crate_types = driver::collect_crate_types(sess, attrs);
789                     for &style in &crate_types {
790                         let fname = rustc_trans_utils::link::filename_for_input(
791                             sess,
792                             style,
793                             &id,
794                             &t_outputs
795                         );
796                         println!("{}",
797                                  fname.file_name()
798                                       .unwrap()
799                                       .to_string_lossy());
800                     }
801                 }
802                 Cfg => {
803                     let allow_unstable_cfg = UnstableFeatures::from_environment()
804                         .is_nightly_build();
805
806                     let mut cfgs = Vec::new();
807                     for &(name, ref value) in sess.parse_sess.config.iter() {
808                         let gated_cfg = GatedCfg::gate(&ast::MetaItem {
809                             name,
810                             node: ast::MetaItemKind::Word,
811                             span: DUMMY_SP,
812                         });
813
814                         // Note that crt-static is a specially recognized cfg
815                         // directive that's printed out here as part of
816                         // rust-lang/rust#37406, but in general the
817                         // `target_feature` cfg is gated under
818                         // rust-lang/rust#29717. For now this is just
819                         // specifically allowing the crt-static cfg and that's
820                         // it, this is intended to get into Cargo and then go
821                         // through to build scripts.
822                         let value = value.as_ref().map(|s| s.as_str());
823                         let value = value.as_ref().map(|s| s.as_ref());
824                         if name != "target_feature" || value != Some("crt-static") {
825                             if !allow_unstable_cfg && gated_cfg.is_some() {
826                                 continue;
827                             }
828                         }
829
830                         cfgs.push(if let Some(value) = value {
831                             format!("{}=\"{}\"", name, value)
832                         } else {
833                             format!("{}", name)
834                         });
835                     }
836
837                     cfgs.sort();
838                     for cfg in cfgs {
839                         println!("{}", cfg);
840                     }
841                 }
842                 RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => {
843                     trans.print(*req, sess);
844                 }
845                 // Any output here interferes with Cargo's parsing of other printed output
846                 PrintRequest::NativeStaticLibs => {}
847             }
848         }
849         return Compilation::Stop;
850     }
851 }
852
853 /// Returns a version string such as "0.12.0-dev".
854 fn release_str() -> Option<&'static str> {
855     option_env!("CFG_RELEASE")
856 }
857
858 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
859 fn commit_hash_str() -> Option<&'static str> {
860     option_env!("CFG_VER_HASH")
861 }
862
863 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
864 fn commit_date_str() -> Option<&'static str> {
865     option_env!("CFG_VER_DATE")
866 }
867
868 /// Prints version information
869 pub fn version(binary: &str, matches: &getopts::Matches) {
870     let verbose = matches.opt_present("verbose");
871
872     println!("{} {}",
873              binary,
874              option_env!("CFG_VERSION").unwrap_or("unknown version"));
875     if verbose {
876         fn unw(x: Option<&str>) -> &str {
877             x.unwrap_or("unknown")
878         }
879         println!("binary: {}", binary);
880         println!("commit-hash: {}", unw(commit_hash_str()));
881         println!("commit-date: {}", unw(commit_date_str()));
882         println!("host: {}", config::host_triple());
883         println!("release: {}", unw(release_str()));
884         rustc_trans::print_version();
885     }
886 }
887
888 fn usage(verbose: bool, include_unstable_options: bool) {
889     let groups = if verbose {
890         config::rustc_optgroups()
891     } else {
892         config::rustc_short_optgroups()
893     };
894     let mut options = getopts::Options::new();
895     for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
896         (option.apply)(&mut options);
897     }
898     let message = format!("Usage: rustc [OPTIONS] INPUT");
899     let nightly_help = if nightly_options::is_nightly_build() {
900         "\n    -Z help             Print internal options for debugging rustc"
901     } else {
902         ""
903     };
904     let verbose_help = if verbose {
905         ""
906     } else {
907         "\n    --help -v           Print the full set of options rustc accepts"
908     };
909     println!("{}\nAdditional help:
910     -C help             Print codegen options
911     -W help             \
912               Print 'lint' options and default settings{}{}\n",
913              options.usage(&message),
914              nightly_help,
915              verbose_help);
916 }
917
918 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
919     println!("
920 Available lint options:
921     -W <foo>           Warn about <foo>
922     -A <foo>           \
923               Allow <foo>
924     -D <foo>           Deny <foo>
925     -F <foo>           Forbid <foo> \
926               (deny <foo> and all attempts to override)
927
928 ");
929
930     fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
931         let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
932         lints.sort_by(|x: &&Lint, y: &&Lint| {
933             match x.default_level.cmp(&y.default_level) {
934                 // The sort doesn't case-fold but it's doubtful we care.
935                 Equal => x.name.cmp(y.name),
936                 r => r,
937             }
938         });
939         lints
940     }
941
942     fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
943                         -> Vec<(&'static str, Vec<lint::LintId>)> {
944         let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
945         lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
946                        &(y, _): &(&'static str, Vec<lint::LintId>)| {
947             x.cmp(y)
948         });
949         lints
950     }
951
952     let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
953                                                    .iter()
954                                                    .cloned()
955                                                    .partition(|&(_, p)| p);
956     let plugin = sort_lints(plugin);
957     let builtin = sort_lints(builtin);
958
959     let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
960                                                                  .iter()
961                                                                  .cloned()
962                                                                  .partition(|&(.., p)| p);
963     let plugin_groups = sort_lint_groups(plugin_groups);
964     let builtin_groups = sort_lint_groups(builtin_groups);
965
966     let max_name_len = plugin.iter()
967                              .chain(&builtin)
968                              .map(|&s| s.name.chars().count())
969                              .max()
970                              .unwrap_or(0);
971     let padded = |x: &str| {
972         let mut s = repeat(" ")
973                         .take(max_name_len - x.chars().count())
974                         .collect::<String>();
975         s.push_str(x);
976         s
977     };
978
979     println!("Lint checks provided by rustc:\n");
980     println!("    {}  {:7.7}  {}", padded("name"), "default", "meaning");
981     println!("    {}  {:7.7}  {}", padded("----"), "-------", "-------");
982
983     let print_lints = |lints: Vec<&Lint>| {
984         for lint in lints {
985             let name = lint.name_lower().replace("_", "-");
986             println!("    {}  {:7.7}  {}",
987                      padded(&name),
988                      lint.default_level.as_str(),
989                      lint.desc);
990         }
991         println!("\n");
992     };
993
994     print_lints(builtin);
995
996
997
998     let max_name_len = max("warnings".len(),
999                            plugin_groups.iter()
1000                                         .chain(&builtin_groups)
1001                                         .map(|&(s, _)| s.chars().count())
1002                                         .max()
1003                                         .unwrap_or(0));
1004
1005     let padded = |x: &str| {
1006         let mut s = repeat(" ")
1007                         .take(max_name_len - x.chars().count())
1008                         .collect::<String>();
1009         s.push_str(x);
1010         s
1011     };
1012
1013     println!("Lint groups provided by rustc:\n");
1014     println!("    {}  {}", padded("name"), "sub-lints");
1015     println!("    {}  {}", padded("----"), "---------");
1016     println!("    {}  {}", padded("warnings"), "all lints that are set to issue warnings");
1017
1018     let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
1019         for (name, to) in lints {
1020             let name = name.to_lowercase().replace("_", "-");
1021             let desc = to.into_iter()
1022                          .map(|x| x.to_string().replace("_", "-"))
1023                          .collect::<Vec<String>>()
1024                          .join(", ");
1025             println!("    {}  {}", padded(&name), desc);
1026         }
1027         println!("\n");
1028     };
1029
1030     print_lint_groups(builtin_groups);
1031
1032     match (loaded_plugins, plugin.len(), plugin_groups.len()) {
1033         (false, 0, _) | (false, _, 0) => {
1034             println!("Compiler plugins can provide additional lints and lint groups. To see a \
1035                       listing of these, re-run `rustc -W help` with a crate filename.");
1036         }
1037         (false, ..) => panic!("didn't load lint plugins but got them anyway!"),
1038         (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
1039         (true, l, g) => {
1040             if l > 0 {
1041                 println!("Lint checks provided by plugins loaded by this crate:\n");
1042                 print_lints(plugin);
1043             }
1044             if g > 0 {
1045                 println!("Lint groups provided by plugins loaded by this crate:\n");
1046                 print_lint_groups(plugin_groups);
1047             }
1048         }
1049     }
1050 }
1051
1052 fn describe_debug_flags() {
1053     println!("\nAvailable debug options:\n");
1054     print_flag_list("-Z", config::DB_OPTIONS);
1055 }
1056
1057 fn describe_codegen_flags() {
1058     println!("\nAvailable codegen options:\n");
1059     print_flag_list("-C", config::CG_OPTIONS);
1060 }
1061
1062 fn print_flag_list<T>(cmdline_opt: &str,
1063                       flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) {
1064     let max_len = flag_list.iter()
1065                            .map(|&(name, _, opt_type_desc, _)| {
1066                                let extra_len = match opt_type_desc {
1067                                    Some(..) => 4,
1068                                    None => 0,
1069                                };
1070                                name.chars().count() + extra_len
1071                            })
1072                            .max()
1073                            .unwrap_or(0);
1074
1075     for &(name, _, opt_type_desc, desc) in flag_list {
1076         let (width, extra) = match opt_type_desc {
1077             Some(..) => (max_len - 4, "=val"),
1078             None => (max_len, ""),
1079         };
1080         println!("    {} {:>width$}{} -- {}",
1081                  cmdline_opt,
1082                  name.replace("_", "-"),
1083                  extra,
1084                  desc,
1085                  width = width);
1086     }
1087 }
1088
1089 /// Process command line options. Emits messages as appropriate. If compilation
1090 /// should continue, returns a getopts::Matches object parsed from args,
1091 /// otherwise returns None.
1092 ///
1093 /// The compiler's handling of options is a little complicated as it ties into
1094 /// our stability story, and it's even *more* complicated by historical
1095 /// accidents. The current intention of each compiler option is to have one of
1096 /// three modes:
1097 ///
1098 /// 1. An option is stable and can be used everywhere.
1099 /// 2. An option is unstable, but was historically allowed on the stable
1100 ///    channel.
1101 /// 3. An option is unstable, and can only be used on nightly.
1102 ///
1103 /// Like unstable library and language features, however, unstable options have
1104 /// always required a form of "opt in" to indicate that you're using them. This
1105 /// provides the easy ability to scan a code base to check to see if anything
1106 /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag.
1107 ///
1108 /// All options behind `-Z` are considered unstable by default. Other top-level
1109 /// options can also be considered unstable, and they were unlocked through the
1110 /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of
1111 /// instability in both cases, though.
1112 ///
1113 /// So with all that in mind, the comments below have some more detail about the
1114 /// contortions done here to get things to work out correctly.
1115 pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
1116     // Throw away the first argument, the name of the binary
1117     let args = &args[1..];
1118
1119     if args.is_empty() {
1120         // user did not write `-v` nor `-Z unstable-options`, so do not
1121         // include that extra information.
1122         usage(false, false);
1123         return None;
1124     }
1125
1126     // Parse with *all* options defined in the compiler, we don't worry about
1127     // option stability here we just want to parse as much as possible.
1128     let mut options = getopts::Options::new();
1129     for option in config::rustc_optgroups() {
1130         (option.apply)(&mut options);
1131     }
1132     let matches = match options.parse(args) {
1133         Ok(m) => m,
1134         Err(f) => early_error(ErrorOutputType::default(), &f.to_string()),
1135     };
1136
1137     // For all options we just parsed, we check a few aspects:
1138     //
1139     // * If the option is stable, we're all good
1140     // * If the option wasn't passed, we're all good
1141     // * If `-Z unstable-options` wasn't passed (and we're not a -Z option
1142     //   ourselves), then we require the `-Z unstable-options` flag to unlock
1143     //   this option that was passed.
1144     // * If we're a nightly compiler, then unstable options are now unlocked, so
1145     //   we're good to go.
1146     // * Otherwise, if we're a truly unstable option then we generate an error
1147     //   (unstable option being used on stable)
1148     // * If we're a historically stable-but-should-be-unstable option then we
1149     //   emit a warning that we're going to turn this into an error soon.
1150     nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());
1151
1152     if matches.opt_present("h") || matches.opt_present("help") {
1153         // Only show unstable options in --help if we *really* accept unstable
1154         // options, which catches the case where we got `-Z unstable-options` on
1155         // the stable channel of Rust which was accidentally allowed
1156         // historically.
1157         usage(matches.opt_present("verbose"),
1158               nightly_options::is_unstable_enabled(&matches));
1159         return None;
1160     }
1161
1162     // Don't handle -W help here, because we might first load plugins.
1163     let r = matches.opt_strs("Z");
1164     if r.iter().any(|x| *x == "help") {
1165         describe_debug_flags();
1166         return None;
1167     }
1168
1169     let cg_flags = matches.opt_strs("C");
1170     if cg_flags.iter().any(|x| *x == "help") {
1171         describe_codegen_flags();
1172         return None;
1173     }
1174
1175     if cg_flags.iter().any(|x| *x == "no-stack-check") {
1176         early_warn(ErrorOutputType::default(),
1177                    "the --no-stack-check flag is deprecated and does nothing");
1178     }
1179
1180     if cg_flags.contains(&"passes=list".to_string()) {
1181         rustc_trans::print_passes();
1182         return None;
1183     }
1184
1185     if matches.opt_present("version") {
1186         version("rustc", &matches);
1187         return None;
1188     }
1189
1190     Some(matches)
1191 }
1192
1193 fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> {
1194     match *input {
1195         Input::File(ref ifile) => {
1196             parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess)
1197         }
1198         Input::Str { ref name, ref input } => {
1199             parse::parse_crate_attrs_from_source_str(name.clone(),
1200                                                      input.clone(),
1201                                                      &sess.parse_sess)
1202         }
1203     }
1204 }
1205
1206 /// Runs `f` in a suitable thread for running `rustc`; returns a
1207 /// `Result` with either the return value of `f` or -- if a panic
1208 /// occurs -- the panic value.
1209 pub fn in_rustc_thread<F, R>(f: F) -> Result<R, Box<Any + Send>>
1210     where F: FnOnce() -> R + Send + 'static,
1211           R: Send + 'static,
1212 {
1213     // Temporarily have stack size set to 16MB to deal with nom-using crates failing
1214     const STACK_SIZE: usize = 16 * 1024 * 1024; // 16MB
1215
1216     let mut cfg = thread::Builder::new().name("rustc".to_string());
1217
1218     // FIXME: Hacks on hacks. If the env is trying to override the stack size
1219     // then *don't* set it explicitly.
1220     if env::var_os("RUST_MIN_STACK").is_none() {
1221         cfg = cfg.stack_size(STACK_SIZE);
1222     }
1223
1224     let thread = cfg.spawn(f);
1225     thread.unwrap().join()
1226 }
1227
1228 /// Run a procedure which will detect panics in the compiler and print nicer
1229 /// error messages rather than just failing the test.
1230 ///
1231 /// The diagnostic emitter yielded to the procedure should be used for reporting
1232 /// errors of the compiler.
1233 pub fn monitor<F: FnOnce() + Send + 'static>(f: F) {
1234     struct Sink(Arc<Mutex<Vec<u8>>>);
1235     impl Write for Sink {
1236         fn write(&mut self, data: &[u8]) -> io::Result<usize> {
1237             Write::write(&mut *self.0.lock().unwrap(), data)
1238         }
1239         fn flush(&mut self) -> io::Result<()> {
1240             Ok(())
1241         }
1242     }
1243
1244     let data = Arc::new(Mutex::new(Vec::new()));
1245     let err = Sink(data.clone());
1246
1247     let result = in_rustc_thread(move || {
1248         io::set_panic(Some(box err));
1249         f()
1250     });
1251
1252     if let Err(value) = result {
1253         // Thread panicked without emitting a fatal diagnostic
1254         if !value.is::<errors::FatalError>() {
1255             let emitter =
1256                 Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto,
1257                                                                 None,
1258                                                                 false));
1259             let handler = errors::Handler::with_emitter(true, false, emitter);
1260
1261             // a .span_bug or .bug call has already printed what
1262             // it wants to print.
1263             if !value.is::<errors::ExplicitBug>() {
1264                 handler.emit(&MultiSpan::new(),
1265                              "unexpected panic",
1266                              errors::Level::Bug);
1267             }
1268
1269             let xs = ["the compiler unexpectedly panicked. this is a bug.".to_string(),
1270                       format!("we would appreciate a bug report: {}", BUG_REPORT_URL),
1271                       format!("rustc {} running on {}",
1272                               option_env!("CFG_VERSION").unwrap_or("unknown_version"),
1273                               config::host_triple())];
1274             for note in &xs {
1275                 handler.emit(&MultiSpan::new(),
1276                              &note,
1277                              errors::Level::Note);
1278             }
1279             if match env::var_os("RUST_BACKTRACE") {
1280                 Some(val) => &val != "0",
1281                 None => false,
1282             } {
1283                 handler.emit(&MultiSpan::new(),
1284                              "run with `RUST_BACKTRACE=1` for a backtrace",
1285                              errors::Level::Note);
1286             }
1287
1288             eprintln!("{}", str::from_utf8(&data.lock().unwrap()).unwrap());
1289         }
1290
1291         exit_on_err();
1292     }
1293 }
1294
1295 fn exit_on_err() -> ! {
1296     // Panic so the process returns a failure code, but don't pollute the
1297     // output with some unnecessary panic messages, we've already
1298     // printed everything that we needed to.
1299     io::set_panic(Some(box io::sink()));
1300     panic!();
1301 }
1302
1303 #[cfg(stage0)]
1304 pub fn diagnostics_registry() -> errors::registry::Registry {
1305     use errors::registry::Registry;
1306
1307     Registry::new(&[])
1308 }
1309
1310 #[cfg(not(stage0))]
1311 pub fn diagnostics_registry() -> errors::registry::Registry {
1312     use errors::registry::Registry;
1313
1314     let mut all_errors = Vec::new();
1315     all_errors.extend_from_slice(&rustc::DIAGNOSTICS);
1316     all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS);
1317     all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
1318     all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
1319     #[cfg(feature="llvm")]
1320     all_errors.extend_from_slice(&rustc_trans::DIAGNOSTICS);
1321     all_errors.extend_from_slice(&rustc_trans_utils::DIAGNOSTICS);
1322     all_errors.extend_from_slice(&rustc_const_eval::DIAGNOSTICS);
1323     all_errors.extend_from_slice(&rustc_metadata::DIAGNOSTICS);
1324     all_errors.extend_from_slice(&rustc_passes::DIAGNOSTICS);
1325     all_errors.extend_from_slice(&rustc_plugin::DIAGNOSTICS);
1326     all_errors.extend_from_slice(&rustc_mir::DIAGNOSTICS);
1327     all_errors.extend_from_slice(&syntax::DIAGNOSTICS);
1328
1329     Registry::new(&all_errors)
1330 }
1331
1332 pub fn get_args() -> Vec<String> {
1333     env::args_os().enumerate()
1334         .map(|(i, arg)| arg.into_string().unwrap_or_else(|arg| {
1335              early_error(ErrorOutputType::default(),
1336                          &format!("Argument {} is not valid Unicode: {:?}", i, arg))
1337          }))
1338         .collect()
1339 }
1340
1341 pub fn main() {
1342     env_logger::init().unwrap();
1343     let result = run(|| run_compiler(&get_args(),
1344                                      &mut RustcDefaultCalls,
1345                                      None,
1346                                      None));
1347     process::exit(result as i32);
1348 }