blastdiff 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,456 @@
1
+ """Deterministic AST symbol-diff and caller blast-radius analyzer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import PurePosixPath
6
+
7
+ from blastdiff.core.languages.base import analyze_file_cached, get_analyzer_for_path
8
+ from blastdiff.core.models import (
9
+ BlastRadiusReport,
10
+ CallerImpact,
11
+ CallSite,
12
+ FileReview,
13
+ FileSymbols,
14
+ ImportRef,
15
+ SymbolChange,
16
+ SymbolDef,
17
+ )
18
+
19
+ # Common builtins and generic container/object methods that require an explicit
20
+ # module import link to count as a cross-file caller.
21
+ _COMMON_GENERIC_NAMES: frozenset[str] = frozenset(
22
+ {
23
+ "get",
24
+ "set",
25
+ "put",
26
+ "pop",
27
+ "add",
28
+ "run",
29
+ "open",
30
+ "close",
31
+ "read",
32
+ "write",
33
+ "items",
34
+ "keys",
35
+ "values",
36
+ "append",
37
+ "extend",
38
+ "update",
39
+ "copy",
40
+ "clear",
41
+ "format",
42
+ "split",
43
+ "join",
44
+ "strip",
45
+ "replace",
46
+ "find",
47
+ "index",
48
+ "count",
49
+ "sort",
50
+ "reverse",
51
+ "push",
52
+ "shift",
53
+ "slice",
54
+ "splice",
55
+ "map",
56
+ "filter",
57
+ "reduce",
58
+ "forEach",
59
+ "includes",
60
+ "toString",
61
+ "valueOf",
62
+ "len",
63
+ "str",
64
+ "int",
65
+ "float",
66
+ "bool",
67
+ "list",
68
+ "dict",
69
+ "tuple",
70
+ "print",
71
+ "super",
72
+ "type",
73
+ "isinstance",
74
+ "hasattr",
75
+ "getattr",
76
+ "setattr",
77
+ "next",
78
+ "iter",
79
+ "range",
80
+ "enumerate",
81
+ "zip",
82
+ "min",
83
+ "max",
84
+ "sum",
85
+ "any",
86
+ "all",
87
+ "__init__",
88
+ "__str__",
89
+ "__repr__",
90
+ "constructor",
91
+ }
92
+ )
93
+
94
+
95
+ def is_test_path(file_path: str) -> bool:
96
+ """Return True if a repository-relative path represents a test file."""
97
+ norm = file_path.replace("\\", "/").lower()
98
+ parts = [p for p in norm.split("/") if p]
99
+ if not parts:
100
+ return False
101
+ basename = parts[-1]
102
+ dir_parts = parts[:-1]
103
+ if any(p in ("tests", "test", "__tests__") for p in dir_parts):
104
+ return True
105
+ if basename.startswith("test_"):
106
+ return True
107
+ if "_test." in basename or ".test." in basename or ".spec." in basename:
108
+ return True
109
+ return False
110
+
111
+
112
+ def _find_enclosing_symbol(
113
+ line_numbers: list[int],
114
+ definitions: list[SymbolDef],
115
+ ) -> SymbolDef | None:
116
+ """Return the innermost SymbolDef overlapping any line in line_numbers."""
117
+ if not line_numbers or not definitions:
118
+ return None
119
+ best: SymbolDef | None = None
120
+ best_span: int | None = None
121
+ for sym in definitions:
122
+ if any(sym.start_line <= ln <= sym.end_line for ln in line_numbers):
123
+ span = sym.end_line - sym.start_line
124
+ if best is None or best_span is None or span < best_span:
125
+ best = sym
126
+ best_span = span
127
+ return best
128
+
129
+
130
+ def _module_candidates_for_path(file_path: str) -> set[str]:
131
+ """Derive possible import module tokens matching a file path."""
132
+ norm = file_path.replace("\\", "/").lstrip("./")
133
+ p = PurePosixPath(norm)
134
+ parts = list(p.parts)
135
+ if not parts:
136
+ return set()
137
+ stem = p.stem
138
+ candidates: set[str] = set()
139
+ if stem and stem not in ("__init__", "index"):
140
+ candidates.add(stem)
141
+ elif len(parts) >= 2:
142
+ candidates.add(parts[-2])
143
+
144
+ # Build dotted and slash suffixes without file extension
145
+ no_ext_parts = [*parts[:-1], stem] if stem not in ("__init__", "index") else parts[:-1]
146
+ for i in range(len(no_ext_parts)):
147
+ suffix_parts = no_ext_parts[i:]
148
+ if suffix_parts:
149
+ candidates.add(".".join(suffix_parts))
150
+ candidates.add("/".join(suffix_parts))
151
+ return candidates
152
+
153
+
154
+ def _file_imports_target(
155
+ imports: list[ImportRef],
156
+ target_candidates: set[str],
157
+ bare_name: str,
158
+ enclosing_class: str | None,
159
+ ) -> bool:
160
+ """Return True if a file's imports reference the defining module or symbol."""
161
+ for imp in imports:
162
+ if bare_name in imp.names or (enclosing_class and enclosing_class in imp.names):
163
+ return True
164
+ mod = imp.module.strip()
165
+ if not mod:
166
+ continue
167
+ mod_clean = mod.lstrip(".").lstrip("/")
168
+ if mod_clean in target_candidates:
169
+ return True
170
+ # Handle relative JS/TS imports like `./pricing`, `../utils/pricing`
171
+ if "/" in mod_clean:
172
+ mod_no_ext = mod_clean
173
+ for ext in (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"):
174
+ if mod_no_ext.endswith(ext):
175
+ mod_no_ext = mod_no_ext[: -len(ext)]
176
+ break
177
+ if mod_no_ext in target_candidates or mod_no_ext.rsplit("/", 1)[-1] in target_candidates:
178
+ return True
179
+ if "." in mod_clean:
180
+ last_seg = mod_clean.rsplit(".", 1)[-1]
181
+ if last_seg in target_candidates:
182
+ return True
183
+ # Handle `from . import module_stem`
184
+ for name in imp.names:
185
+ if name in target_candidates:
186
+ return True
187
+ return False
188
+
189
+
190
+ def analyze_blast_radius(
191
+ files: list[FileReview],
192
+ base_sources: dict[str, str],
193
+ head_sources: dict[str, str],
194
+ repo_sources: dict[str, str],
195
+ ) -> tuple[BlastRadiusReport, dict[str, list[SymbolChange]], dict[str, list[str]]]:
196
+ """Analyze symbol changes across diff files and compute caller blast radius."""
197
+ diff_paths = {f.path for f in files}
198
+ deleted_paths = {f.path for f in files if f.status == "deleted"}
199
+
200
+ parsed_head_cache: dict[str, FileSymbols] = {}
201
+ all_symbol_changes: list[tuple[SymbolChange, SymbolDef]] = []
202
+ per_file_changes_map: dict[str, list[tuple[SymbolChange, SymbolDef]]] = {}
203
+
204
+ for file_review in files:
205
+ analyzer = get_analyzer_for_path(file_review.path)
206
+ if analyzer is None:
207
+ continue
208
+
209
+ base_key = file_review.old_path or file_review.path
210
+ base_text = base_sources.get(base_key, "") if file_review.status != "added" else ""
211
+ head_text = head_sources.get(file_review.path, "") if file_review.status != "deleted" else ""
212
+
213
+ base_syms = (
214
+ analyze_file_cached(file_review.path, base_text)
215
+ if base_text
216
+ else None
217
+ ) or FileSymbols(file_path=file_review.path, language=file_review.language)
218
+ head_syms = (
219
+ analyze_file_cached(file_review.path, head_text)
220
+ if head_text
221
+ else None
222
+ ) or FileSymbols(file_path=file_review.path, language=file_review.language)
223
+ if head_text:
224
+ parsed_head_cache[file_review.path] = head_syms
225
+
226
+ # Map each hunk to its innermost enclosing symbol
227
+ added_lines: set[int] = set()
228
+ deleted_lines: set[int] = set()
229
+ for hunk in file_review.hunks:
230
+ hunk_new_lines = [
231
+ dl.new_lineno for dl in hunk.lines if dl.kind == "add" and dl.new_lineno is not None
232
+ ]
233
+ hunk_old_lines = [
234
+ dl.old_lineno for dl in hunk.lines if dl.kind == "del" and dl.old_lineno is not None
235
+ ]
236
+ hunk_ctx_new = [
237
+ dl.new_lineno for dl in hunk.lines if dl.kind == "ctx" and dl.new_lineno is not None
238
+ ]
239
+ added_lines.update(hunk_new_lines)
240
+ deleted_lines.update(hunk_old_lines)
241
+
242
+ enclosing = _find_enclosing_symbol(hunk_new_lines or hunk_ctx_new, head_syms.definitions)
243
+ if enclosing is None and hunk_old_lines:
244
+ enclosing = _find_enclosing_symbol(hunk_old_lines, base_syms.definitions)
245
+ if enclosing is not None:
246
+ hunk.symbol_name = enclosing.qualified_name
247
+
248
+ base_defs: dict[str, SymbolDef] = {d.qualified_name: d for d in base_syms.definitions}
249
+ head_defs: dict[str, SymbolDef] = {d.qualified_name: d for d in head_syms.definitions}
250
+
251
+ # Collect method line spans per class to avoid marking a class modified
252
+ # solely because a child method body changed.
253
+ head_child_spans: dict[str, list[tuple[int, int]]] = {}
254
+ for d in head_syms.definitions:
255
+ if d.kind == "method" and "." in d.qualified_name:
256
+ cls_name = d.qualified_name.rsplit(".", 1)[0]
257
+ head_child_spans.setdefault(cls_name, []).append((d.start_line, d.end_line))
258
+
259
+ base_child_spans: dict[str, list[tuple[int, int]]] = {}
260
+ for d in base_syms.definitions:
261
+ if d.kind == "method" and "." in d.qualified_name:
262
+ cls_name = d.qualified_name.rsplit(".", 1)[0]
263
+ base_child_spans.setdefault(cls_name, []).append((d.start_line, d.end_line))
264
+
265
+ file_changes: list[tuple[SymbolChange, SymbolDef]] = []
266
+
267
+ # Changed or removed symbols
268
+ for qname, bdef in base_defs.items():
269
+ hdef = head_defs.get(qname)
270
+ if hdef is None:
271
+ sc = SymbolChange(
272
+ file_path=file_review.path,
273
+ name=qname,
274
+ kind=bdef.kind,
275
+ change_type="removed",
276
+ old_signature=bdef.signature,
277
+ new_signature=None,
278
+ start_line=bdef.start_line,
279
+ )
280
+ file_changes.append((sc, bdef))
281
+ elif bdef.signature != hdef.signature:
282
+ sc = SymbolChange(
283
+ file_path=file_review.path,
284
+ name=qname,
285
+ kind=hdef.kind,
286
+ change_type="signature_changed",
287
+ old_signature=bdef.signature,
288
+ new_signature=hdef.signature,
289
+ start_line=hdef.start_line,
290
+ )
291
+ file_changes.append((sc, hdef))
292
+ else:
293
+ # Check if body lines overlap the diff
294
+ if hdef.kind == "class":
295
+ h_spans = head_child_spans.get(qname, [])
296
+ b_spans = base_child_spans.get(qname, [])
297
+ head_hit = any(
298
+ hdef.start_line <= ln <= hdef.end_line
299
+ and not any(s <= ln <= e for s, e in h_spans)
300
+ for ln in added_lines
301
+ )
302
+ base_hit = any(
303
+ bdef.start_line <= ln <= bdef.end_line
304
+ and not any(s <= ln <= e for s, e in b_spans)
305
+ for ln in deleted_lines
306
+ )
307
+ else:
308
+ head_hit = any(hdef.start_line <= ln <= hdef.end_line for ln in added_lines)
309
+ base_hit = any(bdef.start_line <= ln <= bdef.end_line for ln in deleted_lines)
310
+
311
+ if head_hit or base_hit:
312
+ sc = SymbolChange(
313
+ file_path=file_review.path,
314
+ name=qname,
315
+ kind=hdef.kind,
316
+ change_type="modified",
317
+ old_signature=bdef.signature,
318
+ new_signature=hdef.signature,
319
+ start_line=hdef.start_line,
320
+ )
321
+ file_changes.append((sc, hdef))
322
+
323
+ # Newly added symbols
324
+ for qname, hdef in head_defs.items():
325
+ if qname not in base_defs:
326
+ sc = SymbolChange(
327
+ file_path=file_review.path,
328
+ name=qname,
329
+ kind=hdef.kind,
330
+ change_type="added",
331
+ old_signature=None,
332
+ new_signature=hdef.signature,
333
+ start_line=hdef.start_line,
334
+ )
335
+ file_changes.append((sc, hdef))
336
+
337
+ file_changes.sort(key=lambda pair: (pair[0].start_line, pair[0].name))
338
+ per_file_changes_map[file_review.path] = file_changes
339
+ all_symbol_changes.extend(file_changes)
340
+
341
+ # Index all repository sources (preferring head_sources for changed files)
342
+ effective_sources: dict[str, str] = {}
343
+ for path, src in repo_sources.items():
344
+ norm = path.replace("\\", "/")
345
+ if norm not in deleted_paths:
346
+ effective_sources[norm] = src
347
+ for path, src in head_sources.items():
348
+ norm = path.replace("\\", "/")
349
+ if norm not in deleted_paths:
350
+ effective_sources[norm] = src
351
+
352
+ calls_by_name: dict[str, list[CallSite]] = {}
353
+ imports_by_file: dict[str, list[ImportRef]] = {}
354
+
355
+ if all_symbol_changes:
356
+ for path, src in effective_sources.items():
357
+ syms = parsed_head_cache.get(path)
358
+ if syms is None:
359
+ syms = analyze_file_cached(path, src)
360
+ if syms is None:
361
+ continue
362
+ parsed_head_cache[path] = syms
363
+ imports_by_file[path] = syms.imports
364
+ for call in syms.calls:
365
+ calls_by_name.setdefault(call.callee_name, []).append(call)
366
+
367
+ # Match callers to each SymbolChange
368
+ module_candidates_cache: dict[str, set[str]] = {}
369
+ for sc, sym_def in all_symbol_changes:
370
+ def_file = sc.file_path
371
+ bare_name = sym_def.name
372
+ enclosing_class = (
373
+ sym_def.qualified_name.rsplit(".", 1)[0]
374
+ if sym_def.kind == "method" and "." in sym_def.qualified_name
375
+ else None
376
+ )
377
+ if def_file not in module_candidates_cache:
378
+ module_candidates_cache[def_file] = _module_candidates_for_path(def_file)
379
+ target_candidates = module_candidates_cache[def_file]
380
+
381
+ raw_calls = calls_by_name.get(bare_name, [])
382
+ seen_keys: set[tuple[str, int, str | None]] = set()
383
+ impacts: list[CallerImpact] = []
384
+
385
+ for call in raw_calls:
386
+ # Exclude definition line itself
387
+ if call.file_path == def_file and call.line == sc.start_line:
388
+ continue
389
+
390
+ if call.file_path != def_file:
391
+ caller_imports = imports_by_file.get(call.file_path, [])
392
+ has_import_link = _file_imports_target(
393
+ caller_imports,
394
+ target_candidates,
395
+ bare_name,
396
+ enclosing_class,
397
+ )
398
+ if not has_import_link:
399
+ if not sym_def.exported:
400
+ continue
401
+ if bare_name in _COMMON_GENERIC_NAMES:
402
+ continue
403
+
404
+ dedup_key = (call.file_path, call.line, call.enclosing_symbol)
405
+ if dedup_key in seen_keys:
406
+ continue
407
+ seen_keys.add(dedup_key)
408
+
409
+ impacts.append(
410
+ CallerImpact(
411
+ file_path=call.file_path,
412
+ line=call.line,
413
+ enclosing_symbol=call.enclosing_symbol,
414
+ snippet=call.snippet,
415
+ in_diff=(call.file_path in diff_paths),
416
+ is_test=is_test_path(call.file_path),
417
+ )
418
+ )
419
+
420
+ impacts.sort(key=lambda c: (c.is_test, c.in_diff, c.file_path, c.line))
421
+ sc.callers = impacts
422
+ sc.unmodified_caller_count = sum(1 for c in impacts if not c.in_diff and not c.is_test)
423
+ sc.test_callers = [c for c in impacts if c.is_test]
424
+
425
+ per_file_symbol_changes: dict[str, list[SymbolChange]] = {}
426
+ per_file_reaching_tests: dict[str, list[str]] = {}
427
+
428
+ for file_review in files:
429
+ pairs = per_file_changes_map.get(file_review.path, [])
430
+ changes = [sc for sc, _ in pairs]
431
+ per_file_symbol_changes[file_review.path] = changes
432
+ file_review.symbol_changes = changes
433
+
434
+ reaching_set: set[str] = set()
435
+ for sc in changes:
436
+ for tc in sc.test_callers:
437
+ label = (
438
+ f"{tc.file_path}::{tc.enclosing_symbol}"
439
+ if tc.enclosing_symbol
440
+ else f"{tc.file_path}:{tc.line}"
441
+ )
442
+ reaching_set.add(label)
443
+ reaching_sorted = sorted(reaching_set)
444
+ per_file_reaching_tests[file_review.path] = reaching_sorted
445
+ file_review.reaching_tests = reaching_sorted
446
+
447
+ flat_changes = [sc for sc, _ in all_symbol_changes]
448
+ report = BlastRadiusReport(
449
+ total_symbol_changes=len(flat_changes),
450
+ signature_breaks=sum(1 for c in flat_changes if c.change_type == "signature_changed"),
451
+ removed_symbols=sum(1 for c in flat_changes if c.change_type == "removed"),
452
+ unmodified_callers_total=sum(c.unmodified_caller_count for c in flat_changes),
453
+ changes=flat_changes,
454
+ )
455
+
456
+ return report, per_file_symbol_changes, per_file_reaching_tests