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