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