Commit Graph
13 Commits
Author SHA1 Message Date
Martin Vogel 7e4745ddd1 test(py-lsp): regression for #228 (cross-file classmethod on class)
#228: a class/static method invoked on a cross-file imported class name
(ActionRecordX.build_from_text(...)) produced no CALLS edge, so the
method looked like dead code (in/out degree 0). The v0.7.0 py_lsp
cross-file resolver handles this; the test feeds the exact pattern through
cbm_run_py_lsp_cross and asserts the call resolves.

Closes #228.
2026-05-31 03:14:17 +02:00
Martin Vogel fd81dffc8f feat(py_lsp): decorator flags + verifications for generators / dataclasses / properties
Round 6:

CBMRegisteredFunc gains a `flags` bitfield (CBMFuncFlags) and a
`decorator_qns` NULL-terminated list. py_register_def populates them
from CBMDefinition.decorators by short-name match — so `@property`,
`@functools.cache`, `@abc.abstractmethod`, `@typing.overload`, and
`@final` all light up regardless of qualified vs bare reference. The
flags aren't consumed by resolution yet (still on roadmap: emit
distinct edge for @property attribute access vs method call); they
are recorded so future overload selection / property modeling can
use them without another schema change.

The struct extension is at-tail and existing call sites that memset
to zero stay correct; non-Python LSPs see flags=0 / decorator_qns=NULL
and behave identically.

Three new verification tests prove that generators, dataclasses, and
@property already work end-to-end through the Round 4-5 infrastructure
without further code changes:
- Generator[Foo, ...] iterables in for-loop bind loop var to Foo via
  py_iterable_element_type's existing TEMPLATE handling.
- @dataclass class Point: x: Foo (class-body annotated assignment) is
  picked up by Round 4's third-pass field registrar; p.x.method()
  resolves through the field type.
- @property def thing(self) -> Foo: c.thing returns Foo because
  attribute access on NAMED routes through py_func_return_type which
  yields the getter's annotated return.

All 2895 prior tests stay green; 3 new tests pass. Total 2898 / 0.
Bench unchanged at 95% (the small bench fixture doesn't exercise
the new patterns; will expand in Round 7).
2026-05-09 10:02:12 +02:00
Martin Vogel ce54e817b7 feat(py_lsp): subscript + super().__init__() + operator dunders
Round 5 parity push:

Subscript value typing — py_eval_expr_type's subscript branch resolves
indexing against the container's TEMPLATE type:
- TEMPLATE("dict"|"Mapping"|"defaultdict"|"OrderedDict"|...)[K] -> V
- TEMPLATE("list"|"set"|"frozenset"|"Sequence"|"Iterable"|...)[i] -> elem
- TEMPLATE("tuple", [A, B, ...])[literal_int] -> args[idx]
  - Non-literal index returns UNION of all element types.

This unlocks the `self.cache[k].method()` pattern that's everywhere in
real Python. Also fixes `items[0].method()` for typed lists.

super().__init__(...) constructor edge — super().<attr> already worked
for regular methods; __init__ is special-cased because parent classes
typically don't register __init__ with a useful return type. Strategy
"lsp_super_init" with confidence 0.85.

Operator dunders — a + b looks up __add__ on a's type and uses its
return type. Same for *, -, /, //, %, **, <<, >>, &, |, ^, @. Falls
back to left-operand type when registry has no info (correct for the
common int+int / str+str / list+list cases).

3 new tests; all 2892 prior tests stay green. Bench unchanged at 95%
(fixture doesn't exercise these patterns directly — Round 6 will
expand it).
2026-05-09 09:53:43 +02:00
Martin Vogel 4b993899a0 feat(py_lsp): instance attribute typing — 79% -> 95% resolution
Round 4 / final parity push. Tracks self.x = expr from __init__ and
class-body annotated assignments (`x: Foo`) as registered fields on
the enclosing class type.

py_register_instance_field mutates the registry's CBMRegisteredType
field_names / field_types arrays in place. Re-registering the same
name overwrites; first-seen wins for capture order. Arena-allocated,
not a hot path.

