codeveto 0.1.0__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 (106) hide show
  1. codeveto/__init__.py +3 -0
  2. codeveto/__main__.py +8 -0
  3. codeveto/ai/__init__.py +19 -0
  4. codeveto/ai/harness.py +303 -0
  5. codeveto/ai/packets.py +855 -0
  6. codeveto/ai/policy.py +222 -0
  7. codeveto/ai/prompt.py +101 -0
  8. codeveto/ai/providers/__init__.py +178 -0
  9. codeveto/ai/providers/claude.py +247 -0
  10. codeveto/ai/providers/openai_compat.py +246 -0
  11. codeveto/ai/runner.py +293 -0
  12. codeveto/ai/verify.py +324 -0
  13. codeveto/anchor.py +211 -0
  14. codeveto/cli.py +247 -0
  15. codeveto/cli_explain.py +49 -0
  16. codeveto/cli_hook.py +31 -0
  17. codeveto/cli_init.py +254 -0
  18. codeveto/cli_mcp.py +29 -0
  19. codeveto/cli_packets.py +35 -0
  20. codeveto/cli_publish.py +29 -0
  21. codeveto/cli_review.py +362 -0
  22. codeveto/cli_rules.py +78 -0
  23. codeveto/cli_verify.py +47 -0
  24. codeveto/config.py +1229 -0
  25. codeveto/data/README.md +16 -0
  26. codeveto/data/ai-wire.schema.json +53 -0
  27. codeveto/data/prompts/system.md +57 -0
  28. codeveto/data/report-v1.schema.json +268 -0
  29. codeveto/data/templates/forgejo-codeveto.yml +104 -0
  30. codeveto/data/templates/github-codeveto.yml +18 -0
  31. codeveto/embedded.py +311 -0
  32. codeveto/engine.py +1570 -0
  33. codeveto/git.py +1549 -0
  34. codeveto/globs.py +348 -0
  35. codeveto/integrations/__init__.py +1 -0
  36. codeveto/integrations/hooks.py +327 -0
  37. codeveto/integrations/mcp.py +770 -0
  38. codeveto/integrations/mcp_ai.py +77 -0
  39. codeveto/integrations/prepush.py +222 -0
  40. codeveto/jsonsafe.py +60 -0
  41. codeveto/languages.py +539 -0
  42. codeveto/lexers.py +2560 -0
  43. codeveto/model.py +372 -0
  44. codeveto/publish/__init__.py +28 -0
  45. codeveto/publish/action.py +330 -0
  46. codeveto/publish/common.py +84 -0
  47. codeveto/publish/diff.py +208 -0
  48. codeveto/publish/event.py +241 -0
  49. codeveto/publish/forgejo.py +184 -0
  50. codeveto/publish/github.py +380 -0
  51. codeveto/publish/http.py +263 -0
  52. codeveto/publish/pull.py +218 -0
  53. codeveto/publish/untrusted.py +110 -0
  54. codeveto/py.typed +0 -0
  55. codeveto/redact.py +113 -0
  56. codeveto/render/__init__.py +64 -0
  57. codeveto/render/agent.py +43 -0
  58. codeveto/render/github.py +101 -0
  59. codeveto/render/json.py +23 -0
  60. codeveto/render/markdown.py +208 -0
  61. codeveto/render/safe.py +249 -0
  62. codeveto/render/sarif.py +217 -0
  63. codeveto/render/text.py +210 -0
  64. codeveto/report.py +252 -0
  65. codeveto/rules/__init__.py +84 -0
  66. codeveto/rules/agent.py +2972 -0
  67. codeveto/rules/base.py +1026 -0
  68. codeveto/rules/ci.py +1708 -0
  69. codeveto/rules/config.py +493 -0
  70. codeveto/rules/deps.py +1693 -0
  71. codeveto/rules/docker.py +479 -0
  72. codeveto/rules/examples/__init__.py +148 -0
  73. codeveto/rules/examples/agent.py +839 -0
  74. codeveto/rules/examples/ci.py +1046 -0
  75. codeveto/rules/examples/config.py +191 -0
  76. codeveto/rules/examples/deps.py +369 -0
  77. codeveto/rules/examples/docker.py +157 -0
  78. codeveto/rules/examples/go.py +241 -0
  79. codeveto/rules/examples/hygiene.py +466 -0
  80. codeveto/rules/examples/js.py +462 -0
  81. codeveto/rules/examples/python.py +595 -0
  82. codeveto/rules/examples/rust.py +268 -0
  83. codeveto/rules/examples/secrets.py +561 -0
  84. codeveto/rules/examples/security.py +608 -0
  85. codeveto/rules/examples/shell.py +174 -0
  86. codeveto/rules/examples/sql.py +194 -0
  87. codeveto/rules/examples/tests.py +497 -0
  88. codeveto/rules/go.py +328 -0
  89. codeveto/rules/hygiene.py +1094 -0
  90. codeveto/rules/js.py +768 -0
  91. codeveto/rules/python.py +1642 -0
  92. codeveto/rules/rust.py +209 -0
  93. codeveto/rules/secrets.py +1335 -0
  94. codeveto/rules/security.py +3680 -0
  95. codeveto/rules/shell.py +867 -0
  96. codeveto/rules/sql.py +629 -0
  97. codeveto/rules/tests.py +1404 -0
  98. codeveto/schema.py +384 -0
  99. codeveto/statements.py +607 -0
  100. codeveto/worktree.py +1176 -0
  101. codeveto/yamlish.py +1179 -0
  102. codeveto-0.1.0.dist-info/METADATA +253 -0
  103. codeveto-0.1.0.dist-info/RECORD +106 -0
  104. codeveto-0.1.0.dist-info/WHEEL +4 -0
  105. codeveto-0.1.0.dist-info/entry_points.txt +2 -0
  106. codeveto-0.1.0.dist-info/licenses/LICENSE +21 -0
