ai-editor-tree-engine-dev 1.0.176__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.
Files changed (121) hide show
  1. ai_editor_tree_engine_dev-1.0.176.dist-info/METADATA +35 -0
  2. ai_editor_tree_engine_dev-1.0.176.dist-info/RECORD +121 -0
  3. ai_editor_tree_engine_dev-1.0.176.dist-info/WHEEL +5 -0
  4. ai_editor_tree_engine_dev-1.0.176.dist-info/licenses/LICENSE +21 -0
  5. ai_editor_tree_engine_dev-1.0.176.dist-info/top_level.txt +1 -0
  6. tree_engine/PUBLIC_API.md +161 -0
  7. tree_engine/__init__.py +327 -0
  8. tree_engine/checks/__init__.py +60 -0
  9. tree_engine/checks/builtin/__init__.py +5 -0
  10. tree_engine/checks/builtin/compile_check.py +53 -0
  11. tree_engine/checks/builtin/csv_syntax.py +51 -0
  12. tree_engine/checks/builtin/docstrings.py +211 -0
  13. tree_engine/checks/builtin/encoding.py +55 -0
  14. tree_engine/checks/builtin/fleet_rules.py +227 -0
  15. tree_engine/checks/builtin/format_syntax.py +82 -0
  16. tree_engine/checks/builtin/jsonl_syntax.py +49 -0
  17. tree_engine/checks/builtin/shipped.py +52 -0
  18. tree_engine/checks/builtin/syntax.py +118 -0
  19. tree_engine/checks/builtin/xml_wellformed.py +51 -0
  20. tree_engine/checks/chain.py +332 -0
  21. tree_engine/checks/external/__init__.py +5 -0
  22. tree_engine/checks/external/_base.py +61 -0
  23. tree_engine/checks/external/bandit.py +53 -0
  24. tree_engine/checks/external/black.py +48 -0
  25. tree_engine/checks/external/flake8.py +38 -0
  26. tree_engine/checks/external/isort.py +38 -0
  27. tree_engine/checks/external/mypy.py +45 -0
  28. tree_engine/checks/external/ruff.py +45 -0
  29. tree_engine/checks/external/runner.py +197 -0
  30. tree_engine/checks/model.py +110 -0
  31. tree_engine/checks/options.py +73 -0
  32. tree_engine/checks/plugin.py +171 -0
  33. tree_engine/checks/registry.py +349 -0
  34. tree_engine/core/address.py +376 -0
  35. tree_engine/core/identifier_map.py +266 -0
  36. tree_engine/core/identity.py +226 -0
  37. tree_engine/core/instrumentation.py +399 -0
  38. tree_engine/core/integrity.py +341 -0
  39. tree_engine/core/integrity_full.py +382 -0
  40. tree_engine/core/journal.py +260 -0
  41. tree_engine/core/journal_compose.py +571 -0
  42. tree_engine/core/live_tree.py +785 -0
  43. tree_engine/core/locking.py +188 -0
  44. tree_engine/core/move.py +585 -0
  45. tree_engine/core/move_references.py +323 -0
  46. tree_engine/core/node_types.py +408 -0
  47. tree_engine/core/nodes.py +348 -0
  48. tree_engine/core/offsets.py +24 -0
  49. tree_engine/core/operations.py +825 -0
  50. tree_engine/core/plugin_boundary.py +160 -0
  51. tree_engine/core/position_map.py +263 -0
  52. tree_engine/core/position_transfer.py +512 -0
  53. tree_engine/core/range_refresh.py +366 -0
  54. tree_engine/core/reference_cache.py +360 -0
  55. tree_engine/core/references.py +223 -0
  56. tree_engine/core/reparse.py +378 -0
  57. tree_engine/core/short_id.py +296 -0
  58. tree_engine/core/subtree_apply.py +397 -0
  59. tree_engine/core/subtree_copy.py +399 -0
  60. tree_engine/core/transactions.py +397 -0
  61. tree_engine/core/trivia.py +396 -0
  62. tree_engine/core/updates.py +398 -0
  63. tree_engine/core/validation.py +377 -0
  64. tree_engine/errors.py +104 -0
  65. tree_engine/exceptions.py +376 -0
  66. tree_engine/facade.py +4524 -0
  67. tree_engine/plugins/_statements.py +369 -0
  68. tree_engine/plugins/bsl/block_edit.py +449 -0
  69. tree_engine/plugins/bsl/blocks.py +127 -0
  70. tree_engine/plugins/bsl/checker.py +297 -0
  71. tree_engine/plugins/bsl/dialects.py +303 -0
  72. tree_engine/plugins/bsl/generator.py +481 -0
  73. tree_engine/plugins/bsl/import_map.py +995 -0
  74. tree_engine/plugins/bsl/plugin.py +452 -0
  75. tree_engine/plugins/contract.py +355 -0
  76. tree_engine/plugins/cpp/import_map.py +505 -0
  77. tree_engine/plugins/cpp/languages.py +99 -0
  78. tree_engine/plugins/cpp/plugin.py +501 -0
  79. tree_engine/plugins/csv_format.py +676 -0
  80. tree_engine/plugins/detachable.py +156 -0
  81. tree_engine/plugins/fallback.py +421 -0
  82. tree_engine/plugins/ini_format.py +330 -0
  83. tree_engine/plugins/json_format.py +813 -0
  84. tree_engine/plugins/json_pointer.py +203 -0
  85. tree_engine/plugins/jsonl_format.py +392 -0
  86. tree_engine/plugins/markdown_format.py +748 -0
  87. tree_engine/plugins/onec_query_format.py +61 -0
  88. tree_engine/plugins/parse_position.py +54 -0
  89. tree_engine/plugins/plain_text.py +1543 -0
  90. tree_engine/plugins/python/export_map.py +306 -0
  91. tree_engine/plugins/python/import_map.py +429 -0
  92. tree_engine/plugins/python/plugin.py +1710 -0
  93. tree_engine/plugins/registry.py +497 -0
  94. tree_engine/plugins/scan.py +87 -0
  95. tree_engine/plugins/selection.py +228 -0
  96. tree_engine/plugins/sql_format.py +61 -0
  97. tree_engine/plugins/toml_format.py +1072 -0
  98. tree_engine/plugins/xml_format.py +911 -0
  99. tree_engine/plugins/yaml/builder.py +49 -0
  100. tree_engine/plugins/yaml/emitter.py +225 -0
  101. tree_engine/plugins/yaml/flow.py +227 -0
  102. tree_engine/plugins/yaml/plugin.py +458 -0
  103. tree_engine/plugins/yaml/ranges.py +52 -0
  104. tree_engine/plugins/yaml/reader.py +359 -0
  105. tree_engine/plugins/yaml/scanner.py +298 -0
  106. tree_engine/query/adapter.py +283 -0
  107. tree_engine/query/engine.py +853 -0
  108. tree_engine/query/inspection.py +498 -0
  109. tree_engine/query/outline.py +288 -0
  110. tree_engine/query/predicates.py +263 -0
  111. tree_engine/query/rendered_lines.py +46 -0
  112. tree_engine/query/results.py +206 -0
  113. tree_engine/query/selector.py +400 -0
  114. tree_engine/query/xml_query.py +747 -0
  115. tree_engine/storage/codec.py +400 -0
  116. tree_engine/storage/document_bridge.py +579 -0
  117. tree_engine/storage/file_txn.py +459 -0
  118. tree_engine/storage/history.py +106 -0
  119. tree_engine/storage/lifecycle.py +622 -0
  120. tree_engine/storage/schema.py +403 -0
  121. tree_engine/storage/session_guard.py +398 -0
