]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/lib.rs
069ab37a2ad013e6df688f0896f0a09d4a9dbc41
[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, ~[plugins::PluginJson]);
84
85 pub fn main() {
86     std::os::set_exit_status(main_args(std::os::args()));
87 }
88
89 pub fn opts() -> ~[getopts::OptGroup] {
90     use getopts::*;
91     ~[
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!("{}", getopts::usage(format!("{} [options] <input>", argv0), opts()));
130 }
131
132 pub fn main_args(args: &[~str]) -> int {
133     let matches = match getopts::getopts(args.tail(), opts()) {
134         Ok(m) => m,
135         Err(err) => {
136             println!("{}", err.to_err_msg());
137             return 1;
138         }
139     };
140     if matches.opt_present("h") || matches.opt_present("help") {
141         usage(args[0]);
142         return 0;
143     } else if matches.opt_present("version") {
144         rustc::version(args[0]);
145         return 0;
146     }
147
148     if matches.free.len() == 0 {
149         println!("expected an input file to act on");
150         return 1;
151     } if matches.free.len() > 1 {
152         println!("only one input file may be specified");
153         return 1;
154     }
155     let input = matches.free[0].as_slice();
156
157     let libs = matches.opt_strs("L").map(|s| Path::new(s.as_slice())).move_iter().collect();
158
159     let test_args = matches.opt_strs("test-args");
160     let test_args = test_args.iter().flat_map(|s| s.words()).map(|s| s.to_owned()).to_owned_vec();
161
162     let should_test = matches.opt_present("test");
163     let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
164
165     let output = matches.opt_str("o").map(|s| Path::new(s));
166
167     match (should_test, markdown_input) {
168         (true, true) => return markdown::test(input, libs, test_args),
169         (true, false) => return test::run(input, libs, test_args),
170
171         (false, true) => return markdown::render(input, output.unwrap_or(Path::new("doc")),
172                                                  &matches),
173         (false, false) => {}
174     }
175
176     if matches.opt_strs("passes") == ~[~"list"] {
177         println!("Available passes for running rustdoc:");
178         for &(name, _, description) in PASSES.iter() {
179             println!("{:>20s} - {}", name, description);
180         }
181         println!("{}", "\nDefault passes for rustdoc:"); // FIXME: #9970
182         for &name in DEFAULT_PASSES.iter() {
183             println!("{:>20s}", name);
184         }
185         return 0;
186     }
187
188     let (krate, res) = match acquire_input(input, &matches) {
189         Ok(pair) => pair,
190         Err(s) => {
191             println!("input error: {}", s);
192             return 1;
193         }
194     };
195
196     info!("going to format");
197     let started = time::precise_time_ns();
198     match matches.opt_str("w").as_ref().map(|s| s.as_slice()) {
199         Some("html") | None => {
200             match html::render::run(krate, output.unwrap_or(Path::new("doc"))) {
201                 Ok(()) => {}
202                 Err(e) => fail!("failed to generate documentation: {}", e),
203             }
204         }
205         Some("json") => {
206             match json_output(krate, res, output.unwrap_or(Path::new("doc.json"))) {
207                 Ok(()) => {}
208                 Err(e) => fail!("failed to write json: {}", e),
209             }
210         }
211         Some(s) => {
212             println!("unknown output format: {}", s);
213             return 1;
214         }
215     }
216     let ended = time::precise_time_ns();
217     info!("Took {:.03f}s", (ended as f64 - started as f64) / 1e9f64);
218
219     return 0;
220 }
221
222 /// Looks inside the command line arguments to extract the relevant input format
223 /// and files and then generates the necessary rustdoc output for formatting.
224 fn acquire_input(input: &str,
225                  matches: &getopts::Matches) -> Result<Output, ~str> {
226     match matches.opt_str("r").as_ref().map(|s| s.as_slice()) {
227         Some("rust") => Ok(rust_input(input, matches)),
228         Some("json") => json_input(input),
229         Some(s) => Err("unknown input format: " + s),
230         None => {
231             if input.ends_with(".json") {
232                 json_input(input)
233             } else {
234                 Ok(rust_input(input, matches))
235             }
236         }
237     }
238 }
239
240 /// Interprets the input file as a rust source file, passing it through the
241 /// compiler all the way through the analysis passes. The rustdoc output is then
242 /// generated from the cleaned AST of the crate.
243 ///
244 /// This form of input will run all of the plug/cleaning passes
245 fn rust_input(cratefile: &str, matches: &getopts::Matches) -> Output {
246     let mut default_passes = !matches.opt_present("no-defaults");
247     let mut passes = matches.opt_strs("passes");
248     let mut plugins = matches.opt_strs("plugins");
249
250     // First, parse the crate and extract all relevant information.
251     let libs = matches.opt_strs("L").map(|s| Path::new(s.as_slice()));
252     let cfgs = matches.opt_strs("cfg");
253     let cr = Path::new(cratefile);
254     info!("starting to run rustc");
255     let (krate, analysis) = std::task::try(proc() {
256         let cr = cr;
257         core::run_core(libs.move_iter().collect(), cfgs, &cr)
258     }).unwrap();
259     info!("finished with rustc");
260     local_data::set(analysiskey, analysis);
261
262     // Process all of the crate attributes, extracting plugin metadata along
263     // with the passes which we are supposed to run.
264     match krate.module.get_ref().doc_list() {
265         Some(nested) => {
266             for inner in nested.iter() {
267                 match *inner {
268                     clean::Word(ref x) if "no_default_passes" == *x => {
269                         default_passes = false;
270                     }
271                     clean::NameValue(ref x, ref value) if "passes" == *x => {
272                         for pass in value.words() {
273                             passes.push(pass.to_owned());
274                         }
275                     }
276                     clean::NameValue(ref x, ref value) if "plugins" == *x => {
277                         for p in value.words() {
278                             plugins.push(p.to_owned());
279                         }
280                     }
281                     _ => {}
282                 }
283             }
284         }
285         None => {}
286     }
287     if default_passes {
288         for name in DEFAULT_PASSES.rev_iter() {
289             passes.unshift(name.to_owned());
290         }
291     }
292
293     // Load all plugins/passes into a PluginManager
294     let path = matches.opt_str("plugin-path").unwrap_or(~"/tmp/rustdoc/plugins");
295     let mut pm = plugins::PluginManager::new(Path::new(path));
296     for pass in passes.iter() {
297         let plugin = match PASSES.iter().position(|&(p, _, _)| p == *pass) {
298             Some(i) => PASSES[i].val1(),
299             None => {
300                 error!("unknown pass {}, skipping", *pass);
301                 continue
302             },
303         };
304         pm.add_plugin(plugin);
305     }
306     info!("loading plugins...");
307     for pname in plugins.move_iter() {
308         pm.load_plugin(pname);
309     }
310
311     // Run everything!
312     info!("Executing passes/plugins");
313     return pm.run_plugins(krate);
314 }
315
316 /// This input format purely deserializes the json output file. No passes are
317 /// run over the deserialized output.
318 fn json_input(input: &str) -> Result<Output, ~str> {
319     let mut input = match File::open(&Path::new(input)) {
320         Ok(f) => f,
321         Err(e) => return Err(format!("couldn't open {}: {}", input, e)),
322     };
323     match json::from_reader(&mut input) {
324         Err(s) => Err(s.to_str()),
325         Ok(json::Object(obj)) => {
326             let mut obj = obj;
327             // Make sure the schema is what we expect
328             match obj.pop(&~"schema") {
329                 Some(json::String(version)) => {
330                     if version.as_slice() != SCHEMA_VERSION {
331                         return Err(format!("sorry, but I only understand \
332                                             version {}", SCHEMA_VERSION))
333                     }
334                 }
335                 Some(..) => return Err(~"malformed json"),
336                 None => return Err(~"expected a schema version"),
337             }
338             let krate = match obj.pop(&~"crate") {
339                 Some(json) => {
340                     let mut d = json::Decoder::new(json);
341                     Decodable::decode(&mut d)
342                 }
343                 None => return Err(~"malformed json"),
344             };
345             // FIXME: this should read from the "plugins" field, but currently
346             //      Json doesn't implement decodable...
347             let plugin_output = ~[];
348             Ok((krate, plugin_output))
349         }
350         Ok(..) => Err(~"malformed json input: expected an object at the top"),
351     }
352 }
353
354 /// Outputs the crate/plugin json as a giant json blob at the specified
355 /// destination.
356 fn json_output(krate: clean::Crate, res: ~[plugins::PluginJson],
357                dst: Path) -> io::IoResult<()> {
358     // {
359     //   "schema": version,
360     //   "crate": { parsed crate ... },
361     //   "plugins": { output of plugins ... }
362     // }
363     let mut json = ~collections::TreeMap::new();
364     json.insert(~"schema", json::String(SCHEMA_VERSION.to_owned()));
365     let plugins_json = ~res.move_iter().filter_map(|opt| opt).collect();
366
367     // FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode
368     // straight to the Rust JSON representation.
369     let crate_json_str = {
370         let mut w = MemWriter::new();
371         {
372             let mut encoder = json::Encoder::new(&mut w as &mut io::Writer);
373             krate.encode(&mut encoder);
374         }
375         str::from_utf8_owned(w.unwrap()).unwrap()
376     };
377     let crate_json = match json::from_str(crate_json_str) {
378         Ok(j) => j,
379         Err(e) => fail!("Rust generated JSON is invalid: {:?}", e)
380     };
381
382     json.insert(~"crate", crate_json);
383     json.insert(~"plugins", json::Object(plugins_json));
384
385     let mut file = try!(File::create(&dst));
386     try!(json::Object(json).to_writer(&mut file));
387     Ok(())
388 }