Skip to content

Commit f4e6ca9

Browse files
committed
fix: correct Lean scopes, open resolution, and export aliases
1 parent 362b5f1 commit f4e6ca9

4 files changed

Lines changed: 1088 additions & 179 deletions

File tree

‎codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py‎

Lines changed: 23 additions & 107 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from collections import defaultdict
1616
from contextlib import contextmanager
1717
from pathlib import Path
18+
from typing import TYPE_CHECKING
1819

1920
from codewiki.src.be.dependency_analyzer.models.core import CallRelationship, Node
2021
from codewiki.src.be.dependency_analyzer.utils.external_symbols import (
@@ -26,10 +27,11 @@
2627
from codewiki.src.be.dependency_analyzer.utils.patterns import CODE_EXTENSIONS
2728
from codewiki.src.be.dependency_analyzer.utils.security import safe_open_text
2829

29-
logger = logging.getLogger(__name__)
30+
if TYPE_CHECKING:
31+
from codewiki.src.be.dependency_analyzer.analyzers.lean import LeanFile, LeanScope
32+
from codewiki.src.be.dependency_analyzer.analyzers.lean_resolution import LeanNameResolver
3033

31-
# `_resolve_lean_name` result: no declaration has this name (try a shorter one).
32-
_LEAN_NO_MATCH = object()
34+
logger = logging.getLogger(__name__)
3335

3436

3537
class TimeoutError(BaseException):
@@ -676,16 +678,12 @@ def _analyze_vue_file(self, file_path: str, content: str, repo_dir: str):
676678
logger.exception(f"Failed to analyze Vue file {file_path}")
677679

678680
def _reset_lean_state(self) -> None:
679-
# Relative path -> imported module names, per Lean file.
680-
self._lean_imports: dict[str, list[str]] = {}
681-
# Node id -> (namespace prefixes innermost first, open namespaces).
682-
self._lean_scopes: dict[str, tuple[list[str], list[str]]] = {}
683-
# Constructor/field FQN -> ids of the structures or inductives it names.
681+
self._lean_files: dict[str, LeanFile] = {}
682+
self._lean_scopes: dict[str, LeanScope] = {}
684683
self._lean_aliases: dict[str, list[str]] = defaultdict(list)
685684
self._lean_private: set[str] = set()
686-
self._lean_index: dict[str, list[str]] | None = None
687-
self._lean_modules: dict[str, set[str]] = {}
688-
self._lean_visible: dict[str, frozenset[str]] = {}
685+
self._lean_protected: set[str] = set()
686+
self._lean_resolver: LeanNameResolver | None = None
689687

690688
def _analyze_lean_file(self, file_path: str, content: str, repo_dir: str):
691689
"""
@@ -709,110 +707,28 @@ def _analyze_lean_file(self, file_path: str, content: str, repo_dir: str):
709707
self.functions[func.id] = func
710708

711709
self.call_relationships.extend(analyzer.call_relationships)
712-
self._lean_imports[analyzer.relative_path] = analyzer.imports
710+
self._lean_files[analyzer.relative_path] = analyzer.scan
713711
self._lean_scopes.update(analyzer.scopes)
714712
for alias, node_id in analyzer.aliases.items():
715713
self._lean_aliases[alias].append(node_id)
716714
self._lean_private.update(analyzer.private_ids)
715+
self._lean_protected.update(analyzer.protected_ids)
717716
except Exception:
718717
logger.exception(f"Failed to analyze Lean file {file_path}")
719718

720-
def _build_lean_index(self) -> dict[str, list[str]]:
721-
"""FQN -> Lean node ids, and module name -> files. A module name maps
722-
to every file whose path ends with it (`Geo.Point` -> `src/Geo/Point.lean`),
723-
because the Lake source folder is not known."""
724-
if self._lean_index is None:
725-
index: dict[str, list[str]] = defaultdict(list)
726-
for func_id, func in self.functions.items():
727-
if func.language == "lean" and func.qualified_name:
728-
index[func.qualified_name].append(func_id)
729-
for alias, node_ids in self._lean_aliases.items():
730-
for node_id in node_ids:
731-
if node_id not in index[alias]:
732-
index[alias].append(node_id)
733-
modules: dict[str, set[str]] = defaultdict(set)
734-
for rel in self._lean_imports:
735-
parts = rel[: -len(".lean")].split("/")
736-
for k in range(len(parts)):
737-
modules[".".join(parts[k:])].add(rel)
738-
self._lean_index = index
739-
self._lean_modules = modules
740-
return self._lean_index
741-
742-
def _lean_visible_files(self, rel: str) -> frozenset[str]:
743-
"""The file itself and every repository file it imports, transitively."""
744-
if rel not in self._lean_visible:
745-
self._build_lean_index()
746-
seen = {rel}
747-
queue = [rel]
748-
while queue:
749-
current = queue.pop()
750-
for module in self._lean_imports.get(current, []):
751-
for target in self._lean_modules.get(module, ()):
752-
if target not in seen:
753-
seen.add(target)
754-
queue.append(target)
755-
self._lean_visible[rel] = frozenset(seen)
756-
return self._lean_visible[rel]
757-
758719
def _resolve_lean_callee(self, callee: str, caller: Node) -> str | None:
759-
"""Resolve a Lean reference to one declaration by exact FQN, in Lean's
760-
order: the caller's namespaces (innermost first), the root, then the
761-
open namespaces. No match, or more than one, drops the reference.
762-
763-
When the whole dotted name matches nothing, its longest prefix that
764-
matches is the constant and the rest are projections, as in Lean
765-
(`origin.x` is `origin` then the field `x`)."""
766-
parts = callee.split(".")
767-
for end in range(len(parts), 0, -1):
768-
found = self._resolve_lean_name(".".join(parts[:end]), caller)
769-
if found is not _LEAN_NO_MATCH:
770-
return found
771-
return None
772-
773-
def _resolve_lean_name(self, callee: str, caller: Node):
774-
"""One exact name: a node id, None (ambiguous or recursion: stop), or
775-
_LEAN_NO_MATCH (try a shorter prefix)."""
776-
index = self._build_lean_index()
777-
visible = self._lean_visible_files(caller.relative_path)
778-
namespaces, opens = self._lean_scopes.get(caller.id, ([], []))
779-
780-
def qualify(prefix: str, name: str) -> str:
781-
return f"{prefix}.{name}" if prefix else name
782-
783-
def matches(fqn: str) -> list[str]:
784-
return [
785-
node_id
786-
for node_id in index.get(fqn, [])
787-
if self.functions[node_id].relative_path in visible
788-
and (
789-
node_id not in self._lean_private
790-
or self.functions[node_id].relative_path == caller.relative_path
791-
)
792-
]
793-
794-
def unique(found) -> str | None:
795-
# A reference to the caller itself is recursion, not an edge.
796-
found = list(found)
797-
return found[0] if len(found) == 1 and found[0] != caller.id else None
798-
799-
if callee.startswith("_root_."):
800-
found = matches(callee[len("_root_.") :])
801-
return unique(found) if found else _LEAN_NO_MATCH
802-
803-
prefixes = [*namespaces, ""]
804-
for prefix in prefixes:
805-
found = matches(qualify(prefix, callee))
806-
if found:
807-
return unique(found) # the innermost match shadows the outer ones
808-
809-
opened = {
810-
node_id
811-
for name in opens
812-
for prefix in prefixes
813-
for node_id in matches(qualify(qualify(prefix, name), callee))
814-
}
815-
return unique(opened) if opened else _LEAN_NO_MATCH
720+
from codewiki.src.be.dependency_analyzer.analyzers.lean_resolution import LeanNameResolver
721+
722+
if self._lean_resolver is None:
723+
self._lean_resolver = LeanNameResolver(
724+
self.functions,
725+
self._lean_files,
726+
self._lean_scopes,
727+
self._lean_aliases,
728+
self._lean_private,
729+
self._lean_protected,
730+
)
731+
return self._lean_resolver.resolve(callee, caller)
816732

817733
def _analyze_go_file(self, file_path: str, content: str, repo_dir: str):
818734
"""

0 commit comments

Comments
 (0)