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