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