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): (Vec<_>, _) = lint_store.get_lints()
269 .iter().cloned().partition(|&(_, p)| p);
270 let plugin = sort_lints(plugin);
271 let builtin = sort_lints(builtin);
273 let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
274 .iter().cloned().partition(|&(_, _, p)| p);
275 let plugin_groups = sort_lint_groups(plugin_groups);
276 let builtin_groups = sort_lint_groups(builtin_groups);
278 let max_name_len = plugin.iter().chain(builtin.iter())
279 .map(|&s| s.name.width(true))
281 let padded = |x: &str| {
282 let mut s = repeat(" ").take(max_name_len - x.chars().count())
283 .collect::<String>();
288 println!("Lint checks provided by rustc:\n");
289 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
290 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
292 let print_lints = |lints: Vec<&Lint>| {
293 for lint in lints.into_iter() {
294 let name = lint.name_lower().replace("_", "-");
295 println!(" {} {:7.7} {}",
296 padded(name[]), lint.default_level.as_str(), lint.desc);
301 print_lints(builtin);
305 let max_name_len = plugin_groups.iter().chain(builtin_groups.iter())
306 .map(|&(s, _)| s.width(true))
308 let padded = |x: &str| {
309 let mut s = repeat(" ").take(max_name_len - x.chars().count())
310 .collect::<String>();
315 println!("Lint groups provided by rustc:\n");
316 println!(" {} {}", padded("name"), "sub-lints");
317 println!(" {} {}", padded("----"), "---------");
319 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
320 for (name, to) in lints.into_iter() {
321 let name = name.chars().map(|x| x.to_lowercase())
322 .collect::<String>().replace("_", "-");
323 let desc = to.into_iter().map(|x| x.as_str().replace("_", "-"))
324 .collect::<Vec<String>>().connect(", ");
326 padded(name[]), desc);
331 print_lint_groups(builtin_groups);
333 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
334 (false, 0, _) | (false, _, 0) => {
335 println!("Compiler plugins can provide additional lints and lint groups. To see a \
336 listing of these, re-run `rustc -W help` with a crate filename.");
338 (false, _, _) => panic!("didn't load lint plugins but got them anyway!"),
339 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
342 println!("Lint checks provided by plugins loaded by this crate:\n");
346 println!("Lint groups provided by plugins loaded by this crate:\n");
347 print_lint_groups(plugin_groups);
353 fn describe_debug_flags() {
354 println!("\nAvailable debug options:\n");
355 let r = config::debugging_opts_map();
356 for tuple in r.iter() {
358 (ref name, ref desc, _) => {
359 println!(" -Z {:>20} -- {}", *name, *desc);
365 fn describe_codegen_flags() {
366 println!("\nAvailable codegen options:\n");
367 for &(name, _, opt_type_desc, desc) in config::CG_OPTIONS.iter() {
368 let (width, extra) = match opt_type_desc {
369 Some(..) => (21, "=val"),
372 println!(" -C {:>width$}{} -- {}", name.replace("_", "-"),
373 extra, desc, width=width);
377 /// Process command line options. Emits messages as appropriate. If compilation
378 /// should continue, returns a getopts::Matches object parsed from args, otherwise
380 pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
381 // Throw away the first argument, the name of the binary
382 let _binary = args.remove(0);
385 // user did not write `-v` nor `-Z unstable-options`, so do not
386 // include that extra information.
392 match getopts::getopts(args[], config::optgroups()[]) {
394 Err(f_stable_attempt) => {
395 // redo option parsing, including unstable options this time,
396 // in anticipation that the mishandled option was one of the
398 let all_groups : Vec<getopts::OptGroup>
399 = config::rustc_optgroups().into_iter().map(|x|x.opt_group).collect();
400 match getopts::getopts(args.as_slice(), all_groups.as_slice()) {
402 let r = m_unstable.opt_strs("Z");
403 let include_unstable_options = r.iter().any(|x| *x == "unstable-options");
404 if include_unstable_options {
407 early_error(f_stable_attempt.to_string().as_slice());
411 // ignore the error from the unstable attempt; just
412 // pass the error we got from the first try.
413 early_error(f_stable_attempt.to_string().as_slice());
419 let r = matches.opt_strs("Z");
420 let include_unstable_options = r.iter().any(|x| *x == "unstable-options");
422 if matches.opt_present("h") || matches.opt_present("help") {
423 usage(matches.opt_present("verbose"), include_unstable_options);
427 // Don't handle -W help here, because we might first load plugins.
429 let r = matches.opt_strs("Z");
430 if r.iter().any(|x| *x == "help") {
431 describe_debug_flags();
435 let cg_flags = matches.opt_strs("C");
436 if cg_flags.iter().any(|x| *x == "help") {
437 describe_codegen_flags();
441 if cg_flags.contains(&"passes=list".to_string()) {
442 unsafe { ::llvm::LLVMRustPrintPasses(); }
446 if matches.opt_present("version") {
447 version("rustc", &matches);
454 fn print_crate_info(sess: &Session,
455 input: Option<&Input>,
457 ofile: &Option<Path>)
459 if sess.opts.prints.len() == 0 { return false }
461 let attrs = input.map(|input| parse_crate_attrs(sess, input));
462 for req in sess.opts.prints.iter() {
464 PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
465 PrintRequest::FileNames |
466 PrintRequest::CrateName => {
467 let input = match input {
468 Some(input) => input,
469 None => early_error("no input file provided"),
471 let attrs = attrs.as_ref().unwrap().as_slice();
472 let t_outputs = driver::build_output_filenames(input,
477 let id = link::find_crate_name(Some(sess), attrs.as_slice(),
479 if *req == PrintRequest::CrateName {
483 let crate_types = driver::collect_crate_types(sess, attrs);
484 let metadata = driver::collect_crate_metadata(sess, attrs);
485 *sess.crate_metadata.borrow_mut() = metadata;
486 for &style in crate_types.iter() {
487 let fname = link::filename_for_input(sess, style,
489 &t_outputs.with_extension(""));
490 println!("{}", fname.filename_display());
498 fn parse_crate_attrs(sess: &Session, input: &Input) ->
499 Vec<ast::Attribute> {
500 let result = match *input {
501 Input::File(ref ifile) => {
502 parse::parse_crate_attrs_from_file(ifile,
506 Input::Str(ref src) => {
507 parse::parse_crate_attrs_from_source_str(
508 driver::anon_src().to_string(),
514 result.into_iter().collect()
517 pub fn list_metadata(sess: &Session, path: &Path,
518 out: &mut io::Writer) -> io::IoResult<()> {
519 metadata::loader::list_file_metadata(sess.target.target.options.is_like_osx, path, out)
522 /// Run a procedure which will detect panics in the compiler and print nicer
523 /// error messages rather than just failing the test.
525 /// The diagnostic emitter yielded to the procedure should be used for reporting
526 /// errors of the compiler.
527 pub fn monitor<F:FnOnce()+Send>(f: F) {
528 static STACK_SIZE: uint = 8 * 1024 * 1024; // 8MB
530 let (tx, rx) = channel();
531 let w = io::ChanWriter::new(tx);
532 let mut r = io::ChanReader::new(rx);
534 let mut cfg = thread::Builder::new().name("rustc".to_string());
536 // FIXME: Hacks on hacks. If the env is trying to override the stack size
537 // then *don't* set it explicitly.
538 if os::getenv("RUST_MIN_STACK").is_none() {
539 cfg = cfg.stack_size(STACK_SIZE);
542 match cfg.spawn(move || { std::io::stdio::set_stderr(box w); f() }).join() {
543 Ok(()) => { /* fallthrough */ }
545 // Thread panicked without emitting a fatal diagnostic
546 if !value.is::<diagnostic::FatalError>() {
547 let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
549 // a .span_bug or .bug call has already printed what
550 // it wants to print.
551 if !value.is::<diagnostic::ExplicitBug>() {
560 "the compiler unexpectedly panicked. this is a bug.".to_string(),
561 format!("we would appreciate a bug report: {}",
563 "run with `RUST_BACKTRACE=1` for a backtrace".to_string(),
565 for note in xs.iter() {
566 emitter.emit(None, note[], None, diagnostic::Note)
569 match r.read_to_string() {
570 Ok(s) => println!("{}", s),
573 format!("failed to read internal \
581 // Panic so the process returns a failure code, but don't pollute the
582 // output with some unnecessary panic messages, we've already
583 // printed everything that we needed to.
584 io::stdio::set_stderr(box io::util::NullWriter);
591 let args = std::os::args();
592 let result = run(args);
593 std::os::set_exit_status(result);