]> git.proxmox.com Git - rustc.git/blame - src/librustdoc/lib.rs
New upstream version 1.12.1+dfsg1
[rustc.git] / src / librustdoc / lib.rs
CommitLineData
1a4d82fc
JJ
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"]
e9174d1e 12#![unstable(feature = "rustdoc", issue = "27812")]
1a4d82fc
JJ
13#![crate_type = "dylib"]
14#![crate_type = "rlib"]
e9174d1e 15#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
9cc50fc6
SL
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/")]
7453a54e 19#![cfg_attr(not(stage0), deny(warnings))]
85aaf69f
SL
20
21#![feature(box_patterns)]
1a4d82fc 22#![feature(box_syntax)]
85aaf69f 23#![feature(libc)]
85aaf69f 24#![feature(rustc_private)]
62682a34 25#![feature(set_stdio)]
62682a34 26#![feature(slice_patterns)]
85aaf69f 27#![feature(staged_api)]
85aaf69f
SL
28#![feature(test)]
29#![feature(unicode)]
54a0048b 30#![feature(question_mark)]
1a4d82fc
JJ
31
32extern crate arena;
33extern crate getopts;
34extern crate libc;
35extern crate rustc;
54a0048b 36extern crate rustc_const_eval;
5bcae85e 37extern crate rustc_const_math;
1a4d82fc
JJ
38extern crate rustc_trans;
39extern crate rustc_driver;
85aaf69f 40extern crate rustc_resolve;
c34b1796
AL
41extern crate rustc_lint;
42extern crate rustc_back;
92a42be0 43extern crate rustc_metadata;
1a4d82fc 44extern crate serialize;
54a0048b 45#[macro_use] extern crate syntax;
3157f602 46extern crate syntax_pos;
c34b1796 47extern crate test as testing;
d9579d0f 48extern crate rustc_unicode;
1a4d82fc 49#[macro_use] extern crate log;
3157f602 50extern crate rustc_errors as errors;
1a4d82fc 51
c34b1796 52extern crate serialize as rustc_serialize; // used by deriving
1a4d82fc 53
5bcae85e 54use std::collections::{BTreeMap, BTreeSet};
9cc50fc6 55use std::default::Default;
85aaf69f 56use std::env;
c34b1796 57use std::path::PathBuf;
62682a34 58use std::process;
85aaf69f 59use std::sync::mpsc::channel;
c34b1796 60
1a4d82fc 61use externalfiles::ExternalHtml;
1a4d82fc 62use rustc::session::search_paths::SearchPaths;
5bcae85e
SL
63use rustc::session::config::{ErrorOutputType, RustcOptGroup, nightly_options,
64 Externs};
1a4d82fc
JJ
65
66#[macro_use]
67pub mod externalfiles;
68
69pub mod clean;
70pub mod core;
71pub mod doctree;
72pub mod fold;
73pub mod html {
74 pub mod highlight;
75 pub mod escape;
76 pub mod item_type;
77 pub mod format;
78 pub mod layout;
79 pub mod markdown;
80 pub mod render;
81 pub mod toc;
82}
83pub mod markdown;
84pub mod passes;
85pub mod plugins;
1a4d82fc 86pub mod visit_ast;
a7813a04 87pub mod visit_lib;
1a4d82fc
JJ
88pub mod test;
89mod flock;
90
54a0048b
SL
91use clean::Attributes;
92
1a4d82fc
JJ
93type Pass = (&'static str, // name
94 fn(clean::Crate) -> plugins::PluginResult, // fn
95 &'static str); // description
96
c34b1796 97const PASSES: &'static [Pass] = &[
1a4d82fc
JJ
98 ("strip-hidden", passes::strip_hidden,
99 "strips all doc(hidden) items from the output"),
100 ("unindent-comments", passes::unindent_comments,
101 "removes excess indentation on comments in order for markdown to like it"),
102 ("collapse-docs", passes::collapse_docs,
103 "concatenates all document attributes into one document attribute"),
104 ("strip-private", passes::strip_private,
54a0048b
SL
105 "strips all private items from a crate which cannot be seen externally, \
106 implies strip-priv-imports"),
107 ("strip-priv-imports", passes::strip_priv_imports,
108 "strips all private import statements (`use`, `extern crate`) from a crate"),
1a4d82fc
JJ
109];
110
c34b1796 111const DEFAULT_PASSES: &'static [&'static str] = &[
1a4d82fc
JJ
112 "strip-hidden",
113 "strip-private",
114 "collapse-docs",
115 "unindent-comments",
116];
117
1a4d82fc
JJ
118struct Output {
119 krate: clean::Crate,
a7813a04 120 renderinfo: html::render::RenderInfo,
1a4d82fc
JJ
121 passes: Vec<String>,
122}
123
124pub fn main() {
85aaf69f 125 const STACK_SIZE: usize = 32000000; // 32MB
9346a6ac 126 let res = std::thread::Builder::new().stack_size(STACK_SIZE).spawn(move || {
85aaf69f
SL
127 let s = env::args().collect::<Vec<_>>();
128 main_args(&s)
c1a9b12d 129 }).unwrap().join().unwrap_or(101);
62682a34 130 process::exit(res as i32);
1a4d82fc
JJ
131}
132
54a0048b
SL
133fn stable(g: getopts::OptGroup) -> RustcOptGroup { RustcOptGroup::stable(g) }
134fn unstable(g: getopts::OptGroup) -> RustcOptGroup { RustcOptGroup::unstable(g) }
135
136pub fn opts() -> Vec<RustcOptGroup> {
1a4d82fc
JJ
137 use getopts::*;
138 vec!(
54a0048b
SL
139 stable(optflag("h", "help", "show this help message")),
140 stable(optflag("V", "version", "print rustdoc's version")),
141 stable(optflag("v", "verbose", "use verbose output")),
142 stable(optopt("r", "input-format", "the input type of the specified file",
143 "[rust]")),
144 stable(optopt("w", "output-format", "the output type to write",
145 "[html]")),
146 stable(optopt("o", "output", "where to place the output", "PATH")),
147 stable(optopt("", "crate-name", "specify the name of this crate", "NAME")),
148 stable(optmulti("L", "library-path", "directory to add to crate search path",
149 "DIR")),
150 stable(optmulti("", "cfg", "pass a --cfg to rustc", "")),
151 stable(optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH")),
152 stable(optmulti("", "plugin-path", "directory to load plugins from", "DIR")),
153 stable(optmulti("", "passes",
154 "list of passes to also run, you might want \
155 to pass it multiple times; a value of `list` \
156 will print available passes",
157 "PASSES")),
158 stable(optmulti("", "plugins", "space separated list of plugins to also load",
159 "PLUGINS")),
160 stable(optflag("", "no-defaults", "don't run the default passes")),
161 stable(optflag("", "test", "run code examples as tests")),
162 stable(optmulti("", "test-args", "arguments to pass to the test runner",
163 "ARGS")),
164 stable(optopt("", "target", "target triple to document", "TRIPLE")),
165 stable(optmulti("", "markdown-css",
166 "CSS files to include via <link> in a rendered Markdown file",
167 "FILES")),
168 stable(optmulti("", "html-in-header",
169 "files to include inline in the <head> section of a rendered Markdown file \
170 or generated documentation",
171 "FILES")),
172 stable(optmulti("", "html-before-content",
173 "files to include inline between <body> and the content of a rendered \
174 Markdown file or generated documentation",
175 "FILES")),
176 stable(optmulti("", "html-after-content",
177 "files to include inline between the content and </body> of a rendered \
178 Markdown file or generated documentation",
179 "FILES")),
180 stable(optopt("", "markdown-playground-url",
181 "URL to send code snippets to", "URL")),
182 stable(optflag("", "markdown-no-toc", "don't include table of contents")),
183 unstable(optopt("e", "extend-css",
184 "to redefine some css rules with a given file to generate doc with your \
185 own theme", "PATH")),
186 unstable(optmulti("Z", "",
187 "internal and debugging options (only on nightly build)", "FLAG")),
1a4d82fc
JJ
188 )
189}
190
191pub fn usage(argv0: &str) {
192 println!("{}",
85aaf69f 193 getopts::usage(&format!("{} [options] <input>", argv0),
54a0048b
SL
194 &opts().into_iter()
195 .map(|x| x.opt_group)
196 .collect::<Vec<getopts::OptGroup>>()));
1a4d82fc
JJ
197}
198
c34b1796 199pub fn main_args(args: &[String]) -> isize {
54a0048b
SL
200 let all_groups: Vec<getopts::OptGroup> = opts()
201 .into_iter()
202 .map(|x| x.opt_group)
203 .collect();
204 let matches = match getopts::getopts(&args[1..], &all_groups) {
1a4d82fc
JJ
205 Ok(m) => m,
206 Err(err) => {
207 println!("{}", err);
208 return 1;
209 }
210 };
54a0048b
SL
211 // Check for unstable options.
212 nightly_options::check_nightly_options(&matches, &opts());
213
1a4d82fc 214 if matches.opt_present("h") || matches.opt_present("help") {
85aaf69f 215 usage(&args[0]);
1a4d82fc
JJ
216 return 0;
217 } else if matches.opt_present("version") {
218 rustc_driver::version("rustdoc", &matches);
219 return 0;
220 }
221
222 if matches.opt_strs("passes") == ["list"] {
223 println!("Available passes for running rustdoc:");
85aaf69f 224 for &(name, _, description) in PASSES {
1a4d82fc
JJ
225 println!("{:>20} - {}", name, description);
226 }
b039eaaf 227 println!("\nDefault passes for rustdoc:");
85aaf69f 228 for &name in DEFAULT_PASSES {
1a4d82fc
JJ
229 println!("{:>20}", name);
230 }
231 return 0;
232 }
233
9346a6ac 234 if matches.free.is_empty() {
1a4d82fc
JJ
235 println!("expected an input file to act on");
236 return 1;
237 } if matches.free.len() > 1 {
238 println!("only one input file may be specified");
239 return 1;
240 }
85aaf69f 241 let input = &matches.free[0];
1a4d82fc
JJ
242
243 let mut libs = SearchPaths::new();
85aaf69f 244 for s in &matches.opt_strs("L") {
9cc50fc6 245 libs.add_path(s, ErrorOutputType::default());
1a4d82fc
JJ
246 }
247 let externs = match parse_externs(&matches) {
248 Ok(ex) => ex,
249 Err(err) => {
250 println!("{}", err);
251 return 1;
252 }
253 };
254
255 let test_args = matches.opt_strs("test-args");
256 let test_args: Vec<String> = test_args.iter()
d9579d0f 257 .flat_map(|s| s.split_whitespace())
1a4d82fc
JJ
258 .map(|s| s.to_string())
259 .collect();
260
261 let should_test = matches.opt_present("test");
262 let markdown_input = input.ends_with(".md") || input.ends_with(".markdown");
263
c34b1796 264 let output = matches.opt_str("o").map(|s| PathBuf::from(&s));
54a0048b 265 let css_file_extension = matches.opt_str("e").map(|s| PathBuf::from(&s));
1a4d82fc
JJ
266 let cfgs = matches.opt_strs("cfg");
267
54a0048b
SL
268 if let Some(ref p) = css_file_extension {
269 if !p.is_file() {
270 println!("{}", "--extend-css option must take a css file as input");
271 return 1;
272 }
273 }
274
1a4d82fc 275 let external_html = match ExternalHtml::load(
85aaf69f
SL
276 &matches.opt_strs("html-in-header"),
277 &matches.opt_strs("html-before-content"),
278 &matches.opt_strs("html-after-content")) {
1a4d82fc
JJ
279 Some(eh) => eh,
280 None => return 3
281 };
282 let crate_name = matches.opt_str("crate-name");
283
284 match (should_test, markdown_input) {
285 (true, true) => {
92a42be0 286 return markdown::test(input, cfgs, libs, externs, test_args)
1a4d82fc
JJ
287 }
288 (true, false) => {
289 return test::run(input, cfgs, libs, externs, test_args, crate_name)
290 }
c34b1796
AL
291 (false, true) => return markdown::render(input,
292 output.unwrap_or(PathBuf::from("doc")),
1a4d82fc
JJ
293 &matches, &external_html,
294 !matches.opt_present("markdown-no-toc")),
295 (false, false) => {}
296 }
1a4d82fc
JJ
297 let out = match acquire_input(input, externs, &matches) {
298 Ok(out) => out,
299 Err(s) => {
300 println!("input error: {}", s);
301 return 1;
302 }
303 };
a7813a04 304 let Output { krate, passes, renderinfo } = out;
1a4d82fc 305 info!("going to format");
85aaf69f 306 match matches.opt_str("w").as_ref().map(|s| &**s) {
1a4d82fc 307 Some("html") | None => {
54a0048b
SL
308 html::render::run(krate, &external_html,
309 output.unwrap_or(PathBuf::from("doc")),
310 passes.into_iter().collect(),
a7813a04
XL
311 css_file_extension,
312 renderinfo)
54a0048b 313 .expect("failed to generate documentation")
1a4d82fc
JJ
314 }
315 Some(s) => {
316 println!("unknown output format: {}", s);
317 return 1;
318 }
319 }
320
321 return 0;
322}
323
324/// Looks inside the command line arguments to extract the relevant input format
325/// and files and then generates the necessary rustdoc output for formatting.
326fn acquire_input(input: &str,
5bcae85e 327 externs: Externs,
1a4d82fc 328 matches: &getopts::Matches) -> Result<Output, String> {
85aaf69f 329 match matches.opt_str("r").as_ref().map(|s| &**s) {
1a4d82fc 330 Some("rust") => Ok(rust_input(input, externs, matches)),
1a4d82fc
JJ
331 Some(s) => Err(format!("unknown input format: {}", s)),
332 None => {
54a0048b 333 Ok(rust_input(input, externs, matches))
1a4d82fc
JJ
334 }
335 }
336}
337
338/// Extracts `--extern CRATE=PATH` arguments from `matches` and
5bcae85e 339/// returns a map mapping crate names to their paths or else an
1a4d82fc 340/// error message.
5bcae85e
SL
341fn parse_externs(matches: &getopts::Matches) -> Result<Externs, String> {
342 let mut externs = BTreeMap::new();
85aaf69f 343 for arg in &matches.opt_strs("extern") {
c34b1796 344 let mut parts = arg.splitn(2, '=');
54a0048b
SL
345 let name = parts.next().ok_or("--extern value must not be empty".to_string())?;
346 let location = parts.next()
347 .ok_or("--extern value must be of the format `foo=bar`"
348 .to_string())?;
1a4d82fc 349 let name = name.to_string();
5bcae85e 350 externs.entry(name).or_insert_with(BTreeSet::new).insert(location.to_string());
1a4d82fc 351 }
5bcae85e 352 Ok(Externs::new(externs))
1a4d82fc
JJ
353}
354
355/// Interprets the input file as a rust source file, passing it through the
356/// compiler all the way through the analysis passes. The rustdoc output is then
357/// generated from the cleaned AST of the crate.
358///
359/// This form of input will run all of the plug/cleaning passes
5bcae85e 360fn rust_input(cratefile: &str, externs: Externs, matches: &getopts::Matches) -> Output {
1a4d82fc
JJ
361 let mut default_passes = !matches.opt_present("no-defaults");
362 let mut passes = matches.opt_strs("passes");
363 let mut plugins = matches.opt_strs("plugins");
364
365 // First, parse the crate and extract all relevant information.
366 let mut paths = SearchPaths::new();
85aaf69f 367 for s in &matches.opt_strs("L") {
9cc50fc6 368 paths.add_path(s, ErrorOutputType::default());
1a4d82fc
JJ
369 }
370 let cfgs = matches.opt_strs("cfg");
371 let triple = matches.opt_str("target");
372
c34b1796 373 let cr = PathBuf::from(cratefile);
1a4d82fc
JJ
374 info!("starting to run rustc");
375
85aaf69f 376 let (tx, rx) = channel();
c1a9b12d 377 rustc_driver::monitor(move || {
85aaf69f
SL
378 use rustc::session::config::Input;
379
c34b1796
AL
380 tx.send(core::run_core(paths, cfgs, externs, Input::File(cr),
381 triple)).unwrap();
c1a9b12d 382 });
a7813a04 383 let (mut krate, renderinfo) = rx.recv().unwrap();
1a4d82fc 384 info!("finished with rustc");
1a4d82fc 385
7453a54e
SL
386 if let Some(name) = matches.opt_str("crate-name") {
387 krate.name = name
1a4d82fc
JJ
388 }
389
390 // Process all of the crate attributes, extracting plugin metadata along
391 // with the passes which we are supposed to run.
54a0048b
SL
392 for attr in krate.module.as_ref().unwrap().attrs.list("doc") {
393 match *attr {
394 clean::Word(ref w) if "no_default_passes" == *w => {
395 default_passes = false;
396 },
397 clean::NameValue(ref name, ref value) => {
398 let sink = match &name[..] {
399 "passes" => &mut passes,
400 "plugins" => &mut plugins,
401 _ => continue,
402 };
403 for p in value.split_whitespace() {
404 sink.push(p.to_string());
1a4d82fc
JJ
405 }
406 }
54a0048b 407 _ => (),
1a4d82fc 408 }
1a4d82fc 409 }
54a0048b 410
1a4d82fc
JJ
411 if default_passes {
412 for name in DEFAULT_PASSES.iter().rev() {
413 passes.insert(0, name.to_string());
414 }
415 }
416
417 // Load all plugins/passes into a PluginManager
418 let path = matches.opt_str("plugin-path")
419 .unwrap_or("/tmp/rustdoc/plugins".to_string());
c34b1796 420 let mut pm = plugins::PluginManager::new(PathBuf::from(path));
85aaf69f 421 for pass in &passes {
1a4d82fc
JJ
422 let plugin = match PASSES.iter()
423 .position(|&(p, _, _)| {
424 p == *pass
425 }) {
426 Some(i) => PASSES[i].1,
427 None => {
428 error!("unknown pass {}, skipping", *pass);
429 continue
430 },
431 };
432 pm.add_plugin(plugin);
433 }
434 info!("loading plugins...");
85aaf69f 435 for pname in plugins {
1a4d82fc
JJ
436 pm.load_plugin(pname);
437 }
438
439 // Run everything!
440 info!("Executing passes/plugins");
54a0048b 441 let krate = pm.run_plugins(krate);
a7813a04 442 Output { krate: krate, renderinfo: renderinfo, passes: passes }
1a4d82fc 443}