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