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