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,481 @@
1
+ """Common-model-to-BSL export and output generation for the BSL translator
2
+ (concept C-015).
3
+
4
+ Scope (narrowed to the EXPORT/GENERATE direction only, per this step's
5
+ brief): tree-sitter-bsl provides no reverse generator, so this module is
6
+ where the BSL plugin owns both its own generation-ready representation and
7
+ the rules that render it into final bytes ({p105}). It is the sibling and
8
+ mirror image of the already-merged ``import_map.py``: every construct that
9
+ module singles out for special treatment (variable_declaration, annotation,
10
+ the by-value parameter modifier) gets a matching generation rule here,
11
+ selected from ``dialects.py`` so no keyword spelling is hard-coded.
12
+
13
+ Generation strategy:
14
+
15
+ * A generic node (kind ``"bsl:<tree-sitter node type>"``) carries, in its
16
+ own ``content`` field, the exact original source text of its whole
17
+ subtree ({p047}). A leaf (no children) is rendered by re-emitting
18
+ ``content`` -- reusing unchanged bytes per {p105} with no live buffer
19
+ needed. When ``options["buffer"]``/``options["source"]`` *is* supplied,
20
+ its bytes are preferred over ``content`` for any node still carrying a
21
+ valid ``buffer_range``, per {p105}'s literal wording.
22
+ * A generic node *with* children is rendered by gap-stitching: each child
23
+ renders recursively (so a change anywhere below propagates upward,
24
+ however deeply nested), and the byte runs *between* children
25
+ (punctuation, un-mapped keywords, whitespace) are copied from the
26
+ parent's own captured span -- so an edited descendant surfaces correctly
27
+ while the rest of an unchanged document is still reproduced by straight
28
+ byte copying.
29
+ * :class:`~tree_engine.core.node_types.VariableDeclarationNode`,
30
+ :class:`~tree_engine.core.node_types.AnnotationNode` (when its
31
+ ``annotation_kind`` was recognized on import) and the by-value parameter
32
+ modifier are rendered from their own stored fields via
33
+ ``dialects.keyword_for_target_dialect``/``dialects.get_annotation_form``,
34
+ so a changed or freshly constructed node still renders correct BSL
35
+ syntax in the document's own dialect ({p105}, {p115}). The written
36
+ keyword forms are single-space-separated, matching tree-sitter-bsl's own
37
+ grammar exactly (verified against real parses), so this same rule also
38
+ reproduces an untouched node's original bytes exactly -- no separate
39
+ "did this change" detection is needed.
40
+ * :class:`~tree_engine.core.node_types.PreprocessorDirectiveNode` has no
41
+ BSL-specific child interpretation to invert ({p043}), so it is always
42
+ reproduced from its own captured ``content`` verbatim.
43
+ * The document's own dialect is auto-detected by scanning for the first
44
+ recognized keyword token or annotation prefix via ``dialects``' own
45
+ lookup tables, and can be overridden with ``options["dialect"]``; every
46
+ synthesized keyword uses this one resolved dialect, honoured
47
+ consistently throughout the output ({p047}, {p105}).
48
+ * A node kind this plugin does not own (not ``"bsl:"``- or
49
+ ``"core:"``-prefixed) raises
50
+ :class:`~tree_engine.plugins.contract.UnsupportedTranslationError`
51
+ (``ErrorCode.UNSUPPORTED_TRANSLATION``), naming the offending kind.
52
+
53
+ ``export_from_common`` returns a small immutable :class:`BSLGenerationTree`
54
+ -- the generation-ready representation ({p105}) -- and ``generate_output``
55
+ renders it, or (running ``export_from_common`` internally) a bare
56
+ common-model ``Node``/``Document`` directly, per
57
+ ``FormatPluginContract.generate_output``'s own documented allowance.
58
+
59
+ Source-of-truth requirement labels honored here: {p043}, {p044}, {p047},
60
+ {p105}, {p115}.
61
+ """
62
+
63
+ from __future__ import annotations
64
+
65
+ from dataclasses import dataclass
66
+ from typing import Any, Mapping, Optional, Tuple, Union
67
+
68
+ from tree_engine.core.node_types import (
69
+ AnnotationNode,
70
+ PreprocessorDirectiveNode,
71
+ VariableDeclarationNode,
72
+ VariableDeclaratorNode,
73
+ )
74
+ from tree_engine.core.nodes import Document, Node, walk
75
+ from tree_engine.plugins.bsl import dialects
76
+ from tree_engine.plugins.contract import FormatPluginContractError, UnsupportedTranslationError
77
+
78
+ __all__ = [
79
+ "FORMAT_ID",
80
+ "BSLGenerationTree",
81
+ "BSLGenerator",
82
+ "export_from_common",
83
+ "generate_output",
84
+ ]
85
+
86
+ FORMAT_ID = "bsl"
87
+
88
+ _GENERIC_PREFIX = "bsl:"
89
+ _PARAMETER_KIND = f"{_GENERIC_PREFIX}parameter"
90
+ _VAR_DECL_KIND = VariableDeclarationNode._KIND
91
+ _VAR_DECLARATOR_KIND = VariableDeclaratorNode._KIND
92
+ _ANNOTATION_KIND = AnnotationNode._KIND
93
+ _PREPROC_KIND = PreprocessorDirectiveNode._KIND
94
+
95
+
96
+ @dataclass(frozen=True)
97
+ class BSLGenerationTree:
98
+ """The BSL plugin's own generation-ready representation ({p105}):
99
+ the common-model subtree to render, the single keyword dialect every
100
+ synthesized token in the render must use, and the optional original
101
+ source bytes that unchanged spans are preferred to be copied from."""
102
+
103
+ root: Node
104
+ dialect: str
105
+ source_bytes: Optional[bytes] = None
106
+
107
+
108
+ def _contract_error(message: str) -> FormatPluginContractError:
109
+ return FormatPluginContractError(plugin_id=FORMAT_ID, message=message)
110
+
111
+
112
+ def _unsupported(node_kind: str) -> UnsupportedTranslationError:
113
+ return UnsupportedTranslationError(
114
+ node_type=node_kind, format_id=FORMAT_ID,
115
+ message=f"BSL generator has no rendering rule for node kind {node_kind!r}",
116
+ )
117
+
118
+
119
+ def _resolve_root(common_tree: Union[Node, Document]) -> Node:
120
+ if isinstance(common_tree, Document):
121
+ return common_tree.root
122
+ if isinstance(common_tree, Node):
123
+ return common_tree
124
+ raise _contract_error(f"expected a common-model Node or Document, got {type(common_tree).__name__}")
125
+
126
+
127
+ def _resolve_source_bytes(options: Mapping[str, Any]) -> Optional[bytes]:
128
+ source = options.get("source")
129
+ if isinstance(source, (bytes, bytearray)):
130
+ return bytes(source)
131
+ return None
132
+
133
+
134
+ def _detect_dialect(root: Node) -> str:
135
+ """Scan ``root``'s subtree for the first recognized keyword token or
136
+ annotation prefix and return the dialect it belongs to, defaulting to
137
+ :data:`dialects.RUSSIAN` when nothing recognizable is found (e.g. an
138
+ empty document)."""
139
+
140
+ for node in walk(root):
141
+ content = node.fields.get("content")
142
+ if not isinstance(content, str) or not content.strip():
143
+ continue
144
+ token = content.strip()
145
+ kind = str(node.kind)
146
+ # A variable declaration swallows its own VAR/EXPORT keyword tokens
147
+ # into fields, so the scan must read the raw source fragment too --
148
+ # otherwise an English document silently regenerates in Russian.
149
+ first_word = token.split(",")[0].split()[0] if token.split() else ""
150
+ if first_word:
151
+ for dialect in (dialects.RUSSIAN, dialects.ENGLISH):
152
+ if dialects.get_canonical_keyword(first_word, dialect) is not None:
153
+ return dialect
154
+ if kind.endswith("_KEYWORD"):
155
+ if dialects.get_canonical_keyword(token, dialects.RUSSIAN) is not None:
156
+ return dialects.RUSSIAN
157
+ if dialects.get_canonical_keyword(token, dialects.ENGLISH) is not None:
158
+ return dialects.ENGLISH
159
+ elif kind == _ANNOTATION_KIND:
160
+ if dialects.is_annotation_prefix(token, dialects.RUSSIAN) is not None:
161
+ return dialects.RUSSIAN
162
+ if dialects.is_annotation_prefix(token, dialects.ENGLISH) is not None:
163
+ return dialects.ENGLISH
164
+ return dialects.RUSSIAN
165
+
166
+
167
+ def _resolve_dialect(root: Node, options: Mapping[str, Any]) -> str:
168
+ override = options.get("dialect")
169
+ if override is not None:
170
+ return dialects.normalize_dialect(override)
171
+ return _detect_dialect(root)
172
+
173
+
174
+ def export_from_common(
175
+ common_tree: Union[Node, Document], options: Optional[Mapping[str, Any]] = None
176
+ ) -> BSLGenerationTree:
177
+ """Translate a common-model ``Document``/``Node`` into this plugin's
178
+ own generation-ready representation ({p105}): resolves which subtree to
179
+ render, the one keyword dialect to honour throughout, and the original
180
+ bytes (if source was supplied via ``options``) unchanged spans are
181
+ preferred to be copied from.
182
+
183
+ ``options`` recognizes ``"dialect"`` (an explicit override, normalized
184
+ via :func:`dialects.normalize_dialect`) and ``"source"`` (raw ``bytes``);
185
+ both are optional.
186
+ """
187
+
188
+ resolved_options = options or {}
189
+ root = _resolve_root(common_tree)
190
+ dialect = _resolve_dialect(root, resolved_options)
191
+ source_bytes = _resolve_source_bytes(resolved_options)
192
+ return BSLGenerationTree(root=root, dialect=dialect, source_bytes=source_bytes)
193
+
194
+
195
+ def _leaf_bytes(node: Node, source_bytes: Optional[bytes]) -> bytes:
196
+ """The exact bytes of one node with no rule-based rendering of its
197
+ own: preferably a slice of a live buffer's bytes at the node's own
198
+ ``buffer_range`` ({p105}), falling back to the node's own captured
199
+ ``content`` field (itself an exact original-text capture at import
200
+ time, per ``import_map.py``)."""
201
+
202
+ content = node.fields.get("content", "")
203
+ content_bytes = (
204
+ content if isinstance(content, bytes) else str(content).encode("utf-8")
205
+ )
206
+ if source_bytes is not None and node.buffer_range is not None:
207
+ start, end = node.buffer_range
208
+ if 0 <= start <= end <= len(source_bytes):
209
+ source_slice = source_bytes[start:end]
210
+ # Fragment nodes retain tree-sitter byte spans relative to the
211
+ # fragment that created them. After a structural edit those
212
+ # offsets can still be in range of the document's original
213
+ # source, but designate unrelated bytes (and may begin in the
214
+ # middle of a UTF-8 character). Only reuse the shared source
215
+ # buffer when it agrees with this node's imported raw content;
216
+ # otherwise the node's own captured fragment text is authoritative.
217
+ if not content_bytes or source_slice == content_bytes:
218
+ return source_slice
219
+ return content_bytes
220
+
221
+
222
+ def _stitch(
223
+ node: Node, children: Tuple[Node, ...], start_abs: int, dialect: str, source_bytes: Optional[bytes]
224
+ ) -> bytes:
225
+ """Render ``children`` (a node's own children, or a trailing slice of
226
+ them) recursively, filling the byte gaps between consecutive children
227
+ -- punctuation, un-mapped keywords, whitespace -- from ``node``'s own
228
+ captured span, starting at the absolute byte offset ``start_abs``.
229
+ A changed or newly rendered child's bytes are substituted in place of
230
+ whatever the parent's own captured span held there, so a change at any
231
+ depth surfaces correctly in the stitched result."""
232
+
233
+ own_bytes = _leaf_bytes(node, source_bytes)
234
+ base = node.buffer_range[0] if node.buffer_range is not None else 0
235
+ cursor = max(0, start_abs - base)
236
+ pieces = []
237
+ for child in children:
238
+ child_bytes = _render(child, dialect, source_bytes)
239
+ child_range = child.buffer_range
240
+ if child_range is not None and node.buffer_range is not None:
241
+ rel_start = child_range[0] - base
242
+ rel_end = child_range[1] - base
243
+ if 0 <= rel_start <= len(own_bytes) and rel_start >= cursor:
244
+ pieces.append(own_bytes[cursor:rel_start])
245
+ pieces.append(child_bytes)
246
+ cursor = max(cursor, min(rel_end, len(own_bytes)))
247
+ continue
248
+ pieces.append(child_bytes)
249
+ pieces.append(own_bytes[cursor:])
250
+ return b"".join(pieces)
251
+
252
+
253
+ def _render_generic(node: Node, dialect: str, source_bytes: Optional[bytes]) -> bytes:
254
+ if not node.children or node.buffer_range is None:
255
+ return _leaf_bytes(node, source_bytes)
256
+ return _stitch(node, node.children, node.buffer_range[0], dialect, source_bytes)
257
+
258
+
259
+ def _render_var_decl(node: Node, dialect: str) -> bytes:
260
+ """Render a :class:`VariableDeclarationNode` from its own
261
+ ``declarators``/``separators``/``export`` fields ({iblr}/{p044}): exact
262
+ original inter-declarator separators reused verbatim.
263
+
264
+ Keyword text (bug cd41e1fc): BSL keywords are case-insensitive, and
265
+ ``import_map.py`` never rewrites a document's own written case --
266
+ rendering must not either. ``var_keyword_text``/``export_keyword_text``
267
+ (set on import, absent on a node built fresh with the plain wrapper
268
+ constructor) hold the ORIGINAL written token text; they are reused
269
+ verbatim when present. Only a keyword with no captured original text --
270
+ a freshly constructed node, or ``export`` flipped on where the source
271
+ had no ``EXPORT_KEYWORD`` to capture -- falls back to synthesizing the
272
+ canonical spelling for ``dialect`` via ``dialects``.
273
+
274
+ Keyword-adjacent whitespace (bug cd41e1fc round 3): the gap between
275
+ ``VAR_KEYWORD`` and the first declarator, and between the last
276
+ declarator and ``EXPORT_KEYWORD``, is likewise reused verbatim from the
277
+ captured ``leading_gap_text``/``export_gap_text`` fields when present
278
+ -- a fixed single space is only ever synthesized as the fallback for a
279
+ freshly constructed node with no captured gap to reuse."""
280
+
281
+ wrapper = VariableDeclarationNode.from_node(node)
282
+ var_keyword_text = node.fields.get("var_keyword_text")
283
+ var_keyword = (
284
+ str(var_keyword_text)
285
+ if var_keyword_text
286
+ else dialects.keyword_for_target_dialect(dialects.VAR, dialect)
287
+ )
288
+ leading_gap = node.fields.get("leading_gap_text")
289
+ parts = [var_keyword, str(leading_gap) if leading_gap is not None else " "]
290
+ declarators = wrapper.declarators
291
+ separators = wrapper.separators
292
+ for index, declarator in enumerate(declarators):
293
+ if index > 0 and index - 1 < len(separators):
294
+ parts.append(separators[index - 1])
295
+ parts.append(declarator.name)
296
+ if wrapper.export:
297
+ export_keyword_text = node.fields.get("export_keyword_text")
298
+ export_keyword = (
299
+ str(export_keyword_text)
300
+ if export_keyword_text
301
+ else dialects.keyword_for_target_dialect(dialects.EXPORT, dialect)
302
+ )
303
+ export_gap = node.fields.get("export_gap_text")
304
+ parts.append(str(export_gap) if export_gap is not None else " ")
305
+ parts.append(export_keyword)
306
+ trailing_gap = node.fields.get("trailing_gap_text")
307
+ parts.append(str(trailing_gap) if trailing_gap is not None else "")
308
+ parts.append(";")
309
+ return "".join(parts).encode("utf-8")
310
+
311
+
312
+ def _render_annotation(node: Node, dialect: str) -> bytes:
313
+ """Render an :class:`AnnotationNode`.
314
+
315
+ Keyword text (bug cd41e1fc): a document's own written annotation case
316
+ (e.g. ``&наСервере``) must never be rewritten to the dialect table's
317
+ canonical spelling (``&НаСервере``) -- ``annotation_kind`` is derived
318
+ case-insensitively (per :func:`dialects.is_annotation_prefix`) purely
319
+ for future attribute use, never to normalize the rendered text. Every
320
+ imported node -- recognized or not -- carries its own captured
321
+ ``content`` and is reproduced from it verbatim. Only a node built fresh
322
+ with the plain wrapper constructor (no captured ``content``, e.g. a
323
+ newly synthesized ``&AtServer`` argument-bearing annotation) falls back
324
+ to synthesizing the canonical prefix plus its parenthesized, separator-
325
+ joined argument list for ``dialect`` via
326
+ :func:`dialects.get_annotation_form` ({an01}, {p047})."""
327
+
328
+ content = node.fields.get("content")
329
+ if content:
330
+ return str(content).encode("utf-8")
331
+ kind = node.fields.get("annotation_kind")
332
+ if kind is None:
333
+ return b""
334
+ prefix = dialects.get_annotation_form(kind, dialect).encode("utf-8")
335
+ wrapper = AnnotationNode.from_node(node)
336
+ arguments = wrapper.arguments
337
+ if not arguments:
338
+ return prefix
339
+ separators = wrapper.argument_separators
340
+ rendered = [_render(argument, dialect, None) for argument in arguments]
341
+ body = [rendered[0]]
342
+ for index in range(1, len(rendered)):
343
+ sep = separators[index - 1].encode("utf-8") if index - 1 < len(separators) else b""
344
+ body.append(sep)
345
+ body.append(rendered[index])
346
+ return prefix + b"(" + b"".join(body) + b")"
347
+
348
+
349
+ def _has_leading_by_value_modifier(text: str) -> bool:
350
+ """True when ``text`` opens with the by-value modifier token, in
351
+ either dialect and any case (per {p115}). Used to tell an already-
352
+ written modifier (case preserved verbatim, bug cd41e1fc) apart from a
353
+ freshly inserted one (synthesized in ``dialect``'s canonical spelling,
354
+ per the existing insertion contract)."""
355
+
356
+ left = text.lstrip(" \t")
357
+ for sep in (" ", "\t"):
358
+ token, found, _ = left.partition(sep)
359
+ if found and dialects.is_by_value_modifier(token):
360
+ return True
361
+ return False
362
+
363
+
364
+ def _strip_leading_modifier(text: str) -> str:
365
+ """When ``text`` opens with the by-value modifier token (either
366
+ dialect, per {p115}), return the remainder with that token and its
367
+ following run of spaces/tabs removed; otherwise return ``text``
368
+ unchanged. Used only on the ``by_value=False`` (removed/absent
369
+ modifier) path."""
370
+
371
+ left = text.lstrip(" \t")
372
+ for sep in (" ", "\t"):
373
+ token, found, remainder = left.partition(sep)
374
+ if found and dialects.is_by_value_modifier(token):
375
+ return remainder.lstrip(" \t")
376
+ return text
377
+
378
+
379
+ def _render_parameter(node: Node, dialect: str, source_bytes: Optional[bytes]) -> bytes:
380
+ """Render a ``bsl:parameter`` node: reconstruct its full text
381
+ generically (so a nested change still surfaces).
382
+
383
+ Keyword text (bug cd41e1fc): when ``by_value`` is true AND the node's
384
+ own generic text already opens with a by-value modifier token (any
385
+ case, either dialect -- i.e. this parameter is unmodified from
386
+ import), that text is returned completely unchanged, preserving the
387
+ document's own written case exactly. Only a genuinely NEW modifier --
388
+ ``by_value=True`` with no existing leading modifier token, the
389
+ insertion contract already covers -- is synthesized in ``dialect``'s
390
+ canonical spelling ({p115}). No attribute means no modifier."""
391
+
392
+ rendered = _render_generic(node, dialect, source_bytes)
393
+ text = rendered.decode("utf-8")
394
+ if bool(node.fields.get(dialects.BY_VALUE, False)):
395
+ if _has_leading_by_value_modifier(text):
396
+ return text.encode("utf-8")
397
+ keyword = dialects.keyword_for_target_dialect(dialects.BY_VALUE, dialect)
398
+ return f"{keyword} {text}".encode("utf-8")
399
+ rest = _strip_leading_modifier(text)
400
+ return rest.encode("utf-8")
401
+
402
+
403
+ def _render(node: Node, dialect: str, source_bytes: Optional[bytes]) -> bytes:
404
+ """Dispatch one common-model node to its rendering rule and return its
405
+ exact BSL bytes, in ``dialect``."""
406
+
407
+ kind = node.kind
408
+ if kind == _VAR_DECL_KIND:
409
+ return _render_var_decl(node, dialect)
410
+ if kind == _VAR_DECLARATOR_KIND:
411
+ return str(node.fields.get("name", "")).encode("utf-8")
412
+ if kind == _ANNOTATION_KIND:
413
+ return _render_annotation(node, dialect)
414
+ if kind == _PREPROC_KIND:
415
+ # A paired directive (block) or a conditional branch holds its body as children: stitch them.
416
+ return _render_generic(node, dialect, source_bytes)
417
+ if kind == _PARAMETER_KIND:
418
+ return _render_parameter(node, dialect, source_bytes)
419
+ if not str(kind).startswith(_GENERIC_PREFIX):
420
+ raise _unsupported(str(kind))
421
+ return _render_generic(node, dialect, source_bytes)
422
+
423
+
424
+ def generate_output(
425
+ target: Union[BSLGenerationTree, Node, Document], options: Optional[Mapping[str, Any]] = None
426
+ ) -> bytes:
427
+ """Render ``target`` into final BSL source bytes.
428
+
429
+ ``target`` is either an already-built :class:`BSLGenerationTree` (the
430
+ normal two-step path, via :func:`export_from_common`) or a bare
431
+ common-model ``Node``/``Document``, in which case
432
+ :func:`export_from_common` is run internally first, per
433
+ ``FormatPluginContract.generate_output``'s own documented allowance to
434
+ combine the stages behind one call.
435
+
436
+ Raises :class:`~tree_engine.plugins.contract.UnsupportedTranslationError`
437
+ for a node kind this plugin does not own, and
438
+ :class:`~tree_engine.plugins.contract.FormatPluginContractError` for any
439
+ other kind of ``target``.
440
+ """
441
+
442
+ resolved_options = options or {}
443
+ if isinstance(target, BSLGenerationTree):
444
+ representation = target
445
+ elif isinstance(target, (Node, Document)):
446
+ representation = export_from_common(target, resolved_options)
447
+ else:
448
+ raise _contract_error(
449
+ f"cannot generate BSL output for {type(target).__name__}; expected a "
450
+ "BSLGenerationTree, Node, or Document"
451
+ )
452
+ return _render(representation.root, representation.dialect, representation.source_bytes)
453
+
454
+
455
+ class BSLGenerator:
456
+ """Export (common model -> generation-ready representation) and
457
+ generate (representation -> bytes) stages of the BSL translator.
458
+
459
+ Supplies the export half of the bidirectional translator described by
460
+ ``tree_engine.plugins.contract.FormatPluginContract`` ({p056}, {p057});
461
+ the import stage is delivered by the sibling, already-merged
462
+ ``BSLImportMap``, and the remaining contract surface (``metadata``,
463
+ ``parse_document``, ...) is composed later.
464
+ """
465
+
466
+ def export_from_common(
467
+ self, common_tree: Union[Node, Document], options: Optional[Mapping[str, Any]] = None
468
+ ) -> BSLGenerationTree:
469
+ """Translate a common-model ``Document``/``Node`` into this
470
+ plugin's own generation-ready representation; see the module-level
471
+ :func:`export_from_common` for the full contract."""
472
+
473
+ return export_from_common(common_tree, options)
474
+
475
+ def generate_output(
476
+ self, target: Union[BSLGenerationTree, Node, Document], options: Optional[Mapping[str, Any]] = None
477
+ ) -> bytes:
478
+ """Render ``target`` into final BSL source bytes; see the
479
+ module-level :func:`generate_output` for the full contract."""
480
+
481
+ return generate_output(target, options)