rustdoc: remove unchecked_claim_error_was_emitted call in main_args.

`main_args` calls `from_matches`, which does lots of initialization. If
anything goes wrong, `from_matches` emits an error message and returns
`Err(1)` (or `Err(3)`). `main_args` then turns the `Err(1)` into
`Err(ErrorGuaranteed)`, because that's what `catch_with_exit_code`
requires on error. But `catch_with_exit_code` doesn't do anything with
the `ErrorGuaranteed`, it just exits with `EXIT_FAILURE`.

We can avoid the creation of the `ErrorGuaranteed` (which requires
an undesirable `unchecked_claim_error_was_emitted` call), by changing
`from_matches` to instead eagerly abort if anything goes wrong. The
behaviour from the user's point of view is the same: an early abort with
an `EXIT_FAILURE` exit code.

And we can also simplify `from_matches` to return an `Option` instead of
a `Result`:
- Old `Err(0)` case --> `None`
- Old `Err(_)` case --> fatal error.

This requires similar changes to `ScrapeExamplesOptions::new` and
`load_call_locations`.
This commit is contained in:
Nicholas Nethercote 2024-02-07 09:01:49 +11:00
parent e6794ddfb0
commit 83adf883a2
3 changed files with 53 additions and 101 deletions

View File

@ -323,20 +323,20 @@ impl Options {
early_dcx: &mut EarlyDiagCtxt, early_dcx: &mut EarlyDiagCtxt,
matches: &getopts::Matches, matches: &getopts::Matches,
args: Vec<String>, args: Vec<String>,
) -> Result<(Options, RenderOptions), i32> { ) -> Option<(Options, RenderOptions)> {
// Check for unstable options. // Check for unstable options.
nightly_options::check_nightly_options(early_dcx, matches, &opts()); nightly_options::check_nightly_options(early_dcx, matches, &opts());
if args.is_empty() || matches.opt_present("h") || matches.opt_present("help") { if args.is_empty() || matches.opt_present("h") || matches.opt_present("help") {
crate::usage("rustdoc"); crate::usage("rustdoc");
return Err(0); return None;
} else if matches.opt_present("version") { } else if matches.opt_present("version") {
rustc_driver::version!(&early_dcx, "rustdoc", matches); rustc_driver::version!(&early_dcx, "rustdoc", matches);
return Err(0); return None;
} }
if rustc_driver::describe_flag_categories(early_dcx, &matches) { if rustc_driver::describe_flag_categories(early_dcx, &matches) {
return Err(0); return None;
} }
let color = config::parse_color(early_dcx, matches); let color = config::parse_color(early_dcx, matches);
@ -382,7 +382,7 @@ impl Options {
} }
} }
return Err(0); return None;
} }
let mut emit = Vec::new(); let mut emit = Vec::new();
@ -390,10 +390,7 @@ impl Options {
for kind in list.split(',') { for kind in list.split(',') {
match kind.parse() { match kind.parse() {
Ok(kind) => emit.push(kind), Ok(kind) => emit.push(kind),
Err(()) => { Err(()) => dcx.fatal(format!("unrecognized emission type: {kind}")),
dcx.err(format!("unrecognized emission type: {kind}"));
return Err(1);
}
} }
} }
} }
@ -403,7 +400,7 @@ impl Options {
&& !matches.opt_present("show-coverage") && !matches.opt_present("show-coverage")
&& !nightly_options::is_unstable_enabled(matches) && !nightly_options::is_unstable_enabled(matches)
{ {
early_dcx.early_fatal( dcx.fatal(
"the -Z unstable-options flag must be passed to enable --output-format for documentation generation (see https://github.com/rust-lang/rust/issues/76578)", "the -Z unstable-options flag must be passed to enable --output-format for documentation generation (see https://github.com/rust-lang/rust/issues/76578)",
); );
} }
@ -420,10 +417,7 @@ impl Options {
} }
let paths = match theme::load_css_paths(content) { let paths = match theme::load_css_paths(content) {
Ok(p) => p, Ok(p) => p,
Err(e) => { Err(e) => dcx.fatal(e),
dcx.err(e);
return Err(1);
}
}; };
let mut errors = 0; let mut errors = 0;
@ -442,9 +436,9 @@ impl Options {
} }
} }
if errors != 0 { if errors != 0 {
return Err(1); dcx.fatal("[check-theme] one or more tests failed");
} }
return Err(0); return None;
} }
let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(early_dcx, matches); let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(early_dcx, matches);
@ -452,11 +446,9 @@ impl Options {
let input = PathBuf::from(if describe_lints { let input = PathBuf::from(if describe_lints {
"" // dummy, this won't be used "" // dummy, this won't be used
} else if matches.free.is_empty() { } else if matches.free.is_empty() {
dcx.err("missing file operand"); dcx.fatal("missing file operand");
return Err(1);
} else if matches.free.len() > 1 { } else if matches.free.len() > 1 {
dcx.err("too many file operands"); dcx.fatal("too many file operands");
return Err(1);
} else { } else {
&matches.free[0] &matches.free[0]
}); });
@ -466,10 +458,7 @@ impl Options {
let externs = parse_externs(early_dcx, matches, &unstable_opts); let externs = parse_externs(early_dcx, matches, &unstable_opts);
let extern_html_root_urls = match parse_extern_html_roots(matches) { let extern_html_root_urls = match parse_extern_html_roots(matches) {
Ok(ex) => ex, Ok(ex) => ex,
Err(err) => { Err(err) => dcx.fatal(err),
dcx.err(err);
return Err(1);
}
}; };
let default_settings: Vec<Vec<(String, String)>> = vec![ let default_settings: Vec<Vec<(String, String)>> = vec![
@ -526,16 +515,14 @@ impl Options {
let no_run = matches.opt_present("no-run"); let no_run = matches.opt_present("no-run");
if !should_test && no_run { if !should_test && no_run {
dcx.err("the `--test` flag must be passed to enable `--no-run`"); dcx.fatal("the `--test` flag must be passed to enable `--no-run`");
return Err(1);
} }
let out_dir = matches.opt_str("out-dir").map(|s| PathBuf::from(&s)); let out_dir = matches.opt_str("out-dir").map(|s| PathBuf::from(&s));
let output = matches.opt_str("output").map(|s| PathBuf::from(&s)); let output = matches.opt_str("output").map(|s| PathBuf::from(&s));
let output = match (out_dir, output) { let output = match (out_dir, output) {
(Some(_), Some(_)) => { (Some(_), Some(_)) => {
dcx.err("cannot use both 'out-dir' and 'output' at once"); dcx.fatal("cannot use both 'out-dir' and 'output' at once");
return Err(1);
} }
(Some(out_dir), None) => out_dir, (Some(out_dir), None) => out_dir,
(None, Some(output)) => output, (None, Some(output)) => output,
@ -549,8 +536,7 @@ impl Options {
if let Some(ref p) = extension_css { if let Some(ref p) = extension_css {
if !p.is_file() { if !p.is_file() {
dcx.err("option --extend-css argument must be a file"); dcx.fatal("option --extend-css argument must be a file");
return Err(1);
} }
} }
@ -566,31 +552,25 @@ impl Options {
} }
let paths = match theme::load_css_paths(content) { let paths = match theme::load_css_paths(content) {
Ok(p) => p, Ok(p) => p,
Err(e) => { Err(e) => dcx.fatal(e),
dcx.err(e);
return Err(1);
}
}; };
for (theme_file, theme_s) in for (theme_file, theme_s) in
matches.opt_strs("theme").iter().map(|s| (PathBuf::from(&s), s.to_owned())) matches.opt_strs("theme").iter().map(|s| (PathBuf::from(&s), s.to_owned()))
{ {
if !theme_file.is_file() { if !theme_file.is_file() {
dcx.struct_err(format!("invalid argument: \"{theme_s}\"")) dcx.struct_fatal(format!("invalid argument: \"{theme_s}\""))
.with_help("arguments to --theme must be files") .with_help("arguments to --theme must be files")
.emit(); .emit();
return Err(1);
} }
if theme_file.extension() != Some(OsStr::new("css")) { if theme_file.extension() != Some(OsStr::new("css")) {
dcx.struct_err(format!("invalid argument: \"{theme_s}\"")) dcx.struct_fatal(format!("invalid argument: \"{theme_s}\""))
.with_help("arguments to --theme must have a .css extension") .with_help("arguments to --theme must have a .css extension")
.emit(); .emit();
return Err(1);
} }
let (success, ret) = theme::test_theme_against(&theme_file, &paths, &dcx); let (success, ret) = theme::test_theme_against(&theme_file, &paths, &dcx);
if !success { if !success {
dcx.err(format!("error loading theme file: \"{theme_s}\"")); dcx.fatal(format!("error loading theme file: \"{theme_s}\""));
return Err(1);
} else if !ret.is_empty() { } else if !ret.is_empty() {
dcx.struct_warn(format!( dcx.struct_warn(format!(
"theme file \"{theme_s}\" is missing CSS rules from the default theme", "theme file \"{theme_s}\" is missing CSS rules from the default theme",
@ -620,22 +600,18 @@ impl Options {
edition, edition,
&None, &None,
) else { ) else {
return Err(3); dcx.fatal("`ExternalHtml::load` failed");
}; };
match matches.opt_str("r").as_deref() { match matches.opt_str("r").as_deref() {
Some("rust") | None => {} Some("rust") | None => {}
Some(s) => { Some(s) => dcx.fatal(format!("unknown input format: {s}")),
dcx.err(format!("unknown input format: {s}"));
return Err(1);
}
} }
let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s)); let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s));
if let Some(ref index_page) = index_page { if let Some(ref index_page) = index_page {
if !index_page.is_file() { if !index_page.is_file() {
dcx.err("option `--index-page` argument must be a file"); dcx.fatal("option `--index-page` argument must be a file");
return Err(1);
} }
} }
@ -646,8 +622,7 @@ impl Options {
let crate_types = match parse_crate_types_from_list(matches.opt_strs("crate-type")) { let crate_types = match parse_crate_types_from_list(matches.opt_strs("crate-type")) {
Ok(types) => types, Ok(types) => types,
Err(e) => { Err(e) => {
dcx.err(format!("unknown crate type: {e}")); dcx.fatal(format!("unknown crate type: {e}"));
return Err(1);
} }
}; };
@ -655,18 +630,13 @@ impl Options {
Some(s) => match OutputFormat::try_from(s.as_str()) { Some(s) => match OutputFormat::try_from(s.as_str()) {
Ok(out_fmt) => { Ok(out_fmt) => {
if !out_fmt.is_json() && show_coverage { if !out_fmt.is_json() && show_coverage {
dcx.struct_err( dcx.fatal(
"html output format isn't supported for the --show-coverage option", "html output format isn't supported for the --show-coverage option",
) );
.emit();
return Err(1);
} }
out_fmt out_fmt
} }
Err(e) => { Err(e) => dcx.fatal(e),
dcx.err(e);
return Err(1);
}
}, },
None => OutputFormat::default(), None => OutputFormat::default(),
}; };
@ -709,16 +679,14 @@ impl Options {
let html_no_source = matches.opt_present("html-no-source"); let html_no_source = matches.opt_present("html-no-source");
if generate_link_to_definition && (show_coverage || output_format != OutputFormat::Html) { if generate_link_to_definition && (show_coverage || output_format != OutputFormat::Html) {
dcx.struct_err( dcx.fatal(
"--generate-link-to-definition option can only be used with HTML output format", "--generate-link-to-definition option can only be used with HTML output format",
) );
.emit();
return Err(1);
} }
let scrape_examples_options = ScrapeExamplesOptions::new(matches, &dcx)?; let scrape_examples_options = ScrapeExamplesOptions::new(matches, &dcx);
let with_examples = matches.opt_strs("with-examples"); let with_examples = matches.opt_strs("with-examples");
let call_locations = crate::scrape_examples::load_call_locations(with_examples, &dcx)?; let call_locations = crate::scrape_examples::load_call_locations(with_examples, &dcx);
let unstable_features = let unstable_features =
rustc_feature::UnstableFeatures::from_environment(crate_name.as_deref()); rustc_feature::UnstableFeatures::from_environment(crate_name.as_deref());
@ -793,7 +761,7 @@ impl Options {
no_emit_shared: false, no_emit_shared: false,
html_no_source, html_no_source,
}; };
Ok((options, render_options)) Some((options, render_options))
} }
/// Returns `true` if the file given as `self.input` is a Markdown file. /// Returns `true` if the file given as `self.input` is a Markdown file.

View File

@ -720,15 +720,8 @@ fn main_args(
// Note that we discard any distinction between different non-zero exit // Note that we discard any distinction between different non-zero exit
// codes from `from_matches` here. // codes from `from_matches` here.
let (options, render_options) = match config::Options::from_matches(early_dcx, &matches, args) { let (options, render_options) = match config::Options::from_matches(early_dcx, &matches, args) {
Ok(opts) => opts, Some(opts) => opts,
Err(code) => { None => return Ok(()),
return if code == 0 {
Ok(())
} else {
#[allow(deprecated)]
Err(ErrorGuaranteed::unchecked_claim_error_was_emitted())
};
}
}; };
let diag = let diag =

View File

@ -38,28 +38,23 @@ pub(crate) struct ScrapeExamplesOptions {
} }
impl ScrapeExamplesOptions { impl ScrapeExamplesOptions {
pub(crate) fn new( pub(crate) fn new(matches: &getopts::Matches, dcx: &rustc_errors::DiagCtxt) -> Option<Self> {
matches: &getopts::Matches,
dcx: &rustc_errors::DiagCtxt,
) -> Result<Option<Self>, i32> {
let output_path = matches.opt_str("scrape-examples-output-path"); let output_path = matches.opt_str("scrape-examples-output-path");
let target_crates = matches.opt_strs("scrape-examples-target-crate"); let target_crates = matches.opt_strs("scrape-examples-target-crate");
let scrape_tests = matches.opt_present("scrape-tests"); let scrape_tests = matches.opt_present("scrape-tests");
match (output_path, !target_crates.is_empty(), scrape_tests) { match (output_path, !target_crates.is_empty(), scrape_tests) {
(Some(output_path), true, _) => Ok(Some(ScrapeExamplesOptions { (Some(output_path), true, _) => Some(ScrapeExamplesOptions {
output_path: PathBuf::from(output_path), output_path: PathBuf::from(output_path),
target_crates, target_crates,
scrape_tests, scrape_tests,
})), }),
(Some(_), false, _) | (None, true, _) => { (Some(_), false, _) | (None, true, _) => {
dcx.err("must use --scrape-examples-output-path and --scrape-examples-target-crate together"); dcx.fatal("must use --scrape-examples-output-path and --scrape-examples-target-crate together");
Err(1)
} }
(None, false, true) => { (None, false, true) => {
dcx.err("must use --scrape-examples-output-path and --scrape-examples-target-crate with --scrape-tests"); dcx.fatal("must use --scrape-examples-output-path and --scrape-examples-target-crate with --scrape-tests");
Err(1)
} }
(None, false, false) => Ok(None), (None, false, false) => None,
} }
} }
} }
@ -342,11 +337,13 @@ pub(crate) fn run(
pub(crate) fn load_call_locations( pub(crate) fn load_call_locations(
with_examples: Vec<String>, with_examples: Vec<String>,
dcx: &rustc_errors::DiagCtxt, dcx: &rustc_errors::DiagCtxt,
) -> Result<AllCallLocations, i32> { ) -> AllCallLocations {
let inner = || {
let mut all_calls: AllCallLocations = FxHashMap::default(); let mut all_calls: AllCallLocations = FxHashMap::default();
for path in with_examples { for path in with_examples {
let bytes = fs::read(&path).map_err(|e| format!("{e} (for path {path})"))?; let bytes = match fs::read(&path) {
Ok(bytes) => bytes,
Err(e) => dcx.fatal(format!("failed to load examples: {e}")),
};
let mut decoder = MemDecoder::new(&bytes, 0); let mut decoder = MemDecoder::new(&bytes, 0);
let calls = AllCallLocations::decode(&mut decoder); let calls = AllCallLocations::decode(&mut decoder);
@ -355,11 +352,5 @@ pub(crate) fn load_call_locations(
} }
} }
Ok(all_calls) all_calls
};
inner().map_err(|e: String| {
dcx.err(format!("failed to load examples: {e}"));
1
})
} }