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.
- ai_editor_tree_engine_dev-1.0.176.dist-info/METADATA +35 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/RECORD +121 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/WHEEL +5 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/licenses/LICENSE +21 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/top_level.txt +1 -0
- tree_engine/PUBLIC_API.md +161 -0
- tree_engine/__init__.py +327 -0
- tree_engine/checks/__init__.py +60 -0
- tree_engine/checks/builtin/__init__.py +5 -0
- tree_engine/checks/builtin/compile_check.py +53 -0
- tree_engine/checks/builtin/csv_syntax.py +51 -0
- tree_engine/checks/builtin/docstrings.py +211 -0
- tree_engine/checks/builtin/encoding.py +55 -0
- tree_engine/checks/builtin/fleet_rules.py +227 -0
- tree_engine/checks/builtin/format_syntax.py +82 -0
- tree_engine/checks/builtin/jsonl_syntax.py +49 -0
- tree_engine/checks/builtin/shipped.py +52 -0
- tree_engine/checks/builtin/syntax.py +118 -0
- tree_engine/checks/builtin/xml_wellformed.py +51 -0
- tree_engine/checks/chain.py +332 -0
- tree_engine/checks/external/__init__.py +5 -0
- tree_engine/checks/external/_base.py +61 -0
- tree_engine/checks/external/bandit.py +53 -0
- tree_engine/checks/external/black.py +48 -0
- tree_engine/checks/external/flake8.py +38 -0
- tree_engine/checks/external/isort.py +38 -0
- tree_engine/checks/external/mypy.py +45 -0
- tree_engine/checks/external/ruff.py +45 -0
- tree_engine/checks/external/runner.py +197 -0
- tree_engine/checks/model.py +110 -0
- tree_engine/checks/options.py +73 -0
- tree_engine/checks/plugin.py +171 -0
- tree_engine/checks/registry.py +349 -0
- tree_engine/core/address.py +376 -0
- tree_engine/core/identifier_map.py +266 -0
- tree_engine/core/identity.py +226 -0
- tree_engine/core/instrumentation.py +399 -0
- tree_engine/core/integrity.py +341 -0
- tree_engine/core/integrity_full.py +382 -0
- tree_engine/core/journal.py +260 -0
- tree_engine/core/journal_compose.py +571 -0
- tree_engine/core/live_tree.py +785 -0
- tree_engine/core/locking.py +188 -0
- tree_engine/core/move.py +585 -0
- tree_engine/core/move_references.py +323 -0
- tree_engine/core/node_types.py +408 -0
- tree_engine/core/nodes.py +348 -0
- tree_engine/core/offsets.py +24 -0
- tree_engine/core/operations.py +825 -0
- tree_engine/core/plugin_boundary.py +160 -0
- tree_engine/core/position_map.py +263 -0
- tree_engine/core/position_transfer.py +512 -0
- tree_engine/core/range_refresh.py +366 -0
- tree_engine/core/reference_cache.py +360 -0
- tree_engine/core/references.py +223 -0
- tree_engine/core/reparse.py +378 -0
- tree_engine/core/short_id.py +296 -0
- tree_engine/core/subtree_apply.py +397 -0
- tree_engine/core/subtree_copy.py +399 -0
- tree_engine/core/transactions.py +397 -0
- tree_engine/core/trivia.py +396 -0
- tree_engine/core/updates.py +398 -0
- tree_engine/core/validation.py +377 -0
- tree_engine/errors.py +104 -0
- tree_engine/exceptions.py +376 -0
- tree_engine/facade.py +4524 -0
- tree_engine/plugins/_statements.py +369 -0
- tree_engine/plugins/bsl/block_edit.py +449 -0
- tree_engine/plugins/bsl/blocks.py +127 -0
- tree_engine/plugins/bsl/checker.py +297 -0
- tree_engine/plugins/bsl/dialects.py +303 -0
- tree_engine/plugins/bsl/generator.py +481 -0
- tree_engine/plugins/bsl/import_map.py +995 -0
- tree_engine/plugins/bsl/plugin.py +452 -0
- tree_engine/plugins/contract.py +355 -0
- tree_engine/plugins/cpp/import_map.py +505 -0
- tree_engine/plugins/cpp/languages.py +99 -0
- tree_engine/plugins/cpp/plugin.py +501 -0
- tree_engine/plugins/csv_format.py +676 -0
- tree_engine/plugins/detachable.py +156 -0
- tree_engine/plugins/fallback.py +421 -0
- tree_engine/plugins/ini_format.py +330 -0
- tree_engine/plugins/json_format.py +813 -0
- tree_engine/plugins/json_pointer.py +203 -0
- tree_engine/plugins/jsonl_format.py +392 -0
- tree_engine/plugins/markdown_format.py +748 -0
- tree_engine/plugins/onec_query_format.py +61 -0
- tree_engine/plugins/parse_position.py +54 -0
- tree_engine/plugins/plain_text.py +1543 -0
- tree_engine/plugins/python/export_map.py +306 -0
- tree_engine/plugins/python/import_map.py +429 -0
- tree_engine/plugins/python/plugin.py +1710 -0
- tree_engine/plugins/registry.py +497 -0
- tree_engine/plugins/scan.py +87 -0
- tree_engine/plugins/selection.py +228 -0
- tree_engine/plugins/sql_format.py +61 -0
- tree_engine/plugins/toml_format.py +1072 -0
- tree_engine/plugins/xml_format.py +911 -0
- tree_engine/plugins/yaml/builder.py +49 -0
- tree_engine/plugins/yaml/emitter.py +225 -0
- tree_engine/plugins/yaml/flow.py +227 -0
- tree_engine/plugins/yaml/plugin.py +458 -0
- tree_engine/plugins/yaml/ranges.py +52 -0
- tree_engine/plugins/yaml/reader.py +359 -0
- tree_engine/plugins/yaml/scanner.py +298 -0
- tree_engine/query/adapter.py +283 -0
- tree_engine/query/engine.py +853 -0
- tree_engine/query/inspection.py +498 -0
- tree_engine/query/outline.py +288 -0
- tree_engine/query/predicates.py +263 -0
- tree_engine/query/rendered_lines.py +46 -0
- tree_engine/query/results.py +206 -0
- tree_engine/query/selector.py +400 -0
- tree_engine/query/xml_query.py +747 -0
- tree_engine/storage/codec.py +400 -0
- tree_engine/storage/document_bridge.py +579 -0
- tree_engine/storage/file_txn.py +459 -0
- tree_engine/storage/history.py +106 -0
- tree_engine/storage/lifecycle.py +622 -0
- tree_engine/storage/schema.py +403 -0
- tree_engine/storage/session_guard.py +398 -0
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
"""Base node schema and document format contract for concept C-002.
|
|
2
|
+
|
|
3
|
+
Scope (concept C-002, CommonTreeModel, narrowed to the base node schema and
|
|
4
|
+
the document-level format contract): this module defines ``NodeKind``,
|
|
5
|
+
``Node``, and ``Document`` -- the core's only working tree representation,
|
|
6
|
+
per frozen HRS fragments {p008} and {p045} -- plus the ``make_node``
|
|
7
|
+
construction primitive and the ``iter_children``/``walk`` traversal
|
|
8
|
+
primitives.
|
|
9
|
+
|
|
10
|
+
Per {p045}, the core works only with this common model: it never imports,
|
|
11
|
+
subclasses, or otherwise depends on LibCST (or any other external
|
|
12
|
+
parser/codegen library) as a working type. Format plugins are the only code
|
|
13
|
+
allowed to touch such external libraries, and they translate between their
|
|
14
|
+
own representation and this common model at their call boundary. Nothing in
|
|
15
|
+
this file imports a format plugin, and nothing here performs storage,
|
|
16
|
+
persistence, or public-facade work.
|
|
17
|
+
|
|
18
|
+
Design notes for sibling steps:
|
|
19
|
+
|
|
20
|
+
* ``Node`` carries five reserved, inert extension-point attributes --
|
|
21
|
+
``node_id``, ``short_id``, ``extended_type``, ``buffer_range``, and
|
|
22
|
+
``references`` -- and ``Document`` carries a reserved ``document_id``.
|
|
23
|
+
All default to ``None`` (or an empty tuple for ``references``) and are
|
|
24
|
+
never read or assigned anywhere else in this file. They exist purely so
|
|
25
|
+
the sibling identity (node_id/short_id), extended-node-type, buffer-range,
|
|
26
|
+
and reference-integrity steps have a stable place to attach their own
|
|
27
|
+
behavior without renegotiating this schema.
|
|
28
|
+
* Neither ``Node`` nor ``Document`` declares ``__slots__``, and ``fields``
|
|
29
|
+
is an open ``str``-keyed mapping. This deliberately leaves room for the
|
|
30
|
+
sibling ``trivia.py`` module to attach trivia/whitespace/comment data
|
|
31
|
+
later (via a dedicated field, a side table, or a subclass) without this
|
|
32
|
+
file precluding that; no trivia/comment/whitespace storage is defined
|
|
33
|
+
here.
|
|
34
|
+
* Per requirement (7) of this step, no ad hoc exception/error-string
|
|
35
|
+
taxonomy is invented for malformed construction. All validation failures
|
|
36
|
+
raise ``NodeSchemaError``, which always carries an ``ErrorCode`` from the
|
|
37
|
+
shared catalog in ``src/tree_engine/errors.py``. Every failure in this
|
|
38
|
+
file is a shape/type mismatch between supplied construction data and the
|
|
39
|
+
node/document schema, so ``ErrorCode.INVALID_PARENT_TYPE`` -- the one
|
|
40
|
+
CORE-layer catalog code about a value not matching the type a
|
|
41
|
+
parent/container expects -- is reused consistently rather than minting a
|
|
42
|
+
new code per call site.
|
|
43
|
+
|
|
44
|
+
Source-of-truth requirement labels honored here: {p008}, {p045}, {p050}.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
from __future__ import annotations
|
|
48
|
+
|
|
49
|
+
from dataclasses import dataclass, field
|
|
50
|
+
from types import MappingProxyType
|
|
51
|
+
from typing import (
|
|
52
|
+
Any,
|
|
53
|
+
Dict,
|
|
54
|
+
Iterator,
|
|
55
|
+
Mapping,
|
|
56
|
+
Optional,
|
|
57
|
+
Sequence,
|
|
58
|
+
Tuple,
|
|
59
|
+
Union,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
from tree_engine.errors import ErrorCode
|
|
63
|
+
|
|
64
|
+
__all__ = [
|
|
65
|
+
"NodeKind",
|
|
66
|
+
"NodeSchemaError",
|
|
67
|
+
"Node",
|
|
68
|
+
"Document",
|
|
69
|
+
"make_node",
|
|
70
|
+
"iter_children",
|
|
71
|
+
"walk",
|
|
72
|
+
]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class NodeSchemaError(Exception):
|
|
76
|
+
"""Raised when Node/Document construction data violates the schema.
|
|
77
|
+
|
|
78
|
+
Always carries the originating ``ErrorCode`` from the shared catalog
|
|
79
|
+
(``src/tree_engine/errors.py``) as ``self.code``, so callers can branch
|
|
80
|
+
on the stable code rather than parsing message text.
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
def __init__(self, code: ErrorCode, message: str) -> None:
|
|
84
|
+
super().__init__(f"[{code.value}] {message}")
|
|
85
|
+
self.code = code
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class NodeKind(str):
|
|
89
|
+
"""Opaque, per-format node-kind identifier.
|
|
90
|
+
|
|
91
|
+
A ``NodeKind`` is a plain, non-empty string handle that a format plugin
|
|
92
|
+
(or test/caller) assigns to name its own node types, e.g.
|
|
93
|
+
``"python:FunctionDef"`` or ``"bsl:Procedure"``. The core namespace
|
|
94
|
+
defined in this file does not enumerate, know, or care about the
|
|
95
|
+
universe of kind strings -- per {p045} that knowledge stays inside
|
|
96
|
+
format plugins -- it only requires that a kind be a non-empty string.
|
|
97
|
+
Being a ``str`` subclass, a ``NodeKind`` compares and hashes exactly
|
|
98
|
+
like the string it wraps.
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
__slots__ = ()
|
|
102
|
+
|
|
103
|
+
def __new__(cls, value: str) -> "NodeKind":
|
|
104
|
+
if not isinstance(value, str) or not value:
|
|
105
|
+
raise NodeSchemaError(
|
|
106
|
+
ErrorCode.INVALID_PARENT_TYPE,
|
|
107
|
+
f"node kind must be a non-empty string, got {value!r}",
|
|
108
|
+
)
|
|
109
|
+
return super().__new__(cls, value)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
Primitive = Union[str, int, float, bool, bytes, None]
|
|
113
|
+
FieldValue = Union[Primitive, "Node", Tuple["Node", ...]]
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@dataclass(frozen=True)
|
|
117
|
+
class Node:
|
|
118
|
+
"""An immutable node in the common tree model.
|
|
119
|
+
|
|
120
|
+
``kind`` names the node's format-defined type. ``fields`` is a
|
|
121
|
+
read-only, ``str``-keyed mapping of named node data, where each value
|
|
122
|
+
is either a primitive (``str``, ``int``, ``float``, ``bool``,
|
|
123
|
+
``bytes``, or ``None``), a single ``Node``, or an ordered ``tuple`` of
|
|
124
|
+
``Node`` instances (an "ordered child sequence" attached under a named
|
|
125
|
+
field, e.g. a function's ``body`` field). ``children`` is the separate,
|
|
126
|
+
explicit, ordered tuple of every direct child node used by the generic
|
|
127
|
+
traversal primitives below (``iter_children``/``walk``); it may repeat
|
|
128
|
+
or reorganize node references also reachable through ``fields``, or
|
|
129
|
+
stand fully on its own -- this file does not require the two to be
|
|
130
|
+
kept in lockstep, only that each is independently well-formed.
|
|
131
|
+
|
|
132
|
+
Nodes are immutable and must be built bottom-up (a child object must
|
|
133
|
+
already exist before it can be placed in its parent's ``children`` or
|
|
134
|
+
``fields``), so no ``Node`` graph constructed through ``make_node`` can
|
|
135
|
+
ever contain a reference cycle.
|
|
136
|
+
|
|
137
|
+
Use ``make_node`` to construct a validated instance; the dataclass
|
|
138
|
+
constructor itself performs no validation, which sibling steps may
|
|
139
|
+
rely on when reconstructing an already-validated node (e.g. to attach
|
|
140
|
+
an identity produced elsewhere).
|
|
141
|
+
"""
|
|
142
|
+
|
|
143
|
+
kind: NodeKind
|
|
144
|
+
fields: Mapping[str, FieldValue]
|
|
145
|
+
children: Tuple["Node", ...]
|
|
146
|
+
|
|
147
|
+
# Reserved extension-point slots for sibling steps. Inert here: default
|
|
148
|
+
# only, never read or written anywhere else in this file.
|
|
149
|
+
node_id: Optional[Any] = None
|
|
150
|
+
short_id: Optional[Any] = None
|
|
151
|
+
extended_type: Optional[Any] = None
|
|
152
|
+
buffer_range: Optional[Any] = None
|
|
153
|
+
references: Tuple[Any, ...] = field(default_factory=tuple)
|
|
154
|
+
|
|
155
|
+
def __deepcopy__(self, memo: Dict[int, Any]) -> "Node":
|
|
156
|
+
"""``copy.deepcopy`` support (bug 554f6521 residual tier): ``fields`` is wrapped in a
|
|
157
|
+
``MappingProxyType`` by :func:`make_node`/``_validate_fields`` for immutability, and
|
|
158
|
+
``copy.deepcopy``'s default machinery has no registered handler for that type -- it
|
|
159
|
+
falls through to ``__reduce_ex__``, which raises ``TypeError: cannot pickle
|
|
160
|
+
'mappingproxy' object`` -- so ANY caller deep-copying a live tree that carries even one
|
|
161
|
+
already-frozen ``Node`` (a compound/module node's own excluded positional trivia field,
|
|
162
|
+
e.g. an ``IndentedBlock``'s ``header`` -- see ``core.live_tree.to_live``'s docstring)
|
|
163
|
+
broke outright the first time something (a session-history point-in-time reconstruction,
|
|
164
|
+
confirmed live) actually tried it. Rebuilds a structurally-identical ``Node`` with every
|
|
165
|
+
attribute independently deep-copied -- ``fields`` unwrapped to a plain ``dict``, copied,
|
|
166
|
+
and re-wrapped in a fresh ``MappingProxyType`` -- registering the result in ``memo``
|
|
167
|
+
before recursing into ``children``/``fields`` so a ``Node`` referenced from more than one
|
|
168
|
+
place in the same deepcopy call is copied once and shared, exactly as ``copy.deepcopy``
|
|
169
|
+
already guarantees for every other object graph."""
|
|
170
|
+
import copy
|
|
171
|
+
|
|
172
|
+
copied = Node(
|
|
173
|
+
kind=self.kind,
|
|
174
|
+
fields=MappingProxyType(copy.deepcopy(dict(self.fields), memo)),
|
|
175
|
+
children=copy.deepcopy(self.children, memo),
|
|
176
|
+
node_id=copy.deepcopy(self.node_id, memo),
|
|
177
|
+
short_id=copy.deepcopy(self.short_id, memo),
|
|
178
|
+
extended_type=copy.deepcopy(self.extended_type, memo),
|
|
179
|
+
buffer_range=copy.deepcopy(self.buffer_range, memo),
|
|
180
|
+
references=copy.deepcopy(self.references, memo),
|
|
181
|
+
)
|
|
182
|
+
memo[id(self)] = copied
|
|
183
|
+
return copied
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
@dataclass
|
|
187
|
+
class Document:
|
|
188
|
+
"""A tree document: an immutable ``root`` plus the format contract.
|
|
189
|
+
|
|
190
|
+
Per {p050}: ``representation_format_id`` is the mandatory format of the
|
|
191
|
+
document's *current working representation*; ``source_format_id`` is
|
|
192
|
+
the originally selected/preserved format. In the ordinary case the two
|
|
193
|
+
are equal. Under plain-text fallback, ``representation_format_id`` is
|
|
194
|
+
set to ``"plain_text"`` while ``source_format_id`` is left untouched,
|
|
195
|
+
so the original format is still known for the next open and for
|
|
196
|
+
diagnostics. ``format_id`` is the public read-only alias for
|
|
197
|
+
``representation_format_id`` -- no separate ``language`` entity is
|
|
198
|
+
introduced.
|
|
199
|
+
|
|
200
|
+
``Document`` is a plain (non-frozen) dataclass: unlike ``Node``, its
|
|
201
|
+
format-contract fields are expected to be updated in place as the
|
|
202
|
+
document's lifecycle progresses (e.g. entering or leaving plain-text
|
|
203
|
+
fallback), while ``root`` itself is still replaced wholesale (new
|
|
204
|
+
immutable ``Node`` graph in, old one out) rather than mutated.
|
|
205
|
+
"""
|
|
206
|
+
|
|
207
|
+
root: Node
|
|
208
|
+
source_format_id: str
|
|
209
|
+
# Omitting it means "ordinary case" and derives it from source_format_id
|
|
210
|
+
# ({p050}); it is set explicitly only when the two genuinely differ, as
|
|
211
|
+
# under plain-text fallback.
|
|
212
|
+
representation_format_id: Optional[str] = None
|
|
213
|
+
|
|
214
|
+
# Reserved extension-point slot for a sibling step (cross-document
|
|
215
|
+
# identity). Inert here: default only, never read or written anywhere
|
|
216
|
+
# else in this file.
|
|
217
|
+
document_id: Optional[Any] = None
|
|
218
|
+
|
|
219
|
+
def __post_init__(self) -> None:
|
|
220
|
+
if not isinstance(self.root, Node):
|
|
221
|
+
raise NodeSchemaError(
|
|
222
|
+
ErrorCode.INVALID_PARENT_TYPE,
|
|
223
|
+
f"Document.root must be a Node, got {type(self.root).__name__}",
|
|
224
|
+
)
|
|
225
|
+
_validate_format_id("source_format_id", self.source_format_id)
|
|
226
|
+
if self.representation_format_id is None:
|
|
227
|
+
self.representation_format_id = self.source_format_id
|
|
228
|
+
_validate_format_id("representation_format_id", self.representation_format_id)
|
|
229
|
+
|
|
230
|
+
@property
|
|
231
|
+
def format_id(self) -> str:
|
|
232
|
+
"""Public read-only alias for ``representation_format_id`` ({p050})."""
|
|
233
|
+
return self.representation_format_id
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def make_node(
|
|
237
|
+
kind: Union[NodeKind, str],
|
|
238
|
+
fields: Optional[Mapping[str, Any]] = None,
|
|
239
|
+
children: Sequence[Any] = (),
|
|
240
|
+
) -> Node:
|
|
241
|
+
"""Build a ``Node``, validating that kind/fields/children are consistent.
|
|
242
|
+
|
|
243
|
+
``kind`` is coerced to (and validated as) a ``NodeKind``. ``fields``
|
|
244
|
+
defaults to empty and each entry is checked against the ``FieldValue``
|
|
245
|
+
union described on ``Node``. ``children`` defaults to empty and every
|
|
246
|
+
entry must itself be a ``Node``; order is preserved exactly as given.
|
|
247
|
+
|
|
248
|
+
Raises ``NodeSchemaError`` (carrying ``ErrorCode.INVALID_PARENT_TYPE``)
|
|
249
|
+
on any shape mismatch, before constructing anything.
|
|
250
|
+
"""
|
|
251
|
+
|
|
252
|
+
validated_kind = kind if isinstance(kind, NodeKind) else NodeKind(kind)
|
|
253
|
+
validated_fields = _validate_fields(fields or {})
|
|
254
|
+
validated_children = _validate_children(children)
|
|
255
|
+
return Node(kind=validated_kind, fields=validated_fields, children=validated_children)
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def iter_children(node: Node) -> Iterator[Node]:
|
|
259
|
+
"""Yield ``node``'s direct children, in the order given at construction.
|
|
260
|
+
|
|
261
|
+
This does not recurse; it is exactly ``iter(node.children)``.
|
|
262
|
+
"""
|
|
263
|
+
|
|
264
|
+
return iter(node.children)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def walk(node: Node) -> Iterator[Node]:
|
|
268
|
+
"""Depth-first, pre-order traversal of ``node``'s subtree.
|
|
269
|
+
|
|
270
|
+
Yields ``node`` itself first, then walks each entry of
|
|
271
|
+
``node.children`` in order, recursively. Because ``Node`` is immutable
|
|
272
|
+
and every child must exist before ``make_node`` can place it in its
|
|
273
|
+
parent, a tree built through this module can never contain a
|
|
274
|
+
reference cycle, so this traversal always terminates; each distinct
|
|
275
|
+
tree position is visited exactly once, in a stable, repeatable order.
|
|
276
|
+
"""
|
|
277
|
+
|
|
278
|
+
yield node
|
|
279
|
+
for child in node.children:
|
|
280
|
+
yield from walk(child)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _is_primitive(value: Any) -> bool:
|
|
284
|
+
return value is None or isinstance(value, (str, int, float, bool, bytes))
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _validate_field_value(name: str, value: Any) -> FieldValue:
|
|
288
|
+
if _is_primitive(value):
|
|
289
|
+
return value
|
|
290
|
+
if isinstance(value, Node):
|
|
291
|
+
return value
|
|
292
|
+
if isinstance(value, (tuple, list)):
|
|
293
|
+
items = tuple(value)
|
|
294
|
+
for item in items:
|
|
295
|
+
if not isinstance(item, Node):
|
|
296
|
+
raise NodeSchemaError(
|
|
297
|
+
ErrorCode.INVALID_PARENT_TYPE,
|
|
298
|
+
f"field {name!r}: ordered child sequence entries must be "
|
|
299
|
+
f"Node instances, got {type(item).__name__}",
|
|
300
|
+
)
|
|
301
|
+
return items
|
|
302
|
+
raise NodeSchemaError(
|
|
303
|
+
ErrorCode.INVALID_PARENT_TYPE,
|
|
304
|
+
f"field {name!r} has unsupported value type {type(value).__name__}; "
|
|
305
|
+
"expected a primitive, a Node, or an ordered sequence of Node",
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _validate_fields(fields: Mapping[str, Any]) -> Mapping[str, FieldValue]:
|
|
310
|
+
if not isinstance(fields, Mapping):
|
|
311
|
+
raise NodeSchemaError(
|
|
312
|
+
ErrorCode.INVALID_PARENT_TYPE,
|
|
313
|
+
f"fields must be a mapping, got {type(fields).__name__}",
|
|
314
|
+
)
|
|
315
|
+
validated: Dict[str, FieldValue] = {}
|
|
316
|
+
for name, value in fields.items():
|
|
317
|
+
if not isinstance(name, str) or not name:
|
|
318
|
+
raise NodeSchemaError(
|
|
319
|
+
ErrorCode.INVALID_PARENT_TYPE,
|
|
320
|
+
f"field name must be a non-empty string, got {name!r}",
|
|
321
|
+
)
|
|
322
|
+
validated[name] = _validate_field_value(name, value)
|
|
323
|
+
return MappingProxyType(validated)
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _validate_children(children: Sequence[Any]) -> Tuple[Node, ...]:
|
|
327
|
+
if not isinstance(children, (tuple, list)):
|
|
328
|
+
raise NodeSchemaError(
|
|
329
|
+
ErrorCode.INVALID_PARENT_TYPE,
|
|
330
|
+
f"children must be an ordered sequence, got {type(children).__name__}",
|
|
331
|
+
)
|
|
332
|
+
validated = tuple(children)
|
|
333
|
+
for index, child in enumerate(validated):
|
|
334
|
+
if not isinstance(child, Node):
|
|
335
|
+
raise NodeSchemaError(
|
|
336
|
+
ErrorCode.INVALID_PARENT_TYPE,
|
|
337
|
+
f"children[{index}] must be a Node instance, got "
|
|
338
|
+
f"{type(child).__name__}",
|
|
339
|
+
)
|
|
340
|
+
return validated
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _validate_format_id(field_name: str, value: Any) -> None:
|
|
344
|
+
if not isinstance(value, str) or not value:
|
|
345
|
+
raise NodeSchemaError(
|
|
346
|
+
ErrorCode.INVALID_PARENT_TYPE,
|
|
347
|
+
f"Document.{field_name} must be a non-empty string, got {value!r}",
|
|
348
|
+
)
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Character-offset to UTF-8 byte-offset conversion for ``buffer_range`` (bug b548f445).
|
|
2
|
+
|
|
3
|
+
Author: Vasiliy Zdanovskiy
|
|
4
|
+
email: vasilyvz@gmail.com
|
|
5
|
+
|
|
6
|
+
Plugins scan their source as ``str`` and so measure positions in characters, while
|
|
7
|
+
``buffer_range`` is a half-open ``(start, end)`` pair of UTF-8 BYTE offsets into the source bytes
|
|
8
|
+
(the unit the python plugin already uses). :func:`char_to_byte_offset` bridges the two in O(n) once
|
|
9
|
+
per document and O(1) per lookup; for pure-ASCII text it is the identity.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from itertools import accumulate
|
|
15
|
+
from typing import Callable
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def char_to_byte_offset(text: str) -> Callable[[int], int]:
|
|
19
|
+
"""Return ``f(char_index) -> byte_index`` for ``text`` encoded as UTF-8 (``0 <= index <= len(text)``)."""
|
|
20
|
+
if text.isascii():
|
|
21
|
+
return lambda index: index
|
|
22
|
+
table = [0]
|
|
23
|
+
table.extend(accumulate(len(ch.encode("utf-8", "surrogateescape")) for ch in text))
|
|
24
|
+
return table.__getitem__
|