Rename many EarlyDiagCtxt arguments.

This commit is contained in:
Nicholas Nethercote 2023-12-18 10:57:26 +11:00
parent f422dca3ae
commit d58e372853
10 changed files with 196 additions and 196 deletions

View file

@ -23,12 +23,12 @@ fn arg_expand(arg: String) -> Result<Vec<String>, Error> {
/// **Note:** This function doesn't interpret argument 0 in any special way. /// **Note:** This function doesn't interpret argument 0 in any special way.
/// If this function is intended to be used with command line arguments, /// If this function is intended to be used with command line arguments,
/// `argv[0]` must be removed prior to calling it manually. /// `argv[0]` must be removed prior to calling it manually.
pub fn arg_expand_all(handler: &EarlyDiagCtxt, at_args: &[String]) -> Vec<String> { pub fn arg_expand_all(early_dcx: &EarlyDiagCtxt, at_args: &[String]) -> Vec<String> {
let mut args = Vec::new(); let mut args = Vec::new();
for arg in at_args { for arg in at_args {
match arg_expand(arg.clone()) { match arg_expand(arg.clone()) {
Ok(arg) => args.extend(arg), Ok(arg) => args.extend(arg),
Err(err) => handler.early_error(format!("Failed to load argument file: {err}")), Err(err) => early_dcx.early_error(format!("Failed to load argument file: {err}")),
} }
} }
args args

View file

@ -495,7 +495,7 @@ fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<OutFileNa
// Extract input (string or file and optional path) from matches. // Extract input (string or file and optional path) from matches.
fn make_input( fn make_input(
handler: &EarlyDiagCtxt, early_dcx: &EarlyDiagCtxt,
free_matches: &[String], free_matches: &[String],
) -> Result<Option<Input>, ErrorGuaranteed> { ) -> Result<Option<Input>, ErrorGuaranteed> {
if free_matches.len() == 1 { if free_matches.len() == 1 {
@ -505,7 +505,7 @@ fn make_input(
if io::stdin().read_to_string(&mut src).is_err() { if io::stdin().read_to_string(&mut src).is_err() {
// Immediately stop compilation if there was an issue reading // Immediately stop compilation if there was an issue reading
// the input (for example if the input stream is not UTF-8). // the input (for example if the input stream is not UTF-8).
let reported = handler.early_error_no_abort( let reported = early_dcx.early_error_no_abort(
"couldn't read from stdin, as it did not contain valid UTF-8", "couldn't read from stdin, as it did not contain valid UTF-8",
); );
return Err(reported); return Err(reported);
@ -537,7 +537,7 @@ pub enum Compilation {
Continue, Continue,
} }
fn handle_explain(handler: &EarlyDiagCtxt, registry: Registry, code: &str, color: ColorConfig) { fn handle_explain(early_dcx: &EarlyDiagCtxt, registry: Registry, code: &str, color: ColorConfig) {
let upper_cased_code = code.to_ascii_uppercase(); let upper_cased_code = code.to_ascii_uppercase();
let normalised = let normalised =
if upper_cased_code.starts_with('E') { upper_cased_code } else { format!("E{code:0>4}") }; if upper_cased_code.starts_with('E') { upper_cased_code } else { format!("E{code:0>4}") };
@ -567,7 +567,7 @@ fn handle_explain(handler: &EarlyDiagCtxt, registry: Registry, code: &str, color
} }
} }
Err(InvalidErrorCode) => { Err(InvalidErrorCode) => {
handler.early_error(format!("{code} is not a valid error code")); early_dcx.early_error(format!("{code} is not a valid error code"));
} }
} }
} }
@ -669,7 +669,7 @@ fn process_rlink(sess: &Session, compiler: &interface::Compiler) {
} }
} }
fn list_metadata(handler: &EarlyDiagCtxt, sess: &Session, metadata_loader: &dyn MetadataLoader) { fn list_metadata(early_dcx: &EarlyDiagCtxt, sess: &Session, metadata_loader: &dyn MetadataLoader) {
match sess.io.input { match sess.io.input {
Input::File(ref ifile) => { Input::File(ref ifile) => {
let path = &(*ifile); let path = &(*ifile);
@ -685,13 +685,13 @@ fn list_metadata(handler: &EarlyDiagCtxt, sess: &Session, metadata_loader: &dyn
safe_println!("{}", String::from_utf8(v).unwrap()); safe_println!("{}", String::from_utf8(v).unwrap());
} }
Input::Str { .. } => { Input::Str { .. } => {
handler.early_error("cannot list metadata for stdin"); early_dcx.early_error("cannot list metadata for stdin");
} }
} }
} }
fn print_crate_info( fn print_crate_info(
handler: &EarlyDiagCtxt, early_dcx: &EarlyDiagCtxt,
codegen_backend: &dyn CodegenBackend, codegen_backend: &dyn CodegenBackend,
sess: &Session, sess: &Session,
parse_attrs: bool, parse_attrs: bool,
@ -838,7 +838,7 @@ fn print_crate_info(
.expect("unknown Apple target OS"); .expect("unknown Apple target OS");
println_info!("deployment_target={}", format!("{major}.{minor}")) println_info!("deployment_target={}", format!("{major}.{minor}"))
} else { } else {
handler early_dcx
.early_error("only Apple targets currently support deployment version info") .early_error("only Apple targets currently support deployment version info")
} }
} }
@ -869,7 +869,7 @@ pub macro version($handler: expr, $binary: literal, $matches: expr) {
#[doc(hidden)] // use the macro instead #[doc(hidden)] // use the macro instead
pub fn version_at_macro_invocation( pub fn version_at_macro_invocation(
handler: &EarlyDiagCtxt, early_dcx: &EarlyDiagCtxt,
binary: &str, binary: &str,
matches: &getopts::Matches, matches: &getopts::Matches,
version: &str, version: &str,
@ -890,7 +890,7 @@ pub fn version_at_macro_invocation(
let debug_flags = matches.opt_strs("Z"); let debug_flags = matches.opt_strs("Z");
let backend_name = debug_flags.iter().find_map(|x| x.strip_prefix("codegen-backend=")); let backend_name = debug_flags.iter().find_map(|x| x.strip_prefix("codegen-backend="));
get_codegen_backend(handler, &None, backend_name).print_version(); get_codegen_backend(early_dcx, &None, backend_name).print_version();
} }
} }
@ -1068,7 +1068,7 @@ Available lint options:
/// Show help for flag categories shared between rustdoc and rustc. /// Show help for flag categories shared between rustdoc and rustc.
/// ///
/// Returns whether a help option was printed. /// Returns whether a help option was printed.
pub fn describe_flag_categories(handler: &EarlyDiagCtxt, matches: &Matches) -> bool { pub fn describe_flag_categories(early_dcx: &EarlyDiagCtxt, matches: &Matches) -> bool {
// Handle the special case of -Wall. // Handle the special case of -Wall.
let wall = matches.opt_strs("W"); let wall = matches.opt_strs("W");
if wall.iter().any(|x| *x == "all") { if wall.iter().any(|x| *x == "all") {
@ -1090,12 +1090,12 @@ pub fn describe_flag_categories(handler: &EarlyDiagCtxt, matches: &Matches) -> b
} }
if cg_flags.iter().any(|x| *x == "no-stack-check") { if cg_flags.iter().any(|x| *x == "no-stack-check") {
handler.early_warn("the --no-stack-check flag is deprecated and does nothing"); early_dcx.early_warn("the --no-stack-check flag is deprecated and does nothing");
} }
if cg_flags.iter().any(|x| *x == "passes=list") { if cg_flags.iter().any(|x| *x == "passes=list") {
let backend_name = debug_flags.iter().find_map(|x| x.strip_prefix("codegen-backend=")); let backend_name = debug_flags.iter().find_map(|x| x.strip_prefix("codegen-backend="));
get_codegen_backend(handler, &None, backend_name).print_passes(); get_codegen_backend(early_dcx, &None, backend_name).print_passes();
return true; return true;
} }
@ -1156,7 +1156,7 @@ fn print_flag_list<T>(
/// This does not need to be `pub` for rustc itself, but @chaosite needs it to /// This does not need to be `pub` for rustc itself, but @chaosite needs it to
/// be public when using rustc as a library, see /// be public when using rustc as a library, see
/// <https://github.com/rust-lang/rust/commit/2b4c33817a5aaecabf4c6598d41e190080ec119e> /// <https://github.com/rust-lang/rust/commit/2b4c33817a5aaecabf4c6598d41e190080ec119e>
pub fn handle_options(handler: &EarlyDiagCtxt, args: &[String]) -> Option<getopts::Matches> { pub fn handle_options(early_dcx: &EarlyDiagCtxt, args: &[String]) -> Option<getopts::Matches> {
if args.is_empty() { if args.is_empty() {
// user did not write `-v` nor `-Z unstable-options`, so do not // user did not write `-v` nor `-Z unstable-options`, so do not
// include that extra information. // include that extra information.
@ -1182,7 +1182,7 @@ pub fn handle_options(handler: &EarlyDiagCtxt, args: &[String]) -> Option<getopt
.map(|(flag, _)| format!("{e}. Did you mean `-{flag} {opt}`?")), .map(|(flag, _)| format!("{e}. Did you mean `-{flag} {opt}`?")),
_ => None, _ => None,
}; };
handler.early_error(msg.unwrap_or_else(|| e.to_string())); early_dcx.early_error(msg.unwrap_or_else(|| e.to_string()));
}); });
// For all options we just parsed, we check a few aspects: // For all options we just parsed, we check a few aspects:
@ -1196,7 +1196,7 @@ pub fn handle_options(handler: &EarlyDiagCtxt, args: &[String]) -> Option<getopt
// we're good to go. // we're good to go.
// * Otherwise, if we're an unstable option then we generate an error // * Otherwise, if we're an unstable option then we generate an error
// (unstable option being used on stable) // (unstable option being used on stable)
nightly_options::check_nightly_options(handler, &matches, &config::rustc_optgroups()); nightly_options::check_nightly_options(early_dcx, &matches, &config::rustc_optgroups());
if matches.opt_present("h") || matches.opt_present("help") { if matches.opt_present("h") || matches.opt_present("help") {
// Only show unstable options in --help if we accept unstable options. // Only show unstable options in --help if we accept unstable options.
@ -1206,12 +1206,12 @@ pub fn handle_options(handler: &EarlyDiagCtxt, args: &[String]) -> Option<getopt
return None; return None;
} }
if describe_flag_categories(handler, &matches) { if describe_flag_categories(early_dcx, &matches) {
return None; return None;
} }
if matches.opt_present("version") { if matches.opt_present("version") {
version!(handler, "rustc", &matches); version!(early_dcx, "rustc", &matches);
return None; return None;
} }
@ -1472,16 +1472,16 @@ fn report_ice(
/// This allows tools to enable rust logging without having to magically match rustc's /// This allows tools to enable rust logging without having to magically match rustc's
/// tracing crate version. /// tracing crate version.
pub fn init_rustc_env_logger(handler: &EarlyDiagCtxt) { pub fn init_rustc_env_logger(early_dcx: &EarlyDiagCtxt) {
init_logger(handler, rustc_log::LoggerConfig::from_env("RUSTC_LOG")); init_logger(early_dcx, rustc_log::LoggerConfig::from_env("RUSTC_LOG"));
} }
/// This allows tools to enable rust logging without having to magically match rustc's /// This allows tools to enable rust logging without having to magically match rustc's
/// tracing crate version. In contrast to `init_rustc_env_logger` it allows you to choose /// tracing crate version. In contrast to `init_rustc_env_logger` it allows you to choose
/// the values directly rather than having to set an environment variable. /// the values directly rather than having to set an environment variable.
pub fn init_logger(handler: &EarlyDiagCtxt, cfg: rustc_log::LoggerConfig) { pub fn init_logger(early_dcx: &EarlyDiagCtxt, cfg: rustc_log::LoggerConfig) {
if let Err(error) = rustc_log::init_logger(cfg) { if let Err(error) = rustc_log::init_logger(cfg) {
handler.early_error(error.to_string()); early_dcx.early_error(error.to_string());
} }
} }

View file

@ -161,16 +161,16 @@ pub(crate) fn run_in_thread_pool_with_globals<F: FnOnce() -> R + Send, R: Send>(
}) })
} }
fn load_backend_from_dylib(handler: &EarlyDiagCtxt, path: &Path) -> MakeBackendFn { fn load_backend_from_dylib(early_dcx: &EarlyDiagCtxt, path: &Path) -> MakeBackendFn {
let lib = unsafe { Library::new(path) }.unwrap_or_else(|err| { let lib = unsafe { Library::new(path) }.unwrap_or_else(|err| {
let err = format!("couldn't load codegen backend {path:?}: {err}"); let err = format!("couldn't load codegen backend {path:?}: {err}");
handler.early_error(err); early_dcx.early_error(err);
}); });
let backend_sym = unsafe { lib.get::<MakeBackendFn>(b"__rustc_codegen_backend") } let backend_sym = unsafe { lib.get::<MakeBackendFn>(b"__rustc_codegen_backend") }
.unwrap_or_else(|e| { .unwrap_or_else(|e| {
let err = format!("couldn't load codegen backend: {e}"); let err = format!("couldn't load codegen backend: {e}");
handler.early_error(err); early_dcx.early_error(err);
}); });
// Intentionally leak the dynamic library. We can't ever unload it // Intentionally leak the dynamic library. We can't ever unload it
@ -185,7 +185,7 @@ fn load_backend_from_dylib(handler: &EarlyDiagCtxt, path: &Path) -> MakeBackendF
/// ///
/// A name of `None` indicates that the default backend should be used. /// A name of `None` indicates that the default backend should be used.
pub fn get_codegen_backend( pub fn get_codegen_backend(
handler: &EarlyDiagCtxt, early_dcx: &EarlyDiagCtxt,
maybe_sysroot: &Option<PathBuf>, maybe_sysroot: &Option<PathBuf>,
backend_name: Option<&str>, backend_name: Option<&str>,
) -> Box<dyn CodegenBackend> { ) -> Box<dyn CodegenBackend> {
@ -196,11 +196,11 @@ pub fn get_codegen_backend(
match backend_name.unwrap_or(default_codegen_backend) { match backend_name.unwrap_or(default_codegen_backend) {
filename if filename.contains('.') => { filename if filename.contains('.') => {
load_backend_from_dylib(handler, filename.as_ref()) load_backend_from_dylib(early_dcx, filename.as_ref())
} }
#[cfg(feature = "llvm")] #[cfg(feature = "llvm")]
"llvm" => rustc_codegen_llvm::LlvmCodegenBackend::new, "llvm" => rustc_codegen_llvm::LlvmCodegenBackend::new,
backend_name => get_codegen_sysroot(handler, maybe_sysroot, backend_name), backend_name => get_codegen_sysroot(early_dcx, maybe_sysroot, backend_name),
} }
}); });
@ -233,7 +233,7 @@ fn get_rustc_path_inner(bin_path: &str) -> Option<PathBuf> {
} }
fn get_codegen_sysroot( fn get_codegen_sysroot(
handler: &EarlyDiagCtxt, early_dcx: &EarlyDiagCtxt,
maybe_sysroot: &Option<PathBuf>, maybe_sysroot: &Option<PathBuf>,
backend_name: &str, backend_name: &str,
) -> MakeBackendFn { ) -> MakeBackendFn {
@ -271,7 +271,7 @@ fn get_codegen_sysroot(
"failed to find a `codegen-backends` folder \ "failed to find a `codegen-backends` folder \
in the sysroot candidates:\n* {candidates}" in the sysroot candidates:\n* {candidates}"
); );
handler.early_error(err); early_dcx.early_error(err);
}); });
info!("probing {} for a codegen backend", sysroot.display()); info!("probing {} for a codegen backend", sysroot.display());
@ -282,7 +282,7 @@ fn get_codegen_sysroot(
sysroot.display(), sysroot.display(),
e e
); );
handler.early_error(err); early_dcx.early_error(err);
}); });
let mut file: Option<PathBuf> = None; let mut file: Option<PathBuf> = None;
@ -310,16 +310,16 @@ fn get_codegen_sysroot(
prev.display(), prev.display(),
path.display() path.display()
); );
handler.early_error(err); early_dcx.early_error(err);
} }
file = Some(path.clone()); file = Some(path.clone());
} }
match file { match file {
Some(ref s) => load_backend_from_dylib(handler, s), Some(ref s) => load_backend_from_dylib(early_dcx, s),
None => { None => {
let err = format!("unsupported builtin codegen backend `{backend_name}`"); let err = format!("unsupported builtin codegen backend `{backend_name}`");
handler.early_error(err); early_dcx.early_error(err);
} }
} }
} }

