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,369 @@
1
+ """Shared statement-splitting model of the ``sql`` and ``onec_query`` format plugins (matrix D-CD).
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+
6
+ A query file is a ``<format>:document`` root with one ``<format>:statement`` child per statement, in file
7
+ order. A statement ends at the first ``;`` that is not protected by a comment, a quoted construct or (SQL)
8
+ a dollar quote. Its ``raw`` field holds its exact text: leading trivia (blank and comment lines), the body
9
+ and the ``;``, then the rest of that line when it is only blanks, with its line terminator. Text after the
10
+ last ``;`` that holds more than whitespace and comments is a last statement without ``;``; trivia only
11
+ becomes the document's ``tail``. A leading byte order mark is kept on the document in ``bom``. Rendering
12
+ replays these fields, so ``dumps(loads(x)) == x`` for every input, and parsing can never fail, so no input
13
+ ever triggers the plain-text fallback.
14
+
15
+ The scanner is linear in the size of the text: it jumps from token to token with ``str.find`` and one
16
+ compiled pattern, never character by character.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import re
22
+ from dataclasses import dataclass, replace
23
+ from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union
24
+ from uuid import UUID
25
+
26
+ from tree_engine.core.identity import generate_node_id
27
+ from tree_engine.core.nodes import Document, Node, make_node
28
+ from tree_engine.core.plugin_boundary import FormatBoundary
29
+ from tree_engine.exceptions import (
30
+ FormatContentParseFailed,
31
+ FormatFragmentParseFailed,
32
+ FormatPluginContractError,
33
+ UnsupportedTranslation,
34
+ )
35
+ from tree_engine.plugins.contract import FormatPluginContract, FormatPluginMetadata, SemanticRoleMapping
36
+
37
+ __all__ = ["Dialect", "Unterminated", "split_statements", "find_unterminated", "StatementFormatPlugin"]
38
+
39
+ _BOM = "\ufeff"
40
+ _ROLE_MAP = SemanticRoleMapping({})
41
+ _Source = Union[str, bytes]
42
+ _DOLLAR = re.compile(r"\$([A-Za-z_\u0080-￿][A-Za-z0-9_\u0080-￿]*)?\$")
43
+ _IDENT_CHAR = re.compile(r"[A-Za-z0-9_\u0080-￿]")
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class Dialect:
48
+ """What protects a ``;``: line comment mark, block comments, quote characters and dollar quoting."""
49
+
50
+ line_comment: str
51
+ block_comment: bool
52
+ #: (quote character, what an unterminated one is called), e.g. ``("'", "string literal")``.
53
+ quotes: Tuple[Tuple[str, str], ...]
54
+ dollar_quote: bool
55
+
56
+ def pattern(self) -> "re.Pattern[str]":
57
+ parts = [re.escape(self.line_comment)]
58
+ if self.block_comment:
59
+ parts.append(re.escape("/*"))
60
+ parts.append("[" + re.escape("".join(q for q, _ in self.quotes)) + "]")
61
+ parts.append(";")
62
+ if self.dollar_quote:
63
+ parts.append(r"\$")
64
+ return re.compile("|".join(parts))
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class Unterminated:
69
+ """The opening of an unterminated construct: 0-based offset, what it is."""
70
+
71
+ offset: int
72
+ what: str
73
+
74
+
75
+ _PATTERNS: Dict[Dialect, "re.Pattern[str]"] = {}
76
+
77
+
78
+ def _pattern(dialect: Dialect) -> "re.Pattern[str]":
79
+ found = _PATTERNS.get(dialect)
80
+ if found is None:
81
+ found = _PATTERNS[dialect] = dialect.pattern()
82
+ return found
83
+
84
+
85
+ def _skip_quoted(text: str, pos: int, quote: str) -> int:
86
+ """Offset after the closing ``quote`` of the construct opened at ``pos``; ``-1`` when it never closes.
87
+ A doubled quote is an escaped quote and stays inside."""
88
+ i = pos + 1
89
+ while True:
90
+ j = text.find(quote, i)
91
+ if j < 0:
92
+ return -1
93
+ if text.startswith(quote, j + 1):
94
+ i = j + 2
95
+ continue
96
+ return j + 1
97
+
98
+
99
+ def _scan(text: str, dialect: Dialect, stop_at_statement: bool, start: int = 0) -> Tuple[int, Optional[Unterminated]]:
100
+ """Scan from ``start``. With ``stop_at_statement`` return (offset after the first unprotected ``;``, None),
101
+ or (-1, None) when there is none. Otherwise scan to the end and return (-1, the first unterminated construct)."""
102
+ pattern = _pattern(dialect)
103
+ pos = start
104
+ size = len(text)
105
+ while pos < size:
106
+ match = pattern.search(text, pos)
107
+ if match is None:
108
+ return -1, None
109
+ token = match.group()
110
+ at = match.start()
111
+ if token == ";":
112
+ if stop_at_statement:
113
+ return at + 1, None
114
+ pos = at + 1
115
+ elif token == dialect.line_comment:
116
+ end = len(text)
117
+ for eol in ("\n", "\r"):
118
+ k = text.find(eol, at)
119
+ if 0 <= k < end:
120
+ end = k
121
+ pos = end
122
+ elif token == "/*":
123
+ k = text.find("*/", at + 2)
124
+ if k < 0:
125
+ return -1, Unterminated(at, "block comment")
126
+ pos = k + 2
127
+ elif token == "$":
128
+ m = _DOLLAR.match(text, at)
129
+ if m is None or (at > 0 and _IDENT_CHAR.match(text[at - 1])):
130
+ pos = at + 1
131
+ continue
132
+ k = text.find(m.group(), m.end())
133
+ if k < 0:
134
+ return -1, Unterminated(at, "dollar-quoted string")
135
+ pos = k + len(m.group())
136
+ else:
137
+ end = _skip_quoted(text, at, token)
138
+ if end < 0:
139
+ what = dict(dialect.quotes)[token]
140
+ return -1, Unterminated(at, what)
141
+ pos = end
142
+ return -1, None
143
+
144
+
145
+ def find_unterminated(text: str, dialect: Dialect) -> Optional[Unterminated]:
146
+ """The first construct (string, quoted identifier, block comment, dollar quote) that never closes."""
147
+ return _scan(text, dialect, False)[1]
148
+
149
+
150
+ def _end_of_line(text: str, pos: int) -> int:
151
+ """After a statement's ``;``: take the rest of the line when it is only blanks, with one terminator."""
152
+ size = len(text)
153
+ i = pos
154
+ while i < size and text[i] in " \t":
155
+ i += 1
156
+ if i >= size:
157
+ return i
158
+ if text.startswith("\r\n", i):
159
+ return i + 2
160
+ if text[i] in "\r\n":
161
+ return i + 1
162
+ return pos
163
+
164
+
165
+ def _only_trivia(text: str, dialect: Dialect) -> bool:
166
+ """True when ``text`` is whitespace and complete comments only."""
167
+ pos, size = 0, len(text)
168
+ while pos < size:
169
+ if text[pos].isspace():
170
+ pos += 1
171
+ continue
172
+ if text.startswith(dialect.line_comment, pos):
173
+ ends = [k for k in (text.find("\n", pos), text.find("\r", pos)) if k >= 0]
174
+ pos = min(ends) if ends else size
175
+ continue
176
+ if dialect.block_comment and text.startswith("/*", pos):
177
+ k = text.find("*/", pos + 2)
178
+ if k < 0:
179
+ return False
180
+ pos = k + 2
181
+ continue
182
+ return False
183
+ return True
184
+
185
+
186
+ def split_statements(text: str, dialect: Dialect) -> Tuple[List[str], str]:
187
+ """(statement texts, trailing trivia). ``"".join(statements) + tail == text``."""
188
+ statements: List[str] = []
189
+ pos, size = 0, len(text)
190
+ while pos < size:
191
+ end, _ = _scan(text, dialect, True, pos)
192
+ if end < 0:
193
+ rest = text[pos:]
194
+ if _only_trivia(rest, dialect):
195
+ return statements, rest
196
+ statements.append(rest)
197
+ return statements, ""
198
+ end = _end_of_line(text, end)
199
+ statements.append(text[pos:end])
200
+ pos = end
201
+ return statements, ""
202
+
203
+
204
+ def _contract_error(message: str, format_id: str) -> FormatPluginContractError:
205
+ return FormatPluginContractError(message, plugin_id=format_id)
206
+
207
+
208
+ def _make(kind: str, fields: Mapping[str, Any], children: Sequence[Node] = ()) -> Node:
209
+ return replace(
210
+ make_node(kind, fields=dict(fields), children=tuple(children)),
211
+ node_id=generate_node_id(),
212
+ short_id=None,
213
+ )
214
+
215
+
216
+ class StatementFormatPlugin(FormatPluginContract, FormatBoundary):
217
+ """Lossless statement-list format plugin; a subclass supplies ``FORMAT_ID``, ``DIALECT`` and metadata."""
218
+
219
+ FORMAT_ID = ""
220
+ DIALECT: Dialect
221
+ _META: FormatPluginMetadata
222
+ #: Every node gets a compact id under ``semantic_compact_ids`` (read by ``facade._semantic_short_id_order``).
223
+ all_nodes_compact_ids = True
224
+
225
+ @property
226
+ def metadata(self) -> FormatPluginMetadata:
227
+ return self._META
228
+
229
+ @property
230
+ def _doc_kind(self) -> str:
231
+ return f"{self.FORMAT_ID}:document"
232
+
233
+ @property
234
+ def _stmt_kind(self) -> str:
235
+ return f"{self.FORMAT_ID}:statement"
236
+
237
+ def _decode(self, source: _Source, label: str, error: type) -> str:
238
+ if isinstance(source, str):
239
+ return source
240
+ if isinstance(source, (bytes, bytearray)):
241
+ try:
242
+ return bytes(source).decode("utf-8")
243
+ except UnicodeDecodeError as exc:
244
+ raise error(f"cannot decode {self.FORMAT_ID}: {exc}", format_id=self.FORMAT_ID) from exc
245
+ raise _contract_error(f"{label} must be str or bytes, got {type(source).__name__}", self.FORMAT_ID)
246
+
247
+ def _statements(self, text: str) -> Tuple[List[Node], str]:
248
+ texts, tail = split_statements(text, self.DIALECT)
249
+ return [_make(self._stmt_kind, {"raw": t}) for t in texts], tail
250
+
251
+ def parse_document(
252
+ self,
253
+ source: _Source,
254
+ options: Optional[Mapping[str, Any]] = None,
255
+ *,
256
+ source_format_id: Optional[str] = None,
257
+ ) -> Document:
258
+ del options, source_format_id
259
+ text = self._decode(source, "source", FormatContentParseFailed)
260
+ fields: Dict[str, Any] = {}
261
+ if text.startswith(_BOM):
262
+ fields["bom"] = _BOM
263
+ text = text[1:]
264
+ children, tail = self._statements(text)
265
+ if tail:
266
+ fields["tail"] = tail
267
+ return Document(root=_make(self._doc_kind, fields, children), source_format_id=self.FORMAT_ID)
268
+
269
+ def parse_fragment(
270
+ self,
271
+ source: _Source,
272
+ options: Optional[Mapping[str, Any]] = None,
273
+ *,
274
+ source_format_id: Optional[str] = None,
275
+ ) -> Union[Node, List[Node]]:
276
+ """A fragment is one or more statements; text after the last ``;`` is a statement of its own."""
277
+ del options, source_format_id
278
+ text = self._decode(source, "fragment", FormatFragmentParseFailed)
279
+ children, tail = self._statements(text)
280
+ if tail:
281
+ children.append(_make(self._stmt_kind, {"raw": tail}))
282
+ if not children:
283
+ raise FormatFragmentParseFailed(
284
+ f"a {self.FORMAT_ID} fragment must hold at least one statement", format_id=self.FORMAT_ID
285
+ )
286
+ return children[0] if len(children) == 1 else children
287
+
288
+ def _render(self, node: Node) -> str:
289
+ kind = str(node.kind)
290
+ if kind == self._doc_kind:
291
+ bom = node.fields.get("bom")
292
+ tail = node.fields.get("tail")
293
+ body = "".join(self._render(child) for child in node.children)
294
+ return (bom if isinstance(bom, str) else "") + body + (tail if isinstance(tail, str) else "")
295
+ if kind == self._stmt_kind:
296
+ raw = node.fields.get("raw")
297
+ return raw if isinstance(raw, str) else ""
298
+ raise UnsupportedTranslation(
299
+ f"node kind {kind!r} has no {self.FORMAT_ID} form", node_type=kind, format_id=self.FORMAT_ID
300
+ )
301
+
302
+ def import_external_tree(
303
+ self, external_tree: Any, options: Optional[Mapping[str, Any]] = None
304
+ ) -> Union[Node, Document]:
305
+ return self.import_to_common(external_tree, options)
306
+
307
+ def import_to_common(
308
+ self, external_representation: Any, options: Optional[Mapping[str, Any]] = None
309
+ ) -> Union[Node, Document]:
310
+ del options
311
+ if isinstance(external_representation, (str, bytes, bytearray)):
312
+ return self.parse_document(external_representation)
313
+ raise UnsupportedTranslation(
314
+ f"expected {self.FORMAT_ID} source text",
315
+ node_type=type(external_representation).__name__,
316
+ format_id=self.FORMAT_ID,
317
+ )
318
+
319
+ def export_from_common(
320
+ self, nodes: Union[Node, Document], options: Optional[Mapping[str, Any]] = None
321
+ ) -> Any:
322
+ del options
323
+ if not isinstance(nodes, (Node, Document)):
324
+ raise _contract_error(f"expected Node or Document, got {type(nodes).__name__}", self.FORMAT_ID)
325
+ return self._render(nodes.root if isinstance(nodes, Document) else nodes)
326
+
327
+ def generate_output(
328
+ self, target: Union[Node, Document, Any], options: Optional[Mapping[str, Any]] = None
329
+ ) -> Union[str, bytes]:
330
+ options = options or {}
331
+ if isinstance(target, (Node, Document)):
332
+ text = self._render(target.root if isinstance(target, Document) else target)
333
+ elif isinstance(target, str):
334
+ text = target
335
+ else:
336
+ raise _contract_error(
337
+ f"cannot render {type(target).__name__}; expected Node/Document/str", self.FORMAT_ID
338
+ )
339
+ return text.encode("utf-8") if options.get("as_bytes") else text
340
+
341
+ def semantic_role_mapping(self) -> SemanticRoleMapping:
342
+ return _ROLE_MAP
343
+
344
+ def nodes_at_line(self, document: Any, line: int) -> List[Tuple[Any, Tuple[int, int]]]:
345
+ """Nodes covering ``line`` with their ``(first, last)`` lines, from the live tree: a statement keeps
346
+ its exact text in ``raw`` and no byte offsets (bug f840eb52). Editor hook (D-CB.2)."""
347
+ from tree_engine.query.rendered_lines import break_count, covering_nodes, span_from
348
+
349
+ root = document.root
350
+ entries: List[Tuple[Any, Tuple[int, int], int]] = []
351
+ cursor = 1
352
+ for child in root.children:
353
+ text = self._render(child)
354
+ entries.append((child, span_from(text, cursor), 1))
355
+ cursor += break_count(text)
356
+ entries.append((root, span_from(self._render(root), 1), 0))
357
+ return covering_nodes(line, entries)
358
+
359
+ def render_document(self, document: Document) -> bytes:
360
+ result = self.generate_output(document, {"as_bytes": True})
361
+ if not isinstance(result, bytes):
362
+ raise _contract_error("render_document did not return bytes", self.FORMAT_ID)
363
+ return result
364
+
365
+ def render_fragment(self, node: Node) -> str:
366
+ result = self.generate_output(node)
367
+ if not isinstance(result, str):
368
+ raise _contract_error("render_fragment did not return str", self.FORMAT_ID)
369
+ return result