py_lookup_field walks the alias / embedded chain with the same
CBM_LSP_MAX_LOOKUP_DEPTH cap as method lookup, so inherited fields
resolve through MRO without stack-overflow risk on pathological
hierarchies.

Field-fallback wired into py_eval_expr_type's attribute branch:
when method lookup misses, try field lookup. Returns the field's
type so downstream attribute / call resolution chains naturally.
Same fallback applied to UNION (single-match heuristic).

py_process_class now does three passes:
1. Class-body annotated assignments (`x: int = ...`) → fields.
2. __init__ / __post_init__ → self.x = expr fields.
3. All other methods.
This guarantees fields are registered before methods that reference
them, regardless of source order.

Annotated assignment binding fix: py_resolve_annotation is now called
on assignment annotations too, so `self.cache: dict[str, str] = {}`
binds with the proper TEMPLATE type instead of NAMED("dict[str, str]").

Bench result on the 136-line fixture: **95%** (36/38 calls resolved,
8.06 ms). Up from 79%. The 5% gap covers cases that need a full
constraint solver — see Final Stopping Point doc.

2 new tests; all 2890 prior tests stay green. Total 2892 / 0.
2026-05-09 03:38:06 +02:00
Martin Vogel e7dcadc3dd feat(py_lsp): match/case narrowing, await passthrough, expanded bench
Round 3 parity push:

- match/case (PEP 634): when the case pattern is class_pattern (wrapped
  in a case_pattern), narrow the match subject identifier to NAMED(class)
  inside the case body. Push/pop scope per case. Capture sub-patterns
  bind to UNKNOWN (field-type extraction is a v1.1 task — would require
  field type info in the registry).
- await expr: identity passthrough. async def f() -> T registers with
  return T, so `await f()` returning T is the resolved-call shape we
  want without modeling Coroutine[Any, Any, T] explicitly.
- Expanded test_py_lsp_bench.c fixture from 65 lines to 136 lines
  exercising every parity feature: dotted-module walks, dataclass +
  Self chaining, multi-inheritance with super(), Optional/Union
  annotations + narrowing (isinstance / is not None / walrus), generic
  list[T] / dict[K, V] / defaultdict comprehensions, classmethod /
  staticmethod, match/case dispatch, async/await, common stdlib
  (logging.getLogger, json.loads, pathlib.Path, functools.lru_cache).

