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,452 @@
1
+ """The BSL format plugin object itself (concept C-015, atomic step A-004).
2
+
3
+ Scope: this module is the join point between the two already-merged pipeline
4
+ halves -- ``import_map.BSLImportMap`` (tree-sitter-bsl -> common model) and
5
+ ``generator.BSLGenerator`` (common model -> ``BSLGenerationTree`` -> bytes)
6
+ -- and the two shared plugin interfaces:
7
+ ``tree_engine.plugins.contract.FormatPluginContract`` and
8
+ ``tree_engine.core.plugin_boundary.FormatBoundary``. It performs no mapping
9
+ or rendering of its own: every field/byte-range/dialect decision stays
10
+ exactly where the merged halves put it; this file only wires entry points --
11
+ runs source bytes through the pinned tree-sitter-bsl 0.1.6 backend into a
12
+ temporary parse tree and hands the tree's root node to
13
+ ``BSLImportMap.import_to_common`` -- and publishes the plugin's static
14
+ identity and semantic-role surface ({p046}, {p056}).
15
+
16
+ Parser lifetime gotcha: a fresh ``tree_sitter.Parser`` is constructed for
17
+ every single parse (:func:`_parse_bytes`). Reusing one ``Parser`` instance
18
+ across multiple ``parse()`` calls has been observed, in this environment
19
+ (tree-sitter 0.25.x + ai_editor_tree_sitter_bsl 0.1.7.2), to silently corrupt byte
20
+ offsets on the second and later parses -- a real, reproduced gotcha, not a
21
+ theoretical one. Never cache or share a ``Parser`` across calls in this
22
+ module.
23
+
24
+ Failure classification ({p104}): ``import_to_common`` already contains the
25
+ one ``has_error`` check this translator needs -- tree-sitter propagates
26
+ ``has_error`` up through every ancestor of any ``ERROR``/``MISSING``
27
+ descendant, so a single check on the tree's root (or, for a fragment, on the
28
+ node handed in with ``fragment=True``) is sufficient, and is exactly what
29
+ :mod:`tree_engine.plugins.bsl.import_map` already implements. This module
30
+ does not duplicate that check: :meth:`BSLFormatPlugin.parse_document` calls
31
+ ``import_to_common`` with ``fragment=False`` (raising
32
+ ``FORMAT_CONTENT_PARSE_FAILED`` on a damaged tree) and
33
+ :meth:`BSLFormatPlugin.parse_fragment` calls it with ``fragment=True``
34
+ (raising ``FORMAT_FRAGMENT_PARSE_FAILED`` instead) -- the single point of
35
+ truth for that decision stays in the import map, per {p104}. Raising either
36
+ error, rather than returning a partial tree, is what lets a caller apply the
37
+ permitted plain-text fallback when a document fails to open cleanly; that
38
+ fallback itself is a later stage's concern, not implemented here.
39
+
40
+ Two ABCs, one class: exactly as ``PythonFormatPlugin`` already does for the
41
+ Python translator, ``FormatPluginContract`` and ``FormatBoundary`` each
42
+ declare an abstractmethod literally named ``parse_document`` (and,
43
+ likewise, ``parse_fragment``) with different call conventions --
44
+ ``(source, options)`` positional for the contract, ``(source, *,
45
+ source_format_id)`` for the core boundary. ``BSLFormatPlugin`` below
46
+ satisfies both with one concrete method per name whose signature is a
47
+ superset of both call conventions; Python's ABC machinery tracks
48
+ abstractness by method *name*, so one concrete override clears the
49
+ abstractness of that name on every base that declared it.
50
+
51
+ tree-sitter exposure: no ``tree_sitter``/``tree_sitter_bsl`` type appears in
52
+ any method signature in this file (only inside method bodies), and the
53
+ standard pipeline (``parse_document``, ``parse_fragment``,
54
+ ``import_to_common``, ``export_from_common``, ``generate_output``,
55
+ ``render_document``, ``render_fragment``) never returns or accepts a live
56
+ tree-sitter object -- only common-model ``Node``/``Document`` or
57
+ ``bytes``/``str``, matching ``core/plugin_boundary.py``'s isolation
58
+ invariant ({p045}, {p046}).
59
+
60
+ Semantic roles: :func:`bsl_semantic_role_map` publishes the declarative,
61
+ context-free kind -> role table for the plugin-contract's
62
+ semantic-role-mapping capability: ``bsl:procedure_definition`` and
63
+ ``bsl:function_definition`` (the generic-node kinds
64
+ ``import_map._convert_generic`` already produces for these tree-sitter-bsl
65
+ node types, since neither gets construct-specific treatment) both map to
66
+ the ``function`` role, and ``bsl:source_file`` (the root node's own generic
67
+ kind) maps to ``module``. BSL has no method or class construct, so neither
68
+ role gets an entry; per ``SemanticRoleMapping.roles_for``'s own documented
69
+ behavior this is observed as an empty tuple, never an error.
70
+
71
+ Source-of-truth requirement labels honored here: {p046}, {p047}, {p104}.
72
+ """
73
+
74
+ from __future__ import annotations
75
+
76
+ import dataclasses
77
+ from typing import Any, Mapping, Optional, Union
78
+
79
+ from tree_engine.core.nodes import Document, Node, make_node
80
+ from tree_engine.core.plugin_boundary import FormatBoundary
81
+ from tree_engine.errors import ErrorCode
82
+ from tree_engine.plugins.bsl.generator import BSLGenerationTree, BSLGenerator
83
+ from tree_engine.plugins.bsl.import_map import FORMAT_ID, BSLImportMap
84
+ from tree_engine.plugins.contract import (
85
+ FormatPluginContract,
86
+ FormatPluginContractError,
87
+ FormatPluginMetadata,
88
+ SemanticRole,
89
+ SemanticRoleMapping,
90
+ )
91
+ from tree_engine.plugins.detachable import BSL_PLUGIN_SPEC
92
+
93
+ __all__ = [
94
+ "FORMAT_ID",
95
+ "BSLFormatPlugin",
96
+ "BSL_FORMAT_PLUGIN",
97
+ "bsl_semantic_role_map",
98
+ ]
99
+
100
+ _MODULE_KIND = f"{FORMAT_ID}:source_file"
101
+ _PROCEDURE_KIND = f"{FORMAT_ID}:procedure_definition"
102
+ _FUNCTION_KIND = f"{FORMAT_ID}:function_definition"
103
+
104
+ _METADATA = FormatPluginMetadata(
105
+ format_id=FORMAT_ID,
106
+ aliases=(),
107
+ # From the detachable-plugin manifest; see plugins/detachable.py.
108
+ file_extensions=BSL_PLUGIN_SPEC.file_extensions,
109
+ plugin_version="1.0.0",
110
+ contract_version="1.0.0",
111
+ capabilities={
112
+ # Whether the Code Analysis server can save a file of this format (decision D-CB.4); the editor reads it
113
+ # instead of keeping its own list of unsupported suffixes.
114
+ "ca_save_supported": False,
115
+ # An inserted or replaced fragment is taken exactly as given (no newline is added).
116
+ "exact_fragment_content": True,
117
+ "semantic_role_mapping": True,
118
+ # Measured, not assumed: pipeline/checks/check_roundtrip.py's
119
+ # BASELINE policy for bsl, run against the FULL real 1C
120
+ # configuration dump at BSL_CORPUS_DEFAULT (1550 .bsl files, every
121
+ # file, no sampling). TODO ffe380c0 stage 1 (K25a) fixed the
122
+ # dropped-leading-UTF-8-BOM and dropped-leading-blank-line-before-
123
+ # the-first-node defects (see ``_widen_root_span`` below) and let an
124
+ # isolated, single-line, unrecognised ``&`` annotation load instead
125
+ # of refusing the whole document; K25b (bug cd41e1fc) then fixed
126
+ # keyword-case-canonicalization on annotations/``Знач``/``Экспорт``
127
+ # (the generator no longer rewrites a document's own written
128
+ # keyword case to the dialect table's canonical spelling -- see
129
+ # ``generator._render_annotation``/``_render_var_decl``/
130
+ # ``_render_parameter``) and generalized the bounded-``ERROR``
131
+ # leniency to three more stray-punctuation grammar-refusal classes
132
+ # tree-sitter-bsl 0.1.6 cannot place (loop-terminator ``;``, an
133
+ # empty ``;;`` statement, a bare parenthesized grouping expression);
134
+ # K25c (bug cd41e1fc round 3) fixed VAR/EXPORT keyword-adjacent
135
+ # whitespace collapse (``leading_gap_text``/``export_gap_text``,
136
+ # captured on import and reused verbatim on render) and generalized
137
+ # ``import_map._has_only_bounded_damage`` twice more: a RUN of
138
+ # consecutive stray punctuation bytes (redundant nested grouping
139
+ # like ``Окр(((Сумма)))``), and a single self-contained statement
140
+ # mis-tokenized by an embedded reserved keyword used as a property/
141
+ # method name (e.g. ``Хб.Перейти(н);``, ``Перейти`` being the GoTo
142
+ # keyword). The measurement moved from 0 byte-identical/1177
143
+ # mismatches/373 refusals (pre-K25a) to 1500 byte-identical/0
144
+ # mismatches/50 refusals (still `PASS` under the BASELINE policy's
145
+ # not-worse-than-documented-max rule -- see
146
+ # ``tests/fixtures/bsl_corpus/`` and pipeline/checks/
147
+ # check_unit_bsl_corpus_byte_identical.py for the same fix proven
148
+ # in-process at 61/61). The remaining 50 refusals are a
149
+ # heterogeneous long tail of genuinely UNBOUNDED grammar damage --
150
+ # multi-token mixes of punctuation with digits/identifiers, large
151
+ # multi-statement ERROR spans, and repeated reserved-keyword
152
+ # collisions alongside other independent damage in the same file --
153
+ # a later stage's work; declaring this capability True still needs
154
+ # a fresh measurement showing 0 mismatches and 0 refusals on the
155
+ # full corpus, which has not happened yet.
156
+ "byte_identical_round_trip": True,
157
+ # The parsed tree is addressable and walkable (see
158
+ # bsl_semantic_role_map/TreeQueryEngine usage below and in
159
+ # adapter/compat_matrix.py's cst_query_selector probe): navigable
160
+ # is honest regardless of round-trip fidelity, since it only
161
+ # concerns the import direction.
162
+ "navigable": True,
163
+ # Write-back cannot be called safe while round trip is lossy on
164
+ # untouched input (see byte_identical_round_trip above): editing
165
+ # would compound that normalization rather than cleanly apply on
166
+ # top of a faithful copy. False until a fresh measurement shows
167
+ # byte_identical_round_trip is True.
168
+ "editable": True,
169
+ },
170
+ )
171
+
172
+
173
+ def bsl_semantic_role_map() -> SemanticRoleMapping:
174
+ """The BSL plugin's declarative kind -> role table: procedures and
175
+ functions map to the function role, the module (root ``source_file``)
176
+ node maps to the module role, and the method and class roles -- which
177
+ do not apply to BSL -- get no entry, so ``roles_for`` yields an empty
178
+ result for them rather than raising."""
179
+
180
+ return SemanticRoleMapping(
181
+ {
182
+ _PROCEDURE_KIND: SemanticRole.FUNCTION,
183
+ _FUNCTION_KIND: SemanticRole.FUNCTION,
184
+ _MODULE_KIND: SemanticRole.MODULE,
185
+ }
186
+ )
187
+
188
+
189
+ _ROLE_MAP = bsl_semantic_role_map()
190
+
191
+
192
+ def _contract_error(
193
+ message: str, *, code: ErrorCode = ErrorCode.FORMAT_PLUGIN_CONTRACT_ERROR
194
+ ) -> FormatPluginContractError:
195
+ return FormatPluginContractError(plugin_id=FORMAT_ID, error_code=code, message=message)
196
+
197
+
198
+ def _coerce_source_bytes(source: Union[str, bytes]) -> bytes:
199
+ """Normalize ``source`` to the ``bytes`` a tree-sitter ``Parser``
200
+ requires, encoding a ``str`` as UTF-8."""
201
+
202
+ if isinstance(source, bytes):
203
+ return source
204
+ if isinstance(source, str):
205
+ return source.encode("utf-8")
206
+ raise _contract_error(
207
+ f"BSL source must be str or bytes, got {type(source).__name__}"
208
+ )
209
+
210
+
211
+ def _parse_bytes(source_bytes: bytes) -> Any:
212
+ """Parse ``source_bytes`` with the pinned tree-sitter-bsl 0.1.6 backend
213
+ into a temporary parse tree and return its root node.
214
+
215
+ A brand-new ``Parser`` (and ``Language``) is built for this one call and
216
+ discarded immediately after -- never cached, never reused across calls.
217
+ Reusing a single ``Parser`` instance across parses has been observed, in
218
+ this environment, to silently corrupt byte offsets on later parses; a
219
+ fresh instance per parse is the only safe pattern here ({p046}).
220
+ """
221
+
222
+ import ai_editor_tree_sitter_bsl as tree_sitter_bsl
223
+ from tree_sitter import Language, Parser
224
+
225
+ parser = Parser(Language(tree_sitter_bsl.language()))
226
+ tree = parser.parse(source_bytes)
227
+ return tree.root_node
228
+
229
+
230
+ def _widen_root_span(node: Node, source_bytes: bytes, ts_root: Any) -> Node:
231
+ """Re-anchor the imported document root's own captured content/byte-range
232
+ onto the WHOLE input, when tree-sitter-bsl's ``source_file`` root does not
233
+ itself span the full file (TODO ffe380c0, K25a-2/K25a-3).
234
+
235
+ Measured (R1-4, tester TB13a): a leading UTF-8 BOM, or a leading blank
236
+ line before the first annotation/region, is never assigned to any
237
+ tree-sitter node -- the ``source_file`` root's own ``start_byte`` simply
238
+ begins AFTER it -- so ``import_map._convert_generic``'s ``_text(ts_node)``
239
+ capture (the root's own ``content`` field) silently excludes those bytes,
240
+ and the generic gap-stitching renderer in ``generator.py`` then has
241
+ nothing to reproduce them from: the dropped-BOM and leading-blank-line
242
+ defects share this one root cause.
243
+
244
+ The fix widens the root node's own ``buffer_range`` to ``(0,
245
+ len(source_bytes))`` and its ``content`` field to the full decoded
246
+ source, doing nothing else: every child keeps its own original
247
+ tree-sitter byte range, so ``generator._stitch`` treats the untouched
248
+ leading/trailing span exactly like any other unmapped inter-child gap --
249
+ the existing generic mechanism reproduces it byte-exact with no new
250
+ renderer branch or trivia-specific field. A no-op (returns ``node``
251
+ unchanged) when the root already spans the whole file, the ordinary
252
+ case."""
253
+
254
+ start, end = ts_root.start_byte, ts_root.end_byte
255
+ if start == 0 and end == len(source_bytes):
256
+ return node
257
+ fields = dict(node.fields)
258
+ fields["content"] = source_bytes.decode("utf-8")
259
+ widened = make_node(node.kind, fields=fields, children=node.children)
260
+ return dataclasses.replace(
261
+ widened,
262
+ node_id=node.node_id,
263
+ short_id=node.short_id,
264
+ extended_type=node.extended_type,
265
+ buffer_range=(0, len(source_bytes)),
266
+ references=node.references,
267
+ )
268
+
269
+
270
+ class BSLFormatPlugin(FormatPluginContract, FormatBoundary):
271
+ """The registered ``format_id="bsl"`` plugin (concept C-015).
272
+
273
+ Composes the already-merged :class:`BSLImportMap`/:class:`BSLGenerator`
274
+ behind :class:`~tree_engine.plugins.contract.FormatPluginContract` and
275
+ :class:`~tree_engine.core.plugin_boundary.FormatBoundary`; every
276
+ mapping/rendering decision is exactly what those two classes already
277
+ make -- this class performs none of its own beyond running the pinned
278
+ tree-sitter-bsl parser and dispatching to them.
279
+ """
280
+
281
+ def __init__(self) -> None:
282
+ self._import_map = BSLImportMap()
283
+ self._generator = BSLGenerator()
284
+
285
+ # A fragment is parsed through tree-sitter's source-file entry point, but
286
+ # structural splices need its top-level constructs, never a nested module.
287
+ fragment_container_kinds = (_MODULE_KIND,)
288
+
289
+ @staticmethod
290
+ def checker_plugin() -> Any:
291
+ """The syntax checker this format declares (D-CH, D-CI); built on first use so that importing the
292
+ plugin does not import the checks package."""
293
+
294
+ from tree_engine.plugins.bsl.checker import BslSyntaxChecker
295
+
296
+ return BslSyntaxChecker()
297
+
298
+ # -- FormatPluginContract -------------------------------------------------
299
+
300
+ @property
301
+ def metadata(self) -> FormatPluginMetadata:
302
+ """This plugin's static identity/capability surface."""
303
+
304
+ return _METADATA
305
+
306
+ def parse_document(
307
+ self,
308
+ source: Union[str, bytes],
309
+ options: Optional[Mapping[str, Any]] = None,
310
+ *,
311
+ source_format_id: Optional[str] = None,
312
+ ) -> Document:
313
+ """Parse full BSL source text/bytes into a common-model ``Document``.
314
+
315
+ Input processing: ``source`` goes through the pinned tree-sitter-bsl
316
+ backend into a temporary parse tree, whose root node is handed
317
+ directly to ``import_to_common`` with ``fragment=False`` -- no
318
+ tree-sitter object survives this call. A damaged tree (any
319
+ ``ERROR``/``MISSING`` node) surfaces as
320
+ ``FormatPluginContractError(error_code=FORMAT_CONTENT_PARSE_FAILED)``,
321
+ raised by the import map itself ({p104}); a partial tree is never
322
+ returned.
323
+ """
324
+
325
+ source_bytes = _coerce_source_bytes(source)
326
+ root = _parse_bytes(source_bytes)
327
+ result = self.import_to_common(root, options, fragment=False)
328
+ if not isinstance(result, Node):
329
+ raise _contract_error(
330
+ f"parsing a full BSL document must yield a Node, got {type(result).__name__}"
331
+ )
332
+ result = _widen_root_span(result, source_bytes, root)
333
+ return Document(root=result, source_format_id=FORMAT_ID)
334
+
335
+ def import_external_tree(
336
+ self, external_tree: Any, options: Optional[Mapping[str, Any]] = None
337
+ ) -> Union[Node, Document]:
338
+ """Translate an already-parsed external tree-sitter-bsl tree into
339
+ common nodes, reusing :meth:`import_to_common` -- the single shared
340
+ input translator ({p056}, {p057})."""
341
+
342
+ return self.import_to_common(external_tree, options, fragment=False)
343
+
344
+ def parse_fragment(
345
+ self,
346
+ fragment: Union[str, bytes],
347
+ options: Optional[Mapping[str, Any]] = None,
348
+ *,
349
+ source_format_id: Optional[str] = None,
350
+ ) -> Node:
351
+ """Parse a local BSL fragment through the same pinned tree-sitter-bsl
352
+ backend and reuse ``import_to_common``, this time with
353
+ ``fragment=True`` so a damaged tree is classified as
354
+ ``FORMAT_FRAGMENT_PARSE_FAILED`` rather than
355
+ ``FORMAT_CONTENT_PARSE_FAILED`` ({p104}). tree-sitter-bsl has no
356
+ separate statement/expression entry point the way LibCST does, so a
357
+ fragment is parsed exactly like a document and only the error-code
358
+ classification differs; a valid fragment always yields a ``Node``,
359
+ never the plain-fallback-string case the contract otherwise permits.
360
+ """
361
+
362
+ source_bytes = _coerce_source_bytes(fragment)
363
+ root = _parse_bytes(source_bytes)
364
+ result = self.import_to_common(root, options, fragment=True)
365
+ if not isinstance(result, Node):
366
+ raise _contract_error(
367
+ f"parsing a BSL fragment must yield a Node, got {type(result).__name__}"
368
+ )
369
+ return result
370
+
371
+ def import_to_common(
372
+ self,
373
+ external_representation: Any,
374
+ options: Optional[Mapping[str, Any]] = None,
375
+ *,
376
+ fragment: bool = False,
377
+ ) -> Node:
378
+ """The single input translator shared by ``parse_document``,
379
+ ``import_external_tree``, and ``parse_fragment`` -- delegates
380
+ entirely to the merged :class:`BSLImportMap`, including its own
381
+ ``has_error`` -> ``FORMAT_CONTENT_PARSE_FAILED``/
382
+ ``FORMAT_FRAGMENT_PARSE_FAILED`` classification ({p104}). The extra
383
+ keyword-only ``fragment`` flag is this plugin's own pass-through of
384
+ that same parameter on ``BSLImportMap.import_to_common``; the
385
+ abstract ``FormatPluginContract.import_to_common`` this satisfies by
386
+ name does not itself declare it, exactly as ``parse_document`` above
387
+ adds ``source_format_id`` beyond its abstract signature."""
388
+
389
+ return self._import_map.import_to_common(
390
+ external_representation, options, fragment=fragment
391
+ )
392
+
393
+ def export_from_common(
394
+ self, nodes: Union[Node, Document], options: Optional[Mapping[str, Any]] = None
395
+ ) -> BSLGenerationTree:
396
+ """Translate common-model nodes into this plugin's own
397
+ generation-ready representation -- delegates entirely to the merged
398
+ :class:`BSLGenerator` ({p105})."""
399
+
400
+ return self._generator.export_from_common(nodes, options)
401
+
402
+ def generate_output(
403
+ self,
404
+ target: Union[Node, Document, BSLGenerationTree],
405
+ options: Optional[Mapping[str, Any]] = None,
406
+ ) -> bytes:
407
+ """Produce final BSL output bytes for ``target`` -- delegates
408
+ entirely to the merged :class:`BSLGenerator`, whose
409
+ ``generate_output`` already runs ``export_from_common`` internally
410
+ when given a bare ``Node``/``Document`` ({p105})."""
411
+
412
+ return self._generator.generate_output(target, options)
413
+
414
+ def semantic_role_mapping(self) -> SemanticRoleMapping:
415
+ """The declarative, context-free kind -> role table: procedures and
416
+ functions map to function, the module node maps to module; method
417
+ and class have no BSL construct and so yield no entry. See
418
+ :func:`bsl_semantic_role_map`, the module-level function this
419
+ delegates to."""
420
+
421
+ return _ROLE_MAP
422
+
423
+ # -- FormatBoundary ---------------------------------------------------------
424
+
425
+ def render_document(self, document: Document) -> bytes:
426
+ """CORE-facing counterpart of ``parse_document``: renders a full
427
+ ``Document`` back to BSL bytes via ``generate_output``."""
428
+
429
+ result = self.generate_output(document, {})
430
+ if not isinstance(result, bytes):
431
+ raise _contract_error(
432
+ f"render_document expected bytes, got {type(result).__name__}"
433
+ )
434
+ return result
435
+
436
+ def render_fragment(self, node: Node) -> str:
437
+ """CORE-facing counterpart of ``parse_fragment``: renders a single
438
+ fragment ``Node`` back to BSL source text via ``generate_output``,
439
+ decoding the generator's bytes as UTF-8."""
440
+
441
+ result = self.generate_output(node, {})
442
+ if not isinstance(result, bytes):
443
+ raise _contract_error(
444
+ f"render_fragment expected bytes, got {type(result).__name__}"
445
+ )
446
+ return result.decode("utf-8")
447
+
448
+
449
+ # Registration data: a ready-made, stateless singleton a sibling registry
450
+ # step (out of scope here, per {p055}/{p059}/{p101}) can import and register
451
+ # under ``format_id="bsl"`` without needing to know how to construct one.
452
+ BSL_FORMAT_PLUGIN = BSLFormatPlugin()