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