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