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