]> git.lizzy.rs Git - rust.git/blob - src/librustc/driver/mod.rs
auto merge of #14234 : alexcrichton/rust/rollup, r=alexcrichton
[rust.git] / src / librustc / driver / mod.rs
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.
4 //
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.
10
11 pub use syntax::diagnostic;
12
13 use back::link;
14 use driver::driver::{Input, FileInput, StrInput};
15 use driver::session::{Session, build_session};
16 use middle::lint;
17 use metadata;
18
19 use std::any::AnyRefExt;
20 use std::cmp;
21 use std::io;
22 use std::os;
23 use std::str;
24 use std::task::TaskBuilder;
25
26 use syntax::ast;
27 use syntax::parse;
28 use syntax::diagnostic::Emitter;
29
30 use getopts;
31
32
33 pub mod driver;
34 pub mod session;
35 pub mod config;
36
37
38 pub fn main_args(args: &[~str]) -> int {
39     let owned_args = args.to_owned();
40     monitor(proc() run_compiler(owned_args));
41     0
42 }
43
44 static BUG_REPORT_URL: &'static str =
45     "http://static.rust-lang.org/doc/master/complement-bugreport.html";
46
47 fn run_compiler(args: &[~str]) {
48     let matches = match handle_options(Vec::from_slice(args)) {
49         Some(matches) => matches,
50         None => return
51     };
52
53     let (input, input_file_path) = match matches.free.len() {
54         0u => early_error("no input filename given"),
55         1u => {
56             let ifile = matches.free.get(0).as_slice();
57             if ifile == "-" {
58                 let contents = io::stdin().read_to_end().unwrap();
59                 let src = str::from_utf8(contents.as_slice()).unwrap()
60                                                              .to_strbuf();
61                 (StrInput(src), None)
62             } else {
63                 (FileInput(Path::new(ifile)), Some(Path::new(ifile)))
64             }
65         }
66         _ => early_error("multiple input filenames provided")
67     };
68
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));
74
75     let pretty = matches.opt_default("pretty", "normal").map(|a| {
76         parse_pretty(&sess, a)
77     });
78     match pretty {
79         Some::<PpMode>(ppm) => {
80             driver::pretty_print_input(sess, cfg, &input, ppm, ofile);
81             return;
82         }
83         None::<PpMode> => {/* continue */ }
84     }
85
86     let r = matches.opt_strs("Z");
87     if r.contains(&("ls".to_owned())) {
88         match input {
89             FileInput(ref ifile) => {
90                 let mut stdout = io::stdout();
91                 list_metadata(&sess, &(*ifile), &mut stdout).unwrap();
92             }
93             StrInput(_) => {
94                 early_error("can not list metadata for stdin");
95             }
96         }
97         return;
98     }
99
100     if print_crate_info(&sess, &input, &odir, &ofile) {
101         return;
102     }
103
104     driver::compile_input(sess, cfg, &input, &odir, &ofile);
105 }
106
107 pub fn version(command: &str) {
108     let vers = match option_env!("CFG_VERSION") {
109         Some(vers) => vers,
110         None => "unknown version"
111     };
112     println!("{} {}", command, vers);
113     println!("host: {}", driver::host_triple());
114 }
115
116 fn usage() {
117     let message = format!("Usage: rustc [OPTIONS] INPUT");
118     println!("{}\n\
119 Additional help:
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()));
124 }
125
126 fn describe_warnings() {
127     println!("
128 Available lint options:
129     -W <foo>           Warn about <foo>
130     -A <foo>           Allow <foo>
131     -D <foo>           Deny <foo>
132     -F <foo>           Forbid <foo> (deny, and deny all overrides)
133 ");
134
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();
140
141     let mut max_key = 0;
142     for &(_, name) in lint_dict.iter() {
143         max_key = cmp::max(name.len(), max_key);
144     }
145     fn padded(max: uint, s: &str) -> ~str {
146         " ".repeat(max - s.len()) + s
147     }
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),
158                  spec.desc);
159     }
160     println!("");
161 }
162
163 fn describe_debug_flags() {
164     println!("\nAvailable debug options:\n");
165     let r = config::debugging_opts_map();
166     for tuple in r.iter() {
167         match *tuple {
168             (ref name, ref desc, _) => {
169                 println!("    -Z {:>20s} -- {}", *name, *desc);
170             }
171         }
172     }
173 }
174
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) {
182             (25, "")
183         } else {
184             (21, "=val")
185         };
186         println!("    -C {:>width$s}{} -- {}", name.replace("_", "-"),
187                  extra, desc, width=width);
188     }
189 }
190
191 /// Process command line options. Emits messages as appropirate.If compilation
192 /// should continue, returns a getopts::Matches object parsed from args, otherwise
193 /// returns None.
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();
197
198     if args.is_empty() { usage(); return None; }
199
200     let matches =
201         match getopts::getopts(args.as_slice(), config::optgroups().as_slice()) {
202             Ok(m) => m,
203             Err(f) => {
204                 early_error(f.to_err_msg());
205             }
206         };
207
208     if matches.opt_present("h") || matches.opt_present("help") {
209         usage();
210         return None;
211     }
212
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()) {
216         describe_warnings();
217         return None;
218     }
219
220     let r = matches.opt_strs("Z");
221     if r.iter().any(|x| x == &"help".to_owned()) {
222         describe_debug_flags();
223         return None;
224     }
225
226     let cg_flags = matches.opt_strs("C");
227     if cg_flags.iter().any(|x| x == &"help".to_owned()) {
228         describe_codegen_flags();
229         return None;
230     }
231
232     if cg_flags.contains(&"passes=list".to_owned()) {
233         unsafe { ::lib::llvm::llvm::LLVMRustPrintPasses(); }
234         return None;
235     }
236
237     if matches.opt_present("v") || matches.opt_present("version") {
238         version("rustc");
239         return None;
240     }
241
242     Some(matches)
243 }
244
245 fn print_crate_info(sess: &Session,
246                     input: &Input,
247                     odir: &Option<Path>,
248                     ofile: &Option<Path>)
249                     -> bool {
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,
255                                                        odir,
256                                                        ofile,
257                                                        attrs.as_slice(),
258                                                        sess);
259         let id = link::find_crate_id(attrs.as_slice(),
260                                      t_outputs.out_filestem.as_slice());
261
262         if crate_id {
263             println!("{}", id.to_str());
264         }
265         if crate_name {
266             println!("{}", id.name);
267         }
268         if crate_file_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());
274             }
275         }
276
277         true
278     } else {
279         false
280     }
281 }
282
283 pub enum PpMode {
284     PpmNormal,
285     PpmExpanded,
286     PpmTyped,
287     PpmIdentified,
288     PpmExpandedIdentified,
289     PpmFlowGraph(ast::NodeId),
290 }
291
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") => {
303              match from_str(s) {
304                  Some(id) => PpmFlowGraph(id),
305                  None => sess.fatal(format!("`pretty flowgraph=<nodeid>` needs \
306                                              an integer <nodeid>; got {}", s))
307              }
308         }
309         _ => {
310             sess.fatal(format!(
311                 "argument to `pretty` must be one of `normal`, \
312                  `expanded`, `flowgraph=<nodeid>`, `typed`, `identified`, \
313                  or `expanded,identified`; got {}", name));
314         }
315     }
316 }
317
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,
323                                                Vec::new(),
324                                                &sess.parse_sess)
325         }
326         StrInput(ref src) => {
327             parse::parse_crate_attrs_from_source_str(
328                 driver::anon_src().to_strbuf(),
329                 src.to_strbuf(),
330                 Vec::new(),
331                 &sess.parse_sess)
332         }
333     };
334     result.move_iter().collect()
335 }
336
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);
341 }
342
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)
347 }
348
349 /// Run a procedure which will detect failures in the compiler and print nicer
350 /// error messages rather than just failing the test.
351 ///
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.
358     #[cfg(rtopt)]
359     static STACK_SIZE: uint = 6000000;  // 6MB
360     #[cfg(not(rtopt))]
361     static STACK_SIZE: uint = 20000000; // 20MB
362
363     let mut task_builder = TaskBuilder::new().named("rustc");
364
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);
369     }
370
371     let (tx, rx) = channel();
372     let w = io::ChanWriter::new(tx);
373     let mut r = io::ChanReader::new(rx);
374
375     match task_builder.try(proc() {
376         io::stdio::set_stderr(box w);
377         f()
378     }) {
379         Ok(()) => { /* fallthrough */ }
380         Err(value) => {
381             // Task failed without emitting a fatal diagnostic
382             if !value.is::<diagnostic::FatalError>() {
383                 let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto);
384
385                 // a .span_bug or .bug call has already printed what
386                 // it wants to print.
387                 if !value.is::<diagnostic::ExplicitBug>() {
388                     emitter.emit(
389                         None,
390                         "unexpected failure",
391                         diagnostic::Bug);
392                 }
393
394                 let xs = [
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(),
398                 ];
399                 for note in xs.iter() {
400                     emitter.emit(None, *note, diagnostic::Note)
401                 }
402
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),
407                                            diagnostic::Error),
408                 }
409             }
410
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);
415             fail!();
416         }
417     }
418 }