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.
Files changed (121) hide show
  1. ai_editor_tree_engine_dev-1.0.176.dist-info/METADATA +35 -0
  2. ai_editor_tree_engine_dev-1.0.176.dist-info/RECORD +121 -0
  3. ai_editor_tree_engine_dev-1.0.176.dist-info/WHEEL +5 -0
  4. ai_editor_tree_engine_dev-1.0.176.dist-info/licenses/LICENSE +21 -0
  5. ai_editor_tree_engine_dev-1.0.176.dist-info/top_level.txt +1 -0
  6. tree_engine/PUBLIC_API.md +161 -0
  7. tree_engine/__init__.py +327 -0
  8. tree_engine/checks/__init__.py +60 -0
  9. tree_engine/checks/builtin/__init__.py +5 -0
  10. tree_engine/checks/builtin/compile_check.py +53 -0
  11. tree_engine/checks/builtin/csv_syntax.py +51 -0
  12. tree_engine/checks/builtin/docstrings.py +211 -0
  13. tree_engine/checks/builtin/encoding.py +55 -0
  14. tree_engine/checks/builtin/fleet_rules.py +227 -0
  15. tree_engine/checks/builtin/format_syntax.py +82 -0
  16. tree_engine/checks/builtin/jsonl_syntax.py +49 -0
  17. tree_engine/checks/builtin/shipped.py +52 -0
  18. tree_engine/checks/builtin/syntax.py +118 -0
  19. tree_engine/checks/builtin/xml_wellformed.py +51 -0
  20. tree_engine/checks/chain.py +332 -0
  21. tree_engine/checks/external/__init__.py +5 -0
  22. tree_engine/checks/external/_base.py +61 -0
  23. tree_engine/checks/external/bandit.py +53 -0
  24. tree_engine/checks/external/black.py +48 -0
  25. tree_engine/checks/external/flake8.py +38 -0
  26. tree_engine/checks/external/isort.py +38 -0
  27. tree_engine/checks/external/mypy.py +45 -0
  28. tree_engine/checks/external/ruff.py +45 -0
  29. tree_engine/checks/external/runner.py +197 -0
  30. tree_engine/checks/model.py +110 -0
  31. tree_engine/checks/options.py +73 -0
  32. tree_engine/checks/plugin.py +171 -0
  33. tree_engine/checks/registry.py +349 -0
  34. tree_engine/core/address.py +376 -0
  35. tree_engine/core/identifier_map.py +266 -0
  36. tree_engine/core/identity.py +226 -0
  37. tree_engine/core/instrumentation.py +399 -0
  38. tree_engine/core/integrity.py +341 -0
  39. tree_engine/core/integrity_full.py +382 -0
  40. tree_engine/core/journal.py +260 -0
  41. tree_engine/core/journal_compose.py +571 -0
  42. tree_engine/core/live_tree.py +785 -0
  43. tree_engine/core/locking.py +188 -0
  44. tree_engine/core/move.py +585 -0
  45. tree_engine/core/move_references.py +323 -0
  46. tree_engine/core/node_types.py +408 -0
  47. tree_engine/core/nodes.py +348 -0
  48. tree_engine/core/offsets.py +24 -0
  49. tree_engine/core/operations.py +825 -0
  50. tree_engine/core/plugin_boundary.py +160 -0
  51. tree_engine/core/position_map.py +263 -0
  52. tree_engine/core/position_transfer.py +512 -0
  53. tree_engine/core/range_refresh.py +366 -0
  54. tree_engine/core/reference_cache.py +360 -0
  55. tree_engine/core/references.py +223 -0
  56. tree_engine/core/reparse.py +378 -0
  57. tree_engine/core/short_id.py +296 -0
  58. tree_engine/core/subtree_apply.py +397 -0
  59. tree_engine/core/subtree_copy.py +399 -0
  60. tree_engine/core/transactions.py +397 -0
  61. tree_engine/core/trivia.py +396 -0
  62. tree_engine/core/updates.py +398 -0
  63. tree_engine/core/validation.py +377 -0
  64. tree_engine/errors.py +104 -0
  65. tree_engine/exceptions.py +376 -0
  66. tree_engine/facade.py +4524 -0
  67. tree_engine/plugins/_statements.py +369 -0
  68. tree_engine/plugins/bsl/block_edit.py +449 -0
  69. tree_engine/plugins/bsl/blocks.py +127 -0
  70. tree_engine/plugins/bsl/checker.py +297 -0
  71. tree_engine/plugins/bsl/dialects.py +303 -0
  72. tree_engine/plugins/bsl/generator.py +481 -0
  73. tree_engine/plugins/bsl/import_map.py +995 -0
  74. tree_engine/plugins/bsl/plugin.py +452 -0
  75. tree_engine/plugins/contract.py +355 -0
  76. tree_engine/plugins/cpp/import_map.py +505 -0
  77. tree_engine/plugins/cpp/languages.py +99 -0
  78. tree_engine/plugins/cpp/plugin.py +501 -0
  79. tree_engine/plugins/csv_format.py +676 -0
  80. tree_engine/plugins/detachable.py +156 -0
  81. tree_engine/plugins/fallback.py +421 -0
  82. tree_engine/plugins/ini_format.py +330 -0
  83. tree_engine/plugins/json_format.py +813 -0
  84. tree_engine/plugins/json_pointer.py +203 -0
  85. tree_engine/plugins/jsonl_format.py +392 -0
  86. tree_engine/plugins/markdown_format.py +748 -0
  87. tree_engine/plugins/onec_query_format.py +61 -0
  88. tree_engine/plugins/parse_position.py +54 -0
  89. tree_engine/plugins/plain_text.py +1543 -0
  90. tree_engine/plugins/python/export_map.py +306 -0
  91. tree_engine/plugins/python/import_map.py +429 -0
  92. tree_engine/plugins/python/plugin.py +1710 -0
  93. tree_engine/plugins/registry.py +497 -0
  94. tree_engine/plugins/scan.py +87 -0
  95. tree_engine/plugins/selection.py +228 -0
  96. tree_engine/plugins/sql_format.py +61 -0
  97. tree_engine/plugins/toml_format.py +1072 -0
  98. tree_engine/plugins/xml_format.py +911 -0
  99. tree_engine/plugins/yaml/builder.py +49 -0
  100. tree_engine/plugins/yaml/emitter.py +225 -0
  101. tree_engine/plugins/yaml/flow.py +227 -0
  102. tree_engine/plugins/yaml/plugin.py +458 -0
  103. tree_engine/plugins/yaml/ranges.py +52 -0
  104. tree_engine/plugins/yaml/reader.py +359 -0
  105. tree_engine/plugins/yaml/scanner.py +298 -0
  106. tree_engine/query/adapter.py +283 -0
  107. tree_engine/query/engine.py +853 -0
  108. tree_engine/query/inspection.py +498 -0
  109. tree_engine/query/outline.py +288 -0
  110. tree_engine/query/predicates.py +263 -0
  111. tree_engine/query/rendered_lines.py +46 -0
  112. tree_engine/query/results.py +206 -0
  113. tree_engine/query/selector.py +400 -0
  114. tree_engine/query/xml_query.py +747 -0
  115. tree_engine/storage/codec.py +400 -0
  116. tree_engine/storage/document_bridge.py +579 -0
  117. tree_engine/storage/file_txn.py +459 -0
  118. tree_engine/storage/history.py +106 -0
  119. tree_engine/storage/lifecycle.py +622 -0
  120. tree_engine/storage/schema.py +403 -0
  121. tree_engine/storage/session_guard.py +398 -0
