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