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,359 @@
|
|
|
1
|
+
"""Lossless YAML reader for the format plugin (concept C-016, step G-023/T-001/A-005).
|
|
2
|
+
|
|
3
|
+
Author: Vasiliy Zdanovskiy
|
|
4
|
+
email: vasilyvz@gmail.com
|
|
5
|
+
|
|
6
|
+
Scope: turning YAML *block* structure -- indentation, entries, scalars, block
|
|
7
|
+
scalars, trivia and document markers -- into common-model nodes without losing
|
|
8
|
+
a single byte. :class:`YamlReader` inherits the flow-collection reader from
|
|
9
|
+
:mod:`.flow`, so one object reads both syntaxes; node construction lives in
|
|
10
|
+
:mod:`.builder` and the lexical predicates in :mod:`.scanner`. This module
|
|
11
|
+
does not implement the plugin contract and never renders anything back --
|
|
12
|
+
``plugin.py`` and ``emitter.py`` own those.
|
|
13
|
+
|
|
14
|
+
The byte-fidelity scheme ({p022}) is the whole design. Every byte of the
|
|
15
|
+
source ends up owned by exactly one node:
|
|
16
|
+
|
|
17
|
+
* trivia and scalars store their own text verbatim in ``fields["raw"]``;
|
|
18
|
+
* every entry and every flow container stores the text before its value in
|
|
19
|
+
``fields["head"]`` and the text after it in ``fields["tail"]``.
|
|
20
|
+
|
|
21
|
+
So a node renders as ``head + rendered children + tail``, the concatenation of
|
|
22
|
+
a whole tree reproduces the source exactly, and -- unlike a scheme that stores
|
|
23
|
+
one raw blob per subtree -- editing a nested node really does change the
|
|
24
|
+
output, because each ancestor's text is assembled from its live children
|
|
25
|
+
rather than replayed from a stale copy.
|
|
26
|
+
|
|
27
|
+
Trivia lines become nodes of their own, attached to the innermost block open
|
|
28
|
+
at that point. Which block owns a comment is a semantic nicety; the rendered
|
|
29
|
+
order, and therefore byte identity, is the same either way.
|
|
30
|
+
|
|
31
|
+
Source-of-truth requirement labels honored here: {p013}, {p022}, {p049},
|
|
32
|
+
{p097}.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
from __future__ import annotations
|
|
36
|
+
|
|
37
|
+
import bisect
|
|
38
|
+
from types import MappingProxyType
|
|
39
|
+
from typing import List, Optional, Tuple
|
|
40
|
+
|
|
41
|
+
from tree_engine.core.nodes import Node
|
|
42
|
+
from tree_engine.plugins.yaml.builder import NodeBuilder
|
|
43
|
+
from tree_engine.plugins.yaml.flow import ANCHOR_MESSAGE, FlowReader
|
|
44
|
+
from tree_engine.plugins.yaml.scanner import (
|
|
45
|
+
BLOCK_HEADER_RE, ENTRY_KINDS, FLOW_OPENERS, KIND_BLANK, KIND_BLOCK, KIND_COMMENT,
|
|
46
|
+
KIND_ITEM, KIND_MAPPING, KIND_MARKER, KIND_PAIR, KIND_SCALAR, KIND_SEQUENCE,
|
|
47
|
+
KIND_TRIVIA, NO_TRANSLATION, decode_block, decode_scalar, find_colon, indent_of,
|
|
48
|
+
is_marker, is_trivia, scan_quoted, starts_item, syntax, unsupported,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
__all__ = ["patch_head", "YamlReader"]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def patch_head(node: Node, marker: str, width: int) -> Node:
|
|
55
|
+
"""Give a compact ``- key: value`` marker back to its deepest first entry.
|
|
56
|
+
|
|
57
|
+
To read the compact form the reader rewrites the ``- `` marker to spaces,
|
|
58
|
+
so the nested block sees a normally indented first line and needs no
|
|
59
|
+
special case. That rewrite must not reach the tree, so this puts the
|
|
60
|
+
original marker text back on the first entry that actually owns a head --
|
|
61
|
+
recursing through nested compact items such as ``- - a``, whose outer item
|
|
62
|
+
holds no head of its own. Identity is preserved: the rebuilt node keeps
|
|
63
|
+
its ``node_id`` and ``short_id``.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
fields, children = node.fields, node.children
|
|
67
|
+
if node.kind in ENTRY_KINDS and fields.get("head"):
|
|
68
|
+
merged = dict(fields)
|
|
69
|
+
merged["head"] = marker + str(fields["head"])[width:]
|
|
70
|
+
fields = MappingProxyType(merged)
|
|
71
|
+
elif children:
|
|
72
|
+
children = (patch_head(children[0], marker, width),) + children[1:]
|
|
73
|
+
else:
|
|
74
|
+
return node
|
|
75
|
+
return Node(kind=node.kind, fields=fields, children=children,
|
|
76
|
+
node_id=node.node_id, short_id=node.short_id)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class YamlReader(FlowReader):
|
|
80
|
+
"""Reads one YAML source text into common-model nodes.
|
|
81
|
+
|
|
82
|
+
The reader works on two coordinate systems at once: a list of lines with
|
|
83
|
+
their terminators, for block structure and indentation, and the original
|
|
84
|
+
flat text with a per-line start offset table, for constructs that may run
|
|
85
|
+
past a line end (quoted scalars, continued plain scalars, multi-line flow
|
|
86
|
+
collections). Nothing but common-model nodes ever leaves this class, so no
|
|
87
|
+
internal representation can cross the plugin boundary.
|
|
88
|
+
"""
|
|
89
|
+
|
|
90
|
+
def __init__(self, text: str, builder: NodeBuilder) -> None:
|
|
91
|
+
self.text = text
|
|
92
|
+
self.lines = text.splitlines(keepends=True)
|
|
93
|
+
self.count = len(self.lines)
|
|
94
|
+
self.builder = builder
|
|
95
|
+
self.starts = [0]
|
|
96
|
+
for line in self.lines:
|
|
97
|
+
self.starts.append(self.starts[-1] + len(line))
|
|
98
|
+
for number, line in enumerate(self.lines, start=1):
|
|
99
|
+
if line.strip() and "\t" in line[:indent_of(line) + 1]:
|
|
100
|
+
raise syntax("tab character in indentation", number)
|
|
101
|
+
|
|
102
|
+
# -- shared position helpers ------------------------------------------
|
|
103
|
+
|
|
104
|
+
def _span(self, first: int, begin: int, node: Node, end: int) -> Tuple[str, Node, str, int]:
|
|
105
|
+
"""Wrap a value that occupies ``begin``..``end`` into an entry's parts.
|
|
106
|
+
|
|
107
|
+
``first`` is the line the owning entry starts on, which is not always
|
|
108
|
+
the line the value starts on: a plain scalar written under its key
|
|
109
|
+
begins further down, and every byte in between -- the line break, any
|
|
110
|
+
trivia, the indentation -- stays in the head.
|
|
111
|
+
"""
|
|
112
|
+
|
|
113
|
+
row = min(bisect.bisect_right(self.starts, end) - 1, self.count - 1)
|
|
114
|
+
tail = self.text[end:self.starts[row] + len(self.lines[row])]
|
|
115
|
+
return self.text[self.starts[first]:begin], node, tail, row + 1
|
|
116
|
+
|
|
117
|
+
# -- block structure ---------------------------------------------------
|
|
118
|
+
|
|
119
|
+
def read_stream(self) -> List[Node]:
|
|
120
|
+
"""Read the whole line stream into the top-level document children."""
|
|
121
|
+
|
|
122
|
+
children: List[Node] = []
|
|
123
|
+
index = 0
|
|
124
|
+
while index < self.count:
|
|
125
|
+
if is_marker(self.lines[index]):
|
|
126
|
+
children.append(self.builder.node(KIND_MARKER, {"raw": self.lines[index]}))
|
|
127
|
+
index += 1
|
|
128
|
+
continue
|
|
129
|
+
block, after = self.read_block(index, -1)
|
|
130
|
+
if after == index:
|
|
131
|
+
raise syntax("cannot classify line", index + 1)
|
|
132
|
+
children.append(block)
|
|
133
|
+
index = after
|
|
134
|
+
return children
|
|
135
|
+
|
|
136
|
+
def _next_entry(self, index: int) -> Optional[int]:
|
|
137
|
+
"""Return the index of the first non-trivia line at/after ``index``."""
|
|
138
|
+
|
|
139
|
+
while index < self.count and is_trivia(self.lines[index]):
|
|
140
|
+
index += 1
|
|
141
|
+
return index if index < self.count else None
|
|
142
|
+
|
|
143
|
+
def read_block(self, index: int, min_indent: int, seq_equal: bool = False) -> Tuple[Node, int]:
|
|
144
|
+
"""Read one indentation block: its entries plus the trivia between them.
|
|
145
|
+
|
|
146
|
+
The first entry fixes the block's indentation. ``seq_equal`` marks the
|
|
147
|
+
YAML form where a sequence sits at the same indentation as the key it
|
|
148
|
+
belongs to, in which case a same-indent line that is not a ``-`` entry
|
|
149
|
+
ends the block rather than joining it.
|
|
150
|
+
"""
|
|
151
|
+
|
|
152
|
+
children: List[Node] = []
|
|
153
|
+
block_indent: Optional[int] = None
|
|
154
|
+
kind: Optional[str] = None
|
|
155
|
+
while index < self.count:
|
|
156
|
+
line = self.lines[index]
|
|
157
|
+
if is_marker(line):
|
|
158
|
+
break
|
|
159
|
+
if is_trivia(line):
|
|
160
|
+
trivia = KIND_BLANK if not line.strip() else KIND_COMMENT
|
|
161
|
+
children.append(self.builder.node(trivia, {"raw": line}))
|
|
162
|
+
index += 1
|
|
163
|
+
continue
|
|
164
|
+
indent = indent_of(line)
|
|
165
|
+
if block_indent is None:
|
|
166
|
+
if indent < min_indent or (indent == min_indent
|
|
167
|
+
and not (seq_equal and starts_item(line, indent))):
|
|
168
|
+
break
|
|
169
|
+
block_indent = indent
|
|
170
|
+
elif indent < block_indent:
|
|
171
|
+
break
|
|
172
|
+
elif seq_equal and not starts_item(line, indent):
|
|
173
|
+
break # a same-indent sequence ends where its parent mapping resumes
|
|
174
|
+
elif indent > block_indent:
|
|
175
|
+
raise syntax("unexpected indentation", index + 1)
|
|
176
|
+
entry, index = self.read_entry(index, block_indent)
|
|
177
|
+
entry_kind = KIND_SEQUENCE if entry.kind == KIND_ITEM else KIND_MAPPING
|
|
178
|
+
if kind is None:
|
|
179
|
+
kind = entry_kind
|
|
180
|
+
elif kind != entry_kind:
|
|
181
|
+
raise syntax("mapping and sequence entries in one block", index)
|
|
182
|
+
children.append(entry)
|
|
183
|
+
return self.builder.node(kind or KIND_TRIVIA, {}, children), index
|
|
184
|
+
|
|
185
|
+
def read_entry(self, index: int, indent: int) -> Tuple[Node, int]:
|
|
186
|
+
"""Read one mapping pair or one sequence item together with its value."""
|
|
187
|
+
|
|
188
|
+
line = self.lines[index]
|
|
189
|
+
if starts_item(line, indent):
|
|
190
|
+
head, value, tail, after = self.read_value(index, indent + 1, indent, False, True)
|
|
191
|
+
kind, fields = KIND_ITEM, {"head": head, "tail": tail}
|
|
192
|
+
else:
|
|
193
|
+
key_raw, colon = self._scan_key(line, indent, index + 1)
|
|
194
|
+
head, value, tail, after = self.read_value(index, colon + 1, indent, True, False)
|
|
195
|
+
kind = KIND_PAIR
|
|
196
|
+
fields = {"key": decode_scalar(key_raw), "key_raw": key_raw,
|
|
197
|
+
"head": head, "tail": tail}
|
|
198
|
+
return self.builder.node(kind, fields, (value,) if value is not None else ()), after
|
|
199
|
+
|
|
200
|
+
def _scan_key(self, line: str, start: int, number: int) -> Tuple[str, int]:
|
|
201
|
+
"""Return a block mapping key's source text and its ``:`` separator index."""
|
|
202
|
+
|
|
203
|
+
if line[start] in NO_TRANSLATION:
|
|
204
|
+
raise unsupported("Anchored", f"YAML indicator {line[start]!r} {ANCHOR_MESSAGE}")
|
|
205
|
+
if line[start] in FLOW_OPENERS:
|
|
206
|
+
raise unsupported("FlowKey", "a flow collection used as a block mapping key "
|
|
207
|
+
"is outside this plugin's subset")
|
|
208
|
+
if line[start] in "\"'":
|
|
209
|
+
end = index = scan_quoted(line, start, number)
|
|
210
|
+
while index < len(line) and line[index] == " ":
|
|
211
|
+
index += 1
|
|
212
|
+
if index >= len(line) or line[index] != ":":
|
|
213
|
+
raise syntax("expected ':' after a quoted mapping key", number)
|
|
214
|
+
return line[start:end], index
|
|
215
|
+
colon = find_colon(line, start)
|
|
216
|
+
if colon < 0:
|
|
217
|
+
raise syntax("expected a mapping or sequence entry", number)
|
|
218
|
+
key_raw = line[start:colon].rstrip(" ")
|
|
219
|
+
if not key_raw:
|
|
220
|
+
raise syntax("empty mapping key", number)
|
|
221
|
+
if key_raw.startswith("<<"):
|
|
222
|
+
raise unsupported("MergeKey", "YAML merge keys ('<<') cannot round-trip faithfully")
|
|
223
|
+
return key_raw, colon
|
|
224
|
+
|
|
225
|
+
def read_value(self, index: int, start: int, indent: int, allow_same: bool,
|
|
226
|
+
compact: bool) -> Tuple[str, Optional[Node], str, int]:
|
|
227
|
+
"""Read one entry's value as ``(head, value, tail, next_index)``.
|
|
228
|
+
|
|
229
|
+
``start`` is the column just past the ``:`` or ``-`` that introduced
|
|
230
|
+
the value. ``allow_same`` permits a block sequence at the entry's own
|
|
231
|
+
indentation (legal only under a mapping key); ``compact`` permits the
|
|
232
|
+
``- key: value`` form (legal only for a sequence item).
|
|
233
|
+
"""
|
|
234
|
+
|
|
235
|
+
line = self.lines[index]
|
|
236
|
+
rest = line[start:]
|
|
237
|
+
if not rest.strip() or rest.lstrip(" ").startswith("#"):
|
|
238
|
+
return self._value_below(index, indent, allow_same, line)
|
|
239
|
+
position = start
|
|
240
|
+
while position < len(line) and line[position] == " ":
|
|
241
|
+
position += 1
|
|
242
|
+
char = line[position]
|
|
243
|
+
if char in NO_TRANSLATION:
|
|
244
|
+
raise unsupported("Anchored", f"YAML indicator {char!r} {ANCHOR_MESSAGE}")
|
|
245
|
+
if char in FLOW_OPENERS:
|
|
246
|
+
begin = self.starts[index] + position
|
|
247
|
+
node, end = self.read_flow(begin)
|
|
248
|
+
return self._span(index, begin, node, end)
|
|
249
|
+
if char in "|>":
|
|
250
|
+
return self._read_block_scalar(index, position, indent)
|
|
251
|
+
if compact and (starts_item(line, position) or find_colon(line, position) >= 0):
|
|
252
|
+
marker = line[:position]
|
|
253
|
+
self.lines[index] = " " * position + line[position:]
|
|
254
|
+
block, after = self.read_block(index, position - 1)
|
|
255
|
+
return "", patch_head(block, marker, position), "", after
|
|
256
|
+
return self._scalar_value(index, index, position, indent)
|
|
257
|
+
|
|
258
|
+
def _value_below(self, index: int, indent: int, allow_same: bool,
|
|
259
|
+
line: str) -> Tuple[str, Optional[Node], str, int]:
|
|
260
|
+
"""Resolve an entry whose line ends after the ``:`` or ``-``.
|
|
261
|
+
|
|
262
|
+
What follows is a nested block, a plain scalar written on the lines
|
|
263
|
+
below, or nothing at all (a null value).
|
|
264
|
+
"""
|
|
265
|
+
|
|
266
|
+
nxt = self._next_entry(index + 1)
|
|
267
|
+
if nxt is not None and not is_marker(self.lines[nxt]):
|
|
268
|
+
deeper = indent_of(self.lines[nxt])
|
|
269
|
+
entry = self.lines[nxt]
|
|
270
|
+
same = allow_same and deeper == indent and starts_item(entry, deeper)
|
|
271
|
+
if same or (deeper > indent and (starts_item(entry, deeper)
|
|
272
|
+
or find_colon(entry, deeper) >= 0)):
|
|
273
|
+
block, after = self.read_block(index + 1, indent, same)
|
|
274
|
+
return line, block, "", after
|
|
275
|
+
if deeper > indent:
|
|
276
|
+
return self._scalar_value(index, nxt, deeper, indent)
|
|
277
|
+
return line, None, "", index + 1
|
|
278
|
+
|
|
279
|
+
def _scalar_value(self, first: int, index: int, start: int,
|
|
280
|
+
indent: int) -> Tuple[str, Node, str, int]:
|
|
281
|
+
"""Build a scalar value node whose head reaches back to line ``first``."""
|
|
282
|
+
|
|
283
|
+
begin = self.starts[index] + start
|
|
284
|
+
raw, end = self._read_scalar(index, start, indent)
|
|
285
|
+
fields = {"raw": raw, "value": decode_scalar(raw),
|
|
286
|
+
"style": raw[0] if raw[0] in "\"'" else "plain"}
|
|
287
|
+
return self._span(first, begin, self.builder.node(KIND_SCALAR, fields), end)
|
|
288
|
+
|
|
289
|
+
def _plain_end(self, start: int) -> int:
|
|
290
|
+
"""Return the end offset of one plain-scalar line segment from ``start``."""
|
|
291
|
+
|
|
292
|
+
end = start
|
|
293
|
+
while end < len(self.text):
|
|
294
|
+
char = self.text[end]
|
|
295
|
+
if char == "\n" or (char == "#" and end > start and self.text[end - 1] == " "):
|
|
296
|
+
break
|
|
297
|
+
end += 1
|
|
298
|
+
while end > start and self.text[end - 1] in " \r":
|
|
299
|
+
end -= 1
|
|
300
|
+
return end
|
|
301
|
+
|
|
302
|
+
def _read_scalar(self, index: int, start: int, indent: int) -> Tuple[str, int]:
|
|
303
|
+
"""Read one inline scalar at line ``index``, column ``start``.
|
|
304
|
+
|
|
305
|
+
Returns its verbatim source text and its absolute end offset. A quoted
|
|
306
|
+
scalar may run past the line end. A plain scalar absorbs every
|
|
307
|
+
following line that is more indented than ``indent`` and is not itself
|
|
308
|
+
an entry, a marker, or trivia -- YAML's multi-line plain scalar.
|
|
309
|
+
"""
|
|
310
|
+
|
|
311
|
+
begin = self.starts[index] + start
|
|
312
|
+
if self.text[begin] in "\"'":
|
|
313
|
+
end = scan_quoted(self.text, begin, index + 1)
|
|
314
|
+
return self.text[begin:end], end
|
|
315
|
+
end = self._plain_end(begin)
|
|
316
|
+
if end == begin:
|
|
317
|
+
raise syntax("empty scalar value", index + 1)
|
|
318
|
+
while True:
|
|
319
|
+
newline = self.text.find("\n", end)
|
|
320
|
+
if newline < 0 or self.text[end:newline].strip():
|
|
321
|
+
break # a trailing comment ends the scalar; only spaces may follow
|
|
322
|
+
row = bisect.bisect_right(self.starts, newline)
|
|
323
|
+
if row >= self.count or is_trivia(self.lines[row]) or is_marker(self.lines[row]):
|
|
324
|
+
break
|
|
325
|
+
below, line = indent_of(self.lines[row]), self.lines[row]
|
|
326
|
+
if below < indent or (below == indent and (starts_item(line, below)
|
|
327
|
+
or find_colon(line, below) >= 0)):
|
|
328
|
+
break # a sibling entry, not a continuation of this scalar
|
|
329
|
+
head = self.starts[row] + below
|
|
330
|
+
stop = self._plain_end(head)
|
|
331
|
+
if stop == head:
|
|
332
|
+
break
|
|
333
|
+
end = stop
|
|
334
|
+
return self.text[begin:end], end
|
|
335
|
+
|
|
336
|
+
def _read_block_scalar(self, index: int, start: int,
|
|
337
|
+
indent: int) -> Tuple[str, Node, str, int]:
|
|
338
|
+
"""Read a ``|``/``>`` header line plus every body line it owns."""
|
|
339
|
+
|
|
340
|
+
line = self.lines[index]
|
|
341
|
+
header = line[start:].rstrip("\r\n").rstrip(" ")
|
|
342
|
+
comment = header.find(" #")
|
|
343
|
+
if comment >= 0:
|
|
344
|
+
header = header[:comment].rstrip(" ")
|
|
345
|
+
if not BLOCK_HEADER_RE.fullmatch(header):
|
|
346
|
+
raise unsupported("BlockScalar", f"unsupported block scalar header {header!r}")
|
|
347
|
+
body: List[str] = []
|
|
348
|
+
cursor = index + 1
|
|
349
|
+
while cursor < self.count and (not self.lines[cursor].strip()
|
|
350
|
+
or indent_of(self.lines[cursor]) > indent):
|
|
351
|
+
body.append(self.lines[cursor])
|
|
352
|
+
cursor += 1
|
|
353
|
+
if not header.endswith("+"): # trailing blanks are the enclosing block's trivia
|
|
354
|
+
while body and not body[-1].strip():
|
|
355
|
+
body.pop()
|
|
356
|
+
cursor -= 1
|
|
357
|
+
fields = {"raw": "".join(body), "style": header,
|
|
358
|
+
"value": decode_block(header, body, indent)}
|
|
359
|
+
return line, self.builder.node(KIND_BLOCK, fields), "", cursor
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
"""Lexical layer of the YAML format plugin (concept C-016, step G-023/T-001/A-005).
|
|
2
|
+
|
|
3
|
+
Author: Vasiliy Zdanovskiy
|
|
4
|
+
email: vasilyvz@gmail.com
|
|
5
|
+
|
|
6
|
+
Scope: the vocabulary every other module of ``tree_engine.plugins.yaml`` is
|
|
7
|
+
built on -- the node-kind names, the typed-error shorthands, the single-line
|
|
8
|
+
predicates that classify a source line, and the scalar decoders that turn one
|
|
9
|
+
piece of source text into a YAML 1.2 core-schema value. Nothing here knows
|
|
10
|
+
about block structure, node identity, or the plugin contract: that is
|
|
11
|
+
``reader.py``, ``emitter.py``, and ``plugin.py`` respectively. This module
|
|
12
|
+
imports only the standard library and the shared ``tree_engine`` error
|
|
13
|
+
hierarchy, never a third-party YAML library and never the legacy editor
|
|
14
|
+
package.
|
|
15
|
+
|
|
16
|
+
Two error vocabularies meet here and must not be confused:
|
|
17
|
+
|
|
18
|
+
* :class:`YamlSyntaxError` is package-private and purely internal. The reader
|
|
19
|
+
raises it for damaged source; ``plugin.py`` is the only place allowed to
|
|
20
|
+
catch it, and it converts it to ``FormatContentParseFailed`` for a whole
|
|
21
|
+
document or ``FormatFragmentParseFailed`` for a fragment. It never escapes
|
|
22
|
+
the plugin boundary.
|
|
23
|
+
* :func:`unsupported` builds the public
|
|
24
|
+
``tree_engine.exceptions.UnsupportedTranslation`` for a construct that is
|
|
25
|
+
well-formed YAML but has no faithful representation in this plugin's model.
|
|
26
|
+
It propagates to the caller unchanged.
|
|
27
|
+
|
|
28
|
+
:func:`contract_error` is reserved for a caller violating the calling contract
|
|
29
|
+
(passing a value of the wrong type); it is never used for malformed input.
|
|
30
|
+
|
|
31
|
+
Source-of-truth requirement labels honored here: {p022}, {p049}, {p062}.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
from __future__ import annotations
|
|
35
|
+
|
|
36
|
+
import json
|
|
37
|
+
import re
|
|
38
|
+
from typing import Union
|
|
39
|
+
|
|
40
|
+
from tree_engine.exceptions import FormatPluginContractError, UnsupportedTranslation
|
|
41
|
+
|
|
42
|
+
__all__ = [
|
|
43
|
+
"FORMAT_ID",
|
|
44
|
+
"KIND_DOCUMENT", "KIND_MAPPING", "KIND_PAIR", "KIND_SEQUENCE", "KIND_ITEM",
|
|
45
|
+
"KIND_SCALAR", "KIND_BLOCK", "KIND_FLOW_MAPPING", "KIND_FLOW_PAIR",
|
|
46
|
+
"KIND_FLOW_SEQUENCE", "KIND_FLOW_ITEM", "KIND_COMMENT", "KIND_BLANK",
|
|
47
|
+
"KIND_MARKER", "KIND_TRIVIA",
|
|
48
|
+
"RAW_KINDS", "STRUCTURE_KINDS", "MAPPING_KINDS", "SEQUENCE_KINDS", "PAIR_KINDS",
|
|
49
|
+
"ENTRY_KINDS", "VALUE_KINDS", "TRIVIA_KINDS",
|
|
50
|
+
"NO_TRANSLATION", "FLOW_OPENERS", "FLOW_INDICATORS", "BLOCK_HEADER_RE",
|
|
51
|
+
"YamlSyntaxError", "syntax", "unsupported", "contract_error",
|
|
52
|
+
"indent_of", "is_trivia", "is_marker", "starts_item", "find_colon", "scan_quoted",
|
|
53
|
+
"fold", "decode_scalar", "decode_block",
|
|
54
|
+
]
|
|
55
|
+
|
|
56
|
+
FORMAT_ID = "yaml"
|
|
57
|
+
|
|
58
|
+
#: One namespaced ``NodeKind`` string per construct this plugin models. Block
|
|
59
|
+
#: and flow collections are deliberately distinct kinds: they carry the same
|
|
60
|
+
#: data but completely different source syntax, and keeping them apart is what
|
|
61
|
+
#: lets the emitter reproduce each one verbatim.
|
|
62
|
+
(KIND_DOCUMENT, KIND_MAPPING, KIND_PAIR, KIND_SEQUENCE, KIND_ITEM, KIND_SCALAR,
|
|
63
|
+
KIND_BLOCK, KIND_FLOW_MAPPING, KIND_FLOW_PAIR, KIND_FLOW_SEQUENCE, KIND_FLOW_ITEM,
|
|
64
|
+
KIND_COMMENT, KIND_BLANK, KIND_MARKER, KIND_TRIVIA) = [
|
|
65
|
+
f"{FORMAT_ID}:{name}" for name in (
|
|
66
|
+
"Document", "Mapping", "Pair", "Sequence", "Item", "Scalar", "BlockScalar",
|
|
67
|
+
"FlowMapping", "FlowPair", "FlowSequence", "FlowItem",
|
|
68
|
+
"Comment", "Blank", "Marker", "Trivia")]
|
|
69
|
+
|
|
70
|
+
#: Leaf kinds whose whole source text is stored verbatim in ``fields["raw"]``.
|
|
71
|
+
RAW_KINDS = (KIND_COMMENT, KIND_BLANK, KIND_MARKER, KIND_SCALAR, KIND_BLOCK)
|
|
72
|
+
|
|
73
|
+
#: Kinds rendered as ``head + rendered children + tail``. Block containers
|
|
74
|
+
#: simply carry no head or tail, so one uniform rule covers every one of them.
|
|
75
|
+
STRUCTURE_KINDS = (KIND_DOCUMENT, KIND_MAPPING, KIND_SEQUENCE, KIND_TRIVIA,
|
|
76
|
+
KIND_FLOW_MAPPING, KIND_FLOW_SEQUENCE,
|
|
77
|
+
KIND_PAIR, KIND_ITEM, KIND_FLOW_PAIR, KIND_FLOW_ITEM)
|
|
78
|
+
|
|
79
|
+
MAPPING_KINDS = (KIND_MAPPING, KIND_FLOW_MAPPING)
|
|
80
|
+
SEQUENCE_KINDS = (KIND_SEQUENCE, KIND_FLOW_SEQUENCE)
|
|
81
|
+
PAIR_KINDS = (KIND_PAIR, KIND_FLOW_PAIR)
|
|
82
|
+
ENTRY_KINDS = (KIND_PAIR, KIND_ITEM, KIND_FLOW_PAIR, KIND_FLOW_ITEM)
|
|
83
|
+
VALUE_KINDS = (KIND_MAPPING, KIND_SEQUENCE, KIND_SCALAR, KIND_BLOCK,
|
|
84
|
+
KIND_FLOW_MAPPING, KIND_FLOW_SEQUENCE)
|
|
85
|
+
TRIVIA_KINDS = (KIND_COMMENT, KIND_BLANK)
|
|
86
|
+
|
|
87
|
+
#: Anchor, alias, tag and explicit-key indicators. Each of these carries
|
|
88
|
+
#: identity or type information that this plugin's model cannot reproduce, so
|
|
89
|
+
#: every one of them raises ``UNSUPPORTED_TRANSLATION`` instead of being
|
|
90
|
+
#: silently flattened.
|
|
91
|
+
NO_TRANSLATION = "&*!?"
|
|
92
|
+
FLOW_OPENERS = "{["
|
|
93
|
+
FLOW_INDICATORS = ",{}[]"
|
|
94
|
+
|
|
95
|
+
_INT_RE = re.compile(r"[-+]?[0-9]+")
|
|
96
|
+
_FLOAT_RE = re.compile(
|
|
97
|
+
r"[-+]?(?:[0-9]*\.[0-9]+|[0-9]+\.[0-9]*)(?:[eE][-+]?[0-9]+)?|[-+]?[0-9]+[eE][-+]?[0-9]+")
|
|
98
|
+
#: A block-scalar header: the style indicator plus optional explicit indent
|
|
99
|
+
#: and chomping indicators, in either order (``|``, ``>-``, ``|2+``, ...).
|
|
100
|
+
BLOCK_HEADER_RE = re.compile(r"[|>](?:[1-9][+-]?|[+-]?[1-9]?)")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class YamlSyntaxError(Exception):
|
|
104
|
+
"""Package-private malformed-YAML signal.
|
|
105
|
+
|
|
106
|
+
Raised by the reader, caught only in ``plugin.py``, and translated there
|
|
107
|
+
into the public ``FormatContentParseFailed`` / ``FormatFragmentParseFailed``
|
|
108
|
+
exception appropriate to the call. It never crosses the plugin boundary.
|
|
109
|
+
|
|
110
|
+
``line`` is the 1-based source line of the failure and ``column`` its 1-based column; the scanner
|
|
111
|
+
knows only lines today, so ``column`` is 1 (the column follows in a later release).
|
|
112
|
+
"""
|
|
113
|
+
|
|
114
|
+
def __init__(self, message: str = "", line: int = 1, column: int = 1) -> None:
|
|
115
|
+
super().__init__(message)
|
|
116
|
+
self.line = max(1, int(line))
|
|
117
|
+
self.column = max(1, int(column))
|
|
118
|
+
self.bare_message = message
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def syntax(message: str, number: int) -> YamlSyntaxError:
|
|
122
|
+
"""Build a :class:`YamlSyntaxError` naming the 1-based source line."""
|
|
123
|
+
|
|
124
|
+
return YamlSyntaxError(f"{message} (line {number})", line=number)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def unsupported(node_type: str, message: str) -> UnsupportedTranslation:
|
|
128
|
+
"""Build the public ``UNSUPPORTED_TRANSLATION`` error for ``node_type``."""
|
|
129
|
+
|
|
130
|
+
return UnsupportedTranslation(message, node_type=node_type, format_id=FORMAT_ID)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def contract_error(message: str) -> FormatPluginContractError:
|
|
134
|
+
"""Build the ``FORMAT_PLUGIN_CONTRACT_ERROR`` for a bad caller argument."""
|
|
135
|
+
|
|
136
|
+
return FormatPluginContractError(message, plugin_id=FORMAT_ID)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def indent_of(line: str) -> int:
|
|
140
|
+
"""Return the number of leading spaces on ``line``."""
|
|
141
|
+
|
|
142
|
+
return len(line) - len(line.lstrip(" "))
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def is_trivia(line: str) -> bool:
|
|
146
|
+
"""Return whether ``line`` is blank or holds nothing but a comment."""
|
|
147
|
+
|
|
148
|
+
return not line.strip() or line.lstrip(" ").startswith("#")
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def is_marker(line: str) -> bool:
|
|
152
|
+
"""Return whether ``line`` is a ``---`` or ``...`` document marker."""
|
|
153
|
+
|
|
154
|
+
text = line.rstrip("\r\n")
|
|
155
|
+
return text in ("---", "...") or text[:4] in ("--- ", "... ")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def starts_item(line: str, indent: int) -> bool:
|
|
159
|
+
"""Return whether ``line`` carries a block-sequence ``-`` marker at ``indent``.
|
|
160
|
+
|
|
161
|
+
The dash must be followed by whitespace or the line end; ``-1`` is a
|
|
162
|
+
scalar, not a sequence entry.
|
|
163
|
+
"""
|
|
164
|
+
|
|
165
|
+
if indent >= len(line) or line[indent] != "-":
|
|
166
|
+
return False
|
|
167
|
+
return indent + 1 >= len(line) or line[indent + 1] in " \t\r\n"
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def find_colon(line: str, start: int) -> int:
|
|
171
|
+
"""Return the index of the ``key: value`` separator at/after ``start``, else ``-1``.
|
|
172
|
+
|
|
173
|
+
A token that opens with a quote is skipped whole, so a ``:`` inside a
|
|
174
|
+
quoted scalar can never masquerade as a mapping separator. A token that
|
|
175
|
+
opens a flow collection is rejected outright: a flow collection is a value
|
|
176
|
+
or a whole node, never the start of a block mapping key here.
|
|
177
|
+
"""
|
|
178
|
+
|
|
179
|
+
index = start
|
|
180
|
+
if index < len(line) and line[index] in FLOW_OPENERS:
|
|
181
|
+
return -1
|
|
182
|
+
if index < len(line) and line[index] in "\"'":
|
|
183
|
+
try:
|
|
184
|
+
index = scan_quoted(line, index, 0)
|
|
185
|
+
except YamlSyntaxError:
|
|
186
|
+
return -1
|
|
187
|
+
while index < len(line):
|
|
188
|
+
char = line[index]
|
|
189
|
+
if char in "\r\n" or (char == "#" and index > start and line[index - 1] == " "):
|
|
190
|
+
return -1
|
|
191
|
+
if char == ":" and (index + 1 >= len(line) or line[index + 1] in " \r\n"):
|
|
192
|
+
return index
|
|
193
|
+
index += 1
|
|
194
|
+
return -1
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def scan_quoted(text: str, start: int, number: int) -> int:
|
|
198
|
+
"""Return the index just past the quoted scalar beginning at ``start``.
|
|
199
|
+
|
|
200
|
+
``text`` bounds the scan, and that is deliberate: callers pass a single
|
|
201
|
+
line when a construct may not span lines (a block mapping key) and the
|
|
202
|
+
whole document when it may (any quoted value), so one function serves
|
|
203
|
+
both without a mode flag.
|
|
204
|
+
"""
|
|
205
|
+
|
|
206
|
+
quote, index = text[start], start + 1
|
|
207
|
+
while index < len(text):
|
|
208
|
+
char = text[index]
|
|
209
|
+
if char == "\\" and quote == '"':
|
|
210
|
+
index += 2
|
|
211
|
+
elif char == quote:
|
|
212
|
+
if quote == "'" and text[index + 1:index + 2] == "'":
|
|
213
|
+
index += 2 # a doubled single quote is an escaped quote
|
|
214
|
+
continue
|
|
215
|
+
return index + 1
|
|
216
|
+
else:
|
|
217
|
+
index += 1
|
|
218
|
+
raise syntax("unterminated quoted scalar", number)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def fold(text: str) -> str:
|
|
222
|
+
"""Apply YAML flow folding to a multi-line scalar's content.
|
|
223
|
+
|
|
224
|
+
A single line break folds into one space; a run of *n* consecutive breaks
|
|
225
|
+
yields *n - 1* newlines. The intermediate NUL sentinel keeps the newlines
|
|
226
|
+
produced by the first pass from being folded away by the second.
|
|
227
|
+
"""
|
|
228
|
+
|
|
229
|
+
if "\n" not in text:
|
|
230
|
+
return text
|
|
231
|
+
folded = re.sub(r"[ \t]*\n(?:[ \t]*\n)+[ \t]*",
|
|
232
|
+
lambda run: "\x00" * (run.group(0).count("\n") - 1), text)
|
|
233
|
+
return re.sub(r"[ \t]*\n[ \t]*", " ", folded).replace("\x00", "\n")
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def decode_scalar(raw: str) -> Union[str, int, float, bool, None]:
|
|
237
|
+
"""Decode one scalar's source text into a YAML 1.2 core-schema value.
|
|
238
|
+
|
|
239
|
+
Double-quoted scalars go through the JSON string decoder, which shares
|
|
240
|
+
YAML's escape vocabulary for everything except the two YAML-only forms
|
|
241
|
+
handled first: a backslash before a line break suppresses that break
|
|
242
|
+
entirely, and ``"\\ "`` is an escaped space used to protect leading
|
|
243
|
+
whitespace. Anything the decoder still rejects falls back to the folded
|
|
244
|
+
body rather than raising -- a scalar's exact source text is preserved
|
|
245
|
+
separately, so a decode fallback can never cost byte fidelity.
|
|
246
|
+
"""
|
|
247
|
+
|
|
248
|
+
if raw.startswith('"'):
|
|
249
|
+
body = fold(re.sub(r"\\\n[ \t]*", "", raw[1:-1]))
|
|
250
|
+
body = re.sub(r"(?<!\\)((?:\\\\)*)\\ ", r"\1 ", body)
|
|
251
|
+
try:
|
|
252
|
+
return json.loads(f'"{body}"')
|
|
253
|
+
except ValueError:
|
|
254
|
+
return body
|
|
255
|
+
raw = fold(raw)
|
|
256
|
+
if raw.startswith("'"):
|
|
257
|
+
return raw[1:-1].replace("''", "'")
|
|
258
|
+
lowered = raw.lower()
|
|
259
|
+
if raw == "" or lowered in ("~", "null"):
|
|
260
|
+
return None
|
|
261
|
+
if lowered in ("true", "false"):
|
|
262
|
+
return lowered == "true"
|
|
263
|
+
if _INT_RE.fullmatch(raw):
|
|
264
|
+
return int(raw, 10)
|
|
265
|
+
return float(raw) if _FLOAT_RE.fullmatch(raw) else raw
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def decode_block(style: str, lines: "list[str]", indent: int) -> str:
|
|
269
|
+
"""Decode a literal (``|``) or folded (``>``) block scalar body.
|
|
270
|
+
|
|
271
|
+
``style`` is the header text, ``lines`` the body lines with their
|
|
272
|
+
terminators, ``indent`` the owning entry's indentation. An explicit indent
|
|
273
|
+
digit is relative to ``indent``; without one the first non-empty line sets
|
|
274
|
+
the content indentation. Chomping is applied last: ``-`` strips every
|
|
275
|
+
trailing newline, ``+`` keeps them all, and the default clips to one.
|
|
276
|
+
"""
|
|
277
|
+
|
|
278
|
+
digits = [char for char in style if char.isdigit()]
|
|
279
|
+
chomp = "+" if "+" in style else ("-" if "-" in style else "")
|
|
280
|
+
body = [line.rstrip("\n").rstrip("\r") for line in lines]
|
|
281
|
+
width = (indent + int(digits[0])) if digits else next(
|
|
282
|
+
(indent_of(line) for line in body if line.strip()), 0)
|
|
283
|
+
rows = [line[width:] if len(line) > width else "" for line in body]
|
|
284
|
+
if style[0] == "|":
|
|
285
|
+
text = "".join(row + "\n" for row in rows)
|
|
286
|
+
else:
|
|
287
|
+
pieces = rows[:1]
|
|
288
|
+
for position in range(1, len(rows)):
|
|
289
|
+
row, previous = rows[position], rows[position - 1]
|
|
290
|
+
# A break folds into a space only between two non-empty lines that
|
|
291
|
+
# are both at the content indentation; anything else keeps it.
|
|
292
|
+
folded = row and previous and row[0] != " " and previous[0] != " "
|
|
293
|
+
pieces.append((" " if folded else "\n") + row)
|
|
294
|
+
text = ("".join(pieces) + "\n") if rows else ""
|
|
295
|
+
core = text.rstrip("\n")
|
|
296
|
+
if chomp:
|
|
297
|
+
return core if chomp == "-" else text
|
|
298
|
+
return core + "\n" if core else ""
|