Skip to main content

normalize_languages/
zsh.rs

1//! Zsh language support.
2
3use crate::external_packages::ResolvedPackage;
4use crate::{
5    Export, Import, Language, Symbol, SymbolKind, Visibility, VisibilityMechanism,
6    simple_function_symbol,
7};
8use std::path::{Path, PathBuf};
9use tree_sitter::Node;
10
11/// Zsh language support.
12pub struct Zsh;
13
14impl Language for Zsh {
15    fn name(&self) -> &'static str {
16        "Zsh"
17    }
18    fn extensions(&self) -> &'static [&'static str] {
19        &["zsh", "zshrc", "zshenv", "zprofile"]
20    }
21    fn grammar_name(&self) -> &'static str {
22        "zsh"
23    }
24
25    fn has_symbols(&self) -> bool {
26        true
27    }
28
29    fn container_kinds(&self) -> &'static [&'static str] {
30        &[]
31    }
32
33    fn function_kinds(&self) -> &'static [&'static str] {
34        &["function_definition"]
35    }
36
37    fn type_kinds(&self) -> &'static [&'static str] {
38        &[]
39    }
40
41    fn import_kinds(&self) -> &'static [&'static str] {
42        &["command"] // source, .
43    }
44
45    fn public_symbol_kinds(&self) -> &'static [&'static str] {
46        &["function_definition"]
47    }
48
49    fn visibility_mechanism(&self) -> VisibilityMechanism {
50        VisibilityMechanism::AllPublic
51    }
52
53    fn extract_public_symbols(&self, node: &Node, content: &str) -> Vec<Export> {
54        if node.kind() != "function_definition" {
55            return Vec::new();
56        }
57
58        let name = match self.node_name(node, content) {
59            Some(n) => n.to_string(),
60            None => return Vec::new(),
61        };
62
63        vec![Export {
64            name,
65            kind: SymbolKind::Function,
66            line: node.start_position().row + 1,
67        }]
68    }
69
70    fn scope_creating_kinds(&self) -> &'static [&'static str] {
71        &["function_definition", "subshell", "command_substitution"]
72    }
73
74    fn control_flow_kinds(&self) -> &'static [&'static str] {
75        &[
76            "if_statement",
77            "for_statement",
78            "while_statement",
79            "case_statement",
80        ]
81    }
82
83    fn complexity_nodes(&self) -> &'static [&'static str] {
84        &[
85            "if_statement",
86            "elif_clause",
87            "for_statement",
88            "while_statement",
89            "case_statement",
90            "case_item",
91        ]
92    }
93
94    fn nesting_nodes(&self) -> &'static [&'static str] {
95        &[
96            "function_definition",
97            "if_statement",
98            "for_statement",
99            "while_statement",
100        ]
101    }
102
103    fn signature_suffix(&self) -> &'static str {
104        ""
105    }
106
107    fn extract_function(&self, node: &Node, content: &str, _in_container: bool) -> Option<Symbol> {
108        let name = self.node_name(node, content)?;
109        Some(simple_function_symbol(
110            node,
111            content,
112            name,
113            self.extract_docstring(node, content),
114        ))
115    }
116
117    fn extract_container(&self, _node: &Node, _content: &str) -> Option<Symbol> {
118        None
119    }
120    fn extract_type(&self, _node: &Node, _content: &str) -> Option<Symbol> {
121        None
122    }
123
124    fn extract_docstring(&self, node: &Node, content: &str) -> Option<String> {
125        let mut prev = node.prev_sibling();
126        let mut doc_lines = Vec::new();
127
128        while let Some(sibling) = prev {
129            let text = &content[sibling.byte_range()];
130            if sibling.kind() == "comment" && text.starts_with('#') {
131                let line = text.strip_prefix('#').unwrap_or(text).trim();
132                doc_lines.push(line.to_string());
133                prev = sibling.prev_sibling();
134            } else {
135                break;
136            }
137        }
138
139        if doc_lines.is_empty() {
140            return None;
141        }
142
143        doc_lines.reverse();
144        Some(doc_lines.join(" "))
145    }
146
147    fn extract_attributes(&self, _node: &Node, _content: &str) -> Vec<String> {
148        Vec::new()
149    }
150
151    fn extract_imports(&self, node: &Node, content: &str) -> Vec<Import> {
152        if node.kind() != "command" {
153            return Vec::new();
154        }
155
156        let text = &content[node.byte_range()];
157        let line = node.start_position().row + 1;
158
159        // source file or . file
160        let module = if let Some(rest) = text.strip_prefix("source ") {
161            Some(rest.trim().to_string())
162        } else if let Some(rest) = text.strip_prefix(". ") {
163            Some(rest.trim().to_string())
164        } else {
165            None
166        };
167
168        if let Some(module) = module {
169            return vec![Import {
170                module,
171                names: Vec::new(),
172                alias: None,
173                is_wildcard: false,
174                is_relative: true,
175                line,
176            }];
177        }
178
179        Vec::new()
180    }
181
182    fn format_import(&self, import: &Import, _names: Option<&[&str]>) -> String {
183        // Zsh: source file or . file
184        format!("source {}", import.module)
185    }
186
187    fn is_public(&self, _node: &Node, _content: &str) -> bool {
188        true
189    }
190    fn get_visibility(&self, _node: &Node, _content: &str) -> Visibility {
191        Visibility::Public
192    }
193
194    fn is_test_symbol(&self, symbol: &crate::Symbol) -> bool {
195        let name = symbol.name.as_str();
196        match symbol.kind {
197            crate::SymbolKind::Function | crate::SymbolKind::Method => name.starts_with("test_"),
198            crate::SymbolKind::Module => name == "tests" || name == "test",
199            _ => false,
200        }
201    }
202
203    fn embedded_content(&self, _node: &Node, _content: &str) -> Option<crate::EmbeddedBlock> {
204        None
205    }
206
207    fn container_body<'a>(&self, node: &'a Node<'a>) -> Option<Node<'a>> {
208        node.child_by_field_name("body")
209    }
210
211    fn body_has_docstring(&self, _body: &Node, _content: &str) -> bool {
212        false
213    }
214
215    fn node_name<'a>(&self, node: &Node, content: &'a str) -> Option<&'a str> {
216        node.child_by_field_name("name")
217            .map(|n| &content[n.byte_range()])
218    }
219
220    fn file_path_to_module_name(&self, path: &Path) -> Option<String> {
221        let name = path.file_name()?.to_str()?;
222        if name.ends_with(".zsh") || name.starts_with(".zsh") || name == "zshrc" {
223            let stem = path.file_stem()?.to_str()?;
224            return Some(stem.to_string());
225        }
226        None
227    }
228
229    fn module_name_to_paths(&self, module: &str) -> Vec<String> {
230        vec![format!("{}.zsh", module), format!("functions/{}", module)]
231    }
232
233    fn lang_key(&self) -> &'static str {
234        "zsh"
235    }
236
237    fn is_stdlib_import(&self, _import_name: &str, _project_root: &Path) -> bool {
238        false
239    }
240    fn find_stdlib(&self, _project_root: &Path) -> Option<PathBuf> {
241        None
242    }
243
244    fn resolve_local_import(&self, import: &str, current_file: &Path, _: &Path) -> Option<PathBuf> {
245        let dir = current_file.parent()?;
246        let full = dir.join(import);
247        if full.is_file() { Some(full) } else { None }
248    }
249
250    fn resolve_external_import(&self, _: &str, _: &Path) -> Option<ResolvedPackage> {
251        None
252    }
253    fn get_version(&self, _: &Path) -> Option<String> {
254        None
255    }
256
257    fn find_package_cache(&self, _project_root: &Path) -> Option<PathBuf> {
258        if let Some(home) = std::env::var_os("HOME") {
259            let oh_my_zsh = PathBuf::from(&home).join(".oh-my-zsh");
260            if oh_my_zsh.is_dir() {
261                return Some(oh_my_zsh);
262            }
263            let zdotdir = PathBuf::from(&home).join(".zsh");
264            if zdotdir.is_dir() {
265                return Some(zdotdir);
266            }
267        }
268        None
269    }
270
271    fn indexable_extensions(&self) -> &'static [&'static str] {
272        &["zsh"]
273    }
274    fn package_sources(&self, _: &Path) -> Vec<crate::PackageSource> {
275        Vec::new()
276    }
277
278    fn should_skip_package_entry(&self, name: &str, is_dir: bool) -> bool {
279        use crate::traits::skip_dotfiles;
280        if skip_dotfiles(name) {
281            return true;
282        }
283        if is_dir {
284            return false;
285        }
286        // Zsh files often don't have extensions
287        !name.ends_with(".zsh") && !name.contains("zsh")
288    }
289
290    fn discover_packages(&self, _: &crate::PackageSource) -> Vec<(String, PathBuf)> {
291        Vec::new()
292    }
293
294    fn package_module_name(&self, entry_name: &str) -> String {
295        entry_name
296            .strip_suffix(".zsh")
297            .unwrap_or(entry_name)
298            .to_string()
299    }
300
301    fn find_package_entry(&self, path: &Path) -> Option<PathBuf> {
302        if path.is_file() {
303            Some(path.to_path_buf())
304        } else {
305            None
306        }
307    }
308}
309
310#[cfg(test)]
311mod tests {
312    use super::*;
313    use crate::validate_unused_kinds_audit;
314
315    #[test]
316    fn unused_node_kinds_audit() {
317        #[rustfmt::skip]
318        let documented_unused: &[&str] = &[
319            "else_clause",
320        ];
321        validate_unused_kinds_audit(&Zsh, documented_unused)
322            .expect("Zsh unused node kinds audit failed");
323    }
324}