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