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,995 @@
1
+ """tree-sitter-bsl-to-common-model import pipeline for the BSL translator
2
+ (concept C-015).
3
+
4
+ Scope (narrowed to the IMPORT direction only, per this step's brief): this
5
+ module converts an already-parsed tree-sitter-bsl 0.1.6 parse tree node
6
+ into a common-model :class:`~tree_engine.core.nodes.Node`
7
+ (concept C-002), mapping the constructs {p047}/{p044}/{p043}/{an01}/{iblr}/
8
+ {p115} single out for explicit treatment, and preserving everything else
9
+ losslessly as an extensible node. The EXPORT direction and the
10
+ ``FormatPluginContract``/``FormatBoundary`` composition are sibling steps'
11
+ concern and are not implemented here.
12
+
13
+ Mapping rules, per the governing HRS fragments:
14
+
15
+ * ``var_statement``/``var_definition`` (a tree-sitter-bsl grammar
16
+ distinction between an in-procedure and a module-level declaration,
17
+ collapsed here into one code path) -> :class:`VariableDeclarationNode`
18
+ with ordered :class:`VariableDeclaratorNode` children, one per declared
19
+ identifier, separated by the exact original inter-declarator source
20
+ bytes ({iblr}). A trailing ``EXPORT_KEYWORD`` sets the declaration's
21
+ ``export`` field ({p044}, {p047}); export is not propagated onto
22
+ individual declarators, mirroring the grammar's own placement of the
23
+ keyword at the statement level.
24
+ * a ``preprocessor`` node wrapping a nested ``annotation`` node (the
25
+ grammar's own representation of ``&НаСервере``/``&AtServer``-style
26
+ constructs) -> :class:`AnnotationNode`, keyed to its own inner byte
27
+ range, never combined with :class:`PreprocessorDirectiveNode` ({an01}).
28
+ Any other ``preprocessor`` node (``#Если``/``#If`` and friends) ->
29
+ :class:`PreprocessorDirectiveNode`, kept flat (no BSL-specific child
30
+ interpretation), per {p043}.
31
+ * a ``parameter`` node whose own children contain the by-value modifier
32
+ token (``Знач``/``Val``, detected via
33
+ :func:`tree_engine.plugins.bsl.dialects.is_by_value_modifier` rather than
34
+ by tree-sitter node-kind name) gets a ``by_value`` field set ``True`` on
35
+ its mapped node; absent otherwise ({p115}).
36
+ * everything else that parsed without error -- ``procedure_definition``,
37
+ ``function_definition``, expressions, statements, individual keyword and
38
+ punctuation tokens, and so on -- becomes a plain extensible
39
+ :class:`~tree_engine.core.nodes.Node` of kind ``"bsl:<tree-sitter node
40
+ type>"`` (mirroring the ``"python:<LibCST class name>"`` convention
41
+ already used by the Python translator's import map), carrying its own
42
+ raw byte span and content, with no synthetic wrapper type invented for
43
+ it, so a future plugin revision may interpret or upgrade it ({p047}).
44
+ Its children are converted the same way, recursively, so a mapped
45
+ construct nested at any depth (e.g. a ``var_statement`` inside a
46
+ procedure body) is still recognized by the same dispatch.
47
+
48
+ Both keyword dialects are handled by this single code path: tree-sitter-
49
+ bsl's own grammar already unifies ``Процедура``/``Procedure``,
50
+ ``Перем``/``Var``, ``Экспорт``/``Export`` and so on under one node type per
51
+ construct, so no dialect branch is needed for the constructs above; the
52
+ one dialect-sensitive decision left to this module -- the by-value
53
+ modifier and the annotation-prefix canonical label -- is delegated to
54
+ ``dialects.py`` rather than re-encoded here. The original written keyword
55
+ form is preserved verbatim in every mapped node's ``content`` field (never
56
+ canonicalized), so round-trip generation later restores the document's own
57
+ dialect exactly.
58
+
59
+ Per {p104}, detecting ``has_error``/``ERROR``/missing nodes and choosing
60
+ between ``FORMAT_CONTENT_PARSE_FAILED`` and ``FORMAT_FRAGMENT_PARSE_FAILED``
61
+ is primarily the responsibility of the calling ``parse_document``/
62
+ ``parse_fragment`` logic (not yet merged); this module's own walk only maps
63
+ already-valid trees. As a defense-in-depth backstop against ever
64
+ synthesizing a partial common-model tree from damaged input, ``import_to_
65
+ common`` still refuses upfront -- via a loud
66
+ :class:`~tree_engine.plugins.contract.FormatPluginContractError` carrying
67
+ the appropriate one of those two codes -- to walk a tree-sitter node that
68
+ itself reports ``has_error`` (tree-sitter propagates this up through every
69
+ ancestor of an ``ERROR`` or ``MISSING`` descendant, so a single check on
70
+ the node handed to this function is sufficient).
71
+
72
+ No tree-sitter node kinds leak into the core: every ``Node`` this module
73
+ returns carries only an opaque, plugin-namespaced ``NodeKind`` string, a
74
+ plain ``fields`` mapping, and a ``children`` tuple of further ``Node``
75
+ values -- the shapes ``tree_engine.core.nodes.make_node`` already
76
+ validates. No tree-sitter object is retained or returned once
77
+ ``import_to_common`` returns.
78
+
79
+ Node identity: every node this module returns carries a fresh UUID4
80
+ ``node_id`` ({p013}) and a positive integer ``short_id`` ({p097}), assigned
81
+ at the single :func:`_convert` dispatch point every mapped node passes
82
+ through -- the root, every generic node, and the wrapper-typed constructs
83
+ alike -- so an imported BSL document is addressable and queryable without a
84
+ second pass, exactly as the Python translator's import map already does.
85
+
86
+ Source-of-truth requirement labels honored here: {p013}, {p043}, {an01},
87
+ {p044}, {p046}, {p047}, {p097}, {p104}, {iblr}, {p115}.
88
+ """
89
+
90
+ from __future__ import annotations
91
+
92
+ import dataclasses
93
+ import json
94
+ from typing import Any, Dict, List, Mapping, Optional, TYPE_CHECKING, Tuple
95
+
96
+ from tree_engine.core.identity import generate_node_id
97
+ from tree_engine.core.node_types import (
98
+ AnnotationNode,
99
+ PreprocessorDirectiveNode,
100
+ VariableDeclarationNode,
101
+ VariableDeclaratorNode,
102
+ )
103
+
104
+ # The wrapper types imported above already stamp node_id/short_id on the
105
+ # nodes they build, drawing every short id from this one monotonic counter in
106
+ # ``node_types``. The generic mapping below deliberately reuses that same
107
+ # counter object rather than opening a second sequence of its own: a single
108
+ # imported BSL document mixes wrapper-built nodes (variable declarations,
109
+ # annotations, preprocessor directives) with generic ones, and two
110
+ # independent counters would hand out colliding short ids inside it.
111
+ from tree_engine.core.node_types import _short_id_counter as _SHORT_ID_COUNTER
112
+ from tree_engine.core.nodes import Node, make_node
113
+ from tree_engine.errors import ErrorCode
114
+ from tree_engine.plugins.bsl import blocks as _blocks
115
+ from tree_engine.plugins.bsl import dialects
116
+ from tree_engine.plugins.contract import FormatPluginContractError
117
+
118
+ if TYPE_CHECKING:
119
+ from tree_sitter import Node as TSNode
120
+
121
+ __all__ = [
122
+ "FORMAT_ID",
123
+ "BSLImportMap",
124
+ "import_to_common",
125
+ ]
126
+
127
+ FORMAT_ID = "bsl"
128
+
129
+ _KIND_PREFIX = "bsl:"
130
+ _VAR_DECLARATION_TYPES = ("var_statement", "var_definition")
131
+ _IDENTIFIER_TYPE = "identifier"
132
+ _VARIABLE_SPEC_TYPE = "variable_spec"
133
+ _VAR_KEYWORD_TYPE = "VAR_KEYWORD"
134
+ _EXPORT_KEYWORD_TYPE = "EXPORT_KEYWORD"
135
+ _PREPROCESSOR_TYPE = "preprocessor"
136
+ _ANNOTATION_TYPE = "annotation"
137
+ _PARAMETER_TYPE = "parameter"
138
+ _METHOD_TYPES = ("procedure_definition", "function_definition")
139
+ _AVAILABILITY_BY_ANNOTATION = {
140
+ dialects.AT_SERVER: "Server",
141
+ dialects.AT_CLIENT: "Client",
142
+ dialects.AT_SERVER_NO_CONTEXT: "ServerNoContext",
143
+ dialects.AT_CLIENT_AT_SERVER_NO_CONTEXT: "ClientServerNoContext",
144
+ }
145
+
146
+
147
+ def _contract_error(message: str, *, code: ErrorCode) -> FormatPluginContractError:
148
+ return FormatPluginContractError(plugin_id=FORMAT_ID, error_code=code, message=message)
149
+
150
+
151
+ def _text(ts_node: "TSNode") -> str:
152
+ """The exact original source text of ``ts_node``, decoded as UTF-8."""
153
+
154
+ raw = ts_node.text
155
+ return raw.decode("utf-8") if raw is not None else ""
156
+
157
+
158
+ def _slice(container: "TSNode", start_byte: int, end_byte: int) -> str:
159
+ """The exact original source text spanning ``[start_byte, end_byte)``,
160
+ sliced out of ``container``'s own text via relative byte offsets --
161
+ used for inter-declarator separators, which are not themselves a
162
+ tree-sitter node."""
163
+
164
+ raw = container.text
165
+ if raw is None:
166
+ return ""
167
+ base = container.start_byte
168
+ return raw[start_byte - base : end_byte - base].decode("utf-8")
169
+
170
+
171
+ class _StructureError(Exception):
172
+ """A paired directive or a language control structure is not well formed (D-CE.3).
173
+
174
+ ``offset`` is the byte offset of the offending line, when it is known."""
175
+
176
+ def __init__(self, message: str, offset: Optional[int] = None) -> None:
177
+ super().__init__(message)
178
+ self.offset = offset
179
+
180
+
181
+ def _convert_generic(ts_node: "TSNode") -> Node:
182
+ """Fallback mapping for any tree-sitter-bsl node with no explicit
183
+ construct-specific treatment: a flat, plugin-namespaced extensible
184
+ ``Node`` (no synthetic wrapper type) carrying its own raw byte span and
185
+ content, with every child converted the same way, recursively, so a
186
+ mapped construct nested at any depth is still recognized. Paired
187
+ preprocessor directives among the children are grouped into block nodes
188
+ (:func:`_convert_sequence`)."""
189
+
190
+ kind = f"{_KIND_PREFIX}{ts_node.type}"
191
+ children = tuple(_convert_sequence(list(ts_node.children), ts_node))
192
+ node = make_node(kind, fields={"content": _text(ts_node)}, children=children)
193
+ return dataclasses.replace(node, buffer_range=(ts_node.start_byte, ts_node.end_byte))
194
+
195
+
196
+ # -- blocks (D-CE.2, D-CF.1) --------------------------------------------------------------------
197
+
198
+ _TRIVIA_KINDS = ("bsl:line_comment", AnnotationNode._KIND)
199
+
200
+
201
+ def _range(node: Node) -> Tuple[int, int]:
202
+ assert node.buffer_range is not None
203
+ return node.buffer_range
204
+
205
+
206
+ def _block_node(kind: str, container: "TSNode", start: int, end: int,
207
+ fields: Dict[str, Any], children: List[Node]) -> Node:
208
+ """A block or branch node spanning ``[start, end)`` of ``container``'s source."""
209
+ all_fields: Dict[str, Any] = {"content": _slice(container, start, end)}
210
+ all_fields.update(fields)
211
+ node = make_node(kind, fields=all_fields, children=tuple(children))
212
+ node = dataclasses.replace(node, buffer_range=(start, end))
213
+ if kind == _blocks.PREPROC_KIND:
214
+ node = dataclasses.replace(node, extended_type="PreprocessorDirectiveNode")
215
+ return _with_identity(node)
216
+
217
+
218
+ def _body_end(head_end: int, items: List[Node]) -> int:
219
+ return _range(items[-1])[1] if items else head_end
220
+
221
+
222
+ def _group_directives(items: List[Node], container: "TSNode") -> List[Node]:
223
+ """Pair the flat ``#`` directive nodes of one sibling list into block nodes (stack scan).
224
+
225
+ A block whose opener and closer are not siblings of the same list, an opener without closer, a closer
226
+ without opener or a branch outside a conditional raises :class:`_StructureError`."""
227
+
228
+ def directive(item: Node) -> Optional[Tuple[str, str]]:
229
+ if item.kind != _blocks.PREPROC_KIND or _blocks.is_block(item):
230
+ return None
231
+ return _blocks.classify_directive(str(item.fields.get("content", "")))
232
+
233
+ if not any(directive(item) is not None for item in items):
234
+ return items
235
+ out: List[Node] = []
236
+ # frame: [block_kind, opener, branches]; branch: [branch_kind, head_node, body_items]
237
+ stack: List[List[Any]] = []
238
+
239
+ def sink() -> List[Node]:
240
+ return stack[-1][2][-1][2] if stack else out
241
+
242
+ for item in items:
243
+ found = directive(item)
244
+ if found is None:
245
+ sink().append(item)
246
+ continue
247
+ role, kind = found
248
+ if role == "open":
249
+ stack.append([kind, item, [["if" if kind == "conditional" else kind, item, []]]])
250
+ elif role == "branch":
251
+ if not stack or stack[-1][0] != "conditional":
252
+ raise _StructureError("a branch directive outside a conditional block", _range(item)[0])
253
+ if stack[-1][2][-1][0] == "else":
254
+ raise _StructureError("a branch directive after #Иначе", _range(item)[0])
255
+ stack[-1][2].append([kind, item, []])
256
+ else:
257
+ if not stack or stack[-1][0] != kind:
258
+ raise _StructureError("a closing directive without a matching opener", _range(item)[0])
259
+ block_kind, opener, branches = stack.pop()
260
+ start, end = _range(opener)[0], _range(item)[1]
261
+ block_children: List[Node]
262
+ if block_kind == "conditional":
263
+ block_children = []
264
+ for branch_kind, head_node, body in branches:
265
+ h_start, h_end = _range(head_node)
266
+ fields: Dict[str, Any] = {
267
+ _blocks.BRANCH_KIND: branch_kind,
268
+ _blocks.HEAD: str(head_node.fields.get("content", "")),
269
+ }
270
+ condition = head_node.fields.get(_blocks.CONDITION)
271
+ if isinstance(condition, str) and condition:
272
+ fields[_blocks.CONDITION] = condition
273
+ block_children.append(_block_node(
274
+ _blocks.PREPROC_KIND, container, h_start, _body_end(h_end, body), fields, body))
275
+ else:
276
+ block_children = branches[0][2]
277
+ block = _block_node(
278
+ _blocks.PREPROC_KIND, container, start, end,
279
+ {_blocks.BLOCK_KIND: block_kind, _blocks.HEAD: str(opener.fields.get("content", ""))},
280
+ block_children,
281
+ )
282
+ sink().append(block)
283
+ if stack:
284
+ raise _StructureError("a preprocessor opener without a closing directive", _range(stack[-1][1])[0])
285
+ return out
286
+
287
+
288
+ # -- nested preprocessor nodes of the own parser build ---------------------------------------------
289
+
290
+ _PREPROC_KEYWORDS = frozenset({
291
+ "PREPROC_IF_KEYWORD", "PREPROC_ELSIF_KEYWORD", "PREPROC_ELSE_KEYWORD", "PREPROC_ENDIF_KEYWORD",
292
+ "PREPROC_REGION_KEYWORD", "PREPROC_ENDREGION_KEYWORD",
293
+ })
294
+ _PREPROC_CONDITIONAL_KEYWORDS = frozenset({"PREPROC_IF_KEYWORD", "PREPROC_ELSIF_KEYWORD"})
295
+
296
+
297
+ class _DirectiveHead:
298
+ """The directive line of a nested ``preprocessor`` node (``#Если ... Тогда``, ``#Иначе``, ``#КонецЕсли``,
299
+ ``#Область Имя``) seen as one flat sibling, the shape the block grouping works on."""
300
+
301
+ type = "_directive_head"
302
+
303
+ def __init__(self, start_byte: int, end_byte: int, condition: Optional[str]) -> None:
304
+ self.start_byte = start_byte
305
+ self.end_byte = end_byte
306
+ self.condition = condition
307
+ self.text = b""
308
+
309
+
310
+ def _is_nested_preprocessor(ts_node: "TSNode") -> bool:
311
+ return ts_node.type == _PREPROCESSOR_TYPE and any(c.type in _PREPROC_KEYWORDS for c in ts_node.children)
312
+
313
+
314
+ def _flatten_preprocessors(ts_children: List["TSNode"], container: "TSNode") -> List[Any]:
315
+ """Replace each nested ``preprocessor`` node (directive line, body and closing directive in ONE node) with its
316
+ flat form: a :class:`_DirectiveHead` per directive line and the body nodes as plain siblings."""
317
+
318
+ out: List[Any] = []
319
+ for child in ts_children:
320
+ if not _is_nested_preprocessor(child):
321
+ out.append(child)
322
+ continue
323
+ items = list(child.children)
324
+ index = 0
325
+ while index < len(items):
326
+ item = items[index]
327
+ index += 1
328
+ if item.type not in _PREPROC_KEYWORDS:
329
+ out.extend(_flatten_preprocessors([item], container))
330
+ continue
331
+ end, condition = item.end_byte, None
332
+ if item.type in _PREPROC_CONDITIONAL_KEYWORDS:
333
+ while index < len(items):
334
+ part = items[index]
335
+ index += 1
336
+ if part.type == "expression" and condition is None:
337
+ condition = _text(part)
338
+ end = part.end_byte
339
+ if part.type == "THEN_KEYWORD":
340
+ break
341
+ elif item.type == "PREPROC_REGION_KEYWORD":
342
+ while index < len(items) and items[index].type != "line_comment" and \
343
+ b"\n" not in (container.text or b"")[item.start_byte - container.start_byte:
344
+ items[index].start_byte - container.start_byte]:
345
+ end = items[index].end_byte
346
+ index += 1
347
+ out.append(_DirectiveHead(item.start_byte, end, condition))
348
+ return out
349
+
350
+
351
+ def _convert_directive_head(head: _DirectiveHead, container: "TSNode") -> Node:
352
+ extra: Dict[str, Any] = {}
353
+ if head.condition:
354
+ extra[_blocks.CONDITION] = head.condition
355
+ wrapped = PreprocessorDirectiveNode(
356
+ start_byte=head.start_byte, end_byte=head.end_byte,
357
+ content=_slice(container, head.start_byte, head.end_byte), **extra,
358
+ )
359
+ return wrapped.node
360
+
361
+
362
+ def _convert_sequence(ts_children: List["TSNode"], container: "TSNode", *, trivia: bool = False) -> List[Node]:
363
+ """Convert one sibling list: nodes, language blocks, method trivia (module level) and directive blocks."""
364
+ flat: List[Node] = []
365
+ pending: List[Node] = []
366
+ index = 0
367
+ ts_children = _flatten_preprocessors(ts_children, container)
368
+ while index < len(ts_children):
369
+ child = ts_children[index]
370
+ index += 1
371
+ mapped: Node
372
+ if isinstance(child, _DirectiveHead):
373
+ mapped = _with_identity(_convert_directive_head(child, container))
374
+ elif child.type in _blocks.LANGUAGE_BLOCK_KINDS:
375
+ extend = child.end_byte
376
+ following = ts_children[index] if index < len(ts_children) else None
377
+ if (following is not None and following.type in ("ERROR", ";", "empty_statement")
378
+ and following.text == b";" and following.start_byte == child.end_byte):
379
+ # The parser leaves the ``;`` after ``КонецЦикла`` / ``КонецЕсли`` / ``КонецПопытки`` outside the
380
+ # block (an ERROR node in 0.1.6, a ``;`` token or an ``empty_statement`` in the own build).
381
+ extend = following.end_byte
382
+ index += 1
383
+ mapped = _with_identity(_convert_language_block(child, container, extend))
384
+ elif child.type in _VAR_DECLARATION_TYPES and _is_terminator(ts_children, index, child, container):
385
+ mapped = _with_identity(_convert_var_declaration(child, ts_children[index]))
386
+ index += 1
387
+ else:
388
+ mapped = _convert(child)
389
+ if trivia:
390
+ if child.type in _METHOD_TYPES and pending:
391
+ mapped = _with_method_trivia(mapped, child, pending, container)
392
+ pending = pending + [mapped] if mapped.kind in _TRIVIA_KINDS else []
393
+ flat.append(mapped)
394
+ return _group_directives(flat, container)
395
+
396
+
397
+ def _is_terminator(ts_children: List["TSNode"], index: int, declaration: "TSNode", container: "TSNode") -> bool:
398
+ """Whether the sibling at ``index`` is the ``;`` closing ``declaration`` (only blanks between them)."""
399
+
400
+ if index >= len(ts_children):
401
+ return False
402
+ following = ts_children[index]
403
+ if following.type not in (";", "empty_statement"):
404
+ return False
405
+ between = _slice(container, declaration.end_byte, following.start_byte)
406
+ return not between.strip(" \t") and (following.text or b"") == b";"
407
+
408
+
409
+ def _expression_text(ts_node: "TSNode") -> Optional[str]:
410
+ expression = next((c for c in ts_node.children if c.type == "expression"), None)
411
+ return _text(expression) if expression is not None else None
412
+
413
+
414
+ def _first(ts_node: "TSNode", *types: str) -> Optional["TSNode"]:
415
+ return next((c for c in ts_node.children if c.type in types), None)
416
+
417
+
418
+ def _body(ts_children: List["TSNode"], container: "TSNode") -> List[Node]:
419
+ return _convert_sequence(ts_children, container)
420
+
421
+
422
+ def _convert_language_block(ts_node: "TSNode", container: "TSNode", end: int) -> Node:
423
+ """A control structure (``Если``, ``Для``, ``Для Каждого``, ``Пока``, ``Попытка``) as a block node.
424
+
425
+ The header tokens (opener keyword, condition, ``Тогда``/``Цикл``) are not nodes: they are the block's and
426
+ branches' ``head``/``condition`` attributes. The closing keyword stays in the block's own text."""
427
+ block_kind = _blocks.LANGUAGE_BLOCK_KINDS[ts_node.type]
428
+ kind = f"{_KIND_PREFIX}{ts_node.type}"
429
+ children = list(ts_node.children)
430
+ start = ts_node.start_byte
431
+
432
+ if block_kind == "if":
433
+ opener = _first(ts_node, "IF_KEYWORD")
434
+ then = _first(ts_node, "THEN_KEYWORD")
435
+ closer = _first(ts_node, "ENDIF_KEYWORD")
436
+ if opener is None or then is None or closer is None:
437
+ raise _StructureError("a conditional statement without its keywords", ts_node.start_byte)
438
+ clauses = [c for c in children if c.type in ("elseif_clause", "else_clause")]
439
+ first_body_end = clauses[0].start_byte if clauses else closer.start_byte
440
+ body = [c for c in children if then.end_byte <= c.start_byte < first_body_end and c.type != "ENDIF_KEYWORD"]
441
+ branches: List[Node] = []
442
+ items = _body(body, ts_node)
443
+ head_end = then.end_byte
444
+ branches.append(_block_node(
445
+ f"{_KIND_PREFIX}if_clause", ts_node, opener.start_byte, _body_end(head_end, items),
446
+ {_blocks.BRANCH_KIND: "if", _blocks.HEAD: _slice(ts_node, opener.start_byte, head_end),
447
+ _blocks.CONDITION: _expression_text(ts_node) or ""}, items))
448
+ seen_else = False
449
+ for clause in clauses:
450
+ if seen_else:
451
+ raise _StructureError("a branch after Иначе")
452
+ if clause.type == "elseif_clause":
453
+ kw = _first(clause, "ELSIF_KEYWORD")
454
+ th = _first(clause, "THEN_KEYWORD")
455
+ if kw is None or th is None:
456
+ raise _StructureError("a malformed ИначеЕсли")
457
+ body_nodes = [c for c in clause.children if c.start_byte >= th.end_byte]
458
+ items = _body(body_nodes, ts_node)
459
+ branches.append(_block_node(
460
+ f"{_KIND_PREFIX}elseif_clause", ts_node, kw.start_byte, _body_end(th.end_byte, items),
461
+ {_blocks.BRANCH_KIND: "elsif", _blocks.HEAD: _slice(ts_node, kw.start_byte, th.end_byte),
462
+ _blocks.CONDITION: _expression_text(clause) or ""}, items))
463
+ else:
464
+ seen_else = True
465
+ kw = _first(clause, "ELSE_KEYWORD")
466
+ if kw is None:
467
+ raise _StructureError("a malformed Иначе")
468
+ body_nodes = [c for c in clause.children if c.start_byte >= kw.end_byte]
469
+ items = _body(body_nodes, ts_node)
470
+ branches.append(_block_node(
471
+ f"{_KIND_PREFIX}else_clause", ts_node, kw.start_byte, _body_end(kw.end_byte, items),
472
+ {_blocks.BRANCH_KIND: "else", _blocks.HEAD: _slice(ts_node, kw.start_byte, kw.end_byte)},
473
+ items))
474
+ return _block_node(kind, container, start, end,
475
+ {_blocks.BLOCK_KIND: "if",
476
+ _blocks.HEAD: _slice(ts_node, opener.start_byte, then.end_byte)}, branches)
477
+
478
+ if block_kind == "try":
479
+ opener = _first(ts_node, "TRY_KEYWORD")
480
+ except_kw = _first(ts_node, "EXCEPT_KEYWORD")
481
+ closer = _first(ts_node, "ENDTRY_KEYWORD")
482
+ if opener is None or except_kw is None or closer is None:
483
+ raise _StructureError("a Попытка statement without its keywords", ts_node.start_byte)
484
+ try_body = [c for c in children if opener.end_byte <= c.start_byte < except_kw.start_byte]
485
+ except_body = [c for c in children if except_kw.end_byte <= c.start_byte < closer.start_byte]
486
+ try_items, except_items = _body(try_body, ts_node), _body(except_body, ts_node)
487
+ branches = [
488
+ _block_node(f"{_KIND_PREFIX}try_clause", ts_node, opener.start_byte,
489
+ _body_end(opener.end_byte, try_items),
490
+ {_blocks.BRANCH_KIND: "try", _blocks.HEAD: _text(opener)}, try_items),
491
+ _block_node(f"{_KIND_PREFIX}except_clause", ts_node, except_kw.start_byte,
492
+ _body_end(except_kw.end_byte, except_items),
493
+ {_blocks.BRANCH_KIND: "except", _blocks.HEAD: _text(except_kw)}, except_items),
494
+ ]
495
+ return _block_node(kind, container, start, end,
496
+ {_blocks.BLOCK_KIND: "try", _blocks.HEAD: _text(opener)}, branches)
497
+
498
+ # loops
499
+ do = _first(ts_node, "DO_KEYWORD")
500
+ closer = _first(ts_node, "ENDDO_KEYWORD")
501
+ if do is None or closer is None:
502
+ raise _StructureError("a loop without its keywords", ts_node.start_byte)
503
+ body_nodes = [c for c in children if do.end_byte <= c.start_byte < closer.start_byte]
504
+ items = _body(body_nodes, ts_node)
505
+ return _block_node(kind, container, start, end,
506
+ {_blocks.BLOCK_KIND: block_kind, _blocks.HEAD: _slice(ts_node, start, do.end_byte)}, items)
507
+
508
+
509
+ def _method_fields(ts_node: "TSNode") -> Dict[str, Any]:
510
+ """Extract the small, stable method view without changing its raw tree.
511
+
512
+ The generic children remain the source of truth for rendering. These
513
+ fields only make the grammar's method header useful to query clients.
514
+ """
515
+ identifier = next((c for c in ts_node.children if c.type == _IDENTIFIER_TYPE), None)
516
+ parameters = next((c for c in ts_node.children if c.type == "parameters"), None)
517
+ items: List[Dict[str, Any]] = []
518
+ if parameters is not None:
519
+ for parameter in parameters.children:
520
+ if parameter.type != _PARAMETER_TYPE:
521
+ continue
522
+ name = next((c for c in parameter.children if c.type == _IDENTIFIER_TYPE), None)
523
+ item: Dict[str, Any] = {
524
+ "name": _text(name) if name is not None else "",
525
+ "by_value": any(dialects.is_by_value_modifier(_text(c)) for c in parameter.children),
526
+ }
527
+ equals = next((i for i, c in enumerate(parameter.children) if c.type == "="), None)
528
+ if equals is not None and equals + 1 < len(parameter.children):
529
+ item["default"] = _text(parameter.children[equals + 1])
530
+ items.append(item)
531
+ return {
532
+ "name": _text(identifier) if identifier is not None else "",
533
+ "export": any(c.type == _EXPORT_KEYWORD_TYPE for c in ts_node.children),
534
+ "parameters_json": json.dumps(items, ensure_ascii=False),
535
+ }
536
+
537
+
538
+ def _with_method_trivia(node: Node, method: "TSNode", trivia: List[Node], root: "TSNode") -> Node:
539
+ """Attach leading method trivia as query metadata without changing shape.
540
+
541
+ Keeping the grammar's root-child topology intact is essential to the
542
+ import contract and to byte stitching; editor operations use this metadata
543
+ to recognize the trivia that travels with a method.
544
+ """
545
+ fields = dict(node.fields)
546
+ fields.update(_method_fields(method))
547
+ annotations = [str(n.fields.get("content", "")) for n in trivia if n.kind == AnnotationNode._KIND]
548
+ if annotations:
549
+ fields["annotations_json"] = json.dumps(annotations, ensure_ascii=False)
550
+ for annotation in annotations:
551
+ canonical = dialects.is_annotation_prefix(annotation)
552
+ availability = _AVAILABILITY_BY_ANNOTATION.get(canonical)
553
+ if availability is not None:
554
+ fields["availability"] = availability
555
+ break
556
+ rebuilt = make_node(node.kind, fields=fields, children=node.children)
557
+ return dataclasses.replace(
558
+ rebuilt, node_id=node.node_id, short_id=node.short_id,
559
+ buffer_range=(method.start_byte, method.end_byte),
560
+ )
561
+
562
+
563
+ def _convert_source_file(ts_node: "TSNode") -> Node:
564
+ """Convert the root while folding leading method trivia into its method and
565
+ grouping paired preprocessor directives into block nodes (D-CE.2).
566
+
567
+ A block is evaluated by nobody: the engine never selects a branch."""
568
+ children = _convert_sequence(list(ts_node.children), ts_node, trivia=True)
569
+ node = make_node(f"{_KIND_PREFIX}{ts_node.type}", fields={"content": _text(ts_node)}, children=tuple(children))
570
+ return dataclasses.replace(node, buffer_range=(ts_node.start_byte, ts_node.end_byte))
571
+
572
+
573
+ def _convert_parameter(ts_node: "TSNode") -> Node:
574
+ """A procedure/function ``parameter`` node: the generic mapping, plus a
575
+ ``by_value`` field when one of its own children is the by-value
576
+ passing-mode modifier in either dialect, detected purely via
577
+ ``dialects.is_by_value_modifier`` -- never by tree-sitter node-kind
578
+ name -- so the same code path covers ``Знач`` and ``Val`` alike
579
+ ({p115})."""
580
+
581
+ base = _convert_generic(ts_node)
582
+ is_by_value = any(dialects.is_by_value_modifier(_text(child)) for child in ts_node.children)
583
+ if not is_by_value:
584
+ return base
585
+ fields = dict(base.fields)
586
+ fields[dialects.BY_VALUE] = True
587
+ rebuilt = make_node(base.kind, fields=fields, children=base.children)
588
+ return dataclasses.replace(rebuilt, buffer_range=base.buffer_range)
589
+
590
+
591
+ def _convert_preprocessor(ts_node: "TSNode") -> Node:
592
+ """A ``preprocessor`` node: either the wrapper around a recognized
593
+ ``annotation`` construct -- mapped to a standalone
594
+ :class:`AnnotationNode`, keyed to the inner node's own byte range, and
595
+ never combined with :class:`PreprocessorDirectiveNode` ({an01}) -- or
596
+ any other preprocessor construct (``#Если``/``#If`` and friends),
597
+ mapped flat to :class:`PreprocessorDirectiveNode` with no BSL-specific
598
+ child interpretation ({p043})."""
599
+
600
+ annotation_child = next(
601
+ (child for child in ts_node.children if child.type == _ANNOTATION_TYPE), None
602
+ )
603
+ if annotation_child is not None:
604
+ content = _text(annotation_child)
605
+ canonical = dialects.is_annotation_prefix(content)
606
+ extra: Dict[str, Any] = {"annotation_kind": canonical} if canonical is not None else {}
607
+ wrapped = AnnotationNode(
608
+ start_byte=annotation_child.start_byte,
609
+ end_byte=annotation_child.end_byte,
610
+ content=content,
611
+ **extra,
612
+ )
613
+ return wrapped.node
614
+
615
+ extra_directive: Dict[str, Any] = {}
616
+ condition = _expression_text(ts_node)
617
+ if condition:
618
+ extra_directive[_blocks.CONDITION] = condition
619
+ wrapped = PreprocessorDirectiveNode(
620
+ start_byte=ts_node.start_byte, end_byte=ts_node.end_byte, content=_text(ts_node), **extra_directive
621
+ )
622
+ return wrapped.node
623
+
624
+
625
+ def _declared_identifier(child: "TSNode") -> "TSNode":
626
+ """The identifier node of one declared name: the child itself (in-procedure ``var_statement``) or the
627
+ identifier inside a ``variable_spec`` (module-level ``var_definition`` of the own parser build)."""
628
+
629
+ if child.type != _VARIABLE_SPEC_TYPE:
630
+ return child
631
+ return next((c for c in child.children if c.type == _IDENTIFIER_TYPE), child)
632
+
633
+
634
+ def _convert_var_declaration(ts_node: "TSNode", terminator: Optional["TSNode"] = None) -> Node:
635
+ """A ``var_statement`` (in-procedure) or ``var_definition``
636
+ (module-level) node -- the same tree-sitter-bsl grammar distinction
637
+ collapsed here into one code path -- mapped to one
638
+ :class:`VariableDeclarationNode` whose ordered children are one
639
+ :class:`VariableDeclaratorNode` per declared identifier, with the
640
+ exact original inter-declarator source bytes preserved as separators,
641
+ per {iblr}. A trailing ``EXPORT_KEYWORD`` child sets the declaration's
642
+ ``export`` field ({p044}, {p047}); it is not propagated onto
643
+ individual declarators, since the grammar itself attaches the keyword
644
+ once, at the statement level.
645
+
646
+ The ``VAR_KEYWORD``/``EXPORT_KEYWORD`` tokens' own written text is
647
+ captured verbatim into the ``var_keyword_text``/``export_keyword_text``
648
+ fields (bug cd41e1fc): BSL keywords are case-insensitive, and the
649
+ generator must never rewrite a document's own written case to the
650
+ dialect table's canonical spelling on an unmodified round trip. The
651
+ exact original whitespace RUNS between the ``VAR_KEYWORD`` and the
652
+ first declarator, and between the last declarator and the
653
+ ``EXPORT_KEYWORD`` (when present), are likewise captured verbatim into
654
+ ``leading_gap_text``/``export_gap_text`` (bug cd41e1fc round 3): the
655
+ generator's own separators were previously a fixed single space,
656
+ collapsing multiple/irregular whitespace (``Перем А`` -> ``Перем А``)
657
+ on an otherwise unmodified round trip."""
658
+
659
+ # The own parser build leaves the closing ``;`` of a declaration outside the declaration node (a sibling
660
+ # ``;`` token or ``empty_statement``); ``terminator`` is that node. The declaration keeps owning its ``;``.
661
+ end_byte = terminator.end_byte if terminator is not None else ts_node.end_byte
662
+ container = ts_node.parent if terminator is not None and ts_node.parent is not None else ts_node
663
+ identifiers: List["TSNode"] = [
664
+ _declared_identifier(child)
665
+ for child in ts_node.children
666
+ if child.type in (_IDENTIFIER_TYPE, _VARIABLE_SPEC_TYPE)
667
+ ]
668
+ var_keyword = next(
669
+ (child for child in ts_node.children if child.type == _VAR_KEYWORD_TYPE), None
670
+ )
671
+ export_keyword = next(
672
+ (child for child in ts_node.children if child.type == _EXPORT_KEYWORD_TYPE), None
673
+ )
674
+
675
+ declarators = [
676
+ VariableDeclaratorNode(
677
+ start_byte=ident.start_byte,
678
+ end_byte=ident.end_byte,
679
+ content=_text(ident),
680
+ name=_text(ident),
681
+ )
682
+ for ident in identifiers
683
+ ]
684
+ separators = [
685
+ _slice(container, prev.end_byte, nxt.start_byte)
686
+ for prev, nxt in zip(identifiers, identifiers[1:])
687
+ ]
688
+
689
+ extra: Dict[str, Any] = {}
690
+ if var_keyword is not None:
691
+ extra["var_keyword_text"] = _text(var_keyword)
692
+ if identifiers:
693
+ extra["leading_gap_text"] = _slice(
694
+ container, var_keyword.end_byte, identifiers[0].start_byte
695
+ )
696
+ if export_keyword is not None:
697
+ extra["export_keyword_text"] = _text(export_keyword)
698
+ if identifiers:
699
+ extra["export_gap_text"] = _slice(
700
+ container, identifiers[-1].end_byte, export_keyword.start_byte
701
+ )
702
+ if identifiers:
703
+ tail_start = export_keyword.end_byte if export_keyword is not None else identifiers[-1].end_byte
704
+ tail = _slice(container, tail_start, end_byte)
705
+ if tail.endswith(";"):
706
+ extra["trailing_gap_text"] = tail[:-1]
707
+
708
+ wrapped = VariableDeclarationNode(
709
+ start_byte=ts_node.start_byte,
710
+ end_byte=end_byte,
711
+ content=_slice(container, ts_node.start_byte, end_byte),
712
+ declarators=declarators,
713
+ separators=separators,
714
+ export=export_keyword is not None,
715
+ **extra,
716
+ )
717
+ return wrapped.node
718
+
719
+
720
+ def _with_identity(node: Node) -> Node:
721
+ """Guarantee the identity invariant on one mapped node: a fresh UUID4
722
+ ``node_id`` ({p013}) and the next monotonic ``short_id`` ({p097}), a
723
+ positive integer whose 0x-hex form is only an outward rendering.
724
+
725
+ A slot already filled by the wrapper types -- which stamp both from the
726
+ very counter reused here -- is kept as it stands: re-stamping would
727
+ desynchronize a wrapper node from the copies of itself that
728
+ :class:`VariableDeclarationNode`/:class:`AnnotationNode` keep in both
729
+ ``fields`` and ``children``."""
730
+
731
+ if node.node_id is not None and node.short_id is not None:
732
+ return node
733
+ return dataclasses.replace(
734
+ node,
735
+ node_id=node.node_id if node.node_id is not None else generate_node_id(),
736
+ short_id=node.short_id if node.short_id is not None else next(_SHORT_ID_COUNTER),
737
+ )
738
+
739
+
740
+ def _convert(ts_node: "TSNode") -> Node:
741
+ """Dispatch one tree-sitter-bsl node to its mapped common-model
742
+ ``Node``, per this module's mapping rules. Every branch ultimately
743
+ returns a plain, already-validated ``Node`` -- wrapper types
744
+ (:class:`AnnotationNode` and friends) are unwrapped to their own
745
+ ``.node`` immediately, so a parent's ``children`` tuple never holds
746
+ anything but base ``Node`` instances, satisfying
747
+ ``tree_engine.core.nodes.make_node``'s own shape contract.
748
+
749
+ This is also the one choke point every mapped node passes through --
750
+ the document root, every generic node, and each recursively converted
751
+ child alike -- so :func:`_with_identity` applied to the dispatch result
752
+ is what makes the whole imported tree carry identity, on the fragment
753
+ path exactly as on the document path."""
754
+
755
+ node_type = ts_node.type
756
+ if node_type == "source_file":
757
+ mapped = _convert_source_file(ts_node)
758
+ elif node_type in _VAR_DECLARATION_TYPES:
759
+ mapped = _convert_var_declaration(ts_node)
760
+ elif node_type == _PREPROCESSOR_TYPE:
761
+ mapped = _convert_preprocessor(ts_node)
762
+ elif node_type == _PARAMETER_TYPE:
763
+ mapped = _convert_parameter(ts_node)
764
+ else:
765
+ mapped = _convert_generic(ts_node)
766
+ return _with_identity(mapped)
767
+
768
+
769
+ def _collect_error_shape(ts_node: "TSNode") -> Tuple[List["TSNode"], bool]:
770
+ """Walk ``ts_node``'s subtree once and return ``(top_level_errors,
771
+ any_missing)``: every outermost ``ERROR`` node (an ``ERROR`` whose parent
772
+ chain, up to ``ts_node``, contains no other ``ERROR``) and whether any
773
+ ``MISSING`` node exists anywhere in the subtree, nested or not. Used only
774
+ to recognize the one narrow exception in :func:`import_to_common` below;
775
+ it never changes what counts as damage for any other shape."""
776
+
777
+ top_level_errors: List["TSNode"] = []
778
+ any_missing = False
779
+
780
+ def walk(node: "TSNode", inside_error: bool) -> None:
781
+ nonlocal any_missing
782
+ if getattr(node, "is_missing", False):
783
+ any_missing = True
784
+ if node.type == "ERROR":
785
+ if not inside_error:
786
+ top_level_errors.append(node)
787
+ for child in node.children:
788
+ walk(child, True)
789
+ return
790
+ for child in node.children:
791
+ walk(child, inside_error)
792
+
793
+ walk(ts_node, False)
794
+ return top_level_errors, any_missing
795
+
796
+
797
+ # Bare, stray punctuation tokens tree-sitter-bsl 0.1.6 cannot place in its
798
+ # grammar and marks as an ERROR even though everything around them parses
799
+ # cleanly (bug cd41e1fc classification, K25b/K25c): the terminator `;`
800
+ # after `КонецЦикла`/`КонецПопытки`-style block keywords, an empty
801
+ # double-semicolon statement, and the bracket tokens of a bare parenthesized
802
+ # grouping expression (`Если (Условие) Тогда`, `А = (Б + В) * 2`, a nested
803
+ # call argument, or REDUNDANT nested grouping like `Окр(((Сумма)))`) -- the
804
+ # grammar happily parses the CONTENTS of the parentheses as an ordinary
805
+ # sibling expression; only the stray bracket/semicolon bytes themselves are
806
+ # rejected, sometimes as a RUN of more than one such byte (K25c, e.g. `((`
807
+ # or `))` when redundant grouping nests two or three layers deep -- 24
808
+ # files measured at run-length 2, 28 at run-length 3 on the external
809
+ # corpus). A run qualifies only when EVERY byte in the ERROR's own span is
810
+ # one of these three; a run containing anything else is never swallowed.
811
+ _STRAY_PUNCTUATION_BYTES = frozenset(b";()")
812
+
813
+ # A single mis-tokenized statement (K25c): tree-sitter-bsl 0.1.6 lexes a
814
+ # handful of BSL keywords (e.g. `Перейти`, the GoTo statement keyword)
815
+ # context-insensitively, so using one of them as a property/method name
816
+ # after a `.` (`Хб.Перейти(н)`) breaks the surrounding statement's parse
817
+ # even though it is otherwise perfectly ordinary. Rather than special-case
818
+ # every colliding keyword, an ERROR of this shape is recognized STRUCTURALLY
819
+ # and kept as opaque, byte-preserved content (no attribute or identifier is
820
+ # derived from it, exactly like the other two bounded shapes): it must (a)
821
+ # end with the statement terminator `;`, (b) contain that `;` EXACTLY ONCE
822
+ # (so it is one statement, never several concatenated ones), (c) balance
823
+ # its own parentheses count, and (d) stay under
824
+ # :data:`_MAX_SELF_CONTAINED_STATEMENT_LENGTH` bytes -- a generous cap that
825
+ # still excludes the one genuinely severe outlier the tester measured (a
826
+ # single file's ERROR spanning 18613 bytes, nearly its entire remainder).
827
+ _MAX_SELF_CONTAINED_STATEMENT_LENGTH = 200
828
+
829
+
830
+ def _is_self_contained_mistokenized_statement(text: bytes) -> bool:
831
+ if not text or not text.endswith(b";"):
832
+ return False
833
+ if len(text) > _MAX_SELF_CONTAINED_STATEMENT_LENGTH:
834
+ return False
835
+ if text.count(b";") != 1:
836
+ return False
837
+ return text.count(b"(") == text.count(b")")
838
+
839
+
840
+ def _is_bounded_error(ts_node: "TSNode") -> bool:
841
+ """True when ``ts_node`` (an outermost ``ERROR`` node) is one of the
842
+ three narrow, owner/tester-classified exceptions to
843
+ ``import_to_common``'s refusal rule -- its bytes are kept exactly as
844
+ ordinary surrounding content and no attribute is derived from them:
845
+
846
+ * K25a-4 (R1-3, {an01}): an unrecognised ``&`` compilation directive/
847
+ annotation confined to its own line;
848
+ * K25b/K25c (bug cd41e1fc): a RUN of one or more stray punctuation
849
+ bytes -- each one of :data:`_STRAY_PUNCTUATION_BYTES` -- that the
850
+ grammar could not place, with everything around it parsed as
851
+ ordinary, well-formed siblings;
852
+ * K25c (bug cd41e1fc round 3): a single self-contained statement the
853
+ grammar mis-tokenized because it uses a recognized keyword where an
854
+ identifier was expected (:func:`_is_self_contained_mistokenized_statement`).
855
+
856
+ Every other ``ERROR`` shape is UNBOUNDED and still refuses the whole
857
+ document/fragment exactly as before."""
858
+
859
+ text = ts_node.text or b""
860
+ if text.startswith(b"&") and b"\n" not in text:
861
+ return True
862
+ if text and all(byte in _STRAY_PUNCTUATION_BYTES for byte in text):
863
+ return True
864
+ return _is_self_contained_mistokenized_statement(text)
865
+
866
+
867
+ def _has_only_bounded_damage(ts_node: "TSNode") -> bool:
868
+ """Whether parser recovery can be preserved as opaque source spans.
869
+
870
+ ``tree-sitter-bsl`` 0.1.6 reports ``ERROR`` for several valid BSL
871
+ constructs that its grammar cannot model, including larger expressions
872
+ whose recovery spans contain identifiers and punctuation. The common
873
+ model maps those nodes generically and the BSL renderer stitches their
874
+ captured byte ranges back into the source, so accepting an ``ERROR``
875
+ alone does not invent structure or normalize the document.
876
+
877
+ A ``MISSING`` node is different: tree-sitter had to synthesize a token
878
+ that the source does not contain. Such a tree is incomplete and must
879
+ retain the established parse refusal. Require an outermost ``ERROR``
880
+ as well so a hypothetical ``has_error`` shape with neither recovery
881
+ marker is never accepted by accident.
882
+ """
883
+
884
+ top_level_errors, any_missing = _collect_error_shape(ts_node)
885
+ return bool(top_level_errors) and not any_missing
886
+
887
+
888
+ _STRUCTURE_TOKENS = frozenset({
889
+ "ELSE_KEYWORD", "ELSIF_KEYWORD", "EXCEPT_KEYWORD", "ENDIF_KEYWORD", "ENDTRY_KEYWORD", "ENDDO_KEYWORD",
890
+ "PREPROC_ELSE_KEYWORD", "PREPROC_ELSIF_KEYWORD", "PREPROC_ENDIF_KEYWORD", "PREPROC_ENDREGION_KEYWORD",
891
+ })
892
+
893
+
894
+ def _has_structure_damage(ts_node: "TSNode") -> bool:
895
+ """True when a recovery ``ERROR`` swallowed a block keyword (a second ``Иначе``, a lone ``КонецЕсли``...).
896
+
897
+ Such a tree is a structure error (D-CF.0), never an opaque recovery span."""
898
+ stack = [ts_node]
899
+ while stack:
900
+ node = stack.pop()
901
+ if node.type == "ERROR":
902
+ inner = [node]
903
+ while inner:
904
+ current = inner.pop()
905
+ if current.type in _STRUCTURE_TOKENS:
906
+ return True
907
+ inner.extend(current.children)
908
+ continue
909
+ stack.extend(node.children)
910
+ return False
911
+
912
+
913
+ def import_to_common(
914
+ external_representation: "TSNode",
915
+ options: Optional[Mapping[str, Any]] = None,
916
+ *,
917
+ fragment: bool = False,
918
+ ) -> Node:
919
+ """Translate an already-parsed tree-sitter-bsl ``Node`` (a document's
920
+ root, or a subtree for fragment use) into a common-model ``Node``,
921
+ walking the tree per this module's mapping rules.
922
+
923
+ ``options`` is accepted for contract-signature compatibility and
924
+ currently unused. Pass ``fragment=True`` when ``external_representation``
925
+ is a local fragment rather than a whole document's root, so a rejected
926
+ damaged tree is reported under ``FORMAT_FRAGMENT_PARSE_FAILED`` instead
927
+ of ``FORMAT_CONTENT_PARSE_FAILED`` ({p104}).
928
+
929
+ Raises :class:`~tree_engine.plugins.contract.FormatPluginContractError`
930
+ -- carrying whichever of those two codes applies -- when
931
+ ``external_representation`` itself reports ``has_error`` (tree-sitter
932
+ propagates this up through every ancestor of any ``ERROR`` or
933
+ ``MISSING`` descendant, so this single check catches damage anywhere in
934
+ the subtree being imported): this module maps only already-valid parse
935
+ trees and never synthesizes a partial common-model tree from one that
936
+ is not, even though primary classification for a whole document or
937
+ fragment is the calling ``parse_document``/``parse_fragment`` logic's
938
+ responsibility. Recovery-only exceptions
939
+ (:func:`_has_only_bounded_damage`): a tree containing one or more
940
+ ``ERROR`` nodes but no ``MISSING`` nodes lets the document/fragment
941
+ through. Each recovery node is mapped like any other generic node (its
942
+ bytes are preserved verbatim and no BSL-specific attribute is derived).
943
+ Any ``MISSING`` node still refuses the document or fragment because the
944
+ parser had to synthesize source that was not present.
945
+ """
946
+
947
+ code = ErrorCode.FORMAT_FRAGMENT_PARSE_FAILED if fragment else ErrorCode.FORMAT_CONTENT_PARSE_FAILED
948
+ if getattr(external_representation, "has_error", False):
949
+ if not _has_only_bounded_damage(external_representation) or _has_structure_damage(external_representation):
950
+ raise _contract_error(
951
+ "tree-sitter-bsl parse tree contains an ERROR or MISSING node; "
952
+ "refusing to map a partial tree",
953
+ code=code,
954
+ )
955
+ try:
956
+ return _convert(external_representation)
957
+ except _StructureError as exc:
958
+ raise _contract_error(f"BSL structure error: {exc}", code=code) from exc
959
+
960
+
961
+ def structure_problem(external_representation: "TSNode") -> Optional[Tuple[int, str]]:
962
+ """The block-structure error of a parse tree as ``(byte offset, message)``, or ``None`` (D-CE.3)."""
963
+
964
+ try:
965
+ _convert(external_representation)
966
+ except _StructureError as exc:
967
+ offset = exc.offset if exc.offset is not None else external_representation.start_byte
968
+ return offset, f"BSL structure error: {exc}"
969
+ return None
970
+
971
+
972
+ class BSLImportMap:
973
+ """Import (tree-sitter-bsl -> common model) stage of the BSL
974
+ translator.
975
+
976
+ Supplies the ``import_to_common`` stage that
977
+ ``tree_engine.plugins.contract.FormatPluginContract`` requires
978
+ ({p046}, {p056}, {p057}); ``parse_document``/``parse_fragment`` (which
979
+ own the ``has_error`` primary classification, per {p104}), the export
980
+ stage, and the remaining contract surface are delivered by sibling
981
+ steps and composed with this class later.
982
+ """
983
+
984
+ def import_to_common(
985
+ self,
986
+ external_representation: "TSNode",
987
+ options: Optional[Mapping[str, Any]] = None,
988
+ *,
989
+ fragment: bool = False,
990
+ ) -> Node:
991
+ """Translate an already-parsed tree-sitter-bsl ``Node`` into a
992
+ common-model ``Node``; see the module-level :func:`import_to_common`
993
+ for the full contract."""
994
+
995
+ return import_to_common(external_representation, options, fragment=fragment)