Skip to content

Commit

Permalink
Rollup merge of rust-lang#114822 - GuillaumeGomez:code-readability-im…
Browse files Browse the repository at this point in the history
…provement, r=notriddle

Improve code readability by moving fmt args directly into the string

There are some of occurrences where I also transformed `write!(f, "{}", x)` into `f.write_str(x.as_str())`.

r? `@notriddle`
  • Loading branch information
GuillaumeGomez authored Aug 15, 2023
2 parents 1f28a76 + 9f21e6d commit ffabd64
Show file tree
Hide file tree
Showing 35 changed files with 342 additions and 336 deletions.
18 changes: 9 additions & 9 deletions src/librustdoc/clean/auto_trait.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ where
let tcx = self.cx.tcx;
let trait_ref = ty::Binder::dummy(ty::TraitRef::new(tcx, trait_def_id, [ty]));
if !self.cx.generated_synthetics.insert((ty, trait_def_id)) {
debug!("get_auto_trait_impl_for({:?}): already generated, aborting", trait_ref);
debug!("get_auto_trait_impl_for({trait_ref:?}): already generated, aborting");
return None;
}

Expand Down Expand Up @@ -140,7 +140,7 @@ where
let ty = tcx.type_of(item_def_id).instantiate_identity();
let f = auto_trait::AutoTraitFinder::new(tcx);

debug!("get_auto_trait_impls({:?})", ty);
debug!("get_auto_trait_impls({ty:?})");
let auto_traits: Vec<_> = self.cx.auto_traits.to_vec();
let mut auto_traits: Vec<Item> = auto_traits
.into_iter()
Expand All @@ -163,9 +163,9 @@ where
fn get_lifetime(region: Region<'_>, names_map: &FxHashMap<Symbol, Lifetime>) -> Lifetime {
region_name(region)
.map(|name| {
names_map.get(&name).unwrap_or_else(|| {
panic!("Missing lifetime with name {:?} for {:?}", name.as_str(), region)
})
names_map
.get(&name)
.unwrap_or_else(|| panic!("Missing lifetime with name {name:?} for {region:?}"))
})
.unwrap_or(&Lifetime::statik())
.clone()
Expand Down Expand Up @@ -372,7 +372,7 @@ where

let output = output.as_ref().cloned().map(Box::new);
if old_output.is_some() && old_output != output {
panic!("Output mismatch for {:?} {:?} {:?}", ty, old_output, output);
panic!("Output mismatch for {ty:?} {old_output:?} {output:?}");
}

let new_params = GenericArgs::Parenthesized { inputs: old_input, output };
Expand Down Expand Up @@ -462,7 +462,7 @@ where
);
let mut generic_params = raw_generics.params;

debug!("param_env_to_generics({:?}): generic_params={:?}", item_def_id, generic_params);
debug!("param_env_to_generics({item_def_id:?}): generic_params={generic_params:?}");

let mut has_sized = FxHashSet::default();
let mut ty_to_bounds: FxHashMap<_, FxHashSet<_>> = Default::default();
Expand Down Expand Up @@ -623,7 +623,7 @@ where
// loop
ty_to_traits.entry(ty.clone()).or_default().insert(trait_.clone());
}
_ => panic!("Unexpected LHS {:?} for {:?}", lhs, item_def_id),
_ => panic!("Unexpected LHS {lhs:?} for {item_def_id:?}"),
}
}
};
Expand Down Expand Up @@ -710,7 +710,7 @@ where
/// involved (impls rarely have more than a few bounds) means that it
/// shouldn't matter in practice.
fn unstable_debug_sort<T: Debug>(&self, vec: &mut [T]) {
vec.sort_by_cached_key(|x| format!("{:?}", x))
vec.sort_by_cached_key(|x| format!("{x:?}"))
}

