]> git.lizzy.rs Git - rust.git/blob - src/librustc/driver/mod.rs
623698f6c71ae7a596bb0132f0db8e303e5e7594
[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 lint;
17 use metadata;
18
19 use std::any::AnyRefExt;
20 use std::io;
21 use std::os;
22 use std::str;
23 use std::task::TaskBuilder;
24
25 use syntax::ast;
26 use syntax::parse;
27 use syntax::diagnostic::Emitter;
28
29 use getopts;
30
31
32 pub mod driver;
33 pub mod session;
34 pub mod config;
35
36
37 pub fn main_args(args: &[String]) -> int {
38     let owned_args = args.to_owned();
39     monitor(proc() run_compiler(owned_args.as_slice()));
40     0
41 }
42
43 static BUG_REPORT_URL: &'static str =
44     "http://doc.rust-lang.org/complement-bugreport.html";
45
46 fn run_compiler(args: &[String]) {
47     let matches = match handle_options(Vec::from_slice(args)) {
48         Some(matches) => matches,
49         None => return
50     };
51
52     let sopts = config::build_session_options(&matches);
53     if sopts.describe_lints {
54         describe_lints();
55         return;
56     }
57
58     let (input, input_file_path) = match matches.free.len() {
59         0u => early_error("no input filename given"),
60         1u => {
61             let ifile = matches.free.get(0).as_slice();
62             if ifile == "-" {
63                 let contents = io::stdin().read_to_end().unwrap();
64                 let src = str::from_utf8(contents.as_slice()).unwrap()
65                                                              .to_string();
66                 (StrInput(src), None)
67             } else {
68                 (FileInput(Path::new(ifile)), Some(Path::new(ifile)))
69             }
70         }
71         _ => early_error("multiple input filenames provided")
72     };
73
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));
78
79     let pretty = matches.opt_default("pretty", "normal").map(|a| {
80         parse_pretty(&sess, a.as_slice())
81     });
82     match pretty {
83         Some::<PpMode>(ppm) => {
84             driver::pretty_print_input(sess, cfg, &input, ppm, ofile);
85             return;
86         }
87         None::<PpMode> => {/* continue */ }
88     }
89
90     let r = matches.opt_strs("Z");
91     if r.contains(&("ls".to_string())) {
92         match input {
93             FileInput(ref ifile) => {
94                 let mut stdout = io::stdout();
95                 list_metadata(&sess, &(*ifile), &mut stdout).unwrap();
96             }
97             StrInput(_) => {
98                 early_error("can not list metadata for stdin");
99             }
100         }
101         return;
102     }
103
104     if print_crate_info(&sess, &input, &odir, &ofile) {
105         return;
106     }
107
108     driver::compile_input(sess, cfg, &input, &odir, &ofile);
109 }
110
111 pub fn version(command: &str) {
112     let vers = match option_env!("CFG_VERSION") {
113         Some(vers) => vers,
114         None => "unknown version"
115     };
116     println!("{} {}", command, vers);
117     println!("host: {}", driver::host_triple());
118 }
119
120 fn usage() {
121     let message = format!("Usage: rustc [OPTIONS] INPUT");
122     println!("{}\n\
123 Additional help:
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()));
129 }
130
131 fn describe_lints() {
132     println!("
133 Available lint options:
134     -W <foo>           Warn about <foo>
135     -A <foo>           Allow <foo>
136     -D <foo>           Deny <foo>
137     -F <foo>           Forbid <foo> (deny, and deny all overrides)
138 ");
139
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),
144             r => r,
145         }
146     });
147
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())
152         .max().unwrap_or(0);
153     let padded = |x: &str| {
154         format!("{}{}", " ".repeat(max_name_len - x.char_len()), x)
155     };
156
157     println!("\nAvailable lint checks:\n");
158     println!("    {}  {:7.7s}  {}", padded("name"), "default", "meaning");
159     println!("    {}  {:7.7s}  {}", padded("----"), "-------", "-------");
160     println!("");
161
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);
166     }
167     println!("");
168 }
169
170 fn describe_debug_flags() {
171     println!("\nAvailable debug options:\n");
172     let r = config::debugging_opts_map();
173     for tuple in r.iter() {
174         match *tuple {
175             (ref name, ref desc, _) => {
176                 println!("    -Z {:>20s} -- {}", *name, *desc);
177             }
178         }
179     }
180 }
181
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) {
189             (25, "")
190         } else {
191             (21, "=val")
192         };
193         println!("    -C {:>width$s}{} -- {}", name.replace("_", "-"),
194                  extra, desc, width=width);
195     }
196 }
197
198 /// Process command line options. Emits messages as appropriate. If compilation
199 /// should continue, returns a getopts::Matches object parsed from args, otherwise
200 /// returns None.
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();
204
205     if args.is_empty() {
206         usage();
207         return None;
208     }
209
210     let matches =
211         match getopts::getopts(args.as_slice(), config::optgroups().as_slice()) {
212             Ok(m) => m,
213             Err(f) => {
214                 early_error(f.to_str().as_slice());
215             }
216         };
217
218     if matches.opt_present("h") || matches.opt_present("help") {
219         usage();
220         return None;
221     }
222
223     // Don't handle -W help here, because we might first load plugins.
224
225     let r = matches.opt_strs("Z");
226     if r.iter().any(|x| x.as_slice() == "help") {
227         describe_debug_flags();
228         return None;
229     }
230
231     let cg_flags = matches.opt_strs("C");
232     if cg_flags.iter().any(|x| x.as_slice() == "help") {
233         describe_codegen_flags();
234         return None;
235     }
236
237     if cg_flags.contains(&"passes=list".to_string()) {
238         unsafe { ::lib::llvm::llvm::LLVMRustPrintPasses(); }
239         return None;
240     }
241
242     if matches.opt_present("v") || matches.opt_present("version") {
243         version("rustc");
244         return None;
245     }
246
247     Some(matches)
248 }
249
250 fn print_crate_info(sess: &Session,
251                     input: &Input,
252                     odir: &Option<Path>,
253                     ofile: &Option<Path>)
254                     -> bool {
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,
260                                                        odir,
261                                                        ofile,
262                                                        attrs.as_slice(),
263                                                        sess);
264         let id = link::find_crate_id(attrs.as_slice(),
265                                      t_outputs.out_filestem.as_slice());
266
267         if crate_id {
268             println!("{}", id.to_str());
269         }
270         if crate_name {
271             println!("{}", id.name);
272         }
273         if crate_file_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());
279             }
280         }
281
282         true
283     } else {
284         false
285     }
286 }
287
288 pub enum PpMode {
289     PpmNormal,
290     PpmExpanded,
291     PpmTyped,
292     PpmIdentified,
293     PpmExpandedIdentified,
294     PpmFlowGraph(ast::NodeId),
295 }
296
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),
310                  None => {
311                      sess.fatal(format!("`pretty flowgraph=<nodeid>` needs \
312                                          an integer <nodeid>; got {}",
313                                         arg.unwrap_or("nothing")).as_slice())
314                  }
315              }
316         }
317         _ => {
318             sess.fatal(format!(
319                 "argument to `pretty` must be one of `normal`, \
320                  `expanded`, `flowgraph=<nodeid>`, `typed`, `identified`, \
321                  or `expanded,identified`; got {}", name).as_slice());
322         }
323     }
324 }
325
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,
331                                                Vec::new(),
332                                                &sess.parse_sess)
333         }
334         StrInput(ref src) => {
335             parse::parse_crate_attrs_from_source_str(
336                 driver::anon_src().to_string(),
337                 src.to_string(),
338                 Vec::new(),
339                 &sess.parse_sess)
340         }
341     };
342     result.move_iter().collect()
343 }
344
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);
349 }
350
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)
354 }
355
356 /// Run a procedure which will detect failures in the compiler and print nicer
357 /// error messages rather than just failing the test.
358 ///
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.
365     #[cfg(rtopt)]
366     static STACK_SIZE: uint = 6000000;  // 6MB
367     #[cfg(not(rtopt))]
368     static STACK_SIZE: uint = 20000000; // 20MB
369
370     let (tx, rx) = channel();
371     let w = io::ChanWriter::new(tx);
372     let mut r = io::ChanReader::new(rx);
373
374     let mut task = TaskBuilder::new().named("rustc").stderr(box w);
375
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);
380     }
381
382     match task.try(f) {
383         Ok(()) => { /* fallthrough */ }
384         Err(value) => {
385             // Task failed without emitting a fatal diagnostic
386             if !value.is::<diagnostic::FatalError>() {
387                 let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto);
388
389                 // a .span_bug or .bug call has already printed what
390                 // it wants to print.
391                 if !value.is::<diagnostic::ExplicitBug>() {
392                     emitter.emit(
393                         None,
394                         "unexpected failure",
395                         diagnostic::Bug);
396                 }
397
398                 let xs = [
399                     "the compiler hit an unexpected failure path. this is a bug.".to_string(),
400                     format!("we would appreciate a bug report: {}",
401                             BUG_REPORT_URL),
402                     "run with `RUST_BACKTRACE=1` for a backtrace".to_string(),
403                 ];
404                 for note in xs.iter() {
405                     emitter.emit(None, note.as_slice(), diagnostic::Note)
406                 }
407
408                 match r.read_to_str() {
409                     Ok(s) => println!("{}", s),
410                     Err(e) => {
411                         emitter.emit(None,
412                                      format!("failed to read internal \
413                                               stderr: {}",
414                                              e).as_slice(),
415                                      diagnostic::Error)
416                     }
417                 }
418             }
419
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);
424             fail!();
425         }
426     }
427 }