Skip to content

Use write_str() instead of write!() when possible #109175

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

Closed
wants to merge 1 commit into from
Closed
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
2 changes: 1 addition & 1 deletion compiler/rustc_ast/src/util/literal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ impl fmt::Display for LitKind {
LitKind::Err => {
// This only shows up in places like `-Zunpretty=hir` output, so we
// don't bother to produce something useful.
write!(f, "<bad-literal>")?;
f.write_str("<bad-literal>")?;
}
}

Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_const_eval/src/const_eval/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ impl fmt::Display for ConstEvalErrKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use self::ConstEvalErrKind::*;
match self {
ConstAccessesStatic => write!(f, "constant accesses static"),
ConstAccessesStatic => f.write_str("constant accesses static"),
ModifiedGlobal => {
write!(f, "modifying a static's initial value from another static's initializer")
f.write_str("modifying a static's initial value from another static's initializer")
}
AssertFailure(msg) => write!(f, "{:?}", msg),
Panic { msg, line, col, file } => {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_const_eval/src/const_eval/machine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ pub enum MemoryKind {
impl fmt::Display for MemoryKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
MemoryKind::Heap => write!(f, "heap allocation"),
MemoryKind::Heap => f.write_str("heap allocation"),
}
}
}
Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_const_eval/src/interpret/eval_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ impl<'tcx> fmt::Display for FrameInfo<'tcx> {
if tcx.def_key(self.instance.def_id()).disambiguated_data.data
== DefPathData::ClosureExpr
{
write!(f, "inside closure")
f.write_str("inside closure")
} else {
// Note: this triggers a `good_path_bug` state, which means that if we ever get here
// we must emit a diagnostic. We should never display a `FrameInfo` unless we
Expand Down Expand Up @@ -987,12 +987,12 @@ impl<'a, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> std::fmt::Debug
if frame != self.ecx.frame_idx() {
write!(fmt, " ({} frames up)", self.ecx.frame_idx() - frame)?;
}
write!(fmt, ":")?;
fmt.write_str(":")?;

match self.ecx.stack()[frame].locals[local].value {
LocalValue::Dead => write!(fmt, " is dead")?,
LocalValue::Dead => fmt.write_str(" is dead")?,
LocalValue::Live(Operand::Immediate(Immediate::Uninit)) => {
write!(fmt, " is uninitialized")?
fmt.write_str(" is uninitialized")?
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unless benchmarks show that this is actually perf-critical, I'd rather stick to the old code and prioritize code readability and uniformity. It's better (IMO) to have the same uniform code for format strings with and without any interpolation.

}
LocalValue::Live(Operand::Indirect(mplace)) => {
write!(
Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_const_eval/src/interpret/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ impl<T: MayLeak> MayLeak for MemoryKind<T> {
impl<T: fmt::Display> fmt::Display for MemoryKind<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
MemoryKind::Stack => write!(f, "stack variable"),
MemoryKind::CallerLocation => write!(f, "caller location"),
MemoryKind::Stack => f.write_str("stack variable"),
MemoryKind::CallerLocation => f.write_str("caller location"),
MemoryKind::Machine(m) => write!(f, "{}", m),
}
}
Expand Down Expand Up @@ -893,7 +893,7 @@ impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> std::fmt::Debug for DumpAllocs<'a,
// global alloc
match self.ecx.tcx.try_get_global_alloc(id) {
Some(GlobalAlloc::Memory(alloc)) => {
write!(fmt, " (unchanged global, ")?;
fmt.write_str(" (unchanged global, ")?;
write_allocation_track_relocs(
&mut *fmt,
*self.ecx.tcx,
Expand All @@ -914,7 +914,7 @@ impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> std::fmt::Debug for DumpAllocs<'a,
write!(fmt, " (static: {})", self.ecx.tcx.def_path_str(did))?;
}
None => {
write!(fmt, " (deallocated)")?;
fmt.write_str(" (deallocated)")?;
}
}
}
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 @@ -41,7 +41,7 @@ pub enum Error {
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Utf8Error(None) => write!(fmt, "Utf8 error"),
Error::Utf8Error(None) => fmt.write_str("Utf8 error"),
Error::Utf8Error(Some(path)) => write!(fmt, "Utf8 error in {path}"),
Error::IOError(path, err) => write!(fmt, "IO Error: {path}: {err}"),
}
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_error_messages/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,15 @@ impl fmt::Display for TranslationBundleError {
write!(f, "could not parse ftl file: {}", e)
}
TranslationBundleError::AddResource(e) => write!(f, "failed to add resource: {}", e),
TranslationBundleError::MissingLocale => write!(f, "missing locale directory"),
TranslationBundleError::MissingLocale => f.write_str("missing locale directory"),
TranslationBundleError::ReadLocalesDir(e) => {
write!(f, "could not read locales dir: {}", e)
}
TranslationBundleError::ReadLocalesDirEntry(e) => {
write!(f, "could not read locales dir entry: {}", e)
}
TranslationBundleError::LocaleIsNotDir => {
write!(f, "`$sysroot/share/locales/$locale` is not a directory")
f.write_str("`$sysroot/share/locales/$locale` is not a directory")
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_expand/src/mbe/macro_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ impl Display for MatcherLoc {
if let Some(kind) = kind {
write!(f, ":{}", kind)?;
}
write!(f, "`")?;
f.write_str("`")?;
Ok(())
}
MatcherLoc::Eof => f.write_str("end of macro"),
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_feature/src/builtin_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ impl std::fmt::Debug for AttributeGate {
Self::Gated(ref stab, name, expl, _) => {
write!(fmt, "Gated({stab:?}, {name}, {expl})")
}
Self::Ungated => write!(fmt, "Ungated"),
Self::Ungated => fmt.write_str("Ungated"),
}
}
}
Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_feature/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@ pub enum State {
impl fmt::Debug for State {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
State::Accepted { .. } => write!(f, "accepted"),
State::Active { .. } => write!(f, "active"),
State::Removed { .. } => write!(f, "removed"),
State::Stabilized { .. } => write!(f, "stabilized"),
State::Accepted { .. } => f.write_str("accepted"),
State::Active { .. } => f.write_str("active"),
State::Removed { .. } => f.write_str("removed"),
State::Stabilized { .. } => f.write_str("stabilized"),
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_hir/src/hir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1620,9 +1620,9 @@ impl ConstContext {
impl fmt::Display for ConstContext {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::Const => write!(f, "constant"),
Self::Static(_) => write!(f, "static"),
Self::ConstFn => write!(f, "constant function"),
Self::Const => f.write_str("constant"),
Self::Static(_) => f.write_str("static"),
Self::ConstFn => f.write_str("constant function"),
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_infer/src/infer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -531,8 +531,8 @@ impl<'tcx> fmt::Display for FixupError<'tcx> {
"cannot determine the type of this number; \
add a suffix to specify the type explicitly"
),
UnresolvedTy(_) => write!(f, "unconstrained type"),
UnresolvedConst(_) => write!(f, "unconstrained const value"),
UnresolvedTy(_) => f.write_str("unconstrained type"),
UnresolvedConst(_) => f.write_str("unconstrained const value"),
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_infer/src/infer/region_constraints/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -702,7 +702,7 @@ impl<'tcx> RegionConstraintCollector<'_, 'tcx> {

impl fmt::Debug for RegionSnapshot {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "RegionSnapshot")
f.write_str("RegionSnapshot")
}
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_infer/src/traits/structural_impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ impl<'tcx> fmt::Debug for traits::FulfillmentErrorCode<'tcx> {
super::CodeConstEquateError(ref a, ref b) => {
write!(f, "CodeConstEquateError({:?}, {:?})", a, b)
}
super::CodeAmbiguity => write!(f, "Ambiguity"),
super::CodeAmbiguity => f.write_str("Ambiguity"),
super::CodeCycle(ref cycle) => write!(f, "Cycle({:?})", cycle),
}
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_interface/src/callbacks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ fn def_id_debug(def_id: rustc_hir::def_id::DefId, f: &mut fmt::Formatter<'_>) ->
}
Ok(())
})?;
write!(f, ")")
f.write_str(")")
}

/// Sets up the callbacks in prior crates which we want to refer to the
Expand Down
22 changes: 11 additions & 11 deletions compiler/rustc_macros/src/diagnostics/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -516,11 +516,11 @@ impl FromStr for SuggestionKind {
impl fmt::Display for SuggestionKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SuggestionKind::Normal => write!(f, "normal"),
SuggestionKind::Short => write!(f, "short"),
SuggestionKind::Hidden => write!(f, "hidden"),
SuggestionKind::Verbose => write!(f, "verbose"),
SuggestionKind::ToolOnly => write!(f, "tool-only"),
SuggestionKind::Normal => f.write_str("normal"),
SuggestionKind::Short => f.write_str("short"),
SuggestionKind::Hidden => f.write_str("hidden"),
SuggestionKind::Verbose => f.write_str("verbose"),
SuggestionKind::ToolOnly => f.write_str("tool-only"),
}
}
}
Expand Down Expand Up @@ -822,13 +822,13 @@ impl SubdiagnosticKind {
impl quote::IdentFragment for SubdiagnosticKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SubdiagnosticKind::Label => write!(f, "label"),
SubdiagnosticKind::Note => write!(f, "note"),
SubdiagnosticKind::Help => write!(f, "help"),
SubdiagnosticKind::Warn => write!(f, "warn"),
SubdiagnosticKind::Suggestion { .. } => write!(f, "suggestions_with_style"),
SubdiagnosticKind::Label => f.write_str("label"),
SubdiagnosticKind::Note => f.write_str("note"),
SubdiagnosticKind::Help => f.write_str("help"),
SubdiagnosticKind::Warn => f.write_str("warn"),
SubdiagnosticKind::Suggestion { .. } => f.write_str("suggestions_with_style"),
SubdiagnosticKind::MultipartSuggestion { .. } => {
write!(f, "multipart_suggestion_with_style")
f.write_str("multipart_suggestion_with_style")
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/dep_graph/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ impl rustc_query_system::dep_graph::DepKind for DepKind {
Ok(())
})?;

write!(f, ")")
f.write_str(")")
}

fn with_deps<OP, R>(task_deps: TaskDepsRef<'_>, op: OP) -> R
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/mir/coverage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ impl Debug for CoverageKind {
},
rhs.index(),
),
Unreachable => write!(fmt, "Unreachable"),
Unreachable => fmt.write_str("Unreachable"),
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/mir/interpret/allocation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ impl<'tcx> fmt::Debug for ConstAllocation<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// The debug representation of this is very verbose and basically useless,
// so don't print it.
write!(f, "ConstAllocation {{ .. }}")
f.write_str("ConstAllocation { .. }")
}
}

