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"]
19 #![crate_type = "dylib"]
20 #![crate_type = "rlib"]
21 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
22 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
23 html_root_url = "http://doc.rust-lang.org/nightly/")]
25 #![feature(default_type_params, globs, macro_rules, phase, quote)]
26 #![feature(slicing_syntax, unsafe_destructor)]
27 #![feature(rustc_diagnostic_macros)]
28 #![feature(unboxed_closures)]
33 extern crate graphviz;
36 extern crate rustc_back;
37 extern crate rustc_borrowck;
38 extern crate rustc_resolve;
39 extern crate rustc_trans;
40 extern crate rustc_typeck;
41 #[phase(plugin, link)] extern crate log;
42 #[phase(plugin, link)] extern crate syntax;
43 extern crate serialize;
44 extern crate "rustc_llvm" as llvm;
46 pub use syntax::diagnostic;
48 use rustc_trans::back::link;
49 use rustc::session::{config, Session, build_session};
50 use rustc::session::config::{Input, PrintRequest};
51 use rustc::lint::Lint;
54 use rustc::DIAGNOSTICS;
56 use std::any::AnyRefExt;
58 use std::iter::repeat;
62 use rustc::session::early_error;
66 use syntax::diagnostic::Emitter;
67 use syntax::diagnostics;
75 pub fn run(args: Vec<String>) -> int {
76 monitor(move |:| run_compiler(args.as_slice()));
80 static BUG_REPORT_URL: &'static str =
81 "http://doc.rust-lang.org/complement-bugreport.html";
83 fn run_compiler(args: &[String]) {
84 let matches = match handle_options(args.to_vec()) {
85 Some(matches) => matches,
89 let descriptions = diagnostics::registry::Registry::new(&DIAGNOSTICS);
90 match matches.opt_str("explain") {
92 match descriptions.find_description(code[]) {
93 Some(ref description) => {
94 println!("{}", description);
97 early_error(format!("no extended information for {}", code)[]);
105 let sopts = config::build_session_options(&matches);
106 let odir = matches.opt_str("out-dir").map(|o| Path::new(o));
107 let ofile = matches.opt_str("o").map(|o| Path::new(o));
108 let (input, input_file_path) = match matches.free.len() {
110 if sopts.describe_lints {
111 let mut ls = lint::LintStore::new();
112 ls.register_builtin(None);
113 describe_lints(&ls, false);
116 let sess = build_session(sopts, None, descriptions);
117 if print_crate_info(&sess, None, &odir, &ofile) {
120 early_error("no input filename given");
123 let ifile = matches.free[0][];
125 let contents = io::stdin().read_to_end().unwrap();
126 let src = String::from_utf8(contents).unwrap();
127 (Input::Str(src), None)
129 (Input::File(Path::new(ifile)), Some(Path::new(ifile)))
132 _ => early_error("multiple input filenames provided")
135 let sess = build_session(sopts, input_file_path, descriptions);
136 let cfg = config::build_configuration(&sess);
137 if print_crate_info(&sess, Some(&input), &odir, &ofile) {
141 let pretty = matches.opt_default("pretty", "normal").map(|a| {
142 // stable pretty-print variants only
143 pretty::parse_pretty(&sess, a.as_slice(), false)
145 let pretty = if pretty.is_none() &&
146 sess.debugging_opt(config::UNSTABLE_OPTIONS) {
147 matches.opt_str("xpretty").map(|a| {
148 // extended with unstable pretty-print variants
149 pretty::parse_pretty(&sess, a.as_slice(), true)
155 match pretty.into_iter().next() {
156 Some((ppm, opt_uii)) => {
157 pretty::pretty_print_input(sess, cfg, &input, ppm, opt_uii, ofile);
160 None => {/* continue */ }
163 let r = matches.opt_strs("Z");
164 if r.contains(&("ls".to_string())) {
166 Input::File(ref ifile) => {
167 let mut stdout = io::stdout();
168 list_metadata(&sess, &(*ifile), &mut stdout).unwrap();
171 early_error("can not list metadata for stdin");
177 driver::compile_input(sess, cfg, &input, &odir, &ofile, None);
180 /// Returns a version string such as "0.12.0-dev".
181 pub fn release_str() -> Option<&'static str> {
182 option_env!("CFG_RELEASE")
185 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
186 pub fn commit_hash_str() -> Option<&'static str> {
187 option_env!("CFG_VER_HASH")
190 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
191 pub fn commit_date_str() -> Option<&'static str> {
192 option_env!("CFG_VER_DATE")
195 /// Prints version information and returns None on success or an error
196 /// message on panic.
197 pub fn version(binary: &str, matches: &getopts::Matches) {
198 let verbose = matches.opt_present("verbose");
200 println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
202 fn unw(x: Option<&str>) -> &str { x.unwrap_or("unknown") }
203 println!("binary: {}", binary);
204 println!("commit-hash: {}", unw(commit_hash_str()));
205 println!("commit-date: {}", unw(commit_date_str()));
206 println!("host: {}", config::host_triple());
207 println!("release: {}", unw(release_str()));
211 fn usage(verbose: bool, include_unstable_options: bool) {
212 let groups = if verbose {
213 config::rustc_optgroups()
215 config::rustc_short_optgroups()
217 let groups : Vec<_> = groups.into_iter()
218 .filter(|x| include_unstable_options || x.is_stable())
221 let message = format!("Usage: rustc [OPTIONS] INPUT");
222 let extra_help = if verbose {
225 "\n --help -v Print the full set of options rustc accepts"
229 -C help Print codegen options
230 -W help Print 'lint' options and default settings
231 -Z help Print internal options for debugging rustc{}\n",
232 getopts::usage(message.as_slice(), groups.as_slice()),
236 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
238 Available lint options:
239 -W <foo> Warn about <foo>
242 -F <foo> Forbid <foo> (deny, and deny all overrides)
246 fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
247 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
248 lints.sort_by(|x: &&Lint, y: &&Lint| {
249 match x.default_level.cmp(&y.default_level) {
250 // The sort doesn't case-fold but it's doubtful we care.
251 Equal => x.name.cmp(y.name),
258 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
259 -> Vec<(&'static str, Vec<lint::LintId>)> {
260 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
261 lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
262 &(y, _): &(&'static str, Vec<lint::LintId>)| {
268 let (plugin, builtin) = lint_store.get_lints().partitioned(|&(_, p)| p);
269 let plugin = sort_lints(plugin);
270 let builtin = sort_lints(builtin);
272 let (plugin_groups, builtin_groups) = lint_store.get_lint_groups().partitioned(|&(_, _, p)| p);
273 let plugin_groups = sort_lint_groups(plugin_groups);
274 let builtin_groups = sort_lint_groups(builtin_groups);
276 let max_name_len = plugin.iter().chain(builtin.iter())
277 .map(|&s| s.name.width(true))
279 let padded = |x: &str| {
280 let mut s = repeat(" ").take(max_name_len - x.chars().count())
281 .collect::<String>();
286 println!("Lint checks provided by rustc:\n");
287 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
288 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
290 let print_lints = |lints: Vec<&Lint>| {
291 for lint in lints.into_iter() {
292 let name = lint.name_lower().replace("_", "-");
293 println!(" {} {:7.7} {}",
294 padded(name[]), lint.default_level.as_str(), lint.desc);
299 print_lints(builtin);
303 let max_name_len = plugin_groups.iter().chain(builtin_groups.iter())
304 .map(|&(s, _)| s.width(true))
306 let padded = |x: &str| {
307 let mut s = repeat(" ").take(max_name_len - x.chars().count())
308 .collect::<String>();
313 println!("Lint groups provided by rustc:\n");
314 println!(" {} {}", padded("name"), "sub-lints");
315 println!(" {} {}", padded("----"), "---------");
317 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
318 for (name, to) in lints.into_iter() {
319 let name = name.chars().map(|x| x.to_lowercase())
320 .collect::<String>().replace("_", "-");
321 let desc = to.into_iter().map(|x| x.as_str().replace("_", "-"))
322 .collect::<Vec<String>>().connect(", ");
324 padded(name[]), desc);
329 print_lint_groups(builtin_groups);
331 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
332 (false, 0, _) | (false, _, 0) => {
333 println!("Compiler plugins can provide additional lints and lint groups. To see a \
334 listing of these, re-run `rustc -W help` with a crate filename.");
336 (false, _, _) => panic!("didn't load lint plugins but got them anyway!"),
337 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
340 println!("Lint checks provided by plugins loaded by this crate:\n");
344 println!("Lint groups provided by plugins loaded by this crate:\n");
345 print_lint_groups(plugin_groups);
351 fn describe_debug_flags() {
352 println!("\nAvailable debug options:\n");
353 let r = config::debugging_opts_map();
354 for tuple in r.iter() {
356 (ref name, ref desc, _) => {
357 println!(" -Z {:>20} -- {}", *name, *desc);
363 fn describe_codegen_flags() {
364 println!("\nAvailable codegen options:\n");
365 for &(name, _, opt_type_desc, desc) in config::CG_OPTIONS.iter() {
366 let (width, extra) = match opt_type_desc {
367 Some(..) => (21, "=val"),
370 println!(" -C {:>width$}{} -- {}", name.replace("_", "-"),
371 extra, desc, width=width);
375 /// Process command line options. Emits messages as appropriate. If compilation
376 /// should continue, returns a getopts::Matches object parsed from args, otherwise
378 pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
379 // Throw away the first argument, the name of the binary
380 let _binary = args.remove(0).unwrap();
383 // user did not write `-v` nor `-Z unstable-options`, so do not
384 // include that extra information.
390 match getopts::getopts(args[], config::optgroups()[]) {
392 Err(f_stable_attempt) => {
393 // redo option parsing, including unstable options this time,
394 // in anticipation that the mishandled option was one of the
396 let all_groups : Vec<getopts::OptGroup>
397 = config::rustc_optgroups().into_iter().map(|x|x.opt_group).collect();
398 match getopts::getopts(args.as_slice(), all_groups.as_slice()) {
400 let r = m_unstable.opt_strs("Z");
401 let include_unstable_options = r.iter().any(|x| *x == "unstable-options");
402 if include_unstable_options {
405 early_error(f_stable_attempt.to_string().as_slice());
409 // ignore the error from the unstable attempt; just
410 // pass the error we got from the first try.
411 early_error(f_stable_attempt.to_string().as_slice());
417 let r = matches.opt_strs("Z");
418 let include_unstable_options = r.iter().any(|x| *x == "unstable-options");
420 if matches.opt_present("h") || matches.opt_present("help") {
421 usage(matches.opt_present("verbose"), include_unstable_options);
425 // Don't handle -W help here, because we might first load plugins.
427 let r = matches.opt_strs("Z");
428 if r.iter().any(|x| *x == "help") {
429 describe_debug_flags();
433 let cg_flags = matches.opt_strs("C");
434 if cg_flags.iter().any(|x| *x == "help") {
435 describe_codegen_flags();
439 if cg_flags.contains(&"passes=list".to_string()) {
440 unsafe { ::llvm::LLVMRustPrintPasses(); }
444 if matches.opt_present("version") {
445 version("rustc", &matches);
452 fn print_crate_info(sess: &Session,
453 input: Option<&Input>,
455 ofile: &Option<Path>)
457 if sess.opts.prints.len() == 0 { return false }
459 let attrs = input.map(|input| parse_crate_attrs(sess, input));
460 for req in sess.opts.prints.iter() {
462 PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
463 PrintRequest::FileNames |
464 PrintRequest::CrateName => {
465 let input = match input {
466 Some(input) => input,
467 None => early_error("no input file provided"),
469 let attrs = attrs.as_ref().unwrap().as_slice();
470 let t_outputs = driver::build_output_filenames(input,
475 let id = link::find_crate_name(Some(sess), attrs.as_slice(),
477 if *req == PrintRequest::CrateName {
481 let crate_types = driver::collect_crate_types(sess, attrs);
482 let metadata = driver::collect_crate_metadata(sess, attrs);
483 *sess.crate_metadata.borrow_mut() = metadata;
484 for &style in crate_types.iter() {
485 let fname = link::filename_for_input(sess, style,
487 &t_outputs.with_extension(""));
488 println!("{}", fname.filename_display());
496 fn parse_crate_attrs(sess: &Session, input: &Input) ->
497 Vec<ast::Attribute> {
498 let result = match *input {
499 Input::File(ref ifile) => {
500 parse::parse_crate_attrs_from_file(ifile,
504 Input::Str(ref src) => {
505 parse::parse_crate_attrs_from_source_str(
506 driver::anon_src().to_string(),
512 result.into_iter().collect()
515 pub fn list_metadata(sess: &Session, path: &Path,
516 out: &mut io::Writer) -> io::IoResult<()> {
517 metadata::loader::list_file_metadata(sess.target.target.options.is_like_osx, path, out)
520 /// Run a procedure which will detect panics in the compiler and print nicer
521 /// error messages rather than just failing the test.
523 /// The diagnostic emitter yielded to the procedure should be used for reporting
524 /// errors of the compiler.
525 pub fn monitor<F:FnOnce()+Send>(f: F) {
526 static STACK_SIZE: uint = 8 * 1024 * 1024; // 8MB
528 let (tx, rx) = channel();
529 let w = io::ChanWriter::new(tx);
530 let mut r = io::ChanReader::new(rx);
532 let mut cfg = thread::Builder::new().name("rustc".to_string());
534 // FIXME: Hacks on hacks. If the env is trying to override the stack size
535 // then *don't* set it explicitly.
536 if os::getenv("RUST_MIN_STACK").is_none() {
537 cfg = cfg.stack_size(STACK_SIZE);
540 match cfg.spawn(move || { std::io::stdio::set_stderr(box w); f() }).join() {
541 Ok(()) => { /* fallthrough */ }
543 // Thread panicked without emitting a fatal diagnostic
544 if !value.is::<diagnostic::FatalError>() {
545 let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
547 // a .span_bug or .bug call has already printed what
548 // it wants to print.
549 if !value.is::<diagnostic::ExplicitBug>() {
558 "the compiler unexpectedly panicked. this is a bug.".to_string(),
559 format!("we would appreciate a bug report: {}",
561 "run with `RUST_BACKTRACE=1` for a backtrace".to_string(),
563 for note in xs.iter() {
564 emitter.emit(None, note[], None, diagnostic::Note)
567 match r.read_to_string() {
568 Ok(s) => println!("{}", s),
571 format!("failed to read internal \
579 // Panic so the process returns a failure code, but don't pollute the
580 // output with some unnecessary panic messages, we've already
581 // printed everything that we needed to.
582 io::stdio::set_stderr(box io::util::NullWriter);
589 let args = std::os::args();
590 let result = run(args);
591 std::os::set_exit_status(result);