Skip to main content

normalize_languages/
erlang.rs

1//! Erlang language support.
2
3use crate::{Import, Language, LanguageSymbols};
4use tree_sitter::Node;
5
6/// Erlang language support.
7pub struct Erlang;
8
9impl Language for Erlang {
10    fn name(&self) -> &'static str {
11        "Erlang"
12    }
13    fn extensions(&self) -> &'static [&'static str] {
14        &["erl", "hrl"]
15    }
16    fn grammar_name(&self) -> &'static str {
17        "erlang"
18    }
19
20    fn as_symbols(&self) -> Option<&dyn LanguageSymbols> {
21        Some(self)
22    }
23
24    fn extract_imports(&self, node: &Node, content: &str) -> Vec<Import> {
25        if node.kind() != "module_attribute" {
26            return Vec::new();
27        }
28
29        let text = &content[node.byte_range()];
30        let line = node.start_position().row + 1;
31
32        // Handle -import(module, [...]).
33        if text.starts_with("-import(")
34            && let Some(start) = text.find('(')
35        {
36            let rest = &text[start + 1..];
37            if let Some(comma) = rest.find(',') {
38                let module = rest[..comma].trim().to_string();
39                return vec![Import {
40                    module,
41                    names: Vec::new(),
42                    alias: None,
43                    is_wildcard: false,
44                    is_relative: false,
45                    line,
46                }];
47            }
48        }
49
50        // Handle -include("file.hrl"). or -include_lib("app/include/file.hrl").
51        if text.starts_with("-include")
52            && let Some(start) = text.find('"')
53        {
54            let rest = &text[start + 1..];
55            if let Some(end) = rest.find('"') {
56                let module = rest[..end].to_string();
57                return vec![Import {
58                    module,
59                    names: Vec::new(),
60                    alias: None,
61                    is_wildcard: false,
62                    is_relative: text.starts_with("-include("),
63                    line,
64                }];
65            }
66        }
67
68        Vec::new()
69    }
70
71    fn format_import(&self, import: &Import, names: Option<&[&str]>) -> String {
72        // Erlang: -import(module, [func/arity, ...]).
73        let names_to_use: Vec<&str> = names
74            .map(|n| n.to_vec())
75            .unwrap_or_else(|| import.names.iter().map(|s| s.as_str()).collect());
76        if names_to_use.is_empty() {
77            format!("-import({}, []).", import.module)
78        } else {
79            format!("-import({}, [{}]).", import.module, names_to_use.join(", "))
80        }
81    }
82
83    fn extract_attributes(&self, node: &Node, content: &str) -> Vec<String> {
84        let mut attrs = Vec::new();
85        let mut prev = node.prev_sibling();
86        while let Some(sibling) = prev {
87            if sibling.kind() == "module_attribute" {
88                let text = content[sibling.byte_range()].trim();
89                if text.starts_with("-spec(")
90                    || text.starts_with("-spec ")
91                    || text.starts_with("-callback(")
92                    || text.starts_with("-deprecated(")
93                    || text.starts_with("-deprecated.")
94                {
95                    attrs.insert(0, text.to_string());
96                }
97                prev = sibling.prev_sibling();
98            } else if sibling.kind() == "comment" {
99                prev = sibling.prev_sibling();
100            } else {
101                break;
102            }
103        }
104        attrs
105    }
106
107    fn build_signature(&self, node: &Node, content: &str) -> String {
108        if node.kind() == "function_clause"
109            && let Some(name_node) = node.child_by_field_name("name")
110        {
111            let name = &content[name_node.byte_range()];
112            let arity = node
113                .child_by_field_name("arguments")
114                .map(|args| {
115                    let mut cursor = args.walk();
116                    args.children(&mut cursor).count()
117                })
118                .unwrap_or(0);
119            return format!("{}/{}", name, arity);
120        }
121        let text = &content[node.byte_range()];
122        text.lines().next().unwrap_or(text).trim().to_string()
123    }
124
125    fn is_test_symbol(&self, symbol: &crate::Symbol) -> bool {
126        let name = symbol.name.as_str();
127        match symbol.kind {
128            crate::SymbolKind::Function | crate::SymbolKind::Method => name.starts_with("test_"),
129            crate::SymbolKind::Module => name == "tests" || name == "test",
130            _ => false,
131        }
132    }
133
134    fn test_file_globs(&self) -> &'static [&'static str] {
135        &["**/*_SUITE.erl", "**/*_test.erl", "**/*_tests.erl"]
136    }
137}
138
139impl LanguageSymbols for Erlang {}
140
141#[cfg(test)]
142mod tests {
143    use super::*;
144    use crate::validate_unused_kinds_audit;
145
146    #[test]
147    fn unused_node_kinds_audit() {
148        #[rustfmt::skip]
149        let documented_unused: &[&str] = &[
150            "ann_type", "b_generator", "binary_comprehension", "bit_type_list",
151            "bit_type_unit", "block_expr", "catch_expr", "clause_body",
152            "cond_match_expr", "deprecated_module", "export_attribute",
153            "export_type_attribute", "field_type", "fun_type", "fun_type_sig",
154            "generator", "guard_clause", "import_attribute", "list_comprehension",
155            "map_comprehension", "map_generator", "match_expr", "module",
156            "pp_elif", "pp_else", "pp_endif", "pp_if", "pp_ifdef", "pp_ifndef",
157            "range_type", "remote_module", "replacement_cr_clauses",
158            "replacement_function_clauses", "ssr_definition", "try_after",
159            "try_class", "try_stack", "type_guards", "type_name", "type_sig",
160            // control flow — not extracted as symbols
161            "cr_clause",
162            "try_expr",
163            "fun_clause",
164            "if_expr",
165            "if_clause",
166            "case_expr",
167            "catch_clause",
168        ];
169        validate_unused_kinds_audit(&Erlang, documented_unused)
170            .expect("Erlang unused node kinds audit failed");
171    }
172}