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