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