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