use crate::docstring::extract_preceding_prefix_comments;
use crate::traits::{ImportSpec, ModuleId, ModuleResolver, Resolution, ResolverConfig};
use crate::{Import, Language, LanguageSymbols, Visibility};
use std::path::Path;
use tree_sitter::Node;
pub struct Lua;
impl Language for Lua {
fn name(&self) -> &'static str {
"Lua"
}
fn extensions(&self) -> &'static [&'static str] {
&["lua"]
}
fn grammar_name(&self) -> &'static str {
"lua"
}
fn as_symbols(&self) -> Option<&dyn LanguageSymbols> {
Some(self)
}
fn signature_suffix(&self) -> &'static str {
" end"
}
fn build_signature(&self, node: &Node, content: &str) -> String {
let name = match self.node_name(node, content) {
Some(n) => n,
None => {
let text = &content[node.byte_range()];
return text.lines().next().unwrap_or(text).trim().to_string();
}
};
let params = node
.child_by_field_name("parameters")
.map(|p| content[p.byte_range()].to_string())
.unwrap_or_else(|| "()".to_string());
let text = &content[node.byte_range()];
let is_local = text.trim_start().starts_with("local ");
let keyword = if is_local {
"local function"
} else {
"function"
};
format!("{} {}{}", keyword, name, params)
}
fn extract_imports(&self, node: &Node, content: &str) -> Vec<Import> {
if node.kind() != "function_call" {
return Vec::new();
}
let func_name = node
.child_by_field_name("name")
.map(|n| &content[n.byte_range()]);
if func_name != Some("require") {
return Vec::new();
}
if let Some(args) = node.child_by_field_name("arguments") {
let mut cursor = args.walk();
for child in args.children(&mut cursor) {
if child.kind() == "string" {
let module = content[child.byte_range()]
.trim_matches(|c| c == '"' || c == '\'' || c == '[' || c == ']')
.to_string();
return vec![Import {
module,
names: Vec::new(),
alias: None,
is_wildcard: false,
is_relative: false,
line: node.start_position().row + 1,
}];
}
}
}
Vec::new()
}
fn format_import(&self, import: &Import, _names: Option<&[&str]>) -> String {
format!("require(\"{}\")", import.module)
}
fn get_visibility(&self, node: &Node, content: &str) -> Visibility {
let text = &content[node.byte_range()];
if text.trim_start().starts_with("local ") {
Visibility::Private
} else {
Visibility::Public
}
}
fn is_test_symbol(&self, symbol: &crate::Symbol) -> bool {
let name = symbol.name.as_str();
match symbol.kind {
crate::SymbolKind::Function | crate::SymbolKind::Method => name.starts_with("test_"),
crate::SymbolKind::Module => name == "tests" || name == "test",
_ => false,
}
}
fn extract_docstring(&self, node: &Node, content: &str) -> Option<String> {
extract_preceding_prefix_comments(node, content, "---")
}
fn container_body<'a>(&self, node: &'a Node<'a>) -> Option<Node<'a>> {
node.child_by_field_name("body")
}
fn module_resolver(&self) -> Option<&dyn ModuleResolver> {
static RESOLVER: LuaModuleResolver = LuaModuleResolver;
Some(&RESOLVER)
}
}
impl LanguageSymbols for Lua {}
pub struct LuaModuleResolver;
impl ModuleResolver for LuaModuleResolver {
fn workspace_config(&self, root: &Path) -> ResolverConfig {
ResolverConfig {
workspace_root: root.to_path_buf(),
path_mappings: Vec::new(),
search_roots: vec![root.to_path_buf()],
}
}
fn module_of_file(&self, root: &Path, file: &Path, _cfg: &ResolverConfig) -> Vec<ModuleId> {
let ext = file.extension().and_then(|e| e.to_str()).unwrap_or("");
if ext != "lua" {
return Vec::new();
}
if let Ok(rel) = file.strip_prefix(root) {
let rel_str = rel.to_str().unwrap_or("");
let module = if rel_str.ends_with("/init.lua") || rel_str == "init.lua" {
rel_str
.trim_end_matches("/init.lua")
.trim_end_matches("init.lua")
.trim_end_matches('/')
.replace('/', ".")
} else {
rel_str.trim_end_matches(".lua").replace('/', ".")
};
if !module.is_empty() {
return vec![ModuleId {
canonical_path: module,
}];
}
}
Vec::new()
}
fn resolve(&self, from_file: &Path, spec: &ImportSpec, cfg: &ResolverConfig) -> Resolution {
let ext = from_file.extension().and_then(|e| e.to_str()).unwrap_or("");
if ext != "lua" {
return Resolution::NotApplicable;
}
let raw = &spec.raw;
let path_part = raw.replace('.', "/");
let exported_name = raw.rsplit('.').next().unwrap_or(raw).to_string();
let direct = cfg.workspace_root.join(format!("{}.lua", path_part));
if direct.exists() {
return Resolution::Resolved(direct, exported_name);
}
let init = cfg.workspace_root.join(format!("{}/init.lua", path_part));
if init.exists() {
return Resolution::Resolved(init, exported_name);
}
Resolution::NotFound
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::validate_unused_kinds_audit;
#[test]
fn unused_node_kinds_audit() {
#[rustfmt::skip]
let documented_unused: &[&str] = &[ "binary_expression", "block",
"bracket_index_expression", "else_statement",
"empty_statement", "for_generic_clause",
"for_numeric_clause", "identifier", "label_statement", "parenthesized_expression", "table_constructor",
"unary_expression", "vararg_expression", "variable_declaration",
"return_statement",
"while_statement",
"elseif_statement",
"for_statement",
"goto_statement",
"do_statement",
"if_statement",
"break_statement",
"repeat_statement",
"function_call",
];
validate_unused_kinds_audit(&Lua, documented_unused)
.expect("Lua unused node kinds audit failed");
}
}