Bench result on the new fixture: 38 calls, 30 resolved, 79%, 7.50 ms.
Remaining 21% includes patterns where intermediate types lose precision
(e.g. super() constructor, dict subscript), instance attribute typing
(self.x where x isn't annotated at class scope), and decorator
return-type substitution (lru_cache).

All 2888 prior tests stay green; 2 new tests + bench expansion. Total
2890 / 0.
2026-05-09 03:29:51 +02:00
Martin Vogel fa45e7defc feat(py_lsp): narrowing, walrus, comprehension element typing
Round 2/3 parity push. Three connected gap fixes that share an annotation-
parser and a generic-aware iterable model.

Annotation parser upgrade:
- py_resolve_annotation now turns subscripted forms into structured types
  rather than stripping. `Optional[Foo]` -> UNION(NAMED(Foo), None).
  `Union[A, B]` -> UNION. `list[Foo]` / `dict[K, V]` / `Iterable[T]` ->
  TEMPLATE with arg list. `X | Y` (PEP 604) handled at depth zero.
- New py_parse_type_text_qn variant: same parser without scope lookup,
  used by py_register_def at registry-build time. Bare class names are
  qualified to <module_qn>.<name> so registry lookups match.
- py_register_def prefers d->return_type (full subscripted text) over
  d->return_types[0] when brackets are present — extract_defs's array
  form strips the subscript, losing element types like Optional[Foo].

Narrowing:
- if isinstance(x, T): bind x as NAMED(T) inside the consequence body
  (block-scoped via push/pop).
- if x is not None: strip None from x's UNION inside the consequence;
  py_match_is_none recognizes "is not" as the single tree-sitter token
  it actually is, walks through parens / walrus to find the underlying
  identifier.
- Else branch unchanged — narrow's negation (not-T, including-None) is
  not modeled in v1.

Walrus + truthy:
- if (x := compute()) is not None: walrus binds x in the enclosing scope
  (PEP 572) so the body sees x. py_bind_walrus_in walks the cond AST
  looking for named_expression / assignment_expression nodes.

Comprehension + for-loop element typing:
- New py_iterable_element_type maps TEMPLATE(list/set/Iterable/...) to
  arg[0]; TEMPLATE(dict) to key arg; TEMPLATE(tuple, ...) to UNION of
  args.
- Comprehensions push their own scope and bind for_in_clause loop vars
  to the iterable's element type before walking body / filter clauses.
  for_statement does the same.

UNION attribute access fallback (used when narrowing can't run):
- obj_type=UNION & exactly one non-None NAMED member has the attr:
  emit edge with strategy=lsp_method_union, confidence 0.85.

7 new test_py_lsp.c cases. All 2880 prior tests stay green; 8 new tests
land. Bench unchanged (small fixture, no narrowing exercised there).
2026-05-09 03:17:37 +02:00
Martin Vogel 2e042dab0b feat(py_lsp): Round 1 parity push (parent-modules, cast, Self, fwd-refs)
Parity push #1 — six gap fixes on top of the 11-phase plan:

- Parent-module bindings: `import a.b.c` now binds `a`, `a.b`, `a.b.c`
  via py_bind_dotted_prefixes. Walks the dotted prefix chain on every
  import, regardless of import_is_from_style. Plus an attribute-access
  path on a MODULE that detects submodules: when the registry has any
  function whose qn starts with `<mod>.<attr>.`, evaluating `mod.attr`
  yields MODULE("<mod>.<attr>"). This makes `os.path.join(...)` and
  similar resolve correctly.

- typing.cast(T, x) returns NAMED(T) (re-evaluating T as an annotation,
  so generic subscripts and forward references both resolve). Detects
  bare `cast(...)` and qualified `typing.cast(...)` forms.

- typing.assert_type(x, T) is a no-op at runtime; we type the result
  as type-of(x).

- Forward references as quoted strings: `def f(x: "Foo")` strips quotes
  and re-resolves the inner annotation. Also handles double-quoted and
  single-quoted forms.

- Self return type substitution: methods declared returning `Self` /
  `typing.Self` / `typing_extensions.Self` substitute to NAMED(receiver)
  at call resolution time. Enables fluent / builder pattern chaining
  to keep resolving methods after each step.

- Generic subscript stripping: annotations like `list[Foo]` strip to
  `list` for v1; `Optional[Foo]` likewise. Container element-type
  substitution still deferred (Phase 8+).

Generator additions:
- Allowlist now includes urllib, http, concurrent (top stdlib usage).
- `from X import *` re-export following at generation time. Modules
  like os.path (a star-import shim of posixpath / ntpath / genericpath)
  now have all forwarded definitions registered under their own QN.
  Iterates to a fixed point with an 8-step ceiling. typeshed tree
  expansion is bounded — only modules transitively reachable from the
  allowlist are pulled in.

Stats: 137 modules, 904 classes (2797 methods), 886 free functions
(was 114 / 753 / 794). Generated file grows from 20K to ~22K lines.

6 new test_py_lsp.c cases. All 2874 prior tests stay green.
2026-05-09 01:39:28 +02:00
Martin Vogel fa6bfd125f feat(py_lsp): stdlib registry from typeshed + generator
Phase 10 of Python LSP integration. Adds:

- scripts/gen-py-stdlib.py: walks a typeshed/stdlib checkout, parses
  each .pyi via Python's stdlib `ast` module, and emits one C source
  file populating cbm_python_stdlib_register. v1 simplifications:
    - overload stacks collapse to first signature
    - ParamSpec / TypeVarTuple / Concatenate skipped
    - version guards (if sys.version_info >= ...) flattened to union
      of branches
    - per-symbol min/max version guards not yet emitted (v1.1 follow-up)
  Module allowlist matches PYTHON_LSP_PLAN.md Phase 10 list — top
  stdlib modules by usage in indexed Python projects, skipping
  tkinter / turtle / curses / xml / email for size.

- internal/cbm/lsp/generated/python_stdlib_data.c (auto-generated,
  20,021 lines): 114 modules, 753 classes (2,385 methods), 794 free
  functions registered. Source pinned to typeshed commit
  a7912d521e16ff63caf7a8b64b9072542be36777 (recorded in header).
  Compiles cleanly under ASan + UBSan.

- lsp_all.c includes the generated file. The CBM_PYTHON_STDLIB_GENERATED
  macro disables py_lsp.c's no-op stub so the real registration runs.

4 new test_py_lsp.c cases verify resolution against the registry:
os.getcwd, collections.defaultdict constructor, pathlib.Path.exists
method via typed parameter, logging.getLogger.

Known v1 limitation captured in test comments: `import os.path` only
binds the leaf `path` in scope, so `os.path.join` style chained
attribute access on the parent module name doesn't yet resolve.
Phase 10.5 will stamp parent-module bindings.

All 2869 prior tests stay green; 4 new stdlib tests pass.
2026-05-09 00:39:21 +02:00
Martin Vogel f4f9ed47f6 feat(py_lsp): cross-file resolution + batch entry point
Phase 9 of Python LSP integration. Implements cbm_run_py_lsp_cross and
cbm_batch_py_lsp_cross, mirroring the Go LSP pattern:

- cbm_run_py_lsp_cross builds a per-call registry from caller-supplied
  CBMLSPDef[] entries (covering both file-local and cross-file
  definitions), then re-parses the source via tree_sitter_python (or
  uses cached_tree when supplied) and runs the standard
  py_lsp_process_file pipeline.
- py_register_lsp_defs translates CBMLSPDef shapes into
  CBMRegisteredType / CBMRegisteredFunc entries. Python-specific
  Protocol label is recognized as an interface-like structural type.
  Pipe-separated embedded_types and method_names_str are split into
  arena-allocated NULL-terminated arrays. Method receivers auto-create
  type entries when the type isn't otherwise registered, matching the
  Go convention.
- cbm_batch_py_lsp_cross loops the per-file entry, isolating each file
  in its own arena and copying string fields into the caller's arena
  so they outlive the file's scratch space.

3 new test_py_lsp.c cases cover cross-file method dispatch, cross-file
inheritance (Child(Base) calling self.shared from another module), and
batch processing of two interconnected files. All 2866 prior tests stay
green; 3 new cross-file tests pass.
2026-05-09 00:17:59 +02:00
Martin Vogel 329d266ed3 feat(py_lsp): decorators, super() resolution, multi-inheritance
Phases 7-8 of Python LSP integration. Adds:

- super().method() resolution: when the call's receiver is a super() proxy
  inside a class context, walk the enclosing class's embedded_types and
  resolve the attribute against the first base where it exists. Edge
  carries strategy="lsp_super" and confidence 0.88.
- Multi-inheritance dispatch already worked for the current registry shape
  (embedded_types is a list, py_lookup_attribute iterates) — added an
  explicit test to lock in the behavior.

Also fixes a Python class-body extraction gap upstream of py_lsp: the
generic extract_class_methods walker skipped any class-body child whose
node type wasn't a function_definition, which excluded everything wrapped
in a decorated_definition (i.e. every @classmethod / @staticmethod /
@property method). Patched to peek through decorated_definition for the
inner function_definition before calling resolve_method_name. This is the
root cause of the C.classmethod() / C.staticmethod() resolution miss and
the fix is independent of language-specific decorator semantics — any
language whose grammar uses decorated_definition benefits.

7 new test_py_lsp.c cases cover decorated functions, classmethod calls,
staticmethod calls, dataclass constructor + method dispatch, super() to
the right base, multi-inheritance attribute resolution on both bases, and
PEP 695-style class names without subscript handling. All 2859 prior
tests stay green; 7 new tests pass. Total: 2866 / 0.
2026-05-09 00:03:00 +02:00
Martin Vogel 1c83c5df4b feat(py_lsp): scope binding, expression typing, method dispatch
Bundles Phases 4-6 of Python LSP integration. py_lsp.c gains a real
binder + expression evaluator + call resolver mirroring go_lsp.c's
shape:

- py_register_def populates the registry from CBMFileResult.defs.
  Class/Type defs land as registered types; Method/Function defs as
  registered functions with receiver_type derived from the qualified
  name parent. Python's extract_defs records a class's bases as a
  single "(Base, Other)" string, so we split commas at depth 0,
  strip parens / generic subscripts / keyword args (metaclass=...)
  to produce usable embedded_types entries.
- py_lsp_process_file walks function/class definitions, pushing scope
  per function and binding self/cls to the enclosing class type
  (after parameter binding so the receiver wins over an unannotated
  `self` parameter).
- py_bind_parameters resolves type annotations via py_resolve_annotation:
  scope -> module-qualified registry lookup -> bare NAMED fallback.
- py_eval_expr_type covers literals (int/float/str/bool/None plus list/
  dict/set/tuple containers), names (via scope, then module symbol),
  attribute access on MODULE / NAMED, call expressions (constructors,
  module-local functions, attribute calls), comparison / boolean /
  ternary expressions, and parenthesized / binary fallthrough.
- py_lookup_attribute walks the registry's embedded_types chain with
  the shared CBM_LSP_MAX_LOOKUP_DEPTH cap so MRO chains terminate
  cleanly.
- py_emit_resolved_call writes (caller_qn, callee_qn, strategy,
  confidence) entries to result->resolved_calls. Strategies:
  lsp_direct, lsp_constructor, lsp_method, lsp_module_attr,
  lsp_module_attr_unresolved.

6 new test_py_lsp.c cases cover direct calls, simple method dispatch,
self.method, constructor-then-method, single-inheritance dispatch,
and the no-false-positive guarantee on UNKNOWN receivers.

All 2853 previous tests stay green; 6 new py_lsp tests pass.
2026-05-08 23:47:33 +02:00
Martin Vogel 40eb9afaca feat(py_lsp): bind imports into scope as MODULE / NAMED
Phase 3 of Python LSP integration. py_lsp_bind_imports walks the
import map populated from CBMFileResult.imports and binds each entry
into the root scope:

- `import X` / `import X as Y` -> bind to MODULE(X) (heuristic: when
  module_qn does not end with `.<local_name>`).
- `from X import Y` / `from X import Y as Z` -> bind to NAMED(X.Y).
  Phase 6 attribute resolution will downgrade to MODULE / class /
  function as registry lookups become available.
- `from X import *` -> recorded in the import map but not scope-bound.
  Phase 9 cross-file resolution will use the entry to walk re-exports.
- Relative imports (`from . import x`, `from ..pkg import y`) bind via
  the same heuristic; module path is preserved so cross-file matching
  can still locate the target later.

py_lsp_lookup_in_scope test hook added for unit-level scope inspection.

9 new tests in test_py_lsp.c. All 2844 prior tests stay green.
2026-05-08 23:14:19 +02:00
Martin Vogel b1a6285601 feat(lsp): py_lsp scaffold + smoke tests
Phase 2 of Python LSP integration. Adds the py_lsp module mirroring
the go_lsp / c_lsp pattern: PyLSPContext, single-file entry
(cbm_run_py_lsp), cross-file + batch shells, stdlib registration stub.

Bodies are no-ops at this phase. Subsequent phases fill in:
  Phase 3 — imports
  Phase 4 — scope binding
  Phase 5 — expression typing
  Phase 6 — attribute resolution + method dispatch
  Phase 7 — decorators
  Phase 8 — class hierarchy + generics
  Phase 9 — cross-file resolution + batch
  Phase 10 — cbm_python_stdlib_register from typeshed

Wired into cbm_extract_file alongside the existing Go and C/C++ LSP
calls. lsp_all.c #includes py_lsp.c so the CGo umbrella picks it up
without a separate translation unit.

tests/test_py_lsp.c adds 5 smoke cases: empty source, single function,
single class, syntax error recovery, imports pass-through. The helper
shape (extract_py / find_resolved / require_resolved) matches
test_go_lsp.c so future phases can grow the suite by category.

All 2839 existing tests stay green; 5 new py_lsp tests pass.
2026-05-08 23:06:02 +02:00