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