From f5f496efd086ae763075295eac8aae757909f29c Mon Sep 17 00:00:00 2001 From: QuietMisdreavus Date: Tue, 30 Oct 2018 08:47:54 -0500 Subject: [PATCH] parse command-line into a central Options struct --- src/librustdoc/config.rs | 488 +++++++++++++++++++++++++++++++++++++ src/librustdoc/lib.rs | 336 +++---------------------- src/librustdoc/markdown.rs | 4 +- 3 files changed, 528 insertions(+), 300 deletions(-) create mode 100644 src/librustdoc/config.rs diff --git a/src/librustdoc/config.rs b/src/librustdoc/config.rs new file mode 100644 index 00000000000..4a9b3574cd8 --- /dev/null +++ b/src/librustdoc/config.rs @@ -0,0 +1,488 @@ +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::PathBuf; + +use errors; +use errors::emitter::ColorConfig; +use getopts; +use rustc::lint::Level; +use rustc::session::early_error; +use rustc::session::config::{CodegenOptions, DebuggingOptions, ErrorOutputType, Externs}; +use rustc::session::config::{nightly_options, build_codegen_options, build_debugging_options, + get_cmd_lint_options}; +use rustc::session::search_paths::SearchPaths; +use rustc_driver; +use rustc_target::spec::TargetTriple; +use syntax::edition::Edition; + +use core::new_handler; +use externalfiles::ExternalHtml; +use html; +use html::markdown::IdMap; +use opts; +use passes::{self, DefaultPassOption}; +use theme; + +pub struct Options { + // Basic options / Options passed directly to rustc + + /// The crate root or Markdown file to load. + pub input: PathBuf, + /// Output directory to generate docs into. Defaults to `doc`. + pub output: PathBuf, + /// The name of the crate being documented. + pub crate_name: Option, + /// How to format errors and warnings. + pub error_format: ErrorOutputType, + /// Library search paths to hand to the compiler. + pub libs: SearchPaths, + /// The list of external crates to link against. + pub externs: Externs, + /// List of `cfg` flags to hand to the compiler. Always includes `rustdoc`. + pub cfgs: Vec, + /// Codegen options to hand to the compiler. + pub codegen_options: CodegenOptions, + /// Debugging (`-Z`) options to pass to the compiler. + pub debugging_options: DebuggingOptions, + /// The target used to compile the crate against. + pub target: Option, + /// Edition used when reading the crate. Defaults to "2015". Also used by default when + /// compiling doctests from the crate. + pub edition: Edition, + /// The path to the sysroot. Used during the compilation process. + pub maybe_sysroot: Option, + /// Linker to use when building doctests. + pub linker: Option, + /// Lint information passed over the command-line. + pub lint_opts: Vec<(String, Level)>, + /// Whether to ask rustc to describe the lints it knows. Practically speaking, this will not be + /// used, since we abort if we have no input file, but it's included for completeness. + pub describe_lints: bool, + /// What level to cap lints at. + pub lint_cap: Option, + + // Options specific to running doctests + + /// Whether we should run doctests instead of generating docs. + pub should_test: bool, + /// List of arguments to pass to the test harness, if running tests. + pub test_args: Vec, + + // Options that affect the documentation process + + /// The selected default set of passes to use. + /// + /// Be aware: This option can come both from the CLI and from crate attributes! + pub default_passes: DefaultPassOption, + /// Any passes manually selected by the user. + /// + /// Be aware: This option can come both from the CLI and from crate attributes! + pub manual_passes: Vec, + /// Whether to display warnings during doc generation or while gathering doctests. By default, + /// all non-rustdoc-specific lints are allowed when generating docs. + pub display_warnings: bool, + /// A pre-populated `IdMap` with the default headings and any headings added by Markdown files + /// processed by `external_html`. + pub id_map: IdMap, + + // Options that alter generated documentation pages + + /// External files to insert into generated pages. + pub external_html: ExternalHtml, + /// If present, playground URL to use in the "Run" button added to code samples. + /// + /// Be aware: This option can come both from the CLI and from crate attributes! + pub playground_url: Option, + /// Crate version to note on the sidebar of generated docs. + pub crate_version: Option, + /// Whether to sort modules alphabetically on a module page instead of using declaration order. + /// `true` by default. + /// + /// FIXME(misdreavus): the flag name is `--sort-modules-by-appearance` but the meaning is + /// inverted once read + pub sort_modules_alphabetically: bool, + /// List of themes to extend the docs with. Original argument name is included to assist in + /// displaying errors if it fails a theme check. + pub themes: Vec, + /// If present, CSS file that contains rules to add to the default CSS. + pub extension_css: Option, + /// A map of crate names to the URL to use instead of querying the crate's `html_root_url`. + pub extern_html_root_urls: BTreeMap, + /// If present, suffix added to CSS/JavaScript files when referencing them in generated pages. + pub resource_suffix: String, + /// Whether to run the static CSS/JavaScript through a minifier when outputting them. `true` by + /// default. + /// + /// FIXME(misdreavus): the flag name is `--disable-minification` but the meaning is inverted + /// once read + pub enable_minification: bool, + /// Whether to create an index page in the root of the output directory. If this is true but + /// `enable_index_page` is None, generate a static listing of crates instead. + pub enable_index_page: bool, + /// A file to use as the index page at the root of the output directory. Overrides + /// `enable_index_page` to be true if set. + pub index_page: Option, + + // Options specific to reading standalone Markdown files + + /// Whether to generate a table of contents on the output file when reading a standalone + /// Markdown file. + pub markdown_no_toc: bool, + /// Additional CSS files to link in pages generated from standlone Markdown files. + pub markdown_css: Vec, + /// If present, playground URL to use in the "Run" button added to code samples generated from + /// standalone Markdown files. If not present, `playground_url` is used. + pub markdown_playground_url: Option, +} + +impl Options { + /// Parses the given command-line for options. If an error message or other early-return has + /// been printed, returns `Err` with the exit code. + pub fn from_matches(matches: &getopts::Matches) -> Result { + // Check for unstable options. + nightly_options::check_nightly_options(&matches, &opts()); + + if matches.opt_present("h") || matches.opt_present("help") { + ::usage("rustdoc"); + return Err(0); + } else if matches.opt_present("version") { + rustc_driver::version("rustdoc", &matches); + return Err(0); + } + + if matches.opt_strs("passes") == ["list"] { + println!("Available passes for running rustdoc:"); + for pass in passes::PASSES { + println!("{:>20} - {}", pass.name(), pass.description()); + } + println!("\nDefault passes for rustdoc:"); + for &name in passes::DEFAULT_PASSES { + println!("{:>20}", name); + } + println!("\nPasses run with `--document-private-items`:"); + for &name in passes::DEFAULT_PRIVATE_PASSES { + println!("{:>20}", name); + } + return Err(0); + } + + let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) { + Some("auto") => ColorConfig::Auto, + Some("always") => ColorConfig::Always, + Some("never") => ColorConfig::Never, + None => ColorConfig::Auto, + Some(arg) => { + early_error(ErrorOutputType::default(), + &format!("argument for --color must be `auto`, `always` or `never` \ + (instead was `{}`)", arg)); + } + }; + let error_format = match matches.opt_str("error-format").as_ref().map(|s| &s[..]) { + Some("human") => ErrorOutputType::HumanReadable(color), + Some("json") => ErrorOutputType::Json(false), + Some("pretty-json") => ErrorOutputType::Json(true), + Some("short") => ErrorOutputType::Short(color), + None => ErrorOutputType::HumanReadable(color), + Some(arg) => { + early_error(ErrorOutputType::default(), + &format!("argument for --error-format must be `human`, `json` or \ + `short` (instead was `{}`)", arg)); + } + }; + + let codegen_options = build_codegen_options(matches, error_format); + let debugging_options = build_debugging_options(matches, error_format); + + let diag = new_handler(error_format, + None, + debugging_options.treat_err_as_bug, + debugging_options.ui_testing); + + // check for deprecated options + check_deprecated_options(&matches, &diag); + + let to_check = matches.opt_strs("theme-checker"); + if !to_check.is_empty() { + let paths = theme::load_css_paths(include_bytes!("html/static/themes/light.css")); + let mut errors = 0; + + println!("rustdoc: [theme-checker] Starting tests!"); + for theme_file in to_check.iter() { + print!(" - Checking \"{}\"...", theme_file); + let (success, differences) = theme::test_theme_against(theme_file, &paths, &diag); + if !differences.is_empty() || !success { + println!(" FAILED"); + errors += 1; + if !differences.is_empty() { + println!("{}", differences.join("\n")); + } + } else { + println!(" OK"); + } + } + if errors != 0 { + return Err(1); + } + return Err(0); + } + + if matches.free.is_empty() { + diag.struct_err("missing file operand").emit(); + return Err(1); + } + if matches.free.len() > 1 { + diag.struct_err("too many file operands").emit(); + return Err(1); + } + let input = PathBuf::from(&matches.free[0]); + + let mut libs = SearchPaths::new(); + for s in &matches.opt_strs("L") { + libs.add_path(s, error_format); + } + let externs = match parse_externs(&matches) { + Ok(ex) => ex, + Err(err) => { + diag.struct_err(&err).emit(); + return Err(1); + } + }; + let extern_html_root_urls = match parse_extern_html_roots(&matches) { + Ok(ex) => ex, + Err(err) => { + diag.struct_err(err).emit(); + return Err(1); + } + }; + + let test_args = matches.opt_strs("test-args"); + let test_args: Vec = test_args.iter() + .flat_map(|s| s.split_whitespace()) + .map(|s| s.to_string()) + .collect(); + + let should_test = matches.opt_present("test"); + + let output = matches.opt_str("o") + .map(|s| PathBuf::from(&s)) + .unwrap_or_else(|| PathBuf::from("doc")); + let mut cfgs = matches.opt_strs("cfg"); + cfgs.push("rustdoc".to_string()); + + let extension_css = matches.opt_str("e").map(|s| PathBuf::from(&s)); + + if let Some(ref p) = extension_css { + if !p.is_file() { + diag.struct_err("option --extend-css argument must be a file").emit(); + return Err(1); + } + } + + let mut themes = Vec::new(); + if matches.opt_present("themes") { + let paths = theme::load_css_paths(include_bytes!("html/static/themes/light.css")); + + for (theme_file, theme_s) in matches.opt_strs("themes") + .iter() + .map(|s| (PathBuf::from(&s), s.to_owned())) { + if !theme_file.is_file() { + diag.struct_err("option --themes arguments must all be files").emit(); + return Err(1); + } + let (success, ret) = theme::test_theme_against(&theme_file, &paths, &diag); + if !success || !ret.is_empty() { + diag.struct_err(&format!("invalid theme: \"{}\"", theme_s)) + .help("check what's wrong with the --theme-checker option") + .emit(); + return Err(1); + } + themes.push(theme_file); + } + } + + let mut id_map = html::markdown::IdMap::new(); + id_map.populate(html::render::initial_ids()); + let external_html = match ExternalHtml::load( + &matches.opt_strs("html-in-header"), + &matches.opt_strs("html-before-content"), + &matches.opt_strs("html-after-content"), + &matches.opt_strs("markdown-before-content"), + &matches.opt_strs("markdown-after-content"), &diag, &mut id_map) { + Some(eh) => eh, + None => return Err(3), + }; + + let edition = matches.opt_str("edition").unwrap_or("2015".to_string()); + let edition = match edition.parse() { + Ok(e) => e, + Err(_) => { + diag.struct_err("could not parse edition").emit(); + return Err(1); + } + }; + + match matches.opt_str("w").as_ref().map(|s| &**s) { + Some("html") | None => {} + Some(s) => { + diag.struct_err(&format!("unknown output format: {}", s)).emit(); + return Err(1); + } + } + + let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s)); + if let Some(ref index_page) = index_page { + if !index_page.is_file() { + diag.struct_err("option `--index-page` argument must be a file").emit(); + return Err(1); + } + } + + let target = matches.opt_str("target").map(|target| { + if target.ends_with(".json") { + TargetTriple::TargetPath(PathBuf::from(target)) + } else { + TargetTriple::TargetTriple(target) + } + }); + + let default_passes = if matches.opt_present("no-defaults") { + passes::DefaultPassOption::None + } else if matches.opt_present("document-private-items") { + passes::DefaultPassOption::Private + } else { + passes::DefaultPassOption::Default + }; + let manual_passes = matches.opt_strs("passes"); + + let crate_name = matches.opt_str("crate-name"); + let playground_url = matches.opt_str("playground-url"); + let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from); + let display_warnings = matches.opt_present("display-warnings"); + let linker = matches.opt_str("linker").map(PathBuf::from); + let sort_modules_alphabetically = !matches.opt_present("sort-modules-by-appearance"); + let resource_suffix = matches.opt_str("resource-suffix").unwrap_or_default(); + let enable_minification = !matches.opt_present("disable-minification"); + let markdown_no_toc = matches.opt_present("markdown-no-toc"); + let markdown_css = matches.opt_strs("markdown-css"); + let markdown_playground_url = matches.opt_str("markdown-playground-url"); + let crate_version = matches.opt_str("crate-version"); + let enable_index_page = matches.opt_present("enable-index-page") || index_page.is_some(); + + let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(matches, error_format); + + Ok(Options { + input, + output, + crate_name, + error_format, + libs, + externs, + cfgs, + codegen_options, + debugging_options, + target, + edition, + maybe_sysroot, + linker, + lint_opts, + describe_lints, + lint_cap, + should_test, + test_args, + default_passes, + manual_passes, + display_warnings, + id_map, + external_html, + playground_url, + crate_version, + sort_modules_alphabetically, + themes, + extension_css, + extern_html_root_urls, + resource_suffix, + enable_minification, + enable_index_page, + index_page, + markdown_no_toc, + markdown_css, + markdown_playground_url, + }) + } + + /// Returns whether the file given as `self.input` is a Markdown file. + pub fn markdown_input(&self) -> bool { + self.input.extension() + .map_or(false, |e| e == "md" || e == "markdown") + } +} + +/// Prints deprecation warnings for deprecated options +fn check_deprecated_options(matches: &getopts::Matches, diag: &errors::Handler) { + let deprecated_flags = [ + "input-format", + "output-format", + "no-defaults", + "passes", + ]; + + for flag in deprecated_flags.into_iter() { + if matches.opt_present(flag) { + let mut err = diag.struct_warn(&format!("the '{}' flag is considered deprecated", + flag)); + err.warn("please see https://github.com/rust-lang/rust/issues/44136"); + + if *flag == "no-defaults" { + err.help("you may want to use --document-private-items"); + } + + err.emit(); + } + } +} + +/// Extracts `--extern-html-root-url` arguments from `matches` and returns a map of crate names to +/// the given URLs. If an `--extern-html-root-url` argument was ill-formed, returns an error +/// describing the issue. +fn parse_extern_html_roots(matches: &getopts::Matches) + -> Result, &'static str> +{ + let mut externs = BTreeMap::new(); + for arg in &matches.opt_strs("extern-html-root-url") { + let mut parts = arg.splitn(2, '='); + let name = parts.next().ok_or("--extern-html-root-url must not be empty")?; + let url = parts.next().ok_or("--extern-html-root-url must be of the form name=url")?; + externs.insert(name.to_string(), url.to_string()); + } + + Ok(externs) +} + +/// Extracts `--extern CRATE=PATH` arguments from `matches` and +/// returns a map mapping crate names to their paths or else an +/// error message. +// FIXME(eddyb) This shouldn't be duplicated with `rustc::session`. +fn parse_externs(matches: &getopts::Matches) -> Result { + let mut externs: BTreeMap<_, BTreeSet<_>> = BTreeMap::new(); + for arg in &matches.opt_strs("extern") { + let mut parts = arg.splitn(2, '='); + let name = parts.next().ok_or("--extern value must not be empty".to_string())?; + let location = parts.next().map(|s| s.to_string()); + if location.is_none() && !nightly_options::is_unstable_enabled(matches) { + return Err("the `-Z unstable-options` flag must also be passed to \ + enable `--extern crate_name` without `=path`".to_string()); + } + let name = name.to_string(); + externs.entry(name).or_default().insert(location); + } + Ok(Externs::new(externs)) +} diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index e1cb96edd48..a9ed5386f61 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -53,22 +53,17 @@ extern crate serialize as rustc_serialize; // used by deriving -use errors::ColorConfig; - -use std::collections::{BTreeMap, BTreeSet}; use std::default::Default; use std::env; use std::panic; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use std::process; use std::sync::mpsc::channel; use syntax::edition::Edition; -use externalfiles::ExternalHtml; use rustc::session::{early_warn, early_error}; use rustc::session::search_paths::SearchPaths; use rustc::session::config::{ErrorOutputType, RustcOptGroup, Externs, CodegenOptions}; -use rustc::session::config::{nightly_options, build_codegen_options}; use rustc_target::spec::TargetTriple; use rustc::session::config::get_cmd_lint_options; @@ -76,6 +71,7 @@ mod externalfiles; mod clean; +mod config; mod core; mod doctree; mod fold; @@ -367,250 +363,55 @@ fn main_args(args: &[String]) -> isize { early_error(ErrorOutputType::default(), &err.to_string()); } }; - // Check for unstable options. - nightly_options::check_nightly_options(&matches, &opts()); - - if matches.opt_present("h") || matches.opt_present("help") { - usage("rustdoc"); - return 0; - } else if matches.opt_present("version") { - rustc_driver::version("rustdoc", &matches); - return 0; - } - - if matches.opt_strs("passes") == ["list"] { - println!("Available passes for running rustdoc:"); - for pass in passes::PASSES { - println!("{:>20} - {}", pass.name(), pass.description()); - } - println!("\nDefault passes for rustdoc:"); - for &name in passes::DEFAULT_PASSES { - println!("{:>20}", name); - } - println!("\nPasses run with `--document-private-items`:"); - for &name in passes::DEFAULT_PRIVATE_PASSES { - println!("{:>20}", name); - } - return 0; - } - - let color = match matches.opt_str("color").as_ref().map(|s| &s[..]) { - Some("auto") => ColorConfig::Auto, - Some("always") => ColorConfig::Always, - Some("never") => ColorConfig::Never, - None => ColorConfig::Auto, - Some(arg) => { - early_error(ErrorOutputType::default(), - &format!("argument for --color must be `auto`, `always` or `never` \ - (instead was `{}`)", arg)); - } - }; - let error_format = match matches.opt_str("error-format").as_ref().map(|s| &s[..]) { - Some("human") => ErrorOutputType::HumanReadable(color), - Some("json") => ErrorOutputType::Json(false), - Some("pretty-json") => ErrorOutputType::Json(true), - Some("short") => ErrorOutputType::Short(color), - None => ErrorOutputType::HumanReadable(color), - Some(arg) => { - early_error(ErrorOutputType::default(), - &format!("argument for --error-format must be `human`, `json` or \ - `short` (instead was `{}`)", arg)); - } + let options = match config::Options::from_matches(&matches) { + Ok(opts) => opts, + Err(code) => return code, }; - let treat_err_as_bug = matches.opt_strs("Z").iter().any(|x| { - *x == "treat-err-as-bug" - }); - let ui_testing = matches.opt_strs("Z").iter().any(|x| { - *x == "ui-testing" - }); - - let diag = core::new_handler(error_format, None, treat_err_as_bug, ui_testing); - - // check for deprecated options - check_deprecated_options(&matches, &diag); - - let to_check = matches.opt_strs("theme-checker"); - if !to_check.is_empty() { - let paths = theme::load_css_paths(include_bytes!("html/static/themes/light.css")); - let mut errors = 0; - - println!("rustdoc: [theme-checker] Starting tests!"); - for theme_file in to_check.iter() { - print!(" - Checking \"{}\"...", theme_file); - let (success, differences) = theme::test_theme_against(theme_file, &paths, &diag); - if !differences.is_empty() || !success { - println!(" FAILED"); - errors += 1; - if !differences.is_empty() { - println!("{}", differences.join("\n")); - } - } else { - println!(" OK"); - } - } - if errors != 0 { - return 1; - } - return 0; - } - - if matches.free.is_empty() { - diag.struct_err("missing file operand").emit(); - return 1; - } - if matches.free.len() > 1 { - diag.struct_err("too many file operands").emit(); - return 1; - } - let input = matches.free[0].clone(); - - let mut libs = SearchPaths::new(); - for s in &matches.opt_strs("L") { - libs.add_path(s, error_format); - } - let externs = match parse_externs(&matches) { - Ok(ex) => ex, - Err(err) => { - diag.struct_err(&err).emit(); - return 1; - } - }; - let extern_urls = match parse_extern_html_roots(&matches) { - Ok(ex) => ex, - Err(err) => { - diag.struct_err(err).emit(); - return 1; - } - }; - - let test_args = matches.opt_strs("test-args"); - let test_args: Vec = test_args.iter() - .flat_map(|s| s.split_whitespace()) - .map(|s| s.to_string()) - .collect(); - let should_test = matches.opt_present("test"); - let markdown_input = Path::new(&input).extension() - .map_or(false, |e| e == "md" || e == "markdown"); + let diag = core::new_handler(options.error_format, + None, + options.debugging_options.treat_err_as_bug, + options.debugging_options.ui_testing); - let output = matches.opt_str("o").map(|s| PathBuf::from(&s)); - let css_file_extension = matches.opt_str("e").map(|s| PathBuf::from(&s)); - let mut cfgs = matches.opt_strs("cfg"); - cfgs.push("rustdoc".to_string()); - - if let Some(ref p) = css_file_extension { - if !p.is_file() { - diag.struct_err("option --extend-css argument must be a file").emit(); - return 1; - } - } - - let mut themes = Vec::new(); - if matches.opt_present("themes") { - let paths = theme::load_css_paths(include_bytes!("html/static/themes/light.css")); - - for (theme_file, theme_s) in matches.opt_strs("themes") - .iter() - .map(|s| (PathBuf::from(&s), s.to_owned())) { - if !theme_file.is_file() { - diag.struct_err("option --themes arguments must all be files").emit(); - return 1; - } - let (success, ret) = theme::test_theme_against(&theme_file, &paths, &diag); - if !success || !ret.is_empty() { - diag.struct_err(&format!("invalid theme: \"{}\"", theme_s)) - .help("check what's wrong with the --theme-checker option") - .emit(); - return 1; - } - themes.push(theme_file); - } - } - - let mut id_map = html::markdown::IdMap::new(); - id_map.populate(html::render::initial_ids()); - let external_html = match ExternalHtml::load( - &matches.opt_strs("html-in-header"), - &matches.opt_strs("html-before-content"), - &matches.opt_strs("html-after-content"), - &matches.opt_strs("markdown-before-content"), - &matches.opt_strs("markdown-after-content"), &diag, &mut id_map) { - Some(eh) => eh, - None => return 3, - }; - let crate_name = matches.opt_str("crate-name"); - let playground_url = matches.opt_str("playground-url"); - let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from); - let display_warnings = matches.opt_present("display-warnings"); - let linker = matches.opt_str("linker").map(PathBuf::from); - let sort_modules_alphabetically = !matches.opt_present("sort-modules-by-appearance"); - let resource_suffix = matches.opt_str("resource-suffix"); - let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s)); - let enable_index_page = matches.opt_present("enable-index-page") || index_page.is_some(); - let enable_minification = !matches.opt_present("disable-minification"); - - let edition = matches.opt_str("edition").unwrap_or("2015".to_string()); - let edition = match edition.parse() { - Ok(e) => e, - Err(_) => { - diag.struct_err("could not parse edition").emit(); - return 1; - } - }; - if let Some(ref index_page) = index_page { - if !index_page.is_file() { - diag.struct_err("option `--index-page` argument must be a file").emit(); - return 1; - } - } - - let cg = build_codegen_options(&matches, ErrorOutputType::default()); - - match (should_test, markdown_input) { + match (options.should_test, options.markdown_input()) { (true, true) => { - return markdown::test(&input, cfgs, libs, externs, test_args, maybe_sysroot, - display_warnings, linker, edition, cg, &diag) + return markdown::test(&options.input, options.cfgs, options.libs, options.externs, + options.test_args, options.maybe_sysroot, + options.display_warnings, options.linker, options.edition, + options.codegen_options, &diag) } (true, false) => { - return test::run(Path::new(&input), cfgs, libs, externs, test_args, crate_name, - maybe_sysroot, display_warnings, linker, edition, cg) + return test::run(&options.input, options.cfgs, options.libs, options.externs, + options.test_args, options.crate_name, options.maybe_sysroot, + options.display_warnings, options.linker, options.edition, + options.codegen_options) } - (false, true) => return markdown::render(Path::new(&input), - output.unwrap_or(PathBuf::from("doc")), - &matches, &external_html, - !matches.opt_present("markdown-no-toc"), &diag), + (false, true) => return markdown::render(&options.input, options.output, + &matches, + &options.external_html, + !options.markdown_no_toc, &diag), (false, false) => {} } - let output_format = matches.opt_str("w"); - - let res = acquire_input(PathBuf::from(input), externs, edition, cg, matches, error_format, + let res = acquire_input(options.input.clone(), options.externs.clone(), options.edition, + options.codegen_options.clone(), matches, options.error_format, move |out, matches| { let Output { krate, passes, renderinfo } = out; - let diag = core::new_handler(error_format, None, treat_err_as_bug, ui_testing); info!("going to format"); - match output_format.as_ref().map(|s| &**s) { - Some("html") | None => { - html::render::run(krate, extern_urls, &external_html, playground_url, - output.unwrap_or(PathBuf::from("doc")), - resource_suffix.unwrap_or(String::new()), - passes.into_iter().collect(), - css_file_extension, - renderinfo, - sort_modules_alphabetically, - themes, - enable_minification, id_map, - enable_index_page, index_page, - &matches, - &diag) - .expect("failed to generate documentation"); - 0 - } - Some(s) => { - diag.struct_err(&format!("unknown output format: {}", s)).emit(); - 1 - } - } + html::render::run(krate, options.extern_html_root_urls, &options.external_html, options.playground_url, + options.output, + options.resource_suffix, + passes.into_iter().collect(), + options.extension_css, + renderinfo, + options.sort_modules_alphabetically, + options.themes, + options.enable_minification, options.id_map, + options.enable_index_page, options.index_page, + &matches, + &diag) + .expect("failed to generate documentation"); + 0 }); res.unwrap_or_else(|s| { diag.struct_err(&format!("input error: {}", s)).emit(); @@ -636,43 +437,6 @@ fn acquire_input(input: PathBuf, } } -/// Extracts `--extern CRATE=PATH` arguments from `matches` and -/// returns a map mapping crate names to their paths or else an -/// error message. -// FIXME(eddyb) This shouldn't be duplicated with `rustc::session`. -fn parse_externs(matches: &getopts::Matches) -> Result { - let mut externs: BTreeMap<_, BTreeSet<_>> = BTreeMap::new(); - for arg in &matches.opt_strs("extern") { - let mut parts = arg.splitn(2, '='); - let name = parts.next().ok_or("--extern value must not be empty".to_string())?; - let location = parts.next().map(|s| s.to_string()); - if location.is_none() && !nightly_options::is_unstable_enabled(matches) { - return Err("the `-Z unstable-options` flag must also be passed to \ - enable `--extern crate_name` without `=path`".to_string()); - } - let name = name.to_string(); - externs.entry(name).or_default().insert(location); - } - Ok(Externs::new(externs)) -} - -/// Extracts `--extern-html-root-url` arguments from `matches` and returns a map of crate names to -/// the given URLs. If an `--extern-html-root-url` argument was ill-formed, returns an error -/// describing the issue. -fn parse_extern_html_roots(matches: &getopts::Matches) - -> Result, &'static str> -{ - let mut externs = BTreeMap::new(); - for arg in &matches.opt_strs("extern-html-root-url") { - let mut parts = arg.splitn(2, '='); - let name = parts.next().ok_or("--extern-html-root-url must not be empty")?; - let url = parts.next().ok_or("--extern-html-root-url must be of the form name=url")?; - externs.insert(name.to_string(), url.to_string()); - } - - Ok(externs) -} - /// Interprets the input file as a rust source file, passing it through the /// compiler all the way through the analysis passes. The rustdoc output is then /// generated from the cleaned AST of the crate. @@ -792,27 +556,3 @@ fn rust_input(cratefile: PathBuf, Err(_) => panic::resume_unwind(Box::new(errors::FatalErrorMarker)), } } - -/// Prints deprecation warnings for deprecated options -fn check_deprecated_options(matches: &getopts::Matches, diag: &errors::Handler) { - let deprecated_flags = [ - "input-format", - "output-format", - "no-defaults", - "passes", - ]; - - for flag in deprecated_flags.into_iter() { - if matches.opt_present(flag) { - let mut err = diag.struct_warn(&format!("the '{}' flag is considered deprecated", - flag)); - err.warn("please see https://github.com/rust-lang/rust/issues/44136"); - - if *flag == "no-defaults" { - err.help("you may want to use --document-private-items"); - } - - err.emit(); - } - } -} diff --git a/src/librustdoc/markdown.rs b/src/librustdoc/markdown.rs index 0084c0f8592..d8243bb3586 100644 --- a/src/librustdoc/markdown.rs +++ b/src/librustdoc/markdown.rs @@ -140,7 +140,7 @@ pub fn render(input: &Path, mut output: PathBuf, matches: &getopts::Matches, } /// Run any tests/code examples in the markdown file `input`. -pub fn test(input: &str, cfgs: Vec, libs: SearchPaths, externs: Externs, +pub fn test(input: &Path, cfgs: Vec, libs: SearchPaths, externs: Externs, mut test_args: Vec, maybe_sysroot: Option, display_warnings: bool, linker: Option, edition: Edition, cg: CodegenOptions, diag: &errors::Handler) -> isize { @@ -153,7 +153,7 @@ pub fn test(input: &str, cfgs: Vec, libs: SearchPaths, externs: Externs, let mut opts = TestOptions::default(); opts.no_crate_inject = true; opts.display_warnings = display_warnings; - let mut collector = Collector::new(input.to_owned(), cfgs, libs, cg, externs, + let mut collector = Collector::new(input.display().to_string(), cfgs, libs, cg, externs, true, opts, maybe_sysroot, None, Some(PathBuf::from(input)), linker, edition); -- 2.44.0