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,458 @@
1
+ """The YAML format plugin surface (concept C-016, step G-023/T-001/A-005).
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+
6
+ Scope: the contract surface itself -- published metadata, the pipeline stages
7
+ of ``FormatPluginContract``, the CORE-side ``FormatBoundary`` methods, and the
8
+ ready-made ``YAML_FORMAT_PLUGIN`` singleton a sibling registry step registers
9
+ under ``format_id="yaml"`` for the ``.yaml``/``.yml`` extensions. The work
10
+ itself lives in the package's other modules: :mod:`.scanner` (lexical layer),
11
+ :mod:`.builder` (node identity), :mod:`.reader` and :mod:`.flow` (source text
12
+ to common-model nodes) and :mod:`.emitter` (common model back out). This
13
+ package is standalone -- standard library plus sibling
14
+ ``tree_engine`` modules only, no third-party YAML library and nothing from the
15
+ legacy editor package.
16
+
17
+ Supported subset: block mappings; block sequences, including the compact
18
+ ``- key: value`` form and the form that sits at the same indentation as its
19
+ key; flow mappings ``{a: 1}`` and flow sequences ``[1, 2]``, nested freely,
20
+ spanning lines, with comments and trailing commas inside them; plain, single-
21
+ and double-quoted scalars, on one line or continued over the lines below;
22
+ literal (``|``) and folded (``>``) block scalars with indent and chomping
23
+ indicators; full-line and trailing comments; blank lines; ``---``/``...``
24
+ document markers.
25
+
26
+ Error classification is exact, and the three cases never overlap:
27
+
28
+ * ``UNSUPPORTED_TRANSLATION`` -- well-formed YAML this model cannot reproduce
29
+ faithfully: anchors (``&``), aliases (``*``), tags (``!``), explicit keys
30
+ (``?``), merge keys (``<<``), and a flow collection used as a block mapping
31
+ key. Never a silent flattening.
32
+ * ``FORMAT_CONTENT_PARSE_FAILED`` / ``FORMAT_FRAGMENT_PARSE_FAILED`` --
33
+ damaged source: a tab in the indentation, an unterminated quoted scalar or
34
+ flow collection, inconsistent indentation, mapping and sequence entries in
35
+ one block, or a line that is neither an entry nor trivia (which includes a
36
+ bare top-level scalar document, outside this subset). The first code is for
37
+ a whole document, the second for a fragment.
38
+ * ``FORMAT_PLUGIN_CONTRACT_ERROR`` -- only a caller passing an argument of the
39
+ wrong type. Never used for anything the source text did.
40
+
41
+ Every node the plugin produces carries a fresh UUID4 ``node_id`` and a
42
+ document-local positive ``short_id`` ({p013}, {p097}).
43
+
44
+ Source-of-truth requirement labels honored here: {p022}, {p026}, {p049},
45
+ {p056}, {p060}, {p062}.
46
+ """
47
+
48
+ from __future__ import annotations
49
+
50
+ from types import MappingProxyType
51
+ from typing import Any, List, Mapping, Optional, Tuple, Union
52
+
53
+ from tree_engine.core.nodes import Document, Node
54
+ from tree_engine.core.plugin_boundary import FormatBoundary
55
+ from tree_engine.exceptions import FormatContentParseFailed, FormatFragmentParseFailed
56
+ from tree_engine.plugins.contract import (
57
+ FormatPluginContract, FormatPluginMetadata, SemanticRoleMapping,
58
+ )
59
+ from tree_engine.plugins.json_pointer import JsonPointerNotation
60
+ from tree_engine.plugins.yaml.builder import NodeBuilder
61
+ from tree_engine.plugins.yaml.emitter import (
62
+ emit, is_source_tree, node_to_plain, plain_to_node, render,
63
+ )
64
+ from tree_engine.plugins.yaml.ranges import assign_buffer_ranges
65
+ from tree_engine.plugins.yaml.reader import YamlReader
66
+ from tree_engine.plugins.yaml.scanner import (
67
+ ENTRY_KINDS, FORMAT_ID, KIND_DOCUMENT, KIND_FLOW_ITEM,
68
+ KIND_FLOW_MAPPING, KIND_FLOW_PAIR, KIND_FLOW_SEQUENCE, KIND_ITEM, KIND_MAPPING,
69
+ KIND_PAIR, KIND_SEQUENCE, KIND_TRIVIA, MAPPING_KINDS, PAIR_KINDS, SEQUENCE_KINDS,
70
+ YamlSyntaxError, contract_error,
71
+ )
72
+
73
+ __all__ = ["FORMAT_ID", "METADATA", "YAML_POINTER", "YamlFormatPlugin", "YAML_FORMAT_PLUGIN"]
74
+
75
+ METADATA = FormatPluginMetadata(
76
+ format_id=FORMAT_ID,
77
+ aliases=("yml",),
78
+ file_extensions=("yaml", "yml"),
79
+ plugin_version="1.0.0",
80
+ contract_version="1.0.0",
81
+ capabilities={
82
+ # Whether the Code Analysis server can save a file of this format (decision D-CB.4); the editor reads it
83
+ # instead of keeping its own list of unsupported suffixes.
84
+ "ca_save_supported": True,
85
+ "semantic_role_mapping": True,
86
+ # Measured: pipeline/checks/check_roundtrip.py's STRICT policy for
87
+ # yaml round-tripped the FULL real corpus (916/918 tracked
88
+ # .yaml/.yml files, no sampling) byte-identical, and the 2
89
+ # remaining refusals are excused (PyYAML itself rejects the same
90
+ # bytes as malformed) -- True is honest.
91
+ "byte_identical_round_trip": True,
92
+ # Addressable common-model tree, walkable for preview/search.
93
+ "navigable": True,
94
+ # Round trip is byte-identical (modulo the excused-malformed
95
+ # exception above) -- safe for write-back.
96
+ "editable": True,
97
+ },
98
+ )
99
+
100
+ #: YAML models no function, method, class or module construct, so the mapping
101
+ #: is empty by design. Callers observe that as ``roles_for(role) == ()`` for
102
+ #: every standard role, which is exactly what {p056} asks of a format that
103
+ #: does not model them -- not an error and not an omission.
104
+ _ROLE_MAP = SemanticRoleMapping({})
105
+
106
+ #: Entry kinds that carry a sequence position rather than a key.
107
+ _ITEM_KINDS = (KIND_ITEM, KIND_FLOW_ITEM)
108
+
109
+ #: ``context_kind`` values (bug f2991fc0's hint, stage S3 of wish 8564a2ba)
110
+ #: that mark an insert/replace landing at a BLOCK entry slot -- either an
111
+ #: existing sibling entry's own kind, or the routed container's kind when
112
+ #: the container is currently empty (see ``facade._insert_context_kind``).
113
+ #: A fragment landing here is unambiguously "one or more entries", never a
114
+ #: bare container VALUE, which is what licenses the unwrap in
115
+ #: :meth:`YamlFormatPlugin.parse_fragment` below.
116
+ _BLOCK_ENTRY_CONTEXTS = (KIND_PAIR, KIND_ITEM, KIND_MAPPING, KIND_SEQUENCE)
117
+
118
+ #: The flow-collection counterpart of ``_BLOCK_ENTRY_CONTEXTS``.
119
+ _FLOW_ENTRY_CONTEXTS = (KIND_FLOW_PAIR, KIND_FLOW_ITEM, KIND_FLOW_MAPPING, KIND_FLOW_SEQUENCE)
120
+
121
+
122
+ def _decode_fragment_text(fragment: Union[str, bytes]) -> str:
123
+ """Decode a fragment argument to ``str``, raising the fragment-scoped public error.
124
+
125
+ Shared by the flow-entry path below, which needs the decoded text before
126
+ any reader exists to decode it through (unlike the block path, whose
127
+ ``_read`` does its own bytes-to-str step).
128
+ """
129
+
130
+ if isinstance(fragment, (bytes, bytearray)):
131
+ try:
132
+ return bytes(fragment).decode("utf-8")
133
+ except UnicodeDecodeError as exc:
134
+ raise FormatFragmentParseFailed(
135
+ f"cannot decode YAML fragment as utf-8: {exc}", plugin_id=FORMAT_ID) from exc
136
+ if isinstance(fragment, str):
137
+ return fragment
138
+ raise contract_error(f"YAML fragment must be str or bytes, got {type(fragment).__name__}")
139
+
140
+
141
+ def _flow_fragment_entry(text: str, entry_kind: str) -> Node:
142
+ """Parse a standalone flow-entry fragment (bug/feature S3, wish 8564a2ba).
143
+
144
+ A caller inserting a new flow item/pair supplies, at either edge of
145
+ ``text``, the ``", "`` (or whatever spacing/format this document actually
146
+ uses) separator that belongs between the new entry and whichever existing
147
+ neighbour supplies none of its own -- exactly the punctuation
148
+ ``FlowReader._flow_entry`` itself would fold into the PRECEDING entry's
149
+ ``tail`` were this fragment already sitting inside a real ``[...]``/
150
+ ``{...}`` collection. A run of whitespace plus at most one comma is
151
+ trimmed from each edge here and folded into the returned node's own
152
+ ``head``/``tail``, so the CORE text in between is parsed exactly like an
153
+ entry found inside a real collection -- a quoted value's own internal
154
+ comma or whitespace is never touched, only what surrounds it.
155
+ """
156
+
157
+ builder = NodeBuilder()
158
+ edge = YamlReader(text, builder)
159
+ lead = edge._flow_skip(0)
160
+ if lead < len(text) and text[lead] == ",":
161
+ lead = edge._flow_skip(lead + 1)
162
+ trail = len(text)
163
+ while trail > lead and text[trail - 1] in " \t\r\n":
164
+ trail -= 1
165
+ if trail > lead and text[trail - 1] == ",":
166
+ trail -= 1
167
+ while trail > lead and text[trail - 1] in " \t\r\n":
168
+ trail -= 1
169
+ core = text[lead:trail]
170
+ if not core:
171
+ raise YamlSyntaxError("empty value in a flow fragment")
172
+ core_reader = YamlReader(core, builder)
173
+ entry, end = core_reader._flow_entry(0, entry_kind)
174
+ if end != len(core):
175
+ raise YamlSyntaxError("unexpected trailing text in a flow fragment")
176
+ fields = dict(entry.fields)
177
+ fields["head"] = text[:lead] + fields.get("head", "")
178
+ fields["tail"] = fields.get("tail", "") + text[trail:]
179
+ return Node(kind=entry.kind, fields=MappingProxyType(fields), children=entry.children,
180
+ node_id=entry.node_id, short_id=entry.short_id)
181
+
182
+
183
+ def _pointer_key(entry: Node) -> Optional[str]:
184
+ """A mapping entry's pointer token: its decoded key, else its raw key text.
185
+
186
+ ``decode_scalar`` resolves a key to its YAML value, so ``port: 8080`` gives
187
+ the integer ``8080`` and a JSON Pointer -- whose tokens are strings and
188
+ nothing else -- cannot use it directly. ``key_raw`` is the exact source
189
+ text of the same key, which IS a string and is what a reader of the file
190
+ would type, so it is the fallback. An entry carrying neither has no token
191
+ and no pointer, rather than one invented from its position.
192
+ """
193
+
194
+ key = entry.fields.get("key")
195
+ if isinstance(key, str):
196
+ return key
197
+ raw = entry.fields.get("key_raw")
198
+ return raw if isinstance(raw, str) else None
199
+
200
+
201
+ def _pointer_step(parent: Node, child: Node, ordinal: int) -> Optional[Tuple[Tuple[str, ...], bool]]:
202
+ """This format's structural half of RFC 6901, for ``JsonPointerNotation``.
203
+
204
+ YAML models comments, blank lines and ``---`` markers as real nodes so a
205
+ document round-trips byte-identically. None of them is a value, and RFC
206
+ 6901 addresses values only, so each is refused a pointer instead of being
207
+ given a synthesized one. Block and flow collections are distinct kinds
208
+ carrying identical data, and both are handled by the same clauses here.
209
+ """
210
+
211
+ kind, child_kind = parent.kind, child.kind
212
+ if kind == KIND_DOCUMENT:
213
+ # The stream wrapper is not a value; its single value block is what the
214
+ # empty pointer names, so the block claims the root rather than nesting
215
+ # under it.
216
+ return None if child_kind == KIND_TRIVIA else ((), True)
217
+ if kind in MAPPING_KINDS:
218
+ if child_kind not in PAIR_KINDS:
219
+ return None
220
+ key = _pointer_key(child)
221
+ return ((key,), False) if key is not None else None
222
+ if kind in SEQUENCE_KINDS:
223
+ return ((str(ordinal),), False) if child_kind in _ITEM_KINDS else None
224
+ if kind in ENTRY_KINDS:
225
+ # A pair or item is the route to its value, never the value itself.
226
+ return ((), True)
227
+ return None
228
+
229
+
230
+ #: The plugin's reference-notation declaration, read duck-typed by
231
+ #: ``tree_engine.core.identifier_map``. ``root_addressable`` is false because
232
+ #: ``yaml:Document`` is a stream wrapper: the empty pointer names the value
233
+ #: block inside it, which claims that pointer through the step above.
234
+ YAML_POINTER = JsonPointerNotation(_pointer_step, root_addressable=False)
235
+
236
+
237
+ class YamlFormatPlugin(FormatPluginContract, FormatBoundary):
238
+ """The registered ``format_id="yaml"`` plugin (concept C-016).
239
+
240
+ ``FormatPluginContract`` and ``FormatBoundary`` each declare an abstract
241
+ method named ``parse_document`` (and likewise ``parse_fragment``) with
242
+ different call conventions -- ``(source, options)`` positionally for the
243
+ contract, ``(source, *, source_format_id)`` for the core boundary. The
244
+ signatures below are supersets of both, so one concrete method satisfies
245
+ each name on both bases, exactly as the plain_text and BSL plugins do.
246
+ """
247
+
248
+ #: This format's native reference notation ({p021} third correspondence):
249
+ #: JSON Pointer, computed and parsed here rather than by shared code.
250
+ native_reference = YAML_POINTER
251
+
252
+ @property
253
+ def metadata(self) -> FormatPluginMetadata:
254
+ """Return this plugin's static identity and capability surface."""
255
+
256
+ return METADATA
257
+
258
+ def _read(self, source: Union[str, bytes]) -> Tuple[NodeBuilder, List[Node]]:
259
+ """Decode ``source`` and read it, raising the package-private syntax signal.
260
+
261
+ Shared by ``parse_document`` and ``parse_fragment`` so both go through
262
+ exactly one reader; each caller maps :class:`YamlSyntaxError` to the
263
+ error code its own stage owns.
264
+ """
265
+
266
+ if isinstance(source, (bytes, bytearray)):
267
+ try:
268
+ text = bytes(source).decode("utf-8")
269
+ except UnicodeDecodeError as exc:
270
+ raise YamlSyntaxError(f"cannot decode YAML source as utf-8: {exc}") from exc
271
+ elif isinstance(source, str):
272
+ text = source
273
+ else:
274
+ raise contract_error(
275
+ f"YAML source must be str or bytes, got {type(source).__name__}")
276
+ builder = NodeBuilder()
277
+ return builder, YamlReader(text, builder).read_stream()
278
+
279
+ def parse_document(self, source: Union[str, bytes],
280
+ options: Optional[Mapping[str, Any]] = None, *,
281
+ source_format_id: Optional[str] = None) -> Document:
282
+ """Parse full YAML source into a common-model ``Document``.
283
+
284
+ Damaged source raises ``FormatContentParseFailed``
285
+ (``ErrorCode.FORMAT_CONTENT_PARSE_FAILED``), the code that authorizes
286
+ the plain-text fallback per {p023}. Well-formed YAML that this model
287
+ cannot reproduce raises ``UnsupportedTranslation`` instead, and that
288
+ distinction is deliberate: only the first justifies falling back.
289
+ """
290
+
291
+ try:
292
+ builder, children = self._read(source)
293
+ except YamlSyntaxError as exc:
294
+ raise FormatContentParseFailed(f"cannot parse YAML document: {exc}", plugin_id=FORMAT_ID,
295
+ line=exc.line, column=exc.column,
296
+ message=exc.bare_message or str(exc)) from exc
297
+ root = builder.node(KIND_DOCUMENT, {}, children)
298
+ text = source if isinstance(source, str) else bytes(source).decode("utf-8")
299
+ return Document(root=assign_buffer_ranges(root, text), source_format_id=FORMAT_ID)
300
+
301
+ def parse_fragment(self, fragment: Union[str, bytes],
302
+ options: Optional[Mapping[str, Any]] = None, *,
303
+ source_format_id: Optional[str] = None) -> Union[Node, List[Node]]:
304
+ """Parse one YAML fragment into common-model node(s).
305
+
306
+ Damaged fragment text raises ``FormatFragmentParseFailed``
307
+ (``ErrorCode.FORMAT_FRAGMENT_PARSE_FAILED``), the fragment-scoped
308
+ counterpart of the document code, so a caller can tell which stage
309
+ failed. A fragment holding one block gets that block; one holding
310
+ several gets a document node wrapping them.
311
+
312
+ ``options["context_kind"]`` (bug f2991fc0, stage S3 of wish 8564a2ba)
313
+ is the kind of the node this fragment is about to replace, or of the
314
+ anchor/container it will land beside/inside. Two shapes it
315
+ disambiguates here, where the block reader's own grammar cannot
316
+ otherwise tell "one whole container VALUE" from "one or more
317
+ ENTRIES of an existing container" apart:
318
+
319
+ * a FLOW context (``yaml:Flow*``) -- routed to
320
+ :func:`_flow_fragment_entry`, since a bare flow item/pair (``"99"``,
321
+ ``"k: v"``) has no block-entry syntax at all and the ordinary block
322
+ reader rejects it outright ("expected a mapping or sequence
323
+ entry").
324
+ * a BLOCK entry context (``yaml:Pair``/``Item``/``Mapping``/
325
+ ``Sequence``) -- the ordinary block reader parses a single
326
+ ``"key: value\\n"``/``"- value\\n"`` fragment into a ONE-CHILD
327
+ ``yaml:Mapping``/``yaml:Sequence`` wrapper (its own block-structure
328
+ grammar always wraps entries in their container kind, even for
329
+ exactly one), and splicing that wrapper in as an entry's own
330
+ SIBLING silently corrupts the tree with a container-kind node
331
+ where only entry-kind nodes belong (adversarially confirmed: a
332
+ ``facade.replace``/``insert`` of such a fragment at a ``yaml:Pair``
333
+ slot leaves a stray ``yaml:Mapping`` sibling of ``yaml:Pair``
334
+ nodes, even though the rendered BYTES still happen to come out
335
+ right). The container context here licenses unwrapping that
336
+ single-child wrapper to the entry/entries it actually holds.
337
+ """
338
+
339
+ context_kind: Optional[str] = None
340
+ if isinstance(options, Mapping):
341
+ raw_context = options.get("context_kind")
342
+ if isinstance(raw_context, str):
343
+ context_kind = raw_context
344
+
345
+ if context_kind in _FLOW_ENTRY_CONTEXTS:
346
+ text = _decode_fragment_text(fragment)
347
+ entry_kind = (KIND_FLOW_ITEM if context_kind in (KIND_FLOW_ITEM, KIND_FLOW_SEQUENCE)
348
+ else KIND_FLOW_PAIR)
349
+ try:
350
+ return _flow_fragment_entry(text, entry_kind)
351
+ except YamlSyntaxError as exc:
352
+ raise FormatFragmentParseFailed(f"cannot parse YAML flow fragment: {exc}",
353
+ plugin_id=FORMAT_ID) from exc
354
+
355
+ try:
356
+ builder, children = self._read(fragment)
357
+ except YamlSyntaxError as exc:
358
+ raise FormatFragmentParseFailed(f"cannot parse YAML fragment: {exc}",
359
+ plugin_id=FORMAT_ID) from exc
360
+ if len(children) == 1:
361
+ result = children[0]
362
+ if (context_kind in _BLOCK_ENTRY_CONTEXTS
363
+ and result.kind in (KIND_MAPPING, KIND_SEQUENCE) and result.children):
364
+ entries = list(result.children)
365
+ return entries[0] if len(entries) == 1 else entries
366
+ return result
367
+ return builder.node(KIND_DOCUMENT, {}, children)
368
+
369
+ def import_external_tree(self, external_tree: Any,
370
+ options: Optional[Mapping[str, Any]] = None) -> Union[Node, Document]:
371
+ """Translate an external YAML representation through the shared importer."""
372
+
373
+ return self.import_to_common(external_tree, options)
374
+
375
+ def import_to_common(self, external_representation: Any,
376
+ options: Optional[Mapping[str, Any]] = None) -> Union[Node, Document]:
377
+ """The single input translator shared by every stage ({p056}, {p057}).
378
+
379
+ Accepts YAML source text or bytes, which it reads here, or an
380
+ already-decoded plain Python value, which it converts to raw-less
381
+ nodes; common-model input passes through unchanged. The result is
382
+ always common-model nodes, never an internal representation.
383
+ """
384
+
385
+ if isinstance(external_representation, (Node, Document)):
386
+ return external_representation
387
+ if isinstance(external_representation, (str, bytes, bytearray)):
388
+ return self.parse_document(external_representation, options)
389
+ return plain_to_node(NodeBuilder(), external_representation, frozenset())
390
+
391
+ def export_from_common(self, nodes: Union[Node, Document],
392
+ options: Optional[Mapping[str, Any]] = None) -> Any:
393
+ """Translate common-model nodes into plain YAML-compatible Python data."""
394
+
395
+ root = nodes.root if isinstance(nodes, Document) else nodes
396
+ if not isinstance(root, Node):
397
+ raise contract_error(f"expected a Node or Document, got {type(nodes).__name__}")
398
+ return node_to_plain(root)
399
+
400
+ def generate_output(self, target: Union[Node, Document, Any],
401
+ options: Optional[Mapping[str, Any]] = None) -> Union[str, bytes]:
402
+ """Produce the final YAML text, or bytes when ``options['as_bytes']`` is set.
403
+
404
+ A tree that still carries its parsed source text is replayed verbatim,
405
+ which is what makes the document round trip byte for byte; a tree built
406
+ from plain values, and a plain value handed in directly, are written in
407
+ the deterministic canonical style instead.
408
+ """
409
+
410
+ options = options or {}
411
+ if isinstance(target, (Node, Document)):
412
+ root = target.root if isinstance(target, Document) else target
413
+ text = render(root) if is_source_tree(root) else emit(node_to_plain(root), 0)
414
+ elif isinstance(target, (dict, list, tuple, str, int, float, bool)) or target is None:
415
+ text = emit(target, 0)
416
+ else:
417
+ raise contract_error(f"cannot generate output for {type(target).__name__}")
418
+ return text.encode("utf-8") if options.get("as_bytes") else text
419
+
420
+ def semantic_role_mapping(self) -> SemanticRoleMapping:
421
+ """Return the declarative kind-to-role table: empty for YAML ({p056})."""
422
+
423
+ return _ROLE_MAP
424
+
425
+ # -- FormatBoundary ----------------------------------------------------
426
+
427
+ def render_document(self, document: Document) -> bytes:
428
+ """Render a whole ``Document`` back to source bytes, byte-identically."""
429
+
430
+ result = self.generate_output(document, {"as_bytes": True})
431
+ if not isinstance(result, bytes):
432
+ raise contract_error(f"render_document expected bytes, got {type(result).__name__}")
433
+ return result
434
+
435
+ def render_fragment(self, node: Node) -> str:
436
+ """Render a single fragment ``Node`` back to source text."""
437
+
438
+ result = self.generate_output(node, {})
439
+ if not isinstance(result, str):
440
+ raise contract_error(f"render_fragment expected str, got {type(result).__name__}")
441
+ return result
442
+
443
+ # Deliberately NO adjust_after_delete hook (verifier finding B, S3 of wish
444
+ # 8564a2ba): an earlier version synthesized the empty-collection marker a
445
+ # BLOCK entry needs after its value's last real child is deleted by
446
+ # mutating the owning Pair's/Item's ``head`` field directly, OUTSIDE the
447
+ # mutation journal -- which left session_undo restoring a sibling next to
448
+ # a now-STALE marker and raising an unhandled ValueError (nothing recorded
449
+ # the field change, so nothing could reverse it). The marker is instead
450
+ # computed PURELY at render time, from the already-current tree shape,
451
+ # every time the document renders -- see
452
+ # ``tree_engine.plugins.yaml.emitter.render``'s own docstring. Nothing is
453
+ # mutated, so there is nothing for undo/redo to desynchronize from.
454
+
455
+
456
+ #: Ready-made stateless singleton, the same registration shape the plain_text,
457
+ #: JSON, TOML, Python and BSL plugins expose.
458
+ YAML_FORMAT_PLUGIN = YamlFormatPlugin()
@@ -0,0 +1,52 @@
1
+ """``buffer_range`` assignment for a freshly parsed YAML tree (bug b548f445).
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+
6
+ The reader gives every source byte to exactly one node ({p022}): a leaf renders as its ``raw`` and a
7
+ structural node as ``head`` + its children + ``tail`` (see :func:`emitter.render`). A node's offset
8
+ therefore follows from lengths alone, with no second scan of the source and no ``render_fragment``
9
+ call. Offsets are half-open UTF-8 byte offsets into the source, the python plugin's unit.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from dataclasses import replace
15
+ from typing import Dict, Tuple
16
+
17
+ from tree_engine.core.nodes import Node
18
+ from tree_engine.core.offsets import char_to_byte_offset
19
+ from tree_engine.plugins.yaml.scanner import RAW_KINDS
20
+
21
+ __all__ = ["assign_buffer_ranges"]
22
+
23
+
24
+ def assign_buffer_ranges(root: Node, text: str) -> Node:
25
+ """Return ``root`` rebuilt (identities preserved) with ``buffer_range`` on every node."""
26
+
27
+ conv = char_to_byte_offset(text)
28
+ lengths: Dict[int, int] = {}
29
+
30
+ def length(node: Node) -> int:
31
+ cached = lengths.get(id(node))
32
+ if cached is None:
33
+ if node.kind in RAW_KINDS:
34
+ cached = len(node.fields.get("raw", ""))
35
+ else:
36
+ cached = (len(node.fields.get("head", "")) + len(node.fields.get("tail", ""))
37
+ + sum(length(child) for child in node.children))
38
+ lengths[id(node)] = cached
39
+ return cached
40
+
41
+ def build(node: Node, start: int) -> Node:
42
+ children: Tuple[Node, ...] = ()
43
+ if node.children:
44
+ pos = start + len(node.fields.get("head", ""))
45
+ built = []
46
+ for child in node.children:
47
+ built.append(build(child, pos))
48
+ pos += length(child)
49
+ children = tuple(built)
50
+ return replace(node, children=children, buffer_range=(conv(start), conv(start + length(node))))
51
+
52
+ return build(root, 0)