Skip to content

Commit 110471b

Browse files
Rollup merge of #149028 - GuillaumeGomez:unify-anchor, r=lolbinarycat
[rustdoc] Remove `UrlFragment::render` method to unify `clean::types::links` and `anchor` Fixes #148648. First part of #148547. The last part will be about handle `AssocItemLink` differently (either remove it or change how we do it). r? `@lolbinarycat`
2 parents 8d66eb5 + 8f76773 commit 110471b

File tree

6 files changed

+55
-74
lines changed

6 files changed

+55
-74
lines changed

src/librustdoc/clean/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,7 @@ pub(crate) fn clean_trait_ref_with_constraints<'tcx>(
249249
trait_ref: ty::PolyTraitRef<'tcx>,
250250
constraints: ThinVec<AssocItemConstraint>,
251251
) -> Path {
252-
let kind = cx.tcx.def_kind(trait_ref.def_id()).into();
252+
let kind = ItemType::from_def_id(trait_ref.def_id(), cx.tcx);
253253
if !matches!(kind, ItemType::Trait | ItemType::TraitAlias) {
254254
span_bug!(cx.tcx.def_span(trait_ref.def_id()), "`TraitRef` had unexpected kind {kind:?}");
255255
}

src/librustdoc/clean/types.rs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use std::fmt::Write;
12
use std::hash::Hash;
23
use std::path::PathBuf;
34
use std::sync::{Arc, OnceLock as OnceCell};
@@ -522,8 +523,16 @@ impl Item {
522523
debug!(?id);
523524
if let Ok(HrefInfo { mut url, .. }) = href(*id, cx) {
524525
debug!(?url);
525-
if let Some(ref fragment) = *fragment {
526-
fragment.render(&mut url, cx.tcx())
526+
match fragment {
527+
Some(UrlFragment::Item(def_id)) => {
528+
write!(url, "{}", crate::html::format::fragment(*def_id, cx.tcx()))
529+
.unwrap();
530+
}
531+
Some(UrlFragment::UserWritten(raw)) => {
532+
url.push('#');
533+
url.push_str(raw);
534+
}
535+
None => {}
527536
}
528537
Some(RenderedLink {
529538
original_text: s.clone(),

src/librustdoc/clean/utils.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ use crate::clean::{
2626
};
2727
use crate::core::DocContext;
2828
use crate::display::Joined as _;
29+
use crate::formats::item_type::ItemType;
2930

3031
#[cfg(test)]
3132
mod tests;
@@ -496,7 +497,7 @@ pub(crate) fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId {
496497

497498
let (kind, did) = match res {
498499
Res::Def(
499-
kind @ (AssocTy
500+
AssocTy
500501
| AssocFn
501502
| AssocConst
502503
| Variant
@@ -511,9 +512,9 @@ pub(crate) fn register_res(cx: &mut DocContext<'_>, res: Res) -> DefId {
511512
| Const
512513
| Static { .. }
513514
| Macro(..)
514-
| TraitAlias),
515+
| TraitAlias,
515516
did,
516-
) => (kind.into(), did),
517+
) => (ItemType::from_def_id(did, cx.tcx), did),
517518

518519
_ => panic!("register_res: unexpected {res:?}"),
519520
};

src/librustdoc/formats/item_type.rs

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
use std::fmt;
44

55
use rustc_hir::def::{CtorOf, DefKind, MacroKinds};
6+
use rustc_hir::def_id::DefId;
7+
use rustc_middle::ty::TyCtxt;
68
use rustc_span::hygiene::MacroKind;
79
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
810

@@ -147,17 +149,10 @@ impl<'a> From<&'a clean::Item> for ItemType {
147149
}
148150
}
149151

150-
impl From<DefKind> for ItemType {
151-
fn from(other: DefKind) -> Self {
152-
Self::from_def_kind(other, None)
153-
}
154-
}
155-
156152
impl ItemType {
157-
/// Depending on the parent kind, some variants have a different translation (like a `Method`
158-
/// becoming a `TyMethod`).
159-
pub(crate) fn from_def_kind(kind: DefKind, parent_kind: Option<DefKind>) -> Self {
160-
match kind {
153+
pub(crate) fn from_def_id(def_id: DefId, tcx: TyCtxt<'_>) -> Self {
154+
let def_kind = tcx.def_kind(def_id);
155+
match def_kind {
161156
DefKind::Enum => Self::Enum,
162157
DefKind::Fn => Self::Function,
163158
DefKind::Mod => Self::Module,
@@ -176,8 +171,13 @@ impl ItemType {
176171
DefKind::Variant => Self::Variant,
177172
DefKind::Field => Self::StructField,
178173
DefKind::AssocTy => Self::AssocType,
179-
DefKind::AssocFn if let Some(DefKind::Trait) = parent_kind => Self::TyMethod,
180-
DefKind::AssocFn => Self::Method,
174+
DefKind::AssocFn => {
175+
if tcx.associated_item(def_id).defaultness(tcx).has_value() {
176+
Self::Method
177+
} else {
178+
Self::TyMethod
179+
}
180+
}
181181
DefKind::Ctor(CtorOf::Struct, _) => Self::Struct,
182182
DefKind::Ctor(CtorOf::Variant, _) => Self::Variant,
183183
DefKind::AssocConst => Self::AssocConst,

src/librustdoc/html/format.rs

Lines changed: 27 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -431,7 +431,6 @@ fn generate_item_def_id_path(
431431
original_def_id: DefId,
432432
cx: &Context<'_>,
433433
root_path: Option<&str>,
434-
original_def_kind: DefKind,
435434
) -> Result<HrefInfo, HrefError> {
436435
use rustc_middle::traits::ObligationCause;
437436
use rustc_trait_selection::infer::TyCtxtInferExt;
@@ -457,15 +456,14 @@ fn generate_item_def_id_path(
457456
let relative = clean::inline::item_relative_path(tcx, def_id);
458457
let fqp: Vec<Symbol> = once(crate_name).chain(relative).collect();
459458

460-
let def_kind = tcx.def_kind(def_id);
461-
let shortty = def_kind.into();
459+
let shortty = ItemType::from_def_id(def_id, tcx);
462460
let module_fqp = to_module_fqp(shortty, &fqp);
463461
let mut is_remote = false;
464462

465463
let url_parts = url_parts(cx.cache(), def_id, module_fqp, &cx.current, &mut is_remote)?;
466464
let mut url_parts = make_href(root_path, shortty, url_parts, &fqp, is_remote);
467465
if def_id != original_def_id {
468-
let kind = ItemType::from_def_kind(original_def_kind, Some(def_kind));
466+
let kind = ItemType::from_def_id(original_def_id, tcx);
469467
url_parts = format!("{url_parts}#{kind}.{}", tcx.item_name(original_def_id))
470468
};
471469
Ok(HrefInfo { url: url_parts, kind: shortty, rust_path: fqp })
@@ -605,7 +603,7 @@ pub(crate) fn href_with_root_path(
605603
} else if did.is_local() {
606604
return Err(HrefError::Private);
607605
} else {
608-
return generate_item_def_id_path(did, original_did, cx, root_path, def_kind);
606+
return generate_item_def_id_path(did, original_did, cx, root_path);
609607
}
610608
}
611609
};
@@ -835,26 +833,36 @@ fn print_higher_ranked_params_with_space(
835833
})
836834
}
837835

838-
pub(crate) fn print_anchor(did: DefId, text: Symbol, cx: &Context<'_>) -> impl Display {
836+
pub(crate) fn fragment(did: DefId, tcx: TyCtxt<'_>) -> impl Display {
839837
fmt::from_fn(move |f| {
840-
if let Ok(HrefInfo { url, kind, rust_path }) = href(did, cx) {
841-
let tcx = cx.tcx();
842-
let def_kind = tcx.def_kind(did);
843-
let anchor = if matches!(
844-
def_kind,
845-
DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst | DefKind::Variant
846-
) {
838+
let def_kind = tcx.def_kind(did);
839+
match def_kind {
840+
DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst | DefKind::Variant => {
841+
let item_type = ItemType::from_def_id(did, tcx);
842+
write!(f, "#{}.{}", item_type.as_str(), tcx.item_name(did))
843+
}
844+
DefKind::Field => {
847845
let parent_def_id = tcx.parent(did);
848-
let item_type =
849-
ItemType::from_def_kind(def_kind, Some(tcx.def_kind(parent_def_id)));
850-
format!("#{}.{}", item_type.as_str(), tcx.item_name(did))
851-
} else {
852-
String::new()
853-
};
846+
f.write_char('#')?;
847+
if tcx.def_kind(parent_def_id) == DefKind::Variant {
848+
write!(f, "variant.{}.field", tcx.item_name(parent_def_id).as_str())?;
849+
} else {
850+
f.write_str("structfield")?;
851+
};
852+
write!(f, ".{}", tcx.item_name(did))
853+
}
854+
_ => Ok(()),
855+
}
856+
})
857+
}
854858

859+
pub(crate) fn print_anchor(did: DefId, text: Symbol, cx: &Context<'_>) -> impl Display {
860+
fmt::from_fn(move |f| {
861+
if let Ok(HrefInfo { url, kind, rust_path }) = href(did, cx) {
855862
write!(
856863
f,
857864
r#"<a class="{kind}" href="{url}{anchor}" title="{kind} {path}">{text}</a>"#,
865+
anchor = fragment(did, cx.tcx()),
858866
path = join_path_syms(rust_path),
859867
text = EscapeBodyText(text.as_str()),
860868
)

src/librustdoc/passes/collect_intra_doc_links.rs

Lines changed: 0 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -203,43 +203,6 @@ pub(crate) enum UrlFragment {
203203
UserWritten(String),
204204
}
205205

206-
impl UrlFragment {
207-
/// Render the fragment, including the leading `#`.
208-
pub(crate) fn render(&self, s: &mut String, tcx: TyCtxt<'_>) {
209-
s.push('#');
210-
match self {
211-
&UrlFragment::Item(def_id) => {
212-
let kind = match tcx.def_kind(def_id) {
213-
DefKind::AssocFn => {
214-
if tcx.associated_item(def_id).defaultness(tcx).has_value() {
215-
"method."
216-
} else {
217-
"tymethod."
218-
}
219-
}
220-
DefKind::AssocConst => "associatedconstant.",
221-
DefKind::AssocTy => "associatedtype.",
222-
DefKind::Variant => "variant.",
223-
DefKind::Field => {
224-
let parent_id = tcx.parent(def_id);
225-
if tcx.def_kind(parent_id) == DefKind::Variant {
226-
s.push_str("variant.");
227-
s.push_str(tcx.item_name(parent_id).as_str());
228-
".field."
229-
} else {
230-
"structfield."
231-
}
232-
}
233-
kind => bug!("unexpected associated item kind: {kind:?}"),
234-
};
235-
s.push_str(kind);
236-
s.push_str(tcx.item_name(def_id).as_str());
237-
}
238-
UrlFragment::UserWritten(raw) => s.push_str(raw),
239-
}
240-
}
241-
}
242-
243206
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
244207
pub(crate) struct ResolutionInfo {
245208
item_id: DefId,

0 commit comments

Comments
 (0)