]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/lib.rs
Stabilize `std::convert` and related code
[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(set_stdio)]
29 #![feature(libc)]
30 #![feature(rustc_private)]
31 #![feature(staged_api)]
32 #![feature(std_misc)]
33 #![feature(test)]
34 #![feature(unicode)]
35 #![feature(str_words)]
36 #![feature(file_path)]
37 #![feature(path_ext)]
38 #![feature(path_relative_from)]
39 #![feature(slice_patterns)]
40
41 extern crate arena;
42 extern crate getopts;
43 extern crate libc;
44 extern crate rustc;
45 extern crate rustc_trans;
46 extern crate rustc_driver;
47 extern crate rustc_resolve;
48 extern crate rustc_lint;
49 extern crate rustc_back;
50 extern crate serialize;
51 extern crate syntax;
52 extern crate test as testing;
53 extern crate unicode;
54 #[macro_use] extern crate log;
55
56 extern crate serialize as rustc_serialize; // used by deriving
57
58 use std::cell::RefCell;
59 use std::collections::HashMap;
60 use std::env;
61 use std::fs::File;
62 use std::io::{self, Read, Write};
63 use std::path::PathBuf;
64 use std::rc::Rc;
65 use std::sync::mpsc::channel;
66
67 use externalfiles::ExternalHtml;
68 use serialize::Decodable;
69 use serialize::json::{self, Json};
70 use rustc::session::search_paths::SearchPaths;
71
72 // reexported from `clean` so it can be easily updated with the mod itself
73 pub use clean::SCHEMA_VERSION;
74
75 #[macro_use]
76 pub mod externalfiles;
77
78 pub mod clean;
79 pub mod core;
80 pub mod doctree;
81 pub mod fold;
82 pub mod html {
83     pub mod highlight;
84     pub mod escape;
85     pub mod item_type;
86     pub mod format;
87     pub mod layout;
88     pub mod markdown;
89     pub mod render;
90     pub mod toc;
91 }
92 pub mod markdown;
93 pub mod passes;
94 pub mod plugins;
95 pub mod stability_summary;
96 pub mod visit_ast;
97 pub mod test;
98 mod flock;
99
100 type Pass = (&'static str,                                      // name
101              fn(clean::Crate) -> plugins::PluginResult,         // fn
102              &'static str);                                     // description
103
104 const PASSES: &'static [Pass] = &[
105     ("strip-hidden", passes::strip_hidden,
106      "strips all doc(hidden) items from the output"),
107     ("unindent-comments", passes::unindent_comments,
108      "removes excess indentation on comments in order for markdown to like it"),
109     ("collapse-docs", passes::collapse_docs,
110      "concatenates all document attributes into one document attribute"),
111     ("strip-private", passes::strip_private,
112      "strips all private items from a crate which cannot be seen externally"),
113 ];
114
115 const DEFAULT_PASSES: &'static [&'static str] = &[
116     "strip-hidden",
117     "strip-private",
118     "collapse-docs",
119     "unindent-comments",
120 ];
121
122 thread_local!(pub static ANALYSISKEY: Rc<RefCell<Option<core::CrateAnalysis>>> = {
123     Rc::new(RefCell::new(None))
124 });
125
126 struct Output {
127     krate: clean::Crate,
128     json_plugins: Vec<plugins::PluginJson>,
129     passes: Vec<String>,
130 }
131
132 pub fn main() {
133     const STACK_SIZE: usize = 32000000; // 32MB
134     let res = std::thread::Builder::new().stack_size(STACK_SIZE).scoped(move || {
135         let s = env::args().collect::<Vec<_>>();
136         main_args(&s)
137     }).unwrap().join();
138     env::set_exit_status(res as i32);
139 }
140
141 pub fn opts() -> Vec<getopts::OptGroup> {
142     use getopts::*;
143     vec!(
144         optflag("h", "help", "show this help message"),
145         optflag("V", "version", "print rustdoc's version"),
146         optflag("v", "verbose", "use verbose output"),
147         optopt("r", "input-format", "the input type of the specified file",
148                "[rust|json]"),
149         optopt("w", "output-format", "the output type to write",
150                "[html|json]"),
151         optopt("o", "output", "where to place the output", "PATH"),
152         optopt("", "crate-name", "specify the name of this crate", "NAME"),
153         optmulti("L", "library-path", "directory to add to crate search path",
154                  "DIR"),
155         optmulti("", "cfg", "pass a --cfg to rustc", ""),
156         optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH"),
157         optmulti("", "plugin-path", "directory to load plugins from", "DIR"),
158         optmulti("", "passes", "space separated list of passes to also run, a \
159                                 value of `list` 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.tail(), &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:"); // FIXME: #9970
216         for &name in DEFAULT_PASSES {
217             println!("{:>20}", name);
218         }
219         return 0;
220     }
221
222     if matches.free.len() == 0 {
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);
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.words())
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, 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
278     let out = match acquire_input(input, externs, &matches) {
279         Ok(out) => out,
280         Err(s) => {
281             println!("input error: {}", s);
282             return 1;
283         }
284     };
285     let Output { krate, json_plugins, passes, } = out;
286     info!("going to format");
287     match matches.opt_str("w").as_ref().map(|s| &**s) {
288         Some("html") | None => {
289             match html::render::run(krate, &external_html,
290                                     output.unwrap_or(PathBuf::from("doc")),
291                                     passes.into_iter().collect()) {
292                 Ok(()) => {}
293                 Err(e) => panic!("failed to generate documentation: {}", e),
294             }
295         }
296         Some("json") => {
297             match json_output(krate, json_plugins,
298                               output.unwrap_or(PathBuf::from("doc.json"))) {
299                 Ok(()) => {}
300                 Err(e) => panic!("failed to write json: {}", e),
301             }
302         }
303         Some(s) => {
304             println!("unknown output format: {}", s);
305             return 1;
306         }
307     }
308
309     return 0;
310 }
311
312 /// Looks inside the command line arguments to extract the relevant input format
313 /// and files and then generates the necessary rustdoc output for formatting.
314 fn acquire_input(input: &str,
315                  externs: core::Externs,
316                  matches: &getopts::Matches) -> Result<Output, String> {
317     match matches.opt_str("r").as_ref().map(|s| &**s) {
318         Some("rust") => Ok(rust_input(input, externs, matches)),
319         Some("json") => json_input(input),
320         Some(s) => Err(format!("unknown input format: {}", s)),
321         None => {
322             if input.ends_with(".json") {
323                 json_input(input)
324             } else {
325                 Ok(rust_input(input, externs, matches))
326             }
327         }
328     }
329 }
330
331 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
332 /// returns a `HashMap` mapping crate names to their paths or else an
333 /// error message.
334 fn parse_externs(matches: &getopts::Matches) -> Result<core::Externs, String> {
335     let mut externs = HashMap::new();
336     for arg in &matches.opt_strs("extern") {
337         let mut parts = arg.splitn(1, '=');
338         let name = match parts.next() {
339             Some(s) => s,
340             None => {
341                 return Err("--extern value must not be empty".to_string());
342             }
343         };
344         let location = match parts.next() {
345             Some(s) => s,
346             None => {
347                 return Err("--extern value must be of the format `foo=bar`".to_string());
348             }
349         };
350         let name = name.to_string();
351         externs.entry(name).or_insert(vec![]).push(location.to_string());
352     }
353     Ok(externs)
354 }
355
356 /// Interprets the input file as a rust source file, passing it through the
357 /// compiler all the way through the analysis passes. The rustdoc output is then
358 /// generated from the cleaned AST of the crate.
359 ///
360 /// This form of input will run all of the plug/cleaning passes
361 #[allow(deprecated)] // for old Path in plugin manager
362 fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matches) -> Output {
363     let mut default_passes = !matches.opt_present("no-defaults");
364     let mut passes = matches.opt_strs("passes");
365     let mut plugins = matches.opt_strs("plugins");
366
367     // First, parse the crate and extract all relevant information.
368     let mut paths = SearchPaths::new();
369     for s in &matches.opt_strs("L") {
370         paths.add_path(s);
371     }
372     let cfgs = matches.opt_strs("cfg");
373     let triple = matches.opt_str("target");
374
375     let cr = PathBuf::from(cratefile);
376     info!("starting to run rustc");
377
378     let (tx, rx) = channel();
379     std::thread::spawn(move || {
380         use rustc::session::config::Input;
381
382         tx.send(core::run_core(paths, cfgs, externs, Input::File(cr),
383                                triple)).unwrap();
384     }).join().map_err(|_| "rustc failed").unwrap();
385     let (mut krate, analysis) = rx.recv().unwrap();
386     info!("finished with rustc");
387     let mut analysis = Some(analysis);
388     ANALYSISKEY.with(|s| {
389         *s.borrow_mut() = analysis.take();
390     });
391
392     match matches.opt_str("crate-name") {
393         Some(name) => krate.name = name,
394         None => {}
395     }
396
397     // Process all of the crate attributes, extracting plugin metadata along
398     // with the passes which we are supposed to run.
399     match krate.module.as_ref().unwrap().doc_list() {
400         Some(nested) => {
401             for inner in nested {
402                 match *inner {
403                     clean::Word(ref x)
404                             if "no_default_passes" == *x => {
405                         default_passes = false;
406                     }
407                     clean::NameValue(ref x, ref value)
408                             if "passes" == *x => {
409                         for pass in value.words() {
410                             passes.push(pass.to_string());
411                         }
412                     }
413                     clean::NameValue(ref x, ref value)
414                             if "plugins" == *x => {
415                         for p in value.words() {
416                             plugins.push(p.to_string());
417                         }
418                     }
419                     _ => {}
420                 }
421             }
422         }
423         None => {}
424     }
425     if default_passes {
426         for name in DEFAULT_PASSES.iter().rev() {
427             passes.insert(0, name.to_string());
428         }
429     }
430
431     // Load all plugins/passes into a PluginManager
432     let path = matches.opt_str("plugin-path")
433                       .unwrap_or("/tmp/rustdoc/plugins".to_string());
434     let mut pm = plugins::PluginManager::new(PathBuf::from(path));
435     for pass in &passes {
436         let plugin = match PASSES.iter()
437                                  .position(|&(p, _, _)| {
438                                      p == *pass
439                                  }) {
440             Some(i) => PASSES[i].1,
441             None => {
442                 error!("unknown pass {}, skipping", *pass);
443                 continue
444             },
445         };
446         pm.add_plugin(plugin);
447     }
448     info!("loading plugins...");
449     for pname in plugins {
450         pm.load_plugin(pname);
451     }
452
453     // Run everything!
454     info!("Executing passes/plugins");
455     let (krate, json) = pm.run_plugins(krate);
456     return Output { krate: krate, json_plugins: json, passes: passes, };
457 }
458
459 /// This input format purely deserializes the json output file. No passes are
460 /// run over the deserialized output.
461 fn json_input(input: &str) -> Result<Output, String> {
462     let mut bytes = Vec::new();
463     match File::open(input).and_then(|mut f| f.read_to_end(&mut bytes)) {
464         Ok(_) => {}
465         Err(e) => return Err(format!("couldn't open {}: {}", input, e)),
466     };
467     match json::from_reader(&mut &bytes[..]) {
468         Err(s) => Err(format!("{:?}", s)),
469         Ok(Json::Object(obj)) => {
470             let mut obj = obj;
471             // Make sure the schema is what we expect
472             match obj.remove(&"schema".to_string()) {
473                 Some(Json::String(version)) => {
474                     if version != SCHEMA_VERSION {
475                         return Err(format!(
476                                 "sorry, but I only understand version {}",
477                                 SCHEMA_VERSION))
478                     }
479                 }
480                 Some(..) => return Err("malformed json".to_string()),
481                 None => return Err("expected a schema version".to_string()),
482             }
483             let krate = match obj.remove(&"crate".to_string()) {
484                 Some(json) => {
485                     let mut d = json::Decoder::new(json);
486                     Decodable::decode(&mut d).unwrap()
487                 }
488                 None => return Err("malformed json".to_string()),
489             };
490             // FIXME: this should read from the "plugins" field, but currently
491             //      Json doesn't implement decodable...
492             let plugin_output = Vec::new();
493             Ok(Output { krate: krate, json_plugins: plugin_output, passes: Vec::new(), })
494         }
495         Ok(..) => {
496             Err("malformed json input: expected an object at the \
497                  top".to_string())
498         }
499     }
500 }
501
502 /// Outputs the crate/plugin json as a giant json blob at the specified
503 /// destination.
504 fn json_output(krate: clean::Crate, res: Vec<plugins::PluginJson> ,
505                dst: PathBuf) -> io::Result<()> {
506     // {
507     //   "schema": version,
508     //   "crate": { parsed crate ... },
509     //   "plugins": { output of plugins ... }
510     // }
511     let mut json = std::collections::BTreeMap::new();
512     json.insert("schema".to_string(), Json::String(SCHEMA_VERSION.to_string()));
513     let plugins_json = res.into_iter()
514                           .filter_map(|opt| {
515                               match opt {
516                                   None => None,
517                                   Some((string, json)) => {
518                                       Some((string.to_string(), json))
519                                   }
520                               }
521                           }).collect();
522
523     // FIXME #8335: yuck, Rust -> str -> JSON round trip! No way to .encode
524     // straight to the Rust JSON representation.
525     let crate_json_str = format!("{}", json::as_json(&krate));
526     let crate_json = match json::from_str(&crate_json_str) {
527         Ok(j) => j,
528         Err(e) => panic!("Rust generated JSON is invalid: {:?}", e)
529     };
530
531     json.insert("crate".to_string(), crate_json);
532     json.insert("plugins".to_string(), Json::Object(plugins_json));
533
534     let mut file = try!(File::create(&dst));
535     write!(&mut file, "{}", Json::Object(json))
536 }