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;
24 use std::task::TaskBuilder;
28 use syntax::diagnostic::Emitter;
38 pub fn main_args(args: &[~str]) -> int {
39 let owned_args = args.to_owned();
40 monitor(proc() run_compiler(owned_args));
44 static BUG_REPORT_URL: &'static str =
45 "http://static.rust-lang.org/doc/master/complement-bugreport.html";
47 fn run_compiler(args: &[~str]) {
48 let matches = match handle_options(Vec::from_slice(args)) {
49 Some(matches) => matches,
53 let (input, input_file_path) = match matches.free.len() {
54 0u => early_error("no input filename given"),
56 let ifile = matches.free.get(0).as_slice();
58 let contents = io::stdin().read_to_end().unwrap();
59 let src = str::from_utf8(contents.as_slice()).unwrap()
63 (FileInput(Path::new(ifile)), Some(Path::new(ifile)))
66 _ => early_error("multiple input filenames provided")
69 let sopts = config::build_session_options(&matches);
70 let sess = build_session(sopts, input_file_path);
71 let cfg = config::build_configuration(&sess);
72 let odir = matches.opt_str("out-dir").map(|o| Path::new(o));
73 let ofile = matches.opt_str("o").map(|o| Path::new(o));
75 let pretty = matches.opt_default("pretty", "normal").map(|a| {
76 parse_pretty(&sess, a)
79 Some::<PpMode>(ppm) => {
80 driver::pretty_print_input(sess, cfg, &input, ppm, ofile);
83 None::<PpMode> => {/* continue */ }
86 let r = matches.opt_strs("Z");
87 if r.contains(&("ls".to_owned())) {
89 FileInput(ref ifile) => {
90 let mut stdout = io::stdout();
91 list_metadata(&sess, &(*ifile), &mut stdout).unwrap();
94 early_error("can not list metadata for stdin");
100 if print_crate_info(&sess, &input, &odir, &ofile) {
104 driver::compile_input(sess, cfg, &input, &odir, &ofile);
107 pub fn version(command: &str) {
108 let vers = match option_env!("CFG_VERSION") {
110 None => "unknown version"
112 println!("{} {}", command, vers);
113 println!("host: {}", driver::host_triple());
117 let message = format!("Usage: rustc [OPTIONS] INPUT");
120 -C help Print codegen options
121 -W help Print 'lint' options and default settings
122 -Z help Print internal options for debugging rustc\n",
123 getopts::usage(message, config::optgroups().as_slice()));
126 fn describe_warnings() {
128 Available lint options:
129 -W <foo> Warn about <foo>
132 -F <foo> Forbid <foo> (deny, and deny all overrides)
135 let lint_dict = lint::get_lint_dict();
136 let mut lint_dict = lint_dict.move_iter()
137 .map(|(k, v)| (v, k))
138 .collect::<Vec<(lint::LintSpec, &'static str)> >();
139 lint_dict.as_mut_slice().sort();
142 for &(_, name) in lint_dict.iter() {
143 max_key = cmp::max(name.len(), max_key);
145 fn padded(max: uint, s: &str) -> ~str {
146 " ".repeat(max - s.len()) + s
148 println!("\nAvailable lint checks:\n");
149 println!(" {} {:7.7s} {}",
150 padded(max_key, "name"), "default", "meaning");
151 println!(" {} {:7.7s} {}\n",
152 padded(max_key, "----"), "-------", "-------");
153 for (spec, name) in lint_dict.move_iter() {
154 let name = name.replace("_", "-");
155 println!(" {} {:7.7s} {}",
156 padded(max_key, name),
157 lint::level_to_str(spec.default),
163 fn describe_debug_flags() {
164 println!("\nAvailable debug options:\n");
165 let r = config::debugging_opts_map();
166 for tuple in r.iter() {
168 (ref name, ref desc, _) => {
169 println!(" -Z {:>20s} -- {}", *name, *desc);
175 fn describe_codegen_flags() {
176 println!("\nAvailable codegen options:\n");
177 let mut cg = config::basic_codegen_options();
178 for &(name, parser, desc) in config::CG_OPTIONS.iter() {
179 // we invoke the parser function on `None` to see if this option needs
180 // an argument or not.
181 let (width, extra) = if parser(&mut cg, None) {
186 println!(" -C {:>width$s}{} -- {}", name.replace("_", "-"),
187 extra, desc, width=width);
191 /// Process command line options. Emits messages as appropirate.If compilation
192 /// should continue, returns a getopts::Matches object parsed from args, otherwise
194 pub fn handle_options(mut args: Vec<~str>) -> Option<getopts::Matches> {
195 // Throw away the first argument, the name of the binary
196 let _binary = args.shift().unwrap();
198 if args.is_empty() { usage(); return None; }
201 match getopts::getopts(args.as_slice(), config::optgroups().as_slice()) {
204 early_error(f.to_err_msg());
208 if matches.opt_present("h") || matches.opt_present("help") {
213 let lint_flags = matches.opt_strs("W").move_iter().collect::<Vec<_>>().append(
214 matches.opt_strs("warn").as_slice());
215 if lint_flags.iter().any(|x| x == &"help".to_owned()) {
220 let r = matches.opt_strs("Z");
221 if r.iter().any(|x| x == &"help".to_owned()) {
222 describe_debug_flags();
226 let cg_flags = matches.opt_strs("C");
227 if cg_flags.iter().any(|x| x == &"help".to_owned()) {
228 describe_codegen_flags();
232 if cg_flags.contains(&"passes=list".to_owned()) {
233 unsafe { ::lib::llvm::llvm::LLVMRustPrintPasses(); }
237 if matches.opt_present("v") || matches.opt_present("version") {
245 fn print_crate_info(sess: &Session,
248 ofile: &Option<Path>)
250 let (crate_id, crate_name, crate_file_name) = sess.opts.print_metas;
251 // these nasty nested conditions are to avoid doing extra work
252 if crate_id || crate_name || crate_file_name {
253 let attrs = parse_crate_attrs(sess, input);
254 let t_outputs = driver::build_output_filenames(input,
259 let id = link::find_crate_id(attrs.as_slice(),
260 t_outputs.out_filestem.as_slice());
263 println!("{}", id.to_str());
266 println!("{}", id.name);
269 let crate_types = driver::collect_crate_types(sess, attrs.as_slice());
270 for &style in crate_types.iter() {
271 let fname = link::filename_for_input(sess, style, &id,
272 &t_outputs.with_extension(""));
273 println!("{}", fname.filename_display());
288 PpmExpandedIdentified,
289 PpmFlowGraph(ast::NodeId),
292 pub fn parse_pretty(sess: &Session, name: &str) -> PpMode {
293 let mut split = name.splitn('=', 1);
294 let first = split.next().unwrap();
295 let opt_second = split.next();
296 match (opt_second, first) {
297 (None, "normal") => PpmNormal,
298 (None, "expanded") => PpmExpanded,
299 (None, "typed") => PpmTyped,
300 (None, "expanded,identified") => PpmExpandedIdentified,
301 (None, "identified") => PpmIdentified,
302 (Some(s), "flowgraph") => {
304 Some(id) => PpmFlowGraph(id),
305 None => sess.fatal(format!("`pretty flowgraph=<nodeid>` needs \
306 an integer <nodeid>; got {}", s))
311 "argument to `pretty` must be one of `normal`, \
312 `expanded`, `flowgraph=<nodeid>`, `typed`, `identified`, \
313 or `expanded,identified`; got {}", name));
318 fn parse_crate_attrs(sess: &Session, input: &Input) ->
319 Vec<ast::Attribute> {
320 let result = match *input {
321 FileInput(ref ifile) => {
322 parse::parse_crate_attrs_from_file(ifile,
326 StrInput(ref src) => {
327 parse::parse_crate_attrs_from_source_str(
328 driver::anon_src().to_strbuf(),
334 result.move_iter().collect()
337 pub fn early_error(msg: &str) -> ! {
338 let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto);
339 emitter.emit(None, msg, diagnostic::Fatal);
340 fail!(diagnostic::FatalError);
343 pub fn list_metadata(sess: &Session, path: &Path,
344 out: &mut io::Writer) -> io::IoResult<()> {
345 metadata::loader::list_file_metadata(
346 config::cfg_os_to_meta_os(sess.targ_cfg.os), path, out)
349 /// Run a procedure which will detect failures in the compiler and print nicer
350 /// error messages rather than just failing the test.
352 /// The diagnostic emitter yielded to the procedure should be used for reporting
353 /// errors of the compiler.
354 fn monitor(f: proc():Send) {
355 // FIXME: This is a hack for newsched since it doesn't support split stacks.
356 // rustc needs a lot of stack! When optimizations are disabled, it needs
357 // even *more* stack than usual as well.
359 static STACK_SIZE: uint = 6000000; // 6MB
361 static STACK_SIZE: uint = 20000000; // 20MB
363 let mut task_builder = TaskBuilder::new().named("rustc");
365 // FIXME: Hacks on hacks. If the env is trying to override the stack size
366 // then *don't* set it explicitly.
367 if os::getenv("RUST_MIN_STACK").is_none() {
368 task_builder.opts.stack_size = Some(STACK_SIZE);
371 let (tx, rx) = channel();
372 let w = io::ChanWriter::new(tx);
373 let mut r = io::ChanReader::new(rx);
375 match task_builder.try(proc() {
376 io::stdio::set_stderr(box w);
379 Ok(()) => { /* fallthrough */ }
381 // Task failed without emitting a fatal diagnostic
382 if !value.is::<diagnostic::FatalError>() {
383 let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto);
385 // a .span_bug or .bug call has already printed what
386 // it wants to print.
387 if !value.is::<diagnostic::ExplicitBug>() {
390 "unexpected failure",
395 "the compiler hit an unexpected failure path. this is a bug.".to_owned(),
396 "we would appreciate a bug report: " + BUG_REPORT_URL,
397 "run with `RUST_BACKTRACE=1` for a backtrace".to_owned(),
399 for note in xs.iter() {
400 emitter.emit(None, *note, diagnostic::Note)
403 match r.read_to_str() {
404 Ok(s) => println!("{}", s),
405 Err(e) => emitter.emit(None,
406 format!("failed to read internal stderr: {}", e),
411 // Fail so the process returns a failure code, but don't pollute the
412 // output with some unnecessary failure messages, we've already
413 // printed everything that we needed to.
414 io::stdio::set_stderr(box io::util::NullWriter);