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