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