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,676 @@
1
+ """Lossless CSV format plugin for the tree engine (``format_id='csv'``, matrix decision D-CC).
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+
6
+ Model: a ``csv:document`` root with one ``csv:row`` child per record and one ``csv:cell`` child per field.
7
+ There is no header node: the first record is an ordinary row.
8
+
9
+ * ``csv:document`` fields: ``delimiter``, ``record_separator`` (``LF``/``CRLF``/``CR``), ``quote_char``, ``has_bom``,
10
+ ``row_count``, ``column_count_max``, ``delimiter_source`` (``detected``/``explicit``) and ``delimiter_ambiguous``.
11
+ * ``csv:row`` fields: ``index``, ``cell_count``, ``terminator`` (the literal record terminator, ``""`` for a last
12
+ record without one), ``ragged`` (``cell_count != column_count_max``) and ``delimiter`` (so a row renders on its own).
13
+ * ``csv:cell`` fields: ``index``, ``value`` (unquoted and unescaped) and ``quoted``.
14
+
15
+ Rendering replays exactly these bytes, so ``dumps(loads(x)) == x`` for every input that parses. A blank line is a row
16
+ with one empty cell. A record terminator is ``\\r\\n``, ``\\n`` or ``\\r`` outside quotes unless ``record_separator`` is
17
+ given, in which case only that terminator ends a record. A quote opens a quoted field only at the start of a field; inside
18
+ an unquoted field it is literal. An unterminated quote, or text between a closing quote and the next delimiter, raises
19
+ ``FORMAT_CONTENT_PARSE_FAILED`` with the 1-based position of the construct (D-BM).
20
+
21
+ The delimiter is auto-detected among ``, ; TAB |`` from the first records: the candidate with the most records of the
22
+ modal column count (at least two columns) wins; a tie is reported with ``delimiter_ambiguous`` and resolved in the order
23
+ ``, ; TAB |``.
24
+
25
+ Edits: a fragment replacing or inserted as a cell is the cell VALUE (quotes are added when the value needs them or the
26
+ replaced cell was quoted for no other reason); a fragment for a row is exactly one record. ``row_count`` is kept exact
27
+ by every edit; ``column_count_max`` and the ``ragged`` flags are recomputed when an edit changes the maximum.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import re
33
+ from collections import Counter
34
+ from dataclasses import replace
35
+ from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union
36
+
37
+ from tree_engine.core.identity import generate_node_id
38
+ from tree_engine.core.nodes import Document, Node, make_node
39
+ from tree_engine.core.plugin_boundary import FormatBoundary
40
+ from tree_engine.exceptions import (
41
+ FormatContentParseFailed,
42
+ FormatFragmentParseFailed,
43
+ FormatPluginContractError,
44
+ UnsupportedTranslation,
45
+ )
46
+ from tree_engine.plugins.contract import (
47
+ FormatPluginContract,
48
+ FormatPluginMetadata,
49
+ SemanticRoleMapping,
50
+ )
51
+ from tree_engine.plugins.parse_position import position_details, utf8_failure_details
52
+
53
+ __all__ = ["FORMAT_ID", "CsvFormatPlugin", "CSV_FORMAT_PLUGIN", "csv_failure"]
54
+
55
+ FORMAT_ID = "csv"
56
+ KIND_DOCUMENT = "csv:document"
57
+ KIND_ROW = "csv:row"
58
+ KIND_CELL = "csv:cell"
59
+ _BOM = ""
60
+ _QUOTE = '"'
61
+ _DELIMITERS = (",", ";", "\t", "|")
62
+ _SEPARATORS = {"LF": "\n", "CRLF": "\r\n", "CR": "\r"}
63
+ _NAMES = {literal: name for name, literal in _SEPARATORS.items()}
64
+ _SAMPLE_ROWS = 100
65
+
66
+ _METADATA = FormatPluginMetadata(
67
+ format_id=FORMAT_ID,
68
+ aliases=(),
69
+ file_extensions=("csv",),
70
+ plugin_version="1.0.0",
71
+ contract_version="1.0.0",
72
+ capabilities={
73
+ # CAS 1.6.284 accepts .csv on project_file_transfer_upload_save with a byte-identical read-back.
74
+ "ca_save_supported": True,
75
+ # A record list has no query language: the editor answers a search with UNKNOWN_FORMAT (Q-CSV-7 a).
76
+ "search_supported": False,
77
+ # A cell or row fragment is taken byte for byte: no newline is appended to a replaced cell value.
78
+ "exact_fragment_content": True,
79
+ "semantic_role_mapping": True,
80
+ "byte_identical_round_trip": True,
81
+ "navigable": True,
82
+ "editable": True,
83
+ },
84
+ )
85
+ _ROLE_MAP = SemanticRoleMapping({})
86
+ _Source = Union[str, bytes]
87
+
88
+
89
+ class _Malformed(Exception):
90
+ """Internal: the text is not parseable; ``offset`` is a character offset into the parsed text."""
91
+
92
+ def __init__(self, offset: int, message: str) -> None:
93
+ super().__init__(message)
94
+ self.offset = offset
95
+ self.message = message
96
+
97
+
98
+ def _contract_error(message: str) -> FormatPluginContractError:
99
+ return FormatPluginContractError(message, plugin_id=FORMAT_ID)
100
+
101
+
102
+ # ---------------------------------------------------------------------------------------------- tokenizer
103
+ _PATTERNS: Dict[Tuple[str, Optional[str]], Tuple[Any, Any]] = {}
104
+
105
+
106
+ def _patterns(delimiter: str, separator: Optional[str]) -> Tuple[Any, Any]:
107
+ """(field pattern, terminator pattern) for ``delimiter`` and an explicit separator literal or ``None``."""
108
+ key = (delimiter, separator)
109
+ found = _PATTERNS.get(key)
110
+ if found is None:
111
+ d = re.escape(delimiter)
112
+ if separator is None:
113
+ field, term = rf"[^{d}\r\n]*", r"\r\n|\n|\r"
114
+ elif separator == "\n":
115
+ field, term = rf"[^{d}\n]*", r"\n"
116
+ elif separator == "\r":
117
+ field, term = rf"[^{d}\r]*", r"\r"
118
+ else:
119
+ field, term = rf"(?:[^{d}\r\n]|\r(?!\n)|\n)*", r"\r\n"
120
+ found = (re.compile(field), re.compile(term))
121
+ _PATTERNS[key] = found
122
+ return found
123
+
124
+
125
+ Row = Tuple[List[Tuple[str, bool]], str]
126
+
127
+
128
+ def _tokenize(text: str, delimiter: str, separator: Optional[str], limit: Optional[int] = None) -> List[Row]:
129
+ """Records of ``text`` as ``(cells, terminator)``; a cell is ``(value, quoted)``. Raises :class:`_Malformed`."""
130
+ field_re, term_re = _patterns(delimiter, separator)
131
+ rows: List[Row] = []
132
+ pos, size = 0, len(text)
133
+ while pos < size:
134
+ if limit is not None and len(rows) >= limit:
135
+ break
136
+ cells: List[Tuple[str, bool]] = []
137
+ while True:
138
+ if pos < size and text[pos] == _QUOTE:
139
+ start, scan = pos, pos + 1
140
+ while True:
141
+ close = text.find(_QUOTE, scan)
142
+ if close < 0:
143
+ raise _Malformed(start, "unterminated quoted field")
144
+ if text.startswith('""', close):
145
+ scan = close + 2
146
+ continue
147
+ break
148
+ value = text[start + 1 : close]
149
+ if '""' in value:
150
+ value = value.replace('""', _QUOTE)
151
+ pos = close + 1
152
+ if pos < size and not text.startswith(delimiter, pos) and term_re.match(text, pos) is None:
153
+ raise _Malformed(pos, "unexpected text after the closing quote of a quoted field")
154
+ cells.append((value, True))
155
+ else:
156
+ match = field_re.match(text, pos)
157
+ cells.append((match.group(0), False))
158
+ pos = match.end()
159
+ if pos < size and text.startswith(delimiter, pos):
160
+ pos += len(delimiter)
161
+ continue
162
+ break
163
+ found = term_re.match(text, pos)
164
+ terminator = ""
165
+ if found is not None:
166
+ terminator = found.group(0)
167
+ pos = found.end()
168
+ rows.append((cells, terminator))
169
+ return rows
170
+
171
+
172
+ def _detect_delimiter(text: str, separator: Optional[str]) -> Tuple[str, bool]:
173
+ """(delimiter, ambiguous) from a sample of the first records."""
174
+ scores: List[Tuple[int, int, str]] = []
175
+ for delimiter in _DELIMITERS:
176
+ try:
177
+ sample = _tokenize(text, delimiter, separator, _SAMPLE_ROWS)
178
+ except _Malformed:
179
+ continue
180
+ counts = Counter(len(cells) for cells, _ in sample if len(cells) >= 2)
181
+ if counts:
182
+ width, score = max(counts.items(), key=lambda item: (item[1], item[0]))
183
+ scores.append((score, width, delimiter))
184
+ if not scores:
185
+ return ",", False
186
+ best = max(score for score, _, _ in scores)
187
+ tied = [delimiter for score, _, delimiter in scores if score == best]
188
+ return tied[0], len(tied) > 1
189
+
190
+
191
+ def _read_options(options: Optional[Mapping[str, Any]]) -> Tuple[Optional[str], Optional[str]]:
192
+ delimiter = (options or {}).get("delimiter")
193
+ separator = (options or {}).get("record_separator")
194
+ if delimiter is not None and (
195
+ not isinstance(delimiter, str) or len(delimiter) != 1 or delimiter in (_QUOTE, "\r", "\n")
196
+ ):
197
+ raise _contract_error("delimiter must be one character that is not a quote, CR or LF")
198
+ if separator is not None and separator not in _SEPARATORS:
199
+ raise _contract_error("record_separator must be one of LF, CRLF, CR")
200
+ return delimiter, separator
201
+
202
+
203
+ # ---------------------------------------------------------------------------------------------- nodes
204
+ def _node(kind: str, fields: Mapping[str, Any], children: Sequence[Node] = ()) -> Node:
205
+ return replace(
206
+ make_node(kind, fields=dict(fields), children=tuple(children)),
207
+ node_id=generate_node_id(),
208
+ short_id=None,
209
+ )
210
+
211
+
212
+ def _row_node(
213
+ cells: Sequence[Tuple[str, bool]], terminator: Optional[str], delimiter: str, index: int, widest: int = 0
214
+ ) -> Node:
215
+ children = [
216
+ _node(KIND_CELL, {"index": i, "value": value, "quoted": quoted}) for i, (value, quoted) in enumerate(cells)
217
+ ]
218
+ fields: Dict[str, Any] = {"index": index, "cell_count": len(children), "ragged": len(children) != widest, "delimiter": delimiter}
219
+ if terminator is not None:
220
+ fields["terminator"] = terminator
221
+ return _node(KIND_ROW, fields, children)
222
+
223
+
224
+ def _parse(text: str, delimiter_option: Optional[str], separator_option: Optional[str]) -> Document:
225
+ has_bom = text.startswith(_BOM)
226
+ if has_bom:
227
+ text = text[1:]
228
+ separator = None if separator_option is None else _SEPARATORS[separator_option]
229
+ ambiguous = False
230
+ if delimiter_option is None:
231
+ delimiter, ambiguous = _detect_delimiter(text, separator)
232
+ else:
233
+ delimiter = delimiter_option
234
+ try:
235
+ records = _tokenize(text, delimiter, separator)
236
+ except _Malformed as exc:
237
+ raise FormatContentParseFailed(
238
+ exc.message, format_id=FORMAT_ID, **position_details(text, exc.offset, exc.message)
239
+ ) from None
240
+ if separator_option is not None:
241
+ record_separator = separator_option
242
+ else:
243
+ record_separator = next((_NAMES[t] for _, t in records if t), "LF")
244
+ widest = max((len(cells) for cells, _ in records), default=0)
245
+ rows = [
246
+ _row_node(cells, terminator, delimiter, index, widest) for index, (cells, terminator) in enumerate(records)
247
+ ]
248
+ root = _node(
249
+ KIND_DOCUMENT,
250
+ {
251
+ "delimiter": delimiter,
252
+ "record_separator": record_separator,
253
+ "quote_char": _QUOTE,
254
+ "has_bom": has_bom,
255
+ "row_count": len(rows),
256
+ "column_count_max": widest,
257
+ "delimiter_source": "explicit" if delimiter_option is not None else "detected",
258
+ "delimiter_ambiguous": ambiguous,
259
+ },
260
+ rows,
261
+ )
262
+ return Document(root=root, source_format_id=FORMAT_ID)
263
+
264
+
265
+ def csv_failure(source: _Source) -> Optional[Dict[str, Any]]:
266
+ """The position details (``line``, ``column``, ``message``) of the first thing that stops ``source`` from
267
+ parsing as csv, or ``None`` when it parses. Used by the ``csv_syntax`` checker; builds no tree."""
268
+ if isinstance(source, (bytes, bytearray)):
269
+ try:
270
+ text = bytes(source).decode("utf-8")
271
+ except UnicodeDecodeError as exc:
272
+ return utf8_failure_details(bytes(source), exc)
273
+ else:
274
+ text = source
275
+ if text.startswith(_BOM):
276
+ text = text[1:]
277
+ delimiter, _ = _detect_delimiter(text, None)
278
+ try:
279
+ _tokenize(text, delimiter, None)
280
+ except _Malformed as exc:
281
+ return position_details(text, exc.offset, exc.message)
282
+ return None
283
+
284
+
285
+ # ---------------------------------------------------------------------------------------------- rendering
286
+ def _needs_quote(value: str, delimiter: str) -> bool:
287
+ return (
288
+ delimiter in value
289
+ or _QUOTE in value
290
+ or "\r" in value
291
+ or "\n" in value
292
+ or value[:1] in (" ", "\t")
293
+ or value[-1:] in (" ", "\t")
294
+ )
295
+
296
+
297
+ def _cell_source(cell: Node) -> str:
298
+ value = cell.fields.get("value")
299
+ value = value if isinstance(value, str) else ""
300
+ if cell.fields.get("quoted"):
301
+ return _QUOTE + value.replace(_QUOTE, '""') + _QUOTE
302
+ return value
303
+
304
+
305
+ def _row_source(row: Node, delimiter: str, default: Optional[str]) -> str:
306
+ """The row's text; an empty terminator is replaced by ``default`` when one is given (a row that is no
307
+ longer the last needs a real terminator)."""
308
+ own = row.fields.get("terminator")
309
+ own = own if isinstance(own, str) else ""
310
+ end = own if (default is None or own) else default
311
+ return delimiter.join(_cell_source(cell) for cell in row.children) + end
312
+
313
+
314
+ def _render_document(root: Node) -> str:
315
+ fields = root.fields
316
+ delimiter = fields.get("delimiter") if isinstance(fields.get("delimiter"), str) else ","
317
+ default = _SEPARATORS.get(str(fields.get("record_separator")), "\n")
318
+ rows = root.children
319
+ last = len(rows) - 1
320
+ parts = [_row_source(row, delimiter, default if index != last else None) for index, row in enumerate(rows)]
321
+ return (_BOM if fields.get("has_bom") else "") + "".join(parts)
322
+
323
+
324
+ def _render(node: Node) -> str:
325
+ kind = str(node.kind)
326
+ if kind == KIND_DOCUMENT:
327
+ return _render_document(node)
328
+ if kind == KIND_ROW:
329
+ delimiter = node.fields.get("delimiter")
330
+ return _row_source(node, delimiter if isinstance(delimiter, str) else ",", None)
331
+ if kind == KIND_CELL:
332
+ value = node.fields.get("value")
333
+ return value if isinstance(value, str) else ""
334
+ raise UnsupportedTranslation(
335
+ f"node kind {kind!r} has no CSV form", node_type=kind, format_id=FORMAT_ID
336
+ )
337
+
338
+
339
+ # ---------------------------------------------------------------------------------------------- live-tree upkeep
340
+ def _root(node: Any) -> Any:
341
+ while node is not None and node.parent is not None:
342
+ node = node.parent
343
+ return node
344
+
345
+
346
+ def _delimiter_of(root: Any) -> str:
347
+ value = root.fields.get("delimiter") if root is not None else None
348
+ return value if isinstance(value, str) else ","
349
+
350
+
351
+ def _separator_of(root: Any) -> str:
352
+ return _SEPARATORS.get(str(root.fields.get("record_separator")), "\n") if root is not None else "\n"
353
+
354
+
355
+ def _reindex(siblings: Sequence[Any], start: int) -> None:
356
+ for index in range(max(0, start), len(siblings)):
357
+ node = siblings[index]
358
+ if node.fields.get("index") != index:
359
+ node.fields = {**node.fields, "index": index}
360
+
361
+
362
+ def _recompute_widest(root: Any) -> None:
363
+ """Set ``column_count_max`` from the rows and refresh the ``ragged`` flag of every row that changed."""
364
+ widest = max((len(row.children) for row in root.children), default=0)
365
+ if root.fields.get("column_count_max") != widest:
366
+ root.fields = {**root.fields, "column_count_max": widest}
367
+ for row in root.children:
368
+ ragged = len(row.children) != widest
369
+ if row.fields.get("ragged") != ragged or row.fields.get("cell_count") != len(row.children):
370
+ row.fields = {**row.fields, "ragged": ragged, "cell_count": len(row.children)}
371
+
372
+
373
+ def _settle_row(row: Any, root: Any, count_before: Optional[int] = None) -> None:
374
+ """Refresh a row's own counts. The whole document is revisited only when the maximum may have moved:
375
+ the row grew past it, or it shrank from it."""
376
+ count = len(row.children)
377
+ widest = root.fields.get("column_count_max", 0)
378
+ if count > widest or (count_before is not None and count_before == widest and count < widest):
379
+ _recompute_widest(root)
380
+ return
381
+ ragged = count != widest
382
+ if row.fields.get("cell_count") != count or row.fields.get("ragged") != ragged:
383
+ row.fields = {**row.fields, "cell_count": count, "ragged": ragged}
384
+
385
+
386
+ def _quoted_for(value: str, delimiter: str, replaced: Optional[Any]) -> bool:
387
+ """A value is quoted when it needs it, or when the cell it replaces was quoted for no reason of its own."""
388
+ if _needs_quote(value, delimiter):
389
+ return True
390
+ if replaced is None:
391
+ return False
392
+ old = replaced.fields.get("value")
393
+ return bool(replaced.fields.get("quoted")) and not _needs_quote(old if isinstance(old, str) else "", delimiter)
394
+
395
+
396
+ class CsvFormatPlugin(FormatPluginContract, FormatBoundary):
397
+ """Registered lossless ``format_id='csv'`` plugin."""
398
+
399
+ @staticmethod
400
+ def open_options() -> Dict[str, str]:
401
+ """Editor hook (``facade.format_hook(format_id, "open_options")``): name -> description of the open
402
+ options this format reads. The editor builds its open parameters from these, so a format declares its own."""
403
+ return {
404
+ "delimiter": "csv only: the column delimiter, one character that is not a quote, CR or LF; "
405
+ "default: detected from the first records",
406
+ "record_separator": "csv only: the record separator, one of LF, CRLF, CR; default: detected",
407
+ }
408
+
409
+ @staticmethod
410
+ def validate_open_options(options: Mapping[str, Any]) -> Dict[str, str]:
411
+ """name -> problem for each refused value (the same rules ``parse_document`` applies)."""
412
+ problems: Dict[str, str] = {}
413
+ for name in ("delimiter", "record_separator"):
414
+ if name in options:
415
+ try:
416
+ _read_options({name: options[name]})
417
+ except FormatPluginContractError as exc:
418
+ problems[name] = str(exc)
419
+ return problems
420
+
421
+ @staticmethod
422
+ def checker_plugin() -> Any:
423
+ """The builtin ``csv_syntax`` checker (loaded on first use; the checks package imports this module)."""
424
+ from tree_engine.checks.builtin.csv_syntax import CsvSyntaxChecker
425
+
426
+ return CsvSyntaxChecker()
427
+
428
+ @property
429
+ def metadata(self) -> FormatPluginMetadata:
430
+ return _METADATA
431
+
432
+ @staticmethod
433
+ def _decode(source: _Source, label: str, error: type) -> str:
434
+ if isinstance(source, str):
435
+ return source
436
+ if isinstance(source, (bytes, bytearray)):
437
+ try:
438
+ return bytes(source).decode("utf-8")
439
+ except UnicodeDecodeError as exc:
440
+ raise error(f"cannot decode CSV: {exc}", format_id=FORMAT_ID) from exc
441
+ raise _contract_error(f"{label} must be str or bytes, got {type(source).__name__}")
442
+
443
+ def parse_document(
444
+ self,
445
+ source: _Source,
446
+ options: Optional[Mapping[str, Any]] = None,
447
+ *,
448
+ source_format_id: Optional[str] = None,
449
+ ) -> Document:
450
+ del source_format_id
451
+ delimiter, separator = _read_options(options)
452
+ return _parse(self._decode(source, "source", FormatContentParseFailed), delimiter, separator)
453
+
454
+ @staticmethod
455
+ def fragment_options(root: Any) -> Dict[str, Any]:
456
+ """Read by the facade before every fragment parse: the document's delimiter."""
457
+ return {"delimiter": _delimiter_of(root)}
458
+
459
+ def parse_fragment(
460
+ self,
461
+ source: _Source,
462
+ options: Optional[Mapping[str, Any]] = None,
463
+ *,
464
+ source_format_id: Optional[str] = None,
465
+ ) -> Node:
466
+ """A fragment in a cell position is the cell VALUE; anywhere else it is exactly one record.
467
+ A record's own terminator is kept when the fragment ends with one; otherwise the hooks give it
468
+ the replaced or preceding row's."""
469
+ del source_format_id
470
+ options = options or {}
471
+ text = self._decode(source, "fragment", FormatFragmentParseFailed)
472
+ if str(options.get("context_kind") or "") == KIND_CELL:
473
+ return _node(KIND_CELL, {"value": text})
474
+ delimiter = options.get("delimiter")
475
+ delimiter = delimiter if isinstance(delimiter, str) and len(delimiter) == 1 else ","
476
+ try:
477
+ records = _tokenize(text, delimiter, None)
478
+ except _Malformed as exc:
479
+ raise FormatFragmentParseFailed(
480
+ f"fragment is not a valid CSV record: {exc.message}", format_id=FORMAT_ID
481
+ ) from None
482
+ if len(records) != 1:
483
+ raise FormatFragmentParseFailed(
484
+ "a CSV row fragment must be exactly one record", format_id=FORMAT_ID
485
+ )
486
+ cells, terminator = records[0]
487
+ return _row_node(cells, terminator or None, delimiter, 0)
488
+
489
+ # -- layout hooks (duck-typed, called by the facade) ---------------------
490
+
491
+ @staticmethod
492
+ def adjust_replace_fragment(deleted: Sequence[Any], incoming: Sequence[Any]) -> None:
493
+ """Runs before the splice: the new node takes the replaced node's place-bound fields."""
494
+ if not deleted or not incoming:
495
+ return
496
+ first, last = deleted[0], deleted[-1]
497
+ parent = first.parent
498
+ if first.kind == KIND_ROW:
499
+ root = parent
500
+ for offset, node in enumerate(incoming):
501
+ if node.kind != KIND_ROW:
502
+ continue
503
+ fields = dict(node.fields)
504
+ fields["index"] = (first.fields.get("index") or 0) + offset
505
+ fields["delimiter"] = _delimiter_of(root)
506
+ if "terminator" not in fields:
507
+ terminator = last.fields.get("terminator")
508
+ fields["terminator"] = terminator if isinstance(terminator, str) else _separator_of(root)
509
+ node.fields = fields
510
+ elif first.kind == KIND_CELL and parent is not None:
511
+ delimiter = _delimiter_of(_root(parent))
512
+ for offset, node in enumerate(incoming):
513
+ if node.kind != KIND_CELL:
514
+ continue
515
+ value = node.fields.get("value")
516
+ value = value if isinstance(value, str) else ""
517
+ node.fields = {
518
+ **node.fields,
519
+ "index": (first.fields.get("index") or 0) + offset,
520
+ "quoted": _quoted_for(value, delimiter, first),
521
+ }
522
+
523
+ @staticmethod
524
+ def adjust_after_insert(parent: Any, inserted: Sequence[Any]) -> None:
525
+ """Runs after the splice: terminators, quoting, indexes and counts of what landed."""
526
+ if parent is None or not inserted:
527
+ return
528
+ siblings = list(parent.children)
529
+ positions = [i for i, s in enumerate(siblings) if any(s is n for n in inserted)]
530
+ if not positions:
531
+ return
532
+ first = min(positions)
533
+ if parent.kind == KIND_DOCUMENT:
534
+ default = _separator_of(parent)
535
+ delimiter = _delimiter_of(parent)
536
+ for index in positions:
537
+ node = siblings[index]
538
+ if node.kind != KIND_ROW:
539
+ continue
540
+ fields = dict(node.fields)
541
+ fields["delimiter"] = delimiter
542
+ if not isinstance(fields.get("terminator"), str):
543
+ previous = siblings[index - 1].fields.get("terminator") if index > 0 else None
544
+ fields["terminator"] = previous if isinstance(previous, str) else default
545
+ node.fields = fields
546
+ _reindex(siblings, first)
547
+ parent.fields = {**parent.fields, "row_count": len(siblings)}
548
+ for index in positions:
549
+ if siblings[index].kind == KIND_ROW:
550
+ _settle_row(siblings[index], parent)
551
+ elif parent.kind == KIND_ROW:
552
+ root = _root(parent)
553
+ delimiter = _delimiter_of(root)
554
+ for index in positions:
555
+ node = siblings[index]
556
+ if node.kind != KIND_CELL:
557
+ continue
558
+ value = node.fields.get("value")
559
+ value = value if isinstance(value, str) else ""
560
+ quoted = bool(node.fields.get("quoted")) or _needs_quote(value, delimiter)
561
+ node.fields = {**node.fields, "quoted": quoted}
562
+ _reindex(siblings, first)
563
+ _settle_row(parent, root)
564
+
565
+ @staticmethod
566
+ def adjust_after_delete(
567
+ parent: Any, deleted: Sequence[Any], *, children_before: Sequence[Any]
568
+ ) -> Optional[str]:
569
+ """Runs after the removal: indexes and counts of what is left."""
570
+ if parent is None or not deleted:
571
+ return None
572
+ gone = [i for i, s in enumerate(children_before) if any(s is n for n in deleted)]
573
+ siblings = list(parent.children)
574
+ _reindex(siblings, min(gone) if gone else 0)
575
+ if parent.kind == KIND_DOCUMENT:
576
+ widest = parent.fields.get("column_count_max", 0)
577
+ parent.fields = {**parent.fields, "row_count": len(siblings)}
578
+ if any(len(n.children) == widest for n in deleted if n.kind == KIND_ROW):
579
+ _recompute_widest(parent)
580
+ elif parent.kind == KIND_ROW:
581
+ before = len(children_before)
582
+ _settle_row(parent, _root(parent), before)
583
+ return None
584
+
585
+ # -- contract surface -----------------------------------------------------
586
+
587
+ def import_external_tree(
588
+ self, external_tree: Any, options: Optional[Mapping[str, Any]] = None
589
+ ) -> Union[Node, Document]:
590
+ return self.import_to_common(external_tree, options)
591
+
592
+ def import_to_common(
593
+ self, external_representation: Any, options: Optional[Mapping[str, Any]] = None
594
+ ) -> Union[Node, Document]:
595
+ if isinstance(external_representation, (str, bytes, bytearray)):
596
+ return self.parse_document(external_representation, options)
597
+ raise UnsupportedTranslation(
598
+ "expected CSV source text",
599
+ node_type=type(external_representation).__name__,
600
+ format_id=FORMAT_ID,
601
+ )
602
+
603
+ def export_from_common(
604
+ self, nodes: Union[Node, Document], options: Optional[Mapping[str, Any]] = None
605
+ ) -> Any:
606
+ del options
607
+ if not isinstance(nodes, (Node, Document)):
608
+ raise _contract_error(f"expected Node or Document, got {type(nodes).__name__}")
609
+ return _render(nodes.root if isinstance(nodes, Document) else nodes)
610
+
611
+ def generate_output(
612
+ self, target: Union[Node, Document, Any], options: Optional[Mapping[str, Any]] = None
613
+ ) -> Union[str, bytes]:
614
+ options = options or {}
615
+ if isinstance(target, (Node, Document)):
616
+ text = _render(target.root if isinstance(target, Document) else target)
617
+ elif isinstance(target, str):
618
+ text = target
619
+ else:
620
+ raise _contract_error(
621
+ f"cannot render {type(target).__name__}; expected Node/Document/str"
622
+ )
623
+ return text.encode("utf-8") if options.get("as_bytes") else text
624
+
625
+ def semantic_role_mapping(self) -> SemanticRoleMapping:
626
+ return _ROLE_MAP
627
+
628
+ def preview_info(self, document: Any, node: Any) -> Dict[str, Any]:
629
+ """What a preview block of ``node`` shows (editor hook, D-CB.2, bug f840eb52): the document's delimiter,
630
+ record separator, BOM, row and column counts and delimiter source; a row's index, cell count and
631
+ raggedness; a cell's index, value and quoting; and the node's exact current text as ``content``."""
632
+ kind = str(node.kind)
633
+ wanted = {
634
+ KIND_DOCUMENT: (
635
+ "delimiter", "record_separator", "quote_char", "has_bom", "row_count", "column_count_max",
636
+ "delimiter_source", "delimiter_ambiguous",
637
+ ),
638
+ KIND_ROW: ("index", "cell_count", "ragged"),
639
+ KIND_CELL: ("index", "value", "quoted"),
640
+ }.get(kind, ())
641
+ attributes = {key: node.fields[key] for key in wanted if key in node.fields}
642
+ return {"name": None, "attributes": attributes, "summary": {}, "content": _render(node)}
643
+
644
+ def nodes_at_line(self, document: Any, line: int) -> List[Tuple[Any, Tuple[int, int]]]:
645
+ """Nodes covering ``line`` with their ``(first, last)`` lines, from the live tree: a row keeps no byte
646
+ offsets (bug f840eb52). The most specific node of a line is its record (row); cells are reached through
647
+ the row's children. Editor hook (D-CB.2)."""
648
+ from tree_engine.query.rendered_lines import break_count, covering_nodes, span_from
649
+
650
+ root = document.root
651
+ delimiter = _delimiter_of(root)
652
+ default = _SEPARATORS.get(str(root.fields.get("record_separator")), "\n")
653
+ rows = list(root.children)
654
+ entries: List[Tuple[Any, Tuple[int, int], int]] = []
655
+ cursor = 1
656
+ for index, row in enumerate(rows):
657
+ text = _row_source(row, delimiter, default if index != len(rows) - 1 else None)
658
+ entries.append((row, span_from(text, cursor), 1))
659
+ cursor += break_count(text)
660
+ entries.append((root, span_from(_render_document(root), 1), 0))
661
+ return covering_nodes(line, entries)
662
+
663
+ def render_document(self, document: Document) -> bytes:
664
+ result = self.generate_output(document, {"as_bytes": True})
665
+ if not isinstance(result, bytes):
666
+ raise _contract_error("render_document did not return bytes")
667
+ return result
668
+
669
+ def render_fragment(self, node: Node) -> str:
670
+ result = self.generate_output(node)
671
+ if not isinstance(result, str):
672
+ raise _contract_error("render_fragment did not return str")
673
+ return result
674
+
675
+
676
+ CSV_FORMAT_PLUGIN = CsvFormatPlugin()