docsrs_cli/docs_rs/assoc.rs
1//! Rustdoc associated-item anchor families.
2//!
3//! Rustdoc does not have "the method anchor". It emits **one id prefix per
4//! member category**, and every category coexists inside the parent page:
5//!
6//! | Category | Anchor id prefix | Parent page |
7//! |--------------------------|------------------------|----------------------|
8//! | inherent / default method| `method.` | struct, enum, trait… |
9//! | required trait method | `tymethod.` | trait |
10//! | associated type | `associatedtype.` | trait |
11//! | associated constant | `associatedconstant.` | struct, trait |
12//! | enum variant | `variant.` | enum |
13//! | struct / union field | `structfield.` | struct, union |
14//!
15//! Measured on `std::iter::Iterator`: 198 `associatedtype.` ids, 75 `method.`
16//! ids and 1 `tymethod.` id on a single page.
17//!
18//! Modelling this as "two spellings of method" is what let `Iterator::Item` and
19//! `Duration::MAX` build impossible URLs (`std/iter/Iterator/type.Item.html`)
20//! long after required trait methods were fixed. The axis is the **category**,
21//! so this module owns the whole family in one place: prefixes, parent-page
22//! probe order, and the detection rule that decides whether a path is an
23//! associated item at all.
24//!
25//! Pure data and pure functions — no HTTP, no HTML parse (one-shot safe).
26
27use crate::item_kind::ItemKind;
28
29/// Anchor id prefixes for an associated function, in probe order.
30///
31/// Both can coexist on one trait page, so probe order — never document order —
32/// decides the winner. The split is upstream behaviour: rustc keeps
33/// `tests/rustdoc-html/anchors/anchor-id-trait-tymethod-28478.rs` as a guard.
34pub const METHOD_ANCHOR_PREFIXES: &[&str] = &["method.", "tymethod."];
35
36/// Anchor id prefix for an associated type (`type Item;` inside a trait).
37const TYPE_ANCHOR_PREFIXES: &[&str] = &["associatedtype."];
38
39/// Anchor id prefix for an associated constant (`const MAX: Self;`).
40const CONSTANT_ANCHOR_PREFIXES: &[&str] = &["associatedconstant."];
41
42/// Anchor id prefix for an enum variant (`Option::Some`).
43const VARIANT_ANCHOR_PREFIXES: &[&str] = &["variant."];
44
45/// Anchor id prefix for a struct or union field (`Range::start`).
46const STRUCT_FIELD_ANCHOR_PREFIXES: &[&str] = &["structfield."];
47
48/// Sentinel prefix of the "anchor absent on the parent page" error message.
49///
50/// The live probe in [`crate::docs_rs`] and the recovery path in
51/// `crate::ops` both match on it to stop walking parent kinds once the parent
52/// page was found but the member was not. It is a contract between those call
53/// sites, so it lives here instead of being retyped as a literal at each one.
54pub const ASSOC_ANCHOR_MISS_PREFIX: &str = "associated item anchor ";
55
56/// Parent kinds probed for an associated function (struct first — common case).
57const METHOD_PARENT_KINDS: &[ItemKind] = &[
58 ItemKind::Struct,
59 ItemKind::Enum,
60 ItemKind::Trait,
61 ItemKind::Type,
62 ItemKind::Union,
63];
64
65/// Parent kinds probed for an associated type (trait first — they live there).
66const TYPE_PARENT_KINDS: &[ItemKind] = &[
67 ItemKind::Trait,
68 ItemKind::Struct,
69 ItemKind::Enum,
70 ItemKind::Union,
71 ItemKind::Type,
72];
73
74/// Parent kinds probed for an associated constant (struct first: `Duration::MAX`).
75const CONSTANT_PARENT_KINDS: &[ItemKind] = &[
76 ItemKind::Struct,
77 ItemKind::Trait,
78 ItemKind::Enum,
79 ItemKind::Union,
80 ItemKind::Type,
81];
82
83/// Parent kinds probed for an enum variant.
84///
85/// Exactly one entry: only an `enum` has variants, so probing anything else
86/// would spend a rate-limited GET on a page that cannot host the anchor.
87const VARIANT_PARENT_KINDS: &[ItemKind] = &[ItemKind::Enum];
88
89/// Parent kinds probed for a field: structs first, then unions.
90///
91/// Rustdoc uses the same `structfield.` prefix for both, so the family is one
92/// axis with two possible hosts.
93const STRUCT_FIELD_PARENT_KINDS: &[ItemKind] = &[ItemKind::Struct, ItemKind::Union];
94
95/// Which rustdoc anchor family a `Parent::member` path resolves through.
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub enum AssocAnchorKind {
98 /// Inherent method, defaulted trait method, or required trait method.
99 Method,
100 /// Associated type declared inside a trait.
101 Type,
102 /// Associated constant declared on a type or trait.
103 Constant,
104 /// Enum variant (`Option::Some`).
105 Variant,
106 /// Struct or union field (`Range::start`).
107 StructField,
108}
109
110impl AssocAnchorKind {
111 /// Anchor id prefixes to try, in probe order.
112 pub fn anchor_prefixes(self) -> &'static [&'static str] {
113 match self {
114 Self::Method => METHOD_ANCHOR_PREFIXES,
115 Self::Type => TYPE_ANCHOR_PREFIXES,
116 Self::Constant => CONSTANT_ANCHOR_PREFIXES,
117 Self::Variant => VARIANT_ANCHOR_PREFIXES,
118 Self::StructField => STRUCT_FIELD_ANCHOR_PREFIXES,
119 }
120 }
121
122 /// Prefix the URL builder bakes into the planned fragment.
123 ///
124 /// Only one fragment fits in a URL; the extractor still tries every prefix
125 /// of the family against the fetched page.
126 pub fn primary_prefix(self) -> &'static str {
127 // Every family declares at least one prefix, so index 0 always exists.
128 self.anchor_prefixes()[0]
129 }
130
131 /// Parent page kinds to probe, in order.
132 ///
133 /// Single source of truth: the live probe in [`crate::docs_rs`] and the
134 /// suggestion probe in `crate::ops` must walk the same kinds in the same
135 /// order, or a member found by one stays invisible to the other.
136 pub fn parent_kind_probe(self) -> &'static [ItemKind] {
137 match self {
138 Self::Method => METHOD_PARENT_KINDS,
139 Self::Type => TYPE_PARENT_KINDS,
140 Self::Constant => CONSTANT_PARENT_KINDS,
141 Self::Variant => VARIANT_PARENT_KINDS,
142 Self::StructField => STRUCT_FIELD_PARENT_KINDS,
143 }
144 }
145
146 /// [`Self::parent_kind_probe`] as wire strings for the `--dry-run` envelope.
147 ///
148 /// Derived from the kind list rather than mirrored by hand. Hand-kept string
149 /// mirrors used to sit right below the "single source of truth" promise
150 /// above, and they made `--dry-run` capable of *lying*: reordering the kinds
151 /// without reordering the strings would have published a probe order the
152 /// live fetch never walks, to an agent that plans on exactly that field.
153 pub fn parent_kind_probe_names(self) -> impl Iterator<Item = &'static str> + Clone {
154 self.parent_kind_probe().iter().map(|k| k.as_str())
155 }
156
157 /// Build the ordered anchor ids a live fetch will try for `name`.
158 pub fn anchor_ids(self, name: &str) -> Vec<String> {
159 self.anchor_prefixes()
160 .iter()
161 .map(|prefix| format!("{prefix}{name}"))
162 .collect()
163 }
164}
165
166/// Detect a parent-qualified associated item: `Parent::member`.
167///
168/// `segs` must already have the crate-root prefix stripped (see
169/// [`super::strip_crate_prefix_segments`]).
170///
171/// Exactly **one** predicate decides this: the parent segment starts with an
172/// ASCII uppercase letter. An uppercase module would fire rustc's
173/// `non_snake_case` lint, so an uppercase parent *is* a type — never a module —
174/// and the path therefore can never be a free item. That single rule keeps
175/// `u32::MAX` and `f32::EPSILON` on the legacy free-constant page
176/// (`std/u32/constant.MAX.html`) the standard library still serves, while
177/// routing `Duration::MAX` to `struct.Duration.html#associatedconstant.MAX`.
178///
179/// The leaf's letter case is **not** consulted. It looks like a second
180/// discriminator, but it adds no discriminating power once the parent is known
181/// to be a type — it only narrows the domain, and rebuilds the original defect
182/// inside the range it excludes. With a leaf-case guard, `Iterator::item` fell
183/// through to the free-item branch and built `std/iter/Iterator/type.item.html`,
184/// a path no rustdoc ever emitted, with no suggestions. Without it, the same
185/// typo reaches the parent page and fails with the real member names.
186///
187/// Returns `None` for every other shape, so the caller falls back to the free
188/// item page (`{kind}.{name}.html`).
189pub fn associated_item_path(kind: ItemKind, segs: &[String]) -> Option<AssocAnchorKind> {
190 let [.., parent, leaf] = segs else {
191 return None;
192 };
193 if !parent
194 .chars()
195 .next()
196 .is_some_and(|c| c.is_ascii_uppercase())
197 {
198 return None;
199 }
200 // An empty leaf (`Parent::`) would build an anchor with no member name.
201 if leaf.is_empty() {
202 return None;
203 }
204 match kind {
205 ItemKind::Fn => Some(AssocAnchorKind::Method),
206 ItemKind::Type => Some(AssocAnchorKind::Type),
207 ItemKind::Constant => Some(AssocAnchorKind::Constant),
208 ItemKind::Variant => Some(AssocAnchorKind::Variant),
209 ItemKind::StructField => Some(AssocAnchorKind::StructField),
210 // Kinds that own a page of their own are never members of a parent.
211 _ => None,
212 }
213}
214
215/// Anchor family a kind resolves through *regardless* of path shape.
216///
217/// Returns `Some` only for kinds that rustdoc never gives a page of their own,
218/// so a caller can reject `variant Some` (no parent) with the real reason
219/// instead of letting it fall through and build `variant.Some.html`.
220pub fn member_only_family(kind: ItemKind) -> Option<AssocAnchorKind> {
221 match kind {
222 ItemKind::Variant => Some(AssocAnchorKind::Variant),
223 ItemKind::StructField => Some(AssocAnchorKind::StructField),
224 _ => None,
225 }
226}
227
228/// Recover the anchor family and bare member name from a planned URL fragment.
229///
230/// A fragment names its own family without ambiguity, so the fetch path reads
231/// the family off the URL it already holds instead of threading an extra
232/// parameter through every layer.
233pub fn assoc_from_fragment(fragment: &str) -> Option<(AssocAnchorKind, &str)> {
234 const FAMILIES: &[AssocAnchorKind] = &[
235 AssocAnchorKind::Method,
236 AssocAnchorKind::Type,
237 AssocAnchorKind::Constant,
238 AssocAnchorKind::Variant,
239 AssocAnchorKind::StructField,
240 ];
241 FAMILIES.iter().find_map(|family| {
242 family
243 .anchor_prefixes()
244 .iter()
245 .find_map(|prefix| fragment.strip_prefix(prefix))
246 .filter(|name| !name.is_empty())
247 .map(|name| (*family, name))
248 })
249}
250
251/// Strip any prefix of `prefixes` from a rustdoc anchor id.
252///
253/// Returns the bare member name, or `None` when the id names something outside
254/// the family (`variant.Some`, a section heading, …).
255pub fn strip_assoc_anchor_prefix<'a>(id: &'a str, prefixes: &[&str]) -> Option<&'a str> {
256 prefixes
257 .iter()
258 .find_map(|prefix| id.strip_prefix(prefix))
259 .filter(|name| !name.is_empty())
260}