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