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,911 @@
1
+ """Lossless XML format plugin for the tree engine.
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+
6
+ Rule of the XML format contract (matrix decision D-AD):
7
+
8
+ * a ``.xml`` file is a structural tree: the document, every element (tag name and attributes),
9
+ text, CDATA, comments, processing instructions, the XML declaration and the DOCTYPE;
10
+ * the tree is lossless: every node keeps the exact source slice it was read from, so parsing and
11
+ rendering with no edit returns every byte (whitespace, attribute order and quoting, entities,
12
+ line ends);
13
+ * an edit changes only the edited node: an element keeps its start tag (``start_raw``) and end tag
14
+ (``end_raw``) verbatim and its children render in place; an attribute edit rewrites only the one
15
+ attribute value inside the start tag (:func:`apply_attribute_edit`);
16
+ * a source that is not well-formed XML is refused at parse time with
17
+ ``FormatContentParseFailed`` (the caller falls back to the full text tree), and a fragment that
18
+ is not well-formed content with ``FormatFragmentParseFailed``.
19
+
20
+ Node kinds: ``xml:Document``, ``xml:Element``, ``xml:Text``, ``xml:CData``, ``xml:Comment``,
21
+ ``xml:ProcessingInstruction``, ``xml:Declaration``, ``xml:Doctype``. Leaves carry ``raw`` (the
22
+ exact source slice) and ``value`` (the decoded data); an element carries ``name``, ``start_raw``,
23
+ ``end_raw`` (empty for a self-closing element) and ``self_closing``.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import re
29
+ from dataclasses import replace
30
+ from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union
31
+ from xml.parsers import expat
32
+
33
+ from tree_engine.core.identity import generate_node_id
34
+ from tree_engine.core.nodes import Document, Node, make_node
35
+ from tree_engine.core.plugin_boundary import FormatBoundary
36
+ from tree_engine.core.short_id import ShortIdMap
37
+ from tree_engine.plugins.parse_position import line_column
38
+ from tree_engine.exceptions import (
39
+ FormatContentParseFailed,
40
+ FormatFragmentParseFailed,
41
+ FormatPluginContractError,
42
+ UnsupportedTranslation,
43
+ )
44
+ from tree_engine.plugins.contract import (
45
+ FormatPluginContract,
46
+ FormatPluginMetadata,
47
+ SemanticRoleMapping,
48
+ )
49
+
50
+ __all__ = [
51
+ "FORMAT_ID",
52
+ "KIND_DOCUMENT",
53
+ "KIND_ELEMENT",
54
+ "KIND_TEXT",
55
+ "KIND_CDATA",
56
+ "KIND_COMMENT",
57
+ "KIND_PI",
58
+ "KIND_DECLARATION",
59
+ "KIND_DOCTYPE",
60
+ "XmlFormatPlugin",
61
+ "XML_FORMAT_PLUGIN",
62
+ "apply_attribute_edit",
63
+ "element_attributes",
64
+ "check_well_formed",
65
+ "XML_NAMESPACE_URI",
66
+ "split_qualified_name",
67
+ "namespace_scope",
68
+ "describe_element",
69
+ "render_node",
70
+ "element_parts",
71
+ ]
72
+
73
+ FORMAT_ID = "xml"
74
+ KIND_DOCUMENT = "xml:Document"
75
+ KIND_ELEMENT = "xml:Element"
76
+ KIND_TEXT = "xml:Text"
77
+ KIND_CDATA = "xml:CData"
78
+ KIND_COMMENT = "xml:Comment"
79
+ KIND_PI = "xml:ProcessingInstruction"
80
+ KIND_DECLARATION = "xml:Declaration"
81
+ KIND_DOCTYPE = "xml:Doctype"
82
+
83
+ _LEAF_KINDS = frozenset(
84
+ {KIND_TEXT, KIND_CDATA, KIND_COMMENT, KIND_PI, KIND_DECLARATION, KIND_DOCTYPE}
85
+ )
86
+
87
+ _METADATA = FormatPluginMetadata(
88
+ format_id=FORMAT_ID,
89
+ aliases=(),
90
+ file_extensions=("xml",),
91
+ plugin_version="1.0.0",
92
+ contract_version="1.0.0",
93
+ capabilities={
94
+ # Whether the Code Analysis server can save a file of this format (decision D-CB.4); the editor reads it
95
+ # instead of keeping its own list of unsupported suffixes.
96
+ "ca_save_supported": True,
97
+ "semantic_role_mapping": True,
98
+ # Every node keeps its exact source slice; the unit tests round-trip declaration, DOCTYPE,
99
+ # comments, CDATA, processing instructions, entities, mixed quoting and CRLF byte for byte.
100
+ "byte_identical_round_trip": True,
101
+ "navigable": True,
102
+ "editable": True,
103
+ # An inserted or replaced fragment is taken exactly as given (no newline is added), and may come
104
+ # in the ``value`` field of an operation.
105
+ "exact_fragment_content": True,
106
+ },
107
+ )
108
+ _ROLE_MAP = SemanticRoleMapping({})
109
+ _Source = Union[str, bytes]
110
+
111
+ _NAME_RE = re.compile(r"[^\s/>=]+")
112
+ _ATTR_RE = re.compile(r"""([^\s=/>]+)(\s*=\s*)(?:"([^"]*)"|'([^']*)')""")
113
+ _ATTR_NAME_OK = re.compile(r"^[A-Za-z_:][A-Za-z0-9_.:\-]*$")
114
+ _ENTITY_RE = re.compile(r"&(#x[0-9A-Fa-f]+|#[0-9]+|amp|lt|gt|quot|apos);")
115
+ _PREDEFINED = {"amp": "&", "lt": "<", "gt": ">", "quot": '"', "apos": "'"}
116
+
117
+
118
+ def _contract_error(message: str) -> FormatPluginContractError:
119
+ return FormatPluginContractError(message, plugin_id=FORMAT_ID)
120
+
121
+
122
+ def _unsupported(kind: str, message: str) -> UnsupportedTranslation:
123
+ return UnsupportedTranslation(message, node_type=kind, format_id=FORMAT_ID)
124
+
125
+
126
+ # ---------------------------------------------------------------------------------------------
127
+ # Well-formedness
128
+ # ---------------------------------------------------------------------------------------------
129
+ def check_well_formed(text: str, namespaces: bool = True) -> Optional[str]:
130
+ """Return ``None`` when ``text`` is a well-formed XML document, else the parser's message.
131
+
132
+ The check is done by the standard library's expat parser over the UTF-8 bytes of ``text``
133
+ (the declared encoding is overridden, so a declaration cannot make the check read other
134
+ bytes). No external entity or DTD is fetched.
135
+
136
+ With ``namespaces`` (the default) the parser also applies the XML namespace rules: a prefix
137
+ that no declaration in scope binds (element or attribute) and two attributes that resolve to
138
+ the same expanded name are refused, on top of expat's own duplicate-attribute refusal. The
139
+ tree is built with ``namespaces=False`` so that a file with an undeclared prefix still opens
140
+ as a tree and can be repaired; the write check uses the strict form.
141
+ """
142
+ if namespaces:
143
+ parser = expat.ParserCreate(encoding="utf-8", namespace_separator=" ")
144
+ else:
145
+ parser = expat.ParserCreate(encoding="utf-8")
146
+ try:
147
+ parser.Parse(text.encode("utf-8"), True)
148
+ except expat.ExpatError as exc:
149
+ return (
150
+ f"{expat.ErrorString(exc.code)} at line {exc.lineno}, column {exc.offset}"
151
+ )
152
+ return None
153
+
154
+
155
+ _OFFSET_RE = re.compile(r"offset (\d+)")
156
+
157
+
158
+ def _offset_of(message: str) -> Optional[int]:
159
+ found = _OFFSET_RE.search(message)
160
+ return int(found.group(1)) if found else None
161
+
162
+
163
+ def well_formed_failure(text: str, namespaces: bool = True) -> Optional[Dict[str, Any]]:
164
+ """Like :func:`check_well_formed` but returns the structured failure or ``None``.
165
+
166
+ The mapping holds ``code`` (expat error number), ``line`` and ``column`` (both >= 1, as expat
167
+ reports them), ``message`` (expat's text) and ``text`` (the ``check_well_formed`` rendering).
168
+ """
169
+ if namespaces:
170
+ parser = expat.ParserCreate(encoding="utf-8", namespace_separator=" ")
171
+ else:
172
+ parser = expat.ParserCreate(encoding="utf-8")
173
+ try:
174
+ parser.Parse(text.encode("utf-8"), True)
175
+ except expat.ExpatError as exc:
176
+ message = expat.ErrorString(exc.code)
177
+ return {"code": exc.code, "line": max(1, exc.lineno), "column": max(1, exc.offset), "message": message,
178
+ "text": f"{message} at line {exc.lineno}, column {exc.offset}"}
179
+ return None
180
+
181
+
182
+ def _unescape(raw: str) -> str:
183
+ def one(match: "re.Match[str]") -> str:
184
+ token = match.group(1)
185
+ if token in _PREDEFINED:
186
+ return _PREDEFINED[token]
187
+ try:
188
+ if token.startswith("#x"):
189
+ return chr(int(token[2:], 16))
190
+ return chr(int(token[1:]))
191
+ except (ValueError, OverflowError):
192
+ return match.group(0)
193
+
194
+ return _ENTITY_RE.sub(one, raw)
195
+
196
+
197
+ def _escape_attr(value: str, quote: str) -> str:
198
+ out = value.replace("&", "&amp;").replace("<", "&lt;")
199
+ return out.replace(quote, "&quot;" if quote == '"' else "&apos;")
200
+
201
+
202
+ # ---------------------------------------------------------------------------------------------
203
+ # Tokenizer: splits source text into lossless tokens
204
+ # ---------------------------------------------------------------------------------------------
205
+ class _Token:
206
+ __slots__ = ("kind", "raw")
207
+
208
+ def __init__(self, kind: str, raw: str) -> None:
209
+ self.kind = kind
210
+ self.raw = raw
211
+
212
+
213
+ _START = "start"
214
+ _END = "end"
215
+
216
+
217
+ def _find_tag_end(text: str, start: int) -> int:
218
+ """Index just past the ``>`` closing the tag that starts at ``start`` (quotes respected)."""
219
+ quote = ""
220
+ i = start + 1
221
+ n = len(text)
222
+ while i < n:
223
+ ch = text[i]
224
+ if quote:
225
+ if ch == quote:
226
+ quote = ""
227
+ elif ch in "\"'":
228
+ quote = ch
229
+ elif ch == ">":
230
+ return i + 1
231
+ i += 1
232
+ raise ValueError(f"unterminated tag at offset {start}")
233
+
234
+
235
+ def _find_doctype_end(text: str, start: int) -> int:
236
+ depth = 0
237
+ quote = ""
238
+ i = start
239
+ n = len(text)
240
+ while i < n:
241
+ ch = text[i]
242
+ if quote:
243
+ if ch == quote:
244
+ quote = ""
245
+ elif ch in "\"'":
246
+ quote = ch
247
+ elif text.startswith("<!--", i):
248
+ end = text.find("-->", i + 4)
249
+ if end < 0:
250
+ raise ValueError(f"unterminated comment in DOCTYPE at offset {i}")
251
+ i = end + 3
252
+ continue
253
+ elif ch == "[":
254
+ depth += 1
255
+ elif ch == "]":
256
+ depth -= 1
257
+ elif ch == ">" and depth <= 0:
258
+ return i + 1
259
+ i += 1
260
+ raise ValueError(f"unterminated DOCTYPE at offset {start}")
261
+
262
+
263
+ def _tokenize(text: str) -> List[_Token]:
264
+ tokens: List[_Token] = []
265
+ i = 0
266
+ n = len(text)
267
+ first_markup_seen = False
268
+ while i < n:
269
+ if text.startswith("<!--", i):
270
+ end = text.find("-->", i + 4)
271
+ if end < 0:
272
+ raise ValueError(f"unterminated comment at offset {i}")
273
+ tokens.append(_Token(KIND_COMMENT, text[i : end + 3]))
274
+ i = end + 3
275
+ elif text.startswith("<![CDATA[", i):
276
+ end = text.find("]]>", i + 9)
277
+ if end < 0:
278
+ raise ValueError(f"unterminated CDATA section at offset {i}")
279
+ tokens.append(_Token(KIND_CDATA, text[i : end + 3]))
280
+ i = end + 3
281
+ elif text.startswith("<?", i):
282
+ end = text.find("?>", i + 2)
283
+ if end < 0:
284
+ raise ValueError(f"unterminated processing instruction at offset {i}")
285
+ raw = text[i : end + 2]
286
+ kind = KIND_PI
287
+ if (
288
+ not first_markup_seen
289
+ and re.match(r"<\?xml(?=[\s?])", raw)
290
+ and all(t.kind == KIND_TEXT and t.raw == "" for t in tokens)
291
+ ):
292
+ kind = KIND_DECLARATION
293
+ tokens.append(_Token(kind, raw))
294
+ i = end + 2
295
+ elif text.startswith("<!DOCTYPE", i):
296
+ end = _find_doctype_end(text, i + 9)
297
+ tokens.append(_Token(KIND_DOCTYPE, text[i:end]))
298
+ i = end
299
+ elif text.startswith("</", i):
300
+ end = _find_tag_end(text, i)
301
+ tokens.append(_Token(_END, text[i:end]))
302
+ i = end
303
+ elif text.startswith("<", i):
304
+ end = _find_tag_end(text, i)
305
+ tokens.append(_Token(_START, text[i:end]))
306
+ i = end
307
+ else:
308
+ end = text.find("<", i)
309
+ if end < 0:
310
+ end = n
311
+ tokens.append(_Token(KIND_TEXT, text[i:end]))
312
+ i = end
313
+ if tokens[-1].kind != KIND_TEXT:
314
+ first_markup_seen = True
315
+ return tokens
316
+
317
+
318
+ # ---------------------------------------------------------------------------------------------
319
+ # Tree building
320
+ # ---------------------------------------------------------------------------------------------
321
+ def _node(
322
+ kind: str,
323
+ fields: Mapping[str, Any],
324
+ children: Sequence[Node],
325
+ short_ids: ShortIdMap,
326
+ ) -> Node:
327
+ validated = make_node(kind, fields=dict(fields), children=tuple(children))
328
+ node_id = generate_node_id()
329
+ return replace(validated, node_id=node_id, short_id=short_ids.allocate(node_id))
330
+
331
+
332
+ def _leaf(token: _Token, short_ids: ShortIdMap) -> Node:
333
+ raw = token.raw
334
+ fields: Dict[str, Any] = {"raw": raw}
335
+ if token.kind == KIND_TEXT:
336
+ fields["value"] = _unescape(raw)
337
+ elif token.kind == KIND_CDATA:
338
+ fields["value"] = raw[len("<![CDATA[") : -len("]]>")]
339
+ elif token.kind == KIND_COMMENT:
340
+ fields["value"] = raw[len("<!--") : -len("-->")]
341
+ elif token.kind in (KIND_PI, KIND_DECLARATION):
342
+ body = raw[2:-2]
343
+ target = _NAME_RE.match(body)
344
+ name = target.group(0) if target else ""
345
+ fields["target"] = name
346
+ fields["value"] = body[len(name) :].strip()
347
+ elif token.kind == KIND_DOCTYPE:
348
+ match = re.match(r"<!DOCTYPE\s+([^\s\[>]+)", raw)
349
+ fields["name"] = match.group(1) if match else ""
350
+ return _node(token.kind, fields, (), short_ids)
351
+
352
+
353
+ def _start_name(start_raw: str) -> str:
354
+ match = _NAME_RE.match(start_raw, 1)
355
+ return match.group(0) if match else ""
356
+
357
+
358
+ def _build(tokens: Sequence[_Token], short_ids: ShortIdMap) -> List[Node]:
359
+ """Turn tokens into top-level nodes; an unbalanced token list raises ``ValueError``."""
360
+ # stack entries: [start_raw, name, children]
361
+ stack: List[List[Any]] = []
362
+ top: List[Node] = []
363
+
364
+ def add(node: Node) -> None:
365
+ (stack[-1][2] if stack else top).append(node)
366
+
367
+ for token in tokens:
368
+ if token.kind == _START:
369
+ name = _start_name(token.raw)
370
+ if not name:
371
+ raise ValueError(f"tag without a name: {token.raw!r}")
372
+ if token.raw.endswith("/>"):
373
+ add(
374
+ _node(
375
+ KIND_ELEMENT,
376
+ {
377
+ "name": name,
378
+ "start_raw": token.raw,
379
+ "end_raw": "",
380
+ "self_closing": True,
381
+ },
382
+ (),
383
+ short_ids,
384
+ )
385
+ )
386
+ else:
387
+ stack.append([token.raw, name, []])
388
+ elif token.kind == _END:
389
+ if not stack:
390
+ raise ValueError(f"end tag without a start tag: {token.raw!r}")
391
+ start_raw, name, children = stack.pop()
392
+ end_name = token.raw[2:-1].strip()
393
+ if end_name != name:
394
+ raise ValueError(f"end tag {token.raw!r} does not match <{name}>")
395
+ add(
396
+ _node(
397
+ KIND_ELEMENT,
398
+ {
399
+ "name": name,
400
+ "start_raw": start_raw,
401
+ "end_raw": token.raw,
402
+ "self_closing": False,
403
+ },
404
+ children,
405
+ short_ids,
406
+ )
407
+ )
408
+ else:
409
+ add(_leaf(token, short_ids))
410
+ if stack:
411
+ raise ValueError(f"element <{stack[-1][1]}> is not closed")
412
+ return top
413
+
414
+
415
+ def _decode(source: _Source, label: str, failure: type) -> str:
416
+ if isinstance(source, str):
417
+ return source
418
+ if isinstance(source, (bytes, bytearray)):
419
+ try:
420
+ return bytes(source).decode("utf-8")
421
+ except UnicodeDecodeError as exc:
422
+ raise failure(
423
+ f"cannot decode XML {label}: {exc}", format_id=FORMAT_ID
424
+ ) from exc
425
+ raise _contract_error(f"{label} must be str or bytes, got {type(source).__name__}")
426
+
427
+
428
+ def _parse_document_text(text: str) -> Document:
429
+ problem = well_formed_failure(text, namespaces=False)
430
+ if problem is not None:
431
+ raise FormatContentParseFailed(
432
+ f"cannot parse XML: {problem['text']}", format_id=FORMAT_ID,
433
+ line=problem["line"], column=problem["column"], message=problem["message"],
434
+ )
435
+ short_ids = ShortIdMap()
436
+ try:
437
+ top = _build(_tokenize(text), short_ids)
438
+ except ValueError as exc:
439
+ offset = _offset_of(str(exc))
440
+ line, column = line_column(text, len(text) if offset is None else offset)
441
+ raise FormatContentParseFailed(
442
+ f"cannot parse XML: {exc}", format_id=FORMAT_ID,
443
+ line=line, column=column, message=str(exc),
444
+ ) from exc
445
+ root = _node(KIND_DOCUMENT, {}, top, short_ids)
446
+ return Document(root=root, source_format_id=FORMAT_ID)
447
+
448
+
449
+ def _without_repeated_attributes(start_raw: str) -> str:
450
+ """``start_raw`` with every later attribute of an already seen name cut out (probe use only)."""
451
+ name = _NAME_RE.match(start_raw, 1)
452
+ pos = name.end() if name else 1
453
+ seen = set()
454
+ out = []
455
+ last = 0
456
+ for match in _ATTR_RE.finditer(start_raw, pos):
457
+ if match.group(1) in seen:
458
+ out.append(start_raw[last : match.start()])
459
+ last = match.end()
460
+ seen.add(match.group(1))
461
+ out.append(start_raw[last:])
462
+ return "".join(out)
463
+
464
+
465
+ def _parse_fragment_text(text: str) -> Node:
466
+ short_ids = ShortIdMap()
467
+ try:
468
+ tokens = _tokenize(text)
469
+ # The declaration and the DOCTYPE are only legal at the start of a document: leave them
470
+ # out of the well-formedness probe, keep them as nodes of the fragment.
471
+ # A repeated attribute name is not a parse failure of the fragment: like an undeclared
472
+ # prefix it is left in the tree and refused by the strict write check (VALIDATION_ERROR,
473
+ # decision D-Y, Rule point 7), so the probe sees each start tag once per attribute name.
474
+ probe = "".join(
475
+ _without_repeated_attributes(t.raw) if t.kind == _START else t.raw
476
+ for t in tokens
477
+ if t.kind not in (KIND_DECLARATION, KIND_DOCTYPE)
478
+ )
479
+ problem = check_well_formed(f"<_>{probe}</_>", namespaces=False)
480
+ if problem is not None:
481
+ raise FormatFragmentParseFailed(
482
+ f"cannot parse XML fragment: {problem}", format_id=FORMAT_ID
483
+ )
484
+ top = _build(tokens, short_ids)
485
+ except ValueError as exc:
486
+ raise FormatFragmentParseFailed(
487
+ f"cannot parse XML fragment: {exc}", format_id=FORMAT_ID
488
+ ) from exc
489
+ return _node(KIND_DOCUMENT, {}, top, short_ids)
490
+
491
+
492
+ # ---------------------------------------------------------------------------------------------
493
+ # Rendering
494
+ # ---------------------------------------------------------------------------------------------
495
+ def _expanded_start(start_raw: str) -> str:
496
+ """``<a x='1' />`` -> ``<a x='1'>`` for a self-closing element that gained children."""
497
+ body = start_raw[:-2].rstrip()
498
+ return body + ">"
499
+
500
+
501
+ def element_parts(node: Any) -> Tuple[str, str]:
502
+ """``(head, tail)`` of an element: its rendered start tag and its rendered end tag.
503
+
504
+ The element renders as ``head + children + tail``. A self-closing element without children is
505
+ its start tag alone (empty tail); a self-closing element that gained children is expanded to a
506
+ start tag and a ``</name>`` end tag.
507
+ """
508
+ fields = node.fields
509
+ start = fields.get("start_raw")
510
+ name = str(fields.get("name", ""))
511
+ if not isinstance(start, str):
512
+ start = f"<{name}>" if node.children else f"<{name}/>"
513
+ end = fields.get("end_raw")
514
+ if not isinstance(end, str):
515
+ end = f"</{name}>"
516
+ if start.endswith("/>"):
517
+ if not node.children:
518
+ return start, ""
519
+ return _expanded_start(start), f"</{name}>"
520
+ return start, (end or f"</{name}>")
521
+
522
+
523
+ def _render(node: Node) -> str:
524
+ kind = node.kind
525
+ if kind == KIND_DOCUMENT:
526
+ return "".join(_render(child) for child in node.children)
527
+ if kind == KIND_ELEMENT:
528
+ head, tail = element_parts(node)
529
+ return head + "".join(_render(child) for child in node.children) + tail
530
+ if kind in _LEAF_KINDS:
531
+ raw = node.fields.get("raw")
532
+ if isinstance(raw, str):
533
+ return raw
534
+ value = str(node.fields.get("value", ""))
535
+ if kind == KIND_TEXT:
536
+ return value.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
537
+ if kind == KIND_CDATA:
538
+ return f"<![CDATA[{value}]]>"
539
+ if kind == KIND_COMMENT:
540
+ return f"<!--{value}-->"
541
+ if kind in (KIND_PI, KIND_DECLARATION):
542
+ target = str(node.fields.get("target", ""))
543
+ return f"<?{target} {value}?>" if value else f"<?{target}?>"
544
+ return f"<!DOCTYPE {node.fields.get('name', '')}>"
545
+ raise _unsupported(str(kind), f"node kind {kind!r} has no XML form")
546
+
547
+
548
+ # ---------------------------------------------------------------------------------------------
549
+ # Attributes of a start tag
550
+ # ---------------------------------------------------------------------------------------------
551
+ def element_attributes(start_raw: str) -> List[Tuple[str, str, str]]:
552
+ """The attributes of a start tag in source order: ``(name, decoded value, quote char)``."""
553
+ name = _NAME_RE.match(start_raw, 1)
554
+ pos = name.end() if name else 1
555
+ found: List[Tuple[str, str, str]] = []
556
+ for match in _ATTR_RE.finditer(start_raw, pos):
557
+ quote = '"' if match.group(3) is not None else "'"
558
+ raw_value = match.group(3) if match.group(3) is not None else match.group(4)
559
+ found.append((match.group(1), _unescape(raw_value), quote))
560
+ return found
561
+
562
+
563
+ def apply_attribute_edit(start_raw: str, name: str, value: Optional[Any]) -> str:
564
+ """Return ``start_raw`` with attribute ``name`` set to ``value`` (``None`` removes it).
565
+
566
+ Only the one attribute changes: an existing attribute keeps its position, its spacing and its
567
+ quote character (the value is escaped for that quote); a new attribute is appended after the
568
+ last attribute (or the tag name) as `` name="value"``; every other byte is untouched.
569
+ """
570
+ if not isinstance(name, str) or not _ATTR_NAME_OK.match(name):
571
+ raise ValueError(f"invalid XML attribute name: {name!r}")
572
+ tag = _NAME_RE.match(start_raw, 1)
573
+ pos = tag.end() if tag else 1
574
+ matches = list(_ATTR_RE.finditer(start_raw, pos))
575
+ for match in matches:
576
+ if match.group(1) != name:
577
+ continue
578
+ if value is None:
579
+ before = start_raw[: match.start()]
580
+ return before.rstrip(" \t\r\n") + start_raw[match.end() :]
581
+ quote = '"' if match.group(3) is not None else "'"
582
+ group = 3 if match.group(3) is not None else 4
583
+ text = _escape_attr(str(value), quote)
584
+ return start_raw[: match.start(group)] + text + start_raw[match.end(group) :]
585
+ if value is None:
586
+ return start_raw
587
+ insert_at = matches[-1].end() if matches else pos
588
+ return (
589
+ start_raw[:insert_at]
590
+ + f' {name}="{_escape_attr(str(value), chr(34))}"'
591
+ + start_raw[insert_at:]
592
+ )
593
+
594
+
595
+ def render_node(node: Any) -> str:
596
+ """The exact source text of ``node`` (an engine node or live node of any XML kind).
597
+
598
+ An element is its start tag, its children and its end tag, so the text always follows the
599
+ current state of the tree; the document node is the whole file.
600
+ """
601
+ return _render(node)
602
+
603
+
604
+ # ---------------------------------------------------------------------------------------------
605
+ # Namespaces: prefix, local name and namespace URI resolved through the declarations in scope
606
+ # ---------------------------------------------------------------------------------------------
607
+ XML_NAMESPACE_URI = "http://www.w3.org/XML/1998/namespace"
608
+
609
+
610
+ def split_qualified_name(name: str) -> Tuple[str, str]:
611
+ """``p:a`` -> ``("p", "a")``; ``a`` -> ``("", "a")`` (only the first colon splits)."""
612
+ prefix, sep, local = name.partition(":")
613
+ if sep and prefix and local:
614
+ return prefix, local
615
+ return "", name
616
+
617
+
618
+ def namespace_scope(
619
+ start_raws: Sequence[str], inherited: Optional[Mapping[str, str]] = None
620
+ ) -> Dict[str, str]:
621
+ """The prefix -> URI bindings in force after the start tags ``start_raws`` (outermost first).
622
+
623
+ The default namespace is the key ``""``; ``xmlns=""`` rebinds it to the empty string (no
624
+ namespace). The ``xml`` prefix is always bound.
625
+ """
626
+ scope: Dict[str, str] = {"xml": XML_NAMESPACE_URI}
627
+ if inherited:
628
+ scope.update(inherited)
629
+ for start_raw in start_raws:
630
+ for name, value, _quote in element_attributes(start_raw):
631
+ if name == "xmlns":
632
+ scope[""] = value
633
+ elif name.startswith("xmlns:"):
634
+ scope[name[len("xmlns:") :]] = value
635
+ return scope
636
+
637
+
638
+ def describe_element(start_raws: Sequence[str]) -> Dict[str, Any]:
639
+ """Prefix, local name, namespace URI and attribute nodes of the LAST start tag in the chain.
640
+
641
+ ``start_raws`` are the start tags from the outermost ancestor down to the element itself.
642
+ Result keys: ``prefix``, ``local_name``, ``namespace_uri`` (strings, ``""`` when none) and
643
+ ``attribute_nodes`` (ordered ``{name, value, prefix, local_name, namespace_uri}``). An
644
+ unprefixed attribute has no namespace; a namespace declaration is an attribute whose prefix is
645
+ ``xmlns`` (or empty for the default declaration) and which has no namespace either; a prefix
646
+ that no declaration binds resolves to ``""``.
647
+ """
648
+ scope = namespace_scope(start_raws)
649
+ own = start_raws[-1]
650
+ tag = _NAME_RE.match(own, 1)
651
+ prefix, local = split_qualified_name(tag.group(0) if tag else "")
652
+ uri = scope.get(prefix, "") if prefix else scope.get("", "")
653
+ attribute_nodes: List[Dict[str, str]] = []
654
+ for name, value, _quote in element_attributes(own):
655
+ if name == "xmlns":
656
+ a_prefix, a_local, a_uri = "", "xmlns", ""
657
+ elif name.startswith("xmlns:"):
658
+ a_prefix, a_local, a_uri = "xmlns", name[len("xmlns:") :], ""
659
+ else:
660
+ a_prefix, a_local = split_qualified_name(name)
661
+ a_uri = scope.get(a_prefix, "") if a_prefix else ""
662
+ attribute_nodes.append(
663
+ {
664
+ "name": name,
665
+ "value": value,
666
+ "prefix": a_prefix,
667
+ "local_name": a_local,
668
+ "namespace_uri": a_uri,
669
+ }
670
+ )
671
+ return {
672
+ "prefix": prefix,
673
+ "local_name": local,
674
+ "namespace_uri": uri,
675
+ "attribute_nodes": attribute_nodes,
676
+ }
677
+
678
+
679
+ class XmlFormatPlugin(FormatPluginContract, FormatBoundary):
680
+ """Registered lossless ``format_id='xml'`` plugin."""
681
+
682
+ #: ``parse_fragment`` returns an ``xml:Document`` wrapping the fragment's own nodes (the shape
683
+ #: ``parse_document`` gives a whole file); the facade unwraps it to those nodes.
684
+ fragment_container_kinds = (KIND_DOCUMENT,)
685
+
686
+ @property
687
+ def metadata(self) -> FormatPluginMetadata:
688
+ return _METADATA
689
+
690
+ def is_type_compatible(
691
+ self, parent: Any, position: Optional[str], incoming: Any
692
+ ) -> bool:
693
+ """A leaf (text, CDATA, comment, processing instruction, declaration, DOCTYPE) never
694
+ hosts a child; the declaration and the DOCTYPE only live directly under the document.
695
+ """
696
+ parent_kind = getattr(parent, "kind", None)
697
+ if parent_kind is not None and str(parent_kind) in _LEAF_KINDS:
698
+ return False
699
+ incoming_kind = str(getattr(incoming, "kind", ""))
700
+ if (
701
+ incoming_kind in (KIND_DECLARATION, KIND_DOCTYPE)
702
+ and parent_kind is not None
703
+ ):
704
+ return str(parent_kind) == KIND_DOCUMENT
705
+ return True
706
+
707
+ def parse_document(
708
+ self,
709
+ source: _Source,
710
+ options: Optional[Mapping[str, Any]] = None,
711
+ *,
712
+ source_format_id: Optional[str] = None,
713
+ ) -> Document:
714
+ del options, source_format_id
715
+ return _parse_document_text(_decode(source, "source", FormatContentParseFailed))
716
+
717
+ def parse_fragment(
718
+ self,
719
+ source: _Source,
720
+ options: Optional[Mapping[str, Any]] = None,
721
+ *,
722
+ source_format_id: Optional[str] = None,
723
+ ) -> Node:
724
+ del options, source_format_id
725
+ return _parse_fragment_text(
726
+ _decode(source, "fragment", FormatFragmentParseFailed)
727
+ )
728
+
729
+ def import_external_tree(
730
+ self, external_tree: Any, options: Optional[Mapping[str, Any]] = None
731
+ ) -> Union[Node, Document]:
732
+ return self.import_to_common(external_tree, options)
733
+
734
+ def import_to_common(
735
+ self, external_representation: Any, options: Optional[Mapping[str, Any]] = None
736
+ ) -> Union[Node, Document]:
737
+ del options
738
+ if isinstance(external_representation, (str, bytes, bytearray)):
739
+ return self.parse_document(external_representation)
740
+ raise _unsupported(
741
+ type(external_representation).__name__, "expected XML source text"
742
+ )
743
+
744
+ def export_from_common(
745
+ self, nodes: Union[Node, Document], options: Optional[Mapping[str, Any]] = None
746
+ ) -> Any:
747
+ del options
748
+ if not isinstance(nodes, (Node, Document)):
749
+ raise _contract_error(
750
+ f"expected Node or Document, got {type(nodes).__name__}"
751
+ )
752
+ return _render(nodes.root if isinstance(nodes, Document) else nodes)
753
+
754
+ def generate_output(
755
+ self,
756
+ target: Union[Node, Document, Any],
757
+ options: Optional[Mapping[str, Any]] = None,
758
+ ) -> Union[str, bytes]:
759
+ options = options or {}
760
+ if isinstance(target, (Node, Document)):
761
+ text = _render(target.root if isinstance(target, Document) else target)
762
+ elif isinstance(target, str):
763
+ text = target
764
+ else:
765
+ raise _contract_error(
766
+ f"cannot render {type(target).__name__}; expected Node/Document/str"
767
+ )
768
+ return text.encode("utf-8") if options.get("as_bytes") else text
769
+
770
+ def semantic_role_mapping(self) -> SemanticRoleMapping:
771
+ return _ROLE_MAP
772
+
773
+ def render_document(self, document: Document) -> bytes:
774
+ result = self.generate_output(document, {"as_bytes": True})
775
+ if not isinstance(result, bytes):
776
+ raise _contract_error("render_document did not return bytes")
777
+ return result
778
+
779
+ def nodes_at_line(self, document: Any, line: int) -> List[Tuple[Any, Tuple[int, int]]]:
780
+ """Nodes covering ``line``, from the live tree (an xml node keeps no byte offsets, so the
781
+ answer follows the draft after edits). Editor hook (D-CB.2)."""
782
+ from tree_engine.query.xml_query import nodes_at_line_xml
783
+
784
+ return nodes_at_line_xml(document, line)
785
+
786
+ def search_nodes(
787
+ self,
788
+ document: Any,
789
+ query: Optional[str],
790
+ search_type: str,
791
+ node_type: Optional[str] = None,
792
+ name: Optional[str] = None,
793
+ qualname: Optional[str] = None,
794
+ start_line: Optional[int] = None,
795
+ end_line: Optional[int] = None,
796
+ include_code: bool = False,
797
+ ) -> List[Any]:
798
+ """Matches of one search over an XML document (decision D-AD rule points 13-15, hook D-CB.2).
799
+
800
+ ``xpath`` (and ``simple`` with a ``query``) run the XPath-like query of
801
+ ``tree_engine.query.xml_query``; ``text`` finds the substring in the full file text and names the
802
+ deepest node containing each occurrence; ``simple`` filters the node universe by field."""
803
+ from tree_engine.query import xml_query
804
+
805
+ if search_type == "xpath" or (search_type == "simple" and query and query.strip()):
806
+ if not query:
807
+ raise ValueError("query parameter required for xpath search")
808
+ return xml_query.query_xml(document, query, include_source=include_code)
809
+ if search_type == "simple":
810
+ found: List[Any] = []
811
+ for qm in xml_query.all_nodes_xml(document, include_source=include_code):
812
+ if node_type and node_type not in (qm.type, qm.type.rpartition(":")[2]):
813
+ continue
814
+ if name and (qm.name or None) != name:
815
+ continue
816
+ if qualname and qm.qualname != qualname:
817
+ continue
818
+ if start_line is not None or end_line is not None:
819
+ if qm.range is None:
820
+ continue
821
+ if start_line is not None and qm.range.start.line < start_line:
822
+ continue
823
+ if end_line is not None and qm.range.end.line > end_line:
824
+ continue
825
+ found.append(qm)
826
+ return found
827
+ if search_type == "text":
828
+ if not query:
829
+ raise ValueError("query parameter required for text search")
830
+ return xml_query.search_text_xml(
831
+ document, query, include_source=include_code, start_line=start_line, end_line=end_line
832
+ )
833
+ raise ValueError(f"Invalid search_type: {search_type}. Must be 'simple', 'xpath', or 'text'")
834
+
835
+ def check_source(self, text: str, strict: bool = True) -> Optional[str]:
836
+ """``None`` when ``text`` is well-formed XML, else the parser's message. ``strict`` applies the
837
+ namespace rules (the write check); the tree itself is built without them (editor hook)."""
838
+ return check_well_formed(text, namespaces=strict)
839
+
840
+ def preview_info(self, document: Any, node: Any) -> Dict[str, Any]:
841
+ """What a preview block of ``node`` shows beyond the generic fields (editor hook, D-CB.2):
842
+ ``name``, ``attributes`` (the element's own, then a ``value`` for a leaf), ``summary`` (the
843
+ namespace description of an element) and ``content`` (the node's exact current source)."""
844
+ kind = str(node.kind)
845
+ name = None
846
+ if kind == KIND_ELEMENT:
847
+ name = str(node.fields.get("name", "")) or None
848
+ elif kind in (KIND_PI, KIND_DECLARATION, KIND_DOCTYPE):
849
+ key = "name" if kind == KIND_DOCTYPE else "target"
850
+ name = str(node.fields.get(key, "")) or None
851
+ attributes: Dict[str, Any] = {}
852
+ summary: Dict[str, Any] = {}
853
+ if kind == KIND_ELEMENT:
854
+ start = node.fields.get("start_raw")
855
+ if isinstance(start, str):
856
+ reserved = {"text", "short_id", "tree_preview_child_count"}
857
+ for attr, value, _quote in element_attributes(start):
858
+ attributes[f"@{attr}" if attr in reserved else attr] = value
859
+ chain: List[str] = []
860
+ current: Any = node
861
+ while current is not None:
862
+ if current.kind == KIND_ELEMENT and isinstance(current.fields.get("start_raw"), str):
863
+ chain.append(current.fields["start_raw"])
864
+ parent_id = document.parent_index.get(current.node_id)
865
+ current = document.nodes_by_id[parent_id] if parent_id is not None else None
866
+ chain.reverse()
867
+ summary = describe_element(chain) if chain else {}
868
+ elif kind != KIND_DOCUMENT:
869
+ attributes["value"] = str(node.fields.get("value", node.fields.get("name", "")))
870
+ return {"name": name, "attributes": attributes, "summary": summary, "content": render_node(node)}
871
+
872
+ def plan_edit_attributes(self, node: Any, attributes: Mapping[str, Any]) -> Dict[str, Any]:
873
+ """Field updates that change the named attributes inside the element's start tag only
874
+ (quoting and spacing of everything else stay); ``None`` removes an attribute. The facade
875
+ applies the result with ``set_attribute`` (editor hook, decision D-CB.2)."""
876
+ if str(node.kind) != KIND_ELEMENT:
877
+ raise ValueError(f"edit_attributes needs an element node, got {node.kind!r}")
878
+ old = node.fields.get("start_raw")
879
+ if not isinstance(old, str):
880
+ raise ValueError("element has no start tag text")
881
+ start = old
882
+ for name, value in attributes.items():
883
+ start = apply_attribute_edit(start, str(name), value)
884
+ return {} if start == old else {"start_raw": start}
885
+
886
+ def plan_edit_content(self, node: Any, content: str) -> Tuple[str, str]:
887
+ """``("set_body"|"replace", text)`` that replaces the content of ``node`` keeping its kind:
888
+ an element's children, the data of a text node, CDATA section, comment or processing
889
+ instruction (editor hook, decision D-CB.2)."""
890
+ kind = str(node.kind)
891
+ if kind == KIND_ELEMENT:
892
+ return "set_body", content
893
+ if kind == KIND_TEXT:
894
+ return "replace", content
895
+ if kind == KIND_CDATA:
896
+ return "replace", f"<![CDATA[{content}]]>"
897
+ if kind == KIND_COMMENT:
898
+ return "replace", f"<!--{content}-->"
899
+ if kind == KIND_PI:
900
+ target = str(node.fields.get("target", ""))
901
+ return "replace", f"<?{target}{f' {content}' if content else ''}?>"
902
+ raise ValueError(f"edit_content is not supported on a {kind!r} node")
903
+
904
+ def render_fragment(self, node: Node) -> str:
905
+ result = self.generate_output(node)
906
+ if not isinstance(result, str):
907
+ raise _contract_error("render_fragment did not return str")
908
+ return result
909
+
910
+
911
+ XML_FORMAT_PLUGIN = XmlFormatPlugin()