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