]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/lib.rs
Rollup merge of #21325 - nagisa:thread-panicking, r=steveklabnik
[rust.git] / src / librustc_driver / lib.rs
1 // Copyright 2014 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 #![crate_name = "rustc_driver"]
18 #![unstable]
19 #![staged_api]
20 #![crate_type = "dylib"]
21 #![crate_type = "rlib"]
22 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
23       html_favicon_url = "http://www.rust-lang.org/favicon.ico",
24       html_root_url = "http://doc.rust-lang.org/nightly/")]
25
26 #![allow(unknown_features)]
27 #![feature(quote)]
28 #![feature(slicing_syntax, unsafe_destructor)]
29 #![feature(box_syntax)]
30 #![feature(rustc_diagnostic_macros)]
31 #![allow(unknown_features)] #![feature(int_uint)]
32 #![allow(unstable)]
33
34 extern crate arena;
35 extern crate flate;
36 extern crate getopts;
37 extern crate graphviz;
38 extern crate libc;
39 extern crate rustc;
40 extern crate rustc_back;
41 extern crate rustc_borrowck;
42 extern crate rustc_privacy;
43 extern crate rustc_resolve;
44 extern crate rustc_trans;
45 extern crate rustc_typeck;
46 extern crate serialize;
47 extern crate "rustc_llvm" as llvm;
48 #[macro_use] extern crate log;
49 #[macro_use] extern crate syntax;
50
51 pub use syntax::diagnostic;
52
53 use driver::CompileController;
54
55 use rustc_resolve as resolve;
56 use rustc_trans::back::link;
57 use rustc_trans::save;
58 use rustc::session::{config, Session, build_session};
59 use rustc::session::config::{Input, PrintRequest, UnstableFeatures};
60 use rustc::lint::Lint;
61 use rustc::lint;
62 use rustc::metadata;
63 use rustc::metadata::creader::CrateOrString::Str;
64 use rustc::util::common::time;
65
66 use std::cmp::Ordering::Equal;
67 use std::io;
68 use std::iter::repeat;
69 use std::os;
70 use std::sync::mpsc::channel;
71 use std::thread;
72
73 use rustc::session::early_error;
74
75 use syntax::ast;
76 use syntax::parse;
77 use syntax::diagnostic::Emitter;
78 use syntax::diagnostics;
79
80 #[cfg(test)]
81 pub mod test;
82
83 pub mod driver;
84 pub mod pretty;
85
86 pub fn run(args: Vec<String>) -> int {
87     monitor(move |:| run_compiler(args.as_slice()));
88     0
89 }
90
91 static BUG_REPORT_URL: &'static str =
92     "http://doc.rust-lang.org/complement-bugreport.html";
93
94 fn run_compiler(args: &[String]) {
95     let matches = match handle_options(args.to_vec()) {
96         Some(matches) => matches,
97         None => return
98     };
99
100     let descriptions = diagnostics_registry();
101     match matches.opt_str("explain") {
102         Some(ref code) => {
103             match descriptions.find_description(&code[]) {
104                 Some(ref description) => {
105                     println!("{}", description);
106                 }
107                 None => {
108                     early_error(&format!("no extended information for {}", code)[]);
109                 }
110             }
111             return;
112         },
113         None => ()
114     }
115
116     let sopts = config::build_session_options(&matches);
117     let odir = matches.opt_str("out-dir").map(|o| Path::new(o));
118     let ofile = matches.opt_str("o").map(|o| Path::new(o));
119     let (input, input_file_path) = match matches.free.len() {
120         0u => {
121             if sopts.describe_lints {
122                 let mut ls = lint::LintStore::new();
123                 ls.register_builtin(None);
124                 describe_lints(&ls, false);
125                 return;
126             }
127             let sess = build_session(sopts, None, descriptions);
128             if print_crate_info(&sess, None, &odir, &ofile) {
129                 return;
130             }
131             early_error("no input filename given");
132         }
133         1u => {
134             let ifile = &matches.free[0][];
135             if ifile == "-" {
136                 let contents = io::stdin().read_to_end().unwrap();
137                 let src = String::from_utf8(contents).unwrap();
138                 (Input::Str(src), None)
139             } else {
140                 (Input::File(Path::new(ifile)), Some(Path::new(ifile)))
141             }
142         }
143         _ => early_error("multiple input filenames provided")
144     };
145
146     let mut sopts = sopts;
147     sopts.unstable_features = get_unstable_features_setting();
148
149     let mut sess = build_session(sopts, input_file_path, descriptions);
150
151     let cfg = config::build_configuration(&sess);
152     if print_crate_info(&sess, Some(&input), &odir, &ofile) {
153         return
154     }
155
156     let pretty = if sess.opts.debugging_opts.unstable_options {
157         matches.opt_default("pretty", "normal").map(|a| {
158             // stable pretty-print variants only
159             pretty::parse_pretty(&sess, a.as_slice(), false)
160         })
161     } else {
162         None
163     };
164     let pretty = if pretty.is_none() &&
165         sess.unstable_options() {
166             matches.opt_str("xpretty").map(|a| {
167                 // extended with unstable pretty-print variants
168                 pretty::parse_pretty(&sess, a.as_slice(), true)
169             })
170         } else {
171             pretty
172         };
173
174     match pretty.into_iter().next() {
175         Some((ppm, opt_uii)) => {
176             pretty::pretty_print_input(sess, cfg, &input, ppm, opt_uii, ofile);
177             return;
178         }
179         None => {/* continue */ }
180     }
181
182     if sess.unstable_options() {
183         sess.opts.show_span = matches.opt_str("show-span");
184     }
185
186     let r = matches.opt_strs("Z");
187     if r.contains(&("ls".to_string())) {
188         match input {
189             Input::File(ref ifile) => {
190                 let mut stdout = io::stdout();
191                 list_metadata(&sess, &(*ifile), &mut stdout).unwrap();
192             }
193             Input::Str(_) => {
194                 early_error("cannot list metadata for stdin");
195             }
196         }
197         return;
198     }
199
200     let plugins = sess.opts.debugging_opts.extra_plugins.clone();
201     let control = build_controller(&sess);
202     driver::compile_input(sess, cfg, &input, &odir, &ofile, Some(plugins), control);
203 }
204
205 fn build_controller<'a>(sess: &Session) -> CompileController<'a> {
206     let mut control = CompileController::basic();
207
208     if sess.opts.parse_only ||
209        sess.opts.show_span.is_some() ||
210        sess.opts.debugging_opts.ast_json_noexpand {
211         control.after_parse.stop = true;
212     }
213
214     if sess.opts.no_analysis || sess.opts.debugging_opts.ast_json {
215         control.after_write_deps.stop = true;
216     }
217
218     if sess.opts.no_trans {
219         control.after_analysis.stop = true;
220     }
221
222     if !sess.opts.output_types.iter().any(|&i| i == config::OutputTypeExe) {
223         control.after_llvm.stop = true;
224     }
225
226     if sess.opts.debugging_opts.save_analysis {
227         control.after_analysis.callback = box |state| {
228             time(state.session.time_passes(), "save analysis", state.krate.unwrap(), |krate|
229                  save::process_crate(state.session,
230                                      krate,
231                                      state.analysis.unwrap(),
232                                      state.out_dir));
233         };
234         control.make_glob_map = resolve::MakeGlobMap::Yes;
235     }
236
237     control
238 }
239
240 pub fn get_unstable_features_setting() -> UnstableFeatures {
241     // Whether this is a feature-staged build, i.e. on the beta or stable channel
242     let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some();
243     // The secret key needed to get through the rustc build itself by
244     // subverting the unstable features lints
245     let bootstrap_secret_key = option_env!("CFG_BOOTSTRAP_KEY");
246     // The matching key to the above, only known by the build system
247     let bootstrap_provided_key = os::getenv("RUSTC_BOOTSTRAP_KEY");
248     match (disable_unstable_features, bootstrap_secret_key, bootstrap_provided_key) {
249         (_, Some(ref s), Some(ref p)) if s == p => UnstableFeatures::Cheat,
250         (true, _, _) => UnstableFeatures::Disallow,
251         (false, _, _) => UnstableFeatures::Default
252     }
253 }
254
255 /// Returns a version string such as "0.12.0-dev".
256 pub fn release_str() -> Option<&'static str> {
257     option_env!("CFG_RELEASE")
258 }
259
260 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
261 pub fn commit_hash_str() -> Option<&'static str> {
262     option_env!("CFG_VER_HASH")
263 }
264
265 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
266 pub fn commit_date_str() -> Option<&'static str> {
267     option_env!("CFG_VER_DATE")
268 }
269
270 /// Prints version information and returns None on success or an error
271 /// message on panic.
272 pub fn version(binary: &str, matches: &getopts::Matches) {
273     let verbose = matches.opt_present("verbose");
274
275     println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
276     if verbose {
277         fn unw(x: Option<&str>) -> &str { x.unwrap_or("unknown") }
278         println!("binary: {}", binary);
279         println!("commit-hash: {}", unw(commit_hash_str()));
280         println!("commit-date: {}", unw(commit_date_str()));
281         println!("host: {}", config::host_triple());
282         println!("release: {}", unw(release_str()));
283     }
284 }
285
286 fn usage(verbose: bool, include_unstable_options: bool) {
287     let groups = if verbose {
288         config::rustc_optgroups()
289     } else {
290         config::rustc_short_optgroups()
291     };
292     let groups : Vec<_> = groups.into_iter()
293         .filter(|x| include_unstable_options || x.is_stable())
294         .map(|x|x.opt_group)
295         .collect();
296     let message = format!("Usage: rustc [OPTIONS] INPUT");
297     let extra_help = if verbose {
298         ""
299     } else {
300         "\n    --help -v           Print the full set of options rustc accepts"
301     };
302     println!("{}\n\
303 Additional help:
304     -C help             Print codegen options
305     -W help             Print 'lint' options and default settings
306     -Z help             Print internal options for debugging rustc{}\n",
307               getopts::usage(message.as_slice(), groups.as_slice()),
308               extra_help);
309 }
310
311 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
312     println!("
313 Available lint options:
314     -W <foo>           Warn about <foo>
315     -A <foo>           Allow <foo>
316     -D <foo>           Deny <foo>
317     -F <foo>           Forbid <foo> (deny, and deny all overrides)
318
319 ");
320
321     fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
322         let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
323         lints.sort_by(|x: &&Lint, y: &&Lint| {
324             match x.default_level.cmp(&y.default_level) {
325                 // The sort doesn't case-fold but it's doubtful we care.
326                 Equal => x.name.cmp(y.name),
327                 r => r,
328             }
329         });
330         lints
331     }
332
333     fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
334                      -> Vec<(&'static str, Vec<lint::LintId>)> {
335         let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
336         lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
337                        &(y, _): &(&'static str, Vec<lint::LintId>)| {
338             x.cmp(y)
339         });
340         lints
341     }
342
343     let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
344         .iter().cloned().partition(|&(_, p)| p);
345     let plugin = sort_lints(plugin);
346     let builtin = sort_lints(builtin);
347
348     let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
349         .iter().cloned().partition(|&(_, _, p)| p);
350     let plugin_groups = sort_lint_groups(plugin_groups);
351     let builtin_groups = sort_lint_groups(builtin_groups);
352
353     let max_name_len = plugin.iter().chain(builtin.iter())
354         .map(|&s| s.name.width(true))
355         .max().unwrap_or(0);
356     let padded = |&: x: &str| {
357         let mut s = repeat(" ").take(max_name_len - x.chars().count())
358                                .collect::<String>();
359         s.push_str(x);
360         s
361     };
362
363     println!("Lint checks provided by rustc:\n");
364     println!("    {}  {:7.7}  {}", padded("name"), "default", "meaning");
365     println!("    {}  {:7.7}  {}", padded("----"), "-------", "-------");
366
367     let print_lints = |&: lints: Vec<&Lint>| {
368         for lint in lints.into_iter() {
369             let name = lint.name_lower().replace("_", "-");
370             println!("    {}  {:7.7}  {}",
371                      padded(&name[]), lint.default_level.as_str(), lint.desc);
372         }
373         println!("\n");
374     };
375
376     print_lints(builtin);
377
378
379
380     let max_name_len = plugin_groups.iter().chain(builtin_groups.iter())
381         .map(|&(s, _)| s.width(true))
382         .max().unwrap_or(0);
383     let padded = |&: x: &str| {
384         let mut s = repeat(" ").take(max_name_len - x.chars().count())
385                                .collect::<String>();
386         s.push_str(x);
387         s
388     };
389
390     println!("Lint groups provided by rustc:\n");
391     println!("    {}  {}", padded("name"), "sub-lints");
392     println!("    {}  {}", padded("----"), "---------");
393
394     let print_lint_groups = |&: lints: Vec<(&'static str, Vec<lint::LintId>)>| {
395         for (name, to) in lints.into_iter() {
396             let name = name.chars().map(|x| x.to_lowercase())
397                            .collect::<String>().replace("_", "-");
398             let desc = to.into_iter().map(|x| x.as_str().replace("_", "-"))
399                          .collect::<Vec<String>>().connect(", ");
400             println!("    {}  {}",
401                      padded(&name[]), desc);
402         }
403         println!("\n");
404     };
405
406     print_lint_groups(builtin_groups);
407
408     match (loaded_plugins, plugin.len(), plugin_groups.len()) {
409         (false, 0, _) | (false, _, 0) => {
410             println!("Compiler plugins can provide additional lints and lint groups. To see a \
411                       listing of these, re-run `rustc -W help` with a crate filename.");
412         }
413         (false, _, _) => panic!("didn't load lint plugins but got them anyway!"),
414         (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
415         (true, l, g) => {
416             if l > 0 {
417                 println!("Lint checks provided by plugins loaded by this crate:\n");
418                 print_lints(plugin);
419             }
420             if g > 0 {
421                 println!("Lint groups provided by plugins loaded by this crate:\n");
422                 print_lint_groups(plugin_groups);
423             }
424         }
425     }
426 }
427
428 fn describe_debug_flags() {
429     println!("\nAvailable debug options:\n");
430     for &(name, _, opt_type_desc, desc) in config::DB_OPTIONS.iter() {
431         let (width, extra) = match opt_type_desc {
432             Some(..) => (21, "=val"),
433             None => (25, "")
434         };
435         println!("    -Z {:>width$}{} -- {}", name.replace("_", "-"),
436                  extra, desc, width=width);
437     }
438 }
439
440 fn describe_codegen_flags() {
441     println!("\nAvailable codegen options:\n");
442     for &(name, _, opt_type_desc, desc) in config::CG_OPTIONS.iter() {
443         let (width, extra) = match opt_type_desc {
444             Some(..) => (21, "=val"),
445             None => (25, "")
446         };
447         println!("    -C {:>width$}{} -- {}", name.replace("_", "-"),
448                  extra, desc, width=width);
449     }
450 }
451
452 /// Process command line options. Emits messages as appropriate. If compilation
453 /// should continue, returns a getopts::Matches object parsed from args, otherwise
454 /// returns None.
455 pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
456     // Throw away the first argument, the name of the binary
457     let _binary = args.remove(0);
458
459     if args.is_empty() {
460         // user did not write `-v` nor `-Z unstable-options`, so do not
461         // include that extra information.
462         usage(false, false);
463         return None;
464     }
465
466     let matches =
467         match getopts::getopts(&args[], &config::optgroups()[]) {
468             Ok(m) => m,
469             Err(f_stable_attempt) => {
470                 // redo option parsing, including unstable options this time,
471                 // in anticipation that the mishandled option was one of the
472                 // unstable ones.
473                 let all_groups : Vec<getopts::OptGroup>
474                     = config::rustc_optgroups().into_iter().map(|x|x.opt_group).collect();
475                 match getopts::getopts(args.as_slice(), all_groups.as_slice()) {
476                     Ok(m_unstable) => {
477                         let r = m_unstable.opt_strs("Z");
478                         let include_unstable_options = r.iter().any(|x| *x == "unstable-options");
479                         if include_unstable_options {
480                             m_unstable
481                         } else {
482                             early_error(f_stable_attempt.to_string().as_slice());
483                         }
484                     }
485                     Err(_) => {
486                         // ignore the error from the unstable attempt; just
487                         // pass the error we got from the first try.
488                         early_error(f_stable_attempt.to_string().as_slice());
489                     }
490                 }
491             }
492         };
493
494     let r = matches.opt_strs("Z");
495     let include_unstable_options = r.iter().any(|x| *x == "unstable-options");
496
497     if matches.opt_present("h") || matches.opt_present("help") {
498         usage(matches.opt_present("verbose"), include_unstable_options);
499         return None;
500     }
501
502     // Don't handle -W help here, because we might first load plugins.
503
504     let r = matches.opt_strs("Z");
505     if r.iter().any(|x| *x == "help") {
506         describe_debug_flags();
507         return None;
508     }
509
510     let cg_flags = matches.opt_strs("C");
511     if cg_flags.iter().any(|x| *x == "help") {
512         describe_codegen_flags();
513         return None;
514     }
515
516     if cg_flags.contains(&"passes=list".to_string()) {
517         unsafe { ::llvm::LLVMRustPrintPasses(); }
518         return None;
519     }
520
521     if matches.opt_present("version") {
522         version("rustc", &matches);
523         return None;
524     }
525
526     Some(matches)
527 }
528
529 fn print_crate_info(sess: &Session,
530                     input: Option<&Input>,
531                     odir: &Option<Path>,
532                     ofile: &Option<Path>)
533                     -> bool {
534     if sess.opts.prints.len() == 0 { return false }
535
536     let attrs = input.map(|input| parse_crate_attrs(sess, input));
537     for req in sess.opts.prints.iter() {
538         match *req {
539             PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
540             PrintRequest::FileNames |
541             PrintRequest::CrateName => {
542                 let input = match input {
543                     Some(input) => input,
544                     None => early_error("no input file provided"),
545                 };
546                 let attrs = attrs.as_ref().unwrap().as_slice();
547                 let t_outputs = driver::build_output_filenames(input,
548                                                                odir,
549                                                                ofile,
550                                                                attrs,
551                                                                sess);
552                 let id = link::find_crate_name(Some(sess), attrs.as_slice(),
553                                                input);
554                 if *req == PrintRequest::CrateName {
555                     println!("{}", id);
556                     continue
557                 }
558                 let crate_types = driver::collect_crate_types(sess, attrs);
559                 let metadata = driver::collect_crate_metadata(sess, attrs);
560                 *sess.crate_metadata.borrow_mut() = metadata;
561                 for &style in crate_types.iter() {
562                     let fname = link::filename_for_input(sess, style,
563                                                          id.as_slice(),
564                                                          &t_outputs.with_extension(""));
565                     println!("{}", fname.filename_display());
566                 }
567             }
568         }
569     }
570     return true;
571 }
572
573 fn parse_crate_attrs(sess: &Session, input: &Input) ->
574                      Vec<ast::Attribute> {
575     let result = match *input {
576         Input::File(ref ifile) => {
577             parse::parse_crate_attrs_from_file(ifile,
578                                                Vec::new(),
579                                                &sess.parse_sess)
580         }
581         Input::Str(ref src) => {
582             parse::parse_crate_attrs_from_source_str(
583                 driver::anon_src().to_string(),
584                 src.to_string(),
585                 Vec::new(),
586                 &sess.parse_sess)
587         }
588     };
589     result.into_iter().collect()
590 }
591
592 pub fn list_metadata(sess: &Session, path: &Path,
593                      out: &mut io::Writer) -> io::IoResult<()> {
594     metadata::loader::list_file_metadata(sess.target.target.options.is_like_osx, path, out)
595 }
596
597 /// Run a procedure which will detect panics in the compiler and print nicer
598 /// error messages rather than just failing the test.
599 ///
600 /// The diagnostic emitter yielded to the procedure should be used for reporting
601 /// errors of the compiler.
602 pub fn monitor<F:FnOnce()+Send>(f: F) {
603     static STACK_SIZE: uint = 8 * 1024 * 1024; // 8MB
604
605     let (tx, rx) = channel();
606     let w = io::ChanWriter::new(tx);
607     let mut r = io::ChanReader::new(rx);
608
609     let mut cfg = thread::Builder::new().name("rustc".to_string());
610
611     // FIXME: Hacks on hacks. If the env is trying to override the stack size
612     // then *don't* set it explicitly.
613     if os::getenv("RUST_MIN_STACK").is_none() {
614         cfg = cfg.stack_size(STACK_SIZE);
615     }
616
617     match cfg.scoped(move || { std::io::stdio::set_stderr(box w); f() }).join() {
618         Ok(()) => { /* fallthrough */ }
619         Err(value) => {
620             // Thread panicked without emitting a fatal diagnostic
621             if !value.is::<diagnostic::FatalError>() {
622                 let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
623
624                 // a .span_bug or .bug call has already printed what
625                 // it wants to print.
626                 if !value.is::<diagnostic::ExplicitBug>() {
627                     emitter.emit(
628                         None,
629                         "unexpected panic",
630                         None,
631                         diagnostic::Bug);
632                 }
633
634                 let xs = [
635                     "the compiler unexpectedly panicked. this is a bug.".to_string(),
636                     format!("we would appreciate a bug report: {}",
637                             BUG_REPORT_URL),
638                     "run with `RUST_BACKTRACE=1` for a backtrace".to_string(),
639                 ];
640                 for note in xs.iter() {
641                     emitter.emit(None, &note[], None, diagnostic::Note)
642                 }
643
644                 match r.read_to_string() {
645                     Ok(s) => println!("{}", s),
646                     Err(e) => {
647                         emitter.emit(None,
648                                      &format!("failed to read internal \
649                                               stderr: {}", e)[],
650                                      None,
651                                      diagnostic::Error)
652                     }
653                 }
654             }
655
656             // Panic so the process returns a failure code, but don't pollute the
657             // output with some unnecessary panic messages, we've already
658             // printed everything that we needed to.
659             io::stdio::set_stderr(box io::util::NullWriter);
660             panic!();
661         }
662     }
663 }
664
665 pub fn diagnostics_registry() -> diagnostics::registry::Registry {
666     use syntax::diagnostics::registry::Registry;
667
668     let all_errors = Vec::new() +
669         rustc::diagnostics::DIAGNOSTICS.as_slice() +
670         rustc_typeck::diagnostics::DIAGNOSTICS.as_slice() +
671         rustc_resolve::diagnostics::DIAGNOSTICS.as_slice();
672
673     Registry::new(&*all_errors)
674 }
675
676 pub fn main() {
677     let args = std::os::args();
678     let result = run(args);
679     std::os::set_exit_status(result);
680 }
681