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,747 @@
1
+ """Source-line index, text search, node-at-line lookup and the XPath-like query of an XML document.
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+
6
+ Rule points 13-15 of the XML format contract (matrix decision D-AD):
7
+
8
+ * The XML plugin keeps the exact source slice of every node but no byte offsets, so the position of
9
+ a node is derived from the tree: the document renders as head + children + tail for every
10
+ element, and the running length gives each node its character span in the file text. A line is
11
+ counted by line feeds, so a CRLF file counts one line per line break; the span of a node runs
12
+ from the line of its first character to the line of its last character. The index is built from
13
+ the live tree on every call, so it always follows the draft after edits.
14
+ * ``search_text_xml`` searches the full file text; every occurrence names the DEEPEST node whose
15
+ source contains it (a text node wins a tie with its parent element, an occurrence inside a start
16
+ or end tag names the element), one match per node, in document order.
17
+ * ``nodes_at_line_xml`` lists every node covering a line, smallest source span first (equal spans:
18
+ the innermost node, then the earlier one in document order).
19
+ * ``query_xml`` evaluates the XPath-like query on XML documents. It reads the forms of the editor's
20
+ existing selector grammar (``tree_engine.query.selector``: descendant by blank, ``>`` child, ``//``
21
+ descendant, ``[attr OP value]`` with ``= != ~= ^= $= > < >= <=``, ``:first``, ``:last``,
22
+ ``:nth(N)``, ``:not(step)``) and adds the XML-native forms: single ``/`` (absolute child step),
23
+ ``[N]`` (1-based position among the siblings the step matched under one parent), ``[@name]``
24
+ (attribute presence), ``@name`` (attribute selection; the result is the element that owns the
25
+ attribute), ``text()`` (text and CDATA), ``comment()``, ``processing-instruction()``, ``node()``
26
+ and ``prefix:name``. Element steps match elements only (``*`` is any element). A prefixed name is
27
+ resolved through the namespace declarations in scope at the document element: every element
28
+ whose own prefix resolves to the same URI and has the same local name matches; a prefix the
29
+ document element does not bind is compared literally. An unprefixed name matches an element
30
+ without a prefix. A malformed query raises :class:`QueryParseError` (an ``InvalidSelector``).
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import re
36
+ from bisect import bisect_left
37
+ from dataclasses import dataclass, field
38
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
39
+
40
+ from tree_engine.core.address import build_node_address_view
41
+ from tree_engine.core.short_id import to_hex
42
+ from tree_engine.plugins import xml_format as xf
43
+ from tree_engine.query.results import Position, QueryMatch, Range
44
+ from tree_engine.query.selector import QueryParseError
45
+
46
+ __all__ = [
47
+ "XmlEntry",
48
+ "XmlIndex",
49
+ "build_xml_index",
50
+ "all_nodes_xml",
51
+ "search_text_xml",
52
+ "nodes_at_line_xml",
53
+ "query_xml",
54
+ "parse_xml_query",
55
+ ]
56
+
57
+
58
+ # ---------------------------------------------------------------------------------------------
59
+ # Index: character span, line span and namespace scope of every node
60
+ # ---------------------------------------------------------------------------------------------
61
+ @dataclass(eq=False)
62
+ class XmlEntry:
63
+ """One node of the document with its span in the rendered file text."""
64
+
65
+ node: Any
66
+ index: int
67
+ depth: int
68
+ start: int
69
+ end: int
70
+ parent: Optional["XmlEntry"]
71
+ kids: List["XmlEntry"] = field(default_factory=list)
72
+ scope: Dict[str, str] = field(default_factory=dict)
73
+ last: int = 0 # index of the last entry of this subtree (document order)
74
+ _attrs: Optional[List[Tuple[str, str, str]]] = None
75
+ _starts: Optional[List[int]] = None
76
+
77
+ @property
78
+ def kind(self) -> str:
79
+ return str(self.node.kind)
80
+
81
+ @property
82
+ def is_element(self) -> bool:
83
+ return self.kind == xf.KIND_ELEMENT
84
+
85
+ def attributes(self) -> List[Tuple[str, str, str]]:
86
+ if self._attrs is None:
87
+ start = self.node.fields.get("start_raw") if self.is_element else None
88
+ self._attrs = xf.element_attributes(start) if isinstance(start, str) else []
89
+ return self._attrs
90
+
91
+ def kid_starts(self) -> List[int]:
92
+ if self._starts is None:
93
+ self._starts = [kid.start for kid in self.kids]
94
+ return self._starts
95
+
96
+
97
+ class XmlIndex:
98
+ """The document nodes in document order, the file text and the line lookup."""
99
+
100
+ def __init__(self, entries: List[XmlEntry], text: str) -> None:
101
+ self.entries = entries
102
+ self.text = text
103
+ self.newlines: List[int] = [m.start() for m in re.finditer("\n", text)]
104
+ self.by_id: Dict[str, XmlEntry] = {str(e.node.node_id): e for e in entries}
105
+ self.document: XmlEntry = entries[0]
106
+ self.query_scope: Dict[str, str] = {"xml": xf.XML_NAMESPACE_URI}
107
+ for kid in self.document.kids:
108
+ if kid.is_element:
109
+ self.query_scope = kid.scope
110
+ break
111
+
112
+ def line_of(self, offset: int) -> int:
113
+ """1-based line of the character at ``offset`` (a line feed belongs to the line it ends)."""
114
+ return bisect_left(self.newlines, offset) + 1
115
+
116
+ def position(self, offset: int) -> Position:
117
+ line = self.line_of(offset)
118
+ line_start = self.newlines[line - 2] + 1 if line > 1 else 0
119
+ return Position(line=line, column=offset - line_start)
120
+
121
+ def span_offsets(self, entry: XmlEntry) -> Tuple[int, int]:
122
+ """Offsets of the first and of the last character of the entry (equal for an empty node)."""
123
+ return entry.start, max(entry.end - 1, entry.start)
124
+
125
+ def line_span(self, entry: XmlEntry) -> Tuple[int, int]:
126
+ first, last = self.span_offsets(entry)
127
+ return self.line_of(first), self.line_of(last)
128
+
129
+ def source_of(self, entry: XmlEntry) -> str:
130
+ return self.text[entry.start : entry.end]
131
+
132
+
133
+ def build_xml_index(document: Any) -> XmlIndex:
134
+ """Index the live tree of ``document`` (an XML ``TreeDocument``); never reparses the source."""
135
+ entries: List[XmlEntry] = []
136
+ parts: List[str] = []
137
+ position = 0
138
+
139
+ def make(node: Any, parent: Optional[XmlEntry], head: str) -> XmlEntry:
140
+ nonlocal position
141
+ depth = 0 if parent is None else parent.depth + 1
142
+ scope: Dict[str, str] = dict(parent.scope) if parent is not None else {"xml": xf.XML_NAMESPACE_URI}
143
+ if str(node.kind) == xf.KIND_ELEMENT:
144
+ start_raw = node.fields.get("start_raw")
145
+ if isinstance(start_raw, str):
146
+ scope = xf.namespace_scope([start_raw], inherited=scope)
147
+ entry = XmlEntry(node, len(entries), depth, position, position, parent, scope=scope)
148
+ entries.append(entry)
149
+ if parent is not None:
150
+ parent.kids.append(entry)
151
+ parts.append(head)
152
+ position += len(head)
153
+ return entry
154
+
155
+ root = document.root
156
+ root_entry = make(root, None, "")
157
+ # frames: [entry, iterator over the children, tail text]
158
+ stack: List[List[Any]] = [[root_entry, iter(list(root.children)), ""]]
159
+ while stack:
160
+ frame = stack[-1]
161
+ entry, children, tail = frame
162
+ child = next(children, None)
163
+ if child is None:
164
+ parts.append(tail)
165
+ position += len(tail)
166
+ entry.end = position
167
+ entry.last = len(entries) - 1
168
+ stack.pop()
169
+ continue
170
+ kind = str(child.kind)
171
+ if kind == xf.KIND_ELEMENT:
172
+ head, child_tail = xf.element_parts(child)
173
+ child_entry = make(child, entry, head)
174
+ stack.append([child_entry, iter(list(child.children)), child_tail])
175
+ else:
176
+ child_entry = make(child, entry, xf.render_node(child))
177
+ child_entry.end = position
178
+ child_entry.last = child_entry.index
179
+ return XmlIndex(entries, "".join(parts))
180
+
181
+
182
+ # ---------------------------------------------------------------------------------------------
183
+ # Result records
184
+ # ---------------------------------------------------------------------------------------------
185
+ def _node_name(node: Any) -> str:
186
+ kind = str(node.kind)
187
+ fields = node.fields
188
+ if kind == xf.KIND_ELEMENT or kind == xf.KIND_DOCTYPE:
189
+ return str(fields.get("name", "")) or ""
190
+ if kind in (xf.KIND_PI, xf.KIND_DECLARATION):
191
+ return str(fields.get("target", "")) or ""
192
+ return ""
193
+
194
+
195
+ def _chain(entry: XmlEntry) -> List[XmlEntry]:
196
+ chain: List[XmlEntry] = []
197
+ current = entry.parent
198
+ while current is not None:
199
+ chain.append(current)
200
+ current = current.parent
201
+ chain.reverse()
202
+ return chain
203
+
204
+
205
+ def _match(index: XmlIndex, entry: XmlEntry, include_source: bool) -> QueryMatch:
206
+ node = entry.node
207
+ first, last = index.span_offsets(entry)
208
+ start = index.position(first)
209
+ end_position = index.position(last)
210
+ short_id = node.short_id
211
+ return QueryMatch(
212
+ node_id=node.node_id,
213
+ short_id_hex=to_hex(short_id) if isinstance(short_id, int) and short_id >= 1 else "",
214
+ type=str(node.kind),
215
+ kind="",
216
+ name=_node_name(node),
217
+ range=Range(start=start, end=end_position),
218
+ parent_path=tuple(
219
+ build_node_address_view(a.node.node_id, a.node.short_id)
220
+ for a in _chain(entry)
221
+ if isinstance(a.node.short_id, int) and a.node.short_id >= 1
222
+ ),
223
+ source=index.source_of(entry) if include_source else None,
224
+ qualname=None,
225
+ kind_namespaced=str(node.kind),
226
+ )
227
+
228
+
229
+ def _matches_of(index: XmlIndex, entries: Sequence[XmlEntry], include_source: bool) -> List[QueryMatch]:
230
+ return [_match(index, e, include_source) for e in entries]
231
+
232
+
233
+ def all_nodes_xml(document: Any, include_source: bool = False) -> List[QueryMatch]:
234
+ """Every node below the document node, in document order (the universe of a simple search)."""
235
+ index = build_xml_index(document)
236
+ return _matches_of(index, index.entries[1:], include_source)
237
+
238
+
239
+ # ---------------------------------------------------------------------------------------------
240
+ # Text search and node at line
241
+ # ---------------------------------------------------------------------------------------------
242
+ def _deepest_containing(index: XmlIndex, start: int, end: int) -> XmlEntry:
243
+ """The deepest node whose source contains the character range ``[start, end)``."""
244
+ current = index.document
245
+ while True:
246
+ starts = current.kid_starts()
247
+ pos = bisect_left(starts, start + 1) - 1 # the last kid starting at or before ``start``
248
+ if pos < 0:
249
+ return current
250
+ kid = current.kids[pos]
251
+ if kid.start <= start and end <= kid.end:
252
+ current = kid
253
+ continue
254
+ return current
255
+
256
+
257
+ def search_text_xml(
258
+ document: Any,
259
+ needle: str,
260
+ include_source: bool = False,
261
+ start_line: Optional[int] = None,
262
+ end_line: Optional[int] = None,
263
+ ) -> List[QueryMatch]:
264
+ """Occurrences of ``needle`` in the file text, one match per deepest containing node."""
265
+ index = build_xml_index(document)
266
+ if not needle:
267
+ return []
268
+ found: Dict[int, XmlEntry] = {}
269
+ at = index.text.find(needle)
270
+ while at >= 0:
271
+ entry = _deepest_containing(index, at, at + len(needle))
272
+ if entry is not index.document:
273
+ found.setdefault(entry.index, entry)
274
+ at = index.text.find(needle, at + 1)
275
+ result: List[XmlEntry] = []
276
+ for key in sorted(found):
277
+ entry = found[key]
278
+ s_line, e_line = index.line_span(entry)
279
+ if start_line is not None and s_line < start_line:
280
+ continue
281
+ if end_line is not None and e_line > end_line:
282
+ continue
283
+ result.append(entry)
284
+ return _matches_of(index, result, include_source)
285
+
286
+
287
+ def nodes_at_line_xml(document: Any, line: int) -> List[Tuple[Any, Tuple[int, int]]]:
288
+ """Every node covering ``line`` with its ``(start_line, end_line)``, smallest span first."""
289
+ index = build_xml_index(document)
290
+ covering: List[Tuple[Tuple[int, int, int], XmlEntry, Tuple[int, int]]] = []
291
+ for entry in index.entries:
292
+ s_line, e_line = index.line_span(entry)
293
+ if s_line <= line <= e_line:
294
+ covering.append(((e_line - s_line, -entry.depth, entry.index), entry, (s_line, e_line)))
295
+ covering.sort(key=lambda item: item[0])
296
+ return [(entry.node, span) for _key, entry, span in covering]
297
+
298
+
299
+ # ---------------------------------------------------------------------------------------------
300
+ # Query language
301
+ # ---------------------------------------------------------------------------------------------
302
+ @dataclass(frozen=True)
303
+ class _Test:
304
+ kind: str # name | any | text | comment | pi | node | attr
305
+ prefix: str = ""
306
+ local: str = ""
307
+ target: Optional[str] = None
308
+
309
+
310
+ @dataclass(frozen=True)
311
+ class _Pred:
312
+ kind: str # pos | attr | prop
313
+ number: int = 0
314
+ name: str = ""
315
+ op: str = ""
316
+ value: str = ""
317
+
318
+
319
+ @dataclass(frozen=True)
320
+ class _Pseudo:
321
+ kind: str # first | last | nth | not
322
+ number: int = 0
323
+ inner: Optional["_Step"] = None
324
+
325
+
326
+ @dataclass(frozen=True)
327
+ class _Step:
328
+ sep: str # "/" | "//" | ">" | " "
329
+ test: _Test
330
+ preds: Tuple[_Pred, ...] = ()
331
+ pseudos: Tuple[_Pseudo, ...] = ()
332
+
333
+
334
+ _NAME = re.compile(r"[^\W\d][\w.\-]*")
335
+ _OPS = (">=", "<=", "!=", "~=", "^=", "$=", ">", "<", "=")
336
+ _KIND_TESTS = {"text": "text", "comment": "comment", "processing-instruction": "pi", "node": "node"}
337
+ _PSEUDO_WORDS = ("first", "last")
338
+
339
+
340
+ class _Parser:
341
+ def __init__(self, text: str) -> None:
342
+ self.text = text
343
+ self.i = 0
344
+ self.n = len(text)
345
+
346
+ def fail(self, message: str) -> "QueryParseError":
347
+ return QueryParseError(
348
+ f"Invalid XML selector: {message} at position {self.i}",
349
+ query_string=self.text,
350
+ parse_position=self.i,
351
+ )
352
+
353
+ def ws(self) -> bool:
354
+ start = self.i
355
+ while self.i < self.n and self.text[self.i].isspace():
356
+ self.i += 1
357
+ return self.i > start
358
+
359
+ def parse(self) -> List[_Step]:
360
+ self.ws()
361
+ if self.i >= self.n:
362
+ raise self.fail("empty query")
363
+ steps: List[_Step] = []
364
+ sep = self._leading_sep()
365
+ while True:
366
+ self.ws()
367
+ steps.append(self.step(sep, allow_pseudo_only=True))
368
+ blank = self.ws()
369
+ if self.i >= self.n:
370
+ return steps
371
+ if self.text.startswith("//", self.i):
372
+ sep = "//"
373
+ self.i += 2
374
+ elif self.text[self.i] == "/":
375
+ sep = "/"
376
+ self.i += 1
377
+ elif self.text[self.i] == ">":
378
+ sep = ">"
379
+ self.i += 1
380
+ elif blank:
381
+ sep = " "
382
+ else:
383
+ raise self.fail(f"unexpected character {self.text[self.i]!r}")
384
+
385
+ def _leading_sep(self) -> str:
386
+ if self.text.startswith("//", self.i):
387
+ self.i += 2
388
+ return "//"
389
+ if self.text[self.i] == "/":
390
+ self.i += 1
391
+ return "/"
392
+ if self.text[self.i] == ">":
393
+ raise self.fail("a query cannot start with '>'")
394
+ return "//"
395
+
396
+ def name(self) -> Tuple[str, str]:
397
+ match = _NAME.match(self.text, self.i)
398
+ if match is None:
399
+ raise self.fail("a name is expected")
400
+ prefix, local = "", match.group(0)
401
+ self.i = match.end()
402
+ if self.i < self.n and self.text[self.i] == ":":
403
+ rest = _NAME.match(self.text, self.i + 1)
404
+ if rest is not None and not self._is_pseudo_at(self.i + 1, rest):
405
+ prefix, local = local, rest.group(0)
406
+ self.i = rest.end()
407
+ return prefix, local
408
+
409
+ def _is_pseudo_at(self, pos: int, rest: "re.Match[str]") -> bool:
410
+ word = rest.group(0)
411
+ if word in _PSEUDO_WORDS:
412
+ return True
413
+ return word in ("nth", "not") and rest.end() < self.n and self.text[rest.end()] == "("
414
+
415
+ def step(self, sep: str, allow_pseudo_only: bool = False, inner: bool = False) -> _Step:
416
+ if self.i >= self.n:
417
+ raise self.fail("a step is expected")
418
+ ch = self.text[self.i]
419
+ if ch == "@":
420
+ self.i += 1
421
+ if self.i < self.n and self.text[self.i] == "*":
422
+ self.i += 1
423
+ test = _Test("attr", "", "*")
424
+ else:
425
+ prefix, local = self.name()
426
+ test = _Test("attr", prefix, local)
427
+ if self.i < self.n and self.text[self.i] in "[:":
428
+ raise self.fail("an attribute step takes no predicate")
429
+ return _Step(sep, test)
430
+ if ch == "*":
431
+ self.i += 1
432
+ test = _Test("any")
433
+ elif ch in "[:":
434
+ if not allow_pseudo_only and not inner:
435
+ raise self.fail("a step is expected")
436
+ test = _Test("any")
437
+ else:
438
+ prefix, local = self.name()
439
+ if self.i < self.n and self.text[self.i] == "(" and not prefix and local in _KIND_TESTS:
440
+ self.i += 1
441
+ self.ws()
442
+ target: Optional[str] = None
443
+ if self.i < self.n and self.text[self.i] in "'\"":
444
+ target = self.quoted()
445
+ self.ws()
446
+ if self.i >= self.n or self.text[self.i] != ")":
447
+ raise self.fail("')' is expected")
448
+ self.i += 1
449
+ if target is not None and local != "processing-instruction":
450
+ raise self.fail(f"{local}() takes no argument")
451
+ test = _Test(_KIND_TESTS[local], target=target)
452
+ else:
453
+ test = _Test("name", prefix, local)
454
+ preds: List[_Pred] = []
455
+ pseudos: List[_Pseudo] = []
456
+ while self.i < self.n and self.text[self.i] == "[":
457
+ preds.append(self.predicate(inner))
458
+ while self.i < self.n and self.text[self.i] == ":":
459
+ pseudos.append(self.pseudo())
460
+ return _Step(sep, test, tuple(preds), tuple(pseudos))
461
+
462
+ def quoted(self) -> str:
463
+ quote = self.text[self.i]
464
+ self.i += 1
465
+ out: List[str] = []
466
+ while self.i < self.n:
467
+ ch = self.text[self.i]
468
+ if ch == "\\" and self.i + 1 < self.n:
469
+ out.append(self.text[self.i + 1])
470
+ self.i += 2
471
+ continue
472
+ if ch == quote:
473
+ self.i += 1
474
+ return "".join(out)
475
+ out.append(ch)
476
+ self.i += 1
477
+ raise self.fail("unterminated string")
478
+
479
+ def predicate(self, inner: bool) -> _Pred:
480
+ self.i += 1 # '['
481
+ self.ws()
482
+ if self.i >= self.n:
483
+ raise self.fail("unterminated predicate")
484
+ if self.text[self.i].isdigit():
485
+ end = self.i
486
+ while end < self.n and self.text[end].isdigit():
487
+ end += 1
488
+ number = int(self.text[self.i : end])
489
+ self.i = end
490
+ self.ws()
491
+ self.close_bracket()
492
+ if inner:
493
+ raise self.fail("a position is not allowed inside :not()")
494
+ if number < 1:
495
+ raise self.fail("a position starts at 1")
496
+ return _Pred("pos", number=number)
497
+ is_attr = self.text[self.i] == "@"
498
+ if is_attr:
499
+ self.i += 1
500
+ prefix, local = self.name()
501
+ name = f"{prefix}:{local}" if prefix else local
502
+ self.ws()
503
+ if self.i < self.n and self.text[self.i] == "]":
504
+ self.i += 1
505
+ if not is_attr:
506
+ raise self.fail("a predicate without '@' needs a comparison")
507
+ return _Pred("attr", name=name)
508
+ op = next((o for o in _OPS if self.text.startswith(o, self.i)), None)
509
+ if op is None:
510
+ raise self.fail("a comparison operator or ']' is expected")
511
+ self.i += len(op)
512
+ self.ws()
513
+ if self.i >= self.n:
514
+ raise self.fail("a value is expected")
515
+ if self.text[self.i] in "'\"":
516
+ value = self.quoted()
517
+ else:
518
+ end = self.i
519
+ while end < self.n and self.text[end] not in "]" and not self.text[end].isspace():
520
+ end += 1
521
+ value = self.text[self.i : end]
522
+ if not value:
523
+ raise self.fail("a value is expected")
524
+ self.i = end
525
+ self.ws()
526
+ self.close_bracket()
527
+ return _Pred("attr" if is_attr else "prop", name=name, op=op, value=value)
528
+
529
+ def close_bracket(self) -> None:
530
+ if self.i >= self.n or self.text[self.i] != "]":
531
+ raise self.fail("']' is expected")
532
+ self.i += 1
533
+
534
+ def pseudo(self) -> _Pseudo:
535
+ self.i += 1 # ':'
536
+ match = _NAME.match(self.text, self.i)
537
+ if match is None:
538
+ raise self.fail("a pseudo name is expected")
539
+ word = match.group(0).lower()
540
+ self.i = match.end()
541
+ if word in _PSEUDO_WORDS:
542
+ return _Pseudo(word)
543
+ if word == "nth":
544
+ self.expect("(")
545
+ self.ws()
546
+ end = self.i
547
+ while end < self.n and self.text[end].isdigit():
548
+ end += 1
549
+ if end == self.i:
550
+ raise self.fail(":nth requires an integer argument, e.g. :nth(0)")
551
+ number = int(self.text[self.i : end])
552
+ self.i = end
553
+ self.ws()
554
+ self.expect(")")
555
+ return _Pseudo("nth", number=number)
556
+ if word == "not":
557
+ self.expect("(")
558
+ self.ws()
559
+ inner = self.step(" ", inner=True)
560
+ self.ws()
561
+ self.expect(")")
562
+ if inner.test.kind == "attr":
563
+ raise self.fail("an attribute step is not allowed inside :not()")
564
+ return _Pseudo("not", inner=inner)
565
+ raise self.fail(f"unsupported pseudo {word!r}")
566
+
567
+ def expect(self, ch: str) -> None:
568
+ if self.i >= self.n or self.text[self.i] != ch:
569
+ raise self.fail(f"{ch!r} is expected")
570
+ self.i += 1
571
+
572
+
573
+ def parse_xml_query(selector: str) -> List[_Step]:
574
+ """Parse ``selector`` into steps; raises :class:`QueryParseError` on a malformed query."""
575
+ return _Parser(selector).parse()
576
+
577
+
578
+ # ---------------------------------------------------------------------------------------------
579
+ # Evaluation
580
+ # ---------------------------------------------------------------------------------------------
581
+ def _split(name: str) -> Tuple[str, str]:
582
+ return xf.split_qualified_name(name)
583
+
584
+
585
+ def _name_matches(
586
+ entry: XmlEntry, test: _Test, qscope: Dict[str, str]
587
+ ) -> bool:
588
+ prefix, local = _split(str(entry.node.fields.get("name", "")))
589
+ if local != test.local:
590
+ return False
591
+ if not test.prefix:
592
+ return prefix == ""
593
+ uri = qscope.get(test.prefix)
594
+ if uri is None:
595
+ return prefix == test.prefix
596
+ own = entry.scope.get(prefix, "") if prefix else entry.scope.get("", "")
597
+ return own == uri
598
+
599
+
600
+ def _test_matches(entry: XmlEntry, test: _Test, qscope: Dict[str, str]) -> bool:
601
+ kind = entry.kind
602
+ if test.kind == "name":
603
+ return kind == xf.KIND_ELEMENT and _name_matches(entry, test, qscope)
604
+ if test.kind == "any":
605
+ return kind == xf.KIND_ELEMENT
606
+ if test.kind == "text":
607
+ return kind in (xf.KIND_TEXT, xf.KIND_CDATA)
608
+ if test.kind == "comment":
609
+ return kind == xf.KIND_COMMENT
610
+ if test.kind == "pi":
611
+ if kind != xf.KIND_PI:
612
+ return False
613
+ return test.target is None or str(entry.node.fields.get("target", "")) == test.target
614
+ return True # node()
615
+
616
+
617
+ def _attribute_values(entry: XmlEntry, name: str, qscope: Dict[str, str]) -> List[str]:
618
+ if not entry.is_element:
619
+ return []
620
+ prefix, local = _split(name)
621
+ uri = qscope.get(prefix) if prefix and prefix not in ("xmlns",) else None
622
+ found: List[str] = []
623
+ for a_name, a_value, _quote in entry.attributes():
624
+ if name == "*" or a_name == name:
625
+ found.append(a_value)
626
+ elif prefix and uri is not None and not a_name.startswith("xmlns"):
627
+ a_prefix, a_local = _split(a_name)
628
+ if a_prefix and a_local == local and entry.scope.get(a_prefix, "") == uri:
629
+ found.append(a_value)
630
+ return found
631
+
632
+
633
+ def _compare(actual: str, op: str, expected: str) -> bool:
634
+ if op == "=":
635
+ return actual == expected
636
+ if op == "!=":
637
+ return actual != expected
638
+ if op == "~=":
639
+ return expected in actual
640
+ if op == "^=":
641
+ return actual.startswith(expected)
642
+ if op == "$=":
643
+ return actual.endswith(expected)
644
+ try:
645
+ left, right = float(actual), float(expected)
646
+ except ValueError:
647
+ return False
648
+ return {">": left > right, "<": left < right, ">=": left >= right, "<=": left <= right}[op]
649
+
650
+
651
+ def _property(index: XmlIndex, entry: XmlEntry, name: str) -> Optional[str]:
652
+ node = entry.node
653
+ if name == "name":
654
+ return _node_name(node) or None
655
+ if name in ("type", "kind"):
656
+ return str(node.kind) if name == "type" else str(node.kind).rpartition(":")[2]
657
+ if name == "value":
658
+ value = node.fields.get("value")
659
+ return str(value) if value is not None else None
660
+ if name in ("start_line", "end_line"):
661
+ s_line, e_line = index.line_span(entry)
662
+ return str(s_line if name == "start_line" else e_line)
663
+ return None
664
+
665
+
666
+ def _pred_holds(index: XmlIndex, entry: XmlEntry, pred: _Pred, qscope: Dict[str, str]) -> bool:
667
+ if pred.kind == "attr":
668
+ values = _attribute_values(entry, pred.name, qscope)
669
+ if not pred.op:
670
+ return bool(values)
671
+ return any(_compare(v, pred.op, pred.value) for v in values)
672
+ actual = _property(index, entry, pred.name)
673
+ return actual is not None and _compare(actual, pred.op, pred.value)
674
+
675
+
676
+ def _filter(
677
+ index: XmlIndex, candidates: List[XmlEntry], step: _Step, qscope: Dict[str, str]
678
+ ) -> List[XmlEntry]:
679
+ current = [c for c in candidates if _test_matches(c, step.test, qscope)]
680
+ for pred in step.preds:
681
+ if pred.kind == "pos":
682
+ current = [current[pred.number - 1]] if pred.number <= len(current) else []
683
+ else:
684
+ current = [c for c in current if _pred_holds(index, c, pred, qscope)]
685
+ return current
686
+
687
+
688
+ def _holds_single(index: XmlIndex, entry: XmlEntry, step: _Step, qscope: Dict[str, str]) -> bool:
689
+ return bool(_filter(index, [entry], step, qscope))
690
+
691
+
692
+ def _apply_pseudos(
693
+ index: XmlIndex, entries: List[XmlEntry], step: _Step, qscope: Dict[str, str]
694
+ ) -> List[XmlEntry]:
695
+ for pseudo in step.pseudos:
696
+ if pseudo.kind == "first":
697
+ entries = entries[:1]
698
+ elif pseudo.kind == "last":
699
+ entries = entries[-1:] if entries else []
700
+ elif pseudo.kind == "nth":
701
+ entries = [entries[pseudo.number]] if 0 <= pseudo.number < len(entries) else []
702
+ elif pseudo.kind == "not" and pseudo.inner is not None:
703
+ inner = pseudo.inner
704
+ entries = [e for e in entries if not _holds_single(index, e, inner, qscope)]
705
+ return entries
706
+
707
+
708
+ def _parents_of(index: XmlIndex, contexts: List[XmlEntry], sep: str) -> List[XmlEntry]:
709
+ """The entries whose children a step reads: the contexts, or every descendant-or-self of them."""
710
+ if sep in ("/", ">"):
711
+ return contexts
712
+ parents: List[XmlEntry] = []
713
+ covered = -1
714
+ for ctx in contexts:
715
+ if ctx.index <= covered:
716
+ continue # inside the subtree of a context already expanded
717
+ parents.extend(index.entries[ctx.index : ctx.last + 1])
718
+ covered = ctx.last
719
+ return parents
720
+
721
+
722
+ def _eval_step(
723
+ index: XmlIndex, contexts: List[XmlEntry], step: _Step, qscope: Dict[str, str]
724
+ ) -> List[XmlEntry]:
725
+ contexts = sorted(set(contexts), key=lambda e: e.index) if len(contexts) > 1 else contexts
726
+ parents = _parents_of(index, contexts, step.sep)
727
+ if step.test.kind == "attr":
728
+ name = f"{step.test.prefix}:{step.test.local}" if step.test.prefix else step.test.local
729
+ out = [p for p in parents if _attribute_values(p, name, qscope)]
730
+ else:
731
+ out = []
732
+ for parent in parents:
733
+ out.extend(_filter(index, parent.kids, step, qscope))
734
+ out = sorted(set(out), key=lambda e: e.index)
735
+ return _apply_pseudos(index, out, step, qscope)
736
+
737
+
738
+ def query_xml(document: Any, selector: str, *, include_source: bool = False) -> List[QueryMatch]:
739
+ """Run the XPath-like ``selector`` over the XML ``document``; matches in document order."""
740
+ steps = parse_xml_query(selector)
741
+ index = build_xml_index(document)
742
+ contexts: List[XmlEntry] = [index.document]
743
+ for step in steps:
744
+ if not contexts:
745
+ break
746
+ contexts = _eval_step(index, contexts, step, index.query_scope)
747
+ return _matches_of(index, contexts, include_source)