Skip to main content

normalize_languages/
javascript.rs

1//! JavaScript language support.
2
3use crate::ecmascript;
4use crate::external_packages::ResolvedPackage;
5use crate::{Export, Import, Language, Symbol, Visibility, VisibilityMechanism};
6use std::path::{Path, PathBuf};
7use tree_sitter::Node;
8
9/// JavaScript language support.
10pub struct JavaScript;
11
12impl Language for JavaScript {
13    fn name(&self) -> &'static str {
14        "JavaScript"
15    }
16    fn extensions(&self) -> &'static [&'static str] {
17        &["js", "mjs", "cjs", "jsx"]
18    }
19    fn grammar_name(&self) -> &'static str {
20        "javascript"
21    }
22
23    fn has_symbols(&self) -> bool {
24        true
25    }
26
27    fn container_kinds(&self) -> &'static [&'static str] {
28        ecmascript::JS_CONTAINER_KINDS
29    }
30    fn function_kinds(&self) -> &'static [&'static str] {
31        ecmascript::JS_FUNCTION_KINDS
32    }
33    fn type_kinds(&self) -> &'static [&'static str] {
34        ecmascript::JS_TYPE_KINDS
35    }
36    fn import_kinds(&self) -> &'static [&'static str] {
37        ecmascript::IMPORT_KINDS
38    }
39    fn public_symbol_kinds(&self) -> &'static [&'static str] {
40        ecmascript::PUBLIC_SYMBOL_KINDS
41    }
42    fn visibility_mechanism(&self) -> VisibilityMechanism {
43        VisibilityMechanism::ExplicitExport
44    }
45    fn scope_creating_kinds(&self) -> &'static [&'static str] {
46        ecmascript::SCOPE_CREATING_KINDS
47    }
48    fn control_flow_kinds(&self) -> &'static [&'static str] {
49        ecmascript::CONTROL_FLOW_KINDS
50    }
51    fn complexity_nodes(&self) -> &'static [&'static str] {
52        ecmascript::COMPLEXITY_NODES
53    }
54    fn nesting_nodes(&self) -> &'static [&'static str] {
55        ecmascript::NESTING_NODES
56    }
57
58    fn signature_suffix(&self) -> &'static str {
59        " {}"
60    }
61
62    fn extract_function(&self, node: &Node, content: &str, in_container: bool) -> Option<Symbol> {
63        let name = self.node_name(node, content)?;
64        Some(ecmascript::extract_function(
65            node,
66            content,
67            in_container,
68            name,
69        ))
70    }
71
72    fn extract_container(&self, node: &Node, content: &str) -> Option<Symbol> {
73        let name = self.node_name(node, content)?;
74        Some(ecmascript::extract_container(node, content, name))
75    }
76
77    fn extract_type(&self, node: &Node, content: &str) -> Option<Symbol> {
78        // JS classes are the only type-like construct
79        self.extract_container(node, content)
80    }
81
82    fn extract_docstring(&self, _node: &Node, _content: &str) -> Option<String> {
83        // JS doesn't have standardized docstrings (JSDoc would require comment parsing)
84        None
85    }
86
87    fn extract_attributes(&self, _node: &Node, _content: &str) -> Vec<String> {
88        Vec::new()
89    }
90
91    fn extract_imports(&self, node: &Node, content: &str) -> Vec<Import> {
92        ecmascript::extract_imports(node, content)
93    }
94
95    fn format_import(&self, import: &Import, names: Option<&[&str]>) -> String {
96        ecmascript::format_import(import, names)
97    }
98
99    fn extract_public_symbols(&self, node: &Node, content: &str) -> Vec<Export> {
100        ecmascript::extract_public_symbols(node, content)
101    }
102
103    fn is_public(&self, _node: &Node, _content: &str) -> bool {
104        // JS uses export statements, not visibility modifiers on declarations
105        true
106    }
107
108    fn get_visibility(&self, _node: &Node, _content: &str) -> Visibility {
109        Visibility::Public
110    }
111
112    fn is_test_symbol(&self, symbol: &crate::Symbol) -> bool {
113        {
114            let name = symbol.name.as_str();
115            match symbol.kind {
116                crate::SymbolKind::Function | crate::SymbolKind::Method => {
117                    name.starts_with("test_")
118                        || name.starts_with("Test")
119                        || name == "describe"
120                        || name == "it"
121                        || name == "test"
122                }
123                crate::SymbolKind::Module => {
124                    name == "tests" || name == "test" || name == "__tests__"
125                }
126                _ => false,
127            }
128        }
129    }
130
131    fn embedded_content(&self, _node: &Node, _content: &str) -> Option<crate::EmbeddedBlock> {
132        None
133    }
134
135    fn container_body<'a>(&self, node: &'a Node<'a>) -> Option<Node<'a>> {
136        node.child_by_field_name("body")
137    }
138
139    fn body_has_docstring(&self, _body: &Node, _content: &str) -> bool {
140        false
141    }
142
143    fn node_name<'a>(&self, node: &Node, content: &'a str) -> Option<&'a str> {
144        let name_node = node.child_by_field_name("name")?;
145        Some(&content[name_node.byte_range()])
146    }
147
148    fn file_path_to_module_name(&self, path: &Path) -> Option<String> {
149        let ext = path.extension()?.to_str()?;
150        if !["js", "mjs", "cjs", "jsx"].contains(&ext) {
151            return None;
152        }
153        // For relative imports, just use the path without extension
154        let stem = path.with_extension("");
155        Some(stem.to_string_lossy().to_string())
156    }
157
158    fn module_name_to_paths(&self, module: &str) -> Vec<String> {
159        vec![
160            format!("{}.js", module),
161            format!("{}.mjs", module),
162            format!("{}/index.js", module),
163        ]
164    }
165
166    fn is_stdlib_import(&self, _import_name: &str, _project_root: &Path) -> bool {
167        // Node.js built-ins (could check against a list, but we don't have source for them)
168        false
169    }
170
171    fn find_stdlib(&self, _project_root: &Path) -> Option<PathBuf> {
172        // Node.js stdlib is compiled into the runtime
173        None
174    }
175
176    // === Import Resolution ===
177
178    fn lang_key(&self) -> &'static str {
179        "js"
180    }
181
182    fn resolve_local_import(
183        &self,
184        module: &str,
185        current_file: &Path,
186        _project_root: &Path,
187    ) -> Option<PathBuf> {
188        ecmascript::resolve_local_import(module, current_file, ecmascript::JS_EXTENSIONS)
189    }
190
191    fn resolve_external_import(
192        &self,
193        import_name: &str,
194        project_root: &Path,
195    ) -> Option<ResolvedPackage> {
196        ecmascript::resolve_external_import(import_name, project_root)
197    }
198
199    fn get_version(&self, _project_root: &Path) -> Option<String> {
200        ecmascript::get_version()
201    }
202
203    fn find_package_cache(&self, project_root: &Path) -> Option<PathBuf> {
204        ecmascript::find_package_cache(project_root)
205    }
206
207    fn indexable_extensions(&self) -> &'static [&'static str] {
208        &["js", "mjs", "cjs"]
209    }
210
211    fn package_sources(&self, project_root: &Path) -> Vec<crate::PackageSource> {
212        use crate::{PackageSource, PackageSourceKind};
213        let mut sources = Vec::new();
214        if let Some(cache) = self.find_package_cache(project_root) {
215            sources.push(PackageSource {
216                name: "node_modules",
217                path: cache,
218                kind: PackageSourceKind::NpmScoped,
219                version_specific: false,
220            });
221        }
222        // Also check for Deno cache
223        if let Some(deno_cache) = ecmascript::find_deno_cache() {
224            let npm_cache = deno_cache.join("npm").join("registry.npmjs.org");
225            if npm_cache.is_dir() {
226                sources.push(PackageSource {
227                    name: "deno-npm",
228                    path: npm_cache,
229                    kind: PackageSourceKind::Deno,
230                    version_specific: false,
231                });
232            }
233        }
234        sources
235    }
236
237    fn should_skip_package_entry(&self, name: &str, is_dir: bool) -> bool {
238        use crate::traits::{has_extension, skip_dotfiles};
239        if skip_dotfiles(name) {
240            return true;
241        }
242        // Skip common non-source dirs
243        if is_dir && (name == "node_modules" || name == ".bin" || name == "test" || name == "tests")
244        {
245            return true;
246        }
247        !is_dir && !has_extension(name, self.indexable_extensions())
248    }
249
250    fn discover_packages(&self, source: &crate::PackageSource) -> Vec<(String, PathBuf)> {
251        match source.kind {
252            crate::PackageSourceKind::NpmScoped => self.discover_npm_scoped_packages(&source.path),
253            crate::PackageSourceKind::Deno => discover_deno_packages(&source.path),
254            _ => Vec::new(),
255        }
256    }
257
258    fn package_module_name(&self, entry_name: &str) -> String {
259        // Strip common JS extensions
260        for ext in &[".js", ".mjs", ".cjs"] {
261            if let Some(name) = entry_name.strip_suffix(ext) {
262                return name.to_string();
263            }
264        }
265        entry_name.to_string()
266    }
267
268    fn find_package_entry(&self, path: &Path) -> Option<PathBuf> {
269        if path.is_file() {
270            return Some(path.to_path_buf());
271        }
272        ecmascript::find_package_entry(path)
273    }
274}
275
276/// Discover packages in Deno npm cache (package/version/ structure with scoped packages).
277fn discover_deno_packages(source_path: &Path) -> Vec<(String, PathBuf)> {
278    let entries = match std::fs::read_dir(source_path) {
279        Ok(e) => e,
280        Err(_) => return Vec::new(),
281    };
282
283    let mut packages = Vec::new();
284
285    for entry in entries.flatten() {
286        let path = entry.path();
287        let name = entry.file_name().to_string_lossy().to_string();
288
289        if !path.is_dir() {
290            continue;
291        }
292
293        // Handle scoped packages (@scope/name)
294        if name.starts_with('@') {
295            if let Ok(scoped) = std::fs::read_dir(&path) {
296                for scoped_entry in scoped.flatten() {
297                    let scoped_path = scoped_entry.path();
298                    let scoped_name =
299                        format!("{}/{}", name, scoped_entry.file_name().to_string_lossy());
300                    if let Some((pkg_name, pkg_path)) =
301                        find_deno_version_dir(&scoped_path, &scoped_name)
302                    {
303                        packages.push((pkg_name, pkg_path));
304                    }
305                }
306            }
307        } else if let Some((pkg_name, pkg_path)) = find_deno_version_dir(&path, &name) {
308            packages.push((pkg_name, pkg_path));
309        }
310    }
311
312    packages
313}
314
315/// Find the latest version directory in a Deno package directory.
316fn find_deno_version_dir(pkg_path: &Path, pkg_name: &str) -> Option<(String, PathBuf)> {
317    let versions: Vec<_> = std::fs::read_dir(pkg_path)
318        .ok()?
319        .flatten()
320        .filter(|e| e.path().is_dir())
321        .collect();
322
323    if versions.is_empty() {
324        return None;
325    }
326
327    // Use the last version (sorted lexically, usually latest)
328    let version_dir = versions.last()?.path();
329    Some((pkg_name.to_string(), version_dir))
330}
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335    use crate::validate_unused_kinds_audit;
336
337    /// Documents node kinds that exist in the JavaScript grammar but aren't used in trait methods.
338    /// Run `cross_check_node_kinds` in registry.rs to see all potentially useful kinds.
339    #[test]
340    fn unused_node_kinds_audit() {
341        #[rustfmt::skip]
342        let documented_unused: &[&str] = &[
343            // STRUCTURAL
344            "class_body",              // class body block
345            "class_heritage",          // extends clause
346            "class_static_block",      // static { }
347            "formal_parameters",       // function params
348            "field_definition",        // class field
349            "identifier",              // too common
350            "private_property_identifier", // #field
351            "property_identifier",     // obj.prop
352            "shorthand_property_identifier", // { x } shorthand
353            "shorthand_property_identifier_pattern", // destructuring shorthand
354            "statement_block",         // { }
355            "statement_identifier",    // label name
356            "switch_body",             // switch cases
357
358            // CLAUSE
359            "else_clause",             // else branch
360            "finally_clause",          // finally block
361
362            // EXPRESSION
363            "assignment_expression",   // x = y
364            "augmented_assignment_expression", // x += y
365            "await_expression",        // await foo
366            "call_expression",         // foo()
367            "function_expression",     // function() {}
368            "member_expression",       // foo.bar
369            "new_expression",          // new Foo()
370            "parenthesized_expression",// (expr)
371            "sequence_expression",     // a, b
372            "subscript_expression",    // arr[i]
373            "unary_expression",        // -x, !x
374            "update_expression",       // x++
375            "yield_expression",        // yield x
376
377            // IMPORT/EXPORT DETAILS
378            "export_clause",           // export { a, b }
379            "export_specifier",        // export { a as b }
380            "import",                  // import keyword
381            "import_attribute",        // import attributes
382            "import_clause",           // import clause
383            "import_specifier",        // import { a }
384            "named_imports",           // { a, b }
385            "namespace_export",        // export * as ns
386            "namespace_import",        // import * as ns
387
388            // DECLARATION
389            "debugger_statement",      // debugger;
390            "empty_statement",         // ;
391            "expression_statement",    // expr;
392            "generator_function",      // function* foo
393            "labeled_statement",       // label: stmt
394            "lexical_declaration",     // let/const
395            "using_declaration",       // using x = ...
396            "variable_declaration",    // var x
397            "with_statement",          // with (obj) - deprecated
398
399            // JSX
400            "jsx_expression",          // {expr} in JSX
401        ];
402
403        validate_unused_kinds_audit(&JavaScript, documented_unused)
404            .expect("JavaScript unused node kinds audit failed");
405    }
406}