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