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,396 @@
1
+ """Trivia, whitespace/comment, and format-attribute containers for C-002.
2
+
3
+ Scope (concept C-002, ``CommonTreeModel``, narrowed to the lossless
4
+ trivia/whitespace/comment layer and the extensible format-attribute
5
+ side-channel): this module defines ``TriviaKind``, ``TriviaPiece``,
6
+ ``CommentPlacement``, ``CommentSlot``, ``Trivia``, ``FormatAttributes`` and
7
+ the ``NodeTriviaBinding`` attachment helper, per frozen HRS fragments
8
+ {p008} (the common model must be a structural superset of LibCST's
9
+ trivia/whitespace/comment/format-detail representation) and {p022}
10
+ (byte-for-byte preservation of unchanged text -- comments, blank lines,
11
+ whitespace, line endings, original formatting round-trip exactly; nothing
12
+ here silently reformats anything).
13
+
14
+ Depends on the sibling core-node-schema module
15
+ (``src/tree_engine/core/nodes.py``) only for the ``Node`` type used in
16
+ annotations; per this step's contract that reference is ``TYPE_CHECKING``
17
+ -only so importing this module never triggers a runtime import of
18
+ ``nodes.py`` (no hard import cycle). This module does not redefine
19
+ ``Node``, a field type, or a child-sequence type -- ``nodes.py`` remains
20
+ the single base schema. It also does not itself carry ``NodeSchemaError``
21
+ (that type lives in ``nodes.py`` and, per the same TYPE_CHECKING-only
22
+ constraint, is not imported here either); ``TriviaError`` below mirrors
23
+ its shape -- an ``ErrorCode`` from the shared catalog plus a message --
24
+ without importing it, so every failure in this file still surfaces one of
25
+ the stable codes from ``src/tree_engine/errors.py`` rather than an ad hoc
26
+ string or a second, unrelated code taxonomy.
27
+
28
+ Implements exactly the four containers this step scopes:
29
+
30
+ 1. ``TriviaKind`` + ``TriviaPiece`` -- one immutable, unnormalized raw
31
+ source substring plus its kind (whitespace, newline, or comment).
32
+ 2. ``CommentSlot`` -- classifies a comment ``TriviaPiece`` as leading,
33
+ trailing, or inline relative to its owning node, bundling the
34
+ immediately adjacent whitespace/newline pieces so ordering and
35
+ adjacency -- and therefore exact reconstruction -- survive on their
36
+ own, independent of whatever container later holds the slot.
37
+ 3. ``Trivia`` -- ordered leading/trailing sequences of ``TriviaPiece``
38
+ and/or ``CommentSlot`` attachable to a node, with a ``raw_text``
39
+ property that concatenates back to the exact original bytes.
40
+ 4. ``FormatAttributes`` -- a namespaced, mapping-like side-channel for
41
+ arbitrary per-format detail attributes outside the base schema, keyed
42
+ by plugin/format id, that never drops an unrecognized key on
43
+ get/set/merge/copy.
44
+
45
+ ``NodeTriviaBinding`` is the attachment point ``nodes.py`` reserves this
46
+ module: since ``Node`` declares no trivia/format-attribute field of its
47
+ own (by design -- see its module docstring), a binding pairs a ``Node``
48
+ with its optional ``Trivia`` and ``FormatAttributes`` as an external,
49
+ copyable side table entry, without touching the base schema.
50
+
51
+ Non-goals, explicitly out of scope for this artifact: parser/codegen
52
+ translation logic (format plugins own that), node identity/addressing,
53
+ and storage/persistence.
54
+
55
+ Source-of-truth requirement labels honored here: {p008}, {p022}.
56
+ """
57
+
58
+ from __future__ import annotations
59
+
60
+ import enum
61
+ from dataclasses import dataclass, field
62
+ from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union
63
+
64
+ from tree_engine.errors import ErrorCode
65
+
66
+ if TYPE_CHECKING:
67
+ from tree_engine.core.nodes import Node
68
+
69
+ __all__ = [
70
+ "TriviaError",
71
+ "TriviaKind",
72
+ "TriviaPiece",
73
+ "CommentPlacement",
74
+ "CommentSlot",
75
+ "TriviaElement",
76
+ "Trivia",
77
+ "FormatAttributes",
78
+ "NodeTriviaBinding",
79
+ ]
80
+
81
+
82
+ class TriviaError(Exception):
83
+ """Raised when trivia/format-attribute data violates this module's
84
+ invariants (a malformed piece, an invalid comment classification, or
85
+ a reconstruction mismatch).
86
+
87
+ Always carries the originating ``ErrorCode`` from the shared catalog
88
+ (``src/tree_engine/errors.py``) as ``self.code``, the same contract
89
+ the sibling core schema's ``NodeSchemaError`` follows, so callers can
90
+ branch on the stable code rather than parsing message text.
91
+ """
92
+
93
+ def __init__(self, code: ErrorCode, message: str) -> None:
94
+ super().__init__(f"[{code.value}] {message}")
95
+ self.code = code
96
+
97
+
98
+ class TriviaKind(str, enum.Enum):
99
+ """Kind of one raw trivia substring. A ``str`` enum so values compare
100
+ and serialize like plain strings while staying a closed set."""
101
+
102
+ WHITESPACE = "WHITESPACE"
103
+ NEWLINE = "NEWLINE"
104
+ COMMENT = "COMMENT"
105
+
106
+
107
+ @dataclass(frozen=True)
108
+ class TriviaPiece:
109
+ """One immutable, unnormalized raw source substring plus its kind.
110
+
111
+ ``text`` is stored exactly as it appeared in the source -- no
112
+ trimming, case-folding, tab expansion, or newline-style
113
+ canonicalization -- so concatenating a sequence of pieces always
114
+ reproduces the original bytes, per {p022}. An empty string is a valid
115
+ ``text`` (e.g. a zero-length placeholder piece).
116
+ """
117
+
118
+ kind: TriviaKind
119
+ text: str
120
+
121
+ def __post_init__(self) -> None:
122
+ if not isinstance(self.kind, TriviaKind):
123
+ raise TriviaError(
124
+ ErrorCode.INVALID_PARENT_TYPE,
125
+ f"TriviaPiece.kind must be a TriviaKind, got {type(self.kind).__name__}",
126
+ )
127
+ if not isinstance(self.text, str):
128
+ raise TriviaError(
129
+ ErrorCode.INVALID_PARENT_TYPE,
130
+ f"TriviaPiece.text must be a str, got {type(self.text).__name__}",
131
+ )
132
+
133
+
134
+ class CommentPlacement(str, enum.Enum):
135
+ """Where a comment sits relative to the node it is attached to."""
136
+
137
+ LEADING = "LEADING"
138
+ TRAILING = "TRAILING"
139
+ INLINE = "INLINE"
140
+
141
+
142
+ def _coerce_piece_tuple(name: str, value: Any) -> Tuple[TriviaPiece, ...]:
143
+ if not isinstance(value, (tuple, list)):
144
+ raise TriviaError(
145
+ ErrorCode.INVALID_PARENT_TYPE,
146
+ f"{name} must be an ordered sequence, got {type(value).__name__}",
147
+ )
148
+ items = tuple(value)
149
+ for index, item in enumerate(items):
150
+ if not isinstance(item, TriviaPiece):
151
+ raise TriviaError(
152
+ ErrorCode.INVALID_PARENT_TYPE,
153
+ f"{name}[{index}] must be a TriviaPiece, got {type(item).__name__}",
154
+ )
155
+ if item.kind is TriviaKind.COMMENT:
156
+ raise TriviaError(
157
+ ErrorCode.INVALID_PARENT_TYPE,
158
+ f"{name}[{index}] must not itself be a COMMENT piece "
159
+ "(comments nest only via CommentSlot.piece)",
160
+ )
161
+ return items
162
+
163
+
164
+ @dataclass(frozen=True)
165
+ class CommentSlot:
166
+ """Classifies a comment ``TriviaPiece`` as leading, trailing, or
167
+ inline relative to its owning node.
168
+
169
+ ``leading_whitespace``/``trailing_whitespace`` bundle the
170
+ whitespace/newline pieces immediately adjacent to the comment inside
171
+ the slot itself, so a ``CommentSlot`` reconstructs its own exact
172
+ original byte run through ``raw_text`` regardless of what sequence
173
+ later holds it -- ordering and adjacency of the surrounding pieces
174
+ survive with the classification rather than depending on external
175
+ list position.
176
+ """
177
+
178
+ piece: TriviaPiece
179
+ placement: CommentPlacement
180
+ leading_whitespace: Tuple[TriviaPiece, ...] = field(default_factory=tuple)
181
+ trailing_whitespace: Tuple[TriviaPiece, ...] = field(default_factory=tuple)
182
+
183
+ def __post_init__(self) -> None:
184
+ if not isinstance(self.piece, TriviaPiece):
185
+ raise TriviaError(
186
+ ErrorCode.INVALID_PARENT_TYPE,
187
+ f"CommentSlot.piece must be a TriviaPiece, got {type(self.piece).__name__}",
188
+ )
189
+ if self.piece.kind is not TriviaKind.COMMENT:
190
+ raise TriviaError(
191
+ ErrorCode.INVALID_PARENT_TYPE,
192
+ f"CommentSlot.piece must carry TriviaKind.COMMENT, got {self.piece.kind!r}",
193
+ )
194
+ if not isinstance(self.placement, CommentPlacement):
195
+ raise TriviaError(
196
+ ErrorCode.INVALID_PARENT_TYPE,
197
+ f"CommentSlot.placement must be a CommentPlacement, got "
198
+ f"{type(self.placement).__name__}",
199
+ )
200
+ object.__setattr__(
201
+ self, "leading_whitespace",
202
+ _coerce_piece_tuple("CommentSlot.leading_whitespace", self.leading_whitespace),
203
+ )
204
+ object.__setattr__(
205
+ self, "trailing_whitespace",
206
+ _coerce_piece_tuple("CommentSlot.trailing_whitespace", self.trailing_whitespace),
207
+ )
208
+
209
+ @property
210
+ def raw_text(self) -> str:
211
+ """Exact original byte run this slot covers: adjacent leading
212
+ whitespace, then the comment itself, then adjacent trailing
213
+ whitespace -- byte-for-byte, no normalization."""
214
+ leading = "".join(p.text for p in self.leading_whitespace)
215
+ trailing = "".join(p.text for p in self.trailing_whitespace)
216
+ return f"{leading}{self.piece.text}{trailing}"
217
+
218
+
219
+ TriviaElement = Union[TriviaPiece, CommentSlot]
220
+
221
+
222
+ def _coerce_element_tuple(name: str, value: Any) -> Tuple[TriviaElement, ...]:
223
+ if not isinstance(value, (tuple, list)):
224
+ raise TriviaError(
225
+ ErrorCode.INVALID_PARENT_TYPE,
226
+ f"{name} must be an ordered sequence, got {type(value).__name__}",
227
+ )
228
+ items = tuple(value)
229
+ for index, item in enumerate(items):
230
+ if not isinstance(item, (TriviaPiece, CommentSlot)):
231
+ raise TriviaError(
232
+ ErrorCode.INVALID_PARENT_TYPE,
233
+ f"{name}[{index}] must be a TriviaPiece or CommentSlot, got "
234
+ f"{type(item).__name__}",
235
+ )
236
+ return items
237
+
238
+
239
+ def _render(elements: Tuple[TriviaElement, ...]) -> str:
240
+ parts = []
241
+ for element in elements:
242
+ parts.append(element.text if isinstance(element, TriviaPiece) else element.raw_text)
243
+ return "".join(parts)
244
+
245
+
246
+ @dataclass(frozen=True)
247
+ class Trivia:
248
+ """Ordered leading and trailing trivia attachable to a ``Node``.
249
+
250
+ ``leading`` is the trivia that precedes the owning node (blank lines,
251
+ indentation, standalone comments); ``trailing`` is the trivia that
252
+ follows it on the way to the next token (inline/trailing comments,
253
+ the line's newline). Each entry is either a plain ``TriviaPiece`` or a
254
+ ``CommentSlot``. ``raw_text`` concatenates every element of
255
+ ``leading`` then every element of ``trailing``, in order, reproducing
256
+ the exact original surrounding bytes with no trimming or
257
+ normalization, per {p022}.
258
+ """
259
+
260
+ leading: Tuple[TriviaElement, ...] = field(default_factory=tuple)
261
+ trailing: Tuple[TriviaElement, ...] = field(default_factory=tuple)
262
+
263
+ def __post_init__(self) -> None:
264
+ object.__setattr__(self, "leading", _coerce_element_tuple("Trivia.leading", self.leading))
265
+ object.__setattr__(self, "trailing", _coerce_element_tuple("Trivia.trailing", self.trailing))
266
+
267
+ @property
268
+ def leading_text(self) -> str:
269
+ return _render(self.leading)
270
+
271
+ @property
272
+ def trailing_text(self) -> str:
273
+ return _render(self.trailing)
274
+
275
+ @property
276
+ def raw_text(self) -> str:
277
+ """Full original byte run this trivia covers: ``leading_text``
278
+ followed by ``trailing_text``, byte-for-byte."""
279
+ return self.leading_text + self.trailing_text
280
+
281
+
282
+ def _require_namespace_key(namespace: Any, key: Any) -> None:
283
+ if not isinstance(namespace, str) or not namespace:
284
+ raise TriviaError(
285
+ ErrorCode.INVALID_PARENT_TYPE,
286
+ f"FormatAttributes namespace must be a non-empty str, got {namespace!r}",
287
+ )
288
+ if not isinstance(key, str) or not key:
289
+ raise TriviaError(
290
+ ErrorCode.INVALID_PARENT_TYPE,
291
+ f"FormatAttributes key must be a non-empty str, got {key!r}",
292
+ )
293
+
294
+
295
+ @dataclass
296
+ class FormatAttributes:
297
+ """Namespaced, mapping-like side-channel for per-format detail
298
+ attributes not covered by the base node schema, keyed by plugin/format
299
+ id (e.g. ``"python"``, ``"bsl"``), per {p008}.
300
+
301
+ Every mutator (``set``/``merge``) returns a *new* ``FormatAttributes``
302
+ rather than mutating in place, mirroring the rest of the common
303
+ model's copy-on-write style; ``copy`` is still provided explicitly so
304
+ a caller can snapshot one without going through a no-op mutation.
305
+ Namespaces and keys this module has never heard of are carried
306
+ through unchanged in every case -- nothing here filters, drops, or
307
+ inspects key names.
308
+ """
309
+
310
+ _data: Dict[str, Dict[str, Any]] = field(default_factory=dict)
311
+
312
+ def get(self, namespace: str, key: str, default: Any = None) -> Any:
313
+ _require_namespace_key(namespace, key)
314
+ return self._data.get(namespace, {}).get(key, default)
315
+
316
+ def set(self, namespace: str, key: str, value: Any) -> "FormatAttributes":
317
+ _require_namespace_key(namespace, key)
318
+ new_data = {ns: dict(attrs) for ns, attrs in self._data.items()}
319
+ new_data.setdefault(namespace, {})[key] = value
320
+ return FormatAttributes(new_data)
321
+
322
+ def namespaces(self) -> Tuple[str, ...]:
323
+ return tuple(self._data.keys())
324
+
325
+ def items(self, namespace: str) -> Tuple[Tuple[str, Any], ...]:
326
+ return tuple(self._data.get(namespace, {}).items())
327
+
328
+ def merge(self, other: "FormatAttributes") -> "FormatAttributes":
329
+ """Combine ``self`` with ``other``, namespace by namespace. On a
330
+ key collision within a namespace, ``other`` wins; every
331
+ non-colliding key from both sides -- known or unknown -- survives.
332
+ """
333
+ if not isinstance(other, FormatAttributes):
334
+ raise TriviaError(
335
+ ErrorCode.INVALID_PARENT_TYPE,
336
+ f"FormatAttributes.merge expects a FormatAttributes, got {type(other).__name__}",
337
+ )
338
+ merged = {ns: dict(attrs) for ns, attrs in self._data.items()}
339
+ for namespace, attrs in other._data.items():
340
+ merged.setdefault(namespace, {}).update(attrs)
341
+ return FormatAttributes(merged)
342
+
343
+ def copy(self) -> "FormatAttributes":
344
+ return FormatAttributes({ns: dict(attrs) for ns, attrs in self._data.items()})
345
+
346
+ def to_dict(self) -> Dict[str, Dict[str, Any]]:
347
+ """A plain, independent snapshot: mutating the result never
348
+ affects this ``FormatAttributes``."""
349
+ return {ns: dict(attrs) for ns, attrs in self._data.items()}
350
+
351
+
352
+ @dataclass(frozen=True)
353
+ class NodeTriviaBinding:
354
+ """Pairs an immutable ``Node`` with its optional ``Trivia`` and
355
+ ``FormatAttributes`` side channels.
356
+
357
+ ``nodes.py`` reserves no dedicated trivia/format-attribute field on
358
+ ``Node`` itself (by design, so this module can attach such data "via
359
+ a dedicated field, a side table, or a subclass" without renegotiating
360
+ the base schema); a binding is that side-table entry, copyable as one
361
+ unit. ``node`` is never validated as a ``Node`` instance here (only
362
+ referenced under ``TYPE_CHECKING`` per this step's import contract),
363
+ so callers may bind trivia to any node-shaped object that later
364
+ proves compatible with the sibling schema.
365
+ """
366
+
367
+ node: "Node"
368
+ trivia: Optional[Trivia] = None
369
+ format_attributes: Optional[FormatAttributes] = None
370
+
371
+ def __post_init__(self) -> None:
372
+ if self.trivia is not None and not isinstance(self.trivia, Trivia):
373
+ raise TriviaError(
374
+ ErrorCode.INVALID_PARENT_TYPE,
375
+ f"NodeTriviaBinding.trivia must be a Trivia or None, got {type(self.trivia).__name__}",
376
+ )
377
+ if self.format_attributes is not None and not isinstance(self.format_attributes, FormatAttributes):
378
+ raise TriviaError(
379
+ ErrorCode.INVALID_PARENT_TYPE,
380
+ "NodeTriviaBinding.format_attributes must be a FormatAttributes or None, "
381
+ f"got {type(self.format_attributes).__name__}",
382
+ )
383
+
384
+ def copy(self) -> "NodeTriviaBinding":
385
+ """Copy this binding for the same ``node``: ``trivia`` is reused
386
+ as-is (it is itself immutable), while ``format_attributes`` -- if
387
+ present -- is snapshotted via its own ``copy`` so every namespaced
388
+ key, known or unknown, survives independently of the original."""
389
+ fa = self.format_attributes.copy() if self.format_attributes is not None else None
390
+ return NodeTriviaBinding(node=self.node, trivia=self.trivia, format_attributes=fa)
391
+
392
+ def with_trivia(self, trivia: Trivia) -> "NodeTriviaBinding":
393
+ return NodeTriviaBinding(node=self.node, trivia=trivia, format_attributes=self.format_attributes)
394
+
395
+ def with_format_attributes(self, format_attributes: FormatAttributes) -> "NodeTriviaBinding":
396
+ return NodeTriviaBinding(node=self.node, trivia=self.trivia, format_attributes=format_attributes)