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