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