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,1072 @@
|
|
|
1
|
+
"""The TOML format plugin (concept C-016, atomic step A-007).
|
|
2
|
+
|
|
3
|
+
Author: Vasiliy Zdanovskiy
|
|
4
|
+
email: vasilyvz@gmail.com
|
|
5
|
+
|
|
6
|
+
``FormatPluginContract``/``FormatBoundary`` for ``format_id="toml"``. A document
|
|
7
|
+
is an ordered tree of ``toml:Document`` -> ``toml:Table``/``toml:ArrayOfTables``
|
|
8
|
+
-> ``toml:KeyValue``/``toml:Comment``/``toml:Blank``. Headers nest by dotted-key
|
|
9
|
+
prefix, so ``[a.b]`` becomes a child of ``[a]`` while a repeated ``[[a]]`` stays a
|
|
10
|
+
sibling: array-of-tables semantics carried structurally, not by re-reading text.
|
|
11
|
+
|
|
12
|
+
Byte fidelity ({p022}): ``tomllib`` only decides whether a document is *valid* --
|
|
13
|
+
it drops comments, blank lines, quoting and spacing, so it can never drive
|
|
14
|
+
rendering. A lossless scanner instead cuts the source into entries whose spans
|
|
15
|
+
tile it with no gap and no overlap; each leaf node stores its span in
|
|
16
|
+
``fields["raw"]`` while a table/array-of-tables header stores its own header
|
|
17
|
+
line (bracketed key plus any inline comment) in ``fields["header_raw"]`` --
|
|
18
|
+
identity data the parser alone populates, not a cache of the header's composed
|
|
19
|
+
subtree, so it stays outside ``CACHED_SOURCE_FIELDS`` and survives a pointwise
|
|
20
|
+
splice of the table's children (bug 581c1fe1). Rendering concatenates those
|
|
21
|
+
spans depth-first, which is document order by construction -- hence
|
|
22
|
+
``render_document(parse_document(raw)) == raw``. Valid TOML
|
|
23
|
+
the scanner cannot tile raises ``UNSUPPORTED_TRANSLATION``, never a silent
|
|
24
|
+
reformat. ``_Entry``/``_ParsedSource`` stay private. Every node gets a fresh UUID4
|
|
25
|
+
``node_id`` and a local ``short_id`` ({p013}). Errors: bad document/fragment ->
|
|
26
|
+
``FormatContent``/``FormatFragmentParseFailed``; unrepresentable ->
|
|
27
|
+
``UnsupportedTranslation``; ``FormatPluginContractError`` only for a caller
|
|
28
|
+
breaking the call contract. Labels: {p013} {p022} {p049} {p056} {p057}.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
import json
|
|
34
|
+
import re
|
|
35
|
+
try:
|
|
36
|
+
import tomllib
|
|
37
|
+
except ModuleNotFoundError: # Python < 3.11
|
|
38
|
+
import tomli as tomllib # type: ignore[no-redef]
|
|
39
|
+
from dataclasses import dataclass, replace
|
|
40
|
+
from datetime import date, datetime, time
|
|
41
|
+
from typing import Any, Dict, List, Literal, Mapping, Optional, Sequence, Tuple, Union
|
|
42
|
+
|
|
43
|
+
from tree_engine.core.identity import generate_node_id
|
|
44
|
+
from tree_engine.core.offsets import char_to_byte_offset
|
|
45
|
+
from tree_engine.core.nodes import Document, Node, make_node
|
|
46
|
+
from tree_engine.core.plugin_boundary import FormatBoundary
|
|
47
|
+
from tree_engine.core.short_id import ShortIdMap
|
|
48
|
+
from tree_engine.exceptions import (FormatContentParseFailed, FormatFragmentParseFailed,
|
|
49
|
+
FormatPluginContractError, UnsupportedTranslation)
|
|
50
|
+
from tree_engine.plugins.contract import (FormatPluginContract, FormatPluginMetadata,
|
|
51
|
+
SemanticRoleMapping)
|
|
52
|
+
from tree_engine.plugins.json_pointer import JsonPointerNotation
|
|
53
|
+
from tree_engine.plugins.parse_position import line_column
|
|
54
|
+
|
|
55
|
+
__all__ = ["FORMAT_ID", "TOML_POINTER", "TomlFormatPlugin", "TOML_FORMAT_PLUGIN"]
|
|
56
|
+
|
|
57
|
+
FORMAT_ID = "toml"
|
|
58
|
+
KIND_DOCUMENT = f"{FORMAT_ID}:Document"
|
|
59
|
+
KIND_TABLE = f"{FORMAT_ID}:Table"
|
|
60
|
+
KIND_ARRAY_OF_TABLES = f"{FORMAT_ID}:ArrayOfTables"
|
|
61
|
+
KIND_KEYVALUE = f"{FORMAT_ID}:KeyValue"
|
|
62
|
+
KIND_COMMENT = f"{FORMAT_ID}:Comment"
|
|
63
|
+
KIND_BLANK = f"{FORMAT_ID}:Blank"
|
|
64
|
+
#: One element of an array value, and one key/value pair of an inline table:
|
|
65
|
+
#: the VALUE TREE a key/value line carries below itself. A TOML value is not
|
|
66
|
+
#: a line, so these are the only nodes of this format whose span is smaller
|
|
67
|
+
#: than a line -- see ``_tile_value``.
|
|
68
|
+
KIND_ARRAY_ITEM = f"{FORMAT_ID}:ArrayItem"
|
|
69
|
+
KIND_INLINE_PAIR = f"{FORMAT_ID}:InlinePair"
|
|
70
|
+
|
|
71
|
+
# ``aliases`` is empty (TOML has no second established name; the registry still
|
|
72
|
+
# indexes format_id + ``.toml``), and so is the role map: TOML has no
|
|
73
|
+
# function/method/class/module, so ``roles_for(role) == ()`` ({p056}).
|
|
74
|
+
_METADATA = FormatPluginMetadata(
|
|
75
|
+
format_id=FORMAT_ID, aliases=(), file_extensions=("toml",),
|
|
76
|
+
plugin_version="1.0.0", contract_version="1.0.0",
|
|
77
|
+
capabilities={
|
|
78
|
+
# Whether the Code Analysis server can save a file of this format (decision D-CB.4); the editor reads it
|
|
79
|
+
# instead of keeping its own list of unsupported suffixes.
|
|
80
|
+
"ca_save_supported": False,
|
|
81
|
+
"semantic_role_mapping": True,
|
|
82
|
+
# Measured: pipeline/checks/check_roundtrip.py's STRICT policy for
|
|
83
|
+
# toml round-tripped the FULL real corpus (3/3 tracked .toml
|
|
84
|
+
# files, no sampling) byte-identical -- True is honest.
|
|
85
|
+
"byte_identical_round_trip": True,
|
|
86
|
+
# Addressable common-model tree, walkable for preview/search.
|
|
87
|
+
"navigable": True,
|
|
88
|
+
# Round trip is byte-identical -- safe for write-back.
|
|
89
|
+
"editable": True,
|
|
90
|
+
})
|
|
91
|
+
_ROLE_MAP = SemanticRoleMapping({})
|
|
92
|
+
_HEADER_KINDS = (KIND_TABLE, KIND_ARRAY_OF_TABLES)
|
|
93
|
+
_LEAF_KINDS = (KIND_KEYVALUE, KIND_COMMENT, KIND_BLANK)
|
|
94
|
+
#: The value-tree kinds: nodes BELOW a key/value line rather than lines of
|
|
95
|
+
#: their own. They render as part of their parent's value span and are
|
|
96
|
+
#: numbered after every line-level node (see ``deferred_short_id_kinds``).
|
|
97
|
+
_VALUE_KINDS = (KIND_ARRAY_ITEM, KIND_INLINE_PAIR)
|
|
98
|
+
#: ``fields["container"]`` on a node whose value IS a container: which
|
|
99
|
+
#: bracket pair re-composes it when its cached ``raw`` span is gone.
|
|
100
|
+
_CONTAINER_BRACKETS = {"array": ("[", "]"), "table": ("{", "}")}
|
|
101
|
+
_BARE_KEY = re.compile(r"^[A-Za-z0-9_-]+$")
|
|
102
|
+
_VALUE_STOP = "\n#,]}"
|
|
103
|
+
_Options = Optional[Mapping[str, Any]]
|
|
104
|
+
_Source = Union[str, bytes]
|
|
105
|
+
_TOML_AT_RE = re.compile(r"\(at line (\d+), column (\d+)\)")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _toml_failure_position(text: str, exc: BaseException) -> Dict[str, Any]:
|
|
109
|
+
"""``line``/``column``/``message`` details for a TOML failure (``tomllib`` quotes ``at line L, column C``)."""
|
|
110
|
+
raw = str(exc)
|
|
111
|
+
found = _TOML_AT_RE.search(raw)
|
|
112
|
+
if found:
|
|
113
|
+
return {"line": int(found.group(1)), "column": int(found.group(2)),
|
|
114
|
+
"message": raw[:found.start()].strip() or raw}
|
|
115
|
+
line, column = line_column(text, len(text))
|
|
116
|
+
return {"line": line, "column": column, "message": raw or "parse error"}
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _contract_error(message: str) -> FormatPluginContractError:
|
|
120
|
+
return FormatPluginContractError(message, plugin_id=FORMAT_ID)
|
|
121
|
+
def _unsupported(node_type: str, message: str) -> UnsupportedTranslation:
|
|
122
|
+
return UnsupportedTranslation(message, node_type=node_type, format_id=FORMAT_ID)
|
|
123
|
+
class _TomlScanError(Exception):
|
|
124
|
+
"""Internal, module-private lossless-scan signal (never escapes)."""
|
|
125
|
+
@dataclass(frozen=True)
|
|
126
|
+
class _Entry:
|
|
127
|
+
"""One tiled source span plus what the scanner learned about it.
|
|
128
|
+
|
|
129
|
+
``prefix``/``suffix`` split a key/value line around its VALUE span --
|
|
130
|
+
``raw == prefix + value_text + suffix`` exactly -- so the line can be
|
|
131
|
+
re-composed byte-faithfully around a changed value once a pointwise
|
|
132
|
+
edit has dropped its cached ``raw`` (see ``_render``). They are empty
|
|
133
|
+
for every other entry kind, which has no value of its own.
|
|
134
|
+
"""
|
|
135
|
+
kind: str
|
|
136
|
+
raw: str
|
|
137
|
+
key: str = ""
|
|
138
|
+
value_text: str = ""
|
|
139
|
+
prefix: str = ""
|
|
140
|
+
suffix: str = ""
|
|
141
|
+
start: int = 0
|
|
142
|
+
@dataclass(frozen=True)
|
|
143
|
+
class _ParsedSource:
|
|
144
|
+
"""A whole scanned document: the private marker type ``import_to_common``
|
|
145
|
+
dispatches on, holding the entries whose spans tile the source exactly."""
|
|
146
|
+
entries: Tuple[_Entry, ...]
|
|
147
|
+
# The scanned text, set only by ``parse_document``: its presence asks ``_build_root`` to assign
|
|
148
|
+
# every node its ``buffer_range`` (half-open UTF-8 byte offsets, bug b548f445).
|
|
149
|
+
ranged_text: Optional[str] = None
|
|
150
|
+
|
|
151
|
+
def _scan_string(text: str, pos: int) -> int:
|
|
152
|
+
"""Scan one TOML string literal starting at its opening quote."""
|
|
153
|
+
quote = text[pos]
|
|
154
|
+
multiline = text[pos : pos + 3] == quote * 3
|
|
155
|
+
index = pos + 3 if multiline else pos + 1
|
|
156
|
+
while index < len(text):
|
|
157
|
+
char = text[index]
|
|
158
|
+
if char == "\\" and quote == '"':
|
|
159
|
+
index += 2
|
|
160
|
+
continue
|
|
161
|
+
if char == quote:
|
|
162
|
+
if not multiline:
|
|
163
|
+
return index + 1
|
|
164
|
+
if text[index : index + 3] == quote * 3:
|
|
165
|
+
# A run longer than three ends with the closing delimiter; the
|
|
166
|
+
# leading extras are content (`"""a""""` holds one quote).
|
|
167
|
+
run = index
|
|
168
|
+
while run < len(text) and text[run] == quote:
|
|
169
|
+
run += 1
|
|
170
|
+
return run
|
|
171
|
+
elif char == "\n" and not multiline:
|
|
172
|
+
break
|
|
173
|
+
index += 1
|
|
174
|
+
raise _TomlScanError(f"unterminated string opened at offset {pos}")
|
|
175
|
+
def _skip_atom(text: str, index: int) -> int:
|
|
176
|
+
"""Advance one position, jumping a whole string literal or comment."""
|
|
177
|
+
if text[index] in "\"'":
|
|
178
|
+
return _scan_string(text, index)
|
|
179
|
+
if text[index] == "#":
|
|
180
|
+
newline = text.find("\n", index)
|
|
181
|
+
return len(text) if newline == -1 else newline
|
|
182
|
+
return index + 1
|
|
183
|
+
def _scan_bracketed(text: str, pos: int) -> int:
|
|
184
|
+
"""Scan a ``[...]``/``{...}`` span, nesting- and quote-aware."""
|
|
185
|
+
depth = 0
|
|
186
|
+
index = pos
|
|
187
|
+
while index < len(text):
|
|
188
|
+
if text[index] in "[{":
|
|
189
|
+
depth += 1
|
|
190
|
+
elif text[index] in "]}":
|
|
191
|
+
depth -= 1
|
|
192
|
+
if depth == 0:
|
|
193
|
+
return index + 1
|
|
194
|
+
index = _skip_atom(text, index)
|
|
195
|
+
raise _TomlScanError(f"unterminated bracket opened at offset {pos}")
|
|
196
|
+
def _scan_value(text: str, pos: int) -> int:
|
|
197
|
+
"""Scan one right-hand-side value, excluding any trailing comment."""
|
|
198
|
+
if text[pos] in "\"'":
|
|
199
|
+
return _scan_string(text, pos)
|
|
200
|
+
if text[pos] in "[{":
|
|
201
|
+
return _scan_bracketed(text, pos)
|
|
202
|
+
index = pos
|
|
203
|
+
while index < len(text) and text[index] not in _VALUE_STOP:
|
|
204
|
+
index += 1
|
|
205
|
+
while index > pos and text[index - 1] in " \t\r":
|
|
206
|
+
index -= 1
|
|
207
|
+
if index == pos:
|
|
208
|
+
raise _TomlScanError(f"missing value at offset {pos}")
|
|
209
|
+
return index
|
|
210
|
+
def _scan_line_tail(text: str, pos: int) -> int:
|
|
211
|
+
"""Consume trailing blanks, an optional comment, and the line break."""
|
|
212
|
+
index = pos
|
|
213
|
+
while index < len(text) and text[index] in " \t\r":
|
|
214
|
+
index += 1
|
|
215
|
+
if index < len(text) and text[index] == "#":
|
|
216
|
+
index = _skip_atom(text, index)
|
|
217
|
+
return index + 1 if index < len(text) and text[index] == "\n" else index
|
|
218
|
+
def _scan_key(text: str, pos: int) -> int:
|
|
219
|
+
"""Scan a possibly dotted and quoted key up to its ``=`` separator."""
|
|
220
|
+
index = pos
|
|
221
|
+
while index < len(text) and text[index] != "\n":
|
|
222
|
+
if text[index] == "=":
|
|
223
|
+
return index
|
|
224
|
+
index = _skip_atom(text, index)
|
|
225
|
+
raise _TomlScanError(f"expected '=' after the key at offset {pos}")
|
|
226
|
+
def _scan_entries(text: str) -> Tuple[_Entry, ...]:
|
|
227
|
+
"""Split ``text`` into entries whose spans tile it exactly."""
|
|
228
|
+
entries: List[_Entry] = []
|
|
229
|
+
pos, size = 0, len(text)
|
|
230
|
+
while pos < size:
|
|
231
|
+
start = index = pos
|
|
232
|
+
while index < size and text[index] in " \t\r":
|
|
233
|
+
index += 1
|
|
234
|
+
if index >= size or text[index] == "\n":
|
|
235
|
+
pos = index + 1 if index < size else size
|
|
236
|
+
entries.append(_Entry(KIND_BLANK, text[start:pos], start=start))
|
|
237
|
+
elif text[index] == "#":
|
|
238
|
+
pos = _scan_line_tail(text, index)
|
|
239
|
+
entries.append(_Entry(KIND_COMMENT, text[start:pos], value_text=text[index:pos].rstrip("\r\n"), start=start))
|
|
240
|
+
elif text[index] == "[":
|
|
241
|
+
width = 2 if text[index : index + 2] == "[[" else 1
|
|
242
|
+
close = _scan_bracketed(text, index)
|
|
243
|
+
key = text[index + width : close - width].strip()
|
|
244
|
+
if not key:
|
|
245
|
+
raise _TomlScanError(f"empty table header at offset {index}")
|
|
246
|
+
pos = _scan_line_tail(text, close)
|
|
247
|
+
kind = KIND_ARRAY_OF_TABLES if width == 2 else KIND_TABLE
|
|
248
|
+
entries.append(_Entry(kind, text[start:pos], key=key, start=start))
|
|
249
|
+
else:
|
|
250
|
+
separator = _scan_key(text, index)
|
|
251
|
+
value_start = separator + 1
|
|
252
|
+
while value_start < size and text[value_start] in " \t":
|
|
253
|
+
value_start += 1
|
|
254
|
+
if value_start >= size:
|
|
255
|
+
raise _TomlScanError(f"missing value after '=' at offset {separator}")
|
|
256
|
+
value_end = _scan_value(text, value_start)
|
|
257
|
+
pos = _scan_line_tail(text, value_end)
|
|
258
|
+
entries.append(_Entry(KIND_KEYVALUE, text[start:pos], key=text[index:separator].strip(),
|
|
259
|
+
value_text=text[value_start:value_end],
|
|
260
|
+
prefix=text[start:value_start], suffix=text[value_end:pos], start=start))
|
|
261
|
+
return tuple(entries)
|
|
262
|
+
|
|
263
|
+
@dataclass(frozen=True)
|
|
264
|
+
class _ValuePart:
|
|
265
|
+
"""One tiled element of an array or inline-table value span.
|
|
266
|
+
|
|
267
|
+
``leading`` is the element's own PRECEDING trivia -- whitespace, newlines
|
|
268
|
+
and whole standalone comment lines that come before the value on the
|
|
269
|
+
page -- stored on the element itself exactly the way ``json_format``
|
|
270
|
+
stores a member's/item's ``leading`` (and for the same reason: it
|
|
271
|
+
describes the element's place among its siblings, not the element, so a
|
|
272
|
+
splice elsewhere in the container never touches it). ``key_raw``/``sep``
|
|
273
|
+
are an inline-table pair's key text and its ``=`` run, empty for an
|
|
274
|
+
array item. ``value_text`` is the element's own value span -- itself
|
|
275
|
+
bracketed when the element is a nested array/inline table.
|
|
276
|
+
|
|
277
|
+
``trailing`` is the element's own FOLLOWING trivia on the SAME source
|
|
278
|
+
line: the separating comma (if present) plus an inline ``#`` comment
|
|
279
|
+
that trails it, never crossing a newline (bug c8723441). Before this
|
|
280
|
+
field existed, that same text was folded into the NEXT element's
|
|
281
|
+
``leading`` (or, for the last element, into the container's
|
|
282
|
+
``closing_trivia``) -- so deleting one element silently deleted its
|
|
283
|
+
PREVIOUS sibling's own trailing comment instead of its own, and the
|
|
284
|
+
element's own trailing comment survived the delete attached to nothing.
|
|
285
|
+
Attaching it here instead means a delete removes exactly one element's
|
|
286
|
+
own text, in whichever position it occupies.
|
|
287
|
+
"""
|
|
288
|
+
leading: str
|
|
289
|
+
key_raw: str
|
|
290
|
+
sep: str
|
|
291
|
+
value_text: str
|
|
292
|
+
trailing: str = ""
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
@dataclass(frozen=True)
|
|
296
|
+
class _Container:
|
|
297
|
+
"""A tiled array/inline-table value: ``kind`` + elements + closing trivia.
|
|
298
|
+
|
|
299
|
+
Tiling is exact by construction:
|
|
300
|
+
``open + sum(part.leading + part.key_raw + part.sep + part.value_text +
|
|
301
|
+
part.trailing) + closing_trivia + close == value_text``, which
|
|
302
|
+
``_tile_value`` asserts before returning -- a span it cannot tile yields
|
|
303
|
+
``None`` and the value stays one opaque leaf rather than a lossy
|
|
304
|
+
decomposition.
|
|
305
|
+
"""
|
|
306
|
+
kind: str
|
|
307
|
+
parts: Tuple[_ValuePart, ...]
|
|
308
|
+
closing_trivia: str
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _skip_value_trivia(text: str, pos: int, limit: int) -> int:
|
|
312
|
+
"""Advance over whitespace, newlines and whole comments inside a value."""
|
|
313
|
+
while pos < limit:
|
|
314
|
+
char = text[pos]
|
|
315
|
+
if char in " \t\r\n":
|
|
316
|
+
pos += 1
|
|
317
|
+
elif char == "#":
|
|
318
|
+
pos = min(_skip_atom(text, pos), limit)
|
|
319
|
+
else:
|
|
320
|
+
break
|
|
321
|
+
return pos
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _tile_value(value_text: str) -> Optional[_Container]:
|
|
325
|
+
"""Split an array/inline-table value span into its elements, losslessly.
|
|
326
|
+
|
|
327
|
+
A ``toml:KeyValue`` keeps its whole line as one ``raw`` span for byte
|
|
328
|
+
fidelity ({p022}), but a COMPOSITE value is a container with real
|
|
329
|
+
elements a caller must be able to address, drill into and edit -- the
|
|
330
|
+
same structure ``json_format`` gives a JSON array/object. This performs
|
|
331
|
+
that decomposition with the module's OWN lossless value scanner
|
|
332
|
+
(``_scan_value``/``_skip_atom``), so a comma inside a nested array, an
|
|
333
|
+
inline table or a quoted string is never mistaken for a top-level
|
|
334
|
+
separator, and the parts tile the span with no gap and no overlap.
|
|
335
|
+
|
|
336
|
+
Returns ``None`` -- never raises -- for a scalar value and for any
|
|
337
|
+
composite span the scanner cannot tile exactly; the caller then keeps
|
|
338
|
+
the value as one opaque leaf, which still renders byte-identically.
|
|
339
|
+
"""
|
|
340
|
+
text = value_text
|
|
341
|
+
if len(text) < 2 or text[0] not in "[{":
|
|
342
|
+
return None
|
|
343
|
+
kind = "array" if text[0] == "[" else "table"
|
|
344
|
+
if not text.endswith(_CONTAINER_BRACKETS[kind][1]):
|
|
345
|
+
return None
|
|
346
|
+
limit = len(text) - 1
|
|
347
|
+
parts: List[_ValuePart] = []
|
|
348
|
+
pos = 1
|
|
349
|
+
closing_trivia = ""
|
|
350
|
+
try:
|
|
351
|
+
while True:
|
|
352
|
+
lead_start = pos
|
|
353
|
+
scan = _skip_value_trivia(text, pos, limit)
|
|
354
|
+
if scan >= limit:
|
|
355
|
+
closing_trivia = text[lead_start:limit]
|
|
356
|
+
break
|
|
357
|
+
leading = text[lead_start:scan]
|
|
358
|
+
key_raw = sep = ""
|
|
359
|
+
if kind == "table":
|
|
360
|
+
separator = _scan_key(text, scan)
|
|
361
|
+
if separator >= limit:
|
|
362
|
+
raise _TomlScanError(f"inline pair without a value at offset {scan}")
|
|
363
|
+
key_raw = text[scan:separator]
|
|
364
|
+
value_start = separator + 1
|
|
365
|
+
while value_start < limit and text[value_start] in " \t":
|
|
366
|
+
value_start += 1
|
|
367
|
+
sep = text[separator:value_start]
|
|
368
|
+
scan = value_start
|
|
369
|
+
value_end = _scan_value(text, scan)
|
|
370
|
+
if value_end > limit:
|
|
371
|
+
raise _TomlScanError(f"value overruns its container at offset {scan}")
|
|
372
|
+
trailing_end = _scan_element_trailing(text, value_end, limit)
|
|
373
|
+
parts.append(_ValuePart(leading, key_raw, sep, text[scan:value_end],
|
|
374
|
+
text[value_end:trailing_end]))
|
|
375
|
+
pos = trailing_end
|
|
376
|
+
except _TomlScanError:
|
|
377
|
+
return None
|
|
378
|
+
container = _Container(kind=kind, parts=tuple(parts), closing_trivia=closing_trivia)
|
|
379
|
+
if _compose_container(container, (part.value_text for part in container.parts)) != text:
|
|
380
|
+
return None
|
|
381
|
+
return container
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def _scan_element_trailing(text: str, pos: int, limit: int) -> int:
|
|
385
|
+
"""One array/inline-table element's OWN trailing trivia: an optional
|
|
386
|
+
separating comma plus an optional inline ``#`` comment, both on the
|
|
387
|
+
SAME source line as the value -- never crossing a newline, which is
|
|
388
|
+
what keeps a standalone comment line before the NEXT element out of
|
|
389
|
+
this span (it stays that element's own ``leading`` instead). See
|
|
390
|
+
``_ValuePart.trailing`` for why this must be attributed to THIS
|
|
391
|
+
element rather than folded into the next one's leading trivia.
|
|
392
|
+
"""
|
|
393
|
+
end = pos
|
|
394
|
+
scan = pos
|
|
395
|
+
while scan < limit and text[scan] in " \t":
|
|
396
|
+
scan += 1
|
|
397
|
+
if scan < limit and text[scan] == ",":
|
|
398
|
+
scan += 1
|
|
399
|
+
end = scan
|
|
400
|
+
scan_comment = end
|
|
401
|
+
while scan_comment < limit and text[scan_comment] in " \t":
|
|
402
|
+
scan_comment += 1
|
|
403
|
+
if scan_comment < limit and text[scan_comment] == "#":
|
|
404
|
+
end = min(_skip_atom(text, scan_comment), limit)
|
|
405
|
+
return end
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def _compose_container(container: _Container, values: Any) -> str:
|
|
409
|
+
"""Re-assemble one container span from its parts and their value texts."""
|
|
410
|
+
open_char, close_char = _CONTAINER_BRACKETS[container.kind]
|
|
411
|
+
body = "".join(
|
|
412
|
+
f"{part.leading}{part.key_raw}{part.sep}{value}{part.trailing}"
|
|
413
|
+
for part, value in zip(container.parts, values)
|
|
414
|
+
)
|
|
415
|
+
return f"{open_char}{body}{container.closing_trivia}{close_char}"
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def _new_node(kind: str, fields: Mapping[str, Any], kids: Sequence[Node], ids: ShortIdMap,
|
|
419
|
+
buffer_range: Optional[Tuple[int, int]] = None) -> Node:
|
|
420
|
+
"""Build a validated node carrying a fresh UUID4 id and short_id ({p013}) and, for a parsed
|
|
421
|
+
document, its ``buffer_range`` (half-open UTF-8 byte offsets, bug b548f445)."""
|
|
422
|
+
validated = make_node(kind, fields=dict(fields), children=tuple(kids))
|
|
423
|
+
node_id = generate_node_id()
|
|
424
|
+
return replace(validated, node_id=node_id, short_id=ids.allocate(node_id), buffer_range=buffer_range)
|
|
425
|
+
def _build_root(source: _ParsedSource, ids: ShortIdMap) -> Node:
|
|
426
|
+
"""Nest the tiled entries into a tree; table headers nest by key prefix."""
|
|
427
|
+
top: List[Node] = []
|
|
428
|
+
stack: List[Tuple[str, _Entry, List[Node]]] = []
|
|
429
|
+
conv = char_to_byte_offset(source.ranged_text) if source.ranged_text is not None else None
|
|
430
|
+
|
|
431
|
+
def span(start: int, end: int) -> Optional[Tuple[int, int]]:
|
|
432
|
+
return (conv(start), conv(end)) if conv else None
|
|
433
|
+
|
|
434
|
+
def close_one() -> None:
|
|
435
|
+
key, entry, children = stack.pop()
|
|
436
|
+
# 'header_raw' -- not 'raw' -- holds the table/array-of-tables header LINE
|
|
437
|
+
# (the bracketed key plus its own inline comment, e.g. '[table] # note\n').
|
|
438
|
+
# It is per-node identity data the parser alone populates, never a cache of
|
|
439
|
+
# the table's composed subtree, so it stays outside ``CACHED_SOURCE_FIELDS``
|
|
440
|
+
# (core/live_tree.py): a pointwise splice of this table's children
|
|
441
|
+
# invalidates composed-source caches on ancestors, but the header line
|
|
442
|
+
# itself does not depend on the children and must survive unchanged
|
|
443
|
+
# (bug 581c1fe1).
|
|
444
|
+
# A table spans its header line through the end of its last child entry.
|
|
445
|
+
header = span(entry.start, entry.start + len(entry.raw))
|
|
446
|
+
extent = (header[0], children[-1].buffer_range[1]) if header and children else header
|
|
447
|
+
node = _new_node(entry.kind, {"header_raw": entry.raw, "key": key}, children, ids,
|
|
448
|
+
buffer_range=extent)
|
|
449
|
+
(stack[-1][2] if stack else top).append(node)
|
|
450
|
+
|
|
451
|
+
def value_node(kind: str, part: _ValuePart, ids: ShortIdMap, start: int) -> Node:
|
|
452
|
+
"""One tiled value element -> a node keeping its own value span.
|
|
453
|
+
|
|
454
|
+
No generic ``"raw"`` cache here (bug c8723441): ``facade._extract_cached_source``
|
|
455
|
+
-- what a delete/replace journal entry's "before" capture, and
|
|
456
|
+
``node_source_text``, both use -- checks a node's ``"raw"`` field
|
|
457
|
+
FIRST, before ever calling back into the plugin's own rendering.
|
|
458
|
+
Caching the bare VALUE span there (as this used to, for
|
|
459
|
+
``KIND_ARRAY_ITEM`` only) made every captured "before" fragment for
|
|
460
|
+
an array element just its value, silently dropping the element's
|
|
461
|
+
own ``leading``/``trailing`` trivia -- exactly the bytes ``undo``
|
|
462
|
+
needs to restore a multi-line array's original layout and inline
|
|
463
|
+
comment. Leaving no ``"raw"`` field here routes both the in-context
|
|
464
|
+
render (``_render_element`` already falls back to ``_render_value``,
|
|
465
|
+
which reads ``value_text`` -- identical output, see below) and the
|
|
466
|
+
standalone capture path through ``_render`` -> ``_render_element``,
|
|
467
|
+
which composes ``leading + value + trailing`` from this node's own
|
|
468
|
+
fields -- this element's full, byte-faithful text either way.
|
|
469
|
+
``leading``/``trailing``/``key_raw``/``sep`` are position and
|
|
470
|
+
identity data the parser alone populates and a splice must never
|
|
471
|
+
disturb -- exactly the split ``json_format`` draws for a
|
|
472
|
+
``json:Member``.
|
|
473
|
+
"""
|
|
474
|
+
fields: dict = {
|
|
475
|
+
"value_text": part.value_text, # identity: this element's own value
|
|
476
|
+
"leading": part.leading,
|
|
477
|
+
"trailing": part.trailing,
|
|
478
|
+
}
|
|
479
|
+
if kind == KIND_INLINE_PAIR:
|
|
480
|
+
fields["key_raw"], fields["sep"] = part.key_raw, part.sep
|
|
481
|
+
fields["key"] = part.key_raw.strip()
|
|
482
|
+
# A NESTED composite element is a container in its own right and
|
|
483
|
+
# carries the same identity fields its parent does, so one rule --
|
|
484
|
+
# "``container`` names the bracket pair, ``closing_trivia`` the text
|
|
485
|
+
# before the closer" -- re-composes it at any depth.
|
|
486
|
+
fields.update(value_fields(part.value_text))
|
|
487
|
+
value_start = start + len(part.leading) + len(part.key_raw) + len(part.sep)
|
|
488
|
+
end = value_start + len(part.value_text) + len(part.trailing)
|
|
489
|
+
return _new_node(kind, fields, value_children(part.value_text, ids, value_start), ids,
|
|
490
|
+
buffer_range=span(start, end))
|
|
491
|
+
|
|
492
|
+
def value_children(value_text: str, ids: ShortIdMap, start: int) -> Tuple[Node, ...]:
|
|
493
|
+
"""The value tree below one value span (``start`` = its character offset): () for a scalar."""
|
|
494
|
+
container = _tile_value(value_text)
|
|
495
|
+
if container is None:
|
|
496
|
+
return ()
|
|
497
|
+
kind = KIND_ARRAY_ITEM if container.kind == "array" else KIND_INLINE_PAIR
|
|
498
|
+
nodes: List[Node] = []
|
|
499
|
+
pos = start + 1 # past the opening bracket
|
|
500
|
+
for part in container.parts:
|
|
501
|
+
nodes.append(value_node(kind, part, ids, pos))
|
|
502
|
+
pos += len(part.leading) + len(part.key_raw) + len(part.sep) + len(part.value_text) + len(part.trailing)
|
|
503
|
+
return tuple(nodes)
|
|
504
|
+
|
|
505
|
+
def value_fields(value_text: str) -> dict:
|
|
506
|
+
"""The container identity fields a composite value carries, if any."""
|
|
507
|
+
container = _tile_value(value_text)
|
|
508
|
+
if container is None:
|
|
509
|
+
return {}
|
|
510
|
+
return {"container": container.kind, "closing_trivia": container.closing_trivia}
|
|
511
|
+
|
|
512
|
+
def leaf(entry: _Entry) -> Node:
|
|
513
|
+
"""One non-header entry -> a leaf node keeping its exact span.
|
|
514
|
+
|
|
515
|
+
A key/value line whose value is an array or an inline table is NOT
|
|
516
|
+
a leaf any more: it carries that value's elements as real children
|
|
517
|
+
({p013} identity, addressable and drillable), while its own ``raw``
|
|
518
|
+
still replays the untouched line byte-identically.
|
|
519
|
+
"""
|
|
520
|
+
fields: dict = {"raw": entry.raw}
|
|
521
|
+
kids: Tuple[Node, ...] = ()
|
|
522
|
+
if entry.kind == KIND_KEYVALUE:
|
|
523
|
+
fields["key"], fields["value_text"] = entry.key, entry.value_text
|
|
524
|
+
fields["prefix_raw"], fields["suffix_raw"] = entry.prefix, entry.suffix
|
|
525
|
+
fields.update(value_fields(entry.value_text))
|
|
526
|
+
kids = value_children(entry.value_text, ids, entry.start + len(entry.prefix))
|
|
527
|
+
elif entry.kind == KIND_COMMENT:
|
|
528
|
+
fields["text"] = entry.value_text
|
|
529
|
+
return _new_node(entry.kind, fields, kids, ids, buffer_range=span(entry.start, entry.start + len(entry.raw)))
|
|
530
|
+
|
|
531
|
+
for entry in source.entries:
|
|
532
|
+
if entry.kind in _HEADER_KINDS:
|
|
533
|
+
while stack and not entry.key.startswith(stack[-1][0] + "."):
|
|
534
|
+
close_one()
|
|
535
|
+
stack.append((entry.key, entry, []))
|
|
536
|
+
else:
|
|
537
|
+
(stack[-1][2] if stack else top).append(leaf(entry))
|
|
538
|
+
while stack:
|
|
539
|
+
close_one()
|
|
540
|
+
whole = span(0, len(source.ranged_text)) if source.ranged_text is not None else None
|
|
541
|
+
return _new_node(KIND_DOCUMENT, {}, top, ids, buffer_range=whole)
|
|
542
|
+
def _render(node: Node) -> str:
|
|
543
|
+
"""Common model -> text, replaying each node's exact stored span. A node with
|
|
544
|
+
no span (caller-synthesized) falls back to a minimal deterministic form."""
|
|
545
|
+
kind = node.kind
|
|
546
|
+
if kind == KIND_DOCUMENT:
|
|
547
|
+
return "".join(_render(child) for child in node.children)
|
|
548
|
+
if kind in _HEADER_KINDS:
|
|
549
|
+
# Header identity, not a composed-subtree cache -- see close_one().
|
|
550
|
+
header_raw = node.fields.get("header_raw")
|
|
551
|
+
if not isinstance(header_raw, str):
|
|
552
|
+
brackets = "[[{}]]" if kind == KIND_ARRAY_OF_TABLES else "[{}]"
|
|
553
|
+
header_raw = brackets.format(node.fields.get("key", "")) + "\n"
|
|
554
|
+
return header_raw + "".join(_render(child) for child in node.children)
|
|
555
|
+
if kind in _LEAF_KINDS:
|
|
556
|
+
raw = node.fields.get("raw")
|
|
557
|
+
if isinstance(raw, str):
|
|
558
|
+
return raw
|
|
559
|
+
if kind == KIND_KEYVALUE:
|
|
560
|
+
# No cache: the line was edited (or synthesized). Replay its own
|
|
561
|
+
# prefix/suffix spans around the freshly composed value, so only
|
|
562
|
+
# the value differs from the original bytes; a synthesized node
|
|
563
|
+
# with neither falls back to the minimal deterministic form.
|
|
564
|
+
prefix = node.fields.get("prefix_raw")
|
|
565
|
+
suffix = node.fields.get("suffix_raw")
|
|
566
|
+
if isinstance(prefix, str) and isinstance(suffix, str):
|
|
567
|
+
return prefix + _render_value(node) + suffix
|
|
568
|
+
return f"{node.fields.get('key', '')} = {_render_value(node)}\n"
|
|
569
|
+
return f"{node.fields.get('text', '#')}\n" if kind == KIND_COMMENT else "\n"
|
|
570
|
+
if kind in _VALUE_KINDS:
|
|
571
|
+
# Standalone (no sibling context): render this one element's own
|
|
572
|
+
# stored trivia verbatim, neither injecting nor stripping a
|
|
573
|
+
# separating comma -- there are no siblings here to separate it
|
|
574
|
+
# from. Used by ``render_fragment``/``node_source_text`` to capture
|
|
575
|
+
# a node's own byte-faithful text (bug c8723441's undo path).
|
|
576
|
+
return _render_element(node, 0, 1, None)
|
|
577
|
+
raise _unsupported(str(kind), f"node kind {kind!r} has no TOML representation")
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def _render_value(node: Node) -> str:
|
|
581
|
+
"""One node's VALUE span: its cached/scalar text, or its composed container."""
|
|
582
|
+
container = node.fields.get("container")
|
|
583
|
+
if not isinstance(container, str) or container not in _CONTAINER_BRACKETS:
|
|
584
|
+
value_text = node.fields.get("value_text")
|
|
585
|
+
return value_text if isinstance(value_text, str) else ""
|
|
586
|
+
open_char, close_char = _CONTAINER_BRACKETS[container]
|
|
587
|
+
total = len(node.children)
|
|
588
|
+
body = "".join(
|
|
589
|
+
_render_element(child, index, total, container) for index, child in enumerate(node.children)
|
|
590
|
+
)
|
|
591
|
+
closing = node.fields.get("closing_trivia")
|
|
592
|
+
return open_char + body + (closing if isinstance(closing, str) else "") + close_char
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
def _render_element(node: Node, index: int, total: int, container_kind: Optional[str]) -> str:
|
|
596
|
+
"""One value-tree element: its own ``leading`` trivia, key, value and
|
|
597
|
+
``trailing`` trivia (its own separating comma plus any inline comment
|
|
598
|
+
that trails it -- see ``_ValuePart.trailing``).
|
|
599
|
+
|
|
600
|
+
A caller-inserted element carries neither of its own, so the minimal
|
|
601
|
+
separator is synthesized here from its POSITION among its (possibly
|
|
602
|
+
just-changed) siblings: no leading needed before the first element, a
|
|
603
|
+
single space before a later one; no trailing comma needed after the
|
|
604
|
+
last element, one needed after any other. An inline TABLE additionally
|
|
605
|
+
forbids a trailing comma before its closing ``}}`` (unlike an array,
|
|
606
|
+
where one trailing comma is legal TOML and bug c8723441's own fixture
|
|
607
|
+
keeps it after the delete that makes an element last) -- ``json_format``
|
|
608
|
+
performs the same first/last normalization on ``leading`` alone; this
|
|
609
|
+
format needs it on the ``trailing`` side too because the comma has to
|
|
610
|
+
move to a different side when this element gains or loses a follower.
|
|
611
|
+
"""
|
|
612
|
+
leading = node.fields.get("leading")
|
|
613
|
+
if not isinstance(leading, str) or not leading:
|
|
614
|
+
leading = "" if index == 0 else " "
|
|
615
|
+
key_raw = node.fields.get("key_raw")
|
|
616
|
+
sep = node.fields.get("sep")
|
|
617
|
+
head = (key_raw if isinstance(key_raw, str) else "") + (sep if isinstance(sep, str) else "")
|
|
618
|
+
raw = node.fields.get("raw")
|
|
619
|
+
value = raw if isinstance(raw, str) else _render_value(node)
|
|
620
|
+
trailing = node.fields.get("trailing")
|
|
621
|
+
is_last = index == total - 1
|
|
622
|
+
if not isinstance(trailing, str) or not trailing:
|
|
623
|
+
trailing = "" if is_last else ","
|
|
624
|
+
elif is_last and container_kind == "table" and "," in trailing:
|
|
625
|
+
# Inline tables never permit a trailing comma before '}' -- strip
|
|
626
|
+
# just the comma, keep any comment that followed it.
|
|
627
|
+
trailing = trailing.replace(",", "", 1)
|
|
628
|
+
elif not is_last and "," not in trailing:
|
|
629
|
+
trailing = "," + trailing
|
|
630
|
+
return leading + head + value + trailing
|
|
631
|
+
|
|
632
|
+
def _dump_key(key: Any) -> str:
|
|
633
|
+
"""Render one key segment, quoting it when it is not a bare TOML key."""
|
|
634
|
+
if not isinstance(key, str):
|
|
635
|
+
raise _unsupported(type(key).__name__, f"TOML keys must be strings, got {key!r}")
|
|
636
|
+
return key if _BARE_KEY.match(key) else json.dumps(key, ensure_ascii=False)
|
|
637
|
+
def _dump_value(value: Any) -> str:
|
|
638
|
+
"""Render one inline TOML value; an unmappable type raises ({p049})."""
|
|
639
|
+
if isinstance(value, bool):
|
|
640
|
+
return "true" if value else "false"
|
|
641
|
+
if isinstance(value, (int, float)):
|
|
642
|
+
return str(value) if isinstance(value, int) else repr(value)
|
|
643
|
+
if isinstance(value, str):
|
|
644
|
+
# TOML basic strings accept exactly the JSON escape set minus "\/",
|
|
645
|
+
# which json.dumps never emits, so its output is a valid literal.
|
|
646
|
+
return json.dumps(value, ensure_ascii=False)
|
|
647
|
+
if isinstance(value, (datetime, date, time)):
|
|
648
|
+
return value.isoformat()
|
|
649
|
+
if isinstance(value, (list, tuple)):
|
|
650
|
+
return "[" + ", ".join(_dump_value(item) for item in value) + "]"
|
|
651
|
+
if isinstance(value, Mapping):
|
|
652
|
+
return "{" + ", ".join(f"{_dump_key(k)} = {_dump_value(v)}" for k, v in value.items()) + "}"
|
|
653
|
+
raise _unsupported(type(value).__name__, f"{type(value).__name__!r} has no TOML value form")
|
|
654
|
+
def _dump_toml(mapping: Any, path: Tuple[str, ...] = ()) -> str:
|
|
655
|
+
"""Plain mapping -> TOML: scalars first, then sub-tables; a non-empty list of
|
|
656
|
+
mappings becomes a ``[[array of tables]]``."""
|
|
657
|
+
if not isinstance(mapping, Mapping):
|
|
658
|
+
raise _unsupported(type(mapping).__name__, "a TOML document root must be a mapping")
|
|
659
|
+
pairs: List[str] = []
|
|
660
|
+
tables: List[str] = []
|
|
661
|
+
for key, value in mapping.items():
|
|
662
|
+
child = path + (key,)
|
|
663
|
+
head = ".".join(_dump_key(part) for part in child)
|
|
664
|
+
if isinstance(value, Mapping):
|
|
665
|
+
tables.append(f"[{head}]\n" + _dump_toml(value, child))
|
|
666
|
+
elif (isinstance(value, (list, tuple)) and len(value) > 0
|
|
667
|
+
and all(isinstance(item, Mapping) for item in value)):
|
|
668
|
+
tables.extend(f"[[{head}]]\n" + _dump_toml(item, child) for item in value)
|
|
669
|
+
else:
|
|
670
|
+
pairs.append(f"{_dump_key(key)} = {_dump_value(value)}\n")
|
|
671
|
+
return "".join(pairs) + "".join(tables)
|
|
672
|
+
|
|
673
|
+
def _split_dotted_key(key: str) -> Tuple[str, ...]:
|
|
674
|
+
"""Split a TOML dotted key into its segments, unquoting each one.
|
|
675
|
+
|
|
676
|
+
``a.b`` is two segments, and so is ``a."b.c"`` -- but the second one's dot
|
|
677
|
+
is content, not a separator, which is exactly why this cannot be a
|
|
678
|
+
``str.split(".")``. Quoted segments are decoded so the resulting token is
|
|
679
|
+
the key a reader means, not the source spelling of it.
|
|
680
|
+
"""
|
|
681
|
+
|
|
682
|
+
segments: List[str] = []
|
|
683
|
+
current: List[str] = []
|
|
684
|
+
index = 0
|
|
685
|
+
while index < len(key):
|
|
686
|
+
char = key[index]
|
|
687
|
+
if char in "\"'":
|
|
688
|
+
try:
|
|
689
|
+
end = _scan_string(key, index)
|
|
690
|
+
except _TomlScanError:
|
|
691
|
+
# A key no scanner can close is not a key this notation can
|
|
692
|
+
# express; the caller-synthesized node it came from simply gets
|
|
693
|
+
# no pointer rather than one built from a guess at where the
|
|
694
|
+
# quote was meant to end.
|
|
695
|
+
return ()
|
|
696
|
+
literal = key[index:end]
|
|
697
|
+
try:
|
|
698
|
+
current.append(json.loads(literal) if char == '"' else literal[1:-1])
|
|
699
|
+
except ValueError:
|
|
700
|
+
current.append(literal)
|
|
701
|
+
index = end
|
|
702
|
+
continue
|
|
703
|
+
if char == ".":
|
|
704
|
+
segments.append("".join(current).strip())
|
|
705
|
+
current = []
|
|
706
|
+
else:
|
|
707
|
+
current.append(char)
|
|
708
|
+
index += 1
|
|
709
|
+
segments.append("".join(current).strip())
|
|
710
|
+
return tuple(segment for segment in segments if segment != "")
|
|
711
|
+
|
|
712
|
+
|
|
713
|
+
def _key_text(node: Node) -> str:
|
|
714
|
+
"""A node's header/key text, or ``""`` when it carries none as a string.
|
|
715
|
+
|
|
716
|
+
``toml:Document`` has no key at all, and a caller-synthesized node may hold
|
|
717
|
+
a non-string one; both answer ``""``, which
|
|
718
|
+
:func:`_split_dotted_key` turns into no segments and hence no pointer.
|
|
719
|
+
"""
|
|
720
|
+
|
|
721
|
+
key = node.fields.get("key")
|
|
722
|
+
return key if isinstance(key, str) else ""
|
|
723
|
+
|
|
724
|
+
|
|
725
|
+
def _relative_key(parent: Node, child: Node) -> Tuple[str, ...]:
|
|
726
|
+
"""The header segments ``child`` adds below ``parent``'s own header.
|
|
727
|
+
|
|
728
|
+
A table header carries its FULL dotted key -- ``[a.b]`` stores ``"a.b"``
|
|
729
|
+
even though the tree already nests it under ``[a]`` -- so emitting all of
|
|
730
|
+
it would produce ``/a/a/b``. The parent's own segments are dropped, which
|
|
731
|
+
is a prefix comparison on parsed segments rather than on raw text, so a
|
|
732
|
+
quoted segment cannot be mis-stripped.
|
|
733
|
+
"""
|
|
734
|
+
|
|
735
|
+
child_segments = _split_dotted_key(_key_text(child))
|
|
736
|
+
parent_segments = _split_dotted_key(_key_text(parent))
|
|
737
|
+
if parent_segments and child_segments[:len(parent_segments)] == parent_segments:
|
|
738
|
+
return child_segments[len(parent_segments):]
|
|
739
|
+
return child_segments
|
|
740
|
+
|
|
741
|
+
|
|
742
|
+
def _array_of_tables_ordinal(parent: Node, child: Node) -> int:
|
|
743
|
+
"""How many earlier siblings repeat ``child``'s ``[[header]]``.
|
|
744
|
+
|
|
745
|
+
``[[a]]`` written three times is a three-element array, kept structurally
|
|
746
|
+
as three sibling nodes with one key; their pointers differ only by this
|
|
747
|
+
index, so it has to be counted over the siblings rather than read off the
|
|
748
|
+
node.
|
|
749
|
+
"""
|
|
750
|
+
|
|
751
|
+
key = child.fields.get("key")
|
|
752
|
+
count = 0
|
|
753
|
+
for sibling in parent.children:
|
|
754
|
+
if sibling is child:
|
|
755
|
+
break
|
|
756
|
+
if sibling.kind == KIND_ARRAY_OF_TABLES and sibling.fields.get("key") == key:
|
|
757
|
+
count += 1
|
|
758
|
+
return count
|
|
759
|
+
|
|
760
|
+
|
|
761
|
+
def _pointer_step(parent: Node, child: Node, ordinal: int) -> Optional[Tuple[Tuple[str, ...], bool]]:
|
|
762
|
+
"""This format's structural half of RFC 6901, for ``JsonPointerNotation``.
|
|
763
|
+
|
|
764
|
+
TOML is a line-tiled model rather than a value tree, so the mapping is the
|
|
765
|
+
least direct of the three: a table's pointer is its dotted key expanded
|
|
766
|
+
into one token per segment, a key/value pair's is the same below whatever
|
|
767
|
+
table contains it, and a repeated ``[[table]]`` adds its occurrence index
|
|
768
|
+
because that is what the array element's pointer is. Comments and blank
|
|
769
|
+
lines exist only to make the document render byte-identically; they are
|
|
770
|
+
not values and get no pointer.
|
|
771
|
+
"""
|
|
772
|
+
|
|
773
|
+
kind = child.kind
|
|
774
|
+
if kind == KIND_ARRAY_ITEM:
|
|
775
|
+
# An array element's pointer token is its index, exactly as RFC 6901
|
|
776
|
+
# addresses a JSON array element -- and exactly the token the EDITOR's
|
|
777
|
+
# own forest notation (``ai_editor.core.tree_temp.identity``) already
|
|
778
|
+
# issues for the same element, which is what lets the two identities
|
|
779
|
+
# be bound to one another instead of drifting apart.
|
|
780
|
+
return ((str(ordinal),), True)
|
|
781
|
+
if kind == KIND_INLINE_PAIR:
|
|
782
|
+
segments = _split_dotted_key(_key_text(child))
|
|
783
|
+
return (segments, True) if segments else None
|
|
784
|
+
if kind == KIND_KEYVALUE:
|
|
785
|
+
segments = _split_dotted_key(_key_text(child))
|
|
786
|
+
return (segments, True) if segments else None
|
|
787
|
+
if kind == KIND_TABLE:
|
|
788
|
+
segments = _relative_key(parent, child)
|
|
789
|
+
return (segments, True) if segments else None
|
|
790
|
+
if kind == KIND_ARRAY_OF_TABLES:
|
|
791
|
+
segments = _relative_key(parent, child)
|
|
792
|
+
if not segments:
|
|
793
|
+
return None
|
|
794
|
+
return (segments + (str(_array_of_tables_ordinal(parent, child)),), True)
|
|
795
|
+
return None
|
|
796
|
+
|
|
797
|
+
|
|
798
|
+
#: The plugin's reference-notation declaration, read duck-typed by
|
|
799
|
+
#: ``tree_engine.core.identifier_map``. A TOML document IS its root table, so
|
|
800
|
+
#: ``toml:Document`` is what the empty pointer names.
|
|
801
|
+
TOML_POINTER = JsonPointerNotation(_pointer_step, root_addressable=True)
|
|
802
|
+
|
|
803
|
+
|
|
804
|
+
class TomlFormatPlugin(FormatPluginContract, FormatBoundary):
|
|
805
|
+
"""The registered ``format_id="toml"`` plugin (concept C-016)."""
|
|
806
|
+
|
|
807
|
+
#: This format's native reference notation ({p021} third correspondence):
|
|
808
|
+
#: JSON Pointer, computed and parsed here rather than by shared code.
|
|
809
|
+
native_reference = TOML_POINTER
|
|
810
|
+
|
|
811
|
+
#: ``parse_fragment`` always wraps its result in a ``toml:Document`` (see
|
|
812
|
+
#: ``_build_root``'s own last line -- a fragment IS a mini standalone
|
|
813
|
+
#: document, root table and all), even for a fragment that is just one or
|
|
814
|
+
#: a few bare key/value lines. Without this declaration,
|
|
815
|
+
#: ``facade._fragment`` has no way to tell that wrapper apart from a
|
|
816
|
+
#: genuine value and never unwraps it, so ``insert()`` spliced the WHOLE
|
|
817
|
+
#: ``toml:Document`` in as a literal child of the real target container
|
|
818
|
+
#: instead of the fragment's own entries -- structurally valid (the
|
|
819
|
+
#: engine does not reject it) but wrong: the inserted key was buried one
|
|
820
|
+
#: level too deep, under a phantom document node with no key of its own.
|
|
821
|
+
#: Declaring it here is the exact fix ``plugins/plain_text.py`` already
|
|
822
|
+
#: uses for the identical shape.
|
|
823
|
+
fragment_container_kinds = (KIND_DOCUMENT,)
|
|
824
|
+
|
|
825
|
+
#: Bug c6042d8c: parent kinds under which an insertion is unambiguously a
|
|
826
|
+
#: whole document-level statement, read duck-typed by
|
|
827
|
+
#: ``tree_engine.facade._fragment`` (the same declaration style as
|
|
828
|
+
#: ``fragment_container_kinds`` just above) to pass ``options["mode"] =
|
|
829
|
+
#: "document"`` through to :meth:`parse_fragment`. Only the document ROOT
|
|
830
|
+
#: itself qualifies: a fragment landing directly under ``toml:Document``
|
|
831
|
+
#: is a top-level statement even when it happens not to be
|
|
832
|
+
#: newline-terminated (the bug's own reproduction), so the decision must
|
|
833
|
+
#: not fall back to the raw_text.endswith("\\n") heuristic. Deliberately
|
|
834
|
+
#: narrower than "any kind that ever holds document-level children" --
|
|
835
|
+
#: e.g. ``KIND_KEYVALUE`` is EXCLUDED even though a top-level key/value
|
|
836
|
+
#: line's OWN kind is ``KIND_KEYVALUE``, because a ``KIND_KEYVALUE`` node
|
|
837
|
+
#: is also the direct parent of a VALUE tree (its array elements/inline
|
|
838
|
+
#: pairs) once its value is a composite -- the same kind name means two
|
|
839
|
+
#: different levels depending on which node carries it, so only the
|
|
840
|
+
#: actual immediate parent's kind (never a sibling's or a routed
|
|
841
|
+
#: fallback's) may drive this, and ``toml:Document`` is the sole kind for
|
|
842
|
+
#: which that is unambiguous.
|
|
843
|
+
document_level_parent_kinds = (KIND_DOCUMENT,)
|
|
844
|
+
|
|
845
|
+
#: Kinds whose compact ``short_id`` is issued AFTER every other
|
|
846
|
+
#: addressable node's, read duck-typed by
|
|
847
|
+
#: ``tree_engine.facade._semantic_short_id_order``. The value tree
|
|
848
|
+
#: (array elements, inline-table pairs) is a second-class citizen of
|
|
849
|
+
#: this line-oriented document model: it sits BELOW the line level, so
|
|
850
|
+
#: numbering it in plain document order would renumber every key/value
|
|
851
|
+
#: line that follows an array -- a caller's ``node_ref`` for a line is
|
|
852
|
+
#: the address it has been given for years, while the value tree is new.
|
|
853
|
+
#: Deferring these kinds keeps the line-level numbering exactly as it
|
|
854
|
+
#: was (Document=1, then each table and key/value in document order) and
|
|
855
|
+
#: appends the value tree after it, which is also the numbering the
|
|
856
|
+
#: editor's own forest identity map produced before the value tree
|
|
857
|
+
#: existed in the engine at all.
|
|
858
|
+
deferred_short_id_kinds = _VALUE_KINDS
|
|
859
|
+
|
|
860
|
+
@property
|
|
861
|
+
def metadata(self) -> FormatPluginMetadata:
|
|
862
|
+
"""Static identity: ``toml`` plus the ``.toml`` file extension."""
|
|
863
|
+
return _METADATA
|
|
864
|
+
|
|
865
|
+
def _scan(self, text: str, malformed: type) -> _ParsedSource:
|
|
866
|
+
"""Validate with ``tomllib``, then tile the text losslessly."""
|
|
867
|
+
try:
|
|
868
|
+
tomllib.loads(text) # the authority on validity, never on layout
|
|
869
|
+
entries = _scan_entries(text)
|
|
870
|
+
except (tomllib.TOMLDecodeError, ValueError, TypeError, _TomlScanError) as exc:
|
|
871
|
+
raise malformed(f"cannot parse TOML: {exc}", format_id=FORMAT_ID,
|
|
872
|
+
**_toml_failure_position(text, exc)) from exc
|
|
873
|
+
if "".join(entry.raw for entry in entries) != text:
|
|
874
|
+
raise _unsupported(KIND_DOCUMENT, "this TOML cannot be tiled losslessly")
|
|
875
|
+
return _ParsedSource(entries=entries)
|
|
876
|
+
|
|
877
|
+
@staticmethod
|
|
878
|
+
def _decode(source: _Source, label: str) -> str:
|
|
879
|
+
"""Accept text or UTF-8 bytes; anything else breaks the call contract."""
|
|
880
|
+
if isinstance(source, str):
|
|
881
|
+
return source
|
|
882
|
+
if isinstance(source, (bytes, bytearray)):
|
|
883
|
+
return bytes(source).decode("utf-8")
|
|
884
|
+
raise _contract_error(f"{label} must be str or bytes, got {type(source).__name__}")
|
|
885
|
+
|
|
886
|
+
def parse_document(self, source: _Source, options: _Options = None, *, source_format_id: Optional[str] = None) -> Document:
|
|
887
|
+
"""Parse a whole TOML document ({p022}); malformed input raises
|
|
888
|
+
``FormatContentParseFailed`` (FORMAT_CONTENT_PARSE_FAILED)."""
|
|
889
|
+
text = self._decode(source, "source")
|
|
890
|
+
result = self.import_to_common(replace(self._scan(text, FormatContentParseFailed), ranged_text=text), options)
|
|
891
|
+
if not isinstance(result, Document):
|
|
892
|
+
raise _contract_error(f"a document must yield a Document, got {type(result).__name__}")
|
|
893
|
+
return result
|
|
894
|
+
|
|
895
|
+
def parse_fragment(self, fragment: _Source, options: _Options = None, *, mode: Literal["auto", "document", "value"] = "auto", source_format_id: Optional[str] = None) -> Node:
|
|
896
|
+
"""Parse a standalone TOML fragment into one container ``Node``; an
|
|
897
|
+
unrecognizable one raises ``FormatFragmentParseFailed``. The raw text is
|
|
898
|
+
never returned as a "no structure" signal: the boundary fixes ``Node``.
|
|
899
|
+
|
|
900
|
+
Handles both document-shaped fragments (a whole TOML document) and
|
|
901
|
+
value-mode fragments (a bare array element or inline-table pair, captured
|
|
902
|
+
via node_source_text for undo/redo): when a whole-document parse fails,
|
|
903
|
+
retries by wrapping the text as a synthetic array or table element and
|
|
904
|
+
extracting the value node, reusing the same value tiler (_tile_value)
|
|
905
|
+
that produces KIND_ARRAY_ITEM / KIND_INLINE_PAIR during document scan.
|
|
906
|
+
|
|
907
|
+
The `mode` parameter explicitly controls the parsing strategy:
|
|
908
|
+
- "auto" (default): use the heuristic (raw_text.endswith("\\n") -> document, else -> value).
|
|
909
|
+
The facade drives this explicitly for a document-level insertion (bug c6042d8c) by
|
|
910
|
+
passing ``options["mode"] = "document"`` whenever it addresses a parent kind this plugin
|
|
911
|
+
declares via ``document_level_parent_kinds`` (the same duck-typed declaration style as
|
|
912
|
+
``fragment_container_kinds``); a caller that does not recognize the target shape leaves
|
|
913
|
+
"auto" untouched, preserving today's heuristic exactly.
|
|
914
|
+
- "document": parse as document-level fragment (newline-terminate if needed)
|
|
915
|
+
- "value": parse as value-mode fragment (array element or inline pair)
|
|
916
|
+
|
|
917
|
+
The `mode` can also be passed via options["mode"] for compatibility with
|
|
918
|
+
the facade's option-passing mechanism.
|
|
919
|
+
"""
|
|
920
|
+
raw_text = self._decode(fragment, "fragment")
|
|
921
|
+
|
|
922
|
+
# Allow mode to be passed via options dict (from facade)
|
|
923
|
+
if options is not None and "mode" in options:
|
|
924
|
+
mode = options["mode"]
|
|
925
|
+
|
|
926
|
+
# Determine whether to try document-shaped parse first based on explicit mode
|
|
927
|
+
# or the heuristic for backward compatibility (auto mode).
|
|
928
|
+
should_try_document = (mode == "document") or (mode == "auto" and raw_text.endswith("\n"))
|
|
929
|
+
|
|
930
|
+
if should_try_document:
|
|
931
|
+
try:
|
|
932
|
+
# For document mode, ensure text ends with newline for proper parsing
|
|
933
|
+
doc_text = raw_text if raw_text.endswith("\n") else raw_text + "\n"
|
|
934
|
+
return _build_root(self._scan(doc_text, FormatFragmentParseFailed), ShortIdMap())
|
|
935
|
+
except FormatFragmentParseFailed:
|
|
936
|
+
pass
|
|
937
|
+
|
|
938
|
+
# Try value-mode for single-line or bare-value fragments (for undo/redo).
|
|
939
|
+
# Captured fragments from array/inline-pair nodes (via node_source_text)
|
|
940
|
+
# may be parseable as documents too (e.g. "b = 2"), but should return
|
|
941
|
+
# the value-mode node, not a document wrapper.
|
|
942
|
+
# Skip value-mode parsing if explicitly in document mode.
|
|
943
|
+
if mode == "document":
|
|
944
|
+
# If document mode was explicitly requested but document parse failed,
|
|
945
|
+
# try one final fallback with unstripped text as a bare document
|
|
946
|
+
try:
|
|
947
|
+
return _build_root(self._scan(raw_text, FormatFragmentParseFailed), ShortIdMap())
|
|
948
|
+
except FormatFragmentParseFailed:
|
|
949
|
+
raise FormatFragmentParseFailed(f"cannot parse TOML fragment in document mode", format_id=FORMAT_ID)
|
|
950
|
+
|
|
951
|
+
# Strip only for value-mode parsing to remove leading/trailing whitespace
|
|
952
|
+
text = raw_text.strip()
|
|
953
|
+
|
|
954
|
+
# Try value-mode: inline table pair (wrap in a synthetic inline table)
|
|
955
|
+
try:
|
|
956
|
+
wrapped_table = f"dummy = {{a = 0, {text}}}"
|
|
957
|
+
ids = ShortIdMap()
|
|
958
|
+
parsed = self._scan(wrapped_table, FormatFragmentParseFailed)
|
|
959
|
+
root = _build_root(parsed, ids)
|
|
960
|
+
# The wrapped table becomes a KeyValue node with inline-pair children
|
|
961
|
+
if root.children and len(root.children) > 0:
|
|
962
|
+
keyvalue = root.children[0]
|
|
963
|
+
if keyvalue.kind == KIND_KEYVALUE and len(keyvalue.children) > 1:
|
|
964
|
+
# Extract the second inline pair and return with a fresh node_id
|
|
965
|
+
extracted = keyvalue.children[1]
|
|
966
|
+
return replace(
|
|
967
|
+
make_node(extracted.kind, fields=dict(extracted.fields),
|
|
968
|
+
children=extracted.children),
|
|
969
|
+
node_id=generate_node_id())
|
|
970
|
+
except (FormatFragmentParseFailed, IndexError, AttributeError):
|
|
971
|
+
pass
|
|
972
|
+
|
|
973
|
+
# Try value-mode: bare array element (wrap in a synthetic key-value pair).
|
|
974
|
+
# UNSTRIPPED ``raw_text``, never ``text`` (bug c8723441): a multi-line
|
|
975
|
+
# array element's captured fragment carries its own leading newline
|
|
976
|
+
# and indentation (e.g. "\n 2, # two") as meaningful trivia to
|
|
977
|
+
# replay, not padding to discard -- ``text`` was stripped only for
|
|
978
|
+
# the inline-table attempt above, where that trivia cannot occur (an
|
|
979
|
+
# inline table is single-line by the TOML grammar itself). A "\n" is
|
|
980
|
+
# inserted before the synthetic closing ']' rather than reusing
|
|
981
|
+
# ``raw_text`` bare, so a captured trailing inline "#" comment (which
|
|
982
|
+
# runs to end-of-line, not to the next "]") cannot swallow the
|
|
983
|
+
# bracket the way it would if the comment and "]" shared one line.
|
|
984
|
+
try:
|
|
985
|
+
wrapped_array = f"dummy = [{raw_text}\n]"
|
|
986
|
+
ids = ShortIdMap()
|
|
987
|
+
parsed = self._scan(wrapped_array, FormatFragmentParseFailed)
|
|
988
|
+
root = _build_root(parsed, ids)
|
|
989
|
+
# The wrapped array becomes a KeyValue node with array-element children
|
|
990
|
+
if root.children and len(root.children) > 0:
|
|
991
|
+
keyvalue = root.children[0]
|
|
992
|
+
if keyvalue.kind == KIND_KEYVALUE and keyvalue.children:
|
|
993
|
+
# Extract the first array element and return with a fresh node_id
|
|
994
|
+
extracted = keyvalue.children[0]
|
|
995
|
+
return replace(
|
|
996
|
+
make_node(extracted.kind, fields=dict(extracted.fields),
|
|
997
|
+
children=extracted.children),
|
|
998
|
+
node_id=generate_node_id())
|
|
999
|
+
except (FormatFragmentParseFailed, IndexError, AttributeError):
|
|
1000
|
+
pass
|
|
1001
|
+
|
|
1002
|
+
# Try normal document-shaped parse last (only when value-mode fails)
|
|
1003
|
+
try:
|
|
1004
|
+
return _build_root(self._scan(text, FormatFragmentParseFailed), ShortIdMap())
|
|
1005
|
+
except FormatFragmentParseFailed:
|
|
1006
|
+
pass
|
|
1007
|
+
|
|
1008
|
+
# If all else fails, raise the original error
|
|
1009
|
+
raise FormatFragmentParseFailed(f"cannot parse TOML fragment", format_id=FORMAT_ID)
|
|
1010
|
+
|
|
1011
|
+
def import_external_tree(self, external_tree: Any, options: _Options = None) -> Union[Node, Document]:
|
|
1012
|
+
"""Import an already-decoded TOML mapping (e.g. from ``tomllib.load``)."""
|
|
1013
|
+
return self.import_to_common(external_tree, options)
|
|
1014
|
+
|
|
1015
|
+
def import_to_common(self, external_representation: Any, options: _Options = None) -> Union[Node, Document]:
|
|
1016
|
+
"""The single input translator ({p056}, {p057}): this module's private scan
|
|
1017
|
+
result, or a plain mapping -- serialized to TOML then re-scanned, so it
|
|
1018
|
+
carries the same span invariants as a parse."""
|
|
1019
|
+
if isinstance(external_representation, _ParsedSource):
|
|
1020
|
+
root = _build_root(external_representation, ShortIdMap())
|
|
1021
|
+
return Document(root=root, source_format_id=FORMAT_ID)
|
|
1022
|
+
if isinstance(external_representation, Mapping):
|
|
1023
|
+
return self.parse_document(_dump_toml(external_representation), options)
|
|
1024
|
+
raise _unsupported(type(external_representation).__name__, "expected a scan or mapping")
|
|
1025
|
+
|
|
1026
|
+
def export_from_common(self, nodes: Union[Node, Document], options: _Options = None) -> Any:
|
|
1027
|
+
"""Common-model nodes -> the plain mapping backend representation. Native
|
|
1028
|
+
date/time literals surface here as ``datetime``/``date``/``time``; in the
|
|
1029
|
+
tree they stay exact text, which is what keeps rendering byte-identical."""
|
|
1030
|
+
if not isinstance(nodes, (Node, Document)):
|
|
1031
|
+
raise _contract_error(f"expected a Node or Document, got {type(nodes).__name__}")
|
|
1032
|
+
root = nodes.root if isinstance(nodes, Document) else nodes
|
|
1033
|
+
try:
|
|
1034
|
+
return tomllib.loads(_render(root))
|
|
1035
|
+
except (tomllib.TOMLDecodeError, ValueError, TypeError) as exc:
|
|
1036
|
+
raise _unsupported(str(root.kind), f"not a standalone TOML document: {exc}") from exc
|
|
1037
|
+
|
|
1038
|
+
def generate_output(self, target: Union[Node, Document, Any], options: _Options = None) -> Union[str, bytes]:
|
|
1039
|
+
"""Final TOML text (bytes with ``options["as_bytes"]``): common-model input
|
|
1040
|
+
replays stored spans byte-identically, a plain mapping dumps canonically."""
|
|
1041
|
+
options = options or {}
|
|
1042
|
+
if isinstance(target, (Node, Document)):
|
|
1043
|
+
text = _render(target.root if isinstance(target, Document) else target)
|
|
1044
|
+
elif isinstance(target, Mapping):
|
|
1045
|
+
text = _dump_toml(target)
|
|
1046
|
+
elif isinstance(target, str):
|
|
1047
|
+
text = target
|
|
1048
|
+
else:
|
|
1049
|
+
raise _contract_error(f"cannot render {type(target).__name__}; expected Node/Document/mapping/str")
|
|
1050
|
+
return text.encode("utf-8") if options.get("as_bytes") else text
|
|
1051
|
+
|
|
1052
|
+
def semantic_role_mapping(self) -> SemanticRoleMapping:
|
|
1053
|
+
"""TOML models no function, method, class, or module ({p056})."""
|
|
1054
|
+
return _ROLE_MAP
|
|
1055
|
+
|
|
1056
|
+
def render_document(self, document: Document) -> bytes:
|
|
1057
|
+
"""CORE-facing counterpart of ``parse_document``: exact UTF-8 bytes."""
|
|
1058
|
+
result = self.generate_output(document, {"as_bytes": True})
|
|
1059
|
+
if not isinstance(result, bytes):
|
|
1060
|
+
raise _contract_error(f"render_document expected bytes, got {type(result).__name__}")
|
|
1061
|
+
return result
|
|
1062
|
+
|
|
1063
|
+
def render_fragment(self, node: Node) -> str:
|
|
1064
|
+
"""CORE-facing counterpart of ``parse_fragment``: exact source text."""
|
|
1065
|
+
result = self.generate_output(node, {})
|
|
1066
|
+
if not isinstance(result, str):
|
|
1067
|
+
raise _contract_error(f"render_fragment expected str, got {type(result).__name__}")
|
|
1068
|
+
return result
|
|
1069
|
+
|
|
1070
|
+
# Ready-made singleton a sibling registry step can import and register under
|
|
1071
|
+
# ``format_id="toml"``, mirroring ``JSON_FORMAT_PLUGIN``/``BSL_FORMAT_PLUGIN``.
|
|
1072
|
+
TOML_FORMAT_PLUGIN = TomlFormatPlugin()
|