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,206 @@
1
+ """Query-result record model for the ported tree-query engine (concept C-009).
2
+
3
+ Scope (concept C-009, narrowed to the compact-result shape only, per {p005}
4
+ and {p021}): this module owns exactly one thing -- the immutable
5
+ ``QueryMatch`` record every match returned by the ported ``cst_query``
6
+ engine must carry, plus the single small helper, :func:`build_query_match`,
7
+ that assembles one from values already known by its caller.
8
+
9
+ Per {p021}, every node view in this package -- a query result included --
10
+ must carry both the compact hex-form ``short_id`` and the canonical UUID4
11
+ ``node_id`` together, since the compact form is only a later-addressing
12
+ shortcut and never a substitute for the canonical id. This module reuses
13
+ the existing {p021} pair type, :class:`tree_engine.core.address
14
+ .NodeAddressView` (``short_id_hex`` + ``node_id``), for each
15
+ ``parent_path`` entry instead of hand-rolling a second pair type or
16
+ formatting hex itself -- see ``tree_engine.core.address
17
+ .build_node_address_view``, which is how a caller is expected to have
18
+ produced that pair in the first place.
19
+
20
+ This file defines data only. It does not parse selectors, walk trees,
21
+ resolve semantic roles, evaluate predicates, or orchestrate a query --
22
+ all of that is out of scope here and belongs entirely to sibling files
23
+ under this same tactical step (G-018/T-001). This module has no dependency
24
+ on any of those siblings, and none of them may depend on anything from
25
+ this module beyond the ``QueryMatch`` shape and the ``build_query_match``
26
+ constructor.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ from dataclasses import dataclass
32
+ from typing import Any, Optional, Sequence, Tuple
33
+
34
+ from tree_engine.core.address import NodeAddressView
35
+
36
+ __all__ = [
37
+ "Position",
38
+ "Range",
39
+ "QueryMatch",
40
+ "build_query_match",
41
+ ]
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class Position:
46
+ """A single source location: a 1- or 0-based line/column pair.
47
+
48
+ This module does not fix the numbering convention -- that is a
49
+ format-plugin concern -- it only guarantees ``line`` and ``column`` are
50
+ carried together as given.
51
+ """
52
+
53
+ line: int
54
+ column: int
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class Range:
59
+ """A node's source span, as a simple ``start``/``end`` position pair."""
60
+
61
+ start: Position
62
+ end: Position
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class QueryMatch:
67
+ """One immutable query result, per the {p021} compact-result contract.
68
+
69
+ Fields:
70
+
71
+ * ``node_id`` -- the matched node's canonical UUID4 node_id.
72
+ * ``short_id_hex`` -- the matched node's compact hex-form short_id
73
+ (from the sibling ``tree_engine.core.short_id`` module). Exists only
74
+ for later re-addressing without a further search; never a substitute
75
+ for ``node_id``.
76
+ * ``type`` -- the concrete node kind as produced by the loaded format,
77
+ e.g. the underlying construct name or a format extension type such
78
+ as ``preprocessor_directive`` or ``variable_declaration``.
79
+ * ``kind`` -- the standard semantic role (``function``, ``method``,
80
+ ``class``, ``module``) the traversal adapter mapped the node to, or
81
+ ``""`` when no role applies.
82
+ * ``name`` -- the node's short display name, or ``""`` when it has
83
+ none.
84
+ * ``range`` -- the node's start/end position as a :class:`Range`, or
85
+ ``None`` (S6b of wish 8564a2ba, contract made explicit) when the
86
+ underlying node genuinely has no source position to report -- e.g.
87
+ a format plugin's own node carries no ``range`` attribute at all,
88
+ or (the python plugin, concretely) a LibCST field whose
89
+ ``_codegen_impl`` never renders it under this document's own
90
+ shape, so LibCST's ``ByteSpanPositionProvider`` never resolves a
91
+ byte span for it (see ``tree_engine.plugins.python.import_map
92
+ ._ZERO_WIDTH_SPAN_ANCHOR`` for the one node/field pair this engine
93
+ knows how to recover a position for regardless). A caller MUST
94
+ check for ``None`` before reading ``.start``/``.end`` -- never
95
+ assume every match is positioned; see
96
+ ``ai_editor.commands.universal_file_edit.search_command._collect``,
97
+ which degrades a range-less match to an explicitly uncorrelated
98
+ one instead of crashing.
99
+ * ``parent_path`` -- an ordered tuple of ancestor
100
+ :class:`~tree_engine.core.address.NodeAddressView` entries, from the
101
+ document root down to but excluding the matched node itself. Each
102
+ entry carries both the ancestor's ``node_id`` and its
103
+ ``short_id_hex``, so any ancestor can be addressed later without a
104
+ further search.
105
+ * ``source`` -- the node's source text, present only when the caller
106
+ asked for source to be included; ``None`` (absent) otherwise.
107
+ * ``qualname`` -- (S6a of wish 8564a2ba, additive) the node's dotted
108
+ qualified name (e.g. ``"Outer.method"``), when the loaded format's
109
+ plugin can resolve one (see :func:`build_query_match`'s ``node``
110
+ duck-type below); ``None`` when the format has no such concept, or
111
+ the concept is inapplicable to this particular node.
112
+ * ``kind_namespaced`` -- (S6a of wish 8564a2ba, additive) the node's own
113
+ raw, namespaced kind string exactly as stored on the common-model
114
+ ``Node`` (e.g. ``"python:FunctionDef"``), always populated
115
+ regardless of what ``type`` above resolves to for this match. Exists
116
+ so a caller that needs the RAW kind (for re-addressing, or because
117
+ ``type`` above was overridden to a bare, format-local display name)
118
+ never has to re-derive it.
119
+
120
+ Every field is stored exactly as given -- this type performs no
121
+ coercion, normalization, or validation of any kind. It is a shape, not
122
+ a validator; overwriting a field after construction is rejected by the
123
+ ``frozen`` dataclass machinery rather than silently succeeding.
124
+ """
125
+
126
+ node_id: Any
127
+ short_id_hex: str
128
+ type: str
129
+ kind: str
130
+ name: str
131
+ range: Optional[Range]
132
+ parent_path: Tuple[NodeAddressView, ...]
133
+ source: Optional[str] = None
134
+ qualname: Optional[str] = None
135
+ kind_namespaced: Optional[str] = None
136
+
137
+
138
+ def build_query_match(
139
+ node: Any,
140
+ kind: str,
141
+ short_id_hex: str,
142
+ parent_path: Sequence[NodeAddressView],
143
+ source: Optional[str] = None,
144
+ ) -> QueryMatch:
145
+ """Assemble a :class:`QueryMatch` from values already known to the caller.
146
+
147
+ Performs no tree walking, parsing, predicate evaluation, or lookup of
148
+ any kind -- it only reads already-attached data off ``node`` and
149
+ threads the remaining, already-resolved arguments straight into the
150
+ record. Every value this function needs must already be known by the
151
+ caller (the traversal adapter) before calling it.
152
+
153
+ ``node`` is duck-typed, the same convention already used by
154
+ ``tree_engine.core.address`` for its ``document`` parameter: this
155
+ helper reads ``node.node_id``, ``node.name`` and ``node.range``
156
+ directly, and ``node.type`` -- falling back to ``node.kind`` when
157
+ ``type`` is absent, for direct compatibility with
158
+ ``tree_engine.core.nodes.Node``, whose own attribute for "the node's
159
+ format-defined type" is named ``kind``. It never falls back to a
160
+ lookup, a default document, or any sibling module.
161
+
162
+ ``kind`` is the already-resolved standard semantic role (or ``""``
163
+ when inapplicable), ``short_id_hex`` is the already-rendered compact
164
+ hex short_id (see ``tree_engine.core.short_id.to_hex`` and
165
+ ``tree_engine.core.address.build_node_address_view``, both
166
+ sibling-owned renderers this function never calls itself), and
167
+ ``parent_path`` is the already-built ordered ancestor sequence. All
168
+ three are threaded through unchanged.
169
+
170
+ ``qualname`` (S6a of wish 8564a2ba, additive) is read the same
171
+ duck-typed way as ``name``/``range`` -- ``getattr(node, "qualname",
172
+ None)`` -- so a caller that hands in a plain ``tree_engine.core.nodes
173
+ .Node`` (which has no such attribute) simply gets ``None``, exactly as
174
+ before this field existed; a caller that hands in a node-shaped view
175
+ exposing a real ``qualname`` (e.g. the query engine's own per-node
176
+ attribute view, once a format plugin resolves one) gets it threaded
177
+ through unchanged. ``kind_namespaced`` is always the node's own raw
178
+ ``kind`` string (``str(getattr(node, "kind", node_type))``),
179
+ independent of whatever ``type`` above resolved to.
180
+ """
181
+
182
+ node_type = getattr(node, "type", None)
183
+ kind_namespaced = str(
184
+ getattr(node, "kind", node_type if node_type is not None else "")
185
+ )
186
+ if node_type is None:
187
+ node_type = getattr(node, "kind", "")
188
+
189
+ name = getattr(node, "name", None)
190
+ if name is None:
191
+ name = ""
192
+
193
+ qualname = getattr(node, "qualname", None)
194
+
195
+ return QueryMatch(
196
+ node_id=node.node_id,
197
+ short_id_hex=short_id_hex,
198
+ type=node_type,
199
+ kind=kind,
200
+ name=name,
201
+ range=getattr(node, "range", None),
202
+ parent_path=tuple(parent_path),
203
+ source=source,
204
+ qualname=qualname,
205
+ kind_namespaced=kind_namespaced,
206
+ )
@@ -0,0 +1,400 @@
1
+ """Selector language for the tree-query engine: AST, grammar, parser, error.
2
+
3
+ This module vendors the selector language into ``tree_engine`` so the
4
+ package is self-contained and installable on its own, depending on no
5
+ legacy package. It is a faithful PORT of the legacy ``cst_query`` AST and
6
+ Lark parser plus that package's query-parse exception: grammar, transformer
7
+ logic, accepted and rejected inputs, and error message text are carried
8
+ over verbatim. The legacy sources are untouched -- a copy, not a move.
9
+
10
+ Supported features: steps ``TYPE`` / ``TYPE:*`` / ``*``; combinators
11
+ descendant (space), direct child (``>``), recursive descendant (``//``);
12
+ predicates ``[attr OP value]`` / ``[@attr OP value]`` with string ops
13
+ ``=``, ``!=``, ``~=`` (contains), ``^=`` (starts-with), ``$=`` (ends-with)
14
+ and numeric ops ``>``, ``<``, ``>=``, ``<=``; pseudos ``:first``,
15
+ ``:last``, ``:nth(N)``, ``:not(selector)``. Values may be quoted or bare;
16
+ whitespace is insignificant except as the descendant combinator. Examples:
17
+ ``function[name='foo']``, ``//FunctionDef[@name='foo']``,
18
+ ``function[@name^='_']:not([name^='__'])``, ``class > method:first``,
19
+ ``Def:*[name='run']``.
20
+
21
+ Error discipline: the legacy parser raised ``QueryParseError``, an
22
+ exception carrying the ad-hoc string code ``"QUERY_PARSE_ERROR"``. That
23
+ taxonomy does not exist here, but the frozen catalog in
24
+ :mod:`tree_engine.errors` already owns a code for exactly this condition --
25
+ ``ErrorCode.INVALID_SELECTOR``, "a query/drill_down selector is malformed
26
+ or cannot be applied" -- so the ported exception is based on the project's
27
+ own hierarchy: it subclasses :class:`tree_engine.exceptions.InvalidSelector`
28
+ rather than inventing a new code. The legacy constructor signature and the
29
+ ``.message``/``.details`` attributes are preserved, so call sites passing
30
+ ``details={"error_code": ...}`` keep working unchanged. One consequence is
31
+ deliberate: ``TreeEngineException`` prefixes every message with its code,
32
+ so ``str(err)`` reads ``"[INVALID_SELECTOR] msg"`` where the legacy class
33
+ rendered the bare message (``.message`` still holds the bare text).
34
+
35
+ Author: Vasiliy Zdanovskiy
36
+ email: vasilyvz@gmail.com
37
+ """
38
+
39
+ from __future__ import annotations
40
+
41
+ from dataclasses import dataclass
42
+ from enum import Enum
43
+ from typing import Any, Dict, Optional
44
+
45
+ from lark import Lark, Transformer, Token, UnexpectedInput
46
+
47
+ from tree_engine.exceptions import InvalidSelector
48
+
49
+ __all__ = [
50
+ "QueryParseError",
51
+ "Combinator",
52
+ "PredicateOp",
53
+ "Predicate",
54
+ "PseudoKind",
55
+ "Pseudo",
56
+ "SelectorStep",
57
+ "Query",
58
+ "parse_selector",
59
+ ]
60
+
61
+
62
+ class QueryParseError(InvalidSelector):
63
+ """Raised when a selector cannot be parsed or cannot be executed.
64
+
65
+ Ported from the legacy query-parse exception and rebased onto this
66
+ project's own error hierarchy: the stable catalog code is
67
+ ``ErrorCode.INVALID_SELECTOR``, fixed by :class:`InvalidSelector` and
68
+ never restated here. The legacy keyword arguments are kept so callers
69
+ and call sites port over without edits.
70
+ """
71
+
72
+ def __init__(
73
+ self,
74
+ message: str,
75
+ query_string: Optional[str] = None,
76
+ parse_position: Optional[int] = None,
77
+ details: Optional[Dict[str, Any]] = None,
78
+ ) -> None:
79
+ """Initialize with the legacy arguments: the human-readable message,
80
+ the optional offending query string, the optional character position
81
+ the failure was detected at, and an optional extra-details dict."""
82
+ super().__init__(message, **(details or {}))
83
+ self.message = message
84
+ self.query_string = query_string
85
+ self.parse_position = parse_position
86
+
87
+
88
+ # --- Selector AST (ported from the legacy cst_query ``ast`` module) --------
89
+
90
+
91
+ class Combinator(str, Enum):
92
+ """Selector step relation."""
93
+
94
+ DESCENDANT = " "
95
+ CHILD = ">"
96
+ RECURSIVE_DESCENDANT = "//"
97
+
98
+
99
+ class PredicateOp(str, Enum):
100
+ """Predicate operator for attribute tests."""
101
+
102
+ EQ = "="
103
+ NE = "!="
104
+ CONTAINS = "~="
105
+ PREFIX = "^="
106
+ SUFFIX = "$="
107
+ GT = ">"
108
+ LT = "<"
109
+ GTE = ">="
110
+ LTE = "<="
111
+
112
+
113
+ @dataclass(frozen=True)
114
+ class Predicate:
115
+ """Attribute predicate like [name="foo"] or [qualname^="A.B"]."""
116
+
117
+ attr: str
118
+ op: PredicateOp
119
+ value: str
120
+
121
+
122
+ class PseudoKind(str, Enum):
123
+ """Pseudo-class / functional pseudo."""
124
+
125
+ FIRST = "first"
126
+ LAST = "last"
127
+ NTH = "nth"
128
+ NOT = "not"
129
+
130
+
131
+ @dataclass(frozen=True)
132
+ class Pseudo:
133
+ """Pseudo like :first, :last, :nth(0)."""
134
+
135
+ kind: PseudoKind
136
+ index: Optional[int] = None
137
+
138
+
139
+ @dataclass(frozen=True)
140
+ class SelectorStep:
141
+ """
142
+ A single selector step.
143
+
144
+ `node_type` can be:
145
+ - "*" (match anything)
146
+ - alias: module, class, function, method, stmt, smallstmt, import
147
+ - LibCST node class name (e.g. If, For, Try, With, Return)
148
+ - "Type:*" for prefix/suffix match (e.g. Def:* -> FunctionDef, ClassDef)
149
+ """
150
+
151
+ node_type: str
152
+ predicates: tuple[Predicate, ...] = ()
153
+ pseudos: tuple[Pseudo, ...] = ()
154
+ not_selector: Optional["Query"] = None
155
+
156
+
157
+ @dataclass(frozen=True)
158
+ class Query:
159
+ """A full query, e.g. class[name="A"] > function[name="m"] stmt[type="If"]."""
160
+
161
+ first: SelectorStep
162
+ rest: tuple[tuple[Combinator, SelectorStep], ...] = ()
163
+
164
+
165
+ # --- Grammar and parser (ported from the legacy cst_query ``parser``) ------
166
+
167
+ _GRAMMAR = r"""
168
+ ?start: selector
169
+
170
+ selector: dslash_step ((CHILD step) | dslash_step | step)*
171
+ | step ((CHILD step) | dslash_step | step)*
172
+ CHILD: ">"
173
+ DSLASH: "//"
174
+
175
+ dslash_step: DSLASH step
176
+
177
+ step: node_type predicate* pseudo*
178
+ | predicate+ pseudo*
179
+ | pseudo+
180
+ node_type: STAR | NAME type_wildcard?
181
+ type_wildcard: ":*"
182
+ STAR: "*"
183
+
184
+ predicate: "[" AT? NAME OP value "]"
185
+ AT: "@"
186
+ OP: ">=" | "<=" | "!=" | "~=" | "^=" | "$=" | ">" | "<" | "="
187
+ ?value: STRING | BAREWORD
188
+
189
+ pseudo: ":" NAME pseudo_args?
190
+ pseudo_args: "(" INT ")"
191
+ | "(" selector ")"
192
+
193
+ NAME: /[a-zA-Z_][a-zA-Z0-9_]*/
194
+ BAREWORD: /[^\]\s\)]+/
195
+ INT: /[0-9]+/
196
+
197
+ %import common.ESCAPED_STRING -> STRING
198
+ %import common.WS_INLINE -> WS
199
+ %ignore WS
200
+ """
201
+
202
+
203
+ _parser = Lark(_GRAMMAR, parser="lalr", start="start")
204
+
205
+
206
+ @dataclass(frozen=True)
207
+ class _ParsedPseudo:
208
+ name: str
209
+ index: Optional[int]
210
+ not_query: Optional["Query"] = None
211
+
212
+
213
+ class _ToAst(Transformer):
214
+ """Lark transformer: converts parse tree into CSTQuery AST nodes."""
215
+
216
+ def NAME(self, t: Token) -> str: # noqa: N802
217
+ return str(t)
218
+
219
+ def INT(self, t: Token) -> int: # noqa: N802
220
+ return int(str(t))
221
+
222
+ def STAR(self, _t: Token) -> str: # noqa: N802
223
+ return "*"
224
+
225
+ def BAREWORD(self, t: Token) -> str: # noqa: N802
226
+ """Parse bareword value, handling quoted strings that were parsed as barewords.
227
+
228
+ Sometimes quoted strings (especially single quotes inside double-quoted
229
+ Python strings) are parsed as BAREWORD instead of STRING.
230
+ We need to detect and handle these cases.
231
+ """
232
+ raw = str(t)
233
+ if len(raw) >= 2 and raw[0] == raw[-1] and raw[0] in ("'", '"'):
234
+ unquoted = raw[1:-1]
235
+ try:
236
+ return bytes(unquoted, "utf-8").decode("unicode_escape")
237
+ except (UnicodeDecodeError, UnicodeError):
238
+ return unquoted
239
+ return raw
240
+
241
+ def STRING(self, t: Token) -> str: # noqa: N802
242
+ """Parse string value, removing quotes and handling escape sequences.
243
+
244
+ Lark provides the string token with quotes included.
245
+ We need to remove the outer quotes and decode escape sequences.
246
+ """
247
+ raw = str(t)
248
+ if len(raw) >= 2:
249
+ if raw[0] == raw[-1] and raw[0] in ("'", '"'):
250
+ unquoted = raw[1:-1]
251
+ try:
252
+ return bytes(unquoted, "utf-8").decode("unicode_escape")
253
+ except (UnicodeDecodeError, UnicodeError):
254
+ return unquoted
255
+ return raw
256
+
257
+ def OP(self, t: Token) -> str: # noqa: N802
258
+ return str(t)
259
+
260
+ def predicate(self, items: list[Any]) -> Predicate:
261
+ """Build Predicate; strip optional AT token before attr name."""
262
+ filtered = [
263
+ it for it in items if not (isinstance(it, Token) and it.type == "AT")
264
+ ]
265
+ attr, op_str, value = str(filtered[0]), str(filtered[1]), str(filtered[2])
266
+ return Predicate(attr=attr, op=PredicateOp(op_str), value=value)
267
+
268
+ def dslash_step(self, items: list[Any]) -> tuple[Combinator, SelectorStep]:
269
+ """Transform //step into (RECURSIVE_DESCENDANT, inner step).
270
+
271
+ Leading ``//`` starts a recursive descendant search from the tree root;
272
+ a chained ``//`` after a prior step applies the same combinator between
273
+ steps (e.g. ``//ClassDef//FunctionDef``).
274
+ """
275
+ inner = next((it for it in items if isinstance(it, SelectorStep)), None)
276
+ if inner is None:
277
+ raise QueryParseError("dslash_step: expected SelectorStep")
278
+ return (Combinator.RECURSIVE_DESCENDANT, inner)
279
+
280
+ def pseudo_args(self, items: list[Any]) -> Any:
281
+ """Return INT for :nth or Query for :not; else first item."""
282
+ if items and isinstance(items[0], int):
283
+ return items[0]
284
+ if items and isinstance(items[0], Query):
285
+ return items[0]
286
+ return items[0] if items else None
287
+
288
+ def pseudo(self, items: list[Any]) -> _ParsedPseudo:
289
+ """Build _ParsedPseudo from parsed pseudo token and optional arg."""
290
+ name = str(items[0])
291
+ arg = items[1] if len(items) > 1 else None
292
+ if isinstance(arg, int):
293
+ return _ParsedPseudo(name=name, index=arg)
294
+ if isinstance(arg, Query):
295
+ return _ParsedPseudo(name=name, index=None, not_query=arg)
296
+ return _ParsedPseudo(name=name, index=None)
297
+
298
+ def node_type(self, items: list[Any]) -> str:
299
+ """Build node type string, appending ':*' for wildcard suffix."""
300
+ name = str(items[0])
301
+ if len(items) > 1:
302
+ return name + ":*"
303
+ return name
304
+
305
+ def step(self, items: list[Any]) -> SelectorStep:
306
+ """Build SelectorStep from node_type, predicates, pseudos and :not."""
307
+ node_type: str = "*"
308
+ predicates: list[Predicate] = []
309
+ pseudos: list[Pseudo] = []
310
+ not_selector: Any = None
311
+ for it in items:
312
+ if isinstance(it, str):
313
+ node_type = it
314
+ elif isinstance(it, Predicate):
315
+ predicates.append(it)
316
+ elif isinstance(it, _ParsedPseudo):
317
+ p = _pseudo_from_parsed(it)
318
+ if p.kind == PseudoKind.NOT:
319
+ not_selector = it.not_query
320
+ else:
321
+ pseudos.append(p)
322
+ else:
323
+ raise QueryParseError(f"Unexpected step item: {it!r}")
324
+ return SelectorStep(
325
+ node_type=node_type,
326
+ predicates=tuple(predicates),
327
+ pseudos=tuple(pseudos),
328
+ not_selector=not_selector,
329
+ )
330
+
331
+ def selector(self, items: list[Any]) -> Query:
332
+ """Build Query from parsed steps and combinators."""
333
+ if not items:
334
+ raise QueryParseError("Empty selector")
335
+ first_item = items[0]
336
+ if isinstance(first_item, tuple):
337
+ _leading_comb, first = first_item
338
+ if not isinstance(first, SelectorStep):
339
+ raise QueryParseError("Invalid selector start")
340
+ elif isinstance(first_item, SelectorStep):
341
+ first = first_item
342
+ else:
343
+ raise QueryParseError("Invalid selector start")
344
+ rest: list[tuple[Combinator, SelectorStep]] = []
345
+ i = 1
346
+ while i < len(items):
347
+ it = items[i]
348
+ if isinstance(it, Token) and it.type == "CHILD":
349
+ step = items[i + 1]
350
+ if not isinstance(step, SelectorStep):
351
+ raise QueryParseError("Invalid selector sequence")
352
+ rest.append((Combinator.CHILD, step))
353
+ i += 2
354
+ continue
355
+ if isinstance(it, tuple):
356
+ comb, step = it
357
+ if not isinstance(step, SelectorStep):
358
+ raise QueryParseError("Invalid selector sequence")
359
+ rest.append((comb, step))
360
+ i += 1
361
+ continue
362
+ if isinstance(it, SelectorStep):
363
+ rest.append((Combinator.DESCENDANT, it))
364
+ i += 1
365
+ continue
366
+ raise QueryParseError("Invalid selector sequence")
367
+ return Query(first=first, rest=tuple(rest))
368
+
369
+
370
+ def _pseudo_from_parsed(p: _ParsedPseudo) -> Pseudo:
371
+ name = p.name.lower()
372
+ if name == PseudoKind.FIRST.value:
373
+ if p.index is not None:
374
+ raise QueryParseError(":first does not accept arguments")
375
+ return Pseudo(kind=PseudoKind.FIRST)
376
+ if name == PseudoKind.LAST.value:
377
+ if p.index is not None:
378
+ raise QueryParseError(":last does not accept arguments")
379
+ return Pseudo(kind=PseudoKind.LAST)
380
+ if name == PseudoKind.NTH.value:
381
+ if not isinstance(p.index, int):
382
+ raise QueryParseError(":nth requires an integer argument, e.g. :nth(0)")
383
+ return Pseudo(kind=PseudoKind.NTH, index=p.index)
384
+ if name == PseudoKind.NOT.value:
385
+ return Pseudo(kind=PseudoKind.NOT)
386
+ raise QueryParseError(f"Unsupported pseudo: {p.name}")
387
+
388
+
389
+ def parse_selector(selector: str) -> Query:
390
+ """
391
+ Parse a selector into a CSTQuery AST.
392
+
393
+ Raises:
394
+ QueryParseError
395
+ """
396
+ try:
397
+ tree = _parser.parse(selector)
398
+ return _ToAst().transform(tree)
399
+ except UnexpectedInput as e:
400
+ raise QueryParseError(f"Invalid selector: {e}") from e