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