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