Skip to main content

cuc/
namespace.rs

1use std::fmt::Display;
2
3#[derive(Debug, Clone)]
4pub struct NameSpace {
5    scope: Vec<String>,
6}
7
8#[derive(Debug, Clone)]
9pub struct NameSpaceView<'me> {
10    scope: &'me [String],
11}
12
13impl NameSpace {
14    const SEPARATOR: &'static str = "::";
15    const FUNC_SEPARATOR: &'static str = "_";
16
17    pub fn root() -> Self {
18        Self { scope: vec![] }
19    }
20
21    pub fn is_root(&self) -> bool {
22        self.scope.is_empty()
23    }
24
25    pub fn view(&self) -> NameSpaceView<'_> {
26        NameSpaceView {
27            scope: self.scope.as_slice(),
28        }
29    }
30
31    pub fn join<S>(mut self, other: S) -> Self
32    where
33        S: Into<String>,
34    {
35        let other = other.into();
36        if !other.trim().is_empty() {
37            self.scope.push(other);
38        }
39        self
40    }
41
42    pub fn parent(&self) -> NameSpaceView<'_> {
43        if !self.scope.is_empty() {
44            NameSpaceView {
45                scope: &self.scope[..self.scope.len() - 1],
46            }
47        } else {
48            NameSpaceView { scope: &[] }
49        }
50    }
51
52    pub fn display(&self) -> String {
53        self.scope.join(Self::SEPARATOR)
54    }
55}
56
57impl Default for NameSpace {
58    fn default() -> Self {
59        Self::root()
60    }
61}
62
63impl From<NameSpaceView<'_>> for NameSpace {
64    fn from(value: NameSpaceView) -> Self {
65        NameSpace {
66            scope: value.scope.to_vec(),
67        }
68    }
69}
70
71impl NameSpaceView<'_> {
72    pub fn is_root(&self) -> bool {
73        self.scope.is_empty()
74    }
75
76    pub fn parent(&self) -> NameSpaceView<'_> {
77        if !self.scope.is_empty() {
78            NameSpaceView {
79                scope: &self.scope[..self.scope.len() - 1],
80            }
81        } else {
82            NameSpaceView { scope: &[] }
83        }
84
85        // assert_eq!(parent_scope("a_b_c_"), "a_b");
86        // assert_eq!(parent_scope("a_b_c"), "a_b");
87        // assert_eq!(parent_scope("a_"), ""); // only one level
88        // assert_eq!(parent_scope("abc"), ""); // no underscores
89    }
90
91    pub fn display(&self) -> String {
92        self.scope.join(NameSpace::SEPARATOR)
93    }
94
95    pub fn as_func_str(&self) -> String {
96        self.scope.join(NameSpace::FUNC_SEPARATOR)
97    }
98
99    fn join_func_str(this: &mut String, other: impl AsRef<str>) {
100        let other = other.as_ref();
101        if !other.is_empty() {
102            *this += other;
103            *this += NameSpace::FUNC_SEPARATOR;
104        }
105    }
106
107    pub fn flag_func_name<S>(&self, name: S) -> String
108    where
109        S: AsRef<str>,
110    {
111        let mut func_name = String::from("_flag_");
112        Self::join_func_str(&mut func_name, self.as_func_str());
113        func_name += name.as_ref();
114        func_name
115    }
116
117    pub fn global_flag_func_name(&self) -> String {
118        let mut func_name = String::from("_global_flags_");
119        func_name += &self.as_func_str();
120        func_name
121    }
122
123    /// Ancestor scopes ordered from the root namespace down to `self` (inclusive).
124    pub fn lineage(&self) -> Vec<NameSpaceView<'_>> {
125        (0..=self.scope.len())
126            .map(|len| NameSpaceView {
127                scope: &self.scope[..len],
128            })
129            .collect()
130    }
131
132    pub fn cmd_func_name<S>(&self, name: S) -> String
133    where
134        S: AsRef<str>,
135    {
136        let mut func_name = String::from("_cmd_");
137        Self::join_func_str(&mut func_name, self.as_func_str());
138        func_name += name.as_ref();
139        func_name
140    }
141}
142
143impl Display for NameSpace {
144    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
145        write!(f, "{}", self.display())
146    }
147}
148
149impl Display for NameSpaceView<'_> {
150    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
151        write!(f, "{}", self.display())
152    }
153}
154
155/// Encode an arbitrary Usage name as a collision-free Lua identifier fragment.
156/// Underscores are encoded too, so punctuation escapes cannot collide with literal text.
157pub fn slugify<S>(input: S) -> String
158where
159    S: AsRef<str>,
160{
161    input.as_ref().chars().fold(String::new(), |mut out, c| {
162        if c.is_ascii_alphanumeric() {
163            out.push(c);
164        } else {
165            out.push_str(&format!("_u{:x}_", c as u32));
166        }
167        out
168    })
169}
170
171pub fn arg_complete_func_name<S>(complete_name: S) -> String
172where
173    S: AsRef<str>,
174{
175    let mut func_name = String::from("_complete_arg_");
176    func_name += &slugify(complete_name.as_ref());
177    func_name
178}
179
180pub fn sigil_arg_func_name<S>(arg_name: S) -> String
181where
182    S: AsRef<str>,
183{
184    let mut func_name = String::from("_sigil_arg_");
185    func_name += &slugify(arg_name.as_ref());
186    func_name
187}
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192
193    #[test]
194    fn test_constants() {
195        assert_eq!(NameSpace::SEPARATOR, "::");
196        assert_eq!(NameSpace::FUNC_SEPARATOR, "_");
197    }
198
199    #[test]
200    fn slugify_produces_valid_distinct_lua_identifier_fragments() {
201        assert_eq!(slugify("tool-alias"), "tool_u2d_alias");
202        assert_eq!(slugify("工具"), "_u5de5__u5177_");
203        assert_ne!(slugify("a-b"), slugify("ab"));
204        assert_ne!(slugify("a-b"), slugify("a_u2d_b"));
205    }
206
207    #[test]
208    fn test_root() {
209        let ns = NameSpace::root();
210        assert!(ns.scope.is_empty());
211        assert!(ns.is_root());
212    }
213
214    #[test]
215    fn test_is_root() {
216        let root_ns = NameSpace::root();
217        assert!(root_ns.is_root());
218
219        let non_root_ns = NameSpace::root().join("test");
220        assert!(!non_root_ns.is_root());
221    }
222
223    #[test]
224    fn test_view() {
225        let ns = NameSpace::root().join("a").join("b");
226        let view = ns.view();
227        assert_eq!(view.scope, &["a", "b"]);
228
229        let root_ns = NameSpace::root();
230        let root_view = root_ns.view();
231        assert_eq!(root_view.scope, &[] as &[String]);
232    }
233
234    #[test]
235    fn test_join_string() {
236        let ns = NameSpace::root().join("test");
237        assert_eq!(ns.scope, vec!["test"]);
238        assert!(!ns.is_root());
239    }
240
241    #[test]
242    fn test_join_empty_string() {
243        let ns = NameSpace::root().join("");
244        assert!(ns.is_root()); // Empty string should not be added
245        assert_eq!(ns.scope, Vec::<String>::new());
246    }
247
248    #[test]
249    fn test_join_whitespace_only() {
250        let ns = NameSpace::root().join("   ");
251        assert!(ns.is_root()); // Whitespace-only should not be added
252        assert_eq!(ns.scope, Vec::<String>::new());
253    }
254
255    #[test]
256    fn test_join_whitespace_around_content() {
257        let ns = NameSpace::root().join("  test  ");
258        assert_eq!(ns.scope, vec!["  test  "]); // trim() only checks, doesn't modify
259    }
260
261    #[test]
262    fn test_join_chaining() {
263        let ns = NameSpace::root().join("a").join("b").join("c");
264        assert_eq!(ns.scope, vec!["a", "b", "c"]);
265    }
266
267    #[test]
268    fn test_join_mixed_empty() {
269        let ns = NameSpace::root()
270            .join("a")
271            .join("")
272            .join("b")
273            .join("   ")
274            .join("c");
275        assert_eq!(ns.scope, vec!["a", "b", "c"]);
276    }
277
278    #[test]
279    fn test_parent_empty_scope() {
280        let ns = NameSpace::root();
281        let parent = ns.parent();
282        assert_eq!(parent.scope, &[] as &[String]);
283    }
284
285    #[test]
286    fn test_parent_single_level() {
287        let ns = NameSpace::root().join("a");
288        let parent = ns.parent();
289        assert_eq!(parent.scope, &[] as &[String]);
290    }
291
292    #[test]
293    fn test_parent_multi_level() {
294        let ns = NameSpace::root().join("a").join("b").join("c");
295        let parent = ns.parent();
296        assert_eq!(parent.scope, &["a", "b"]);
297    }
298
299    #[test]
300    fn test_display_empty() {
301        let ns = NameSpace::root();
302        assert_eq!(ns.display(), "");
303    }
304
305    #[test]
306    fn test_display_single() {
307        let ns = NameSpace::root().join("test");
308        assert_eq!(ns.display(), "test");
309    }
310
311    #[test]
312    fn test_display_multiple() {
313        let ns = NameSpace::root().join("a").join("b").join("c");
314        assert_eq!(ns.display(), "a::b::c");
315    }
316
317    #[test]
318    fn test_display_with_special_chars() {
319        let ns = NameSpace::root().join("a_b").join("c::d").join("e-f");
320        assert_eq!(ns.display(), "a_b::c::d::e-f");
321    }
322
323    #[test]
324    fn test_complex_workflow() {
325        let ns = NameSpace::root()
326            .join("module")
327            .join("submodule")
328            .join("function");
329
330        assert!(!ns.is_root());
331        assert_eq!(ns.display(), "module::submodule::function");
332
333        let parent = ns.parent();
334        assert_eq!(parent.scope, &["module", "submodule"]);
335
336        let view = ns.view();
337        assert_eq!(view.scope, &["module", "submodule", "function"]);
338    }
339
340    #[test]
341    fn test_edge_cases() {
342        let ns1 = NameSpace::root().join("\t");
343        assert!(ns1.is_root());
344
345        let ns2 = NameSpace::root().join("\n");
346        assert!(ns2.is_root());
347
348        let ns3 = NameSpace::root().join(" \t \n ");
349        assert!(ns3.is_root());
350    }
351}