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