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, ErrorKind};
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}
34
35impl ItemKind {
36    /// Stable JSON / filter string.
37    pub fn as_str(self) -> &'static str {
38        match self {
39            Self::Module => "module",
40            Self::Struct => "struct",
41            Self::Trait => "trait",
42            Self::Enum => "enum",
43            Self::Union => "union",
44            Self::Fn => "fn",
45            Self::Type => "type",
46            Self::Constant => "constant",
47            Self::Static => "static",
48            Self::Macro => "macro",
49            Self::Attribute => "attribute",
50            Self::Derive => "derive",
51        }
52    }
53
54    /// Filename prefix in rustdoc HTML (e.g. `struct`, `fn`, `attr`, `constant`).
55    ///
56    /// Modern rustdoc/docs.rs uses `constant.NAME.html` (not legacy `const.NAME.html`).
57    pub fn file_prefix(self) -> &'static str {
58        match self {
59            Self::Module => "module",
60            Self::Struct => "struct",
61            Self::Trait => "trait",
62            Self::Enum => "enum",
63            Self::Union => "union",
64            Self::Fn => "fn",
65            Self::Type => "type",
66            Self::Constant => "constant",
67            Self::Static => "static",
68            Self::Macro => "macro",
69            Self::Attribute => "attr",
70            Self::Derive => "derive",
71        }
72    }
73
74    /// Parse CLI / filter aliases into canonical kind.
75    ///
76    /// # Errors
77    ///
78    /// Returns [`ErrorKind::InvalidInput`] when `input` is not a known kind alias.
79    pub fn parse(input: &str) -> AppResult<Self> {
80        let s = input.trim().to_ascii_lowercase();
81        match s.as_str() {
82            "module" | "mod" => Ok(Self::Module),
83            "struct" => Ok(Self::Struct),
84            "trait" => Ok(Self::Trait),
85            "enum" => Ok(Self::Enum),
86            "union" => Ok(Self::Union),
87            "fn" | "function" | "method" => Ok(Self::Fn),
88            "type" => Ok(Self::Type),
89            "const" | "constant" => Ok(Self::Constant),
90            "static" => Ok(Self::Static),
91            "macro" => Ok(Self::Macro),
92            "attr" | "attribute" => Ok(Self::Attribute),
93            "derive" => Ok(Self::Derive),
94            other => Err(AppError::new(
95                ErrorKind::InvalidInput,
96                format!("unknown item type '{other}'"),
97            )),
98        }
99    }
100
101    /// Infer kind from all.html href (e.g. `struct.Name.html`, `attr.foo.html`).
102    ///
103    /// Accepts modern `constant.` and legacy `const.` prefixes for Constant.
104    pub fn from_href(href: &str) -> Option<Self> {
105        let file = href.rsplit('/').next().unwrap_or(href);
106        let file = file.split('#').next().unwrap_or(file);
107        let prefix = file.split('.').next().unwrap_or("");
108        match prefix {
109            "struct" => Some(Self::Struct),
110            "trait" => Some(Self::Trait),
111            "fn" => Some(Self::Fn),
112            "enum" => Some(Self::Enum),
113            "type" => Some(Self::Type),
114            // Modern rustdoc: constant.NAME.html; legacy: const.NAME.html
115            "constant" | "const" => Some(Self::Constant),
116            "static" => Some(Self::Static),
117            "macro" => Some(Self::Macro),
118            "union" => Some(Self::Union),
119            "attr" => Some(Self::Attribute),
120            "derive" => Some(Self::Derive),
121            // Module pages use index.html (no typed prefix).
122            "index" => Some(Self::Module),
123            _ => {
124                // Associated method anchors: `struct.Foo.html#method.bar`
125                if href.contains("#method.") {
126                    Some(Self::Fn)
127                } else {
128                    None
129                }
130            }
131        }
132    }
133}
134
135/// Replace hyphens with underscores for rustc crate/module path segments.
136pub fn rustc_crate_name(pkg: &str) -> String {
137    pkg.replace('-', "_")
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143
144    #[test]
145    fn hyphen_to_underscore() {
146        assert_eq!(rustc_crate_name("async-trait"), "async_trait");
147        assert_eq!(rustc_crate_name("serde"), "serde");
148    }
149
150    #[test]
151    fn fn_aliases() {
152        assert_eq!(ItemKind::parse("fn").unwrap(), ItemKind::Fn);
153        assert_eq!(ItemKind::parse("function").unwrap(), ItemKind::Fn);
154    }
155
156    #[test]
157    fn href_classifier() {
158        assert_eq!(ItemKind::from_href("fn.foo.html"), Some(ItemKind::Fn));
159        assert_eq!(ItemKind::from_href("union.U.html"), Some(ItemKind::Union));
160        assert_eq!(
161            ItemKind::from_href("attr.async_trait.html"),
162            Some(ItemKind::Attribute)
163        );
164        assert_eq!(
165            ItemKind::from_href("derive.Serialize.html"),
166            Some(ItemKind::Derive)
167        );
168        assert_eq!(
169            ItemKind::from_href("de/trait.Deserialize.html"),
170            Some(ItemKind::Trait)
171        );
172        assert_eq!(ItemKind::from_href("unknown.html"), None);
173    }
174
175    #[test]
176    fn constant_prefix_modern_and_legacy() {
177        assert_eq!(ItemKind::file_prefix(ItemKind::Constant), "constant");
178        assert_eq!(
179            ItemKind::from_href("constant.MAX.html"),
180            Some(ItemKind::Constant)
181        );
182        assert_eq!(
183            ItemKind::from_href("constant._SC_OPEN_MAX.html"),
184            Some(ItemKind::Constant)
185        );
186        // Legacy rustdoc href still classifies as Constant.
187        assert_eq!(
188            ItemKind::from_href("const.MAX.html"),
189            Some(ItemKind::Constant)
190        );
191        assert_eq!(ItemKind::parse("const").unwrap(), ItemKind::Constant);
192        assert_eq!(ItemKind::parse("constant").unwrap(), ItemKind::Constant);
193        assert_eq!(ItemKind::Constant.as_str(), "constant");
194    }
195}