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