Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
feat(py_lsp): builtin/template attribute dispatch + wrappers + dedup
Martin Vogeldd3a8161636f
diff --git a/internal/cbm/lsp/py_lsp.c b/internal/cbm/lsp/py_lsp.cindex f0bd9dce5..307bf57e1 100644--- a/internal/cbm/lsp/py_lsp.c+++ b/internal/cbm/lsp/py_lsp.c@@ -176,6 +176,22 @@ static char* py_node_text(PyLSPContext* ctx, TSNode node) {static void py_emit_resolved_call(PyLSPContext* ctx, const char* callee_qn,const char* strategy, float confidence) {if (!ctx || !ctx->resolved_calls || !callee_qn || !ctx->enclosing_func_qn) return;+ // Dedupe by (caller, callee). When multiple resolution paths converge+ // on the same edge (e.g. expression typing and emission both walk a+ // node), keep only the first entry — the path with the higher+ // confidence wins on subsequent re-emission.+ for (int i = 0; i < ctx->resolved_calls->count; i++) {+ CBMResolvedCall* rc = &ctx->resolved_calls->items[i];+ if (rc->caller_qn && rc->callee_qn &&+ strcmp(rc->caller_qn, ctx->enclosing_func_qn) == 0 &&+ strcmp(rc->callee_qn, callee_qn) == 0) {+ if (confidence > rc->confidence) {+ rc->confidence = confidence;+ rc->strategy = strategy;+ }+ return;+ }+ }CBMResolvedCall rc;memset(&rc, 0, sizeof(rc));rc.caller_qn = ctx->enclosing_func_qn;@@ -437,10 +453,18 @@ static const CBMType* py_eval_expr_type(PyLSPContext* ctx, TSNode node) {if (strcmp(name, "True") == 0 || strcmp(name, "False") == 0)return cbm_type_builtin(ctx->arena, "bool");if (strcmp(name, "None") == 0) return cbm_type_builtin(ctx->arena, "None");- // Module/package-local function — caller QN inferred from registry.+ // Module/package-local function.const CBMRegisteredFunc* f = cbm_registry_lookup_symbol(ctx->registry,ctx->module_qn, name);if (f) return py_func_return_type(ctx, f->qualified_name);+ // Builtins fallback (range / len / list / str / int / etc.). For+ // builtin classes, this returns the class as NAMED so subsequent+ // attribute access works.+ f = cbm_registry_lookup_symbol(ctx->registry, "builtins", name);+ if (f) return py_func_return_type(ctx, f->qualified_name);+ const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry,+ cbm_arena_sprintf(ctx->arena, "builtins.%s", name));+ if (rt) return cbm_type_builtin(ctx->arena, name);return cbm_type_unknown();}@@ -484,6 +508,27 @@ static const CBMType* py_eval_expr_type(PyLSPContext* ctx, TSNode node) {obj_type->data.named.qualified_name, attr_name);if (field) return field;}+ if (obj_type->kind == CBM_TYPE_BUILTIN && obj_type->data.builtin.name) {+ // Builtins map to typeshed stdlib via "builtins.<typename>".+ const char* recv_qn = cbm_arena_sprintf(ctx->arena, "builtins.%s",+ obj_type->data.builtin.name);+ const CBMRegisteredFunc* f = py_lookup_attribute(ctx, recv_qn, attr_name);+ if (f) return py_func_return_type_recv(ctx, f->qualified_name, recv_qn);+ }+ if (obj_type->kind == CBM_TYPE_TEMPLATE &&+ obj_type->data.template_type.template_name) {+ // dict[K, V].get / list[T].append etc — receiver is the+ // unparameterized container in typeshed: builtins.dict /+ // builtins.list / collections.abc.Mapping etc.+ const char* tname = obj_type->data.template_type.template_name;+ // Try builtins.<tname> first, then bare tname.+ const char* recv_qn = cbm_arena_sprintf(ctx->arena, "builtins.%s", tname);+ const CBMRegisteredFunc* f = py_lookup_attribute(ctx, recv_qn, attr_name);+ if (!f) {+ f = py_lookup_attribute(ctx, tname, attr_name);+ }+ if (f) return py_func_return_type_recv(ctx, f->qualified_name, recv_qn);+ }if (obj_type->kind == CBM_TYPE_UNION) {int matches = 0;const CBMRegisteredFunc* hit = NULL;@@ -575,6 +620,13 @@ static const CBMType* py_eval_expr_type(PyLSPContext* ctx, TSNode node) {const CBMRegisteredFunc* f = cbm_registry_lookup_symbol(ctx->registry,ctx->module_qn, fname);if (f) return py_func_return_type(ctx, f->qualified_name);+ // Builtins fallback: range / len / list / str / int / etc.+ f = cbm_registry_lookup_symbol(ctx->registry, "builtins", fname);+ if (f) return py_func_return_type(ctx, f->qualified_name);+ // Builtin class constructor: list() / dict() / set() / str() / ...+ const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry,+ cbm_arena_sprintf(ctx->arena, "builtins.%s", fname));+ if (rt) return cbm_type_builtin(ctx->arena, fname);}if (strcmp(fk, "attribute") == 0) {@@ -819,7 +871,6 @@ static void py_emit_call_for(PyLSPContext* ctx, TSNode call_node) {const CBMType* in_scope = cbm_scope_lookup(ctx->current_scope, fname);if (!cbm_type_is_unknown(in_scope) && in_scope->kind == CBM_TYPE_NAMED) {const char* qn = in_scope->data.named.qualified_name;- // Treat the call as targeting __init__; emit edge to the class QN.py_emit_resolved_call(ctx, qn, "lsp_constructor", 0.85f);return;}@@ -830,7 +881,19 @@ static void py_emit_call_for(PyLSPContext* ctx, TSNode call_node) {py_emit_resolved_call(ctx, f->qualified_name, "lsp_direct", 0.95f);return;}- // Builtin / unknown — skip silently (low confidence)+ // Builtins (range / len / list / dict / str / int / print / ...).+ f = cbm_registry_lookup_symbol(ctx->registry, "builtins", fname);+ if (f) {+ py_emit_resolved_call(ctx, f->qualified_name, "lsp_builtin", 0.92f);+ return;+ }+ const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry,+ cbm_arena_sprintf(ctx->arena, "builtins.%s", fname));+ if (rt) {+ py_emit_resolved_call(ctx, rt->qualified_name,+ "lsp_builtin_constructor", 0.88f);+ return;+ }return;}@@ -902,6 +965,29 @@ static void py_emit_call_for(PyLSPContext* ctx, TSNode call_node) {return;}}+ if (obj_type->kind == CBM_TYPE_BUILTIN && obj_type->data.builtin.name) {+ // Builtins -> "builtins.<typename>" in typeshed.+ const char* recv_qn = cbm_arena_sprintf(ctx->arena, "builtins.%s",+ obj_type->data.builtin.name);+ const CBMRegisteredFunc* f = py_lookup_attribute(ctx, recv_qn, attr_name);+ if (f) {+ py_emit_resolved_call(ctx, f->qualified_name, "lsp_builtin_method", 0.9f);+ return;+ }+ }+ if (obj_type->kind == CBM_TYPE_TEMPLATE &&+ obj_type->data.template_type.template_name) {+ const char* tname = obj_type->data.template_type.template_name;+ const char* recv_qn = cbm_arena_sprintf(ctx->arena, "builtins.%s", tname);+ const CBMRegisteredFunc* f = py_lookup_attribute(ctx, recv_qn, attr_name);+ if (!f) {+ f = py_lookup_attribute(ctx, tname, attr_name);+ }+ if (f) {+ py_emit_resolved_call(ctx, f->qualified_name, "lsp_generic_method", 0.88f);+ return;+ }+ }if (obj_type->kind == CBM_TYPE_UNION) {// Try each non-None member; if exactly one matches, emit.int matches = 0;@@ -1387,6 +1473,38 @@ static const CBMType* py_parse_type_text_qn(CBMArena* arena, const char* ann,return cbm_type_union(arena, arg_types, arg_n);}}+ // Type-wrapper annotations that don't change the underlying+ // type for resolution: ClassVar[T], Final[T], InitVar[T],+ // ReadOnly[T], Required[T], NotRequired[T], Annotated[T, ...]+ // (drop metadata), Mapped[T] (SQLAlchemy 2.0), and+ // typing_extensions/typing variants of all these. Returns+ // the wrapped type T.+ static const char* wrapper_names[] = {+ "ClassVar", "Final", "InitVar", "ReadOnly",+ "Required", "NotRequired", "Annotated",+ "Mapped", "WriteOnlyMapped", "DynamicMapped", // SQLAlchemy+ "typing.ClassVar", "typing.Final", "typing.Annotated",+ "typing.Required", "typing.NotRequired", "typing.ReadOnly",+ "typing_extensions.ClassVar", "typing_extensions.Final",+ "typing_extensions.Annotated", "typing_extensions.Required",+ "typing_extensions.NotRequired", "typing_extensions.ReadOnly",+ "dataclasses.InitVar",+ NULL};+ for (int wi = 0; wrapper_names[wi]; wi++) {+ if (strcmp(btrim, wrapper_names[wi]) == 0) {+ if (arg_types && arg_n >= 1 && arg_types[0]) {+ return arg_types[0];+ }+ }+ }+ // Type[T] / type[T] -> instance of T's metaclass... for+ // resolution purposes, treat as the class itself.+ if (strcmp(btrim, "Type") == 0 || strcmp(btrim, "type") == 0 ||+ strcmp(btrim, "typing.Type") == 0) {+ if (arg_types && arg_n >= 1 && arg_types[0]) {+ return arg_types[0];+ }+ }if (arg_types && arg_n > 0) {return cbm_type_template(arena, btrim, arg_types, arg_n);}@@ -1530,6 +1648,30 @@ static const CBMType* py_resolve_annotation(PyLSPContext* ctx, const char* ann)return cbm_type_union(ctx->arena, arg_types, arg_n);}}+ // Type wrappers that don't change the underlying type:+ // ClassVar / Final / InitVar / ReadOnly / Required /+ // NotRequired / Annotated / Mapped (SQLAlchemy) / Type[T].+ // Returns the wrapped type T directly.+ static const char* wrapper_names[] = {+ "ClassVar", "Final", "InitVar", "ReadOnly",+ "Required", "NotRequired", "Annotated",+ "Mapped", "WriteOnlyMapped", "DynamicMapped",+ "Type", "type",+ "typing.ClassVar", "typing.Final", "typing.Annotated",+ "typing.Required", "typing.NotRequired", "typing.ReadOnly",+ "typing.Type",+ "typing_extensions.ClassVar", "typing_extensions.Final",+ "typing_extensions.Annotated", "typing_extensions.Required",+ "typing_extensions.NotRequired", "typing_extensions.ReadOnly",+ "dataclasses.InitVar",+ NULL};+ for (int wi = 0; wrapper_names[wi]; wi++) {+ if (strcmp(btrim, wrapper_names[wi]) == 0) {+ if (arg_types && arg_n >= 1 && arg_types[0]) {+ return arg_types[0];+ }+ }+ }// Generic containers -> TEMPLATEif (arg_types && arg_n > 0) {return cbm_type_template(ctx->arena, btrim, arg_types, arg_n);diff --git a/tests/test_py_lsp_bench.c b/tests/test_py_lsp_bench.cindex f826cce21..0ada8be80 100644--- a/tests/test_py_lsp_bench.c+++ b/tests/test_py_lsp_bench.c@@ -1,20 +1,29 @@/*- * test_py_lsp_bench.c — Phase 11 / parity-tracking benchmark.+ * test_py_lsp_bench.c — parity-tracking benchmark for py_lsp.*- * The fixture is hand-written to exercise the resolver across the patterns- * py_lsp now supports: imports + dotted submodule walks, dataclass + super,- * generic container annotations + comprehension element typing, type- * narrowing via isinstance / is not None / walrus, match/case class- * patterns, async/await, fluent chaining via Self, classmethod /- * staticmethod, stdlib calls (logging / pathlib / collections / json /- * functools), Optional / Union annotations.+ * The fixture is a synthetic but representative ~250-line Python file+ * that exercises every parity feature py_lsp implements:+ * - imports + dotted submodule walks (os.path)+ * - dataclass + class-body annotated fields+ * - inheritance with super() calls (method + __init__)+ * - Self return type (fluent chains)+ * - generic containers + comprehension element typing+ * - dict / list / tuple subscript value types+ * - narrowing (isinstance / is not None / walrus + None)+ * - match/case class patterns+ * - async / await+ * - classmethod / staticmethod+ * - @property attribute access+ * - SQLAlchemy 2.0-style Mapped[T] annotations+ * - Pydantic-style BaseModel with field annotations+ * - typing.Annotated / ClassVar / Final / InitVar wrappers+ * - generator yield with for-loop element typing+ * - operator dunder dispatch+ * - typing.cast / assert_type+ * - common stdlib calls (logging, pathlib, json, functools)*- * Tests assert:- * - All resolved calls go to plausible callees (no garbage QNs).- * - Resolution ratio passes the 70%-application+stdlib target.- * - Per-file extraction time stays under 50 ms (sanitizers on).- *- * For repo-level benchmarks see docs/BENCHMARK_PYTHON.md.+ * Asserts: resolution ratio >= 50% under sanitizers (production target+ * is 95%+ — see docs/BENCHMARK_PYTHON.md).*/#include "test_framework.h"#include "cbm.h"@@ -27,10 +36,13 @@ static const char *bench_source ="import json\n""import logging\n""import functools\n"- "from dataclasses import dataclass\n"+ "from dataclasses import dataclass, field\n""from pathlib import Path\n""from collections import defaultdict\n"- "from typing import Optional, Self, cast\n"+ "from typing import (\n"+ " Optional, Self, cast, ClassVar, Final, Annotated, Generator,\n"+ " NamedTuple, Protocol\n"+ ")\n""\n""log = logging.getLogger('bench')\n""\n"@@ -39,23 +51,47 @@ static const char *bench_source =" name: str\n"" debug: bool\n"" extras: list[str]\n"+ " LIMIT: ClassVar[int] = 100\n"" def display(self) -> str:\n"" return self.name\n"" def with_debug(self, on: bool) -> Self:\n"" self.debug = on\n"" return self\n""\n"+ "class Mapped:\n"+ " pass\n"+ "\n"+ "class User:\n"+ " id: Annotated[int, 'primary_key']\n"+ " name: Final[str]\n"+ " email: str\n"+ " posts: list[str]\n"+ " def __init__(self, id: int, name: str, email: str):\n"+ " self.id = id\n"+ " self.name = name\n"+ " self.email = email\n"+ " self.posts = []\n"+ " def display_name(self) -> str:\n"+ " return self.name\n"+ " @property\n"+ " def domain(self) -> str:\n"+ " return self.email.split('@')[1]\n"+ "\n""class BaseStore:\n"" def __init__(self, root: Path):\n"- " self.root = root\n"+ " self.root: Path = root\n"+ " self.metadata: dict[str, str] = {}\n"" def get(self, key: str) -> Optional[str]:\n"- " return None\n"+ " return self.metadata.get(key)\n"" def put(self, key: str, value: str) -> None:\n"- " return None\n"+ " self.metadata[key] = value\n"" def keys(self) -> list[str]:\n"- " return []\n"+ " return list(self.metadata.keys())\n""\n""class FileStore(BaseStore):\n"+ " def __init__(self, root: Path):\n"+ " super().__init__(root)\n"+ " self.cache: dict[str, str] = {}\n"" @classmethod\n"" def open(cls, root: Path) -> Self:\n"" return cls(root)\n"@@ -63,24 +99,17 @@ static const char *bench_source =" def is_writable(p: Path) -> bool:\n"" return True\n"" def get(self, key: str) -> Optional[str]:\n"+ " if key in self.cache:\n"+ " return self.cache[key]\n"" full = self.root / key\n"" if full.exists():\n"- " return full.read_text()\n"+ " text = full.read_text()\n"+ " self.cache[key] = text\n"+ " return text\n"" return None\n"" def put(self, key: str, value: str) -> None:\n"- " return super().put(key, value)\n"- "\n"- "class CachedStore(FileStore):\n"- " def __init__(self, root: Path):\n"- " super().__init__(root)\n"- " self.cache: dict[str, str] = {}\n"- " def get(self, key: str) -> Optional[str]:\n"- " if key in self.cache:\n"- " return self.cache[key]\n"- " result = super().get(key)\n"- " if result is not None:\n"- " self.cache[key] = result\n"- " return result\n"+ " super().put(key, value)\n"+ " self.cache[key] = value\n""\n""class Result:\n"" def __init__(self, ok: bool, value: Optional[str]):\n"@@ -90,13 +119,19 @@ static const char *bench_source =" return self.value or 'empty'\n""\n""class App:\n"- " def __init__(self, cfg: Config):\n"+ " def __init__(self, cfg: Config, store: BaseStore):\n"" self.cfg = cfg\n"- " self.store: BaseStore = FileStore.open(Path(os.getcwd()))\n"+ " self.store = store\n"+ " self.users: dict[int, User] = {}\n"" self.counts: dict[str, int] = defaultdict(int)\n"" self.logger = logging.getLogger('app')\n"" def display_config(self) -> str:\n"" return self.cfg.display()\n"+ " def add_user(self, u: User) -> None:\n"+ " self.users[u.id] = u\n"+ " self.logger.info('added %s', u.display_name())\n"+ " def get_user(self, uid: int) -> Optional[User]:\n"+ " return self.users.get(uid)\n"" def lookup(self, key: str) -> Result:\n"" result = self.store.get(key)\n"" self.counts[key] += 1\n"@@ -106,9 +141,10 @@ static const char *bench_source =" self.logger.info('wrote %s', key)\n"" def display_results(self, results: list[Result]) -> list[str]:\n"" return [r.display() for r in results]\n"+ " def display_users(self) -> list[str]:\n"+ " return [u.display_name() for u in self.users.values()]\n"" def filter_active(self, keys: list[str]) -> list[str]:\n"- " active = [k for k in keys if self.lookup(k).ok]\n"- " return active\n"+ " return [k for k in keys if self.lookup(k).ok]\n"" def with_debug(self) -> Self:\n"" self.cfg = self.cfg.with_debug(True)\n"" return self\n"@@ -118,8 +154,7 @@ static const char *bench_source =" return None\n""\n""def parse_response(payload: str) -> dict[str, str]:\n"- " data = json.loads(payload)\n"- " return data\n"+ " return json.loads(payload)\n""\n""async def fetch(key: str) -> Optional[str]:\n"" return slow_lookup(key)\n"@@ -131,10 +166,16 @@ static const char *bench_source =" out.append(v)\n"" return out\n""\n"+ "def gen_users(n: int) -> Generator[User, None, None]:\n"+ " for i in range(n):\n"+ " yield User(i, 'name' + str(i), '[email protected]')\n"+ "\n""def classify(x) -> str:\n"" match x:\n"" case Config():\n"" return x.display()\n"+ " case User():\n"+ " return x.display_name()\n"" case Result():\n"" return x.display()\n"" case App():\n"@@ -147,17 +188,27 @@ static const char *bench_source =" return s.get(key)\n"" return None\n""\n"- "def main():\n"+ "def first_writable(stores: list[BaseStore]) -> Optional[BaseStore]:\n"+ " for s in stores:\n"+ " if isinstance(s, FileStore):\n"+ " return s\n"+ " return None\n"+ "\n"+ "def main() -> None:\n"" cfg = Config('app', True, ['x', 'y'])\n"- " app = App(cfg)\n"+ " fs = FileStore.open(Path(os.getcwd()))\n"+ " app = App(cfg, fs)\n"" app.with_debug().write('a', '1')\n"" res = app.lookup('a')\n"- " print(res.display())\n"" classify(cfg)\n"" classify(res)\n"" classify(app)\n"" payload = parse_response('{}')\n"- " print(payload)\n";+ " log.info('payload=%s', payload)\n"+ " for u in gen_users(3):\n"+ " app.add_user(u)\n"+ " summary = app.display_users()\n"+ " log.info('users=%d', len(summary))\n";static double elapsed_ms(struct timespec t0, struct timespec t1) {double s = (double)(t1.tv_sec - t0.tv_sec);@@ -191,18 +242,14 @@ TEST(pylsp_bench_resolution_ratio) {ASSERT_GTE(calls, 1);ASSERT_GTE(resolved, 1);- /* Resolution-ratio floor: with the larger fixture covering narrowing /- * comprehensions / Self / async / match-case / stdlib, we expect a- * higher ratio than the original 65-line test. Floor at 50% under- * sanitizers — production targets per docs/BENCHMARK_PYTHON.md are- * 40% application / 70% stdlib-included. */- if (calls >= 16) {- ASSERT_GTE(resolved * 2, calls); // ratio >= 50%+ /* Floor at 50% under sanitizers; production target is 95% per+ * docs/BENCHMARK_PYTHON.md. */+ if (calls >= 30) {+ ASSERT_GTE(resolved * 2, calls);}- /* Absolute time budget: <100 ms for ~150-line fixture under- * ASan + UBSan. No-sanitizer target is < 10 ms. */- ASSERT(ms < 100.0);+ /* <150 ms time budget for ~200-line fixture under ASan + UBSan. */+ ASSERT(ms < 150.0);cbm_free_result(r);PASS();