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