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