Improve code readability by moving fmt args directly into the string

This commit is contained in:
Guillaume Gomez
2023-08-14 22:25:32 +02:00
parent 3071e0aef6
commit a1a94b1c0f
35 changed files with 261 additions and 300 deletions

View File

@@ -46,7 +46,7 @@ where
let tcx = self.cx.tcx; let tcx = self.cx.tcx;
let trait_ref = ty::Binder::dummy(ty::TraitRef::new(tcx, trait_def_id, [ty])); let trait_ref = ty::Binder::dummy(ty::TraitRef::new(tcx, trait_def_id, [ty]));
if !self.cx.generated_synthetics.insert((ty, trait_def_id)) { 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; return None;
} }
@@ -140,7 +140,7 @@ where
let ty = tcx.type_of(item_def_id).instantiate_identity(); let ty = tcx.type_of(item_def_id).instantiate_identity();
let f = auto_trait::AutoTraitFinder::new(tcx); 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 auto_traits: Vec<_> = self.cx.auto_traits.to_vec();
let mut auto_traits: Vec<Item> = auto_traits let mut auto_traits: Vec<Item> = auto_traits
.into_iter() .into_iter()
@@ -164,7 +164,7 @@ where
region_name(region) region_name(region)
.map(|name| { .map(|name| {
names_map.get(&name).unwrap_or_else(|| { names_map.get(&name).unwrap_or_else(|| {
panic!("Missing lifetime with name {:?} for {:?}", name.as_str(), region) panic!("Missing lifetime with name {:?} for {region:?}", name.as_str())
}) })
}) })
.unwrap_or(&Lifetime::statik()) .unwrap_or(&Lifetime::statik())
@@ -372,7 +372,7 @@ where
let output = output.as_ref().cloned().map(Box::new); let output = output.as_ref().cloned().map(Box::new);
if old_output.is_some() && old_output != output { 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 }; let new_params = GenericArgs::Parenthesized { inputs: old_input, output };
@@ -462,7 +462,7 @@ where
); );
let mut generic_params = raw_generics.params; 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 has_sized = FxHashSet::default();
let mut ty_to_bounds: FxHashMap<_, FxHashSet<_>> = Default::default(); let mut ty_to_bounds: FxHashMap<_, FxHashSet<_>> = Default::default();
@@ -623,7 +623,7 @@ where
// loop // loop
ty_to_traits.entry(ty.clone()).or_default().insert(trait_.clone()); 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:?}"),
} }
} }
}; };
@@ -710,7 +710,7 @@ where
/// involved (impls rarely have more than a few bounds) means that it /// involved (impls rarely have more than a few bounds) means that it
/// shouldn't matter in practice. /// shouldn't matter in practice.
fn unstable_debug_sort<T: Debug>(&self, vec: &mut [T]) { 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 { fn is_fn_trait(&self, path: &Path) -> bool {

View File

@@ -17,7 +17,7 @@ impl<'a, 'tcx> BlanketImplFinder<'a, 'tcx> {
let param_env = cx.tcx.param_env(item_def_id); let param_env = cx.tcx.param_env(item_def_id);
let ty = cx.tcx.type_of(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(); let mut impls = Vec::new();
for trait_def_id in cx.tcx.all_traits() { for trait_def_id in cx.tcx.all_traits() {
if !cx.cache.effective_visibilities.is_reachable(cx.tcx, trait_def_id) if !cx.cache.effective_visibilities.is_reachable(cx.tcx, trait_def_id)
@@ -72,7 +72,7 @@ impl<'a, 'tcx> BlanketImplFinder<'a, 'tcx> {
.into_iter() .into_iter()
.chain(Some(ty::Binder::dummy(impl_trait_ref).to_predicate(infcx.tcx))); .chain(Some(ty::Binder::dummy(impl_trait_ref).to_predicate(infcx.tcx)));
for predicate in predicates { for predicate in predicates {
debug!("testing predicate {:?}", predicate); debug!("testing predicate {predicate:?}");
let obligation = traits::Obligation::new( let obligation = traits::Obligation::new(
infcx.tcx, infcx.tcx,
traits::ObligationCause::dummy(), traits::ObligationCause::dummy(),

View File

@@ -434,9 +434,9 @@ impl<'a> fmt::Display for Display<'a> {
} }
if let (true, Cfg::Cfg(_, Some(feat))) = (short_longhand, sub_cfg) { if let (true, Cfg::Cfg(_, Some(feat))) = (short_longhand, sub_cfg) {
if self.1.is_html() { if self.1.is_html() {
write!(fmt, "<code>{}</code>", feat)?; write!(fmt, "<code>{feat}</code>")?;
} else { } else {
write!(fmt, "`{}`", feat)?; write!(fmt, "`{feat}`")?;
} }
} else { } else {
write_with_opt_paren(fmt, !sub_cfg.is_all(), Display(sub_cfg, self.1))?; write_with_opt_paren(fmt, !sub_cfg.is_all(), Display(sub_cfg, self.1))?;
@@ -471,9 +471,9 @@ impl<'a> fmt::Display for Display<'a> {
} }
if let (true, Cfg::Cfg(_, Some(feat))) = (short_longhand, sub_cfg) { if let (true, Cfg::Cfg(_, Some(feat))) = (short_longhand, sub_cfg) {
if self.1.is_html() { if self.1.is_html() {
write!(fmt, "<code>{}</code>", feat)?; write!(fmt, "<code>{feat}</code>")?;
} else { } else {
write!(fmt, "`{}`", feat)?; write!(fmt, "`{feat}`")?;
} }
} else { } else {
write_with_opt_paren(fmt, !sub_cfg.is_simple(), Display(sub_cfg, self.1))?; write_with_opt_paren(fmt, !sub_cfg.is_simple(), Display(sub_cfg, self.1))?;
@@ -551,21 +551,21 @@ impl<'a> fmt::Display for Display<'a> {
"sgx" => "SGX", "sgx" => "SGX",
_ => "", _ => "",
}, },
(sym::target_endian, Some(endian)) => return write!(fmt, "{}-endian", endian), (sym::target_endian, Some(endian)) => return write!(fmt, "{endian}-endian"),
(sym::target_pointer_width, Some(bits)) => return write!(fmt, "{}-bit", bits), (sym::target_pointer_width, Some(bits)) => return write!(fmt, "{bits}-bit"),
(sym::target_feature, Some(feat)) => match self.1 { (sym::target_feature, Some(feat)) => match self.1 {
Format::LongHtml => { 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::LongPlain => return write!(fmt, "target feature `{feat}`"),
Format::ShortHtml => return write!(fmt, "<code>{}</code>", feat), Format::ShortHtml => return write!(fmt, "<code>{feat}</code>"),
}, },
(sym::feature, Some(feat)) => match self.1 { (sym::feature, Some(feat)) => match self.1 {
Format::LongHtml => { 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::LongPlain => return write!(fmt, "crate feature `{feat}`"),
Format::ShortHtml => return write!(fmt, "<code>{}</code>", feat), Format::ShortHtml => return write!(fmt, "<code>{feat}</code>"),
}, },
_ => "", _ => "",
}; };
@@ -580,12 +580,12 @@ impl<'a> fmt::Display for Display<'a> {
Escape(v.as_str()) Escape(v.as_str())
) )
} else { } else {
write!(fmt, r#"`{}="{}"`"#, name, v) write!(fmt, r#"`{name}="{v}"`"#)
} }
} else if self.1.is_html() { } else if self.1.is_html() {
write!(fmt, "<code>{}</code>", Escape(name.as_str())) write!(fmt, "<code>{}</code>", Escape(name.as_str()))
} else { } else {
write!(fmt, "`{}`", name) write!(fmt, "`{name}`")
} }
} }
} }

View File

@@ -50,7 +50,7 @@ pub(crate) fn try_inline(
} }
let mut ret = Vec::new(); let mut ret = Vec::new();
debug!("attrs={:?}", attrs); debug!("attrs={attrs:?}");
let attrs_without_docs = attrs.map(|(attrs, def_id)| { let attrs_without_docs = attrs.map(|(attrs, def_id)| {
(attrs.into_iter().filter(|a| a.doc_str().is_none()).cloned().collect::<Vec<_>>(), def_id) (attrs.into_iter().filter(|a| a.doc_str().is_none()).cloned().collect::<Vec<_>>(), def_id)
@@ -529,7 +529,7 @@ pub(crate) fn build_impl(
} }
let (merged_attrs, cfg) = merge_attrs(cx, load_attrs(cx, did), attrs); let (merged_attrs, cfg) = merge_attrs(cx, load_attrs(cx, did), attrs);
trace!("merged_attrs={:?}", merged_attrs); trace!("merged_attrs={merged_attrs:?}");
trace!( trace!(
"build_impl: impl {:?} for {:?}", "build_impl: impl {:?} for {:?}",
@@ -781,7 +781,7 @@ pub(crate) fn record_extern_trait(cx: &mut DocContext<'_>, did: DefId) {
cx.active_extern_traits.insert(did); cx.active_extern_traits.insert(did);
} }
debug!("record_extern_trait: {:?}", did); debug!("record_extern_trait: {did:?}");
let trait_ = build_external_trait(cx, did); let trait_ = build_external_trait(cx, did);
cx.external_traits.borrow_mut().insert(did, trait_); cx.external_traits.borrow_mut().insert(did, trait_);

View File

@@ -215,7 +215,7 @@ pub(crate) fn clean_trait_ref_with_bindings<'tcx>(
) -> Path { ) -> Path {
let kind = cx.tcx.def_kind(trait_ref.def_id()).into(); let kind = cx.tcx.def_kind(trait_ref.def_id()).into();
if !matches!(kind, ItemType::Trait | ItemType::TraitAlias) { 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); inline::record_extern_fqn(cx, trait_ref.def_id(), kind);
let path = let path =
@@ -304,7 +304,7 @@ pub(crate) fn clean_middle_region<'tcx>(region: ty::Region<'tcx>) -> Option<Life
| ty::ReError(_) | ty::ReError(_)
| ty::RePlaceholder(..) | ty::RePlaceholder(..)
| ty::ReErased => { | ty::ReErased => {
debug!("cannot clean region {:?}", region); debug!("cannot clean region {region:?}");
None None
} }
} }
@@ -1867,11 +1867,11 @@ fn normalize<'tcx>(
.map(|resolved| infcx.resolve_vars_if_possible(resolved.value)); .map(|resolved| infcx.resolve_vars_if_possible(resolved.value));
match normalized { match normalized {
Ok(normalized_value) => { Ok(normalized_value) => {
debug!("normalized {:?} to {:?}", ty, normalized_value); debug!("normalized {ty:?} to {normalized_value:?}");
Some(normalized_value) Some(normalized_value)
} }
Err(err) => { Err(err) => {
debug!("failed to normalize {:?}: {:?}", ty, err); debug!("failed to normalize {ty:?}: {err:?}");
None None
} }
} }

View File

@@ -78,7 +78,7 @@ impl ItemId {
#[track_caller] #[track_caller]
pub(crate) fn expect_def_id(self) -> DefId { pub(crate) fn expect_def_id(self) -> DefId {
self.as_def_id() 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] #[inline]
@@ -352,7 +352,7 @@ fn is_field_vis_inherited(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
match tcx.def_kind(parent) { match tcx.def_kind(parent) {
DefKind::Struct | DefKind::Union => false, DefKind::Struct | DefKind::Union => false,
DefKind::Variant => true, DefKind::Variant => true,
parent_kind => panic!("unexpected parent kind: {:?}", parent_kind), parent_kind => panic!("unexpected parent kind: {parent_kind:?}"),
} }
} }
@@ -436,7 +436,7 @@ impl Item {
attrs: Box<Attributes>, attrs: Box<Attributes>,
cfg: Option<Arc<Cfg>>, cfg: Option<Arc<Cfg>>,
) -> Item { ) -> Item {
trace!("name={:?}, def_id={:?} cfg={:?}", name, def_id, cfg); trace!("name={name:?}, def_id={def_id:?} cfg={cfg:?}");
Item { Item {
item_id: def_id.into(), item_id: def_id.into(),

View File

@@ -218,7 +218,7 @@ pub(crate) fn build_deref_target_impls(
pub(crate) fn name_from_pat(p: &hir::Pat<'_>) -> Symbol { pub(crate) fn name_from_pat(p: &hir::Pat<'_>) -> Symbol {
use rustc_hir::*; 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 { Symbol::intern(&match p.kind {
PatKind::Wild | PatKind::Struct(..) => return kw::Underscore, PatKind::Wild | PatKind::Struct(..) => return kw::Underscore,
@@ -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 /// Given a type Path, resolve it to a Type using the TyCtxt
pub(crate) fn resolve_type(cx: &mut DocContext<'_>, path: Path) -> Type { pub(crate) fn resolve_type(cx: &mut DocContext<'_>, path: Path) -> Type {
debug!("resolve_type({:?})", path); debug!("resolve_type({path:?})");
match path.res { match path.res {
Res::PrimTy(p) => Primitive(PrimitiveType::from(p)), Res::PrimTy(p) => Primitive(PrimitiveType::from(p)),
@@ -500,7 +500,7 @@ pub(crate) fn get_auto_trait_and_blanket_impls(
/// [`href()`]: crate::html::format::href /// [`href()`]: crate::html::format::href
pub(crate) fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId { pub(crate) fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId {
use DefKind::*; use DefKind::*;
debug!("register_res({:?})", res); debug!("register_res({res:?})");
let (kind, did) = match res { let (kind, did) = match res {
Res::Def( Res::Def(
@@ -523,7 +523,7 @@ pub(crate) fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId {
did, did,
) => (kind.into(), did), ) => (kind.into(), did),
_ => panic!("register_res: unexpected {:?}", res), _ => panic!("register_res: unexpected {res:?}"),
}; };
if did.is_local() { if did.is_local() {
return did; return did;
@@ -601,7 +601,7 @@ pub(super) fn render_macro_arms<'a>(
) -> String { ) -> String {
let mut out = String::new(); let mut out = String::new();
for matcher in matchers { for matcher in matchers {
writeln!(out, " {} => {{ ... }}{}", render_macro_matcher(tcx, matcher), arm_delim) writeln!(out, " {} => {{ ... }}{arm_delim}", render_macro_matcher(tcx, matcher))
.unwrap(); .unwrap();
} }
out out
@@ -618,20 +618,18 @@ pub(super) fn display_macro_source(
let matchers = def.body.tokens.chunks(4).map(|arm| &arm[0]); let matchers = def.body.tokens.chunks(4).map(|arm| &arm[0]);
if def.macro_rules { if def.macro_rules {
format!("macro_rules! {} {{\n{}}}", name, render_macro_arms(cx.tcx, matchers, ";")) format!("macro_rules! {name} {{\n{}}}", render_macro_arms(cx.tcx, matchers, ";"))
} else { } else {
if matchers.len() <= 1 { if matchers.len() <= 1 {
format!( format!(
"{}macro {}{} {{\n ...\n}}", "{}macro {name}{} {{\n ...\n}}",
visibility_to_src_with_space(Some(vis), cx.tcx, def_id), visibility_to_src_with_space(Some(vis), cx.tcx, def_id),
name,
matchers.map(|matcher| render_macro_matcher(cx.tcx, matcher)).collect::<String>(), matchers.map(|matcher| render_macro_matcher(cx.tcx, matcher)).collect::<String>(),
) )
} else { } else {
format!( format!(
"{}macro {} {{\n{}}}", "{}macro {name} {{\n{}}}",
visibility_to_src_with_space(Some(vis), cx.tcx, def_id), visibility_to_src_with_space(Some(vis), cx.tcx, def_id),
name,
render_macro_arms(cx.tcx, matchers, ","), render_macro_arms(cx.tcx, matchers, ","),
) )
} }

View File

@@ -50,7 +50,7 @@ impl TryFrom<&str> for OutputFormat {
match value { match value {
"json" => Ok(OutputFormat::Json), "json" => Ok(OutputFormat::Json),
"html" => Ok(OutputFormat::Html), "html" => Ok(OutputFormat::Html),
_ => Err(format!("unknown output format `{}`", value)), _ => Err(format!("unknown output format `{value}`")),
} }
} }
} }
@@ -383,7 +383,7 @@ impl Options {
match kind.parse() { match kind.parse() {
Ok(kind) => emit.push(kind), Ok(kind) => emit.push(kind),
Err(()) => { Err(()) => {
diag.err(format!("unrecognized emission type: {}", kind)); diag.err(format!("unrecognized emission type: {kind}"));
return Err(1); return Err(1);
} }
} }
@@ -415,7 +415,7 @@ impl Options {
println!("rustdoc: [check-theme] Starting tests! (Ignoring all other arguments)"); println!("rustdoc: [check-theme] Starting tests! (Ignoring all other arguments)");
for theme_file in to_check.iter() { for theme_file in to_check.iter() {
print!(" - Checking \"{}\"...", theme_file); print!(" - Checking \"{theme_file}\"...");
let (success, differences) = theme::test_theme_against(theme_file, &paths, &diag); let (success, differences) = theme::test_theme_against(theme_file, &paths, &diag);
if !differences.is_empty() || !success { if !differences.is_empty() || !success {
println!(" FAILED"); println!(" FAILED");
@@ -556,30 +556,28 @@ impl Options {
matches.opt_strs("theme").iter().map(|s| (PathBuf::from(&s), s.to_owned())) matches.opt_strs("theme").iter().map(|s| (PathBuf::from(&s), s.to_owned()))
{ {
if !theme_file.is_file() { if !theme_file.is_file() {
diag.struct_err(format!("invalid argument: \"{}\"", theme_s)) diag.struct_err(format!("invalid argument: \"{theme_s}\""))
.help("arguments to --theme must be files") .help("arguments to --theme must be files")
.emit(); .emit();
return Err(1); return Err(1);
} }
if theme_file.extension() != Some(OsStr::new("css")) { if theme_file.extension() != Some(OsStr::new("css")) {
diag.struct_err(format!("invalid argument: \"{}\"", theme_s)) diag.struct_err(format!("invalid argument: \"{theme_s}\""))
.help("arguments to --theme must have a .css extension") .help("arguments to --theme must have a .css extension")
.emit(); .emit();
return Err(1); return Err(1);
} }
let (success, ret) = theme::test_theme_against(&theme_file, &paths, &diag); let (success, ret) = theme::test_theme_against(&theme_file, &paths, &diag);
if !success { if !success {
diag.struct_err(format!("error loading theme file: \"{}\"", theme_s)).emit(); diag.struct_err(format!("error loading theme file: \"{theme_s}\"")).emit();
return Err(1); return Err(1);
} else if !ret.is_empty() { } else if !ret.is_empty() {
diag.struct_warn(format!( diag.struct_warn(format!(
"theme file \"{}\" is missing CSS rules from the default theme", "theme file \"{theme_s}\" is missing CSS rules from the default theme",
theme_s
)) ))
.warn("the theme may appear incorrect when loaded") .warn("the theme may appear incorrect when loaded")
.help(format!( .help(format!(
"to see what rules are missing, call `rustdoc --check-theme \"{}\"`", "to see what rules are missing, call `rustdoc --check-theme \"{theme_s}\"`",
theme_s
)) ))
.emit(); .emit();
} }
@@ -608,7 +606,7 @@ impl Options {
match matches.opt_str("r").as_deref() { match matches.opt_str("r").as_deref() {
Some("rust") | None => {} Some("rust") | None => {}
Some(s) => { Some(s) => {
diag.struct_err(format!("unknown input format: {}", s)).emit(); diag.struct_err(format!("unknown input format: {s}")).emit();
return Err(1); return Err(1);
} }
} }
@@ -628,7 +626,7 @@ impl Options {
let crate_types = match parse_crate_types_from_list(matches.opt_strs("crate-type")) { let crate_types = match parse_crate_types_from_list(matches.opt_strs("crate-type")) {
Ok(types) => types, Ok(types) => types,
Err(e) => { Err(e) => {
diag.struct_err(format!("unknown crate type: {}", e)).emit(); diag.struct_err(format!("unknown crate type: {e}")).emit();
return Err(1); return Err(1);
} }
}; };
@@ -787,7 +785,7 @@ fn check_deprecated_options(matches: &getopts::Matches, diag: &rustc_errors::Han
for &flag in deprecated_flags.iter() { for &flag in deprecated_flags.iter() {
if matches.opt_present(flag) { if matches.opt_present(flag) {
diag.struct_warn(format!("the `{}` flag is deprecated", flag)) diag.struct_warn(format!("the `{flag}` flag is deprecated"))
.note( .note(
"see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \ "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
for more information", for more information",
@@ -800,7 +798,7 @@ fn check_deprecated_options(matches: &getopts::Matches, diag: &rustc_errors::Han
for &flag in removed_flags.iter() { for &flag in removed_flags.iter() {
if matches.opt_present(flag) { if matches.opt_present(flag) {
let mut err = diag.struct_warn(format!("the `{}` flag no longer functions", flag)); let mut err = diag.struct_warn(format!("the `{flag}` flag no longer functions"));
err.note( err.note(
"see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \ "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
for more information", for more information",

View File

@@ -283,7 +283,7 @@ pub(crate) fn create_config(
let hir = tcx.hir(); let hir = tcx.hir();
let body = hir.body(hir.body_owned_by(def_id)); let body = hir.body(hir.body_owned_by(def_id));
debug!("visiting body for {:?}", def_id); debug!("visiting body for {def_id:?}");
EmitIgnoredResolutionErrors::new(tcx).visit_body(body); EmitIgnoredResolutionErrors::new(tcx).visit_body(body);
(rustc_interface::DEFAULT_QUERY_PROVIDERS.typeck)(tcx, def_id) (rustc_interface::DEFAULT_QUERY_PROVIDERS.typeck)(tcx, def_id)
}; };
@@ -377,7 +377,7 @@ pub(crate) fn run_global_ctxt(
fn report_deprecated_attr(name: &str, diag: &rustc_errors::Handler, sp: Span) { fn report_deprecated_attr(name: &str, diag: &rustc_errors::Handler, sp: Span) {
let mut msg = let mut msg =
diag.struct_span_warn(sp, format!("the `#![doc({})]` attribute is deprecated", name)); diag.struct_span_warn(sp, format!("the `#![doc({name})]` attribute is deprecated"));
msg.note( msg.note(
"see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \ "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
for more information", for more information",
@@ -470,7 +470,7 @@ impl<'tcx> Visitor<'tcx> for EmitIgnoredResolutionErrors<'tcx> {
} }
fn visit_path(&mut self, path: &Path<'tcx>, _id: HirId) { fn visit_path(&mut self, path: &Path<'tcx>, _id: HirId) {
debug!("visiting path {:?}", path); debug!("visiting path {path:?}");
if path.res == Res::Err { if path.res == Res::Err {
// We have less context here than in rustc_resolve, // We have less context here than in rustc_resolve,
// so we can only emit the name and span. // so we can only emit the name and span.
@@ -487,8 +487,7 @@ impl<'tcx> Visitor<'tcx> for EmitIgnoredResolutionErrors<'tcx> {
self.tcx.sess, self.tcx.sess,
path.span, path.span,
E0433, E0433,
"failed to resolve: {}", "failed to resolve: {label}",
label
); );
err.span_label(path.span, label); err.span_label(path.span, label);
err.note("this error was originally ignored because you are running `rustdoc`"); err.note("this error was originally ignored because you are running `rustdoc`");

View File

@@ -72,7 +72,7 @@ impl DocFS {
let sender = self.errors.clone().expect("can't write after closing"); let sender = self.errors.clone().expect("can't write after closing");
self.pool.execute(move || { self.pool.execute(move || {
fs::write(&path, contents).unwrap_or_else(|e| { fs::write(&path, contents).unwrap_or_else(|e| {
sender.send(format!("\"{}\": {}", path.display(), e)).unwrap_or_else(|_| { sender.send(format!("\"{}\": {e}", path.display())).unwrap_or_else(|_| {
panic!("failed to send error on \"{}\"", path.display()) panic!("failed to send error on \"{}\"", path.display())
}) })
}); });

View File

@@ -192,7 +192,7 @@ pub(crate) fn run(options: RustdocOptions) -> Result<(), ErrorGuaranteed> {
// The allow lint level is not expected, // The allow lint level is not expected,
// as if allow is specified, no message // as if allow is specified, no message
// is to be emitted. // is to be emitted.
v => unreachable!("Invalid lint level '{}'", v), v => unreachable!("Invalid lint level '{v}'"),
}) })
.unwrap_or("warn") .unwrap_or("warn")
.to_string(); .to_string();
@@ -404,7 +404,7 @@ fn run_test(
compiler.stdin(Stdio::piped()); compiler.stdin(Stdio::piped());
compiler.stderr(Stdio::piped()); compiler.stderr(Stdio::piped());
debug!("compiler invocation for doctest: {:?}", compiler); debug!("compiler invocation for doctest: {compiler:?}");
let mut child = compiler.spawn().expect("Failed to spawn rustc process"); let mut child = compiler.spawn().expect("Failed to spawn rustc process");
{ {
@@ -933,7 +933,7 @@ impl Collector {
if !item_path.is_empty() { if !item_path.is_empty() {
item_path.push(' '); item_path.push(' ');
} }
format!("{} - {}(line {})", filename.prefer_local(), item_path, line) format!("{} - {item_path}(line {line})", filename.prefer_local())
} }
pub(crate) fn set_position(&mut self, position: Span) { pub(crate) fn set_position(&mut self, position: Span) {
@@ -1010,7 +1010,7 @@ impl Tester for Collector {
path.push(&test_id); path.push(&test_id);
if let Err(err) = std::fs::create_dir_all(&path) { if let Err(err) = std::fs::create_dir_all(&path) {
eprintln!("Couldn't create directory for doctest executables: {}", err); eprintln!("Couldn't create directory for doctest executables: {err}");
panic::resume_unwind(Box::new(())); panic::resume_unwind(Box::new(()));
} }
@@ -1079,7 +1079,7 @@ impl Tester for Collector {
eprint!("Test executable succeeded, but it's marked `should_panic`."); eprint!("Test executable succeeded, but it's marked `should_panic`.");
} }
TestFailure::MissingErrorCodes(codes) => { TestFailure::MissingErrorCodes(codes) => {
eprint!("Some expected error codes were not found: {:?}", codes); eprint!("Some expected error codes were not found: {codes:?}");
} }
TestFailure::ExecutionError(err) => { TestFailure::ExecutionError(err) => {
eprint!("Couldn't run the test: {err}"); eprint!("Couldn't run the test: {err}");

View File

@@ -37,8 +37,7 @@ impl ExternalHtml {
let bc = load_external_files(before_content, diag)?; let bc = load_external_files(before_content, diag)?;
let m_bc = load_external_files(md_before_content, diag)?; let m_bc = load_external_files(md_before_content, diag)?;
let bc = format!( let bc = format!(
"{}{}", "{bc}{}",
bc,
Markdown { Markdown {
content: &m_bc, content: &m_bc,
links: &[], links: &[],
@@ -53,8 +52,7 @@ impl ExternalHtml {
let ac = load_external_files(after_content, diag)?; let ac = load_external_files(after_content, diag)?;
let m_ac = load_external_files(md_after_content, diag)?; let m_ac = load_external_files(md_after_content, diag)?;
let ac = format!( let ac = format!(
"{}{}", "{ac}{}",
ac,
Markdown { Markdown {
content: &m_ac, content: &m_ac,
links: &[], links: &[],
@@ -83,7 +81,7 @@ pub(crate) fn load_string<P: AsRef<Path>>(
let contents = match fs::read(file_path) { let contents = match fs::read(file_path) {
Ok(bytes) => bytes, Ok(bytes) => bytes,
Err(e) => { Err(e) => {
diag.struct_err(format!("error reading `{}`: {}", file_path.display(), e)).emit(); diag.struct_err(format!("error reading `{}`: {e}", file_path.display())).emit();
return Err(LoadStringError::ReadFail); return Err(LoadStringError::ReadFail);
} }
}; };

View File

@@ -228,9 +228,9 @@ impl clean::GenericParamDef {
if let Some(default) = default { if let Some(default) = default {
if f.alternate() { if f.alternate() {
write!(f, " = {:#}", default)?; write!(f, " = {default:#}")?;
} else { } else {
write!(f, " = {}", default)?; write!(f, " = {default}")?;
} }
} }
@@ -451,9 +451,9 @@ impl clean::GenericBound {
hir::TraitBoundModifier::MaybeConst => "", hir::TraitBoundModifier::MaybeConst => "",
}; };
if f.alternate() { if f.alternate() {
write!(f, "{}{:#}", modifier_str, ty.print(cx)) write!(f, "{modifier_str}{:#}", ty.print(cx))
} else { } else {
write!(f, "{}{}", modifier_str, ty.print(cx)) write!(f, "{modifier_str}{}", ty.print(cx))
} }
} }
}) })
@@ -599,7 +599,7 @@ fn generate_macro_def_id_path(
let cstore = CStore::from_tcx(tcx); let cstore = CStore::from_tcx(tcx);
// We need this to prevent a `panic` when this function is used from intra doc links... // We need this to prevent a `panic` when this function is used from intra doc links...
if !cstore.has_crate_data(def_id.krate) { if !cstore.has_crate_data(def_id.krate) {
debug!("No data for crate {}", crate_name); debug!("No data for crate {crate_name}");
return Err(HrefError::NotInExternalCache); return Err(HrefError::NotInExternalCache);
} }
// Check to see if it is a macro 2.0 or built-in macro. // Check to see if it is a macro 2.0 or built-in macro.
@@ -631,19 +631,18 @@ fn generate_macro_def_id_path(
let url = match cache.extern_locations[&def_id.krate] { let url = match cache.extern_locations[&def_id.krate] {
ExternalLocation::Remote(ref s) => { ExternalLocation::Remote(ref s) => {
// `ExternalLocation::Remote` always end with a `/`. // `ExternalLocation::Remote` always end with a `/`.
format!("{}{}", s, path.iter().map(|p| p.as_str()).join("/")) format!("{s}{}", path.iter().map(|p| p.as_str()).join("/"))
} }
ExternalLocation::Local => { ExternalLocation::Local => {
// `root_path` always end with a `/`. // `root_path` always end with a `/`.
format!( format!(
"{}{}/{}", "{}{crate_name}/{}",
root_path.unwrap_or(""), root_path.unwrap_or(""),
crate_name,
path.iter().map(|p| p.as_str()).join("/") path.iter().map(|p| p.as_str()).join("/")
) )
} }
ExternalLocation::Unknown => { ExternalLocation::Unknown => {
debug!("crate {} not in cache when linkifying macros", crate_name); debug!("crate {crate_name} not in cache when linkifying macros");
return Err(HrefError::NotInExternalCache); return Err(HrefError::NotInExternalCache);
} }
}; };
@@ -732,7 +731,7 @@ pub(crate) fn href_with_root_path(
_ => { _ => {
let prefix = shortty.as_str(); let prefix = shortty.as_str();
let last = fqp.last().unwrap(); let last = fqp.last().unwrap();
url_parts.push_fmt(format_args!("{}.{}.html", prefix, last)); url_parts.push_fmt(format_args!("{prefix}.{last}.html"));
} }
} }
Ok((url_parts.finish(), shortty, fqp.to_vec())) Ok((url_parts.finish(), shortty, fqp.to_vec()))
@@ -838,7 +837,7 @@ fn resolved_path<'cx>(
} else { } else {
anchor(did, last.name, cx).to_string() anchor(did, last.name, cx).to_string()
}; };
write!(w, "{}{}", path, last.args.print(cx))?; write!(w, "{path}{}", last.args.print(cx))?;
} }
Ok(()) Ok(())
} }
@@ -906,7 +905,7 @@ fn primitive_link_fragment(
None => {} None => {}
} }
} }
write!(f, "{}", name)?; f.write_str(name)?;
if needs_termination { if needs_termination {
write!(f, "</a>")?; write!(f, "</a>")?;
} }
@@ -946,15 +945,11 @@ pub(crate) fn anchor<'a, 'cx: 'a>(
if let Ok((url, short_ty, fqp)) = parts { if let Ok((url, short_ty, fqp)) = parts {
write!( write!(
f, f,
r#"<a class="{}" href="{}" title="{} {}">{}</a>"#, r#"<a class="{short_ty}" href="{url}" title="{short_ty} {}">{text}</a>"#,
short_ty,
url,
short_ty,
join_with_double_colon(&fqp), join_with_double_colon(&fqp),
text.as_str()
) )
} else { } else {
write!(f, "{}", text) f.write_str(text.as_str())
} }
}) })
} }
@@ -965,10 +960,10 @@ fn fmt_type<'cx>(
use_absolute: bool, use_absolute: bool,
cx: &'cx Context<'_>, cx: &'cx Context<'_>,
) -> fmt::Result { ) -> fmt::Result {
trace!("fmt_type(t = {:?})", t); trace!("fmt_type(t = {t:?})");
match *t { match *t {
clean::Generic(name) => write!(f, "{}", name), clean::Generic(name) => f.write_str(name.as_str()),
clean::Type::Path { ref path } => { clean::Type::Path { ref path } => {
// Paths like `T::Output` and `Self::Output` should be rendered with all segments. // Paths like `T::Output` and `Self::Output` should be rendered with all segments.
let did = path.def_id(); let did = path.def_id();
@@ -1085,13 +1080,13 @@ fn fmt_type<'cx>(
if matches!(**t, clean::Generic(_)) || t.is_assoc_ty() { if matches!(**t, clean::Generic(_)) || t.is_assoc_ty() {
let text = if f.alternate() { let text = if f.alternate() {
format!("*{} {:#}", m, t.print(cx)) format!("*{m} {:#}", t.print(cx))
} else { } else {
format!("*{} {}", m, t.print(cx)) format!("*{m} {}", t.print(cx))
}; };
primitive_link(f, clean::PrimitiveType::RawPointer, &text, cx) primitive_link(f, clean::PrimitiveType::RawPointer, &text, cx)
} else { } else {
primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{} ", m), cx)?; primitive_link(f, clean::PrimitiveType::RawPointer, &format!("*{m} "), cx)?;
fmt::Display::fmt(&t.print(cx), f) fmt::Display::fmt(&t.print(cx), f)
} }
} }
@@ -1446,10 +1441,10 @@ impl clean::FnDecl {
write!(f, "self")?; write!(f, "self")?;
} }
clean::SelfBorrowed(Some(ref lt), mtbl) => { clean::SelfBorrowed(Some(ref lt), mtbl) => {
write!(f, "{}{} {}self", amp, lt.print(), mtbl.print_with_space())?; write!(f, "{amp}{} {}self", lt.print(), mtbl.print_with_space())?;
} }
clean::SelfBorrowed(None, mtbl) => { clean::SelfBorrowed(None, mtbl) => {
write!(f, "{}{}self", amp, mtbl.print_with_space())?; write!(f, "{amp}{}self", mtbl.print_with_space())?;
} }
clean::SelfExplicit(ref typ) => { clean::SelfExplicit(ref typ) => {
write!(f, "self: ")?; write!(f, "self: ")?;
@@ -1523,7 +1518,7 @@ pub(crate) fn visibility_print_with_space<'a, 'tcx: 'a>(
"pub(super) ".into() "pub(super) ".into()
} else { } else {
let path = cx.tcx().def_path(vis_did); let path = cx.tcx().def_path(vis_did);
debug!("path={:?}", path); debug!("path={path:?}");
// modified from `resolved_path()` to work with `DefPathData` // modified from `resolved_path()` to work with `DefPathData`
let last_name = path.data.last().unwrap().data.get_opt_name().unwrap(); let last_name = path.data.last().unwrap().data.get_opt_name().unwrap();
let anchor = anchor(vis_did, last_name, cx); let anchor = anchor(vis_did, last_name, cx);
@@ -1532,12 +1527,12 @@ pub(crate) fn visibility_print_with_space<'a, 'tcx: 'a>(
for seg in &path.data[..path.data.len() - 1] { for seg in &path.data[..path.data.len() - 1] {
let _ = write!(s, "{}::", seg.data.get_opt_name().unwrap()); let _ = write!(s, "{}::", seg.data.get_opt_name().unwrap());
} }
let _ = write!(s, "{}) ", anchor); let _ = write!(s, "{anchor}) ");
s.into() s.into()
} }
} }
}; };
display_fn(move |f| write!(f, "{}", to_print)) display_fn(move |f| f.write_str(&to_print))
} }
/// This function is the same as print_with_space, except that it renders no links. /// This function is the same as print_with_space, except that it renders no links.
@@ -1632,7 +1627,7 @@ impl clean::Import {
if name == self.source.path.last() { if name == self.source.path.last() {
write!(f, "use {};", self.source.print(cx)) write!(f, "use {};", self.source.print(cx))
} else { } else {
write!(f, "use {} as {};", self.source.print(cx), name) write!(f, "use {} as {name};", self.source.print(cx))
} }
} }
clean::ImportKind::Glob => { clean::ImportKind::Glob => {
@@ -1661,7 +1656,7 @@ impl clean::ImportSource {
if let hir::def::Res::PrimTy(p) = self.path.res { if let hir::def::Res::PrimTy(p) = self.path.res {
primitive_link(f, PrimitiveType::from(p), name.as_str(), cx)?; primitive_link(f, PrimitiveType::from(p), name.as_str(), cx)?;
} else { } else {
write!(f, "{}", name)?; f.write_str(name.as_str())?;
} }
Ok(()) Ok(())
} }

View File

@@ -929,15 +929,15 @@ fn string_without_closing_tag<T: Display>(
open_tag: bool, open_tag: bool,
) -> Option<&'static str> { ) -> Option<&'static str> {
let Some(klass) = klass else { let Some(klass) = klass else {
write!(out, "{}", text).unwrap(); write!(out, "{text}").unwrap();
return None; return None;
}; };
let Some(def_span) = klass.get_span() else { let Some(def_span) = klass.get_span() else {
if !open_tag { if !open_tag {
write!(out, "{}", text).unwrap(); write!(out, "{text}").unwrap();
return None; return None;
} }
write!(out, "<span class=\"{}\">{}", klass.as_html(), text).unwrap(); write!(out, "<span class=\"{}\">{text}", klass.as_html()).unwrap();
return Some("</span>"); return Some("</span>");
}; };
@@ -947,14 +947,13 @@ fn string_without_closing_tag<T: Display>(
match t { match t {
"self" | "Self" => write!( "self" | "Self" => write!(
&mut path, &mut path,
"<span class=\"{}\">{}</span>", "<span class=\"{}\">{t}</span>",
Class::Self_(DUMMY_SP).as_html(), Class::Self_(DUMMY_SP).as_html(),
t
), ),
"crate" | "super" => { "crate" | "super" => {
write!(&mut path, "<span class=\"{}\">{}</span>", Class::KeyWord.as_html(), t) write!(&mut path, "<span class=\"{}\">{t}</span>", Class::KeyWord.as_html())
} }
t => write!(&mut path, "{}", t), t => write!(&mut path, "{t}"),
} }
.expect("Failed to build source HTML path"); .expect("Failed to build source HTML path");
path path
@@ -997,13 +996,13 @@ fn string_without_closing_tag<T: Display>(
if !open_tag { if !open_tag {
// We're already inside an element which has the same klass, no need to give it // We're already inside an element which has the same klass, no need to give it
// again. // again.
write!(out, "<a href=\"{}\">{}", href, text_s).unwrap(); write!(out, "<a href=\"{href}\">{text_s}").unwrap();
} else { } else {
let klass_s = klass.as_html(); let klass_s = klass.as_html();
if klass_s.is_empty() { if klass_s.is_empty() {
write!(out, "<a href=\"{}\">{}", href, text_s).unwrap(); write!(out, "<a href=\"{href}\">{text_s}").unwrap();
} else { } else {
write!(out, "<a class=\"{}\" href=\"{}\">{}", klass_s, href, text_s).unwrap(); write!(out, "<a class=\"{klass_s}\" href=\"{href}\">{text_s}").unwrap();
} }
} }
return Some("</a>"); return Some("</a>");
@@ -1018,7 +1017,7 @@ fn string_without_closing_tag<T: Display>(
out.write_str(&text_s).unwrap(); out.write_str(&text_s).unwrap();
Some("") Some("")
} else { } else {
write!(out, "<span class=\"{}\">{}", klass_s, text_s).unwrap(); write!(out, "<span class=\"{klass_s}\">{text_s}").unwrap();
Some("</span>") Some("</span>")
} }
} }

View File

@@ -23,7 +23,7 @@ fn test_html_highlighting() {
let html = { let html = {
let mut out = Buffer::new(); let mut out = Buffer::new();
write_code(&mut out, src, None, None); write_code(&mut out, src, None, None);
format!("{}<pre><code>{}</code></pre>\n", STYLE, out.into_inner()) format!("{STYLE}<pre><code>{}</code></pre>\n", out.into_inner())
}; };
expect_file!["fixtures/sample.html"].assert_eq(&html); expect_file!["fixtures/sample.html"].assert_eq(&html);
}); });

View File

@@ -78,8 +78,7 @@ impl HtmlWithLimit {
pub(super) fn open_tag(&mut self, tag_name: &'static str) { pub(super) fn open_tag(&mut self, tag_name: &'static str) {
assert!( assert!(
tag_name.chars().all(|c| ('a'..='z').contains(&c)), tag_name.chars().all(|c| ('a'..='z').contains(&c)),
"tag_name contained non-alphabetic chars: {:?}", "tag_name contained non-alphabetic chars: {tag_name:?}",
tag_name
); );
self.queued_tags.push(tag_name); self.queued_tags.push(tag_name);
} }
@@ -88,7 +87,7 @@ impl HtmlWithLimit {
pub(super) fn close_tag(&mut self) { pub(super) fn close_tag(&mut self) {
match self.unclosed_tags.pop() { match self.unclosed_tags.pop() {
// Close the most recently opened tag. // Close the most recently opened tag.
Some(tag_name) => write!(self.buf, "</{}>", tag_name).unwrap(), Some(tag_name) => write!(self.buf, "</{tag_name}>").unwrap(),
// There are valid cases where `close_tag()` is called without // There are valid cases where `close_tag()` is called without
// there being any tags to close. For example, this occurs when // there being any tags to close. For example, this occurs when
// a tag is opened after the length limit is exceeded; // a tag is opened after the length limit is exceeded;
@@ -101,7 +100,7 @@ impl HtmlWithLimit {
/// Write all queued tags and add them to the `unclosed_tags` list. /// Write all queued tags and add them to the `unclosed_tags` list.
fn flush_queue(&mut self) { fn flush_queue(&mut self) {
for tag_name in self.queued_tags.drain(..) { for tag_name in self.queued_tags.drain(..) {
write!(self.buf, "<{}>", tag_name).unwrap(); write!(self.buf, "<{tag_name}>").unwrap();
self.unclosed_tags.push(tag_name); self.unclosed_tags.push(tag_name);
} }

View File

@@ -246,9 +246,8 @@ impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'_, 'a, I> {
return Some(Event::Html( return Some(Event::Html(
format!( format!(
"<div class=\"example-wrap\">\ "<div class=\"example-wrap\">\
<pre class=\"language-{}\"><code>{}</code></pre>\ <pre class=\"language-{lang}\"><code>{}</code></pre>\
</div>", </div>",
lang,
Escape(&original_text), Escape(&original_text),
) )
.into(), .into(),
@@ -288,8 +287,9 @@ impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'_, 'a, I> {
let test_escaped = small_url_encode(test); let test_escaped = small_url_encode(test);
Some(format!( Some(format!(
r#"<a class="test-arrow" target="_blank" href="{}?code={}{}&amp;edition={}">Run</a>"#, "<a class=\"test-arrow\" \
url, test_escaped, channel, edition, target=\"_blank\" \
href=\"{url}?code={test_escaped}{channel}&amp;edition={edition}\">Run</a>",
)) ))
}); });
@@ -349,7 +349,7 @@ impl<'a, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, I> {
dest, dest,
title, title,
))) => { ))) => {
debug!("saw start of shortcut link to {} with title {}", dest, title); debug!("saw start of shortcut link to {dest} with title {title}");
// If this is a shortcut link, it was resolved by the broken_link_callback. // If this is a shortcut link, it was resolved by the broken_link_callback.
// So the URL will already be updated properly. // So the URL will already be updated properly.
let link = self.links.iter().find(|&link| *link.href == **dest); let link = self.links.iter().find(|&link| *link.href == **dest);
@@ -370,7 +370,7 @@ impl<'a, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, I> {
dest, dest,
_, _,
))) => { ))) => {
debug!("saw end of shortcut link to {}", dest); debug!("saw end of shortcut link to {dest}");
if self.links.iter().any(|link| *link.href == **dest) { if self.links.iter().any(|link| *link.href == **dest) {
assert!(self.shortcut_link.is_some(), "saw closing link without opening tag"); assert!(self.shortcut_link.is_some(), "saw closing link without opening tag");
self.shortcut_link = None; self.shortcut_link = None;
@@ -379,7 +379,7 @@ impl<'a, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, I> {
// Handle backticks in inline code blocks, but only if we're in the middle of a shortcut link. // Handle backticks in inline code blocks, but only if we're in the middle of a shortcut link.
// [`fn@f`] // [`fn@f`]
Some(Event::Code(text)) => { Some(Event::Code(text)) => {
trace!("saw code {}", text); trace!("saw code {text}");
if let Some(link) = self.shortcut_link { if let Some(link) = self.shortcut_link {
// NOTE: this only replaces if the code block is the *entire* text. // NOTE: this only replaces if the code block is the *entire* text.
// If only part of the link has code highlighting, the disambiguator will not be removed. // If only part of the link has code highlighting, the disambiguator will not be removed.
@@ -394,7 +394,7 @@ impl<'a, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, I> {
l.href == link.href l.href == link.href
&& Some(&**text) == l.original_text.get(1..l.original_text.len() - 1) && Some(&**text) == l.original_text.get(1..l.original_text.len() - 1)
}) { }) {
debug!("replacing {} with {}", text, link.new_text); debug!("replacing {text} with {}", link.new_text);
*text = CowStr::Borrowed(&link.new_text); *text = CowStr::Borrowed(&link.new_text);
} }
} }
@@ -402,7 +402,7 @@ impl<'a, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, I> {
// Replace plain text in links, but only in the middle of a shortcut link. // Replace plain text in links, but only in the middle of a shortcut link.
// [fn@f] // [fn@f]
Some(Event::Text(text)) => { Some(Event::Text(text)) => {
trace!("saw text {}", text); trace!("saw text {text}");
if let Some(link) = self.shortcut_link { if let Some(link) = self.shortcut_link {
// NOTE: same limitations as `Event::Code` // NOTE: same limitations as `Event::Code`
if let Some(link) = self if let Some(link) = self
@@ -410,7 +410,7 @@ impl<'a, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, I> {
.iter() .iter()
.find(|l| l.href == link.href && **text == *l.original_text) .find(|l| l.href == link.href && **text == *l.original_text)
{ {
debug!("replacing {} with {}", text, link.new_text); debug!("replacing {text} with {}", link.new_text);
*text = CowStr::Borrowed(&link.new_text); *text = CowStr::Borrowed(&link.new_text);
} }
} }
@@ -522,12 +522,12 @@ impl<'a, 'b, 'ids, I: Iterator<Item = SpannedEvent<'a>>> Iterator
let mut html_header = String::new(); let mut html_header = String::new();
html::push_html(&mut html_header, self.buf.iter().map(|(ev, _)| ev.clone())); html::push_html(&mut html_header, self.buf.iter().map(|(ev, _)| ev.clone()));
let sec = builder.push(level as u32, html_header, id.clone()); let sec = builder.push(level as u32, html_header, id.clone());
self.buf.push_front((Event::Html(format!("{} ", sec).into()), 0..0)); self.buf.push_front((Event::Html(format!("{sec} ").into()), 0..0));
} }
let level = let level =
std::cmp::min(level as u32 + (self.heading_offset as u32), MAX_HEADER_LEVEL); std::cmp::min(level as u32 + (self.heading_offset as u32), MAX_HEADER_LEVEL);
self.buf.push_back((Event::Html(format!("</a></h{}>", level).into()), 0..0)); self.buf.push_back((Event::Html(format!("</a></h{level}>").into()), 0..0));
let start_tags = format!( let start_tags = format!(
"<h{level} id=\"{id}\">\ "<h{level} id=\"{id}\">\
@@ -681,14 +681,14 @@ impl<'a, I: Iterator<Item = SpannedEvent<'a>>> Iterator for Footnotes<'a, I> {
v.sort_by(|a, b| a.1.cmp(&b.1)); v.sort_by(|a, b| a.1.cmp(&b.1));
let mut ret = String::from("<div class=\"footnotes\"><hr><ol>"); let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
for (mut content, id) in v { for (mut content, id) in v {
write!(ret, "<li id=\"fn{}\">", id).unwrap(); write!(ret, "<li id=\"fn{id}\">").unwrap();
let mut is_paragraph = false; let mut is_paragraph = false;
if let Some(&Event::End(Tag::Paragraph)) = content.last() { if let Some(&Event::End(Tag::Paragraph)) = content.last() {
content.pop(); content.pop();
is_paragraph = true; is_paragraph = true;
} }
html::push_html(&mut ret, content.into_iter()); html::push_html(&mut ret, content.into_iter());
write!(ret, "&nbsp;<a href=\"#fnref{}\">↩</a>", id).unwrap(); write!(ret, "&nbsp;<a href=\"#fnref{id}\">↩</a>").unwrap();
if is_paragraph { if is_paragraph {
ret.push_str("</p>"); ret.push_str("</p>");
} }
@@ -959,7 +959,7 @@ impl LangString {
} { } {
if let Some(extra) = extra { if let Some(extra) = extra {
extra.error_invalid_codeblock_attr( extra.error_invalid_codeblock_attr(
format!("unknown attribute `{}`. Did you mean `{}`?", x, flag), format!("unknown attribute `{x}`. Did you mean `{flag}`?"),
help, help,
); );
} }
@@ -1038,7 +1038,7 @@ impl MarkdownWithToc<'_> {
html::push_html(&mut s, p); html::push_html(&mut s, p);
} }
format!("<nav id=\"TOC\">{}</nav>{}", toc.into_toc().print(), s) format!("<nav id=\"TOC\">{}</nav>{s}", toc.into_toc().print())
} }
} }

View File

@@ -206,15 +206,14 @@ impl<'tcx> Context<'tcx> {
format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate) format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate)
} else { } else {
format!( format!(
"API documentation for the Rust `{}` {} in crate `{}`.", "API documentation for the Rust `{}` {tyname} in crate `{}`.",
it.name.as_ref().unwrap(), it.name.as_ref().unwrap(),
tyname,
self.shared.layout.krate self.shared.layout.krate
) )
}; };
let name; let name;
let tyname_s = if it.is_crate() { let tyname_s = if it.is_crate() {
name = format!("{} crate", tyname); name = format!("{tyname} crate");
name.as_str() name.as_str()
} else { } else {
tyname.as_str() tyname.as_str()
@@ -264,7 +263,7 @@ impl<'tcx> Context<'tcx> {
current_path.push_str(&item_path(ty, names.last().unwrap().as_str())); current_path.push_str(&item_path(ty, names.last().unwrap().as_str()));
redirections.borrow_mut().insert(current_path, path); redirections.borrow_mut().insert(current_path, path);
} }
None => return layout::redirect(&format!("{}{}", self.root_path(), path)), None => return layout::redirect(&format!("{}{path}", self.root_path())),
} }
} }
} }
@@ -382,11 +381,7 @@ impl<'tcx> Context<'tcx> {
let hiline = span.hi(self.sess()).line; let hiline = span.hi(self.sess()).line;
format!( format!(
"#{}", "#{}",
if loline == hiline { if loline == hiline { loline.to_string() } else { format!("{loline}-{hiline}") }
loline.to_string()
} else {
format!("{}-{}", loline, hiline)
}
) )
} else { } else {
"".to_string() "".to_string()
@@ -855,12 +850,12 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
// If the item is a macro, redirect from the old macro URL (with !) // If the item is a macro, redirect from the old macro URL (with !)
// to the new one (without). // to the new one (without).
if item_type == ItemType::Macro { if item_type == ItemType::Macro {
let redir_name = format!("{}.{}!.html", item_type, name); let redir_name = format!("{item_type}.{name}!.html");
if let Some(ref redirections) = self.shared.redirections { if let Some(ref redirections) = self.shared.redirections {
let crate_name = &self.shared.layout.krate; let crate_name = &self.shared.layout.krate;
redirections.borrow_mut().insert( redirections.borrow_mut().insert(
format!("{}/{}", crate_name, redir_name), format!("{crate_name}/{redir_name}"),
format!("{}/{}", crate_name, file_name), format!("{crate_name}/{file_name}"),
); );
} else { } else {
let v = layout::redirect(file_name); let v = layout::redirect(file_name);

View File

@@ -85,7 +85,7 @@ use crate::DOC_RUST_LANG_ORG_CHANNEL;
pub(crate) fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ { pub(crate) fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ {
crate::html::format::display_fn(move |f| { crate::html::format::display_fn(move |f| {
if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { f.write_str(v) } if !v.ends_with('/') && !v.is_empty() { write!(f, "{v}/") } else { f.write_str(v) }
}) })
} }
@@ -416,7 +416,7 @@ fn document<'a, 'cx: 'a>(
heading_offset: HeadingOffset, heading_offset: HeadingOffset,
) -> impl fmt::Display + 'a + Captures<'cx> { ) -> impl fmt::Display + 'a + Captures<'cx> {
if let Some(ref name) = item.name { if let Some(ref name) = item.name {
info!("Documenting {}", name); info!("Documenting {name}");
} }
display_fn(move |f| { display_fn(move |f| {
@@ -513,7 +513,7 @@ fn document_full_inner<'a, 'cx: 'a>(
) -> impl fmt::Display + 'a + Captures<'cx> { ) -> impl fmt::Display + 'a + Captures<'cx> {
display_fn(move |f| { display_fn(move |f| {
if let Some(s) = item.opt_doc_value() { if let Some(s) = item.opt_doc_value() {
debug!("Doc block: =====\n{}\n=====", s); debug!("Doc block: =====\n{s}\n=====");
if is_collapsible { if is_collapsible {
write!( write!(
f, f,
@@ -565,12 +565,10 @@ fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<Strin
}; };
debug!( debug!(
"Portability {:?} {:?} (parent: {:?}) - {:?} = {:?}", "Portability {:?} {:?} (parent: {parent:?}) - {:?} = {cfg:?}",
item.name, item.name,
item.cfg, item.cfg,
parent,
parent.and_then(|p| p.cfg.as_ref()), parent.and_then(|p| p.cfg.as_ref()),
cfg
); );
Some(cfg?.render_long_html()) Some(cfg?.render_long_html())
@@ -1041,7 +1039,7 @@ fn render_attributes_in_pre<'a, 'b: 'a>(
) -> impl fmt::Display + Captures<'a> + Captures<'b> { ) -> impl fmt::Display + Captures<'a> + Captures<'b> {
crate::html::format::display_fn(move |f| { crate::html::format::display_fn(move |f| {
for a in it.attributes(tcx, false) { for a in it.attributes(tcx, false) {
writeln!(f, "{}{}", prefix, a)?; writeln!(f, "{prefix}{a}")?;
} }
Ok(()) Ok(())
}) })
@@ -1245,7 +1243,7 @@ fn render_deref_methods(
_ => None, _ => None,
}) })
.expect("Expected associated type binding"); .expect("Expected associated type binding");
debug!("Render deref methods for {:#?}, target {:#?}", impl_.inner_impl().for_, target); debug!("Render deref methods for {:#?}, target {target:#?}", impl_.inner_impl().for_);
let what = let what =
AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut }; AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut };
if let Some(did) = target.def_id(cache) { if let Some(did) = target.def_id(cache) {

View File

@@ -310,9 +310,8 @@ fn toggle_open(mut w: impl fmt::Write, text: impl fmt::Display) {
w, w,
"<details class=\"toggle type-contents-toggle\">\ "<details class=\"toggle type-contents-toggle\">\
<summary class=\"hideme\">\ <summary class=\"hideme\">\
<span>Show {}</span>\ <span>Show {text}</span>\
</summary>", </summary>",
text
) )
.unwrap(); .unwrap();
} }
@@ -412,7 +411,7 @@ fn item_module(w: &mut Buffer, cx: &mut Context<'_>, item: &clean::Item, items:
) )
}); });
debug!("{:?}", indices); debug!("{indices:?}");
let mut last_section = None; let mut last_section = None;
for &idx in &indices { for &idx in &indices {
@@ -431,8 +430,7 @@ fn item_module(w: &mut Buffer, cx: &mut Context<'_>, item: &clean::Item, items:
w, w,
"<h2 id=\"{id}\" class=\"small-section-header\">\ "<h2 id=\"{id}\" class=\"small-section-header\">\
<a href=\"#{id}\">{name}</a>\ <a href=\"#{id}\">{name}</a>\
</h2>{}", </h2>{ITEM_TABLE_OPEN}",
ITEM_TABLE_OPEN,
id = cx.derive_id(my_section.id()), id = cx.derive_id(my_section.id()),
name = my_section.name(), name = my_section.name(),
); );
@@ -485,7 +483,7 @@ fn item_module(w: &mut Buffer, cx: &mut Context<'_>, item: &clean::Item, items:
w.write_str(ITEM_TABLE_ROW_OPEN); w.write_str(ITEM_TABLE_ROW_OPEN);
let id = match import.kind { let id = match import.kind {
clean::ImportKind::Simple(s) => { clean::ImportKind::Simple(s) => {
format!(" id=\"{}\"", cx.derive_id(format!("reexport.{}", s))) format!(" id=\"{}\"", cx.derive_id(format!("reexport.{s}")))
} }
clean::ImportKind::Glob => String::new(), clean::ImportKind::Glob => String::new(),
}; };
@@ -583,10 +581,8 @@ fn extra_info_tags<'a, 'tcx: 'a>(
display_fn(move |f| { display_fn(move |f| {
write!( write!(
f, f,
r#"<span class="stab {}" title="{}">{}</span>"#, r#"<span class="stab {class}" title="{}">{contents}</span>"#,
class,
Escape(title), Escape(title),
contents
) )
}) })
} }
@@ -614,7 +610,7 @@ fn extra_info_tags<'a, 'tcx: 'a>(
(cfg, _) => cfg.as_deref().cloned(), (cfg, _) => cfg.as_deref().cloned(),
}; };
debug!("Portability name={:?} {:?} - {:?} = {:?}", item.name, item.cfg, parent.cfg, cfg); debug!("Portability name={:?} {:?} - {:?} = {cfg:?}", item.name, item.cfg, parent.cfg);
if let Some(ref cfg) = cfg { if let Some(ref cfg) = cfg {
write!( write!(
f, f,
@@ -689,14 +685,13 @@ fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean:
wrap_item(w, |mut w| { wrap_item(w, |mut w| {
write!( write!(
w, w,
"{attrs}{}{}{}trait {}{}{}", "{attrs}{vis}{unsafety}{is_auto}trait {name}{generics}{bounds}",
visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
t.unsafety(tcx).print_with_space(),
if t.is_auto(tcx) { "auto " } else { "" },
it.name.unwrap(),
t.generics.print(cx),
bounds,
attrs = render_attributes_in_pre(it, "", tcx), attrs = render_attributes_in_pre(it, "", tcx),
vis = visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
unsafety = t.unsafety(tcx).print_with_space(),
is_auto = if t.is_auto(tcx) { "auto " } else { "" },
name = it.name.unwrap(),
generics = t.generics.print(cx),
); );
if !t.generics.where_predicates.is_empty() { if !t.generics.where_predicates.is_empty() {
@@ -742,10 +737,8 @@ fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean:
toggle_open( toggle_open(
&mut w, &mut w,
format_args!( format_args!(
"{} associated constant{} and {} method{}", "{count_consts} associated constant{} and {count_methods} method{}",
count_consts,
pluralize(count_consts), pluralize(count_consts),
count_methods,
pluralize(count_methods), pluralize(count_methods),
), ),
); );
@@ -768,7 +761,7 @@ fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean:
} }
if !toggle && should_hide_fields(count_methods) { if !toggle && should_hide_fields(count_methods) {
toggle = true; toggle = true;
toggle_open(&mut w, format_args!("{} methods", count_methods)); toggle_open(&mut w, format_args!("{count_methods} methods"));
} }
if count_consts != 0 && count_methods != 0 { if count_consts != 0 && count_methods != 0 {
w.write_str("\n"); w.write_str("\n");
@@ -837,9 +830,9 @@ fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean:
fn trait_item(w: &mut Buffer, cx: &mut Context<'_>, m: &clean::Item, t: &clean::Item) { fn trait_item(w: &mut Buffer, cx: &mut Context<'_>, m: &clean::Item, t: &clean::Item) {
let name = m.name.unwrap(); let name = m.name.unwrap();
info!("Documenting {} on {:?}", name, t.name); info!("Documenting {name} on {:?}", t.name);
let item_type = m.type_(); let item_type = m.type_();
let id = cx.derive_id(format!("{}.{}", item_type, name)); let id = cx.derive_id(format!("{item_type}.{name}"));
let mut content = Buffer::empty_from(w); let mut content = Buffer::empty_from(w);
write!(&mut content, "{}", document(cx, m, Some(t), HeadingOffset::H5)); write!(&mut content, "{}", document(cx, m, Some(t), HeadingOffset::H5));
let toggled = !content.is_empty(); let toggled = !content.is_empty();
@@ -847,7 +840,7 @@ fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean:
let method_toggle_class = if item_type.is_method() { " method-toggle" } else { "" }; let method_toggle_class = if item_type.is_method() { " method-toggle" } else { "" };
write!(w, "<details class=\"toggle{method_toggle_class}\" open><summary>"); write!(w, "<details class=\"toggle{method_toggle_class}\" open><summary>");
} }
write!(w, "<section id=\"{}\" class=\"method\">", id); write!(w, "<section id=\"{id}\" class=\"method\">");
render_rightside(w, cx, m, t, RenderMode::Normal); render_rightside(w, cx, m, t, RenderMode::Normal);
write!(w, "<h4 class=\"code-header\">"); write!(w, "<h4 class=\"code-header\">");
render_assoc_item( render_assoc_item(
@@ -1170,12 +1163,12 @@ fn item_trait_alias(
wrap_item(w, |w| { wrap_item(w, |w| {
write!( write!(
w, w,
"{attrs}trait {}{}{} = {};", "{attrs}trait {name}{generics}{where_b} = {bounds};",
it.name.unwrap(),
t.generics.print(cx),
print_where_clause(&t.generics, cx, 0, Ending::Newline),
bounds(&t.bounds, true, cx),
attrs = render_attributes_in_pre(it, "", cx.tcx()), attrs = render_attributes_in_pre(it, "", cx.tcx()),
name = it.name.unwrap(),
generics = t.generics.print(cx),
where_b = print_where_clause(&t.generics, cx, 0, Ending::Newline),
bounds = bounds(&t.bounds, true, cx),
) )
.unwrap(); .unwrap();
}); });
@@ -1198,12 +1191,12 @@ fn item_opaque_ty(
wrap_item(w, |w| { wrap_item(w, |w| {
write!( write!(
w, w,
"{attrs}type {}{}{where_clause} = impl {bounds};", "{attrs}type {name}{generics}{where_clause} = impl {bounds};",
it.name.unwrap(), attrs = render_attributes_in_pre(it, "", cx.tcx()),
t.generics.print(cx), name = it.name.unwrap(),
generics = t.generics.print(cx),
where_clause = print_where_clause(&t.generics, cx, 0, Ending::Newline), where_clause = print_where_clause(&t.generics, cx, 0, Ending::Newline),
bounds = bounds(&t.bounds, false, cx), bounds = bounds(&t.bounds, false, cx),
attrs = render_attributes_in_pre(it, "", cx.tcx()),
) )
.unwrap(); .unwrap();
}); });
@@ -1223,13 +1216,13 @@ fn item_typedef(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clea
wrap_item(w, |w| { wrap_item(w, |w| {
write!( write!(
w, w,
"{attrs}{}type {}{}{where_clause} = {type_};", "{attrs}{vis}type {name}{generics}{where_clause} = {type_};",
visibility_print_with_space(it.visibility(cx.tcx()), it.item_id, cx), attrs = render_attributes_in_pre(it, "", cx.tcx()),
it.name.unwrap(), vis = visibility_print_with_space(it.visibility(cx.tcx()), it.item_id, cx),
t.generics.print(cx), name = it.name.unwrap(),
generics = t.generics.print(cx),
where_clause = print_where_clause(&t.generics, cx, 0, Ending::Newline), where_clause = print_where_clause(&t.generics, cx, 0, Ending::Newline),
type_ = t.type_.print(cx), type_ = t.type_.print(cx),
attrs = render_attributes_in_pre(it, "", cx.tcx()),
); );
}); });
} }
@@ -1354,7 +1347,7 @@ fn item_enum(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, e: &clean::
w.write_str("{\n"); w.write_str("{\n");
let toggle = should_hide_fields(count_variants); let toggle = should_hide_fields(count_variants);
if toggle { if toggle {
toggle_open(&mut w, format_args!("{} variants", count_variants)); toggle_open(&mut w, format_args!("{count_variants} variants"));
} }
for v in e.variants() { for v in e.variants() {
w.write_str(" "); w.write_str(" ");
@@ -1362,7 +1355,7 @@ fn item_enum(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, e: &clean::
match *v.kind { match *v.kind {
// FIXME(#101337): Show discriminant // FIXME(#101337): Show discriminant
clean::VariantItem(ref var) => match var.kind { clean::VariantItem(ref var) => match var.kind {
clean::VariantKind::CLike => write!(w, "{}", name), clean::VariantKind::CLike => w.write_str(name.as_str()),
clean::VariantKind::Tuple(ref s) => { clean::VariantKind::Tuple(ref s) => {
write!(w, "{name}({})", print_tuple_struct_fields(cx, s),); write!(w, "{name}({})", print_tuple_struct_fields(cx, s),);
} }
@@ -1418,7 +1411,7 @@ fn item_enum(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, e: &clean::
let clean::VariantItem(variant_data) = &*variant.kind else { unreachable!() }; let clean::VariantItem(variant_data) = &*variant.kind else { unreachable!() };
if let clean::VariantKind::Tuple(ref s) = variant_data.kind { if let clean::VariantKind::Tuple(ref s) = variant_data.kind {
write!(w, "({})", print_tuple_struct_fields(cx, s),); write!(w, "({})", print_tuple_struct_fields(cx, s));
} }
w.write_str("</h3></section>"); w.write_str("</h3></section>");
@@ -1617,7 +1610,7 @@ fn item_struct(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean
for (index, (field, ty)) in fields.enumerate() { for (index, (field, ty)) in fields.enumerate() {
let field_name = let field_name =
field.name.map_or_else(|| index.to_string(), |sym| sym.as_str().to_string()); field.name.map_or_else(|| index.to_string(), |sym| sym.as_str().to_string());
let id = cx.derive_id(format!("{}.{}", ItemType::StructField, field_name)); let id = cx.derive_id(format!("{}.{field_name}", ItemType::StructField));
write!( write!(
w, w,
"<span id=\"{id}\" class=\"{item_type} small-section-header\">\ "<span id=\"{id}\" class=\"{item_type} small-section-header\">\
@@ -1722,7 +1715,7 @@ pub(super) fn full_path(cx: &Context<'_>, item: &clean::Item) -> String {
pub(super) fn item_path(ty: ItemType, name: &str) -> String { pub(super) fn item_path(ty: ItemType, name: &str) -> String {
match ty { match ty {
ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)), ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)),
_ => format!("{}.{}.html", ty, name), _ => format!("{ty}.{name}.html"),
} }
} }
@@ -1845,7 +1838,7 @@ fn render_union<'a, 'cx: 'a>(
fields.iter().filter(|field| matches!(*field.kind, clean::StructFieldItem(..))).count(); fields.iter().filter(|field| matches!(*field.kind, clean::StructFieldItem(..))).count();
let toggle = should_hide_fields(count_fields); let toggle = should_hide_fields(count_fields);
if toggle { if toggle {
toggle_open(&mut f, format_args!("{} fields", count_fields)); toggle_open(&mut f, format_args!("{count_fields} fields"));
} }
for field in fields { for field in fields {
@@ -1908,14 +1901,13 @@ fn render_struct(
let has_visible_fields = count_fields > 0; let has_visible_fields = count_fields > 0;
let toggle = should_hide_fields(count_fields); let toggle = should_hide_fields(count_fields);
if toggle { if toggle {
toggle_open(&mut w, format_args!("{} fields", count_fields)); toggle_open(&mut w, format_args!("{count_fields} fields"));
} }
for field in fields { for field in fields {
if let clean::StructFieldItem(ref ty) = *field.kind { if let clean::StructFieldItem(ref ty) = *field.kind {
write!( write!(
w, w,
"\n{} {}{}: {},", "\n{tab} {}{}: {},",
tab,
visibility_print_with_space(field.visibility(tcx), field.item_id, cx), visibility_print_with_space(field.visibility(tcx), field.item_id, cx),
field.name.unwrap(), field.name.unwrap(),
ty.print(cx), ty.print(cx),
@@ -1925,9 +1917,9 @@ fn render_struct(
if has_visible_fields { if has_visible_fields {
if it.has_stripped_entries().unwrap() { if it.has_stripped_entries().unwrap() {
write!(w, "\n{} /* private fields */", tab); write!(w, "\n{tab} /* private fields */");
} }
write!(w, "\n{}", tab); write!(w, "\n{tab}");
} else if it.has_stripped_entries().unwrap() { } else if it.has_stripped_entries().unwrap() {
write!(w, " /* private fields */ "); write!(w, " /* private fields */ ");
} }

View File

@@ -330,7 +330,7 @@ fn sidebar_deref_methods<'a>(
) { ) {
let c = cx.cache(); let c = cx.cache();
debug!("found Deref: {:?}", impl_); debug!("found Deref: {impl_:?}");
if let Some((target, real_target)) = if let Some((target, real_target)) =
impl_.inner_impl().items.iter().find_map(|item| match *item.kind { impl_.inner_impl().items.iter().find_map(|item| match *item.kind {
clean::AssocTypeItem(box ref t, _) => Some(match *t { clean::AssocTypeItem(box ref t, _) => Some(match *t {
@@ -340,7 +340,7 @@ fn sidebar_deref_methods<'a>(
_ => None, _ => None,
}) })
{ {
debug!("found target, real_target: {:?} {:?}", target, real_target); debug!("found target, real_target: {target:?} {real_target:?}");
if let Some(did) = target.def_id(c) && if let Some(did) = target.def_id(c) &&
let Some(type_did) = impl_.inner_impl().for_.def_id(c) && let Some(type_did) = impl_.inner_impl().for_.def_id(c) &&
// `impl Deref<Target = S> for S` // `impl Deref<Target = S> for S`
@@ -357,7 +357,7 @@ fn sidebar_deref_methods<'a>(
}) })
.and_then(|did| c.impls.get(&did)); .and_then(|did| c.impls.get(&did));
if let Some(impls) = inner_impl { if let Some(impls) = inner_impl {
debug!("found inner_impl: {:?}", impls); debug!("found inner_impl: {impls:?}");
let mut ret = impls let mut ret = impls
.iter() .iter()
.filter(|i| i.inner_impl().trait_.is_none()) .filter(|i| i.inner_impl().trait_.is_none())
@@ -510,10 +510,10 @@ fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String {
return url; return url;
} }
let mut add = 1; let mut add = 1;
while !used_links.insert(format!("{}-{}", url, add)) { while !used_links.insert(format!("{url}-{add}")) {
add += 1; add += 1;
} }
format!("{}-{}", url, add) format!("{url}-{add}")
} }
fn get_methods<'a>( fn get_methods<'a>(
@@ -529,7 +529,7 @@ fn get_methods<'a>(
Some(ref name) if !name.is_empty() && item.is_method() => { Some(ref name) if !name.is_empty() && item.is_method() => {
if !for_deref || super::should_render_item(item, deref_mut, tcx) { if !for_deref || super::should_render_item(item, deref_mut, tcx) {
Some(Link::new( Some(Link::new(
get_next_url(used_links, format!("{}.{}", ItemType::Method, name)), get_next_url(used_links, format!("{}.{name}", ItemType::Method)),
name.as_str(), name.as_str(),
)) ))
} else { } else {
@@ -549,7 +549,7 @@ fn get_associated_constants<'a>(
.iter() .iter()
.filter_map(|item| match item.name { .filter_map(|item| match item.name {
Some(ref name) if !name.is_empty() && item.is_associated_const() => Some(Link::new( Some(ref name) if !name.is_empty() && item.is_associated_const() => Some(Link::new(
get_next_url(used_links, format!("{}.{}", ItemType::AssocConst, name)), get_next_url(used_links, format!("{}.{name}", ItemType::AssocConst)),
name.as_str(), name.as_str(),
)), )),
_ => None, _ => None,

View File

@@ -73,7 +73,7 @@ pub(super) fn write_shared(
} }
let bytes = try_err!(fs::read(&entry.path), &entry.path); let bytes = try_err!(fs::read(&entry.path), &entry.path);
let filename = format!("{}{}.{}", theme, cx.shared.resource_suffix, extension); let filename = format!("{theme}{}.{extension}", cx.shared.resource_suffix);
cx.shared.fs.write(cx.dst.join(filename), bytes)?; cx.shared.fs.write(cx.dst.join(filename), bytes)?;
} }
@@ -112,7 +112,7 @@ pub(super) fn write_shared(
let mut krates = Vec::new(); let mut krates = Vec::new();
if path.exists() { if path.exists() {
let prefix = format!("\"{}\"", krate); let prefix = format!("\"{krate}\"");
for line in BufReader::new(File::open(path)?).lines() { for line in BufReader::new(File::open(path)?).lines() {
let line = line?; let line = line?;
if !line.starts_with('"') { if !line.starts_with('"') {
@@ -157,7 +157,7 @@ pub(super) fn write_shared(
let mut krates = Vec::new(); let mut krates = Vec::new();
if path.exists() { if path.exists() {
let prefix = format!("\"{}\"", krate); let prefix = format!("\"{krate}\"");
for line in BufReader::new(File::open(path)?).lines() { for line in BufReader::new(File::open(path)?).lines() {
let line = line?; let line = line?;
if !line.starts_with('"') { if !line.starts_with('"') {
@@ -213,10 +213,10 @@ pub(super) fn write_shared(
let dirs = if subs.is_empty() && files.is_empty() { let dirs = if subs.is_empty() && files.is_empty() {
String::new() String::new()
} else { } else {
format!(",[{}]", subs) format!(",[{subs}]")
}; };
let files = files.join(","); let files = files.join(",");
let files = if files.is_empty() { String::new() } else { format!(",[{}]", files) }; let files = if files.is_empty() { String::new() } else { format!(",[{files}]") };
format!( format!(
"[\"{name}\"{dirs}{files}]", "[\"{name}\"{dirs}{files}]",
name = self.elem.to_str().expect("invalid osstring conversion"), name = self.elem.to_str().expect("invalid osstring conversion"),
@@ -319,8 +319,8 @@ if (typeof exports !== 'undefined') {exports.searchIndex = searchIndex};
})?; })?;
write_invocation_specific("crates.js", &|| { write_invocation_specific("crates.js", &|| {
let krates = krates.iter().map(|k| format!("\"{}\"", k)).join(","); let krates = krates.iter().map(|k| format!("\"{k}\"")).join(",");
Ok(format!("window.ALL_CRATES = [{}];", krates).into_bytes()) Ok(format!("window.ALL_CRATES = [{krates}];").into_bytes())
})?; })?;
if options.enable_index_page { if options.enable_index_page {
@@ -349,9 +349,8 @@ if (typeof exports !== 'undefined') {exports.searchIndex = searchIndex};
.iter() .iter()
.map(|s| { .map(|s| {
format!( format!(
"<li><a href=\"{}index.html\">{}</a></li>", "<li><a href=\"{}index.html\">{s}</a></li>",
ensure_trailing_slash(s), ensure_trailing_slash(s),
s
) )
}) })
.collect::<String>() .collect::<String>()
@@ -444,7 +443,7 @@ if (typeof exports !== 'undefined') {exports.searchIndex = searchIndex};
mydst.push(part.to_string()); mydst.push(part.to_string());
} }
cx.shared.ensure_dir(&mydst)?; cx.shared.ensure_dir(&mydst)?;
mydst.push(&format!("{}.{}.js", remote_item_type, remote_path[remote_path.len() - 1])); mydst.push(&format!("{remote_item_type}.{}.js", remote_path[remote_path.len() - 1]));
let (mut all_implementors, _) = let (mut all_implementors, _) =
try_err!(collect(&mydst, krate.name(cx.tcx()).as_str()), &mydst); try_err!(collect(&mydst, krate.name(cx.tcx()).as_str()), &mydst);

View File

@@ -146,9 +146,8 @@ impl DocVisitor for SourceCollector<'_, '_> {
self.cx.shared.tcx.sess.span_err( self.cx.shared.tcx.sess.span_err(
span, span,
format!( format!(
"failed to render source code for `{}`: {}", "failed to render source code for `{}`: {e}",
filename.prefer_local(), filename.prefer_local(),
e,
), ),
); );
false false

View File

@@ -53,7 +53,7 @@ pub(crate) fn suffix_path(filename: &str, suffix: &str) -> PathBuf {
// which would result in `style.min-suffix.css` which isn't what we // which would result in `style.min-suffix.css` which isn't what we
// want. // want.
let (base, ext) = filename.split_once('.').unwrap(); let (base, ext) = filename.split_once('.').unwrap();
let filename = format!("{}{}.{}", base, suffix, ext); let filename = format!("{base}{suffix}.{ext}");
filename.into() filename.into()
} }

View File

@@ -139,7 +139,7 @@ impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> {
fn item(&mut self, item: clean::Item) -> Result<(), Error> { fn item(&mut self, item: clean::Item) -> Result<(), Error> {
let item_type = item.type_(); let item_type = item.type_();
let item_name = item.name; let item_name = item.name;
trace!("rendering {} {:?}", item_type, item_name); trace!("rendering {item_type} {item_name:?}");
// Flatten items that recursively store other items. We include orphaned items from // Flatten items that recursively store other items. We include orphaned items from
// stripped modules and etc that are otherwise reachable. // stripped modules and etc that are otherwise reachable.
@@ -203,11 +203,11 @@ impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> {
if !can_be_ignored { if !can_be_ignored {
assert_eq!(old_item, new_item); assert_eq!(old_item, new_item);
} }
trace!("replaced {:?}\nwith {:?}", old_item, new_item); trace!("replaced {old_item:?}\nwith {new_item:?}");
} }
} }
trace!("done rendering {} {:?}", item_type, item_name); trace!("done rendering {item_type} {item_name:?}");
Ok(()) Ok(())
} }

View File

@@ -192,8 +192,7 @@ fn init_logging(handler: &EarlyErrorHandler) {
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) => handler.early_error(format!(
"invalid log color value '{}': expected one of always, never, or auto", "invalid log color value '{value}': expected one of always, never, or auto",
value
)), )),
Err(VarError::NotUnicode(value)) => handler.early_error(format!( Err(VarError::NotUnicode(value)) => handler.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",
@@ -224,7 +223,7 @@ fn get_args(handler: &EarlyErrorHandler) -> Option<Vec<String>> {
.map(|(i, arg)| { .map(|(i, arg)| {
arg.into_string() arg.into_string()
.map_err(|arg| { .map_err(|arg| {
handler.early_warn(format!("Argument {} is not valid Unicode: {:?}", i, arg)); handler.early_warn(format!("Argument {i} is not valid Unicode: {arg:?}"));
}) })
.ok() .ok()
}) })
@@ -665,11 +664,10 @@ fn usage(argv0: &str) {
for option in opts() { for option in opts() {
(option.apply)(&mut options); (option.apply)(&mut options);
} }
println!("{}", options.usage(&format!("{} [options] <input>", argv0))); println!("{}", options.usage(&format!("{argv0} [options] <input>")));
println!(" @path Read newline separated options from `path`\n"); println!(" @path Read newline separated options from `path`\n");
println!( println!(
"More information available at {}/rustdoc/what-is-rustdoc.html", "More information available at {DOC_RUST_LANG_ORG_CHANNEL}/rustdoc/what-is-rustdoc.html",
DOC_RUST_LANG_ORG_CHANNEL
); );
} }
@@ -699,7 +697,7 @@ fn run_renderer<'tcx, T: formats::FormatRenderer<'tcx>>(
tcx.sess.struct_err(format!("couldn't generate documentation: {}", e.error)); tcx.sess.struct_err(format!("couldn't generate documentation: {}", e.error));
let file = e.file.display().to_string(); let file = e.file.display().to_string();
if !file.is_empty() { if !file.is_empty() {
msg.note(format!("failed to create or modify \"{}\"", file)); msg.note(format!("failed to create or modify \"{file}\""));
} }
Err(msg.emit()) Err(msg.emit())
} }

View File

@@ -43,7 +43,7 @@ pub(crate) fn render<P: AsRef<Path>>(
edition: Edition, edition: Edition,
) -> Result<(), String> { ) -> Result<(), String> {
if let Err(e) = create_dir_all(&options.output) { if let Err(e) = create_dir_all(&options.output) {
return Err(format!("{}: {}", options.output.display(), e)); return Err(format!("{}: {e}", options.output.display()));
} }
let input = input.as_ref(); let input = input.as_ref();
@@ -57,11 +57,11 @@ pub(crate) fn render<P: AsRef<Path>>(
.expect("Writing to a String can't fail"); .expect("Writing to a String can't fail");
} }
let input_str = read_to_string(input).map_err(|err| format!("{}: {}", input.display(), err))?; let input_str = read_to_string(input).map_err(|err| format!("{}: {err}", input.display()))?;
let playground_url = options.markdown_playground_url.or(options.playground_url); let playground_url = options.markdown_playground_url.or(options.playground_url);
let playground = playground_url.map(|url| markdown::Playground { crate_name: None, url }); let playground = playground_url.map(|url| markdown::Playground { crate_name: None, url });
let mut out = File::create(&output).map_err(|e| format!("{}: {}", output.display(), e))?; let mut out = File::create(&output).map_err(|e| format!("{}: {e}", output.display()))?;
let (metadata, text) = extract_leading_metadata(&input_str); let (metadata, text) = extract_leading_metadata(&input_str);
if metadata.is_empty() { if metadata.is_empty() {
@@ -129,7 +129,7 @@ pub(crate) fn render<P: AsRef<Path>>(
); );
match err { match err {
Err(e) => Err(format!("cannot write to `{}`: {}", output.display(), e)), Err(e) => Err(format!("cannot write to `{}`: {e}", output.display())),
Ok(_) => Ok(()), Ok(_) => Ok(()),
} }
} }
@@ -137,7 +137,7 @@ pub(crate) fn render<P: AsRef<Path>>(
/// Runs any tests/code examples in the markdown file `input`. /// Runs any tests/code examples in the markdown file `input`.
pub(crate) fn test(options: Options) -> Result<(), String> { pub(crate) fn test(options: Options) -> Result<(), String> {
let input_str = read_to_string(&options.input) let input_str = read_to_string(&options.input)
.map_err(|err| format!("{}: {}", options.input.display(), err))?; .map_err(|err| format!("{}: {err}", options.input.display()))?;
let mut opts = GlobalTestOptions::default(); let mut opts = GlobalTestOptions::default();
opts.no_crate_inject = true; opts.no_crate_inject = true;
let mut collector = Collector::new( let mut collector = Collector::new(

View File

@@ -146,8 +146,8 @@ impl<'a, 'b> CoverageCalculator<'a, 'b> {
examples_percentage: f64, examples_percentage: f64,
) { ) {
println!( println!(
"| {:<35} | {:>10} | {:>9.1}% | {:>10} | {:>9.1}% |", "| {name:<35} | {:>10} | {percentage:>9.1}% | {:>10} | {:>9.1}% |",
name, count.with_docs, percentage, count.with_examples, examples_percentage, count.with_docs, count.with_examples, examples_percentage,
); );
} }
@@ -249,7 +249,7 @@ impl<'a, 'b> DocVisitor for CoverageCalculator<'a, 'b> {
if let Some(span) = i.span(self.ctx.tcx) { if let Some(span) = i.span(self.ctx.tcx) {
let filename = span.filename(self.ctx.sess()); let filename = span.filename(self.ctx.sess());
debug!("counting {:?} {:?} in {:?}", i.type_(), i.name, filename); debug!("counting {:?} {:?} in {filename:?}", i.type_(), i.name);
self.items.entry(filename).or_default().count_item( self.items.entry(filename).or_default().count_item(
has_docs, has_docs,
has_doc_example, has_doc_example,

View File

@@ -117,7 +117,7 @@ pub(crate) fn look_for_tests<'tcx>(cx: &DocContext<'tcx>, dox: &str, item: &Item
if tests.found_tests == 0 && cx.tcx.features().rustdoc_missing_doc_code_examples { if tests.found_tests == 0 && cx.tcx.features().rustdoc_missing_doc_code_examples {
if should_have_doc_example(cx, item) { if should_have_doc_example(cx, item) {
debug!("reporting error for {:?} (hir_id={:?})", item, hir_id); debug!("reporting error for {item:?} (hir_id={hir_id:?})");
let sp = item.attr_span(cx.tcx); let sp = item.attr_span(cx.tcx);
cx.tcx.struct_span_lint_hir( cx.tcx.struct_span_lint_hir(
crate::lint::MISSING_DOC_CODE_EXAMPLES, crate::lint::MISSING_DOC_CODE_EXAMPLES,

View File

@@ -150,7 +150,7 @@ impl TryFrom<ResolveRes> for Res {
PrimTy(prim) => Ok(Res::Primitive(PrimitiveType::from_hir(prim))), PrimTy(prim) => Ok(Res::Primitive(PrimitiveType::from_hir(prim))),
// e.g. `#[derive]` // e.g. `#[derive]`
ToolMod | NonMacroAttr(..) | Err => Result::Err(()), ToolMod | NonMacroAttr(..) | Err => Result::Err(()),
other => bug!("unrecognized res {:?}", other), other => bug!("unrecognized res {other:?}"),
} }
} }
} }
@@ -224,7 +224,7 @@ impl UrlFragment {
"structfield." "structfield."
} }
} }
kind => bug!("unexpected associated item kind: {:?}", kind), kind => bug!("unexpected associated item kind: {kind:?}"),
}; };
s.push_str(kind); s.push_str(kind);
s.push_str(tcx.item_name(def_id).as_str()); s.push_str(tcx.item_name(def_id).as_str());
@@ -279,7 +279,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
unresolved: path_str.into(), unresolved: path_str.into(),
}; };
debug!("looking for enum variant {}", path_str); debug!("looking for enum variant {path_str}");
let mut split = path_str.rsplitn(3, "::"); let mut split = path_str.rsplitn(3, "::");
let variant_field_name = split let variant_field_name = split
.next() .next()
@@ -410,7 +410,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
}) })
.and_then(|res| res.try_into().ok()) .and_then(|res| res.try_into().ok())
.or_else(|| resolve_primitive(path_str, ns)); .or_else(|| resolve_primitive(path_str, ns));
debug!("{} resolved to {:?} in namespace {:?}", path_str, result, ns); debug!("{path_str} resolved to {result:?} in namespace {ns:?}");
result result
} }
@@ -453,7 +453,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
// If there's no `::`, it's not an associated item. // If there's no `::`, it's not an associated item.
// So we can be sure that `rustc_resolve` was accurate when it said it wasn't resolved. // So we can be sure that `rustc_resolve` was accurate when it said it wasn't resolved.
.ok_or_else(|| { .ok_or_else(|| {
debug!("found no `::`, assuming {} was correctly not in scope", item_name); debug!("found no `::`, assuming {item_name} was correctly not in scope");
UnresolvedPath { UnresolvedPath {
item_id, item_id,
module_id, module_id,
@@ -603,7 +603,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
def_kind @ (DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::ForeignTy), def_kind @ (DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::ForeignTy),
did, did,
) => { ) => {
debug!("looking for associated item named {} for item {:?}", item_name, did); debug!("looking for associated item named {item_name} for item {did:?}");
// Checks if item_name is a variant of the `SomeItem` enum // Checks if item_name is a variant of the `SomeItem` enum
if ns == TypeNS && def_kind == DefKind::Enum { if ns == TypeNS && def_kind == DefKind::Enum {
match tcx.type_of(did).instantiate_identity().kind() { match tcx.type_of(did).instantiate_identity().kind() {
@@ -651,7 +651,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
.collect::<Vec<_>>(); .collect::<Vec<_>>();
} }
debug!("got associated item {:?}", assoc_items); debug!("got associated item {assoc_items:?}");
if !assoc_items.is_empty() { if !assoc_items.is_empty() {
return assoc_items; return assoc_items;
@@ -660,7 +660,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
if ns != Namespace::ValueNS { if ns != Namespace::ValueNS {
return Vec::new(); return Vec::new();
} }
debug!("looking for fields named {} for {:?}", item_name, did); debug!("looking for fields named {item_name} for {did:?}");
// FIXME: this doesn't really belong in `associated_item` (maybe `variant_field` is better?) // FIXME: this doesn't really belong in `associated_item` (maybe `variant_field` is better?)
// NOTE: it's different from variant_field because it only resolves struct fields, // NOTE: it's different from variant_field because it only resolves struct fields,
// not variant fields (2 path segments, not 3). // not variant fields (2 path segments, not 3).
@@ -727,7 +727,7 @@ fn resolve_associated_trait_item<'a>(
// Give precedence to inherent impls. // Give precedence to inherent impls.
let traits = trait_impls_for(cx, ty, module); let traits = trait_impls_for(cx, ty, module);
let tcx = cx.tcx; let tcx = cx.tcx;
debug!("considering traits {:?}", traits); debug!("considering traits {traits:?}");
let candidates = traits let candidates = traits
.iter() .iter()
.flat_map(|&(impl_, trait_)| { .flat_map(|&(impl_, trait_)| {
@@ -744,7 +744,7 @@ fn resolve_associated_trait_item<'a>(
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
// FIXME(#74563): warn about ambiguity // FIXME(#74563): warn about ambiguity
debug!("the candidates were {:?}", candidates); debug!("the candidates were {candidates:?}");
candidates candidates
} }
@@ -790,10 +790,8 @@ fn trait_impls_for<'a>(
// Check if these are the same type. // Check if these are the same type.
let impl_type = trait_ref.skip_binder().self_ty(); let impl_type = trait_ref.skip_binder().self_ty();
trace!( trace!(
"comparing type {} with kind {:?} against type {:?}", "comparing type {impl_type} with kind {:?} against type {ty:?}",
impl_type,
impl_type.kind(), impl_type.kind(),
ty
); );
// Fast path: if this is a primitive simple `==` will work // Fast path: if this is a primitive simple `==` will work
// NOTE: the `match` is necessary; see #92662. // NOTE: the `match` is necessary; see #92662.
@@ -940,7 +938,7 @@ fn preprocess_link(
let path_str = match strip_generics_from_path(path_str) { let path_str = match strip_generics_from_path(path_str) {
Ok(path) => path, Ok(path) => path,
Err(err) => { Err(err) => {
debug!("link has malformed generics: {}", path_str); debug!("link has malformed generics: {path_str}");
return Some(Err(PreprocessingError::MalformedGenerics(err, path_str.to_owned()))); return Some(Err(PreprocessingError::MalformedGenerics(err, path_str.to_owned())));
} }
}; };
@@ -987,7 +985,7 @@ impl LinkCollector<'_, '_> {
if !may_have_doc_links(&doc) { if !may_have_doc_links(&doc) {
continue; continue;
} }
debug!("combined_docs={}", doc); debug!("combined_docs={doc}");
// NOTE: if there are links that start in one crate and end in another, this will not resolve them. // NOTE: if there are links that start in one crate and end in another, this will not resolve them.
// This is a degenerate case and it's not supported by rustdoc. // This is a degenerate case and it's not supported by rustdoc.
let item_id = item_id.unwrap_or_else(|| item.item_id.expect_def_id()); let item_id = item_id.unwrap_or_else(|| item.item_id.expect_def_id());
@@ -1130,10 +1128,10 @@ impl LinkCollector<'_, '_> {
item: &Item, item: &Item,
diag_info: &DiagnosticInfo<'_>, diag_info: &DiagnosticInfo<'_>,
) -> Option<()> { ) -> Option<()> {
debug!("intra-doc link to {} resolved to {:?}", path_str, (kind, id)); debug!("intra-doc link to {path_str} resolved to {:?}", (kind, id));
// Disallow e.g. linking to enums with `struct@` // Disallow e.g. linking to enums with `struct@`
debug!("saw kind {:?} with disambiguator {:?}", kind, disambiguator); debug!("saw kind {kind:?} with disambiguator {disambiguator:?}");
match (kind, disambiguator) { match (kind, disambiguator) {
| (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const))) | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
// NOTE: this allows 'method' to mean both normal functions and associated functions // NOTE: this allows 'method' to mean both normal functions and associated functions
@@ -1174,7 +1172,7 @@ impl LinkCollector<'_, '_> {
diag_info: &DiagnosticInfo<'_>, diag_info: &DiagnosticInfo<'_>,
) { ) {
// The resolved item did not match the disambiguator; give a better error than 'not found' // The resolved item did not match the disambiguator; give a better error than 'not found'
let msg = format!("incompatible link kind for `{}`", path_str); let msg = format!("incompatible link kind for `{path_str}`");
let callback = |diag: &mut Diagnostic, sp: Option<rustc_span::Span>, link_range| { let callback = |diag: &mut Diagnostic, sp: Option<rustc_span::Span>, link_range| {
let note = format!( let note = format!(
"this link resolved to {} {}, which is not {} {}", "this link resolved to {} {}, which is not {} {}",
@@ -1459,7 +1457,7 @@ impl Disambiguator {
"value" => NS(Namespace::ValueNS), "value" => NS(Namespace::ValueNS),
"macro" => NS(Namespace::MacroNS), "macro" => NS(Namespace::MacroNS),
"prim" | "primitive" => Primitive, "prim" | "primitive" => Primitive,
_ => return Err((format!("unknown disambiguator `{}`", prefix), 0..idx)), _ => return Err((format!("unknown disambiguator `{prefix}`"), 0..idx)),
}; };
Ok(Some((d, &rest[1..], &rest[1..]))) Ok(Some((d, &rest[1..], &rest[1..])))
} else { } else {
@@ -1527,7 +1525,7 @@ enum Suggestion {
impl Suggestion { impl Suggestion {
fn descr(&self) -> Cow<'static, str> { fn descr(&self) -> Cow<'static, str> {
match self { match self {
Self::Prefix(x) => format!("prefix with `{}@`", x).into(), Self::Prefix(x) => format!("prefix with `{x}@`").into(),
Self::Function => "add parentheses".into(), Self::Function => "add parentheses".into(),
Self::Macro => "add an exclamation mark".into(), Self::Macro => "add an exclamation mark".into(),
Self::RemoveDisambiguator => "remove the disambiguator".into(), Self::RemoveDisambiguator => "remove the disambiguator".into(),
@@ -1537,9 +1535,9 @@ impl Suggestion {
fn as_help(&self, path_str: &str) -> String { fn as_help(&self, path_str: &str) -> String {
// FIXME: if this is an implied shortcut link, it's bad style to suggest `@` // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
match self { match self {
Self::Prefix(prefix) => format!("{}@{}", prefix, path_str), Self::Prefix(prefix) => format!("{prefix}@{path_str}"),
Self::Function => format!("{}()", path_str), Self::Function => format!("{path_str}()"),
Self::Macro => format!("{}!", path_str), Self::Macro => format!("{path_str}!"),
Self::RemoveDisambiguator => path_str.into(), Self::RemoveDisambiguator => path_str.into(),
} }
} }
@@ -1574,7 +1572,7 @@ impl Suggestion {
match self { match self {
Self::Prefix(prefix) => { Self::Prefix(prefix) => {
// FIXME: if this is an implied shortcut link, it's bad style to suggest `@` // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
let mut sugg = vec![(sp.with_hi(inner_sp.lo()), format!("{}@", prefix))]; let mut sugg = vec![(sp.with_hi(inner_sp.lo()), format!("{prefix}@"))];
if sp.hi() != inner_sp.hi() { if sp.hi() != inner_sp.hi() {
sugg.push((inner_sp.shrink_to_hi().with_hi(sp.hi()), String::new())); sugg.push((inner_sp.shrink_to_hi().with_hi(sp.hi()), String::new()));
} }
@@ -1618,7 +1616,7 @@ fn report_diagnostic(
) { ) {
let Some(hir_id) = DocContext::as_local_hir_id(tcx, item.item_id) else { let Some(hir_id) = DocContext::as_local_hir_id(tcx, item.item_id) else {
// If non-local, no need to check anything. // If non-local, no need to check anything.
info!("ignoring warning from parent crate: {}", msg); info!("ignoring warning from parent crate: {msg}");
return; return;
}; };
@@ -1696,15 +1694,14 @@ fn resolution_failure(
report_diagnostic( report_diagnostic(
tcx, tcx,
BROKEN_INTRA_DOC_LINKS, BROKEN_INTRA_DOC_LINKS,
format!("unresolved link to `{}`", path_str), format!("unresolved link to `{path_str}`"),
&diag_info, &diag_info,
|diag, sp, link_range| { |diag, sp, link_range| {
let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx),); let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx));
let assoc_item_not_allowed = |res: Res| { let assoc_item_not_allowed = |res: Res| {
let name = res.name(tcx); let name = res.name(tcx);
format!( format!(
"`{}` is {} {}, not a module or type, and cannot have associated items", "`{name}` is {} {}, not a module or type, and cannot have associated items",
name,
res.article(), res.article(),
res.descr() res.descr()
) )
@@ -1750,7 +1747,7 @@ fn resolution_failure(
name = start; name = start;
for ns in [TypeNS, ValueNS, MacroNS] { for ns in [TypeNS, ValueNS, MacroNS] {
if let Ok(v_res) = collector.resolve(start, ns, item_id, module_id) { if let Ok(v_res) = collector.resolve(start, ns, item_id, module_id) {
debug!("found partial_res={:?}", v_res); debug!("found partial_res={v_res:?}");
if !v_res.is_empty() { if !v_res.is_empty() {
*partial_res = Some(full_res(tcx, v_res[0])); *partial_res = Some(full_res(tcx, v_res[0]));
*unresolved = end.into(); *unresolved = end.into();
@@ -1771,10 +1768,10 @@ fn resolution_failure(
let note = if partial_res.is_some() { let note = if partial_res.is_some() {
// Part of the link resolved; e.g. `std::io::nonexistent` // Part of the link resolved; e.g. `std::io::nonexistent`
let module_name = tcx.item_name(module); let module_name = tcx.item_name(module);
format!("no item named `{}` in module `{}`", unresolved, module_name) format!("no item named `{unresolved}` in module `{module_name}`")
} else { } else {
// None of the link resolved; e.g. `Notimported` // None of the link resolved; e.g. `Notimported`
format!("no item named `{}` in scope", unresolved) format!("no item named `{unresolved}` in scope")
}; };
if let Some(span) = sp { if let Some(span) = sp {
diag.span_label(span, note); diag.span_label(span, note);
@@ -1879,11 +1876,9 @@ fn resolution_failure(
}; };
let name = res.name(tcx); let name = res.name(tcx);
let note = format!( let note = format!(
"the {} `{}` has no {} named `{}`", "the {} `{name}` has no {} named `{unresolved}`",
res.descr(), res.descr(),
name,
disambiguator.map_or(path_description, |d| d.descr()), disambiguator.map_or(path_description, |d| d.descr()),
unresolved,
); );
if let Some(span) = sp { if let Some(span) = sp {
diag.span_label(span, note); diag.span_label(span, note);
@@ -1978,7 +1973,7 @@ fn report_malformed_generics(
report_diagnostic( report_diagnostic(
cx.tcx, cx.tcx,
BROKEN_INTRA_DOC_LINKS, BROKEN_INTRA_DOC_LINKS,
format!("unresolved link to `{}`", path_str), format!("unresolved link to `{path_str}`"),
&diag_info, &diag_info,
|diag, sp, _link_range| { |diag, sp, _link_range| {
let note = match err { let note = match err {
@@ -2030,7 +2025,7 @@ fn ambiguity_error(
return false; return false;
} }
let mut msg = format!("`{}` is ", path_str); let mut msg = format!("`{path_str}` is ");
match kinds.as_slice() { match kinds.as_slice() {
[res1, res2] => { [res1, res2] => {
msg += &format!( msg += &format!(
@@ -2094,7 +2089,7 @@ fn suggest_disambiguator(
diag.span_suggestion_verbose(sp, help, suggestion_text, Applicability::MaybeIncorrect); diag.span_suggestion_verbose(sp, help, suggestion_text, Applicability::MaybeIncorrect);
} }
} else { } else {
diag.help(format!("{}: {}", help, suggestion.as_help(path_str))); diag.help(format!("{help}: {}", suggestion.as_help(path_str)));
} }
} }
@@ -2108,8 +2103,7 @@ fn privacy_error(cx: &DocContext<'_>, diag_info: &DiagnosticInfo<'_>, path_str:
} }
None => "<unknown>", None => "<unknown>",
}; };
let msg = let msg = format!("public documentation for `{item_name}` links to private item `{path_str}`");
format!("public documentation for `{}` links to private item `{}`", item_name, path_str);
report_diagnostic(cx.tcx, PRIVATE_INTRA_DOC_LINKS, msg, diag_info, |diag, sp, _link_range| { report_diagnostic(cx.tcx, PRIVATE_INTRA_DOC_LINKS, msg, diag_info, |diag, sp, _link_range| {
if let Some(sp) = sp { if let Some(sp) = sp {
@@ -2160,6 +2154,6 @@ fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
"never" | "!" => Never, "never" | "!" => Never,
_ => return None, _ => return None,
}; };
debug!("resolved primitives {:?}", prim); debug!("resolved primitives {prim:?}");
Some(Res::Primitive(prim)) Some(Res::Primitive(prim))
} }

View File

@@ -28,7 +28,7 @@ pub(super) fn visit_item(cx: &DocContext<'_>, item: &Item) {
.span_suggestion( .span_suggestion(
sp, sp,
"use an automatic link instead", "use an automatic link instead",
format!("<{}>", url), format!("<{url}>"),
Applicability::MachineApplicable, Applicability::MachineApplicable,
) )
}); });
@@ -74,7 +74,7 @@ fn find_raw_urls(
range: Range<usize>, range: Range<usize>,
f: &impl Fn(&DocContext<'_>, &'static str, &str, Range<usize>), f: &impl Fn(&DocContext<'_>, &'static str, &str, Range<usize>),
) { ) {
trace!("looking for raw urls in {}", text); trace!("looking for raw urls in {text}");
// For now, we only check "full" URLs (meaning, starting with "http://" or "https://"). // For now, we only check "full" URLs (meaning, starting with "http://" or "https://").
for match_ in URL_REGEX.find_iter(text) { for match_ in URL_REGEX.find_iter(text) {
let url = match_.as_str(); let url = match_.as_str();

View File

@@ -107,7 +107,7 @@ fn check_rust_syntax(
// just give a `help` instead. // just give a `help` instead.
lint.span_help( lint.span_help(
sp.from_inner(InnerSpan::new(0, 3)), sp.from_inner(InnerSpan::new(0, 3)),
format!("{}: ```text", explanation), format!("{explanation}: ```text"),
); );
} else if empty_block { } else if empty_block {
lint.span_suggestion( lint.span_suggestion(
@@ -118,7 +118,7 @@ fn check_rust_syntax(
); );
} }
} else if empty_block || is_ignore { } else if empty_block || is_ignore {
lint.help(format!("{}: ```text", explanation)); lint.help(format!("{explanation}: ```text"));
} }
// FIXME(#67563): Provide more context for these errors by displaying the spans inline. // FIXME(#67563): Provide more context for these errors by displaying the spans inline.
@@ -160,7 +160,7 @@ impl Emitter for BufferEmitter {
.translate_message(&diag.message[0].0, &fluent_args) .translate_message(&diag.message[0].0, &fluent_args)
.unwrap_or_else(|e| panic!("{e}")); .unwrap_or_else(|e| panic!("{e}"));
buffer.messages.push(format!("error from rustc: {}", translated_main_message)); buffer.messages.push(format!("error from rustc: {translated_main_message}"));
if diag.is_error() { if diag.is_error() {
buffer.has_errors = true; buffer.has_errors = true;
} }

View File

@@ -155,7 +155,7 @@ pub(crate) fn visit_item(cx: &DocContext<'_>, item: &Item) {
let t = t.to_lowercase(); let t = t.to_lowercase();
!ALLOWED_UNCLOSED.contains(&t.as_str()) !ALLOWED_UNCLOSED.contains(&t.as_str())
}) { }) {
report_diag(format!("unclosed HTML tag `{}`", tag), range, true); report_diag(format!("unclosed HTML tag `{tag}`"), range, true);
} }
if let Some(range) = is_in_comment { if let Some(range) = is_in_comment {
@@ -194,14 +194,14 @@ fn drop_tag(
// `tags` is used as a queue, meaning that everything after `pos` is included inside it. // `tags` is used as a queue, meaning that everything after `pos` is included inside it.
// So `<h2><h3></h2>` will look like `["h2", "h3"]`. So when closing `h2`, we will still // So `<h2><h3></h2>` will look like `["h2", "h3"]`. So when closing `h2`, we will still
// have `h3`, meaning the tag wasn't closed as it should have. // have `h3`, meaning the tag wasn't closed as it should have.
f(format!("unclosed HTML tag `{}`", last_tag_name), &last_tag_span, true); f(format!("unclosed HTML tag `{last_tag_name}`"), &last_tag_span, true);
} }
// Remove the `tag_name` that was originally closed // Remove the `tag_name` that was originally closed
tags.pop(); tags.pop();
} else { } else {
// It can happen for example in this case: `<h2></script></h2>` (the `h2` tag isn't required // It can happen for example in this case: `<h2></script></h2>` (the `h2` tag isn't required
// but it helps for the visualization). // but it helps for the visualization).
f(format!("unopened HTML tag `{}`", tag_name), &range, false); f(format!("unopened HTML tag `{tag_name}`"), &range, false);
} }
} }
@@ -355,7 +355,7 @@ fn extract_html_tag(
if let Some(quote_pos) = quote_pos { if let Some(quote_pos) = quote_pos {
let qr = Range { start: quote_pos, end: quote_pos }; let qr = Range { start: quote_pos, end: quote_pos };
f( f(
format!("unclosed quoted HTML attribute on tag `{}`", tag_name), format!("unclosed quoted HTML attribute on tag `{tag_name}`"),
&qr, &qr,
false, false,
); );
@@ -368,7 +368,7 @@ fn extract_html_tag(
at == "svg" || at == "math" at == "svg" || at == "math"
}); });
if !valid { if !valid {
f(format!("invalid self-closing HTML tag `{}`", tag_name), &r, false); f(format!("invalid self-closing HTML tag `{tag_name}`"), &r, false);
} }
} else { } else {
tags.push((tag_name, r)); tags.push((tag_name, r));

View File

@@ -255,7 +255,7 @@ where
let fn_key = tcx.def_path_hash(*def_id); let fn_key = tcx.def_path_hash(*def_id);
let fn_entries = self.calls.entry(fn_key).or_default(); let fn_entries = self.calls.entry(fn_key).or_default();
trace!("Including expr: {:?}", call_span); trace!("Including expr: {call_span:?}");
let enclosing_item_span = let enclosing_item_span =
source_map.span_extend_to_prev_char(enclosing_item_span, '\n', false); source_map.span_extend_to_prev_char(enclosing_item_span, '\n', false);
let location = let location =
@@ -345,7 +345,7 @@ pub(crate) fn load_call_locations(
let inner = || { let inner = || {
let mut all_calls: AllCallLocations = FxHashMap::default(); let mut all_calls: AllCallLocations = FxHashMap::default();
for path in with_examples { for path in with_examples {
let bytes = fs::read(&path).map_err(|e| format!("{} (for path {})", e, path))?; let bytes = fs::read(&path).map_err(|e| format!("{e} (for path {path})"))?;
let mut decoder = MemDecoder::new(&bytes, 0); let mut decoder = MemDecoder::new(&bytes, 0);
let calls = AllCallLocations::decode(&mut decoder); let calls = AllCallLocations::decode(&mut decoder);
@@ -358,7 +358,7 @@ pub(crate) fn load_call_locations(
}; };
inner().map_err(|e: String| { inner().map_err(|e: String| {
diag.err(format!("failed to load examples: {}", e)); diag.err(format!("failed to load examples: {e}"));
1 1
}) })
} }

View File

@@ -180,7 +180,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
/// 1. The items which are not glob imports/reexports. /// 1. The items which are not glob imports/reexports.
/// 2. The glob imports/reexports. /// 2. The glob imports/reexports.
fn visit_mod_contents(&mut self, def_id: LocalDefId, m: &'tcx hir::Mod<'tcx>) { fn visit_mod_contents(&mut self, def_id: LocalDefId, m: &'tcx hir::Mod<'tcx>) {
debug!("Going through module {:?}", m); debug!("Going through module {m:?}");
// Keep track of if there were any private modules in the path. // Keep track of if there were any private modules in the path.
let orig_inside_public_path = self.inside_public_path; let orig_inside_public_path = self.inside_public_path;
self.inside_public_path &= self.cx.tcx.local_visibility(def_id).is_public(); self.inside_public_path &= self.cx.tcx.local_visibility(def_id).is_public();
@@ -203,7 +203,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
} }
} }
self.inside_public_path = orig_inside_public_path; self.inside_public_path = orig_inside_public_path;
debug!("Leaving module {:?}", m); debug!("Leaving module {m:?}");
} }
/// Tries to resolve the target of a `pub use` statement and inlines the /// Tries to resolve the target of a `pub use` statement and inlines the
@@ -394,7 +394,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
renamed: Option<Symbol>, renamed: Option<Symbol>,
import_id: Option<LocalDefId>, import_id: Option<LocalDefId>,
) { ) {
debug!("visiting item {:?}", item); debug!("visiting item {item:?}");
if self.inside_body { if self.inside_body {
// Only impls can be "seen" outside a body. For example: // Only impls can be "seen" outside a body. For example:
// //