]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/lib.rs
Merge pull request #20510 from tshepang/patch-6
[rust.git] / src / librustc_driver / lib.rs
1 // Copyright 2014 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 //! The Rust compiler.
12 //!
13 //! # Note
14 //!
15 //! This API is completely unstable and subject to change.
16
17 #![crate_name = "rustc_driver"]
18 #![experimental]
19 #![crate_type = "dylib"]
20 #![crate_type = "rlib"]
21 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
22       html_favicon_url = "http://www.rust-lang.org/favicon.ico",
23       html_root_url = "http://doc.rust-lang.org/nightly/")]
24
25 #![feature(default_type_params, globs, macro_rules, phase, quote)]
26 #![feature(slicing_syntax, unsafe_destructor)]
27 #![feature(rustc_diagnostic_macros)]
28 #![feature(unboxed_closures)]
29 #![feature(associated_types)]
30
31 extern crate arena;
32 extern crate flate;
33 extern crate getopts;
34 extern crate graphviz;
35 extern crate libc;
36 extern crate rustc;
37 extern crate rustc_back;
38 extern crate rustc_borrowck;
39 extern crate rustc_resolve;
40 extern crate rustc_trans;
41 extern crate rustc_typeck;
42 #[phase(plugin, link)] extern crate log;
43 #[phase(plugin, link)] extern crate syntax;
44 extern crate serialize;
45 extern crate "rustc_llvm" as llvm;
46
47 pub use syntax::diagnostic;
48
49 use rustc_trans::back::link;
50 use rustc::session::{config, Session, build_session};
51 use rustc::session::config::{Input, PrintRequest};
52 use rustc::lint::Lint;
53 use rustc::lint;
54 use rustc::metadata;
55 use rustc::DIAGNOSTICS;
56
57 use std::cmp::Ordering::Equal;
58 use std::io;
59 use std::iter::repeat;
60 use std::os;
61 use std::sync::mpsc::channel;
62 use std::thread;
63
64 use rustc::session::early_error;
65
66 use syntax::ast;
67 use syntax::parse;
68 use syntax::diagnostic::Emitter;
69 use syntax::diagnostics;
70
71 #[cfg(test)]
72 pub mod test;
73
74 pub mod driver;
75 pub mod pretty;
76
77 pub fn run(args: Vec<String>) -> int {
78     monitor(move |:| run_compiler(args.as_slice()));
79     0
80 }
81
82 static BUG_REPORT_URL: &'static str =
83     "http://doc.rust-lang.org/complement-bugreport.html";
84
85 fn run_compiler(args: &[String]) {
86     let matches = match handle_options(args.to_vec()) {
87         Some(matches) => matches,
88         None => return
89     };
90
91     let descriptions = diagnostics::registry::Registry::new(&DIAGNOSTICS);
92     match matches.opt_str("explain") {
93         Some(ref code) => {
94             match descriptions.find_description(code[]) {
95                 Some(ref description) => {
96                     println!("{}", description);
97                 }
98                 None => {
99                     early_error(format!("no extended information for {}", code)[]);
100                 }
101             }
102             return;
103         },
104         None => ()
105     }
106
107     let sopts = config::build_session_options(&matches);
108     let odir = matches.opt_str("out-dir").map(|o| Path::new(o));
109     let ofile = matches.opt_str("o").map(|o| Path::new(o));
110     let (input, input_file_path) = match matches.free.len() {
111         0u => {
112             if sopts.describe_lints {
113                 let mut ls = lint::LintStore::new();
114                 ls.register_builtin(None);
115                 describe_lints(&ls, false);
116                 return;
117             }
118             let sess = build_session(sopts, None, descriptions);
119             if print_crate_info(&sess, None, &odir, &ofile) {
120                 return;
121             }
122             early_error("no input filename given");
123         }
124         1u => {
125             let ifile = matches.free[0][];
126             if ifile == "-" {
127                 let contents = io::stdin().read_to_end().unwrap();
128                 let src = String::from_utf8(contents).unwrap();
129                 (Input::Str(src), None)
130             } else {
131                 (Input::File(Path::new(ifile)), Some(Path::new(ifile)))
132             }
133         }
134         _ => early_error("multiple input filenames provided")
135     };
136
137     let sess = build_session(sopts, input_file_path, descriptions);
138     let cfg = config::build_configuration(&sess);
139     if print_crate_info(&sess, Some(&input), &odir, &ofile) {
140         return
141     }
142
143     let pretty = matches.opt_default("pretty", "normal").map(|a| {
144         // stable pretty-print variants only
145         pretty::parse_pretty(&sess, a.as_slice(), false)
146     });
147     let pretty = if pretty.is_none() &&
148         sess.debugging_opt(config::UNSTABLE_OPTIONS) {
149             matches.opt_str("xpretty").map(|a| {
150                 // extended with unstable pretty-print variants
151                 pretty::parse_pretty(&sess, a.as_slice(), true)
152             })
153         } else {
154             pretty
155         };
156
157     match pretty.into_iter().next() {
158         Some((ppm, opt_uii)) => {
159             pretty::pretty_print_input(sess, cfg, &input, ppm, opt_uii, ofile);
160             return;
161         }
162         None => {/* continue */ }
163     }
164
165     let r = matches.opt_strs("Z");
166     if r.contains(&("ls".to_string())) {
167         match input {
168             Input::File(ref ifile) => {
169                 let mut stdout = io::stdout();
170                 list_metadata(&sess, &(*ifile), &mut stdout).unwrap();
171             }
172             Input::Str(_) => {
173                 early_error("can not list metadata for stdin");
174             }
175         }
176         return;
177     }
178
179     driver::compile_input(sess, cfg, &input, &odir, &ofile, None);
180 }
181
182 /// Returns a version string such as "0.12.0-dev".
183 pub fn release_str() -> Option<&'static str> {
184     option_env!("CFG_RELEASE")
185 }
186
187 /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
188 pub fn commit_hash_str() -> Option<&'static str> {
189     option_env!("CFG_VER_HASH")
190 }
191
192 /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
193 pub fn commit_date_str() -> Option<&'static str> {
194     option_env!("CFG_VER_DATE")
195 }
196
197 /// Prints version information and returns None on success or an error
198 /// message on panic.
199 pub fn version(binary: &str, matches: &getopts::Matches) {
200     let verbose = matches.opt_present("verbose");
201
202     println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
203     if verbose {
204         fn unw(x: Option<&str>) -> &str { x.unwrap_or("unknown") }
205         println!("binary: {}", binary);
206         println!("commit-hash: {}", unw(commit_hash_str()));
207         println!("commit-date: {}", unw(commit_date_str()));
208         println!("host: {}", config::host_triple());
209         println!("release: {}", unw(release_str()));
210     }
211 }
212
213 fn usage(verbose: bool, include_unstable_options: bool) {
214     let groups = if verbose {
215         config::rustc_optgroups()
216     } else {
217         config::rustc_short_optgroups()
218     };
219     let groups : Vec<_> = groups.into_iter()
220         .filter(|x| include_unstable_options || x.is_stable())
221         .map(|x|x.opt_group)
222         .collect();
223     let message = format!("Usage: rustc [OPTIONS] INPUT");
224     let extra_help = if verbose {
225         ""
226     } else {
227         "\n    --help -v           Print the full set of options rustc accepts"
228     };
229     println!("{}\n\
230 Additional help:
231     -C help             Print codegen options
232     -W help             Print 'lint' options and default settings
233     -Z help             Print internal options for debugging rustc{}\n",
234               getopts::usage(message.as_slice(), groups.as_slice()),
235               extra_help);
236 }
237
238 fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
239     println!("
240 Available lint options:
241     -W <foo>           Warn about <foo>
242     -A <foo>           Allow <foo>
243     -D <foo>           Deny <foo>
244     -F <foo>           Forbid <foo> (deny, and deny all overrides)
245
246 ");
247
248     fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
249         let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
250         lints.sort_by(|x: &&Lint, y: &&Lint| {
251             match x.default_level.cmp(&y.default_level) {
252                 // The sort doesn't case-fold but it's doubtful we care.
253                 Equal => x.name.cmp(y.name),
254                 r => r,
255             }
256         });
257         lints
258     }
259
260     fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
261                      -> Vec<(&'static str, Vec<lint::LintId>)> {
262         let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
263         lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
264                        &(y, _): &(&'static str, Vec<lint::LintId>)| {
265             x.cmp(y)
266         });
267         lints
268     }
269
270     let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
271         .iter().cloned().partition(|&(_, p)| p);
272     let plugin = sort_lints(plugin);
273     let builtin = sort_lints(builtin);
274
275     let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
276         .iter().cloned().partition(|&(_, _, p)| p);
277     let plugin_groups = sort_lint_groups(plugin_groups);
278     let builtin_groups = sort_lint_groups(builtin_groups);
279
280     let max_name_len = plugin.iter().chain(builtin.iter())
281         .map(|&s| s.name.width(true))
282         .max().unwrap_or(0);
283     let padded = |&: x: &str| {
284         let mut s = repeat(" ").take(max_name_len - x.chars().count())
285                                .collect::<String>();
286         s.push_str(x);
287         s
288     };
289
290     println!("Lint checks provided by rustc:\n");
291     println!("    {}  {:7.7}  {}", padded("name"), "default", "meaning");
292     println!("    {}  {:7.7}  {}", padded("----"), "-------", "-------");
293
294     let print_lints = |&: lints: Vec<&Lint>| {
295         for lint in lints.into_iter() {
296             let name = lint.name_lower().replace("_", "-");
297             println!("    {}  {:7.7}  {}",
298                      padded(name[]), lint.default_level.as_str(), lint.desc);
299         }
300         println!("\n");
301     };
302
303     print_lints(builtin);
304
305
306
307     let max_name_len = plugin_groups.iter().chain(builtin_groups.iter())
308         .map(|&(s, _)| s.width(true))
309         .max().unwrap_or(0);
310     let padded = |&: x: &str| {
311         let mut s = repeat(" ").take(max_name_len - x.chars().count())
312                                .collect::<String>();
313         s.push_str(x);
314         s
315     };
316
317     println!("Lint groups provided by rustc:\n");
318     println!("    {}  {}", padded("name"), "sub-lints");
319     println!("    {}  {}", padded("----"), "---------");
320
321     let print_lint_groups = |&: lints: Vec<(&'static str, Vec<lint::LintId>)>| {
322         for (name, to) in lints.into_iter() {
323             let name = name.chars().map(|x| x.to_lowercase())
324                            .collect::<String>().replace("_", "-");
325             let desc = to.into_iter().map(|x| x.as_str().replace("_", "-"))
326                          .collect::<Vec<String>>().connect(", ");
327             println!("    {}  {}",
328                      padded(name[]), desc);
329         }
330         println!("\n");
331     };
332
333     print_lint_groups(builtin_groups);
334
335     match (loaded_plugins, plugin.len(), plugin_groups.len()) {
336         (false, 0, _) | (false, _, 0) => {
337             println!("Compiler plugins can provide additional lints and lint groups. To see a \
338                       listing of these, re-run `rustc -W help` with a crate filename.");
339         }
340         (false, _, _) => panic!("didn't load lint plugins but got them anyway!"),
341         (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
342         (true, l, g) => {
343             if l > 0 {
344                 println!("Lint checks provided by plugins loaded by this crate:\n");
345                 print_lints(plugin);
346             }
347             if g > 0 {
348                 println!("Lint groups provided by plugins loaded by this crate:\n");
349                 print_lint_groups(plugin_groups);
350             }
351         }
352     }
353 }
354
355 fn describe_debug_flags() {
356     println!("\nAvailable debug options:\n");
357     let r = config::debugging_opts_map();
358     for tuple in r.iter() {
359         match *tuple {
360             (ref name, ref desc, _) => {
361                 println!("    -Z {:>20} -- {}", *name, *desc);
362             }
363         }
364     }
365 }
366
367 fn describe_codegen_flags() {
368     println!("\nAvailable codegen options:\n");
369     for &(name, _, opt_type_desc, desc) in config::CG_OPTIONS.iter() {
370         let (width, extra) = match opt_type_desc {
371             Some(..) => (21, "=val"),
372             None => (25, "")
373         };
374         println!("    -C {:>width$}{} -- {}", name.replace("_", "-"),
375                  extra, desc, width=width);
376     }
377 }
378
379 /// Process command line options. Emits messages as appropriate. If compilation
380 /// should continue, returns a getopts::Matches object parsed from args, otherwise
381 /// returns None.
382 pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
383     // Throw away the first argument, the name of the binary
384     let _binary = args.remove(0);
385
386     if args.is_empty() {
387         // user did not write `-v` nor `-Z unstable-options`, so do not
388         // include that extra information.
389         usage(false, false);
390         return None;
391     }
392
393     let matches =
394         match getopts::getopts(args[], config::optgroups()[]) {
395             Ok(m) => m,
396             Err(f_stable_attempt) => {
397                 // redo option parsing, including unstable options this time,
398                 // in anticipation that the mishandled option was one of the
399                 // unstable ones.
400                 let all_groups : Vec<getopts::OptGroup>
401                     = config::rustc_optgroups().into_iter().map(|x|x.opt_group).collect();
402                 match getopts::getopts(args.as_slice(), all_groups.as_slice()) {
403                     Ok(m_unstable) => {
404                         let r = m_unstable.opt_strs("Z");
405                         let include_unstable_options = r.iter().any(|x| *x == "unstable-options");
406                         if include_unstable_options {
407                             m_unstable
408                         } else {
409                             early_error(f_stable_attempt.to_string().as_slice());
410                         }
411                     }
412                     Err(_) => {
413                         // ignore the error from the unstable attempt; just
414                         // pass the error we got from the first try.
415                         early_error(f_stable_attempt.to_string().as_slice());
416                     }
417                 }
418             }
419         };
420
421     let r = matches.opt_strs("Z");
422     let include_unstable_options = r.iter().any(|x| *x == "unstable-options");
423
424     if matches.opt_present("h") || matches.opt_present("help") {
425         usage(matches.opt_present("verbose"), include_unstable_options);
426         return None;
427     }
428
429     // Don't handle -W help here, because we might first load plugins.
430
431     let r = matches.opt_strs("Z");
432     if r.iter().any(|x| *x == "help") {
433         describe_debug_flags();
434         return None;
435     }
436
437     let cg_flags = matches.opt_strs("C");
438     if cg_flags.iter().any(|x| *x == "help") {
439         describe_codegen_flags();
440         return None;
441     }
442
443     if cg_flags.contains(&"passes=list".to_string()) {
444         unsafe { ::llvm::LLVMRustPrintPasses(); }
445         return None;
446     }
447
448     if matches.opt_present("version") {
449         version("rustc", &matches);
450         return None;
451     }
452
453     Some(matches)
454 }
455
456 fn print_crate_info(sess: &Session,
457                     input: Option<&Input>,
458                     odir: &Option<Path>,
459                     ofile: &Option<Path>)
460                     -> bool {
461     if sess.opts.prints.len() == 0 { return false }
462
463     let attrs = input.map(|input| parse_crate_attrs(sess, input));
464     for req in sess.opts.prints.iter() {
465         match *req {
466             PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
467             PrintRequest::FileNames |
468             PrintRequest::CrateName => {
469                 let input = match input {
470                     Some(input) => input,
471                     None => early_error("no input file provided"),
472                 };
473                 let attrs = attrs.as_ref().unwrap().as_slice();
474                 let t_outputs = driver::build_output_filenames(input,
475                                                                odir,
476                                                                ofile,
477                                                                attrs,
478                                                                sess);
479                 let id = link::find_crate_name(Some(sess), attrs.as_slice(),
480                                                input);
481                 if *req == PrintRequest::CrateName {
482                     println!("{}", id);
483                     continue
484                 }
485                 let crate_types = driver::collect_crate_types(sess, attrs);
486                 let metadata = driver::collect_crate_metadata(sess, attrs);
487                 *sess.crate_metadata.borrow_mut() = metadata;
488                 for &style in crate_types.iter() {
489                     let fname = link::filename_for_input(sess, style,
490                                                          id.as_slice(),
491                                                          &t_outputs.with_extension(""));
492                     println!("{}", fname.filename_display());
493                 }
494             }
495         }
496     }
497     return true;
498 }
499
500 fn parse_crate_attrs(sess: &Session, input: &Input) ->
501                      Vec<ast::Attribute> {
502     let result = match *input {
503         Input::File(ref ifile) => {
504             parse::parse_crate_attrs_from_file(ifile,
505                                                Vec::new(),
506                                                &sess.parse_sess)
507         }
508         Input::Str(ref src) => {
509             parse::parse_crate_attrs_from_source_str(
510                 driver::anon_src().to_string(),
511                 src.to_string(),
512                 Vec::new(),
513                 &sess.parse_sess)
514         }
515     };
516     result.into_iter().collect()
517 }
518
519 pub fn list_metadata(sess: &Session, path: &Path,
520                      out: &mut io::Writer) -> io::IoResult<()> {
521     metadata::loader::list_file_metadata(sess.target.target.options.is_like_osx, path, out)
522 }
523
524 /// Run a procedure which will detect panics in the compiler and print nicer
525 /// error messages rather than just failing the test.
526 ///
527 /// The diagnostic emitter yielded to the procedure should be used for reporting
528 /// errors of the compiler.
529 pub fn monitor<F:FnOnce()+Send>(f: F) {
530     static STACK_SIZE: uint = 8 * 1024 * 1024; // 8MB
531
532     let (tx, rx) = channel();
533     let w = io::ChanWriter::new(tx);
534     let mut r = io::ChanReader::new(rx);
535
536     let mut cfg = thread::Builder::new().name("rustc".to_string());
537
538     // FIXME: Hacks on hacks. If the env is trying to override the stack size
539     // then *don't* set it explicitly.
540     if os::getenv("RUST_MIN_STACK").is_none() {
541         cfg = cfg.stack_size(STACK_SIZE);
542     }
543
544     match cfg.spawn(move || { std::io::stdio::set_stderr(box w); f() }).join() {
545         Ok(()) => { /* fallthrough */ }
546         Err(value) => {
547             // Thread panicked without emitting a fatal diagnostic
548             if !value.is::<diagnostic::FatalError>() {
549                 let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
550
551                 // a .span_bug or .bug call has already printed what
552                 // it wants to print.
553                 if !value.is::<diagnostic::ExplicitBug>() {
554                     emitter.emit(
555                         None,
556                         "unexpected panic",
557                         None,
558                         diagnostic::Bug);
559                 }
560
561                 let xs = [
562                     "the compiler unexpectedly panicked. this is a bug.".to_string(),
563                     format!("we would appreciate a bug report: {}",
564                             BUG_REPORT_URL),
565                     "run with `RUST_BACKTRACE=1` for a backtrace".to_string(),
566                 ];
567                 for note in xs.iter() {
568                     emitter.emit(None, note[], None, diagnostic::Note)
569                 }
570
571                 match r.read_to_string() {
572                     Ok(s) => println!("{}", s),
573                     Err(e) => {
574                         emitter.emit(None,
575                                      format!("failed to read internal \
576                                               stderr: {}", e)[],
577                                      None,
578                                      diagnostic::Error)
579                     }
580                 }
581             }
582
583             // Panic so the process returns a failure code, but don't pollute the
584             // output with some unnecessary panic messages, we've already
585             // printed everything that we needed to.
586             io::stdio::set_stderr(box io::util::NullWriter);
587             panic!();
588         }
589     }
590 }
591
592 pub fn main() {
593     let args = std::os::args();
594     let result = run(args);
595     std::os::set_exit_status(result);
596 }