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,501 @@
|
|
|
1
|
+
"""The C / C++ / CUDA format plugin objects (wish 2a977287, stage i: navigable-only MVP).
|
|
2
|
+
|
|
3
|
+
Scope: this module is the join point between
|
|
4
|
+
:mod:`tree_engine.plugins.cpp.languages` (grammar dispatch/parsing),
|
|
5
|
+
:mod:`tree_engine.plugins.cpp.import_map` (tree-sitter tree -> common model), and the two shared
|
|
6
|
+
plugin interfaces this codebase's other plugins already implement --
|
|
7
|
+
``tree_engine.plugins.contract.FormatPluginContract`` and
|
|
8
|
+
``tree_engine.core.plugin_boundary.FormatBoundary`` -- exactly as
|
|
9
|
+
``tree_engine.plugins.bsl.plugin.BSLFormatPlugin`` does for BSL. One concrete class,
|
|
10
|
+
``CppFamilyFormatPlugin``, is parameterized by ``format_id`` and instantiated three times below
|
|
11
|
+
(``C_FORMAT_PLUGIN``, ``CPP_FORMAT_PLUGIN``, ``CUDA_FORMAT_PLUGIN``) rather than three
|
|
12
|
+
near-identical subclasses, because every stage of the pipeline (grammar dispatch, node mapping,
|
|
13
|
+
rendering) already branches on ``format_id`` internally in ``languages.py``/``import_map.py``.
|
|
14
|
+
|
|
15
|
+
Rendering strategy ({p046}/{p047}-equivalent honesty about what this MVP actually promises): per
|
|
16
|
+
:mod:`tree_engine.plugins.cpp.import_map`'s own docstring, every mapped node's ``content`` field IS
|
|
17
|
+
its own exact original source text. ``generate_output`` below does nothing more than read that
|
|
18
|
+
field back off the target node and re-encode it as UTF-8 -- there is no code generator here the
|
|
19
|
+
way ``tree_engine.plugins.bsl.generator.BSLGenerator`` is one, because nothing this plugin does is
|
|
20
|
+
allowed to regenerate text from structured fields (that is exactly the mechanism that broke BSL's
|
|
21
|
+
own byte-identical claim). This is also why ``export_from_common`` is the identity function: the
|
|
22
|
+
common-model node already IS this plugin's own "generation-ready representation".
|
|
23
|
+
|
|
24
|
+
Root-span correction (see ``import_map``'s docstring for the measurement): tree-sitter's
|
|
25
|
+
``translation_unit`` does not extend its own span to cover leading whitespace/blank lines before
|
|
26
|
+
the first real token. :meth:`CppFamilyFormatPlugin.parse_document` is the one place that holds
|
|
27
|
+
both the freshly mapped root node AND the original source bytes at the same time, so it is the one
|
|
28
|
+
place that can and does correct this -- overwriting the mapped root's ``content``/``buffer_range``
|
|
29
|
+
with the FULL original source text/span whenever they differ, leaving every other field (including
|
|
30
|
+
the whole rest of the tree, unaffected) exactly as ``import_map`` produced it. This is what makes
|
|
31
|
+
``render_document(parse_document(source)) == source`` unconditionally true for this plugin family,
|
|
32
|
+
not merely true on the fixtures that happen not to start with leading blank lines.
|
|
33
|
+
|
|
34
|
+
Fragments: per the design brief for this stage (\"parse_fragment may return a plain str for 'no
|
|
35
|
+
structure' in this MVP\"), :meth:`CppFamilyFormatPlugin.parse_fragment` makes no attempt at
|
|
36
|
+
structural fragment parsing at all -- it always returns the fragment's own text as a plain ``str``,
|
|
37
|
+
which the ``FormatPluginContract`` explicitly permits as the "no structure recognized" signal.
|
|
38
|
+
Real fragment structure (so that, e.g., a single inserted statement can be understood on its own)
|
|
39
|
+
is deferred to the editing stage, per the design brief; implementing it now would require deciding
|
|
40
|
+
how a bare fragment should be wrapped for a language whose grammar has no dedicated
|
|
41
|
+
statement/expression entry point the way LibCST does, which is exactly the kind of premature
|
|
42
|
+
decision editing-stage work should make, not this one.
|
|
43
|
+
|
|
44
|
+
Whole-file parse refusals (R2, verifier residue): every case below raises
|
|
45
|
+
``FORMAT_CONTENT_PARSE_FAILED`` because the underlying tree-sitter parse tree reports
|
|
46
|
+
``has_error`` -- see :func:`tree_engine.plugins.cpp.import_map.import_to_common`'s docstring for
|
|
47
|
+
where that is turned into the typed refusal -- with the ONE exception the fix below recovers:
|
|
48
|
+
|
|
49
|
+
* **A macro-decorated declaration** (e.g. ``EXPORT int g;`` where ``EXPORT`` is an object-like
|
|
50
|
+
macro expanding to an attribute) is refused: the grammar has no rule for an unknown bare
|
|
51
|
+
identifier immediately before a declaration's type, so it reports an error at that point even
|
|
52
|
+
though the file is perfectly valid C once ``EXPORT`` is preprocessed away -- this plugin never
|
|
53
|
+
runs the C preprocessor (macros are represented as nodes, never expanded; see the module-level
|
|
54
|
+
``PreprocDefineObject``/``PreprocDefineFunction`` docs in ``import_map``), so it cannot tell this
|
|
55
|
+
apart from a genuine syntax error. See ``tests/plugins/cpp/test_parse_refusals.py`` (or the
|
|
56
|
+
README's own "What is not yet handled" section) for a pinned refusal case.
|
|
57
|
+
* **A ``Q_OBJECT``-style class body** (Qt's ``signals:``/``slots:`` pseudo-access-specifiers,
|
|
58
|
+
which are not real C++ keywords -- ``Q_OBJECT`` alone, without those, parses fine) is refused
|
|
59
|
+
for the same reason: this plugin has no preprocessor and tree-sitter-cpp's grammar has no rule
|
|
60
|
+
for either token in that position.
|
|
61
|
+
* **A file ending in a preprocessor directive with no final newline** (``#define X 1``,
|
|
62
|
+
``#include <stdio.h>``, ``#pragma once``, ... with no trailing ``b"\\n"``) used to be refused
|
|
63
|
+
the same way -- ``#if``/``#ifdef``/``#endif`` are unaffected (their own terminator is
|
|
64
|
+
``#endif``, not a newline), but a directive whose OWN grammar rule wants a line terminator has
|
|
65
|
+
nothing to consume at EOF without one. THIS ONE IS FIXED: see the no-final-newline retry on
|
|
66
|
+
:meth:`CppFamilyFormatPlugin.parse_document`, proven byte-identical by the
|
|
67
|
+
``no_final_newline_directive.c``/``.h`` corpus fixtures -- and see that same method's "Retry
|
|
68
|
+
span trim" note (R2) for the follow-up fix: the retry's own augmented buffer used to leak a
|
|
69
|
+
phantom trailing byte into the LAST node's own span/``content`` (invisible to the
|
|
70
|
+
whole-document round trip, which always renders the ROOT's own corrected span, but wrong for
|
|
71
|
+
any other node read directly, e.g. via ``tree_engine.facade.node_source_text``) until
|
|
72
|
+
:func:`_trim_overrun_spans` started clamping every node's span back down to the real
|
|
73
|
+
``source_bytes`` after such a retry; see ``tests/plugins/cpp/test_span_audit.py`` for the
|
|
74
|
+
corpus-wide assertion this now holds unconditionally.
|
|
75
|
+
|
|
76
|
+
Semantic roles: :func:`role_mapping_for` publishes each format's declarative kind -> role table --
|
|
77
|
+
function/method definitions map to FUNCTION, ``ClassSpecifier``/``StructSpecifier`` to CLASS (a C
|
|
78
|
+
``struct`` is a perfectly good CLASS for query purposes; C has no ``class`` keyword so
|
|
79
|
+
``c:ClassSpecifier`` simply never occurs, which the query engine's own documented behavior -- an
|
|
80
|
+
empty ``roles_for`` result for an inapplicable role -- treats identically to a mapped-but-absent
|
|
81
|
+
kind), and ``TranslationUnit`` to MODULE. Method promotion (a member ``FunctionDefinition`` nested
|
|
82
|
+
inside a class/struct becoming a METHOD rather than a FUNCTION) is NOT implemented in this stage:
|
|
83
|
+
the design brief only asks for "function definitions -> FUNCTION, class/struct -> CLASS, translation
|
|
84
|
+
unit -> MODULE", and C++'s ``function_definition`` node type is identical for a free function and a
|
|
85
|
+
member function -- disambiguating the two needs ancestor-aware ``role_for`` context-climbing this
|
|
86
|
+
plugin does not implement, so METHOD is left unmapped for this stage, exactly as BSL leaves it
|
|
87
|
+
unmapped for a format with no method construct at all.
|
|
88
|
+
"""
|
|
89
|
+
|
|
90
|
+
from __future__ import annotations
|
|
91
|
+
|
|
92
|
+
import dataclasses
|
|
93
|
+
from typing import Any, Mapping, Optional, Union
|
|
94
|
+
|
|
95
|
+
from tree_engine.core.nodes import Document, Node, make_node
|
|
96
|
+
from tree_engine.core.plugin_boundary import FormatBoundary
|
|
97
|
+
from tree_engine.errors import ErrorCode
|
|
98
|
+
from tree_engine.plugins.cpp import languages
|
|
99
|
+
from tree_engine.plugins.cpp.import_map import import_to_common
|
|
100
|
+
from tree_engine.plugins.contract import (
|
|
101
|
+
FormatPluginContract,
|
|
102
|
+
FormatPluginContractError,
|
|
103
|
+
FormatPluginMetadata,
|
|
104
|
+
SemanticRole,
|
|
105
|
+
SemanticRoleMapping,
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
__all__ = [
|
|
109
|
+
"CppFamilyFormatPlugin",
|
|
110
|
+
"C_FORMAT_PLUGIN",
|
|
111
|
+
"CPP_FORMAT_PLUGIN",
|
|
112
|
+
"CUDA_FORMAT_PLUGIN",
|
|
113
|
+
"role_mapping_for",
|
|
114
|
+
]
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _contract_error(
|
|
118
|
+
format_id: str, message: str, *, code: ErrorCode = ErrorCode.FORMAT_PLUGIN_CONTRACT_ERROR
|
|
119
|
+
) -> FormatPluginContractError:
|
|
120
|
+
return FormatPluginContractError(plugin_id=format_id, error_code=code, message=message)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _coerce_source_bytes(source: Union[str, bytes], format_id: str) -> bytes:
|
|
124
|
+
"""Normalize ``source`` to the ``bytes`` a tree-sitter ``Parser`` requires."""
|
|
125
|
+
|
|
126
|
+
if isinstance(source, bytes):
|
|
127
|
+
return source
|
|
128
|
+
if isinstance(source, str):
|
|
129
|
+
return source.encode("utf-8")
|
|
130
|
+
raise _contract_error(
|
|
131
|
+
format_id, f"{format_id} source must be str or bytes, got {type(source).__name__}"
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _coerce_text(value: Union[str, bytes], format_id: str) -> str:
|
|
136
|
+
if isinstance(value, str):
|
|
137
|
+
return value
|
|
138
|
+
if isinstance(value, bytes):
|
|
139
|
+
return value.decode("utf-8")
|
|
140
|
+
raise _contract_error(
|
|
141
|
+
format_id, f"{format_id} fragment must be str or bytes, got {type(value).__name__}"
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _module_kind(format_id: str) -> str:
|
|
146
|
+
return f"{format_id}:TranslationUnit"
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _function_kind(format_id: str) -> str:
|
|
150
|
+
return f"{format_id}:FunctionDefinition"
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _class_kinds(format_id: str) -> Mapping[str, SemanticRole]:
|
|
154
|
+
return {
|
|
155
|
+
f"{format_id}:ClassSpecifier": SemanticRole.CLASS,
|
|
156
|
+
f"{format_id}:StructSpecifier": SemanticRole.CLASS,
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def role_mapping_for(format_id: str) -> SemanticRoleMapping:
|
|
161
|
+
"""This format's declarative kind -> role table; see the module docstring for what is
|
|
162
|
+
(function, class/struct, module) and is not (method) modeled at this stage."""
|
|
163
|
+
|
|
164
|
+
mapping = {
|
|
165
|
+
_function_kind(format_id): SemanticRole.FUNCTION,
|
|
166
|
+
_module_kind(format_id): SemanticRole.MODULE,
|
|
167
|
+
}
|
|
168
|
+
mapping.update(_class_kinds(format_id))
|
|
169
|
+
return SemanticRoleMapping(mapping)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _metadata_for(format_id: str) -> FormatPluginMetadata:
|
|
173
|
+
return FormatPluginMetadata(
|
|
174
|
+
format_id=format_id,
|
|
175
|
+
aliases=(),
|
|
176
|
+
file_extensions=languages.file_extensions(format_id),
|
|
177
|
+
plugin_version="1.0.0",
|
|
178
|
+
contract_version="1.0.0",
|
|
179
|
+
capabilities={
|
|
180
|
+
"semantic_role_mapping": True,
|
|
181
|
+
# Measured (see tests/plugins/cpp and pipeline/checks/check_roundtrip.py's FormatSpec
|
|
182
|
+
# entries for this format): render_document(parse_document(source)) == source over the
|
|
183
|
+
# project's own tests/plugins/cpp/corpus fixtures, including every preprocessor/
|
|
184
|
+
# conditional-group/CUDA-kernel-launch construct that corpus exercises. True by
|
|
185
|
+
# construction, not by luck: generate_output always returns a node's own verbatim
|
|
186
|
+
# `content` field (see this module's docstring), and parse_document corrects the one
|
|
187
|
+
# measured tree-sitter root-span gap (leading whitespace before translation_unit's
|
|
188
|
+
# first token) before returning -- see CppFamilyFormatPlugin.parse_document.
|
|
189
|
+
"byte_identical_round_trip": True,
|
|
190
|
+
# The parsed tree is addressable/walkable (every node carries identity and children;
|
|
191
|
+
# see import_map.py) independent of round-trip fidelity -- navigable concerns only the
|
|
192
|
+
# import direction.
|
|
193
|
+
"navigable": True,
|
|
194
|
+
# Stage i is explicitly navigable-only: no mutation/export-back-with-edits path exists
|
|
195
|
+
# yet (parse_fragment does not even attempt structural parsing -- see this module's
|
|
196
|
+
# docstring). Editing is a later stage of wish 2a977287, not implemented here.
|
|
197
|
+
"editable": False,
|
|
198
|
+
},
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
class CppFamilyFormatPlugin(FormatPluginContract, FormatBoundary):
|
|
203
|
+
"""One registered ``format_id`` (``"c"``, ``"cpp"``, or ``"cuda"``) of this plugin package.
|
|
204
|
+
|
|
205
|
+
Composes :mod:`tree_engine.plugins.cpp.languages` (grammar dispatch) and
|
|
206
|
+
:mod:`tree_engine.plugins.cpp.import_map` (tree-sitter tree -> common model) behind
|
|
207
|
+
:class:`~tree_engine.plugins.contract.FormatPluginContract` and
|
|
208
|
+
:class:`~tree_engine.core.plugin_boundary.FormatBoundary`, exactly as
|
|
209
|
+
``tree_engine.plugins.bsl.plugin.BSLFormatPlugin`` does for BSL -- see this module's docstring
|
|
210
|
+
for why generation needs no separate generator object here.
|
|
211
|
+
"""
|
|
212
|
+
|
|
213
|
+
def __init__(self, format_id: str) -> None:
|
|
214
|
+
if format_id not in languages.SUPPORTED_FORMATS:
|
|
215
|
+
raise ValueError(f"unsupported cpp-family format_id {format_id!r}")
|
|
216
|
+
self._format_id = format_id
|
|
217
|
+
self._metadata = _metadata_for(format_id)
|
|
218
|
+
self._role_mapping = role_mapping_for(format_id)
|
|
219
|
+
|
|
220
|
+
# -- FormatPluginContract -------------------------------------------------
|
|
221
|
+
|
|
222
|
+
@property
|
|
223
|
+
def metadata(self) -> FormatPluginMetadata:
|
|
224
|
+
return self._metadata
|
|
225
|
+
|
|
226
|
+
def parse_document(
|
|
227
|
+
self,
|
|
228
|
+
source: Union[str, bytes],
|
|
229
|
+
options: Optional[Mapping[str, Any]] = None,
|
|
230
|
+
*,
|
|
231
|
+
source_format_id: Optional[str] = None,
|
|
232
|
+
) -> Document:
|
|
233
|
+
"""Parse full source text/bytes into a common-model ``Document``.
|
|
234
|
+
|
|
235
|
+
See this module's docstring for the root-span correction applied here: whenever the
|
|
236
|
+
mapped root node's own ``content``/``buffer_range`` do not already cover the FULL original
|
|
237
|
+
source (tree-sitter's ``translation_unit`` can start after leading whitespace/blank lines),
|
|
238
|
+
they are overwritten with the full original text/span before the ``Document`` is returned,
|
|
239
|
+
so a caller never observes the underlying tree-sitter quirk.
|
|
240
|
+
|
|
241
|
+
No-final-newline retry (see this module's docstring): a file ENDING in a preprocessor
|
|
242
|
+
directive (``#define``/``#include``/``#pragma``/... -- anything whose own grammar rule
|
|
243
|
+
wants a terminating newline) with no trailing ``b"\\n"`` of its own reports ``has_error``
|
|
244
|
+
even though every node's own span is unaffected by whether that newline exists (measured:
|
|
245
|
+
a ``preproc_def``'s ``start_byte:end_byte`` is identical parsed with or without one). One
|
|
246
|
+
retry with a virtual trailing newline appended recovers this exact case: if the first
|
|
247
|
+
parse errors and the source does not already end in a newline, parse
|
|
248
|
+
``source_bytes + b"\\n"`` once instead and use ITS tree when that one comes back clean,
|
|
249
|
+
never masking a genuinely broken file (one still ``has_error`` on the retry) behind a
|
|
250
|
+
second attempt.
|
|
251
|
+
|
|
252
|
+
Retry span trim (R2, verifier residue -- bug in the original retry, not merely an
|
|
253
|
+
untested gap): every node the retry's tree produces is mapped against the AUGMENTED
|
|
254
|
+
buffer, so any node whose ``end_byte`` reaches the appended virtual ``b"\\n"`` -- in
|
|
255
|
+
practice the file's own last node, e.g. the very ``preproc_def``/``preproc_include``/
|
|
256
|
+
``preproc_call`` this retry exists to recover -- carries a span/``content`` one byte
|
|
257
|
+
longer than the real ``source_bytes``, phantom trailing newline included. The ROOT node
|
|
258
|
+
is unaffected because :func:`_cover_full_span` below always overwrites it wholesale from
|
|
259
|
+
the real ``source_bytes`` regardless, which is why the whole-document
|
|
260
|
+
``render_document(parse_document(source)) == source`` measurement this plugin advertises
|
|
261
|
+
never caught it -- but any OTHER node, read directly (e.g. through
|
|
262
|
+
``tree_engine.facade.node_source_text``), overran EOF by one byte. Whenever the retry
|
|
263
|
+
path is taken, :func:`_trim_overrun_spans` walks the WHOLE mapped tree first and clamps
|
|
264
|
+
every node's ``buffer_range``/``content`` back down to ``len(source_bytes)``, re-slicing
|
|
265
|
+
``content`` from the real (un-augmented) bytes rather than trusting the augmented one's
|
|
266
|
+
text -- a no-op for every node that does not reach the appended byte.
|
|
267
|
+
"""
|
|
268
|
+
|
|
269
|
+
source_bytes = _coerce_source_bytes(source, self._format_id)
|
|
270
|
+
root_ts_node = languages.parse_bytes(self._format_id, source_bytes)
|
|
271
|
+
used_virtual_newline_retry = False
|
|
272
|
+
if root_ts_node.has_error and not source_bytes.endswith(b"\n"):
|
|
273
|
+
retry_root = languages.parse_bytes(self._format_id, source_bytes + b"\n")
|
|
274
|
+
if not retry_root.has_error:
|
|
275
|
+
root_ts_node = retry_root
|
|
276
|
+
used_virtual_newline_retry = True
|
|
277
|
+
mapped = self.import_to_common(root_ts_node, options, fragment=False)
|
|
278
|
+
if not isinstance(mapped, Node):
|
|
279
|
+
raise _contract_error(
|
|
280
|
+
self._format_id,
|
|
281
|
+
f"parsing a full {self._format_id} document must yield a Node, got "
|
|
282
|
+
f"{type(mapped).__name__}",
|
|
283
|
+
)
|
|
284
|
+
if used_virtual_newline_retry:
|
|
285
|
+
mapped = _trim_overrun_spans(mapped, source_bytes)
|
|
286
|
+
mapped = _cover_full_span(mapped, source_bytes)
|
|
287
|
+
return Document(root=mapped, source_format_id=self._format_id)
|
|
288
|
+
|
|
289
|
+
def import_external_tree(
|
|
290
|
+
self, external_tree: Any, options: Optional[Mapping[str, Any]] = None
|
|
291
|
+
) -> Union[Node, Document]:
|
|
292
|
+
"""Translate an already-parsed external tree-sitter tree into common nodes.
|
|
293
|
+
|
|
294
|
+
Unlike :meth:`parse_document`, this method never sees the original source bytes
|
|
295
|
+
independent of the tree it is handed, so the root-span correction above cannot be applied
|
|
296
|
+
here -- see this module's docstring for why that limitation is real but out of scope for
|
|
297
|
+
what this stage promises (a whole-document ``parse_document``/``render_document`` round
|
|
298
|
+
trip, which is exactly what is measured).
|
|
299
|
+
"""
|
|
300
|
+
|
|
301
|
+
return self.import_to_common(external_tree, options, fragment=False)
|
|
302
|
+
|
|
303
|
+
def parse_fragment(
|
|
304
|
+
self,
|
|
305
|
+
fragment: Union[str, bytes],
|
|
306
|
+
options: Optional[Mapping[str, Any]] = None,
|
|
307
|
+
*,
|
|
308
|
+
source_format_id: Optional[str] = None,
|
|
309
|
+
) -> str:
|
|
310
|
+
"""Always returns the fragment's own text as a plain ``str`` -- see this module's
|
|
311
|
+
docstring for why structural fragment parsing is deliberately not attempted in this
|
|
312
|
+
stage."""
|
|
313
|
+
|
|
314
|
+
return _coerce_text(fragment, self._format_id)
|
|
315
|
+
|
|
316
|
+
def import_to_common(
|
|
317
|
+
self,
|
|
318
|
+
external_representation: Any,
|
|
319
|
+
options: Optional[Mapping[str, Any]] = None,
|
|
320
|
+
*,
|
|
321
|
+
fragment: bool = False,
|
|
322
|
+
) -> Node:
|
|
323
|
+
"""The single input translator shared by ``parse_document``/``import_external_tree`` --
|
|
324
|
+
delegates entirely to :func:`tree_engine.plugins.cpp.import_map.import_to_common`."""
|
|
325
|
+
|
|
326
|
+
return import_to_common(
|
|
327
|
+
external_representation, options, format_id=self._format_id, fragment=fragment
|
|
328
|
+
)
|
|
329
|
+
|
|
330
|
+
def export_from_common(
|
|
331
|
+
self, nodes: Union[Node, Document], options: Optional[Mapping[str, Any]] = None
|
|
332
|
+
) -> Union[Node, Document]:
|
|
333
|
+
"""Identity: the common-model node already IS this plugin's generation-ready
|
|
334
|
+
representation, per this module's docstring."""
|
|
335
|
+
|
|
336
|
+
return nodes
|
|
337
|
+
|
|
338
|
+
def generate_output(
|
|
339
|
+
self,
|
|
340
|
+
target: Union[Node, Document, Any],
|
|
341
|
+
options: Optional[Mapping[str, Any]] = None,
|
|
342
|
+
) -> bytes:
|
|
343
|
+
"""Return ``target``'s own verbatim ``content`` field, UTF-8 encoded.
|
|
344
|
+
|
|
345
|
+
``target`` is either a ``Document`` (its ``root`` is used) or a bare ``Node`` -- never
|
|
346
|
+
anything else, since :meth:`export_from_common` never produces a third shape.
|
|
347
|
+
|
|
348
|
+
No reconstruction fallback (R1-a, verifier residue -- restores this format's original,
|
|
349
|
+
loud behaviour): this format is ``editable: False`` and ``tree_engine.facade`` refuses
|
|
350
|
+
every mutating entry point on it before anything splices (see
|
|
351
|
+
``facade._require_editable``), so a live mutation reaching this method at all means that
|
|
352
|
+
gate was bypassed -- a caller went around the facade directly, or monkeypatched the gate
|
|
353
|
+
off. A prior revision of this method papered over exactly that case by falling back to
|
|
354
|
+
recursively concatenating a content-less node's children's own rendered text once
|
|
355
|
+
``tree_engine.core.live_tree.invalidate_cached_source`` had dropped the mutated node's
|
|
356
|
+
ancestor chain's cached ``content``: that fallback is LOSSY relative to the original
|
|
357
|
+
byte-for-byte content (a gap between two children that belongs to neither of them, e.g.
|
|
358
|
+
separating whitespace or a byte a deleted sibling took with it, is never reconstructed)
|
|
359
|
+
and, worse, it rendered SILENTLY -- with the gate off, a delete followed by ``dumps()``
|
|
360
|
+
returned a plausible-looking but wrong document instead of any signal that something had
|
|
361
|
+
gone wrong. Removed: a node with no ``content`` field of its own -- mutated-tree fallback
|
|
362
|
+
or a genuine plugin defect alike -- always raises ``FORMAT_PLUGIN_CONTRACT_ERROR`` naming
|
|
363
|
+
the node kind, never partial bytes.
|
|
364
|
+
"""
|
|
365
|
+
|
|
366
|
+
if isinstance(target, Document):
|
|
367
|
+
node = target.root
|
|
368
|
+
elif isinstance(target, Node):
|
|
369
|
+
node = target
|
|
370
|
+
else:
|
|
371
|
+
raise _contract_error(
|
|
372
|
+
self._format_id,
|
|
373
|
+
f"generate_output expected a Node or Document, got {type(target).__name__}",
|
|
374
|
+
)
|
|
375
|
+
return self._render_text(node).encode("utf-8")
|
|
376
|
+
|
|
377
|
+
def _render_text(self, node: Node) -> str:
|
|
378
|
+
"""``node``'s own verbatim ``content`` field, or a loud
|
|
379
|
+
``FORMAT_PLUGIN_CONTRACT_ERROR`` naming its kind -- see :meth:`generate_output`'s
|
|
380
|
+
docstring for why this format never falls back to reconstructing text from children."""
|
|
381
|
+
|
|
382
|
+
content = node.fields.get("content")
|
|
383
|
+
if isinstance(content, str):
|
|
384
|
+
return content
|
|
385
|
+
raise _contract_error(
|
|
386
|
+
self._format_id,
|
|
387
|
+
f"node kind {node.kind!r} carries no renderable string 'content' field",
|
|
388
|
+
)
|
|
389
|
+
|
|
390
|
+
def semantic_role_mapping(self) -> SemanticRoleMapping:
|
|
391
|
+
return self._role_mapping
|
|
392
|
+
|
|
393
|
+
# -- FormatBoundary ---------------------------------------------------------
|
|
394
|
+
|
|
395
|
+
def render_document(self, document: Document) -> bytes:
|
|
396
|
+
result = self.generate_output(document, {})
|
|
397
|
+
if not isinstance(result, bytes):
|
|
398
|
+
raise _contract_error(
|
|
399
|
+
self._format_id, f"render_document expected bytes, got {type(result).__name__}"
|
|
400
|
+
)
|
|
401
|
+
return result
|
|
402
|
+
|
|
403
|
+
def render_fragment(self, node: Node) -> str:
|
|
404
|
+
result = self.generate_output(node, {})
|
|
405
|
+
if not isinstance(result, bytes):
|
|
406
|
+
raise _contract_error(
|
|
407
|
+
self._format_id, f"render_fragment expected bytes, got {type(result).__name__}"
|
|
408
|
+
)
|
|
409
|
+
return result.decode("utf-8")
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def _trim_overrun_spans(node: Node, source_bytes: bytes) -> Node:
|
|
413
|
+
"""Recursively clamp every node whose reported span extends past ``len(source_bytes)`` --
|
|
414
|
+
see :meth:`CppFamilyFormatPlugin.parse_document`'s "Retry span trim" note for why this is
|
|
415
|
+
needed only after the no-final-newline retry parses the AUGMENTED buffer.
|
|
416
|
+
|
|
417
|
+
Rebuilds bottom-up: a child's own trim result is what the parent's ``children`` tuple AND
|
|
418
|
+
every field value that references that same child object (``then_branch``,
|
|
419
|
+
``elif_branches``, ``else_branch``, the single-``Node`` ``condition``/body-holding fields,
|
|
420
|
+
...) both get retargeted to, so a node reachable through more than one field never ends up
|
|
421
|
+
disagreeing with itself about whether it was trimmed. A node whose own span already fits
|
|
422
|
+
inside ``source_bytes`` (the overwhelming majority) is returned completely unchanged --
|
|
423
|
+
right down to object identity -- so this is a no-op walk everywhere the retry's virtual byte
|
|
424
|
+
was never reached.
|
|
425
|
+
"""
|
|
426
|
+
|
|
427
|
+
limit = len(source_bytes)
|
|
428
|
+
trimmed_children = tuple(
|
|
429
|
+
_trim_overrun_spans(child, source_bytes) for child in node.children
|
|
430
|
+
)
|
|
431
|
+
children_changed = trimmed_children != node.children
|
|
432
|
+
child_map = {id(old): new for old, new in zip(node.children, trimmed_children)}
|
|
433
|
+
|
|
434
|
+
def _retarget(value: Any) -> Any:
|
|
435
|
+
if isinstance(value, Node):
|
|
436
|
+
return child_map.get(id(value), value)
|
|
437
|
+
if (
|
|
438
|
+
isinstance(value, tuple)
|
|
439
|
+
and value
|
|
440
|
+
and all(isinstance(item, Node) for item in value)
|
|
441
|
+
):
|
|
442
|
+
return tuple(child_map.get(id(item), item) for item in value)
|
|
443
|
+
return value
|
|
444
|
+
|
|
445
|
+
new_fields = {key: _retarget(value) for key, value in node.fields.items()}
|
|
446
|
+
fields_changed = any(new_fields[key] is not node.fields[key] for key in new_fields)
|
|
447
|
+
|
|
448
|
+
start, end = node.buffer_range
|
|
449
|
+
buffer_range = node.buffer_range
|
|
450
|
+
if end > limit:
|
|
451
|
+
new_start = min(start, limit)
|
|
452
|
+
buffer_range = (new_start, limit)
|
|
453
|
+
content = node.fields.get("content")
|
|
454
|
+
if isinstance(content, str):
|
|
455
|
+
new_fields["content"] = source_bytes[new_start:limit].decode("utf-8")
|
|
456
|
+
|
|
457
|
+
if (
|
|
458
|
+
not children_changed
|
|
459
|
+
and not fields_changed
|
|
460
|
+
and buffer_range == node.buffer_range
|
|
461
|
+
):
|
|
462
|
+
return node
|
|
463
|
+
|
|
464
|
+
rebuilt = make_node(node.kind, fields=new_fields, children=trimmed_children)
|
|
465
|
+
return dataclasses.replace(
|
|
466
|
+
rebuilt,
|
|
467
|
+
node_id=node.node_id,
|
|
468
|
+
short_id=node.short_id,
|
|
469
|
+
extended_type=node.extended_type,
|
|
470
|
+
buffer_range=buffer_range,
|
|
471
|
+
references=node.references,
|
|
472
|
+
)
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
def _cover_full_span(node: Node, source_bytes: bytes) -> Node:
|
|
476
|
+
"""Rewrite ``node``'s ``content``/``buffer_range`` to cover the FULL ``source_bytes`` span
|
|
477
|
+
whenever they do not already, correcting the one measured tree-sitter root-span gap documented
|
|
478
|
+
on ``CppFamilyFormatPlugin.parse_document`` -- a no-op (returns ``node`` unchanged) whenever the
|
|
479
|
+
mapped root already covers byte 0 through ``len(source_bytes)``, which is the common case."""
|
|
480
|
+
|
|
481
|
+
full_text = source_bytes.decode("utf-8")
|
|
482
|
+
if node.fields.get("content") == full_text and node.buffer_range == (0, len(source_bytes)):
|
|
483
|
+
return node
|
|
484
|
+
fields = dict(node.fields)
|
|
485
|
+
fields["content"] = full_text
|
|
486
|
+
rebuilt = make_node(node.kind, fields=fields, children=node.children)
|
|
487
|
+
return dataclasses.replace(
|
|
488
|
+
rebuilt,
|
|
489
|
+
node_id=node.node_id,
|
|
490
|
+
short_id=node.short_id,
|
|
491
|
+
extended_type=node.extended_type,
|
|
492
|
+
buffer_range=(0, len(source_bytes)),
|
|
493
|
+
references=node.references,
|
|
494
|
+
)
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
#: Registration data: ready-made, stateless singletons a sibling registry step can import and
|
|
498
|
+
#: register under their own ``format_id`` without needing to know how to construct one.
|
|
499
|
+
C_FORMAT_PLUGIN = CppFamilyFormatPlugin(languages.FORMAT_C)
|
|
500
|
+
CPP_FORMAT_PLUGIN = CppFamilyFormatPlugin(languages.FORMAT_CPP)
|
|
501
|
+
CUDA_FORMAT_PLUGIN = CppFamilyFormatPlugin(languages.FORMAT_CUDA)
|