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,306 @@
1
+ """Common-model-to-LibCST export pipeline for the Python translator (C-014).
2
+
3
+ Scope (concept C-014, narrowed to the EXPORT direction only): this module is
4
+ the exact inverse of the merged ``import_map.py``. It converts a common-model
5
+ tree (:class:`~tree_engine.core.nodes.Node` / ``Document``) that was built by
6
+ (or shaped exactly like) ``PythonImportMap.import_to_common`` back into a
7
+ *temporary* LibCST tree, then runs LibCST's own code generation to produce
8
+ source bytes in the encoding preserved on the common model. It also exposes
9
+ ``export_tree``, the export side of the ``import_tree``/``export_tree``
10
+ bridge {p048} for callers that want the reconstructed LibCST object itself
11
+ (the "LibCST-compatible subset") rather than generated bytes.
12
+
13
+ Translation strategy -- generic, mirroring the importer exactly: every
14
+ common-model ``Node`` whose ``kind`` is ``"python:<LibCST class name>"`` is
15
+ rebuilt by looking up that class on the installed ``libcst`` module and
16
+ calling it with keyword arguments built from ``Node.fields``, one entry per
17
+ LibCST dataclass field -- no hand-maintained per-node-kind table, so the
18
+ mapping can never drift from the importer's. The two marker kinds the
19
+ importer introduced are decoded back into the exact values LibCST expects:
20
+
21
+ * ``"python:$sentinel"`` (only ever ``libcst.MaybeSentinel.DEFAULT`` in this
22
+ LibCST version, per the importer's own docstring) is resolved back to the
23
+ named ``enum.Enum`` member, importing whatever module the marker recorded
24
+ rather than hard-coding ``MaybeSentinel`` -- symmetric with the importer's
25
+ own generic (not per-node-kind) treatment of enum values.
26
+ * ``"python:$scalar"`` unwraps back to the bare primitive it wrapped, for a
27
+ primitive that appeared as an element of a ``Sequence``/``tuple`` field.
28
+
29
+ A common-model ``Node`` whose ``kind`` names no attribute of ``libcst`` at
30
+ all has no mappable LibCST equivalent and raises
31
+ :class:`~tree_engine.plugins.contract.UnsupportedTranslationError` (carrying
32
+ ``ErrorCode.UNSUPPORTED_TRANSLATION`` from ``src/tree_engine/errors.py``),
33
+ identifying the offending node kind -- never guessed, approximated, or
34
+ silently dropped. A recognized kind whose stored fields do not satisfy that
35
+ LibCST class's own constructor (a shape mismatch, not a missing mapping) is a
36
+ different failure and raises
37
+ :class:`~tree_engine.plugins.contract.FormatPluginContractError` instead, the
38
+ same distinction the importer draws between "cannot represent" and "not a
39
+ CSTNode at all".
40
+
41
+ Byte ranges ({p102}) are metadata the importer attached to
42
+ ``Node.buffer_range`` for addressing/query purposes; LibCST's code generator
43
+ never consumes stored byte offsets, only trivia/whitespace/comment fields
44
+ (which are ordinary ``Node.fields`` entries here, exactly as the importer
45
+ left them), so an unchanged document reproduces its own byte ranges for free
46
+ by reproducing its own bytes -- this module has nothing extra to "replay"
47
+ for them. Likewise ``encoding``, ``default_indent``, ``default_newline``,
48
+ ``has_trailing_newline``, ``header``, and ``footer`` need no side-channel:
49
+ they are simply ``"python:Module"``'s own ``fields`` entries, restored by
50
+ the same generic field-by-field reconstruction as every other node.
51
+
52
+ A full document (a common-model ``Document`` whose ``root`` is a
53
+ ``"python:Module"`` node) is rebuilt into a real ``libcst.Module`` and
54
+ rendered via its own ``.bytes`` property (``code_for_node(self).encode(self.encoding)``),
55
+ so the preserved encoding is exactly what produces the final bytes. A bare
56
+ fragment ``Node`` is rebuilt into whatever ``CSTNode`` its kind names and
57
+ rendered via ``libcst.Module(body=[]).code_for_node(fragment)`` -- the
58
+ documented way to render an arbitrary ``CSTNode`` without a real enclosing
59
+ module -- returning ``str`` rather than ``bytes`` since a fragment carries no
60
+ preserved encoding of its own.
61
+
62
+ Every LibCST object this module constructs is local to one
63
+ ``export_from_common``/``export_tree`` call: ``export_from_common`` returns
64
+ only ``bytes``/``str`` and retains no reference to the tree it built once it
65
+ returns, so nothing keeps that temporary tree alive afterward (including on
66
+ the ``UnsupportedTranslationError``/``FormatPluginContractError`` paths,
67
+ which unwind without stashing anything in module- or instance-level state).
68
+ ``export_tree`` is the one deliberate exception: per its bridge contract it
69
+ returns the rebuilt LibCST object itself to the caller, exactly as
70
+ ``import_tree`` accepts one -- the caller, not this module, owns it from
71
+ that point on.
72
+
73
+ ``PythonExportMap`` is not itself a complete
74
+ :class:`~tree_engine.plugins.contract.FormatPluginContract` implementation
75
+ -- it supplies that contract's export stage only, the sibling counterpart of
76
+ ``PythonImportMap``; a later step composes both into the full plugin.
77
+
78
+ Source-of-truth requirement labels honored here: {p008}, {p022}, {p048},
79
+ {p049}, {p102}.
80
+ """
81
+
82
+ from __future__ import annotations
83
+
84
+ import importlib
85
+ from typing import Any, Dict, Mapping, Optional, Union
86
+
87
+ import libcst
88
+
89
+ from tree_engine.core.nodes import Document, FieldValue, Node
90
+ from tree_engine.plugins.contract import FormatPluginContractError, UnsupportedTranslationError
91
+
92
+ __all__ = [
93
+ "FORMAT_ID",
94
+ "PythonExportMap",
95
+ "export_tree",
96
+ ]
97
+
98
+ FORMAT_ID = "python"
99
+
100
+ _KIND_PREFIX = "python:"
101
+ _SENTINEL_KIND = f"{_KIND_PREFIX}$sentinel"
102
+ _SCALAR_KIND = f"{_KIND_PREFIX}$scalar"
103
+
104
+
105
+ def _contract_error(message: str) -> FormatPluginContractError:
106
+ return FormatPluginContractError(plugin_id=FORMAT_ID, message=message)
107
+
108
+
109
+ def _unsupported(node_kind: str, message: str = "") -> UnsupportedTranslationError:
110
+ return UnsupportedTranslationError(node_type=node_kind, format_id=FORMAT_ID, message=message)
111
+
112
+
113
+ def _resolve_enum_member(enum_class_path: str, member_name: str) -> Any:
114
+ """Resolve a ``"$sentinel"`` marker's ``enum_class``/``member`` pair
115
+ back to the live ``enum.Enum`` member, generically -- not hard-coded to
116
+ ``MaybeSentinel`` -- by importing progressively shorter module-name
117
+ prefixes of the dotted path until one imports successfully, then
118
+ walking any remaining dotted attribute(s) off of it. Mirrors the
119
+ importer's own generic (not per-enum-kind) treatment of enum values."""
120
+
121
+ parts = enum_class_path.split(".")
122
+ for split in range(len(parts), 0, -1):
123
+ module_name = ".".join(parts[:split])
124
+ try:
125
+ module = importlib.import_module(module_name)
126
+ except ImportError:
127
+ continue
128
+ target: Any = module
129
+ try:
130
+ for attr in parts[split:]:
131
+ target = getattr(target, attr)
132
+ except AttributeError:
133
+ continue
134
+ if isinstance(target, type):
135
+ return getattr(target, member_name)
136
+ raise _contract_error(
137
+ f"cannot resolve enum class {enum_class_path!r} recorded on a "
138
+ "'$sentinel' marker node"
139
+ )
140
+
141
+
142
+ def _rebuild_node(node: Node) -> Any:
143
+ """Rebuild one common-model ``Node`` back into whatever LibCST-side
144
+ value it represents: a decoded enum member for a ``"$sentinel"``
145
+ marker, the unwrapped primitive for a ``"$scalar"`` marker, or a real
146
+ ``libcst.CSTNode`` for every other (``"python:<ClassName>"``) kind."""
147
+
148
+ if not isinstance(node, Node):
149
+ raise _contract_error(f"expected a Node, got {type(node).__name__}")
150
+
151
+ if node.kind == _SENTINEL_KIND:
152
+ enum_class_path = node.fields.get("enum_class")
153
+ member_name = node.fields.get("member")
154
+ if not isinstance(enum_class_path, str) or not isinstance(member_name, str):
155
+ raise _contract_error(
156
+ "malformed '$sentinel' marker node: expected string "
157
+ "'enum_class' and 'member' fields"
158
+ )
159
+ return _resolve_enum_member(enum_class_path, member_name)
160
+
161
+ if node.kind == _SCALAR_KIND:
162
+ if "value" not in node.fields:
163
+ raise _contract_error("malformed '$scalar' marker node: missing 'value' field")
164
+ return node.fields["value"]
165
+
166
+ if not node.kind.startswith(_KIND_PREFIX):
167
+ raise _unsupported(str(node.kind), f"node kind {node.kind!r} is not a Python plugin kind")
168
+
169
+ class_name = str(node.kind)[len(_KIND_PREFIX):]
170
+ cst_cls = getattr(libcst, class_name, None)
171
+ if cst_cls is None or not isinstance(cst_cls, type) or not issubclass(cst_cls, libcst.CSTNode):
172
+ raise _unsupported(
173
+ str(node.kind),
174
+ f"no libcst.{class_name} class exists; this common-model node "
175
+ "kind has no mappable LibCST equivalent",
176
+ )
177
+
178
+ kwargs: Dict[str, Any] = {}
179
+ for field_name, field_value in node.fields.items():
180
+ kwargs[field_name] = _rebuild_field_value(field_value)
181
+
182
+ try:
183
+ return cst_cls(**kwargs)
184
+ except TypeError as exc:
185
+ raise _contract_error(
186
+ f"stored fields of node kind {node.kind!r} do not satisfy "
187
+ f"libcst.{class_name}'s constructor: {exc}"
188
+ ) from exc
189
+
190
+
191
+ def _rebuild_field_value(value: FieldValue) -> Any:
192
+ """Inverse of the importer's ``_convert_value``: a primitive passes
193
+ through unchanged, a single ``Node`` is rebuilt via ``_rebuild_node``
194
+ (decoding a marker or reconstructing a real ``CSTNode``), and a tuple
195
+ is rebuilt element-wise the same way, in order."""
196
+
197
+ if value is None or isinstance(value, (str, int, float, bool, bytes)):
198
+ return value
199
+ if isinstance(value, Node):
200
+ return _rebuild_node(value)
201
+ if isinstance(value, tuple):
202
+ return [_rebuild_node(item) for item in value]
203
+ raise _contract_error(
204
+ f"unexpected common-model field value type {type(value).__name__}; "
205
+ "expected a primitive, a Node, or a tuple of Node"
206
+ )
207
+
208
+
209
+ def _rebuild(common_tree: Union[Node, Document]) -> Any:
210
+ """Rebuild the temporary LibCST object for either a full ``Document``
211
+ (root must reconstruct into a ``libcst.Module``) or a bare fragment
212
+ ``Node`` (reconstructs into whatever ``CSTNode`` its kind names)."""
213
+
214
+ if isinstance(common_tree, Document):
215
+ rebuilt = _rebuild_node(common_tree.root)
216
+ if not isinstance(rebuilt, libcst.Module):
217
+ raise _contract_error(
218
+ "Document.root did not reconstruct into a libcst.Module "
219
+ f"(got {type(rebuilt).__name__}); a Document's root must be "
220
+ "a 'python:Module' node"
221
+ )
222
+ return rebuilt
223
+ if isinstance(common_tree, Node):
224
+ return _rebuild_node(common_tree)
225
+ raise _contract_error(
226
+ f"expected a common-model Node or Document, got {type(common_tree).__name__}"
227
+ )
228
+
229
+
230
+ def _generate(rebuilt: Any) -> Union[bytes, str]:
231
+ """Run LibCST's own code generation over an already-rebuilt temporary
232
+ tree. A ``libcst.Module`` renders to ``bytes`` via its own ``.bytes``
233
+ property, which encodes ``code_for_node(self)`` using the module's own
234
+ preserved ``encoding`` -- exactly the preserved-encoding byte output
235
+ this step requires. Any other ``CSTNode`` (a fragment) has no encoding
236
+ of its own, so it renders to ``str`` via an empty scratch
237
+ ``libcst.Module``'s ``code_for_node`` -- LibCST's documented way to
238
+ render an arbitrary node without a real enclosing module."""
239
+
240
+ if isinstance(rebuilt, libcst.Module):
241
+ return rebuilt.bytes
242
+ if isinstance(rebuilt, libcst.CSTNode):
243
+ return libcst.Module(body=[]).code_for_node(rebuilt)
244
+ raise _contract_error(
245
+ f"rebuilt value is not a libcst.CSTNode (got {type(rebuilt).__name__}); "
246
+ "cannot generate output"
247
+ )
248
+
249
+
250
+ class PythonExportMap:
251
+ """Export (common model -> LibCST -> bytes/str) stage of the Python
252
+ translator.
253
+
254
+ Supplies the export half of the bidirectional translator described by
255
+ ``tree_engine.plugins.contract.FormatPluginContract`` ({p056}, {p057});
256
+ the import stage is delivered by the sibling, already-merged
257
+ ``PythonImportMap``, and the remaining contract surface (``metadata``,
258
+ ``parse_document``, ...) is composed later.
259
+ """
260
+
261
+ def export_from_common(
262
+ self,
263
+ common_tree: Union[Node, Document],
264
+ options: Optional[Mapping[str, Any]] = None,
265
+ ) -> Union[bytes, str]:
266
+ """Translate a common-model ``Document``/``Node`` back into source
267
+ output: ``bytes`` (in the encoding preserved on the ``Document``)
268
+ for a full document, or ``str`` for a bare fragment ``Node``.
269
+ ``options`` is accepted for contract-signature compatibility and
270
+ currently unused by the export path itself.
271
+
272
+ Raises :class:`~tree_engine.plugins.contract.UnsupportedTranslationError`
273
+ for a common-model node kind with no mappable LibCST equivalent, and
274
+ :class:`~tree_engine.plugins.contract.FormatPluginContractError` for
275
+ any other export-side contract violation (malformed marker data, a
276
+ recognized kind whose fields do not satisfy its LibCST
277
+ constructor, or a non-Module ``Document.root``). No LibCST object
278
+ is retained after this call returns, on either the success or the
279
+ error path.
280
+ """
281
+
282
+ rebuilt = _rebuild(common_tree)
283
+ return _generate(rebuilt)
284
+
285
+
286
+ def export_tree(
287
+ common_tree: Union[Node, Document],
288
+ *,
289
+ options: Optional[Mapping[str, Any]] = None,
290
+ ) -> Any:
291
+ """Export side of the ``import_tree``/``export_tree`` bridge {p048}:
292
+ rebuilds and returns the temporary LibCST object itself (a
293
+ ``libcst.Module`` for a ``Document``, or the appropriate ``CSTNode``
294
+ for a fragment ``Node``) for a caller that wants the LibCST-compatible
295
+ object rather than generated bytes/str -- the exact inverse of
296
+ ``import_tree`` accepting an already-parsed LibCST object. Unlike
297
+ :meth:`PythonExportMap.export_from_common`, the rebuilt object is
298
+ deliberately handed back here rather than discarded: from this point
299
+ on the caller, not this module, owns it.
300
+
301
+ Raises the same :class:`~tree_engine.plugins.contract.UnsupportedTranslationError`/
302
+ :class:`~tree_engine.plugins.contract.FormatPluginContractError` as
303
+ :meth:`PythonExportMap.export_from_common` for the same reasons.
304
+ """
305
+
306
+ return _rebuild(common_tree)