codeveto/yamlish.py ADDED
@@ -0,0 +1,1179 @@
1
+ """A bounded reader for the YAML subset that configuration files use.
2
+
3
+ :func:`parse` reads block mappings and sequences (including sequences at
4
+ their parent key's indentation), flow collections, plain, single- and
5
+ double-quoted scalars (multi-line too), block scalars (``|``/``>`` with
6
+ chomping and indentation indicators), comments and multiple documents. Tags
7
+ are kept as text; anchors and aliases are recorded and never expanded, so
8
+ alias bombs cost nothing. Scalars are strings: there is no type resolution.
9
+
10
+ Every node carries 1-based ``start_line``/``end_line`` (Git numbering) and
11
+ mapping entries carry ``key_line``.
12
+
13
+ The result separates three things:
14
+
15
+ - ``errors``: hard syntax errors only, the ones a YAML parser certainly
16
+ rejects: tab indentation outside block scalars (``tab-indent``),
17
+ inconsistent indentation (``indent``), an unterminated quoted scalar
18
+ (``unterminated-quote``) or flow collection (``unterminated-flow``), and a
19
+ mapping key where a value is required, as in ``a: b: c`` (``key-in-value``).
20
+ - ``duplicates``: duplicate keys in one mapping, with both lines.
21
+ - ``unsupported``: constructs this reader does not handle (explicit ``?``
22
+ keys, complex keys, other malformed structure) and bound overruns. The
23
+ caller treats them as partial coverage, never as a syntax error.
24
+
25
+ A document with an error or an unsupported construct is left out of
26
+ ``documents``; reading resumes at the next ``---``. Bounds: nesting depth 64,
27
+ 100,000 nodes, and input over 1 MiB is refused with an ``unsupported`` note.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import bisect
33
+ import re
34
+ from dataclasses import dataclass, field
35
+
36
+ __all__ = [
37
+ "MAX_BYTES",
38
+ "MAX_DEPTH",
39
+ "MAX_NODES",
40
+ "YamlAlias",
41
+ "YamlDocument",
42
+ "YamlDuplicate",
43
+ "YamlEntry",
44
+ "YamlError",
45
+ "YamlMap",
46
+ "YamlNode",
47
+ "YamlResult",
48
+ "YamlScalar",
49
+ "YamlSeq",
50
+ "parse",
51
+ "to_python",
52
+ ]
53
+
54
+ MAX_DEPTH = 64
55
+ MAX_NODES = 100_000
56
+ MAX_BYTES = 1 << 20
57
+
58
+
59
+ # --- Nodes ---------------------------------------------------------------------------
60
+
61
+
62
+ @dataclass(frozen=True, slots=True)
63
+ class YamlScalar:
64
+ """A scalar; ``value`` is the decoded string, ``style`` how it was written.
65
+
66
+ ``style`` is ``plain``, ``single``, ``double``, ``literal`` or ``folded``.
67
+ For a block scalar, ``start_line`` is the header line and ``content_line``
68
+ the first non-empty body line (``None`` for an empty body). ``line_map``
69
+ holds ``(offset in value, file line)`` pairs where each source line's text
70
+ starts, so :meth:`line_of` maps any offset of ``value`` to its line.
71
+ """
72
+
73
+ value: str
74
+ style: str
75
+ start_line: int
76
+ end_line: int
77
+ tag: str | None = None
78
+ anchor: str | None = None
79
+ content_line: int | None = None
80
+ line_map: tuple[tuple[int, int], ...] = ()
81
+
82
+ def line_of(self, offset: int) -> int:
83
+ """1-based file line of ``value[offset]`` (exact for literal block scalars)."""
84
+ if not self.line_map:
85
+ return self.start_line
86
+ k = bisect.bisect_right(self.line_map, (offset, 1 << 62)) - 1
87
+ return self.line_map[max(k, 0)][1]
88
+
89
+
90
+ @dataclass(frozen=True, slots=True)
91
+ class YamlAlias:
92
+ """An alias ``*name``; never expanded."""
93
+
94
+ name: str
95
+ start_line: int
96
+ end_line: int
97
+ tag: str | None = None
98
+ anchor: str | None = None
99
+
100
+
101
+ @dataclass(frozen=True, slots=True)
102
+ class YamlEntry:
103
+ """One ``key: value`` pair; ``value`` is ``None`` when empty."""
104
+
105
+ key: YamlScalar | YamlAlias
106
+ value: YamlNode | None
107
+ key_line: int
108
+
109
+ @property
110
+ def key_text(self) -> str:
111
+ return _key_text(self.key)
112
+
113
+
114
+ @dataclass(frozen=True, slots=True)
115
+ class YamlMap:
116
+ """A mapping; entries keep source order, duplicates included."""
117
+
118
+ entries: tuple[YamlEntry, ...]
119
+ start_line: int
120
+ end_line: int
121
+ flow: bool = False
122
+ tag: str | None = None
123
+ anchor: str | None = None
124
+
125
+ def get(self, key: str) -> YamlNode | None:
126
+ """The value of the last entry with ``key`` (``None`` if absent or empty)."""
127
+ entry = self.entry(key)
128
+ return None if entry is None else entry.value
129
+
130
+ def entry(self, key: str) -> YamlEntry | None:
131
+ """The last entry with ``key``, or ``None``."""
132
+ found = None
133
+ for item in self.entries:
134
+ if item.key_text == key:
135
+ found = item
136
+ return found
137
+
138
+ def keys(self) -> tuple[str, ...]:
139
+ return tuple(e.key_text for e in self.entries)
140
+
141
+
142
+ @dataclass(frozen=True, slots=True)
143
+ class YamlSeq:
144
+ """A sequence; an empty item (a bare ``-``) is ``None``."""
145
+
146
+ items: tuple[YamlNode | None, ...]
147
+ start_line: int
148
+ end_line: int
149
+ flow: bool = False
150
+ tag: str | None = None
151
+ anchor: str | None = None
152
+
153
+
154
+ YamlNode = YamlScalar | YamlAlias | YamlMap | YamlSeq
155
+
156
+
157
+ @dataclass(frozen=True, slots=True)
158
+ class YamlDocument:
159
+ """One document; ``anchors`` and ``aliases`` are ``(name, line)`` in order."""
160
+
161
+ root: YamlNode | None
162
+ start_line: int
163
+ end_line: int
164
+ anchors: tuple[tuple[str, int], ...] = ()
165
+ aliases: tuple[tuple[str, int], ...] = ()
166
+
167
+
168
+ @dataclass(frozen=True, slots=True)
169
+ class YamlError:
170
+ """A hard syntax error at a 1-based line."""
171
+
172
+ line: int
173
+ code: str
174
+ message: str
175
+
176
+
177
+ @dataclass(frozen=True, slots=True)
178
+ class YamlDuplicate:
179
+ """A key repeated in one mapping: first seen at ``first_line``, again at ``line``."""
180
+
181
+ key: str
182
+ first_line: int
183
+ line: int
184
+
185
+
186
+ @dataclass(frozen=True, slots=True)
187
+ class YamlResult:
188
+ documents: tuple[YamlDocument, ...] = ()
189
+ errors: tuple[YamlError, ...] = ()
190
+ duplicates: tuple[YamlDuplicate, ...] = ()
191
+ unsupported: tuple[str, ...] = ()
192
+
193
+ @property
194
+ def ok(self) -> bool:
195
+ """No hard error and nothing unsupported."""
196
+ return not self.errors and not self.unsupported
197
+
198
+
199
+ def _key_text(key: YamlScalar | YamlAlias) -> str:
200
+ return "*" + key.name if isinstance(key, YamlAlias) else key.value
201
+
202
+
203
+ def to_python(node: YamlNode | None) -> object:
204
+ """Plain ``dict``/``list``/``str`` view; an alias becomes ``"*name"``; later keys win."""
205
+ if node is None:
206
+ return None
207
+ if isinstance(node, YamlScalar):
208
+ return node.value
209
+ if isinstance(node, YamlAlias):
210
+ return "*" + node.name
211
+ if isinstance(node, YamlSeq):
212
+ return [to_python(item) for item in node.items]
213
+ return {e.key_text: to_python(e.value) for e in node.entries}
214
+
215
+
216
+ # --- Parser --------------------------------------------------------------------------
217
+
218
+
219
+ class _Stop(Exception):
220
+ """Abandon the current document (``error`` or unsupported ``note``)."""
221
+
222
+ def __init__(self, line: int, *, code: str = "", message: str = "", note: str = "") -> None:
223
+ super().__init__(message or note)
224
+ self.line = line
225
+ self.code = code
226
+ self.message = message
227
+ self.note = note
228
+
229
+
230
+ class _Limit(Exception):
231
+ """A global bound was hit; stop reading."""
232
+
233
+
234
+ _KEY_INDICATOR = re.compile(r":(?:[ \t]|$)|[ \t]#")
235
+ _RESERVED = frozenset("@`%")
236
+ _FLOW_PLAIN_STOP = re.compile(r"[,\[\]{}]|:(?:[ \t,\[\]{}]|$)|[ \t]#")
237
+
238
+
239
+ def _flow_plain_end(row: str, k: int) -> int | None:
240
+ """Where a plain scalar in a flow collection stops (``None``: end of row)."""
241
+ m = _FLOW_PLAIN_STOP.search(row, k)
242
+ return None if m is None else m.start()
243
+
244
+
245
+ _ESCAPES = {
246
+ "0": "\0",
247
+ "a": "\a",
248
+ "b": "\b",
249
+ "t": "\t",
250
+ "\t": "\t",
251
+ "n": "\n",
252
+ "v": "\v",
253
+ "f": "\f",
254
+ "r": "\r",
255
+ "e": "\x1b",
256
+ " ": " ",
257
+ '"': '"',
258
+ "/": "/",
259
+ "\\": "\\",
260
+ "N": "\x85",
261
+ "_": "\xa0",
262
+ "L": "\u2028",
263
+ "P": "\u2029",
264
+ }
265
+ _HEX_ESCAPES = {"x": 2, "u": 4, "U": 8}
266
+
267
+
268
+ def _is_doc_marker(line: str) -> bool:
269
+ return line.startswith(("---", "...")) and (len(line) == 3 or line[3] in " \t")
270
+
271
+
272
+ @dataclass
273
+ class _Doc:
274
+ anchors: list[tuple[str, int]] = field(default_factory=list)
275
+ aliases: list[tuple[str, int]] = field(default_factory=list)
276
+
277
+
278
+ class _Parser:
279
+ def __init__(self, text: str) -> None:
280
+ lines = text.split("\n")
281
+ if lines and lines[-1] == "":
282
+ lines.pop()
283
+ self.lines = [row[:-1] if row.endswith("\r") else row for row in lines]
284
+ self.n = len(self.lines)
285
+ self.i = 0
286
+ self.depth = 0
287
+ self.nodes = 0
288
+ self.doc = _Doc()
289
+ self.errors: list[YamlError] = []
290
+ self.duplicates: list[YamlDuplicate] = []
291
+ self.unsupported: list[str] = []
292
+
293
+ # Helpers.
294
+
295
+ def count(self) -> None:
296
+ self.nodes += 1
297
+ if self.nodes > MAX_NODES:
298
+ raise _Limit
299
+
300
+ def enter(self, line: int) -> None:
301
+ self.depth += 1
302
+ if self.depth > MAX_DEPTH:
303
+ raise _Stop(line, note=f"nesting deeper than {MAX_DEPTH}")
304
+
305
+ def leave(self) -> None:
306
+ self.depth -= 1
307
+
308
+ def unsupported_at(self, li: int, what: str) -> _Stop:
309
+ return _Stop(li + 1, note=f"line {li + 1}: {what}")
310
+
311
+ def error_at(self, li: int, code: str, message: str) -> _Stop:
312
+ return _Stop(li + 1, code=code, message=message)
313
+
314
+ def properties(
315
+ self, row: str, col: int, li: int, props: tuple[str | None, str | None], stops: str
316
+ ) -> tuple[tuple[str | None, str | None], int]:
317
+ """Anchor and tag tokens at ``col``; a node may have one of each."""
318
+ tag, anchor = props
319
+ while col < len(row) and row[col] in "&!":
320
+ stop = col
321
+ while stop < len(row) and row[stop] not in stops:
322
+ stop += 1
323
+ token = row[col:stop]
324
+ if token.startswith("&"):
325
+ if anchor is not None:
326
+ raise self.error_at(li, "properties", "a node has two anchors")
327
+ anchor = token[1:]
328
+ self.doc.anchors.append((anchor, li + 1))
329
+ else:
330
+ if tag is not None:
331
+ raise self.error_at(li, "properties", "a node has two tags")
332
+ tag = token
333
+ col = self.skip_space(row, stop)
334
+ return (tag, anchor), col
335
+
336
+ def check_plain_start(self, li: int, c: str) -> None:
337
+ if c in _RESERVED:
338
+ raise self.error_at(li, "indicator", f"{c!r} cannot start a plain scalar")
339
+
340
+ def skip_blank(self) -> int | None:
341
+ """Advance to the next content line (not blank, not only a comment)."""
342
+ while self.i < self.n:
343
+ row = self.lines[self.i]
344
+ stripped = row.lstrip(" \t")
345
+ if stripped and not stripped.startswith("#"):
346
+ return self.i
347
+ self.i += 1
348
+ return None
349
+
350
+ def indent(self, li: int) -> int:
351
+ row = self.lines[li]
352
+ n = len(row) - len(row.lstrip(" "))
353
+ if n < len(row) and row[n] == "\t":
354
+ raise self.error_at(li, "tab-indent", "tab character in indentation")
355
+ return n
356
+
357
+ def at_doc_marker(self, li: int) -> bool:
358
+ return _is_doc_marker(self.lines[li])
359
+
360
+ @staticmethod
361
+ def is_seq_entry(row: str, col: int) -> bool:
362
+ return row.startswith("-", col) and (col + 1 == len(row) or row[col + 1] in " \t")
363
+
364
+ @staticmethod
365
+ def skip_space(row: str, col: int) -> int:
366
+ while col < len(row) and row[col] in " \t":
367
+ col += 1
368
+ return col
369
+
370
+ @staticmethod
371
+ def rest_empty(row: str, col: int) -> bool:
372
+ return col >= len(row) or row[col] == "#"
373
+
374
+ # Documents.
375
+
376
+ def parse(self) -> YamlResult:
377
+ documents: list[YamlDocument] = []
378
+ try:
379
+ while True:
380
+ li = self.skip_blank()
381
+ if li is None:
382
+ break
383
+ row = self.lines[li]
384
+ if row.startswith("%"):
385
+ self.i = li + 1
386
+ continue
387
+ if row.startswith("...") and _is_doc_marker(row):
388
+ self.i = li + 1
389
+ continue
390
+ doc = self.document(li)
391
+ if doc is not None:
392
+ documents.append(doc)
393
+ except _Limit:
394
+ self.unsupported.append(f"more than {MAX_NODES} nodes; reading stopped")
395
+ return YamlResult(
396
+ tuple(documents),
397
+ tuple(self.errors),
398
+ tuple(self.duplicates),
399
+ tuple(self.unsupported),
400
+ )
401
+
402
+ def document(self, li: int) -> YamlDocument | None:
403
+ self.doc = _Doc()
404
+ self.depth = 0
405
+ start = li
406
+ try:
407
+ row = self.lines[li]
408
+ root_indent = len(row) - len(row.lstrip(" "))
409
+ if row.startswith("---") and _is_doc_marker(row):
410
+ col = self.skip_space(row, 3)
411
+ nxt_li = li + 1
412
+ while nxt_li < self.n and not self.lines[nxt_li].strip(" \t"):
413
+ nxt_li += 1
414
+ if self.rest_empty(row, col) and nxt_li < self.n:
415
+ nrow = self.lines[nxt_li]
416
+ root_indent = len(nrow) - len(nrow.lstrip(" "))
417
+ if self.rest_empty(row, col):
418
+ self.i = li + 1
419
+ root = self.block_node(-1)
420
+ else:
421
+ root = self.node_at(li, col, -1, "doc")
422
+ else:
423
+ root = self.block_node(-1)
424
+ nxt = self.skip_blank()
425
+ if nxt is not None and not self.at_doc_marker(nxt):
426
+ if self.indent(nxt) < root_indent:
427
+ raise self.error_at(nxt, "indent", "inconsistent indentation")
428
+ raise self.unsupported_at(nxt, "unexpected content after the document root")
429
+ end = (nxt if nxt is not None else self.n) - 1
430
+ if nxt is not None and self.lines[nxt].startswith("..."):
431
+ self.i = nxt + 1
432
+ return YamlDocument(
433
+ root,
434
+ start + 1,
435
+ max(end, start) + 1,
436
+ tuple(self.doc.anchors),
437
+ tuple(self.doc.aliases),
438
+ )
439
+ except _Stop as stop:
440
+ if stop.code:
441
+ self.errors.append(YamlError(stop.line, stop.code, stop.message))
442
+ else:
443
+ self.unsupported.append(stop.note)
444
+ self.resync(start)
445
+ return None
446
+ except RecursionError:
447
+ self.unsupported.append(f"line {start + 1}: document too deeply nested")
448
+ self.resync(start)
449
+ return None
450
+
451
+ def resync(self, start: int) -> None:
452
+ # Skip to the next document start (a "---" line is never inside a scalar).
453
+ i = max(self.i, start + 1)
454
+ while i < self.n and not (
455
+ self.lines[i].startswith("---") and _is_doc_marker(self.lines[i])
456
+ ):
457
+ i += 1
458
+ self.i = i
459
+
460
+ # Block structure.
461
+
462
+ def block_node(
463
+ self,
464
+ parent: int,
465
+ *,
466
+ compact: int | None = None,
467
+ props: tuple[str | None, str | None] = (None, None),
468
+ ) -> YamlNode | None:
469
+ """A node on the following lines, indented more than ``parent``.
470
+
471
+ ``compact`` allows a sequence at exactly that indentation (a mapping
472
+ value whose ``-`` entries line up with the key).
473
+ """
474
+ li = self.skip_blank()
475
+ if li is None or self.at_doc_marker(li):
476
+ return self.empty(props, self.i)
477
+ ind = self.indent(li)
478
+ if ind <= parent:
479
+ if compact is not None and ind == compact and self.is_seq_entry(self.lines[li], ind):
480
+ return self.block_seq(li, ind, props)
481
+ return self.empty(props, li)
482
+ return self.node_at(li, ind, parent, "block", props)
483
+
484
+ def empty(self, props: tuple[str | None, str | None], li: int) -> YamlNode | None:
485
+ tag, anchor = props
486
+ if tag is None and anchor is None:
487
+ return None
488
+ self.count()
489
+ line = max(li, 1)
490
+ return YamlScalar("", "plain", line, line, tag, anchor)
491
+
492
+ def node_at(
493
+ self,
494
+ li: int,
495
+ col: int,
496
+ parent: int,
497
+ ctx: str,
498
+ props: tuple[str | None, str | None] = (None, None),
499
+ ) -> YamlNode | None:
500
+ """The node whose first token is at ``(li, col)``.
501
+
502
+ ``ctx`` is ``block`` (line start), ``seq`` (after ``- ``), ``value``
503
+ (after ``key: ``) or ``doc`` (after ``--- ``).
504
+ """
505
+ row = self.lines[li]
506
+ if self.alias_has_colon(row, col):
507
+ raise self.unsupported_at(li, "alias name containing ':'")
508
+ if self.key_line(row, col):
509
+ if ctx in ("value", "doc"):
510
+ raise self.error_at(li, "key-in-value", "mapping key where a value is required")
511
+ # Properties on the first key's line belong to that key.
512
+ return self.block_map(li, col, props)
513
+ try:
514
+ props, col = self.properties(row, col, li, props, " \t")
515
+ except _Stop:
516
+ # "&map" alone on a line, then "&key [a, b]: v": the first anchor
517
+ # belongs to a mapping whose key is a flow collection.
518
+ if props != (None, None):
519
+ self.flow_key_ahead(li, col)
520
+ raise
521
+ tag, anchor = props
522
+ if self.rest_empty(row, col):
523
+ self.i = li + 1
524
+ self.enter(li + 1)
525
+ node = self.block_node(parent, compact=parent if ctx == "value" else None, props=props)
526
+ self.leave()
527
+ return self.empty(props, li + 1) if node is None else node
528
+ c = row[col]
529
+ if self.is_seq_entry(row, col):
530
+ if ctx in ("value", "doc"):
531
+ raise self.unsupported_at(li, "block sequence entry where a value is expected")
532
+ return self.block_seq(li, col, props)
533
+ if c in "|>":
534
+ return self.block_scalar(li, col, parent, props)
535
+ if c in "[{":
536
+ node, end_li, end_col = self.flow(li, col, props)
537
+ tail = self.lines[end_li]
538
+ rest = self.skip_space(tail, end_col)
539
+ if rest < len(tail) and tail[rest] == ":":
540
+ raise self.unsupported_at(end_li, "flow collection used as a mapping key")
541
+ if not self.rest_empty(tail, rest):
542
+ raise self.unsupported_at(end_li, "unexpected text after a flow collection")
543
+ self.i = end_li + 1
544
+ return node
545
+ if c == "?" and (col + 1 == len(row) or row[col + 1] in " \t"):
546
+ raise self.unsupported_at(li, "explicit mapping key ('? ')")
547
+ self.check_plain_start(li, c)
548
+ if c == "*":
549
+ stop = col + 1
550
+ while stop < len(row) and row[stop] not in " \t,[]{}":
551
+ stop += 1
552
+ name = row[col + 1 : stop]
553
+ if not name:
554
+ raise self.unsupported_at(li, "empty alias")
555
+ if not self.rest_empty(row, self.skip_space(row, stop)):
556
+ raise self.unsupported_at(li, "unexpected text after an alias")
557
+ self.count()
558
+ self.doc.aliases.append((name, li + 1))
559
+ self.i = li + 1
560
+ return YamlAlias(name, li + 1, li + 1, tag, anchor)
561
+ if c in "\"'":
562
+ scalar, end_li, end_col = self.quoted(li, col, props)
563
+ tail = self.lines[end_li]
564
+ rest = self.skip_space(tail, end_col)
565
+ if rest < len(tail) and tail[rest] == ":":
566
+ raise self.unsupported_at(li, "multi-line implicit key")
567
+ if not self.rest_empty(tail, rest):
568
+ raise self.unsupported_at(end_li, "unexpected text after a quoted scalar")
569
+ self.i = end_li + 1
570
+ return scalar
571
+ return self.plain(li, col, parent, props)
572
+
573
+ def flow_key_ahead(self, li: int, col: int) -> None:
574
+ """Report a flow collection used as a mapping key after the properties at ``col``."""
575
+ _, col = self.properties(self.lines[li], col, li, (None, None), " \t")
576
+ if not self.lines[li].startswith(("[", "{"), col):
577
+ return
578
+ _, end_li, end_col = self.flow(li, col, (None, None))
579
+ tail = self.lines[end_li]
580
+ rest = self.skip_space(tail, end_col)
581
+ if rest < len(tail) and tail[rest] == ":":
582
+ raise self.unsupported_at(end_li, "flow collection used as a mapping key")
583
+
584
+ @classmethod
585
+ def alias_has_colon(cls, row: str, col: int) -> bool:
586
+ """Is the node at ``col`` an alias whose name holds ``:`` (``*a:``)?
587
+
588
+ YAML reads the ``:`` as part of the name; libyaml-based parsers read
589
+ it as a key indicator, so the reader cannot tell what the line means.
590
+ """
591
+ while col < len(row) and row[col] in "&!":
592
+ while col < len(row) and row[col] not in " \t":
593
+ col += 1
594
+ col = cls.skip_space(row, col)
595
+ if not row.startswith("*", col):
596
+ return False
597
+ stop = col + 1
598
+ while stop < len(row) and row[stop] not in " \t,[]{}":
599
+ stop += 1
600
+ return ":" in row[col + 1 : stop]
601
+
602
+ def key_line(self, row: str, col: int) -> bool:
603
+ """Does ``row`` hold an implicit mapping key starting at ``col``?"""
604
+ while col < len(row) and row[col] in "&!":
605
+ while col < len(row) and row[col] not in " \t":
606
+ col += 1
607
+ col = self.skip_space(row, col)
608
+ if col >= len(row):
609
+ return False
610
+ c = row[col]
611
+ if c in "[{#|>" or self.is_seq_entry(row, col):
612
+ return False
613
+ if c == "?" and (col + 1 == len(row) or row[col + 1] in " \t"):
614
+ return False
615
+ if c in "\"'":
616
+ stop = self.quote_end(row, col)
617
+ if stop is None:
618
+ return False
619
+ elif c == "*":
620
+ stop = col + 1
621
+ while stop < len(row) and row[stop] not in " \t,[]{}:":
622
+ stop += 1
623
+ else:
624
+ found = _KEY_INDICATOR.search(row, col)
625
+ return found is not None and found.group()[0] == ":"
626
+ rest = self.skip_space(row, stop)
627
+ return (
628
+ rest < len(row)
629
+ and row[rest] == ":"
630
+ and (rest + 1 == len(row) or row[rest + 1] in " \t")
631
+ )
632
+
633
+ @staticmethod
634
+ def quote_end(row: str, col: int) -> int | None:
635
+ """Index after the quote that closes the scalar at ``col`` on the same row."""
636
+ q = row[col]
637
+ k = col + 1
638
+ while k < len(row):
639
+ ch = row[k]
640
+ if q == '"' and ch == "\\":
641
+ k += 2
642
+ continue
643
+ if ch == q:
644
+ if q == "'" and row.startswith("''", k):
645
+ k += 2
646
+ continue
647
+ return k + 1
648
+ k += 1
649
+ return None
650
+
651
+ def parse_key(self, li: int, col: int) -> tuple[YamlScalar | YamlAlias, int]:
652
+ """The key at ``(li, col)``; return it and the column after its ``:``."""
653
+ row = self.lines[li]
654
+ (tag, anchor), col = self.properties(row, col, li, (None, None), " \t")
655
+ if col >= len(row):
656
+ raise self.unsupported_at(li, "empty mapping key")
657
+ c = row[col]
658
+ self.check_plain_start(li, c)
659
+ self.count()
660
+ key: YamlScalar | YamlAlias
661
+ if c in "\"'":
662
+ key, end_li, end_col = self.quoted(li, col, (tag, anchor))
663
+ if end_li != li:
664
+ raise self.unsupported_at(li, "multi-line implicit key")
665
+ colon = self.skip_space(row, end_col)
666
+ elif c == "*":
667
+ if self.alias_has_colon(row, col):
668
+ raise self.unsupported_at(li, "alias name containing ':'")
669
+ stop = col + 1
670
+ while stop < len(row) and row[stop] not in " \t:":
671
+ stop += 1
672
+ key = YamlAlias(row[col + 1 : stop], li + 1, li + 1, tag, anchor)
673
+ self.doc.aliases.append((key.name, li + 1))
674
+ colon = self.skip_space(row, stop)
675
+ elif c in "[{":
676
+ raise self.unsupported_at(li, "flow collection used as a mapping key")
677
+ elif c == "?":
678
+ raise self.unsupported_at(li, "explicit mapping key ('? ')")
679
+ else:
680
+ found = _KEY_INDICATOR.search(row, col)
681
+ if found is None or found.group()[0] != ":":
682
+ raise self.unsupported_at(li, "expected a mapping key")
683
+ text = row[col : found.start()].rstrip(" \t")
684
+ if not text:
685
+ raise self.unsupported_at(li, "empty mapping key")
686
+ key = YamlScalar(text, "plain", li + 1, li + 1, tag, anchor)
687
+ colon = found.start()
688
+ if colon >= len(row) or row[colon] != ":":
689
+ raise self.unsupported_at(li, "expected ':' after a mapping key")
690
+ return key, colon + 1
691
+
692
+ def block_map(self, li: int, m: int, props: tuple[str | None, str | None]) -> YamlMap:
693
+ """A block mapping whose keys sit at column ``m``, the first on line ``li``."""
694
+ self.enter(li + 1)
695
+ self.count()
696
+ entries: list[YamlEntry] = []
697
+ seen: dict[str, int] = {}
698
+ last = cur = li
699
+ while True:
700
+ key, after = self.parse_key(cur, m)
701
+ name = _key_text(key)
702
+ if name in seen:
703
+ self.duplicates.append(YamlDuplicate(name, seen[name], cur + 1))
704
+ else:
705
+ seen[name] = cur + 1
706
+ row = self.lines[cur]
707
+ col = self.skip_space(row, after)
708
+ if self.rest_empty(row, col):
709
+ self.i = cur + 1
710
+ value = self.block_node(m, compact=m)
711
+ else:
712
+ value = self.node_at(cur, col, m, "value")
713
+ entries.append(YamlEntry(key, value, cur + 1))
714
+ last = max(cur, self.i - 1)
715
+ nxt = self.skip_blank()
716
+ if nxt is None or self.at_doc_marker(nxt):
717
+ break
718
+ ind = self.indent(nxt)
719
+ if ind < m:
720
+ break
721
+ if ind > m:
722
+ raise self.error_at(nxt, "indent", "inconsistent indentation")
723
+ if self.is_seq_entry(self.lines[nxt], ind):
724
+ raise self.unsupported_at(nxt, "sequence entry inside a mapping")
725
+ cur = nxt
726
+ self.leave()
727
+ tag, anchor = props
728
+ return YamlMap(tuple(entries), li + 1, self.end_line(last), False, tag, anchor)
729
+
730
+ def end_line(self, last: int) -> int:
731
+ # The last consumed content line (skipping trailing blank lines).
732
+ i = min(last, self.n - 1)
733
+ while i > 0 and not self.lines[i].strip(" \t"):
734
+ i -= 1
735
+ return i + 1
736
+
737
+ def block_seq(self, li: int, d: int, props: tuple[str | None, str | None]) -> YamlSeq:
738
+ self.enter(li + 1)
739
+ self.count()
740
+ items: list[YamlNode | None] = []
741
+ cur = li
742
+ last = li
743
+ while True:
744
+ row = self.lines[cur]
745
+ col = self.skip_space(row, d + 1)
746
+ if self.rest_empty(row, col):
747
+ self.i = cur + 1
748
+ item = self.block_node(d)
749
+ else:
750
+ item = self.node_at(cur, col, d, "seq")
751
+ items.append(item)
752
+ last = max(cur, self.i - 1)
753
+ nxt = self.skip_blank()
754
+ if nxt is None or self.at_doc_marker(nxt):
755
+ break
756
+ ind = self.indent(nxt)
757
+ if ind < d:
758
+ break
759
+ if ind > d:
760
+ raise self.error_at(nxt, "indent", "inconsistent indentation")
761
+ if not self.is_seq_entry(self.lines[nxt], d):
762
+ break
763
+ cur = nxt
764
+ self.leave()
765
+ tag, anchor = props
766
+ return YamlSeq(tuple(items), li + 1, self.end_line(last), False, tag, anchor)
767
+
768
+ def plain(
769
+ self, li: int, col: int, parent: int, props: tuple[str | None, str | None]
770
+ ) -> YamlScalar:
771
+ row = self.lines[li]
772
+ cut = _KEY_INDICATOR.search(row, col)
773
+ first = row[col : cut.start() if cut is not None else len(row)].rstrip(" \t")
774
+ parts = [first]
775
+ line_map = [(0, li + 1)]
776
+ length = len(first)
777
+ last = li
778
+ blank = 0
779
+ j = li + 1
780
+ if cut is None:
781
+ while j < self.n:
782
+ line = self.lines[j]
783
+ stripped = line.strip(" \t")
784
+ if not stripped:
785
+ blank += 1
786
+ j += 1
787
+ continue
788
+ ind = len(line) - len(line.lstrip(" "))
789
+ if ind <= parent or line[ind] in "\t#" or (ind == 0 and _is_doc_marker(line)):
790
+ break
791
+ found = _KEY_INDICATOR.search(line, ind)
792
+ if found is not None and found.group()[0] == ":":
793
+ raise self.error_at(j, "key-in-value", "mapping key where a value is required")
794
+ text = line[ind : found.start() if found is not None else len(line)].strip(" \t")
795
+ sep = "\n" * blank if blank else " "
796
+ parts.append(sep)
797
+ line_map.append((length + len(sep), j + 1))
798
+ length += len(sep) + len(text)
799
+ parts.append(text)
800
+ blank = 0
801
+ last = j
802
+ j += 1
803
+ if found is not None:
804
+ break
805
+ self.i = last + 1
806
+ self.count()
807
+ tag, anchor = props
808
+ return YamlScalar(
809
+ "".join(parts), "plain", li + 1, last + 1, tag, anchor, line_map=tuple(line_map)
810
+ )
811
+
812
+ def block_scalar(
813
+ self, li: int, col: int, parent: int, props: tuple[str | None, str | None]
814
+ ) -> YamlScalar:
815
+ row = self.lines[li]
816
+ style = "literal" if row[col] == "|" else "folded"
817
+ k = col + 1
818
+ chomp = ""
819
+ explicit = 0
820
+ while k < len(row) and row[k] in "+-123456789":
821
+ if row[k] in "+-":
822
+ chomp = row[k]
823
+ else:
824
+ explicit = int(row[k])
825
+ k += 1
826
+ k2 = self.skip_space(row, k)
827
+ if k2 < len(row) and (row[k2] != "#" or k2 == k):
828
+ raise self.unsupported_at(li, "unexpected text after a block scalar header")
829
+ content_indent = max(parent, -1) + explicit if explicit else -1
830
+ j = li + 1
831
+ body: list[str] = []
832
+ first_content: int | None = None
833
+ last_content = li
834
+ while j < self.n:
835
+ line = self.lines[j]
836
+ spaces = len(line) - len(line.lstrip(" "))
837
+ if not line.strip(" \t"):
838
+ body.append(line[content_indent:] if content_indent > 0 else "")
839
+ j += 1
840
+ continue
841
+ if content_indent < 0:
842
+ if spaces <= parent:
843
+ break
844
+ content_indent = spaces
845
+ if spaces < content_indent:
846
+ break
847
+ if first_content is None:
848
+ first_content = j
849
+ body.append(line[content_indent:])
850
+ last_content = j
851
+ j += 1
852
+ kept = body[: (last_content - li)] if first_content is not None else []
853
+ trailing = len(body) - len(kept)
854
+ # Body line k (0-based) is file line li + 2 + k.
855
+ if style == "literal":
856
+ value = "\n".join(kept)
857
+ line_map: list[tuple[int, int]] = []
858
+ length = 0
859
+ for k_line, text in enumerate(kept):
860
+ line_map.append((length, li + 2 + k_line))
861
+ length += len(text) + 1
862
+ else:
863
+ value, line_map = _fold(kept, li + 2)
864
+ if kept:
865
+ if chomp == "+":
866
+ value += "\n" * (1 + trailing)
867
+ elif chomp != "-":
868
+ value += "\n"
869
+ self.i = last_content + 1 if first_content is not None else li + 1
870
+ self.count()
871
+ tag, anchor = props
872
+ return YamlScalar(
873
+ value,
874
+ style,
875
+ li + 1,
876
+ last_content + 1,
877
+ tag,
878
+ anchor,
879
+ None if first_content is None else first_content + 1,
880
+ tuple(line_map),
881
+ )
882
+
883
+ # Scalars and flow collections.
884
+
885
+ def quoted(
886
+ self, li: int, col: int, props: tuple[str | None, str | None]
887
+ ) -> tuple[YamlScalar, int, int]:
888
+ """A quoted scalar from ``(li, col)``; return it and where it ends."""
889
+ q = self.lines[li][col]
890
+ out: list[str] = []
891
+ marks = [(0, li + 1)] # (index into out, file line) where each line starts
892
+ j = li
893
+ k = col + 1
894
+ pending_break = False
895
+ while True:
896
+ row = self.lines[j]
897
+ if pending_break:
898
+ k = self.skip_space(row, 0)
899
+ pending_break = False
900
+ marks.append((len(out), j + 1))
901
+ if q == "'":
902
+ close = row.find("'", k)
903
+ if close >= 0 and row.startswith("''", close):
904
+ out.append(row[k:close] + "'")
905
+ k = close + 2
906
+ continue
907
+ if close >= 0:
908
+ out.append(row[k:close])
909
+ end_col = close + 1
910
+ break
911
+ out.append(row[k:].rstrip(" \t"))
912
+ else:
913
+ stop = k
914
+ done = False
915
+ escaped_break = False
916
+ while stop < len(row):
917
+ ch = row[stop]
918
+ if ch == '"':
919
+ out.append(row[k:stop])
920
+ end_col = stop + 1
921
+ done = True
922
+ break
923
+ if ch == "\\":
924
+ out.append(row[k:stop])
925
+ if stop + 1 >= len(row):
926
+ escaped_break = True
927
+ stop += 1
928
+ k = stop
929
+ break
930
+ decoded, width = self.escape(row, stop, j)
931
+ out.append(decoded)
932
+ stop += width
933
+ k = stop
934
+ continue
935
+ stop += 1
936
+ if done:
937
+ break
938
+ if not escaped_break:
939
+ out.append(row[k:].rstrip(" \t"))
940
+ elif out and out[-1] == "":
941
+ out.pop()
942
+ # The scalar continues on the next line.
943
+ j += 1
944
+ blank = 0
945
+ while j < self.n and not self.lines[j].strip(" \t"):
946
+ blank += 1
947
+ j += 1
948
+ if j >= self.n or (_is_doc_marker(self.lines[j])):
949
+ raise self.error_at(li, "unterminated-quote", "unterminated quoted scalar")
950
+ if not (q == '"' and escaped_break):
951
+ out.append("\n" * blank if blank else " ")
952
+ elif blank:
953
+ out.append("\n" * blank)
954
+ pending_break = True
955
+ k = 0
956
+ self.count()
957
+ tag, anchor = props
958
+ style = "single" if q == "'" else "double"
959
+ offsets = [0]
960
+ for piece in out:
961
+ offsets.append(offsets[-1] + len(piece))
962
+ line_map = tuple((offsets[min(i, len(out))], line) for i, line in marks)
963
+ scalar = YamlScalar("".join(out), style, li + 1, j + 1, tag, anchor, line_map=line_map)
964
+ return scalar, j, end_col
965
+
966
+ def escape(self, row: str, at: int, li: int) -> tuple[str, int]:
967
+ ch = row[at + 1]
968
+ simple = _ESCAPES.get(ch)
969
+ if simple is not None:
970
+ return simple, 2
971
+ size = _HEX_ESCAPES.get(ch)
972
+ if size is not None:
973
+ digits = row[at + 2 : at + 2 + size]
974
+ if len(digits) == size and all(c in "0123456789abcdefABCDEF" for c in digits):
975
+ code = int(digits, 16)
976
+ if code <= 0x10FFFF:
977
+ return chr(code), 2 + size
978
+ raise self.unsupported_at(li, f"invalid escape '\\{ch}' in a double-quoted scalar")
979
+
980
+ def flow(
981
+ self, li: int, col: int, props: tuple[str | None, str | None]
982
+ ) -> tuple[YamlNode, int, int]:
983
+ """A flow collection from ``(li, col)``; return it and where it ends."""
984
+ self.enter(li + 1)
985
+ row = self.lines[li]
986
+ opener = row[col]
987
+ closer = "]" if opener == "[" else "}"
988
+ j, k = li, col + 1
989
+ items: list[YamlNode | None] = []
990
+ entries: list[YamlEntry] = []
991
+ seen: dict[str, int] = {}
992
+ while True:
993
+ j, k = self.flow_space(j, k, li)
994
+ row = self.lines[j]
995
+ c = row[k]
996
+ if c == closer:
997
+ k += 1
998
+ break
999
+ if c == ",":
1000
+ raise self.error_at(j, "flow-entry", "empty entry in a flow collection")
1001
+ if c in "]}":
1002
+ raise self.unsupported_at(j, f"mismatched {c!r} in a flow collection")
1003
+ key_line = j
1004
+ node, j, k = self.flow_item(j, k, li)
1005
+ j, k = self.flow_space(j, k, li)
1006
+ row = self.lines[j]
1007
+ value: YamlNode | None = None
1008
+ is_pair = row[k] == ":" and (
1009
+ k + 1 >= len(row)
1010
+ or row[k + 1] in " \t,[]{}"
1011
+ or not isinstance(node, YamlScalar)
1012
+ or node.style != "plain"
1013
+ )
1014
+ if is_pair:
1015
+ k += 1
1016
+ j, k = self.flow_space(j, k, li)
1017
+ if self.lines[j][k] not in ",]}":
1018
+ value, j, k = self.flow_item(j, k, li)
1019
+ if opener == "{" or is_pair:
1020
+ if isinstance(node, (YamlMap, YamlSeq)) or node is None:
1021
+ raise self.unsupported_at(key_line, "complex key in a flow collection")
1022
+ entry = YamlEntry(node, value, key_line + 1)
1023
+ if opener == "{":
1024
+ name = _key_text(node)
1025
+ if name in seen:
1026
+ self.duplicates.append(YamlDuplicate(name, seen[name], key_line + 1))
1027
+ else:
1028
+ seen[name] = key_line + 1
1029
+ entries.append(entry)
1030
+ else:
1031
+ self.count()
1032
+ items.append(YamlMap((entry,), key_line + 1, j + 1, True))
1033
+ else:
1034
+ items.append(node)
1035
+ j, k = self.flow_space(j, k, li)
1036
+ c = self.lines[j][k]
1037
+ if c == ",":
1038
+ k += 1
1039
+ elif c != closer:
1040
+ if not self.closes_later(j, k, closer):
1041
+ raise self.error_at(li, "unterminated-flow", "unterminated flow collection")
1042
+ raise self.unsupported_at(j, "expected ',' in a flow collection")
1043
+ self.leave()
1044
+ self.count()
1045
+ tag, anchor = props
1046
+ result: YamlNode
1047
+ if opener == "[":
1048
+ result = YamlSeq(tuple(items), li + 1, j + 1, True, tag, anchor)
1049
+ else:
1050
+ result = YamlMap(tuple(entries), li + 1, j + 1, True, tag, anchor)
1051
+ return result, j, k
1052
+
1053
+ def closes_later(self, j: int, k: int, closer: str) -> bool:
1054
+ # Is ``closer`` anywhere before the end of the document?
1055
+ i = j
1056
+ while i < self.n:
1057
+ row = self.lines[i]
1058
+ if i > j and _is_doc_marker(row):
1059
+ return False
1060
+ if closer in (row[k:] if i == j else row):
1061
+ return True
1062
+ i += 1
1063
+ return False
1064
+
1065
+ def flow_space(self, j: int, k: int, start: int) -> tuple[int, int]:
1066
+ """Skip whitespace, line breaks and comments inside a flow collection."""
1067
+ while True:
1068
+ row = self.lines[j]
1069
+ while k < len(row) and row[k] in " \t":
1070
+ k += 1
1071
+ if k < len(row) and not (row[k] == "#" and (k == 0 or row[k - 1] in " \t")):
1072
+ return j, k
1073
+ j += 1
1074
+ k = 0
1075
+ if j >= self.n or _is_doc_marker(self.lines[j]):
1076
+ raise self.error_at(start, "unterminated-flow", "unterminated flow collection")
1077
+
1078
+ def flow_item(self, j: int, k: int, start: int) -> tuple[YamlNode | None, int, int]:
1079
+ row = self.lines[j]
1080
+ tag = anchor = None
1081
+ while row[k] in "&!":
1082
+ (tag, anchor), stop = self.properties(row, k, j, (tag, anchor), " \t,[]{}")
1083
+ j, k = self.flow_space(j, stop, start)
1084
+ row = self.lines[j]
1085
+ c = row[k]
1086
+ if c == "?" and (k + 1 >= len(row) or row[k + 1] in " \t,[]{}"):
1087
+ raise self.unsupported_at(j, "explicit key ('? ') in a flow collection")
1088
+ if c in "[{":
1089
+ node, j, k = self.flow(j, k, (tag, anchor))
1090
+ return node, j, k
1091
+ if c in "\"'":
1092
+ scalar, j, k = self.quoted(j, k, (tag, anchor))
1093
+ return scalar, j, k
1094
+ if c == "*":
1095
+ stop = k + 1
1096
+ while stop < len(row) and row[stop] not in " \t,[]{}":
1097
+ stop += 1
1098
+ self.count()
1099
+ self.doc.aliases.append((row[k + 1 : stop], j + 1))
1100
+ return YamlAlias(row[k + 1 : stop], j + 1, j + 1, tag, anchor), j, stop
1101
+ if c in ",]}":
1102
+ return self.empty((tag, anchor), j + 1), j, k
1103
+ self.check_plain_start(j, c)
1104
+ if row.startswith("${{", k) or "${{" in row[k : (_flow_plain_end(row, k) or len(row)) + 2]:
1105
+ # GitHub reads ${{ }} here; YAML does not (its braces are flow
1106
+ # indicators), so the structure is not certain: partial coverage.
1107
+ raise self.unsupported_at(j, "${{ }} expression inside a flow collection")
1108
+ first = j
1109
+ found = _flow_plain_end(row, k)
1110
+ stop = len(row) if found is None else found
1111
+ parts = [row[k:stop].rstrip(" \t")]
1112
+ line_map = [(0, j + 1)]
1113
+ length = len(parts[0])
1114
+ # A plain scalar in a flow collection may go on over line breaks.
1115
+ while found is None:
1116
+ nj = j + 1
1117
+ while nj < self.n and not self.lines[nj].strip(" \t"):
1118
+ nj += 1
1119
+ if nj >= self.n or _is_doc_marker(self.lines[nj]):
1120
+ break
1121
+ nrow = self.lines[nj]
1122
+ nk = self.skip_space(nrow, 0)
1123
+ if nrow[nk] in ",[]{}#:\"'&!*":
1124
+ break
1125
+ j, row = nj, nrow
1126
+ found = _flow_plain_end(row, nk)
1127
+ stop = len(row) if found is None else found
1128
+ parts.append(row[nk:stop].rstrip(" \t"))
1129
+ line_map.append((length + 1, j + 1))
1130
+ length += 1 + len(parts[-1])
1131
+ self.count()
1132
+ text = " ".join(parts)
1133
+ scalar = YamlScalar(text, "plain", first + 1, j + 1, tag, anchor, line_map=tuple(line_map))
1134
+ return scalar, j, stop
1135
+
1136
+
1137
+ def _fold(lines: list[str], first_line: int) -> tuple[str, list[tuple[int, int]]]:
1138
+ """Fold a ``>`` body (lines with indentation removed, ``""`` when empty).
1139
+
1140
+ A break between two text lines becomes a space; one followed by empty
1141
+ lines becomes those lines' breaks; breaks around more-indented lines are
1142
+ kept; leading empty lines are kept. Returns the text and its line map.
1143
+ """
1144
+ out: list[str] = []
1145
+ line_map: list[tuple[int, int]] = []
1146
+ length = 0
1147
+ prev: str | None = None
1148
+ breaks = 0
1149
+ for index, line in enumerate(lines):
1150
+ if not line.strip(" \t"):
1151
+ breaks += 1
1152
+ continue
1153
+ if prev is None:
1154
+ sep = "\n" * breaks
1155
+ elif not prev.startswith((" ", "\t")) and not line.startswith((" ", "\t")):
1156
+ sep = "\n" * breaks if breaks else " "
1157
+ else:
1158
+ sep = "\n" * (breaks + 1)
1159
+ out.append(sep)
1160
+ length += len(sep)
1161
+ line_map.append((length, first_line + index))
1162
+ out.append(line)
1163
+ length += len(line)
1164
+ prev = line
1165
+ breaks = 0
1166
+ return "".join(out), line_map
1167
+
1168
+
1169
+ def parse(text: str) -> YamlResult:
1170
+ """Read ``text``; never raises. One leading byte order mark is ignored."""
1171
+ text = text.removeprefix("\ufeff")
1172
+ if len(text) > MAX_BYTES or (
1173
+ len(text) * 4 > MAX_BYTES and len(text.encode("utf-8", "surrogateescape")) > MAX_BYTES
1174
+ ):
1175
+ return YamlResult(unsupported=(f"input over {MAX_BYTES} bytes; not read",))
1176
+ try:
1177
+ return _Parser(text).parse()
1178
+ except Exception as exc: # a reader bug must not become a crash
1179
+ return YamlResult(unsupported=(f"internal reader error ({type(exc).__name__})",))