]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/lib.rs
Rollup merge of #48033 - GuillaumeGomez:better-char-cast-message, r=estebank
[rust.git] / src / librustdoc / lib.rs
1 // Copyright 2012-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 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
12        html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
13        html_root_url = "https://doc.rust-lang.org/nightly/",
14        html_playground_url = "https://play.rust-lang.org/")]
15 #![deny(warnings)]
16
17 #![feature(ascii_ctype)]
18 #![feature(rustc_private)]
19 #![feature(box_patterns)]
20 #![feature(box_syntax)]
21 #![feature(fs_read_write)]
22 #![feature(libc)]
23 #![feature(set_stdio)]
24 #![feature(slice_patterns)]
25 #![feature(test)]
26 #![feature(unicode)]
27 #![feature(vec_remove_item)]
28
29 extern crate arena;
30 extern crate getopts;
31 extern crate env_logger;
32 extern crate html_diff;
33 extern crate libc;
34 extern crate rustc;
35 extern crate rustc_data_structures;
36 extern crate rustc_const_math;
37 extern crate rustc_trans_utils;
38 extern crate rustc_driver;
39 extern crate rustc_resolve;
40 extern crate rustc_lint;
41 extern crate rustc_back;
42 extern crate rustc_metadata;
43 extern crate rustc_typeck;
44 extern crate serialize;
45 #[macro_use] extern crate syntax;
46 extern crate syntax_pos;
47 extern crate test as testing;
48 extern crate std_unicode;
49 #[macro_use] extern crate log;
50 extern crate rustc_errors as errors;
51 extern crate pulldown_cmark;
52 extern crate tempdir;
53
54 extern crate serialize as rustc_serialize; // used by deriving
55
56 use std::collections::{BTreeMap, BTreeSet};
57 use std::default::Default;
58 use std::env;
59 use std::fmt::Display;
60 use std::io;
61 use std::io::Write;
62 use std::path::{Path, PathBuf};
63 use std::process;
64 use std::sync::mpsc::channel;
65
66 use externalfiles::ExternalHtml;
67 use rustc::session::search_paths::SearchPaths;
68 use rustc::session::config::{ErrorOutputType, RustcOptGroup, nightly_options,
69                              Externs};
70
71 #[macro_use]
72 pub mod externalfiles;
73
74 pub mod clean;
75 pub mod core;
76 pub mod doctree;
77 pub mod fold;
78 pub mod html {
79     pub mod highlight;
80     pub mod escape;
81     pub mod item_type;
82     pub mod format;
83     pub mod layout;
84     pub mod markdown;
85     pub mod render;
86     pub mod toc;
87 }
88 pub mod markdown;
89 pub mod passes;
90 pub mod plugins;
91 pub mod visit_ast;
92 pub mod visit_lib;
93 pub mod test;
94 pub mod theme;
95
96 use clean::AttributesExt;
97
98 use html::markdown::RenderType;
99
100 struct Output {
101     krate: clean::Crate,
102     renderinfo: html::render::RenderInfo,
103     passes: Vec<String>,
104 }
105
106 pub fn main() {
107     const STACK_SIZE: usize = 32_000_000; // 32MB
108     env_logger::init().unwrap();
109     let res = std::thread::Builder::new().stack_size(STACK_SIZE).spawn(move || {
110         get_args().map(|args| main_args(&args)).unwrap_or(1)
111     }).unwrap().join().unwrap_or(101);
112     process::exit(res as i32);
113 }
114
115 fn get_args() -> Option<Vec<String>> {
116     env::args_os().enumerate()
117         .map(|(i, arg)| arg.into_string().map_err(|arg| {
118              print_error(format!("Argument {} is not valid Unicode: {:?}", i, arg));
119         }).ok())
120         .collect()
121 }
122
123 fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
124     where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
125 {
126     RustcOptGroup::stable(name, f)
127 }
128
129 fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
130     where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
131 {
132     RustcOptGroup::unstable(name, f)
133 }
134
135 pub fn opts() -> Vec<RustcOptGroup> {
136     vec![
137         stable("h", |o| o.optflag("h", "help", "show this help message")),
138         stable("V", |o| o.optflag("V", "version", "print rustdoc's version")),
139         stable("v", |o| o.optflag("v", "verbose", "use verbose output")),
140         stable("r", |o| {
141             o.optopt("r", "input-format", "the input type of the specified file",
142                      "[rust]")
143         }),
144         stable("w", |o| {
145             o.optopt("w", "output-format", "the output type to write", "[html]")
146         }),
147         stable("o", |o| o.optopt("o", "output", "where to place the output", "PATH")),
148         stable("crate-name", |o| {
149             o.optopt("", "crate-name", "specify the name of this crate", "NAME")
150         }),
151         stable("L", |o| {
152             o.optmulti("L", "library-path", "directory to add to crate search path",
153                        "DIR")
154         }),
155         stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
156         stable("extern", |o| {
157             o.optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH")
158         }),
159         stable("plugin-path", |o| {
160             o.optmulti("", "plugin-path", "directory to load plugins from", "DIR")
161         }),
162         stable("passes", |o| {
163             o.optmulti("", "passes",
164                        "list of passes to also run, you might want \
165                         to pass it multiple times; a value of `list` \
166                         will print available passes",
167                        "PASSES")
168         }),
169         stable("plugins", |o| {
170             o.optmulti("", "plugins", "space separated list of plugins to also load",
171                        "PLUGINS")
172         }),
173         stable("no-default", |o| {
174             o.optflag("", "no-defaults", "don't run the default passes")
175         }),
176         stable("document-private-items", |o| {
177             o.optflag("", "document-private-items", "document private items")
178         }),
179         stable("test", |o| o.optflag("", "test", "run code examples as tests")),
180         stable("test-args", |o| {
181             o.optmulti("", "test-args", "arguments to pass to the test runner",
182                        "ARGS")
183         }),
184         stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
185         stable("markdown-css", |o| {
186             o.optmulti("", "markdown-css",
187                        "CSS files to include via <link> in a rendered Markdown file",
188                        "FILES")
189         }),
190         stable("html-in-header", |o|  {
191             o.optmulti("", "html-in-header",
192                        "files to include inline in the <head> section of a rendered Markdown file \
193                         or generated documentation",
194                        "FILES")
195         }),
196         stable("html-before-content", |o| {
197             o.optmulti("", "html-before-content",
198                        "files to include inline between <body> and the content of a rendered \
199                         Markdown file or generated documentation",
200                        "FILES")
201         }),
202         stable("html-after-content", |o| {
203             o.optmulti("", "html-after-content",
204                        "files to include inline between the content and </body> of a rendered \
205                         Markdown file or generated documentation",
206                        "FILES")
207         }),
208         unstable("markdown-before-content", |o| {
209             o.optmulti("", "markdown-before-content",
210                        "files to include inline between <body> and the content of a rendered \
211                         Markdown file or generated documentation",
212                        "FILES")
213         }),
214         unstable("markdown-after-content", |o| {
215             o.optmulti("", "markdown-after-content",
216                        "files to include inline between the content and </body> of a rendered \
217                         Markdown file or generated documentation",
218                        "FILES")
219         }),
220         stable("markdown-playground-url", |o| {
221             o.optopt("", "markdown-playground-url",
222                      "URL to send code snippets to", "URL")
223         }),
224         stable("markdown-no-toc", |o| {
225             o.optflag("", "markdown-no-toc", "don't include table of contents")
226         }),
227         stable("e", |o| {
228             o.optopt("e", "extend-css",
229                      "To add some CSS rules with a given file to generate doc with your \
230                       own theme. However, your theme might break if the rustdoc's generated HTML \
231                       changes, so be careful!", "PATH")
232         }),
233         unstable("Z", |o| {
234             o.optmulti("Z", "",
235                        "internal and debugging options (only on nightly build)", "FLAG")
236         }),
237         stable("sysroot", |o| {
238             o.optopt("", "sysroot", "Override the system root", "PATH")
239         }),
240         unstable("playground-url", |o| {
241             o.optopt("", "playground-url",
242                      "URL to send code snippets to, may be reset by --markdown-playground-url \
243                       or `#![doc(html_playground_url=...)]`",
244                      "URL")
245         }),
246         unstable("disable-commonmark", |o| {
247             o.optflag("", "disable-commonmark", "to disable commonmark doc rendering/testing")
248         }),
249         unstable("display-warnings", |o| {
250             o.optflag("", "display-warnings", "to print code warnings when testing doc")
251         }),
252         unstable("crate-version", |o| {
253             o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
254         }),
255         unstable("linker", |o| {
256             o.optopt("", "linker", "linker used for building executable test code", "PATH")
257         }),
258         unstable("sort-modules-by-appearance", |o| {
259             o.optflag("", "sort-modules-by-appearance", "sort modules by where they appear in the \
260                                                          program, rather than alphabetically")
261         }),
262         unstable("deny-render-differences", |o| {
263             o.optflag("", "deny-render-differences", "abort doc runs when markdown rendering \
264                                                       differences are found")
265         }),
266         unstable("themes", |o| {
267             o.optmulti("", "themes",
268                        "additional themes which will be added to the generated docs",
269                        "FILES")
270         }),
271         unstable("theme-checker", |o| {
272             o.optmulti("", "theme-checker",
273                        "check if given theme is valid",
274                        "FILES")
275         }),
276     ]
277 }
278
279 pub fn usage(argv0: &str) {
280     let mut options = getopts::Options::new();
281     for option in opts() {
282         (option.apply)(&mut options);
283     }
284     println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
285 }
286
287 pub fn main_args(args: &[String]) -> isize {
288     let mut options = getopts::Options::new();
289     for option in opts() {
290         (option.apply)(&mut options);
291     }
292     let matches = match options.parse(&args[1..]) {
293         Ok(m) => m,
294         Err(err) => {
295             print_error(err);
296             return 1;
297         }
298     };
299     // Check for unstable options.
300     nightly_options::check_nightly_options(&matches, &opts());
301
302     // check for deprecated options
303     check_deprecated_options(&matches);
304
305     if matches.opt_present("h") || matches.opt_present("help") {
306         usage("rustdoc");
307         return 0;
308     } else if matches.opt_present("version") {
309         rustc_driver::version("rustdoc", &matches);
310         return 0;
311     }
312
313     if matches.opt_strs("passes") == ["list"] {
314         println!("Available passes for running rustdoc:");
315         for &(name, _, description) in passes::PASSES {
316             println!("{:>20} - {}", name, description);
317         }
318         println!("\nDefault passes for rustdoc:");
319         for &name in passes::DEFAULT_PASSES {
320             println!("{:>20}", name);
321         }
322         return 0;
323     }
324
325     let to_check = matches.opt_strs("theme-checker");
326     if !to_check.is_empty() {
327         let paths = theme::load_css_paths(include_bytes!("html/static/themes/main.css"));
328         let mut errors = 0;
329
330         println!("rustdoc: [theme-checker] Starting tests!");
331         for theme_file in to_check.iter() {
332             print!(" - Checking \"{}\"...", theme_file);
333             let (success, differences) = theme::test_theme_against(theme_file, &paths);
334             if !differences.is_empty() || !success {
335                 println!(" FAILED");
336                 errors += 1;
337                 if !differences.is_empty() {
338                     println!("{}", differences.join("\n"));
339                 }
340             } else {
341                 println!(" OK");
342             }
343         }
344         if errors != 0 {
345             return 1;
346         }
347         return 0;
348     }
349
350     if matches.free.is_empty() {
351         print_error("missing file operand");
352         return 1;
353     }
354     if matches.free.len() > 1 {
355         print_error("too many file operands");
356         return 1;
357     }
358     let input = &matches.free[0];
359
360     let mut libs = SearchPaths::new();
361     for s in &matches.opt_strs("L") {
362         libs.add_path(s, ErrorOutputType::default());
363     }
364     let externs = match parse_externs(&matches) {
365         Ok(ex) => ex,
366         Err(err) => {
367             print_error(err);
368             return 1;
369         }
370     };
371
372     let test_args = matches.opt_strs("test-args");
373     let test_args: Vec<String> = test_args.iter()
374                                           .flat_map(|s| s.split_whitespace())
375                                           .map(|s| s.to_string())
376                                           .collect();
377
378     let should_test = matches.opt_present("test");
379     let markdown_input = Path::new(input).extension()
380         .map_or(false, |e| e == "md" || e == "markdown");
381
382     let output = matches.opt_str("o").map(|s| PathBuf::from(&s));
383     let css_file_extension = matches.opt_str("e").map(|s| PathBuf::from(&s));
384     let cfgs = matches.opt_strs("cfg");
385
386     let render_type = if matches.opt_present("disable-commonmark") {
387         RenderType::Hoedown
388     } else {
389         RenderType::Pulldown
390     };
391
392     if let Some(ref p) = css_file_extension {
393         if !p.is_file() {
394             writeln!(
395                 &mut io::stderr(),
396                 "rustdoc: option --extend-css argument must be a file."
397             ).unwrap();
398             return 1;
399         }
400     }
401
402     let mut themes = Vec::new();
403     if matches.opt_present("themes") {
404         let paths = theme::load_css_paths(include_bytes!("html/static/themes/main.css"));
405
406         for (theme_file, theme_s) in matches.opt_strs("themes")
407                                             .iter()
408                                             .map(|s| (PathBuf::from(&s), s.to_owned())) {
409             if !theme_file.is_file() {
410                 println!("rustdoc: option --themes arguments must all be files");
411                 return 1;
412             }
413             let (success, ret) = theme::test_theme_against(&theme_file, &paths);
414             if !success || !ret.is_empty() {
415                 println!("rustdoc: invalid theme: \"{}\"", theme_s);
416                 println!("         Check what's wrong with the \"theme-checker\" option");
417                 return 1;
418             }
419             themes.push(theme_file);
420         }
421     }
422
423     let external_html = match ExternalHtml::load(
424             &matches.opt_strs("html-in-header"),
425             &matches.opt_strs("html-before-content"),
426             &matches.opt_strs("html-after-content"),
427             &matches.opt_strs("markdown-before-content"),
428             &matches.opt_strs("markdown-after-content"),
429             render_type) {
430         Some(eh) => eh,
431         None => return 3,
432     };
433     let crate_name = matches.opt_str("crate-name");
434     let playground_url = matches.opt_str("playground-url");
435     let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
436     let display_warnings = matches.opt_present("display-warnings");
437     let linker = matches.opt_str("linker").map(PathBuf::from);
438     let sort_modules_alphabetically = !matches.opt_present("sort-modules-by-appearance");
439
440     match (should_test, markdown_input) {
441         (true, true) => {
442             return markdown::test(input, cfgs, libs, externs, test_args, maybe_sysroot,
443                                   render_type, display_warnings, linker)
444         }
445         (true, false) => {
446             return test::run(Path::new(input), cfgs, libs, externs, test_args, crate_name,
447                              maybe_sysroot, render_type, display_warnings, linker)
448         }
449         (false, true) => return markdown::render(Path::new(input),
450                                                  output.unwrap_or(PathBuf::from("doc")),
451                                                  &matches, &external_html,
452                                                  !matches.opt_present("markdown-no-toc"),
453                                                  render_type),
454         (false, false) => {}
455     }
456
457     let output_format = matches.opt_str("w");
458     let deny_render_differences = matches.opt_present("deny-render-differences");
459     let res = acquire_input(PathBuf::from(input), externs, &matches, move |out| {
460         let Output { krate, passes, renderinfo } = out;
461         info!("going to format");
462         match output_format.as_ref().map(|s| &**s) {
463             Some("html") | None => {
464                 html::render::run(krate, &external_html, playground_url,
465                                   output.unwrap_or(PathBuf::from("doc")),
466                                   passes.into_iter().collect(),
467                                   css_file_extension,
468                                   renderinfo,
469                                   render_type,
470                                   sort_modules_alphabetically,
471                                   deny_render_differences,
472                                   themes)
473                     .expect("failed to generate documentation");
474                 0
475             }
476             Some(s) => {
477                 print_error(format!("unknown output format: {}", s));
478                 1
479             }
480         }
481     });
482     res.unwrap_or_else(|s| {
483         print_error(format!("input error: {}", s));
484         1
485     })
486 }
487
488 /// Prints an uniformized error message on the standard error output
489 fn print_error<T>(error_message: T) where T: Display {
490     writeln!(
491         &mut io::stderr(),
492         "rustdoc: {}\nTry 'rustdoc --help' for more information.",
493         error_message
494     ).unwrap();
495 }
496
497 /// Looks inside the command line arguments to extract the relevant input format
498 /// and files and then generates the necessary rustdoc output for formatting.
499 fn acquire_input<R, F>(input: PathBuf,
500                        externs: Externs,
501                        matches: &getopts::Matches,
502                        f: F)
503                        -> Result<R, String>
504 where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R {
505     match matches.opt_str("r").as_ref().map(|s| &**s) {
506         Some("rust") => Ok(rust_input(input, externs, matches, f)),
507         Some(s) => Err(format!("unknown input format: {}", s)),
508         None => Ok(rust_input(input, externs, matches, f))
509     }
510 }
511
512 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
513 /// returns a map mapping crate names to their paths or else an
514 /// error message.
515 fn parse_externs(matches: &getopts::Matches) -> Result<Externs, String> {
516     let mut externs = BTreeMap::new();
517     for arg in &matches.opt_strs("extern") {
518         let mut parts = arg.splitn(2, '=');
519         let name = parts.next().ok_or("--extern value must not be empty".to_string())?;
520         let location = parts.next()
521                                  .ok_or("--extern value must be of the format `foo=bar`"
522                                     .to_string())?;
523         let name = name.to_string();
524         externs.entry(name).or_insert_with(BTreeSet::new).insert(location.to_string());
525     }
526     Ok(Externs::new(externs))
527 }
528
529 /// Interprets the input file as a rust source file, passing it through the
530 /// compiler all the way through the analysis passes. The rustdoc output is then
531 /// generated from the cleaned AST of the crate.
532 ///
533 /// This form of input will run all of the plug/cleaning passes
534 fn rust_input<R, F>(cratefile: PathBuf, externs: Externs, matches: &getopts::Matches, f: F) -> R
535 where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R {
536     let mut default_passes = !matches.opt_present("no-defaults");
537     let mut passes = matches.opt_strs("passes");
538     let mut plugins = matches.opt_strs("plugins");
539
540     // We hardcode in the passes here, as this is a new flag and we
541     // are generally deprecating passes.
542     if matches.opt_present("document-private-items") {
543         default_passes = false;
544
545         passes = vec![
546             String::from("collapse-docs"),
547             String::from("unindent-comments"),
548         ];
549     }
550
551     // First, parse the crate and extract all relevant information.
552     let mut paths = SearchPaths::new();
553     for s in &matches.opt_strs("L") {
554         paths.add_path(s, ErrorOutputType::default());
555     }
556     let cfgs = matches.opt_strs("cfg");
557     let triple = matches.opt_str("target");
558     let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
559     let crate_name = matches.opt_str("crate-name");
560     let crate_version = matches.opt_str("crate-version");
561     let plugin_path = matches.opt_str("plugin-path");
562     let render_type = if matches.opt_present("disable-commonmark") {
563         RenderType::Hoedown
564     } else {
565         RenderType::Pulldown
566     };
567
568     info!("starting to run rustc");
569     let display_warnings = matches.opt_present("display-warnings");
570
571     let force_unstable_if_unmarked = matches.opt_strs("Z").iter().any(|x| {
572         *x == "force-unstable-if-unmarked"
573     });
574
575     let (tx, rx) = channel();
576     rustc_driver::monitor(move || {
577         use rustc::session::config::Input;
578
579         let (mut krate, renderinfo) =
580             core::run_core(paths, cfgs, externs, Input::File(cratefile), triple, maybe_sysroot,
581                            display_warnings, force_unstable_if_unmarked, render_type);
582
583         info!("finished with rustc");
584
585         if let Some(name) = crate_name {
586             krate.name = name
587         }
588
589         krate.version = crate_version;
590
591         // Process all of the crate attributes, extracting plugin metadata along
592         // with the passes which we are supposed to run.
593         for attr in krate.module.as_ref().unwrap().attrs.lists("doc") {
594             let name = attr.name().map(|s| s.as_str());
595             let name = name.as_ref().map(|s| &s[..]);
596             if attr.is_word() {
597                 if name == Some("no_default_passes") {
598                     default_passes = false;
599                 }
600             } else if let Some(value) = attr.value_str() {
601                 let sink = match name {
602                     Some("passes") => &mut passes,
603                     Some("plugins") => &mut plugins,
604                     _ => continue,
605                 };
606                 for p in value.as_str().split_whitespace() {
607                     sink.push(p.to_string());
608                 }
609             }
610         }
611
612         if default_passes {
613             for name in passes::DEFAULT_PASSES.iter().rev() {
614                 passes.insert(0, name.to_string());
615             }
616         }
617
618         // Load all plugins/passes into a PluginManager
619         let path = plugin_path.unwrap_or("/tmp/rustdoc/plugins".to_string());
620         let mut pm = plugins::PluginManager::new(PathBuf::from(path));
621         for pass in &passes {
622             let plugin = match passes::PASSES.iter()
623                                              .position(|&(p, ..)| {
624                                                  p == *pass
625                                              }) {
626                 Some(i) => passes::PASSES[i].1,
627                 None => {
628                     error!("unknown pass {}, skipping", *pass);
629                     continue
630                 },
631             };
632             pm.add_plugin(plugin);
633         }
634         info!("loading plugins...");
635         for pname in plugins {
636             pm.load_plugin(pname);
637         }
638
639         // Run everything!
640         info!("Executing passes/plugins");
641         let krate = pm.run_plugins(krate);
642
643         tx.send(f(Output { krate: krate, renderinfo: renderinfo, passes: passes })).unwrap();
644     });
645     rx.recv().unwrap()
646 }
647
648 /// Prints deprecation warnings for deprecated options
649 fn check_deprecated_options(matches: &getopts::Matches) {
650     let deprecated_flags = [
651        "input-format",
652        "output-format",
653        "plugin-path",
654        "plugins",
655        "no-defaults",
656        "passes",
657     ];
658
659     for flag in deprecated_flags.into_iter() {
660         if matches.opt_present(flag) {
661             eprintln!("WARNING: the '{}' flag is considered deprecated", flag);
662             eprintln!("WARNING: please see https://github.com/rust-lang/rust/issues/44136");
663         }
664     }
665
666     if matches.opt_present("no-defaults") {
667         eprintln!("WARNING: (you may want to use --document-private-items)");
668     }
669 }