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,160 @@
|
|
|
1
|
+
"""CORE-side translation boundary for format plugins (concept C-002).
|
|
2
|
+
|
|
3
|
+
Scope: this module defines the abstract contract a format plugin must
|
|
4
|
+
satisfy to exchange common-model trees with the core, per HRS {p045}. It
|
|
5
|
+
does not define plugin registration, discovery, or lookup -- that is G-004's
|
|
6
|
+
scope -- and it contains no registry. It also does not implement, select, or
|
|
7
|
+
construct any concrete plugin.
|
|
8
|
+
|
|
9
|
+
Isolation invariant ({p045}): the core -- including this file -- must never
|
|
10
|
+
import, type-hint, or otherwise reference a specific external parser/codegen
|
|
11
|
+
library's classes (e.g. LibCST, ``ast``, tree-sitter, ...). Every method
|
|
12
|
+
signature below is typed using only common-model types
|
|
13
|
+
(:class:`~tree_engine.core.nodes.Node`, :class:`~tree_engine.core.nodes.Document`)
|
|
14
|
+
or primitives (``bytes``, ``str``). An external library's tree object may be
|
|
15
|
+
imported and used only inside a concrete plugin module that implements
|
|
16
|
+
:class:`FormatBoundary`, and only within the bodies of that plugin's own
|
|
17
|
+
methods -- never at this module's level and never in any signature defined
|
|
18
|
+
here. A plugin implementation must never let an external library object
|
|
19
|
+
escape across this boundary: every value returned to a caller through
|
|
20
|
+
:class:`FormatBoundary` must be a common-model type or a primitive.
|
|
21
|
+
|
|
22
|
+
Error attribution: this file documents, via each method's docstring, which
|
|
23
|
+
stable :class:`~tree_engine.errors.ErrorCode` (see
|
|
24
|
+
``src/tree_engine/errors.py``) is the expected failure signal for that
|
|
25
|
+
method. It does not define, invent, or duplicate any error code, and it
|
|
26
|
+
defines no exception classes -- the typed exception hierarchy built on the
|
|
27
|
+
catalog is delivered later by the public-facade step tied to concept C-021.
|
|
28
|
+
|
|
29
|
+
Conformance: :func:`implements_format_boundary` is the one small,
|
|
30
|
+
unit-testable helper this module provides so a test can assert that a
|
|
31
|
+
candidate plugin class (or instance) structurally satisfies
|
|
32
|
+
:class:`FormatBoundary`, without that candidate needing to subclass anything
|
|
33
|
+
defined here.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
from __future__ import annotations
|
|
37
|
+
|
|
38
|
+
import abc
|
|
39
|
+
from typing import Any
|
|
40
|
+
|
|
41
|
+
from tree_engine.core.nodes import Document, Node
|
|
42
|
+
|
|
43
|
+
__all__ = [
|
|
44
|
+
"FormatBoundary",
|
|
45
|
+
"implements_format_boundary",
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class FormatBoundary(abc.ABC):
|
|
50
|
+
"""Abstract CORE-side boundary every format plugin must implement.
|
|
51
|
+
|
|
52
|
+
Only common-model types (:class:`Document`, :class:`Node`) or
|
|
53
|
+
primitives (``bytes``, ``str``) appear in these method signatures; no
|
|
54
|
+
external parser/codegen library type may appear as a parameter or
|
|
55
|
+
return type anywhere on this interface. A concrete implementation lives
|
|
56
|
+
entirely inside a plugin module: it may import and use any external
|
|
57
|
+
library it needs within its method bodies, but must translate to and
|
|
58
|
+
from common-model types at this boundary so no external library object
|
|
59
|
+
is ever visible to a caller of this interface.
|
|
60
|
+
|
|
61
|
+
No plugin registration, discovery, or lookup is defined or implied here
|
|
62
|
+
(reserved for G-004); this class only describes the shape a single
|
|
63
|
+
plugin must expose once it has already been resolved by whatever
|
|
64
|
+
mechanism a later step provides.
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
@abc.abstractmethod
|
|
68
|
+
def parse_document(self, source: bytes, *, source_format_id: str) -> Document:
|
|
69
|
+
"""Translate a full source buffer into a common-model ``Document``.
|
|
70
|
+
|
|
71
|
+
``source`` is the raw bytes of an entire source file; the returned
|
|
72
|
+
``Document`` is the common-model tree, with ``source_format_id``
|
|
73
|
+
(and, ordinarily, an equal ``representation_format_id``) recorded
|
|
74
|
+
per {p050}. This is whole-document parsing, distinct from
|
|
75
|
+
:meth:`parse_fragment`.
|
|
76
|
+
|
|
77
|
+
Expected failure signal: a plugin that cannot parse ``source`` as
|
|
78
|
+
valid content of ``source_format_id`` must signal
|
|
79
|
+
``ErrorCode.FORMAT_CONTENT_PARSE_FAILED``.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
raise NotImplementedError
|
|
83
|
+
|
|
84
|
+
@abc.abstractmethod
|
|
85
|
+
def parse_fragment(self, source: str, *, source_format_id: str) -> Node:
|
|
86
|
+
"""Translate a partial/fragment source string into a single ``Node``.
|
|
87
|
+
|
|
88
|
+
Unlike :meth:`parse_document`, ``source`` need not be a complete,
|
|
89
|
+
standalone document -- this is for incremental edit scenarios where
|
|
90
|
+
only a subtree is being (re)parsed. The result is a single
|
|
91
|
+
common-model ``Node`` subtree.
|
|
92
|
+
|
|
93
|
+
Expected failure signal: a plugin that cannot parse ``source`` as a
|
|
94
|
+
recognizable fragment of ``source_format_id`` must signal
|
|
95
|
+
``ErrorCode.FORMAT_FRAGMENT_PARSE_FAILED``.
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
raise NotImplementedError
|
|
99
|
+
|
|
100
|
+
@abc.abstractmethod
|
|
101
|
+
def render_document(self, document: Document) -> bytes:
|
|
102
|
+
"""Translate a common-model ``Document`` back into source bytes.
|
|
103
|
+
|
|
104
|
+
Implementations must preserve byte-for-byte fidelity ({p022}) for
|
|
105
|
+
any subtree of ``document.root`` left untouched since it was
|
|
106
|
+
produced by :meth:`parse_document`.
|
|
107
|
+
|
|
108
|
+
Expected failure signal: if a common-model construct in
|
|
109
|
+
``document`` has no faithful representation in this plugin's
|
|
110
|
+
format, the plugin must signal ``ErrorCode.UNSUPPORTED_TRANSLATION``
|
|
111
|
+
rather than silently dropping or approximating it.
|
|
112
|
+
"""
|
|
113
|
+
|
|
114
|
+
raise NotImplementedError
|
|
115
|
+
|
|
116
|
+
@abc.abstractmethod
|
|
117
|
+
def render_fragment(self, node: Node) -> str:
|
|
118
|
+
"""Translate a single common-model ``Node`` back into source text.
|
|
119
|
+
|
|
120
|
+
The counterpart of :meth:`parse_fragment`: renders one subtree, not
|
|
121
|
+
a whole document.
|
|
122
|
+
|
|
123
|
+
Expected failure signal: if ``node`` (or a construct within it) has
|
|
124
|
+
no faithful representation in this plugin's format, the plugin must
|
|
125
|
+
signal ``ErrorCode.UNSUPPORTED_TRANSLATION``.
|
|
126
|
+
"""
|
|
127
|
+
|
|
128
|
+
raise NotImplementedError
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def implements_format_boundary(candidate: Any) -> bool:
|
|
132
|
+
"""Return whether ``candidate`` structurally satisfies :class:`FormatBoundary`.
|
|
133
|
+
|
|
134
|
+
``candidate`` may be a class or an instance. This is the conformance
|
|
135
|
+
helper a test uses to assert that a plugin class satisfies the
|
|
136
|
+
boundary; it performs the same ABC-registration check
|
|
137
|
+
:func:`issubclass`/``isinstance`` would, without requiring the
|
|
138
|
+
candidate to be constructed first when given a class.
|
|
139
|
+
|
|
140
|
+
Any violation of this boundary's own calling contract by a *runtime*
|
|
141
|
+
call -- a wrong argument type, an external-library object or ``None``
|
|
142
|
+
returned where a common-model type is required, and so on -- is a
|
|
143
|
+
concern for the plugin's own defensive checks and for the caller that
|
|
144
|
+
invokes it; it is signaled via
|
|
145
|
+
``ErrorCode.FORMAT_PLUGIN_CONTRACT_ERROR`` and is out of scope for this
|
|
146
|
+
static structural check.
|
|
147
|
+
"""
|
|
148
|
+
|
|
149
|
+
target = candidate if isinstance(candidate, type) else type(candidate)
|
|
150
|
+
if not issubclass(target, FormatBoundary):
|
|
151
|
+
return False
|
|
152
|
+
# Inheritance alone is not conformance: a subclass that leaves an
|
|
153
|
+
# abstract method unimplemented cannot honour the boundary, and saying
|
|
154
|
+
# otherwise would let a broken plugin pass a conformance assertion.
|
|
155
|
+
if getattr(target, "__abstractmethods__", frozenset()):
|
|
156
|
+
return False
|
|
157
|
+
return all(
|
|
158
|
+
callable(getattr(target, name, None))
|
|
159
|
+
for name in ("parse_document", "parse_fragment", "render_document", "render_fragment")
|
|
160
|
+
)
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
"""Position model for concept C-005 (PositionMap, SubtreeBytesAggregate).
|
|
2
|
+
|
|
3
|
+
This module implements the derive-on-demand-plus-cache position model: byte and
|
|
4
|
+
line positions are DERIVED only at explicit boundaries via one translation-plus-render,
|
|
5
|
+
CACHED until the next journal entry, and the cache is DISCARDED whole by the next
|
|
6
|
+
journal entry (never incrementally patched). The module is format- and tree-agnostic:
|
|
7
|
+
it consumes a caller-supplied render walk, never walks the tree itself.
|
|
8
|
+
|
|
9
|
+
The PositionMap and SubtreeBytesAggregate both implement the JournalListener protocol
|
|
10
|
+
to react to mutations. Listeners are registered once and notified O(1) time per entry.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from typing import Callable, Dict, Iterable, Optional, Tuple
|
|
17
|
+
|
|
18
|
+
from tree_engine.core.journal import (
|
|
19
|
+
BoundaryEvent,
|
|
20
|
+
JournalEntry,
|
|
21
|
+
JournalListener,
|
|
22
|
+
MutationJournal,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"FragmentWalk",
|
|
27
|
+
"NodeSpan",
|
|
28
|
+
"PositionMap",
|
|
29
|
+
"SubtreeBytesAggregate",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# Type alias for a zero-argument callable yielding (node_path, fragment_bytes)
|
|
34
|
+
# in document order for every fragment-bearing node.
|
|
35
|
+
FragmentWalk = Callable[[], Iterable[Tuple[Tuple[str, ...], bytes]]]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class NodeSpan:
|
|
40
|
+
"""Position span of a single node's fragment.
|
|
41
|
+
|
|
42
|
+
Attributes:
|
|
43
|
+
byte_start: Byte offset from document start (0-based, inclusive).
|
|
44
|
+
byte_end: Byte offset from document start (0-based, exclusive).
|
|
45
|
+
line_start: 1-based line number where the fragment's first byte falls.
|
|
46
|
+
line_end: 1-based line number = line_start + (newline count in fragment).
|
|
47
|
+
For half-open semantics [line_start, line_end), this covers lines
|
|
48
|
+
in that range; for a fragment with no newlines, line_start == line_end
|
|
49
|
+
and the fragment occupies a single line.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
byte_start: int
|
|
53
|
+
byte_end: int
|
|
54
|
+
line_start: int
|
|
55
|
+
line_end: int
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class PositionMap(JournalListener):
|
|
59
|
+
"""Derive-on-demand-plus-cache position model.
|
|
60
|
+
|
|
61
|
+
Byte and line positions are derived only at explicit boundaries (via mark_boundary),
|
|
62
|
+
cached until the next journal entry, and discarded whole by any non-boundary entry.
|
|
63
|
+
All public queries (span, node_at_line) derive lazily if no valid cache exists.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
def __init__(self, journal: MutationJournal, walk: FragmentWalk) -> None:
|
|
67
|
+
"""Initialize and register as a listener to the journal.
|
|
68
|
+
|
|
69
|
+
Args:
|
|
70
|
+
journal: The MutationJournal to listen to.
|
|
71
|
+
walk: A zero-argument callable yielding (node_path, fragment_bytes) in document order.
|
|
72
|
+
"""
|
|
73
|
+
self._journal = journal
|
|
74
|
+
self._walk = walk
|
|
75
|
+
self._cache: Optional[Dict[Tuple[str, ...], NodeSpan]] = None
|
|
76
|
+
self._cache_seq: Optional[int] = None
|
|
77
|
+
journal.add_listener(self)
|
|
78
|
+
|
|
79
|
+
def derive(self, event: BoundaryEvent) -> None:
|
|
80
|
+
"""Derive byte and line positions, cache the result, mark a boundary.
|
|
81
|
+
|
|
82
|
+
This is the only place positions are computed. Calls journal.mark_boundary(event),
|
|
83
|
+
runs the walk once, accumulates byte offsets and line numbers per node_path,
|
|
84
|
+
and caches the result together with the boundary seq.
|
|
85
|
+
|
|
86
|
+
Args:
|
|
87
|
+
event: The BoundaryEvent marking this derivation.
|
|
88
|
+
"""
|
|
89
|
+
# Mark the boundary, which appends a boundary entry and fires listeners.
|
|
90
|
+
boundary_entry = self._journal.mark_boundary(event)
|
|
91
|
+
|
|
92
|
+
# Derive positions from a single walk.
|
|
93
|
+
self._cache = {}
|
|
94
|
+
current_byte = 0
|
|
95
|
+
current_line = 1
|
|
96
|
+
|
|
97
|
+
for node_path, fragment in self._walk():
|
|
98
|
+
line_start = current_line
|
|
99
|
+
newline_count = fragment.count(b"\n")
|
|
100
|
+
line_end = current_line + newline_count
|
|
101
|
+
|
|
102
|
+
self._cache[node_path] = NodeSpan(
|
|
103
|
+
byte_start=current_byte,
|
|
104
|
+
byte_end=current_byte + len(fragment),
|
|
105
|
+
line_start=line_start,
|
|
106
|
+
line_end=line_end,
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
current_byte += len(fragment)
|
|
110
|
+
current_line = line_end
|
|
111
|
+
|
|
112
|
+
# Record the boundary seq so we know when the cache is valid.
|
|
113
|
+
self._cache_seq = boundary_entry.seq
|
|
114
|
+
|
|
115
|
+
def on_journal_entry(self, entry: JournalEntry) -> None:
|
|
116
|
+
"""Invalidate the cache on any non-boundary entry.
|
|
117
|
+
|
|
118
|
+
The boundary entry appended by derive() itself will call this method:
|
|
119
|
+
boundary entries (op='boundary') must NOT discard the cache. Only
|
|
120
|
+
non-boundary entries invalidate the cache whole.
|
|
121
|
+
|
|
122
|
+
Args:
|
|
123
|
+
entry: The journal entry that was just appended.
|
|
124
|
+
"""
|
|
125
|
+
if entry.op != "boundary":
|
|
126
|
+
self._cache = None
|
|
127
|
+
self._cache_seq = None
|
|
128
|
+
|
|
129
|
+
def span(self, node_path: Tuple[str, ...]) -> NodeSpan:
|
|
130
|
+
"""Return the span of a node, deriving if needed.
|
|
131
|
+
|
|
132
|
+
If no valid cache exists, derives lazily with BoundaryEvent.POSITION_MAP_DERIVATION.
|
|
133
|
+
|
|
134
|
+
Args:
|
|
135
|
+
node_path: Tuple of node IDs from root to the target node.
|
|
136
|
+
|
|
137
|
+
Returns:
|
|
138
|
+
The NodeSpan for the node.
|
|
139
|
+
|
|
140
|
+
Raises:
|
|
141
|
+
KeyError: If node_path is not in the document.
|
|
142
|
+
"""
|
|
143
|
+
if self._cache is None:
|
|
144
|
+
self.derive(BoundaryEvent.POSITION_MAP_DERIVATION)
|
|
145
|
+
return self._cache[node_path]
|
|
146
|
+
|
|
147
|
+
def node_at_line(self, line: int) -> Tuple[str, ...]:
|
|
148
|
+
"""Return the innermost fragment-bearing node covering a line.
|
|
149
|
+
|
|
150
|
+
Derives lazily if needed. Searches for all nodes covering the line,
|
|
151
|
+
returns the deepest one by path length; on tie, returns the first in document order.
|
|
152
|
+
|
|
153
|
+
Args:
|
|
154
|
+
line: 1-based line number.
|
|
155
|
+
|
|
156
|
+
Returns:
|
|
157
|
+
The node_path of the innermost node covering the line.
|
|
158
|
+
|
|
159
|
+
Raises:
|
|
160
|
+
ValueError: If line is outside the document.
|
|
161
|
+
"""
|
|
162
|
+
if self._cache is None:
|
|
163
|
+
self.derive(BoundaryEvent.POSITION_MAP_DERIVATION)
|
|
164
|
+
|
|
165
|
+
candidates = []
|
|
166
|
+
for node_path, span in self._cache.items():
|
|
167
|
+
# Check coverage: [line_start, line_end) for half-open semantics.
|
|
168
|
+
# A fragment with no newlines has line_start == line_end and covers only that line.
|
|
169
|
+
if span.line_start <= line < span.line_end or (
|
|
170
|
+
span.line_start == span.line_end and line == span.line_start
|
|
171
|
+
):
|
|
172
|
+
candidates.append(node_path)
|
|
173
|
+
|
|
174
|
+
if not candidates:
|
|
175
|
+
raise ValueError(f"Line {line} is outside the document")
|
|
176
|
+
|
|
177
|
+
# Return the deepest node (longest path = most specific).
|
|
178
|
+
return max(candidates, key=lambda p: len(p))
|
|
179
|
+
|
|
180
|
+
@property
|
|
181
|
+
def is_cached(self) -> bool:
|
|
182
|
+
"""Return True if a valid cache exists."""
|
|
183
|
+
return self._cache is not None
|
|
184
|
+
|
|
185
|
+
@property
|
|
186
|
+
def cache_seq(self) -> Optional[int]:
|
|
187
|
+
"""Return the boundary seq the cache was derived at, or None."""
|
|
188
|
+
return self._cache_seq
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class SubtreeBytesAggregate(JournalListener):
|
|
192
|
+
"""Maintains the locally updated ancestor-chain aggregate byte sizes.
|
|
193
|
+
|
|
194
|
+
Each node's subtree byte size = its own fragment bytes + all descendants'.
|
|
195
|
+
Aggregates are updated O(1) per entry by applying byte-size deltas along
|
|
196
|
+
the ancestor chain only (every prefix of node_path).
|
|
197
|
+
"""
|
|
198
|
+
|
|
199
|
+
def __init__(self) -> None:
|
|
200
|
+
"""Initialize with empty byte sizes."""
|
|
201
|
+
self._bytes: Dict[Tuple[str, ...], int] = {}
|
|
202
|
+
|
|
203
|
+
def initialize(self, walk: FragmentWalk) -> None:
|
|
204
|
+
"""Build the initial per-node subtree byte sizes from a full pass.
|
|
205
|
+
|
|
206
|
+
One full walk collecting fragment sizes. For each node, its subtree
|
|
207
|
+
size is computed as the sum of all descendants' fragment sizes.
|
|
208
|
+
|
|
209
|
+
Args:
|
|
210
|
+
walk: A zero-argument callable yielding (node_path, fragment_bytes)
|
|
211
|
+
in document order.
|
|
212
|
+
"""
|
|
213
|
+
self._bytes = {}
|
|
214
|
+
|
|
215
|
+
# First pass: collect fragment sizes for all leaf nodes.
|
|
216
|
+
fragment_bytes: Dict[Tuple[str, ...], int] = {}
|
|
217
|
+
for node_path, fragment in walk():
|
|
218
|
+
fragment_bytes[node_path] = len(fragment)
|
|
219
|
+
|
|
220
|
+
# Second pass: compute subtree sizes by summing descendants.
|
|
221
|
+
for node_path, fragment_size in fragment_bytes.items():
|
|
222
|
+
# Add this node's fragment to itself and all ancestors.
|
|
223
|
+
for i in range(len(node_path) + 1):
|
|
224
|
+
ancestor_path = node_path[:i]
|
|
225
|
+
self._bytes[ancestor_path] = (
|
|
226
|
+
self._bytes.get(ancestor_path, 0) + fragment_size
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
def on_journal_entry(self, entry: JournalEntry) -> None:
|
|
230
|
+
"""Apply byte-size deltas along the ancestor chain.
|
|
231
|
+
|
|
232
|
+
Reads entry.payload['size_delta'] (absent means 0) and applies it
|
|
233
|
+
along entry.node_path (the touched node and all ancestors).
|
|
234
|
+
Boundary entries (op='boundary') carry no size_delta and are a no-op.
|
|
235
|
+
|
|
236
|
+
Args:
|
|
237
|
+
entry: The journal entry that was just appended.
|
|
238
|
+
"""
|
|
239
|
+
if entry.op == "boundary":
|
|
240
|
+
return
|
|
241
|
+
|
|
242
|
+
size_delta = entry.payload.get("size_delta", 0)
|
|
243
|
+
if size_delta == 0:
|
|
244
|
+
return
|
|
245
|
+
|
|
246
|
+
# Apply the delta to the touched node and all ancestors.
|
|
247
|
+
for i in range(len(entry.node_path) + 1):
|
|
248
|
+
ancestor_path = entry.node_path[:i]
|
|
249
|
+
self._bytes[ancestor_path] = self._bytes.get(ancestor_path, 0) + size_delta
|
|
250
|
+
|
|
251
|
+
def bytes_of(self, node_path: Tuple[str, ...]) -> int:
|
|
252
|
+
"""Return the subtree byte size of a node.
|
|
253
|
+
|
|
254
|
+
Args:
|
|
255
|
+
node_path: Tuple of node IDs from root to the target node.
|
|
256
|
+
|
|
257
|
+
Returns:
|
|
258
|
+
The total byte count (fragment + all descendants).
|
|
259
|
+
|
|
260
|
+
Raises:
|
|
261
|
+
KeyError: If node_path is not in the tracking dictionary.
|
|
262
|
+
"""
|
|
263
|
+
return self._bytes[node_path]
|