Skip to main content

normalize_languages/
rescript.rs

1//! ReScript language support.
2
3use crate::external_packages::ResolvedPackage;
4use crate::{Export, Import, Language, Symbol, SymbolKind, Visibility, VisibilityMechanism};
5use std::path::{Path, PathBuf};
6use tree_sitter::Node;
7
8/// ReScript language support.
9pub struct ReScript;
10
11impl Language for ReScript {
12    fn name(&self) -> &'static str {
13        "ReScript"
14    }
15    fn extensions(&self) -> &'static [&'static str] {
16        &["res", "resi"]
17    }
18    fn grammar_name(&self) -> &'static str {
19        "rescript"
20    }
21
22    fn has_symbols(&self) -> bool {
23        true
24    }
25
26    fn container_kinds(&self) -> &'static [&'static str] {
27        &["module_declaration"]
28    }
29
30    fn function_kinds(&self) -> &'static [&'static str] {
31        &["let_binding", "external_declaration"]
32    }
33
34    fn type_kinds(&self) -> &'static [&'static str] {
35        &["type_declaration"]
36    }
37
38    fn import_kinds(&self) -> &'static [&'static str] {
39        &["open_statement"]
40    }
41
42    fn public_symbol_kinds(&self) -> &'static [&'static str] {
43        &["let_binding", "type_declaration", "module_declaration"]
44    }
45
46    fn visibility_mechanism(&self) -> VisibilityMechanism {
47        VisibilityMechanism::AllPublic
48    }
49
50    fn extract_public_symbols(&self, node: &Node, content: &str) -> Vec<Export> {
51        match node.kind() {
52            "let_binding" | "external_declaration" => {
53                if let Some(name) = self.node_name(node, content) {
54                    return vec![Export {
55                        name: name.to_string(),
56                        kind: SymbolKind::Function,
57                        line: node.start_position().row + 1,
58                    }];
59                }
60            }
61            "type_declaration" => {
62                if let Some(name) = self.node_name(node, content) {
63                    return vec![Export {
64                        name: name.to_string(),
65                        kind: SymbolKind::Type,
66                        line: node.start_position().row + 1,
67                    }];
68                }
69            }
70            "module_declaration" => {
71                if let Some(name) = self.node_name(node, content) {
72                    return vec![Export {
73                        name: name.to_string(),
74                        kind: SymbolKind::Module,
75                        line: node.start_position().row + 1,
76                    }];
77                }
78            }
79            _ => {}
80        }
81        Vec::new()
82    }
83
84    fn scope_creating_kinds(&self) -> &'static [&'static str] {
85        &["let_binding", "module_declaration", "block"]
86    }
87
88    fn control_flow_kinds(&self) -> &'static [&'static str] {
89        &["if_expression", "switch_expression"]
90    }
91
92    fn complexity_nodes(&self) -> &'static [&'static str] {
93        &["if_expression", "switch_expression", "switch_match"]
94    }
95
96    fn nesting_nodes(&self) -> &'static [&'static str] {
97        &[
98            "if_expression",
99            "switch_expression",
100            "block",
101            "module_declaration",
102        ]
103    }
104
105    fn signature_suffix(&self) -> &'static str {
106        ""
107    }
108
109    fn extract_function(&self, node: &Node, content: &str, _in_container: bool) -> Option<Symbol> {
110        match node.kind() {
111            "let_binding" | "external_declaration" => {
112                let name = self.node_name(node, content)?;
113                let text = &content[node.byte_range()];
114                let first_line = text.lines().next().unwrap_or(text);
115
116                Some(Symbol {
117                    name: name.to_string(),
118                    kind: SymbolKind::Function,
119                    signature: first_line.trim().to_string(),
120                    docstring: None,
121                    attributes: Vec::new(),
122                    start_line: node.start_position().row + 1,
123                    end_line: node.end_position().row + 1,
124                    visibility: Visibility::Public,
125                    children: Vec::new(),
126                    is_interface_impl: false,
127                    implements: Vec::new(),
128                })
129            }
130            _ => None,
131        }
132    }
133
134    fn extract_container(&self, node: &Node, content: &str) -> Option<Symbol> {
135        if node.kind() != "module_declaration" {
136            return None;
137        }
138
139        let name = self.node_name(node, content)?;
140        let text = &content[node.byte_range()];
141        let first_line = text.lines().next().unwrap_or(text);
142
143        Some(Symbol {
144            name: name.to_string(),
145            kind: SymbolKind::Module,
146            signature: first_line.trim().to_string(),
147            docstring: None,
148            attributes: Vec::new(),
149            start_line: node.start_position().row + 1,
150            end_line: node.end_position().row + 1,
151            visibility: Visibility::Public,
152            children: Vec::new(),
153            is_interface_impl: false,
154            implements: Vec::new(),
155        })
156    }
157
158    fn extract_type(&self, node: &Node, content: &str) -> Option<Symbol> {
159        if node.kind() != "type_declaration" {
160            return None;
161        }
162
163        let name = self.node_name(node, content)?;
164        let text = &content[node.byte_range()];
165        let first_line = text.lines().next().unwrap_or(text);
166
167        Some(Symbol {
168            name: name.to_string(),
169            kind: SymbolKind::Type,
170            signature: first_line.trim().to_string(),
171            docstring: None,
172            attributes: Vec::new(),
173            start_line: node.start_position().row + 1,
174            end_line: node.end_position().row + 1,
175            visibility: Visibility::Public,
176            children: Vec::new(),
177            is_interface_impl: false,
178            implements: Vec::new(),
179        })
180    }
181
182    fn extract_docstring(&self, _node: &Node, _content: &str) -> Option<String> {
183        None
184    }
185
186    fn extract_attributes(&self, _node: &Node, _content: &str) -> Vec<String> {
187        Vec::new()
188    }
189
190    fn extract_imports(&self, node: &Node, content: &str) -> Vec<Import> {
191        if node.kind() != "open_statement" {
192            return Vec::new();
193        }
194
195        let text = &content[node.byte_range()];
196        vec![Import {
197            module: text.trim().to_string(),
198            names: Vec::new(),
199            alias: None,
200            is_wildcard: true,
201            is_relative: false,
202            line: node.start_position().row + 1,
203        }]
204    }
205
206    fn format_import(&self, import: &Import, _names: Option<&[&str]>) -> String {
207        // ReScript: open Module
208        format!("open {}", import.module)
209    }
210
211    fn is_public(&self, _node: &Node, _content: &str) -> bool {
212        true
213    }
214    fn get_visibility(&self, _node: &Node, _content: &str) -> Visibility {
215        Visibility::Public
216    }
217
218    fn is_test_symbol(&self, symbol: &crate::Symbol) -> bool {
219        let name = symbol.name.as_str();
220        match symbol.kind {
221            crate::SymbolKind::Function | crate::SymbolKind::Method => name.starts_with("test_"),
222            crate::SymbolKind::Module => name == "tests" || name == "test",
223            _ => false,
224        }
225    }
226
227    fn embedded_content(&self, _node: &Node, _content: &str) -> Option<crate::EmbeddedBlock> {
228        None
229    }
230
231    fn container_body<'a>(&self, node: &'a Node<'a>) -> Option<Node<'a>> {
232        node.child_by_field_name("body")
233    }
234
235    fn body_has_docstring(&self, _body: &Node, _content: &str) -> bool {
236        false
237    }
238
239    fn node_name<'a>(&self, node: &Node, content: &'a str) -> Option<&'a str> {
240        node.child_by_field_name("name")
241            .map(|n| &content[n.byte_range()])
242    }
243
244    fn file_path_to_module_name(&self, path: &Path) -> Option<String> {
245        let ext = path.extension()?.to_str()?;
246        if !["res", "resi"].contains(&ext) {
247            return None;
248        }
249        let stem = path.file_stem()?.to_str()?;
250        Some(stem.to_string())
251    }
252
253    fn module_name_to_paths(&self, module: &str) -> Vec<String> {
254        vec![format!("{}.res", module), format!("{}.resi", module)]
255    }
256
257    fn lang_key(&self) -> &'static str {
258        "rescript"
259    }
260
261    fn is_stdlib_import(&self, import_name: &str, _project_root: &Path) -> bool {
262        import_name.starts_with("Belt")
263            || import_name.starts_with("Js.")
264            || import_name == "Array"
265            || import_name == "List"
266            || import_name == "Option"
267    }
268
269    fn find_stdlib(&self, _project_root: &Path) -> Option<PathBuf> {
270        None
271    }
272    fn resolve_local_import(&self, _: &str, _: &Path, _: &Path) -> Option<PathBuf> {
273        None
274    }
275    fn resolve_external_import(&self, _: &str, _: &Path) -> Option<ResolvedPackage> {
276        None
277    }
278    fn get_version(&self, _: &Path) -> Option<String> {
279        None
280    }
281    fn find_package_cache(&self, _: &Path) -> Option<PathBuf> {
282        None
283    }
284    fn indexable_extensions(&self) -> &'static [&'static str] {
285        &["res", "resi"]
286    }
287    fn package_sources(&self, _: &Path) -> Vec<crate::PackageSource> {
288        Vec::new()
289    }
290
291    fn should_skip_package_entry(&self, name: &str, is_dir: bool) -> bool {
292        use crate::traits::{has_extension, skip_dotfiles};
293        if skip_dotfiles(name) {
294            return true;
295        }
296        !is_dir && !has_extension(name, self.indexable_extensions())
297    }
298
299    fn discover_packages(&self, _: &crate::PackageSource) -> Vec<(String, PathBuf)> {
300        Vec::new()
301    }
302
303    fn package_module_name(&self, entry_name: &str) -> String {
304        entry_name
305            .strip_suffix(".res")
306            .or_else(|| entry_name.strip_suffix(".resi"))
307            .unwrap_or(entry_name)
308            .to_string()
309    }
310
311    fn find_package_entry(&self, path: &Path) -> Option<PathBuf> {
312        if path.is_file() {
313            Some(path.to_path_buf())
314        } else {
315            None
316        }
317    }
318}
319
320#[cfg(test)]
321mod tests {
322    use super::*;
323    use crate::validate_unused_kinds_audit;
324
325    #[test]
326    fn unused_node_kinds_audit() {
327        #[rustfmt::skip]
328        let documented_unused: &[&str] = &[
329            // Expression nodes
330            "try_expression", "ternary_expression", "while_expression", "for_expression",
331            "call_expression", "pipe_expression", "sequence_expression", "await_expression",
332            "coercion_expression", "lazy_expression", "assert_expression",
333            "parenthesized_expression", "unary_expression", "binary_expression",
334            "subscript_expression", "member_expression", "mutation_expression",
335            "extension_expression",
336            // Type nodes
337            "type_identifier", "type_identifier_path", "unit_type", "generic_type",
338            "function_type", "polyvar_type", "polymorphic_type", "tuple_type",
339            "record_type", "record_type_field", "object_type", "variant_type",
340            "abstract_type", "type_arguments", "type_parameters", "type_constraint",
341            "type_annotation", "type_binding", "type_spread", "constrain_type",
342            "as_aliasing_type", "function_type_parameters",
343            // Module nodes
344            "parenthesized_module_expression", "module_type_constraint", "module_type_annotation",
345            "module_type_of", "constrain_module", "module_identifier", "module_identifier_path",
346            "module_pack", "module_unpack", "module_binding",
347            // Declaration nodes
348            "let_declaration", "exception_declaration", "variant_declaration",
349            "polyvar_declaration", "include_statement",
350            // JSX
351            "jsx_expression", "jsx_identifier", "nested_jsx_identifier",
352            // Pattern matching
353            "exception_pattern", "polyvar_type_pattern",
354            // Identifiers
355            "value_identifier", "value_identifier_path", "variant_identifier",
356            "nested_variant_identifier", "polyvar_identifier", "property_identifier",
357            "extension_identifier", "decorator_identifier",
358            // Clauses
359            "else_clause", "else_if_clause",
360            // Other
361            "function", "expression_statement", "formal_parameters",
362        ];
363        validate_unused_kinds_audit(&ReScript, documented_unused)
364            .expect("ReScript unused node kinds audit failed");
365    }
366}