1use 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
11pub struct Elm;
13
14impl Language for Elm {
15 fn name(&self) -> &'static str {
16 "Elm"
17 }
18 fn extensions(&self) -> &'static [&'static str] {
19 &["elm"]
20 }
21 fn grammar_name(&self) -> &'static str {
22 "elm"
23 }
24
25 fn has_symbols(&self) -> bool {
26 true
27 }
28
29 fn container_kinds(&self) -> &'static [&'static str] {
30 &[
31 "module_declaration",
32 "type_alias_declaration",
33 "type_declaration",
34 ]
35 }
36
37 fn function_kinds(&self) -> &'static [&'static str] {
38 &["value_declaration", "function_declaration_left"]
39 }
40
41 fn type_kinds(&self) -> &'static [&'static str] {
42 &["type_alias_declaration", "type_declaration"]
43 }
44
45 fn import_kinds(&self) -> &'static [&'static str] {
46 &["import_clause"]
47 }
48
49 fn public_symbol_kinds(&self) -> &'static [&'static str] {
50 &[
51 "value_declaration",
52 "type_alias_declaration",
53 "type_declaration",
54 ]
55 }
56
57 fn visibility_mechanism(&self) -> VisibilityMechanism {
58 VisibilityMechanism::ExplicitExport }
60
61 fn extract_public_symbols(&self, node: &Node, content: &str) -> Vec<Export> {
62 let name = match self.node_name(node, content) {
63 Some(n) => n.to_string(),
64 None => return Vec::new(),
65 };
66
67 let kind = match node.kind() {
68 "value_declaration" => SymbolKind::Function,
69 "type_alias_declaration" => SymbolKind::Type,
70 "type_declaration" => SymbolKind::Enum,
71 _ => return Vec::new(),
72 };
73
74 vec![Export {
75 name,
76 kind,
77 line: node.start_position().row + 1,
78 }]
79 }
80
81 fn scope_creating_kinds(&self) -> &'static [&'static str] {
82 &["let_in_expr", "anonymous_function_expr"]
83 }
84
85 fn control_flow_kinds(&self) -> &'static [&'static str] {
86 &["if_else_expr", "case_of_expr"]
87 }
88
89 fn complexity_nodes(&self) -> &'static [&'static str] {
90 &["if_else_expr", "case_of_branch"]
91 }
92
93 fn nesting_nodes(&self) -> &'static [&'static str] {
94 &["value_declaration", "let_in_expr", "case_of_expr"]
95 }
96
97 fn signature_suffix(&self) -> &'static str {
98 ""
99 }
100
101 fn extract_function(&self, node: &Node, content: &str, _in_container: bool) -> Option<Symbol> {
102 let name = self.node_name(node, content)?;
103 Some(simple_function_symbol(
104 node,
105 content,
106 name,
107 self.extract_docstring(node, content),
108 ))
109 }
110
111 fn extract_container(&self, node: &Node, content: &str) -> Option<Symbol> {
112 let name = self.node_name(node, content)?;
113
114 let (kind, keyword) = match node.kind() {
115 "module_declaration" => (SymbolKind::Module, "module"),
116 "type_alias_declaration" => (SymbolKind::Type, "type alias"),
117 "type_declaration" => (SymbolKind::Enum, "type"),
118 _ => return None,
119 };
120
121 Some(Symbol {
122 name: name.to_string(),
123 kind,
124 signature: format!("{} {}", keyword, name),
125 docstring: self.extract_docstring(node, content),
126 attributes: Vec::new(),
127 start_line: node.start_position().row + 1,
128 end_line: node.end_position().row + 1,
129 visibility: Visibility::Public,
130 children: Vec::new(),
131 is_interface_impl: false,
132 implements: Vec::new(),
133 })
134 }
135
136 fn extract_type(&self, node: &Node, content: &str) -> Option<Symbol> {
137 self.extract_container(node, content)
138 }
139
140 fn extract_docstring(&self, node: &Node, content: &str) -> Option<String> {
141 let mut prev = node.prev_sibling();
143 while let Some(sibling) = prev {
144 let text = &content[sibling.byte_range()];
145 if sibling.kind() == "block_comment" {
146 let inner = text
147 .trim_start_matches("{-|")
148 .trim_start_matches("{-")
149 .trim_end_matches("-}")
150 .trim();
151 if !inner.is_empty() {
152 return Some(inner.lines().next().unwrap_or(inner).to_string());
153 }
154 }
155 prev = sibling.prev_sibling();
156 }
157 None
158 }
159
160 fn extract_attributes(&self, _node: &Node, _content: &str) -> Vec<String> {
161 Vec::new()
162 }
163
164 fn extract_imports(&self, node: &Node, content: &str) -> Vec<Import> {
165 if node.kind() != "import_clause" {
166 return Vec::new();
167 }
168
169 let text = &content[node.byte_range()];
170 let line = node.start_position().row + 1;
171
172 if let Some(rest) = text.strip_prefix("import ") {
174 let parts: Vec<&str> = rest.split_whitespace().collect();
175 if let Some(&module) = parts.first() {
176 let alias = parts
177 .iter()
178 .position(|&p| p == "as")
179 .and_then(|i| parts.get(i + 1))
180 .map(|s| s.to_string());
181
182 return vec![Import {
183 module: module.to_string(),
184 names: Vec::new(),
185 alias,
186 is_wildcard: text.contains("exposing (..)"),
187 is_relative: false,
188 line,
189 }];
190 }
191 }
192
193 Vec::new()
194 }
195
196 fn format_import(&self, import: &Import, names: Option<&[&str]>) -> String {
197 let names_to_use: Vec<&str> = names
199 .map(|n| n.to_vec())
200 .unwrap_or_else(|| import.names.iter().map(|s| s.as_str()).collect());
201 if import.is_wildcard {
202 format!("import {} exposing (..)", import.module)
203 } else if names_to_use.is_empty() {
204 format!("import {}", import.module)
205 } else {
206 format!(
207 "import {} exposing ({})",
208 import.module,
209 names_to_use.join(", ")
210 )
211 }
212 }
213
214 fn is_public(&self, _node: &Node, _content: &str) -> bool {
215 true
216 }
217 fn get_visibility(&self, _node: &Node, _content: &str) -> Visibility {
218 Visibility::Public
219 }
220
221 fn is_test_symbol(&self, symbol: &crate::Symbol) -> bool {
222 let name = symbol.name.as_str();
223 match symbol.kind {
224 crate::SymbolKind::Function | crate::SymbolKind::Method => name.starts_with("test_"),
225 crate::SymbolKind::Module => name == "tests" || name == "test",
226 _ => false,
227 }
228 }
229
230 fn embedded_content(&self, _node: &Node, _content: &str) -> Option<crate::EmbeddedBlock> {
231 None
232 }
233
234 fn container_body<'a>(&self, _node: &'a Node<'a>) -> Option<Node<'a>> {
235 None
236 }
237 fn body_has_docstring(&self, _body: &Node, _content: &str) -> bool {
238 false
239 }
240
241 fn node_name<'a>(&self, node: &Node, content: &'a str) -> Option<&'a str> {
242 node.child_by_field_name("name")
243 .map(|n| &content[n.byte_range()])
244 }
245
246 fn file_path_to_module_name(&self, path: &Path) -> Option<String> {
247 let ext = path.extension()?.to_str()?;
248 if ext != "elm" {
249 return None;
250 }
251 let stem = path.file_stem()?.to_str()?;
252 Some(stem.to_string())
253 }
254
255 fn module_name_to_paths(&self, module: &str) -> Vec<String> {
256 let path = module.replace('.', "/");
257 vec![format!("{}.elm", path)]
258 }
259
260 fn lang_key(&self) -> &'static str {
261 "elm"
262 }
263
264 fn is_stdlib_import(&self, import_name: &str, _project_root: &Path) -> bool {
265 import_name.starts_with("Basics")
266 || import_name.starts_with("List")
267 || import_name.starts_with("Maybe")
268 || import_name.starts_with("Result")
269 || import_name.starts_with("String")
270 || import_name.starts_with("Char")
271 || import_name.starts_with("Tuple")
272 || import_name.starts_with("Debug")
273 || import_name.starts_with("Platform")
274 || import_name.starts_with("Cmd")
275 || import_name.starts_with("Sub")
276 }
277
278 fn find_stdlib(&self, _project_root: &Path) -> Option<PathBuf> {
279 None
280 }
281
282 fn resolve_local_import(
283 &self,
284 import: &str,
285 _current_file: &Path,
286 project_root: &Path,
287 ) -> Option<PathBuf> {
288 let path = import.replace('.', "/");
289 let full = project_root.join("src").join(format!("{}.elm", path));
290 if full.is_file() { Some(full) } else { None }
291 }
292
293 fn resolve_external_import(
294 &self,
295 _import_name: &str,
296 _project_root: &Path,
297 ) -> Option<ResolvedPackage> {
298 None
299 }
300
301 fn get_version(&self, project_root: &Path) -> Option<String> {
302 if project_root.join("elm.json").is_file() {
303 return Some("elm.json".to_string());
304 }
305 None
306 }
307
308 fn find_package_cache(&self, _project_root: &Path) -> Option<PathBuf> {
309 if let Some(home) = std::env::var_os("HOME") {
310 let cache = PathBuf::from(home).join(".elm");
311 if cache.is_dir() {
312 return Some(cache);
313 }
314 }
315 None
316 }
317
318 fn indexable_extensions(&self) -> &'static [&'static str] {
319 &["elm"]
320 }
321 fn package_sources(&self, _project_root: &Path) -> Vec<crate::PackageSource> {
322 Vec::new()
323 }
324
325 fn should_skip_package_entry(&self, name: &str, is_dir: bool) -> bool {
326 use crate::traits::{has_extension, skip_dotfiles};
327 if skip_dotfiles(name) {
328 return true;
329 }
330 if is_dir && name == "elm-stuff" {
331 return true;
332 }
333 !is_dir && !has_extension(name, self.indexable_extensions())
334 }
335
336 fn discover_packages(&self, _source: &crate::PackageSource) -> Vec<(String, PathBuf)> {
337 Vec::new()
338 }
339
340 fn package_module_name(&self, entry_name: &str) -> String {
341 entry_name
342 .strip_suffix(".elm")
343 .unwrap_or(entry_name)
344 .to_string()
345 }
346
347 fn find_package_entry(&self, path: &Path) -> Option<PathBuf> {
348 if path.is_file() {
349 Some(path.to_path_buf())
350 } else {
351 None
352 }
353 }
354}
355
356#[cfg(test)]
357mod tests {
358 use super::*;
359 use crate::validate_unused_kinds_audit;
360
361 #[test]
362 fn unused_node_kinds_audit() {
363 #[rustfmt::skip]
364 let documented_unused: &[&str] = &[
365 "as_clause", "block_comment", "case", "exposed_operator", "exposed_type",
366 "exposed_union_constructors", "field_accessor_function_expr", "field_type",
367 "function_call_expr", "import", "infix_declaration", "lower_case_identifier",
368 "lower_type_name", "module", "nullary_constructor_argument_pattern",
369 "operator", "operator_as_function_expr", "operator_identifier",
370 "record_base_identifier", "record_type", "tuple_type", "type",
371 "type_annotation", "type_expression", "type_ref", "type_variable",
372 "upper_case_identifier", "upper_case_qid",
373 ];
374 validate_unused_kinds_audit(&Elm, documented_unused)
375 .expect("Elm unused node kinds audit failed");
376 }
377}