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,156 @@
|
|
|
1
|
+
"""The format plugins that ship with the engine but whose parser is an optional extra.
|
|
2
|
+
|
|
3
|
+
Author: Vasiliy Zdanovskiy
|
|
4
|
+
email: vasilyvz@gmail.com
|
|
5
|
+
|
|
6
|
+
Scope: the declaration, and the one import attempt that acts on it. Nothing else in the package
|
|
7
|
+
may decide what is optional.
|
|
8
|
+
|
|
9
|
+
**Why any format is detachable at all.** The engine's data formats -- ``plain_text``, ``json``,
|
|
10
|
+
``toml``, ``yaml`` -- either need nothing outside the standard library or need one small, stable
|
|
11
|
+
library. The LANGUAGE formats do not: ``python`` wraps LibCST and ``bsl`` wraps tree-sitter plus a
|
|
12
|
+
separately-released 1C grammar. Those track external toolchains on their own schedule, and that
|
|
13
|
+
schedule has already forced this project's hand once -- ``tree-sitter>=0.25,<0.26`` exists because
|
|
14
|
+
``tree-sitter-bsl`` 0.1.6 reports grammar ABI 15, which the 0.24 line cannot load. Keeping the two
|
|
15
|
+
language plugins detachable means that churn cannot stop a consumer who only ever opens a JSON
|
|
16
|
+
file from importing the engine at all. Before this module, ``facade.py`` imported both eagerly, so
|
|
17
|
+
``import tree_engine.facade`` failed without LibCST AND without tree-sitter: the extras that
|
|
18
|
+
declare them optional were a fiction.
|
|
19
|
+
|
|
20
|
+
**What detachable does NOT mean.** It does not mean degrading. When a detached plugin's format is
|
|
21
|
+
actually requested and its library is absent, the engine refuses with a declared, typed error that
|
|
22
|
+
names the extra to install ({p023}) -- never an ``ImportError`` traceback escaping the facade, and
|
|
23
|
+
never a quiet reinterpretation of a 1C module or a Python file as plain text. A wrong answer that
|
|
24
|
+
looks like an answer is worse than a refusal.
|
|
25
|
+
|
|
26
|
+
This module imports nothing heavy itself: it holds strings and calls :func:`importlib.import_module`
|
|
27
|
+
only when asked. The plugin modules read their own extensions back out of it, so the table the
|
|
28
|
+
facade builds for a DETACHED plugin and the metadata that plugin declares when it is present can
|
|
29
|
+
never drift apart.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
import importlib
|
|
35
|
+
import importlib.util
|
|
36
|
+
from dataclasses import dataclass
|
|
37
|
+
from typing import Any, Optional, Tuple
|
|
38
|
+
|
|
39
|
+
__all__ = ["BSL_PLUGIN_SPEC", "DETACHABLE_PLUGIN_SPECS", "PYTHON_PLUGIN_SPEC",
|
|
40
|
+
"DetachablePluginSpec", "load_detachable_plugin"]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class DetachablePluginSpec:
|
|
45
|
+
"""One shipped format whose parser library is an optional install.
|
|
46
|
+
|
|
47
|
+
``module``/``attribute`` locate the ready-made plugin singleton without importing it;
|
|
48
|
+
``requirements`` are the import names that may be missing -- every library the format needs at
|
|
49
|
+
RUN time, not only the ones its module imports at load time -- and ``extra`` is the name a
|
|
50
|
+
consumer installs to get them, so the refusal can say exactly what to do. ``file_extensions`` is the same
|
|
51
|
+
tuple the plugin's own metadata declares -- the plugin reads it from here -- so the facade can
|
|
52
|
+
still map a path to this format, and refuse by name, while the plugin itself is unimportable.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
format_id: str
|
|
56
|
+
module: str
|
|
57
|
+
attribute: str
|
|
58
|
+
requirements: Tuple[str, ...]
|
|
59
|
+
extra: str
|
|
60
|
+
file_extensions: Tuple[str, ...]
|
|
61
|
+
|
|
62
|
+
def unavailable_message(self, missing: str, detail: str) -> str:
|
|
63
|
+
"""The refusal a caller sees when this format is requested and its library is absent.
|
|
64
|
+
|
|
65
|
+
The ``pip install`` line spells ``extra`` VERBATIM. It used to strip the
|
|
66
|
+
``tree-engine-`` prefix, which produced ``ai-editor-tree-engine[python]`` -- an extra the
|
|
67
|
+
distribution does not declare, so pip answers ``WARNING: ai-editor-tree-engine 1.0.97 does
|
|
68
|
+
not provide the extra 'python'`` and installs nothing. A refusal whose remedy is a no-op is
|
|
69
|
+
worse than no remedy: the caller runs it, sees no error, retries, and is refused again.
|
|
70
|
+
"""
|
|
71
|
+
return (f"format {self.format_id!r} is available only with the {self.extra!r} extra: "
|
|
72
|
+
f"{missing} could not be imported ({detail}). Install it with "
|
|
73
|
+
f"pip install 'ai-editor-tree-engine[{self.extra}]' "
|
|
74
|
+
f"-- the engine does not reinterpret a {self.format_id} file as another format.")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
#: LibCST. Python's tree, identity and byte-identical round trip all come from it, and
|
|
78
|
+
#: ``plugins/python/plugin.py`` imports it at module level, so its absence is visible immediately.
|
|
79
|
+
PYTHON_PLUGIN_SPEC = DetachablePluginSpec(
|
|
80
|
+
format_id="python", module="tree_engine.plugins.python.plugin",
|
|
81
|
+
attribute="PYTHON_FORMAT_PLUGIN", requirements=("libcst",), extra="tree-engine-python",
|
|
82
|
+
file_extensions=("py", "pyi"))
|
|
83
|
+
|
|
84
|
+
#: tree-sitter plus the separately released 1C grammar; see this module's docstring for the ABI
|
|
85
|
+
#: constraint that makes detachability load-bearing rather than tidy. Both are named explicitly
|
|
86
|
+
#: because ``plugins/bsl`` defers its ``tree_sitter`` import until the first parse, so the plugin
|
|
87
|
+
#: module imports perfectly well on a machine that cannot parse a single line of BSL: without this
|
|
88
|
+
#: declaration the format would register, then fail at parse time with a classified content error,
|
|
89
|
+
#: and the authorized plain-text fallback would hand back a 1C module reinterpreted as text.
|
|
90
|
+
BSL_PLUGIN_SPEC = DetachablePluginSpec(
|
|
91
|
+
format_id="bsl", module="tree_engine.plugins.bsl.plugin",
|
|
92
|
+
attribute="BSL_FORMAT_PLUGIN", requirements=("tree_sitter", "ai_editor_tree_sitter_bsl"),
|
|
93
|
+
extra="tree-engine-bsl", file_extensions=("bsl",))
|
|
94
|
+
|
|
95
|
+
#: tree-sitter-c / tree-sitter-cpp / tree-sitter-cuda (wish 2a977287 stage i, navigable-only MVP).
|
|
96
|
+
#: One plugin module (``tree_engine.plugins.cpp.plugin``) serves all three format ids, each its own
|
|
97
|
+
#: registered singleton attribute; all three share the one aggregate ``tree-engine-cpp`` extra
|
|
98
|
+
#: (installing it pulls in all three grammars at once, per this MVP's design), but each spec still
|
|
99
|
+
#: names only the ONE grammar module its own format id actually needs at parse time, so a machine
|
|
100
|
+
#: missing just one of the three still gets an accurate per-format refusal naming that grammar,
|
|
101
|
+
#: never a blanket "cpp extra missing" that hides which specific import failed.
|
|
102
|
+
C_PLUGIN_SPEC = DetachablePluginSpec(
|
|
103
|
+
format_id="c", module="tree_engine.plugins.cpp.plugin",
|
|
104
|
+
attribute="C_FORMAT_PLUGIN", requirements=("tree_sitter", "tree_sitter_c"),
|
|
105
|
+
extra="tree-engine-cpp", file_extensions=("c", "h"))
|
|
106
|
+
|
|
107
|
+
CPP_PLUGIN_SPEC = DetachablePluginSpec(
|
|
108
|
+
format_id="cpp", module="tree_engine.plugins.cpp.plugin",
|
|
109
|
+
attribute="CPP_FORMAT_PLUGIN", requirements=("tree_sitter", "tree_sitter_cpp"),
|
|
110
|
+
extra="tree-engine-cpp", file_extensions=("cc", "cpp", "cxx", "hpp", "hh"))
|
|
111
|
+
|
|
112
|
+
#: CUDA MUST use tree-sitter-cuda, never tree-sitter-cpp: the plain C++ grammar tokenizes a kernel
|
|
113
|
+
#: launch's ``<<<...>>>`` as nested shift operators, not as the dedicated ``kernel_call_syntax``
|
|
114
|
+
#: node this plugin's ``cuda:KernelLaunch`` kind depends on -- see
|
|
115
|
+
#: ``tree_engine.plugins.cpp.languages`` for the measured detail.
|
|
116
|
+
CUDA_PLUGIN_SPEC = DetachablePluginSpec(
|
|
117
|
+
format_id="cuda", module="tree_engine.plugins.cpp.plugin",
|
|
118
|
+
attribute="CUDA_FORMAT_PLUGIN", requirements=("tree_sitter", "tree_sitter_cuda"),
|
|
119
|
+
extra="tree-engine-cpp", file_extensions=("cu", "cuh"))
|
|
120
|
+
|
|
121
|
+
#: In the order the facade registers them, which is the order ``list_formats()`` reports.
|
|
122
|
+
#: C/C++/CUDA specs are intentionally NOT registered: the editor serves those files as the
|
|
123
|
+
#: text-backed ``text-cpp`` format group (bug 3aa93da8 ruling); see
|
|
124
|
+
#: ``ai_editor/commands/universal_file_edit/session.py`` which maps FORMAT_TEXT_CPP to
|
|
125
|
+
#: engine_format_id "plain_text". The plugin module ``tree_engine.plugins.cpp`` remains intact,
|
|
126
|
+
#: but its singleton attributes are never auto-registered with the facade.
|
|
127
|
+
DETACHABLE_PLUGIN_SPECS: Tuple[DetachablePluginSpec, ...] = (
|
|
128
|
+
PYTHON_PLUGIN_SPEC, BSL_PLUGIN_SPEC,
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def load_detachable_plugin(spec: DetachablePluginSpec) -> Tuple[Optional[Any], Optional[str]]:
|
|
133
|
+
"""Import ``spec``'s plugin singleton, or say why it is unavailable.
|
|
134
|
+
|
|
135
|
+
Returns ``(plugin, None)`` when everything the format needs is present, and ``(None, message)``
|
|
136
|
+
when it is not. Each declared requirement is looked for FIRST, with ``find_spec``, which
|
|
137
|
+
locates a module without executing it: a plugin that defers its own parser import until the
|
|
138
|
+
first parse would otherwise import cleanly and be registered as available, and its absence
|
|
139
|
+
would then surface as a parse failure -- which is the one classification allowed to open the
|
|
140
|
+
plain-text fallback. Only an :class:`ImportError` is treated as "not installed"; every other
|
|
141
|
+
failure is a real defect in a plugin that IS installed and propagates unchanged, because
|
|
142
|
+
swallowing it would turn a broken plugin into a missing one and send the consumer to install
|
|
143
|
+
something they already have.
|
|
144
|
+
"""
|
|
145
|
+
for requirement in spec.requirements:
|
|
146
|
+
try:
|
|
147
|
+
found = importlib.util.find_spec(requirement)
|
|
148
|
+
except ImportError as exc:
|
|
149
|
+
return None, spec.unavailable_message(requirement, str(exc))
|
|
150
|
+
if found is None:
|
|
151
|
+
return None, spec.unavailable_message(requirement, f"No module named {requirement!r}")
|
|
152
|
+
try:
|
|
153
|
+
module = importlib.import_module(spec.module)
|
|
154
|
+
except ImportError as exc:
|
|
155
|
+
return None, spec.unavailable_message(spec.module, str(exc))
|
|
156
|
+
return getattr(module, spec.attribute), None
|
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
"""Controlled plain-text fallback: tree builder and metadata schema (concept C-013).
|
|
2
|
+
|
|
3
|
+
Scope: this module owns exactly the degraded-representation construction
|
|
4
|
+
path described by {p058}, {p060}, {p063}, {p096}, and {7a9b} -- nothing
|
|
5
|
+
else. It is entered only after a *resolved, known-or-explicit-format*
|
|
6
|
+
plugin's ``parse_document`` has failed with the classified
|
|
7
|
+
``ErrorCode.FORMAT_CONTENT_PARSE_FAILED`` ({p058}, {p063}); every other
|
|
8
|
+
failure -- ``FORMAT_UNKNOWN_EXTENSION``, ``FORMAT_EXTENSION_CONFLICT``,
|
|
9
|
+
``FORMAT_PLUGIN_NOT_FOUND``, ``UNSUPPORTED_TRANSLATION``,
|
|
10
|
+
``FORMAT_PLUGIN_CONTRACT_ERROR``, or any other exception -- must reach the
|
|
11
|
+
caller unmasked, never silently opening a fallback tree in its place.
|
|
12
|
+
|
|
13
|
+
Module boundary: this file never invokes ``parse_document`` (or any other
|
|
14
|
+
plugin method) -- it only *consumes* a diagnostic a caller already caught --
|
|
15
|
+
never touches a storage layer, and performs no file I/O, checksum, or
|
|
16
|
+
atomic write (storage owns the tree-file write contract per C-012). It
|
|
17
|
+
imports exactly one thing from the plain_text plugin, the public
|
|
18
|
+
:data:`~tree_engine.plugins.plain_text.VERBATIM_TEXT_FIELD` field name, so
|
|
19
|
+
the slice recorded on each paragraph is the one that renderer reads.
|
|
20
|
+
|
|
21
|
+
Byte fidelity ({p060}): a file its owning plugin cannot parse must still be
|
|
22
|
+
openable and savable without corruption, so rendering the fallback document
|
|
23
|
+
back out through the plain_text plugin reproduces the input bytes exactly,
|
|
24
|
+
for ANY input: CRLF, a BOM, a missing trailing newline, runs of blank
|
|
25
|
+
lines, and bytes that are not valid UTF-8 at all. Two mechanisms: ``bytes``
|
|
26
|
+
are decoded with ``errors="surrogateescape"`` (round-trip exact, unlike
|
|
27
|
+
``errors="replace"``), and every paragraph node records the verbatim source
|
|
28
|
+
slice it covers -- blank separators included -- next to its ``text``.
|
|
29
|
+
|
|
30
|
+
Lifecycle note ({7a9b}): building a fallback tree never returns a document
|
|
31
|
+
to its source format. This module defines no reparse/rebuild operation, so
|
|
32
|
+
the only way back to ``source_format_id`` is a caller explicitly invoking
|
|
33
|
+
the source plugin's ``parse_document`` again elsewhere.
|
|
34
|
+
|
|
35
|
+
Source-of-truth labels honored here: {p013}, {p023}, {p058}, {p060},
|
|
36
|
+
{p063}, {p088}, {p096}, {p097}, {7a9b}.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
from __future__ import annotations
|
|
40
|
+
|
|
41
|
+
import itertools
|
|
42
|
+
import re
|
|
43
|
+
from dataclasses import dataclass
|
|
44
|
+
from types import MappingProxyType
|
|
45
|
+
from typing import Any, Iterator, List, Mapping, NamedTuple, Tuple, Union
|
|
46
|
+
from uuid import UUID
|
|
47
|
+
|
|
48
|
+
from tree_engine.core.identity import generate_node_id
|
|
49
|
+
from tree_engine.core.nodes import Document, Node, NodeKind, make_node
|
|
50
|
+
from tree_engine.errors import ErrorCode
|
|
51
|
+
from tree_engine.plugins.plain_text import (
|
|
52
|
+
VERBATIM_TEXT_FIELD,
|
|
53
|
+
split_text_paragraphs,
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
__all__ = [
|
|
57
|
+
"PLAIN_TEXT_FORMAT_ID",
|
|
58
|
+
"FallbackMetadata",
|
|
59
|
+
"FallbackTree",
|
|
60
|
+
"build_fallback_tree",
|
|
61
|
+
]
|
|
62
|
+
|
|
63
|
+
#: The fixed ``representation_format_id`` a fallback document always carries
|
|
64
|
+
#: ({p060}, {7a9b}). Never anything else -- there is no configurable
|
|
65
|
+
#: alternative degraded representation.
|
|
66
|
+
PLAIN_TEXT_FORMAT_ID = "plain_text"
|
|
67
|
+
|
|
68
|
+
_ROOT_KIND = NodeKind("plain_text:root")
|
|
69
|
+
_PARAGRAPH_KIND = NodeKind("plain_text:paragraph")
|
|
70
|
+
|
|
71
|
+
#: Line terminators recognized when splitting paragraphs: exactly the three
|
|
72
|
+
#: real ones, never the extras ``str.splitlines`` also breaks on (``\x0b``,
|
|
73
|
+
#: ``\x0c``, ``\x1c``, ``\u2028``, ...), which would re-cut lines inside
|
|
74
|
+
#: content that legitimately contains them.
|
|
75
|
+
_LINE_BREAK = re.compile(r"\r\n|\r|\n")
|
|
76
|
+
|
|
77
|
+
#: Compact per-node ``short_id`` source ({p097}), shared by every node this
|
|
78
|
+
#: module builds, mirroring the plain_text plugin.
|
|
79
|
+
_short_id_counter = itertools.count(1)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class _Paragraph(NamedTuple):
|
|
83
|
+
"""One blank-line-delimited paragraph plus the bytes it stands for.
|
|
84
|
+
|
|
85
|
+
``text`` is the human-facing content: lines joined with ``\\n``, blank
|
|
86
|
+
separators dropped, undecodable bytes shown as ``U+FFFD``.
|
|
87
|
+
``source_text`` is the verbatim slice covered -- own lines with original
|
|
88
|
+
terminators, plus every blank line up to the next paragraph (and, for
|
|
89
|
+
the first, every blank line before it) -- so concatenating them all in
|
|
90
|
+
order reconstructs the payload exactly. ``line_start`` is the 1-based
|
|
91
|
+
line number of the first content line.
|
|
92
|
+
"""
|
|
93
|
+
|
|
94
|
+
text: str
|
|
95
|
+
line_start: int
|
|
96
|
+
source_text: str
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@dataclass(frozen=True)
|
|
100
|
+
class FallbackMetadata:
|
|
101
|
+
"""Fallback-document metadata schema ({p060}, {7a9b}).
|
|
102
|
+
|
|
103
|
+
``source_format_id`` is the originally selected/known format, preserved
|
|
104
|
+
unchanged. ``representation_format_id`` is always
|
|
105
|
+
:data:`PLAIN_TEXT_FORMAT_ID` -- fixed, not caller-supplied, so no caller
|
|
106
|
+
can claim some other degraded representation. ``fallback_reason``
|
|
107
|
+
explains why the fallback was built. ``diagnostic`` carries the
|
|
108
|
+
structured ``FORMAT_CONTENT_PARSE_FAILED`` details (at minimum
|
|
109
|
+
``error_code`` and ``message``; ``plugin_id`` when the originating
|
|
110
|
+
diagnostic exposed one), exactly as raised -- never summarized away.
|
|
111
|
+
"""
|
|
112
|
+
|
|
113
|
+
source_format_id: str
|
|
114
|
+
fallback_reason: str
|
|
115
|
+
diagnostic: Mapping[str, Any]
|
|
116
|
+
representation_format_id: str = PLAIN_TEXT_FORMAT_ID
|
|
117
|
+
|
|
118
|
+
def __post_init__(self) -> None:
|
|
119
|
+
if not isinstance(self.source_format_id, str) or not self.source_format_id:
|
|
120
|
+
raise ValueError(
|
|
121
|
+
f"FallbackMetadata.source_format_id must be a non-empty string, "
|
|
122
|
+
f"got {self.source_format_id!r}"
|
|
123
|
+
)
|
|
124
|
+
if self.representation_format_id != PLAIN_TEXT_FORMAT_ID:
|
|
125
|
+
raise ValueError(
|
|
126
|
+
"FallbackMetadata.representation_format_id must be "
|
|
127
|
+
f"{PLAIN_TEXT_FORMAT_ID!r}, got {self.representation_format_id!r}"
|
|
128
|
+
)
|
|
129
|
+
object.__setattr__(self, "diagnostic", MappingProxyType(dict(self.diagnostic)))
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
@dataclass(frozen=True)
|
|
133
|
+
class FallbackTree:
|
|
134
|
+
"""The structured plain-text fallback tree ({p096}) plus its metadata.
|
|
135
|
+
|
|
136
|
+
``document`` is the common-model ``Document`` -- root plus format
|
|
137
|
+
contract -- with ``representation_format_id`` set to ``plain_text`` and
|
|
138
|
+
``source_format_id`` left exactly as given ({7a9b}). ``paragraphs`` is
|
|
139
|
+
the explicitly ordered dictionary required by {p096}: keyed by each
|
|
140
|
+
paragraph's canonical UUID4 ``node_id``, its values are the same
|
|
141
|
+
paragraph ``Node`` objects also reachable as ``document.root.children``.
|
|
142
|
+
``order`` restates that key sequence as an explicit tuple, so paragraph
|
|
143
|
+
order is directly inspectable rather than inferred from dict iteration.
|
|
144
|
+
``metadata`` is the attached :class:`FallbackMetadata`.
|
|
145
|
+
"""
|
|
146
|
+
|
|
147
|
+
document: Document
|
|
148
|
+
paragraphs: Mapping[UUID, Node]
|
|
149
|
+
order: Tuple[UUID, ...]
|
|
150
|
+
metadata: FallbackMetadata
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def build_fallback_tree(
|
|
154
|
+
source_payload: Union[str, bytes],
|
|
155
|
+
diagnostic: BaseException,
|
|
156
|
+
*,
|
|
157
|
+
source_format_id: str,
|
|
158
|
+
) -> FallbackTree:
|
|
159
|
+
"""Build the structured plain-text fallback tree for a parse failure.
|
|
160
|
+
|
|
161
|
+
Gate ({p058}, {p063}): the fallback opens *only* for a diagnostic that
|
|
162
|
+
classifies as ``FORMAT_CONTENT_PARSE_FAILED``. Two exception conventions
|
|
163
|
+
coexist in this codebase and BOTH are honored, in this order: the
|
|
164
|
+
canonical typed hierarchy of :mod:`tree_engine.exceptions`, exposing the
|
|
165
|
+
code as ``code`` and marking its single fallback-permitting class with
|
|
166
|
+
``plain_text_fallback_permitted``; and the older exceptions of
|
|
167
|
+
:mod:`tree_engine.plugins.contract`, exposing it as ``error_code``. Both
|
|
168
|
+
are read with a plain ``getattr``, so no particular exception class is
|
|
169
|
+
required. For every other diagnostic -- a different code, or none at all
|
|
170
|
+
-- ``diagnostic`` is re-raised unchanged and no tree is built; that is
|
|
171
|
+
what keeps unknown-extension, extension-conflict, missing-plugin,
|
|
172
|
+
incompatible-plugin, translator, and plugin-contract errors from ever
|
|
173
|
+
being masked by a fallback.
|
|
174
|
+
|
|
175
|
+
Construction ({p096}): ``source_payload`` (``str``, or raw ``bytes``
|
|
176
|
+
decoded as UTF-8 with ``errors="surrogateescape"``) is split into
|
|
177
|
+
paragraphs at blank-line boundaries. Each becomes a
|
|
178
|
+
``plain_text:paragraph`` ``Node`` whose ``fields`` carry ``text`` (the
|
|
179
|
+
human-facing content), ``index`` (zero-based position), ``line_start``
|
|
180
|
+
(1-based starting line), and ``source_text`` (the verbatim payload slice
|
|
181
|
+
it covers); a ``plain_text:root`` ``Node`` holds them as its ordered
|
|
182
|
+
``children``. Every node gets a fresh UUID4 ``node_id`` and a positive
|
|
183
|
+
``short_id`` ({p013}, {p097}), and the returned ``document``'s format
|
|
184
|
+
ids are exactly as documented on :class:`FallbackTree`. Because the
|
|
185
|
+
``source_text`` slices tile the payload exactly, rendering that document
|
|
186
|
+
through the plain_text plugin reproduces the original bytes.
|
|
187
|
+
"""
|
|
188
|
+
|
|
189
|
+
error_code, details = _extract_diagnostic(diagnostic)
|
|
190
|
+
if not _fallback_permitted(diagnostic, error_code):
|
|
191
|
+
raise diagnostic
|
|
192
|
+
|
|
193
|
+
text = _decode_payload(source_payload)
|
|
194
|
+
|
|
195
|
+
paragraphs: "dict[UUID, Node]" = {}
|
|
196
|
+
order: List[UUID] = []
|
|
197
|
+
for index, paragraph in enumerate(_split_paragraphs(text)):
|
|
198
|
+
node_id, node = _build_paragraph_node(paragraph, index)
|
|
199
|
+
paragraphs[node_id] = node
|
|
200
|
+
order.append(node_id)
|
|
201
|
+
|
|
202
|
+
root = _build_root_node(tuple(paragraphs[node_id] for node_id in order))
|
|
203
|
+
document = Document(
|
|
204
|
+
root=root,
|
|
205
|
+
source_format_id=source_format_id,
|
|
206
|
+
representation_format_id=PLAIN_TEXT_FORMAT_ID,
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
metadata = FallbackMetadata(
|
|
210
|
+
source_format_id=source_format_id,
|
|
211
|
+
fallback_reason=details.get("message", "") or ErrorCode.FORMAT_CONTENT_PARSE_FAILED.value,
|
|
212
|
+
diagnostic=details,
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
return FallbackTree(
|
|
216
|
+
document=document,
|
|
217
|
+
paragraphs=MappingProxyType(paragraphs),
|
|
218
|
+
order=tuple(order),
|
|
219
|
+
metadata=metadata,
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _extract_diagnostic(diagnostic: BaseException) -> Tuple[Any, Mapping[str, Any]]:
|
|
224
|
+
"""Read the classified error code and a plain details mapping off ``diagnostic``.
|
|
225
|
+
|
|
226
|
+
Never raises on a malformed or foreign diagnostic shape: an absent code
|
|
227
|
+
reads as ``None``, which never equals
|
|
228
|
+
:attr:`ErrorCode.FORMAT_CONTENT_PARSE_FAILED`, so an unrelated exception
|
|
229
|
+
propagates instead of opening a fallback. ``plugin_id`` comes from the
|
|
230
|
+
older exceptions' attribute or the typed hierarchy's ``details``.
|
|
231
|
+
"""
|
|
232
|
+
|
|
233
|
+
error_code = _classified_error_code(diagnostic)
|
|
234
|
+
details: dict = {
|
|
235
|
+
"error_code": getattr(error_code, "value", error_code),
|
|
236
|
+
"message": str(diagnostic),
|
|
237
|
+
}
|
|
238
|
+
plugin_id = getattr(diagnostic, "plugin_id", None)
|
|
239
|
+
if plugin_id is None:
|
|
240
|
+
carried = getattr(diagnostic, "details", None)
|
|
241
|
+
if isinstance(carried, Mapping):
|
|
242
|
+
plugin_id = carried.get("plugin_id")
|
|
243
|
+
if plugin_id is not None:
|
|
244
|
+
details["plugin_id"] = plugin_id
|
|
245
|
+
return error_code, details
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _classified_error_code(diagnostic: BaseException) -> Any:
|
|
249
|
+
"""Return the :class:`ErrorCode` ``diagnostic`` classifies as, if any.
|
|
250
|
+
|
|
251
|
+
Prefers the typed hierarchy's ``code`` over the contract exceptions'
|
|
252
|
+
``error_code``. An attribute holding a non-``ErrorCode`` -- a foreign
|
|
253
|
+
exception that happens to own a ``code``, e.g. ``SystemExit`` -- is
|
|
254
|
+
never mistaken for a classification, but is still returned when no real
|
|
255
|
+
code is present so the details report what the object carried.
|
|
256
|
+
"""
|
|
257
|
+
|
|
258
|
+
typed = getattr(diagnostic, "code", None)
|
|
259
|
+
if isinstance(typed, ErrorCode):
|
|
260
|
+
return typed
|
|
261
|
+
legacy = getattr(diagnostic, "error_code", None)
|
|
262
|
+
if isinstance(legacy, ErrorCode):
|
|
263
|
+
return legacy
|
|
264
|
+
return typed if legacy is None else legacy
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _fallback_permitted(diagnostic: BaseException, error_code: Any) -> bool:
|
|
268
|
+
"""Decide whether ``diagnostic`` may open the plain-text fallback.
|
|
269
|
+
|
|
270
|
+
True for the typed hierarchy's single fallback-permitting class, which
|
|
271
|
+
advertises ``plain_text_fallback_permitted = True`` ({p023}), and for
|
|
272
|
+
any diagnostic classified ``FORMAT_CONTENT_PARSE_FAILED`` -- how the
|
|
273
|
+
older contract exceptions, carrying no such flag, reach this path.
|
|
274
|
+
"""
|
|
275
|
+
|
|
276
|
+
if getattr(diagnostic, "plain_text_fallback_permitted", False) is True:
|
|
277
|
+
return True
|
|
278
|
+
return error_code == ErrorCode.FORMAT_CONTENT_PARSE_FAILED
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _decode_payload(source_payload: Union[str, bytes]) -> str:
|
|
282
|
+
"""Normalize ``source_payload`` to ``str`` for paragraph splitting.
|
|
283
|
+
|
|
284
|
+
``bytes`` is decoded as UTF-8 with ``errors="surrogateescape"``: a
|
|
285
|
+
decode failure must not abort fallback construction, and -- unlike
|
|
286
|
+
``errors="replace"`` -- every undecodable byte is preserved as a lone
|
|
287
|
+
surrogate that re-encodes to exactly itself, so the fallback cannot
|
|
288
|
+
corrupt the latin-1 or binary file it was invoked to rescue.
|
|
289
|
+
"""
|
|
290
|
+
|
|
291
|
+
if isinstance(source_payload, (bytes, bytearray)):
|
|
292
|
+
return bytes(source_payload).decode("utf-8", errors="surrogateescape")
|
|
293
|
+
return source_payload
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _display_text(text: str) -> str:
|
|
297
|
+
"""Render ``text`` for human reading: every surrogateescaped byte -- one
|
|
298
|
+
the payload could not decode as UTF-8 -- becomes ``U+FFFD``. Lossy by
|
|
299
|
+
design; the bytes stay on the node's ``source_text`` field."""
|
|
300
|
+
|
|
301
|
+
return text.encode("utf-8", errors="surrogateescape").decode("utf-8", errors="replace")
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _iter_lines(text: str) -> Iterator[Tuple[str, str]]:
|
|
305
|
+
"""Yield ``(content, terminator)`` per line of ``text``, terminator kept
|
|
306
|
+
verbatim (``""`` for a final unterminated line), so concatenating every
|
|
307
|
+
``content + terminator`` reproduces ``text``."""
|
|
308
|
+
|
|
309
|
+
position = 0
|
|
310
|
+
while position < len(text):
|
|
311
|
+
match = _LINE_BREAK.search(text, position)
|
|
312
|
+
if match is None:
|
|
313
|
+
yield text[position:], ""
|
|
314
|
+
return
|
|
315
|
+
yield text[position:match.start()], match.group(0)
|
|
316
|
+
position = match.end()
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _split_paragraphs(text: str) -> List[_Paragraph]:
|
|
320
|
+
"""Split ``text`` into paragraphs at blank-line boundaries.
|
|
321
|
+
|
|
322
|
+
The boundary rule itself is not implemented here: it is the plain-text
|
|
323
|
+
format's own, declared once in
|
|
324
|
+
:func:`~tree_engine.plugins.plain_text.split_text_paragraphs`, and this
|
|
325
|
+
module calls it so the degraded representation and the ordinary parse
|
|
326
|
+
result cut a document in exactly the same places. What stays local is what
|
|
327
|
+
a FALLBACK paragraph carries on top of the cut: a human-facing ``text``
|
|
328
|
+
(content lines joined with ``\\n``, separators dropped, undecodable bytes
|
|
329
|
+
shown as ``U+FFFD``), the 1-based ``line_start`` of its first content
|
|
330
|
+
line, and the verbatim ``source_text`` slice.
|
|
331
|
+
|
|
332
|
+
Where the two differ is WHERE the document's edge runs are held. The
|
|
333
|
+
plugin's tree has a root node to carry them; a fallback paragraph list has
|
|
334
|
+
no such place, so the leading run is prefixed to the first paragraph's
|
|
335
|
+
``source_text`` and the trailing run appended to the last one's, keeping
|
|
336
|
+
this module's long-standing contract that the ``source_text`` slices tile
|
|
337
|
+
the payload exactly. A payload with no content at all yields one paragraph
|
|
338
|
+
with empty ``text`` and the whole payload as ``source_text``, for the same
|
|
339
|
+
reason; a genuinely empty payload yields no paragraphs.
|
|
340
|
+
|
|
341
|
+
Line splitting stays local too, and deliberately differs from the
|
|
342
|
+
plugin's: :data:`_LINE_BREAK` breaks on the three real terminators only,
|
|
343
|
+
never on the extras ``str.splitlines`` also cuts at, because a rescued
|
|
344
|
+
binary file may legitimately contain them. It is injected into the shared
|
|
345
|
+
cut so only the paragraph boundaries are shared, never the line rule.
|
|
346
|
+
"""
|
|
347
|
+
|
|
348
|
+
layout = split_text_paragraphs(text, split_lines=_split_lines)
|
|
349
|
+
if not layout.paragraphs:
|
|
350
|
+
return [_Paragraph("", 1, text)] if text else []
|
|
351
|
+
paragraphs: List[_Paragraph] = []
|
|
352
|
+
for index, span in enumerate(layout.paragraphs):
|
|
353
|
+
contents = [line.rstrip("\r\n") for line in span.lines]
|
|
354
|
+
source = "".join(span.lines) + span.separator
|
|
355
|
+
if index == 0:
|
|
356
|
+
source = layout.leading_separator + source
|
|
357
|
+
if index == len(layout.paragraphs) - 1:
|
|
358
|
+
source = source + layout.trailing_separator
|
|
359
|
+
paragraphs.append(_Paragraph(
|
|
360
|
+
_display_text("\n".join(contents)),
|
|
361
|
+
span.line_numbers[0] + 1,
|
|
362
|
+
source,
|
|
363
|
+
))
|
|
364
|
+
return paragraphs
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def _split_lines(text: str) -> List[str]:
|
|
368
|
+
"""This module's own line rule: break only on the three real terminators."""
|
|
369
|
+
|
|
370
|
+
return [content + terminator for content, terminator in _iter_lines(text)]
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _build_paragraph_node(paragraph: _Paragraph, index: int) -> Tuple[UUID, Node]:
|
|
374
|
+
"""Build one ``plain_text:paragraph`` ``Node`` with a fresh UUID4 identity."""
|
|
375
|
+
|
|
376
|
+
node = make_node(
|
|
377
|
+
_PARAGRAPH_KIND,
|
|
378
|
+
fields={
|
|
379
|
+
"text": paragraph.text, "index": index,
|
|
380
|
+
"line_start": paragraph.line_start,
|
|
381
|
+
VERBATIM_TEXT_FIELD: paragraph.source_text,
|
|
382
|
+
},
|
|
383
|
+
)
|
|
384
|
+
node_id = generate_node_id()
|
|
385
|
+
node = _with_node_id(node, node_id)
|
|
386
|
+
return node_id, node
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def _build_root_node(paragraph_nodes: Tuple[Node, ...]) -> Node:
|
|
390
|
+
"""Build the ``plain_text:root`` container over ``paragraph_nodes``, in order."""
|
|
391
|
+
|
|
392
|
+
node = make_node(
|
|
393
|
+
_ROOT_KIND,
|
|
394
|
+
fields={"paragraph_count": len(paragraph_nodes)},
|
|
395
|
+
children=paragraph_nodes,
|
|
396
|
+
)
|
|
397
|
+
return _with_node_id(node, generate_node_id())
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def _with_node_id(node: Node, node_id: UUID) -> Node:
|
|
401
|
+
"""Attach ``node_id`` plus a fresh positive ``short_id`` to an
|
|
402
|
+
already-validated ``node``.
|
|
403
|
+
|
|
404
|
+
``Node`` is immutable and ``make_node`` has no ``node_id`` parameter, so
|
|
405
|
+
per ``core/nodes.py``'s own documented pattern for attaching an identity
|
|
406
|
+
produced elsewhere, this constructs a new frozen instance carrying every
|
|
407
|
+
already-validated field plus the identity, re-running no validation. The
|
|
408
|
+
``short_id`` ({p097}) comes from this module's shared counter: without
|
|
409
|
+
one the query engine cannot address a fallback node at all.
|
|
410
|
+
"""
|
|
411
|
+
|
|
412
|
+
return Node(
|
|
413
|
+
kind=node.kind,
|
|
414
|
+
fields=node.fields,
|
|
415
|
+
children=node.children,
|
|
416
|
+
node_id=node_id,
|
|
417
|
+
short_id=next(_short_id_counter),
|
|
418
|
+
extended_type=node.extended_type,
|
|
419
|
+
buffer_range=node.buffer_range,
|
|
420
|
+
references=node.references,
|
|
421
|
+
)
|