]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/lib.rs
d16802a23145f0acb1442d093d7ede05013c7d6b
[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_id = "rustdoc#0.10-pre"]
12 #![desc = "rustdoc, the Rust documentation extractor"]
13 #![license = "MIT/ASL2"]
14 #![crate_type = "dylib"]
15 #![crate_type = "rlib"]
16
17 #![feature(globs, struct_variant, managed_boxes, macro_rules, phase)]
18
19 extern crate syntax;
20 extern crate rustc;
21 extern crate serialize;
22 extern crate sync;
23 extern crate getopts;
24 extern crate collections;
25 extern crate testing = "test";
26 extern crate time;
27 #[phase(syntax, link)]
28 extern crate log;
29
30 use std::local_data;
31 use std::io;
32 use std::io::{File, MemWriter};
33 use std::str;
34 use serialize::{json, Decodable, Encodable};
35
36 pub mod clean;
37 pub mod core;
38 pub mod doctree;
39 pub mod fold;
40 pub mod html {
41     pub mod highlight;
42     pub mod escape;
43     pub mod format;
44     pub mod layout;
45     pub mod markdown;
46     pub mod render;
47     pub mod toc;
48 }
49 pub mod markdown;
50 pub mod passes;
51 pub mod plugins;
52 pub mod visit_ast;
53 pub mod test;
54 mod flock;
55
56 pub static SCHEMA_VERSION: &'static str = "0.8.1";
57
58 type Pass = (&'static str,                                      // name
59              fn(clean::Crate) -> plugins::PluginResult,         // fn
60              &'static str);                                     // description
61
62 static PASSES: &'static [Pass] = &[
63     ("strip-hidden", passes::strip_hidden,
64      "strips all doc(hidden) items from the output"),
65     ("unindent-comments", passes::unindent_comments,
66      "removes excess indentation on comments in order for markdown to like it"),
67     ("collapse-docs", passes::collapse_docs,
68      "concatenates all document attributes into one document attribute"),
69     ("strip-private", passes::strip_private,
70      "strips all private items from a crate which cannot be seen externally"),
71 ];
72
73 static DEFAULT_PASSES: &'static [&'static str] = &[
74     "strip-hidden",
75     "strip-private",
76     "collapse-docs",
77     "unindent-comments",
78 ];
79
80 local_data_key!(pub ctxtkey: @core::DocContext)
81 local_data_key!(pub analysiskey: core::CrateAnalysis)
82
83 type Output = (clean::Crate, Vec<plugins::PluginJson> );
84
85 pub fn main() {
86     std::os::set_exit_status(main_args(std::os::args()));
87 }
88
89 pub fn opts() -> Vec<getopts::OptGroup> {
90     use getopts::*;
91     vec!(
92         optflag("h", "help", "show this help message"),
93         optflag("", "version", "print rustdoc's version"),
94         optopt("r", "input-format", "the input type of the specified file",
95                "[rust|json]"),
96         optopt("w", "output-format", "the output type to write",
97                "[html|json]"),
98         optopt("o", "output", "where to place the output", "PATH"),
99         optmulti("L", "library-path", "directory to add to crate search path",
100                  "DIR"),
101         optmulti("", "cfg", "pass a --cfg to rustc", ""),
102         optmulti("", "plugin-path", "directory to load plugins from", "DIR"),
103         optmulti("", "passes", "space separated list of passes to also run, a \
104                                 value of `list` will print available passes",
105                  "PASSES"),
106         optmulti("", "plugins", "space separated list of plugins to also load",
107                  "PLUGINS"),
108         optflag("", "no-defaults", "don't run the default passes"),
109         optflag("", "test", "run code examples as tests"),
110         optmulti("", "test-args", "arguments to pass to the test runner",
111                  "ARGS"),
112         optmulti("", "markdown-css", "CSS files to include via <link> in a rendered Markdown file",
113                  "FILES"),
114         optmulti("", "markdown-in-header",
115                  "files to include inline in the <head> section of a rendered Markdown file",
116                  "FILES"),
117         optmulti("", "markdown-before-content",
118                  "files to include inline between <body> and the content of a rendered \
119                  Markdown file",
120                  "FILES"),
121         optmulti("", "markdown-after-content",
122                  "files to include inline between the content and </body> of a rendered \
123                  Markdown file",
124                  "FILES")
125     )
126 }
127
128 pub fn usage(argv0: &str) {
129     println!("{}",
130              getopts::usage(format!("{} [options] <input>", argv0),
131                             opts().as_slice()));
132 }
133
134 pub fn main_args(args: &[~str]) -> int {
135     let matches = match getopts::getopts(args.tail(), opts().as_slice()) {
136         Ok(m) => m,
137         Err(err) => {
138             println!("{}", err.to_err_msg());
139             return 1;
140         }
141     };
142     if matches.opt_present("h") || matches.opt_present("help") {
143         usage(args[0]);
144         return 0;
145     } else if matches.opt_present("version") {
146         rustc::version(args[0]);
147         return 0;
148     }
149
150     if matches.free.len() == 0 {
151         println!("expected an input file to act on");
152         return 1;
153     } if matches.free.len() > 1 {
154         println!("only one input file may be specified");
155         return 1;
156     }
157     let input = matches.free.get(0).as_slice();
158
159     let libs = matches.opt_strs("L").iter().map(|s| Path::new(s.as_slice())).collect();
160
161     let test_args = matches.opt_strs("test-args");
162     let test_args: Vec<~str> = test_args.iter()
163                                         .flat_map(|s| s.words())
164                                         .map(|s| s.to_owned())
165                                         .collect();
166
167     let should_test = matches.opt_present("test");
168     let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
169
170     let output = matches.opt_str("o").map(|s| Path::new(s));
171
172     match (should_test, markdown_input) {
173         (true, true) => {
174             return markdown::test(input,
175                                   libs,
176                                   test_args.move_iter().collect())
177         }
178         (true, false) => return test::run(input, libs, test_args),
179
180         (false, true) => return markdown::render(input, output.unwrap_or(Path::new("doc")),
181                                                  &matches),
182         (false, false) => {}
183     }
184
185     if matches.opt_strs("passes").as_slice() == &[~"list"] {
186         println!("Available passes for running rustdoc:");
187         for &(name, _, description) in PASSES.iter() {
188             println!("{:>20s} - {}", name, description);
189         }
190         println!("{}", "\nDefault passes for rustdoc:"); // FIXME: #9970
191         for &name in DEFAULT_PASSES.iter() {
192             println!("{:>20s}", name);
193         }
194         return 0;
195     }
196
197     let (krate, res) = match acquire_input(input, &matches) {
198         Ok(pair) => pair,
199         Err(s) => {
200             println!("input error: {}", s);
201             return 1;
202         }
203     };
204
205     info!("going to format");
206     let started = time::precise_time_ns();
207     match matches.opt_str("w").as_ref().map(|s| s.as_slice()) {
208         Some("html") | None => {
209             match html::render::run(krate, output.unwrap_or(Path::new("doc"))) {
210                 Ok(()) => {}
211                 Err(e) => fail!("failed to generate documentation: {}", e),
212             }
213         }
214         Some("json") => {
215             match json_output(krate, res, output.unwrap_or(Path::new("doc.json"))) {
216                 Ok(()) => {}
217                 Err(e) => fail!("failed to write json: {}", e),
218             }
219         }
220         Some(s) => {
221             println!("unknown output format: {}", s);
222             return 1;
223         }
224     }
225     let ended = time::precise_time_ns();
226     info!("Took {:.03f}s", (ended as f64 - started as f64) / 1e9f64);
227
228     return 0;
229 }
230
231 /// Looks inside the command line arguments to extract the relevant input format
232 /// and files and then generates the necessary rustdoc output for formatting.
233 fn acquire_input(input: &str,
234                  matches: &getopts::Matches) -> Result<Output, ~str> {
235     match matches.opt_str("r").as_ref().map(|s| s.as_slice()) {
236         Some("rust") => Ok(rust_input(input, matches)),
237         Some("json") => json_input(input),
238         Some(s) => Err("unknown input format: " + s),
239         None => {
240             if input.ends_with(".json") {
241                 json_input(input)
242             } else {
243                 Ok(rust_input(input, matches))
244             }
245         }
246     }
247 }
248
249 /// Interprets the input file as a rust source file, passing it through the
250 /// compiler all the way through the analysis passes. The rustdoc output is then
251 /// generated from the cleaned AST of the crate.
252 ///
253 /// This form of input will run all of the plug/cleaning passes
254 fn rust_input(cratefile: &str, matches: &getopts::Matches) -> Output {
255     let mut default_passes = !matches.opt_present("no-defaults");
256     let mut passes = matches.opt_strs("passes");
257     let mut plugins = matches.opt_strs("plugins");
258
259     // First, parse the crate and extract all relevant information.
260     let libs: Vec<Path> = matches.opt_strs("L")
261                                  .iter()
262                                  .map(|s| Path::new(s.as_slice()))
263                                  .collect();
264     let cfgs = matches.opt_strs("cfg");
265     let cr = Path::new(cratefile);
266     info!("starting to run rustc");
267     let (krate, analysis) = std::task::try(proc() {
268         let cr = cr;
269         core::run_core(libs.move_iter().collect(),
270                        cfgs.move_iter().collect(),
271                        &cr)
272     }).unwrap();
273     info!("finished with rustc");
274     local_data::set(analysiskey, analysis);
275
276     // Process all of the crate attributes, extracting plugin metadata along
277     // with the passes which we are supposed to run.
278     match krate.module.get_ref().doc_list() {
279         Some(nested) => {
280             for inner in nested.iter() {
281                 match *inner {
282                     clean::Word(ref x) if "no_default_passes" == *x => {
283                         default_passes = false;
284                     }
285                     clean::NameValue(ref x, ref value) if "passes" == *x => {
286                         for pass in value.words() {
287                             passes.push(pass.to_owned());
288                         }
289                     }
290                     clean::NameValue(ref x, ref value) if "plugins" == *x => {
291                         for p in value.words() {
292                             plugins.push(p.to_owned());
293                         }
294                     }
295                     _ => {}
296                 }
297             }
298         }
299         None => {}
300     }
301     if default_passes {
302         for name in DEFAULT_PASSES.rev_iter() {
303             passes.unshift(name.to_owned());
304         }
305     }
306
307     // Load all plugins/passes into a PluginManager
308     let path = matches.opt_str("plugin-path").unwrap_or(~"/tmp/rustdoc/plugins");
309     let mut pm = plugins::PluginManager::new(Path::new(path));
310     for pass in passes.iter() {
311         let plugin = match PASSES.iter().position(|&(p, _, _)| p == *pass) {
312             Some(i) => PASSES[i].val1(),
313             None => {
314                 error!("unknown pass {}, skipping", *pass);
315                 continue
316             },
317         };
318         pm.add_plugin(plugin);
319     }
320     info!("loading plugins...");
321     for pname in plugins.move_iter() {
322         pm.load_plugin(pname);
323     }
324
325     // Run everything!
326     info!("Executing passes/plugins");
327     return pm.run_plugins(krate);
328 }
329
330 /// This input format purely deserializes the json output file. No passes are
331 /// run over the deserialized output.
332 fn json_input(input: &str) -> Result<Output, ~str> {
333     let mut input = match File::open(&Path::new(input)) {
334         Ok(f) => f,
335         Err(e) => return Err(format!("couldn't open {}: {}", input, e)),
336     };
337     match json::from_reader(&mut input) {
338         Err(s) => Err(s.to_str()),
339         Ok(json::Object(obj)) => {
340             let mut obj = obj;
341             // Make sure the schema is what we expect
342             match obj.pop(&~"schema") {
343                 Some(json::String(version)) => {
344                     if version.as_slice() != SCHEMA_VERSION {
345                         return Err(format!("sorry, but I only understand \
346                                             version {}", SCHEMA_VERSION))
347                     }
348                 }
349                 Some(..) => return Err(~"malformed json"),
350                 None => return Err(~"expected a schema version"),
351             }
352             let krate = match obj.pop(&~"crate") {
353                 Some(json) => {
354                     let mut d = json::Decoder::new(json);
355                     Decodable::decode(&mut d).unwrap()
356                 }
357                 None => return Err(~"malformed json"),
358             };
359             // FIXME: this should read from the "plugins" field, but currently
360             //      Json doesn't implement decodable...
361             let plugin_output = Vec::new();
362             Ok((krate, plugin_output))
363         }
364         Ok(..) => Err(~"malformed json input: expected an object at the top"),
365     }
366 }
367
368 /// Outputs the crate/plugin json as a giant json blob at the specified
369 /// destination.
370 fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
371                dst: Path) -> io::IoResult<()> {
372     // {
373     //   "schema": version,
374     //   "crate": { parsed crate ... },
375     //   "plugins": { output of plugins ... }
376     // }
377     let mut json = ~collections::TreeMap::new();
378     json.insert(~"schema", json::String(SCHEMA_VERSION.to_owned()));
379     let plugins_json = ~res.move_iter().filter_map(|opt| opt).collect();
380
381     // FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode
382     // straight to the Rust JSON representation.
383     let crate_json_str = {
384         let mut w = MemWriter::new();
385         {
386             let mut encoder = json::Encoder::new(&mut w as &mut io::Writer);
387             krate.encode(&mut encoder).unwrap();
388         }
389         str::from_utf8_owned(w.unwrap()).unwrap()
390     };
391     let crate_json = match json::from_str(crate_json_str) {
392         Ok(j) => j,
393         Err(e) => fail!("Rust generated JSON is invalid: {:?}", e)
394     };
395
396     json.insert(~"crate", crate_json);
397     json.insert(~"plugins", json::Object(plugins_json));
398
399     let mut file = try!(File::create(&dst));
400     try!(json::Object(json).to_writer(&mut file));
401     Ok(())
402 }