Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(ast): add PHP tree-sitter support (#1087)
yangxinxin-7a0460487a4b6
diff --git a/openviking/parse/parsers/code/ast/extractor.py b/openviking/parse/parsers/code/ast/extractor.pyindex 3e0f7826b..188b4b327 100644--- a/openviking/parse/parsers/code/ast/extractor.py+++ b/openviking/parse/parsers/code/ast/extractor.py@@ -28,6 +28,7 @@ _EXT_MAP: Dict[str, str] = {".rs": "rust",".go": "go",".cs": "csharp",+ ".php": "php",}# Language key → (module path, class name, constructor kwargs)@@ -48,6 +49,7 @@ _EXTRACTOR_REGISTRY: Dict[str, tuple] = {"rust": ("openviking.parse.parsers.code.ast.languages.rust", "RustExtractor", {}),"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", {}),}diff --git a/openviking/parse/parsers/code/ast/languages/php.py b/openviking/parse/parsers/code/ast/languages/php.pynew file mode 100644index 000000000..b1ef23ad3--- /dev/null+++ b/openviking/parse/parsers/code/ast/languages/php.py@@ -0,0 +1,334 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""PHP AST extractor using tree-sitter-php."""++from __future__ import annotations++from typing import 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 _parse_comment(raw: str) -> str:+ raw = raw.strip()+ if raw.startswith("/**") or raw.startswith("/*"):+ raw = raw[3:] if raw.startswith("/**") else raw[2:]+ if raw.endswith("*/"):+ raw = raw[:-2]+ lines = [l.strip().lstrip("*").strip() for l in raw.split("\n")]+ return "\n".join(l for l in lines if l).strip()+ if raw.startswith("//"):+ return raw[2:].strip()+ if raw.startswith("#"):+ return raw[1:].strip()+ return raw+++def _preceding_doc(siblings: list, idx: int, content_bytes: bytes) -> str:+ if idx <= 0:+ return ""++ adjacent: List[str] = []+ current_start_row = siblings[idx].start_point[0]+ i = idx - 1+ while i >= 0 and siblings[i].type == "comment":+ if current_start_row - siblings[i].end_point[0] > 1:+ break+ adjacent.insert(0, _node_text(siblings[i], content_bytes).strip())+ current_start_row = siblings[i].start_point[0]+ i -= 1++ if not adjacent:+ return ""++ phpdocs = [c for c in adjacent if c.lstrip().startswith("/**")]+ chosen = phpdocs if phpdocs else adjacent+ parsed = [_parse_comment(c) for c in chosen]+ return "\n".join(p for p in parsed if p).strip()+++def _strip_parens(raw: str) -> str:+ raw = raw.strip()+ if raw.startswith("(") and raw.endswith(")"):+ raw = raw[1:-1]+ return raw.strip()+++def _first_named_child_text(node, types: set, content_bytes: bytes) -> str:+ for child in node.children:+ if child.type in types:+ return _node_text(child, content_bytes).strip()+ return ""+++def _collect_typeish_tokens(node, content_bytes: bytes) -> List[str]:+ out: List[str] = []++ def _walk(n) -> None:+ if n.type in (+ "qualified_name",+ "namespace_name",+ "name",+ "identifier",+ ):+ txt = _node_text(n, content_bytes).strip()+ if txt and txt not in out:+ out.append(txt)+ for c in n.children:+ _walk(c)++ _walk(node)+ return out+++def _normalize_name(raw: str) -> str:+ raw = raw.strip()+ while raw.startswith("\\"):+ raw = raw[1:]+ return raw+++def _extract_use_declaration(node, content_bytes: bytes) -> List[str]:+ base_prefix = ""+ group_node = None+ for child in node.children:+ if child.type == "namespace_use_group":+ group_node = child+ break+ if group_node is not None:+ base_node = None+ for child in node.children:+ if child.type == "namespace_name":+ base_node = child+ break+ if base_node is not None:+ base = _normalize_name(_node_text(base_node, content_bytes)).rstrip("\\")+ base_prefix = f"{base}\\" if base else ""++ def _clause_name(clause) -> str:+ name_node = None+ for sub in clause.children:+ if sub.type == "qualified_name":+ name_node = sub+ break+ if name_node is None:+ for sub in clause.children:+ if sub.type == "name":+ name_node = sub+ break+ return _normalize_name(_node_text(name_node, content_bytes)) if name_node is not None else ""++ clauses = []+ if group_node is not None:+ for sub in group_node.children:+ if sub.type == "namespace_use_clause":+ clauses.append(sub)+ else:+ for sub in node.children:+ if sub.type == "namespace_use_clause":+ clauses.append(sub)++ out: List[str] = []+ for clause in clauses:+ name = _clause_name(clause)+ if not name:+ continue+ out.append(f"{base_prefix}{name}" if base_prefix else name)++ return out+++def _extract_function_like(node, content_bytes: bytes, docstring: str = "") -> FunctionSig:+ name = ""+ params = ""+ return_type = ""++ name_node = node.child_by_field_name("name")+ if name_node is not None:+ name = _node_text(name_node, content_bytes).strip()+ if not name:+ name = _first_named_child_text(node, {"name", "identifier"}, content_bytes)++ params_node = node.child_by_field_name("parameters")+ if params_node is None:+ params_node = node.child_by_field_name("parameters_list")+ if params_node is None:+ for child in node.children:+ if child.type in ("formal_parameters", "parameters", "parameter_list"):+ params_node = child+ break+ if params_node is not None:+ params = _strip_parens(_node_text(params_node, content_bytes))++ ret_node = node.child_by_field_name("return_type")+ if ret_node is None:+ ret_node = node.child_by_field_name("type")+ if ret_node is not None:+ return_type = _node_text(ret_node, content_bytes).strip().lstrip(":").strip()+ else:+ for child in node.children:+ if child.type in (+ "nullable_type",+ "union_type",+ "intersection_type",+ "primitive_type",+ "qualified_name",+ "namespace_name",+ "named_type",+ ):+ return_type = _node_text(child, content_bytes).strip().lstrip(":").strip()+ if return_type:+ break++ return FunctionSig(name=name, params=params, return_type=return_type, docstring=docstring)+++def _extract_class(+ node, content_bytes: bytes, docstring: str = "", name_prefix: str = ""+) -> ClassSkeleton:+ name = ""+ bases: List[str] = []+ body_node = None++ name_node = node.child_by_field_name("name")+ if name_node is not None:+ name = _node_text(name_node, content_bytes).strip()+ if not name:+ name = _first_named_child_text(node, {"name", "identifier"}, content_bytes)+ if name_prefix:+ name = f"{name_prefix}{name}" if name else name_prefix.strip()++ for child in node.children:+ if child.type in ("base_clause", "extends_clause", "implements_clause", "class_interface_clause"):+ for b in _collect_typeish_tokens(child, content_bytes):+ if b not in bases:+ bases.append(b)+ elif child.type in ("declaration_list", "class_body", "interface_body", "trait_body"):+ body_node = child+ elif body_node is None and child.type.endswith("_body"):+ body_node = child++ methods: List[FunctionSig] = []+ if body_node is not None:+ siblings = list(body_node.children)+ for idx, child in enumerate(siblings):+ if child.type == "use_declaration":+ for sub in child.children:+ if sub.type in ("name", "qualified_name"):+ t = _normalize_name(_node_text(sub, content_bytes))+ if t and t not in bases:+ bases.append(t)+ elif child.type in ("method_declaration", "method_definition"):+ doc = _preceding_doc(siblings, idx, content_bytes)+ methods.append(_extract_function_like(child, content_bytes, docstring=doc))++ return ClassSkeleton(name=name, bases=bases, docstring=docstring, methods=methods)+++def _dedup_keep_order(items: List[str]) -> List[str]:+ seen = set()+ out = []+ for i in items:+ if i and i not in seen:+ seen.add(i)+ out.append(i)+ return out+++def _leading_module_doc(siblings: list, content_bytes: bytes) -> str:+ for child in siblings:+ if child.type in ("php_tag", "text"):+ continue+ if child.type == "comment":+ raw = _node_text(child, content_bytes).strip()+ if raw.startswith("/**"):+ return _parse_comment(raw)+ continue+ break+ return ""+++def _process_siblings(+ siblings: list,+ content_bytes: bytes,+ imports: List[str],+ classes: List[ClassSkeleton],+ functions: List[FunctionSig],+) -> None:+ for idx, child in enumerate(siblings):+ if child.type == "namespace_use_declaration":+ imports.extend(_extract_use_declaration(child, content_bytes))+ elif child.type == "class_declaration":+ doc = _preceding_doc(siblings, idx, content_bytes)+ classes.append(_extract_class(child, content_bytes, docstring=doc, name_prefix=""))+ elif child.type == "interface_declaration":+ doc = _preceding_doc(siblings, idx, content_bytes)+ classes.append(_extract_class(child, content_bytes, docstring=doc, name_prefix="interface "))+ elif child.type == "trait_declaration":+ doc = _preceding_doc(siblings, idx, content_bytes)+ classes.append(_extract_class(child, content_bytes, docstring=doc, name_prefix="trait "))+ elif child.type == "enum_declaration":+ doc = _preceding_doc(siblings, idx, content_bytes)+ classes.append(_extract_class(child, content_bytes, docstring=doc, name_prefix="enum "))+ elif child.type in ("function_definition", "function_declaration"):+ doc = _preceding_doc(siblings, idx, content_bytes)+ functions.append(_extract_function_like(child, content_bytes, docstring=doc))+ elif child.type == "expression_statement":+ assign = None+ for sub in child.children:+ if sub.type == "assignment_expression":+ assign = sub+ break+ if assign is not None:+ left = None+ right = None+ for sub in assign.children:+ if left is None and sub.type == "variable_name":+ left = sub+ elif right is None and sub.type in ("anonymous_function", "arrow_function"):+ right = sub+ if left is not None and right is not None:+ doc = _preceding_doc(siblings, idx, content_bytes)+ sig = _extract_function_like(right, content_bytes, docstring=doc)+ sig.name = _node_text(left, content_bytes).strip()+ functions.append(sig)+ elif child.type == "namespace_definition":+ for sub in child.children:+ if sub.type in ("declaration_list", "compound_statement"):+ _process_siblings(list(sub.children), content_bytes, imports, classes, functions)+++class PhpExtractor(LanguageExtractor):+ def __init__(self):+ import tree_sitter_php as tsphp+ from tree_sitter import Language, Parser++ self._language = Language(tsphp.language_php())+ 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] = []+ classes: List[ClassSkeleton] = []+ functions: List[FunctionSig] = []++ siblings = list(root.children)+ module_doc = _leading_module_doc(siblings, content_bytes)+ _process_siblings(siblings, content_bytes, imports, classes, functions)++ return CodeSkeleton(+ file_name=file_name,+ language="PHP",+ module_doc=module_doc,+ imports=_dedup_keep_order(imports),+ classes=classes,+ functions=functions,+ )diff --git a/pyproject.toml b/pyproject.tomlindex 9cb87b39f..72d759c4d 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -68,6 +68,7 @@ dependencies = ["tree-sitter-rust>=0.23.0","tree-sitter-go>=0.23.0","tree-sitter-c-sharp>=0.23.0",+ "tree-sitter-php>=0.23.0","loguru>=0.7.3","cryptography>=42.0.0","argon2-cffi>=23.0.0",diff --git a/tests/parse/test_ast_extractor.py b/tests/parse/test_ast_extractor.pyindex 6924a7e8f..0ff82f0c6 100644--- a/tests/parse/test_ast_extractor.py+++ b/tests/parse/test_ast_extractor.py@@ -39,6 +39,12 @@ def _csharp_extractor():return CSharpExtractor()+def _php_extractor():+ from openviking.parse.parsers.code.ast.languages.php import PhpExtractor++ return PhpExtractor()++# ---------------------------------------------------------------------------# Python# ---------------------------------------------------------------------------@@ -469,6 +475,168 @@ public class Calculator {assert "@return sum of a and b" in text+class TestPhpExtractor:+ SAMPLE = """+<?php+/** Module for math utilities.+ *+ * Provides simple arithmetic operations.+ */+namespace App\\Services;++use Foo\\Bar;+use Foo\\Baz as BazAlias;+use Foo\\Group\\{A, B as Bee};++/** A simple calculator service.+ *+ * Supports basic arithmetic operations.+ */+class Calculator extends BaseCalc implements ICalc {+ /** Add two integers.+ *+ * @param int $a First operand+ * @param int $b Second operand+ * @return int Sum+ */+ public function add(int $a, int $b): int {+ return $a + $b;+ }++ // Subtract b from a.+ public function subtract(int $a, int $b): int {+ return $a - $b;+ }+}++/** Multiply two integers. */+function mul(int $a, int $b): int {+ return $a * $b;+}+"""++ def setup_method(self):+ self.e = _php_extractor()++ def test_module_doc(self):+ sk = self.e.extract("math.php", self.SAMPLE)+ print(sk.to_text(verbose=True))+ assert "Module for math utilities" in sk.module_doc++ def test_imports(self):+ sk = self.e.extract("math.php", self.SAMPLE)+ assert "Foo\\Bar" in sk.imports+ assert "Foo\\Baz" in sk.imports+ assert "Foo\\Group\\A" in sk.imports+ assert "Foo\\Group\\B" in sk.imports++ def test_class_extracted(self):+ sk = self.e.extract("math.php", self.SAMPLE)+ names = {c.name for c in sk.classes}+ assert "Calculator" in names++ def test_methods_extracted(self):+ sk = self.e.extract("math.php", 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" in methods+ assert "subtract" in methods+ assert "$a" in methods["add"].params+ assert methods["add"].return_type == "int"++ def test_method_docstring(self):+ sk = self.e.extract("math.php", 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 integers." in methods["add"].docstring+ assert "@param int $a" in methods["add"].docstring+ assert "Subtract b from a." in methods["subtract"].docstring++ def test_function_extracted(self):+ sk = self.e.extract("math.php", self.SAMPLE)+ names = {f.name for f in sk.functions}+ assert "mul" in names++ def test_to_text_compact(self):+ sk = self.e.extract("math.php", self.SAMPLE)+ text = sk.to_text(verbose=False)+ assert "# math.php [PHP]" in text+ assert "class Calculator" in text+ assert "@param" not in text++ def test_to_text_verbose(self):+ sk = self.e.extract("math.php", self.SAMPLE)+ text = sk.to_text(verbose=True)+ assert "Supports basic arithmetic operations." in text+ assert "@param int $a First operand" in text++ def test_trait_use_added_to_bases(self):+ code = """+<?php+trait T1 {}+trait T2 {}+class C {+ use T1, T2;+ public function m() {}+}+"""+ sk = self.e.extract("traits.php", code)+ cls = next(c for c in sk.classes if c.name == "C")+ assert "T1" in cls.bases+ assert "T2" in cls.bases++ def test_trait_and_interface_declarations_included(self):+ code = """+<?php+interface ICalc {}+/** T doc */+trait T { public function t() {} }+"""+ sk = self.e.extract("defs.php", code)+ names = {c.name for c in sk.classes}+ assert "interface ICalc" in names+ assert "trait T" in names++ def test_assignment_closure_extracted_as_function(self):+ code = """+<?php+/** Handler doc. */+$handler = function(int $x): int { return $x; };+$fn = fn($x): int => $x + 1;+"""+ sk = self.e.extract("closures.php", code)+ fns = {f.name: f for f in sk.functions}+ assert "$handler" in fns+ assert fns["$handler"].return_type == "int"+ assert "Handler doc." in fns["$handler"].docstring+ assert "$fn" in fns+ assert fns["$fn"].return_type == "int"++ def test_preceding_doc_prefers_phpdoc(self):+ code = """+<?php+// Noise comment.++/** Real doc. */+function f() {}+"""+ sk = self.e.extract("doc.php", code)+ f = next(fn for fn in sk.functions if fn.name == "f")+ assert f.docstring == "Real doc."++ def test_preceding_doc_falls_back_to_line_comments(self):+ code = """+<?php+// Line 1.+// Line 2.+function g() {}+"""+ sk = self.e.extract("doc2.php", code)+ g = next(fn for fn in sk.functions if fn.name == "g")+ assert "Line 1." in g.docstring+ assert "Line 2." in g.docstring++# ---------------------------------------------------------------------------# C## ---------------------------------------------------------------------------