]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/lib.rs
Rollup merge of #54257 - alexcrichton:wasm-math-symbols, r=TimNN
[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 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
12        html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
13        html_root_url = "https://doc.rust-lang.org/nightly/",
14        html_playground_url = "https://play.rust-lang.org/")]
15
16 #![feature(rustc_private)]
17 #![feature(box_patterns)]
18 #![feature(box_syntax)]
19 #![cfg_attr(not(stage0), feature(nll))]
20 #![feature(set_stdio)]
21 #![feature(slice_sort_by_cached_key)]
22 #![feature(test)]
23 #![feature(vec_remove_item)]
24 #![feature(ptr_offset_from)]
25 #![feature(crate_visibility_modifier)]
26 #![feature(const_fn)]
27
28 #![recursion_limit="256"]
29
30 extern crate arena;
31 extern crate getopts;
32 extern crate env_logger;
33 extern crate rustc;
34 extern crate rustc_data_structures;
35 extern crate rustc_codegen_utils;
36 extern crate rustc_driver;
37 extern crate rustc_resolve;
38 extern crate rustc_lint;
39 extern crate rustc_metadata;
40 extern crate rustc_target;
41 extern crate rustc_typeck;
42 extern crate serialize;
43 #[macro_use] extern crate syntax;
44 extern crate syntax_pos;
45 extern crate test as testing;
46 #[macro_use] extern crate log;
47 extern crate rustc_errors as errors;
48 extern crate pulldown_cmark;
49 extern crate tempfile;
50 extern crate minifier;
51
52 extern crate serialize as rustc_serialize; // used by deriving
53
54 use errors::ColorConfig;
55
56 use std::collections::{BTreeMap, BTreeSet};
57 use std::default::Default;
58 use std::env;
59 use std::panic;
60 use std::path::{Path, PathBuf};
61 use std::process;
62 use std::sync::mpsc::channel;
63
64 use syntax::edition::Edition;
65 use externalfiles::ExternalHtml;
66 use rustc::session::{early_warn, early_error};
67 use rustc::session::search_paths::SearchPaths;
68 use rustc::session::config::{ErrorOutputType, RustcOptGroup, Externs, CodegenOptions};
69 use rustc::session::config::{nightly_options, build_codegen_options};
70 use rustc_target::spec::TargetTriple;
71 use rustc::session::config::get_cmd_lint_options;
72
73 #[macro_use]
74 mod externalfiles;
75
76 mod clean;
77 mod core;
78 mod doctree;
79 mod fold;
80 pub mod html {
81     crate mod highlight;
82     crate mod escape;
83     crate mod item_type;
84     crate mod format;
85     crate mod layout;
86     pub mod markdown;
87     crate mod render;
88     crate mod toc;
89 }
90 mod markdown;
91 mod passes;
92 mod visit_ast;
93 mod visit_lib;
94 mod test;
95 mod theme;
96
97 struct Output {
98     krate: clean::Crate,
99     renderinfo: html::render::RenderInfo,
100     passes: Vec<String>,
101 }
102
103 pub fn main() {
104     let thread_stack_size: usize = if cfg!(target_os = "haiku") {
105         16_000_000 // 16MB on Haiku
106     } else {
107         32_000_000 // 32MB on other platforms
108     };
109     rustc_driver::set_sigpipe_handler();
110     env_logger::init();
111     let res = std::thread::Builder::new().stack_size(thread_stack_size).spawn(move || {
112         syntax::with_globals(move || {
113             get_args().map(|args| main_args(&args)).unwrap_or(1)
114         })
115     }).unwrap().join().unwrap_or(rustc_driver::EXIT_FAILURE);
116     process::exit(res as i32);
117 }
118
119 fn get_args() -> Option<Vec<String>> {
120     env::args_os().enumerate()
121         .map(|(i, arg)| arg.into_string().map_err(|arg| {
122              early_warn(ErrorOutputType::default(),
123                         &format!("Argument {} is not valid Unicode: {:?}", i, arg));
124         }).ok())
125         .collect()
126 }
127
128 fn stable<F>(name: &'static str, f: F) -> RustcOptGroup
129     where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
130 {
131     RustcOptGroup::stable(name, f)
132 }
133
134 fn unstable<F>(name: &'static str, f: F) -> RustcOptGroup
135     where F: Fn(&mut getopts::Options) -> &mut getopts::Options + 'static
136 {
137     RustcOptGroup::unstable(name, f)
138 }
139
140 fn opts() -> Vec<RustcOptGroup> {
141     vec![
142         stable("h", |o| o.optflag("h", "help", "show this help message")),
143         stable("V", |o| o.optflag("V", "version", "print rustdoc's version")),
144         stable("v", |o| o.optflag("v", "verbose", "use verbose output")),
145         stable("r", |o| {
146             o.optopt("r", "input-format", "the input type of the specified file",
147                      "[rust]")
148         }),
149         stable("w", |o| {
150             o.optopt("w", "output-format", "the output type to write", "[html]")
151         }),
152         stable("o", |o| o.optopt("o", "output", "where to place the output", "PATH")),
153         stable("crate-name", |o| {
154             o.optopt("", "crate-name", "specify the name of this crate", "NAME")
155         }),
156         stable("L", |o| {
157             o.optmulti("L", "library-path", "directory to add to crate search path",
158                        "DIR")
159         }),
160         stable("cfg", |o| o.optmulti("", "cfg", "pass a --cfg to rustc", "")),
161         stable("extern", |o| {
162             o.optmulti("", "extern", "pass an --extern to rustc", "NAME=PATH")
163         }),
164         unstable("extern-html-root-url", |o| {
165             o.optmulti("", "extern-html-root-url",
166                        "base URL to use for dependencies", "NAME=URL")
167         }),
168         stable("plugin-path", |o| {
169             o.optmulti("", "plugin-path", "removed", "DIR")
170         }),
171         stable("C", |o| {
172             o.optmulti("C", "codegen", "pass a codegen option to rustc", "OPT[=VALUE]")
173         }),
174         stable("passes", |o| {
175             o.optmulti("", "passes",
176                        "list of passes to also run, you might want \
177                         to pass it multiple times; a value of `list` \
178                         will print available passes",
179                        "PASSES")
180         }),
181         stable("plugins", |o| {
182             o.optmulti("", "plugins", "removed",
183                        "PLUGINS")
184         }),
185         stable("no-default", |o| {
186             o.optflag("", "no-defaults", "don't run the default passes")
187         }),
188         stable("document-private-items", |o| {
189             o.optflag("", "document-private-items", "document private items")
190         }),
191         stable("test", |o| o.optflag("", "test", "run code examples as tests")),
192         stable("test-args", |o| {
193             o.optmulti("", "test-args", "arguments to pass to the test runner",
194                        "ARGS")
195         }),
196         stable("target", |o| o.optopt("", "target", "target triple to document", "TRIPLE")),
197         stable("markdown-css", |o| {
198             o.optmulti("", "markdown-css",
199                        "CSS files to include via <link> in a rendered Markdown file",
200                        "FILES")
201         }),
202         stable("html-in-header", |o|  {
203             o.optmulti("", "html-in-header",
204                        "files to include inline in the <head> section of a rendered Markdown file \
205                         or generated documentation",
206                        "FILES")
207         }),
208         stable("html-before-content", |o| {
209             o.optmulti("", "html-before-content",
210                        "files to include inline between <body> and the content of a rendered \
211                         Markdown file or generated documentation",
212                        "FILES")
213         }),
214         stable("html-after-content", |o| {
215             o.optmulti("", "html-after-content",
216                        "files to include inline between the content and </body> of a rendered \
217                         Markdown file or generated documentation",
218                        "FILES")
219         }),
220         unstable("markdown-before-content", |o| {
221             o.optmulti("", "markdown-before-content",
222                        "files to include inline between <body> and the content of a rendered \
223                         Markdown file or generated documentation",
224                        "FILES")
225         }),
226         unstable("markdown-after-content", |o| {
227             o.optmulti("", "markdown-after-content",
228                        "files to include inline between the content and </body> of a rendered \
229                         Markdown file or generated documentation",
230                        "FILES")
231         }),
232         stable("markdown-playground-url", |o| {
233             o.optopt("", "markdown-playground-url",
234                      "URL to send code snippets to", "URL")
235         }),
236         stable("markdown-no-toc", |o| {
237             o.optflag("", "markdown-no-toc", "don't include table of contents")
238         }),
239         stable("e", |o| {
240             o.optopt("e", "extend-css",
241                      "To add some CSS rules with a given file to generate doc with your \
242                       own theme. However, your theme might break if the rustdoc's generated HTML \
243                       changes, so be careful!", "PATH")
244         }),
245         unstable("Z", |o| {
246             o.optmulti("Z", "",
247                        "internal and debugging options (only on nightly build)", "FLAG")
248         }),
249         stable("sysroot", |o| {
250             o.optopt("", "sysroot", "Override the system root", "PATH")
251         }),
252         unstable("playground-url", |o| {
253             o.optopt("", "playground-url",
254                      "URL to send code snippets to, may be reset by --markdown-playground-url \
255                       or `#![doc(html_playground_url=...)]`",
256                      "URL")
257         }),
258         unstable("display-warnings", |o| {
259             o.optflag("", "display-warnings", "to print code warnings when testing doc")
260         }),
261         unstable("crate-version", |o| {
262             o.optopt("", "crate-version", "crate version to print into documentation", "VERSION")
263         }),
264         unstable("linker", |o| {
265             o.optopt("", "linker", "linker used for building executable test code", "PATH")
266         }),
267         unstable("sort-modules-by-appearance", |o| {
268             o.optflag("", "sort-modules-by-appearance", "sort modules by where they appear in the \
269                                                          program, rather than alphabetically")
270         }),
271         unstable("themes", |o| {
272             o.optmulti("", "themes",
273                        "additional themes which will be added to the generated docs",
274                        "FILES")
275         }),
276         unstable("theme-checker", |o| {
277             o.optmulti("", "theme-checker",
278                        "check if given theme is valid",
279                        "FILES")
280         }),
281         unstable("resource-suffix", |o| {
282             o.optopt("",
283                      "resource-suffix",
284                      "suffix to add to CSS and JavaScript files, e.g. \"light.css\" will become \
285                       \"light-suffix.css\"",
286                      "PATH")
287         }),
288         stable("edition", |o| {
289             o.optopt("", "edition",
290                      "edition to use when compiling rust code (default: 2015)",
291                      "EDITION")
292         }),
293         stable("color", |o| {
294             o.optopt("",
295                      "color",
296                      "Configure coloring of output:
297                                           auto   = colorize, if output goes to a tty (default);
298                                           always = always colorize output;
299                                           never  = never colorize output",
300                      "auto|always|never")
301         }),
302         stable("error-format", |o| {
303             o.optopt("",
304                      "error-format",
305                      "How errors and other messages are produced",
306                      "human|json|short")
307         }),
308         unstable("disable-minification", |o| {
309              o.optflag("",
310                        "disable-minification",
311                        "Disable minification applied on JS files")
312         }),
313         stable("warn", |o| {
314             o.optmulti("W", "warn", "Set lint warnings", "OPT")
315         }),
316         stable("allow", |o| {
317             o.optmulti("A", "allow", "Set lint allowed", "OPT")
318         }),
319         stable("deny", |o| {
320             o.optmulti("D", "deny", "Set lint denied", "OPT")
321         }),
322         stable("forbid", |o| {
323             o.optmulti("F", "forbid", "Set lint forbidden", "OPT")
324         }),
325         stable("cap-lints", |o| {
326             o.optmulti(
327                 "",
328                 "cap-lints",
329                 "Set the most restrictive lint level. \
330                  More restrictive lints are capped at this \
331                  level. By default, it is at `forbid` level.",
332                 "LEVEL",
333             )
334         }),
335     ]
336 }
337
338 fn usage(argv0: &str) {
339     let mut options = getopts::Options::new();
340     for option in opts() {
341         (option.apply)(&mut options);
342     }
343     println!("{}", options.usage(&format!("{} [options] <input>", argv0)));
344 }
345
346 fn main_args(args: &[String]) -> isize {
347     let mut options = getopts::Options::new();
348     for option in opts() {
349         (option.apply)(&mut options);
350     }
351     let matches = match options.parse(&args[1..]) {
352         Ok(m) => m,
353         Err(err) => {
354             early_error(ErrorOutputType::default(), &err.to_string());
355         }
356     };
357     // Check for unstable options.
358     nightly_options::check_nightly_options(&matches, &opts());
359
360     if matches.opt_present("h") || matches.opt_present("help") {
361         usage("rustdoc");
362         return 0;
363     } else if matches.opt_present("version") {
364         rustc_driver::version("rustdoc", &matches);
365         return 0;
366     }
367
368     if matches.opt_strs("passes") == ["list"] {
369         println!("Available passes for running rustdoc:");
370         for pass in passes::PASSES {
371             println!("{:>20} - {}", pass.name(), pass.description());
372         }
373         println!("\nDefault passes for rustdoc:");
374         for &name in passes::DEFAULT_PASSES {
375             println!("{:>20}", name);
376         }
377         println!("\nPasses run with `--document-private-items`:");
378         for &name in passes::DEFAULT_PRIVATE_PASSES {
379             println!("{:>20}", name);
380         }
381         return 0;
382     }
383
384     let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) {
385         Some("auto") => ColorConfig::Auto,
386         Some("always") => ColorConfig::Always,
387         Some("never") => ColorConfig::Never,
388         None => ColorConfig::Auto,
389         Some(arg) => {
390             early_error(ErrorOutputType::default(),
391                         &format!("argument for --color must be `auto`, `always` or `never` \
392                                   (instead was `{}`)", arg));
393         }
394     };
395     let error_format = match matches.opt_str("error-format").as_ref().map(|s| &s[..]) {
396         Some("human") => ErrorOutputType::HumanReadable(color),
397         Some("json") => ErrorOutputType::Json(false),
398         Some("pretty-json") => ErrorOutputType::Json(true),
399         Some("short") => ErrorOutputType::Short(color),
400         None => ErrorOutputType::HumanReadable(color),
401         Some(arg) => {
402             early_error(ErrorOutputType::default(),
403                         &format!("argument for --error-format must be `human`, `json` or \
404                                   `short` (instead was `{}`)", arg));
405         }
406     };
407     let treat_err_as_bug = matches.opt_strs("Z").iter().any(|x| {
408         *x == "treat-err-as-bug"
409     });
410
411     let diag = core::new_handler(error_format, None, treat_err_as_bug);
412
413     // check for deprecated options
414     check_deprecated_options(&matches, &diag);
415
416     let to_check = matches.opt_strs("theme-checker");
417     if !to_check.is_empty() {
418         let paths = theme::load_css_paths(include_bytes!("html/static/themes/light.css"));
419         let mut errors = 0;
420
421         println!("rustdoc: [theme-checker] Starting tests!");
422         for theme_file in to_check.iter() {
423             print!(" - Checking \"{}\"...", theme_file);
424             let (success, differences) = theme::test_theme_against(theme_file, &paths, &diag);
425             if !differences.is_empty() || !success {
426                 println!(" FAILED");
427                 errors += 1;
428                 if !differences.is_empty() {
429                     println!("{}", differences.join("\n"));
430                 }
431             } else {
432                 println!(" OK");
433             }
434         }
435         if errors != 0 {
436             return 1;
437         }
438         return 0;
439     }
440
441     if matches.free.is_empty() {
442         diag.struct_err("missing file operand").emit();
443         return 1;
444     }
445     if matches.free.len() > 1 {
446         diag.struct_err("too many file operands").emit();
447         return 1;
448     }
449     let input = &matches.free[0];
450
451     let mut libs = SearchPaths::new();
452     for s in &matches.opt_strs("L") {
453         libs.add_path(s, error_format);
454     }
455     let externs = match parse_externs(&matches) {
456         Ok(ex) => ex,
457         Err(err) => {
458             diag.struct_err(&err.to_string()).emit();
459             return 1;
460         }
461     };
462     let extern_urls = match parse_extern_html_roots(&matches) {
463         Ok(ex) => ex,
464         Err(err) => {
465             diag.struct_err(err).emit();
466             return 1;
467         }
468     };
469
470     let test_args = matches.opt_strs("test-args");
471     let test_args: Vec<String> = test_args.iter()
472                                           .flat_map(|s| s.split_whitespace())
473                                           .map(|s| s.to_string())
474                                           .collect();
475
476     let should_test = matches.opt_present("test");
477     let markdown_input = Path::new(input).extension()
478         .map_or(false, |e| e == "md" || e == "markdown");
479
480     let output = matches.opt_str("o").map(|s| PathBuf::from(&s));
481     let css_file_extension = matches.opt_str("e").map(|s| PathBuf::from(&s));
482     let mut cfgs = matches.opt_strs("cfg");
483     cfgs.push("rustdoc".to_string());
484
485     if let Some(ref p) = css_file_extension {
486         if !p.is_file() {
487             diag.struct_err("option --extend-css argument must be a file").emit();
488             return 1;
489         }
490     }
491
492     let mut themes = Vec::new();
493     if matches.opt_present("themes") {
494         let paths = theme::load_css_paths(include_bytes!("html/static/themes/light.css"));
495
496         for (theme_file, theme_s) in matches.opt_strs("themes")
497                                             .iter()
498                                             .map(|s| (PathBuf::from(&s), s.to_owned())) {
499             if !theme_file.is_file() {
500                 diag.struct_err("option --themes arguments must all be files").emit();
501                 return 1;
502             }
503             let (success, ret) = theme::test_theme_against(&theme_file, &paths, &diag);
504             if !success || !ret.is_empty() {
505                 diag.struct_err(&format!("invalid theme: \"{}\"", theme_s))
506                     .help("check what's wrong with the --theme-checker option")
507                     .emit();
508                 return 1;
509             }
510             themes.push(theme_file);
511         }
512     }
513
514     let mut id_map = html::markdown::IdMap::new();
515     id_map.populate(html::render::initial_ids());
516     let external_html = match ExternalHtml::load(
517             &matches.opt_strs("html-in-header"),
518             &matches.opt_strs("html-before-content"),
519             &matches.opt_strs("html-after-content"),
520             &matches.opt_strs("markdown-before-content"),
521             &matches.opt_strs("markdown-after-content"), &diag, &mut id_map) {
522         Some(eh) => eh,
523         None => return 3,
524     };
525     let crate_name = matches.opt_str("crate-name");
526     let playground_url = matches.opt_str("playground-url");
527     let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
528     let display_warnings = matches.opt_present("display-warnings");
529     let linker = matches.opt_str("linker").map(PathBuf::from);
530     let sort_modules_alphabetically = !matches.opt_present("sort-modules-by-appearance");
531     let resource_suffix = matches.opt_str("resource-suffix");
532     let enable_minification = !matches.opt_present("disable-minification");
533
534     let edition = matches.opt_str("edition").unwrap_or("2015".to_string());
535     let edition = match edition.parse() {
536         Ok(e) => e,
537         Err(_) => {
538             diag.struct_err("could not parse edition").emit();
539             return 1;
540         }
541     };
542
543     let cg = build_codegen_options(&matches, ErrorOutputType::default());
544
545     match (should_test, markdown_input) {
546         (true, true) => {
547             return markdown::test(input, cfgs, libs, externs, test_args, maybe_sysroot,
548                                   display_warnings, linker, edition, cg, &diag)
549         }
550         (true, false) => {
551             return test::run(Path::new(input), cfgs, libs, externs, test_args, crate_name,
552                              maybe_sysroot, display_warnings, linker, edition, cg)
553         }
554         (false, true) => return markdown::render(Path::new(input),
555                                                  output.unwrap_or(PathBuf::from("doc")),
556                                                  &matches, &external_html,
557                                                  !matches.opt_present("markdown-no-toc"), &diag),
558         (false, false) => {}
559     }
560
561     let output_format = matches.opt_str("w");
562
563     let res = acquire_input(PathBuf::from(input), externs, edition, cg, &matches, error_format,
564                             move |out| {
565         let Output { krate, passes, renderinfo } = out;
566         let diag = core::new_handler(error_format, None, treat_err_as_bug);
567         info!("going to format");
568         match output_format.as_ref().map(|s| &**s) {
569             Some("html") | None => {
570                 html::render::run(krate, extern_urls, &external_html, playground_url,
571                                   output.unwrap_or(PathBuf::from("doc")),
572                                   resource_suffix.unwrap_or(String::new()),
573                                   passes.into_iter().collect(),
574                                   css_file_extension,
575                                   renderinfo,
576                                   sort_modules_alphabetically,
577                                   themes,
578                                   enable_minification, id_map)
579                     .expect("failed to generate documentation");
580                 0
581             }
582             Some(s) => {
583                 diag.struct_err(&format!("unknown output format: {}", s)).emit();
584                 1
585             }
586         }
587     });
588     res.unwrap_or_else(|s| {
589         diag.struct_err(&format!("input error: {}", s)).emit();
590         1
591     })
592 }
593
594 /// Looks inside the command line arguments to extract the relevant input format
595 /// and files and then generates the necessary rustdoc output for formatting.
596 fn acquire_input<R, F>(input: PathBuf,
597                        externs: Externs,
598                        edition: Edition,
599                        cg: CodegenOptions,
600                        matches: &getopts::Matches,
601                        error_format: ErrorOutputType,
602                        f: F)
603                        -> Result<R, String>
604 where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R {
605     match matches.opt_str("r").as_ref().map(|s| &**s) {
606         Some("rust") => Ok(rust_input(input, externs, edition, cg, matches, error_format, f)),
607         Some(s) => Err(format!("unknown input format: {}", s)),
608         None => Ok(rust_input(input, externs, edition, cg, matches, error_format, f))
609     }
610 }
611
612 /// Extracts `--extern CRATE=PATH` arguments from `matches` and
613 /// returns a map mapping crate names to their paths or else an
614 /// error message.
615 // FIXME(eddyb) This shouldn't be duplicated with `rustc::session`.
616 fn parse_externs(matches: &getopts::Matches) -> Result<Externs, String> {
617     let mut externs: BTreeMap<_, BTreeSet<_>> = BTreeMap::new();
618     for arg in &matches.opt_strs("extern") {
619         let mut parts = arg.splitn(2, '=');
620         let name = parts.next().ok_or("--extern value must not be empty".to_string())?;
621         let location = parts.next().map(|s| s.to_string());
622         if location.is_none() && !nightly_options::is_unstable_enabled(matches) {
623             return Err("the `-Z unstable-options` flag must also be passed to \
624                         enable `--extern crate_name` without `=path`".to_string());
625         }
626         let name = name.to_string();
627         externs.entry(name).or_default().insert(location);
628     }
629     Ok(Externs::new(externs))
630 }
631
632 /// Extracts `--extern-html-root-url` arguments from `matches` and returns a map of crate names to
633 /// the given URLs. If an `--extern-html-root-url` argument was ill-formed, returns an error
634 /// describing the issue.
635 fn parse_extern_html_roots(matches: &getopts::Matches)
636     -> Result<BTreeMap<String, String>, &'static str>
637 {
638     let mut externs = BTreeMap::new();
639     for arg in &matches.opt_strs("extern-html-root-url") {
640         let mut parts = arg.splitn(2, '=');
641         let name = parts.next().ok_or("--extern-html-root-url must not be empty")?;
642         let url = parts.next().ok_or("--extern-html-root-url must be of the form name=url")?;
643         externs.insert(name.to_string(), url.to_string());
644     }
645
646     Ok(externs)
647 }
648
649 /// Interprets the input file as a rust source file, passing it through the
650 /// compiler all the way through the analysis passes. The rustdoc output is then
651 /// generated from the cleaned AST of the crate.
652 ///
653 /// This form of input will run all of the plug/cleaning passes
654 fn rust_input<R, F>(cratefile: PathBuf,
655                     externs: Externs,
656                     edition: Edition,
657                     cg: CodegenOptions,
658                     matches: &getopts::Matches,
659                     error_format: ErrorOutputType,
660                     f: F) -> R
661 where R: 'static + Send,
662       F: 'static + Send + FnOnce(Output) -> R
663 {
664     let default_passes = if matches.opt_present("no-defaults") {
665         passes::DefaultPassOption::None
666     } else if matches.opt_present("document-private-items") {
667         passes::DefaultPassOption::Private
668     } else {
669         passes::DefaultPassOption::Default
670     };
671
672     let manual_passes = matches.opt_strs("passes");
673     let plugins = matches.opt_strs("plugins");
674
675     // First, parse the crate and extract all relevant information.
676     let mut paths = SearchPaths::new();
677     for s in &matches.opt_strs("L") {
678         paths.add_path(s, ErrorOutputType::default());
679     }
680     let mut cfgs = matches.opt_strs("cfg");
681     cfgs.push("rustdoc".to_string());
682     let triple = matches.opt_str("target").map(|target| {
683         if target.ends_with(".json") {
684             TargetTriple::TargetPath(PathBuf::from(target))
685         } else {
686             TargetTriple::TargetTriple(target)
687         }
688     });
689     let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
690     let crate_name = matches.opt_str("crate-name");
691     let crate_version = matches.opt_str("crate-version");
692     let plugin_path = matches.opt_str("plugin-path");
693
694     info!("starting to run rustc");
695     let display_warnings = matches.opt_present("display-warnings");
696
697     let force_unstable_if_unmarked = matches.opt_strs("Z").iter().any(|x| {
698         *x == "force-unstable-if-unmarked"
699     });
700     let treat_err_as_bug = matches.opt_strs("Z").iter().any(|x| {
701         *x == "treat-err-as-bug"
702     });
703
704     let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(matches, error_format);
705
706     let (tx, rx) = channel();
707
708     let result = rustc_driver::monitor(move || syntax::with_globals(move || {
709         use rustc::session::config::Input;
710
711         let (mut krate, renderinfo, passes) =
712             core::run_core(paths, cfgs, externs, Input::File(cratefile), triple, maybe_sysroot,
713                            display_warnings, crate_name.clone(),
714                            force_unstable_if_unmarked, edition, cg, error_format,
715                            lint_opts, lint_cap, describe_lints, manual_passes, default_passes,
716                            treat_err_as_bug);
717
718         info!("finished with rustc");
719
720         if let Some(name) = crate_name {
721             krate.name = name
722         }
723
724         krate.version = crate_version;
725
726         if !plugins.is_empty() {
727             eprintln!("WARNING: --plugins no longer functions; see CVE-2018-1000622");
728         }
729
730         if !plugin_path.is_none() {
731             eprintln!("WARNING: --plugin-path no longer functions; see CVE-2018-1000622");
732         }
733
734         info!("Executing passes");
735
736         for pass in &passes {
737             // determine if we know about this pass
738             let pass = match passes::find_pass(pass) {
739                 Some(pass) => if let Some(pass) = pass.late_fn() {
740                     pass
741                 } else {
742                     // not a late pass, but still valid so don't report the error
743                     continue
744                 }
745                 None => {
746                     error!("unknown pass {}, skipping", *pass);
747
748                     continue
749                 },
750             };
751
752             // run it
753             krate = pass(krate);
754         }
755
756         tx.send(f(Output { krate: krate, renderinfo: renderinfo, passes: passes })).unwrap();
757     }));
758
759     match result {
760         Ok(()) => rx.recv().unwrap(),
761         Err(_) => panic::resume_unwind(Box::new(errors::FatalErrorMarker)),
762     }
763 }
764
765 /// Prints deprecation warnings for deprecated options
766 fn check_deprecated_options(matches: &getopts::Matches, diag: &errors::Handler) {
767     let deprecated_flags = [
768        "input-format",
769        "output-format",
770        "no-defaults",
771        "passes",
772     ];
773
774     for flag in deprecated_flags.into_iter() {
775         if matches.opt_present(flag) {
776             let mut err = diag.struct_warn(&format!("the '{}' flag is considered deprecated",
777                                                     flag));
778             err.warn("please see https://github.com/rust-lang/rust/issues/44136");
779
780             if *flag == "no-defaults" {
781                 err.help("you may want to use --document-private-items");
782             }
783
784             err.emit();
785         }
786     }
787 }