@@ -0,0 +1,1710 @@
1
+ """The Python format plugin object itself (concept C-014, atomic step A-003).
2
+
3
+ Scope: this module is the join point between the two already-merged pipeline
4
+ halves -- ``import_map.PythonImportMap`` (LibCST -> common model) and
5
+ ``export_map.PythonExportMap`` (common model -> LibCST -> bytes/str) -- and
6
+ the two shared plugin interfaces: ``tree_engine.plugins.contract.FormatPluginContract``
7
+ and ``tree_engine.core.plugin_boundary.FormatBoundary``. It performs no
8
+ conversion of its own: every field/trivia/byte-range mapping stays exactly
9
+ where the merged halves put it; this file only wires entry points, parses
10
+ source into a temporary LibCST tree (via ``libcst.parse_module`` for a full
11
+ document, ``libcst.parse_statement``/``libcst.parse_expression`` for a
12
+ fragment) and hands that tree to ``PythonImportMap.import_to_common``, and
13
+ publishes the plugin's static identity and semantic-role surface.
14
+
15
+ Two ABCs, one class: ``FormatPluginContract`` and ``FormatBoundary`` each
16
+ declare an abstractmethod literally named ``parse_document`` (and, likewise,
17
+ ``parse_fragment``) with different call conventions -- ``(source, options)``
18
+ positional for the contract, ``(source, *, source_format_id)`` for the core
19
+ boundary. ``PythonFormatPlugin`` below satisfies both with one concrete
20
+ method per name whose signature is a superset of both call conventions
21
+ (``options`` positional-or-omitted, ``source_format_id`` keyword-or-omitted);
22
+ Python's ABC machinery tracks abstractness by method *name*, so one concrete
23
+ override clears the abstractness of that name on every base that declared it.
24
+
25
+ LibCST exposure: the standard pipeline (``parse_document``, ``parse_fragment``,
26
+ ``import_to_common``, ``import_external_tree``, ``export_from_common``,
27
+ ``generate_output``, ``render_document``, ``render_fragment``) never returns
28
+ or accepts a live LibCST object -- only common-model ``Node``/``Document``,
29
+ primitives, or generated ``bytes``/``str``. ``import_tree``/``export_tree``
30
+ are the one deliberate, documented exception {p048}: they are the bridge for
31
+ a caller that already has (or wants back) a real ``libcst.Module``/``CSTNode``,
32
+ exactly as the merged ``import_map.import_tree``/``export_map.export_tree``
33
+ functions they delegate to already document and implement.
34
+
35
+ Semantic roles: ``semantic_role_mapping()`` publishes the context-free,
36
+ declarative kind -> role table (``FormatPluginContract``'s required shape:
37
+ one role per node-type string) for the three kinds that need no structural
38
+ context -- ``python:Module`` -> module, ``python:ClassDef`` -> class,
39
+ ``python:FunctionDef`` -> function. A ``FunctionDef`` nested in a ``ClassDef``
40
+ is still, by LibCST's own shape, a ``python:FunctionDef`` node -- the same
41
+ kind string as a top-level function -- so no flat kind -> role dict can also
42
+ route it to "method" without contradicting itself on the very same key.
43
+ :meth:`PythonFormatPlugin.role_for` is the per-instance resolver the query
44
+ engine uses instead: given a node and its ancestor chain (nearest parent
45
+ first), it promotes a ``FunctionDef`` to method when the nearest enclosing
46
+ ``ClassDef``/``FunctionDef`` ancestor is a ``ClassDef``.
47
+
48
+ Source-of-truth requirement labels honored here: {p048}, {p056}, {p057}, {p102}, {p103}.
49
+ """
50
+
51
+ from __future__ import annotations
52
+
53
+ import ast
54
+ import inspect
55
+ import logging
56
+ import textwrap
57
+ import threading
58
+ from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union
59
+
60
+ import libcst
61
+
62
+ from tree_engine.core.live_tree import LiveNode, clone_live_subtree, to_frozen, walk
63
+ from tree_engine.core.nodes import Document, Node
64
+ from tree_engine.core.plugin_boundary import FormatBoundary
65
+ from tree_engine.errors import ErrorCode
66
+ from tree_engine.plugins.contract import (
67
+ FormatPluginContract,
68
+ FormatPluginContractError,
69
+ FormatPluginMetadata,
70
+ SemanticRole,
71
+ SemanticRoleMapping,
72
+ )
73
+ from tree_engine.plugins.detachable import PYTHON_PLUGIN_SPEC
74
+ from tree_engine.plugins.python import export_map as _export_map
75
+ from tree_engine.plugins.python import import_map as _import_map
76
+ from tree_engine.plugins.python.export_map import PythonExportMap
77
+ from tree_engine.plugins.python.import_map import FORMAT_ID, PythonImportMap
78
+
79
+ __all__ = [
80
+ "FORMAT_ID",
81
+ "PythonFormatPlugin",
82
+ "PYTHON_FORMAT_PLUGIN",
83
+ ]
84
+
85
+ _MODULE_KIND = f"{FORMAT_ID}:Module"
86
+ _CLASSDEF_KIND = f"{FORMAT_ID}:ClassDef"
87
+ _FUNCTIONDEF_KIND = f"{FORMAT_ID}:FunctionDef"
88
+ _INDENTED_BLOCK_KIND = f"{FORMAT_ID}:IndentedBlock"
89
+ _SIMPLE_STRING_KIND = f"{FORMAT_ID}:SimpleString"
90
+ _NAME_KIND = f"{FORMAT_ID}:Name"
91
+ _IMPORTFROM_KIND = f"{FORMAT_ID}:ImportFrom"
92
+ _KIND_PREFIX = f"{FORMAT_ID}:"
93
+
94
+ # The local (post-prefix) kind names ``import_map._convert_value`` mints for
95
+ # a synthetic marker node -- a ``MaybeSentinel.DEFAULT`` field value or a
96
+ # bare primitive inside a node sequence -- neither of which is a real LibCST
97
+ # construct at all (LibCST's own ``CSTNode.children`` property never yields
98
+ # one either). S6a verifier findings #4/#6: this package's own query
99
+ # traversal (``ordered_children_for`` below) drops these entirely, so
100
+ # neither counts toward a match nor breaks ``include_source`` (rendering one
101
+ # through ``export_from_common`` is meaningless -- it names no source span).
102
+ _MARKER_LOCAL_KINDS = frozenset({"$sentinel", "$scalar"})
103
+
104
+ # LibCST's own field, present on every statement-shaped node (``SimpleStatementLine``,
105
+ # ``BaseCompoundStatement`` -- ``FunctionDef``/``ClassDef``/``If``/... included): the blank
106
+ # lines (and any standalone comments among them) that separate a statement from whatever comes
107
+ # before it. This is POSITIONAL/SEPARATING trivia -- the document's own layout, not the
108
+ # statement's content -- exactly the role a ``json:Member``'s own ``leading`` field plays for a
109
+ # JSON object member (see ``plugins/json_format.py``'s module docstring): it belongs to where
110
+ # the statement SITS, and a replacement fragment that starts right at the statement's own
111
+ # keyword (``def``, ``class``, ...) genuinely never carries it, the same way a JSON replacement
112
+ # value never carries its member's comma. See ``adjust_replace_fragment`` below.
113
+ _SEPARATING_TRIVIA_FIELD = "leading_lines"
114
+
115
+ _METADATA = FormatPluginMetadata(
116
+ format_id=FORMAT_ID,
117
+ aliases=(),
118
+ # From the detachable-plugin manifest, so the table the facade builds for this
119
+ # plugin while it is UNIMPORTABLE and the metadata it declares once present can
120
+ # never drift apart -- see plugins/detachable.py.
121
+ file_extensions=PYTHON_PLUGIN_SPEC.file_extensions,
122
+ plugin_version="1.0.0",
123
+ contract_version="1.0.0",
124
+ capabilities={
125
+ # Whether the Code Analysis server can save a file of this format (decision D-CB.4); the editor reads it
126
+ # instead of keeping its own list of unsupported suffixes.
127
+ "ca_save_supported": True,
128
+ "semantic_role_mapping": True,
129
+ "import_tree": True,
130
+ "export_tree": True,
131
+ # Measured: pipeline/checks/check_roundtrip.py's STRICT policy for
132
+ # python (LibCST) round-tripped the FULL real corpus (875/875
133
+ # tracked .py/.pyi files, no sampling) byte-identical, and the
134
+ # engine's emitted output stays black-formatted for every one of
135
+ # those files that was already black-formatted on disk
136
+ # (formatter-idempotence admission) -- True is honest.
137
+ "byte_identical_round_trip": True,
138
+ # Addressable, walkable common-model tree (LibCST-backed).
139
+ "navigable": True,
140
+ # Round trip is byte-identical and structural mutation via
141
+ # import_tree/export_tree plus export_from_common/generate_output
142
+ # is exercised elsewhere in this suite -- safe for write-back.
143
+ "editable": True,
144
+ },
145
+ )
146
+
147
+ _ROLE_MAP = SemanticRoleMapping(
148
+ {
149
+ _MODULE_KIND: SemanticRole.MODULE,
150
+ _CLASSDEF_KIND: SemanticRole.CLASS,
151
+ _FUNCTIONDEF_KIND: SemanticRole.FUNCTION,
152
+ }
153
+ )
154
+
155
+
156
+ def _contract_error(message: str) -> FormatPluginContractError:
157
+ return FormatPluginContractError(plugin_id=FORMAT_ID, message=message)
158
+
159
+
160
+ def _fields_of(node_like: Any) -> Optional[Mapping[str, Any]]:
161
+ """``node_like``'s own ``fields`` mapping, or ``None`` when it has
162
+ none -- the duck-typed check every query-parity hook uses instead of
163
+ ``isinstance(node_like, Node)`` (S6a verifier finding #1): a real,
164
+ facade-loaded document's tree is built from ``core.live_tree
165
+ .LiveNode``, a deliberately separate class from the immutable
166
+ ``core.nodes.Node`` this plugin also produces directly (e.g. from
167
+ ``parse_document`` called on its own, as the test suite's own
168
+ ``PythonFormatPlugin().parse_document(source)`` convention does) --
169
+ both carry a ``fields`` mapping (``LiveNode``'s a plain ``dict``,
170
+ ``Node``'s a ``MappingProxyType``), so checking for that shape
171
+ directly works for either without naming either concrete class.
172
+ """
173
+
174
+ fields = getattr(node_like, "fields", None)
175
+ return fields if isinstance(fields, Mapping) else None
176
+
177
+
178
+ # Pure syntactic whitespace/trivia LibCST kinds -- never carrying
179
+ # meaningful content of their own, always positioned strictly BEFORE or
180
+ # AFTER the content field their own name (``whitespace_before_X``/
181
+ # ``whitespace_after_X``/``lines_after_X``) names. Used only to break an
182
+ # exact (start, end) tie in :meth:`PythonFormatPlugin.ordered_children_for`
183
+ # (S6a verifier finding #4): when a genuinely EMPTY content node (e.g. a
184
+ # parameter-less ``Parameters``) lands at the same zero-width point as its
185
+ # own surrounding whitespace fields, the whitespace sorts first, matching
186
+ # LibCST's own real ``.children`` property (verified empirically).
187
+ _TRIVIA_LOCAL_KINDS = frozenset(
188
+ {"SimpleWhitespace", "ParenthesizedWhitespace", "TrailingWhitespace", "Newline"}
189
+ )
190
+
191
+
192
+ def _is_trivia_kind(node_like: Any) -> bool:
193
+ kind = str(getattr(node_like, "kind", ""))
194
+ local = kind.rpartition(":")[2] or kind
195
+ return local in _TRIVIA_LOCAL_KINDS
196
+
197
+
198
+ # Pure syntactic PUNCTUATION/CONNECTIVE LibCST kinds -- unlike trivia (above), these are not
199
+ # whitespace, but they still carry no independently addressable content of their own: each has
200
+ # exactly ONE fixed textual form for the syntax position it occupies (a comma is always ",", a
201
+ # dot always ".", an opening bracket always the same bracket character), so there is no
202
+ # alternative TEXT a caller could legitimately substitute in place of one. Verified empirically
203
+ # (bug 98478e1f follow-up, live probing against this branch's own facade.replace/delete):
204
+ # replacing one with arbitrary text does not fail -- the fragment parses as a standalone
205
+ # expression and splices in with no separating whitespace of its own -- it silently GLUES onto
206
+ # its neighbours instead (e.g. replacing the ``.`` in ``a.b`` with ``zz`` produces the single
207
+ # identifier ``azzb``, not a parse error), corrupting the document without ever raising.
208
+ #
209
+ # The LibCST operator-token base classes (``BaseBinaryOp``/``BaseBooleanOp``/``BaseCompOp``/
210
+ # ``BaseUnaryOp``/``BaseAugOp`` -- ``Add``, ``Sub``, ``And``, ``Or``, ``Equal``, ``Not``, ``AddAssign``,
211
+ # ...) are included for the SAME reason, confirmed the same way: replacing ``Add`` with arbitrary
212
+ # text (``zz``) silently glues (``a + b`` -> ``azzb``, no error), while replacing it with another
213
+ # BARE operator token (``-``, to swap in ``Sub``) is not even possible today -- ``facade.replace``
214
+ # raises ``FormatFragmentParseFailed`` cleanly, pre-mutation, because a bare operator token has no
215
+ # structure ``parse_fragment`` can parse as a standalone unit. So today there is no text that
216
+ # makes replacing one of these kinds a legitimate, safe edit either way: a real operator swap is
217
+ # refused cleanly (safe), and anything else corrupts silently (unsafe) -- this predicate refuses
218
+ # the unsafe half up front instead.
219
+ #
220
+ # ``$sentinel`` (this plugin's own import-map marker for LibCST's ``MaybeSentinel``, never a real
221
+ # LibCST class -- see ``import_map.py``) is included too: replacing it is a silent NO-OP (it is
222
+ # never rendered), which is not corruption but is not the requested edit either.
223
+ _NON_CONTENT_TOKEN_LOCAL_KINDS = frozenset(
224
+ {
225
+ "Comma", "Dot", "AssignEqual",
226
+ "LeftParen", "RightParen",
227
+ "LeftSquareBracket", "RightSquareBracket",
228
+ "LeftCurlyBrace", "RightCurlyBrace",
229
+ "Colon", "Semicolon",
230
+ "$sentinel",
231
+ }
232
+ )
233
+
234
+ _NON_CONTENT_TOKEN_BASE_CLASSES = (
235
+ libcst.BaseBinaryOp,
236
+ libcst.BaseBooleanOp,
237
+ libcst.BaseCompOp,
238
+ libcst.BaseUnaryOp,
239
+ libcst.BaseAugOp,
240
+ )
241
+
242
+
243
+ def _is_non_content_token_kind(node_like: Any) -> bool:
244
+ kind = str(getattr(node_like, "kind", ""))
245
+ local = kind.rpartition(":")[2] or kind
246
+ if local in _NON_CONTENT_TOKEN_LOCAL_KINDS:
247
+ return True
248
+ cst_cls = getattr(libcst, local, None)
249
+ return isinstance(cst_cls, type) and issubclass(cst_cls, _NON_CONTENT_TOKEN_BASE_CLASSES)
250
+
251
+
252
+ # Real ``_visit_and_replace_children`` field order (LibCST's own
253
+ # hand-written per-class traversal, which is what ``.children`` -- and so
254
+ # legacy's own ``build_index``, walking that exact property -- actually
255
+ # visits), for EVERY LibCST node class this process's own ``libcst`` module
256
+ # exposes -- not a per-class allowlist. A hand-picked exception list
257
+ # (``Del``/``AsName`` only, S6a verifier finding #4) already missed a real
258
+ # case (``ParamSlash``, PEP 570's ``def f(a, /, b)`` marker -- S6a Opus
259
+ # verifier residue, this fix) precisely because it depended on someone
260
+ # having read that one class's source; the same shape recurs wherever a
261
+ # field literally named ``whitespace_after_X``/``whitespace_before_X`` is
262
+ # declared/visited on the OPPOSITE side of a positioned sibling field from
263
+ # where it sits in the byte stream (``ParamSpec``/``TypeVarTuple``, PEP
264
+ # 695's ``**P``/``*Ts`` type-parameter markers, are two more instances of
265
+ # the exact same shape, found only by scanning every class instead of
266
+ # guessing which ones to check).
267
+ #
268
+ # Mechanism (``_derive_field_order_overrides``, run once at import time):
269
+ # for each class, ``inspect.getsource`` its OWN ``_visit_and_replace_children``
270
+ # and read, via a small ``ast`` walk (never executed -- a class is free to
271
+ # hold live LibCST state that must not be touched at import time), the
272
+ # literal keyword-argument order of the ``return ClassName(...)`` expression
273
+ # (or, for the few classes that build the return value in a local variable
274
+ # first -- e.g. ``TypeParam``'s ``ret = TypeParam(...); return ret`` -- the
275
+ # ``Assign`` that variable was last bound from). Python evaluates a call's
276
+ # keyword-argument VALUES strictly in the order they are WRITTEN, left to
277
+ # right, regardless of the order the callee's own ``__init__`` declares them
278
+ # in -- which is exactly what feeds ``_ChildrenCollectionVisitor`` (the
279
+ # object backing LibCST's own ``CSTNode.children`` property) each child, in
280
+ # that same order. A keyword whose value never calls one of LibCST's own
281
+ # ``visit_required``/``visit_optional``/``visit_sentinel``/``visit_sequence``/
282
+ # ``visit_iterable``/``visit_body_sequence``/``visit_body_iterable`` helpers
283
+ # (e.g. ``Arg``'s ``star=self.star``, a plain string field, not a CSTNode)
284
+ # contributes no child and is dropped from the sequence -- it was never one
285
+ # of ``.children``'s entries either.
286
+ #
287
+ # Verified two independent ways (S6a verifier residue, this fix): (1) a
288
+ # systematic scan of every ``CSTNode`` subclass this ``libcst`` install
289
+ # exposes (verified on 1.9.0: 200 public classes, 28 abstract, 172 non-abstract;
290
+ # e.g. ``BaseBinaryOp``, never instantiated) found exactly five classes whose
291
+ # extracted order differs from actual BYTE order -- ``Del``, ``AsName``,
292
+ # ``ParamSlash``, ``ParamSpec``, ``TypeVarTuple``; (2) a corpus exercising
293
+ # every remaining instantiable class (PEP 570/695/750/798/810 constructs
294
+ # included -- positional-only/keyword-only params, generic type params incl.
295
+ # ``*Ts``/``**P``, match statements incl. every pattern kind, walrus,
296
+ # f-strings/t-strings incl. nested ones, lazy imports, starred dict
297
+ # comprehensions, every binary/bitwise/comparison/augmented operator,
298
+ # ``try``/``except``/``except*``, comprehensions, lambda, decorators, slicing)
299
+ # instantiates 163 of 172 non-abstract classes; the 9 uncovered: Break, Comment,
300
+ # Continue, LazyImport, LazyImportFrom, StarredDictComp, TemplatedString,
301
+ # TemplatedStringExpression, TemplatedStringText. Parsed with real LibCST and
302
+ # compared per-instance, node by node, against the SAME five classes -- zero
303
+ # further divergences found (see
304
+ # ``tests/query/test_legacy_parity_cst_query_s6a.py``, which pins this
305
+ # corpus and this exact five-class result so a future libcst upgrade adding
306
+ # a sixth non-lexical class fails loudly instead of silently).
307
+ #
308
+ # Every OTHER class's extracted order is kept here too (not just the
309
+ # divergent five): using it, via :func:`_order_by_field_names`, for a class
310
+ # whose order already happens to equal byte order reproduces byte-sort
311
+ # exactly (there is nothing to reorder), so folding every class into one
312
+ # table -- rather than "byte-sort plus a short list of exceptions" --
313
+ # removes the whole CATEGORY of bug this file has now fixed three times
314
+ # over (Del, AsName, then this), instead of the one class each fix happened
315
+ # to name.
316
+ _HARD_CODED_FIELD_ORDER_OVERRIDES: Mapping[str, Tuple[str, ...]] = {
317
+ # Confirmed non-lexical by direct, human reading of LibCST's source
318
+ # (not just the scan below) -- kept as the floor this plugin falls back
319
+ # to if ``_derive_field_order_overrides`` cannot read ANY class's source
320
+ # at all (e.g. a frozen/zipped install with no ``.py`` files on disk,
321
+ # the one case ``inspect.getsource`` cannot work around), so a total
322
+ # introspection failure regresses to "no override table" rather than
323
+ # silently losing these five specifically-verified fixes. Note: BaseBooleanOp
324
+ # is abstract (never instantiated) yet may appear in the derived table if
325
+ # scan captures its override; this is harmless (unused) and kept for completeness.
326
+ "Del": ("target", "whitespace_after_del", "semicolon"),
327
+ "AsName": ("whitespace_before_as", "name", "whitespace_after_as"),
328
+ "ParamSlash": ("comma", "whitespace_after"),
329
+ "ParamSpec": ("name", "whitespace_after_star"),
330
+ "TypeVarTuple": ("name", "whitespace_after_star"),
331
+ }
332
+
333
+ # The LibCST helpers whose presence in a keyword argument's value expression
334
+ # means that keyword really does hand a child to the visitor (and so is a
335
+ # real ``.children`` entry) -- as opposed to a plain field value such as
336
+ # ``Arg``'s ``star=self.star`` (a bare string, never visited).
337
+ _VISIT_HELPER_NAMES = frozenset(
338
+ {
339
+ "visit_required",
340
+ "visit_optional",
341
+ "visit_sentinel",
342
+ "visit_sequence",
343
+ "visit_iterable",
344
+ "visit_body_sequence",
345
+ "visit_body_iterable",
346
+ }
347
+ )
348
+
349
+
350
+ def _expr_calls_visit_helper(expr: ast.AST) -> bool:
351
+ """True when ``expr`` -- a keyword argument's VALUE expression from a
352
+ ``return ClassName(...)`` call, e.g. ``visit_required(self, "target",
353
+ self.target, visitor)`` or the ternary
354
+ ``visit_required(...) if cond else visit_sequence(...)`` LibCST's own
355
+ ``ImportFrom._visit_and_replace_children`` uses for its ``names`` field
356
+ -- contains a call to one of :data:`_VISIT_HELPER_NAMES` ANYWHERE inside
357
+ it. Walking the whole subtree (rather than checking only the outermost
358
+ call) is what makes the ternary case work: whichever branch runs, both
359
+ of its own alternatives are themselves a ``visit_*`` call, so the
360
+ keyword contributes a child either way.
361
+ """
362
+ for node in ast.walk(expr):
363
+ if isinstance(node, ast.Call):
364
+ func = node.func
365
+ if isinstance(func, ast.Name) and func.id in _VISIT_HELPER_NAMES:
366
+ return True
367
+ if isinstance(func, ast.Attribute) and func.attr in _VISIT_HELPER_NAMES:
368
+ return True
369
+ return False
370
+
371
+
372
+ def _visit_order_from_source(cls: type) -> Optional[Tuple[str, ...]]:
373
+ """The real child-visit order of ``cls`` -- as a tuple of field names,
374
+ in the exact sequence ``cls``'s own ``_visit_and_replace_children``
375
+ hands children to a visitor -- read STATICALLY from its source (never
376
+ executed). Returns ``None`` for a class this reader cannot make sense
377
+ of: an abstract method (no body to read, e.g. ``MatchPattern``), a
378
+ class whose source is unavailable (``inspect.getsource`` raises, e.g.
379
+ under a frozen/zipped install), or a leaf class whose method just
380
+ ``return self`` (zero CSTNode-typed children of its own, e.g.
381
+ ``Comment``/``SimpleWhitespace``/``ImportStar`` -- nothing to order,
382
+ correctly left for the general byte-sort path, which is a no-op on
383
+ zero or one child anyway).
384
+ """
385
+
386
+ method = cls.__dict__.get("_visit_and_replace_children")
387
+ if method is None:
388
+ method = getattr(cls, "_visit_and_replace_children", None)
389
+ if method is None or getattr(method, "__isabstractmethod__", False):
390
+ return None
391
+ try:
392
+ source = inspect.getsource(method)
393
+ except (OSError, TypeError):
394
+ return None
395
+ try:
396
+ parsed = ast.parse(textwrap.dedent(source))
397
+ except SyntaxError:
398
+ return None
399
+ if not parsed.body or not isinstance(
400
+ parsed.body[0], (ast.FunctionDef, ast.AsyncFunctionDef)
401
+ ):
402
+ return None
403
+ function_def = parsed.body[0]
404
+
405
+ # A handful of classes (e.g. ``TypeParam``) build the return value in a
406
+ # local variable first (``ret = TypeParam(...); return ret``) rather
407
+ # than returning the constructor call directly; track every such
408
+ # assignment so the later ``return ret`` still resolves to its call.
409
+ assigned_calls: Dict[str, ast.Call] = {}
410
+ for node in ast.walk(function_def):
411
+ if isinstance(node, ast.Assign) and isinstance(node.value, ast.Call):
412
+ for target in node.targets:
413
+ if isinstance(target, ast.Name):
414
+ assigned_calls[target.id] = node.value
415
+
416
+ call_expr: Optional[ast.Call] = None
417
+ for node in ast.walk(function_def):
418
+ if isinstance(node, ast.Return):
419
+ value = node.value
420
+ if isinstance(value, ast.Call):
421
+ call_expr = value
422
+ elif isinstance(value, ast.Name):
423
+ call_expr = assigned_calls.get(value.id)
424
+ break
425
+
426
+ if call_expr is None:
427
+ return None
428
+
429
+ order = tuple(
430
+ keyword.arg
431
+ for keyword in call_expr.keywords
432
+ if keyword.arg is not None and _expr_calls_visit_helper(keyword.value)
433
+ )
434
+ return order or None
435
+
436
+
437
+ def _derive_field_order_overrides() -> Mapping[str, Tuple[str, ...]]:
438
+ """Build the full class -> real-visit-order table (see the module-level
439
+ comment above) by reading every ``CSTNode`` subclass this process's own
440
+ ``libcst`` module exposes -- ``vars(libcst)``, not
441
+ ``CSTNode.__subclasses__()``: LibCST's own class-construction machinery
442
+ reliably produces additional, non-public class OBJECTS with the same
443
+ ``__name__``/bases reachable only through the subclass graph (verified:
444
+ same name, same base names, different ``id()``, never equal to
445
+ ``libcst.<Name>``) that no real parsed node is ever an instance of --
446
+ ``type(node).__name__`` (what ``import_map.py`` actually builds this
447
+ plugin's own kind strings from) is always the PUBLIC class this module
448
+ enumerates, so scanning anything else would both miss nothing real and
449
+ risk a spurious/duplicate entry.
450
+ """
451
+
452
+ try:
453
+ cst_module = libcst
454
+ except NameError: # pragma: no cover -- libcst is an unconditional import
455
+ return dict(_HARD_CODED_FIELD_ORDER_OVERRIDES)
456
+
457
+ derived: Dict[str, Tuple[str, ...]] = {}
458
+ for value in list(vars(cst_module).values()):
459
+ if not (isinstance(value, type) and issubclass(value, cst_module.CSTNode)):
460
+ continue
461
+ order = _visit_order_from_source(value)
462
+ if order:
463
+ derived[value.__name__] = order
464
+
465
+ if not derived:
466
+ # Total introspection failure (no class's source was readable at
467
+ # all) -- fall back to the floor rather than run with an empty
468
+ # table and silently lose even the confirmed five.
469
+ return dict(_HARD_CODED_FIELD_ORDER_OVERRIDES)
470
+
471
+ for name, order in _HARD_CODED_FIELD_ORDER_OVERRIDES.items():
472
+ derived.setdefault(name, order)
473
+ return derived
474
+
475
+
476
+ # Module-level cache for lazy initialization of _derive_field_order_overrides().
477
+ # This is initialized on first use in _field_order_overrides() to avoid the ~360ms
478
+ # cost at import time.
479
+ _FIELD_ORDER_OVERRIDES: Dict[str, Tuple[str, ...]] | None = None
480
+ _FIELD_ORDER_OVERRIDES_LOCK = threading.Lock()
481
+
482
+
483
+ def _field_order_overrides() -> Mapping[str, Tuple[str, ...]]:
484
+ """Lazily derive and cache the field order overrides table on first use.
485
+
486
+ Thread-safe accessor guarded by a lock. Returns the full class -> real-visit-order
487
+ table derived from every CSTNode subclass this process's libcst module exposes,
488
+ with the hard-coded 5-entry fallback (Del, AsName, ParamSlash, ParamSpec,
489
+ TypeVarTuple) guaranteed to be present.
490
+ """
491
+ global _FIELD_ORDER_OVERRIDES
492
+ if _FIELD_ORDER_OVERRIDES is not None:
493
+ return _FIELD_ORDER_OVERRIDES
494
+
495
+ with _FIELD_ORDER_OVERRIDES_LOCK:
496
+ # Double-check after acquiring lock to avoid race condition
497
+ if _FIELD_ORDER_OVERRIDES is not None:
498
+ return _FIELD_ORDER_OVERRIDES
499
+
500
+ # Perform derivation under lock
501
+ derived = _derive_field_order_overrides()
502
+
503
+ # Completeness assertion: log a warning if any non-abstract public
504
+ # CSTNode subclass with multiple children is missing from the table.
505
+ # Never raise at runtime.
506
+ try:
507
+ cst_module = libcst
508
+ missing_classes = []
509
+ for value in list(vars(cst_module).values()):
510
+ if not (
511
+ isinstance(value, type) and issubclass(value, cst_module.CSTNode)
512
+ ):
513
+ continue
514
+ class_name = value.__name__
515
+ if class_name in derived:
516
+ continue
517
+ # Check if this is a non-abstract class that can have multiple children
518
+ # by looking for at least two visit_* calls in its _visit_and_replace_children
519
+ method = value.__dict__.get("_visit_and_replace_children")
520
+ if method is None:
521
+ method = getattr(value, "_visit_and_replace_children", None)
522
+ if method is None or getattr(method, "__isabstractmethod__", False):
523
+ continue
524
+ try:
525
+ source = inspect.getsource(method)
526
+ visit_count = sum(
527
+ 1
528
+ for helper_name in _VISIT_HELPER_NAMES
529
+ if helper_name in source
530
+ )
531
+ if visit_count >= 2:
532
+ missing_classes.append(class_name)
533
+ except (OSError, TypeError):
534
+ # Source not available; cannot determine if class has multiple children
535
+ pass
536
+
537
+ if missing_classes:
538
+ logging.warning(
539
+ f"LibCST classes with multiple children missing from field order table: {missing_classes}"
540
+ )
541
+ except Exception:
542
+ # Silently ignore any assertion failures
543
+ pass
544
+
545
+ _FIELD_ORDER_OVERRIDES = derived
546
+ return _FIELD_ORDER_OVERRIDES
547
+
548
+
549
+ def _byte_trivia_sort_key(child: Any) -> Tuple[int, int, int]:
550
+ """(start, end, trivia_priority): sorted primarily by start byte, then
551
+ by end byte -- a real, measured LibCST shape (a zero-width whitespace
552
+ field can sit at the exact same START offset as the wider node it
553
+ precedes, e.g. ``whitespace_before_params`` and a non-empty
554
+ ``Parameters`` both starting where the parameter list begins) -- the
555
+ NARROWER (typically zero-width) one sorts first.
556
+
557
+ When start AND end are BOTH tied too (a genuinely empty content node,
558
+ e.g. an EMPTY ``Parameters``, landing at the exact same zero-width
559
+ point as its own surrounding ``whitespace_before_params``/
560
+ ``whitespace_before_colon`` fields), a pure whitespace/trivia kind
561
+ sorts first -- matching LibCST's own real ``.children`` property,
562
+ verified empirically (``def build():``'s real order is
563
+ ``whitespace_before_params, Parameters, whitespace_before_colon``, all
564
+ three landing at the same byte offset).
565
+ """
566
+
567
+ span = getattr(child, "buffer_range", None)
568
+ start, end = span if span is not None else (0, 0)
569
+ return (start, end, 0 if _is_trivia_kind(child) else 1)
570
+
571
+
572
+ def _order_by_field_names(
573
+ node: Node, field_names: Sequence[str], real_children: Sequence[Any]
574
+ ) -> List[Any]:
575
+ """Order ``real_children`` by ``field_names`` (an exact
576
+ ``_FIELD_ORDER_OVERRIDES`` entry), matched back to each field's own
577
+ value by IDENTITY (never ``==``, which a frozen dataclass ``Node``
578
+ would resolve by deep value equality -- wrong here, since two
579
+ genuinely distinct empty ``SimpleWhitespace`` children are value-equal
580
+ but must not be swapped for each other). Any child this node carries
581
+ that ISN'T reachable through one of ``field_names`` (not expected for
582
+ the classes actually listed in ``_FIELD_ORDER_OVERRIDES``, but never
583
+ silently dropped) is appended afterward, byte-sorted.
584
+ """
585
+
586
+ by_id = {id(child): child for child in real_children}
587
+ ordered: List[Any] = []
588
+ used_ids = set()
589
+ for field_name in field_names:
590
+ value = node.fields.get(field_name)
591
+ candidates = value if isinstance(value, (tuple, list)) else (value,)
592
+ for candidate in candidates:
593
+ key = id(candidate)
594
+ if key in by_id and key not in used_ids:
595
+ ordered.append(by_id[key])
596
+ used_ids.add(key)
597
+ leftovers = [child for child in real_children if id(child) not in used_ids]
598
+ leftovers.sort(key=_byte_trivia_sort_key)
599
+ return ordered + leftovers
600
+
601
+
602
+ def _is_marker_kind(node_like: Any) -> bool:
603
+ """True when ``node_like``'s own kind is one of this plugin's
604
+ synthetic, non-CST marker kinds (``$sentinel``/``$scalar`` -- see
605
+ ``import_map._convert_value``) -- a node LibCST's own
606
+ ``CSTNode.children`` property never yields, so the legacy engine's
607
+ traversal never sees one either (S6a verifier findings #4/#6)."""
608
+
609
+ kind = str(getattr(node_like, "kind", ""))
610
+ local = kind.rpartition(":")[2] or kind
611
+ return local in _MARKER_LOCAL_KINDS
612
+
613
+
614
+ def _parse_document_source(source: Union[str, bytes]) -> "libcst.Module":
615
+ """Parse a full document via LibCST's module parser into a temporary
616
+ tree. Raises :class:`FormatPluginContractError` carrying
617
+ ``ErrorCode.FORMAT_CONTENT_PARSE_FAILED`` on a syntax error -- the
618
+ catalog code the core boundary documents for this failure; no typed
619
+ exception subclass for it exists yet ({p023}), so the generic
620
+ contract-error carrier is used, exactly as it is designed to be.
621
+ """
622
+
623
+ if not isinstance(source, (str, bytes)):
624
+ # A wrong argument type is the CALLER breaking the contract, not
625
+ # damaged content: without this guard libcst leaks a bare TypeError,
626
+ # which every sibling plugin classifies and this one did not.
627
+ raise FormatPluginContractError(
628
+ plugin_id=FORMAT_ID,
629
+ error_code=ErrorCode.FORMAT_PLUGIN_CONTRACT_ERROR,
630
+ message=f"source must be str or bytes, got {type(source).__name__}",
631
+ )
632
+ if isinstance(source, str) and source.startswith("\ufeff"):
633
+ # LibCST drops a leading U+FEFF from ``str`` input but recognises the UTF-8 BOM in
634
+ # ``bytes`` (encoding ``utf-8-sig``), which then renders it back as the first 3 bytes
635
+ # (bug 72c3728c, D-AJ). Hand it the bytes form so the BOM is a document-level prefix.
636
+ source = source.encode("utf-8")
637
+ try:
638
+ return libcst.parse_module(source)
639
+ except libcst.ParserSyntaxError as exc:
640
+ raise FormatPluginContractError(
641
+ plugin_id=FORMAT_ID,
642
+ error_code=ErrorCode.FORMAT_CONTENT_PARSE_FAILED,
643
+ message=f"cannot parse Python document: {exc}",
644
+ details={
645
+ "line": max(1, int(getattr(exc, "editor_line", 0) or 1)),
646
+ "column": max(1, int(getattr(exc, "editor_column", 0) or 1)),
647
+ "message": str(getattr(exc, "message", "") or exc),
648
+ },
649
+ ) from exc
650
+
651
+
652
+ _FRAGMENT_KIND_PREFIX = f"{FORMAT_ID}:"
653
+
654
+
655
+ def _context_prefers_statement(context_kind: Optional[str]) -> bool:
656
+ """True when ``context_kind`` -- the kind of the node ``facade.replace()`` is about to
657
+ swap out, or of the anchor node ``facade.insert()``'s fragment will land beside/inside --
658
+ names a LibCST class that is itself a statement (``libcst.BaseStatement``, covering both
659
+ ``SimpleStatementLine`` and every compound statement -- ``FunctionDef``/``ClassDef``/``If``/
660
+ ``For``/... alike) rather than a bare expression (bug f2991fc0).
661
+
662
+ ``_parse_fragment_source``'s default order tries the EXPRESSION parser first (bug
663
+ 13ddeb1/{p106}: a caller replacing a genuine expression-shaped target, e.g. ``Return.value``
664
+ or ``Call.func``, with a bare expression must get that SAME bare expression node back, never
665
+ one silently wrapped in a fresh ``SimpleStatementLine`` the source never asked for). That
666
+ default is wrong the other way round: when the TARGET POSITION itself is statement-shaped --
667
+ a body/suite entry, not a scalar expression field -- a replacement fragment that ALSO happens
668
+ to parse as a bare expression (any string literal, including an ordinary docstring, is
669
+ trivially both) must still land as the full statement/compound node the position needs, since
670
+ only that shape carries STATEMENT-level trivia a bare expression node has no field for at
671
+ all: its own separating ``leading_lines``, its ``trailing_whitespace``/newline, and (via
672
+ ``SimpleStatementLine``/``IndentedBlock`` codegen, never a per-node field) its own rendered
673
+ indentation. Splicing the bare expression directly into a statement sequence renders it with
674
+ none of that -- no indentation, no trailing newline -- so whatever follows it on the source
675
+ text glues directly onto its own last character, exactly bug f2991fc0's reported "closing
676
+ quotes join the following statement".
677
+
678
+ Returns ``False`` (the original, unconditional expression-first order) for any other or
679
+ absent hint, so every existing expression-target call site is completely unaffected.
680
+ """
681
+ if not context_kind or not context_kind.startswith(_FRAGMENT_KIND_PREFIX):
682
+ return False
683
+ class_name = context_kind[len(_FRAGMENT_KIND_PREFIX) :]
684
+ cst_cls = getattr(libcst, class_name, None)
685
+ return isinstance(cst_cls, type) and issubclass(cst_cls, libcst.BaseStatement)
686
+
687
+
688
+ def _context_expects_sequence_element(context_kind: Optional[str]) -> bool:
689
+ """True when ``context_kind`` names a LibCST class that is itself a sequence-element
690
+ wrapper (``libcst.BaseElement``, covering both ``Element`` and ``StarredElement``) -- i.e.
691
+ the fragment ``facade.insert()``/``facade.replace()`` is about to splice will land beside,
692
+ or in place of, one of a ``List``/``Tuple``/``Set`` literal's own ``elements`` (bug
693
+ 25c37cc1), never as a bare expression value in a scalar field.
694
+ """
695
+ if not context_kind or not context_kind.startswith(_FRAGMENT_KIND_PREFIX):
696
+ return False
697
+ class_name = context_kind[len(_FRAGMENT_KIND_PREFIX) :]
698
+ cst_cls = getattr(libcst, class_name, None)
699
+ return isinstance(cst_cls, type) and issubclass(cst_cls, libcst.BaseElement)
700
+
701
+
702
+ def _wrap_as_sequence_element(
703
+ node: "libcst.CSTNode", context_kind: str
704
+ ) -> "libcst.CSTNode":
705
+ """Rewrap a bare-expression fragment parse into the ``BaseElement`` shape (``Element``/
706
+ ``StarredElement``) the target ``List``/``Tuple``/``Set`` slot needs (bug 25c37cc1).
707
+
708
+ A caller naturally writes a list/tuple item's own text WITH the trailing separating comma
709
+ it will visually sit behind (``"FileLinkCommand,"``) -- exactly how the item already reads
710
+ in the surrounding source -- but that trailing comma makes ``libcst.parse_expression`` parse
711
+ an otherwise bare expression as an IMPLICIT one-element ``Tuple`` (LibCST's own bare
712
+ single-element-tuple literal syntax: ``x,`` is a 1-tuple), never as the ``Element`` the
713
+ target slot actually needs. Spliced in unchanged, that bare ``Tuple`` has no
714
+ ``default_comma``/``default_comma_whitespace`` parameters on its own ``_codegen_impl``
715
+ (only ``BaseElement._codegen_impl`` accepts them), so rendering the enclosing
716
+ ``List``/``Tuple`` -- which calls every element via ``el._codegen(state,
717
+ default_comma=...)`` -- raises ``TypeError: Tuple._codegen_impl() got an unexpected
718
+ keyword argument 'default_comma'``: this bug's own reported error, verbatim.
719
+
720
+ Detecting and unwrapping that specific shape -- a ``Tuple`` with exactly one element and no
721
+ explicit parentheses of its own (``lpar``/``rpar`` both empty, i.e. the source held no
722
+ ``(...)`` around it) -- recovers the single value the caller actually meant before
723
+ rewrapping it in the ``BaseElement`` subclass ``context_kind`` names, letting the
724
+ surrounding ``List``/``Tuple``/``Set``'s own ``_codegen_impl`` decide the real comma
725
+ placement via ``comma=MaybeSentinel.DEFAULT`` (present or absent, with or without trailing
726
+ space, depending on position -- exactly as every OTHER element in that same sequence
727
+ already gets it). A fragment with no trailing comma at all (``"FileLinkCommand"``) already
728
+ parses as a bare expression, not a ``Tuple``, and is wrapped unchanged. A genuinely
729
+ parenthesized one-element tuple (``"(1, 2),"`` or ``"(1,),"``) keeps its own explicit
730
+ ``lpar``/``rpar`` and is passed through as that single value -- only the OUTER, implicit,
731
+ unparenthesized tuple a bare trailing comma alone produces is unwrapped.
732
+ """
733
+ value = node
734
+ if (
735
+ isinstance(value, libcst.Tuple)
736
+ and len(value.elements) == 1
737
+ and not value.lpar
738
+ and not value.rpar
739
+ ):
740
+ value = value.elements[0].value
741
+ class_name = context_kind[len(_FRAGMENT_KIND_PREFIX) :]
742
+ cst_cls = getattr(libcst, class_name, None)
743
+ if not (isinstance(cst_cls, type) and issubclass(cst_cls, libcst.BaseElement)):
744
+ cst_cls = libcst.Element
745
+ return cst_cls(value=value)
746
+
747
+
748
+ def _context_expects_small_statement(context_kind: Optional[str]) -> bool:
749
+ """True when ``context_kind`` names a LibCST class that is itself a "small statement"
750
+ (``libcst.BaseSmallStatement`` -- ``Return``, ``Assign``, ``Pass``, ``Expr``, ``Import``,
751
+ ... -- every node that lives directly in a ``SimpleStatementLine.body`` sequence, never on
752
+ its own) -- i.e. the fragment ``facade.replace()`` is about to splice will land in that
753
+ ``body`` sequence itself, never as a standalone statement/suite entry (bug 622727bd).
754
+
755
+ ``BaseSmallStatement`` is a SEPARATE hierarchy from ``libcst.BaseStatement``
756
+ (``_context_prefers_statement``'s own family: ``SimpleStatementLine`` and every compound
757
+ statement) -- a ``Return`` is not itself a ``BaseStatement``, so ``_context_prefers_statement``
758
+ already (correctly) leaves the expression-first parse order in place for it. That is exactly
759
+ why the crash happens: ``"return 99\\n"`` fails the expression parser, then
760
+ ``libcst.parse_statement`` succeeds -- but its *own* result for any small-statement text is
761
+ never the small statement alone, always ONE ``SimpleStatementLine`` wrapping it (LibCST's
762
+ parser has no entry point that returns a bare small statement), so splicing that unwrapped
763
+ result into the target's own ``body`` slot nests a ``SimpleStatementLine`` inside its parent
764
+ ``SimpleStatementLine`` -- and only ``BaseSmallStatement._codegen_impl`` accepts the
765
+ ``default_semicolon`` keyword the parent's own body-sequence codegen calls every element
766
+ with, so rendering raises ``TypeError: SimpleStatementLine._codegen_impl() got an unexpected
767
+ keyword argument 'default_semicolon'``: this bug's own reported error, verbatim.
768
+ """
769
+ if not context_kind or not context_kind.startswith(_FRAGMENT_KIND_PREFIX):
770
+ return False
771
+ class_name = context_kind[len(_FRAGMENT_KIND_PREFIX) :]
772
+ cst_cls = getattr(libcst, class_name, None)
773
+ return isinstance(cst_cls, type) and issubclass(cst_cls, libcst.BaseSmallStatement)
774
+
775
+
776
+ def _unwrap_small_statement(node: "libcst.CSTNode", context_kind: str) -> "libcst.CSTNode":
777
+ """Recover the bare ``BaseSmallStatement`` a small-statement target slot needs (bug
778
+ 622727bd) from ``_parse_fragment_source``'s own always-wrapped statement-parser result.
779
+
780
+ A fragment that parses as one simple statement always comes back as a
781
+ ``SimpleStatementLine`` wrapping exactly the small statement(s) the caller wrote -- for a
782
+ small-statement TARGET (a ``Return``, an ``Assign``, ...), that wrapper itself is never the
783
+ right shape to splice: only its sole ``body`` element is. A ``SimpleStatementLine`` wrapping
784
+ anything OTHER than exactly one small statement (zero, via an empty body no real parse
785
+ produces, or several, via ``a = 1; b = 2``) does not name a single replacement value the
786
+ target slot could hold, so this raises the same typed contract error every other
787
+ caller-shape mismatch in this module raises, never lets an unrecognized shape reach codegen
788
+ to fail as an unclassified ``TypeError``.
789
+ """
790
+ if isinstance(node, libcst.BaseSmallStatement):
791
+ return node
792
+ if isinstance(node, libcst.SimpleStatementLine):
793
+ if len(node.body) == 1:
794
+ return node.body[0]
795
+ raise _contract_error(
796
+ f"a replacement for {context_kind} must parse as exactly one simple "
797
+ f"statement, got {len(node.body)} in {node!r}"
798
+ )
799
+ raise _contract_error(
800
+ f"a replacement for {context_kind} must parse as a simple statement, got "
801
+ f"{type(node).__name__}"
802
+ )
803
+
804
+
805
+ def _context_expects_assign_target(context_kind: Optional[str]) -> bool:
806
+ """True when ``context_kind`` names ``libcst.AssignTarget`` itself -- i.e. the fragment is
807
+ about to replace an ``Assign``/``AugAssign``-style target WRAPPER, not the bare expression
808
+ inside it (bug 5beb0f1d).
809
+
810
+ ``AssignTarget`` (not the ``Name``/``Tuple``/``Attribute``/... it wraps) owns the rendering
811
+ of its own trailing ``" ="`` (its ``target`` field plus ``whitespace_before_equal``); it is
812
+ not a ``libcst.BaseElement`` (that family is ``List``/``Tuple``/``Set`` items, a different
813
+ wrapper already handled by ``_context_expects_sequence_element``), so it needs its own hint,
814
+ the same family as bug 25c37cc1's Element/StarredElement fix but for one concrete class.
815
+ """
816
+ if not context_kind or not context_kind.startswith(_FRAGMENT_KIND_PREFIX):
817
+ return False
818
+ class_name = context_kind[len(_FRAGMENT_KIND_PREFIX) :]
819
+ cst_cls = getattr(libcst, class_name, None)
820
+ return isinstance(cst_cls, type) and issubclass(cst_cls, libcst.AssignTarget)
821
+
822
+
823
+ def _wrap_as_assign_target(node: "libcst.CSTNode") -> "libcst.CSTNode":
824
+ """Rewrap a bare parsed assignment-target expression into the ``AssignTarget`` wrapper the
825
+ target slot needs (bug 5beb0f1d).
826
+
827
+ A caller replacing an ``AssignTarget`` naturally writes just the new target's own text
828
+ (``"y"``), which parses as a bare ``Name`` -- never as an ``AssignTarget`` of its own, since
829
+ that wrapper class is not itself parseable text, only ever constructed around one. Spliced
830
+ in unchanged, that bare ``Name`` has no ``whitespace_before_equal``/``" ="`` of its own to
831
+ render, so the assignment's ``=`` -- which belonged to the ``AssignTarget`` being replaced,
832
+ not to anything still in the tree -- is simply dropped: ``x = a + b`` becomes ``ya + b``
833
+ (the new name spliced in exactly where ``x =`` used to be, with nothing left to render the
834
+ ``=``). Wrapping the bare value back into a fresh ``AssignTarget`` -- LibCST's own default
835
+ ``whitespace_before_equal``/``whitespace_after_equal`` are already a single space each side,
836
+ matching ordinary assignment spacing -- restores it. Only a genuine
837
+ ``BaseAssignTargetExpression`` (``Name``, ``Tuple``, ``List``, ``Attribute``, ``Subscript``,
838
+ ``StarredElement`` -- everything LibCST itself accepts as an assignment target) is wrapped;
839
+ anything else names a caller replacement that could never legally sit in this slot, so it
840
+ raises the same typed contract error every other shape mismatch in this module raises.
841
+ """
842
+ if isinstance(node, libcst.AssignTarget):
843
+ return node
844
+ if isinstance(node, libcst.BaseAssignTargetExpression):
845
+ return libcst.AssignTarget(target=node)
846
+ raise _contract_error(
847
+ "a replacement for python:AssignTarget must parse as an assignment-target "
848
+ f"expression (Name, Tuple, List, Attribute, Subscript, ...), got {type(node).__name__}"
849
+ )
850
+
851
+
852
+ def _parse_fragment_source(
853
+ source: Union[str, bytes], *, prefer_statement: bool = False
854
+ ) -> Optional[Union["libcst.CSTNode", Sequence["libcst.CSTNode"]]]:
855
+ """Parse a fragment via LibCST's expression parser, falling back to the
856
+ statement parser and then, for several top-level statements at once, the
857
+ module parser, into a temporary tree (or sequence of trees). Returns
858
+ ``None`` (never raises) when no parser recognizes ``source`` as a
859
+ structure, so the caller can apply the contract's documented
860
+ plain-fallback-string behavior instead of treating "no structure" as an
861
+ error.
862
+
863
+ The third attempt (defect #1 of bug 554f6521) covers a fragment that is
864
+ several top-level statements at once -- e.g. a module docstring followed
865
+ by a blank line and a ``def`` -- which is neither one expression nor one
866
+ statement, so both narrower parsers reject it outright even though it is
867
+ perfectly parseable Python. ``libcst.parse_module`` accepts exactly that
868
+ shape and its ``.body`` is the ordered tuple of top-level statement
869
+ nodes LibCST itself parsed it into; returning that SEQUENCE (rather than
870
+ the ``Module`` wrapper) lets the caller import each statement through the
871
+ same single-node path it already uses, landing the fragment as
872
+ consecutive siblings instead of one nested document.
873
+
874
+ ``prefer_statement`` (bug f2991fc0, see ``_context_prefers_statement``) reverses the
875
+ expression/statement order for a fragment whose TARGET POSITION is itself statement-shaped:
876
+ the statement (then module) parser runs first, and the expression parser becomes the LAST
877
+ resort rather than the first -- a fragment that is genuinely only a valid expression (never a
878
+ valid statement; every valid expression trivially also is one) still falls through to it, so
879
+ nothing recognized before is now rejected.
880
+ """
881
+
882
+ text = source.decode("utf-8") if isinstance(source, bytes) else source
883
+ if prefer_statement:
884
+ try:
885
+ return libcst.parse_statement(text)
886
+ except libcst.ParserSyntaxError:
887
+ pass
888
+ try:
889
+ body = tuple(libcst.parse_module(text).body)
890
+ if body:
891
+ return body
892
+ except libcst.ParserSyntaxError:
893
+ pass
894
+ try:
895
+ return libcst.parse_expression(text)
896
+ except libcst.ParserSyntaxError:
897
+ return None
898
+ # Expression first: an expression is also a valid expression-statement,
899
+ # and the statement parser would wrap it in a SimpleStatementLine, adding
900
+ # a newline the source never had and breaking the byte-identical fragment
901
+ # round trip {p106} demands.
902
+ try:
903
+ return libcst.parse_expression(text)
904
+ except libcst.ParserSyntaxError:
905
+ pass
906
+ try:
907
+ return libcst.parse_statement(text)
908
+ except libcst.ParserSyntaxError:
909
+ pass
910
+ try:
911
+ body = tuple(libcst.parse_module(text).body)
912
+ except libcst.ParserSyntaxError:
913
+ return None
914
+ return body if body else None
915
+
916
+
917
+ def _accumulated_indent(node: Any) -> str:
918
+ """The indentation PREFIX LibCST's own code generator will apply to a bare statement newly
919
+ attached at ``node`` (walked upward through its real ancestor chain, ``.parent`` link by
920
+ ``.parent`` link) -- the concatenation, outermost level first, of every enclosing
921
+ ``IndentedBlock``'s own ``indent`` string. A block's ``indent`` field is that block's
922
+ EXPLICIT override, present only when its source used a non-default width/character; when it
923
+ is unset (``None`` -- the ordinary case, matching the document's own ``default_indent``)
924
+ LibCST's code generator falls back to the ``Module``'s ``default_indent`` field for that
925
+ level, so this does too (bug 466c10c8: this is exactly the prefix a fresh top-level
926
+ statement -- everything a parsed fragment IS, see ``_reanchor_multiline_string_literals`` --
927
+ would receive purely from being spliced at this position; the fragment's OWN internal
928
+ nesting below its root is untouched, since those blocks are unaffected by the splice).
929
+
930
+ Order here is derived purely from tree STRUCTURE -- each node's real owner
931
+ (``.parent``) -- never from a line number or any other position derived from rendered
932
+ output, per the engine's line-order invariant: this walk would still be correct even if
933
+ every line in the document were renumbered.
934
+ """
935
+ default_indent: Optional[str] = None
936
+ levels: List[str] = []
937
+ current = node
938
+ while current is not None:
939
+ if str(current.kind) == _INDENTED_BLOCK_KIND:
940
+ indent_value = current.fields.get("indent")
941
+ if indent_value is None:
942
+ if default_indent is None:
943
+ root = current
944
+ while root.parent is not None:
945
+ root = root.parent
946
+ default_indent = root.fields.get("default_indent") or " "
947
+ indent_value = default_indent
948
+ levels.append(indent_value)
949
+ current = current.parent
950
+ return "".join(reversed(levels))
951
+
952
+
953
+ def _reanchor_multiline_string_literals(parent: Any, roots: Sequence[Any]) -> None:
954
+ """Re-anchor a spliced fragment's multi-line string literal CONTENT LINES onto the target's
955
+ own depth (bug 466c10c8).
956
+
957
+ Owner design ruling (implemented verbatim here): lines are first-class entities, the same as
958
+ paragraphs -- a multi-line string literal's interior lines are not opaque blob data and must
959
+ move WITH the statement they belong to, not stay stranded at whatever column they were
960
+ authored at.
961
+
962
+ A fragment is always parsed starting at column 0 -- LibCST's statement/module parsers reject
963
+ a fragment whose very FIRST line is itself indented -- so every physical line the caller wrote
964
+ already carries the fragment's own INTERNAL relative structure (one nested line sitting
965
+ deeper than another keeps that shape here, untouched). What changes when the fragment lands
966
+ at a nested target is only the OUTER context: LibCST's code generator re-derives that
967
+ correctly for every STRUCTURAL line on its own (a statement's leading indentation is just
968
+ another field, recomputed from the live ancestor chain at render time) but treats a
969
+ multi-line string as ONE token/leaf -- its embedded newlines are raw characters inside a
970
+ single value, never revisited line by line at render time -- so only that token's OWN opening
971
+ physical line (sharing the line with whatever precedes it, e.g. the statement's own start)
972
+ receives the corrected depth; every line after that was left exactly as authored.
973
+
974
+ The fix: compute the target's own indent PREFIX once (:func:`_accumulated_indent`, called
975
+ against ``parent`` -- the fragment roots' real attachment point, whether already spliced in
976
+ (``adjust_after_insert``) or about to be (``adjust_replace_fragment``'s
977
+ ``deleted[0].parent``, still valid: that hook runs before the splice removes it, and a
978
+ replace's incoming fragment lands at the exact same parent the replaced node is leaving)) and
979
+ prepend it to every line of every multi-line ``SimpleString`` token found in the incoming
980
+ subtree EXCEPT the first (already correctly depth-adjusted by ordinary codegen, see above)
981
+ and any line that is genuinely EMPTY (a blank line inside a docstring stays a bare newline; it
982
+ never gains trailing whitespace no line of code ever asked for). A non-uniform interior --
983
+ e.g. an embedded code sample indented deeper than its surrounding prose -- keeps its own
984
+ shape intact: the shift is one uniform prefix applied to every affected line, so every line's
985
+ relative offset from every other survives exactly.
986
+
987
+ A no-op (returns immediately) when the target's accumulated indent is empty -- i.e. the
988
+ fragment's authored depth (always 0) already matches the target's rendered depth -- so an
989
+ ordinary top-level replacement/insertion is never touched.
990
+
991
+ Only ``python:SimpleString`` values are considered: a REGULAR statement line is not
992
+ re-indented here a second time (LibCST's own codegen already re-indents it correctly by
993
+ virtue of being a genuine structural line; double-shifting it would be the mirror defect).
994
+ """
995
+ indent_prefix = _accumulated_indent(parent) if parent is not None else ""
996
+ if not indent_prefix:
997
+ return
998
+ for root in roots:
999
+ for node in walk(root):
1000
+ if str(node.kind) != _SIMPLE_STRING_KIND:
1001
+ continue
1002
+ value = node.fields.get("value")
1003
+ if not isinstance(value, str) or "\n" not in value:
1004
+ continue
1005
+ lines = value.split("\n")
1006
+ shifted = [lines[0]] + [
1007
+ (indent_prefix + line) if line else line for line in lines[1:]
1008
+ ]
1009
+ new_value = "\n".join(shifted)
1010
+ if new_value != value:
1011
+ node.fields = {**node.fields, "value": new_value}
1012
+
1013
+
1014
+ class PythonFormatPlugin(FormatPluginContract, FormatBoundary):
1015
+ """The registered ``format_id="python"`` plugin (concept C-014).
1016
+
1017
+ Composes the already-merged :class:`PythonImportMap`/:class:`PythonExportMap`
1018
+ behind :class:`~tree_engine.plugins.contract.FormatPluginContract` and
1019
+ :class:`~tree_engine.core.plugin_boundary.FormatBoundary`; every field,
1020
+ trivia, and byte-range mapping is exactly what those two classes already
1021
+ produce/consume -- this class performs no conversion of its own.
1022
+ """
1023
+
1024
+ def __init__(self) -> None:
1025
+ self._import_map = PythonImportMap()
1026
+ self._export_map = PythonExportMap()
1027
+
1028
+ # -- FormatPluginContract -------------------------------------------------
1029
+
1030
+ @property
1031
+ def metadata(self) -> FormatPluginMetadata:
1032
+ """This plugin's static identity/capability surface."""
1033
+
1034
+ return _METADATA
1035
+
1036
+ def parse_document(
1037
+ self,
1038
+ source: Union[str, bytes],
1039
+ options: Optional[Mapping[str, Any]] = None,
1040
+ *,
1041
+ source_format_id: Optional[str] = None,
1042
+ ) -> Document:
1043
+ """Parse full source text/bytes into a common-model ``Document``.
1044
+
1045
+ Input processing: ``source`` goes through ``libcst.parse_module``
1046
+ into a temporary ``libcst.Module``, handed directly to
1047
+ ``import_to_common`` -- no LibCST object survives this call.
1048
+ """
1049
+
1050
+ module = _parse_document_source(source)
1051
+ result = self.import_to_common(module, options)
1052
+ if not isinstance(result, Document):
1053
+ raise _contract_error(
1054
+ f"parsing a full document must yield a Document, got {type(result).__name__}"
1055
+ )
1056
+ return result
1057
+
1058
+ def import_external_tree(
1059
+ self, external_tree: Any, options: Optional[Mapping[str, Any]] = None
1060
+ ) -> Union[Node, Document]:
1061
+ """Translate an already-parsed external LibCST tree into common
1062
+ nodes, reusing :meth:`import_to_common` -- the single shared input
1063
+ translator ({p056}, {p057})."""
1064
+
1065
+ return self.import_to_common(external_tree, options)
1066
+
1067
+ def parse_fragment(
1068
+ self,
1069
+ fragment: Union[str, bytes],
1070
+ options: Optional[Mapping[str, Any]] = None,
1071
+ *,
1072
+ source_format_id: Optional[str] = None,
1073
+ ) -> Union[Node, List[Node], str]:
1074
+ """Parse a code fragment via LibCST's statement, expression, or (for
1075
+ several top-level statements at once) module parser into a temporary
1076
+ tree, then reuse ``import_to_common``. Returns the fragment's own
1077
+ text (never an external tree, never ``None``) when no parser
1078
+ recognizes a structure.
1079
+
1080
+ A fragment that is SEVERAL top-level statements (defect #1 of bug
1081
+ 554f6521) comes back from ``_parse_fragment_source`` as a sequence of
1082
+ CST nodes rather than one; each is imported through the same
1083
+ single-node path below and the resulting list handed back as-is --
1084
+ ``facade._fragment`` already accepts ``parse_fragment`` returning a
1085
+ list/tuple of roots (it splices each one in, in order, as consecutive
1086
+ siblings) for exactly this shape.
1087
+
1088
+ ``options["context_kind"]`` (bug f2991fc0), when given, is the kind of the node this
1089
+ fragment is about to replace or land beside/inside; see
1090
+ ``_context_prefers_statement``/``_parse_fragment_source`` for how it reverses the
1091
+ expression/statement parse order when that context is itself statement-shaped.
1092
+ """
1093
+
1094
+ context_kind = (
1095
+ options.get("context_kind") if isinstance(options, Mapping) else None
1096
+ )
1097
+ cst_node = _parse_fragment_source(
1098
+ fragment, prefer_statement=_context_prefers_statement(context_kind)
1099
+ )
1100
+ if cst_node is None:
1101
+ return fragment if isinstance(fragment, str) else fragment.decode("utf-8")
1102
+ if context_kind and _context_expects_sequence_element(context_kind):
1103
+ # bug 25c37cc1: the target position is one of a List/Tuple/Set's own `elements`,
1104
+ # never a bare expression value -- rewrap (and, for the bare-trailing-comma
1105
+ # implicit-tuple shape, unwrap first) into the BaseElement subclass that slot needs
1106
+ # before this goes anywhere near `import_to_common`/the splice.
1107
+ if isinstance(cst_node, (list, tuple)):
1108
+ cst_node = tuple(
1109
+ _wrap_as_sequence_element(item, context_kind) for item in cst_node
1110
+ )
1111
+ else:
1112
+ cst_node = _wrap_as_sequence_element(cst_node, context_kind)
1113
+ elif context_kind and _context_expects_small_statement(context_kind):
1114
+ # bug 622727bd: the target position is one of a SimpleStatementLine's own `body`
1115
+ # small statements -- unwrap the statement parser's always-present
1116
+ # SimpleStatementLine wrapper down to the bare small statement that slot needs
1117
+ # before this goes anywhere near `import_to_common`/the splice.
1118
+ if isinstance(cst_node, (list, tuple)):
1119
+ cst_node = tuple(
1120
+ _unwrap_small_statement(item, context_kind) for item in cst_node
1121
+ )
1122
+ else:
1123
+ cst_node = _unwrap_small_statement(cst_node, context_kind)
1124
+ elif context_kind and _context_expects_assign_target(context_kind):
1125
+ # bug 5beb0f1d: the target position is an Assign/AugAssign target WRAPPER, not the
1126
+ # bare expression inside it -- rewrap the parsed expression into a fresh
1127
+ # AssignTarget so its own " =" trivia renders, before this goes anywhere near
1128
+ # `import_to_common`/the splice.
1129
+ if isinstance(cst_node, (list, tuple)):
1130
+ cst_node = tuple(_wrap_as_assign_target(item) for item in cst_node)
1131
+ else:
1132
+ cst_node = _wrap_as_assign_target(cst_node)
1133
+ if isinstance(cst_node, (list, tuple)):
1134
+ statements: List[Node] = []
1135
+ for statement in cst_node:
1136
+ imported = self.import_to_common(statement, options)
1137
+ if not isinstance(imported, Node):
1138
+ raise _contract_error(
1139
+ "parsing a fragment must yield a Node, got "
1140
+ f"{type(imported).__name__}"
1141
+ )
1142
+ statements.append(imported)
1143
+ return statements
1144
+ result = self.import_to_common(cst_node, options)
1145
+ if not isinstance(result, Node):
1146
+ raise _contract_error(
1147
+ f"parsing a fragment must yield a Node, got {type(result).__name__}"
1148
+ )
1149
+ return result
1150
+
1151
+ def import_to_common(
1152
+ self, external_representation: Any, options: Optional[Mapping[str, Any]] = None
1153
+ ) -> Union[Node, Document]:
1154
+ """The single input translator shared by ``parse_document``,
1155
+ ``import_external_tree``, and ``parse_fragment`` -- delegates
1156
+ entirely to the merged :class:`PythonImportMap`."""
1157
+
1158
+ return self._import_map.import_to_common(external_representation, options)
1159
+
1160
+ def export_from_common(
1161
+ self, nodes: Union[Node, Document], options: Optional[Mapping[str, Any]] = None
1162
+ ) -> Union[bytes, str]:
1163
+ """Translate common-model nodes into final Python source output --
1164
+ delegates entirely to the merged :class:`PythonExportMap`, whose
1165
+ ``export_from_common`` already runs both the rebuild and LibCST's
1166
+ own code generation in one call ({p103})."""
1167
+
1168
+ return self._export_map.export_from_common(nodes, options)
1169
+
1170
+ def generate_output(
1171
+ self,
1172
+ target: Union[Node, Document, bytes, str],
1173
+ options: Optional[Mapping[str, Any]] = None,
1174
+ ) -> Union[bytes, str]:
1175
+ """Produce final output for ``target``: runs ``export_from_common``
1176
+ when given common-model nodes, or passes an already-exported
1177
+ ``bytes``/``str`` representation through unchanged."""
1178
+
1179
+ if isinstance(target, (Node, Document)):
1180
+ return self.export_from_common(target, options)
1181
+ if isinstance(target, (bytes, str)):
1182
+ return target
1183
+ raise _contract_error(
1184
+ f"cannot generate output for {type(target).__name__}; expected a "
1185
+ "Node, Document, bytes, or str"
1186
+ )
1187
+
1188
+ def semantic_role_mapping(self) -> SemanticRoleMapping:
1189
+ """The declarative, context-free kind -> role table: module, class,
1190
+ and (top-level-shaped) function. See :meth:`role_for` for the
1191
+ context-sensitive method promotion this flat table cannot express.
1192
+ """
1193
+
1194
+ return _ROLE_MAP
1195
+
1196
+ # -- Context-sensitive semantic-role resolution ----------------------------
1197
+
1198
+ def role_for(
1199
+ self, node: Node, ancestors: Sequence[Node] = ()
1200
+ ) -> Optional[SemanticRole]:
1201
+ """Resolve ``node``'s concrete semantic role for the query engine.
1202
+
1203
+ ``ancestors`` is ``node``'s ancestor chain, nearest parent first (an
1204
+ empty sequence for a root/top-level node). A ``python:FunctionDef``
1205
+ is promoted from the declarative FUNCTION mapping to METHOD when the
1206
+ nearest ancestor that is itself a ``ClassDef`` or ``FunctionDef`` is
1207
+ a ``ClassDef`` -- i.e. it is nested directly inside a class body,
1208
+ not inside another function. ``python:Module``/``python:ClassDef``
1209
+ resolve unconditionally, mirroring :data:`_ROLE_MAP`. Any other kind
1210
+ returns ``None`` (this format has no role for it).
1211
+ """
1212
+
1213
+ kind = str(node.kind)
1214
+ if kind == _MODULE_KIND:
1215
+ return SemanticRole.MODULE
1216
+ if kind == _CLASSDEF_KIND:
1217
+ return SemanticRole.CLASS
1218
+ if kind == _FUNCTIONDEF_KIND:
1219
+ for ancestor in ancestors:
1220
+ ancestor_kind = str(ancestor.kind)
1221
+ if ancestor_kind == _CLASSDEF_KIND:
1222
+ return SemanticRole.METHOD
1223
+ if ancestor_kind == _FUNCTIONDEF_KIND:
1224
+ return SemanticRole.FUNCTION
1225
+ return SemanticRole.FUNCTION
1226
+ return None
1227
+
1228
+ # -- S6a query-parity hooks (wish 8564a2ba): legacy cst_query 8-kind ---------
1229
+ # classification, display name, and dotted qualname -- duck-typed hooks the
1230
+ # query engine (``tree_engine.query.engine``) consults when present, never
1231
+ # required by the plugin contract itself. Together they let
1232
+ # ``tree_engine.query`` be a drop-in replacement for
1233
+ # ``ai_editor.cst_query`` on Python documents; see that engine's
1234
+ # ``node_type_utils.get_node_kind``/``get_node_name``/``get_node_qualname``,
1235
+ # which every rule below mirrors byte-for-byte (verified against the real
1236
+ # legacy engine, not just its source).
1237
+
1238
+ def legacy_kind_for(self, node: Node, ancestors: Sequence[Node] = ()) -> str:
1239
+ """The legacy ``cst_query`` 8-word kind vocabulary for ``node``.
1240
+
1241
+ Mirrors ``ai_editor.cst_query.node_type_utils.get_node_kind`` exactly,
1242
+ via LibCST's OWN class hierarchy (looked up by name off ``libcst``
1243
+ itself -- this plugin keeps no separate CST tree to run ``isinstance``
1244
+ against, only the common-model ``kind`` string ``"python:<LibCST
1245
+ class name>"`` already carries): ``module``, ``decorator``, ``class``,
1246
+ ``function``/``method``, ``import``, ``smallstmt``, ``stmt``, or the
1247
+ ``node`` default for anything else (including the ``$sentinel``/
1248
+ ``$scalar`` marker kinds this plugin's own import map introduces,
1249
+ which name no real LibCST class).
1250
+
1251
+ The function/method split is ``ancestors`` (root-to-parent order, the
1252
+ same convention :meth:`role_for` documents) containing a ``ClassDef``
1253
+ ANYWHERE, not merely as the nearest enclosing def/class -- exactly
1254
+ legacy's own ``class_stack`` behavior (never popped by an
1255
+ intervening ``FunctionDef``), verified against the real legacy
1256
+ engine: a function nested inside a method is still classified
1257
+ ``method``, unlike :meth:`role_for`'s narrower nearest-ancestor rule
1258
+ (a pre-existing, out-of-scope divergence between the two hooks noted
1259
+ in this step's report, not fixed here).
1260
+ """
1261
+
1262
+ kind = str(node.kind)
1263
+ if not kind.startswith(_KIND_PREFIX):
1264
+ return "node"
1265
+ local = kind[len(_KIND_PREFIX) :]
1266
+ cst_cls = getattr(libcst, local, None)
1267
+ if not isinstance(cst_cls, type):
1268
+ return "node"
1269
+ if issubclass(cst_cls, libcst.Module):
1270
+ return "module"
1271
+ if issubclass(cst_cls, libcst.Decorator):
1272
+ return "decorator"
1273
+ if issubclass(cst_cls, libcst.ClassDef):
1274
+ return "class"
1275
+ if issubclass(cst_cls, libcst.FunctionDef):
1276
+ for ancestor in ancestors:
1277
+ if str(ancestor.kind) == _CLASSDEF_KIND:
1278
+ return "method"
1279
+ return "function"
1280
+ if issubclass(cst_cls, (libcst.Import, libcst.ImportFrom)):
1281
+ return "import"
1282
+ if issubclass(cst_cls, libcst.BaseSmallStatement):
1283
+ return "smallstmt"
1284
+ if issubclass(cst_cls, libcst.BaseStatement):
1285
+ return "stmt"
1286
+ return "node"
1287
+
1288
+ # -- trivia / non-content-token classification (bug 98478e1f follow-up) -----------------
1289
+ # Duck-typed hooks a caller consults through ``tree_engine.facade.is_trivia_kind``/
1290
+ # ``is_non_content_token`` -- the SAME dispatch convention ``legacy_kind_for`` above
1291
+ # already establishes (``getattr(plugin, name, None)``, called only when present) -- so a
1292
+ # consumer never keeps its own parallel list of "which kinds are safe to address" and asks
1293
+ # the format plugin that actually owns that knowledge instead.
1294
+
1295
+ def is_trivia_kind(self, node: Node) -> bool:
1296
+ """True for a PURE WHITESPACE/format-only node (see :func:`_is_trivia_kind`'s own
1297
+ module-level docstring): zero-width or pure formatting, never independently
1298
+ renderable/spliceable on its own."""
1299
+ return _is_trivia_kind(node)
1300
+
1301
+ def is_non_content_token(self, node: Node) -> bool:
1302
+ """True for a PURE PUNCTUATION/CONNECTIVE token (see
1303
+ :func:`_is_non_content_token_kind`'s own module-level docstring): not whitespace, but
1304
+ still carrying no independently addressable content -- a fixed textual form for its
1305
+ syntax position, with no legitimate alternative text a caller could substitute."""
1306
+ return _is_non_content_token_kind(node)
1307
+
1308
+ def name_for(self, node: Node) -> Optional[str]:
1309
+ """The node's display name, mirroring ``node_type_utils.get_node_name``.
1310
+
1311
+ A ``FunctionDef``/``ClassDef``'s name lives under ``fields["name"]``
1312
+ as a nested ``python:Name`` common-model node (never a scalar, per
1313
+ this plugin's generic dataclass-field import), so its own
1314
+ ``fields["value"]`` is read one level down. A bare ``python:Name``
1315
+ node's own ``value`` field is returned directly (legacy resolves a
1316
+ LibCST ``Name`` node's own name the same way). Every other kind
1317
+ returns ``None`` -- never ``""`` -- exactly as legacy leaves
1318
+ ``NodeInfo.name`` as ``None`` for anything else.
1319
+
1320
+ S6a verifier finding #1 (FATAL): the nested name node is read via
1321
+ ``_fields_of`` -- a duck-typed check for a ``fields`` mapping --
1322
+ rather than ``isinstance(name_node, Node)``. The facade's own
1323
+ loaded documents (``facade.loads``/``facade.query``, the ONLY
1324
+ shape ``ai_editor`` ever hands this plugin) are ``TreeDocument``s
1325
+ whose tree is built from ``core.live_tree.LiveNode``, a
1326
+ deliberately SEPARATE mutable class (never a ``Node`` subclass,
1327
+ per its own module docstring) -- the ``isinstance`` check silently
1328
+ failed for every real, facade-loaded document, so ``name``/
1329
+ ``qualname`` were always empty/``None`` on the one code path
1330
+ ``ai_editor`` actually uses. Verified fixed via
1331
+ ``facade.query(loaded_document, "class[name='Outer']")``.
1332
+ """
1333
+
1334
+ kind = str(node.kind)
1335
+ if kind in (_FUNCTIONDEF_KIND, _CLASSDEF_KIND):
1336
+ name_fields = _fields_of(node.fields.get("name"))
1337
+ if name_fields is not None:
1338
+ value = name_fields.get("value")
1339
+ if isinstance(value, str):
1340
+ return value
1341
+ return None
1342
+ if kind == _NAME_KIND:
1343
+ value = node.fields.get("value")
1344
+ return value if isinstance(value, str) else None
1345
+ return None
1346
+
1347
+ def qualname_for(self, node: Node, ancestors: Sequence[Node] = ()) -> Optional[str]:
1348
+ """The dotted qualified name, mirroring ``get_node_qualname`` exactly,
1349
+ including its two legacy quirks (pinned, not "fixed", for parity):
1350
+
1351
+ * A ``ClassDef``/``FunctionDef`` nested inside ANY enclosing class
1352
+ (at any depth, through intervening functions) gets a qualname
1353
+ built from the enclosing CLASS chain alone -- intervening function
1354
+ names are dropped entirely once a class ancestor exists anywhere
1355
+ up the chain (verified against the real legacy engine: a function
1356
+ nested inside a method is named ``Outer.methodless_helper_name``
1357
+ off the class, never ``Outer.method.inner``).
1358
+ * A ``FunctionDef`` with NO class ancestor at all drops its own
1359
+ NEAREST enclosing function's name from the chain (legacy's
1360
+ ``func_stack[:-1]``) -- a function nested two levels deep in plain
1361
+ functions (no class involved) is named off its GRANDPARENT
1362
+ function, skipping the immediate parent.
1363
+
1364
+ Every other node kind (including ``Decorator``, statements, and bare
1365
+ ``Name`` leaves) gets the concatenation of every ancestor class name
1366
+ followed by every ancestor function name (legacy's default
1367
+ ``class_stack + func_stack`` branch), or ``None`` when neither
1368
+ exists.
1369
+ """
1370
+
1371
+ class_chain = [
1372
+ name
1373
+ for name in (
1374
+ self.name_for(ancestor)
1375
+ for ancestor in ancestors
1376
+ if str(ancestor.kind) == _CLASSDEF_KIND
1377
+ )
1378
+ if name is not None
1379
+ ]
1380
+ kind = str(node.kind)
1381
+ if kind == _CLASSDEF_KIND:
1382
+ own = self.name_for(node)
1383
+ if own is None:
1384
+ return None
1385
+ return ".".join(class_chain + [own]) if class_chain else own
1386
+ if kind == _FUNCTIONDEF_KIND:
1387
+ own = self.name_for(node)
1388
+ if own is None:
1389
+ return None
1390
+ if class_chain:
1391
+ return ".".join(class_chain + [own])
1392
+ func_chain = [
1393
+ name
1394
+ for name in (
1395
+ self.name_for(ancestor)
1396
+ for ancestor in ancestors
1397
+ if str(ancestor.kind) == _FUNCTIONDEF_KIND
1398
+ )
1399
+ if name is not None
1400
+ ]
1401
+ return ".".join(func_chain[:-1] + [own])
1402
+ func_chain_all = [
1403
+ name
1404
+ for name in (
1405
+ self.name_for(ancestor)
1406
+ for ancestor in ancestors
1407
+ if str(ancestor.kind) == _FUNCTIONDEF_KIND
1408
+ )
1409
+ if name is not None
1410
+ ]
1411
+ if class_chain or func_chain_all:
1412
+ return ".".join(class_chain + func_chain_all)
1413
+ return None
1414
+
1415
+ def module_text_for(self, node: Node) -> Optional[str]:
1416
+ """The legacy predicate attribute ``"module"`` (S6a verifier
1417
+ finding #3): the rendered source text of an ``ImportFrom``'s own
1418
+ ``module`` field (an ``Attribute``/``Name`` expression subtree, or
1419
+ ``None`` for a relative-only ``from . import x`` with no module
1420
+ expression at all), mirroring legacy's own precomputed
1421
+ ``extra_attrs["module"]`` -- ``module.code_for_node(node.module)``
1422
+ -- exactly: rendered via this plugin's own ``export_from_common``
1423
+ (through :meth:`render_fragment`, which this step also taught to
1424
+ accept the ``bytes`` a whole-module render produces), never a
1425
+ hand-rebuilt dotted string, so unusual internal whitespace in the
1426
+ module expression round-trips the same way legacy's verbatim
1427
+ ``code_for_node`` does. Every other node kind returns ``None``,
1428
+ matching legacy's own ImportFrom-only ``extra_attrs`` population.
1429
+ """
1430
+
1431
+ if str(node.kind) != _IMPORTFROM_KIND:
1432
+ return None
1433
+ module_field = node.fields.get("module")
1434
+ if _fields_of(module_field) is None:
1435
+ return None
1436
+ frozen = (
1437
+ to_frozen(module_field)
1438
+ if isinstance(module_field, LiveNode)
1439
+ else module_field
1440
+ )
1441
+ try:
1442
+ rendered = self.render_fragment(frozen)
1443
+ except Exception:
1444
+ return None
1445
+ return rendered if isinstance(rendered, str) else None
1446
+
1447
+ def ordered_children_for(self, node: Node) -> Sequence[Node]:
1448
+ """Document-order (source-order) children for query traversal
1449
+ (S6a verifier findings #4/#6): the generic import
1450
+ (``import_map._convert_cst_node``) builds ``Node.children`` by
1451
+ iterating ``dataclasses.fields()`` in LibCST's own DECLARATION
1452
+ order (e.g. a ``ClassDef``'s ``body`` field is declared before its
1453
+ ``decorators`` field), not the textual/source order LibCST's own
1454
+ ``CSTNode.children`` property returns (decorators, and any
1455
+ leading blank-line/comment trivia, come first) -- verified
1456
+ empirically (a real parse, not just reading the dataclass
1457
+ definitions) to diverge from the legacy engine's own traversal,
1458
+ which walks that real ``.children`` property. Deliberately NOT
1459
+ fixed in ``import_map.py`` itself, which many mutating operations
1460
+ (``core.move``/``core.operations``/``core.live_tree.sync_fields``)
1461
+ index into positionally and are out of this step's scope -- this
1462
+ hook only reorders what THIS package's own traversal
1463
+ (``tree_engine.query.adapter._walk``) sees.
1464
+
1465
+ Four things happen together, deliberately: a ``$sentinel``/
1466
+ ``$scalar`` marker child (see :func:`_is_marker_kind`) is dropped
1467
+ entirely -- never indexed, matched, or rendered, closing the
1468
+ traversal-population gap against legacy, which has no such node
1469
+ at all; a ``python:Module``/``python:IndentedBlock``'s own
1470
+ ``header``/``footer`` fields -- import_map's OWN excluded
1471
+ POSITIONAL/SEPARATING trivia (``_MODULE_TRIVIA_ONLY_FIELDS``/
1472
+ ``_INDENTED_BLOCK_TRIVIA_ONLY_FIELDS``, kept off ``children`` so
1473
+ ``sync_fields`` has exactly one splice-able sequence field to
1474
+ target) -- are pulled BACK IN here, query-traversal only, since
1475
+ legacy's own LibCST-backed traversal walks right through them
1476
+ (verified empirically: without this, this package undercounts a
1477
+ measurable, real population of real nodes -- e.g. the
1478
+ ``SimpleWhitespace``/``EmptyLine`` trivia living inside them --
1479
+ against legacy, a gap distinct from the marker-node one); a node
1480
+ whose bare kind names a ``_FIELD_ORDER_OVERRIDES`` entry (every
1481
+ class this ``libcst`` install exposes, per
1482
+ :func:`_derive_field_order_overrides` -- not a short allowlist any
1483
+ more, see the comment above that table) is ordered by that EXACT
1484
+ field sequence (see :func:`_order_by_field_names`) instead of byte
1485
+ position; and any node whose kind has no such entry (an
1486
+ introspection failure only, e.g. a frozen install with no
1487
+ ``.py`` source for that one class, or a leaf class with fewer than
1488
+ two children where reordering could not matter) falls back to
1489
+ being sorted by its own start byte (ties broken by end byte, then
1490
+ by whether the tied child is itself pure whitespace/trivia -- see
1491
+ :func:`_is_trivia_kind` -- since a genuinely EMPTY content node,
1492
+ e.g. a parameter-less ``Parameters``, can land at the exact same
1493
+ zero-width point as its own surrounding whitespace fields),
1494
+ reconstructing source order without touching ``children`` or
1495
+ ``fields`` themselves.
1496
+
1497
+ Formerly a two-class hand-picked exception list (``Del``,
1498
+ ``AsName``) that already missed a real case (``ParamSlash``, PEP
1499
+ 570's ``def f(a, /, b)`` marker -- caught only once an Opus
1500
+ verifier went looking for MORE non-lexical classes rather than
1501
+ trusting the two already found). Replaced here by a table derived
1502
+ PROGRAMMATICALLY from every ``CSTNode`` class ``libcst`` exposes
1503
+ (verified on 1.9.0: 200 public classes, 28 abstract, 172 non-abstract)
1504
+ so no class can be missed by omission again: a systematic read of
1505
+ every class's own ``_visit_and_replace_children`` source, cross-checked
1506
+ against real parses of a corpus built to instantiate every remaining
1507
+ class (``tests/query/test_legacy_parity_cst_query_s6a.py``), found
1508
+ exactly five non-lexical classes -- ``Del``, ``AsName``,
1509
+ ``ParamSlash``, and two more this same scan caught first try,
1510
+ ``ParamSpec``/``TypeVarTuple`` (PEP 695's ``**P``/``*Ts`` type-
1511
+ parameter markers, the identical shape). See
1512
+ :func:`_derive_field_order_overrides` for the exact mechanism and
1513
+ its fallback.
1514
+ """
1515
+
1516
+ real_children = [child for child in node.children if not _is_marker_kind(child)]
1517
+ kind = str(node.kind)
1518
+ if kind in (_MODULE_KIND, _INDENTED_BLOCK_KIND):
1519
+ for field_name in ("header", "footer"):
1520
+ value = node.fields.get(field_name)
1521
+ if isinstance(value, (tuple, list)):
1522
+ real_children.extend(
1523
+ item for item in value if not _is_marker_kind(item)
1524
+ )
1525
+ elif _fields_of(value) is not None and not _is_marker_kind(value):
1526
+ real_children.append(value)
1527
+
1528
+ local_kind = kind.rpartition(":")[2] or kind
1529
+ override = _field_order_overrides().get(local_kind)
1530
+ if override is not None:
1531
+ return tuple(_order_by_field_names(node, override, real_children))
1532
+
1533
+ return tuple(sorted(real_children, key=_byte_trivia_sort_key))
1534
+
1535
+ # -- facade.replace() extension point: node-owned vs. separating trivia -----
1536
+
1537
+ def adjust_replace_fragment(
1538
+ self, deleted: Sequence[Any], incoming: Sequence[Any]
1539
+ ) -> None:
1540
+ """Transplant the FIRST replaced node's own ``leading_lines`` onto the FIRST incoming
1541
+ fragment root when the fragment's own parsed source carries none of its own (bug
1542
+ b4cc5134, item 1): ``tree_engine.facade.replace()`` swaps in a node LibCST parsed from
1543
+ the caller's replacement text alone, and a replacement that starts right at ``def``/
1544
+ ``class``/... never reproduces the blank-line run that separated the OLD node from its
1545
+ previous sibling, silently dropping it.
1546
+
1547
+ The other half of the same contract: what the replacement text DOES carry, it owns.
1548
+ If ``incoming[0].fields["leading_lines"]`` is already non-empty -- the caller's own
1549
+ source began with blank lines of its own, which LibCST's statement parser attaches to
1550
+ the parsed node exactly like any other leading trivia -- that explicit choice wins and
1551
+ nothing here is transplanted on top of it (no stacking).
1552
+
1553
+ This is deliberately narrower than "whatever the old node had, keep": a decorator
1554
+ (``FunctionDef.decorators``) or a trailing same-line comment (folded into a node's own
1555
+ ``header``/trailing whitespace field) is the node's OWN content, not the layout that
1556
+ places it -- a caller who omits either from their replacement text is making a real,
1557
+ intentional edit, and dropping it is the CORRECT behavior (pinned by
1558
+ ``tests/test_universal_file_edit_command.py::
1559
+ test_known_gap_engine_replace_drops_decorator_omitted_from_body_edit`` and
1560
+ ``tests/test_preview_edit_addressing_all_formats.py::
1561
+ test_py_create_search_replace_preview_preserves_omitted_declaration_trivia``). Only
1562
+ ``leading_lines`` -- the field LibCST itself uses exclusively for a statement's
1563
+ separation from its predecessor -- is ever touched here.
1564
+
1565
+ Runs before the incoming fragment is spliced into the document (``facade``'s own
1566
+ ``_adjust_replace_fragment``, called ahead of ``_ops.replace_range``), so the
1567
+ transplanted trivia is cloned with FRESH identity via
1568
+ ``core.live_tree.clone_live_subtree`` rather than reusing the old node's own EmptyLine
1569
+ objects: those are still registered under the node ``replace`` is about to remove at
1570
+ this point, and the preflight validation ``_ops.replace_range`` runs next would reject
1571
+ a fragment that already reuses a live node_id as a conflict.
1572
+ """
1573
+ if not deleted or not incoming:
1574
+ return
1575
+ # Re-anchor any multi-line string literal's content lines onto the target depth
1576
+ # (bug 466c10c8) BEFORE the trivia transplant below: the target parent is
1577
+ # ``deleted[0].parent`` -- still valid here, since the splice this hook runs ahead of
1578
+ # has not removed ``deleted`` yet -- and a replace's incoming fragment always lands at
1579
+ # that exact same parent the replaced node is leaving.
1580
+ _reanchor_multiline_string_literals(deleted[0].parent, incoming)
1581
+ old_first, new_first = deleted[0], incoming[0]
1582
+ old_leading = old_first.fields.get(_SEPARATING_TRIVIA_FIELD)
1583
+ new_leading = new_first.fields.get(_SEPARATING_TRIVIA_FIELD)
1584
+ if not isinstance(old_leading, tuple) or not old_leading:
1585
+ return
1586
+ if not isinstance(new_leading, tuple) or new_leading:
1587
+ return
1588
+ cloned = tuple(
1589
+ clone_live_subtree(node, parent=new_first) for node in old_leading
1590
+ )
1591
+ new_first.children = list(cloned) + list(new_first.children)
1592
+ new_first.fields = {**new_first.fields, _SEPARATING_TRIVIA_FIELD: cloned}
1593
+
1594
+ # -- facade.insert() extension point: stranded module-level bytes -----------
1595
+
1596
+ def adjust_after_insert(self, parent: Any, inserted: Sequence[Any]) -> None:
1597
+ """Give a brand-new module its own trailing newline (bug 62759f8a).
1598
+
1599
+ ``has_trailing_newline`` is ``python:Module``'s own scalar flag for whether
1600
+ the file's last byte is a newline; LibCST's code generator consults it
1601
+ directly -- it is never re-derived from any statement's own trailing
1602
+ whitespace. Parsing a genuinely empty file (0 bytes) correctly records it
1603
+ ``False``: there is no byte to have a newline. Once real content is
1604
+ spliced into that module and this one insert supplies EVERY one of its
1605
+ children (none existed before), rendering with the flag still ``False``
1606
+ drops the newline the inserted text itself asked for
1607
+ (``python_engine_edit._ensure_trailing_newline``), landing a file that
1608
+ fails the server's own flake8 W292 gate on output the server produced
1609
+ itself.
1610
+
1611
+ A populated module is left exactly alone: this only fires when the
1612
+ splice supplied literally every current child, so a real edit to an
1613
+ already-non-empty module -- including one that genuinely lacks a
1614
+ trailing newline -- never has its flag touched.
1615
+
1616
+ Also re-anchors any multi-line string literal's content lines onto the target depth
1617
+ (bug 466c10c8): unlike ``adjust_replace_fragment``, this hook runs AFTER the splice, so
1618
+ ``parent`` is already the real, live attachment point.
1619
+ """
1620
+ _reanchor_multiline_string_literals(parent, inserted)
1621
+ if (
1622
+ parent is None
1623
+ or str(parent.kind) != _MODULE_KIND
1624
+ or not inserted
1625
+ or parent.fields.get("has_trailing_newline")
1626
+ or len(parent.children) != len(inserted)
1627
+ ):
1628
+ return
1629
+ parent.fields = {**parent.fields, "has_trailing_newline": True}
1630
+
1631
+ # -- import_tree / export_tree external-LibCST bridge {p048} ---------------
1632
+
1633
+ def import_tree(
1634
+ self,
1635
+ external_tree: Union["libcst.Module", "libcst.CSTNode"],
1636
+ *,
1637
+ options: Optional[Mapping[str, Any]] = None,
1638
+ ) -> Union[Node, Document]:
1639
+ """Import side of the bridge: delegates to the merged
1640
+ ``import_map.import_tree`` for an externally supplied, already-parsed
1641
+ LibCST object -- no second, divergent import path."""
1642
+
1643
+ return _import_map.import_tree(external_tree, options=options)
1644
+
1645
+ def export_tree(
1646
+ self,
1647
+ common_tree: Union[Node, Document],
1648
+ *,
1649
+ options: Optional[Mapping[str, Any]] = None,
1650
+ ) -> Any:
1651
+ """Export side of the bridge: delegates to the merged
1652
+ ``export_map.export_tree``, which deliberately hands back the
1653
+ rebuilt LibCST object itself -- the one documented exception to
1654
+ "no LibCST object crosses the boundary" ({p048})."""
1655
+
1656
+ return _export_map.export_tree(common_tree, options=options)
1657
+
1658
+ # -- FormatBoundary ---------------------------------------------------------
1659
+
1660
+ def render_document(self, document: Document) -> bytes:
1661
+ """CORE-facing counterpart of ``parse_document``: renders a full
1662
+ ``Document`` back to bytes via ``export_from_common``."""
1663
+
1664
+ result = self.export_from_common(document, {})
1665
+ if not isinstance(result, bytes):
1666
+ raise _contract_error(
1667
+ f"render_document expected bytes, got {type(result).__name__}"
1668
+ )
1669
+ return result
1670
+
1671
+ def render_fragment(self, node: Node) -> str:
1672
+ """CORE-facing counterpart of ``parse_fragment``: renders a single
1673
+ fragment ``Node`` back to source text via ``export_from_common``.
1674
+
1675
+ S6a of wish 8564a2ba (D4/G4): ``node`` is not always a genuine
1676
+ FRAGMENT -- a caller rendering source on request for a query match
1677
+ (``tree_engine.query.engine._render_source``) has no way to know in
1678
+ advance whether the matched node happens to BE the document's own
1679
+ ``python:Module`` root (e.g. a ``"module"`` selector), and
1680
+ ``export_from_common``/``export_map._generate`` deliberately
1681
+ returns ``bytes`` (via LibCST's own ``Module.bytes``, preserving
1682
+ that module's own recorded encoding) rather than ``str`` for
1683
+ exactly that one node shape (bug reproduced during this step: a
1684
+ module match with ``include_source=True`` raised
1685
+ ``FormatPluginContractError`` here before this branch existed).
1686
+ Decoded using the module's own ``fields["encoding"]`` when present
1687
+ (the same encoding ``Module.bytes`` itself just encoded with),
1688
+ falling back to ``"utf-8"`` -- LibCST's own default -- otherwise.
1689
+ """
1690
+
1691
+ result = self.export_from_common(node, {})
1692
+ if isinstance(result, bytes):
1693
+ encoding = "utf-8"
1694
+ fields = getattr(node, "fields", None)
1695
+ if isinstance(fields, Mapping):
1696
+ declared = fields.get("encoding")
1697
+ if isinstance(declared, str) and declared:
1698
+ encoding = declared
1699
+ return result.decode(encoding)
1700
+ if not isinstance(result, str):
1701
+ raise _contract_error(
1702
+ f"render_fragment expected str or bytes, got {type(result).__name__}"
1703
+ )
1704
+ return result
1705
+
1706
+
1707
+ # Registration data: a ready-made, stateless singleton a sibling registry
1708
+ # step (out of scope here, per {p055}/{p059}/{p101}) can import and register
1709
+ # under ``format_id="python"`` without needing to know how to construct one.
1710
+ PYTHON_FORMAT_PLUGIN = PythonFormatPlugin()