range_shift.py 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. """Diff-aware line-shift map for cross-edit LSP delta filtering.
  2. An edit that inserts/deletes lines moves every diagnostic below it, and the delta
  3. filter keys on ``(severity, code, source, message, range)`` — so shifted-but-identical
  4. diagnostics would look brand-new. We build a pre→post line map from
  5. ``difflib.SequenceMatcher.get_opcodes()`` and apply it to the baseline before the
  6. set-difference; diagnostics in a deleted region map to ``None`` and drop out.
  7. Keeping range in the key preserves the "same error at a new line" signal.
  8. """
  9. from __future__ import annotations
  10. import difflib
  11. from typing import Any, Callable, Dict, List, Optional
  12. _Shift = Callable[[int], Optional[int]]
  13. def build_line_shift(pre_text: str, post_text: str) -> _Shift:
  14. """Return ``shift(pre_line) -> post_line | None`` over 0-indexed lines (LSP convention).
  15. ``None`` means the line was deleted. One ``get_opcodes()`` call up front;
  16. the closure scans the (small) opcode list per lookup.
  17. """
  18. pre_lines = pre_text.splitlines() if pre_text else []
  19. post_lines = post_text.splitlines() if post_text else []
  20. if pre_lines == post_lines:
  21. return lambda line: line
  22. # Opcodes are (tag, i1, i2, j1, j2): i-range in pre, j-range in post.
  23. opcodes = difflib.SequenceMatcher(a=pre_lines, b=post_lines, autojunk=False).get_opcodes()
  24. def shift(line: int) -> Optional[int]:
  25. for tag, i1, i2, j1, _j2 in opcodes:
  26. if i1 <= line < i2:
  27. # 'equal' maps by offset; 'delete'/'replace' lines have no
  28. # post counterpart. 'insert' has i1 == i2 and can't match.
  29. return line - i1 + j1 if tag == "equal" else None
  30. if line < i1:
  31. break
  32. # Past the last pre line: anchor at end of post.
  33. return max(0, len(post_lines) - 1) if post_lines else None
  34. return shift
  35. def shift_diagnostic_range(diag: dict[str, Any], shift: _Shift) -> Optional[dict[str, Any]]:
  36. """Copy of ``diag`` with its line range remapped; ``None`` if the start line was deleted.
  37. A multi-line diagnostic whose end straddles the deletion collapses to a
  38. single-line range at the shifted start so it stays in the baseline.
  39. """
  40. rng = diag.get("range") or {}
  41. start = rng.get("start") or {}
  42. end = rng.get("end") or {}
  43. pre_start_line = int(start.get("line", 0))
  44. new_start_line = shift(pre_start_line)
  45. if new_start_line is None:
  46. return None
  47. new_end_line = shift(int(end.get("line", pre_start_line)))
  48. if new_end_line is None:
  49. new_end_line = new_start_line
  50. return {
  51. **diag,
  52. "range": {
  53. "start": {"line": new_start_line, "character": int(start.get("character", 0))},
  54. "end": {"line": new_end_line, "character": int(end.get("character", 0))},
  55. },
  56. }
  57. def shift_baseline(baseline: list[dict[str, Any]], shift: _Shift) -> list[dict[str, Any]]:
  58. """Apply ``shift`` to every diagnostic in ``baseline``, dropping deleted entries."""
  59. shifted = (shift_diagnostic_range(d, shift) for d in baseline if isinstance(d, dict))
  60. return [s for s in shifted if s is not None]
  61. __all__ = ["build_line_shift", "shift_baseline", "shift_diagnostic_range"]