1 // Copyright 2012 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 pub use syntax::diagnostic;
14 use driver::driver::{Input, FileInput, StrInput};
15 use driver::session::{Session, build_session};
19 use std::any::AnyRefExt;
23 use std::task::TaskBuilder;
27 use syntax::diagnostic::Emitter;
37 pub fn main_args(args: &[String]) -> int {
38 let owned_args = args.to_owned();
39 monitor(proc() run_compiler(owned_args.as_slice()));
43 static BUG_REPORT_URL: &'static str =
44 "http://doc.rust-lang.org/complement-bugreport.html";
46 fn run_compiler(args: &[String]) {
47 let matches = match handle_options(Vec::from_slice(args)) {
48 Some(matches) => matches,
52 let sopts = config::build_session_options(&matches);
53 if sopts.describe_lints {
58 let (input, input_file_path) = match matches.free.len() {
59 0u => early_error("no input filename given"),
61 let ifile = matches.free.get(0).as_slice();
63 let contents = io::stdin().read_to_end().unwrap();
64 let src = str::from_utf8(contents.as_slice()).unwrap()
68 (FileInput(Path::new(ifile)), Some(Path::new(ifile)))
71 _ => early_error("multiple input filenames provided")
74 let sess = build_session(sopts, input_file_path);
75 let cfg = config::build_configuration(&sess);
76 let odir = matches.opt_str("out-dir").map(|o| Path::new(o));
77 let ofile = matches.opt_str("o").map(|o| Path::new(o));
79 let pretty = matches.opt_default("pretty", "normal").map(|a| {
80 parse_pretty(&sess, a.as_slice())
83 Some::<PpMode>(ppm) => {
84 driver::pretty_print_input(sess, cfg, &input, ppm, ofile);
87 None::<PpMode> => {/* continue */ }
90 let r = matches.opt_strs("Z");
91 if r.contains(&("ls".to_string())) {
93 FileInput(ref ifile) => {
94 let mut stdout = io::stdout();
95 list_metadata(&sess, &(*ifile), &mut stdout).unwrap();
98 early_error("can not list metadata for stdin");
104 if print_crate_info(&sess, &input, &odir, &ofile) {
108 driver::compile_input(sess, cfg, &input, &odir, &ofile);
111 pub fn version(command: &str) {
112 let vers = match option_env!("CFG_VERSION") {
114 None => "unknown version"
116 println!("{} {}", command, vers);
117 println!("host: {}", driver::host_triple());
121 let message = format!("Usage: rustc [OPTIONS] INPUT");
124 -C help Print codegen options
125 -W help Print 'lint' options and default settings
126 -Z help Print internal options for debugging rustc\n",
127 getopts::usage(message.as_slice(),
128 config::optgroups().as_slice()));
131 fn describe_lints() {
133 Available lint options:
134 -W <foo> Warn about <foo>
137 -F <foo> Forbid <foo> (deny, and deny all overrides)
140 let mut builtin_specs = lint::builtin_lint_specs();
141 builtin_specs.sort_by(|x, y| {
142 match x.default_level.cmp(&y.default_level) {
143 Equal => x.name.cmp(&y.name),
148 // FIXME: What if someone uses combining characters or East Asian fullwidth
149 // characters in a lint name?!?!?
150 let max_name_len = builtin_specs.iter()
151 .map(|&s| s.name.char_len())
153 let padded = |x: &str| {
154 format!("{}{}", " ".repeat(max_name_len - x.char_len()), x)
157 println!("\nAvailable lint checks:\n");
158 println!(" {} {:7.7s} {}", padded("name"), "default", "meaning");
159 println!(" {} {:7.7s} {}", padded("----"), "-------", "-------");
162 for spec in builtin_specs.move_iter() {
163 let name = spec.name.replace("_", "-");
164 println!(" {} {:7.7s} {}",
165 padded(name.as_slice()), spec.default_level.as_str(), spec.desc);
170 fn describe_debug_flags() {
171 println!("\nAvailable debug options:\n");
172 let r = config::debugging_opts_map();
173 for tuple in r.iter() {
175 (ref name, ref desc, _) => {
176 println!(" -Z {:>20s} -- {}", *name, *desc);
182 fn describe_codegen_flags() {
183 println!("\nAvailable codegen options:\n");
184 let mut cg = config::basic_codegen_options();
185 for &(name, parser, desc) in config::CG_OPTIONS.iter() {
186 // we invoke the parser function on `None` to see if this option needs
187 // an argument or not.
188 let (width, extra) = if parser(&mut cg, None) {
193 println!(" -C {:>width$s}{} -- {}", name.replace("_", "-"),
194 extra, desc, width=width);
198 /// Process command line options. Emits messages as appropriate. If compilation
199 /// should continue, returns a getopts::Matches object parsed from args, otherwise
201 pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
202 // Throw away the first argument, the name of the binary
203 let _binary = args.shift().unwrap();
211 match getopts::getopts(args.as_slice(), config::optgroups().as_slice()) {
214 early_error(f.to_str().as_slice());
218 if matches.opt_present("h") || matches.opt_present("help") {
223 // Don't handle -W help here, because we might first load plugins.
225 let r = matches.opt_strs("Z");
226 if r.iter().any(|x| x.as_slice() == "help") {
227 describe_debug_flags();
231 let cg_flags = matches.opt_strs("C");
232 if cg_flags.iter().any(|x| x.as_slice() == "help") {
233 describe_codegen_flags();
237 if cg_flags.contains(&"passes=list".to_string()) {
238 unsafe { ::lib::llvm::llvm::LLVMRustPrintPasses(); }
242 if matches.opt_present("v") || matches.opt_present("version") {
250 fn print_crate_info(sess: &Session,
253 ofile: &Option<Path>)
255 let (crate_id, crate_name, crate_file_name) = sess.opts.print_metas;
256 // these nasty nested conditions are to avoid doing extra work
257 if crate_id || crate_name || crate_file_name {
258 let attrs = parse_crate_attrs(sess, input);
259 let t_outputs = driver::build_output_filenames(input,
264 let id = link::find_crate_id(attrs.as_slice(),
265 t_outputs.out_filestem.as_slice());
268 println!("{}", id.to_str());
271 println!("{}", id.name);
274 let crate_types = driver::collect_crate_types(sess, attrs.as_slice());
275 for &style in crate_types.iter() {
276 let fname = link::filename_for_input(sess, style, &id,
277 &t_outputs.with_extension(""));
278 println!("{}", fname.filename_display());
293 PpmExpandedIdentified,
294 PpmFlowGraph(ast::NodeId),
297 pub fn parse_pretty(sess: &Session, name: &str) -> PpMode {
298 let mut split = name.splitn('=', 1);
299 let first = split.next().unwrap();
300 let opt_second = split.next();
301 match (opt_second, first) {
302 (None, "normal") => PpmNormal,
303 (None, "expanded") => PpmExpanded,
304 (None, "typed") => PpmTyped,
305 (None, "expanded,identified") => PpmExpandedIdentified,
306 (None, "identified") => PpmIdentified,
307 (arg, "flowgraph") => {
308 match arg.and_then(from_str) {
309 Some(id) => PpmFlowGraph(id),
311 sess.fatal(format!("`pretty flowgraph=<nodeid>` needs \
312 an integer <nodeid>; got {}",
313 arg.unwrap_or("nothing")).as_slice())
319 "argument to `pretty` must be one of `normal`, \
320 `expanded`, `flowgraph=<nodeid>`, `typed`, `identified`, \
321 or `expanded,identified`; got {}", name).as_slice());
326 fn parse_crate_attrs(sess: &Session, input: &Input) ->
327 Vec<ast::Attribute> {
328 let result = match *input {
329 FileInput(ref ifile) => {
330 parse::parse_crate_attrs_from_file(ifile,
334 StrInput(ref src) => {
335 parse::parse_crate_attrs_from_source_str(
336 driver::anon_src().to_string(),
342 result.move_iter().collect()
345 pub fn early_error(msg: &str) -> ! {
346 let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto);
347 emitter.emit(None, msg, diagnostic::Fatal);
348 fail!(diagnostic::FatalError);
351 pub fn list_metadata(sess: &Session, path: &Path,
352 out: &mut io::Writer) -> io::IoResult<()> {
353 metadata::loader::list_file_metadata(sess.targ_cfg.os, path, out)
356 /// Run a procedure which will detect failures in the compiler and print nicer
357 /// error messages rather than just failing the test.
359 /// The diagnostic emitter yielded to the procedure should be used for reporting
360 /// errors of the compiler.
361 fn monitor(f: proc():Send) {
362 // FIXME: This is a hack for newsched since it doesn't support split stacks.
363 // rustc needs a lot of stack! When optimizations are disabled, it needs
364 // even *more* stack than usual as well.
366 static STACK_SIZE: uint = 6000000; // 6MB
368 static STACK_SIZE: uint = 20000000; // 20MB
370 let (tx, rx) = channel();
371 let w = io::ChanWriter::new(tx);
372 let mut r = io::ChanReader::new(rx);
374 let mut task = TaskBuilder::new().named("rustc").stderr(box w);
376 // FIXME: Hacks on hacks. If the env is trying to override the stack size
377 // then *don't* set it explicitly.
378 if os::getenv("RUST_MIN_STACK").is_none() {
379 task = task.stack_size(STACK_SIZE);
383 Ok(()) => { /* fallthrough */ }
385 // Task failed without emitting a fatal diagnostic
386 if !value.is::<diagnostic::FatalError>() {
387 let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto);
389 // a .span_bug or .bug call has already printed what
390 // it wants to print.
391 if !value.is::<diagnostic::ExplicitBug>() {
394 "unexpected failure",
399 "the compiler hit an unexpected failure path. this is a bug.".to_string(),
400 format!("we would appreciate a bug report: {}",
402 "run with `RUST_BACKTRACE=1` for a backtrace".to_string(),
404 for note in xs.iter() {
405 emitter.emit(None, note.as_slice(), diagnostic::Note)
408 match r.read_to_str() {
409 Ok(s) => println!("{}", s),
412 format!("failed to read internal \
420 // Fail so the process returns a failure code, but don't pollute the
421 // output with some unnecessary failure messages, we've already
422 // printed everything that we needed to.
423 io::stdio::set_stderr(box io::util::NullWriter);