]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/lib.rs
Updating the instructions for when a tool breaks to use the new toolstate feature
[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(rustc_private)]
18 #![feature(box_patterns)]
19 #![feature(box_syntax)]
20 #![feature(libc)]
21 #![feature(set_stdio)]
22 #![feature(slice_patterns)]
23 #![feature(test)]
24 #![feature(unicode)]
25 #![feature(vec_remove_item)]
26 #![feature(ascii_ctype)]
27
28 extern crate arena;
29 extern crate getopts;
30 extern crate env_logger;
31 extern crate html_diff;
32 extern crate libc;
33 extern crate rustc;
34 extern crate rustc_data_structures;
35 extern crate rustc_const_math;
36 extern crate rustc_trans;
37 extern crate rustc_driver;
38 extern crate rustc_resolve;
39 extern crate rustc_lint;
40 extern crate rustc_back;
41 extern crate rustc_metadata;
42 extern crate rustc_typeck;
43 extern crate serialize;
44 #[macro_use] extern crate syntax;
45 extern crate syntax_pos;
46 extern crate test as testing;
47 extern crate std_unicode;
48 #[macro_use] extern crate log;
49 extern crate rustc_errors as errors;
50 extern crate pulldown_cmark;
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::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,
67                              Externs};
68
69 #[macro_use]
70 pub mod externalfiles;
71
72 pub mod clean;
73 pub mod core;
74 pub mod doctree;
75 pub mod fold;
76 pub mod html {
77     pub mod highlight;
78     pub mod escape;
79     pub mod item_type;
80     pub mod format;
81     pub mod layout;
82     pub mod markdown;
83     pub mod render;
84     pub mod toc;
85 }
86 pub mod markdown;
87 pub mod passes;
88 pub mod plugins;
89 pub mod visit_ast;
90 pub mod visit_lib;
91 pub mod test;
92
93 use clean::AttributesExt;
94
95 use html::markdown::RenderType;
96
97 struct Output {
98     krate: clean::Crate,
99     renderinfo: html::render::RenderInfo,
100     passes: Vec<String>,
101 }
102
103 pub fn main() {
104     const STACK_SIZE: usize = 32_000_000; // 32MB
105     env_logger::init().unwrap();
106     let res = std::thread::Builder::new().stack_size(STACK_SIZE).spawn(move || {
107         get_args().map(|args| main_args(&args)).unwrap_or(1)
108     }).unwrap().join().unwrap_or(101);
109     process::exit(res as i32);
110 }
111
112 fn get_args() -> Option<Vec<String>> {
113     env::args_os().enumerate()
114         .map(|(i, arg)| arg.into_string().map_err(|arg| {
115              print_error(format!("Argument {} is not valid Unicode: {:?}", i, arg));
116         }).ok())
117         .collect()
118 }
119
120 fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
121     where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
122 {
123     RustcOptGroup::stable(name, f)
124 }
125
126 fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
127     where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
128 {
129     RustcOptGroup::unstable(name, f)
130 }
131
132 pub fn opts() -> Vec<RustcOptGroup> {
133     vec![
134         stable("h", |o| o.optflag("h", "help", "show this help message")),
135         stable("V", |o| o.optflag("V", "version", "print rustdoc's version")),
136         stable("v", |o| o.optflag("v", "verbose", "use verbose output")),
137         stable("r", |o| {
138             o.optopt("r", "input-format", "the input type of the specified file",
139                      "[rust]")
140         }),
141         stable("w", |o| {
142             o.optopt("w", "output-format", "the output type to write", "[html]")
143         }),
144         stable("o", |o| o.optopt("o", "output", "where to place the output", "PATH")),
145         stable("crate-name", |o| {
146             o.optopt("", "crate-name", "specify the name of this crate", "NAME")
147         }),
148         stable("L", |o| {
149             o.optmulti("L", "library-path", "directory to add to crate search path",
150                        "DIR")
151         }),
152         stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
153         stable("extern", |o| {
154             o.optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH")
155         }),
156         stable("plugin-path", |o| {
157             o.optmulti("", "plugin-path", "directory to load plugins from", "DIR")
158         }),
159         stable("passes", |o| {
160             o.optmulti("", "passes",
161                        "list of passes to also run, you might want \
162                         to pass it multiple times; a value of `list` \
163                         will print available passes",
164                        "PASSES")
165         }),
166         stable("plugins", |o| {
167             o.optmulti("", "plugins", "space separated list of plugins to also load",
168                        "PLUGINS")
169         }),
170         stable("no-default", |o| {
171             o.optflag("", "no-defaults", "don't run the default passes")
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("enable-commonmark", |o| {
241             o.optflag("", "enable-commonmark", "to enable commonmark doc rendering/testing")
242         }),
243         unstable("display-warnings", |o| {
244             o.optflag("", "display-warnings", "to print code warnings when testing doc")
245         }),
246         unstable("crate-version", |o| {
247             o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
248         }),
249         unstable("linker", |o| {
250             o.optopt("", "linker", "linker used for building executable test code", "PATH")
251         }),
252     ]
253 }
254
255 pub fn usage(argv0: &str) {
256     let mut options = getopts::Options::new();
257     for option in opts() {
258         (option.apply)(&mut options);
259     }
260     println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
261 }
262
263 pub fn main_args(args: &[String]) -> isize {
264     let mut options = getopts::Options::new();
265     for option in opts() {
266         (option.apply)(&mut options);
267     }
268     let matches = match options.parse(&args[1..]) {
269         Ok(m) => m,
270         Err(err) => {
271             print_error(err);
272             return 1;
273         }
274     };
275     // Check for unstable options.
276     nightly_options::check_nightly_options(&matches, &opts());
277
278     if matches.opt_present("h") || matches.opt_present("help") {
279         usage("rustdoc");
280         return 0;
281     } else if matches.opt_present("version") {
282         rustc_driver::version("rustdoc", &matches);
283         return 0;
284     }
285
286     if matches.opt_strs("passes") == ["list"] {
287         println!("Available passes for running rustdoc:");
288         for &(name, _, description) in passes::PASSES {
289             println!("{:>20} - {}", name, description);
290         }
291         println!("\nDefault passes for rustdoc:");
292         for &name in passes::DEFAULT_PASSES {
293             println!("{:>20}", name);
294         }
295         return 0;
296     }
297
298     if matches.free.is_empty() {
299         print_error("missing file operand");
300         return 1;
301     }
302     if matches.free.len() > 1 {
303         print_error("too many file operands");
304         return 1;
305     }
306     let input = &matches.free[0];
307
308     let mut libs = SearchPaths::new();
309     for s in &matches.opt_strs("L") {
310         libs.add_path(s, ErrorOutputType::default());
311     }
312     let externs = match parse_externs(&matches) {
313         Ok(ex) => ex,
314         Err(err) => {
315             print_error(err);
316             return 1;
317         }
318     };
319
320     let test_args = matches.opt_strs("test-args");
321     let test_args: Vec<String> = test_args.iter()
322                                           .flat_map(|s| s.split_whitespace())
323                                           .map(|s| s.to_string())
324                                           .collect();
325
326     let should_test = matches.opt_present("test");
327     let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
328
329     let output = matches.opt_str("o").map(|s| PathBuf::from(&s));
330     let css_file_extension = matches.opt_str("e").map(|s| PathBuf::from(&s));
331     let cfgs = matches.opt_strs("cfg");
332
333     let render_type = if matches.opt_present("enable-commonmark") {
334         RenderType::Pulldown
335     } else {
336         RenderType::Hoedown
337     };
338
339     if let Some(ref p) = css_file_extension {
340         if !p.is_file() {
341             writeln!(
342                 &mut io::stderr(),
343                 "rustdoc: option --extend-css argument must be a file."
344             ).unwrap();
345             return 1;
346         }
347     }
348
349     let external_html = match ExternalHtml::load(
350             &matches.opt_strs("html-in-header"),
351             &matches.opt_strs("html-before-content"),
352             &matches.opt_strs("html-after-content"),
353             &matches.opt_strs("markdown-before-content"),
354             &matches.opt_strs("markdown-after-content"),
355             render_type) {
356         Some(eh) => eh,
357         None => return 3,
358     };
359     let crate_name = matches.opt_str("crate-name");
360     let playground_url = matches.opt_str("playground-url");
361     let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
362     let display_warnings = matches.opt_present("display-warnings");
363     let linker = matches.opt_str("linker");
364
365     match (should_test, markdown_input) {
366         (true, true) => {
367             return markdown::test(input, cfgs, libs, externs, test_args, maybe_sysroot, render_type,
368                                   display_warnings, linker)
369         }
370         (true, false) => {
371             return test::run(input, cfgs, libs, externs, test_args, crate_name, maybe_sysroot,
372                              render_type, display_warnings, linker)
373         }
374         (false, true) => return markdown::render(input,
375                                                  output.unwrap_or(PathBuf::from("doc")),
376                                                  &matches, &external_html,
377                                                  !matches.opt_present("markdown-no-toc"),
378                                                  render_type),
379         (false, false) => {}
380     }
381
382     let output_format = matches.opt_str("w");
383     let res = acquire_input(input, externs, &matches, move |out| {
384         let Output { krate, passes, renderinfo } = out;
385         info!("going to format");
386         match output_format.as_ref().map(|s| &**s) {
387             Some("html") | None => {
388                 html::render::run(krate, &external_html, playground_url,
389                                   output.unwrap_or(PathBuf::from("doc")),
390                                   passes.into_iter().collect(),
391                                   css_file_extension,
392                                   renderinfo,
393                                   render_type)
394                     .expect("failed to generate documentation");
395                 0
396             }
397             Some(s) => {
398                 print_error(format!("unknown output format: {}", s));
399                 1
400             }
401         }
402     });
403     res.unwrap_or_else(|s| {
404         print_error(format!("input error: {}", s));
405         1
406     })
407 }
408
409 /// Prints an uniformized error message on the standard error output
410 fn print_error<T>(error_message: T) where T: Display {
411     writeln!(
412         &mut io::stderr(),
413         "rustdoc: {}\nTry 'rustdoc --help' for more information.",
414         error_message
415     ).unwrap();
416 }
417
418 /// Looks inside the command line arguments to extract the relevant input format
419 /// and files and then generates the necessary rustdoc output for formatting.
420 fn acquire_input<R, F>(input: &str,
421                        externs: Externs,
422                        matches: &getopts::Matches,
423                        f: F)
424                        -> Result<R, String>
425 where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R {
426     match matches.opt_str("r").as_ref().map(|s| &**s) {
427         Some("rust") => Ok(rust_input(input, externs, matches, f)),
428         Some(s) => Err(format!("unknown input format: {}", s)),
429         None => Ok(rust_input(input, externs, matches, f))
430     }
431 }
432
433 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
434 /// returns a map mapping crate names to their paths or else an
435 /// error message.
436 fn parse_externs(matches: &getopts::Matches) -> Result<Externs, String> {
437     let mut externs = BTreeMap::new();
438     for arg in &matches.opt_strs("extern") {
439         let mut parts = arg.splitn(2, '=');
440         let name = parts.next().ok_or("--extern value must not be empty".to_string())?;
441         let location = parts.next()
442                                  .ok_or("--extern value must be of the format `foo=bar`"
443                                     .to_string())?;
444         let name = name.to_string();
445         externs.entry(name).or_insert_with(BTreeSet::new).insert(location.to_string());
446     }
447     Ok(Externs::new(externs))
448 }
449
450 /// Interprets the input file as a rust source file, passing it through the
451 /// compiler all the way through the analysis passes. The rustdoc output is then
452 /// generated from the cleaned AST of the crate.
453 ///
454 /// This form of input will run all of the plug/cleaning passes
455 fn rust_input<R, F>(cratefile: &str, externs: Externs, matches: &getopts::Matches, f: F) -> R
456 where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R {
457     let mut default_passes = !matches.opt_present("no-defaults");
458     let mut passes = matches.opt_strs("passes");
459     let mut plugins = matches.opt_strs("plugins");
460
461     // First, parse the crate and extract all relevant information.
462     let mut paths = SearchPaths::new();
463     for s in &matches.opt_strs("L") {
464         paths.add_path(s, ErrorOutputType::default());
465     }
466     let cfgs = matches.opt_strs("cfg");
467     let triple = matches.opt_str("target");
468     let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
469     let crate_name = matches.opt_str("crate-name");
470     let crate_version = matches.opt_str("crate-version");
471     let plugin_path = matches.opt_str("plugin-path");
472
473     let cr = PathBuf::from(cratefile);
474     info!("starting to run rustc");
475     let display_warnings = matches.opt_present("display-warnings");
476
477     let force_unstable_if_unmarked = matches.opt_strs("Z").iter().any(|x| {
478         *x == "force-unstable-if-unmarked"
479     });
480
481     let (tx, rx) = channel();
482     rustc_driver::monitor(move || {
483         use rustc::session::config::Input;
484
485         let (mut krate, renderinfo) =
486             core::run_core(paths, cfgs, externs, Input::File(cr), triple, maybe_sysroot,
487                            display_warnings, force_unstable_if_unmarked);
488
489         info!("finished with rustc");
490
491         if let Some(name) = crate_name {
492             krate.name = name
493         }
494
495         krate.version = crate_version;
496
497         // Process all of the crate attributes, extracting plugin metadata along
498         // with the passes which we are supposed to run.
499         for attr in krate.module.as_ref().unwrap().attrs.lists("doc") {
500             let name = attr.name().map(|s| s.as_str());
501             let name = name.as_ref().map(|s| &s[..]);
502             if attr.is_word() {
503                 if name == Some("no_default_passes") {
504                     default_passes = false;
505                 }
506             } else if let Some(value) = attr.value_str() {
507                 let sink = match name {
508                     Some("passes") => &mut passes,
509                     Some("plugins") => &mut plugins,
510                     _ => continue,
511                 };
512                 for p in value.as_str().split_whitespace() {
513                     sink.push(p.to_string());
514                 }
515             }
516         }
517
518         if default_passes {
519             for name in passes::DEFAULT_PASSES.iter().rev() {
520                 passes.insert(0, name.to_string());
521             }
522         }
523
524         // Load all plugins/passes into a PluginManager
525         let path = plugin_path.unwrap_or("/tmp/rustdoc/plugins".to_string());
526         let mut pm = plugins::PluginManager::new(PathBuf::from(path));
527         for pass in &passes {
528             let plugin = match passes::PASSES.iter()
529                                              .position(|&(p, ..)| {
530                                                  p == *pass
531                                              }) {
532                 Some(i) => passes::PASSES[i].1,
533                 None => {
534                     error!("unknown pass {}, skipping", *pass);
535                     continue
536                 },
537             };
538             pm.add_plugin(plugin);
539         }
540         info!("loading plugins...");
541         for pname in plugins {
542             pm.load_plugin(pname);
543         }
544
545         // Run everything!
546         info!("Executing passes/plugins");
547         let krate = pm.run_plugins(krate);
548
549         tx.send(f(Output { krate: krate, renderinfo: renderinfo, passes: passes })).unwrap();
550     });
551     rx.recv().unwrap()
552 }