Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(ast): add Lua parser support and extractor wiring (#1286)

Shawn-o78f9663f9417
diff --git a/openviking/parse/parsers/code/ast/extractor.py b/openviking/parse/parsers/code/ast/extractor.py
index 188b4b327..af2753962 100644
--- a/openviking/parse/parsers/code/ast/extractor.py
+++ b/openviking/parse/parsers/code/ast/extractor.py
@@ -29,6 +29,7 @@ _EXT_MAP: Dict[str, str] = {
".go": "go",
".cs": "csharp",
".php": "php",
+ ".lua": "lua",
}
# Language key → (module path, class name, constructor kwargs)
@@ -50,6 +51,7 @@ _EXTRACTOR_REGISTRY: Dict[str, tuple] = {
"go": ("openviking.parse.parsers.code.ast.languages.go", "GoExtractor", {}),
"csharp": ("openviking.parse.parsers.code.ast.languages.csharp", "CSharpExtractor", {}),
"php": ("openviking.parse.parsers.code.ast.languages.php", "PhpExtractor", {}),
+ "lua": ("openviking.parse.parsers.code.ast.languages.lua", "LuaExtractor", {}),
}
diff --git a/openviking/parse/parsers/code/ast/languages/lua.py b/openviking/parse/parsers/code/ast/languages/lua.py
new file mode 100644
index 000000000..dd1a01b8f
--- /dev/null
+++ b/openviking/parse/parsers/code/ast/languages/lua.py
@@ -0,0 +1,155 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Lua AST extractor using tree-sitter-lua."""
+
+from typing import Dict, List, Optional
+
+from openviking.parse.parsers.code.ast.languages.base import LanguageExtractor
+from openviking.parse.parsers.code.ast.skeleton import ClassSkeleton, CodeSkeleton, FunctionSig
+
+
+def _node_text(node, content_bytes: bytes) -> str:
+ return content_bytes[node.start_byte : node.end_byte].decode("utf-8", errors="replace")
+
+
+def _comment_text(node, content_bytes: bytes) -> str:
+ """Extract readable text from a comment node (-- or --[[ ... ]])."""
+ raw = _node_text(node, content_bytes).strip()
+ if raw.startswith("--[["):
+ inner = raw[4:]
+ if inner.endswith("]]"):
+ inner = inner[:-2]
+ lines = [line.strip() for line in inner.split("\n")]
+ return "\n".join(line for line in lines if line).strip()
+ if raw.startswith("--"):
+ return raw[2:].strip()
+ return raw
+
+
+def _preceding_doc(siblings: list, idx: int, content_bytes: bytes) -> str:
+ """Collect consecutive comment nodes immediately before siblings[idx]."""
+ lines: List[str] = []
+ i = idx - 1
+ while i >= 0 and siblings[i].type == "comment":
+ lines.insert(0, _comment_text(siblings[i], content_bytes))
+ i -= 1
+ return "\n".join(lines).strip()
+
+
+def _extract_params(params_node, content_bytes: bytes) -> str:
+ if params_node is None:
+ return ""
+ raw = _node_text(params_node, content_bytes).strip()
+ if raw.startswith("(") and raw.endswith(")"):
+ raw = raw[1:-1]
+ return raw.strip()
+
+
+def _find_require_in_call(call_node, content_bytes: bytes) -> Optional[str]:
+ """Return module name if call_node is require('mod') / require 'mod', else None."""
+ children = list(call_node.children)
+ if not children:
+ return None
+ if children[0].type != "identifier":
+ return None
+ if _node_text(children[0], content_bytes) != "require":
+ return None
+ for child in children[1:]:
+ if child.type == "arguments":
+ for arg in child.children:
+ if arg.type == "string":
+ return _node_text(arg, content_bytes).strip().strip("'\"")
+ elif child.type == "string":
+ return _node_text(child, content_bytes).strip().strip("'\"")
+ return None
+
+
+def _collect_requires(node, content_bytes: bytes) -> List[str]:
+ """Find require() calls in node, not recursing into function bodies."""
+ if node.type == "function_call":
+ mod = _find_require_in_call(node, content_bytes)
+ if mod:
+ return [mod]
+ results: List[str] = []
+ for child in node.children:
+ if child.type in ("block", "function_declaration"):
+ continue
+ results.extend(_collect_requires(child, content_bytes))
+ return results
+
+
+class LuaExtractor(LanguageExtractor):
+ def __init__(self):
+ import tree_sitter_lua as tslua
+ from tree_sitter import Language, Parser
+
+ self._language = Language(tslua.language())
+ self._parser = Parser(self._language)
+
+ def extract(self, file_name: str, content: str) -> CodeSkeleton:
+ content_bytes = content.encode("utf-8")
+ tree = self._parser.parse(content_bytes)
+ root = tree.root_node
+
+ imports: List[str] = []
+ _seen_imports: set = set()
+ _classes: Dict[str, ClassSkeleton] = {}
+ functions: List[FunctionSig] = []
+
+ siblings = list(root.children)
+ for idx, child in enumerate(siblings):
+ # --- require imports (from variable_declaration or bare function_call) ---
+ if child.type in ("variable_declaration", "function_call"):
+ for mod in _collect_requires(child, content_bytes):
+ if mod not in _seen_imports:
+ imports.append(mod)
+ _seen_imports.add(mod)
+
+ # --- function declarations (including local function ...) ---
+ if child.type == "function_declaration":
+ doc = _preceding_doc(siblings, idx, content_bytes)
+ name_node = None
+ params_node = None
+ for c in child.children:
+ if c.type in (
+ "identifier",
+ "dot_index_expression",
+ "method_index_expression",
+ ):
+ name_node = c
+ elif c.type == "parameters":
+ params_node = c
+
+ if name_node is None:
+ continue
+
+ params = _extract_params(params_node, content_bytes)
+
+ if name_node.type == "identifier":
+ name = _node_text(name_node, content_bytes)
+ functions.append(
+ FunctionSig(name=name, params=params, return_type="", docstring=doc)
+ )
+ elif name_node.type in ("dot_index_expression", "method_index_expression"):
+ # M.foo or M:foo — map to class method
+ id_children = [c for c in name_node.children if c.type == "identifier"]
+ if len(id_children) >= 2:
+ table_name = _node_text(id_children[0], content_bytes)
+ method_name = _node_text(id_children[1], content_bytes)
+ fn = FunctionSig(
+ name=method_name, params=params, return_type="", docstring=doc
+ )
+ if table_name not in _classes:
+ _classes[table_name] = ClassSkeleton(
+ name=table_name, bases=[], docstring="", methods=[]
+ )
+ _classes[table_name].methods.append(fn)
+
+ return CodeSkeleton(
+ file_name=file_name,
+ language="Lua",
+ module_doc="",
+ imports=imports,
+ classes=list(_classes.values()),
+ functions=functions,
+ )
diff --git a/pyproject.toml b/pyproject.toml
index df67f4067..d518e847e 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -69,6 +69,7 @@ dependencies = [
"tree-sitter-go>=0.23.0",
"tree-sitter-c-sharp>=0.23.0",
"tree-sitter-php>=0.23.0",
+ "tree-sitter-lua>=0.1.0",
# OpenTelemetry
"opentelemetry-api>=1.14",
"opentelemetry-sdk>=1.14",
diff --git a/tests/parse/test_ast_extractor.py b/tests/parse/test_ast_extractor.py
index 0ff82f0c6..4372f6d6a 100644
--- a/tests/parse/test_ast_extractor.py
+++ b/tests/parse/test_ast_extractor.py
@@ -1091,6 +1091,118 @@ pub fn factorial(n: u64) -> u64 {
assert "Panics if n is negative." in text
+# ---------------------------------------------------------------------------
+# Lua
+# ---------------------------------------------------------------------------
+
+
+def _lua_extractor():
+ from openviking.parse.parsers.code.ast.languages.lua import LuaExtractor
+
+ return LuaExtractor()
+
+
+class TestLuaExtractor:
+ SAMPLE = """local mathx = require("mathx")
+local util = require("util")
+
+local Calculator = {}
+
+-- Add two numbers.
+-- Returns their sum.
+function Calculator.add(a, b)
+ return a + b
+end
+
+-- Subtract b from a.
+-- Returns their difference.
+function Calculator:sub(a, b)
+ return a - b
+end
+
+-- Add two numbers at module scope.
+local function add(a, b)
+ return a + b
+end
+"""
+
+ def setup_method(self):
+ self.e = _lua_extractor()
+
+ def test_imports(self):
+ sk = self.e.extract("calculator.lua", self.SAMPLE)
+ assert "mathx" in sk.imports
+ assert "util" in sk.imports
+ # deduplicated imports should remain unique
+ assert sk.imports.count("mathx") == 1
+
+ def test_class_extracted(self):
+ sk = self.e.extract("calculator.lua", self.SAMPLE)
+ names = {c.name for c in sk.classes}
+ assert "Calculator" in names
+
+ def test_methods_extracted(self):
+ sk = self.e.extract("calculator.lua", self.SAMPLE)
+ cls = next(c for c in sk.classes if c.name == "Calculator")
+ method_names = {m.name for m in cls.methods}
+ assert "add" in method_names
+ assert "sub" in method_names
+
+ def test_method_docstring(self):
+ sk = self.e.extract("calculator.lua", self.SAMPLE)
+ cls = next(c for c in sk.classes if c.name == "Calculator")
+ methods = {m.name: m for m in cls.methods}
+ assert "Add two numbers." in methods["add"].docstring
+ assert "Returns their sum." in methods["add"].docstring
+ assert "Subtract b from a." in methods["sub"].docstring
+
+ def test_function_extracted(self):
+ sk = self.e.extract("calculator.lua", self.SAMPLE)
+ names = {f.name for f in sk.functions}
+ assert "add" in names
+
+ def test_function_docstring(self):
+ sk = self.e.extract("calculator.lua", self.SAMPLE)
+ fns = {f.name: f for f in sk.functions}
+ assert "Add two numbers at module scope." in fns["add"].docstring
+
+ def test_to_text_compact(self):
+ sk = self.e.extract("calculator.lua", self.SAMPLE)
+ text = sk.to_text(verbose=False)
+ assert "# calculator.lua [Lua]" in text
+ assert "Calculator" in text
+ assert "add" in text
+ # only first line of multi-line docstring in compact mode
+ assert "Returns their difference." not in text
+
+ def test_to_text_verbose(self):
+ sk = self.e.extract("calculator.lua", self.SAMPLE)
+ text = sk.to_text(verbose=True)
+ assert "# calculator.lua [Lua]" in text
+ assert "Returns their sum." in text
+ assert "Returns their difference." in text
+
+ def test_dot_method_params(self):
+ code = "function M.compute(x, y, z)\n return x + y + z\nend\n"
+ sk = self.e.extract("m.lua", code)
+ cls = next(c for c in sk.classes if c.name == "M")
+ methods = {m.name: m for m in cls.methods}
+ assert "compute" in methods
+ assert "x, y, z" in methods["compute"].params
+
+ def test_colon_method_not_in_functions(self):
+ code = "function M:init()\nend\nfunction standalone()\nend\n"
+ sk = self.e.extract("m.lua", code)
+ fn_names = {f.name for f in sk.functions}
+ assert "standalone" in fn_names
+ assert "init" not in fn_names
+
+ def test_bare_require(self):
+ code = "require 'inspect'\nfunction foo()\nend\n"
+ sk = self.e.extract("m.lua", code)
+ assert "inspect" in sk.imports
+
+
# ---------------------------------------------------------------------------
# Skeleton.to_text() — verbose vs compact
# ---------------------------------------------------------------------------
@@ -1296,9 +1408,16 @@ class TestASTExtractorDispatch:
assert "# util.cs [C#]" in text
assert "class Util" in text
+ def test_lua_dispatch(self):
+ code = "-- Say hello.\nfunction greet(name)\n return 'Hi ' .. name\nend\n"
+ text = self.extractor.extract_skeleton("hello.lua", code)
+ assert text is not None
+ assert "# hello.lua [Lua]" in text
+ assert "greet" in text
+
def test_unknown_extension_returns_none(self):
code = "def foo(x): pass\nclass Bar: pass\n"
- result = self.extractor.extract_skeleton("script.lua", code)
+ result = self.extractor.extract_skeleton("script.xyz123", code)
assert result is None
def test_never_raises(self):
@@ -1315,3 +1434,5 @@ class TestASTExtractorDispatch:
verbose = self.extractor.extract_skeleton("m.py", code, verbose=True)
assert "Detail here." not in compact
assert "Detail here." in verbose
+
+