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