1use 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
9pub 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 self.extract_container(node, content)
80 }
81
82 fn extract_docstring(&self, _node: &Node, _content: &str) -> Option<String> {
83 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 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 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 false
169 }
170
171 fn find_stdlib(&self, _project_root: &Path) -> Option<PathBuf> {
172 None
174 }
175
176 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 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 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 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
276fn 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 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
315fn 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 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 #[test]
340 fn unused_node_kinds_audit() {
341 #[rustfmt::skip]
342 let documented_unused: &[&str] = &[
343 "class_body", "class_heritage", "class_static_block", "formal_parameters", "field_definition", "identifier", "private_property_identifier", "property_identifier", "shorthand_property_identifier", "shorthand_property_identifier_pattern", "statement_block", "statement_identifier", "switch_body", "else_clause", "finally_clause", "assignment_expression", "augmented_assignment_expression", "await_expression", "call_expression", "function_expression", "member_expression", "new_expression", "parenthesized_expression","sequence_expression", "subscript_expression", "unary_expression", "update_expression", "yield_expression", "export_clause", "export_specifier", "import", "import_attribute", "import_clause", "import_specifier", "named_imports", "namespace_export", "namespace_import", "debugger_statement", "empty_statement", "expression_statement", "generator_function", "labeled_statement", "lexical_declaration", "using_declaration", "variable_declaration", "with_statement", "jsx_expression", ];
402
403 validate_unused_kinds_audit(&JavaScript, documented_unused)
404 .expect("JavaScript unused node kinds audit failed");
405 }
406}