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