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,449 @@
1
+ """Source-splice planning for BSL structural edits (TODO f166b8c9 D-CE.5, D-CF.2-D-CF.4).
2
+
3
+ BSL edits are planned on the source bytes, line by line, and the tree is rebuilt from the edited
4
+ bytes. A plan is a list of non-overlapping :class:`Splice` objects in the coordinates of the
5
+ CURRENT source plus the *container*: the surviving node whose content changes. The facade applies
6
+ the plan, re-parses the result (an unbalanced block is refused there, draft unchanged) and records
7
+ one journal step.
8
+
9
+ Why bytes and not tree surgery: a BSL node's text is stitched from its own captured span and the
10
+ gaps between its children, so an insert or delete that edits the child list alone loses the
11
+ whitespace and newlines around the touched node and duplicates text (the draft corruption of the
12
+ D-CE/D-CF RED, an existing defect for any statement inside a method body). Planning on bytes keeps
13
+ every untouched byte, line ending and indentation exactly as written.
14
+
15
+ Author: Vasiliy Zdanovskiy
16
+ email: vasilyvz@gmail.com
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from dataclasses import dataclass, field
22
+ from typing import Any, List, Optional, Sequence, Tuple
23
+
24
+ from tree_engine.plugins.bsl import blocks as B
25
+
26
+ __all__ = [
27
+ "BlockEditError",
28
+ "Splice",
29
+ "Plan",
30
+ "METHOD_KINDS",
31
+ "ROOT_KIND",
32
+ "apply_splices",
33
+ "scope_of",
34
+ "line_extent",
35
+ "involved",
36
+ "plan_insert",
37
+ "plan_delete",
38
+ "plan_replace",
39
+ "plan_move",
40
+ "plan_attribute",
41
+ ]
42
+
43
+ METHOD_KINDS = frozenset({"bsl:procedure_definition", "bsl:function_definition"})
44
+ TRIVIA_KINDS = frozenset({"bsl:line_comment", "core:annotation"})
45
+ HEADER_KINDS = frozenset({
46
+ "bsl:PROCEDURE_KEYWORD", "bsl:FUNCTION_KEYWORD", "bsl:identifier", "bsl:parameters", "bsl:EXPORT_KEYWORD",
47
+ })
48
+ END_KINDS = frozenset({"bsl:ENDPROCEDURE_KEYWORD", "bsl:ENDFUNCTION_KEYWORD"})
49
+ ROOT_KIND = "bsl:source_file"
50
+
51
+
52
+ class BlockEditError(ValueError):
53
+ """The requested block edit is not admissible (the draft is left untouched)."""
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class Splice:
58
+ """Replace ``source[start:end]`` with ``data``."""
59
+
60
+ start: int
61
+ end: int
62
+ data: bytes
63
+
64
+
65
+ @dataclass
66
+ class Plan:
67
+ """One planned edit: the splices and the surviving node whose content they change."""
68
+
69
+ splices: List[Splice]
70
+ container: Any
71
+ action: str
72
+ targets: List[Any] = field(default_factory=list)
73
+ extra_containers: List[Any] = field(default_factory=list)
74
+
75
+
76
+ # -- byte and line helpers --------------------------------------------------------------------------
77
+
78
+
79
+ def apply_splices(source: bytes, splices: Sequence[Splice]) -> bytes:
80
+ """Apply non-overlapping splices (coordinates of ``source``) back to front."""
81
+ out = source
82
+ for sp in sorted(splices, key=lambda s: (s.start, s.end), reverse=True):
83
+ out = out[: sp.start] + sp.data + out[sp.end:]
84
+ return out
85
+
86
+
87
+ def _line_start(src: bytes, off: int) -> int:
88
+ return src.rfind(b"\n", 0, off) + 1
89
+
90
+
91
+ def _line_after(src: bytes, off: int) -> int:
92
+ i = src.find(b"\n", off)
93
+ return len(src) if i < 0 else i + 1
94
+
95
+
96
+ def _blank(data: bytes) -> bool:
97
+ return data.strip(b" \t\r\n") == b""
98
+
99
+
100
+ def eol_of(src: bytes, near: int = 0) -> bytes:
101
+ """The line ending used near ``near`` (the first one of the file when the line has none)."""
102
+ i = src.find(b"\n", max(0, near))
103
+ if i < 0:
104
+ i = src.find(b"\n")
105
+ return b"\r\n" if i > 0 and src[i - 1: i] == b"\r" else b"\n"
106
+
107
+
108
+ def _normalize_eol(data: bytes, eol: bytes) -> bytes:
109
+ if eol == b"\r\n" and b"\r\n" not in data:
110
+ return data.replace(b"\n", b"\r\n")
111
+ return data
112
+
113
+
114
+ def _range(node: Any) -> Tuple[int, int]:
115
+ rng = node.buffer_range
116
+ if rng is None:
117
+ raise BlockEditError("the node has no source range")
118
+ # The own parser build leaves the ``;`` closing a statement as the next sibling; it belongs to the statement.
119
+ parent = getattr(node, "parent", None)
120
+ if parent is not None and node.kind != ";":
121
+ kids = list(parent.children)
122
+ at = next((i for i, kid in enumerate(kids) if kid is node), None)
123
+ if at is not None and at + 1 < len(kids):
124
+ nxt = kids[at + 1]
125
+ if nxt.kind in (";", "bsl:;") and nxt.buffer_range is not None and nxt.buffer_range[0] == rng[1]:
126
+ return rng[0], nxt.buffer_range[1]
127
+ return rng
128
+
129
+
130
+ def scope_of(node: Any) -> List[Any]:
131
+ """The sibling nodes one logical unit owns: a method with its leading comments and directives."""
132
+ parent = getattr(node, "parent", None)
133
+ if node.kind in METHOD_KINDS and parent is not None:
134
+ siblings = list(parent.children)
135
+ index = siblings.index(node)
136
+ first = index
137
+ while first > 0 and siblings[first - 1].kind in TRIVIA_KINDS:
138
+ first -= 1
139
+ return siblings[first: index + 1]
140
+ return [node]
141
+
142
+
143
+ def _start_of(src: bytes, nodes: Sequence[Any]) -> int:
144
+ a = _range(nodes[0])[0]
145
+ ls = _line_start(src, a)
146
+ return ls if _blank(src[ls:a]) and b"\n" not in src[ls:a] else a
147
+
148
+
149
+ def _end_of(src: bytes, nodes: Sequence[Any]) -> int:
150
+ b = _range(nodes[-1])[1]
151
+ le = _line_after(src, b)
152
+ return le if _blank(src[b:le]) else b
153
+
154
+
155
+ def line_extent(src: bytes, nodes: Sequence[Any]) -> Tuple[int, int]:
156
+ """The whole lines a run of sibling nodes occupies: start of the first line, after the last line ending.
157
+
158
+ A run that opens (closes) the module takes the blank lines before (after) it too, so that the text of
159
+ a module-level run is the same bytes whether or not a neighbour of it was deleted or inserted."""
160
+ start, end = _start_of(src, nodes), _end_of(src, nodes)
161
+ first, last = nodes[0], nodes[-1]
162
+ root = getattr(first, "parent", None)
163
+ if root is not None and root.kind == ROOT_KIND:
164
+ kids = list(root.children)
165
+ if kids and kids[0] is first and _blank(src[:start]):
166
+ start = 0
167
+ if kids and kids[-1] is last and _blank(src[end:]):
168
+ end = len(src)
169
+ return start, end
170
+
171
+
172
+ def _is_unit(node: Any) -> bool:
173
+ return (B.is_block(node) and not B.is_branch(node)) or node.kind in METHOD_KINDS
174
+
175
+
176
+ def involved(node: Any) -> bool:
177
+ """True when ``node`` is, or lies inside, a block, a branch or a method body (excluding the method itself)."""
178
+ current = node
179
+ while current is not None:
180
+ if B.is_block(current) or B.is_branch(current):
181
+ return True
182
+ parent = getattr(current, "parent", None)
183
+ if parent is not None and parent.kind in METHOD_KINDS:
184
+ return True
185
+ current = parent
186
+ return False
187
+
188
+
189
+ # -- insertion points -----------------------------------------------------------------------------
190
+
191
+
192
+ def _after_line(src: bytes, end: int) -> Tuple[int, bool]:
193
+ """Offset that starts the line after the one ``end`` lies on, and whether a line ending must be added."""
194
+ le = _line_after(src, end)
195
+ if _blank(src[end:le]):
196
+ return le, (le == len(src) and not src.endswith(b"\n"))
197
+ return end, True
198
+
199
+
200
+ def _head_end(node: Any) -> int:
201
+ return _range(node)[0] + len(str(node.fields.get(B.HEAD, "")).encode("utf-8"))
202
+
203
+
204
+ def _body(parent: Any) -> List[Any]:
205
+ if parent.kind in METHOD_KINDS:
206
+ return [c for c in parent.children if c.kind not in HEADER_KINDS and c.kind not in END_KINDS]
207
+ return list(parent.children)
208
+
209
+
210
+ def _method_header_end(parent: Any) -> int:
211
+ ends = [_range(c)[1] for c in parent.children if c.kind in HEADER_KINDS]
212
+ if not ends:
213
+ raise BlockEditError("the method has no header")
214
+ return max(ends)
215
+
216
+
217
+ def _branching(parent: Any) -> bool:
218
+ return B.is_block(parent) and parent.fields.get(B.BLOCK_KIND) in ("conditional", "if", "try")
219
+
220
+
221
+ def _insertion_offset(
222
+ src: bytes, position: str, parent: Any, sibling: Any, index: Optional[int]
223
+ ) -> Tuple[int, bool, Any]:
224
+ """Where new lines go. Returns ``(offset, needs_leading_line_ending, container)``."""
225
+ if sibling is not None:
226
+ owner = sibling.parent
227
+ if position == "before":
228
+ if B.is_branch(sibling) and owner is not None and owner.children and owner.children[0] is sibling:
229
+ raise BlockEditError("nothing can be inserted before the first branch of a block")
230
+ return _start_of(src, scope_of(sibling)), False, owner
231
+ if position == "after":
232
+ offset, lead = _after_line(src, _range(sibling)[1])
233
+ return offset, lead, owner
234
+ raise BlockEditError(f"unsupported sibling position {position!r}")
235
+ if parent is None:
236
+ raise BlockEditError("insert needs a parent or a sibling")
237
+ if position == "child_index":
238
+ body = _body(parent) if parent.kind != ROOT_KIND else list(parent.children)
239
+ if index is None:
240
+ raise BlockEditError("child_index needs an index")
241
+ if 0 <= index < len(body):
242
+ return _insertion_offset(src, "before", None, body[index], None) if not (
243
+ B.is_branch(body[index]) and index == 0
244
+ ) else (_start_of(src, [body[index]]), False, parent)
245
+ position = "last_child"
246
+ if _branching(parent):
247
+ kids = list(parent.children)
248
+ if not kids:
249
+ raise BlockEditError("the block has no branch")
250
+ target = kids[0] if position == "first_child" else kids[-1]
251
+ return _insertion_offset(src, position, target, None, None)
252
+ if parent.kind == ROOT_KIND:
253
+ kids = list(parent.children)
254
+ if position == "first_child":
255
+ return (_start_of(src, scope_of(kids[0])) if kids else 0), False, parent
256
+ return len(src), bool(src) and not src.endswith(b"\n"), parent
257
+ if parent.kind in METHOD_KINDS:
258
+ body = _body(parent)
259
+ if position == "first_child":
260
+ if body:
261
+ return _start_of(src, scope_of(body[0])), False, parent
262
+ offset, lead = _after_line(src, _method_header_end(parent))
263
+ return offset, lead, parent
264
+ end_kw = next((c for c in reversed(parent.children) if c.kind in END_KINDS), None)
265
+ if end_kw is None:
266
+ raise BlockEditError("the method has no closing keyword")
267
+ return _start_of(src, [end_kw]), False, parent
268
+ body = _body(parent)
269
+ if position == "first_child":
270
+ if body:
271
+ return _start_of(src, scope_of(body[0])), False, parent
272
+ offset, lead = _after_line(src, _head_end(parent))
273
+ return offset, lead, parent
274
+ if position == "last_child":
275
+ if body:
276
+ offset, lead = _after_line(src, _range(body[-1])[1])
277
+ return offset, lead, parent
278
+ offset, lead = _after_line(src, _head_end(parent))
279
+ return offset, lead, parent
280
+ raise BlockEditError(f"unsupported insert position {position!r}")
281
+
282
+
283
+ def _insert_data(src: bytes, content: bytes, offset: int, lead: bool) -> bytes:
284
+ eol = eol_of(src, offset)
285
+ body = _normalize_eol(content, eol)
286
+ if body.endswith(b"\r\n"):
287
+ body = body[:-2]
288
+ elif body.endswith(b"\n"):
289
+ body = body[:-1]
290
+ at_end = offset >= len(src)
291
+ return (eol if lead else b"") + body + (b"" if (lead and at_end) else eol)
292
+
293
+
294
+ # -- plans -----------------------------------------------------------------------------------------
295
+
296
+
297
+ def plan_insert(
298
+ src: bytes, content: bytes, position: str, parent: Any, sibling: Any, index: Optional[int] = None
299
+ ) -> Plan:
300
+ """Insert ``content`` as whole lines at the position (first / last child of a body, before / after a node)."""
301
+ offset, lead, container = _insertion_offset(src, position, parent, sibling, index)
302
+ return Plan([Splice(offset, offset, _insert_data(src, content, offset, lead))], container, "insert")
303
+
304
+
305
+ def _remove_lines(src: bytes, nodes: Sequence[Any]) -> Splice:
306
+ a, b = line_extent(src, nodes)
307
+ return Splice(a, b, b"")
308
+
309
+
310
+ def plan_delete(src: bytes, targets: Sequence[Any]) -> Plan:
311
+ """Delete whole lines; a branch is deleted by rule D (D-CF.2, D-CF.3)."""
312
+ targets = list(targets)
313
+ if len(targets) == 1 and B.is_branch(targets[0]):
314
+ return _plan_delete_branch(src, targets[0])
315
+ nodes = scope_of(targets[0]) if len(targets) == 1 else targets
316
+ return Plan([_remove_lines(src, nodes)], targets[0].parent, "delete", targets=nodes)
317
+
318
+
319
+ def _plan_delete_branch(src: bytes, branch: Any) -> Plan:
320
+ block = branch.parent
321
+ branches = list(block.children)
322
+ index = branches.index(branch)
323
+ if len(branches) == 1:
324
+ return Plan([_remove_lines(src, scope_of(block))], block.parent, "delete", targets=[block])
325
+ block_kind = block.fields.get(B.BLOCK_KIND)
326
+ removal = _remove_lines(src, [branch])
327
+ if index == 0 and block_kind in ("conditional", "if"):
328
+ following = branches[1]
329
+ kind = following.fields.get(B.BRANCH_KIND)
330
+ if kind == "elsif":
331
+ # Rule D: the next branch becomes the first; its keyword alone takes the removed head's spelling.
332
+ old_kw = B.leading_keyword(str(following.fields.get(B.HEAD, "")))
333
+ new_kw = B.leading_keyword(str(branch.fields.get(B.HEAD, "")))
334
+ start = _range(following)[0]
335
+ keyword = Splice(start, start + len(old_kw.encode("utf-8")), new_kw.encode("utf-8"))
336
+ return Plan([removal, keyword], block, "delete", targets=[branch])
337
+ if kind == "else":
338
+ body = list(following.children)
339
+ if not body:
340
+ return Plan([_remove_lines(src, scope_of(block))], block.parent, "delete", targets=[block])
341
+ a, b = line_extent(src, body)
342
+ lo, hi = line_extent(src, scope_of(block))
343
+ return Plan([Splice(lo, hi, src[a:b])], block.parent, "delete", targets=[block])
344
+ if index == 0 and block_kind == "try":
345
+ # D-CJ (owner BSL-Q4): deleting the head of Попытка removes the Исключение part and keeps the
346
+ # Попытка body as plain statements in the parent: the block is unwrapped.
347
+ body = list(branch.children)
348
+ lo, hi = line_extent(src, scope_of(block))
349
+ if not body:
350
+ return Plan([Splice(lo, hi, b"")], block.parent, "delete", targets=[block])
351
+ a, b = line_extent(src, body)
352
+ return Plan([Splice(lo, hi, src[a:b])], block.parent, "delete", targets=[block])
353
+ return Plan([removal], block, "delete", targets=[branch])
354
+
355
+
356
+ def plan_replace(src: bytes, targets: Sequence[Any], content: bytes) -> Plan:
357
+ """Replace whole lines of the target run with ``content`` (a trailing line ending is kept)."""
358
+ targets = list(targets)
359
+ nodes = scope_of(targets[0]) if len(targets) == 1 else targets
360
+ a, b = line_extent(src, nodes)
361
+ data = _normalize_eol(content, eol_of(src, a))
362
+ if src[a:b].endswith(b"\n") and not data.endswith(b"\n"):
363
+ data += eol_of(src, a)
364
+ return Plan([Splice(a, b, data)], targets[0].parent, "replace", targets=nodes)
365
+
366
+
367
+ def plan_move(
368
+ src: bytes, targets: Sequence[Any], position: str, parent: Any, sibling: Any, index: Optional[int] = None
369
+ ) -> Optional[Plan]:
370
+ """Move whole lines of the target run to the position; ``None`` when nothing would change."""
371
+ targets = list(targets)
372
+ if any(B.is_branch(t) for t in targets):
373
+ raise BlockEditError("a single branch is not movable alone")
374
+ nodes = scope_of(targets[0]) if len(targets) == 1 else targets
375
+ if len(targets) == 1 and targets[0].kind in METHOD_KINDS and getattr(targets[0].parent, "kind", None) == ROOT_KIND:
376
+ return _plan_move_method(src, targets[0], nodes, position, parent, sibling, index)
377
+ a, b = line_extent(src, nodes)
378
+ text = src[a:b]
379
+ eol = eol_of(src, a)
380
+ if not text.endswith(b"\n"):
381
+ text += eol
382
+ offset, lead, dest_container = _insertion_offset(src, position, parent, sibling, index)
383
+ if a < offset < b:
384
+ raise BlockEditError("a node cannot be moved into itself")
385
+ if offset in (a, b):
386
+ return None
387
+ data = _insert_data(src, text, offset, lead)
388
+ plan = Plan([Splice(a, b, b""), Splice(offset, offset, data)], targets[0].parent, "move", targets=nodes)
389
+ plan.extra_containers = [dest_container]
390
+ return plan
391
+
392
+
393
+ def _plan_move_method(
394
+ src: bytes, method: Any, nodes: Sequence[Any], position: str, parent: Any, sibling: Any, index: Optional[int]
395
+ ) -> Optional[Plan]:
396
+ """Move a module-level method with its leading comments and directives; the blank separator travels with it.
397
+
398
+ The method's lines (without the blank lines around them) are cut out together with the blank run that follows
399
+ them (the preceding run when it is the last method) and put back with one blank line between them and the
400
+ neighbour, so the module keeps its blank lines and its trailing line ending (bug 94822248)."""
401
+ start, end = _start_of(src, nodes), _end_of(src, nodes)
402
+ eol = eol_of(src, start)
403
+ text = src[start:end]
404
+ if not text.endswith(b"\n"):
405
+ text += eol
406
+ a, b = start, end
407
+ kids = list(method.parent.children)
408
+ if kids[-1] is nodes[-1]:
409
+ while a > 0 and _blank(src[_line_start(src, a - 1):a]):
410
+ a = _line_start(src, a - 1)
411
+ else:
412
+ while b < len(src) and _blank(src[b:_line_after(src, b)]):
413
+ b = _line_after(src, b)
414
+ offset, lead, container = _insertion_offset(src, position, parent, sibling, index)
415
+ if a < offset < b:
416
+ raise BlockEditError("a node cannot be moved into itself")
417
+ if sibling is not None and position == "before":
418
+ data = text + eol
419
+ elif sibling is not None or position == "last_child":
420
+ # after a neighbour: one blank line, then the method (the text already ends with its line ending)
421
+ data = (eol if lead else b"") + eol + text
422
+ else:
423
+ data = text + eol
424
+ if a <= offset <= b:
425
+ return None
426
+ plan = Plan([Splice(a, b, b""), Splice(offset, offset, data)], method.parent, "move", targets=list(nodes))
427
+ plan.extra_containers = [container]
428
+ return plan
429
+
430
+
431
+ def plan_attribute(src: bytes, node: Any, name: str, value: Any) -> Plan:
432
+ """Edit the ``head`` or the ``condition`` of a block or branch; the children are kept."""
433
+ if not (B.is_block(node) or B.is_branch(node)):
434
+ raise BlockEditError("only a block or a branch has editable head and condition")
435
+ if not isinstance(value, str) or "\n" in value:
436
+ raise BlockEditError(f"{name} must be a single-line string")
437
+ head = str(node.fields.get(B.HEAD, ""))
438
+ start = _range(node)[0]
439
+ if name == B.HEAD:
440
+ new_head = value
441
+ elif name == B.CONDITION:
442
+ span = B.condition_span(head) if B.is_branch(node) else None
443
+ if span is None:
444
+ raise BlockEditError("this node has no condition")
445
+ new_head = head[: span[0]] + value + head[span[1]:]
446
+ else:
447
+ raise BlockEditError(f"{name!r} is not an editable attribute of a block or a branch")
448
+ end = start + len(head.encode("utf-8"))
449
+ return Plan([Splice(start, end, new_head.encode("utf-8"))], node, "attribute", targets=[node])
@@ -0,0 +1,127 @@
1
+ """Block vocabulary of the BSL plugin (TODO f166b8c9 D-CE, D-CF).
2
+
3
+ Paired preprocessor directives and the language control structures are
4
+ exposed as *block* nodes: a container holding ordered *branch* nodes (a
5
+ conditional or ``Попытка``) or directly its statements (a loop, a region, an
6
+ insertion, a deletion). The closing line belongs to the block's own text and
7
+ is never a node.
8
+
9
+ This module holds only the pure vocabulary shared by the import map and the
10
+ engine edit layer: the keyword tables of both dialects and the helpers that
11
+ read a directive or a block head. It imports nothing from the plugin.
12
+
13
+ Author: Vasiliy Zdanovskiy
14
+ email: vasilyvz@gmail.com
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import re
20
+ from typing import Optional, Tuple
21
+
22
+ __all__ = [
23
+ "BLOCK_KIND",
24
+ "BRANCH_KIND",
25
+ "HEAD",
26
+ "CONDITION",
27
+ "BLOCK_KEYS",
28
+ "PREPROC_KIND",
29
+ "LANGUAGE_BLOCK_KINDS",
30
+ "classify_directive",
31
+ "leading_keyword",
32
+ "is_block",
33
+ "is_branch",
34
+ "condition_span",
35
+ ]
36
+
37
+ BLOCK_KIND = "block_kind"
38
+ BRANCH_KIND = "branch_kind"
39
+ HEAD = "head"
40
+ CONDITION = "condition"
41
+ BLOCK_KEYS = (BLOCK_KIND, BRANCH_KIND, HEAD, CONDITION)
42
+
43
+ #: The kind of a paired-directive block or branch (the node type stays ``PreprocessorDirective``).
44
+ PREPROC_KIND = "core:preprocessor_directive"
45
+
46
+ #: tree-sitter statement types that become a language block, with their ``block_kind``.
47
+ LANGUAGE_BLOCK_KINDS = {
48
+ "if_statement": "if",
49
+ "for_statement": "for",
50
+ "for_each_statement": "foreach",
51
+ "while_statement": "while",
52
+ "try_statement": "try",
53
+ }
54
+
55
+ _OPEN = {
56
+ "если": "conditional", "if": "conditional",
57
+ "область": "region", "region": "region",
58
+ "вставка": "insertion", "insert": "insertion",
59
+ "удаление": "deletion", "delete": "deletion",
60
+ }
61
+ _BRANCH = {"иначеесли": "elsif", "elsif": "elsif", "иначе": "else", "else": "else"}
62
+ _CLOSE = {
63
+ "конецесли": "conditional", "endif": "conditional",
64
+ "конецобласти": "region", "endregion": "region",
65
+ "конецвставки": "insertion", "endinsert": "insertion",
66
+ "конецудаления": "deletion", "enddelete": "deletion",
67
+ }
68
+ _WORD = re.compile(r"#[ \t]*(\w+)")
69
+ _KEYWORD = re.compile(r"#?\w+")
70
+
71
+
72
+ def classify_directive(text: str) -> Optional[Tuple[str, str]]:
73
+ """Classify one preprocessor directive line.
74
+
75
+ Returns:
76
+ ``("open", block_kind)``, ``("branch", branch_kind)`` or ``("close", block_kind)``;
77
+ ``None`` for any other ``#`` line.
78
+ """
79
+ match = _WORD.match(text.lstrip())
80
+ if match is None:
81
+ return None
82
+ word = match.group(1).casefold()
83
+ if word in _OPEN:
84
+ return "open", _OPEN[word]
85
+ if word in _BRANCH:
86
+ return "branch", _BRANCH[word]
87
+ if word in _CLOSE:
88
+ return "close", _CLOSE[word]
89
+ return None
90
+
91
+
92
+ def leading_keyword(head: str) -> str:
93
+ """The opener or branch keyword token of a head, spelling and case as written.
94
+
95
+ ``#ИначеЕсли Б Тогда`` -> ``#ИначеЕсли``; ``elsif B Then`` -> ``elsif``.
96
+ """
97
+ match = _KEYWORD.match(head)
98
+ return match.group(0) if match else ""
99
+
100
+
101
+ def is_block(node: object) -> bool:
102
+ """True for a node carrying ``block_kind``."""
103
+ fields = getattr(node, "fields", None)
104
+ return isinstance(fields, dict) and fields.get(BLOCK_KIND) is not None
105
+
106
+
107
+ def is_branch(node: object) -> bool:
108
+ """True for a node carrying ``branch_kind``."""
109
+ fields = getattr(node, "fields", None)
110
+ return isinstance(fields, dict) and fields.get(BRANCH_KIND) is not None
111
+
112
+
113
+ def condition_span(head: str) -> Optional[Tuple[int, int]]:
114
+ """Character span of the condition inside a branch head, or ``None`` for a head without one.
115
+
116
+ The head is ``<keyword> <condition> <then-keyword>``; the span runs from the first
117
+ non-blank character after the keyword to the end of the condition (the text before the last word).
118
+ """
119
+ keyword = leading_keyword(head)
120
+ if not keyword:
121
+ return None
122
+ words = list(re.finditer(r"\S+", head))
123
+ if len(words) < 3:
124
+ return None
125
+ start = words[1].start()
126
+ end = words[-2].end()
127
+ return (start, end) if start < end else None