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,505 @@
|
|
|
1
|
+
"""tree-sitter-{c,cpp,cuda}-to-common-model import pipeline (wish 2a977287, stage i).
|
|
2
|
+
|
|
3
|
+
Scope: this module converts an already-parsed tree-sitter parse tree (from any of the three
|
|
4
|
+
grammars :mod:`tree_engine.plugins.cpp.languages` dispatches to) into a common-model
|
|
5
|
+
:class:`~tree_engine.core.nodes.Node`. It is the single input translator shared by all three
|
|
6
|
+
registered format ids (``c``, ``cpp``, ``cuda``) -- one grammar produces subtly different node
|
|
7
|
+
shapes from another (only CUDA has ``kernel_call_syntax``; only CUDA function definitions carry
|
|
8
|
+
``__global__``/``__device__``/``__host__`` qualifier tokens), but every construct this module gives
|
|
9
|
+
special treatment to (``#include``, object/function macros, ``#undef``, other ``#pragma``-style
|
|
10
|
+
directives, ``#if``/``#ifdef``/``#elif``/``#else``/``#endif`` conditional groups) is shaped
|
|
11
|
+
IDENTICALLY across tree-sitter-c and tree-sitter-cpp (tree-sitter-cuda is itself a tree-sitter-cpp
|
|
12
|
+
derivative, so it inherits the same shapes), which is what lets one converter class serve all
|
|
13
|
+
three grammars via a single ``format_id`` parameter rather than three near-duplicate copies.
|
|
14
|
+
|
|
15
|
+
Content-is-truth rendering strategy (this is the whole byte-identity story, so it is worth stating
|
|
16
|
+
plainly): EVERY mapped node -- generic passthrough or specially-treated construct alike -- carries
|
|
17
|
+
a ``content`` field holding the EXACT original source text for that node's own tree-sitter byte
|
|
18
|
+
range (``ts_node.start_byte:ts_node.end_byte``), obtained by direct slicing, never by
|
|
19
|
+
concatenating/regenerating from child pieces. Slicing a node's own span, rather than gap-stitching
|
|
20
|
+
it back together from children, already includes every byte in that span -- inter-token
|
|
21
|
+
whitespace, comments, line continuations, all of it -- because it IS the literal substring, not a
|
|
22
|
+
reconstruction. This is the same technique
|
|
23
|
+
``tree_engine.plugins.bsl.import_map._convert_generic`` already uses for BSL's fallback nodes
|
|
24
|
+
(only there it feeds a generator that sometimes re-derives output from structured fields instead
|
|
25
|
+
of trusting ``content``, which is what actually broke BSL's byte-identical round trip -- see that
|
|
26
|
+
module's docstring). This plugin never does that: :mod:`tree_engine.plugins.cpp.plugin`'s
|
|
27
|
+
``generate_output`` always returns a node's own ``content`` field verbatim, so nothing this module
|
|
28
|
+
does to enrich a node with extra structured fields (``keyword``, ``condition``, ``then_branch``,
|
|
29
|
+
``elif_branches``, ``else_branch``, ``macro_name``, ``raw_params``, ``raw_value``, ``qualifiers``,
|
|
30
|
+
...) can ever influence what gets rendered back -- those fields exist purely for navigation and
|
|
31
|
+
the query engine.
|
|
32
|
+
|
|
33
|
+
One real gap this content-is-truth strategy does NOT close on its own: tree-sitter's own
|
|
34
|
+
``translation_unit`` root node does not extend its span to cover LEADING whitespace/blank lines
|
|
35
|
+
that precede the first real token (measured: parsing ``b"\\n\\n\\nint x;\\n\\n\\n"`` -- 12 bytes --
|
|
36
|
+
yields a root span of ``(3, 12)``, silently dropping the leading ``b"\\n\\n\\n"``; an empty or
|
|
37
|
+
whitespace-only file gets a zero-width root at the very end of the buffer instead of at its
|
|
38
|
+
start). Every other node's own span is safely contained inside whatever encloses it (a inner gap
|
|
39
|
+
before a node's own first child is still covered by that node's own parent's own full-span slice,
|
|
40
|
+
so it never escapes the document), so this one root-level trivia-loss is the only place this
|
|
41
|
+
matters for a whole-document round trip; it is patched by
|
|
42
|
+
``tree_engine.plugins.cpp.plugin.CppFamilyFormatPlugin.parse_document``, which owns the original
|
|
43
|
+
source bytes and can add the missing prefix back onto the mapped root node's ``content`` --
|
|
44
|
+
readers of this module should never need to reason about it, but it is documented here because
|
|
45
|
+
this module is where the underlying tree-sitter behavior was actually measured.
|
|
46
|
+
|
|
47
|
+
Preprocessor node model, per the governing design (wish 2a977287 stage i brief):
|
|
48
|
+
|
|
49
|
+
* ``preproc_include`` -> ``PreprocInclude``, with a ``path`` field holding the raw ``path`` field
|
|
50
|
+
child's text (``<vector>`` or ``"local.hpp"``, delimiters included -- raw addressing, never
|
|
51
|
+
stripped or resolved).
|
|
52
|
+
* ``preproc_def`` (object-like macro) -> ``PreprocDefineObject``, with ``macro_name`` and
|
|
53
|
+
``raw_value`` (empty string when the macro has no replacement text).
|
|
54
|
+
* ``preproc_function_def`` (function-like macro) -> ``PreprocDefineFunction``, with ``macro_name``,
|
|
55
|
+
``raw_params`` (the whole parenthesized parameter list as one raw string, parentheses included --
|
|
56
|
+
never decomposed into individual parameter nodes; this plugin never expands or interprets a
|
|
57
|
+
macro body) and ``raw_value``.
|
|
58
|
+
* ``preproc_call`` -- the grammar's own generic wrapper for ``#pragma``, ``#error``, ``#line`` and
|
|
59
|
+
``#undef`` alike (they all share this one node type, distinguished only by the literal text of
|
|
60
|
+
their ``directive`` field) -- is split back into two kinds here: a ``directive`` field text of
|
|
61
|
+
``"#undef"`` maps to ``PreprocUndef`` (with ``macro_name`` taken from the ``argument`` field),
|
|
62
|
+
anything else maps to ``PreprocCall`` (with ``directive`` and ``argument`` fields, both raw text).
|
|
63
|
+
* ``preproc_if``/``preproc_ifdef`` -> one ``PreprocConditionalGroup`` per group, with: ``keyword``
|
|
64
|
+
(the opening token's CANONICAL spelling -- ``"#if"``/``"#ifdef"``/``"#ifndef"``, normalized via
|
|
65
|
+
the token's own ``.type`` rather than its raw ``.text``, since ``"# if"``/``"#\tif"`` -- a
|
|
66
|
+
directive with whitespace between ``#`` and the keyword -- is still valid C/C++ and would
|
|
67
|
+
otherwise leak into this field; the group's own ``content`` field is unaffected either way, since
|
|
68
|
+
it is always the exact raw slice of the WHOLE group, so no byte is lost by normalizing this one
|
|
69
|
+
field), ``condition`` (raw text of the grammar's ``condition`` field for ``#if``/``#elif``, or its
|
|
70
|
+
``name`` field for ``#ifdef``/``#ifndef`` -- always a plain string, the full boolean-expression
|
|
71
|
+
text for ``#if`` is never parsed further), ``then_branch`` (an ordered tuple of the group's own
|
|
72
|
+
body nodes -- every named child that is not the condition/name or the nested ``alternative``
|
|
73
|
+
chain), ``elif_branches`` (an ordered tuple of ``PreprocElifBranch`` nodes, walking the grammar's
|
|
74
|
+
own ``alternative`` chain -- each branch's own span/``content`` end at the START of its
|
|
75
|
+
``alternative`` child rather than at its tree-sitter-reported ``end_byte``, so that two
|
|
76
|
+
consecutive ``#elif``s -- which tree-sitter nests one inside the other -- get DISJOINT reported
|
|
77
|
+
spans instead of the first one's span containing the second's; see
|
|
78
|
+
:meth:`_Converter._build_elif_branch`), ``has_else``/``else_branch`` (a plain tuple of body
|
|
79
|
+
nodes -- no wrapper kind, per the design brief's own wording), and ``endif_text`` (the trailing
|
|
80
|
+
``#endif`` token's own canonical spelling, same normalization as ``keyword`` and for the same
|
|
81
|
+
reason; carried as trivia of the group -- tree-sitter attaches this token only to the OUTERMOST
|
|
82
|
+
``preproc_if``/``preproc_ifdef`` of a chain, never to a nested ``preproc_elif``/``preproc_else``,
|
|
83
|
+
so it is read once here at the same level). ALL of these fields are always present on every
|
|
84
|
+
``PreprocConditionalGroup``, empty/false when not applicable, never omitted.
|
|
85
|
+
* ``kernel_call_syntax`` (CUDA only) -> ``KernelLaunch``, with no field beyond the inherited
|
|
86
|
+
``content`` (the raw ``<<<...>>>`` text) -- it already sits exactly where the design brief wants
|
|
87
|
+
it, as a named child of the surrounding ``call_expression``, so no restructuring is needed, only
|
|
88
|
+
the kind rename.
|
|
89
|
+
* ``function_definition`` additionally carries a ``qualifiers`` field: a single space-joined
|
|
90
|
+
string of whichever of ``__global__``/``__device__``/``__host__`` appear as the function's own
|
|
91
|
+
leading anonymous tokens, in source order (empty string otherwise -- C and C++ function
|
|
92
|
+
definitions simply never have one). A plain string, not a tuple: ``Node.fields``' ordered-child-
|
|
93
|
+
sequence tuple shape only ever holds further ``Node`` values, never plain strings.
|
|
94
|
+
|
|
95
|
+
Everything else that parsed without error becomes a plain extensible
|
|
96
|
+
:class:`~tree_engine.core.nodes.Node` of kind ``"<format_id>:<CamelCase(tree-sitter node type)>"``
|
|
97
|
+
(mirroring the ``"python:FunctionDef"``/``"bsl:<type>"`` convention already used by the other two
|
|
98
|
+
translators in this codebase -- see :func:`_camel_kind` for the exact, narrow transform and why a
|
|
99
|
+
handful of anonymous/punctuation token types are deliberately left untouched by it), carrying its
|
|
100
|
+
own raw content and buffer range, with every child -- including anonymous tokens: this plugin
|
|
101
|
+
converts the tree-sitter parse tree completely, not just its named subset -- mapped the same way,
|
|
102
|
+
recursively, so the whole tree is walkable to the leaf level.
|
|
103
|
+
|
|
104
|
+
Per {p104}-equivalent practice already established by the BSL translator: detecting
|
|
105
|
+
``has_error``/``ERROR``/``MISSING`` nodes and choosing between ``FORMAT_CONTENT_PARSE_FAILED`` and
|
|
106
|
+
``FORMAT_FRAGMENT_PARSE_FAILED`` is this module's own responsibility (tree-sitter propagates
|
|
107
|
+
``has_error`` up through every ancestor of any ``ERROR``/``MISSING`` descendant, so a single check
|
|
108
|
+
on the node handed to :func:`import_to_common` is sufficient); this module never synthesizes a
|
|
109
|
+
partial common-model tree from a damaged one.
|
|
110
|
+
|
|
111
|
+
Node identity: every node this module returns carries a fresh UUID4 ``node_id`` and a positive,
|
|
112
|
+
monotonically increasing (within one process; short_id is document-local per {p097} so this need
|
|
113
|
+
not restart at 1 across documents) ``short_id``, assigned at the single :meth:`_Converter.convert`
|
|
114
|
+
dispatch point every mapped node passes through -- mirroring
|
|
115
|
+
``tree_engine.plugins.bsl.import_map``'s own ``_convert``/``_with_identity`` shape -- with one
|
|
116
|
+
documented exception: nodes built by :meth:`_Converter._build_elif_branch` are stamped inline by
|
|
117
|
+
that method itself, since ``preproc_elif``/``preproc_else`` tree-sitter nodes are consumed entirely
|
|
118
|
+
inside :meth:`_Converter._build_conditional_group` and never independently reach the main
|
|
119
|
+
``convert`` dispatch (they are always absorbed into their enclosing ``PreprocConditionalGroup``,
|
|
120
|
+
never left as standalone top-level nodes in the mapped tree).
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
from __future__ import annotations
|
|
124
|
+
|
|
125
|
+
import dataclasses
|
|
126
|
+
import itertools
|
|
127
|
+
import re
|
|
128
|
+
from typing import Any, Dict, FrozenSet, List, Mapping, Optional, Tuple, TYPE_CHECKING
|
|
129
|
+
|
|
130
|
+
from tree_engine.core.identity import generate_node_id
|
|
131
|
+
from tree_engine.core.nodes import Node, make_node
|
|
132
|
+
from tree_engine.errors import ErrorCode
|
|
133
|
+
from tree_engine.plugins.contract import FormatPluginContractError
|
|
134
|
+
|
|
135
|
+
if TYPE_CHECKING:
|
|
136
|
+
from tree_sitter import Node as TSNode
|
|
137
|
+
|
|
138
|
+
__all__ = ["import_to_common", "CppImportMap"]
|
|
139
|
+
|
|
140
|
+
# Document-local per {p097}; a single process-lifetime counter (never reset per parse) is fine
|
|
141
|
+
# because uniqueness only needs to hold WITHIN one document, exactly as
|
|
142
|
+
# ``tree_engine.plugins.bsl.import_map`` documents for the counter it reuses from
|
|
143
|
+
# ``tree_engine.core.node_types``. This plugin does not use any of those BSL-specific wrapper
|
|
144
|
+
# types, so it keeps its own counter rather than sharing one it has no other reason to touch.
|
|
145
|
+
_SHORT_ID_COUNTER = itertools.count(1)
|
|
146
|
+
|
|
147
|
+
_IDENT_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
|
|
148
|
+
|
|
149
|
+
_QUALIFIER_TOKENS: FrozenSet[str] = frozenset({"__global__", "__device__", "__host__"})
|
|
150
|
+
|
|
151
|
+
_UNDEF_DIRECTIVE = "#undef"
|
|
152
|
+
_ENDIF_TYPE = "#endif"
|
|
153
|
+
_PREPROC_ELIF_TYPE = "preproc_elif"
|
|
154
|
+
_PREPROC_ELSE_TYPE = "preproc_else"
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _contract_error(format_id: str, message: str, *, code: ErrorCode) -> FormatPluginContractError:
|
|
158
|
+
return FormatPluginContractError(plugin_id=format_id, error_code=code, message=message)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _camel_kind(node_type: str) -> str:
|
|
162
|
+
"""``tree-sitter node type -> CamelCase kind suffix``, narrowly.
|
|
163
|
+
|
|
164
|
+
Dunder-style tokens (``__global__`` and friends) are returned verbatim: splitting on ``_``
|
|
165
|
+
and capitalizing each non-empty piece would collapse ``__global__`` into ``Global``, silently
|
|
166
|
+
discarding the double-underscore convention from the KIND string (the ``content`` field still
|
|
167
|
+
carries the exact literal text regardless, so this is a readability choice, not a correctness
|
|
168
|
+
one). Anything else that is not a plain identifier-shaped token (punctuation/operators such as
|
|
169
|
+
``"{"``, ``";"``, ``"+"``, or literal directive spellings such as ``"#include"``) is also
|
|
170
|
+
returned verbatim, since CamelCasing would not do anything meaningful to it. An ordinary
|
|
171
|
+
snake_case grammar type name (``function_definition``, ``preproc_include``,
|
|
172
|
+
``translation_unit``, ...) becomes ``FunctionDefinition``/``PreprocInclude``/
|
|
173
|
+
``TranslationUnit``.
|
|
174
|
+
"""
|
|
175
|
+
|
|
176
|
+
if node_type.startswith("__") and node_type.endswith("__") and len(node_type) > 4:
|
|
177
|
+
return node_type
|
|
178
|
+
if not _IDENT_RE.match(node_type):
|
|
179
|
+
return node_type
|
|
180
|
+
parts = [part for part in node_type.split("_") if part]
|
|
181
|
+
if not parts:
|
|
182
|
+
return node_type
|
|
183
|
+
return "".join(part[:1].upper() + part[1:] for part in parts)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
class _Converter:
|
|
187
|
+
"""One conversion pass over one already-parsed tree-sitter tree, for one ``format_id``.
|
|
188
|
+
|
|
189
|
+
Stateless beyond ``format_id`` itself; a fresh instance is built per call to
|
|
190
|
+
:func:`import_to_common` (cheap: it holds nothing but a string).
|
|
191
|
+
"""
|
|
192
|
+
|
|
193
|
+
__slots__ = ("format_id",)
|
|
194
|
+
|
|
195
|
+
def __init__(self, format_id: str) -> None:
|
|
196
|
+
self.format_id = format_id
|
|
197
|
+
|
|
198
|
+
# -- text/identity helpers ------------------------------------------------
|
|
199
|
+
|
|
200
|
+
@staticmethod
|
|
201
|
+
def _text(ts_node: Optional["TSNode"]) -> str:
|
|
202
|
+
if ts_node is None:
|
|
203
|
+
return ""
|
|
204
|
+
raw = ts_node.text
|
|
205
|
+
return raw.decode("utf-8") if raw is not None else ""
|
|
206
|
+
|
|
207
|
+
@staticmethod
|
|
208
|
+
def _with_identity(node: Node) -> Node:
|
|
209
|
+
if node.node_id is not None and node.short_id is not None:
|
|
210
|
+
return node
|
|
211
|
+
return dataclasses.replace(
|
|
212
|
+
node,
|
|
213
|
+
node_id=node.node_id if node.node_id is not None else generate_node_id(),
|
|
214
|
+
short_id=node.short_id if node.short_id is not None else next(_SHORT_ID_COUNTER),
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
def _kind(self, suffix: str) -> str:
|
|
218
|
+
return f"{self.format_id}:{suffix}"
|
|
219
|
+
|
|
220
|
+
# -- the single recursive dispatch point -----------------------------------
|
|
221
|
+
|
|
222
|
+
def convert(self, ts_node: "TSNode") -> Node:
|
|
223
|
+
"""Map one tree-sitter node (and, recursively, its whole subtree) to a common-model
|
|
224
|
+
``Node``. The single choke point every mapped node passes through, per this module's
|
|
225
|
+
docstring."""
|
|
226
|
+
|
|
227
|
+
node_type = ts_node.type
|
|
228
|
+
if node_type == "preproc_include":
|
|
229
|
+
built = self._build_preproc_include(ts_node)
|
|
230
|
+
elif node_type == "preproc_def":
|
|
231
|
+
built = self._build_preproc_define_object(ts_node)
|
|
232
|
+
elif node_type == "preproc_function_def":
|
|
233
|
+
built = self._build_preproc_define_function(ts_node)
|
|
234
|
+
elif node_type == "preproc_call":
|
|
235
|
+
built = self._build_preproc_call(ts_node)
|
|
236
|
+
elif node_type in ("preproc_if", "preproc_ifdef"):
|
|
237
|
+
built = self._build_conditional_group(ts_node)
|
|
238
|
+
elif node_type == "kernel_call_syntax":
|
|
239
|
+
built = self._build_generic(ts_node, kind_override=self._kind("KernelLaunch"))
|
|
240
|
+
elif node_type == "function_definition":
|
|
241
|
+
built = self._build_function_definition(ts_node)
|
|
242
|
+
else:
|
|
243
|
+
built = self._build_generic(ts_node)
|
|
244
|
+
return self._with_identity(built)
|
|
245
|
+
|
|
246
|
+
# -- generic fallback -------------------------------------------------------
|
|
247
|
+
|
|
248
|
+
def _build_generic(
|
|
249
|
+
self,
|
|
250
|
+
ts_node: "TSNode",
|
|
251
|
+
*,
|
|
252
|
+
kind_override: Optional[str] = None,
|
|
253
|
+
extra_fields: Optional[Mapping[str, Any]] = None,
|
|
254
|
+
) -> Node:
|
|
255
|
+
kind = kind_override or self._kind(_camel_kind(ts_node.type))
|
|
256
|
+
children = tuple(self.convert(child) for child in ts_node.children)
|
|
257
|
+
fields: Dict[str, Any] = {"content": self._text(ts_node)}
|
|
258
|
+
if extra_fields:
|
|
259
|
+
fields.update(extra_fields)
|
|
260
|
+
node = make_node(kind, fields=fields, children=children)
|
|
261
|
+
return dataclasses.replace(node, buffer_range=(ts_node.start_byte, ts_node.end_byte))
|
|
262
|
+
|
|
263
|
+
# -- preprocessor: #include ---------------------------------------------------
|
|
264
|
+
|
|
265
|
+
def _build_preproc_include(self, ts_node: "TSNode") -> Node:
|
|
266
|
+
path_node = ts_node.child_by_field_name("path")
|
|
267
|
+
return self._build_generic(
|
|
268
|
+
ts_node,
|
|
269
|
+
kind_override=self._kind("PreprocInclude"),
|
|
270
|
+
extra_fields={"path": self._text(path_node)},
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
# -- preprocessor: object/function macros ------------------------------------
|
|
274
|
+
|
|
275
|
+
def _build_preproc_define_object(self, ts_node: "TSNode") -> Node:
|
|
276
|
+
name_node = ts_node.child_by_field_name("name")
|
|
277
|
+
value_node = ts_node.child_by_field_name("value")
|
|
278
|
+
return self._build_generic(
|
|
279
|
+
ts_node,
|
|
280
|
+
kind_override=self._kind("PreprocDefineObject"),
|
|
281
|
+
extra_fields={
|
|
282
|
+
"macro_name": self._text(name_node),
|
|
283
|
+
"raw_value": self._text(value_node),
|
|
284
|
+
},
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
def _build_preproc_define_function(self, ts_node: "TSNode") -> Node:
|
|
288
|
+
name_node = ts_node.child_by_field_name("name")
|
|
289
|
+
params_node = ts_node.child_by_field_name("parameters")
|
|
290
|
+
value_node = ts_node.child_by_field_name("value")
|
|
291
|
+
return self._build_generic(
|
|
292
|
+
ts_node,
|
|
293
|
+
kind_override=self._kind("PreprocDefineFunction"),
|
|
294
|
+
extra_fields={
|
|
295
|
+
"macro_name": self._text(name_node),
|
|
296
|
+
"raw_params": self._text(params_node),
|
|
297
|
+
"raw_value": self._text(value_node),
|
|
298
|
+
},
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
# -- preprocessor: #undef / #pragma / #error / #line / other -----------------
|
|
302
|
+
|
|
303
|
+
def _build_preproc_call(self, ts_node: "TSNode") -> Node:
|
|
304
|
+
directive_node = ts_node.child_by_field_name("directive")
|
|
305
|
+
argument_node = ts_node.child_by_field_name("argument")
|
|
306
|
+
directive_text = self._text(directive_node)
|
|
307
|
+
argument_text = self._text(argument_node)
|
|
308
|
+
if directive_text == _UNDEF_DIRECTIVE:
|
|
309
|
+
return self._build_generic(
|
|
310
|
+
ts_node,
|
|
311
|
+
kind_override=self._kind("PreprocUndef"),
|
|
312
|
+
extra_fields={"directive": directive_text, "macro_name": argument_text},
|
|
313
|
+
)
|
|
314
|
+
return self._build_generic(
|
|
315
|
+
ts_node,
|
|
316
|
+
kind_override=self._kind("PreprocCall"),
|
|
317
|
+
extra_fields={"directive": directive_text, "argument": argument_text},
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
# -- preprocessor: #if / #ifdef / #ifndef conditional groups ------------------
|
|
321
|
+
|
|
322
|
+
def _body_statements(self, ts_node: "TSNode", exclude_fields: FrozenSet[str]) -> Tuple[Node, ...]:
|
|
323
|
+
"""Every NAMED child of ``ts_node`` whose own field name (if any) is not in
|
|
324
|
+
``exclude_fields`` -- the group/branch's own body, in source order. Anonymous keyword
|
|
325
|
+
tokens (``#if``, `#elif``, ...) are excluded automatically by the ``is_named`` check, never
|
|
326
|
+
by name/type matching."""
|
|
327
|
+
|
|
328
|
+
statements: List[Node] = []
|
|
329
|
+
for index, child in enumerate(ts_node.children):
|
|
330
|
+
if not child.is_named:
|
|
331
|
+
continue
|
|
332
|
+
field_name = ts_node.field_name_for_child(index)
|
|
333
|
+
if field_name in exclude_fields:
|
|
334
|
+
continue
|
|
335
|
+
statements.append(self.convert(child))
|
|
336
|
+
return tuple(statements)
|
|
337
|
+
|
|
338
|
+
@staticmethod
|
|
339
|
+
def _slice_prefix(ts_node: "TSNode", end_byte: int) -> str:
|
|
340
|
+
"""``ts_node``'s own text, truncated to ``[ts_node.start_byte, end_byte)`` -- ``end_byte``
|
|
341
|
+
must not exceed ``ts_node.end_byte``. Used to end a ``PreprocElifBranch``'s own
|
|
342
|
+
``content``/``buffer_range`` at the START of its ``alternative`` child instead of at its
|
|
343
|
+
own (grammar-nested) ``end_byte``, which -- see :meth:`_build_conditional_group` -- would
|
|
344
|
+
otherwise still include the REST of the chain (every later ``#elif``/``#else``, since
|
|
345
|
+
tree-sitter nests each successive branch inside the previous one's own span). Slicing
|
|
346
|
+
``ts_node.text`` itself (rather than re-deriving from an external byte buffer this class
|
|
347
|
+
does not hold a reference to) keeps this a one-line operation with no new state."""
|
|
348
|
+
|
|
349
|
+
raw = ts_node.text
|
|
350
|
+
if raw is None:
|
|
351
|
+
return ""
|
|
352
|
+
return raw[: end_byte - ts_node.start_byte].decode("utf-8")
|
|
353
|
+
|
|
354
|
+
def _build_elif_branch(self, ts_node: "TSNode", span_end: int) -> Node:
|
|
355
|
+
"""One ``preproc_elif`` -> one ``PreprocElifBranch``, whose span/``content`` end at
|
|
356
|
+
``span_end`` (the start of its own ``alternative`` child, or its own natural
|
|
357
|
+
``end_byte`` for the last branch of a chain -- see the caller,
|
|
358
|
+
:meth:`_build_conditional_group`, for why this matters: WITHOUT it, sibling branches'
|
|
359
|
+
reported spans nest inside one another instead of sitting disjoint, since tree-sitter
|
|
360
|
+
itself nests each successive ``#elif``/``#else`` inside the previous one's own span).
|
|
361
|
+
Not reached through :meth:`convert` (see the module docstring's identity note): stamped
|
|
362
|
+
with identity inline, here."""
|
|
363
|
+
|
|
364
|
+
condition_node = ts_node.child_by_field_name("condition")
|
|
365
|
+
condition_text = self._text(condition_node)
|
|
366
|
+
body = self._body_statements(ts_node, frozenset({"condition", "alternative"}))
|
|
367
|
+
condition_children = (self.convert(condition_node),) if condition_node is not None else ()
|
|
368
|
+
children = condition_children + body
|
|
369
|
+
fields = {
|
|
370
|
+
"content": self._slice_prefix(ts_node, span_end),
|
|
371
|
+
"condition": condition_text,
|
|
372
|
+
"body": body,
|
|
373
|
+
}
|
|
374
|
+
node = make_node(self._kind("PreprocElifBranch"), fields=fields, children=children)
|
|
375
|
+
node = dataclasses.replace(node, buffer_range=(ts_node.start_byte, span_end))
|
|
376
|
+
return self._with_identity(node)
|
|
377
|
+
|
|
378
|
+
def _build_conditional_group(self, ts_node: "TSNode") -> Node:
|
|
379
|
+
# ``keyword``/``endif_text`` are normalized to the grammar's own CANONICAL token spelling
|
|
380
|
+
# (``child.type``, e.g. always exactly ``"#if"``/``"#endif"``) rather than that token's own
|
|
381
|
+
# raw text (``self._text(child)``): a directive is still valid C/C++ with whitespace
|
|
382
|
+
# between the ``#`` and the keyword (``"# if"``, ``"#\tendif"``), which tree-sitter still
|
|
383
|
+
# lexes as ONE anonymous token whose `.text` would then carry that inner whitespace -- but
|
|
384
|
+
# whose `.type` is unaffected by it. The group's own `content` field is unaffected by this
|
|
385
|
+
# choice either way (it is always the exact raw slice of the WHOLE group), so choosing to
|
|
386
|
+
# normalize here loses no byte -- it only keeps `keyword`/`endif_text` predictable for a
|
|
387
|
+
# caller comparing them against a literal `"#if"`/`"#endif"` rather than needing to
|
|
388
|
+
# `.strip()` or regex-match an unbounded amount of embedded whitespace first.
|
|
389
|
+
keyword_text = ts_node.children[0].type if ts_node.children else ""
|
|
390
|
+
condition_node = ts_node.child_by_field_name("condition") or ts_node.child_by_field_name("name")
|
|
391
|
+
condition_text = self._text(condition_node)
|
|
392
|
+
then_branch = self._body_statements(
|
|
393
|
+
ts_node, frozenset({"condition", "name", "alternative"})
|
|
394
|
+
)
|
|
395
|
+
|
|
396
|
+
elif_branches: List[Node] = []
|
|
397
|
+
else_branch: Tuple[Node, ...] = ()
|
|
398
|
+
saw_else = False
|
|
399
|
+
cursor = ts_node.child_by_field_name("alternative")
|
|
400
|
+
while cursor is not None:
|
|
401
|
+
if cursor.type == _PREPROC_ELIF_TYPE:
|
|
402
|
+
next_alternative = cursor.child_by_field_name("alternative")
|
|
403
|
+
# Disjoint sibling spans (see _build_elif_branch/_slice_prefix): this branch ends
|
|
404
|
+
# exactly where the NEXT link of the chain begins, or at its own natural end_byte
|
|
405
|
+
# when it is the chain's last elif (which tree-sitter already reports correctly,
|
|
406
|
+
# since nothing is nested inside it in that case).
|
|
407
|
+
span_end = next_alternative.start_byte if next_alternative is not None else cursor.end_byte
|
|
408
|
+
elif_branches.append(self._build_elif_branch(cursor, span_end))
|
|
409
|
+
cursor = next_alternative
|
|
410
|
+
elif cursor.type == _PREPROC_ELSE_TYPE:
|
|
411
|
+
saw_else = True
|
|
412
|
+
else_branch = self._body_statements(cursor, frozenset())
|
|
413
|
+
cursor = None
|
|
414
|
+
else: # pragma: no cover - defensive; the grammar never emits anything else here
|
|
415
|
+
cursor = None
|
|
416
|
+
|
|
417
|
+
endif_text = ""
|
|
418
|
+
if ts_node.children and not ts_node.children[-1].is_named:
|
|
419
|
+
trailing = ts_node.children[-1]
|
|
420
|
+
if trailing.type == _ENDIF_TYPE:
|
|
421
|
+
endif_text = trailing.type
|
|
422
|
+
|
|
423
|
+
condition_children = (self.convert(condition_node),) if condition_node is not None else ()
|
|
424
|
+
children = condition_children + then_branch + tuple(elif_branches) + else_branch
|
|
425
|
+
|
|
426
|
+
fields = {
|
|
427
|
+
"content": self._text(ts_node),
|
|
428
|
+
"keyword": keyword_text,
|
|
429
|
+
"condition": condition_text,
|
|
430
|
+
"then_branch": then_branch,
|
|
431
|
+
"elif_branches": tuple(elif_branches),
|
|
432
|
+
"has_else": saw_else,
|
|
433
|
+
"else_branch": else_branch,
|
|
434
|
+
"endif_text": endif_text,
|
|
435
|
+
}
|
|
436
|
+
node = make_node(self._kind("PreprocConditionalGroup"), fields=fields, children=children)
|
|
437
|
+
node = dataclasses.replace(node, buffer_range=(ts_node.start_byte, ts_node.end_byte))
|
|
438
|
+
return self._with_identity(node)
|
|
439
|
+
|
|
440
|
+
# -- function definitions: CUDA execution-space qualifiers ---------------------
|
|
441
|
+
|
|
442
|
+
def _build_function_definition(self, ts_node: "TSNode") -> Node:
|
|
443
|
+
# ``Node.fields``' ordered-child-sequence tuple shape (see
|
|
444
|
+
# ``tree_engine.core.nodes.FieldValue``) only ever holds ``Node`` entries, never plain
|
|
445
|
+
# strings, so the qualifier list -- there is at most a small, fixed handful of these on
|
|
446
|
+
# any one function, per {_QUALIFIER_TOKENS} -- is encoded as one space-joined ``str``
|
|
447
|
+
# field instead (empty string when none apply, the ordinary case for c/cpp and most cuda
|
|
448
|
+
# functions too).
|
|
449
|
+
qualifiers = tuple(
|
|
450
|
+
child.type
|
|
451
|
+
for child in ts_node.children
|
|
452
|
+
if not child.is_named and child.type in _QUALIFIER_TOKENS
|
|
453
|
+
)
|
|
454
|
+
return self._build_generic(ts_node, extra_fields={"qualifiers": " ".join(qualifiers)})
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def import_to_common(
|
|
458
|
+
external_representation: "TSNode",
|
|
459
|
+
options: Optional[Mapping[str, Any]] = None,
|
|
460
|
+
*,
|
|
461
|
+
format_id: str,
|
|
462
|
+
fragment: bool = False,
|
|
463
|
+
) -> Node:
|
|
464
|
+
"""Translate an already-parsed tree-sitter node (a document's root, or any subtree) into a
|
|
465
|
+
common-model ``Node``, for ``format_id`` in ``("c", "cpp", "cuda")``.
|
|
466
|
+
|
|
467
|
+
Raises :class:`~tree_engine.plugins.contract.FormatPluginContractError` -- carrying
|
|
468
|
+
``FORMAT_FRAGMENT_PARSE_FAILED`` when ``fragment=True``, ``FORMAT_CONTENT_PARSE_FAILED``
|
|
469
|
+
otherwise -- when ``external_representation`` itself reports ``has_error`` (tree-sitter
|
|
470
|
+
propagates this up through every ancestor of any ``ERROR``/``MISSING`` descendant, so this one
|
|
471
|
+
check catches damage anywhere in the subtree). ``options`` is accepted for contract-signature
|
|
472
|
+
compatibility and is currently unused.
|
|
473
|
+
"""
|
|
474
|
+
|
|
475
|
+
if getattr(external_representation, "has_error", False):
|
|
476
|
+
code = ErrorCode.FORMAT_FRAGMENT_PARSE_FAILED if fragment else ErrorCode.FORMAT_CONTENT_PARSE_FAILED
|
|
477
|
+
raise _contract_error(
|
|
478
|
+
format_id,
|
|
479
|
+
f"tree-sitter-{format_id} parse tree contains an ERROR or MISSING node; "
|
|
480
|
+
"refusing to map a partial tree",
|
|
481
|
+
code=code,
|
|
482
|
+
)
|
|
483
|
+
return _Converter(format_id).convert(external_representation)
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
class CppImportMap:
|
|
487
|
+
"""Import (tree-sitter -> common model) stage shared by the c/cpp/cuda plugins.
|
|
488
|
+
|
|
489
|
+
Thin object wrapper around the module-level :func:`import_to_common`, mirroring
|
|
490
|
+
``tree_engine.plugins.bsl.import_map.BSLImportMap``'s own shape.
|
|
491
|
+
"""
|
|
492
|
+
|
|
493
|
+
def __init__(self, format_id: str) -> None:
|
|
494
|
+
self.format_id = format_id
|
|
495
|
+
|
|
496
|
+
def import_to_common(
|
|
497
|
+
self,
|
|
498
|
+
external_representation: "TSNode",
|
|
499
|
+
options: Optional[Mapping[str, Any]] = None,
|
|
500
|
+
*,
|
|
501
|
+
fragment: bool = False,
|
|
502
|
+
) -> Node:
|
|
503
|
+
return import_to_common(
|
|
504
|
+
external_representation, options, format_id=self.format_id, fragment=fragment
|
|
505
|
+
)
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Grammar dispatch for the three format ids this plugin package serves.
|
|
2
|
+
|
|
3
|
+
Scope: this module owns the one place that decides which tree-sitter grammar backs which
|
|
4
|
+
format id, and the one place a fresh ``tree_sitter.Parser``/``Language`` pair is built to run one
|
|
5
|
+
parse. It knows nothing about the common tree model; :mod:`tree_engine.plugins.cpp.import_map`
|
|
6
|
+
consumes ``parse_bytes``'s return value.
|
|
7
|
+
|
|
8
|
+
Fresh-Parser-per-parse, deliberately: ``tree_engine.plugins.bsl.plugin._parse_bytes`` documents a
|
|
9
|
+
measured gotcha in this environment (tree-sitter 0.25.x) where reusing one ``Parser`` instance
|
|
10
|
+
across multiple ``parse()`` calls silently corrupted byte offsets on the second and later calls.
|
|
11
|
+
The same defensive pattern is used here for all three grammars: never cache or share a ``Parser``
|
|
12
|
+
(or the ``Language`` object wrapping a grammar) across calls.
|
|
13
|
+
|
|
14
|
+
Why three grammars, not one: tree-sitter-cpp does not understand CUDA's ``<<<...>>>`` kernel-
|
|
15
|
+
launch syntax -- it tokenizes ``<<<``/`>>>`` as nested left/right-shift operators, so a ``.cu``
|
|
16
|
+
file must go through tree-sitter-cuda, never tree-sitter-cpp, to get a real ``kernel_call_syntax``
|
|
17
|
+
node instead of a garbled binary-expression parse (or an outright ``ERROR`` node, depending on the
|
|
18
|
+
surrounding expression). ``.c``/``.h`` use tree-sitter-c and ``.cc``/``.cpp``/``.cxx``/``.hpp``/
|
|
19
|
+
``.hh`` use tree-sitter-cpp; both grammars share the same preprocessor-directive node shapes
|
|
20
|
+
(``preproc_include``, ``preproc_def``, ``preproc_function_def``, ``preproc_call``, ``preproc_if``,
|
|
21
|
+
``preproc_ifdef``, ``preproc_elif``, ``preproc_else`` -- with the same field names on each), which
|
|
22
|
+
is what lets :mod:`import_map` handle all three languages through one dispatch table instead of
|
|
23
|
+
three near-duplicate copies.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
from typing import Any, Dict, Tuple
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"FORMAT_C",
|
|
32
|
+
"FORMAT_CPP",
|
|
33
|
+
"FORMAT_CUDA",
|
|
34
|
+
"SUPPORTED_FORMATS",
|
|
35
|
+
"file_extensions",
|
|
36
|
+
"parse_bytes",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
FORMAT_C = "c"
|
|
40
|
+
FORMAT_CPP = "cpp"
|
|
41
|
+
FORMAT_CUDA = "cuda"
|
|
42
|
+
|
|
43
|
+
SUPPORTED_FORMATS: Tuple[str, ...] = (FORMAT_C, FORMAT_CPP, FORMAT_CUDA)
|
|
44
|
+
|
|
45
|
+
#: File extensions per format id, WITHOUT the leading dot -- the same shape
|
|
46
|
+
#: ``DetachablePluginSpec.file_extensions``/``FormatPluginMetadata.file_extensions`` use elsewhere
|
|
47
|
+
#: in this codebase (see ``tree_engine.plugins.detachable``).
|
|
48
|
+
_FILE_EXTENSIONS: Dict[str, Tuple[str, ...]] = {
|
|
49
|
+
FORMAT_C: ("c", "h"),
|
|
50
|
+
FORMAT_CPP: ("cc", "cpp", "cxx", "hpp", "hh"),
|
|
51
|
+
FORMAT_CUDA: ("cu", "cuh"),
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def file_extensions(format_id: str) -> Tuple[str, ...]:
|
|
56
|
+
"""The file extensions this plugin package registers for ``format_id``."""
|
|
57
|
+
|
|
58
|
+
return _FILE_EXTENSIONS[format_id]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _grammar_module(format_id: str) -> Any:
|
|
62
|
+
"""Import (lazily -- never at this module's own import time) and return the
|
|
63
|
+
``tree_sitter_c``/``tree_sitter_cpp``/``tree_sitter_cuda`` module backing ``format_id``.
|
|
64
|
+
|
|
65
|
+
Deferred import keeps this whole plugin package importable on a machine that has none of the
|
|
66
|
+
three grammars installed -- exactly the property ``tree_engine.plugins.detachable`` relies on
|
|
67
|
+
to classify the format as DETACHED rather than raising an ``ImportError`` out of a module-level
|
|
68
|
+
import, per that module's own docstring.
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
if format_id == FORMAT_C:
|
|
72
|
+
import tree_sitter_c
|
|
73
|
+
|
|
74
|
+
return tree_sitter_c
|
|
75
|
+
if format_id == FORMAT_CPP:
|
|
76
|
+
import tree_sitter_cpp
|
|
77
|
+
|
|
78
|
+
return tree_sitter_cpp
|
|
79
|
+
if format_id == FORMAT_CUDA:
|
|
80
|
+
import tree_sitter_cuda
|
|
81
|
+
|
|
82
|
+
return tree_sitter_cuda
|
|
83
|
+
raise ValueError(f"unsupported cpp-family format_id {format_id!r}, expected one of {SUPPORTED_FORMATS}")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def parse_bytes(format_id: str, source_bytes: bytes) -> Any:
|
|
87
|
+
"""Parse ``source_bytes`` with ``format_id``'s pinned grammar and return the tree's root node.
|
|
88
|
+
|
|
89
|
+
A brand-new ``Parser`` (and ``Language``) is built for this one call and discarded immediately
|
|
90
|
+
after use -- see this module's docstring for why that is load-bearing, not incidental, in this
|
|
91
|
+
environment.
|
|
92
|
+
"""
|
|
93
|
+
|
|
94
|
+
from tree_sitter import Language, Parser
|
|
95
|
+
|
|
96
|
+
module = _grammar_module(format_id)
|
|
97
|
+
parser = Parser(Language(module.language()))
|
|
98
|
+
tree = parser.parse(source_bytes)
|
|
99
|
+
return tree.root_node
|