Skip to main content

docsrs_cli/
item_kind.rs

1//! ItemKind normalization for rustdoc URLs and all.html filters.
2
3use crate::error::{AppError, AppResult, ErrorDetail};
4
5/// Canonical rustdoc item kinds used by docs.rs HTML.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
7#[serde(rename_all = "snake_case")]
8pub enum ItemKind {
9    /// Module page.
10    Module,
11    /// Struct page.
12    Struct,
13    /// Trait page.
14    Trait,
15    /// Enum page.
16    Enum,
17    /// Union page.
18    Union,
19    /// Function or method page.
20    Fn,
21    /// Type alias page.
22    Type,
23    /// Constant page.
24    Constant,
25    /// Static page.
26    Static,
27    /// Macro page.
28    Macro,
29    /// Attribute macro page.
30    Attribute,
31    /// Derive macro page.
32    Derive,
33    /// Enum variant — always a member of its enum, never its own page.
34    Variant,
35    /// Struct or union field — always a member of its type, never its own page.
36    StructField,
37}
38
39impl ItemKind {
40    /// Stable JSON / filter string.
41    pub fn as_str(self) -> &'static str {
42        match self {
43            Self::Module => "module",
44            Self::Struct => "struct",
45            Self::Trait => "trait",
46            Self::Enum => "enum",
47            Self::Union => "union",
48            Self::Fn => "fn",
49            Self::Type => "type",
50            Self::Constant => "constant",
51            Self::Static => "static",
52            Self::Macro => "macro",
53            Self::Attribute => "attribute",
54            Self::Derive => "derive",
55            Self::Variant => "variant",
56            Self::StructField => "structfield",
57        }
58    }
59
60    /// Whether rustdoc emits a standalone `{prefix}.{name}.html` page for this kind.
61    ///
62    /// [`Self::Variant`] and [`Self::StructField`] return `false`: rustdoc renders
63    /// them only as anchors inside the parent's page. Asking for one without a
64    /// parent-qualified path must fail with that explanation, because the
65    /// alternative — falling through to the free-item branch — would build
66    /// `variant.Some.html`, a URL no rustdoc has ever served.
67    pub fn owns_page(self) -> bool {
68        !matches!(self, Self::Variant | Self::StructField)
69    }
70
71    /// Filename prefix in rustdoc HTML (e.g. `struct`, `fn`, `attr`, `constant`).
72    ///
73    /// `None` for kinds that own no page ([`Self::owns_page`]); callers building a
74    /// free-item URL must reject those before reaching here.
75    ///
76    /// Modern rustdoc/docs.rs uses `constant.NAME.html` (not legacy `const.NAME.html`).
77    pub fn file_prefix(self) -> Option<&'static str> {
78        Some(match self {
79            Self::Module => "module",
80            Self::Struct => "struct",
81            Self::Trait => "trait",
82            Self::Enum => "enum",
83            Self::Union => "union",
84            Self::Fn => "fn",
85            Self::Type => "type",
86            Self::Constant => "constant",
87            Self::Static => "static",
88            Self::Macro => "macro",
89            Self::Attribute => "attr",
90            Self::Derive => "derive",
91            Self::Variant | Self::StructField => return None,
92        })
93    }
94
95    /// Parse CLI / filter aliases into canonical kind.
96    ///
97    /// # Errors
98    ///
99    /// Returns [`crate::error::ErrorKind::InvalidInput`] when `input` is not a known kind alias.
100    pub fn parse(input: &str) -> AppResult<Self> {
101        Ok(Self::parse_with_echo(input)?.0)
102    }
103
104    /// Parse kind for URL building plus the wire echo string for `item_type`.
105    ///
106    /// `method` maps to [`ItemKind::Fn`] for rustdoc URLs but echoes as `"method"`.
107    ///
108    /// # Errors
109    ///
110    /// Returns [`crate::error::ErrorKind::InvalidInput`] when `input` is not a known kind alias.
111    pub fn parse_with_echo(input: &str) -> AppResult<(Self, &'static str)> {
112        let s = input.trim().to_ascii_lowercase();
113        match s.as_str() {
114            "module" | "mod" => Ok((Self::Module, "module")),
115            "struct" => Ok((Self::Struct, "struct")),
116            "trait" => Ok((Self::Trait, "trait")),
117            "enum" => Ok((Self::Enum, "enum")),
118            "union" => Ok((Self::Union, "union")),
119            "fn" | "function" => Ok((Self::Fn, "fn")),
120            "method" => Ok((Self::Fn, "method")),
121            "type" => Ok((Self::Type, "type")),
122            "const" | "constant" => Ok((Self::Constant, "constant")),
123            "static" => Ok((Self::Static, "static")),
124            "macro" => Ok((Self::Macro, "macro")),
125            "attr" | "attribute" => Ok((Self::Attribute, "attribute")),
126            "derive" => Ok((Self::Derive, "derive")),
127            "variant" => Ok((Self::Variant, "variant")),
128            // `field` is the word a Rust programmer uses; `structfield` is the
129            // rustdoc anchor spelling. Accept both, echo the canonical one.
130            "structfield" | "field" => Ok((Self::StructField, "structfield")),
131            other => Err(AppError::of(ErrorDetail::UnknownItemType {
132                value: other.to_string(),
133            })),
134        }
135    }
136
137    /// Infer kind from all.html href (e.g. `struct.Name.html`, `attr.foo.html`).
138    ///
139    /// Accepts modern `constant.` and legacy `const.` prefixes for Constant.
140    pub fn from_href(href: &str) -> Option<Self> {
141        let file = href.rsplit('/').next().unwrap_or(href);
142        let file = file.split('#').next().unwrap_or(file);
143        let prefix = file.split('.').next().unwrap_or("");
144        match prefix {
145            "struct" => Some(Self::Struct),
146            "trait" => Some(Self::Trait),
147            "fn" => Some(Self::Fn),
148            "enum" => Some(Self::Enum),
149            "type" => Some(Self::Type),
150            // Modern rustdoc: constant.NAME.html; legacy: const.NAME.html
151            "constant" | "const" => Some(Self::Constant),
152            "static" => Some(Self::Static),
153            "macro" => Some(Self::Macro),
154            "union" => Some(Self::Union),
155            "attr" => Some(Self::Attribute),
156            "derive" => Some(Self::Derive),
157            // Module pages use index.html (no typed prefix).
158            "index" => Some(Self::Module),
159            _ => {
160                // Member anchors carry the kind in the fragment, not the file
161                // name: `struct.Foo.html#method.bar`, `enum.Option.html#variant.Some`.
162                if href.contains("#method.") {
163                    Some(Self::Fn)
164                } else if href.contains("#variant.") {
165                    Some(Self::Variant)
166                } else if href.contains("#structfield.") {
167                    Some(Self::StructField)
168                } else {
169                    None
170                }
171            }
172        }
173    }
174}
175
176/// Replace hyphens with underscores for rustc crate/module path segments.
177pub fn rustc_crate_name(pkg: &str) -> String {
178    pkg.replace('-', "_")
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184
185    #[test]
186    fn hyphen_to_underscore() {
187        assert_eq!(rustc_crate_name("async-trait"), "async_trait");
188        assert_eq!(rustc_crate_name("serde"), "serde");
189    }
190
191    #[test]
192    fn fn_aliases() {
193        assert_eq!(ItemKind::parse("fn").unwrap(), ItemKind::Fn);
194        assert_eq!(ItemKind::parse("function").unwrap(), ItemKind::Fn);
195        assert_eq!(ItemKind::parse("method").unwrap(), ItemKind::Fn);
196        let (k, echo) = ItemKind::parse_with_echo("method").unwrap();
197        assert_eq!(k, ItemKind::Fn);
198        assert_eq!(echo, "method");
199        let (_, echo) = ItemKind::parse_with_echo("fn").unwrap();
200        assert_eq!(echo, "fn");
201    }
202
203    #[test]
204    fn href_classifier() {
205        assert_eq!(ItemKind::from_href("fn.foo.html"), Some(ItemKind::Fn));
206        assert_eq!(ItemKind::from_href("union.U.html"), Some(ItemKind::Union));
207        assert_eq!(
208            ItemKind::from_href("attr.async_trait.html"),
209            Some(ItemKind::Attribute)
210        );
211        assert_eq!(
212            ItemKind::from_href("derive.Serialize.html"),
213            Some(ItemKind::Derive)
214        );
215        assert_eq!(
216            ItemKind::from_href("de/trait.Deserialize.html"),
217            Some(ItemKind::Trait)
218        );
219        assert_eq!(ItemKind::from_href("unknown.html"), None);
220    }
221
222    #[test]
223    fn constant_prefix_modern_and_legacy() {
224        assert_eq!(ItemKind::file_prefix(ItemKind::Constant), Some("constant"));
225        assert_eq!(
226            ItemKind::from_href("constant.MAX.html"),
227            Some(ItemKind::Constant)
228        );
229        assert_eq!(
230            ItemKind::from_href("constant._SC_OPEN_MAX.html"),
231            Some(ItemKind::Constant)
232        );
233        // Legacy rustdoc href still classifies as Constant.
234        assert_eq!(
235            ItemKind::from_href("const.MAX.html"),
236            Some(ItemKind::Constant)
237        );
238        assert_eq!(ItemKind::parse("const").unwrap(), ItemKind::Constant);
239        assert_eq!(ItemKind::parse("constant").unwrap(), ItemKind::Constant);
240        assert_eq!(ItemKind::Constant.as_str(), "constant");
241    }
242
243    #[test]
244    fn member_only_kinds_own_no_page() {
245        // GAP-ASSOCITEM-002: rustdoc renders a variant and a field only as
246        // anchors on the parent. `file_prefix` returning `None` is what forces
247        // every URL builder to handle that instead of emitting `variant.Some.html`.
248        assert!(!ItemKind::Variant.owns_page());
249        assert!(!ItemKind::StructField.owns_page());
250        assert_eq!(ItemKind::Variant.file_prefix(), None);
251        assert_eq!(ItemKind::StructField.file_prefix(), None);
252        // Every other kind still has one.
253        for k in [
254            ItemKind::Module,
255            ItemKind::Struct,
256            ItemKind::Trait,
257            ItemKind::Enum,
258            ItemKind::Union,
259            ItemKind::Fn,
260            ItemKind::Type,
261            ItemKind::Constant,
262            ItemKind::Static,
263            ItemKind::Macro,
264            ItemKind::Attribute,
265            ItemKind::Derive,
266        ] {
267            assert!(k.owns_page(), "{k:?} should own a page");
268            assert!(k.file_prefix().is_some(), "{k:?} needs a file prefix");
269        }
270    }
271
272    #[test]
273    fn variant_and_field_aliases() {
274        assert_eq!(ItemKind::parse("variant").unwrap(), ItemKind::Variant);
275        assert_eq!(
276            ItemKind::parse("structfield").unwrap(),
277            ItemKind::StructField
278        );
279        // `field` is the spelling a Rust programmer reaches for first.
280        assert_eq!(ItemKind::parse("field").unwrap(), ItemKind::StructField);
281        let (_, echo) = ItemKind::parse_with_echo("field").unwrap();
282        assert_eq!(echo, "structfield");
283    }
284
285    #[test]
286    fn member_anchors_classify_only_when_the_file_name_is_silent() {
287        // `from_href` classifies the PAGE an all.html row points at, so a known
288        // file prefix always wins: `enum.Option.html#variant.Some` is a row about
289        // the enum. The fragment is consulted only as a fallback, for hrefs whose
290        // file name identifies nothing.
291        assert_eq!(
292            ItemKind::from_href("enum.Option.html#variant.Some"),
293            Some(ItemKind::Enum)
294        );
295        assert_eq!(
296            ItemKind::from_href("#variant.Some"),
297            Some(ItemKind::Variant)
298        );
299        assert_eq!(
300            ItemKind::from_href("#structfield.start"),
301            Some(ItemKind::StructField)
302        );
303        // The pre-existing `#method.` fallback keeps the same precedence.
304        assert_eq!(ItemKind::from_href("#method.new"), Some(ItemKind::Fn));
305    }
306}