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