1use crate::traits::{ImportSpec, ModuleId, ModuleResolver, Resolution, ResolverConfig};
4use crate::{ContainerBody, Import, Language, LanguageSymbols, Visibility};
5use std::path::Path;
6use tree_sitter::Node;
7
8pub struct Groovy;
10
11impl Language for Groovy {
12 fn name(&self) -> &'static str {
13 "Groovy"
14 }
15 fn extensions(&self) -> &'static [&'static str] {
16 &["groovy", "gradle", "gvy", "gy", "gsh"]
17 }
18 fn grammar_name(&self) -> &'static str {
19 "groovy"
20 }
21
22 fn as_symbols(&self) -> Option<&dyn LanguageSymbols> {
23 Some(self)
24 }
25
26 fn signature_suffix(&self) -> &'static str {
27 " {}"
28 }
29
30 fn node_name<'a>(&self, node: &Node, content: &'a str) -> Option<&'a str> {
31 node.child_by_field_name("name")
33 .or_else(|| node.child_by_field_name("function"))
34 .map(|n| &content[n.byte_range()])
35 }
36
37 fn extract_docstring(&self, node: &Node, content: &str) -> Option<String> {
38 extract_groovydoc(node, content)
39 }
40
41 fn extract_attributes(&self, node: &Node, content: &str) -> Vec<String> {
42 extract_groovy_annotations(node, content)
43 }
44
45 fn extract_imports(&self, node: &Node, content: &str) -> Vec<Import> {
46 if node.kind() != "groovy_import" {
47 return Vec::new();
48 }
49
50 let text = &content[node.byte_range()];
51 let line = node.start_position().row + 1;
52
53 if let Some(rest) = text.strip_prefix("import ") {
55 let rest = rest.strip_prefix("static ").unwrap_or(rest);
56 let module = rest.trim().trim_end_matches(';').to_string();
57 let is_wildcard = module.ends_with(".*");
58
59 return vec![Import {
60 module: module.trim_end_matches(".*").to_string(),
61 names: Vec::new(),
62 alias: None,
63 is_wildcard,
64 is_relative: false,
65 line,
66 }];
67 }
68
69 Vec::new()
70 }
71
72 fn format_import(&self, import: &Import, names: Option<&[&str]>) -> String {
73 let names_to_use: Vec<&str> = names
75 .map(|n| n.to_vec())
76 .unwrap_or_else(|| import.names.iter().map(|s| s.as_str()).collect());
77 if import.is_wildcard {
78 format!("import {}.*", import.module)
79 } else if names_to_use.is_empty() {
80 format!("import {}", import.module)
81 } else if names_to_use.len() == 1 {
82 format!("import {}.{}", import.module, names_to_use[0])
83 } else {
84 format!("import {}", import.module)
86 }
87 }
88
89 fn get_visibility(&self, node: &Node, content: &str) -> Visibility {
90 let text = &content[node.byte_range()];
91 if text.starts_with("private") {
92 Visibility::Private
93 } else if text.starts_with("protected") {
94 Visibility::Protected
95 } else {
96 Visibility::Public
97 }
98 }
99
100 fn is_test_symbol(&self, symbol: &crate::Symbol) -> bool {
101 let has_test_attr = symbol.attributes.iter().any(|a| a.contains("@Test"));
102 if has_test_attr {
103 return true;
104 }
105 match symbol.kind {
106 crate::SymbolKind::Class => {
107 symbol.name.starts_with("Test") || symbol.name.ends_with("Test")
108 }
109 _ => false,
110 }
111 }
112
113 fn test_file_globs(&self) -> &'static [&'static str] {
114 &[
115 "**/src/test/**/*.groovy",
116 "**/*Test.groovy",
117 "**/*Spec.groovy",
118 ]
119 }
120
121 fn container_body<'a>(&self, node: &'a Node<'a>) -> Option<Node<'a>> {
122 node.child_by_field_name("body")
123 }
124
125 fn analyze_container_body(
126 &self,
127 body_node: &Node,
128 content: &str,
129 inner_indent: &str,
130 ) -> Option<ContainerBody> {
131 crate::body::analyze_brace_body(body_node, content, inner_indent)
132 }
133
134 fn module_resolver(&self) -> Option<&dyn ModuleResolver> {
135 static RESOLVER: GroovyModuleResolver = GroovyModuleResolver;
136 Some(&RESOLVER)
137 }
138}
139
140impl LanguageSymbols for Groovy {}
141
142pub struct GroovyModuleResolver;
148
149const GROOVY_SRC_DIRS: &[&str] = &["src/main/groovy", "src/test/groovy", ""];
150
151impl ModuleResolver for GroovyModuleResolver {
152 fn workspace_config(&self, root: &Path) -> ResolverConfig {
153 ResolverConfig {
154 workspace_root: root.to_path_buf(),
155 path_mappings: Vec::new(),
156 search_roots: GROOVY_SRC_DIRS.iter().map(|d| root.join(d)).collect(),
157 }
158 }
159
160 fn module_of_file(&self, _root: &Path, file: &Path, cfg: &ResolverConfig) -> Vec<ModuleId> {
161 let ext = file.extension().and_then(|e| e.to_str()).unwrap_or("");
162 if ext != "groovy" && ext != "gradle" && ext != "gvy" && ext != "gy" && ext != "gsh" {
163 return Vec::new();
164 }
165 for search_root in &cfg.search_roots {
166 if let Ok(rel) = file.strip_prefix(search_root) {
167 let rel_str = rel.to_str().unwrap_or("");
168 let stripped = rel_str
170 .trim_end_matches(".groovy")
171 .trim_end_matches(".gradle")
172 .trim_end_matches(".gvy")
173 .trim_end_matches(".gy")
174 .trim_end_matches(".gsh");
175 let canonical = stripped.replace(['/', '\\'], ".");
176 if !canonical.is_empty() {
177 return vec![ModuleId {
178 canonical_path: canonical,
179 }];
180 }
181 }
182 }
183 Vec::new()
184 }
185
186 fn resolve(&self, from_file: &Path, spec: &ImportSpec, cfg: &ResolverConfig) -> Resolution {
187 let ext = from_file.extension().and_then(|e| e.to_str()).unwrap_or("");
188 if ext != "groovy" && ext != "gradle" && ext != "gvy" && ext != "gy" && ext != "gsh" {
189 return Resolution::NotApplicable;
190 }
191 let raw = &spec.raw;
192 let path_part = raw.replace('.', "/");
193 let exported_name = raw.rsplit('.').next().unwrap_or(raw).to_string();
194 for search_root in &cfg.search_roots {
195 let candidate = search_root.join(format!("{}.groovy", path_part));
196 if candidate.exists() {
197 return Resolution::Resolved(candidate, exported_name);
198 }
199 }
200 Resolution::NotFound
201 }
202}
203
204fn extract_groovydoc(node: &Node, content: &str) -> Option<String> {
211 let parent = node.parent()?;
212 if parent.kind() != "groovy_doc" {
213 return None;
214 }
215
216 let mut doc_parts: Vec<String> = Vec::new();
217 let mut cursor = parent.walk();
218 for child in parent.children(&mut cursor) {
219 match child.kind() {
220 "first_line" => {
221 let text = content[child.byte_range()].trim();
222 let text = text.strip_suffix("*/").unwrap_or(text).trim();
224 if !text.is_empty() {
225 doc_parts.push(text.to_string());
226 }
227 }
228 "tag_value" => {
229 let text = content[child.byte_range()].trim();
230 if !text.is_empty() {
231 doc_parts.push(text.to_string());
232 }
233 }
234 _ => {}
235 }
236 }
237
238 if doc_parts.is_empty() {
239 None
240 } else {
241 Some(doc_parts.join(" "))
242 }
243}
244
245fn extract_groovy_annotations(node: &Node, content: &str) -> Vec<String> {
250 let mut attrs = Vec::new();
251 let mut cursor = node.walk();
252 for child in node.children(&mut cursor) {
253 if child.kind() == "annotation" {
254 attrs.push(content[child.byte_range()].to_string());
255 }
256 }
257 attrs
258}
259
260#[cfg(test)]
261mod tests {
262 use super::*;
263 use crate::validate_unused_kinds_audit;
264
265 #[test]
266 fn unused_node_kinds_audit() {
267 #[rustfmt::skip]
268 let documented_unused: &[&str] = &[
269 "access_modifier", "array_type", "builtintype", "declaration",
270 "do_while_loop", "dotted_identifier", "for_parameters",
271 "function_call", "function_declaration", "groovy_doc_throws",
272 "identifier", "juxt_function_call", "modifier",
273 "parenthesized_expression", "qualified_name", "return", "switch_block",
274 "type_with_generics", "wildcard_import",
275 "switch_statement",
277 "if_statement",
278 "groovy_import",
279 "while_loop",
280 "try_statement",
281 "for_in_loop",
282 "for_loop",
283 "case",
284 ];
285 validate_unused_kinds_audit(&Groovy, documented_unused)
286 .expect("Groovy unused node kinds audit failed");
287 }
288}