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