]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/lib.rs
Removed some unnecessary RefCells from resolve
[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 #![feature(globs, struct_variant, managed_boxes, macro_rules, phase)]
19
20 extern crate arena;
21 extern crate debug;
22 extern crate getopts;
23 extern crate libc;
24 extern crate rustc;
25 extern crate serialize;
26 extern crate syntax;
27 extern crate "test" as testing;
28 extern crate time;
29 #[phase(plugin, link)] extern crate log;
30
31 use std::io;
32 use std::io::{File, MemWriter};
33 use std::collections::HashMap;
34 use std::collections::hashmap::{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 type Output = (clean::Crate, Vec<plugins::PluginJson> );
90
91 pub fn main() {
92     // Why run rustdoc in a separate task? That's a good question!
93     //
94     // We first begin our adventure at the ancient commit of e7c4fb69. In this
95     // commit it was discovered that the stack limit frobbing on windows ended
96     // up causing some syscalls to fail. This was worked around manually in the
97     // relevant location.
98     //
99     // Our journey now continues with #13259 where it was discovered that this
100     // stack limit frobbing has the ability to affect nearly any syscall. Note
101     // that the key idea here is that there is currently no knowledge as to why
102     // this is happening or how to preserve it, fun times!
103     //
104     // Now we continue along to #16275 where it was discovered that --test on
105     // windows didn't work at all! Yet curiously rustdoc worked without --test.
106     // The exact reason that #16275 cropped up is that during the expansion
107     // phase the compiler attempted to open libstd to read out its macros. This
108     // invoked the LLVMRustOpenArchive shim which in turned went to LLVM to go
109     // open a file and read it. Lo and behold this function returned an error!
110     // It was then discovered that when the same fix mentioned in #13259 was
111     // applied, the error went away. The plot thickens!
112     //
113     // Remember that rustdoc works without --test, which raises the question of
114     // how because the --test and non --test paths are almost identical. The
115     // first thing both paths do is parse and expand a crate! It turns out that
116     // the difference is that --test runs on the *main task* while the normal
117     // path runs in subtask. It turns out that running --test in a sub task also
118     // fixes the problem!
119     //
120     // So, in summary, it is unknown why this is necessary, what it is
121     // preventing, or what the actual bug is. In the meantime, this allows
122     // --test to work on windows, which seems good, right? Fun times.
123     let (tx, rx) = channel();
124     spawn(proc() {
125         std::os::set_exit_status(main_args(std::os::args().as_slice()));
126         tx.send(());
127     });
128
129     // If the task failed, set an error'd exit status
130     if rx.recv_opt().is_err() {
131         std::os::set_exit_status(std::rt::DEFAULT_ERROR_CODE);
132     }
133 }
134
135 pub fn opts() -> Vec<getopts::OptGroup> {
136     use getopts::*;
137     vec!(
138         optflag("h", "help", "show this help message"),
139         optflagopt("", "version", "print rustdoc's version", "verbose"),
140         optopt("r", "input-format", "the input type of the specified file",
141                "[rust|json]"),
142         optopt("w", "output-format", "the output type to write",
143                "[html|json]"),
144         optopt("o", "output", "where to place the output", "PATH"),
145         optopt("", "crate-name", "specify the name of this crate", "NAME"),
146         optmulti("L", "library-path", "directory to add to crate search path",
147                  "DIR"),
148         optmulti("", "cfg", "pass a --cfg to rustc", ""),
149         optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH"),
150         optmulti("", "plugin-path", "directory to load plugins from", "DIR"),
151         optmulti("", "passes", "space separated list of passes to also run, a \
152                                 value of `list` will print available passes",
153                  "PASSES"),
154         optmulti("", "plugins", "space separated list of plugins to also load",
155                  "PLUGINS"),
156         optflag("", "no-defaults", "don't run the default passes"),
157         optflag("", "test", "run code examples as tests"),
158         optmulti("", "test-args", "arguments to pass to the test runner",
159                  "ARGS"),
160         optopt("", "target", "target triple to document", "TRIPLE"),
161         optmulti("", "markdown-css", "CSS files to include via <link> in a rendered Markdown file",
162                  "FILES"),
163         optmulti("", "html-in-header",
164                  "files to include inline in the <head> section of a rendered Markdown file \
165                  or generated documentation",
166                  "FILES"),
167         optmulti("", "html-before-content",
168                  "files to include inline between <body> and the content of a rendered \
169                  Markdown file or generated documentation",
170                  "FILES"),
171         optmulti("", "html-after-content",
172                  "files to include inline between the content and </body> of a rendered \
173                  Markdown file or generated documentation",
174                  "FILES"),
175         optopt("", "markdown-playground-url",
176                "URL to send code snippets to", "URL"),
177         optflag("", "markdown-no-toc", "don't include table of contents")
178     )
179 }
180
181 pub fn usage(argv0: &str) {
182     println!("{}",
183              getopts::usage(format!("{} [options] <input>", argv0).as_slice(),
184                             opts().as_slice()));
185 }
186
187 pub fn main_args(args: &[String]) -> int {
188     let matches = match getopts::getopts(args.tail(), opts().as_slice()) {
189         Ok(m) => m,
190         Err(err) => {
191             println!("{}", err);
192             return 1;
193         }
194     };
195     if matches.opt_present("h") || matches.opt_present("help") {
196         usage(args[0].as_slice());
197         return 0;
198     } else if matches.opt_present("version") {
199         match rustc::driver::version("rustdoc", &matches) {
200             Some(err) => {
201                 println!("{}", err);
202                 return 1
203             },
204             None => return 0
205         }
206     }
207
208     if matches.opt_strs("passes").as_slice() == &["list".to_string()] {
209         println!("Available passes for running rustdoc:");
210         for &(name, _, description) in PASSES.iter() {
211             println!("{:>20s} - {}", name, description);
212         }
213         println!("{}", "\nDefault passes for rustdoc:"); // FIXME: #9970
214         for &name in DEFAULT_PASSES.iter() {
215             println!("{:>20s}", name);
216         }
217         return 0;
218     }
219
220     if matches.free.len() == 0 {
221         println!("expected an input file to act on");
222         return 1;
223     } if matches.free.len() > 1 {
224         println!("only one input file may be specified");
225         return 1;
226     }
227     let input = matches.free[0].as_slice();
228
229     let libs = matches.opt_strs("L").iter().map(|s| Path::new(s.as_slice())).collect();
230     let externs = match parse_externs(&matches) {
231         Ok(ex) => ex,
232         Err(err) => {
233             println!("{}", err);
234             return 1;
235         }
236     };
237
238     let test_args = matches.opt_strs("test-args");
239     let test_args: Vec<String> = test_args.iter()
240                                           .flat_map(|s| s.as_slice().words())
241                                           .map(|s| s.to_string())
242                                           .collect();
243
244     let should_test = matches.opt_present("test");
245     let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
246
247     let output = matches.opt_str("o").map(|s| Path::new(s));
248     let cfgs = matches.opt_strs("cfg");
249
250     let external_html = match ExternalHtml::load(
251             matches.opt_strs("html-in-header").as_slice(),
252             matches.opt_strs("html-before-content").as_slice(),
253             matches.opt_strs("html-after-content").as_slice()) {
254         Some(eh) => eh,
255         None => return 3
256     };
257     let crate_name = matches.opt_str("crate-name");
258
259     match (should_test, markdown_input) {
260         (true, true) => {
261             return markdown::test(input, libs, externs, test_args)
262         }
263         (true, false) => {
264             return test::run(input, cfgs, libs, externs, test_args, crate_name)
265         }
266         (false, true) => return markdown::render(input, output.unwrap_or(Path::new("doc")),
267                                                  &matches, &external_html,
268                                                  !matches.opt_present("markdown-no-toc")),
269         (false, false) => {}
270     }
271
272     let (krate, res) = match acquire_input(input, externs, &matches) {
273         Ok(pair) => pair,
274         Err(s) => {
275             println!("input error: {}", s);
276             return 1;
277         }
278     };
279
280     info!("going to format");
281     let started = time::precise_time_ns();
282     match matches.opt_str("w").as_ref().map(|s| s.as_slice()) {
283         Some("html") | None => {
284             match html::render::run(krate, &external_html, output.unwrap_or(Path::new("doc"))) {
285                 Ok(()) => {}
286                 Err(e) => fail!("failed to generate documentation: {}", e),
287             }
288         }
289         Some("json") => {
290             match json_output(krate, res, output.unwrap_or(Path::new("doc.json"))) {
291                 Ok(()) => {}
292                 Err(e) => fail!("failed to write json: {}", e),
293             }
294         }
295         Some(s) => {
296             println!("unknown output format: {}", s);
297             return 1;
298         }
299     }
300     let ended = time::precise_time_ns();
301     info!("Took {:.03f}s", (ended as f64 - started as f64) / 1e9f64);
302
303     return 0;
304 }
305
306 /// Looks inside the command line arguments to extract the relevant input format
307 /// and files and then generates the necessary rustdoc output for formatting.
308 fn acquire_input(input: &str,
309                  externs: core::Externs,
310                  matches: &getopts::Matches) -> Result<Output, String> {
311     match matches.opt_str("r").as_ref().map(|s| s.as_slice()) {
312         Some("rust") => Ok(rust_input(input, externs, matches)),
313         Some("json") => json_input(input),
314         Some(s) => Err(format!("unknown input format: {}", s)),
315         None => {
316             if input.ends_with(".json") {
317                 json_input(input)
318             } else {
319                 Ok(rust_input(input, externs, matches))
320             }
321         }
322     }
323 }
324
325 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
326 /// returns a `HashMap` mapping crate names to their paths or else an
327 /// error message.
328 fn parse_externs(matches: &getopts::Matches) -> Result<core::Externs, String> {
329     let mut externs = HashMap::new();
330     for arg in matches.opt_strs("extern").iter() {
331         let mut parts = arg.as_slice().splitn(1, '=');
332         let name = match parts.next() {
333             Some(s) => s,
334             None => {
335                 return Err("--extern value must not be empty".to_string());
336             }
337         };
338         let location = match parts.next() {
339             Some(s) => s,
340             None => {
341                 return Err("--extern value must be of the format `foo=bar`".to_string());
342             }
343         };
344         let locs = match externs.entry(name.to_string()) {
345             Vacant(entry) => entry.set(Vec::with_capacity(1)),
346             Occupied(entry) => entry.into_mut(),
347         };
348         locs.push(location.to_string());
349     }
350     Ok(externs)
351 }
352
353 /// Interprets the input file as a rust source file, passing it through the
354 /// compiler all the way through the analysis passes. The rustdoc output is then
355 /// generated from the cleaned AST of the crate.
356 ///
357 /// This form of input will run all of the plug/cleaning passes
358 fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matches) -> Output {
359     let mut default_passes = !matches.opt_present("no-defaults");
360     let mut passes = matches.opt_strs("passes");
361     let mut plugins = matches.opt_strs("plugins");
362
363     // First, parse the crate and extract all relevant information.
364     let libs: Vec<Path> = matches.opt_strs("L")
365                                  .iter()
366                                  .map(|s| Path::new(s.as_slice()))
367                                  .collect();
368     let cfgs = matches.opt_strs("cfg");
369     let triple = matches.opt_str("target");
370
371     let cr = Path::new(cratefile);
372     info!("starting to run rustc");
373     let (mut krate, analysis) = std::task::try(proc() {
374         let cr = cr;
375         core::run_core(libs, cfgs, externs, &cr, triple)
376     }).map_err(|boxed_any|format!("{:?}", boxed_any)).unwrap();
377     info!("finished with rustc");
378     analysiskey.replace(Some(analysis));
379
380     match matches.opt_str("crate-name") {
381         Some(name) => krate.name = name,
382         None => {}
383     }
384
385     // Process all of the crate attributes, extracting plugin metadata along
386     // with the passes which we are supposed to run.
387     match krate.module.as_ref().unwrap().doc_list() {
388         Some(nested) => {
389             for inner in nested.iter() {
390                 match *inner {
391                     clean::Word(ref x)
392                             if "no_default_passes" == x.as_slice() => {
393                         default_passes = false;
394                     }
395                     clean::NameValue(ref x, ref value)
396                             if "passes" == x.as_slice() => {
397                         for pass in value.as_slice().words() {
398                             passes.push(pass.to_string());
399                         }
400                     }
401                     clean::NameValue(ref x, ref value)
402                             if "plugins" == x.as_slice() => {
403                         for p in value.as_slice().words() {
404                             plugins.push(p.to_string());
405                         }
406                     }
407                     _ => {}
408                 }
409             }
410         }
411         None => {}
412     }
413     if default_passes {
414         for name in DEFAULT_PASSES.iter().rev() {
415             passes.insert(0, name.to_string());
416         }
417     }
418
419     // Load all plugins/passes into a PluginManager
420     let path = matches.opt_str("plugin-path")
421                       .unwrap_or("/tmp/rustdoc/plugins".to_string());
422     let mut pm = plugins::PluginManager::new(Path::new(path));
423     for pass in passes.iter() {
424         let plugin = match PASSES.iter()
425                                  .position(|&(p, _, _)| {
426                                      p == pass.as_slice()
427                                  }) {
428             Some(i) => PASSES[i].val1(),
429             None => {
430                 error!("unknown pass {}, skipping", *pass);
431                 continue
432             },
433         };
434         pm.add_plugin(plugin);
435     }
436     info!("loading plugins...");
437     for pname in plugins.into_iter() {
438         pm.load_plugin(pname);
439     }
440
441     // Run everything!
442     info!("Executing passes/plugins");
443     return pm.run_plugins(krate);
444 }
445
446 /// This input format purely deserializes the json output file. No passes are
447 /// run over the deserialized output.
448 fn json_input(input: &str) -> Result<Output, String> {
449     let mut input = match File::open(&Path::new(input)) {
450         Ok(f) => f,
451         Err(e) => {
452             return Err(format!("couldn't open {}: {}", input, e))
453         }
454     };
455     match json::from_reader(&mut input) {
456         Err(s) => Err(s.to_string()),
457         Ok(json::Object(obj)) => {
458             let mut obj = obj;
459             // Make sure the schema is what we expect
460             match obj.pop(&"schema".to_string()) {
461                 Some(json::String(version)) => {
462                     if version.as_slice() != SCHEMA_VERSION {
463                         return Err(format!(
464                                 "sorry, but I only understand version {}",
465                                 SCHEMA_VERSION))
466                     }
467                 }
468                 Some(..) => return Err("malformed json".to_string()),
469                 None => return Err("expected a schema version".to_string()),
470             }
471             let krate = match obj.pop(&"crate".to_string()) {
472                 Some(json) => {
473                     let mut d = json::Decoder::new(json);
474                     Decodable::decode(&mut d).unwrap()
475                 }
476                 None => return Err("malformed json".to_string()),
477             };
478             // FIXME: this should read from the "plugins" field, but currently
479             //      Json doesn't implement decodable...
480             let plugin_output = Vec::new();
481             Ok((krate, plugin_output))
482         }
483         Ok(..) => {
484             Err("malformed json input: expected an object at the \
485                  top".to_string())
486         }
487     }
488 }
489
490 /// Outputs the crate/plugin json as a giant json blob at the specified
491 /// destination.
492 fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
493                dst: Path) -> io::IoResult<()> {
494     // {
495     //   "schema": version,
496     //   "crate": { parsed crate ... },
497     //   "plugins": { output of plugins ... }
498     // }
499     let mut json = std::collections::TreeMap::new();
500     json.insert("schema".to_string(), json::String(SCHEMA_VERSION.to_string()));
501     let plugins_json = res.into_iter()
502                           .filter_map(|opt| {
503                               match opt {
504                                   None => None,
505                                   Some((string, json)) => {
506                                       Some((string.to_string(), json))
507                                   }
508                               }
509                           }).collect();
510
511     // FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode
512     // straight to the Rust JSON representation.
513     let crate_json_str = {
514         let mut w = MemWriter::new();
515         {
516             let mut encoder = json::Encoder::new(&mut w as &mut io::Writer);
517             krate.encode(&mut encoder).unwrap();
518         }
519         String::from_utf8(w.unwrap()).unwrap()
520     };
521     let crate_json = match json::from_str(crate_json_str.as_slice()) {
522         Ok(j) => j,
523         Err(e) => fail!("Rust generated JSON is invalid: {:?}", e)
524     };
525
526     json.insert("crate".to_string(), crate_json);
527     json.insert("plugins".to_string(), json::Object(plugins_json));
528
529     let mut file = try!(File::create(&dst));
530     json::Object(json).to_writer(&mut file)
531 }