Expand Down
28 changes: 14 additions & 14 deletions compiler/rustc_middle/src/mir/interpret/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ impl fmt::Display for InvalidProgramInfo<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use InvalidProgramInfo::*;
match self {
TooGeneric => write!(f, "encountered overly generic constant"),
TooGeneric => f.write_str("encountered overly generic constant"),
AlreadyReported(ErrorGuaranteed { .. }) => {
write!(
f,
Expand Down Expand Up @@ -288,15 +288,15 @@ impl fmt::Display for UndefinedBehaviorInfo {
use UndefinedBehaviorInfo::*;
match self {
Ub(msg) => write!(f, "{msg}"),
Unreachable => write!(f, "entering unreachable code"),
Unreachable => f.write_str("entering unreachable code"),
BoundsCheckFailed { ref len, ref index } => {
write!(f, "indexing out of bounds: the len is {len} but the index is {index}")
}
DivisionByZero => write!(f, "dividing by zero"),
RemainderByZero => write!(f, "calculating the remainder with a divisor of zero"),
DivisionOverflow => write!(f, "overflow in signed division (dividing MIN by -1)"),
RemainderOverflow => write!(f, "overflow in signed remainder (dividing MIN by -1)"),
PointerArithOverflow => write!(f, "overflowing in-bounds pointer arithmetic"),
DivisionByZero => f.write_str("dividing by zero"),
RemainderByZero => f.write_str("calculating the remainder with a divisor of zero"),
DivisionOverflow => f.write_str("overflow in signed division (dividing MIN by -1)"),
RemainderOverflow => f.write_str("overflow in signed remainder (dividing MIN by -1)"),
PointerArithOverflow => f.write_str("overflowing in-bounds pointer arithmetic"),
InvalidMeta(msg) => write!(f, "invalid metadata in wide pointer: {msg}"),
UnterminatedCString(p) => write!(
f,
Expand Down Expand Up @@ -367,13 +367,13 @@ impl fmt::Display for UndefinedBehaviorInfo {
f,
"using uninitialized data, but this operation requires initialized memory"
),
DeadLocal => write!(f, "accessing a dead local variable"),
DeadLocal => f.write_str("accessing a dead local variable"),
ScalarSizeMismatch(self::ScalarSizeMismatch { target_size, data_size }) => write!(
f,
"scalar size mismatch: expected {target_size} bytes but got {data_size} bytes instead",
),
UninhabitedEnumVariantWritten => {
write!(f, "writing discriminant of an uninhabited enum")
f.write_str("writing discriminant of an uninhabited enum")
}
}
}
Expand Down Expand Up @@ -414,7 +414,7 @@ impl fmt::Display for UnsupportedOpInfo {
PartialPointerCopy(ptr) => {
write!(f, "unable to copy parts of a pointer from memory at {ptr:?}")
}
ReadPointerAsBytes => write!(f, "unable to turn pointer into raw bytes"),
ReadPointerAsBytes => f.write_str("unable to turn pointer into raw bytes"),
ThreadLocalStatic(did) => write!(f, "cannot access thread local static ({did:?})"),
ReadExternStatic(did) => write!(f, "cannot read from extern static ({did:?})"),
}
Expand All @@ -441,16 +441,16 @@ impl fmt::Display for ResourceExhaustionInfo {
use ResourceExhaustionInfo::*;
match self {
StackFrameLimitReached => {
write!(f, "reached the configured maximum number of stack frames")
f.write_str("reached the configured maximum number of stack frames")
}
StepLimitReached => {
write!(f, "exceeded interpreter step limit (see `#[const_eval_limit]`)")
f.write_str("exceeded interpreter step limit (see `#[const_eval_limit]`)")
}
MemoryExhausted => {
write!(f, "tried to allocate more memory than available to compiler")
f.write_str("tried to allocate more memory than available to compiler")
}
AddressSpaceFull => {
write!(f, "there are no more free addresses in the address space")
f.write_str("there are no more free addresses in the address space")
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/mir/interpret/pointer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ impl<Prov: Provenance> fmt::Debug for Pointer<Option<Prov>> {
impl<Prov: Provenance> fmt::Display for Pointer<Option<Prov>> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.provenance.is_none() && self.offset.bytes() == 0 {
write!(f, "null pointer")
f.write_str("null pointer")
} else {
fmt::Debug::fmt(self, f)
}
Expand Down
Loading