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, if_let, import_shadowing, macro_rules, phase, quote)]
26 #![feature(slicing_syntax, unsafe_destructor)]
27 #![feature(rustc_diagnostic_macros)]
32 extern crate graphviz;
35 extern crate rustc_typeck;
36 extern crate rustc_back;
37 extern crate rustc_trans;
38 #[phase(plugin, link)] extern crate log;
39 #[phase(plugin, link)] extern crate syntax;
40 extern crate serialize;
41 extern crate "rustc_llvm" as llvm;
43 pub use syntax::diagnostic;
45 use rustc_trans::back::link;
46 use rustc::session::{config, Session, build_session};
47 use rustc::session::config::Input;
48 use rustc::lint::Lint;
51 use rustc::DIAGNOSTICS;
53 use std::any::AnyRefExt;
56 use std::task::TaskBuilder;
58 use rustc::session::early_error;
62 use syntax::diagnostic::Emitter;
63 use syntax::diagnostics;
71 pub fn run(args: Vec<String>) -> int {
72 monitor(proc() run_compiler(args.as_slice()));
76 static BUG_REPORT_URL: &'static str =
77 "http://doc.rust-lang.org/complement-bugreport.html";
79 fn run_compiler(args: &[String]) {
80 let matches = match handle_options(args.to_vec()) {
81 Some(matches) => matches,
85 let descriptions = diagnostics::registry::Registry::new(&DIAGNOSTICS);
86 match matches.opt_str("explain") {
88 match descriptions.find_description(code.as_slice()) {
89 Some(ref description) => {
90 println!("{}", description);
93 early_error(format!("no extended information for {}", code).as_slice());
101 let sopts = config::build_session_options(&matches);
102 let (input, input_file_path) = match matches.free.len() {
104 if sopts.describe_lints {
105 let mut ls = lint::LintStore::new();
106 ls.register_builtin(None);
107 describe_lints(&ls, false);
111 let sess = build_session(sopts, None, descriptions);
112 if sess.debugging_opt(config::PRINT_SYSROOT) {
113 println!("{}", sess.sysroot().display());
117 early_error("no input filename given");
120 let ifile = matches.free[0].as_slice();
122 let contents = io::stdin().read_to_end().unwrap();
123 let src = String::from_utf8(contents).unwrap();
124 (Input::Str(src), None)
126 (Input::File(Path::new(ifile)), Some(Path::new(ifile)))
129 _ => early_error("multiple input filenames provided")
132 let sess = build_session(sopts, input_file_path, descriptions);
133 let cfg = config::build_configuration(&sess);
134 let odir = matches.opt_str("out-dir").map(|o| Path::new(o));
135 let ofile = matches.opt_str("o").map(|o| Path::new(o));
137 let pretty = matches.opt_default("pretty", "normal").map(|a| {
138 pretty::parse_pretty(&sess, a.as_slice())
141 Some((ppm, opt_uii)) => {
142 pretty::pretty_print_input(sess, cfg, &input, ppm, opt_uii, ofile);
145 None => {/* continue */ }
148 let r = matches.opt_strs("Z");
149 if r.contains(&("ls".to_string())) {
151 Input::File(ref ifile) => {
152 let mut stdout = io::stdout();
153 list_metadata(&sess, &(*ifile), &mut stdout).unwrap();
156 early_error("can not list metadata for stdin");
162 if print_crate_info(&sess, &input, &odir, &ofile) {
166 driver::compile_input(sess, cfg, &input, &odir, &ofile, None);
169 /// Returns a version string such as "0.12.0-dev".
170 pub fn release_str() -> Option<&'static str> {
171 option_env!("CFG_RELEASE")
174 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
175 pub fn commit_hash_str() -> Option<&'static str> {
176 option_env!("CFG_VER_HASH")
179 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
180 pub fn commit_date_str() -> Option<&'static str> {
181 option_env!("CFG_VER_DATE")
184 /// Prints version information and returns None on success or an error
185 /// message on panic.
186 pub fn version(binary: &str, matches: &getopts::Matches) -> Option<String> {
187 let verbose = match matches.opt_str("version").as_ref().map(|s| s.as_slice()) {
189 Some("verbose") => true,
190 Some(s) => return Some(format!("Unrecognized argument: {}", s))
193 println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
195 fn unw(x: Option<&str>) -> &str { x.unwrap_or("unknown") }
196 println!("binary: {}", binary);
197 println!("commit-hash: {}", unw(commit_hash_str()));
198 println!("commit-date: {}", unw(commit_date_str()));
199 println!("host: {}", config::host_triple());
200 println!("release: {}", unw(release_str()));
206 let message = format!("Usage: rustc [OPTIONS] INPUT");
209 -C help Print codegen options
210 -W help Print 'lint' options and default settings
211 -Z help Print internal options for debugging rustc\n",
212 getopts::usage(message.as_slice(),
213 config::optgroups().as_slice()));
216 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
218 Available lint options:
219 -W <foo> Warn about <foo>
222 -F <foo> Forbid <foo> (deny, and deny all overrides)
226 fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
227 let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
228 lints.sort_by(|x: &&Lint, y: &&Lint| {
229 match x.default_level.cmp(&y.default_level) {
230 // The sort doesn't case-fold but it's doubtful we care.
231 Equal => x.name.cmp(y.name),
238 fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
239 -> Vec<(&'static str, Vec<lint::LintId>)> {
240 let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
241 lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
242 &(y, _): &(&'static str, Vec<lint::LintId>)| {
248 let (plugin, builtin) = lint_store.get_lints().partitioned(|&(_, p)| p);
249 let plugin = sort_lints(plugin);
250 let builtin = sort_lints(builtin);
252 let (plugin_groups, builtin_groups) = lint_store.get_lint_groups().partitioned(|&(_, _, p)| p);
253 let plugin_groups = sort_lint_groups(plugin_groups);
254 let builtin_groups = sort_lint_groups(builtin_groups);
256 let max_name_len = plugin.iter().chain(builtin.iter())
257 .map(|&s| s.name.width(true))
259 let padded = |x: &str| {
260 let mut s = " ".repeat(max_name_len - x.char_len());
265 println!("Lint checks provided by rustc:\n");
266 println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
267 println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
269 let print_lints = |lints: Vec<&Lint>| {
270 for lint in lints.into_iter() {
271 let name = lint.name_lower().replace("_", "-");
272 println!(" {} {:7.7} {}",
273 padded(name.as_slice()), lint.default_level.as_str(), lint.desc);
278 print_lints(builtin);
282 let max_name_len = plugin_groups.iter().chain(builtin_groups.iter())
283 .map(|&(s, _)| s.width(true))
285 let padded = |x: &str| {
286 let mut s = " ".repeat(max_name_len - x.char_len());
291 println!("Lint groups provided by rustc:\n");
292 println!(" {} {}", padded("name"), "sub-lints");
293 println!(" {} {}", padded("----"), "---------");
295 let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
296 for (name, to) in lints.into_iter() {
297 let name = name.chars().map(|x| x.to_lowercase())
298 .collect::<String>().replace("_", "-");
299 let desc = to.into_iter().map(|x| x.as_str().replace("_", "-"))
300 .collect::<Vec<String>>().connect(", ");
302 padded(name.as_slice()), desc);
307 print_lint_groups(builtin_groups);
309 match (loaded_plugins, plugin.len(), plugin_groups.len()) {
310 (false, 0, _) | (false, _, 0) => {
311 println!("Compiler plugins can provide additional lints and lint groups. To see a \
312 listing of these, re-run `rustc -W help` with a crate filename.");
314 (false, _, _) => panic!("didn't load lint plugins but got them anyway!"),
315 (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
318 println!("Lint checks provided by plugins loaded by this crate:\n");
322 println!("Lint groups provided by plugins loaded by this crate:\n");
323 print_lint_groups(plugin_groups);
329 fn describe_debug_flags() {
330 println!("\nAvailable debug options:\n");
331 let r = config::debugging_opts_map();
332 for tuple in r.iter() {
334 (ref name, ref desc, _) => {
335 println!(" -Z {:>20} -- {}", *name, *desc);
341 fn describe_codegen_flags() {
342 println!("\nAvailable codegen options:\n");
343 for &(name, _, opt_type_desc, desc) in config::CG_OPTIONS.iter() {
344 let (width, extra) = match opt_type_desc {
345 Some(..) => (21, "=val"),
348 println!(" -C {:>width$}{} -- {}", name.replace("_", "-"),
349 extra, desc, width=width);
353 /// Process command line options. Emits messages as appropriate. If compilation
354 /// should continue, returns a getopts::Matches object parsed from args, otherwise
356 pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
357 // Throw away the first argument, the name of the binary
358 let _binary = args.remove(0).unwrap();
366 match getopts::getopts(args.as_slice(), config::optgroups().as_slice()) {
369 early_error(f.to_string().as_slice());
373 if matches.opt_present("h") || matches.opt_present("help") {
378 // Don't handle -W help here, because we might first load plugins.
380 let r = matches.opt_strs("Z");
381 if r.iter().any(|x| *x == "help") {
382 describe_debug_flags();
386 let cg_flags = matches.opt_strs("C");
387 if cg_flags.iter().any(|x| *x == "help") {
388 describe_codegen_flags();
392 if cg_flags.contains(&"passes=list".to_string()) {
393 unsafe { ::llvm::LLVMRustPrintPasses(); }
397 if matches.opt_present("version") {
398 match version("rustc", &matches) {
399 Some(err) => early_error(err.as_slice()),
407 fn print_crate_info(sess: &Session,
410 ofile: &Option<Path>)
412 let (crate_name, crate_file_name) = sess.opts.print_metas;
413 // these nasty nested conditions are to avoid doing extra work
414 if crate_name || crate_file_name {
415 let attrs = parse_crate_attrs(sess, input);
416 let t_outputs = driver::build_output_filenames(input,
421 let id = link::find_crate_name(Some(sess), attrs.as_slice(), input);
427 let crate_types = driver::collect_crate_types(sess, attrs.as_slice());
428 let metadata = driver::collect_crate_metadata(sess, attrs.as_slice());
429 *sess.crate_metadata.borrow_mut() = metadata;
430 for &style in crate_types.iter() {
431 let fname = link::filename_for_input(sess, style, id.as_slice(),
432 &t_outputs.with_extension(""));
433 println!("{}", fname.filename_display());
443 fn parse_crate_attrs(sess: &Session, input: &Input) ->
444 Vec<ast::Attribute> {
445 let result = match *input {
446 Input::File(ref ifile) => {
447 parse::parse_crate_attrs_from_file(ifile,
451 Input::Str(ref src) => {
452 parse::parse_crate_attrs_from_source_str(
453 driver::anon_src().to_string(),
459 result.into_iter().collect()
462 pub fn list_metadata(sess: &Session, path: &Path,
463 out: &mut io::Writer) -> io::IoResult<()> {
464 metadata::loader::list_file_metadata(sess.target.target.options.is_like_osx, path, out)
467 /// Run a procedure which will detect panics in the compiler and print nicer
468 /// error messages rather than just failing the test.
470 /// The diagnostic emitter yielded to the procedure should be used for reporting
471 /// errors of the compiler.
472 pub fn monitor(f: proc():Send) {
473 static STACK_SIZE: uint = 32000000; // 32MB
475 let (tx, rx) = channel();
476 let w = io::ChanWriter::new(tx);
477 let mut r = io::ChanReader::new(rx);
479 let mut task = TaskBuilder::new().named("rustc").stderr(box w);
481 // FIXME: Hacks on hacks. If the env is trying to override the stack size
482 // then *don't* set it explicitly.
483 if os::getenv("RUST_MIN_STACK").is_none() {
484 task = task.stack_size(STACK_SIZE);
488 Ok(()) => { /* fallthrough */ }
490 // Task panicked without emitting a fatal diagnostic
491 if !value.is::<diagnostic::FatalError>() {
492 let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
494 // a .span_bug or .bug call has already printed what
495 // it wants to print.
496 if !value.is::<diagnostic::ExplicitBug>() {
505 "the compiler unexpectedly panicked. this is a bug.".to_string(),
506 format!("we would appreciate a bug report: {}",
508 "run with `RUST_BACKTRACE=1` for a backtrace".to_string(),
510 for note in xs.iter() {
511 emitter.emit(None, note.as_slice(), None, diagnostic::Note)
514 match r.read_to_string() {
515 Ok(s) => println!("{}", s),
518 format!("failed to read internal \
527 // Panic so the process returns a failure code, but don't pollute the
528 // output with some unnecessary panic messages, we've already
529 // printed everything that we needed to.
530 io::stdio::set_stderr(box io::util::NullWriter);
537 let args = std::os::args();
538 let result = run(args);
539 std::os::set_exit_status(result);