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,813 @@
|
|
|
1
|
+
"""The JSON format plugin (concept C-016, atomic step A-003).
|
|
2
|
+
|
|
3
|
+
Implements ``FormatPluginContract`` and ``FormatBoundary`` for
|
|
4
|
+
``format_id="json"``. Objects map to keyed container nodes (``json:Object``,
|
|
5
|
+
whose children are ``json:Member`` nodes carrying the member's key), arrays
|
|
6
|
+
to ordered containers (``json:Array``), scalars to leaf nodes
|
|
7
|
+
(``json:String``/``Number``/``Boolean``/``Null``). No external parser object
|
|
8
|
+
escapes this module: the private parser shapes (``_RawValue``/
|
|
9
|
+
``_DocumentSource``) always convert to common-model ``Node``/``Document``.
|
|
10
|
+
|
|
11
|
+
Byte fidelity: every node built from parsed text keeps its exact original
|
|
12
|
+
source slice in ``fields["raw"]``. A JSON value's span is lexically
|
|
13
|
+
self-contained, so replaying a stored ``"raw"`` string reproduces the whole
|
|
14
|
+
subtree verbatim; nothing untouched since parsing is ever re-formatted. The
|
|
15
|
+
document root's ``"raw"`` is widened to the *entire* original text so outer
|
|
16
|
+
leading/trailing whitespace round-trips too. A node built without parsing
|
|
17
|
+
(``import_to_common`` on a plain Python value) carries no ``"raw"`` and
|
|
18
|
+
falls back to deterministic canonical rendering, computed bottom-up so
|
|
19
|
+
untouched raw-carrying descendants still reuse their exact original text.
|
|
20
|
+
|
|
21
|
+
A container's ``"raw"`` caches its ENTIRE composed subtree, so
|
|
22
|
+
``core.live_tree.invalidate_cached_source`` correctly strips it (per
|
|
23
|
+
``CACHED_SOURCE_FIELDS``) off every ancestor of a pointwise child mutation --
|
|
24
|
+
but the no-cache fallback above then has to recompose that container without
|
|
25
|
+
ever having seen its members'/items' own original layout, which used to
|
|
26
|
+
collapse a whole multi-line object or array to one compact line on ANY
|
|
27
|
+
pointwise edit (bug 5dfa5ae3). Each ``json:Member`` therefore also carries
|
|
28
|
+
its own ``"leading"`` (the exact whitespace/newline/indent/comma slice
|
|
29
|
+
between the previous sibling's end -- or the opening ``{`` -- and this
|
|
30
|
+
member's key) and ``"sep"`` (the exact slice between the key and the value,
|
|
31
|
+
normally ``": "``); each ``json:Array`` item carries the same ``"leading"``
|
|
32
|
+
directly on the item node itself (arrays have no member wrapper). The
|
|
33
|
+
container itself carries ``"closing_trivia"`` (the slice between the last
|
|
34
|
+
member/item and the closing bracket). None of these three names collide with
|
|
35
|
+
``CACHED_SOURCE_FIELDS`` (``"raw"``/``"content"``), so a pointwise splice
|
|
36
|
+
that invalidates the container's composed-subtree cache leaves every
|
|
37
|
+
untouched sibling's own trivia intact -- only the mutated member's own
|
|
38
|
+
rendering changes. A fragment-inserted member/item has none of this parsed
|
|
39
|
+
trivia; the no-cache fallback then borrows it from a sibling (the
|
|
40
|
+
container's dominant style), falling back to a minimal default only when the
|
|
41
|
+
container has no sibling trivia at all (an all-inserted or plain-value
|
|
42
|
+
container), which keeps a genuinely bare/compact container compact.
|
|
43
|
+
|
|
44
|
+
Source-of-truth requirement labels honored here: {p026}, {p060}, {p062}.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
from __future__ import annotations
|
|
48
|
+
|
|
49
|
+
import itertools
|
|
50
|
+
import json
|
|
51
|
+
from dataclasses import dataclass, field, replace
|
|
52
|
+
from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Union
|
|
53
|
+
|
|
54
|
+
from tree_engine.core.identity import generate_node_id
|
|
55
|
+
from tree_engine.core.offsets import char_to_byte_offset
|
|
56
|
+
from tree_engine.core.nodes import Document, Node, make_node
|
|
57
|
+
from tree_engine.core.plugin_boundary import FormatBoundary
|
|
58
|
+
from tree_engine.exceptions import FormatContentParseFailed
|
|
59
|
+
from tree_engine.plugins.parse_position import offset_in_message, position_details
|
|
60
|
+
from tree_engine.plugins.contract import (
|
|
61
|
+
FormatPluginContract, FormatPluginContractError, FormatPluginMetadata,
|
|
62
|
+
SemanticRoleMapping, UnsupportedTranslationError,
|
|
63
|
+
)
|
|
64
|
+
from tree_engine.plugins.json_pointer import JsonPointerNotation
|
|
65
|
+
|
|
66
|
+
__all__ = ["FORMAT_ID", "JSON_POINTER", "JsonFormatPlugin", "JSON_FORMAT_PLUGIN"]
|
|
67
|
+
|
|
68
|
+
FORMAT_ID = "json"
|
|
69
|
+
KIND_OBJECT = f"{FORMAT_ID}:Object"
|
|
70
|
+
KIND_MEMBER = f"{FORMAT_ID}:Member"
|
|
71
|
+
KIND_ARRAY = f"{FORMAT_ID}:Array"
|
|
72
|
+
KIND_STRING = f"{FORMAT_ID}:String"
|
|
73
|
+
KIND_NUMBER = f"{FORMAT_ID}:Number"
|
|
74
|
+
KIND_BOOLEAN = f"{FORMAT_ID}:Boolean"
|
|
75
|
+
KIND_NULL = f"{FORMAT_ID}:Null"
|
|
76
|
+
|
|
77
|
+
_METADATA = FormatPluginMetadata(
|
|
78
|
+
format_id=FORMAT_ID,
|
|
79
|
+
aliases=(),
|
|
80
|
+
file_extensions=("json",),
|
|
81
|
+
plugin_version="1.0.0",
|
|
82
|
+
contract_version="1.0.0",
|
|
83
|
+
capabilities={
|
|
84
|
+
# Whether the Code Analysis server can save a file of this format (decision D-CB.4); the editor reads it
|
|
85
|
+
# instead of keeping its own list of unsupported suffixes.
|
|
86
|
+
"ca_save_supported": True,
|
|
87
|
+
"semantic_role_mapping": True,
|
|
88
|
+
# Measured: pipeline/checks/check_roundtrip.py's STRICT policy for
|
|
89
|
+
# json round-tripped the FULL real corpus (12/12 tracked .json
|
|
90
|
+
# files, no sampling) byte-identical -- True is honest.
|
|
91
|
+
"byte_identical_round_trip": True,
|
|
92
|
+
# Addressable common-model tree, walkable for preview/search.
|
|
93
|
+
"navigable": True,
|
|
94
|
+
# Round trip is byte-identical and structural mutation (member
|
|
95
|
+
# insert/delete/move) is exercised elsewhere in this suite -- safe
|
|
96
|
+
# for write-back.
|
|
97
|
+
"editable": True,
|
|
98
|
+
},
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
# JSON models no function/method/class/module; empty is correct, not an error.
|
|
102
|
+
_ROLE_MAP = SemanticRoleMapping({})
|
|
103
|
+
_WHITESPACE = " \t\n\r"
|
|
104
|
+
|
|
105
|
+
def _contract_error(message: str) -> FormatPluginContractError:
|
|
106
|
+
return FormatPluginContractError(plugin_id=FORMAT_ID, message=message)
|
|
107
|
+
|
|
108
|
+
def _unsupported(node_type: str, message: str) -> UnsupportedTranslationError:
|
|
109
|
+
return UnsupportedTranslationError(node_type=node_type, format_id=FORMAT_ID, message=message)
|
|
110
|
+
|
|
111
|
+
# Every node built here gets a UUID4 ({p013}) + short id ({p097}); never bare make_node.
|
|
112
|
+
_short_id_counter = itertools.count(1)
|
|
113
|
+
|
|
114
|
+
def _identified_node(kind: str, fields: Mapping[str, Any], children: Tuple[Node, ...] = (),
|
|
115
|
+
buffer_range: Optional[Tuple[int, int]] = None) -> Node:
|
|
116
|
+
"""``make_node`` plus a fresh ``node_id``/``short_id`` (and, for a parsed document, the node's
|
|
117
|
+
``buffer_range``: half-open UTF-8 byte offsets into the source, bug b548f445)."""
|
|
118
|
+
return replace(make_node(kind, fields=fields, children=children),
|
|
119
|
+
node_id=generate_node_id(), short_id=next(_short_id_counter),
|
|
120
|
+
buffer_range=buffer_range)
|
|
121
|
+
|
|
122
|
+
def _with_leading(node: Node, leading: str) -> Node:
|
|
123
|
+
"""Attach this array item's own ``"leading"`` trivia to an already-built
|
|
124
|
+
node, preserving its identity (``node_id``/``short_id``/``kind``/
|
|
125
|
+
``children``) -- ``Node``'s constructor performs no validation of its
|
|
126
|
+
own, so adding one extra ``fields`` key is safe (see ``core/nodes.py``)."""
|
|
127
|
+
return replace(node, fields={**node.fields, "leading": leading})
|
|
128
|
+
|
|
129
|
+
class _JsonParseError(Exception):
|
|
130
|
+
"""Internal, module-private malformed-JSON signal (never escapes)."""
|
|
131
|
+
|
|
132
|
+
@dataclass
|
|
133
|
+
class _RawValue:
|
|
134
|
+
"""One parsed JSON value plus its raw slice; private, never returned.
|
|
135
|
+
|
|
136
|
+
``member_leading``/``member_sep`` run parallel to ``members`` (object
|
|
137
|
+
case); ``item_leading`` runs parallel to ``items`` (array case).
|
|
138
|
+
``closing_trivia`` is the container's own slice between its last
|
|
139
|
+
member/item and its closing bracket. See the module docstring (bug
|
|
140
|
+
5dfa5ae3) for why these exist alongside ``raw``.
|
|
141
|
+
"""
|
|
142
|
+
kind: str
|
|
143
|
+
raw: str
|
|
144
|
+
value: Any = None
|
|
145
|
+
members: List[Tuple[str, "_RawValue"]] = field(default_factory=list)
|
|
146
|
+
items: List["_RawValue"] = field(default_factory=list)
|
|
147
|
+
member_leading: List[str] = field(default_factory=list)
|
|
148
|
+
member_sep: List[str] = field(default_factory=list)
|
|
149
|
+
item_leading: List[str] = field(default_factory=list)
|
|
150
|
+
closing_trivia: str = ""
|
|
151
|
+
# Absolute character offset of ``raw`` in the parsed document, and (object case, parallel to
|
|
152
|
+
# ``members``) of each member's key; used to assign ``buffer_range`` (bug b548f445).
|
|
153
|
+
start: int = -1
|
|
154
|
+
member_start: List[int] = field(default_factory=list)
|
|
155
|
+
|
|
156
|
+
@dataclass
|
|
157
|
+
class _DocumentSource:
|
|
158
|
+
"""A whole parsed document: its top-level value, the full text, and the
|
|
159
|
+
OUTER leading/trailing whitespace around the top-level value (the value's
|
|
160
|
+
own 'raw' span never includes either -- see ``_parse_json_text``)."""
|
|
161
|
+
value: _RawValue
|
|
162
|
+
full_text: str
|
|
163
|
+
leading: str = ""
|
|
164
|
+
trailing: str = ""
|
|
165
|
+
|
|
166
|
+
_SCALAR_DECODER = json.JSONDecoder()
|
|
167
|
+
|
|
168
|
+
def _skip_ws(text: str, pos: int) -> int:
|
|
169
|
+
while pos < len(text) and text[pos] in _WHITESPACE:
|
|
170
|
+
pos += 1
|
|
171
|
+
return pos
|
|
172
|
+
|
|
173
|
+
def _scan_value(text: str, pos: int) -> Tuple[_RawValue, int]:
|
|
174
|
+
pos = _skip_ws(text, pos)
|
|
175
|
+
if pos >= len(text):
|
|
176
|
+
raise _JsonParseError(f"unexpected end of input at position {pos}")
|
|
177
|
+
char = text[pos]
|
|
178
|
+
if char == "{":
|
|
179
|
+
return _scan_object(text, pos)
|
|
180
|
+
if char == "[":
|
|
181
|
+
return _scan_array(text, pos)
|
|
182
|
+
try:
|
|
183
|
+
value, end = _SCALAR_DECODER.raw_decode(text, pos)
|
|
184
|
+
except json.JSONDecodeError as exc:
|
|
185
|
+
raise _JsonParseError(f"malformed JSON at position {pos}: {exc}") from exc
|
|
186
|
+
if isinstance(value, (dict, list)):
|
|
187
|
+
raise _JsonParseError(f"unexpected container at position {pos}")
|
|
188
|
+
if isinstance(value, bool):
|
|
189
|
+
kind = KIND_BOOLEAN
|
|
190
|
+
elif value is None:
|
|
191
|
+
kind = KIND_NULL
|
|
192
|
+
elif isinstance(value, str):
|
|
193
|
+
kind = KIND_STRING
|
|
194
|
+
elif isinstance(value, (int, float)):
|
|
195
|
+
kind = KIND_NUMBER
|
|
196
|
+
else: # pragma: no cover - stdlib json never produces another type
|
|
197
|
+
raise _JsonParseError(f"unsupported scalar type at position {pos}")
|
|
198
|
+
return _RawValue(kind=kind, raw=text[pos:end], value=value, start=pos), end
|
|
199
|
+
|
|
200
|
+
def _scan_member(text: str, pos: int) -> Tuple[str, str, _RawValue, int]:
|
|
201
|
+
"""Scan one ``"key": value`` pair starting exactly at ``pos`` (already
|
|
202
|
+
past any leading whitespace -- the caller owns that, since it differs
|
|
203
|
+
between an object's own member loop and a standalone member fragment).
|
|
204
|
+
Returns ``(key, sep, value_raw, end_pos)`` where ``sep`` is the exact
|
|
205
|
+
slice between the key and the value (colon plus whatever whitespace
|
|
206
|
+
surrounds it). Shared by ``_scan_object`` and ``_parse_member_fragment``
|
|
207
|
+
so the two never drift apart (bug 5dfa5ae3)."""
|
|
208
|
+
if pos >= len(text) or text[pos] != '"':
|
|
209
|
+
raise _JsonParseError(f"expected object key (string) at position {pos}")
|
|
210
|
+
try:
|
|
211
|
+
key, pos = _SCALAR_DECODER.raw_decode(text, pos)
|
|
212
|
+
except json.JSONDecodeError as exc:
|
|
213
|
+
raise _JsonParseError(f"malformed object key at position {pos}: {exc}") from exc
|
|
214
|
+
key_end = pos
|
|
215
|
+
pos = _skip_ws(text, pos)
|
|
216
|
+
if pos >= len(text) or text[pos] != ":":
|
|
217
|
+
raise _JsonParseError(f"expected ':' at position {pos}")
|
|
218
|
+
value_raw, pos = _scan_value(text, pos + 1)
|
|
219
|
+
# value_raw.raw is the value's own exact tail slice ending at 'pos', so
|
|
220
|
+
# subtracting its length locates where the value ACTUALLY starts without
|
|
221
|
+
# duplicating _scan_value's internal whitespace-skipping logic here.
|
|
222
|
+
value_start = pos - len(value_raw.raw)
|
|
223
|
+
return key, text[key_end:value_start], value_raw, pos
|
|
224
|
+
|
|
225
|
+
def _parse_member_fragment(text: str) -> Tuple[str, str, _RawValue]:
|
|
226
|
+
"""Parse a standalone ``"key": value`` fragment (no wrapping ``{}``) --
|
|
227
|
+
what ``facade.insert``/``replace`` hand a format's ``parse_fragment``
|
|
228
|
+
when inserting one new member into an existing object. Raises
|
|
229
|
+
``_JsonParseError`` on anything else, including trailing garbage,
|
|
230
|
+
exactly like ``_parse_json_text`` does for a whole value."""
|
|
231
|
+
start = _skip_ws(text, 0)
|
|
232
|
+
key, sep, value_raw, end = _scan_member(text, start)
|
|
233
|
+
if text[end:].strip(_WHITESPACE):
|
|
234
|
+
raise _JsonParseError(f"unexpected trailing content at position {end}")
|
|
235
|
+
return key, sep, value_raw
|
|
236
|
+
|
|
237
|
+
def _scan_object(text: str, pos: int) -> Tuple[_RawValue, int]:
|
|
238
|
+
start = pos
|
|
239
|
+
pos += 1
|
|
240
|
+
members: List[Tuple[str, _RawValue]] = []
|
|
241
|
+
member_start: List[int] = []
|
|
242
|
+
member_leading: List[str] = []
|
|
243
|
+
member_sep: List[str] = []
|
|
244
|
+
# 'boundary' trails one step behind 'pos': it marks the end of the
|
|
245
|
+
# previous element (or the position right after '{' for the first
|
|
246
|
+
# member) and stays put across the comma/whitespace skip below, so the
|
|
247
|
+
# NEXT member's 'leading' slice (text[boundary:key_start]) captures that
|
|
248
|
+
# comma and whitespace verbatim instead of losing it to _skip_ws.
|
|
249
|
+
boundary = pos
|
|
250
|
+
pos = _skip_ws(text, pos)
|
|
251
|
+
if pos < len(text) and text[pos] == "}":
|
|
252
|
+
closing_trivia = text[boundary:pos]
|
|
253
|
+
pos += 1
|
|
254
|
+
return _RawValue(kind=KIND_OBJECT, raw=text[start:pos], members=members,
|
|
255
|
+
member_leading=member_leading, member_sep=member_sep,
|
|
256
|
+
closing_trivia=closing_trivia, start=start, member_start=member_start), pos
|
|
257
|
+
while True:
|
|
258
|
+
pos = _skip_ws(text, pos)
|
|
259
|
+
key_start = pos
|
|
260
|
+
key, sep, value_raw, pos = _scan_member(text, pos)
|
|
261
|
+
member_leading.append(text[boundary:key_start])
|
|
262
|
+
member_start.append(key_start)
|
|
263
|
+
member_sep.append(sep)
|
|
264
|
+
members.append((key, value_raw))
|
|
265
|
+
boundary = pos
|
|
266
|
+
pos = _skip_ws(text, pos)
|
|
267
|
+
if pos >= len(text):
|
|
268
|
+
raise _JsonParseError("unterminated object")
|
|
269
|
+
if text[pos] == ",":
|
|
270
|
+
pos += 1
|
|
271
|
+
continue
|
|
272
|
+
if text[pos] == "}":
|
|
273
|
+
break
|
|
274
|
+
raise _JsonParseError(f"expected ',' or '}}' at position {pos}")
|
|
275
|
+
closing_trivia = text[boundary:pos]
|
|
276
|
+
pos += 1
|
|
277
|
+
return _RawValue(kind=KIND_OBJECT, raw=text[start:pos], members=members,
|
|
278
|
+
member_leading=member_leading, member_sep=member_sep,
|
|
279
|
+
closing_trivia=closing_trivia, start=start, member_start=member_start), pos
|
|
280
|
+
|
|
281
|
+
def _scan_array(text: str, pos: int) -> Tuple[_RawValue, int]:
|
|
282
|
+
start = pos
|
|
283
|
+
pos += 1
|
|
284
|
+
items: List[_RawValue] = []
|
|
285
|
+
item_leading: List[str] = []
|
|
286
|
+
# Same trailing-boundary trick as _scan_object, for the same reason.
|
|
287
|
+
boundary = pos
|
|
288
|
+
pos = _skip_ws(text, pos)
|
|
289
|
+
if pos < len(text) and text[pos] == "]":
|
|
290
|
+
closing_trivia = text[boundary:pos]
|
|
291
|
+
pos += 1
|
|
292
|
+
return _RawValue(kind=KIND_ARRAY, raw=text[start:pos], items=items,
|
|
293
|
+
item_leading=item_leading, closing_trivia=closing_trivia, start=start), pos
|
|
294
|
+
while True:
|
|
295
|
+
item_raw, pos = _scan_value(text, pos)
|
|
296
|
+
item_start = pos - len(item_raw.raw)
|
|
297
|
+
item_leading.append(text[boundary:item_start])
|
|
298
|
+
items.append(item_raw)
|
|
299
|
+
boundary = pos
|
|
300
|
+
pos = _skip_ws(text, pos)
|
|
301
|
+
if pos >= len(text):
|
|
302
|
+
raise _JsonParseError("unterminated array")
|
|
303
|
+
if text[pos] == ",":
|
|
304
|
+
pos += 1
|
|
305
|
+
continue
|
|
306
|
+
if text[pos] == "]":
|
|
307
|
+
break
|
|
308
|
+
raise _JsonParseError(f"expected ',' or ']' at position {pos}")
|
|
309
|
+
closing_trivia = text[boundary:pos]
|
|
310
|
+
pos += 1
|
|
311
|
+
return _RawValue(kind=KIND_ARRAY, raw=text[start:pos], items=items,
|
|
312
|
+
item_leading=item_leading, closing_trivia=closing_trivia, start=start), pos
|
|
313
|
+
|
|
314
|
+
def _parse_json_text(text: str) -> Tuple[_RawValue, str, str]:
|
|
315
|
+
"""Parse one whole document; raises ``_JsonParseError`` on anything
|
|
316
|
+
malformed, including trailing non-whitespace garbage. Returns the
|
|
317
|
+
top-level value plus the OUTER leading/trailing whitespace around it
|
|
318
|
+
(``value.raw`` never includes either, by construction of ``_scan_value``);
|
|
319
|
+
``parse_document`` widens the root's ``raw`` cache with all three, and
|
|
320
|
+
also keeps the leading/trailing pieces as their own identity fields so
|
|
321
|
+
the no-cache fallback can still reproduce them after a pointwise
|
|
322
|
+
invalidation strips that cache (bug 5dfa5ae3)."""
|
|
323
|
+
value, end = _scan_value(text, 0)
|
|
324
|
+
if text[end:].strip(_WHITESPACE):
|
|
325
|
+
raise _JsonParseError(f"unexpected trailing content at position {end}")
|
|
326
|
+
value_start = end - len(value.raw)
|
|
327
|
+
return value, text[:value_start], text[end:]
|
|
328
|
+
|
|
329
|
+
def _raw_to_node(raw_value: _RawValue, conv: Optional[Callable[[int], int]] = None) -> Node:
|
|
330
|
+
"""Build the node tree for ``raw_value``; ``conv`` (character offset -> UTF-8 byte offset) is given
|
|
331
|
+
only when parsing a whole document, and then every node gets its ``buffer_range``."""
|
|
332
|
+
own = (conv(raw_value.start), conv(raw_value.start + len(raw_value.raw))) if conv else None
|
|
333
|
+
if raw_value.kind == KIND_OBJECT:
|
|
334
|
+
members = tuple(
|
|
335
|
+
_identified_node(
|
|
336
|
+
KIND_MEMBER,
|
|
337
|
+
# 'leading'/'sep' -- not 'raw' -- are this MEMBER's own
|
|
338
|
+
# identity data (its layout, not a cache of its composed
|
|
339
|
+
# subtree): the whitespace/newline/indent/comma before its
|
|
340
|
+
# key, and the key-to-value separator. Neither name is in
|
|
341
|
+
# CACHED_SOURCE_FIELDS, so a pointwise splice elsewhere in
|
|
342
|
+
# the object invalidates the OBJECT's 'raw' cache but never
|
|
343
|
+
# touches an untouched member's own layout (bug 5dfa5ae3).
|
|
344
|
+
fields={
|
|
345
|
+
"key": key,
|
|
346
|
+
"leading": raw_value.member_leading[index],
|
|
347
|
+
"sep": raw_value.member_sep[index],
|
|
348
|
+
},
|
|
349
|
+
children=(_raw_to_node(value, conv),),
|
|
350
|
+
buffer_range=(conv(raw_value.member_start[index]), conv(value.start + len(value.raw))) if conv else None,
|
|
351
|
+
)
|
|
352
|
+
for index, (key, value) in enumerate(raw_value.members)
|
|
353
|
+
)
|
|
354
|
+
return _identified_node(
|
|
355
|
+
KIND_OBJECT,
|
|
356
|
+
fields={"raw": raw_value.raw, "closing_trivia": raw_value.closing_trivia},
|
|
357
|
+
children=members, buffer_range=own,
|
|
358
|
+
)
|
|
359
|
+
if raw_value.kind == KIND_ARRAY:
|
|
360
|
+
# Arrays have no per-item wrapper node, so each item's own 'leading'
|
|
361
|
+
# trivia is attached directly to the item node itself -- same
|
|
362
|
+
# identity-not-cache reasoning as the member case above.
|
|
363
|
+
items = tuple(
|
|
364
|
+
_with_leading(_raw_to_node(item, conv), leading)
|
|
365
|
+
for item, leading in zip(raw_value.items, raw_value.item_leading)
|
|
366
|
+
)
|
|
367
|
+
return _identified_node(
|
|
368
|
+
KIND_ARRAY,
|
|
369
|
+
fields={"raw": raw_value.raw, "closing_trivia": raw_value.closing_trivia},
|
|
370
|
+
children=items, buffer_range=own,
|
|
371
|
+
)
|
|
372
|
+
if raw_value.kind == KIND_NULL:
|
|
373
|
+
return _identified_node(KIND_NULL, fields={"raw": raw_value.raw}, buffer_range=own)
|
|
374
|
+
return _identified_node(raw_value.kind, fields={"value": raw_value.value, "raw": raw_value.raw},
|
|
375
|
+
buffer_range=own)
|
|
376
|
+
|
|
377
|
+
def _plain_to_node(value: Any, ancestors: frozenset) -> Node:
|
|
378
|
+
"""Build a raw-less node tree from an already-decoded plain Python
|
|
379
|
+
value; ``ancestors`` holds container ``id()``s on the recursion path,
|
|
380
|
+
rejecting a circular structure instead of looping forever."""
|
|
381
|
+
if isinstance(value, dict):
|
|
382
|
+
marker = id(value)
|
|
383
|
+
if marker in ancestors:
|
|
384
|
+
raise _unsupported("object", "circular reference detected")
|
|
385
|
+
nested = ancestors | {marker}
|
|
386
|
+
members = []
|
|
387
|
+
for key, item in value.items():
|
|
388
|
+
if not isinstance(key, str):
|
|
389
|
+
raise _unsupported("object-key", f"non-string object key: {key!r}")
|
|
390
|
+
members.append(
|
|
391
|
+
_identified_node(KIND_MEMBER, fields={"key": key}, children=(_plain_to_node(item, nested),))
|
|
392
|
+
)
|
|
393
|
+
return _identified_node(KIND_OBJECT, fields={}, children=tuple(members))
|
|
394
|
+
if isinstance(value, (list, tuple)):
|
|
395
|
+
marker = id(value)
|
|
396
|
+
if marker in ancestors:
|
|
397
|
+
raise _unsupported("array", "circular reference detected")
|
|
398
|
+
nested = ancestors | {marker}
|
|
399
|
+
return _identified_node(KIND_ARRAY, fields={}, children=tuple(_plain_to_node(v, nested) for v in value))
|
|
400
|
+
if isinstance(value, bool):
|
|
401
|
+
return _identified_node(KIND_BOOLEAN, fields={"value": value})
|
|
402
|
+
if isinstance(value, str):
|
|
403
|
+
return _identified_node(KIND_STRING, fields={"value": value})
|
|
404
|
+
if isinstance(value, (int, float)):
|
|
405
|
+
return _identified_node(KIND_NUMBER, fields={"value": value})
|
|
406
|
+
if value is None:
|
|
407
|
+
return _identified_node(KIND_NULL, fields={})
|
|
408
|
+
raise _unsupported(
|
|
409
|
+
type(value).__name__, f"Python type {type(value).__name__!r} has no JSON representation"
|
|
410
|
+
)
|
|
411
|
+
|
|
412
|
+
def _node_to_plain(node: Node, ancestors: frozenset) -> Any:
|
|
413
|
+
"""Common model -> JSON-compatible plain dict/list/scalar."""
|
|
414
|
+
marker = id(node)
|
|
415
|
+
if marker in ancestors:
|
|
416
|
+
raise _unsupported(str(node.kind), "circular reference detected")
|
|
417
|
+
nested = ancestors | {marker}
|
|
418
|
+
kind = node.kind
|
|
419
|
+
if kind == KIND_OBJECT:
|
|
420
|
+
result: Dict[str, Any] = {}
|
|
421
|
+
for member in node.children:
|
|
422
|
+
if member.kind != KIND_MEMBER or not member.children:
|
|
423
|
+
raise _unsupported(str(member.kind), "malformed object member")
|
|
424
|
+
key = member.fields.get("key")
|
|
425
|
+
if not isinstance(key, str):
|
|
426
|
+
raise _unsupported("Member", "member key must be a string")
|
|
427
|
+
result[key] = _node_to_plain(member.children[0], nested)
|
|
428
|
+
return result
|
|
429
|
+
if kind == KIND_ARRAY:
|
|
430
|
+
return [_node_to_plain(child, nested) for child in node.children]
|
|
431
|
+
if kind == KIND_STRING:
|
|
432
|
+
value = node.fields.get("value")
|
|
433
|
+
if not isinstance(value, str):
|
|
434
|
+
raise _unsupported(str(kind), "String node missing a str value")
|
|
435
|
+
return value
|
|
436
|
+
if kind == KIND_NUMBER:
|
|
437
|
+
value = node.fields.get("value")
|
|
438
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
439
|
+
raise _unsupported(str(kind), "Number node missing a numeric value")
|
|
440
|
+
return value
|
|
441
|
+
if kind == KIND_BOOLEAN:
|
|
442
|
+
value = node.fields.get("value")
|
|
443
|
+
if not isinstance(value, bool):
|
|
444
|
+
raise _unsupported(str(kind), "Boolean node missing a bool value")
|
|
445
|
+
return value
|
|
446
|
+
if kind == KIND_NULL:
|
|
447
|
+
return None
|
|
448
|
+
raise _unsupported(str(kind), f"node kind {kind!r} has no JSON representation")
|
|
449
|
+
|
|
450
|
+
def _normalize_leading(leading: str, *, need_comma: bool, siblings_leadings: Optional[Sequence[Optional[str]]] = None) -> str:
|
|
451
|
+
"""Ensure a member's/item's leading trivia carries a separating comma iff
|
|
452
|
+
it is not the container's first child. JSON has exactly one spelling for
|
|
453
|
+
that comma, so only its PRESENCE is enforced. For a MULTI-LINE container
|
|
454
|
+
the whitespace around the comma is a position-independent indent block
|
|
455
|
+
(``",\\n "`` -> ``"\\n "`` is exactly the first member's own real
|
|
456
|
+
leading too), so it is kept byte-for-byte when a comma is dropped. For a
|
|
457
|
+
single-line/compact container the post-comma space is tied to the comma
|
|
458
|
+
itself, not an indent (``"[1, 2, 3]"``, never ``"[ 1, 2, 3]"``), so
|
|
459
|
+
dropping the comma there drops that space too. This is what lets a
|
|
460
|
+
delete of the first member turn its (comma-carrying) successor into a
|
|
461
|
+
correct new first member, and an insert at the front pick up a comma it
|
|
462
|
+
never had, without hand-rebuilding every other member's trivia.
|
|
463
|
+
|
|
464
|
+
When adding a comma to leading that has none (bug 82debc78), detect the
|
|
465
|
+
array/object's spacing convention from siblings and adopt it: ', ' if
|
|
466
|
+
siblings use spaces, ',' if compact.
|
|
467
|
+
"""
|
|
468
|
+
comma_index = leading.find(",")
|
|
469
|
+
has_comma = comma_index != -1
|
|
470
|
+
if need_comma and not has_comma:
|
|
471
|
+
# Need to add a comma. Detect spacing convention from siblings.
|
|
472
|
+
separator = ","
|
|
473
|
+
if siblings_leadings is not None:
|
|
474
|
+
# Look for a sibling with a comma to detect the convention
|
|
475
|
+
for sibling_leading in siblings_leadings:
|
|
476
|
+
if sibling_leading is not None and "," in sibling_leading:
|
|
477
|
+
# Found a sibling with comma. Extract the part after comma.
|
|
478
|
+
sibling_comma_idx = sibling_leading.find(",")
|
|
479
|
+
after_comma = sibling_leading[sibling_comma_idx + 1:]
|
|
480
|
+
# If sibling has space after comma (single-line style), use it
|
|
481
|
+
if after_comma and after_comma[0] == " " and "\n" not in after_comma:
|
|
482
|
+
separator = ", "
|
|
483
|
+
break
|
|
484
|
+
return separator + leading
|
|
485
|
+
if not need_comma and has_comma:
|
|
486
|
+
rest = leading[:comma_index] + leading[comma_index + 1:]
|
|
487
|
+
return rest if "\n" in rest else ""
|
|
488
|
+
return leading
|
|
489
|
+
|
|
490
|
+
def _dominant_leading(
|
|
491
|
+
leadings: Sequence[Optional[str]], index: int, need_comma: bool, default: str
|
|
492
|
+
) -> str:
|
|
493
|
+
"""A sibling's own captured/borrowed 'leading' trivia, reused for a
|
|
494
|
+
member/item that has none of its own (fragment-inserted, never parsed) --
|
|
495
|
+
so an insert lands in the container's existing indentation/newline style
|
|
496
|
+
rather than a hand-picked one.
|
|
497
|
+
|
|
498
|
+
A sibling at position 0 plays a structurally different role than every
|
|
499
|
+
other position (no preceding comma at all -- see ``_normalize_leading``),
|
|
500
|
+
so its trivia is only a valid donor for another position-0 slot: a
|
|
501
|
+
same-role donor (``(probe > 0) == need_comma``) is always preferred
|
|
502
|
+
first, falling back to any donor (``_normalize_leading`` fixes up the
|
|
503
|
+
comma afterward) only when no same-role sibling has trivia of its own.
|
|
504
|
+
``default`` covers a container with no captured trivia anywhere (e.g.
|
|
505
|
+
every child freshly inserted, or a container built via
|
|
506
|
+
``_plain_to_node``), which is what keeps a genuinely bare/compact
|
|
507
|
+
container compact."""
|
|
508
|
+
for want_same_role in (True, False):
|
|
509
|
+
for probe in range(index - 1, -1, -1):
|
|
510
|
+
leading = leadings[probe]
|
|
511
|
+
if leading is not None and (not want_same_role or (probe > 0) == need_comma):
|
|
512
|
+
return leading
|
|
513
|
+
for probe in range(index + 1, len(leadings)):
|
|
514
|
+
leading = leadings[probe]
|
|
515
|
+
if leading is not None and (not want_same_role or (probe > 0) == need_comma):
|
|
516
|
+
return leading
|
|
517
|
+
return default
|
|
518
|
+
|
|
519
|
+
def _empty_container_default_leading(closing_trivia: str) -> str:
|
|
520
|
+
"""Default leading for the FIRST child spliced into a container that had
|
|
521
|
+
ZERO parsed children -- no sibling trivia anywhere for ``_dominant_leading``
|
|
522
|
+
to borrow, the case its own ``default`` argument covers.
|
|
523
|
+
|
|
524
|
+
A genuinely bare/compact container (``"{}"``, ``closing_trivia == ""``)
|
|
525
|
+
stays compact: ``""`` is returned unchanged, matching the pre-existing
|
|
526
|
+
default. But a container whose OWN ``closing_trivia`` already contains a
|
|
527
|
+
newline (``"{\\n}\\n"`` parses to ``closing_trivia == "\\n"`` for its
|
|
528
|
+
zero members) has already declared a multi-line layout with nothing but
|
|
529
|
+
that newline to show for it; leaving the new member's leading at ``""``
|
|
530
|
+
left the container self-contradictory -- an unindented member on the
|
|
531
|
+
opening line, immediately followed by a closing brace that still carries
|
|
532
|
+
its own newline (bug 7162cbd2 site-2's engine-boundary half: no
|
|
533
|
+
fragment-inserted member had ever landed in a previously-EMPTY container
|
|
534
|
+
before that bug's fix routed JSON root-object inserts through this
|
|
535
|
+
primitive). Mirroring the closing brace's own indent, one level deeper
|
|
536
|
+
(this module's own established default -- see ``generate_output``'s
|
|
537
|
+
``json.dumps(..., indent=2, ...)`` fallback for a value built from
|
|
538
|
+
scratch), keeps the member's line consistent with what a populated
|
|
539
|
+
multi-line sibling would already look like, and generalizes correctly to
|
|
540
|
+
a NESTED empty container: ``closing_trivia``'s own trailing whitespace
|
|
541
|
+
already carries that container's OWN indent depth, so appending one more
|
|
542
|
+
unit lands the member exactly one level inside it."""
|
|
543
|
+
if "\n" not in closing_trivia:
|
|
544
|
+
return ""
|
|
545
|
+
indent = closing_trivia.rsplit("\n", 1)[-1]
|
|
546
|
+
return "\n" + indent + " "
|
|
547
|
+
|
|
548
|
+
def _render_member_content(member: Node) -> str:
|
|
549
|
+
"""A ``json:Member``'s own key+sep+value text -- everything about it that is
|
|
550
|
+
NOT positional. Deliberately excludes 'leading' (the whitespace/newline/
|
|
551
|
+
indent/comma slice before the key): that trivia describes the member's
|
|
552
|
+
PLACE among its siblings, not the member itself, and is exactly what
|
|
553
|
+
``parse_fragment``'s standalone ``"key": value`` member-fragment shape
|
|
554
|
+
also excludes (bug 6df2cf33) -- so this is both the object-render's own
|
|
555
|
+
per-member piece AND the byte-faithful, round-trippable fragment text a
|
|
556
|
+
caller (``facade._extract_source_from_nodes``) captures for a deleted/
|
|
557
|
+
replaced member: reparsing this text via ``parse_fragment`` and
|
|
558
|
+
reinserting it reproduces an equivalent member, its 'leading' then
|
|
559
|
+
supplied afresh by position (its own if unchanged, borrowed from a
|
|
560
|
+
sibling if fragment-inserted -- see ``_dominant_leading``)."""
|
|
561
|
+
key = member.fields.get("key", "")
|
|
562
|
+
sep = member.fields.get("sep")
|
|
563
|
+
if not isinstance(sep, str):
|
|
564
|
+
sep = ": "
|
|
565
|
+
value_text = _render_node(member.children[0]) if member.children else "null"
|
|
566
|
+
return f"{json.dumps(key, ensure_ascii=False)}{sep}{value_text}"
|
|
567
|
+
|
|
568
|
+
def _render_object(node: Node) -> str:
|
|
569
|
+
"""``KIND_OBJECT`` no-cache fallback: replay each member's own
|
|
570
|
+
'leading' trivia plus its ``_render_member_content``, instead of
|
|
571
|
+
recomposing compactly -- see the module docstring (bug 5dfa5ae3)."""
|
|
572
|
+
children = node.children
|
|
573
|
+
leadings: List[Optional[str]] = [member.fields.get("leading") for member in children]
|
|
574
|
+
closing = node.fields.get("closing_trivia", "")
|
|
575
|
+
if not isinstance(closing, str):
|
|
576
|
+
closing = ""
|
|
577
|
+
parts = []
|
|
578
|
+
for index, member in enumerate(children):
|
|
579
|
+
leading = leadings[index]
|
|
580
|
+
need_comma = index > 0
|
|
581
|
+
if leading is None:
|
|
582
|
+
default = _empty_container_default_leading(closing) if index == 0 else ", "
|
|
583
|
+
leading = _dominant_leading(leadings, index, need_comma, default)
|
|
584
|
+
leading = _normalize_leading(leading, need_comma=need_comma, siblings_leadings=leadings)
|
|
585
|
+
parts.append(f"{leading}{_render_member_content(member)}")
|
|
586
|
+
return "{" + "".join(parts) + closing + "}"
|
|
587
|
+
|
|
588
|
+
def _render_array(node: Node) -> str:
|
|
589
|
+
"""``KIND_ARRAY`` no-cache fallback: replay each item's own 'leading'
|
|
590
|
+
trivia (stored on the item node itself) plus its rendered value -- see
|
|
591
|
+
``_render_object`` and the module docstring (bug 5dfa5ae3)."""
|
|
592
|
+
children = node.children
|
|
593
|
+
leadings: List[Optional[str]] = [child.fields.get("leading") for child in children]
|
|
594
|
+
closing = node.fields.get("closing_trivia", "")
|
|
595
|
+
if not isinstance(closing, str):
|
|
596
|
+
closing = ""
|
|
597
|
+
parts = []
|
|
598
|
+
for index, child in enumerate(children):
|
|
599
|
+
leading = leadings[index]
|
|
600
|
+
need_comma = index > 0
|
|
601
|
+
if leading is None:
|
|
602
|
+
default = _empty_container_default_leading(closing) if index == 0 else ", "
|
|
603
|
+
leading = _dominant_leading(leadings, index, need_comma, default)
|
|
604
|
+
leading = _normalize_leading(leading, need_comma=need_comma, siblings_leadings=leadings)
|
|
605
|
+
parts.append(f"{leading}{_render_node(child)}")
|
|
606
|
+
return "[" + "".join(parts) + closing + "]"
|
|
607
|
+
|
|
608
|
+
def _render_node(node: Node) -> str:
|
|
609
|
+
"""Common model -> final text, reusing stored raw text where present."""
|
|
610
|
+
raw = node.fields.get("raw") if isinstance(node.fields, Mapping) else None
|
|
611
|
+
if isinstance(raw, str):
|
|
612
|
+
return raw
|
|
613
|
+
kind = node.kind
|
|
614
|
+
if kind == KIND_OBJECT:
|
|
615
|
+
text = _render_object(node)
|
|
616
|
+
elif kind == KIND_ARRAY:
|
|
617
|
+
text = _render_array(node)
|
|
618
|
+
elif kind == KIND_MEMBER:
|
|
619
|
+
# A ``json:Member`` caches no 'raw' of its own even when parsed as
|
|
620
|
+
# part of a document (see the module docstring, bug 5dfa5ae3) -- its
|
|
621
|
+
# OWN rendering is its key+sep+value content, 'leading' excluded
|
|
622
|
+
# (see ``_render_member_content``). Reachable here two ways: a
|
|
623
|
+
# top-level ``generate_output(member_node)`` call (what
|
|
624
|
+
# ``facade._extract_source_from_nodes`` uses to capture a deleted/
|
|
625
|
+
# replaced member's byte-faithful fragment, bug 6df2cf33) or, in
|
|
626
|
+
# principle, a member found via 'raw'-less recursion from a parent
|
|
627
|
+
# that itself has no cache -- ``_render_object`` never reaches this
|
|
628
|
+
# branch itself (it calls ``_render_member_content`` directly).
|
|
629
|
+
text = _render_member_content(node)
|
|
630
|
+
elif kind == KIND_STRING:
|
|
631
|
+
text = json.dumps(node.fields.get("value"), ensure_ascii=False)
|
|
632
|
+
elif kind == KIND_NUMBER:
|
|
633
|
+
text = json.dumps(node.fields.get("value"))
|
|
634
|
+
elif kind == KIND_BOOLEAN:
|
|
635
|
+
text = "true" if node.fields.get("value") else "false"
|
|
636
|
+
elif kind == KIND_NULL:
|
|
637
|
+
text = "null"
|
|
638
|
+
else:
|
|
639
|
+
raise _contract_error(f"cannot render node kind {kind!r} to JSON")
|
|
640
|
+
# Only the document ROOT ever carries these (see import_to_common's
|
|
641
|
+
# widening step); every other node's .get() is a harmless no-op. Applied
|
|
642
|
+
# here, unconditionally, so it survives regardless of which branch above
|
|
643
|
+
# produced 'text' -- including a bare top-level scalar document.
|
|
644
|
+
outer_leading = node.fields.get("outer_leading")
|
|
645
|
+
outer_trailing = node.fields.get("outer_trailing")
|
|
646
|
+
if isinstance(outer_leading, str) or isinstance(outer_trailing, str):
|
|
647
|
+
text = (outer_leading if isinstance(outer_leading, str) else "") + text + (
|
|
648
|
+
outer_trailing if isinstance(outer_trailing, str) else ""
|
|
649
|
+
)
|
|
650
|
+
return text
|
|
651
|
+
|
|
652
|
+
def _pointer_step(parent: Node, child: Node, ordinal: int) -> Optional[Tuple[Tuple[str, ...], bool]]:
|
|
653
|
+
"""This format's structural half of RFC 6901, for ``JsonPointerNotation``.
|
|
654
|
+
|
|
655
|
+
JSON is the format the notation was written for, so the mapping is direct
|
|
656
|
+
but for one asymmetry: a pointer names a VALUE. ``/a`` is the value of
|
|
657
|
+
member ``"a"``, and RFC 6901 has no notation at all for the member as a
|
|
658
|
+
thing distinct from its value. ``json:Member`` therefore contributes its
|
|
659
|
+
key and declares itself unaddressable, and the value beneath it claims the
|
|
660
|
+
pointer the member built -- which is what keeps one pointer naming exactly
|
|
661
|
+
one node.
|
|
662
|
+
"""
|
|
663
|
+
|
|
664
|
+
kind = parent.kind
|
|
665
|
+
if kind == KIND_OBJECT:
|
|
666
|
+
if child.kind != KIND_MEMBER:
|
|
667
|
+
return None
|
|
668
|
+
key = child.fields.get("key")
|
|
669
|
+
return ((key,), False) if isinstance(key, str) else None
|
|
670
|
+
if kind == KIND_MEMBER:
|
|
671
|
+
return ((), True)
|
|
672
|
+
if kind == KIND_ARRAY:
|
|
673
|
+
return ((str(ordinal),), True)
|
|
674
|
+
return None
|
|
675
|
+
|
|
676
|
+
|
|
677
|
+
#: The plugin's reference-notation declaration, read duck-typed by
|
|
678
|
+
#: ``tree_engine.core.identifier_map`` -- the same declaration pattern
|
|
679
|
+
#: ``fragment_container_kinds`` already established. A JSON document's root
|
|
680
|
+
#: value IS the document, so it is what the empty pointer names.
|
|
681
|
+
JSON_POINTER = JsonPointerNotation(_pointer_step, root_addressable=True)
|
|
682
|
+
|
|
683
|
+
|
|
684
|
+
class JsonFormatPlugin(FormatPluginContract, FormatBoundary):
|
|
685
|
+
"""The registered ``format_id="json"`` plugin (concept C-016)."""
|
|
686
|
+
|
|
687
|
+
#: This format's native reference notation ({p021} third correspondence):
|
|
688
|
+
#: JSON Pointer, computed and parsed here rather than by shared code.
|
|
689
|
+
native_reference = JSON_POINTER
|
|
690
|
+
|
|
691
|
+
@property
|
|
692
|
+
def metadata(self) -> FormatPluginMetadata:
|
|
693
|
+
return _METADATA
|
|
694
|
+
|
|
695
|
+
def parse_document(self, source: Union[str, bytes], options: Optional[Mapping[str, Any]] = None, *, source_format_id: Optional[str] = None) -> Document:
|
|
696
|
+
"""Parse JSON source into a ``Document``. Raises ``FormatContentParseFailed``
|
|
697
|
+
on malformed JSON; ``FormatPluginContractError`` if ``source`` is not ``str``/``bytes``."""
|
|
698
|
+
if not isinstance(source, (str, bytes)):
|
|
699
|
+
raise _contract_error(f"parse_document expects str or bytes, got {type(source).__name__}")
|
|
700
|
+
text = source.decode("utf-8") if isinstance(source, bytes) else source
|
|
701
|
+
try:
|
|
702
|
+
value, leading, trailing = _parse_json_text(text)
|
|
703
|
+
except _JsonParseError as exc:
|
|
704
|
+
offset = offset_in_message(str(exc))
|
|
705
|
+
raise FormatContentParseFailed(
|
|
706
|
+
f"cannot parse JSON document: {exc}", plugin_id=FORMAT_ID,
|
|
707
|
+
**position_details(text, len(text) if offset is None else offset, str(exc))) from exc
|
|
708
|
+
result = self.import_to_common(
|
|
709
|
+
_DocumentSource(value=value, full_text=text, leading=leading, trailing=trailing), options
|
|
710
|
+
)
|
|
711
|
+
if not isinstance(result, Document):
|
|
712
|
+
raise _contract_error(f"parsing a document must yield a Document, got {type(result).__name__}")
|
|
713
|
+
return result
|
|
714
|
+
|
|
715
|
+
def import_external_tree(self, external_tree: Any, options: Optional[Mapping[str, Any]] = None) -> Union[Node, Document]:
|
|
716
|
+
return self.import_to_common(external_tree, options)
|
|
717
|
+
|
|
718
|
+
def parse_fragment(self, fragment: Union[str, bytes], options: Optional[Mapping[str, Any]] = None, *, source_format_id: Optional[str] = None) -> Union[Node, str]:
|
|
719
|
+
"""Parse a JSON value fragment, OR a standalone ``"key": value`` member
|
|
720
|
+
fragment (no ``insert``/``replace`` caller can otherwise add one new
|
|
721
|
+
member to an existing object -- bug 5dfa5ae3); returns the fragment's
|
|
722
|
+
own text (never raising) when neither shape matches. Raises
|
|
723
|
+
``FormatPluginContractError`` on a non-``str``/``bytes`` input."""
|
|
724
|
+
if not isinstance(fragment, (str, bytes)):
|
|
725
|
+
raise _contract_error(f"parse_fragment expects str or bytes, got {type(fragment).__name__}")
|
|
726
|
+
text = fragment.decode("utf-8") if isinstance(fragment, bytes) else fragment
|
|
727
|
+
try:
|
|
728
|
+
# A fragment's own outer whitespace, unlike a document's, is not
|
|
729
|
+
# preserved -- it is spliced into a larger tree at a specific
|
|
730
|
+
# position, never rendered standalone (same as before this fix).
|
|
731
|
+
value, _leading, _trailing = _parse_json_text(text)
|
|
732
|
+
except _JsonParseError:
|
|
733
|
+
try:
|
|
734
|
+
key, sep, value_raw = _parse_member_fragment(text)
|
|
735
|
+
except _JsonParseError:
|
|
736
|
+
return text
|
|
737
|
+
# No 'leading' field: this member was never parsed as part of a
|
|
738
|
+
# container, so it has no original indentation of its own -- the
|
|
739
|
+
# no-cache object fallback (_render_object) borrows a sibling's
|
|
740
|
+
# 'leading' for it instead (see the module docstring).
|
|
741
|
+
return _identified_node(
|
|
742
|
+
KIND_MEMBER, fields={"key": key, "sep": sep},
|
|
743
|
+
children=(_raw_to_node(value_raw),),
|
|
744
|
+
)
|
|
745
|
+
result = self.import_to_common(value, options)
|
|
746
|
+
if not isinstance(result, Node):
|
|
747
|
+
raise _contract_error(f"parsing a fragment must yield a Node, got {type(result).__name__}")
|
|
748
|
+
return result
|
|
749
|
+
|
|
750
|
+
def import_to_common(self, external_representation: Any, options: Optional[Mapping[str, Any]] = None) -> Union[Node, Document]:
|
|
751
|
+
"""Shared input translator: accepts this module's private parser
|
|
752
|
+
shapes, or an already-decoded plain Python JSON value."""
|
|
753
|
+
if isinstance(external_representation, _DocumentSource):
|
|
754
|
+
full_text = external_representation.full_text
|
|
755
|
+
root = _raw_to_node(external_representation.value, char_to_byte_offset(full_text))
|
|
756
|
+
widened = dict(root.fields)
|
|
757
|
+
widened["raw"] = external_representation.full_text
|
|
758
|
+
# 'outer_leading'/'outer_trailing' -- not 'raw' -- are the root's
|
|
759
|
+
# own identity data (the whitespace around the top-level value
|
|
760
|
+
# that 'raw' widening above folds in): the no-cache fallback
|
|
761
|
+
# needs them separately since a pointwise mutation anywhere in
|
|
762
|
+
# the document invalidates this widened 'raw' cache (bug
|
|
763
|
+
# 5dfa5ae3), same reasoning as 'leading'/'sep'/'closing_trivia'.
|
|
764
|
+
widened["outer_leading"] = external_representation.leading
|
|
765
|
+
widened["outer_trailing"] = external_representation.trailing
|
|
766
|
+
# Same document root, just a widened raw span: keep its identity.
|
|
767
|
+
root = replace(make_node(root.kind, fields=widened, children=root.children),
|
|
768
|
+
node_id=root.node_id, short_id=root.short_id,
|
|
769
|
+
buffer_range=(0, len(full_text.encode("utf-8"))))
|
|
770
|
+
return Document(root=root, source_format_id=FORMAT_ID)
|
|
771
|
+
if isinstance(external_representation, _RawValue):
|
|
772
|
+
return _raw_to_node(external_representation)
|
|
773
|
+
return _plain_to_node(external_representation, frozenset())
|
|
774
|
+
|
|
775
|
+
def export_from_common(self, nodes: Union[Node, Document], options: Optional[Mapping[str, Any]] = None) -> Any:
|
|
776
|
+
"""Common-model nodes -> JSON-compatible dict/list/scalar; raises
|
|
777
|
+
``UnsupportedTranslationError`` for an unmappable construct."""
|
|
778
|
+
root = nodes.root if isinstance(nodes, Document) else nodes
|
|
779
|
+
if not isinstance(root, Node):
|
|
780
|
+
raise _contract_error(f"expected a Node or Document, got {type(nodes).__name__}")
|
|
781
|
+
return _node_to_plain(root, frozenset())
|
|
782
|
+
|
|
783
|
+
def generate_output(self, target: Union[Node, Document, Any], options: Optional[Mapping[str, Any]] = None) -> Union[str, bytes]:
|
|
784
|
+
"""A common-model ``target`` reuses stored raw text verbatim
|
|
785
|
+
(byte-identical); an already-exported value serializes canonically."""
|
|
786
|
+
options = options or {}
|
|
787
|
+
if isinstance(target, (Node, Document)):
|
|
788
|
+
root = target.root if isinstance(target, Document) else target
|
|
789
|
+
text = _render_node(root)
|
|
790
|
+
elif isinstance(target, (dict, list, str, int, float, bool)) or target is None:
|
|
791
|
+
text = json.dumps(target, indent=2, ensure_ascii=False)
|
|
792
|
+
else:
|
|
793
|
+
raise _contract_error(f"cannot generate output for {type(target).__name__}")
|
|
794
|
+
return text.encode("utf-8") if options.get("as_bytes") else text
|
|
795
|
+
|
|
796
|
+
def semantic_role_mapping(self) -> SemanticRoleMapping:
|
|
797
|
+
"""JSON models none of function/method/class/module; empty ({p056})."""
|
|
798
|
+
return _ROLE_MAP
|
|
799
|
+
|
|
800
|
+
def render_document(self, document: Document) -> bytes:
|
|
801
|
+
result = self.generate_output(document, {"as_bytes": True})
|
|
802
|
+
if not isinstance(result, bytes):
|
|
803
|
+
raise _contract_error(f"render_document expected bytes, got {type(result).__name__}")
|
|
804
|
+
return result
|
|
805
|
+
|
|
806
|
+
def render_fragment(self, node: Node) -> str:
|
|
807
|
+
result = self.generate_output(node, {})
|
|
808
|
+
if not isinstance(result, str):
|
|
809
|
+
raise _contract_error(f"render_fragment expected str, got {type(result).__name__}")
|
|
810
|
+
return result
|
|
811
|
+
|
|
812
|
+
# Ready-made singleton a sibling registry step can import and register.
|
|
813
|
+
JSON_FORMAT_PLUGIN = JsonFormatPlugin()
|