|
| 1 | +"""The Analysis Manager: registry, dependency DAG, lazy evaluation, cache, invalidation.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from typing import Any, overload |
| 6 | + |
| 7 | +from coretrace_python.analysis.provider import ( |
| 8 | + Analysis, |
| 9 | + AnyAnalysis, |
| 10 | + FunctionAnalysis, |
| 11 | + R, |
| 12 | + TransformationPass, |
| 13 | +) |
| 14 | +from coretrace_python.hir import nodes |
| 15 | +from coretrace_python.source import SourceSpan |
| 16 | + |
| 17 | + |
| 18 | +class AnalysisError(Exception): |
| 19 | + """Misuse of the analysis registry or dependency declarations.""" |
| 20 | + |
| 21 | + |
| 22 | +class UnregisteredAnalysisError(AnalysisError): |
| 23 | + pass |
| 24 | + |
| 25 | + |
| 26 | +class UndeclaredDependencyError(AnalysisError): |
| 27 | + pass |
| 28 | + |
| 29 | + |
| 30 | +class CyclicDependencyError(AnalysisError): |
| 31 | + pass |
| 32 | + |
| 33 | + |
| 34 | +_CacheKey = tuple[AnyAnalysis, SourceSpan | None] |
| 35 | + |
| 36 | + |
| 37 | +class AnalysisManager: |
| 38 | + """Compute registered analyses lazily, once, and share their results.""" |
| 39 | + |
| 40 | + def __init__(self, module: nodes.Module) -> None: |
| 41 | + self._module = module |
| 42 | + self._registry: set[AnyAnalysis] = set() |
| 43 | + self._cache: dict[_CacheKey, Any] = {} |
| 44 | + self._computing: list[AnyAnalysis] = [] |
| 45 | + |
| 46 | + @property |
| 47 | + def module(self) -> nodes.Module: |
| 48 | + return self._module |
| 49 | + |
| 50 | + # ------------------------------------------------------------------ registry |
| 51 | + |
| 52 | + def register(self, *analyses: AnyAnalysis) -> None: |
| 53 | + for analysis in analyses: |
| 54 | + self._registry.add(analysis) |
| 55 | + self._check_acyclic(analysis) |
| 56 | + |
| 57 | + def dependencies(self, analysis: AnyAnalysis) -> frozenset[AnyAnalysis]: |
| 58 | + """Transitive closure of ``analysis.requires``.""" |
| 59 | + |
| 60 | + found: set[AnyAnalysis] = set() |
| 61 | + pending = list(analysis.requires) |
| 62 | + while pending: |
| 63 | + dependency = pending.pop() |
| 64 | + if dependency not in found: |
| 65 | + found.add(dependency) |
| 66 | + pending.extend(dependency.requires) |
| 67 | + return frozenset(found) |
| 68 | + |
| 69 | + def _check_acyclic(self, root: AnyAnalysis) -> None: |
| 70 | + path: list[AnyAnalysis] = [] |
| 71 | + |
| 72 | + def visit(analysis: AnyAnalysis) -> None: |
| 73 | + if analysis in path: |
| 74 | + cycle = [*path[path.index(analysis) :], analysis] |
| 75 | + raise CyclicDependencyError( |
| 76 | + "dependency cycle: " + " -> ".join(a.name for a in cycle) |
| 77 | + ) |
| 78 | + path.append(analysis) |
| 79 | + for dependency in analysis.requires: |
| 80 | + visit(dependency) |
| 81 | + path.pop() |
| 82 | + |
| 83 | + visit(root) |
| 84 | + |
| 85 | + # ------------------------------------------------------------------ evaluation |
| 86 | + |
| 87 | + @overload |
| 88 | + def get(self, analysis: type[Analysis[R]], function: None = None) -> R: ... |
| 89 | + |
| 90 | + @overload |
| 91 | + def get(self, analysis: type[FunctionAnalysis[R]], function: nodes.Function) -> R: ... |
| 92 | + |
| 93 | + def get(self, analysis: AnyAnalysis, function: nodes.Function | None = None) -> Any: |
| 94 | + self._check_target(analysis, function) |
| 95 | + if analysis not in self._registry: |
| 96 | + raise UnregisteredAnalysisError(f"analysis {analysis.name!r} is not registered") |
| 97 | + if self._computing and analysis not in self._computing[-1].requires: |
| 98 | + current = self._computing[-1] |
| 99 | + raise UndeclaredDependencyError( |
| 100 | + f"{current.name} requests {analysis.name} without declaring it in requires" |
| 101 | + ) |
| 102 | + |
| 103 | + key = self._key(analysis, function) |
| 104 | + if key in self._cache: |
| 105 | + return self._cache[key] |
| 106 | + |
| 107 | + self._computing.append(analysis) |
| 108 | + try: |
| 109 | + if function is None: |
| 110 | + assert issubclass(analysis, Analysis) |
| 111 | + result = analysis.compute(self) |
| 112 | + else: |
| 113 | + assert issubclass(analysis, FunctionAnalysis) |
| 114 | + result = analysis.compute(self, function) |
| 115 | + finally: |
| 116 | + self._computing.pop() |
| 117 | + self._cache[key] = result |
| 118 | + return result |
| 119 | + |
| 120 | + def is_cached(self, analysis: AnyAnalysis, function: nodes.Function | None = None) -> bool: |
| 121 | + self._check_target(analysis, function) |
| 122 | + return self._key(analysis, function) in self._cache |
| 123 | + |
| 124 | + # ------------------------------------------------------------------ invalidation |
| 125 | + |
| 126 | + def run(self, transformation: type[TransformationPass]) -> None: |
| 127 | + """Run a transformation, then drop every cached result it does not preserve.""" |
| 128 | + |
| 129 | + transformation.run(self) |
| 130 | + self._cache = { |
| 131 | + key: result for key, result in self._cache.items() if key[0] in transformation.preserves |
| 132 | + } |
| 133 | + |
| 134 | + # ------------------------------------------------------------------ helpers |
| 135 | + |
| 136 | + @staticmethod |
| 137 | + def _check_target(analysis: AnyAnalysis, function: nodes.Function | None) -> None: |
| 138 | + if issubclass(analysis, FunctionAnalysis) and function is None: |
| 139 | + raise TypeError(f"{analysis.name} is a function analysis and needs a function") |
| 140 | + if issubclass(analysis, Analysis) and function is not None: |
| 141 | + raise TypeError(f"{analysis.name} is a module analysis and takes no function") |
| 142 | + |
| 143 | + @staticmethod |
| 144 | + def _key(analysis: AnyAnalysis, function: nodes.Function | None) -> _CacheKey: |
| 145 | + return (analysis, None if function is None else function.span) |
0 commit comments