View file

@ -1584,7 +1584,7 @@ pub fn build_configuration(sess: &Session, mut user_cfg: Cfg) -> Cfg {
} }
pub(super) fn build_target_config( pub(super) fn build_target_config(
handler: &EarlyDiagCtxt, early_dcx: &EarlyDiagCtxt,
opts: &Options, opts: &Options,
target_override: Option<Target>, target_override: Option<Target>,
sysroot: &Path, sysroot: &Path,
@ -1594,17 +1594,17 @@ pub(super) fn build_target_config(
|t| Ok((t, TargetWarnings::empty())), |t| Ok((t, TargetWarnings::empty())),
); );
let (target, target_warnings) = target_result.unwrap_or_else(|e| { let (target, target_warnings) = target_result.unwrap_or_else(|e| {
handler.early_error(format!( early_dcx.early_error(format!(
"Error loading target specification: {e}. \ "Error loading target specification: {e}. \
Run `rustc --print target-list` for a list of built-in targets" Run `rustc --print target-list` for a list of built-in targets"
)) ))
}); });
for warning in target_warnings.warning_messages() { for warning in target_warnings.warning_messages() {
handler.early_warn(warning) early_dcx.early_warn(warning)
} }
if !matches!(target.pointer_width, 16 | 32 | 64) { if !matches!(target.pointer_width, 16 | 32 | 64) {
handler.early_error(format!( early_dcx.early_error(format!(
"target specification was invalid: unrecognized target-pointer-width {}", "target specification was invalid: unrecognized target-pointer-width {}",
target.pointer_width target.pointer_width
)) ))
@ -1844,7 +1844,7 @@ pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
} }
pub fn get_cmd_lint_options( pub fn get_cmd_lint_options(
handler: &EarlyDiagCtxt, early_dcx: &EarlyDiagCtxt,
matches: &getopts::Matches, matches: &getopts::Matches,
) -> (Vec<(String, lint::Level)>, bool, Option<lint::Level>) { ) -> (Vec<(String, lint::Level)>, bool, Option<lint::Level>) {
let mut lint_opts_with_position = vec![]; let mut lint_opts_with_position = vec![];
@ -1869,14 +1869,14 @@ pub fn get_cmd_lint_options(
let lint_cap = matches.opt_str("cap-lints").map(|cap| { let lint_cap = matches.opt_str("cap-lints").map(|cap| {
lint::Level::from_str(&cap) lint::Level::from_str(&cap)
.unwrap_or_else(|| handler.early_error(format!("unknown lint level: `{cap}`"))) .unwrap_or_else(|| early_dcx.early_error(format!("unknown lint level: `{cap}`")))
}); });
(lint_opts, describe_lints, lint_cap) (lint_opts, describe_lints, lint_cap)
} }
/// Parses the `--color` flag. /// Parses the `--color` flag.
pub fn parse_color(handler: &EarlyDiagCtxt, matches: &getopts::Matches) -> ColorConfig { pub fn parse_color(early_dcx: &EarlyDiagCtxt, matches: &getopts::Matches) -> ColorConfig {
match matches.opt_str("color").as_deref() { match matches.opt_str("color").as_deref() {
Some("auto") => ColorConfig::Auto, Some("auto") => ColorConfig::Auto,
Some("always") => ColorConfig::Always, Some("always") => ColorConfig::Always,
@ -1884,7 +1884,7 @@ pub fn parse_color(handler: &EarlyDiagCtxt, matches: &getopts::Matches) -> Color
None => ColorConfig::Auto, None => ColorConfig::Auto,
Some(arg) => handler.early_error(format!( Some(arg) => early_dcx.early_error(format!(
"argument for `--color` must be auto, \ "argument for `--color` must be auto, \
always or never (instead was `{arg}`)" always or never (instead was `{arg}`)"
)), )),
@ -1930,7 +1930,7 @@ impl JsonUnusedExterns {
/// ///
/// The first value returned is how to render JSON diagnostics, and the second /// The first value returned is how to render JSON diagnostics, and the second
/// is whether or not artifact notifications are enabled. /// is whether or not artifact notifications are enabled.
pub fn parse_json(handler: &EarlyDiagCtxt, matches: &getopts::Matches) -> JsonConfig { pub fn parse_json(early_dcx: &EarlyDiagCtxt, matches: &getopts::Matches) -> JsonConfig {
let mut json_rendered: fn(ColorConfig) -> HumanReadableErrorType = let mut json_rendered: fn(ColorConfig) -> HumanReadableErrorType =
HumanReadableErrorType::Default; HumanReadableErrorType::Default;
let mut json_color = ColorConfig::Never; let mut json_color = ColorConfig::Never;
@ -1942,7 +1942,7 @@ pub fn parse_json(handler: &EarlyDiagCtxt, matches: &getopts::Matches) -> JsonCo
// won't actually be emitting any colors and anything colorized is // won't actually be emitting any colors and anything colorized is
// embedded in a diagnostic message anyway. // embedded in a diagnostic message anyway.
if matches.opt_str("color").is_some() { if matches.opt_str("color").is_some() {
handler.early_error("cannot specify the `--color` option with `--json`"); early_dcx.early_error("cannot specify the `--color` option with `--json`");
} }
for sub_option in option.split(',') { for sub_option in option.split(',') {
@ -1953,7 +1953,7 @@ pub fn parse_json(handler: &EarlyDiagCtxt, matches: &getopts::Matches) -> JsonCo
"unused-externs" => json_unused_externs = JsonUnusedExterns::Loud, "unused-externs" => json_unused_externs = JsonUnusedExterns::Loud,
"unused-externs-silent" => json_unused_externs = JsonUnusedExterns::Silent, "unused-externs-silent" => json_unused_externs = JsonUnusedExterns::Silent,
"future-incompat" => json_future_incompat = true, "future-incompat" => json_future_incompat = true,
s => handler.early_error(format!("unknown `--json` option `{s}`")), s => early_dcx.early_error(format!("unknown `--json` option `{s}`")),
} }
} }
} }
@ -1968,7 +1968,7 @@ pub fn parse_json(handler: &EarlyDiagCtxt, matches: &getopts::Matches) -> JsonCo
/// Parses the `--error-format` flag. /// Parses the `--error-format` flag.
pub fn parse_error_format( pub fn parse_error_format(
handler: &mut EarlyDiagCtxt, early_dcx: &mut EarlyDiagCtxt,
matches: &getopts::Matches, matches: &getopts::Matches,
color: ColorConfig, color: ColorConfig,
json_rendered: HumanReadableErrorType, json_rendered: HumanReadableErrorType,
@ -1990,10 +1990,10 @@ pub fn parse_error_format(
Some("short") => ErrorOutputType::HumanReadable(HumanReadableErrorType::Short(color)), Some("short") => ErrorOutputType::HumanReadable(HumanReadableErrorType::Short(color)),
Some(arg) => { Some(arg) => {
handler.abort_if_error_and_set_error_format(ErrorOutputType::HumanReadable( early_dcx.abort_if_error_and_set_error_format(ErrorOutputType::HumanReadable(
HumanReadableErrorType::Default(color), HumanReadableErrorType::Default(color),
)); ));
handler.early_error(format!( early_dcx.early_error(format!(
"argument for `--error-format` must be `human`, `json` or \ "argument for `--error-format` must be `human`, `json` or \
`short` (instead was `{arg}`)" `short` (instead was `{arg}`)"
)) ))
@ -2010,7 +2010,7 @@ pub fn parse_error_format(
// `--error-format=json`. This means that `--json` is specified we // `--error-format=json`. This means that `--json` is specified we
// should actually be emitting JSON blobs. // should actually be emitting JSON blobs.
_ if !matches.opt_strs("json").is_empty() => { _ if !matches.opt_strs("json").is_empty() => {
handler.early_error("using `--json` requires also using `--error-format=json`"); early_dcx.early_error("using `--json` requires also using `--error-format=json`");
} }
_ => {} _ => {}
@ -2019,10 +2019,10 @@ pub fn parse_error_format(
error_format error_format
} }
pub fn parse_crate_edition(handler: &EarlyDiagCtxt, matches: &getopts::Matches) -> Edition { pub fn parse_crate_edition(early_dcx: &EarlyDiagCtxt, matches: &getopts::Matches) -> Edition {
let edition = match matches.opt_str("edition") { let edition = match matches.opt_str("edition") {
Some(arg) => Edition::from_str(&arg).unwrap_or_else(|_| { Some(arg) => Edition::from_str(&arg).unwrap_or_else(|_| {
handler.early_error(format!( early_dcx.early_error(format!(
"argument for `--edition` must be one of: \ "argument for `--edition` must be one of: \
{EDITION_NAME_LIST}. (instead was `{arg}`)" {EDITION_NAME_LIST}. (instead was `{arg}`)"
)) ))
@ -2039,40 +2039,40 @@ pub fn parse_crate_edition(handler: &EarlyDiagCtxt, matches: &getopts::Matches)
} else { } else {
format!("edition {edition} is unstable and only available with -Z unstable-options") format!("edition {edition} is unstable and only available with -Z unstable-options")
}; };
handler.early_error(msg) early_dcx.early_error(msg)
} }
edition edition
} }
fn check_error_format_stability( fn check_error_format_stability(
handler: &mut EarlyDiagCtxt, early_dcx: &mut EarlyDiagCtxt,
unstable_opts: &UnstableOptions, unstable_opts: &UnstableOptions,
error_format: ErrorOutputType, error_format: ErrorOutputType,
json_rendered: HumanReadableErrorType, json_rendered: HumanReadableErrorType,
) { ) {
if !unstable_opts.unstable_options { if !unstable_opts.unstable_options {
if let ErrorOutputType::Json { pretty: true, json_rendered } = error_format { if let ErrorOutputType::Json { pretty: true, json_rendered } = error_format {
handler.abort_if_error_and_set_error_format(ErrorOutputType::Json { early_dcx.abort_if_error_and_set_error_format(ErrorOutputType::Json {
pretty: false, pretty: false,
json_rendered, json_rendered,
}); });
handler.early_error("`--error-format=pretty-json` is unstable"); early_dcx.early_error("`--error-format=pretty-json` is unstable");
} }
if let ErrorOutputType::HumanReadable(HumanReadableErrorType::AnnotateSnippet(_)) = if let ErrorOutputType::HumanReadable(HumanReadableErrorType::AnnotateSnippet(_)) =
error_format error_format
{ {
handler.abort_if_error_and_set_error_format(ErrorOutputType::Json { early_dcx.abort_if_error_and_set_error_format(ErrorOutputType::Json {
pretty: false, pretty: false,
json_rendered, json_rendered,
}); });
handler.early_error("`--error-format=human-annotate-rs` is unstable"); early_dcx.early_error("`--error-format=human-annotate-rs` is unstable");
} }
} }
} }
fn parse_output_types( fn parse_output_types(
handler: &EarlyDiagCtxt, early_dcx: &EarlyDiagCtxt,
unstable_opts: &UnstableOptions, unstable_opts: &UnstableOptions,
matches: &getopts::Matches, matches: &getopts::Matches,
) -> OutputTypes { ) -> OutputTypes {
@ -2082,7 +2082,7 @@ fn parse_output_types(
for output_type in list.split(',') { for output_type in list.split(',') {
let (shorthand, path) = split_out_file_name(output_type); let (shorthand, path) = split_out_file_name(output_type);
let output_type = OutputType::from_shorthand(shorthand).unwrap_or_else(|| { let output_type = OutputType::from_shorthand(shorthand).unwrap_or_else(|| {
handler.early_error(format!( early_dcx.early_error(format!(
"unknown emission type: `{shorthand}` - expected one of: {display}", "unknown emission type: `{shorthand}` - expected one of: {display}",
display = OutputType::shorthands_display(), display = OutputType::shorthands_display(),
)) ))
@ -2106,7 +2106,7 @@ fn split_out_file_name(arg: &str) -> (&str, Option<OutFileName>) {
} }
fn should_override_cgus_and_disable_thinlto( fn should_override_cgus_and_disable_thinlto(
handler: &EarlyDiagCtxt, early_dcx: &EarlyDiagCtxt,
output_types: &OutputTypes, output_types: &OutputTypes,
matches: &getopts::Matches, matches: &getopts::Matches,
mut codegen_units: Option<usize>, mut codegen_units: Option<usize>,
@ -2126,12 +2126,12 @@ fn should_override_cgus_and_disable_thinlto(
Some(n) if n > 1 => { Some(n) if n > 1 => {
if matches.opt_present("o") { if matches.opt_present("o") {
for ot in &incompatible { for ot in &incompatible {
handler.early_warn(format!( early_dcx.early_warn(format!(
"`--emit={ot}` with `-o` incompatible with \ "`--emit={ot}` with `-o` incompatible with \
`-C codegen-units=N` for N > 1", `-C codegen-units=N` for N > 1",
)); ));
} }
handler.early_warn("resetting to default -C codegen-units=1"); early_dcx.early_warn("resetting to default -C codegen-units=1");
codegen_units = Some(1); codegen_units = Some(1);
disable_local_thinlto = true; disable_local_thinlto = true;
} }
@ -2144,14 +2144,14 @@ fn should_override_cgus_and_disable_thinlto(
} }
if codegen_units == Some(0) { if codegen_units == Some(0) {
handler.early_error("value for codegen units must be a positive non-zero integer"); early_dcx.early_error("value for codegen units must be a positive non-zero integer");
} }
(disable_local_thinlto, codegen_units) (disable_local_thinlto, codegen_units)
} }
fn collect_print_requests( fn collect_print_requests(
handler: &EarlyDiagCtxt, early_dcx: &EarlyDiagCtxt,
cg: &mut CodegenOptions, cg: &mut CodegenOptions,
unstable_opts: &mut UnstableOptions, unstable_opts: &mut UnstableOptions,
matches: &getopts::Matches, matches: &getopts::Matches,
@ -2204,7 +2204,7 @@ fn collect_print_requests(
if unstable_opts.unstable_options { if unstable_opts.unstable_options {
PrintKind::TargetSpec PrintKind::TargetSpec
} else { } else {
handler.early_error( early_dcx.early_error(
"the `-Z unstable-options` flag must also be passed to \ "the `-Z unstable-options` flag must also be passed to \
enable the target-spec-json print option", enable the target-spec-json print option",
); );
@ -2214,7 +2214,7 @@ fn collect_print_requests(
if unstable_opts.unstable_options { if unstable_opts.unstable_options {
PrintKind::AllTargetSpecs PrintKind::AllTargetSpecs
} else { } else {
handler.early_error( early_dcx.early_error(
"the `-Z unstable-options` flag must also be passed to \ "the `-Z unstable-options` flag must also be passed to \
enable the all-target-specs-json print option", enable the all-target-specs-json print option",
); );
@ -2225,7 +2225,7 @@ fn collect_print_requests(
let prints = let prints =
PRINT_KINDS.iter().map(|(name, _)| format!("`{name}`")).collect::<Vec<_>>(); PRINT_KINDS.iter().map(|(name, _)| format!("`{name}`")).collect::<Vec<_>>();
let prints = prints.join(", "); let prints = prints.join(", ");
handler.early_error(format!( early_dcx.early_error(format!(
"unknown print request `{req}`. Valid print requests are: {prints}" "unknown print request `{req}`. Valid print requests are: {prints}"
)); ));
} }
@ -2234,7 +2234,7 @@ fn collect_print_requests(
let out = out.unwrap_or(OutFileName::Stdout); let out = out.unwrap_or(OutFileName::Stdout);
if let OutFileName::Real(path) = &out { if let OutFileName::Real(path) = &out {
if !printed_paths.insert(path.clone()) { if !printed_paths.insert(path.clone()) {
handler.early_error(format!( early_dcx.early_error(format!(
"cannot print multiple outputs to the same path: {}", "cannot print multiple outputs to the same path: {}",
path.display(), path.display(),
)); ));
@ -2247,12 +2247,12 @@ fn collect_print_requests(
prints prints
} }
pub fn parse_target_triple(handler: &EarlyDiagCtxt, matches: &getopts::Matches) -> TargetTriple { pub fn parse_target_triple(early_dcx: &EarlyDiagCtxt, matches: &getopts::Matches) -> TargetTriple {
match matches.opt_str("target") { match matches.opt_str("target") {
Some(target) if target.ends_with(".json") => { Some(target) if target.ends_with(".json") => {
let path = Path::new(&target); let path = Path::new(&target);
TargetTriple::from_path(path).unwrap_or_else(|_| { TargetTriple::from_path(path).unwrap_or_else(|_| {
handler.early_error(format!("target file {path:?} does not exist")) early_dcx.early_error(format!("target file {path:?} does not exist"))
}) })
} }
Some(target) => TargetTriple::TargetTriple(target), Some(target) => TargetTriple::TargetTriple(target),
@ -2261,7 +2261,7 @@ pub fn parse_target_triple(handler: &EarlyDiagCtxt, matches: &getopts::Matches)
} }
fn parse_opt_level( fn parse_opt_level(
handler: &EarlyDiagCtxt, early_dcx: &EarlyDiagCtxt,
matches: &getopts::Matches, matches: &getopts::Matches,
cg: &CodegenOptions, cg: &CodegenOptions,
) -> OptLevel { ) -> OptLevel {
@ -2291,7 +2291,7 @@ fn parse_opt_level(
"s" => OptLevel::Size, "s" => OptLevel::Size,
"z" => OptLevel::SizeMin, "z" => OptLevel::SizeMin,
arg => { arg => {
handler.early_error(format!( early_dcx.early_error(format!(
"optimization level needs to be \ "optimization level needs to be \
between 0-3, s or z (instead was `{arg}`)" between 0-3, s or z (instead was `{arg}`)"
)); ));
@ -2314,21 +2314,21 @@ fn select_debuginfo(matches: &getopts::Matches, cg: &CodegenOptions) -> DebugInf
} }
fn parse_assert_incr_state( fn parse_assert_incr_state(
handler: &EarlyDiagCtxt, early_dcx: &EarlyDiagCtxt,
opt_assertion: &Option<String>, opt_assertion: &Option<String>,
) -> Option<IncrementalStateAssertion> { ) -> Option<IncrementalStateAssertion> {
match opt_assertion { match opt_assertion {
Some(s) if s.as_str() == "loaded" => Some(IncrementalStateAssertion::Loaded), Some(s) if s.as_str() == "loaded" => Some(IncrementalStateAssertion::Loaded),
Some(s) if s.as_str() == "not-loaded" => Some(IncrementalStateAssertion::NotLoaded), Some(s) if s.as_str() == "not-loaded" => Some(IncrementalStateAssertion::NotLoaded),
Some(s) => { Some(s) => {
handler.early_error(format!("unexpected incremental state assertion value: {s}")) early_dcx.early_error(format!("unexpected incremental state assertion value: {s}"))
} }
None => None, None => None,
} }
} }
fn parse_native_lib_kind( fn parse_native_lib_kind(
handler: &EarlyDiagCtxt, early_dcx: &EarlyDiagCtxt,
matches: &getopts::Matches, matches: &getopts::Matches,
kind: &str, kind: &str,
) -> (NativeLibKind, Option<bool>) { ) -> (NativeLibKind, Option<bool>) {
@ -2348,22 +2348,22 @@ fn parse_native_lib_kind(
} else { } else {
", the `-Z unstable-options` flag must also be passed to use it" ", the `-Z unstable-options` flag must also be passed to use it"
}; };
handler.early_error(format!("library kind `link-arg` is unstable{why}")) early_dcx.early_error(format!("library kind `link-arg` is unstable{why}"))
} }
NativeLibKind::LinkArg NativeLibKind::LinkArg
} }
_ => handler.early_error(format!( _ => early_dcx.early_error(format!(
"unknown library kind `{kind}`, expected one of: static, dylib, framework, link-arg" "unknown library kind `{kind}`, expected one of: static, dylib, framework, link-arg"
)), )),
}; };
match modifiers { match modifiers {
None => (kind, None), None => (kind, None),
Some(modifiers) => parse_native_lib_modifiers(handler, kind, modifiers, matches), Some(modifiers) => parse_native_lib_modifiers(early_dcx, kind, modifiers, matches),
} }
} }
fn parse_native_lib_modifiers( fn parse_native_lib_modifiers(
handler: &EarlyDiagCtxt, early_dcx: &EarlyDiagCtxt,
mut kind: NativeLibKind, mut kind: NativeLibKind,
modifiers: &str, modifiers: &str,
matches: &getopts::Matches, matches: &getopts::Matches,
@ -2372,7 +2372,7 @@ fn parse_native_lib_modifiers(
for modifier in modifiers.split(',') { for modifier in modifiers.split(',') {
let (modifier, value) = match modifier.strip_prefix(['+', '-']) { let (modifier, value) = match modifier.strip_prefix(['+', '-']) {
Some(m) => (m, modifier.starts_with('+')), Some(m) => (m, modifier.starts_with('+')),
None => handler.early_error( None => early_dcx.early_error(
"invalid linking modifier syntax, expected '+' or '-' prefix \ "invalid linking modifier syntax, expected '+' or '-' prefix \
before one of: bundle, verbatim, whole-archive, as-needed", before one of: bundle, verbatim, whole-archive, as-needed",
), ),
@ -2385,20 +2385,20 @@ fn parse_native_lib_modifiers(
} else { } else {
", the `-Z unstable-options` flag must also be passed to use it" ", the `-Z unstable-options` flag must also be passed to use it"
}; };
handler.early_error(format!("linking modifier `{modifier}` is unstable{why}")) early_dcx.early_error(format!("linking modifier `{modifier}` is unstable{why}"))
} }
}; };
let assign_modifier = |dst: &mut Option<bool>| { let assign_modifier = |dst: &mut Option<bool>| {
if dst.is_some() { if dst.is_some() {
let msg = format!("multiple `{modifier}` modifiers in a single `-l` option"); let msg = format!("multiple `{modifier}` modifiers in a single `-l` option");
handler.early_error(msg) early_dcx.early_error(msg)
} else { } else {
*dst = Some(value); *dst = Some(value);
} }
}; };
match (modifier, &mut kind) { match (modifier, &mut kind) {
("bundle", NativeLibKind::Static { bundle, .. }) => assign_modifier(bundle), ("bundle", NativeLibKind::Static { bundle, .. }) => assign_modifier(bundle),
("bundle", _) => handler.early_error( ("bundle", _) => early_dcx.early_error(
"linking modifier `bundle` is only compatible with `static` linking kind", "linking modifier `bundle` is only compatible with `static` linking kind",
), ),
@ -2407,7 +2407,7 @@ fn parse_native_lib_modifiers(
("whole-archive", NativeLibKind::Static { whole_archive, .. }) => { ("whole-archive", NativeLibKind::Static { whole_archive, .. }) => {
assign_modifier(whole_archive) assign_modifier(whole_archive)
} }
("whole-archive", _) => handler.early_error( ("whole-archive", _) => early_dcx.early_error(
"linking modifier `whole-archive` is only compatible with `static` linking kind", "linking modifier `whole-archive` is only compatible with `static` linking kind",
), ),
@ -2416,14 +2416,14 @@ fn parse_native_lib_modifiers(
report_unstable_modifier(); report_unstable_modifier();
assign_modifier(as_needed) assign_modifier(as_needed)
} }
("as-needed", _) => handler.early_error( ("as-needed", _) => early_dcx.early_error(
"linking modifier `as-needed` is only compatible with \ "linking modifier `as-needed` is only compatible with \
`dylib` and `framework` linking kinds", `dylib` and `framework` linking kinds",
), ),
// Note: this error also excludes the case with empty modifier // Note: this error also excludes the case with empty modifier
// string, like `modifiers = ""`. // string, like `modifiers = ""`.
_ => handler.early_error(format!( _ => early_dcx.early_error(format!(
"unknown linking modifier `{modifier}`, expected one \ "unknown linking modifier `{modifier}`, expected one \
of: bundle, verbatim, whole-archive, as-needed" of: bundle, verbatim, whole-archive, as-needed"
)), )),
@ -2433,7 +2433,7 @@ fn parse_native_lib_modifiers(
(kind, verbatim) (kind, verbatim)
} }
fn parse_libs(handler: &EarlyDiagCtxt, matches: &getopts::Matches) -> Vec<NativeLib> { fn parse_libs(early_dcx: &EarlyDiagCtxt, matches: &getopts::Matches) -> Vec<NativeLib> {
matches matches
.opt_strs("l") .opt_strs("l")
.into_iter() .into_iter()
@ -2447,7 +2447,7 @@ fn parse_libs(handler: &EarlyDiagCtxt, matches: &getopts::Matches) -> Vec<Native
let (name, kind, verbatim) = match s.split_once('=') { let (name, kind, verbatim) = match s.split_once('=') {
None => (s, NativeLibKind::Unspecified, None), None => (s, NativeLibKind::Unspecified, None),
Some((kind, name)) => { Some((kind, name)) => {
let (kind, verbatim) = parse_native_lib_kind(handler, matches, kind); let (kind, verbatim) = parse_native_lib_kind(early_dcx, matches, kind);
(name.to_string(), kind, verbatim) (name.to_string(), kind, verbatim)
} }
}; };
@ -2457,7 +2457,7 @@ fn parse_libs(handler: &EarlyDiagCtxt, matches: &getopts::Matches) -> Vec<Native
Some((name, new_name)) => (name.to_string(), Some(new_name.to_owned())), Some((name, new_name)) => (name.to_string(), Some(new_name.to_owned())),
}; };
if name.is_empty() { if name.is_empty() {
handler.early_error("library name must not be empty"); early_dcx.early_error("library name must not be empty");
} }
NativeLib { name, new_name, kind, verbatim } NativeLib { name, new_name, kind, verbatim }
}) })
@ -2465,7 +2465,7 @@ fn parse_libs(handler: &EarlyDiagCtxt, matches: &getopts::Matches) -> Vec<Native
} }
pub fn parse_externs( pub fn parse_externs(
handler: &EarlyDiagCtxt, early_dcx: &EarlyDiagCtxt,
matches: &getopts::Matches, matches: &getopts::Matches,
unstable_opts: &UnstableOptions, unstable_opts: &UnstableOptions,
) -> Externs { ) -> Externs {
@ -2493,7 +2493,7 @@ pub fn parse_externs(
}; };
if !is_ascii_ident(&name) { if !is_ascii_ident(&name) {
let mut error = handler.early_struct_error(format!( let mut error = early_dcx.early_struct_error(format!(
"crate name `{name}` passed to `--extern` is not a valid ASCII identifier" "crate name `{name}` passed to `--extern` is not a valid ASCII identifier"
)); ));
let adjusted_name = name.replace('-', "_"); let adjusted_name = name.replace('-', "_");
@ -2555,7 +2555,7 @@ pub fn parse_externs(
let mut force = false; let mut force = false;
if let Some(opts) = options { if let Some(opts) = options {
if !is_unstable_enabled { if !is_unstable_enabled {
handler.early_error( early_dcx.early_error(
"the `-Z unstable-options` flag must also be passed to \ "the `-Z unstable-options` flag must also be passed to \
enable `--extern` options", enable `--extern` options",
); );
@ -2567,14 +2567,14 @@ pub fn parse_externs(
if let ExternLocation::ExactPaths(_) = &entry.location { if let ExternLocation::ExactPaths(_) = &entry.location {
add_prelude = false; add_prelude = false;
} else { } else {
handler.early_error( early_dcx.early_error(
"the `noprelude` --extern option requires a file path", "the `noprelude` --extern option requires a file path",
); );
} }
} }
"nounused" => nounused_dep = true, "nounused" => nounused_dep = true,
"force" => force = true, "force" => force = true,
_ => handler.early_error(format!("unknown --extern option `{opt}`")), _ => early_dcx.early_error(format!("unknown --extern option `{opt}`")),
} }
} }
} }
@ -2593,7 +2593,7 @@ pub fn parse_externs(
} }
fn parse_remap_path_prefix( fn parse_remap_path_prefix(
handler: &EarlyDiagCtxt, early_dcx: &EarlyDiagCtxt,
matches: &getopts::Matches, matches: &getopts::Matches,
unstable_opts: &UnstableOptions, unstable_opts: &UnstableOptions,
) -> Vec<(PathBuf, PathBuf)> { ) -> Vec<(PathBuf, PathBuf)> {
@ -2601,7 +2601,7 @@ fn parse_remap_path_prefix(
.opt_strs("remap-path-prefix") .opt_strs("remap-path-prefix")
.into_iter() .into_iter()
.map(|remap| match remap.rsplit_once('=') { .map(|remap| match remap.rsplit_once('=') {
None => handler.early_error("--remap-path-prefix must contain '=' between FROM and TO"), None => early_dcx.early_error("--remap-path-prefix must contain '=' between FROM and TO"),
Some((from, to)) => (PathBuf::from(from), PathBuf::from(to)), Some((from, to)) => (PathBuf::from(from), PathBuf::from(to)),
}) })
.collect(); .collect();
@ -2616,7 +2616,7 @@ fn parse_remap_path_prefix(
} }
fn parse_logical_env( fn parse_logical_env(
handler: &mut EarlyDiagCtxt, early_dcx: &mut EarlyDiagCtxt,
matches: &getopts::Matches, matches: &getopts::Matches,
) -> FxIndexMap<String, String> { ) -> FxIndexMap<String, String> {
let mut vars = FxIndexMap::default(); let mut vars = FxIndexMap::default();
@ -2625,7 +2625,7 @@ fn parse_logical_env(
if let Some((name, val)) = arg.split_once('=') { if let Some((name, val)) = arg.split_once('=') {
vars.insert(name.to_string(), val.to_string()); vars.insert(name.to_string(), val.to_string());
} else { } else {
handler.early_error(format!("`--env`: specify value for variable `{arg}`")); early_dcx.early_error(format!("`--env`: specify value for variable `{arg}`"));
} }
} }
@ -2634,84 +2634,84 @@ fn parse_logical_env(
// JUSTIFICATION: before wrapper fn is available // JUSTIFICATION: before wrapper fn is available
#[allow(rustc::bad_opt_access)] #[allow(rustc::bad_opt_access)]
pub fn build_session_options(handler: &mut EarlyDiagCtxt, matches: &getopts::Matches) -> Options { pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::Matches) -> Options {
let color = parse_color(handler, matches); let color = parse_color(early_dcx, matches);
let edition = parse_crate_edition(handler, matches); let edition = parse_crate_edition(early_dcx, matches);
let JsonConfig { let JsonConfig {
json_rendered, json_rendered,
json_artifact_notifications, json_artifact_notifications,
json_unused_externs, json_unused_externs,
json_future_incompat, json_future_incompat,
} = parse_json(handler, matches); } = parse_json(early_dcx, matches);
let error_format = parse_error_format(handler, matches, color, json_rendered); let error_format = parse_error_format(early_dcx, matches, color, json_rendered);
handler.abort_if_error_and_set_error_format(error_format); early_dcx.abort_if_error_and_set_error_format(error_format);
let diagnostic_width = matches.opt_get("diagnostic-width").unwrap_or_else(|_| { let diagnostic_width = matches.opt_get("diagnostic-width").unwrap_or_else(|_| {
handler.early_error("`--diagnostic-width` must be an positive integer"); early_dcx.early_error("`--diagnostic-width` must be an positive integer");
}); });
let unparsed_crate_types = matches.opt_strs("crate-type"); let unparsed_crate_types = matches.opt_strs("crate-type");
let crate_types = parse_crate_types_from_list(unparsed_crate_types) let crate_types = parse_crate_types_from_list(unparsed_crate_types)
.unwrap_or_else(|e| handler.early_error(e)); .unwrap_or_else(|e| early_dcx.early_error(e));
let mut unstable_opts = UnstableOptions::build(handler, matches); let mut unstable_opts = UnstableOptions::build(early_dcx, matches);
let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(handler, matches); let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(early_dcx, matches);
check_error_format_stability(handler, &unstable_opts, error_format, json_rendered); check_error_format_stability(early_dcx, &unstable_opts, error_format, json_rendered);
if !unstable_opts.unstable_options && json_unused_externs.is_enabled() { if !unstable_opts.unstable_options && json_unused_externs.is_enabled() {
handler.early_error( early_dcx.early_error(
"the `-Z unstable-options` flag must also be passed to enable \ "the `-Z unstable-options` flag must also be passed to enable \
the flag `--json=unused-externs`", the flag `--json=unused-externs`",
); );
} }
let output_types = parse_output_types(handler, &unstable_opts, matches); let output_types = parse_output_types(early_dcx, &unstable_opts, matches);
let mut cg = CodegenOptions::build(handler, matches); let mut cg = CodegenOptions::build(early_dcx, matches);
let (disable_local_thinlto, mut codegen_units) = let (disable_local_thinlto, mut codegen_units) =
should_override_cgus_and_disable_thinlto(handler, &output_types, matches, cg.codegen_units); should_override_cgus_and_disable_thinlto(early_dcx, &output_types, matches, cg.codegen_units);
if unstable_opts.threads == 0 { if unstable_opts.threads == 0 {
handler.early_error("value for threads must be a positive non-zero integer"); early_dcx.early_error("value for threads must be a positive non-zero integer");
} }
let fuel = unstable_opts.fuel.is_some() || unstable_opts.print_fuel.is_some(); let fuel = unstable_opts.fuel.is_some() || unstable_opts.print_fuel.is_some();
if fuel && unstable_opts.threads > 1 { if fuel && unstable_opts.threads > 1 {
handler.early_error("optimization fuel is incompatible with multiple threads"); early_dcx.early_error("optimization fuel is incompatible with multiple threads");
} }
if fuel && cg.incremental.is_some() { if fuel && cg.incremental.is_some() {
handler.early_error("optimization fuel is incompatible with incremental compilation"); early_dcx.early_error("optimization fuel is incompatible with incremental compilation");
} }
let incremental = cg.incremental.as_ref().map(PathBuf::from); let incremental = cg.incremental.as_ref().map(PathBuf::from);
let assert_incr_state = parse_assert_incr_state(handler, &unstable_opts.assert_incr_state); let assert_incr_state = parse_assert_incr_state(early_dcx, &unstable_opts.assert_incr_state);
if unstable_opts.profile && incremental.is_some() { if unstable_opts.profile && incremental.is_some() {
handler.early_error("can't instrument with gcov profiling when compiling incrementally"); early_dcx.early_error("can't instrument with gcov profiling when compiling incrementally");
} }
if unstable_opts.profile { if unstable_opts.profile {
match codegen_units { match codegen_units {
Some(1) => {} Some(1) => {}
None => codegen_units = Some(1), None => codegen_units = Some(1),
Some(_) => handler Some(_) => early_dcx
.early_error("can't instrument with gcov profiling with multiple codegen units"), .early_error("can't instrument with gcov profiling with multiple codegen units"),
} }
} }
if cg.profile_generate.enabled() && cg.profile_use.is_some() { if cg.profile_generate.enabled() && cg.profile_use.is_some() {
handler.early_error("options `-C profile-generate` and `-C profile-use` are exclusive"); early_dcx.early_error("options `-C profile-generate` and `-C profile-use` are exclusive");
} }
if unstable_opts.profile_sample_use.is_some() if unstable_opts.profile_sample_use.is_some()
&& (cg.profile_generate.enabled() || cg.profile_use.is_some()) && (cg.profile_generate.enabled() || cg.profile_use.is_some())
{ {
handler.early_error( early_dcx.early_error(
"option `-Z profile-sample-use` cannot be used with `-C profile-generate` or `-C profile-use`", "option `-Z profile-sample-use` cannot be used with `-C profile-generate` or `-C profile-use`",
); );
} }
@ -2724,7 +2724,7 @@ pub fn build_session_options(handler: &mut EarlyDiagCtxt, matches: &getopts::Mat
// Unstable values: // Unstable values:
Some(SymbolManglingVersion::Legacy) => { Some(SymbolManglingVersion::Legacy) => {
if !unstable_opts.unstable_options { if !unstable_opts.unstable_options {
handler.early_error( early_dcx.early_error(
"`-C symbol-mangling-version=legacy` requires `-Z unstable-options`", "`-C symbol-mangling-version=legacy` requires `-Z unstable-options`",
); );
} }
@ -2741,7 +2741,7 @@ pub fn build_session_options(handler: &mut EarlyDiagCtxt, matches: &getopts::Mat
| InstrumentCoverage::ExceptUnusedFunctions | InstrumentCoverage::ExceptUnusedFunctions
| InstrumentCoverage::ExceptUnusedGenerics => { | InstrumentCoverage::ExceptUnusedGenerics => {
if !unstable_opts.unstable_options { if !unstable_opts.unstable_options {
handler.early_error( early_dcx.early_error(
"`-C instrument-coverage=branch` and `-C instrument-coverage=except-*` \ "`-C instrument-coverage=branch` and `-C instrument-coverage=except-*` \
require `-Z unstable-options`", require `-Z unstable-options`",
); );
@ -2751,7 +2751,7 @@ pub fn build_session_options(handler: &mut EarlyDiagCtxt, matches: &getopts::Mat
if cg.instrument_coverage != InstrumentCoverage::Off { if cg.instrument_coverage != InstrumentCoverage::Off {
if cg.profile_generate.enabled() || cg.profile_use.is_some() { if cg.profile_generate.enabled() || cg.profile_use.is_some() {
handler.early_error( early_dcx.early_error(
"option `-C instrument-coverage` is not compatible with either `-C profile-use` \ "option `-C instrument-coverage` is not compatible with either `-C profile-use` \
or `-C profile-generate`", or `-C profile-generate`",
); );
@ -2764,7 +2764,7 @@ pub fn build_session_options(handler: &mut EarlyDiagCtxt, matches: &getopts::Mat
match cg.symbol_mangling_version { match cg.symbol_mangling_version {
None => cg.symbol_mangling_version = Some(SymbolManglingVersion::V0), None => cg.symbol_mangling_version = Some(SymbolManglingVersion::V0),
Some(SymbolManglingVersion::Legacy) => { Some(SymbolManglingVersion::Legacy) => {
handler.early_warn( early_dcx.early_warn(
"-C instrument-coverage requires symbol mangling version `v0`, \ "-C instrument-coverage requires symbol mangling version `v0`, \
but `-C symbol-mangling-version=legacy` was specified", but `-C symbol-mangling-version=legacy` was specified",
); );
@ -2781,7 +2781,7 @@ pub fn build_session_options(handler: &mut EarlyDiagCtxt, matches: &getopts::Mat
match cg.lto { match cg.lto {
LtoCli::No | LtoCli::Unspecified => {} LtoCli::No | LtoCli::Unspecified => {}
LtoCli::Yes | LtoCli::NoParam | LtoCli::Thin | LtoCli::Fat => { LtoCli::Yes | LtoCli::NoParam | LtoCli::Thin | LtoCli::Fat => {
handler.early_error("options `-C embed-bitcode=no` and `-C lto` are incompatible") early_dcx.early_error("options `-C embed-bitcode=no` and `-C lto` are incompatible")
} }
} }
} }
@ -2793,7 +2793,7 @@ pub fn build_session_options(handler: &mut EarlyDiagCtxt, matches: &getopts::Mat
let uses_unstable_self_contained_option = let uses_unstable_self_contained_option =
cg.link_self_contained.are_unstable_variants_set(); cg.link_self_contained.are_unstable_variants_set();
if uses_unstable_self_contained_option { if uses_unstable_self_contained_option {
handler.early_error( early_dcx.early_error(
"only `-C link-self-contained` values `y`/`yes`/`on`/`n`/`no`/`off` are stable, \ "only `-C link-self-contained` values `y`/`yes`/`on`/`n`/`no`/`off` are stable, \
the `-Z unstable-options` flag must also be passed to use the unstable values", the `-Z unstable-options` flag must also be passed to use the unstable values",
); );
@ -2801,7 +2801,7 @@ pub fn build_session_options(handler: &mut EarlyDiagCtxt, matches: &getopts::Mat
if let Some(flavor) = cg.linker_flavor { if let Some(flavor) = cg.linker_flavor {
if flavor.is_unstable() { if flavor.is_unstable() {
handler.early_error(format!( early_dcx.early_error(format!(
"the linker flavor `{}` is unstable, the `-Z unstable-options` \ "the linker flavor `{}` is unstable, the `-Z unstable-options` \
flag must also be passed to use the unstable values", flag must also be passed to use the unstable values",
flavor.desc() flavor.desc()
@ -2818,18 +2818,18 @@ pub fn build_session_options(handler: &mut EarlyDiagCtxt, matches: &getopts::Mat
.map(|c| c.as_str().unwrap()) .map(|c| c.as_str().unwrap())
.intersperse(", ") .intersperse(", ")
.collect(); .collect();
handler.early_error(format!( early_dcx.early_error(format!(
"some `-C link-self-contained` components were both enabled and disabled: {names}" "some `-C link-self-contained` components were both enabled and disabled: {names}"
)); ));
} }
let prints = collect_print_requests(handler, &mut cg, &mut unstable_opts, matches); let prints = collect_print_requests(early_dcx, &mut cg, &mut unstable_opts, matches);
let cg = cg; let cg = cg;
let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m)); let sysroot_opt = matches.opt_str("sysroot").map(|m| PathBuf::from(&m));
let target_triple = parse_target_triple(handler, matches); let target_triple = parse_target_triple(early_dcx, matches);
let opt_level = parse_opt_level(handler, matches, &cg); let opt_level = parse_opt_level(early_dcx, matches, &cg);
// The `-g` and `-C debuginfo` flags specify the same setting, so we want to be able // The `-g` and `-C debuginfo` flags specify the same setting, so we want to be able
// to use them interchangeably. See the note above (regarding `-O` and `-C opt-level`) // to use them interchangeably. See the note above (regarding `-O` and `-C opt-level`)
// for more details. // for more details.
@ -2839,35 +2839,35 @@ pub fn build_session_options(handler: &mut EarlyDiagCtxt, matches: &getopts::Mat
let mut search_paths = vec![]; let mut search_paths = vec![];
for s in &matches.opt_strs("L") { for s in &matches.opt_strs("L") {
search_paths.push(SearchPath::from_cli_opt(handler, s)); search_paths.push(SearchPath::from_cli_opt(early_dcx, s));
} }
let libs = parse_libs(handler, matches); let libs = parse_libs(early_dcx, matches);
let test = matches.opt_present("test"); let test = matches.opt_present("test");
if !cg.remark.is_empty() && debuginfo == DebugInfo::None { if !cg.remark.is_empty() && debuginfo == DebugInfo::None {
handler.early_warn("-C remark requires \"-C debuginfo=n\" to show source locations"); early_dcx.early_warn("-C remark requires \"-C debuginfo=n\" to show source locations");
} }
if cg.remark.is_empty() && unstable_opts.remark_dir.is_some() { if cg.remark.is_empty() && unstable_opts.remark_dir.is_some() {
handler.early_warn("using -Z remark-dir without enabling remarks using e.g. -C remark=all"); early_dcx.early_warn("using -Z remark-dir without enabling remarks using e.g. -C remark=all");
} }
let externs = parse_externs(handler, matches, &unstable_opts); let externs = parse_externs(early_dcx, matches, &unstable_opts);
let crate_name = matches.opt_str("crate-name"); let crate_name = matches.opt_str("crate-name");
let remap_path_prefix = parse_remap_path_prefix(handler, matches, &unstable_opts); let remap_path_prefix = parse_remap_path_prefix(early_dcx, matches, &unstable_opts);
let pretty = parse_pretty(handler, &unstable_opts); let pretty = parse_pretty(early_dcx, &unstable_opts);
// query-dep-graph is required if dump-dep-graph is given #106736 // query-dep-graph is required if dump-dep-graph is given #106736
if unstable_opts.dump_dep_graph && !unstable_opts.query_dep_graph { if unstable_opts.dump_dep_graph && !unstable_opts.query_dep_graph {
handler.early_error("can't dump dependency graph without `-Z query-dep-graph`"); early_dcx.early_error("can't dump dependency graph without `-Z query-dep-graph`");
} }
let logical_env = parse_logical_env(handler, matches); let logical_env = parse_logical_env(early_dcx, matches);
// Try to find a directory containing the Rust `src`, for more details see // Try to find a directory containing the Rust `src`, for more details see
// the doc comment on the `real_rust_source_base_dir` field. // the doc comment on the `real_rust_source_base_dir` field.
@ -2898,7 +2898,7 @@ pub fn build_session_options(handler: &mut EarlyDiagCtxt, matches: &getopts::Mat
}; };
let working_dir = std::env::current_dir().unwrap_or_else(|e| { let working_dir = std::env::current_dir().unwrap_or_else(|e| {
handler.early_error(format!("Current directory is invalid: {e}")); early_dcx.early_error(format!("Current directory is invalid: {e}"));
}); });
let remap = file_path_mapping(remap_path_prefix.clone(), &unstable_opts); let remap = file_path_mapping(remap_path_prefix.clone(), &unstable_opts);
@ -2953,7 +2953,7 @@ pub fn build_session_options(handler: &mut EarlyDiagCtxt, matches: &getopts::Mat
} }
} }
fn parse_pretty(handler: &EarlyDiagCtxt, unstable_opts: &UnstableOptions) -> Option<PpMode> { fn parse_pretty(early_dcx: &EarlyDiagCtxt, unstable_opts: &UnstableOptions) -> Option<PpMode> {
use PpMode::*; use PpMode::*;
let first = match unstable_opts.unpretty.as_deref()? { let first = match unstable_opts.unpretty.as_deref()? {
@ -2973,7 +2973,7 @@ fn parse_pretty(handler: &EarlyDiagCtxt, unstable_opts: &UnstableOptions) -> Opt
"mir" => Mir, "mir" => Mir,
"stable-mir" => StableMir, "stable-mir" => StableMir,
"mir-cfg" => MirCFG, "mir-cfg" => MirCFG,
name => handler.early_error(format!( name => early_dcx.early_error(format!(
"argument to `unpretty` must be one of `normal`, `identified`, \ "argument to `unpretty` must be one of `normal`, `identified`, \
`expanded`, `expanded,identified`, `expanded,hygiene`, \ `expanded`, `expanded,identified`, `expanded,hygiene`, \
`ast-tree`, `ast-tree,expanded`, `hir`, `hir,identified`, \ `ast-tree`, `ast-tree,expanded`, `hir`, `hir,identified`, \
@ -3037,7 +3037,7 @@ pub mod nightly_options {
} }
pub fn check_nightly_options( pub fn check_nightly_options(
handler: &EarlyDiagCtxt, early_dcx: &EarlyDiagCtxt,
matches: &getopts::Matches, matches: &getopts::Matches,
flags: &[RustcOptGroup], flags: &[RustcOptGroup],
) { ) {
@ -3053,7 +3053,7 @@ pub mod nightly_options {
continue; continue;
} }
if opt.name != "Z" && !has_z_unstable_option { if opt.name != "Z" && !has_z_unstable_option {
handler.early_error(format!( early_dcx.early_error(format!(
"the `-Z unstable-options` flag must also be passed to enable \ "the `-Z unstable-options` flag must also be passed to enable \
the flag `{}`", the flag `{}`",
opt.name opt.name
@ -3069,17 +3069,17 @@ pub mod nightly_options {
"the option `{}` is only accepted on the nightly compiler", "the option `{}` is only accepted on the nightly compiler",
opt.name opt.name
); );
let _ = handler.early_error_no_abort(msg); let _ = early_dcx.early_error_no_abort(msg);
} }
OptionStability::Stable => {} OptionStability::Stable => {}
} }
} }
if nightly_options_on_stable > 0 { if nightly_options_on_stable > 0 {
handler early_dcx
.early_help("consider switching to a nightly toolchain: `rustup default nightly`"); .early_help("consider switching to a nightly toolchain: `rustup default nightly`");
handler.early_note("selecting a toolchain with `+toolchain` arguments require a rustup proxy; see <https://rust-lang.github.io/rustup/concepts/index.html>"); early_dcx.early_note("selecting a toolchain with `+toolchain` arguments require a rustup proxy; see <https://rust-lang.github.io/rustup/concepts/index.html>");
handler.early_note("for more information about Rust's stability policy, see <https://doc.rust-lang.org/book/appendix-07-nightly-rust.html#unstable-features>"); early_dcx.early_note("for more information about Rust's stability policy, see <https://doc.rust-lang.org/book/appendix-07-nightly-rust.html#unstable-features>");
handler.early_error(format!( early_dcx.early_error(format!(
"{} nightly option{} were parsed", "{} nightly option{} were parsed",
nightly_options_on_stable, nightly_options_on_stable,
if nightly_options_on_stable > 1 { "s" } else { "" } if nightly_options_on_stable > 1 { "s" } else { "" }

View file

@ -255,10 +255,10 @@ macro_rules! options {
impl $struct_name { impl $struct_name {
pub fn build( pub fn build(
handler: &EarlyDiagCtxt, early_dcx: &EarlyDiagCtxt,
matches: &getopts::Matches, matches: &getopts::Matches,
) -> $struct_name { ) -> $struct_name {
build_options(handler, matches, $stat, $prefix, $outputname) build_options(early_dcx, matches, $stat, $prefix, $outputname)
} }
fn dep_tracking_hash(&self, for_crate_hash: bool, error_format: ErrorOutputType) -> u64 { fn dep_tracking_hash(&self, for_crate_hash: bool, error_format: ErrorOutputType) -> u64 {
@ -319,7 +319,7 @@ type OptionSetter<O> = fn(&mut O, v: Option<&str>) -> bool;
type OptionDescrs<O> = &'static [(&'static str, OptionSetter<O>, &'static str, &'static str)]; type OptionDescrs<O> = &'static [(&'static str, OptionSetter<O>, &'static str, &'static str)];
fn build_options<O: Default>( fn build_options<O: Default>(
handler: &EarlyDiagCtxt, early_dcx: &EarlyDiagCtxt,
matches: &getopts::Matches, matches: &getopts::Matches,
descrs: OptionDescrs<O>, descrs: OptionDescrs<O>,
prefix: &str, prefix: &str,
@ -337,12 +337,12 @@ fn build_options<O: Default>(
Some((_, setter, type_desc, _)) => { Some((_, setter, type_desc, _)) => {
if !setter(&mut op, value) { if !setter(&mut op, value) {
match value { match value {
None => handler.early_error( None => early_dcx.early_error(
format!( format!(
"{outputname} option `{key}` requires {type_desc} ({prefix} {key}=<value>)" "{outputname} option `{key}` requires {type_desc} ({prefix} {key}=<value>)"
), ),
), ),
Some(value) => handler.early_error( Some(value) => early_dcx.early_error(
format!( format!(
"incorrect value `{value}` for {outputname} option `{key}` - {type_desc} was expected" "incorrect value `{value}` for {outputname} option `{key}` - {type_desc} was expected"
), ),
@ -350,7 +350,7 @@ fn build_options<O: Default>(
} }
} }
} }
None => handler.early_error(format!("unknown {outputname} option: `{key}`")), None => early_dcx.early_error(format!("unknown {outputname} option: `{key}`")),
} }
} }
return op; return op;

View file

@ -46,7 +46,7 @@ impl PathKind {
} }
impl SearchPath { impl SearchPath {
pub fn from_cli_opt(handler: &EarlyDiagCtxt, path: &str) -> Self { pub fn from_cli_opt(early_dcx: &EarlyDiagCtxt, path: &str) -> Self {
let (kind, path) = if let Some(stripped) = path.strip_prefix("native=") { let (kind, path) = if let Some(stripped) = path.strip_prefix("native=") {
(PathKind::Native, stripped) (PathKind::Native, stripped)
} else if let Some(stripped) = path.strip_prefix("crate=") { } else if let Some(stripped) = path.strip_prefix("crate=") {
@ -61,7 +61,7 @@ impl SearchPath {
(PathKind::All, path) (PathKind::All, path)
}; };
if path.is_empty() { if path.is_empty() {
handler.early_error("empty search path given via `-L`"); early_dcx.early_error("empty search path given via `-L`");
} }
let dir = PathBuf::from(path); let dir = PathBuf::from(path);

View file

@ -1357,7 +1357,7 @@ fn default_emitter(
// JUSTIFICATION: literally session construction // JUSTIFICATION: literally session construction
#[allow(rustc::bad_opt_access)] #[allow(rustc::bad_opt_access)]
pub fn build_session( pub fn build_session(
early_handler: EarlyDiagCtxt, early_dcx: EarlyDiagCtxt,
sopts: config::Options, sopts: config::Options,
io: CompilerIO, io: CompilerIO,
bundle: Option<Lrc<rustc_errors::FluentBundle>>, bundle: Option<Lrc<rustc_errors::FluentBundle>>,
@ -1387,13 +1387,13 @@ pub fn build_session(
None => filesearch::get_or_default_sysroot().expect("Failed finding sysroot"), None => filesearch::get_or_default_sysroot().expect("Failed finding sysroot"),
}; };
let target_cfg = config::build_target_config(&early_handler, &sopts, target_override, &sysroot); let target_cfg = config::build_target_config(&early_dcx, &sopts, target_override, &sysroot);
let host_triple = TargetTriple::from_triple(config::host_triple()); let host_triple = TargetTriple::from_triple(config::host_triple());
let (host, target_warnings) = Target::search(&host_triple, &sysroot).unwrap_or_else(|e| { let (host, target_warnings) = Target::search(&host_triple, &sysroot).unwrap_or_else(|e| {
early_handler.early_error(format!("Error loading host specification: {e}")) early_dcx.early_error(format!("Error loading host specification: {e}"))
}); });
for warning in target_warnings.warning_messages() { for warning in target_warnings.warning_messages() {
early_handler.early_warn(warning) early_dcx.early_warn(warning)
} }
let loader = file_loader.unwrap_or_else(|| Box::new(RealFileLoader)); let loader = file_loader.unwrap_or_else(|| Box::new(RealFileLoader));
@ -1422,9 +1422,9 @@ pub fn build_session(
span_diagnostic = span_diagnostic.with_ice_file(ice_file); span_diagnostic = span_diagnostic.with_ice_file(ice_file);
} }
// Now that the proper handler has been constructed, drop the early handler // Now that the proper handler has been constructed, drop early_dcx to
// to prevent accidental use. // prevent accidental use.
drop(early_handler); drop(early_dcx);
let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile let self_profiler = if let SwitchWithOptPath::Enabled(ref d) = sopts.unstable_opts.self_profile
{ {

View file

@ -320,33 +320,33 @@ impl Options {
/// Parses the given command-line for options. If an error message or other early-return has /// Parses the given command-line for options. If an error message or other early-return has
/// been printed, returns `Err` with the exit code. /// been printed, returns `Err` with the exit code.
pub(crate) fn from_matches( pub(crate) fn from_matches(
handler: &mut EarlyDiagCtxt, early_dcx: &mut EarlyDiagCtxt,
matches: &getopts::Matches, matches: &getopts::Matches,
args: Vec<String>, args: Vec<String>,
) -> Result<(Options, RenderOptions), i32> { ) -> Result<(Options, RenderOptions), i32> {
// Check for unstable options. // Check for unstable options.
nightly_options::check_nightly_options(handler, 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 Err(0);
} else if matches.opt_present("version") { } else if matches.opt_present("version") {
rustc_driver::version!(&handler, "rustdoc", matches); rustc_driver::version!(&early_dcx, "rustdoc", matches);
return Err(0); return Err(0);
} }
if rustc_driver::describe_flag_categories(handler, &matches) { if rustc_driver::describe_flag_categories(early_dcx, &matches) {
return Err(0); return Err(0);
} }
let color = config::parse_color(handler, matches); let color = config::parse_color(early_dcx, matches);
let config::JsonConfig { json_rendered, json_unused_externs, .. } = let config::JsonConfig { json_rendered, json_unused_externs, .. } =
config::parse_json(handler, matches); config::parse_json(early_dcx, matches);
let error_format = config::parse_error_format(handler, matches, color, json_rendered); let error_format = config::parse_error_format(early_dcx, matches, color, json_rendered);
let diagnostic_width = matches.opt_get("diagnostic-width").unwrap_or_default(); let diagnostic_width = matches.opt_get("diagnostic-width").unwrap_or_default();
let codegen_options = CodegenOptions::build(handler, matches); let codegen_options = CodegenOptions::build(early_dcx, matches);
let unstable_opts = UnstableOptions::build(handler, matches); let unstable_opts = UnstableOptions::build(early_dcx, matches);
let diag = new_dcx(error_format, None, diagnostic_width, &unstable_opts); let diag = new_dcx(error_format, None, diagnostic_width, &unstable_opts);
@ -403,7 +403,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)
{ {
handler.early_error( early_dcx.early_error(
"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)",
); );
} }
@ -447,7 +447,7 @@ impl Options {
return Err(0); return Err(0);
} }
let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(handler, matches); let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(early_dcx, matches);
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
@ -462,8 +462,8 @@ impl Options {
}); });
let libs = let libs =
matches.opt_strs("L").iter().map(|s| SearchPath::from_cli_opt(handler, s)).collect(); matches.opt_strs("L").iter().map(|s| SearchPath::from_cli_opt(early_dcx, s)).collect();
let externs = parse_externs(handler, 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) => {
@ -605,7 +605,7 @@ impl Options {
} }
} }
let edition = config::parse_crate_edition(handler, matches); let edition = config::parse_crate_edition(early_dcx, matches);
let mut id_map = html::markdown::IdMap::new(); let mut id_map = html::markdown::IdMap::new();
let Some(external_html) = ExternalHtml::load( let Some(external_html) = ExternalHtml::load(
@ -639,7 +639,7 @@ impl Options {
} }
} }
let target = parse_target_triple(handler, matches); let target = parse_target_triple(early_dcx, matches);
let show_coverage = matches.opt_present("show-coverage"); let show_coverage = matches.opt_present("show-coverage");

View file

@ -189,15 +189,15 @@ pub fn main() {
process::exit(exit_code); process::exit(exit_code);
} }
fn init_logging(handler: &EarlyDiagCtxt) { fn init_logging(early_dcx: &EarlyDiagCtxt) {
let color_logs = match std::env::var("RUSTDOC_LOG_COLOR").as_deref() { let color_logs = match std::env::var("RUSTDOC_LOG_COLOR").as_deref() {
Ok("always") => true, Ok("always") => true,
Ok("never") => false, Ok("never") => false,
Ok("auto") | Err(VarError::NotPresent) => io::stdout().is_terminal(), Ok("auto") | Err(VarError::NotPresent) => io::stdout().is_terminal(),
Ok(value) => handler.early_error(format!( Ok(value) => early_dcx.early_error(format!(
"invalid log color value '{value}': expected one of always, never, or auto", "invalid log color value '{value}': expected one of always, never, or auto",
)), )),
Err(VarError::NotUnicode(value)) => handler.early_error(format!( Err(VarError::NotUnicode(value)) => early_dcx.early_error(format!(
"invalid log color value '{}': expected one of always, never, or auto", "invalid log color value '{}': expected one of always, never, or auto",
value.to_string_lossy() value.to_string_lossy()
)), )),
@ -220,13 +220,13 @@ fn init_logging(handler: &EarlyDiagCtxt) {
tracing::subscriber::set_global_default(subscriber).unwrap(); tracing::subscriber::set_global_default(subscriber).unwrap();
} }
fn get_args(handler: &EarlyDiagCtxt) -> Option<Vec<String>> { fn get_args(early_dcx: &EarlyDiagCtxt) -> Option<Vec<String>> {
env::args_os() env::args_os()
.enumerate() .enumerate()
.map(|(i, arg)| { .map(|(i, arg)| {
arg.into_string() arg.into_string()
.map_err(|arg| { .map_err(|arg| {
handler.early_warn(format!("Argument {i} is not valid Unicode: {arg:?}")); early_dcx.early_warn(format!("Argument {i} is not valid Unicode: {arg:?}"));
}) })
.ok() .ok()
}) })
@ -704,7 +704,7 @@ fn run_renderer<'tcx, T: formats::FormatRenderer<'tcx>>(
} }
fn main_args( fn main_args(
handler: &mut EarlyDiagCtxt, early_dcx: &mut EarlyDiagCtxt,
at_args: &[String], at_args: &[String],
using_internal_features: Arc<AtomicBool>, using_internal_features: Arc<AtomicBool>,
) -> MainResult { ) -> MainResult {
@ -718,7 +718,7 @@ fn main_args(
// the compiler with @empty_file as argv[0] and no more arguments. // the compiler with @empty_file as argv[0] and no more arguments.
let at_args = at_args.get(1..).unwrap_or_default(); let at_args = at_args.get(1..).unwrap_or_default();
let args = rustc_driver::args::arg_expand_all(handler, at_args); let args = rustc_driver::args::arg_expand_all(early_dcx, at_args);
let mut options = getopts::Options::new(); let mut options = getopts::Options::new();
for option in opts() { for option in opts() {
@ -727,13 +727,13 @@ fn main_args(
let matches = match options.parse(&args) { let matches = match options.parse(&args) {
Ok(m) => m, Ok(m) => m,
Err(err) => { Err(err) => {
handler.early_error(err.to_string()); early_dcx.early_error(err.to_string());
} }
}; };
// 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(handler, &matches, args) { let (options, render_options) = match config::Options::from_matches(early_dcx, &matches, args) {
Ok(opts) => opts, Ok(opts) => opts,
Err(code) => { Err(code) => {
return if code == 0 { return if code == 0 {

View file

@ -215,7 +215,7 @@ fn rustc_logger_config() -> rustc_log::LoggerConfig {
cfg cfg
} }
fn init_early_loggers(handler: &EarlyDiagCtxt) { fn init_early_loggers(early_dcx: &EarlyDiagCtxt) {
// Note that our `extern crate log` is *not* the same as rustc's; as a result, we have to // Note that our `extern crate log` is *not* the same as rustc's; as a result, we have to
// initialize them both, and we always initialize `miri`'s first. // initialize them both, and we always initialize `miri`'s first.
let env = env_logger::Env::new().filter("MIRI_LOG").write_style("MIRI_LOG_STYLE"); let env = env_logger::Env::new().filter("MIRI_LOG").write_style("MIRI_LOG_STYLE");
@ -224,15 +224,15 @@ fn init_early_loggers(handler: &EarlyDiagCtxt) {
// If it is not set, we avoid initializing now so that we can initialize later with our custom // If it is not set, we avoid initializing now so that we can initialize later with our custom
// settings, and *not* log anything for what happens before `miri` gets started. // settings, and *not* log anything for what happens before `miri` gets started.
if env::var_os("RUSTC_LOG").is_some() { if env::var_os("RUSTC_LOG").is_some() {
rustc_driver::init_logger(handler, rustc_logger_config()); rustc_driver::init_logger(early_dcx, rustc_logger_config());
} }
} }
fn init_late_loggers(handler: &EarlyDiagCtxt, tcx: TyCtxt<'_>) { fn init_late_loggers(early_dcx: &EarlyDiagCtxt, tcx: TyCtxt<'_>) {
// If `RUSTC_LOG` is not set, then `init_early_loggers` did not call // If `RUSTC_LOG` is not set, then `init_early_loggers` did not call
// `rustc_driver::init_logger`, so we have to do this now. // `rustc_driver::init_logger`, so we have to do this now.
if env::var_os("RUSTC_LOG").is_none() { if env::var_os("RUSTC_LOG").is_none() {
rustc_driver::init_logger(handler, rustc_logger_config()); rustc_driver::init_logger(early_dcx, rustc_logger_config());
} }
// If `MIRI_BACKTRACE` is set and `RUSTC_CTFE_BACKTRACE` is not, set `RUSTC_CTFE_BACKTRACE`. // If `MIRI_BACKTRACE` is set and `RUSTC_CTFE_BACKTRACE` is not, set `RUSTC_CTFE_BACKTRACE`.