]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/lib.rs
Auto merge of #30457 - Manishearth:rollup, r=Manishearth
[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 // Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
12 #![cfg_attr(stage0, feature(custom_attribute))]
13 #![crate_name = "rustdoc"]
14 #![unstable(feature = "rustdoc", issue = "27812")]
15 #![cfg_attr(stage0, staged_api)]
16 #![crate_type = "dylib"]
17 #![crate_type = "rlib"]
18 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
19    html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
20    html_root_url = "https://doc.rust-lang.org/nightly/",
21    html_playground_url = "https://play.rust-lang.org/")]
22
23 #![feature(box_patterns)]
24 #![feature(box_syntax)]
25 #![feature(dynamic_lib)]
26 #![feature(libc)]
27 #![feature(path_relative_from)]
28 #![feature(rustc_private)]
29 #![feature(set_stdio)]
30 #![feature(slice_patterns)]
31 #![feature(staged_api)]
32 #![feature(test)]
33 #![feature(unicode)]
34
35 extern crate arena;
36 extern crate getopts;
37 extern crate libc;
38 extern crate rustc;
39 extern crate rustc_trans;
40 extern crate rustc_driver;
41 extern crate rustc_resolve;
42 extern crate rustc_lint;
43 extern crate rustc_back;
44 extern crate rustc_front;
45 extern crate rustc_metadata;
46 extern crate serialize;
47 extern crate syntax;
48 extern crate test as testing;
49 extern crate rustc_unicode;
50 #[macro_use] extern crate log;
51
52 extern crate serialize as rustc_serialize; // used by deriving
53
54 use std::cell::RefCell;
55 use std::collections::HashMap;
56 use std::env;
57 use std::fs::File;
58 use std::io::{self, Read, Write};
59 use std::path::PathBuf;
60 use std::process;
61 use std::rc::Rc;
62 use std::sync::mpsc::channel;
63
64 use externalfiles::ExternalHtml;
65 use serialize::Decodable;
66 use serialize::json::{self, Json};
67 use rustc::session::search_paths::SearchPaths;
68 use syntax::errors::emitter::ColorConfig;
69
70 // reexported from `clean` so it can be easily updated with the mod itself
71 pub use clean::SCHEMA_VERSION;
72
73 #[macro_use]
74 pub mod externalfiles;
75
76 pub mod clean;
77 pub mod core;
78 pub mod doctree;
79 pub mod fold;
80 pub mod html {
81     pub mod highlight;
82     pub mod escape;
83     pub mod item_type;
84     pub mod format;
85     pub mod layout;
86     pub mod markdown;
87     pub mod render;
88     pub mod toc;
89 }
90 pub mod markdown;
91 pub mod passes;
92 pub mod plugins;
93 pub mod visit_ast;
94 pub mod test;
95 mod flock;
96
97 type Pass = (&'static str,                                      // name
98              fn(clean::Crate) -> plugins::PluginResult,         // fn
99              &'static str);                                     // description
100
101 const PASSES: &'static [Pass] = &[
102     ("strip-hidden", passes::strip_hidden,
103      "strips all doc(hidden) items from the output"),
104     ("unindent-comments", passes::unindent_comments,
105      "removes excess indentation on comments in order for markdown to like it"),
106     ("collapse-docs", passes::collapse_docs,
107      "concatenates all document attributes into one document attribute"),
108     ("strip-private", passes::strip_private,
109      "strips all private items from a crate which cannot be seen externally"),
110 ];
111
112 const DEFAULT_PASSES: &'static [&'static str] = &[
113     "strip-hidden",
114     "strip-private",
115     "collapse-docs",
116     "unindent-comments",
117 ];
118
119 thread_local!(pub static ANALYSISKEY: Rc<RefCell<Option<core::CrateAnalysis>>> = {
120     Rc::new(RefCell::new(None))
121 });
122
123 struct Output {
124     krate: clean::Crate,
125     json_plugins: Vec<plugins::PluginJson>,
126     passes: Vec<String>,
127 }
128
129 pub fn main() {
130     const STACK_SIZE: usize = 32000000; // 32MB
131     let res = std::thread::Builder::new().stack_size(STACK_SIZE).spawn(move || {
132         let s = env::args().collect::<Vec<_>>();
133         main_args(&s)
134     }).unwrap().join().unwrap_or(101);
135     process::exit(res as i32);
136 }
137
138 pub fn opts() -> Vec<getopts::OptGroup> {
139     use getopts::*;
140     vec!(
141         optflag("h", "help", "show this help message"),
142         optflag("V", "version", "print rustdoc's version"),
143         optflag("v", "verbose", "use verbose output"),
144         optopt("r", "input-format", "the input type of the specified file",
145                "[rust|json]"),
146         optopt("w", "output-format", "the output type to write",
147                "[html|json]"),
148         optopt("o", "output", "where to place the output", "PATH"),
149         optopt("", "crate-name", "specify the name of this crate", "NAME"),
150         optmulti("L", "library-path", "directory to add to crate search path",
151                  "DIR"),
152         optmulti("", "cfg", "pass a --cfg to rustc", ""),
153         optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH"),
154         optmulti("", "plugin-path", "directory to load plugins from", "DIR"),
155         optmulti("", "passes", "list of passes to also run, you might want \
156                                 to pass it multiple times; a value of `list` \
157                                 will print available passes",
158                  "PASSES"),
159         optmulti("", "plugins", "space separated list of plugins to also load",
160                  "PLUGINS"),
161         optflag("", "no-defaults", "don't run the default passes"),
162         optflag("", "test", "run code examples as tests"),
163         optmulti("", "test-args", "arguments to pass to the test runner",
164                  "ARGS"),
165         optopt("", "target", "target triple to document", "TRIPLE"),
166         optmulti("", "markdown-css", "CSS files to include via <link> in a rendered Markdown file",
167                  "FILES"),
168         optmulti("", "html-in-header",
169                  "files to include inline in the <head> section of a rendered Markdown file \
170                  or generated documentation",
171                  "FILES"),
172         optmulti("", "html-before-content",
173                  "files to include inline between <body> and the content of a rendered \
174                  Markdown file or generated documentation",
175                  "FILES"),
176         optmulti("", "html-after-content",
177                  "files to include inline between the content and </body> of a rendered \
178                  Markdown file or generated documentation",
179                  "FILES"),
180         optopt("", "markdown-playground-url",
181                "URL to send code snippets to", "URL"),
182         optflag("", "markdown-no-toc", "don't include table of contents")
183     )
184 }
185
186 pub fn usage(argv0: &str) {
187     println!("{}",
188              getopts::usage(&format!("{} [options] <input>", argv0),
189                             &opts()));
190 }
191
192 pub fn main_args(args: &[String]) -> isize {
193     let matches = match getopts::getopts(&args[1..], &opts()) {
194         Ok(m) => m,
195         Err(err) => {
196             println!("{}", err);
197             return 1;
198         }
199     };
200     if matches.opt_present("h") || matches.opt_present("help") {
201         usage(&args[0]);
202         return 0;
203     } else if matches.opt_present("version") {
204         rustc_driver::version("rustdoc", &matches);
205         return 0;
206     }
207
208     if matches.opt_strs("passes") == ["list"] {
209         println!("Available passes for running rustdoc:");
210         for &(name, _, description) in PASSES {
211             println!("{:>20} - {}", name, description);
212         }
213         println!("\nDefault passes for rustdoc:");
214         for &name in DEFAULT_PASSES {
215             println!("{:>20}", name);
216         }
217         return 0;
218     }
219
220     if matches.free.is_empty() {
221         println!("expected an input file to act on");
222         return 1;
223     } if matches.free.len() > 1 {
224         println!("only one input file may be specified");
225         return 1;
226     }
227     let input = &matches.free[0];
228
229     let mut libs = SearchPaths::new();
230     for s in &matches.opt_strs("L") {
231         libs.add_path(s, ColorConfig::Auto);
232     }
233     let externs = match parse_externs(&matches) {
234         Ok(ex) => ex,
235         Err(err) => {
236             println!("{}", err);
237             return 1;
238         }
239     };
240
241     let test_args = matches.opt_strs("test-args");
242     let test_args: Vec<String> = test_args.iter()
243                                           .flat_map(|s| s.split_whitespace())
244                                           .map(|s| s.to_string())
245                                           .collect();
246
247     let should_test = matches.opt_present("test");
248     let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
249
250     let output = matches.opt_str("o").map(|s| PathBuf::from(&s));
251     let cfgs = matches.opt_strs("cfg");
252
253     let external_html = match ExternalHtml::load(
254             &matches.opt_strs("html-in-header"),
255             &matches.opt_strs("html-before-content"),
256             &matches.opt_strs("html-after-content")) {
257         Some(eh) => eh,
258         None => return 3
259     };
260     let crate_name = matches.opt_str("crate-name");
261
262     match (should_test, markdown_input) {
263         (true, true) => {
264             return markdown::test(input, cfgs, libs, externs, test_args)
265         }
266         (true, false) => {
267             return test::run(input, cfgs, libs, externs, test_args, crate_name)
268         }
269         (false, true) => return markdown::render(input,
270                                                  output.unwrap_or(PathBuf::from("doc")),
271                                                  &matches, &external_html,
272                                                  !matches.opt_present("markdown-no-toc")),
273         (false, false) => {}
274     }
275     let out = match acquire_input(input, externs, &matches) {
276         Ok(out) => out,
277         Err(s) => {
278             println!("input error: {}", s);
279             return 1;
280         }
281     };
282     let Output { krate, json_plugins, passes, } = out;
283     info!("going to format");
284     match matches.opt_str("w").as_ref().map(|s| &**s) {
285         Some("html") | None => {
286             match html::render::run(krate, &external_html,
287                                     output.unwrap_or(PathBuf::from("doc")),
288                                     passes.into_iter().collect()) {
289                 Ok(()) => {}
290                 Err(e) => panic!("failed to generate documentation: {}", e),
291             }
292         }
293         Some("json") => {
294             match json_output(krate, json_plugins,
295                               output.unwrap_or(PathBuf::from("doc.json"))) {
296                 Ok(()) => {}
297                 Err(e) => panic!("failed to write json: {}", e),
298             }
299         }
300         Some(s) => {
301             println!("unknown output format: {}", s);
302             return 1;
303         }
304     }
305
306     return 0;
307 }
308
309 /// Looks inside the command line arguments to extract the relevant input format
310 /// and files and then generates the necessary rustdoc output for formatting.
311 fn acquire_input(input: &str,
312                  externs: core::Externs,
313                  matches: &getopts::Matches) -> Result<Output, String> {
314     match matches.opt_str("r").as_ref().map(|s| &**s) {
315         Some("rust") => Ok(rust_input(input, externs, matches)),
316         Some("json") => json_input(input),
317         Some(s) => Err(format!("unknown input format: {}", s)),
318         None => {
319             if input.ends_with(".json") {
320                 json_input(input)
321             } else {
322                 Ok(rust_input(input, externs, matches))
323             }
324         }
325     }
326 }
327
328 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
329 /// returns a `HashMap` mapping crate names to their paths or else an
330 /// error message.
331 fn parse_externs(matches: &getopts::Matches) -> Result<core::Externs, String> {
332     let mut externs = HashMap::new();
333     for arg in &matches.opt_strs("extern") {
334         let mut parts = arg.splitn(2, '=');
335         let name = match parts.next() {
336             Some(s) => s,
337             None => {
338                 return Err("--extern value must not be empty".to_string());
339             }
340         };
341         let location = match parts.next() {
342             Some(s) => s,
343             None => {
344                 return Err("--extern value must be of the format `foo=bar`".to_string());
345             }
346         };
347         let name = name.to_string();
348         externs.entry(name).or_insert(vec![]).push(location.to_string());
349     }
350     Ok(externs)
351 }
352
353 /// Interprets the input file as a rust source file, passing it through the
354 /// compiler all the way through the analysis passes. The rustdoc output is then
355 /// generated from the cleaned AST of the crate.
356 ///
357 /// This form of input will run all of the plug/cleaning passes
358 fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matches) -> Output {
359     let mut default_passes = !matches.opt_present("no-defaults");
360     let mut passes = matches.opt_strs("passes");
361     let mut plugins = matches.opt_strs("plugins");
362
363     // First, parse the crate and extract all relevant information.
364     let mut paths = SearchPaths::new();
365     for s in &matches.opt_strs("L") {
366         paths.add_path(s, ColorConfig::Auto);
367     }
368     let cfgs = matches.opt_strs("cfg");
369     let triple = matches.opt_str("target");
370
371     let cr = PathBuf::from(cratefile);
372     info!("starting to run rustc");
373
374     let (tx, rx) = channel();
375     rustc_driver::monitor(move || {
376         use rustc::session::config::Input;
377
378         tx.send(core::run_core(paths, cfgs, externs, Input::File(cr),
379                                triple)).unwrap();
380     });
381     let (mut krate, analysis) = rx.recv().unwrap();
382     info!("finished with rustc");
383     let mut analysis = Some(analysis);
384     ANALYSISKEY.with(|s| {
385         *s.borrow_mut() = analysis.take();
386     });
387
388     match matches.opt_str("crate-name") {
389         Some(name) => krate.name = name,
390         None => {}
391     }
392
393     // Process all of the crate attributes, extracting plugin metadata along
394     // with the passes which we are supposed to run.
395     match krate.module.as_ref().unwrap().doc_list() {
396         Some(nested) => {
397             for inner in nested {
398                 match *inner {
399                     clean::Word(ref x)
400                             if "no_default_passes" == *x => {
401                         default_passes = false;
402                     }
403                     clean::NameValue(ref x, ref value)
404                             if "passes" == *x => {
405                         for pass in value.split_whitespace() {
406                             passes.push(pass.to_string());
407                         }
408                     }
409                     clean::NameValue(ref x, ref value)
410                             if "plugins" == *x => {
411                         for p in value.split_whitespace() {
412                             plugins.push(p.to_string());
413                         }
414                     }
415                     _ => {}
416                 }
417             }
418         }
419         None => {}
420     }
421     if default_passes {
422         for name in DEFAULT_PASSES.iter().rev() {
423             passes.insert(0, name.to_string());
424         }
425     }
426
427     // Load all plugins/passes into a PluginManager
428     let path = matches.opt_str("plugin-path")
429                       .unwrap_or("/tmp/rustdoc/plugins".to_string());
430     let mut pm = plugins::PluginManager::new(PathBuf::from(path));
431     for pass in &passes {
432         let plugin = match PASSES.iter()
433                                  .position(|&(p, _, _)| {
434                                      p == *pass
435                                  }) {
436             Some(i) => PASSES[i].1,
437             None => {
438                 error!("unknown pass {}, skipping", *pass);
439                 continue
440             },
441         };
442         pm.add_plugin(plugin);
443     }
444     info!("loading plugins...");
445     for pname in plugins {
446         pm.load_plugin(pname);
447     }
448
449     // Run everything!
450     info!("Executing passes/plugins");
451     let (krate, json) = pm.run_plugins(krate);
452     return Output { krate: krate, json_plugins: json, passes: passes, };
453 }
454
455 /// This input format purely deserializes the json output file. No passes are
456 /// run over the deserialized output.
457 fn json_input(input: &str) -> Result<Output, String> {
458     let mut bytes = Vec::new();
459     match File::open(input).and_then(|mut f| f.read_to_end(&mut bytes)) {
460         Ok(_) => {}
461         Err(e) => return Err(format!("couldn't open {}: {}", input, e)),
462     };
463     match json::from_reader(&mut &bytes[..]) {
464         Err(s) => Err(format!("{:?}", s)),
465         Ok(Json::Object(obj)) => {
466             let mut obj = obj;
467             // Make sure the schema is what we expect
468             match obj.remove(&"schema".to_string()) {
469                 Some(Json::String(version)) => {
470                     if version != SCHEMA_VERSION {
471                         return Err(format!(
472                                 "sorry, but I only understand version {}",
473                                 SCHEMA_VERSION))
474                     }
475                 }
476                 Some(..) => return Err("malformed json".to_string()),
477                 None => return Err("expected a schema version".to_string()),
478             }
479             let krate = match obj.remove(&"crate".to_string()) {
480                 Some(json) => {
481                     let mut d = json::Decoder::new(json);
482                     Decodable::decode(&mut d).unwrap()
483                 }
484                 None => return Err("malformed json".to_string()),
485             };
486             // FIXME: this should read from the "plugins" field, but currently
487             //      Json doesn't implement decodable...
488             let plugin_output = Vec::new();
489             Ok(Output { krate: krate, json_plugins: plugin_output, passes: Vec::new(), })
490         }
491         Ok(..) => {
492             Err("malformed json input: expected an object at the \
493                  top".to_string())
494         }
495     }
496 }
497
498 /// Outputs the crate/plugin json as a giant json blob at the specified
499 /// destination.
500 fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
501                dst: PathBuf) -> io::Result<()> {
502     // {
503     //   "schema": version,
504     //   "crate": { parsed crate ... },
505     //   "plugins": { output of plugins ... }
506     // }
507     let mut json = std::collections::BTreeMap::new();
508     json.insert("schema".to_string(), Json::String(SCHEMA_VERSION.to_string()));
509     let plugins_json = res.into_iter()
510                           .filter_map(|opt| {
511                               match opt {
512                                   None => None,
513                                   Some((string, json)) => {
514                                       Some((string.to_string(), json))
515                                   }
516                               }
517                           }).collect();
518
519     // FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode
520     // straight to the Rust JSON representation.
521     let crate_json_str = format!("{}", json::as_json(&krate));
522     let crate_json = match json::from_str(&crate_json_str) {
523         Ok(j) => j,
524         Err(e) => panic!("Rust generated JSON is invalid: {:?}", e)
525     };
526
527     json.insert("crate".to_string(), crate_json);
528     json.insert("plugins".to_string(), Json::Object(plugins_json));
529
530     let mut file = try!(File::create(&dst));
531     write!(&mut file, "{}", Json::Object(json))
532 }