]> git.lizzy.rs Git - rust.git/blob - src/librustc/driver/mod.rs
Fix errors
[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::Lint;
17 use lint;
18 use metadata;
19
20 use std::any::AnyRefExt;
21 use std::io;
22 use std::os;
23 use std::task::TaskBuilder;
24
25 use syntax::ast;
26 use syntax::parse;
27 use syntax::diagnostic::Emitter;
28 use syntax::diagnostics;
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: &[String]) -> int {
39     let owned_args = args.to_owned();
40     monitor(proc() run_compiler(owned_args.as_slice()));
41     0
42 }
43
44 static BUG_REPORT_URL: &'static str =
45     "http://doc.rust-lang.org/complement-bugreport.html";
46
47 fn run_compiler(args: &[String]) {
48     let matches = match handle_options(Vec::from_slice(args)) {
49         Some(matches) => matches,
50         None => return
51     };
52
53     let descriptions = diagnostics::registry::Registry::new(super::DIAGNOSTICS);
54     match matches.opt_str("explain") {
55         Some(ref code) => {
56             match descriptions.find_description(code.as_slice()) {
57                 Some(ref description) => {
58                     println!("{}", description);
59                 }
60                 None => {
61                     early_error(format!("no extended information for {}", code).as_slice());
62                 }
63             }
64             return;
65         },
66         None => ()
67     }
68
69     let sopts = config::build_session_options(&matches);
70     let (input, input_file_path) = match matches.free.len() {
71         0u => {
72             if sopts.describe_lints {
73                 let mut ls = lint::LintStore::new();
74                 ls.register_builtin(None);
75                 describe_lints(&ls, false);
76                 return;
77             }
78             early_error("no input filename given");
79         }
80         1u => {
81             let ifile = matches.free.get(0).as_slice();
82             if ifile == "-" {
83                 let contents = io::stdin().read_to_end().unwrap();
84                 let src = String::from_utf8(contents).unwrap();
85                 (StrInput(src), None)
86             } else {
87                 (FileInput(Path::new(ifile)), Some(Path::new(ifile)))
88             }
89         }
90         _ => early_error("multiple input filenames provided")
91     };
92
93     let sess = build_session(sopts, input_file_path, descriptions);
94     let cfg = config::build_configuration(&sess);
95     let odir = matches.opt_str("out-dir").map(|o| Path::new(o));
96     let ofile = matches.opt_str("o").map(|o| Path::new(o));
97
98     let pretty = matches.opt_default("pretty", "normal").map(|a| {
99         parse_pretty(&sess, a.as_slice())
100     });
101     match pretty {
102         Some::<PpMode>(ppm) => {
103             driver::pretty_print_input(sess, cfg, &input, ppm, ofile);
104             return;
105         }
106         None::<PpMode> => {/* continue */ }
107     }
108
109     let r = matches.opt_strs("Z");
110     if r.contains(&("ls".to_string())) {
111         match input {
112             FileInput(ref ifile) => {
113                 let mut stdout = io::stdout();
114                 list_metadata(&sess, &(*ifile), &mut stdout).unwrap();
115             }
116             StrInput(_) => {
117                 early_error("can not list metadata for stdin");
118             }
119         }
120         return;
121     }
122
123     if print_crate_info(&sess, &input, &odir, &ofile) {
124         return;
125     }
126
127     driver::compile_input(sess, cfg, &input, &odir, &ofile);
128 }
129
130 /// Prints version information and returns None on success or an error
131 /// message on failure.
132 pub fn version(binary: &str, matches: &getopts::Matches) -> Option<String> {
133     let verbose = match matches.opt_str("version").as_ref().map(|s| s.as_slice()) {
134         None => false,
135         Some("verbose") => true,
136         Some(s) => return Some(format!("Unrecognized argument: {}", s))
137     };
138
139     println!("{} {}", binary, env!("CFG_VERSION"));
140     if verbose {
141         println!("binary: {}", binary);
142         println!("commit-hash: {}", option_env!("CFG_VER_HASH").unwrap_or("unknown"));
143         println!("commit-date: {}", option_env!("CFG_VER_DATE").unwrap_or("unknown"));
144         println!("host: {}", driver::host_triple());
145         println!("release: {}", env!("CFG_RELEASE"));
146     }
147     None
148 }
149
150 fn usage() {
151     let message = format!("Usage: rustc [OPTIONS] INPUT");
152     println!("{}\n\
153 Additional help:
154     -C help             Print codegen options
155     -W help             Print 'lint' options and default settings
156     -Z help             Print internal options for debugging rustc\n",
157               getopts::usage(message.as_slice(),
158                              config::optgroups().as_slice()));
159 }
160
161 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
162     println!("
163 Available lint options:
164     -W <foo>           Warn about <foo>
165     -A <foo>           Allow <foo>
166     -D <foo>           Deny <foo>
167     -F <foo>           Forbid <foo> (deny, and deny all overrides)
168
169 ");
170
171     fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
172         let mut lints: Vec<_> = lints.move_iter().map(|(x, _)| x).collect();
173         lints.sort_by(|x: &&Lint, y: &&Lint| {
174             match x.default_level.cmp(&y.default_level) {
175                 // The sort doesn't case-fold but it's doubtful we care.
176                 Equal => x.name.cmp(&y.name),
177                 r => r,
178             }
179         });
180         lints
181     }
182
183     let (plugin, builtin) = lint_store.get_lints().partitioned(|&(_, p)| p);
184     let plugin = sort_lints(plugin);
185     let builtin = sort_lints(builtin);
186
187     // FIXME (#7043): We should use the width in character cells rather than
188     // the number of codepoints.
189     let max_name_len = plugin.iter().chain(builtin.iter())
190         .map(|&s| s.name.char_len())
191         .max().unwrap_or(0);
192     let padded = |x: &str| {
193         " ".repeat(max_name_len - x.char_len()).append(x)
194     };
195
196     println!("Lint checks provided by rustc:\n");
197     println!("    {}  {:7.7s}  {}", padded("name"), "default", "meaning");
198     println!("    {}  {:7.7s}  {}", padded("----"), "-------", "-------");
199
200     let print_lints = |lints: Vec<&Lint>| {
201         for lint in lints.move_iter() {
202             let name = lint.name_lower().replace("_", "-");
203             println!("    {}  {:7.7s}  {}",
204                      padded(name.as_slice()), lint.default_level.as_str(), lint.desc);
205         }
206         println!("\n");
207     };
208
209     print_lints(builtin);
210
211     match (loaded_plugins, plugin.len()) {
212         (false, 0) => {
213             println!("Compiler plugins can provide additional lints. To see a listing of these, \
214                       re-run `rustc -W help` with a crate filename.");
215         }
216         (false, _) => fail!("didn't load lint plugins but got them anyway!"),
217         (true, 0) => println!("This crate does not load any lint plugins."),
218         (true, _) => {
219             println!("Lint checks provided by plugins loaded by this crate:\n");
220             print_lints(plugin);
221         }
222     }
223 }
224
225 fn describe_debug_flags() {
226     println!("\nAvailable debug options:\n");
227     let r = config::debugging_opts_map();
228     for tuple in r.iter() {
229         match *tuple {
230             (ref name, ref desc, _) => {
231                 println!("    -Z {:>20s} -- {}", *name, *desc);
232             }
233         }
234     }
235 }
236
237 fn describe_codegen_flags() {
238     println!("\nAvailable codegen options:\n");
239     let mut cg = config::basic_codegen_options();
240     for &(name, parser, desc) in config::CG_OPTIONS.iter() {
241         // we invoke the parser function on `None` to see if this option needs
242         // an argument or not.
243         let (width, extra) = if parser(&mut cg, None) {
244             (25, "")
245         } else {
246             (21, "=val")
247         };
248         println!("    -C {:>width$s}{} -- {}", name.replace("_", "-"),
249                  extra, desc, width=width);
250     }
251 }
252
253 /// Process command line options. Emits messages as appropriate. If compilation
254 /// should continue, returns a getopts::Matches object parsed from args, otherwise
255 /// returns None.
256 pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
257     // Throw away the first argument, the name of the binary
258     let _binary = args.shift().unwrap();
259
260     if args.is_empty() {
261         usage();
262         return None;
263     }
264
265     let matches =
266         match getopts::getopts(args.as_slice(), config::optgroups().as_slice()) {
267             Ok(m) => m,
268             Err(f) => {
269                 early_error(f.to_string().as_slice());
270             }
271         };
272
273     if matches.opt_present("h") || matches.opt_present("help") {
274         usage();
275         return None;
276     }
277
278     // Don't handle -W help here, because we might first load plugins.
279
280     let r = matches.opt_strs("Z");
281     if r.iter().any(|x| x.as_slice() == "help") {
282         describe_debug_flags();
283         return None;
284     }
285
286     let cg_flags = matches.opt_strs("C");
287     if cg_flags.iter().any(|x| x.as_slice() == "help") {
288         describe_codegen_flags();
289         return None;
290     }
291
292     if cg_flags.contains(&"passes=list".to_string()) {
293         unsafe { ::llvm::LLVMRustPrintPasses(); }
294         return None;
295     }
296
297     if matches.opt_present("version") {
298         match version("rustc", &matches) {
299             Some(err) => early_error(err.as_slice()),
300             None => return None
301         }
302     }
303
304     Some(matches)
305 }
306
307 fn print_crate_info(sess: &Session,
308                     input: &Input,
309                     odir: &Option<Path>,
310                     ofile: &Option<Path>)
311                     -> bool {
312     let (crate_name, crate_file_name) = sess.opts.print_metas;
313     // these nasty nested conditions are to avoid doing extra work
314     if crate_name || crate_file_name {
315         let attrs = parse_crate_attrs(sess, input);
316         let t_outputs = driver::build_output_filenames(input,
317                                                        odir,
318                                                        ofile,
319                                                        attrs.as_slice(),
320                                                        sess);
321         let id = link::find_crate_name(Some(sess), attrs.as_slice(), input);
322
323         if crate_name {
324             println!("{}", id);
325         }
326         if crate_file_name {
327             let crate_types = driver::collect_crate_types(sess, attrs.as_slice());
328             let metadata = driver::collect_crate_metadata(sess, attrs.as_slice());
329             *sess.crate_metadata.borrow_mut() = metadata;
330             for &style in crate_types.iter() {
331                 let fname = link::filename_for_input(sess, style, id.as_slice(),
332                                                      &t_outputs.with_extension(""));
333                 println!("{}", fname.filename_display());
334             }
335         }
336
337         true
338     } else {
339         false
340     }
341 }
342
343 pub enum PpMode {
344     PpmNormal,
345     PpmExpanded,
346     PpmTyped,
347     PpmIdentified,
348     PpmExpandedIdentified,
349     PpmFlowGraph(ast::NodeId),
350 }
351
352 pub fn parse_pretty(sess: &Session, name: &str) -> PpMode {
353     let mut split = name.splitn('=', 1);
354     let first = split.next().unwrap();
355     let opt_second = split.next();
356     match (opt_second, first) {
357         (None, "normal")       => PpmNormal,
358         (None, "expanded")     => PpmExpanded,
359         (None, "typed")        => PpmTyped,
360         (None, "expanded,identified") => PpmExpandedIdentified,
361         (None, "identified")   => PpmIdentified,
362         (arg, "flowgraph") => {
363              match arg.and_then(from_str) {
364                  Some(id) => PpmFlowGraph(id),
365                  None => {
366                      sess.fatal(format!("`pretty flowgraph=<nodeid>` needs \
367                                          an integer <nodeid>; got {}",
368                                         arg.unwrap_or("nothing")).as_slice())
369                  }
370              }
371         }
372         _ => {
373             sess.fatal(format!(
374                 "argument to `pretty` must be one of `normal`, \
375                  `expanded`, `flowgraph=<nodeid>`, `typed`, `identified`, \
376                  or `expanded,identified`; got {}", name).as_slice());
377         }
378     }
379 }
380
381 fn parse_crate_attrs(sess: &Session, input: &Input) ->
382                      Vec<ast::Attribute> {
383     let result = match *input {
384         FileInput(ref ifile) => {
385             parse::parse_crate_attrs_from_file(ifile,
386                                                Vec::new(),
387                                                &sess.parse_sess)
388         }
389         StrInput(ref src) => {
390             parse::parse_crate_attrs_from_source_str(
391                 driver::anon_src().to_string(),
392                 src.to_string(),
393                 Vec::new(),
394                 &sess.parse_sess)
395         }
396     };
397     result.move_iter().collect()
398 }
399
400 pub fn early_error(msg: &str) -> ! {
401     let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
402     emitter.emit(None, msg, None, diagnostic::Fatal);
403     fail!(diagnostic::FatalError);
404 }
405
406 pub fn early_warn(msg: &str) {
407     let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
408     emitter.emit(None, msg, None, diagnostic::Warning);
409 }
410
411 pub fn list_metadata(sess: &Session, path: &Path,
412                      out: &mut io::Writer) -> io::IoResult<()> {
413     metadata::loader::list_file_metadata(sess.targ_cfg.os, path, out)
414 }
415
416 /// Run a procedure which will detect failures in the compiler and print nicer
417 /// error messages rather than just failing the test.
418 ///
419 /// The diagnostic emitter yielded to the procedure should be used for reporting
420 /// errors of the compiler.
421 fn monitor(f: proc():Send) {
422     // FIXME: This is a hack for newsched since it doesn't support split stacks.
423     // rustc needs a lot of stack! When optimizations are disabled, it needs
424     // even *more* stack than usual as well.
425     #[cfg(rtopt)]
426     static STACK_SIZE: uint = 6000000;  // 6MB
427     #[cfg(not(rtopt))]
428     static STACK_SIZE: uint = 20000000; // 20MB
429
430     let (tx, rx) = channel();
431     let w = io::ChanWriter::new(tx);
432     let mut r = io::ChanReader::new(rx);
433
434     let mut task = TaskBuilder::new().named("rustc").stderr(box w);
435
436     // FIXME: Hacks on hacks. If the env is trying to override the stack size
437     // then *don't* set it explicitly.
438     if os::getenv("RUST_MIN_STACK").is_none() {
439         task = task.stack_size(STACK_SIZE);
440     }
441
442     match task.try(f) {
443         Ok(()) => { /* fallthrough */ }
444         Err(value) => {
445             // Task failed without emitting a fatal diagnostic
446             if !value.is::<diagnostic::FatalError>() {
447                 let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
448
449                 // a .span_bug or .bug call has already printed what
450                 // it wants to print.
451                 if !value.is::<diagnostic::ExplicitBug>() {
452                     emitter.emit(
453                         None,
454                         "unexpected failure",
455                         None,
456                         diagnostic::Bug);
457                 }
458
459                 let xs = [
460                     "the compiler hit an unexpected failure path. this is a bug.".to_string(),
461                     format!("we would appreciate a bug report: {}",
462                             BUG_REPORT_URL),
463                     "run with `RUST_BACKTRACE=1` for a backtrace".to_string(),
464                 ];
465                 for note in xs.iter() {
466                     emitter.emit(None, note.as_slice(), None, diagnostic::Note)
467                 }
468
469                 match r.read_to_string() {
470                     Ok(s) => println!("{}", s),
471                     Err(e) => {
472                         emitter.emit(None,
473                                      format!("failed to read internal \
474                                               stderr: {}",
475                                              e).as_slice(),
476                                      None,
477                                      diagnostic::Error)
478                     }
479                 }
480             }
481
482             // Fail so the process returns a failure code, but don't pollute the
483             // output with some unnecessary failure messages, we've already
484             // printed everything that we needed to.
485             io::stdio::set_stderr(box io::util::NullWriter);
486             fail!();
487         }
488     }
489 }