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,785 @@
1
+ """Mutable working mirror of the common tree model, for the mutating core operations.
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+
6
+ Scope: the integration layer between the *immutable* common model of
7
+ ``tree_engine.core.nodes`` and the *mutating* operations of
8
+ ``tree_engine.core.operations``/``move``/``updates``/``subtree_apply``. Those
9
+ operations are deliberately duck-typed ({p010}, {p107}, {p108}): they resolve a
10
+ node's ``parent`` back-link, splice its ``children`` in place, and write
11
+ ``node_id``/``short_id`` on it. ``core.nodes.Node`` is a frozen dataclass with
12
+ no ``parent`` field at all, so it cannot be that node. Until this module, no
13
+ merged file closed that gap and every caller had to invent its own mirror.
14
+
15
+ :class:`LiveNode` is that node: the exact ``Node`` schema -- ``kind``,
16
+ ``fields``, ``children``, plus the five reserved slots ``node_id``,
17
+ ``short_id``, ``extended_type``, ``buffer_range``, ``references`` -- with a
18
+ settable ``parent`` and a list ``children``. :func:`to_live` and
19
+ :func:`to_frozen` are its lossless conversion pair with ``Node``, so a document
20
+ is parsed by a format plugin into ``Node``, mirrored here for editing, and
21
+ converted back for every render.
22
+
23
+ Two rendering realities every editor of this model has to honor, both owned
24
+ here rather than by each caller:
25
+
26
+ * **fields vs children** ({p045}, {p008}). ``nodes.py`` states plainly that
27
+ ``children`` and ``fields`` are not required to be kept in lockstep, and the
28
+ shipped plugins split on exactly that: the Python and BSL generators rebuild
29
+ from node-valued ``fields`` entries, while the JSON and TOML generators walk
30
+ ``children``. A core splice touches ``children`` only, so
31
+ :func:`sync_fields` mirrors the new ``children`` back into the parent's
32
+ node-holding sequence field. Where that mapping is ambiguous the edit is
33
+ refused with a catalog code rather than silently not rendered.
34
+ * **cached source slices**. A plugin may cache a node's original source text on
35
+ the node itself so an untouched document round-trips byte-identically -- JSON
36
+ stores the whole document under ``fields["raw"]``, BSL under
37
+ ``fields["content"]`` -- and replays that cache instead of re-composing from
38
+ children. After a splice, every ancestor of the edit holds a stale cache that
39
+ would replay pre-edit text. :data:`CACHED_SOURCE_FIELDS` names the convention
40
+ and :func:`invalidate_cached_source` drops it along the ancestor chain, so
41
+ the rule is one documented core-side invariant instead of plugin knowledge
42
+ spread through callers.
43
+
44
+ This module performs no validation, no addressing, no locking and no I/O: it
45
+ owns the working representation and nothing else. It raises only
46
+ ``nodes.NodeSchemaError`` carrying an ``ErrorCode`` from the shared catalog,
47
+ the same convention ``core/nodes.py`` established, so a public facade can map
48
+ it to the typed hierarchy without inventing a code of its own.
49
+
50
+ Source-of-truth requirement labels honored here: {p008}, {p010}, {p045},
51
+ {p107}, {p108}.
52
+ """
53
+
54
+ from __future__ import annotations
55
+
56
+ import dataclasses
57
+ from dataclasses import dataclass, field
58
+ from pathlib import Path
59
+ from typing import (
60
+ Any,
61
+ Callable,
62
+ Dict,
63
+ Iterator,
64
+ List,
65
+ Mapping,
66
+ Optional,
67
+ Sequence,
68
+ Tuple,
69
+ )
70
+ from uuid import UUID, uuid4
71
+
72
+ from tree_engine.core.identity import generate_node_id
73
+ from tree_engine.core.journal import MutationJournal
74
+ from tree_engine.core.nodes import Node, NodeKind, NodeSchemaError
75
+ from tree_engine.core.position_map import FragmentWalk, SubtreeBytesAggregate
76
+ from tree_engine.core.short_id import ShortIdMap
77
+ from tree_engine.errors import ErrorCode
78
+
79
+ __all__ = [
80
+ "CACHED_SOURCE_FIELDS",
81
+ "LiveNode",
82
+ "TreeDocument",
83
+ "to_live",
84
+ "to_frozen",
85
+ "clone_live_subtree",
86
+ "walk",
87
+ "relink",
88
+ "sync_fields",
89
+ "invalidate_cached_source",
90
+ ]
91
+
92
+ #: Field names under which a format plugin may cache a node's own original
93
+ #: source slice: JSON's ``raw`` (the document root's covers the entire text)
94
+ #: and BSL's ``content``. A plugin that finds one replays it verbatim instead
95
+ #: of re-composing the node from its children, which is exactly what keeps an
96
+ #: untouched document byte-identical -- and exactly what makes the cache stale
97
+ #: on every ancestor of an edit. See :func:`invalidate_cached_source`.
98
+ CACHED_SOURCE_FIELDS: Tuple[str, ...] = ("raw", "content")
99
+
100
+
101
+ @dataclass(eq=False)
102
+ class LiveNode:
103
+ """A mutable node carrying the exact ``core.nodes.Node`` schema.
104
+
105
+ ``kind``, ``fields`` and ``children`` mirror ``Node``'s three structural
106
+ attributes, and ``node_id``/``short_id``/``extended_type``/``buffer_range``/
107
+ ``references`` mirror its five reserved identity and extension slots.
108
+ ``parent`` is the settable back-link ``Node`` deliberately does not carry
109
+ (immutable bottom-up construction keeps no back-references) and which every
110
+ mutating core operation resolves; ``children`` is a ``list`` so those
111
+ operations can splice it in place.
112
+
113
+ ``eq=False`` keeps identity comparison: ``parent`` makes the graph cyclic,
114
+ so a generated structural ``__eq__`` would recurse forever, and the core's
115
+ splice helpers compare nodes by identity anyway (``siblings.index(node)``).
116
+ """
117
+
118
+ kind: str
119
+ fields: Dict[str, Any]
120
+ children: List["LiveNode"]
121
+ node_id: UUID
122
+ short_id: Optional[int] = None
123
+ extended_type: Optional[str] = None
124
+ buffer_range: Optional[Tuple[int, int]] = None
125
+ references: Tuple[Any, ...] = ()
126
+ parent: Optional["LiveNode"] = field(default=None, repr=False)
127
+
128
+ def get_attribute(self, name: str, default: Any = None) -> Any:
129
+ """Read field ``name``, the accessor ``core.updates`` and the query
130
+ predicate evaluator both look for on a node."""
131
+
132
+ return self.fields.get(name, default)
133
+
134
+ def set_attribute(self, name: str, value: Any) -> None:
135
+ """Set field ``name`` to a primitive value, validating before writing.
136
+
137
+ Rejects anything the ``Node`` field contract does not admit as a plain
138
+ value with ``NodeSchemaError`` (``INVALID_PARENT_TYPE``), the same error
139
+ ``core/nodes.py`` raises for a field-shape mismatch and the one
140
+ ``core.updates.set_attribute`` already catches and re-raises as its own
141
+ typed rejection, having written nothing.
142
+ """
143
+
144
+ if not (value is None or isinstance(value, (str, int, float, bool, bytes))):
145
+ raise NodeSchemaError(
146
+ ErrorCode.INVALID_PARENT_TYPE,
147
+ f"attribute {name!r} must be a primitive value, got {type(value).__name__}",
148
+ )
149
+ self.fields = {**self.fields, name: value}
150
+
151
+
152
+ def _remap(
153
+ fields: Mapping[str, Any], old: Sequence[Any], new: Sequence[Any]
154
+ ) -> Dict[str, Any]:
155
+ """Rebuild ``fields`` with every node value swapped for its counterpart.
156
+
157
+ A field value that *is* one of ``old`` (by object identity) becomes the
158
+ matching entry of ``new`` -- the same fields/children reconciliation
159
+ ``core.subtree_copy`` already performs when it clones a node. A live node
160
+ that is no longer among ``old`` is one a splice detached from ``children``
161
+ while a field still holds it (an ``IndentedBlock``'s ``header``, say); it is
162
+ converted on the spot instead of being left behind as a live node inside an
163
+ otherwise immutable tree.
164
+ """
165
+
166
+ swap = {id(item): replacement for item, replacement in zip(old, new)}
167
+
168
+ def one(value: Any) -> Any:
169
+ if isinstance(value, tuple):
170
+ return tuple(one(item) for item in value)
171
+ if id(value) in swap:
172
+ return swap[id(value)]
173
+ return to_frozen(value) if isinstance(value, LiveNode) else value
174
+
175
+ return {key: one(value) for key, value in fields.items()}
176
+
177
+
178
+ def to_live(node: Node, parent: Optional[LiveNode] = None) -> LiveNode:
179
+ """Mirror an immutable ``Node`` subtree into linked :class:`LiveNode` objects.
180
+
181
+ Every attribute is carried across unchanged; a node that arrives without a
182
+ ``node_id`` (a plugin fragment that assigns identity later) is given a fresh
183
+ UUID4 here so the mirror is always addressable.
184
+
185
+ A field value NOT among ``node.children`` -- a compound/module node's own
186
+ POSITIONAL trivia field deliberately excluded from ``children`` at import
187
+ time, e.g. an ``IndentedBlock``'s ``header`` or a ``Module``'s ``header``/
188
+ ``footer`` (``plugins/python/import_map.py``) -- is left as the immutable
189
+ ``core.nodes.Node`` it already is, verbatim: it is never spliced/addressed
190
+ as a child, so it never needs a ``LiveNode`` mirror, and ``core.nodes.Node``
191
+ itself is ``copy.deepcopy``-safe ({p013}'s frozen dataclass, ``__deepcopy__``
192
+ below) so carrying it through unconverted does not reintroduce the
193
+ ``MappingProxyType``-is-not-picklable failure a naive "convert everything"
194
+ version of this once had (bug 554f6521 defect #4's residual tier).
195
+ """
196
+
197
+ live = LiveNode(
198
+ kind=str(node.kind),
199
+ fields=dict(node.fields),
200
+ children=[],
201
+ parent=parent,
202
+ node_id=node.node_id if node.node_id is not None else generate_node_id(),
203
+ short_id=node.short_id,
204
+ extended_type=node.extended_type,
205
+ buffer_range=node.buffer_range,
206
+ references=tuple(node.references or ()),
207
+ )
208
+ live.children = [to_live(child, live) for child in node.children]
209
+ live.fields = _remap(node.fields, node.children, live.children)
210
+ return live
211
+
212
+
213
+ def to_frozen(live: LiveNode) -> Node:
214
+ """Rebuild the immutable ``Node`` subtree a format plugin renders from.
215
+
216
+ The exact inverse of :func:`to_live`: identity, extension slots, byte range
217
+ and references are preserved, and node-valued ``fields`` entries are
218
+ re-pointed at the rebuilt children so ``fields`` and ``children`` describe
219
+ the same tree on both sides of the conversion.
220
+ """
221
+
222
+ children = [to_frozen(child) for child in live.children]
223
+ return Node(
224
+ kind=NodeKind(live.kind),
225
+ fields=_remap(live.fields, live.children, children),
226
+ children=tuple(children),
227
+ node_id=live.node_id,
228
+ short_id=live.short_id,
229
+ extended_type=live.extended_type,
230
+ buffer_range=live.buffer_range,
231
+ references=live.references,
232
+ )
233
+
234
+
235
+ def clone_live_subtree(node: LiveNode, parent: Optional[LiveNode] = None) -> LiveNode:
236
+ """Deep-copy a live subtree with a FRESH identity throughout: every node gets a brand new
237
+ ``node_id`` (:func:`~tree_engine.core.identity.generate_node_id`) and ``short_id=None`` --
238
+ left for the caller's own short-id allocation to assign, exactly as every freshly parsed
239
+ fragment node already arrives with none. ``fields``/``children`` stay reconciled through
240
+ :func:`_remap`, the same fields/children correspondence :func:`to_live`/:func:`to_frozen`
241
+ already maintain, so a field that held one of ``node``'s own children now holds that
242
+ child's clone instead of the original.
243
+
244
+ Used to graft a piece of an existing subtree onto a DIFFERENT part of the live tree without
245
+ reusing an identity another operation is simultaneously removing or reassigning -- e.g. a
246
+ format plugin transplanting a node's own separating trivia onto its replacement fragment
247
+ before a splice registers it (``plugins/python/plugin.py``'s ``adjust_replace_fragment``).
248
+ Reusing the SAME node objects instead would make the clone and the original the same
249
+ document entry during the brief window both trees reference it, which a validation pass
250
+ checking "is this node_id already in the document" would reject outright.
251
+
252
+ ``buffer_range`` is deliberately dropped (``None``): a clone's byte offsets are not the
253
+ original's, exactly like every other fragment node a plugin parses without an enclosing
254
+ document ({p102}'s own fragment exception).
255
+ """
256
+
257
+ clone = LiveNode(
258
+ kind=node.kind,
259
+ fields=dict(node.fields),
260
+ children=[],
261
+ parent=parent,
262
+ node_id=generate_node_id(),
263
+ short_id=None,
264
+ extended_type=node.extended_type,
265
+ buffer_range=None,
266
+ references=node.references,
267
+ )
268
+ clone.children = [clone_live_subtree(child, clone) for child in node.children]
269
+ clone.fields = _remap(clone.fields, node.children, clone.children)
270
+ return clone
271
+
272
+
273
+ def walk(node: LiveNode) -> Iterator[LiveNode]:
274
+ """Depth-first, pre-order traversal of a live subtree, ``node`` first."""
275
+
276
+ yield node
277
+ for child in node.children:
278
+ yield from walk(child)
279
+
280
+
281
+ def _assign_frozen_short_ids(node: Node, allocate: Callable[[UUID], int]) -> Node:
282
+ """Rebuild an immutable ``core.nodes.Node`` subtree with a ``short_id``
283
+ assigned to every node in it via ``allocate``.
284
+
285
+ Bug 97e154f6: a ``python:Module``'s ``header``/``footer`` and a
286
+ ``python:IndentedBlock``'s ``header``/``footer`` are deliberately excluded
287
+ from ``children`` at import time (``plugins/python/import_map.py``) so
288
+ ``sync_fields`` keeps exactly one splice-able child sequence per parent.
289
+ Per :func:`to_live`'s own contract, a field value not among a node's
290
+ ``children`` is therefore NEVER mirrored into a ``LiveNode`` -- it stays
291
+ the plain immutable ``Node`` it already was at import time, verbatim.
292
+ :func:`TreeDocument.reindex`'s ``walk(self.root)`` only ever sees
293
+ ``LiveNode`` instances reachable through ``children``, so it can never
294
+ reach these field-only subtrees to assign or refresh their ``short_id``
295
+ the way it does for every other node. Left alone, they either keep
296
+ whatever value import time gave them (a defect on its own: {p097}
297
+ requires every short_id to come from the document's own monotonic
298
+ allocator, never a separate import-time source) or, once import stops
299
+ pre-assigning one, keep ``short_id=None`` forever, which later breaks
300
+ every consumer that renders ``short_id_hex`` for them (e.g. the query
301
+ engine's traversal, which -- unlike ``reindex()`` -- deliberately walks
302
+ back into ``header``/``footer`` via the format plugin's own
303
+ ``ordered_children_for``).
304
+
305
+ This walks such a subtree via its own ``children`` (never excluded a
306
+ second level down: nothing a real ``header``/``footer`` value can embed
307
+ is itself a compound statement with its own trivia-only fields), assigns
308
+ each node the SAME monotonic, document-local ``short_id_map`` every
309
+ other node uses via ``allocate``, and rebuilds ``fields`` to point at the
310
+ freshly rebuilt children via :func:`_remap`. The result is deterministic
311
+ for a given document (a fixed pre-order walk over its own fixed tree
312
+ shape) and collision-free with every other node (one shared monotonic
313
+ counter), regardless of what prior ``facade.loads`` calls happened
314
+ earlier in this process -- unlike an import-time module-level counter,
315
+ which is exactly what made bug 97e154f6's collisions depend on prior
316
+ in-process activity.
317
+ """
318
+
319
+ new_children = tuple(_assign_frozen_short_ids(child, allocate) for child in node.children)
320
+ new_fields = _remap(node.fields, node.children, new_children)
321
+ return dataclasses.replace(
322
+ node, children=new_children, fields=new_fields, short_id=allocate(node.node_id)
323
+ )
324
+
325
+
326
+ def relink(node: LiveNode, parent: Optional[LiveNode] = None) -> None:
327
+ """Restore the ``parent`` back-links over a subtree rebuilt elsewhere.
328
+
329
+ ``core.subtree_copy``/``core.subtree_apply`` rebuild nodes through
330
+ ``dataclasses.replace`` and splice them by ``children``/``parent_id``, never
331
+ touching the ``parent`` object link; running this over the affected root
332
+ afterwards puts the back-links back in agreement with ``children``.
333
+ """
334
+
335
+ node.parent = parent
336
+ for child in node.children:
337
+ relink(child, node)
338
+
339
+
340
+ def _field_node_count(value: Any) -> int:
341
+ """How many entries of ``children`` one ``fields`` value contributes, mirroring exactly how
342
+ ``plugins/python/import_map.py``'s ``_convert_cst_node`` built ``children`` in the first
343
+ place: a scalar node contributes one, a non-empty tuple of nodes contributes each of its
344
+ items, anything else (``None``, a primitive, an empty tuple) contributes none."""
345
+
346
+ if isinstance(value, LiveNode):
347
+ return 1
348
+ if isinstance(value, tuple) and value and all(isinstance(item, LiveNode) for item in value):
349
+ return len(value)
350
+ return 0
351
+
352
+
353
+ # bug 25c37cc1 (Tuple-container half): mirrors ``core.operations._PAREN_WRAPPER_FIELD_NAMES`` --
354
+ # see that constant's docstring for the full rationale. ``lpar``/``rpar`` are LibCST's universal
355
+ # optional-wrapping-parentheses fields (present on 41 distinct classes, ``Tuple`` among them);
356
+ # a non-empty one is never genuine child content, so excluding both from this function's own
357
+ # "which field is the ONE real sequence" search below keeps a parenthesized ``python:Tuple``
358
+ # (``fields`` = ``elements``/``lpar``/``rpar``, the last two non-empty purely because of the
359
+ # literal ``(``/``)``) resolving to its real ``elements`` sequence instead of being refused as
360
+ # ambiguous.
361
+ _PAREN_WRAPPER_FIELD_NAMES = frozenset({"lpar", "rpar"})
362
+
363
+
364
+ def sync_fields(parent: Optional[LiveNode]) -> None:
365
+ """Mirror ``parent.children`` back into its node-holding ``fields``.
366
+
367
+ The Python and BSL generators rebuild a node from its node-valued ``fields``
368
+ entries; the JSON and TOML generators walk ``children``. A core splice
369
+ rewrites ``children`` only, so a fields-driven parent would otherwise render
370
+ its pre-edit content. When exactly one field holds a non-empty sequence of
371
+ nodes, that field is unambiguously the parent's child sequence and is
372
+ rewritten from ``children`` -- but NOT by dumping the whole of ``children``
373
+ into it: every OTHER node-valued field (e.g. a ``Call``'s scalar ``func``
374
+ sitting right beside its sequence ``args``, or an ``IndentedBlock``'s scalar
375
+ ``header`` sitting right after its sequence ``body``) still contributes its
376
+ own fixed-count run of entries to ``children``, in ``fields``-declaration
377
+ order, exactly as ``import_map._convert_cst_node`` put them there. Only the
378
+ slice BETWEEN those fixed runs -- ``children`` minus the prefix and suffix
379
+ counts every other field still accounts for -- is what a splice actually
380
+ touched, and that slice, not the full list, is what the one sequence field
381
+ is rewritten from ({p045}; this replaces an earlier version that assigned
382
+ ``tuple(parent.children)`` wholesale, which silently smuggled a neighboring
383
+ scalar field's own node into the sequence whenever one existed -- defect #4
384
+ of bug 554f6521's residual shape, caught here rather than one node kind at a
385
+ time in the importer).
386
+
387
+ When several fields hold node sequences, or the parent's node children sit
388
+ only in single-valued fields, no single field can express the new child
389
+ order; the edit is refused with ``NodeSchemaError``
390
+ (``INVALID_PARENT_TYPE``) rather than accepted and silently not rendered --
391
+ UNLESS ``fields`` already agrees with ``children`` (see below), in which case
392
+ there is nothing left to mirror. Splice into the descendant that does hold
393
+ one sequence instead -- for Python that is the ``Module`` or the
394
+ ``IndentedBlock``, not the ``ClassDef`` whose body is a single node. A parent
395
+ with no node-valued field at all is a children-driven format and needs
396
+ nothing done.
397
+
398
+ A caller that already wrote a scalar node-valued field directly -- e.g.
399
+ ``core.operations.replace_range`` overwriting ``BinaryOperation.fields["left"]``
400
+ in place, the one shape this function itself has no sequence field to rewrite
401
+ for (defect #6 of bug 554f6521) -- leaves ``children`` and ``fields`` back in
402
+ agreement before this ever runs. Raising anyway on a parent nothing is
403
+ actually stale on would turn every later operation touching such a node into
404
+ a hard failure, so the "several/single-valued fields" branch first checks
405
+ whether every node-valued field entry (each scalar value, each sequence
406
+ field's own items, in field-declaration order) is ALREADY exactly
407
+ ``parent.children`` -- by identity, ``LiveNode`` compares ``eq=False`` -- and
408
+ only raises when it is not: a real, unresolved mismatch a caller never fixed
409
+ up itself.
410
+
411
+ ``parent`` may be ``None`` (an operation whose affected parent was the
412
+ document root's own absent parent), in which case this is a no-op.
413
+ """
414
+
415
+ if parent is None:
416
+ return
417
+ field_items = list(parent.fields.items())
418
+ sequences = [
419
+ name
420
+ for name, value in field_items
421
+ if name not in _PAREN_WRAPPER_FIELD_NAMES
422
+ and isinstance(value, tuple)
423
+ and value
424
+ and all(isinstance(item, LiveNode) for item in value)
425
+ ]
426
+ seq_name: Optional[str] = None
427
+ if len(sequences) == 1:
428
+ seq_name = sequences[0]
429
+ elif not sequences and isinstance(parent.fields.get("body"), tuple):
430
+ # Every node-holding tuple field on `parent` is CURRENTLY empty, so
431
+ # none is picked out by non-emptiness above -- the exact shape of a
432
+ # node parsed from empty/near-empty source (e.g. `python:Module` for
433
+ # a brand-new file, whose `body`/`header`/`footer` all start as `()`;
434
+ # bug 62759f8a). A splice into such a parent still only ever touches
435
+ # `children`; left unmirrored, `fields[...]` stays stale forever and
436
+ # every later render reproduces the ORIGINAL (empty) content no
437
+ # matter how much `children` has since grown. `body` is the
438
+ # near-universal LibCST convention for a compound node's own
439
+ # statement sequence (Module/ClassDef/FunctionDef/IndentedBlock), so
440
+ # it is preferred BY NAME whenever nothing else can disambiguate --
441
+ # every genuinely populated case is still resolved by the
442
+ # non-emptiness check above, unchanged.
443
+ seq_name = "body"
444
+ if seq_name is not None:
445
+ prefix = 0
446
+ suffix = 0
447
+ past_sequence = False
448
+ for name, value in field_items:
449
+ if name == seq_name:
450
+ past_sequence = True
451
+ continue
452
+ count = _field_node_count(value)
453
+ if past_sequence:
454
+ suffix += count
455
+ else:
456
+ prefix += count
457
+ children = list(parent.children)
458
+ end = len(children) - suffix
459
+ middle = children[prefix:end] if end >= prefix else []
460
+ parent.fields = {**parent.fields, seq_name: tuple(middle)}
461
+ return
462
+ if sequences or any(
463
+ isinstance(value, LiveNode) for value in parent.fields.values()
464
+ ):
465
+ expected: List[LiveNode] = []
466
+ for value in parent.fields.values():
467
+ if isinstance(value, LiveNode):
468
+ expected.append(value)
469
+ elif isinstance(value, tuple) and value and all(
470
+ isinstance(item, LiveNode) for item in value
471
+ ):
472
+ expected.extend(value)
473
+ if expected == list(parent.children):
474
+ return
475
+ raise NodeSchemaError(
476
+ ErrorCode.INVALID_PARENT_TYPE,
477
+ f"node kind {parent.kind!r} does not hold its children in exactly one sequence "
478
+ "field, so a sequence edit cannot be expressed on it; splice into the "
479
+ "sequence-holding descendant instead",
480
+ )
481
+
482
+
483
+ def invalidate_cached_source(node: Optional[LiveNode]) -> None:
484
+ """Drop the stale cached source slice on ``node`` and each of its ancestors.
485
+
486
+ A plugin that cached its own original text under one of
487
+ :data:`CACHED_SOURCE_FIELDS` replays that cache verbatim rather than
488
+ re-composing from children, which is what makes an untouched document
489
+ byte-identical. After a splice the cache is correct on every node outside
490
+ the edit and stale on every node containing it, so exactly the ancestor
491
+ chain from the edited parent to the root is cleared -- never a sibling,
492
+ never a descendant, and never on an untouched document.
493
+ """
494
+
495
+ current = node
496
+ while current is not None:
497
+ if any(name in current.fields for name in CACHED_SOURCE_FIELDS):
498
+ current.fields = {
499
+ key: value
500
+ for key, value in current.fields.items()
501
+ if key not in CACHED_SOURCE_FIELDS
502
+ }
503
+ current = current.parent
504
+
505
+
506
+ class TreeDocument:
507
+ """One loaded document: its tree, identity, indexes, and version.
508
+
509
+ ``document_id`` is a fresh UUID4 per load and ``document_version`` the monotonic counter every
510
+ mutating command checks and bumps ({p024}). ``source_format_id`` is the originally selected format
511
+ and ``format_id`` the current working one; they differ only under the authorized plain-text
512
+ fallback, which also fills ``fallback_diagnostic`` ({p050}, {7a9b}). ``nodes_by_id``,
513
+ ``short_id_index``, ``short_id_map`` and ``parent_index`` are the document-local addressing state
514
+ ({p097}); ``path`` is the file it was loaded from, or ``None`` for a :func:`loads` document.
515
+
516
+ ``short_id_map`` is the one piece of state a caller may SEED. A document rebuilt from a stored
517
+ tree file already knows which integer every node_id was issued, and letting :meth:`reindex` mint
518
+ a fresh map instead would silently reissue new short_ids for nodes whose identity survived --
519
+ which is exactly the identity loss the persisted map exists to prevent. Passing the stored map
520
+ here makes :meth:`reindex` keep every recorded value and carry the monotonic ``next_short_id``
521
+ across the reload, so a short_id released by an earlier delete is still never reused ({p097}).
522
+ """
523
+
524
+ def __init__(
525
+ self,
526
+ root: LiveNode,
527
+ source_format_id: str,
528
+ format_id: str,
529
+ source_bytes: bytes,
530
+ *,
531
+ path: Optional[Path] = None,
532
+ fallback_diagnostic: Optional[Mapping[str, Any]] = None,
533
+ short_id_map: Optional[ShortIdMap] = None,
534
+ short_id_order: Optional[Callable[["TreeDocument"], Sequence[UUID]]] = None,
535
+ ) -> None:
536
+ self.document_id, self.document_version = uuid4(), 1
537
+ self.root, self.source_bytes, self.path = root, source_bytes, path
538
+ self.source_format_id, self.format_id = source_format_id, format_id
539
+ self.fallback_diagnostic = (
540
+ dict(fallback_diagnostic) if fallback_diagnostic else None
541
+ )
542
+ self.short_id_map = ShortIdMap() if short_id_map is None else short_id_map
543
+ self.short_id_order = short_id_order
544
+ self.nodes_by_id: Dict[UUID, LiveNode] = {}
545
+ self.short_id_index: Dict[int, UUID] = {}
546
+ self.parent_index: Dict[UUID, Optional[UUID]] = {}
547
+ self.journal = MutationJournal()
548
+ # The locally maintained {p067} subtree_bytes aggregate: None is the
549
+ # documented missing/stale sentinel (never computed yet, or a
550
+ # pointwise mutation happened since the last full recompute). Only a
551
+ # caller that owns a fragment walk (the facade, at a fresh-parse/
552
+ # full-rebuild boundary) can populate it -- see
553
+ # recompute_subtree_bytes -- so it starts empty here.
554
+ self._subtree_bytes: Optional[SubtreeBytesAggregate] = None
555
+ self.reindex()
556
+
557
+ def reindex(self) -> None:
558
+ """Rebuild the node, short_id and parent indexes from the live tree.
559
+
560
+ A boundary operation (INITIAL_LOAD, EXPLICIT_FULL_CHECK, EXTERNAL_MODIFICATION_RECOVERY,
561
+ BATCH_CONTROL_CHECK per {p016}), used when a full-document traversal is permitted. Mutations
562
+ use the pointwise API (index_subtree, deindex_subtree, reparent) instead.
563
+
564
+ Semantics: nodes gone from the tree have their short_ids released; when short_id_order is
565
+ defined, a live node outside its returned sequence ALSO has its short_id released and
566
+ node.short_id set to None, and only eligible nodes populate short_id_index. Per {p097}
567
+ released values are never reused, so a node that later becomes eligible again receives a
568
+ NEW short_id. This re-evaluates eligibility that pointwise mutations may have changed,
569
+ ensuring the notation index is correct after a boundary operation.
570
+
571
+ Per {p067}, this also discards the subtree_bytes aggregate: a boundary reindex may
572
+ follow a wholesale root swap (reparse/replace_source), so any aggregate keyed by the
573
+ previous tree's node paths can no longer be trusted. A caller that has a fragment walk
574
+ for the new tree repopulates it via recompute_subtree_bytes right after calling this;
575
+ until it does, subtree_bytes_for reads back the missing/stale sentinel (None).
576
+ """
577
+ self._subtree_bytes = None
578
+ live: Dict[UUID, LiveNode] = {node.node_id: node for node in walk(self.root)}
579
+ for node_id in self.short_id_index.values():
580
+ if node_id not in live:
581
+ self.short_id_map.release(node_id)
582
+ self.nodes_by_id, self.short_id_index = live, {}
583
+ self.parent_index = {
584
+ i: (n.parent.node_id if n.parent is not None else None)
585
+ for i, n in live.items()
586
+ }
587
+ ordered_ids = (
588
+ list(live)
589
+ if self.short_id_order is None
590
+ else list(self.short_id_order(self))
591
+ )
592
+ eligible = set(ordered_ids)
593
+ for node_id, node in live.items():
594
+ if node_id not in eligible:
595
+ self.short_id_map.release(node_id)
596
+ node.short_id = None
597
+ for node_id in ordered_ids:
598
+ node = live.get(node_id)
599
+ if node is None:
600
+ continue
601
+ existing = self.short_id_map.get_short_id(node_id)
602
+ node.short_id = (
603
+ existing
604
+ if existing is not None
605
+ else self.short_id_map.allocate(node_id)
606
+ )
607
+ self.short_id_index[node.short_id] = node_id
608
+
609
+ # Bug 97e154f6: a field value NOT among a live node's own ``children``
610
+ # (a ``python:Module``/``python:IndentedBlock``'s ``header``/``footer``
611
+ # trivia, per ``plugins/python/import_map.py``) is never mirrored into
612
+ # a ``LiveNode`` by ``to_live`` and so is invisible to ``walk()``
613
+ # above; assign it a short_id here too. See ``_fix_field_only_short_ids``.
614
+ for node in live.values():
615
+ self._fix_field_only_short_ids(node)
616
+
617
+ def _allocate_short_id(self, node_id: UUID) -> int:
618
+ """Return ``node_id``'s existing short_id, or freshly allocate one.
619
+
620
+ The single per-node building block both ``reindex`` and
621
+ ``index_subtree`` use, so a node keeps its assigned short_id across
622
+ repeated indexing instead of being handed a new one every time.
623
+ """
624
+
625
+ existing = self.short_id_map.get_short_id(node_id)
626
+ return existing if existing is not None else self.short_id_map.allocate(node_id)
627
+
628
+ def _fix_field_only_short_ids(self, node: LiveNode) -> None:
629
+ """Assign short_ids to ``node``'s field values never mirrored to ``LiveNode``.
630
+
631
+ Bug 97e154f6: a ``python:Module``/``python:IndentedBlock``'s own
632
+ ``header``/``footer`` trivia (``plugins/python/import_map.py``) is
633
+ excluded from ``children`` at import time, so :func:`to_live` leaves
634
+ it as the plain immutable ``core.nodes.Node`` subtree it already was,
635
+ verbatim -- it is never reachable through ``walk()``. Both boundary
636
+ ``reindex()`` and pointwise ``index_subtree()`` call this for every
637
+ node they index, so a freshly imported OR freshly spliced-in subtree
638
+ (e.g. a parsed replacement fragment) gets its embedded trivia
639
+ assigned a short_id exactly like every other node, from the SAME
640
+ document-local monotonic ``short_id_map`` -- never left with a stale
641
+ import-time value or with ``short_id=None``. See
642
+ :func:`_assign_frozen_short_ids`.
643
+ """
644
+
645
+ child_ids = {id(child) for child in node.children}
646
+ for key, value in list(node.fields.items()):
647
+ if isinstance(value, Node) and id(value) not in child_ids:
648
+ node.fields[key] = _assign_frozen_short_ids(value, self._allocate_short_id)
649
+ elif isinstance(value, tuple) and any(
650
+ isinstance(item, Node) and id(item) not in child_ids for item in value
651
+ ):
652
+ node.fields[key] = tuple(
653
+ _assign_frozen_short_ids(item, self._allocate_short_id)
654
+ if isinstance(item, Node) and id(item) not in child_ids
655
+ else item
656
+ for item in value
657
+ )
658
+
659
+ def index_subtree(self, node: LiveNode) -> None:
660
+ """Register node and its descendants into nodes_by_id, parent_index, and short_id_index.
661
+
662
+ A node keeping an existing short_id keeps it; one without gets the next monotonic value
663
+ from short_id_map. Short_id allocation respects {p097}: keep existing short_id, allocate
664
+ monotonically, release on removal via deindex_subtree, never reuse.
665
+
666
+ Cost is proportional to the subtree size, never the document size.
667
+
668
+ Notation index (short_id_order): pointwise indexing assigns short_ids to all indexed nodes
669
+ without consulting short_id_order; the next boundary reindex() re-evaluates eligibility,
670
+ releasing the short_ids of ineligible nodes and rebuilding short_id_index from eligible
671
+ nodes only.
672
+
673
+ Per {p067}, a pointwise structural mutation invalidates the subtree_bytes aggregate back
674
+ to the missing/stale sentinel (None) rather than attempt to patch it -- only a fresh full
675
+ recompute (recompute_subtree_bytes, at the next full-rebuild boundary) makes it non-None
676
+ again.
677
+
678
+ Bug 97e154f6: also assigns a short_id to every field-only trivia
679
+ subtree (e.g. an ``IndentedBlock``'s ``header``/``footer``) a freshly
680
+ spliced-in fragment carries, exactly as ``reindex()`` does for the
681
+ whole document -- see ``_fix_field_only_short_ids``. Without this, a
682
+ node spliced in between two boundary reindexes (a parsed replacement
683
+ fragment, say) would keep such trivia at ``short_id=None`` until the
684
+ next full reindex."""
685
+ self._subtree_bytes = None
686
+ for n in walk(node):
687
+ self.nodes_by_id[n.node_id] = n
688
+ self.parent_index[n.node_id] = (
689
+ n.parent.node_id if n.parent is not None else None
690
+ )
691
+ n.short_id = self._allocate_short_id(n.node_id)
692
+ self.short_id_index[n.short_id] = n.node_id
693
+ self._fix_field_only_short_ids(n)
694
+
695
+ def deindex_subtree(self, node: LiveNode) -> None:
696
+ """Remove node and its descendants from nodes_by_id, parent_index, and short_id_index.
697
+
698
+ Released short_ids are released via short_id_map per {p097}: they are never reused, per
699
+ the monotonic counter that only increments.
700
+
701
+ Cost is proportional to the subtree size, never the document size. Per {p067}, this also
702
+ invalidates the subtree_bytes aggregate back to the missing/stale sentinel -- see
703
+ index_subtree's own docstring."""
704
+ self._subtree_bytes = None
705
+ for n in walk(node):
706
+ self.nodes_by_id.pop(n.node_id, None)
707
+ self.parent_index.pop(n.node_id, None)
708
+ if n.short_id is not None:
709
+ self.short_id_index.pop(n.short_id, None)
710
+ self.short_id_map.release(n.node_id)
711
+
712
+ def reparent(self, node: LiveNode) -> None:
713
+ """Refresh parent_index for node alone after its parent changes.
714
+
715
+ Used when a node's parent pointer changes but its identity and descendants remain in the
716
+ tree. Updates only parent_index[node.node_id]; nodes_by_id and short_id_index are
717
+ unchanged.
718
+
719
+ Cost is O(1)."""
720
+ self.parent_index[node.node_id] = (
721
+ node.parent.node_id if node.parent is not None else None
722
+ )
723
+
724
+ def resolve_short_id(self, short_id: int) -> Sequence[UUID]:
725
+ """The ``normalize_node_address`` accessor: short_id -> node_id, empty when unknown."""
726
+ node_id = self.short_id_map.get_node_id(short_id)
727
+ return () if node_id is None else (node_id,)
728
+
729
+ def source_for(self, node: LiveNode) -> Optional[str]:
730
+ """The node's own text from the loaded source, for ``drill_down``'s source previews."""
731
+ span = node.buffer_range
732
+ return (
733
+ None
734
+ if span is None
735
+ else self.source_bytes[span[0] : span[1]].decode("utf-8", "replace")
736
+ )
737
+
738
+ def recompute_subtree_bytes(self, fragment_walk: FragmentWalk) -> None:
739
+ """(Re)populate the {p067} subtree_bytes aggregate from one full fragment walk.
740
+
741
+ Called by the facade at a fresh-parse/full-rebuild boundary (INITIAL_LOAD via
742
+ :func:`tree_engine.facade.loads`, and the ``reparse``/``replace_source`` rebuilds), never
743
+ by this module itself: building ``walk`` needs the document's format plugin
744
+ (``render_fragment``), which is core-layer-agnostic knowledge this file deliberately does
745
+ not have (see this module's own docstring). One full pass, mirroring
746
+ ``SubtreeBytesAggregate.initialize``'s own cost contract.
747
+
748
+ Per {p067}, this is the ONLY way ``subtree_bytes_for`` starts returning non-``None``
749
+ again after ``reindex()``/``index_subtree``/``deindex_subtree`` discarded it -- a
750
+ pointwise mutation is never "faked" fresh; it stays the missing/stale sentinel until the
751
+ next full recompute.
752
+ """
753
+ aggregate = SubtreeBytesAggregate()
754
+ aggregate.initialize(fragment_walk)
755
+ self._subtree_bytes = aggregate
756
+
757
+ def subtree_bytes_for(self, node_id: UUID) -> Optional[int]:
758
+ """The duck-typed accessor ``drill_down``'s ``expand_below_bytes`` auto-expansion
759
+ consumes (``tree_engine.query.inspection._subtree_bytes_for``). Returns the {p067}
760
+ missing/stale sentinel (``None``) when no aggregate has been computed yet, ``node_id``
761
+ is not (or no longer) live, or the aggregate predates a pointwise mutation -- never a
762
+ stale number.
763
+ """
764
+ if self._subtree_bytes is None:
765
+ return None
766
+ path = self._node_path_for(node_id)
767
+ if path is None:
768
+ return None
769
+ try:
770
+ return self._subtree_bytes.bytes_of(path)
771
+ except KeyError:
772
+ return None
773
+
774
+ def _node_path_for(self, node_id: UUID) -> Optional[Tuple[str, ...]]:
775
+ """Root-to-``node_id`` path of node-id strings, via ``parent_index`` alone (no live
776
+ ``LiveNode``/``.parent`` walk needed), matching the path shape
777
+ ``SubtreeBytesAggregate`` keys its cache by. ``None`` when ``node_id`` is not indexed."""
778
+ if node_id not in self.parent_index:
779
+ return None
780
+ path: List[str] = []
781
+ current: Optional[UUID] = node_id
782
+ while current is not None:
783
+ path.append(str(current))
784
+ current = self.parent_index.get(current)
785
+ return tuple(reversed(path))