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.
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.
11 //! The Rust compiler.
15 //! This API is completely unstable and subject to change.
17 #![crate_name = "rustc_driver"]
18 #![unstable(feature = "rustc_private")]
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/")]
26 #![feature(box_syntax)]
27 #![feature(collections)]
35 #![feature(rustc_diagnostic_macros)]
36 #![feature(rustc_private)]
37 #![feature(slicing_syntax, unsafe_destructor)]
38 #![feature(staged_api)]
45 extern crate graphviz;
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;
59 pub use syntax::diagnostic;
61 use driver::CompileController;
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;
71 use rustc::metadata::creader::CrateOrString::Str;
72 use rustc::util::common::time;
74 use std::cmp::Ordering::Equal;
76 use std::iter::repeat;
78 use std::sync::mpsc::channel;
81 use rustc::session::early_error;
85 use syntax::diagnostic::Emitter;
86 use syntax::diagnostics;
94 pub fn run(args: Vec<String>) -> int {
95 monitor(move |:| run_compiler(args.as_slice()));
99 static BUG_REPORT_URL: &'static str =
100 "http://doc.rust-lang.org/complement-bugreport.html";
102 fn run_compiler(args: &[String]) {
103 let matches = match handle_options(args.to_vec()) {
104 Some(matches) => matches,
108 let descriptions = diagnostics_registry();
109 match matches.opt_str("explain") {
111 match descriptions.find_description(&code[]) {
112 Some(ref description) => {
113 println!("{}", description);
116 early_error(&format!("no extended information for {}", code)[]);
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() {
129 if sopts.describe_lints {
130 let mut ls = lint::LintStore::new();
131 ls.register_builtin(None);
132 describe_lints(&ls, false);
135 let sess = build_session(sopts, None, descriptions);
136 if print_crate_info(&sess, None, &odir, &ofile) {
139 early_error("no input filename given");
142 let ifile = &matches.free[0][];
144 let contents = old_io::stdin().read_to_end().unwrap();
145 let src = String::from_utf8(contents).unwrap();
146 (Input::Str(src), None)
148 (Input::File(Path::new(ifile)), Some(Path::new(ifile)))
151 _ => early_error("multiple input filenames provided")
154 let mut sopts = sopts;
155 sopts.unstable_features = get_unstable_features_setting();
157 let mut sess = build_session(sopts, input_file_path, descriptions);
159 let cfg = config::build_configuration(&sess);
160 if print_crate_info(&sess, Some(&input), &odir, &ofile) {
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)
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)
182 match pretty.into_iter().next() {
183 Some((ppm, opt_uii)) => {
184 pretty::pretty_print_input(sess, cfg, &input, ppm, opt_uii, ofile);
187 None => {/* continue */ }
190 if sess.unstable_options() {
191 sess.opts.show_span = matches.opt_str("show-span");
194 let r = matches.opt_strs("Z");
195 if r.contains(&("ls".to_string())) {
197 Input::File(ref ifile) => {
198 let mut stdout = old_io::stdout();
199 list_metadata(&sess, &(*ifile), &mut stdout).unwrap();
202 early_error("cannot list metadata for stdin");
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);
213 fn build_controller<'a>(sess: &Session) -> CompileController<'a> {
214 let mut control = CompileController::basic();
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;
222 if sess.opts.no_analysis || sess.opts.debugging_opts.ast_json {
223 control.after_write_deps.stop = true;
226 if sess.opts.no_trans {
227 control.after_analysis.stop = true;
230 if !sess.opts.output_types.iter().any(|&i| i == config::OutputTypeExe) {
231 control.after_llvm.stop = true;
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,
239 state.analysis.unwrap(),
242 control.make_glob_map = resolve::MakeGlobMap::Yes;
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
263 /// Returns a version string such as "0.12.0-dev".
264 pub fn release_str() -> Option<&'static str> {
265 option_env!("CFG_RELEASE")
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")
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")
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");
283 println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
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()));
294 fn usage(verbose: bool, include_unstable_options: bool) {
295 let groups = if verbose {
296 config::rustc_optgroups()
298 config::rustc_short_optgroups()
300 let groups : Vec<_> = groups.into_iter()
301 .filter(|x| include_unstable_options || x.is_stable())
304 let message = format!("Usage: rustc [OPTIONS] INPUT");
305 let extra_help = if verbose {
308 "\n --help -v Print the full set of options rustc accepts"
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()),
319 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
321 Available lint options:
322 -W <foo> Warn about <foo>
325 -F <foo> Forbid <foo> (deny, and deny all overrides)
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),
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>)| {
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);
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);
361 let max_name_len = plugin.iter().chain(builtin.iter())
362 .map(|&s| s.name.width(true))
364 let padded = |&: x: &str| {
365 let mut s = repeat(" ").take(max_name_len - x.chars().count())
366 .collect::<String>();
371 println!("Lint checks provided by rustc:\n");
372 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
373 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
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);
384 print_lints(builtin);
388 let max_name_len = plugin_groups.iter().chain(builtin_groups.iter())
389 .map(|&(s, _)| s.width(true))
391 let padded = |&: x: &str| {
392 let mut s = repeat(" ").take(max_name_len - x.chars().count())
393 .collect::<String>();
398 println!("Lint groups provided by rustc:\n");
399 println!(" {} {}", padded("name"), "sub-lints");
400 println!(" {} {}", padded("----"), "---------");
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(", ");
409 padded(&name[]), desc);
414 print_lint_groups(builtin_groups);
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.");
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."),
425 println!("Lint checks provided by plugins loaded by this crate:\n");
429 println!("Lint groups provided by plugins loaded by this crate:\n");
430 print_lint_groups(plugin_groups);
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"),
443 println!(" -Z {:>width$}{} -- {}", name.replace("_", "-"),
444 extra, desc, width=width);
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"),
455 println!(" -C {:>width$}{} -- {}", name.replace("_", "-"),
456 extra, desc, width=width);
460 /// Process command line options. Emits messages as appropriate. If compilation
461 /// should continue, returns a getopts::Matches object parsed from args, otherwise
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);
468 // user did not write `-v` nor `-Z unstable-options`, so do not
469 // include that extra information.
475 match getopts::getopts(&args[], &config::optgroups()[]) {
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
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()) {
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 {
490 early_error(f_stable_attempt.to_string().as_slice());
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());
502 let r = matches.opt_strs("Z");
503 let include_unstable_options = r.iter().any(|x| *x == "unstable-options");
505 if matches.opt_present("h") || matches.opt_present("help") {
506 usage(matches.opt_present("verbose"), include_unstable_options);
510 // Don't handle -W help here, because we might first load plugins.
512 let r = matches.opt_strs("Z");
513 if r.iter().any(|x| *x == "help") {
514 describe_debug_flags();
518 let cg_flags = matches.opt_strs("C");
519 if cg_flags.iter().any(|x| *x == "help") {
520 describe_codegen_flags();
524 if cg_flags.contains(&"passes=list".to_string()) {
525 unsafe { ::llvm::LLVMRustPrintPasses(); }
529 if matches.opt_present("version") {
530 version("rustc", &matches);
537 fn print_crate_info(sess: &Session,
538 input: Option<&Input>,
540 ofile: &Option<Path>)
542 if sess.opts.prints.len() == 0 { return false }
544 let attrs = input.map(|input| parse_crate_attrs(sess, input));
545 for req in sess.opts.prints.iter() {
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"),
554 let attrs = attrs.as_ref().unwrap().as_slice();
555 let t_outputs = driver::build_output_filenames(input,
560 let id = link::find_crate_name(Some(sess), attrs.as_slice(),
562 if *req == PrintRequest::CrateName {
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,
572 &t_outputs.with_extension(""));
573 println!("{}", fname.filename_display());
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,
589 Input::Str(ref src) => {
590 parse::parse_crate_attrs_from_source_str(
591 driver::anon_src().to_string(),
597 result.into_iter().collect()
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)
605 /// Run a procedure which will detect panics in the compiler and print nicer
606 /// error messages rather than just failing the test.
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
613 let (tx, rx) = channel();
614 let w = old_io::ChanWriter::new(tx);
615 let mut r = old_io::ChanReader::new(rx);
617 let mut cfg = thread::Builder::new().name("rustc".to_string());
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);
625 match cfg.scoped(move || { std::old_io::stdio::set_stderr(box w); f() }).join() {
626 Ok(()) => { /* fallthrough */ }
628 // Thread panicked without emitting a fatal diagnostic
629 if !value.is::<diagnostic::FatalError>() {
630 let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
632 // a .span_bug or .bug call has already printed what
633 // it wants to print.
634 if !value.is::<diagnostic::ExplicitBug>() {
643 "the compiler unexpectedly panicked. this is a bug.".to_string(),
644 format!("we would appreciate a bug report: {}",
646 "run with `RUST_BACKTRACE=1` for a backtrace".to_string(),
648 for note in xs.iter() {
649 emitter.emit(None, ¬e[], None, diagnostic::Note)
652 match r.read_to_string() {
653 Ok(s) => println!("{}", s),
656 &format!("failed to read internal \
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);
673 pub fn diagnostics_registry() -> diagnostics::registry::Registry {
674 use syntax::diagnostics::registry::Registry;
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();
681 Registry::new(&*all_errors)
685 let args = std::os::args();
686 let result = run(args);
687 std::os::set_exit_status(result);