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,49 @@
1
+ """Node construction for the YAML plugin (concept C-016, step G-023/T-001/A-005).
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+
6
+ Scope: the single place in this package where a common-model ``Node`` is
7
+ created, so the identity rule holds everywhere by construction rather than by
8
+ each call site remembering it. Per {p013} every node gets a fresh UUID4
9
+ ``node_id``; per {p097} it also gets a document-local, monotonic, positive
10
+ ``short_id`` from one :class:`ShortIdMap` per read.
11
+
12
+ Nothing here knows YAML: it is pure node plumbing shared by the reader and the
13
+ emitter.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from typing import Any, Mapping, Optional, Sequence
19
+
20
+ from tree_engine.core.identity import generate_node_id
21
+ from tree_engine.core.nodes import Node, make_node
22
+ from tree_engine.core.short_id import ShortIdMap
23
+
24
+ __all__ = ["NodeBuilder"]
25
+
26
+
27
+ class NodeBuilder:
28
+ """Builds schema-validated nodes carrying a UUID4 ``node_id`` and a ``short_id``.
29
+
30
+ ``make_node`` performs the schema validation, and the validated result is
31
+ then rebuilt through ``Node`` directly so the identity produced here can be
32
+ attached -- the "attach an identity produced elsewhere" pattern that
33
+ ``core/nodes.py`` documents for its ``make_node``/direct-``Node`` split.
34
+
35
+ One builder serves one document: the short-id counter it owns is
36
+ document-local, which is exactly the scope {p097} defines for short ids.
37
+ """
38
+
39
+ def __init__(self) -> None:
40
+ self.short_ids = ShortIdMap()
41
+
42
+ def node(self, kind: str, fields: Optional[Mapping[str, Any]] = None,
43
+ children: Sequence[Node] = ()) -> Node:
44
+ """Return a validated ``Node`` of ``kind`` carrying a fresh identity."""
45
+
46
+ valid = make_node(kind, dict(fields or {}), list(children))
47
+ node_id = generate_node_id()
48
+ return Node(kind=valid.kind, fields=valid.fields, children=valid.children,
49
+ node_id=node_id, short_id=self.short_ids.allocate(node_id))
@@ -0,0 +1,225 @@
1
+ """Output side of the YAML format plugin (concept C-016, step G-023/T-001/A-005).
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+
6
+ Scope: everything that leaves the common model. Three separate jobs live here
7
+ and they must not be confused with one another:
8
+
9
+ * :func:`render` replays a tree that came from :mod:`.reader`, reassembling
10
+ each node from the verbatim text its own fields hold. This is the path that
11
+ makes ``render_document(parse_document(source)) == source`` true byte for
12
+ byte ({p022}). It is bottom-up: a node's output is its own head, then its
13
+ live children's output, then its own tail, so a replaced subtree really does
14
+ change the result instead of a stale copy of the original text winning.
15
+ * :func:`node_to_plain` projects the model onto ordinary Python data
16
+ (``dict``/``list``/scalars), discarding trivia. This is what
17
+ ``export_from_common`` hands to callers who want the data, not the document.
18
+ * :func:`plain_to_node` and :func:`emit` are the reverse direction for a tree
19
+ that never had source text: nodes built from a plain Python value carry no
20
+ ``raw``/``head``/``tail``, so they are written out in a deterministic
21
+ canonical style instead of replayed. :func:`is_source_tree` is the test that
22
+ decides which of the two paths applies.
23
+
24
+ Source-of-truth requirement labels honored here: {p022}, {p049}, {p056}.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import json
30
+ from typing import Any, Dict
31
+
32
+ from tree_engine.core.nodes import Node
33
+ from tree_engine.plugins.yaml.builder import NodeBuilder
34
+ from tree_engine.plugins.yaml.scanner import (
35
+ ENTRY_KINDS, KIND_BLOCK, KIND_DOCUMENT, KIND_ITEM, KIND_MAPPING, KIND_PAIR,
36
+ KIND_SCALAR, KIND_SEQUENCE, KIND_TRIVIA, MAPPING_KINDS, PAIR_KINDS, RAW_KINDS,
37
+ SEQUENCE_KINDS, STRUCTURE_KINDS, TRIVIA_KINDS, VALUE_KINDS, decode_scalar, unsupported,
38
+ )
39
+
40
+ #: Block entry kinds (never flow: a flow entry's value can only ever be a
41
+ #: scalar or another FLOW container, whose own head/tail already ARE its
42
+ #: brackets and so already render "{}"/"[]" once emptied -- see render()'s
43
+ #: empty-block-value special case below).
44
+ _BLOCK_ENTRY_KINDS = (KIND_PAIR, KIND_ITEM)
45
+ _BLOCK_CONTAINER_KINDS = (KIND_MAPPING, KIND_SEQUENCE)
46
+
47
+ __all__ = ["render", "is_source_tree", "node_to_plain", "plain_to_node",
48
+ "emit_scalar", "emit"]
49
+
50
+ #: Characters that make a plain scalar ambiguous when they open it, so a
51
+ #: string starting with one must be quoted on the canonical output path.
52
+ _UNSAFE_LEAD = "#&*!?|>%@`{}[],'\"-"
53
+
54
+
55
+ def render(node: Node) -> str:
56
+ """Replay a parsed tree's verbatim source text, bottom-up ({p022}).
57
+
58
+ Leaves carry their whole text in ``raw``; every structural node renders as
59
+ its ``head``, then its children, then its ``tail``. Block containers
60
+ simply hold neither, which is why one rule covers documents, block
61
+ mappings and sequences, flow collections and every entry kind alike.
62
+
63
+ One case is NOT plain replay: a block ``Pair``/``Item`` whose single
64
+ child is a block ``Mapping``/``Sequence`` with no REAL entries left
65
+ (trivia -- a comment/blank line the reader attached to it -- does not
66
+ count) renders as ``"<key>: {}"``/``"<indent>- []"`` instead of the
67
+ literal (empty) concatenation. A freshly PARSED document can never
68
+ reach this shape (the reader never builds a childless block container:
69
+ ``read_block`` only creates one when it has read at least one real
70
+ entry), so this never fires on an ordinary round trip -- it exists
71
+ because a live document CAN reach it, via a delete that removes a
72
+ nested container's one remaining entry, and a bare ``"key:\\n"``/``"-
73
+ \\n"`` head with nothing after it reads back as an explicit ``null``,
74
+ not an empty mapping/sequence (verifier finding B, S3 of wish
75
+ 8564a2ba, confirmed live: deleting a mapping's one remaining key left
76
+ ``"meta:\\n"``, which decodes as ``{"meta": None}``). Deciding this
77
+ PURELY at render time -- never by mutating any node's stored fields --
78
+ is deliberate: an earlier version set the marker by rewriting the
79
+ owning Pair's/Item's ``head`` field directly, outside the mutation
80
+ journal, which left ``session_undo`` restoring a child next to a STALE
81
+ marker and raising an unhandled error; nothing is mutated here, so
82
+ there is nothing for undo/redo to desynchronize from.
83
+ """
84
+
85
+ if node.kind in RAW_KINDS:
86
+ raw = node.fields.get("raw")
87
+ if not isinstance(raw, str):
88
+ raise unsupported(str(node.kind), "node carries no verbatim 'raw' text")
89
+ return raw
90
+ if node.kind not in STRUCTURE_KINDS:
91
+ raise unsupported(str(node.kind), f"node kind {node.kind!r} has no YAML representation")
92
+ head, tail = node.fields.get("head", ""), node.fields.get("tail", "")
93
+ if not isinstance(head, str) or not isinstance(tail, str):
94
+ raise unsupported(str(node.kind), "node carries no verbatim head/tail text")
95
+ if (node.kind in _BLOCK_ENTRY_KINDS and head.endswith("\n") and len(node.children) == 1
96
+ and node.children[0].kind in _BLOCK_CONTAINER_KINDS):
97
+ container = node.children[0]
98
+ if all(child.kind in TRIVIA_KINDS for child in container.children):
99
+ marker = "{}" if container.kind == KIND_MAPPING else "[]"
100
+ trivia_text = "".join(render(child) for child in container.children)
101
+ return f"{head[:-1]} {marker}\n{trivia_text}{tail}"
102
+ return head + "".join(render(child) for child in node.children) + tail
103
+
104
+
105
+ def is_source_tree(node: Node) -> bool:
106
+ """Return whether ``node`` came from parsing and can be replayed verbatim.
107
+
108
+ Only the reader attaches ``raw``/``head``/``tail``; a tree built by
109
+ :func:`plain_to_node` carries neither, and must be emitted canonically.
110
+ """
111
+
112
+ if node.kind == KIND_DOCUMENT:
113
+ return True
114
+ if "raw" in node.fields or "head" in node.fields:
115
+ return True
116
+ return any(is_source_tree(child) for child in node.children)
117
+
118
+
119
+ def node_to_plain(node: Node) -> Any:
120
+ """Project common-model nodes onto plain YAML-compatible Python data.
121
+
122
+ Trivia is dropped: comments and blank lines are part of the document, not
123
+ of its data. A document holding several YAML documents yields a list of
124
+ their values, one holding a single document yields that value directly.
125
+ """
126
+
127
+ if node.kind == KIND_DOCUMENT:
128
+ values = [node_to_plain(child) for child in node.children if child.kind in VALUE_KINDS]
129
+ return (values[0] if len(values) == 1 else values) if values else None
130
+ if node.kind in MAPPING_KINDS:
131
+ result: Dict[Any, Any] = {}
132
+ for pair in node.children:
133
+ if pair.kind in PAIR_KINDS:
134
+ result[pair.fields.get("key")] = node_to_plain(pair)
135
+ elif pair.kind not in TRIVIA_KINDS:
136
+ raise unsupported(str(pair.kind), "unexpected child of a YAML mapping")
137
+ return result
138
+ if node.kind in SEQUENCE_KINDS:
139
+ return [node_to_plain(item) for item in node.children if item.kind not in TRIVIA_KINDS]
140
+ if node.kind in ENTRY_KINDS:
141
+ return node_to_plain(node.children[0]) if node.children else None
142
+ if node.kind in (KIND_SCALAR, KIND_BLOCK):
143
+ return node.fields.get("value")
144
+ if node.kind == KIND_TRIVIA:
145
+ return None
146
+ raise unsupported(str(node.kind), f"node kind {node.kind!r} has no YAML value")
147
+
148
+
149
+ def plain_to_node(builder: NodeBuilder, value: Any, seen: frozenset) -> Node:
150
+ """Build raw-less nodes from a plain Python value, for canonical output.
151
+
152
+ ``seen`` carries the ``id()`` of every container on the recursion path, so
153
+ a self-referential structure raises ``UNSUPPORTED_TRANSLATION`` instead of
154
+ recursing forever. Block kinds are used throughout: a value with no source
155
+ text has no flow-versus-block style to preserve.
156
+ """
157
+
158
+ if isinstance(value, (dict, list, tuple)):
159
+ if id(value) in seen:
160
+ raise unsupported(type(value).__name__, "circular reference detected")
161
+ deep = seen | {id(value)}
162
+ if isinstance(value, dict):
163
+ return builder.node(KIND_MAPPING, {}, [
164
+ builder.node(KIND_PAIR, {"key": key}, (plain_to_node(builder, item, deep),))
165
+ for key, item in value.items()])
166
+ return builder.node(KIND_SEQUENCE, {}, [
167
+ builder.node(KIND_ITEM, {}, (plain_to_node(builder, item, deep),))
168
+ for item in value])
169
+ if value is None or isinstance(value, (str, int, float, bool)):
170
+ return builder.node(KIND_SCALAR, {"value": value})
171
+ raise unsupported(type(value).__name__,
172
+ f"Python type {type(value).__name__!r} has no YAML representation")
173
+
174
+
175
+ def emit_scalar(value: Any) -> str:
176
+ """Render one plain value as canonical YAML scalar text.
177
+
178
+ A string is quoted whenever its plain form would not read back as the same
179
+ string -- empty, padded, opening with an indicator, containing ``": "``,
180
+ spanning lines, or decoding as a number, boolean or null.
181
+ """
182
+
183
+ if value is None:
184
+ return "null"
185
+ if isinstance(value, bool):
186
+ return "true" if value else "false"
187
+ if isinstance(value, (int, float)):
188
+ return repr(value)
189
+ if isinstance(value, dict):
190
+ return "{}"
191
+ if isinstance(value, (list, tuple)):
192
+ return "[]"
193
+ if not isinstance(value, str):
194
+ raise unsupported(type(value).__name__,
195
+ f"Python type {type(value).__name__!r} has no YAML representation")
196
+ if (not value or value != value.strip() or value[0] in _UNSAFE_LEAD
197
+ or ": " in value or value.endswith(":") or "\n" in value
198
+ or decode_scalar(value) != value):
199
+ return json.dumps(value, ensure_ascii=False)
200
+ return value
201
+
202
+
203
+ def emit(value: Any, indent: int) -> str:
204
+ """Write plain Python data as deterministic canonical block YAML.
205
+
206
+ Two-space indentation, block style throughout, one entry per line, and an
207
+ empty collection as ``{}``/``[]``. Used only for trees with no original
208
+ source text; anything that came from the reader is replayed by
209
+ :func:`render` instead.
210
+ """
211
+
212
+ pad = " " * indent
213
+ if isinstance(value, dict) and value:
214
+ return "".join(
215
+ f"{pad}{emit_scalar(key)}:\n" + emit(item, indent + 1)
216
+ if isinstance(item, (dict, list, tuple)) and item
217
+ else f"{pad}{emit_scalar(key)}: {emit_scalar(item)}\n"
218
+ for key, item in value.items())
219
+ if isinstance(value, (list, tuple)) and value:
220
+ return "".join(
221
+ f"{pad}-\n" + emit(item, indent + 1)
222
+ if isinstance(item, (dict, list, tuple)) and item
223
+ else f"{pad}- {emit_scalar(item)}\n"
224
+ for item in value)
225
+ return pad + emit_scalar(value) + "\n"
@@ -0,0 +1,227 @@
1
+ """Flow-collection reading for the YAML plugin (concept C-016, step G-023/T-001/A-005).
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+
6
+ Scope: YAML's inline collection syntax -- flow mappings ``{a: 1}`` and flow
7
+ sequences ``[1, 2]`` -- read structurally into common-model nodes without
8
+ losing a byte. Block structure lives in :mod:`.reader`, which inherits
9
+ :class:`FlowReader` and supplies the attributes used here.
10
+
11
+ Flow collections are ordinary YAML, not an exotic corner: roughly two in five
12
+ real documents use them. They are therefore modelled properly -- one node per
13
+ collection, one entry node per element, a real key and value on every pair --
14
+ and not flattened into opaque text.
15
+
16
+ The byte-fidelity scheme ({p022}) assigns every character to exactly one
17
+ owner, which is what lets inner spacing, trailing commas, comments inside a
18
+ collection and multi-line layout all survive a round trip:
19
+
20
+ * the container's ``head`` is its opening bracket plus everything up to the
21
+ first entry (so ``[ ]`` keeps its space);
22
+ * each entry's ``tail`` is everything from the end of that entry up to the
23
+ start of the next one -- whitespace, line breaks, the comma, any comment;
24
+ * the container's ``tail`` is the closing bracket alone.
25
+
26
+ Concatenating head, entries and tail therefore reproduces the source exactly.
27
+
28
+ Source-of-truth requirement labels honored here: {p022}, {p049}, {p062}.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import bisect
34
+ from typing import Any, Dict, List, Tuple
35
+
36
+ from tree_engine.core.nodes import Node
37
+ from tree_engine.plugins.yaml.builder import NodeBuilder
38
+ from tree_engine.plugins.yaml.scanner import (
39
+ FLOW_INDICATORS, FLOW_OPENERS, KIND_FLOW_ITEM, KIND_FLOW_MAPPING, KIND_FLOW_PAIR,
40
+ KIND_FLOW_SEQUENCE, KIND_SCALAR, NO_TRANSLATION, decode_scalar, scan_quoted, syntax,
41
+ unsupported,
42
+ )
43
+
44
+ __all__ = ["ANCHOR_MESSAGE", "FlowReader"]
45
+
46
+ #: Shared wording for every anchor/alias/tag/explicit-key refusal, so the
47
+ #: block reader and the flow reader report the same construct identically.
48
+ ANCHOR_MESSAGE = "(anchor/alias/tag/explicit key) cannot round-trip faithfully"
49
+
50
+ #: Characters that may follow a ``:`` for it to read as a flow key separator.
51
+ _AFTER_COLON = ("", " ", "\t", "\r", "\n", ",", "}", "]", "{", "[")
52
+
53
+
54
+ class FlowReader:
55
+ """Reads YAML flow collections; a base of the full reader, never used alone.
56
+
57
+ The subclass provides ``text`` (the whole source), ``starts`` (the offset
58
+ each line begins at, used only to turn an offset into a line number for
59
+ error messages) and ``builder`` (the identity-assigning node factory).
60
+ Every offset in this class is an absolute index into ``text``, because a
61
+ flow collection may span any number of lines.
62
+ """
63
+
64
+ text: str
65
+ starts: List[int]
66
+ builder: NodeBuilder
67
+
68
+ def _line(self, offset: int) -> int:
69
+ """Return the 1-based source line number containing ``offset``."""
70
+
71
+ return bisect.bisect_right(self.starts, offset)
72
+
73
+ def _flow_skip(self, offset: int) -> int:
74
+ """Skip whitespace, line breaks and comments inside a flow collection.
75
+
76
+ Only ever called where a separator is expected, so a ``#`` here always
77
+ opens a comment and never belongs to a scalar.
78
+ """
79
+
80
+ while offset < len(self.text):
81
+ char = self.text[offset]
82
+ if char in " \t\r\n":
83
+ offset += 1
84
+ elif char == "#":
85
+ newline = self.text.find("\n", offset)
86
+ offset = len(self.text) if newline < 0 else newline
87
+ else:
88
+ break
89
+ return offset
90
+
91
+ def _flow_token_end(self, offset: int) -> int:
92
+ """Return the end offset of one plain or quoted token in flow context.
93
+
94
+ A quoted token is delimited by its quotes and may contain any flow
95
+ indicator; that is what keeps ``"a,b"`` and ``'{x}'`` in one piece. A
96
+ plain token ends at a flow indicator, at a ``:`` acting as a key
97
+ separator, at a comment, or at the line end. Trailing spaces are
98
+ excluded so they fall into the surrounding span instead.
99
+ """
100
+
101
+ if self.text[offset] in "\"'":
102
+ return scan_quoted(self.text, offset, self._line(offset))
103
+ end = offset
104
+ while end < len(self.text):
105
+ char = self.text[end]
106
+ if char in FLOW_INDICATORS or char == "\n":
107
+ break
108
+ if char == ":" and self.text[end + 1:end + 2] in _AFTER_COLON:
109
+ break
110
+ if char == "#" and end > offset and self.text[end - 1] == " ":
111
+ break
112
+ end += 1
113
+ while end > offset and self.text[end - 1] in " \t\r":
114
+ end -= 1
115
+ return end
116
+
117
+ def _flow_value(self, offset: int) -> Tuple[Node, int]:
118
+ """Read one value inside a flow collection: a nested flow, or a scalar."""
119
+
120
+ char = self.text[offset]
121
+ if char in NO_TRANSLATION:
122
+ raise unsupported("Anchored", f"YAML indicator {char!r} {ANCHOR_MESSAGE}")
123
+ if char in FLOW_OPENERS:
124
+ return self.read_flow(offset)
125
+ end = self._flow_token_end(offset)
126
+ raw = self.text[offset:end]
127
+ if not raw:
128
+ raise syntax("empty value in a flow collection", self._line(offset))
129
+ fields = {"raw": raw, "value": decode_scalar(raw),
130
+ "style": raw[0] if raw[0] in "\"'" else "plain"}
131
+ return self.builder.node(KIND_SCALAR, fields), end
132
+
133
+ def _explicit_key_at(self, offset: int) -> bool:
134
+ """Return whether a flow explicit-key indicator ``? `` opens at ``offset``."""
135
+
136
+ return self.text[offset] == "?" and self.text[offset + 1:offset + 2] in (" ", "\t", "\r", "\n")
137
+
138
+ def _is_sequence_pair(self, offset: int) -> bool:
139
+ """Return whether the sequence item at ``offset`` is a single-pair mapping.
140
+
141
+ YAML allows ``[a: b]`` and ``[? a : b]``: a flow sequence entry that is
142
+ a one-pair mapping. A plain or quoted key token followed by a ``:``
143
+ separator marks it; nested-flow keys are not recognised here.
144
+ """
145
+
146
+ char = self.text[offset]
147
+ if self._explicit_key_at(offset):
148
+ return True
149
+ if char in NO_TRANSLATION or char in FLOW_OPENERS or char in FLOW_INDICATORS:
150
+ return False
151
+ colon = self._flow_skip(self._flow_token_end(offset))
152
+ return (self.text[colon:colon + 1] == ":"
153
+ and self.text[colon + 1:colon + 2] in _AFTER_COLON)
154
+
155
+ def _flow_entry(self, offset: int, entry_kind: str) -> Tuple[Node, int]:
156
+ """Read one flow entry together with the separator span that follows it."""
157
+
158
+ fields: Dict[str, Any] = {}
159
+ if entry_kind == KIND_FLOW_ITEM and self._is_sequence_pair(offset):
160
+ entry_kind = KIND_FLOW_PAIR
161
+ if entry_kind == KIND_FLOW_PAIR:
162
+ start = offset
163
+ if self._explicit_key_at(offset):
164
+ offset = self._flow_skip(offset + 1)
165
+ key_end = self._flow_token_end(offset)
166
+ key_raw = self.text[offset:key_end]
167
+ if not key_raw:
168
+ raise syntax("empty key in a flow mapping", self._line(offset))
169
+ if key_raw[0] in NO_TRANSLATION:
170
+ raise unsupported("Anchored", f"YAML indicator {key_raw[0]!r} {ANCHOR_MESSAGE}")
171
+ if key_raw.startswith("<<"):
172
+ raise unsupported("MergeKey",
173
+ "YAML merge keys ('<<') cannot round-trip faithfully")
174
+ colon = self._flow_skip(key_end)
175
+ if self.text[colon:colon + 1] == ":":
176
+ value_at = self._flow_skip(colon + 1)
177
+ value, cursor = self._flow_value(value_at)
178
+ fields["head"] = self.text[start:value_at]
179
+ else: # a valueless entry: YAML's set-like "{a, b}" form
180
+ value, cursor = None, key_end
181
+ fields["head"] = self.text[start:key_end]
182
+ fields.update(key=decode_scalar(key_raw), key_raw=key_raw)
183
+ else:
184
+ value, cursor = self._flow_value(offset)
185
+ fields["head"] = ""
186
+ separator = cursor
187
+ cursor = self._flow_skip(cursor)
188
+ if self.text[cursor:cursor + 1] == ",":
189
+ cursor = self._flow_skip(cursor + 1)
190
+ fields["tail"] = self.text[separator:cursor]
191
+ children = (value,) if value is not None else ()
192
+ return self.builder.node(entry_kind, fields, children), cursor
193
+
194
+ def read_flow(self, offset: int) -> Tuple[Node, int]:
195
+ """Read the flow collection opening at ``offset``; return it and its end.
196
+
197
+ Flow collections nest freely and may span any number of lines. An
198
+ unterminated one, or one closed by the wrong bracket, is damaged
199
+ source and raises the package-private syntax signal rather than an
200
+ unsupported-translation error.
201
+ """
202
+
203
+ opener = self.text[offset]
204
+ closer = "]" if opener == "[" else "}"
205
+ sequence = opener == "["
206
+ cursor = self._flow_skip(offset + 1)
207
+ head = self.text[offset:cursor]
208
+ children: List[Node] = []
209
+ last = offset
210
+ while True:
211
+ if cursor >= len(self.text):
212
+ # Report the line of the last entry read: that is where the
213
+ # collection visibly ran on without a closer.
214
+ raise syntax("unterminated flow collection", self._line(last))
215
+ if self.text[cursor] == closer:
216
+ break
217
+ if self.text[cursor] in "}]":
218
+ raise syntax(f"expected {closer!r} in a flow collection", self._line(cursor))
219
+ entry, after = self._flow_entry(
220
+ cursor, KIND_FLOW_ITEM if sequence else KIND_FLOW_PAIR)
221
+ if after <= cursor: # a guard: an entry must always consume input
222
+ raise syntax("cannot classify flow collection content", self._line(cursor))
223
+ children.append(entry)
224
+ last = cursor
225
+ cursor = after
226
+ kind = KIND_FLOW_SEQUENCE if sequence else KIND_FLOW_MAPPING
227
+ return self.builder.node(kind, {"head": head, "tail": closer}, children), cursor + 1