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