]> git.lizzy.rs Git - rust.git/blob - src/librustc/rustc.rs
0bf0a74b2f43b764bfa262cf2d714e9dbe885282
[rust.git] / src / librustc / rustc.rs
1 // Copyright 2012-2013 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 #[link(name = "rustc",
12        vers = "0.8-pre",
13        uuid = "0ce89b41-2f92-459e-bbc1-8f5fe32f16cf",
14        url = "https://github.com/mozilla/rust/tree/master/src/rustc")];
15
16 #[comment = "The Rust compiler"];
17 #[license = "MIT/ASL2"];
18 #[crate_type = "lib"];
19
20 extern mod extra;
21 extern mod syntax;
22
23 use driver::driver::{host_triple, optgroups, early_error};
24 use driver::driver::{str_input, file_input, build_session_options};
25 use driver::driver::{build_session, build_configuration, parse_pretty};
26 use driver::driver::{pp_mode, pretty_print_input, list_metadata};
27 use driver::driver::{compile_input};
28 use driver::session;
29 use middle::lint;
30
31 use std::io;
32 use std::num;
33 use std::os;
34 use std::result;
35 use std::str;
36 use std::task;
37 use std::vec;
38 use extra::getopts::{groups, opt_present};
39 use extra::getopts;
40 use syntax::codemap;
41 use syntax::diagnostic;
42
43 pub mod middle {
44     pub mod trans;
45     pub mod ty;
46     pub mod subst;
47     pub mod resolve;
48     pub mod typeck;
49     pub mod check_loop;
50     pub mod check_match;
51     pub mod check_const;
52     pub mod lint;
53     pub mod borrowck;
54     pub mod dataflow;
55     pub mod mem_categorization;
56     pub mod liveness;
57     pub mod kind;
58     pub mod freevars;
59     pub mod pat_util;
60     pub mod region;
61     pub mod const_eval;
62     pub mod astencode;
63     pub mod lang_items;
64     pub mod privacy;
65     pub mod moves;
66     pub mod entry;
67     pub mod effect;
68     pub mod reachable;
69     pub mod graph;
70     pub mod cfg;
71     pub mod stack_check;
72 }
73
74 pub mod front {
75     pub mod config;
76     pub mod test;
77     pub mod std_inject;
78 }
79
80 pub mod back {
81     pub mod link;
82     pub mod abi;
83     pub mod upcall;
84     pub mod arm;
85     pub mod mips;
86     pub mod x86;
87     pub mod x86_64;
88     pub mod rpath;
89     pub mod target_strs;
90     pub mod passes;
91 }
92
93 pub mod metadata;
94
95 pub mod driver;
96
97 pub mod util {
98     pub mod common;
99     pub mod ppaux;
100 }
101
102 pub mod lib {
103     pub mod llvm;
104 }
105
106 // A curious inner module that allows ::std::foo to be available in here for
107 // macros.
108 /*
109 mod std {
110     pub use std::clone;
111     pub use std::cmp;
112     pub use std::os;
113     pub use std::str;
114     pub use std::sys;
115     pub use std::to_bytes;
116     pub use std::unstable;
117     pub use extra::serialize;
118 }
119 */
120
121 pub fn version(argv0: &str) {
122     let vers = match option_env!("CFG_VERSION") {
123         Some(vers) => vers,
124         None => "unknown version"
125     };
126     printfln!("%s %s", argv0, vers);
127     printfln!("host: %s", host_triple());
128 }
129
130 pub fn usage(argv0: &str) {
131     let message = fmt!("Usage: %s [OPTIONS] INPUT", argv0);
132     printfln!("%s\
133 Additional help:
134     -W help             Print 'lint' options and default settings
135     -Z help             Print internal options for debugging rustc\n",
136               groups::usage(message, optgroups()));
137 }
138
139 pub fn describe_warnings() {
140     use extra::sort::Sort;
141     println("
142 Available lint options:
143     -W <foo>           Warn about <foo>
144     -A <foo>           Allow <foo>
145     -D <foo>           Deny <foo>
146     -F <foo>           Forbid <foo> (deny, and deny all overrides)
147 ");
148
149     let lint_dict = lint::get_lint_dict();
150     let mut lint_dict = lint_dict.move_iter()
151                                  .map(|(k, v)| (v, k))
152                                  .collect::<~[(lint::LintSpec, &'static str)]>();
153     lint_dict.qsort();
154
155     let mut max_key = 0;
156     for &(_, name) in lint_dict.iter() {
157         max_key = num::max(name.len(), max_key);
158     }
159     fn padded(max: uint, s: &str) -> ~str {
160         str::from_bytes(vec::from_elem(max - s.len(), ' ' as u8)) + s
161     }
162     println("\nAvailable lint checks:\n");
163     printfln!("    %s  %7.7s  %s",
164               padded(max_key, "name"), "default", "meaning");
165     printfln!("    %s  %7.7s  %s\n",
166               padded(max_key, "----"), "-------", "-------");
167     for (spec, name) in lint_dict.move_iter() {
168         let name = name.replace("_", "-");
169         printfln!("    %s  %7.7s  %s",
170                   padded(max_key, name),
171                   lint::level_to_str(spec.default),
172                   spec.desc);
173     }
174     io::println("");
175 }
176
177 pub fn describe_debug_flags() {
178     println("\nAvailable debug options:\n");
179     let r = session::debugging_opts_map();
180     for tuple in r.iter() {
181         match *tuple {
182             (ref name, ref desc, _) => {
183                 printfln!("    -Z %-20s -- %s", *name, *desc);
184             }
185         }
186     }
187 }
188
189 pub fn run_compiler(args: &~[~str], demitter: diagnostic::Emitter) {
190     // Don't display log spew by default. Can override with RUST_LOG.
191     ::std::logging::console_off();
192
193     let mut args = (*args).clone();
194     let binary = args.shift().to_managed();
195
196     if args.is_empty() { usage(binary); return; }
197
198     let matches =
199         &match getopts::groups::getopts(args, optgroups()) {
200           Ok(m) => m,
201           Err(f) => {
202             early_error(demitter, getopts::fail_str(f));
203           }
204         };
205
206     if opt_present(matches, "h") || opt_present(matches, "help") {
207         usage(binary);
208         return;
209     }
210
211     // Display the available lint options if "-W help" or only "-W" is given.
212     let lint_flags = vec::append(getopts::opt_strs(matches, "W"),
213                                  getopts::opt_strs(matches, "warn"));
214
215     let show_lint_options = lint_flags.iter().any(|x| x == &~"help") ||
216         (opt_present(matches, "W") && lint_flags.is_empty());
217
218     if show_lint_options {
219         describe_warnings();
220         return;
221     }
222
223     let r = getopts::opt_strs(matches, "Z");
224     if r.iter().any(|x| x == &~"help") {
225         describe_debug_flags();
226         return;
227     }
228
229     if getopts::opt_maybe_str(matches, "passes") == Some(~"list") {
230         back::passes::list_passes();
231         return;
232     }
233
234     if opt_present(matches, "v") || opt_present(matches, "version") {
235         version(binary);
236         return;
237     }
238     let input = match matches.free.len() {
239       0u => early_error(demitter, ~"no input filename given"),
240       1u => {
241         let ifile = matches.free[0].as_slice();
242         if "-" == ifile {
243             let src = str::from_bytes(io::stdin().read_whole_stream());
244             str_input(src.to_managed())
245         } else {
246             file_input(Path(ifile))
247         }
248       }
249       _ => early_error(demitter, ~"multiple input filenames provided")
250     };
251
252     let sopts = build_session_options(binary, matches, demitter);
253     let sess = build_session(sopts, demitter);
254     let odir = getopts::opt_maybe_str(matches, "out-dir").map_move(|o| Path(o));
255     let ofile = getopts::opt_maybe_str(matches, "o").map_move(|o| Path(o));
256     let cfg = build_configuration(sess);
257     let pretty = do getopts::opt_default(matches, "pretty", "normal").map_move |a| {
258         parse_pretty(sess, a)
259     };
260     match pretty {
261       Some::<pp_mode>(ppm) => {
262         pretty_print_input(sess, cfg, &input, ppm);
263         return;
264       }
265       None::<pp_mode> => {/* continue */ }
266     }
267     let ls = opt_present(matches, "ls");
268     if ls {
269         match input {
270           file_input(ref ifile) => {
271             list_metadata(sess, &(*ifile), io::stdout());
272           }
273           str_input(_) => {
274             early_error(demitter, ~"can not list metadata for stdin");
275           }
276         }
277         return;
278     }
279
280     compile_input(sess, cfg, &input, &odir, &ofile);
281 }
282
283 #[deriving(Eq)]
284 pub enum monitor_msg {
285     fatal,
286     done,
287 }
288
289 /*
290 This is a sanity check that any failure of the compiler is performed
291 through the diagnostic module and reported properly - we shouldn't be calling
292 plain-old-fail on any execution path that might be taken. Since we have
293 console logging off by default, hitting a plain fail statement would make the
294 compiler silently exit, which would be terrible.
295
296 This method wraps the compiler in a subtask and injects a function into the
297 diagnostic emitter which records when we hit a fatal error. If the task
298 fails without recording a fatal error then we've encountered a compiler
299 bug and need to present an error.
300 */
301 pub fn monitor(f: ~fn(diagnostic::Emitter)) {
302     use std::comm::*;
303
304     // XXX: This is a hack for newsched since it doesn't support split stacks.
305     // rustc needs a lot of stack!
306     static STACK_SIZE: uint = 6000000;
307
308     let (p, ch) = stream();
309     let ch = SharedChan::new(ch);
310     let ch_capture = ch.clone();
311     let mut task_builder = task::task();
312     task_builder.supervised();
313
314     // XXX: Hacks on hacks. If the env is trying to override the stack size
315     // then *don't* set it explicitly.
316     if os::getenv("RUST_MIN_STACK").is_none() {
317         task_builder.opts.stack_size = Some(STACK_SIZE);
318     }
319
320     match do task_builder.try {
321         let ch = ch_capture.clone();
322         let ch_capture = ch.clone();
323         // The 'diagnostics emitter'. Every error, warning, etc. should
324         // go through this function.
325         let demitter: @fn(Option<(@codemap::CodeMap, codemap::span)>,
326                           &str,
327                           diagnostic::level) =
328                           |cmsp, msg, lvl| {
329             if lvl == diagnostic::fatal {
330                 ch_capture.send(fatal);
331             }
332             diagnostic::emit(cmsp, msg, lvl);
333         };
334
335         struct finally {
336             ch: SharedChan<monitor_msg>,
337         }
338
339         impl Drop for finally {
340             fn drop(&self) { self.ch.send(done); }
341         }
342
343         let _finally = finally { ch: ch };
344
345         f(demitter);
346
347         // Due reasons explain in #7732, if there was a jit execution context it
348         // must be consumed and passed along to our parent task.
349         back::link::jit::consume_engine()
350     } {
351         result::Ok(_) => { /* fallthrough */ }
352         result::Err(_) => {
353             // Task failed without emitting a fatal diagnostic
354             if p.recv() == done {
355                 diagnostic::emit(
356                     None,
357                     diagnostic::ice_msg("unexpected failure"),
358                     diagnostic::error);
359
360                 let xs = [
361                     ~"the compiler hit an unexpected failure path. \
362                      this is a bug",
363                     ~"try running with RUST_LOG=rustc=1 \
364                      to get further details and report the results \
365                      to github.com/mozilla/rust/issues"
366                 ];
367                 for note in xs.iter() {
368                     diagnostic::emit(None, *note, diagnostic::note)
369                 }
370             }
371             // Fail so the process returns a failure code
372             fail!();
373         }
374     }
375 }
376
377 pub fn main() {
378     let args = os::args();
379     do monitor |demitter| {
380         run_compiler(&args, demitter);
381     }
382 }