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