Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid &format("...") calls in error message code. #111633

Merged
merged 2 commits into from
May 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions compiler/rustc_abi/src/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use tracing::debug;
pub trait LayoutCalculator {
type TargetDataLayoutRef: Borrow<TargetDataLayout>;

fn delay_bug(&self, txt: &str);
fn delay_bug(&self, txt: String);
fn current_data_layout(&self) -> Self::TargetDataLayoutRef;

fn scalar_pair(&self, a: Scalar, b: Scalar) -> LayoutS {
Expand Down Expand Up @@ -969,7 +969,7 @@ fn univariant(
for &i in &inverse_memory_index {
let field = &fields[i];
if !sized {
this.delay_bug(&format!(
this.delay_bug(format!(
"univariant: field #{} comes after unsized field",
offsets.len(),
));
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_borrowck/src/nll.rs
Original file line number Diff line number Diff line change
Expand Up @@ -430,7 +430,7 @@ pub(super) fn dump_annotation<'tcx>(
fn for_each_region_constraint<'tcx>(
tcx: TyCtxt<'tcx>,
closure_region_requirements: &ClosureRegionRequirements<'tcx>,
with_msg: &mut dyn FnMut(&str) -> io::Result<()>,
with_msg: &mut dyn FnMut(String) -> io::Result<()>,
) -> io::Result<()> {
for req in &closure_region_requirements.outlives_requirements {
let subject = match req.subject {
Expand All @@ -439,7 +439,7 @@ fn for_each_region_constraint<'tcx>(
format!("{:?}", ty.instantiate(tcx, |vid| tcx.mk_re_var(vid)))
}
};
with_msg(&format!("where {}: {:?}", subject, req.outlived_free_region,))?;
with_msg(format!("where {}: {:?}", subject, req.outlived_free_region,))?;
}
Ok(())
}
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_borrowck/src/type_check/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ macro_rules! span_mirbug {
$crate::type_check::mirbug(
$context.tcx(),
$context.last_span,
&format!(
format!(
"broken MIR in {:?} ({:?}): {}",
$context.body().source.def_id(),
$elem,
Expand Down Expand Up @@ -274,7 +274,7 @@ fn translate_outlives_facts(typeck: &mut TypeChecker<'_, '_>) {
}

#[track_caller]
fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: &str) {
fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: String) {
// We sometimes see MIR failures (notably predicate failures) due to
// the fact that we check rvalue sized predicates here. So use `delay_span_bug`
// to avoid reporting bugs in those cases.
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_builtin_macros/src/asm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -550,7 +550,7 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
if !parser.errors.is_empty() {
let err = parser.errors.remove(0);
let err_sp = template_span.from_inner(InnerSpan::new(err.span.start, err.span.end));
let msg = &format!("invalid asm template string: {}", err.description);
let msg = format!("invalid asm template string: {}", err.description);
let mut e = ecx.struct_span_err(err_sp, msg);
e.span_label(err_sp, err.label + " in asm template string");
if let Some(note) = err.note {
Expand Down Expand Up @@ -585,7 +585,7 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
|| args.reg_args.contains(idx)
{
let msg = format!("invalid reference to argument at index {}", idx);
let mut err = ecx.struct_span_err(span, &msg);
let mut err = ecx.struct_span_err(span, msg);
err.span_label(span, "from here");

let positional_args = args.operands.len()
Expand Down Expand Up @@ -638,7 +638,7 @@ fn expand_preparsed_asm(ecx: &mut ExtCtxt<'_>, args: AsmArgs) -> Option<ast::Inl
ecx.struct_span_err(
template_span
.from_inner(InnerSpan::new(span.start, span.end)),
&msg,
msg,
)
.emit();
None
Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_builtin_macros/src/deriving/clone.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ fn cs_clone_simple(
}
_ => cx.span_bug(
trait_span,
&format!("unexpected substructure in simple `derive({})`", name),
format!("unexpected substructure in simple `derive({})`", name),
),
}
}
Expand Down Expand Up @@ -179,10 +179,10 @@ fn cs_clone(
vdata = &variant.data;
}
EnumTag(..) | AllFieldlessEnum(..) => {
cx.span_bug(trait_span, &format!("enum tags in `derive({})`", name,))
cx.span_bug(trait_span, format!("enum tags in `derive({})`", name,))
}
StaticEnum(..) | StaticStruct(..) => {
cx.span_bug(trait_span, &format!("associated function in `derive({})`", name))
cx.span_bug(trait_span, format!("associated function in `derive({})`", name))
}
}

Expand All @@ -194,7 +194,7 @@ fn cs_clone(
let Some(ident) = field.name else {
cx.span_bug(
trait_span,
&format!("unnamed field in normal struct in `derive({})`", name,),
format!("unnamed field in normal struct in `derive({})`", name,),
);
};
let call = subcall(cx, field);
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_builtin_macros/src/deriving/generic/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1591,7 +1591,7 @@ impl<'a> TraitDef<'a> {
BYTE_SLICE_IN_PACKED_STRUCT_WITH_DERIVE,
sp,
ast::CRATE_NODE_ID,
&format!(
format!(
"{} slice in a packed struct that derives a built-in trait",
ty
),
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_builtin_macros/src/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -814,7 +814,7 @@ fn report_invalid_references(
};
e = ecx.struct_span_err(
span,
&format!("invalid reference to positional {} ({})", arg_list, num_args_desc),
format!("invalid reference to positional {} ({})", arg_list, num_args_desc),
);
e.note("positional arguments are zero-based");
}
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_builtin_macros/src/source_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,12 +188,12 @@ pub fn expand_include_str(
base::MacEager::expr(cx.expr_str(sp, interned_src))
}
Err(_) => {
cx.span_err(sp, &format!("{} wasn't a utf-8 file", file.display()));
cx.span_err(sp, format!("{} wasn't a utf-8 file", file.display()));
DummyResult::any(sp)
}
},
Err(e) => {
cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
cx.span_err(sp, format!("couldn't read {}: {}", file.display(), e));
DummyResult::any(sp)
}
}
Expand Down Expand Up @@ -221,7 +221,7 @@ pub fn expand_include_bytes(
base::MacEager::expr(expr)
}
Err(e) => {
cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
cx.span_err(sp, format!("couldn't read {}: {}", file.display(), e));
DummyResult::any(sp)
}
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_cranelift/src/pretty_clif.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ pub(crate) fn write_ir_file(
// Using early_warn as no Session is available here
rustc_session::early_warn(
rustc_session::config::ErrorOutputType::default(),
&format!("error writing ir file: {}", err),
format!("error writing ir file: {}", err),
);
}
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_driver_impl/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub fn arg_expand_all(at_args: &[String]) -> Vec<String> {
Ok(arg) => args.extend(arg),
Err(err) => rustc_session::early_error(
rustc_session::config::ErrorOutputType::default(),
&format!("Failed to load argument file: {err}"),
format!("Failed to load argument file: {err}"),
),
}
}
Expand Down
12 changes: 6 additions & 6 deletions compiler/rustc_driver_impl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ fn run_compiler(
1 => panic!("make_input should have provided valid inputs"),
_ => early_error(
config.opts.error_format,
&format!(
format!(
"multiple input filenames provided (first two filenames are `{}` and `{}`)",
matches.free[0], matches.free[1],
),
Expand Down Expand Up @@ -527,7 +527,7 @@ fn handle_explain(registry: Registry, code: &str, output: ErrorOutputType) {
}
}
Err(InvalidErrorCode) => {
early_error(output, &format!("{code} is not a valid error code"));
early_error(output, format!("{code} is not a valid error code"));
}
}
}
Expand Down Expand Up @@ -1102,7 +1102,7 @@ pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
.map(|(flag, _)| format!("{e}. Did you mean `-{flag} {opt}`?")),
_ => None,
};
early_error(ErrorOutputType::default(), &msg.unwrap_or_else(|| e.to_string()));
early_error(ErrorOutputType::default(), msg.unwrap_or_else(|| e.to_string()));
});

// For all options we just parsed, we check a few aspects:
Expand Down Expand Up @@ -1250,7 +1250,7 @@ pub fn install_ice_hook(bug_report_url: &'static str, extra_info: fn(&Handler))
#[cfg(windows)]
if let Some(msg) = info.payload().downcast_ref::<String>() {
if msg.starts_with("failed printing to stdout: ") && msg.ends_with("(os error 232)") {
early_error_no_abort(ErrorOutputType::default(), &msg);
early_error_no_abort(ErrorOutputType::default(), msg.as_str());
WaffleLapkin marked this conversation as resolved.
Show resolved Hide resolved
return;
}
};
Expand Down Expand Up @@ -1342,7 +1342,7 @@ pub fn init_rustc_env_logger() {
/// other than `RUSTC_LOG`.
pub fn init_env_logger(env: &str) {
if let Err(error) = rustc_log::init_env_logger(env) {
early_error(ErrorOutputType::default(), &error.to_string());
early_error(ErrorOutputType::default(), error.to_string());
}
}

Expand Down Expand Up @@ -1409,7 +1409,7 @@ pub fn main() -> ! {
arg.into_string().unwrap_or_else(|arg| {
early_error(
ErrorOutputType::default(),
&format!("argument {i} is not valid Unicode: {arg:?}"),
format!("argument {i} is not valid Unicode: {arg:?}"),
)
})
})
Expand Down
11 changes: 6 additions & 5 deletions compiler/rustc_expand/src/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ use rustc_attr::{self as attr, Deprecation, Stability};
use rustc_data_structures::fx::FxIndexMap;
use rustc_data_structures::sync::{self, Lrc};
use rustc_errors::{
Applicability, DiagnosticBuilder, ErrorGuaranteed, IntoDiagnostic, MultiSpan, PResult,
Applicability, DiagnosticBuilder, DiagnosticMessage, ErrorGuaranteed, IntoDiagnostic,
MultiSpan, PResult,
};
use rustc_lint_defs::builtin::PROC_MACRO_BACK_COMPAT;
use rustc_lint_defs::{BufferedEarlyLint, BuiltinLintDiagnostics, RegisteredTools};
Expand Down Expand Up @@ -1110,7 +1111,7 @@ impl<'a> ExtCtxt<'a> {
pub fn struct_span_err<S: Into<MultiSpan>>(
&self,
sp: S,
msg: &str,
msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
self.sess.parse_sess.span_diagnostic.struct_span_err(sp, msg)
}
Expand All @@ -1132,14 +1133,14 @@ impl<'a> ExtCtxt<'a> {
/// Compilation will be stopped in the near future (at the end of
/// the macro expansion phase).
#[rustc_lint_diagnostics]
pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: impl Into<DiagnosticMessage>) {
self.sess.parse_sess.span_diagnostic.span_err(sp, msg);
}
#[rustc_lint_diagnostics]
pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: impl Into<DiagnosticMessage>) {
self.sess.parse_sess.span_diagnostic.span_warn(sp, msg);
}
pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: impl Into<DiagnosticMessage>) -> ! {
self.sess.parse_sess.span_diagnostic.span_bug(sp, msg);
}
pub fn trace_macros_diag(&mut self) {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_expand/src/expand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1664,7 +1664,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> {
&UNUSED_ATTRIBUTES,
attr.span,
self.cx.current_expansion.lint_node_id,
&format!("unused attribute `{}`", attr_name),
format!("unused attribute `{}`", attr_name),
BuiltinLintDiagnostics::UnusedBuiltinAttribute {
attr_name,
macro_name: pprust::path_to_string(&call.path),
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_expand/src/mbe/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ pub(super) fn failed_to_match_macro<'cx>(

let span = token.span.substitute_dummy(sp);

let mut err = cx.struct_span_err(span, &parse_failure_msg(&token));
let mut err = cx.struct_span_err(span, parse_failure_msg(&token));
err.span_label(span, label);
if !def_span.is_dummy() && !cx.source_map().is_imported(def_span) {
err.span_label(cx.source_map().guess_head_span(def_span), "when calling this macro");
Expand Down Expand Up @@ -170,7 +170,7 @@ impl<'a, 'cx, 'matcher> Tracker<'matcher> for CollectTrackerAndEmitter<'a, 'cx,
}
Error(err_sp, msg) => {
let span = err_sp.substitute_dummy(self.root_span);
self.cx.struct_span_err(span, msg).emit();
self.cx.struct_span_err(span, msg.as_str()).emit();
WaffleLapkin marked this conversation as resolved.
Show resolved Hide resolved
self.result = Some(DummyResult::any(span));
}
ErrorReported(_) => self.result = Some(DummyResult::any(self.root_span)),
Expand Down
13 changes: 9 additions & 4 deletions compiler/rustc_expand/src/mbe/macro_check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ use crate::mbe::{KleeneToken, TokenTree};
use rustc_ast::token::{Delimiter, Token, TokenKind};
use rustc_ast::{NodeId, DUMMY_NODE_ID};
use rustc_data_structures::fx::FxHashMap;
use rustc_errors::MultiSpan;
use rustc_errors::{DiagnosticMessage, MultiSpan};
use rustc_session::lint::builtin::{META_VARIABLE_MISUSE, MISSING_FRAGMENT_SPECIFIER};
use rustc_session::parse::ParseSess;
use rustc_span::symbol::kw;
Expand Down Expand Up @@ -593,7 +593,7 @@ fn check_ops_is_prefix(
return;
}
}
buffer_lint(sess, span.into(), node_id, &format!("unknown macro variable `{}`", name));
buffer_lint(sess, span.into(), node_id, format!("unknown macro variable `{}`", name));
}

/// Returns whether `binder_ops` is a prefix of `occurrence_ops`.
Expand Down Expand Up @@ -626,7 +626,7 @@ fn ops_is_prefix(
if i >= occurrence_ops.len() {
let mut span = MultiSpan::from_span(span);
span.push_span_label(binder.span, "expected repetition");
let message = &format!("variable '{}' is still repeating at this depth", name);
let message = format!("variable '{}' is still repeating at this depth", name);
buffer_lint(sess, span, node_id, message);
return;
}
Expand All @@ -642,7 +642,12 @@ fn ops_is_prefix(
}
}

fn buffer_lint(sess: &ParseSess, span: MultiSpan, node_id: NodeId, message: &str) {
fn buffer_lint(
sess: &ParseSess,
span: MultiSpan,
node_id: NodeId,
message: impl Into<DiagnosticMessage>,
) {
// Macros loaded from other crates have dummy node ids.
if node_id != DUMMY_NODE_ID {
sess.buffer_lint(&META_VARIABLE_MISUSE, span, node_id, message);
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_expand/src/mbe/transcribe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -510,7 +510,7 @@ fn out_of_bounds_err<'a>(
must be less than {max}"
)
};
cx.struct_span_err(span, &msg)
cx.struct_span_err(span, msg)
}

fn transcribe_metavar_expr<'a>(
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_hir_analysis/src/astconv/generics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ fn generic_arg_mismatch_err(
arg: &GenericArg<'_>,
param: &GenericParamDef,
possible_ordering_error: bool,
help: Option<&str>,
help: Option<String>,
) -> ErrorGuaranteed {
let sess = tcx.sess;
let mut err = struct_span_err!(
Expand Down Expand Up @@ -300,7 +300,7 @@ pub fn create_substs_for_generic_args<'tcx, 'a>(
arg,
param,
!args_iter.clone().is_sorted_by_key(|arg| arg.to_ord()),
Some(&format!(
Some(format!(
"reorder the arguments: {}: `<{}>`",
param_types_present
.into_iter()
Expand Down
Loading