fn is_fn_trait(&self, path: &Path) -> bool {
Expand Down
4 changes: 2 additions & 2 deletions src/librustdoc/clean/blanket_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ impl<'a, 'tcx> BlanketImplFinder<'a, 'tcx> {
let param_env = cx.tcx.param_env(item_def_id);
let ty = cx.tcx.type_of(item_def_id);

trace!("get_blanket_impls({:?})", ty);
trace!("get_blanket_impls({ty:?})");
let mut impls = Vec::new();
for trait_def_id in cx.tcx.all_traits() {
if !cx.cache.effective_visibilities.is_reachable(cx.tcx, trait_def_id)
Expand Down Expand Up @@ -72,7 +72,7 @@ impl<'a, 'tcx> BlanketImplFinder<'a, 'tcx> {
.into_iter()
.chain(Some(ty::Binder::dummy(impl_trait_ref).to_predicate(infcx.tcx)));
for predicate in predicates {
debug!("testing predicate {:?}", predicate);
debug!("testing predicate {predicate:?}");
let obligation = traits::Obligation::new(
infcx.tcx,
traits::ObligationCause::dummy(),
Expand Down
28 changes: 14 additions & 14 deletions src/librustdoc/clean/cfg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -434,9 +434,9 @@ impl<'a> fmt::Display for Display<'a> {
}
if let (true, Cfg::Cfg(_, Some(feat))) = (short_longhand, sub_cfg) {
if self.1.is_html() {
write!(fmt, "<code>{}</code>", feat)?;
write!(fmt, "<code>{feat}</code>")?;
} else {
write!(fmt, "`{}`", feat)?;
write!(fmt, "`{feat}`")?;
}
} else {
write_with_opt_paren(fmt, !sub_cfg.is_all(), Display(sub_cfg, self.1))?;
Expand Down Expand Up @@ -471,9 +471,9 @@ impl<'a> fmt::Display for Display<'a> {
}
if let (true, Cfg::Cfg(_, Some(feat))) = (short_longhand, sub_cfg) {
if self.1.is_html() {
write!(fmt, "<code>{}</code>", feat)?;
write!(fmt, "<code>{feat}</code>")?;
} else {
write!(fmt, "`{}`", feat)?;
write!(fmt, "`{feat}`")?;
}
} else {
write_with_opt_paren(fmt, !sub_cfg.is_simple(), Display(sub_cfg, self.1))?;
Expand Down Expand Up @@ -552,21 +552,21 @@ impl<'a> fmt::Display for Display<'a> {
"sgx" => "SGX",
_ => "",
},
(sym::target_endian, Some(endian)) => return write!(fmt, "{}-endian", endian),
(sym::target_pointer_width, Some(bits)) => return write!(fmt, "{}-bit", bits),
(sym::target_endian, Some(endian)) => return write!(fmt, "{endian}-endian"),
(sym::target_pointer_width, Some(bits)) => return write!(fmt, "{bits}-bit"),
(sym::target_feature, Some(feat)) => match self.1 {
Format::LongHtml => {
return write!(fmt, "target feature <code>{}</code>", feat);
return write!(fmt, "target feature <code>{feat}</code>");
}
Format::LongPlain => return write!(fmt, "target feature `{}`", feat),
Format::ShortHtml => return write!(fmt, "<code>{}</code>", feat),
Format::LongPlain => return write!(fmt, "target feature `{feat}`"),
Format::ShortHtml => return write!(fmt, "<code>{feat}</code>"),
},
(sym::feature, Some(feat)) => match self.1 {
Format::LongHtml => {
return write!(fmt, "crate feature <code>{}</code>", feat);
return write!(fmt, "crate feature <code>{feat}</code>");
}
Format::LongPlain => return write!(fmt, "crate feature `{}`", feat),
Format::ShortHtml => return write!(fmt, "<code>{}</code>", feat),
Format::LongPlain => return write!(fmt, "crate feature `{feat}`"),
Format::ShortHtml => return write!(fmt, "<code>{feat}</code>"),
},
_ => "",
};
Expand All @@ -581,12 +581,12 @@ impl<'a> fmt::Display for Display<'a> {
Escape(v.as_str())
)
} else {
write!(fmt, r#"`{}="{}"`"#, name, v)
write!(fmt, r#"`{name}="{v}"`"#)
}
} else if self.1.is_html() {
write!(fmt, "<code>{}</code>", Escape(name.as_str()))
} else {
write!(fmt, "`{}`", name)
write!(fmt, "`{name}`")
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/librustdoc/clean/inline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ pub(crate) fn try_inline(
}
let mut ret = Vec::new();

debug!("attrs={:?}", attrs);
debug!("attrs={attrs:?}");

let attrs_without_docs = attrs.map(|(attrs, def_id)| {
(attrs.into_iter().filter(|a| a.doc_str().is_none()).cloned().collect::<Vec<_>>(), def_id)
Expand Down Expand Up @@ -529,7 +529,7 @@ pub(crate) fn build_impl(
}

let (merged_attrs, cfg) = merge_attrs(cx, load_attrs(cx, did), attrs);
trace!("merged_attrs={:?}", merged_attrs);
trace!("merged_attrs={merged_attrs:?}");

trace!(
"build_impl: impl {:?} for {:?}",
Expand Down Expand Up @@ -781,7 +781,7 @@ pub(crate) fn record_extern_trait(cx: &mut DocContext<'_>, did: DefId) {
cx.active_extern_traits.insert(did);
}

debug!("record_extern_trait: {:?}", did);
debug!("record_extern_trait: {did:?}");
let trait_ = build_external_trait(cx, did);

cx.external_traits.borrow_mut().insert(did, trait_);
Expand Down
8 changes: 4 additions & 4 deletions src/librustdoc/clean/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ pub(crate) fn clean_trait_ref_with_bindings<'tcx>(
) -> Path {
let kind = cx.tcx.def_kind(trait_ref.def_id()).into();
if !matches!(kind, ItemType::Trait | ItemType::TraitAlias) {
span_bug!(cx.tcx.def_span(trait_ref.def_id()), "`TraitRef` had unexpected kind {:?}", kind);
span_bug!(cx.tcx.def_span(trait_ref.def_id()), "`TraitRef` had unexpected kind {kind:?}");
}
inline::record_extern_fqn(cx, trait_ref.def_id(), kind);
let path =
Expand Down Expand Up @@ -304,7 +304,7 @@ pub(crate) fn clean_middle_region<'tcx>(region: ty::Region<'tcx>) -> Option<Life
| ty::ReError(_)
| ty::RePlaceholder(..)
| ty::ReErased => {
debug!("cannot clean region {:?}", region);
debug!("cannot clean region {region:?}");
None
}
}
Expand Down Expand Up @@ -1867,11 +1867,11 @@ fn normalize<'tcx>(
.map(|resolved| infcx.resolve_vars_if_possible(resolved.value));
match normalized {
Ok(normalized_value) => {
debug!("normalized {:?} to {:?}", ty, normalized_value);
debug!("normalized {ty:?} to {normalized_value:?}");
Some(normalized_value)
}
Err(err) => {
debug!("failed to normalize {:?}: {:?}", ty, err);
debug!("failed to normalize {ty:?}: {err:?}");
None
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/librustdoc/clean/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ impl ItemId {
#[track_caller]
pub(crate) fn expect_def_id(self) -> DefId {
self.as_def_id()
.unwrap_or_else(|| panic!("ItemId::expect_def_id: `{:?}` isn't a DefId", self))
.unwrap_or_else(|| panic!("ItemId::expect_def_id: `{self:?}` isn't a DefId"))
}

#[inline]
Expand Down Expand Up @@ -352,7 +352,7 @@ fn is_field_vis_inherited(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
match tcx.def_kind(parent) {
DefKind::Struct | DefKind::Union => false,
DefKind::Variant => true,
parent_kind => panic!("unexpected parent kind: {:?}", parent_kind),
parent_kind => panic!("unexpected parent kind: {parent_kind:?}"),
}
}

Expand Down Expand Up @@ -436,7 +436,7 @@ impl Item {
attrs: Box<Attributes>,
cfg: Option<Arc<Cfg>>,
) -> Item {
trace!("name={:?}, def_id={:?} cfg={:?}", name, def_id, cfg);
trace!("name={name:?}, def_id={def_id:?} cfg={cfg:?}");

Item {
item_id: def_id.into(),
Expand Down
34 changes: 19 additions & 15 deletions src/librustdoc/clean/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ pub(crate) fn build_deref_target_impls(

pub(crate) fn name_from_pat(p: &hir::Pat<'_>) -> Symbol {
use rustc_hir::*;
debug!("trying to get a name from pattern: {:?}", p);
debug!("trying to get a name from pattern: {p:?}");

Symbol::intern(&match p.kind {
PatKind::Wild | PatKind::Struct(..) => return kw::Underscore,
Expand Down Expand Up @@ -461,7 +461,7 @@ pub(crate) fn print_const_expr(tcx: TyCtxt<'_>, body: hir::BodyId) -> String {

/// Given a type Path, resolve it to a Type using the TyCtxt
pub(crate) fn resolve_type(cx: &mut DocContext<'_>, path: Path) -> Type {
debug!("resolve_type({:?})", path);
debug!("resolve_type({path:?})");

match path.res {
Res::PrimTy(p) => Primitive(PrimitiveType::from(p)),
Expand Down Expand Up @@ -500,7 +500,7 @@ pub(crate) fn get_auto_trait_and_blanket_impls(
/// [`href()`]: crate::html::format::href
pub(crate) fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId {
use DefKind::*;
debug!("register_res({:?})", res);
debug!("register_res({res:?})");

let (kind, did) = match res {
Res::Def(
Expand All @@ -523,7 +523,7 @@ pub(crate) fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId {
did,
) => (kind.into(), did),

_ => panic!("register_res: unexpected {:?}", res),
_ => panic!("register_res: unexpected {res:?}"),
};
if did.is_local() {
return did;
Expand Down Expand Up @@ -601,8 +601,12 @@ pub(super) fn render_macro_arms<'a>(
) -> String {
let mut out = String::new();
for matcher in matchers {
writeln!(out, " {} => {{ ... }}{}", render_macro_matcher(tcx, matcher), arm_delim)
.unwrap();
writeln!(
out,
" {matcher} => {{ ... }}{arm_delim}",
matcher = render_macro_matcher(tcx, matcher),
)
.unwrap();
}
out
}
Expand All @@ -618,21 +622,21 @@ pub(super) fn display_macro_source(
let matchers = def.body.tokens.chunks(4).map(|arm| &arm[0]);

if def.macro_rules {
format!("macro_rules! {} {{\n{}}}", name, render_macro_arms(cx.tcx, matchers, ";"))
format!("macro_rules! {name} {{\n{arms}}}", arms = render_macro_arms(cx.tcx, matchers, ";"))
} else {
if matchers.len() <= 1 {
format!(
"{}macro {}{} {{\n ...\n}}",
visibility_to_src_with_space(Some(vis), cx.tcx, def_id),
name,
matchers.map(|matcher| render_macro_matcher(cx.tcx, matcher)).collect::<String>(),
"{vis}macro {name}{matchers} {{\n ...\n}}",
vis = visibility_to_src_with_space(Some(vis), cx.tcx, def_id),
matchers = matchers
.map(|matcher| render_macro_matcher(cx.tcx, matcher))
.collect::<String>(),
)
} else {
format!(
"{}macro {} {{\n{}}}",
visibility_to_src_with_space(Some(vis), cx.tcx, def_id),
name,
render_macro_arms(cx.tcx, matchers, ","),
"{vis}macro {name} {{\n{arms}}}",
vis = visibility_to_src_with_space(Some(vis), cx.tcx, def_id),
arms = render_macro_arms(cx.tcx, matchers, ","),
)
}
}
Expand Down
Loading

0 comments on commit ffabd64

Please sign in to comment.