@@ -0,0 +1,512 @@
1
+ """Exact ``buffer_range`` geometry for a freshly spliced subtree (bugs b47c3558, 20fb996e).
2
+
3
+ WHY THIS MODULE EXISTS. A format plugin resolves byte spans only for a FULL-DOCUMENT parse
4
+ (``plugins/python/import_map.py``: "a bare fragment CSTNode: no document-level byte-span metadata
5
+ to resolve"), so every node a ``replace``/``insert`` splices in arrives with ``buffer_range=None``
6
+ and stays invisible to every reader keyed on it -- ``node_at_line``'s line-covering walk and
7
+ ``universal_file_search``'s engine-identity correlation alike. Guessing that range from
8
+ neighbouring positions is what bug b47c3558's first fix attempted and what made it WORSE: a guess
9
+ that reaches to the next MEASURED sibling swallows whatever unmeasured node sits between, and a
10
+ guess anchored on the replaced node's own start is one decorator short of the truth.
11
+
12
+ The only honest answer is to MEASURE: re-render the spliced run, re-parse those exact bytes through
13
+ the same format plugin that produced the document, and transfer the spans that parse resolves onto
14
+ the live nodes. Two coordinate systems have to be reconciled for that, which is the whole subtlety
15
+ this module encapsulates:
16
+
17
+ * ISO space -- offsets inside the run's own rendered text, exactly what re-parsing it yields.
18
+ * DOCUMENT space -- offsets inside the whole document, what ``buffer_range`` means.
19
+
20
+ For a run spliced at the top level the two differ by one constant. For a run spliced INSIDE an
21
+ indented container they do not: the container re-indents every line of its content, so each line of
22
+ the run's own text gains a fixed prefix once embedded, and the offset shift grows line by line. The
23
+ model below is exactly that -- a base offset plus a per-line indent width -- and it is never
24
+ assumed: it is SOLVED from the run being replaced (whose true document spans are known) and then
25
+ VERIFIED against every one of that run's own aligned nodes plus the independently measured byte
26
+ delta of the splice. A model that does not reproduce all of them is discarded and nothing is
27
+ assigned, leaving ``buffer_range`` at its ``None`` default, which is a safe absence -- no reader
28
+ can silently read the wrong bytes for a range that is not there -- where a wrong span is not.
29
+
30
+ Nothing here imports a plugin, the facade, or any concrete tree type: the two capabilities it needs
31
+ (render one node's own faithful text, parse a full document and hand back its root) arrive as
32
+ injected callables, exactly as ``core.reparse`` already takes its ``parse_fragment``.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ from bisect import bisect_right
38
+ from dataclasses import dataclass
39
+ from typing import Any, Callable, List, Optional, Sequence, Tuple
40
+
41
+ __all__ = [
42
+ "BLANK_LINE_POLICIES",
43
+ "IndentModel",
44
+ "RunSpans",
45
+ "measure_run",
46
+ "solve_model",
47
+ "reproduces",
48
+ "assign_spans",
49
+ ]
50
+
51
+ RenderNode = Callable[[Any], Optional[Any]]
52
+ ParseDocumentRoot = Callable[[str], Optional[Any]]
53
+
54
+
55
+ def _is_node(value: Any) -> bool:
56
+ """Duck-typed common-model node test (this module imports no tree type)."""
57
+ return hasattr(value, "kind") and hasattr(value, "fields")
58
+
59
+
60
+ def _accepts_span(node: Any) -> bool:
61
+ """Whether ``node``'s own ``buffer_range`` can be written at all, probed by writing back what
62
+ it already holds -- a no-op for a live node, an error for an immutable one.
63
+
64
+ A tree carries a few nodes the live mirror deliberately leaves IMMUTABLE: a container's own
65
+ positional trivia held in ``fields`` and excluded from ``children`` (a python ``Module``'s
66
+ header/footer, an ``IndentedBlock``'s header -- see ``core.live_tree.to_live``). Those are
67
+ outside positional bookkeeping altogether: no mutation can shift them, ``walk`` never reaches
68
+ them, and no addressing reader consults them, so the range they carry is whatever the original
69
+ parse left there and goes stale the first time anything before them is edited. Reading such a
70
+ range as evidence would make a correct model look wrong, so they are excluded from measurement
71
+ entirely rather than half-used.
72
+ """
73
+ try:
74
+ node.buffer_range = node.buffer_range
75
+ except (AttributeError, TypeError):
76
+ return False
77
+ return True
78
+
79
+
80
+ def _as_text(rendered: Any) -> Optional[str]:
81
+ if isinstance(rendered, str):
82
+ return rendered
83
+ if isinstance(rendered, (bytes, bytearray)):
84
+ try:
85
+ return bytes(rendered).decode("utf-8")
86
+ except UnicodeDecodeError:
87
+ return None
88
+ return None
89
+
90
+
91
+ def _single_leaf_run(nodes: Sequence[Any], text: str) -> Optional["RunSpans"]:
92
+ """Measure a single scalar leaf whose document parse is necessarily wrapper-shaped."""
93
+ if len(nodes) != 1 or "\n" in text:
94
+ return None
95
+ node = nodes[0]
96
+ if any(_is_node(child) for child in (getattr(node, "children", None) or ())):
97
+ return None
98
+ if not _accepts_span(node):
99
+ return None
100
+ starts, cumulative, owns = _line_table(text, False)
101
+ return RunSpans(
102
+ text=text,
103
+ starts=starts,
104
+ cumulative=cumulative,
105
+ pairs=((node, 0, len(text)),),
106
+ owns_prefix=owns,
107
+ )
108
+
109
+
110
+ #: Whether a BLANK line of a run's own text receives the enclosing container's indent prefix once
111
+ #: the run is embedded. Both happen, in the same document: a blank separator line is normally
112
+ #: rendered bare, but a format is free to indent one (python's ``EmptyLine`` carries its own
113
+ #: ``indent`` flag, and a fragment re-parse can flip it, turning ``"\n"`` into ``" \n"``), and
114
+ #: nothing in a run's own unindented text distinguishes the two. So it is not decided here: both
115
+ #: are tried and the one that reproduces the run's already-known spans -- or the independently
116
+ #: measured byte delta of the splice -- is the one used. See :func:`solve_model`.
117
+ BLANK_LINE_POLICIES: Tuple[bool, ...] = (False, True)
118
+
119
+
120
+ def _line_table(
121
+ text: str,
122
+ blank_lines_indented: bool,
123
+ verbatim_lines: "frozenset[int]" = frozenset(),
124
+ ) -> Tuple[Tuple[int, ...], Tuple[int, ...], Tuple[bool, ...]]:
125
+ """``(line_starts, prefixed_before_and_including, blank_line_owns_its_prefix)`` for ``text``.
126
+
127
+ ``cumulative[k]`` counts how many of lines ``0..k`` receive the enclosing container's indent
128
+ prefix once the run is embedded. Three kinds of line do not:
129
+
130
+ * the trailing empty line after a final newline -- there is nothing on it to indent;
131
+ * a blank separator line, unless ``blank_lines_indented`` says this format indents those;
132
+ * a VERBATIM line -- one that continues a multi-line token, a docstring or any other multi-line
133
+ string literal being the case that matters. Its indentation is the token's own DATA, which
134
+ re-indenting the code around it must not touch, so the bytes on it are carried across
135
+ unchanged. Which lines those are is not guessed from the text: :func:`measure_run` reads it
136
+ off the run's own parse (see :func:`_verbatim_lines`).
137
+ """
138
+ starts: List[int] = [0]
139
+ has_content: List[bool] = []
140
+ content = False
141
+ for index, char in enumerate(text):
142
+ if char == "\n":
143
+ has_content.append(content)
144
+ content = False
145
+ starts.append(index + 1)
146
+ elif not char.isspace():
147
+ content = True
148
+ has_content.append(content)
149
+ last = len(has_content) - 1
150
+ running = 0
151
+ cumulative: List[int] = []
152
+ owns_prefix: List[bool] = []
153
+ for line, flag in enumerate(has_content):
154
+ verbatim = line in verbatim_lines
155
+ blank_indent = (
156
+ blank_lines_indented and not flag and line != last and not verbatim
157
+ )
158
+ running += 1 if (not verbatim and (flag or blank_indent)) else 0
159
+ cumulative.append(running)
160
+ owns_prefix.append(blank_indent)
161
+ return tuple(starts), tuple(cumulative), tuple(owns_prefix)
162
+
163
+
164
+ def _verbatim_lines(root: Any, starts: Sequence[int], length: int) -> "frozenset[int]":
165
+ """Lines of the run's own text that a container carries across UNCHANGED when it re-indents.
166
+
167
+ A token that spans several lines -- a triple-quoted string, most often a docstring -- owns
168
+ every byte between its quotes, indentation included. Re-indenting the code around it moves its
169
+ FIRST line, because the token starts after the indent, and must leave every following line of
170
+ it exactly as written. Detected structurally, with no format knowledge: a node with no children
171
+ is a token, and a token whose span crosses a line boundary continues onto those lines.
172
+
173
+ Getting this wrong is not a rounding error. A method with an ordinary multi-line docstring --
174
+ most real methods -- has more verbatim lines than indented ones, so assuming a uniform indent
175
+ per line misses the true span by several times the indent width, which is exactly why such a
176
+ method could not be measured at all before this was taken into account.
177
+ """
178
+ from bisect import bisect_right as _bisect
179
+
180
+ def line_of(offset: int) -> int:
181
+ index = _bisect(starts, offset) - 1
182
+ return index if index >= 0 else 0
183
+
184
+ lines: set = set()
185
+
186
+ def visit(node: Any) -> None:
187
+ children = [
188
+ value
189
+ for field in (getattr(node, "fields", None) or {}).values()
190
+ for value in (field if isinstance(field, (tuple, list)) else [field])
191
+ if _is_node(value)
192
+ ]
193
+ span = getattr(node, "buffer_range", None)
194
+ if not children and span is not None and 0 <= span[0] <= span[1] <= length:
195
+ first, last = line_of(span[0]), line_of(max(span[0], span[1] - 1))
196
+ lines.update(range(first + 1, last + 1))
197
+ for child in children:
198
+ visit(child)
199
+
200
+ visit(root)
201
+ return frozenset(lines)
202
+
203
+
204
+ @dataclass(frozen=True)
205
+ class IndentModel:
206
+ """The ISO-space -> DOCUMENT-space map: ``base`` is the document offset the run's own text
207
+ starts at, ``width`` the indent prefix each content line gains from the enclosing container
208
+ (``0`` for a run spliced at the top level of its document)."""
209
+
210
+ base: int
211
+ width: int
212
+
213
+
214
+ @dataclass(frozen=True)
215
+ class RunSpans:
216
+ """One rendered run of sibling nodes together with the ISO spans a fresh parse of those exact
217
+ bytes resolved for the live nodes that could be aligned with it."""
218
+
219
+ text: str
220
+ starts: Tuple[int, ...]
221
+ cumulative: Tuple[int, ...]
222
+ pairs: Tuple[Tuple[Any, int, int], ...]
223
+ owns_prefix: Tuple[bool, ...] = ()
224
+ blank_lines_indented: bool = False
225
+ verbatim: "frozenset[int]" = frozenset()
226
+
227
+ def with_blank_line_policy(self, blank_lines_indented: bool) -> "RunSpans":
228
+ """The same measured run read under the other blank-line policy -- a recomputed line table
229
+ over text and spans already in hand, never a second render or parse."""
230
+ if blank_lines_indented == self.blank_lines_indented:
231
+ return self
232
+ starts, cumulative, owns = _line_table(
233
+ self.text, blank_lines_indented, self.verbatim
234
+ )
235
+ return RunSpans(
236
+ text=self.text, starts=starts, cumulative=cumulative, pairs=self.pairs,
237
+ owns_prefix=owns, blank_lines_indented=blank_lines_indented,
238
+ verbatim=self.verbatim,
239
+ )
240
+
241
+ def prefixed_lines(self, offset: int, *, at_end: bool) -> int:
242
+ """How many indent prefixes are inserted BEFORE ``offset`` once the run is embedded.
243
+
244
+ The two ends of a span answer this differently where ``offset`` falls exactly on a line
245
+ boundary, and the difference is the whole indent width -- getting it wrong is what an
246
+ earlier draft of this model got wrong. A container inserts each line's prefix AT that
247
+ line's first byte. A span that STARTS there starts at the line's content, which the prefix
248
+ precedes, so the prefix counts. A span that ENDS there ended on the PREVIOUS line -- it
249
+ stops at the newline, ahead of the next line's prefix -- so it does not. Observed on real
250
+ LibCST spans: a nested ``def``'s own span starts after its indent, while the trailing
251
+ newline before it ends before the next line's.
252
+
253
+ A zero-width span is a boundary rather than content and is measured like a start, so it
254
+ never inverts against the span it sits inside.
255
+ """
256
+ probe = offset - 1 if (at_end and offset > 0) else offset
257
+ line = bisect_right(self.starts, probe) - 1
258
+ if line < 0:
259
+ line = 0
260
+ if line >= len(self.cumulative):
261
+ line = len(self.cumulative) - 1
262
+ if (
263
+ not at_end
264
+ and line < len(self.owns_prefix)
265
+ and self.owns_prefix[line]
266
+ and offset == self.starts[line]
267
+ ):
268
+ # An INDENTED BLANK line's prefix is the blank line's own content -- the node standing
269
+ # for it spans its whitespace -- so a span starting there starts AHEAD of the prefix,
270
+ # unlike one starting at a content line, where the prefix is indentation the first
271
+ # token does not own.
272
+ return self.cumulative[line - 1] if line else 0
273
+ return self.cumulative[line]
274
+
275
+ def map_offset(self, model: IndentModel, offset: int, *, at_end: bool = False) -> int:
276
+ return model.base + offset + model.width * self.prefixed_lines(offset, at_end=at_end)
277
+
278
+ def embedded_length(self, model: IndentModel) -> int:
279
+ """How many DOCUMENT bytes this run occupies once embedded."""
280
+ return self.map_offset(model, len(self.text), at_end=True) - model.base
281
+
282
+
283
+ def _align(live: Any, parsed: Any, out: List[Tuple[Any, int, int]]) -> None:
284
+ """Collect ``(live_node, iso_start, iso_end)`` for every node of ``live`` that matches ``parsed``.
285
+
286
+ Deliberately TOLERANT rather than all-or-nothing. Re-parsing a run's own render as a whole
287
+ document can legitimately re-home the run's leading trivia: blank lines that the document held
288
+ inside the first statement's own leading-trivia field become the re-parsed module's OWN header,
289
+ because in that text nothing precedes them. The BYTE SPANS are identical either way -- only the
290
+ field the trivia hangs from moves -- so a length mismatch on one tuple field is not evidence
291
+ that anything else is misaligned. Such a field is skipped (its nodes simply get no span and
292
+ keep their ``None``) and every other field is still walked, which keeps the run's own roots --
293
+ the nodes this whole exercise exists to measure -- always covered.
294
+
295
+ Alignment is by FIELD NAME, never by ``children`` order: a plugin hook may reorder a spliced
296
+ node's ``children`` relative to what a fresh parse of the same bytes produces (``facade
297
+ ._adjust_replace_fragment`` transplanting separating trivia does exactly that), while ``fields``
298
+ is keyed and therefore stable.
299
+ """
300
+ if getattr(live, "kind", None) != getattr(parsed, "kind", None):
301
+ return
302
+ span = getattr(parsed, "buffer_range", None)
303
+ if span is not None and _accepts_span(live):
304
+ out.append((live, span[0], span[1]))
305
+ live_fields = getattr(live, "fields", None) or {}
306
+ parsed_fields = getattr(parsed, "fields", None) or {}
307
+ for key, live_value in live_fields.items():
308
+ if key not in parsed_fields:
309
+ continue
310
+ parsed_value = parsed_fields[key]
311
+ if _is_node(live_value) and _is_node(parsed_value):
312
+ _align(live_value, parsed_value, out)
313
+ continue
314
+ if isinstance(live_value, (tuple, list)) and isinstance(parsed_value, (tuple, list)):
315
+ if len(live_value) != len(parsed_value):
316
+ continue
317
+ for live_item, parsed_item in zip(live_value, parsed_value):
318
+ if _is_node(live_item) and _is_node(parsed_item):
319
+ _align(live_item, parsed_item, out)
320
+
321
+
322
+ def measure_run(
323
+ nodes: Sequence[Any],
324
+ render_node: RenderNode,
325
+ parse_document_root: ParseDocumentRoot,
326
+ ) -> Optional[RunSpans]:
327
+ """Render ``nodes`` (a contiguous sibling run, in order), re-parse those exact bytes as a
328
+ document, and align the result back onto the live nodes.
329
+
330
+ ``None`` -- measure nothing, assign nothing -- whenever any step cannot be trusted: a node the
331
+ plugin cannot render standalone, bytes it cannot re-parse, or a re-parse whose own top-level
332
+ statements do not correspond one-for-one with the run handed in. The one exception is a
333
+ single-line scalar leaf: a full-document parse necessarily wraps such a fragment, while the
334
+ leaf's own rendered bytes still measure its whole span exactly. Never raises and never guesses.
335
+ """
336
+ if not nodes:
337
+ return None
338
+ chunks: List[str] = []
339
+ for node in nodes:
340
+ text = _as_text(render_node(node))
341
+ if text is None:
342
+ return None
343
+ chunks.append(text)
344
+ text = "".join(chunks)
345
+ if not text:
346
+ return None
347
+ root = parse_document_root(text)
348
+ if root is None:
349
+ return None
350
+ parsed_roots = list(getattr(root, "children", None) or ())
351
+ if len(parsed_roots) != len(nodes):
352
+ return _single_leaf_run(nodes, text)
353
+ pairs: List[Tuple[Any, int, int]] = []
354
+ for live, parsed in zip(nodes, parsed_roots):
355
+ if getattr(live, "kind", None) != getattr(parsed, "kind", None):
356
+ return _single_leaf_run(nodes, text)
357
+ _align(live, parsed, pairs)
358
+ if not pairs:
359
+ return None
360
+ line_starts, _unused, _also_unused = _line_table(text, False)
361
+ verbatim = _verbatim_lines(root, line_starts, len(text))
362
+ starts, cumulative, owns = _line_table(text, False, verbatim)
363
+ return RunSpans(
364
+ text=text, starts=starts, cumulative=cumulative, pairs=tuple(pairs), owns_prefix=owns,
365
+ verbatim=verbatim,
366
+ )
367
+
368
+
369
+ def _mapped_span(run: RunSpans, model: IndentModel, iso_start: int, iso_end: int) -> Tuple[int, int]:
370
+ at_end = iso_end > iso_start
371
+ return (
372
+ run.map_offset(model, iso_start),
373
+ run.map_offset(model, iso_end, at_end=at_end),
374
+ )
375
+
376
+
377
+ def _rewritten_blank_line(run: RunSpans, iso_start: int, iso_end: int) -> bool:
378
+ """Whether a span lies inside a blank line the container INDENTS, where the map does not apply.
379
+
380
+ Everywhere else embedding only SHIFTS bytes, so a span keeps its width and the map is a pure
381
+ offset. An indented blank line is the exception: its own whitespace is not shifted, it is
382
+ REWRITTEN, growing from nothing to the indent -- so the nodes standing for that line's
383
+ whitespace and newline change width, which no offset map can express. They are left unmeasured
384
+ (``buffer_range`` stays ``None``, the engine's safe absence) instead of being given a span that
385
+ is merely plausible. Only that line's own trivia is affected; nothing addressable lives there.
386
+ """
387
+ if not run.blank_lines_indented:
388
+ return False
389
+ index = bisect_right(run.starts, iso_start) - 1
390
+ if index < 0 or index >= len(run.owns_prefix) or not run.owns_prefix[index]:
391
+ return False
392
+ line_end = run.starts[index + 1] if index + 1 < len(run.starts) else len(run.text)
393
+ return iso_end <= line_end
394
+
395
+
396
+ def _fits(run: RunSpans, model: IndentModel) -> bool:
397
+ for node, iso_start, iso_end in run.pairs:
398
+ span = getattr(node, "buffer_range", None)
399
+ if span is None or _rewritten_blank_line(run, iso_start, iso_end):
400
+ continue
401
+ if _mapped_span(run, model, iso_start, iso_end) != tuple(span):
402
+ return False
403
+ return True
404
+
405
+
406
+ def _candidate_widths(run: RunSpans) -> List[int]:
407
+ """Indent widths consistent with the observations ``run`` carries, cheapest first.
408
+
409
+ Each observation says ``document_offset - iso_offset == base + width * prefixed_lines``. Two
410
+ observations whose prefixed-line counts differ pin ``width`` exactly; when they do not the
411
+ width is genuinely unobservable from this run alone (every offset sits in the same line class,
412
+ so ``base + width * count`` is invariant and the assigned spans come out identical either way)
413
+ and ``0`` is the honest representative. The caller still cross-checks whichever width is
414
+ returned against the independently measured byte delta of the splice.
415
+ """
416
+ observations = set()
417
+ for node, iso_start, iso_end in run.pairs:
418
+ span = getattr(node, "buffer_range", None)
419
+ if span is None:
420
+ continue
421
+ at_end = iso_end > iso_start
422
+ if _rewritten_blank_line(run, iso_start, iso_end):
423
+ continue
424
+ for iso_offset, document_offset, ending in (
425
+ (iso_start, span[0], False), (iso_end, span[1], at_end)
426
+ ):
427
+ observations.add((
428
+ run.prefixed_lines(iso_offset, at_end=ending),
429
+ document_offset - iso_offset,
430
+ ))
431
+ widths: List[int] = []
432
+ ordered = sorted(observations)
433
+ for index in range(len(ordered) - 1):
434
+ (count_a, value_a), (count_b, value_b) = ordered[index], ordered[index + 1]
435
+ if count_b == count_a:
436
+ continue
437
+ numerator, denominator = value_b - value_a, count_b - count_a
438
+ if numerator % denominator:
439
+ continue
440
+ width = numerator // denominator
441
+ if width >= 0 and width not in widths:
442
+ widths.append(width)
443
+ if 0 not in widths:
444
+ widths.append(0)
445
+ return widths
446
+
447
+
448
+ def _solve_one(run: RunSpans, width: Optional[int]) -> Optional[IndentModel]:
449
+ anchored = [
450
+ (node, iso_start)
451
+ for node, iso_start, _ in run.pairs
452
+ if getattr(node, "buffer_range", None) is not None
453
+ ]
454
+ if not anchored:
455
+ return None
456
+ widths = [width] if width is not None else _candidate_widths(run)
457
+ for candidate in widths:
458
+ if candidate is None or candidate < 0:
459
+ continue
460
+ node, iso_start = anchored[0]
461
+ span = getattr(node, "buffer_range")
462
+ base = (
463
+ span[0] - iso_start
464
+ - candidate * run.prefixed_lines(iso_start, at_end=False)
465
+ )
466
+ model = IndentModel(base=base, width=candidate)
467
+ if _fits(run, model):
468
+ return model
469
+ return None
470
+
471
+
472
+ def solve_model(
473
+ run: RunSpans, *, width: Optional[int] = None
474
+ ) -> Optional[Tuple[RunSpans, IndentModel]]:
475
+ """The ISO -> DOCUMENT map that reproduces EVERY span ``run``'s live nodes already carry,
476
+ together with the reading of ``run`` under which it does.
477
+
478
+ Two things are unknown and both are SEARCHED, never assumed: the indent width the enclosing
479
+ container adds, and whether it adds it to blank lines as well
480
+ (:data:`BLANK_LINE_POLICIES`). Every combination the run's own observations admit is tried and
481
+ the first that reproduces ALL of them -- every start and every end of every already-positioned
482
+ node in the run -- wins. ``width`` pins the width when the caller already knows it (measuring a
483
+ run being INSERTED, whose container a sibling already characterised).
484
+
485
+ ``None`` when no combination reproduces them: the container does not re-indent by a uniform
486
+ per-line prefix, or the run's own spans are mutually inconsistent. A model that is merely close
487
+ is never returned."""
488
+ for blank_policy in BLANK_LINE_POLICIES:
489
+ candidate_run = run.with_blank_line_policy(blank_policy)
490
+ model = _solve_one(candidate_run, width)
491
+ if model is not None:
492
+ return candidate_run, model
493
+ return None
494
+
495
+
496
+ def reproduces(run: RunSpans, model: IndentModel) -> bool:
497
+ """Whether ``model``, read against ``run``, reproduces every span ``run``'s nodes already
498
+ carry. The caller uses it to ask whether the OTHER blank-line reading of the same run would
499
+ have done just as well -- if it would, the run's own indentation is genuinely undetermined and
500
+ its mapped length cannot be trusted as a measurement."""
501
+ return _fits(run, model)
502
+
503
+
504
+ def assign_spans(run: RunSpans, model: IndentModel) -> int:
505
+ """Write the mapped document spans onto every live node ``run`` aligned. Returns how many."""
506
+ assigned = 0
507
+ for node, iso_start, iso_end in run.pairs:
508
+ if _rewritten_blank_line(run, iso_start, iso_end):
509
+ continue
510
+ node.buffer_range = _mapped_span(run, model, iso_start, iso_end)
511
+ assigned += 1
512
+ return assigned