yeptris 0.6.64.0-riscv64-linux-gnu

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 (164) hide show
  1. checksums.yaml +7 -0
  2. data/README.adoc +150 -0
  3. data/ext/build_windows_native.rb +60 -0
  4. data/ext/libyeptris/extconf.rb +57 -0
  5. data/ext/yeptris_native/cbor_ruby.c +198 -0
  6. data/ext/yeptris_native/extconf.rb +99 -0
  7. data/ext/yeptris_native/json_ruby.c +414 -0
  8. data/ext/yeptris_native/version.h +29 -0
  9. data/ext/yeptris_native/yeptris_native.c +507 -0
  10. data/lib/yeptris/3.3/native.so +0 -0
  11. data/lib/yeptris/cbor.rb +169 -0
  12. data/lib/yeptris/document.rb +319 -0
  13. data/lib/yeptris/ffi.rb +572 -0
  14. data/lib/yeptris/json/descriptor.rb +266 -0
  15. data/lib/yeptris/json.rb +502 -0
  16. data/lib/yeptris/materializer.rb +389 -0
  17. data/lib/yeptris/node.rb +482 -0
  18. data/lib/yeptris/psych/class_loader.rb +24 -0
  19. data/lib/yeptris/psych/coder_shim.rb +55 -0
  20. data/lib/yeptris/psych/drop_in.rb +63 -0
  21. data/lib/yeptris/psych/encodable.rb +14 -0
  22. data/lib/yeptris/psych/handler.rb +95 -0
  23. data/lib/yeptris/psych/parser.rb +114 -0
  24. data/lib/yeptris/psych/scalar_scanner.rb +149 -0
  25. data/lib/yeptris/psych/tree_builder.rb +119 -0
  26. data/lib/yeptris/psych/visitors.rb +670 -0
  27. data/lib/yeptris/psych.rb +796 -0
  28. data/lib/yeptris/schema.rb +253 -0
  29. data/lib/yeptris/validation.rb +320 -0
  30. data/lib/yeptris/valueml.rb +477 -0
  31. data/lib/yeptris/yaml/descriptor.rb +56 -0
  32. data/lib/yeptris/yaml.rb +668 -0
  33. data/lib/yeptris.rb +130 -0
  34. data/libyeptris.so +0 -0
  35. data/vendor/libyeptris/CMakeLists.txt +280 -0
  36. data/vendor/libyeptris/cmake/yeptris-config.cmake.in +5 -0
  37. data/vendor/libyeptris/cmake/yeptris.pc.in +11 -0
  38. data/vendor/libyeptris/src/CMakeLists.txt +183 -0
  39. data/vendor/libyeptris/src/include/yeptris/api.h +32 -0
  40. data/vendor/libyeptris/src/include/yeptris/cbor.h +174 -0
  41. data/vendor/libyeptris/src/include/yeptris/dom.h +196 -0
  42. data/vendor/libyeptris/src/include/yeptris/emit.h +128 -0
  43. data/vendor/libyeptris/src/include/yeptris/error.h +42 -0
  44. data/vendor/libyeptris/src/include/yeptris/events.h +171 -0
  45. data/vendor/libyeptris/src/include/yeptris/json.h +57 -0
  46. data/vendor/libyeptris/src/include/yeptris/json.hpp +258 -0
  47. data/vendor/libyeptris/src/include/yeptris/jsonc_compat.h +115 -0
  48. data/vendor/libyeptris/src/include/yeptris/marshal.h +75 -0
  49. data/vendor/libyeptris/src/include/yeptris/parse.h +121 -0
  50. data/vendor/libyeptris/src/include/yeptris/plan.h +100 -0
  51. data/vendor/libyeptris/src/include/yeptris/resolve.h +81 -0
  52. data/vendor/libyeptris/src/include/yeptris/schema.h +121 -0
  53. data/vendor/libyeptris/src/include/yeptris/tape.h +128 -0
  54. data/vendor/libyeptris/src/include/yeptris/types.h +38 -0
  55. data/vendor/libyeptris/src/include/yeptris/validate.h +401 -0
  56. data/vendor/libyeptris/src/include/yeptris/values.h +108 -0
  57. data/vendor/libyeptris/src/include/yeptris/version.h.in +29 -0
  58. data/vendor/libyeptris/src/include/yeptris/visit.h +77 -0
  59. data/vendor/libyeptris/src/include/yeptris/yajl_compat.h +135 -0
  60. data/vendor/libyeptris/src/include/yeptris.h +24 -0
  61. data/vendor/libyeptris/src/yeptris/build.c +393 -0
  62. data/vendor/libyeptris/src/yeptris/cbor/cbor.h +35 -0
  63. data/vendor/libyeptris/src/yeptris/cbor/decode.c +1054 -0
  64. data/vendor/libyeptris/src/yeptris/cbor/encode.c +836 -0
  65. data/vendor/libyeptris/src/yeptris/cbor/encode_priv.h +32 -0
  66. data/vendor/libyeptris/src/yeptris/cbor/from_marshal.c +982 -0
  67. data/vendor/libyeptris/src/yeptris/cbor/sink.h +36 -0
  68. data/vendor/libyeptris/src/yeptris/common/chartype.c +41 -0
  69. data/vendor/libyeptris/src/yeptris/common/chartype.h +77 -0
  70. data/vendor/libyeptris/src/yeptris/common/cpu.c +81 -0
  71. data/vendor/libyeptris/src/yeptris/common/cpu.h +40 -0
  72. data/vendor/libyeptris/src/yeptris/common/error.c +65 -0
  73. data/vendor/libyeptris/src/yeptris/common/error.h +81 -0
  74. data/vendor/libyeptris/src/yeptris/common/mutex.h +45 -0
  75. data/vendor/libyeptris/src/yeptris/common/nametab.c +275 -0
  76. data/vendor/libyeptris/src/yeptris/common/nametab.h +68 -0
  77. data/vendor/libyeptris/src/yeptris/common/port.h +74 -0
  78. data/vendor/libyeptris/src/yeptris/common/simd_text.c +49 -0
  79. data/vendor/libyeptris/src/yeptris/common/simd_text.h +342 -0
  80. data/vendor/libyeptris/src/yeptris/common/simd_text_avx2.c +672 -0
  81. data/vendor/libyeptris/src/yeptris/common/simd_text_neon.c +793 -0
  82. data/vendor/libyeptris/src/yeptris/common/simd_text_scalar.c +324 -0
  83. data/vendor/libyeptris/src/yeptris/common/string_view.c +34 -0
  84. data/vendor/libyeptris/src/yeptris/common/string_view.h +93 -0
  85. data/vendor/libyeptris/src/yeptris/doc.h +86 -0
  86. data/vendor/libyeptris/src/yeptris/dom/dom.c +1312 -0
  87. data/vendor/libyeptris/src/yeptris/dom/dom.h +332 -0
  88. data/vendor/libyeptris/src/yeptris/dom/hpool.c +107 -0
  89. data/vendor/libyeptris/src/yeptris/dom/mapindex.c +173 -0
  90. data/vendor/libyeptris/src/yeptris/dom/mapindex.h +61 -0
  91. data/vendor/libyeptris/src/yeptris/dom/mutate.c +431 -0
  92. data/vendor/libyeptris/src/yeptris/dom/ytape.c +2323 -0
  93. data/vendor/libyeptris/src/yeptris/dom/ytape.h +96 -0
  94. data/vendor/libyeptris/src/yeptris/emit/emit.c +670 -0
  95. data/vendor/libyeptris/src/yeptris/emit/float/api.h +43 -0
  96. data/vendor/libyeptris/src/yeptris/emit/float/dragon.c +405 -0
  97. data/vendor/libyeptris/src/yeptris/emit/float/floatint.h +231 -0
  98. data/vendor/libyeptris/src/yeptris/emit/float/fpconv.c +428 -0
  99. data/vendor/libyeptris/src/yeptris/emit/float/print.c +396 -0
  100. data/vendor/libyeptris/src/yeptris/emit/style.c +21 -0
  101. data/vendor/libyeptris/src/yeptris/emit/style.h +32 -0
  102. data/vendor/libyeptris/src/yeptris/emit/writer.c +1951 -0
  103. data/vendor/libyeptris/src/yeptris/emit/writer.h +111 -0
  104. data/vendor/libyeptris/src/yeptris/encoding/bom.c +31 -0
  105. data/vendor/libyeptris/src/yeptris/encoding/encoding.h +63 -0
  106. data/vendor/libyeptris/src/yeptris/encoding/transcode.c +157 -0
  107. data/vendor/libyeptris/src/yeptris/encoding/utf8_validate.c +178 -0
  108. data/vendor/libyeptris/src/yeptris/events/capture.c +166 -0
  109. data/vendor/libyeptris/src/yeptris/events/capture.h +39 -0
  110. data/vendor/libyeptris/src/yeptris/events/iterparse.c +298 -0
  111. data/vendor/libyeptris/src/yeptris/events/pull.c +117 -0
  112. data/vendor/libyeptris/src/yeptris/events/push.c +151 -0
  113. data/vendor/libyeptris/src/yeptris/events/recorder.c +144 -0
  114. data/vendor/libyeptris/src/yeptris/events/values.c +630 -0
  115. data/vendor/libyeptris/src/yeptris/events/values_priv.h +53 -0
  116. data/vendor/libyeptris/src/yeptris/events/yaml_compat.c +86 -0
  117. data/vendor/libyeptris/src/yeptris/events/yaml_compat.h +90 -0
  118. data/vendor/libyeptris/src/yeptris/jsonapi/jsonc_compat.c +687 -0
  119. data/vendor/libyeptris/src/yeptris/jsonapi/yajl_compat.c +728 -0
  120. data/vendor/libyeptris/src/yeptris/marshal/to_json.c +650 -0
  121. data/vendor/libyeptris/src/yeptris/marshal.c +988 -0
  122. data/vendor/libyeptris/src/yeptris/memory/allocator.c +20 -0
  123. data/vendor/libyeptris/src/yeptris/memory/allocator.h +43 -0
  124. data/vendor/libyeptris/src/yeptris/memory/arena.c +150 -0
  125. data/vendor/libyeptris/src/yeptris/memory/arena.h +52 -0
  126. data/vendor/libyeptris/src/yeptris/memory/pool.c +133 -0
  127. data/vendor/libyeptris/src/yeptris/memory/pool.h +36 -0
  128. data/vendor/libyeptris/src/yeptris/parse/engine.c +6528 -0
  129. data/vendor/libyeptris/src/yeptris/parse/engine.h +96 -0
  130. data/vendor/libyeptris/src/yeptris/parse/events.h +137 -0
  131. data/vendor/libyeptris/src/yeptris/parse/numbers.c +374 -0
  132. data/vendor/libyeptris/src/yeptris/parse/numbers.h +33 -0
  133. data/vendor/libyeptris/src/yeptris/parse/scalars.c +435 -0
  134. data/vendor/libyeptris/src/yeptris/parse/scalars.h +87 -0
  135. data/vendor/libyeptris/src/yeptris/parse/stream_iter.c +358 -0
  136. data/vendor/libyeptris/src/yeptris/parse.c +1074 -0
  137. data/vendor/libyeptris/src/yeptris/plan.c +824 -0
  138. data/vendor/libyeptris/src/yeptris/resolve/compat11.c +339 -0
  139. data/vendor/libyeptris/src/yeptris/resolve/core12.c +153 -0
  140. data/vendor/libyeptris/src/yeptris/resolve/full12.c +201 -0
  141. data/vendor/libyeptris/src/yeptris/resolve/json12.c +109 -0
  142. data/vendor/libyeptris/src/yeptris/resolve/resolver.h +103 -0
  143. data/vendor/libyeptris/src/yeptris/resolve/tags.c +250 -0
  144. data/vendor/libyeptris/src/yeptris/scan/json.c +839 -0
  145. data/vendor/libyeptris/src/yeptris/scan/json.h +116 -0
  146. data/vendor/libyeptris/src/yeptris/scan/scan.c +862 -0
  147. data/vendor/libyeptris/src/yeptris/scan/scan.h +177 -0
  148. data/vendor/libyeptris/src/yeptris/schema.c +309 -0
  149. data/vendor/libyeptris/src/yeptris/tape.c +2375 -0
  150. data/vendor/libyeptris/src/yeptris/tape_in.h +39 -0
  151. data/vendor/libyeptris/src/yeptris/validate/compile.c +306 -0
  152. data/vendor/libyeptris/src/yeptris/validate/internal.h +347 -0
  153. data/vendor/libyeptris/src/yeptris/validate/jsonschema.c +1922 -0
  154. data/vendor/libyeptris/src/yeptris/validate/output.c +246 -0
  155. data/vendor/libyeptris/src/yeptris/validate/regexp.c +1600 -0
  156. data/vendor/libyeptris/src/yeptris/validate/registry.c +118 -0
  157. data/vendor/libyeptris/src/yeptris/validate/resources.c +601 -0
  158. data/vendor/libyeptris/src/yeptris/validate/stream.c +1155 -0
  159. data/vendor/libyeptris/src/yeptris/validate/validate.c +1043 -0
  160. data/vendor/libyeptris/src/yeptris/version.c +7 -0
  161. data/vendor/libyeptris/src/yeptris/visit/dom_visit.c +115 -0
  162. data/vendor/libyeptris/src/yeptris/visit/json_visit.c +293 -0
  163. data/vendor/libyeptris/src/yeptris/visit/yaml_visit.c +127 -0
  164. metadata +221 -0
@@ -0,0 +1,1951 @@
1
+ /* writer.c — the single writer engine (TODO.impl/13).
2
+ *
3
+ * One recursive emitter drives both sizing (dry: counts only) and
4
+ * output (wet): the size query and the bytes agree by construction.
5
+ *
6
+ * Layout contract (indent = the CONTENT column of the node):
7
+ * block map value: "key: <inline>" or "key:\n<indent+2>…"
8
+ * block seq item: "- <inline>" (compact: nested block collections
9
+ * start on the dash line at indent+2)
10
+ * flow collections re-emit compact: {k: v, k2: v2} / [a, b]
11
+ * scalars re-emit their recorded style; plain values that are not
12
+ * plain-safe in position fall back to double quotes; any multiline
13
+ * scalar emits as a literal block (deterministic upgrade: parse of
14
+ * the upgrade records literal, so byte stability holds)
15
+ * anchors: "&name " before the node; aliases: "*name"
16
+ * multi-document streams mark every document with "---"
17
+ */
18
+
19
+ #include "writer.h"
20
+
21
+ #include "../scan/scan.h"
22
+
23
+ #include <limits.h>
24
+ #include <string.h>
25
+
26
+ #include "style.h"
27
+
28
+ #include <stdio.h>
29
+ #include <stdlib.h>
30
+
31
+ #include "../../include/yeptris/resolve.h"
32
+ #include "float/api.h"
33
+ #include "resolve/resolver.h"
34
+
35
+ /* Decodes a compact node string for the writer's configured run. */
36
+ static yep_view wv(const yep_writer* w, yep_sview sv) {
37
+ yep_view v = {NULL, 0};
38
+ if (sv.len == 0) {
39
+ return v;
40
+ }
41
+ v.len = sv.len;
42
+ v.p = (sv.off & YEP_SV_INPUT ? w->sv_arena : w->sv_input) + (sv.off & YEP_SV_OFF);
43
+ return v;
44
+ }
45
+
46
+ /* Streaming flush (13C): append-only output means any high-water
47
+ * crossing is a safe cut point. */
48
+ static void wr_maybe_flush(yep_writer* w) {
49
+ if (w->sink == NULL || w->dry || w->len < w->watermark) {
50
+ return;
51
+ }
52
+ if (w->sink(w->sink_ctx, w->p, w->len) != 0) {
53
+ w->sink_aborted = 1;
54
+ return;
55
+ }
56
+ w->flushed += w->len;
57
+ w->len = 0;
58
+ }
59
+
60
+ /* the write primitives below are writer.h-visible: the marshal reader
61
+ * (marshal/to_json.c) writes through the same engine (#904 item 5's
62
+ * move kept ONE writer). */
63
+ void wr_col_update(yep_writer* w, const char* p, uint32_t n) {
64
+ for (uint32_t i = n; i > 0; i--) { /* last newline wins */
65
+ if (p[i - 1] == '\n') {
66
+ w->col = (int)(n - i);
67
+ return;
68
+ }
69
+ }
70
+ w->col += (int)n;
71
+ }
72
+
73
+ void wr_reserve(yep_writer* w, size_t need);
74
+
75
+ static void wr_grow(yep_writer* w, size_t need) {
76
+ if (w->oom || w->p == NULL) {
77
+ w->oom = w->p == NULL;
78
+ return;
79
+ }
80
+ size_t want = w->len + need + 1;
81
+ if (want < w->cap * 2) {
82
+ want = w->cap * 2;
83
+ }
84
+ /* raw realloc ON PURPOSE (#904 item 3): w->p is either the buffer
85
+ * the serializers RETURN (release contract: the host's free(),
86
+ * emit.h) or the caller's own bytes — no document allocator may
87
+ * own either, or the host's free() breaks */
88
+ char* np = (char*)realloc(w->p, want);
89
+ if (np == NULL) {
90
+ w->oom = 1;
91
+ return;
92
+ }
93
+ w->p = np;
94
+ w->cap = want;
95
+ }
96
+
97
+ void wr_put(yep_writer* w, const char* p, uint32_t n) {
98
+ if (n > 0) {
99
+ w->last = p[n - 1];
100
+ }
101
+ wr_col_update(w, p, n);
102
+ if (w->dry) {
103
+ w->len += n;
104
+ return;
105
+ }
106
+ if (w->sink != NULL && !w->grow && !w->bounded && w->cap > 0 &&
107
+ (size_t)n > w->cap - w->len - 1) {
108
+ /* the fixed-window streaming route cannot hold this put even
109
+ * after the watermark flush: CHUNK it — window-sized pieces
110
+ * with a flush between each. Append-only output makes any cut
111
+ * a safe cut; the sink sees more, smaller chunks. Memory stays
112
+ * bounded by the window (the route's whole point) — the old
113
+ * unconditional memcpy wrote straight past it for any scalar
114
+ * larger than the remaining room (the 2026-10-31 audit's
115
+ * streaming-overflow finding). */
116
+ size_t off = 0;
117
+ while (off < (size_t)n) {
118
+ if (w->sink_aborted) {
119
+ w->len += (size_t)n - off; /* keep counting: the caller fails */
120
+ return;
121
+ }
122
+ size_t room = w->cap - w->len - 1;
123
+ if (room > (size_t)n - off) {
124
+ room = (size_t)n - off;
125
+ }
126
+ memcpy(w->p + w->len, p + off, room);
127
+ w->len += room;
128
+ off += room;
129
+ if (off < (size_t)n) {
130
+ if (w->sink(w->sink_ctx, w->p, w->len) != 0) {
131
+ w->sink_aborted = 1;
132
+ } else {
133
+ w->flushed += w->len;
134
+ w->len = 0;
135
+ }
136
+ }
137
+ }
138
+ return;
139
+ }
140
+ /* the +1 reserves the terminator slot: the serializers write the
141
+ * NUL at p[len] after the run, and a write landing exactly on cap
142
+ * (len + n == cap) put that NUL one byte past the buffer — the
143
+ * first byte of the next heap block's header (the #182 flake:
144
+ * corrupt deterministic, detected later, timing-varying) */
145
+ if (w->reserve < (size_t)n) {
146
+ wr_reserve(w, n);
147
+ if (w->oom) {
148
+ w->len += n; /* keep counting: the caller fails on oom */
149
+ return;
150
+ }
151
+ }
152
+ if ((size_t)n <= w->reserve) {
153
+ w->reserve -= n;
154
+ } else {
155
+ w->reserve = 0; /* grow=0 trusts the count: the write rides past
156
+ * the bookkeeping exactly as before */
157
+ }
158
+ memcpy(w->p + w->len, p, n);
159
+ w->len += n;
160
+ }
161
+
162
+ /* #739 lane 1: refill the writable reservation. The grow and flush
163
+ * checks move from every byte to every refill; the watermark law is
164
+ * unchanged in spirit (append-only output — any crossing is a safe
165
+ * cut, a sink just sees chunks up to one reserve past the mark).
166
+ * ONLY the growing routes hold a reservation: the caller-buffer and
167
+ * trusted-count routes keep cap bookkeeping that is not the writer's
168
+ * to reason about (several set cap=0), so their writes stay exactly
169
+ * the old per-call trust. */
170
+ void wr_reserve(yep_writer* w, size_t need) {
171
+ /* the FLUSH runs for every route: the fixed-window streaming route
172
+ * (grow=0) has no reservation, so this refill path is its ONLY
173
+ * flush point -- skipping it let len ride to cap and the next
174
+ * write landed past the window (ASan: heap-buffer-overflow WRITE
175
+ * of size 2 exactly 0 bytes after the 128K region; ubuntu's
176
+ * allocator freed-corrupted, macOS's slack absorbed it). */
177
+ wr_maybe_flush(w);
178
+ if (!w->grow || w->bounded) {
179
+ w->reserve = 0;
180
+ return;
181
+ }
182
+ if (w->oom) {
183
+ return;
184
+ }
185
+ if (w->len + need + 1 > w->cap) { /* +1: the terminator */
186
+ wr_grow(w, need);
187
+ if (w->oom) {
188
+ return;
189
+ }
190
+ }
191
+ w->reserve = w->cap - w->len - 1;
192
+ }
193
+
194
+ void wr_byte(yep_writer* w, char c) {
195
+ w->last = c;
196
+ if (c == '\n') {
197
+ w->col = 0;
198
+ } else {
199
+ w->col++;
200
+ }
201
+ if (w->dry) {
202
+ w->len++;
203
+ return;
204
+ }
205
+ if (w->reserve == 0) {
206
+ wr_reserve(w, 1);
207
+ if (w->oom) {
208
+ w->len++;
209
+ return;
210
+ }
211
+ }
212
+ if (w->reserve > 0) {
213
+ w->reserve--; /* grow=0 routes keep it at 0: per-call trust */
214
+ }
215
+ w->p[w->len++] = c;
216
+ }
217
+
218
+ static void wr_indent(yep_writer* w, int depth) {
219
+ for (int i = 0; i < depth; i++) {
220
+ wr_byte(w, ' ');
221
+ }
222
+ }
223
+
224
+ /* json_pretty's per-depth indent: the default two spaces per level,
225
+ * or depth copies of the caller's unit (json.h pretty entry). */
226
+ static void wr_pretty_indent(yep_writer* w, int depth) {
227
+ if (w->json_indent == NULL) {
228
+ wr_indent(w, depth * 2);
229
+ return;
230
+ }
231
+ for (int i = 0; i < depth; i++) {
232
+ wr_put(w, w->json_indent, (uint32_t)w->json_indent_len);
233
+ }
234
+ }
235
+
236
+ static void emit_dq(yep_writer* w, const char* p, uint32_t n) {
237
+ wr_byte(w, '"');
238
+ uint32_t run = 0;
239
+ for (uint32_t i = 0; i < n; i++) {
240
+ unsigned char c = (unsigned char)p[i];
241
+ /* U+0085 (NEL) is a BREAK in YAML: raw it would fold on
242
+ * re-parse. Escape it ('\N' replaces the exact UTF-8 pair, so
243
+ * lengths stay equal). The nightly's fuzz_roundtrip
244
+ * byte-instability crasher, "\"1 \\N\"". */
245
+ if (c == 0xc2 && i + 1 < n && (unsigned char)p[i + 1] == 0x85) {
246
+ if (run) {
247
+ wr_put(w, p + i - run, run);
248
+ run = 0;
249
+ }
250
+ wr_put(w, "\\N", 2);
251
+ i++;
252
+ continue;
253
+ }
254
+ /* LS/PS (U+2028/U+2029) are libyaml breaks: raw, re-parse
255
+ * folds them (the nightly's ";\\P" catch). 2-char escapes of
256
+ * 3-byte sequences: the one-pass dry count sizes them. */
257
+ if (c == 0xe2 && i + 2 < n && (unsigned char)p[i + 1] == 0x80 &&
258
+ ((unsigned char)p[i + 2] == 0xa8 || (unsigned char)p[i + 2] == 0xa9)) {
259
+ if (run) {
260
+ wr_put(w, p + i - run, run);
261
+ run = 0;
262
+ }
263
+ wr_put(w, (unsigned char)p[i + 2] == 0xa8 ? "\\L" : "\\P", 2);
264
+ i += 2;
265
+ continue;
266
+ }
267
+ /* C1 controls (U+0080..U+009F, the UTF-8 pairs c2 80..c2 9f)
268
+ * are NON-PRINTABLE: raw, the re-parse's printability gate
269
+ * rejects the very document we just wrote (the nightly's
270
+ * "\x999" catch — \x99 decodes to U+0099 and the raw pair
271
+ * c2 99 cannot ride). Psych escapes the whole C1 range; the
272
+ * \xNN escape re-enters the doc the same way it left. */
273
+ if (c == 0xc2 && i + 1 < n && (unsigned char)p[i + 1] >= 0x80 &&
274
+ (unsigned char)p[i + 1] <= 0x9f) {
275
+ static const char hd[] = "0123456789ABCDEF";
276
+ if (run) {
277
+ wr_put(w, p + i - run, run);
278
+ run = 0;
279
+ }
280
+ wr_byte(w, '\\');
281
+ wr_byte(w, 'x');
282
+ wr_byte(w, hd[(unsigned char)p[i + 1] >> 4]);
283
+ wr_byte(w, hd[(unsigned char)p[i + 1] & 0xf]);
284
+ i++;
285
+ continue;
286
+ }
287
+ /* U+FFFE/U+FFFF are noncharacters: the printable validator
288
+ * rejects them raw, so emitting them raw makes the document
289
+ * un-re-parseable (the nightly's "["\\uFFFE"]" catch). Their
290
+ * escapes re-enter the doc the same way they left. */
291
+ if (c == 0xef && i + 2 < n && (unsigned char)p[i + 1] == 0xbf &&
292
+ ((unsigned char)p[i + 2] == 0xbe || (unsigned char)p[i + 2] == 0xbf)) {
293
+ if (run) {
294
+ wr_put(w, p + i - run, run);
295
+ run = 0;
296
+ }
297
+ wr_put(w, (unsigned char)p[i + 2] == 0xbe ? "\\uFFFE" : "\\uFFFF", 6);
298
+ i += 2;
299
+ continue;
300
+ }
301
+ /* U+FEFF must never ride raw: at the buffer head it IS the
302
+ * BOM and re-parse would strip it (the nightly's UTF-32LE
303
+ * catch); Psych escapes it everywhere ("") */
304
+ if (c == 0xef && i + 2 < n && (unsigned char)p[i + 1] == 0xbb &&
305
+ (unsigned char)p[i + 2] == 0xbf) {
306
+ if (run) {
307
+ wr_put(w, p + i - run, run);
308
+ run = 0;
309
+ }
310
+ wr_put(w, "\\uFEFF", 6);
311
+ i += 2;
312
+ continue;
313
+ }
314
+ if (c >= 0x20 && c != '"' && c != '\\' && c != 0x7f) {
315
+ run++;
316
+ continue;
317
+ }
318
+ if (run) {
319
+ wr_put(w, p + i - run, run);
320
+ run = 0;
321
+ }
322
+ if (c == '"' || c == '\\') {
323
+ wr_byte(w, '\\');
324
+ wr_byte(w, (char)c);
325
+ } else if (c == '\n') {
326
+ wr_put(w, "\\n", 2);
327
+ } else if (c == '\r') {
328
+ wr_put(w, "\\r", 2);
329
+ } else if (c == '\t') {
330
+ wr_put(w, "\\t", 2);
331
+ } else if (c < 0x20 || c == 0x7f) {
332
+ static const char* named[6] = {"\\0", "\\a", "\\b", "\\v", "\\f", "\\e"};
333
+ static const unsigned char code[6] = {0x00, 0x07, 0x08, 0x0b, 0x0c, 0x1b};
334
+ int k;
335
+ for (k = 0; k < 6; k++) {
336
+ if (code[k] == c) {
337
+ break;
338
+ }
339
+ }
340
+ if (k < 6) {
341
+ wr_put(w, named[k], 2);
342
+ } else {
343
+ static const char hd[] = "0123456789abcdef";
344
+ char hex[4] = {'\\', 'x', hd[(c >> 4) & 0xf], hd[c & 0xf]};
345
+ wr_put(w, hex, 4);
346
+ }
347
+ }
348
+ }
349
+ if (run) {
350
+ wr_put(w, p + n - run, run);
351
+ }
352
+ wr_byte(w, '"');
353
+ }
354
+
355
+ static void emit_sq(yep_writer* w, const char* p, uint32_t n) {
356
+ wr_byte(w, '\'');
357
+ for (uint32_t i = 0; i < n; i++) {
358
+ if (p[i] == '\'') {
359
+ wr_put(w, "''", 2);
360
+ } else {
361
+ wr_byte(w, p[i]);
362
+ }
363
+ }
364
+ wr_byte(w, '\'');
365
+ }
366
+
367
+ /* Block-side width folding (#903): libyaml's plain/single-quoted fold
368
+ * walk. At an INTERIOR single space (not the value's first or last
369
+ * byte, no adjacent spaces) with the column past best_width, the break
370
+ * REPLACES the space and the continuation re-indents to the fold
371
+ * column — parent_col + indent (libyaml's emit_scalar bumps the write
372
+ * indent to parent_indent + best_indent for the scalar's own lines).
373
+ * The folded bodies carry no breaks by construction: sc_route sends
374
+ * multiline content to DQ/literal, so the walk only decides on ' '
375
+ * (IS_SPACE — a tab is content). EXCEPTION (#1268): single-quoted
376
+ * bodies may carry breaks when the value is single-able (no
377
+ * space_break/break_space/specials) — emit_sq_folded renders those
378
+ * breaks per libyaml's write_single_quoted. Columns are BYTES, matching
379
+ * the engine's existing 13B flow fold; libyaml counts characters, so
380
+ * multi-byte content folds at slightly different points (documented
381
+ * divergence, ASCII input folds byte-identically). */
382
+
383
+ /* The fold break: libyaml's write_indent mid-scalar — indention is
384
+ * always clear there, so it is exactly a break plus the pad. */
385
+ static void wr_fold_break(yep_writer* w, int fold_col) {
386
+ wr_byte(w, '\n');
387
+ wr_indent(w, fold_col);
388
+ }
389
+
390
+ /* The shared walk for a plain body (no doubling to apply). The fold
391
+ * decision prices the PENDING run in (it flushes only at a fold): the
392
+ * live column at the candidate space is w->col + run — exactly
393
+ * libyaml's emitter->column at the same byte. */
394
+ static void emit_plain_folded(yep_writer* w, const char* p, uint32_t n, int fold_col) {
395
+ uint32_t run = 0; /* pending flush span length */
396
+ uint32_t i = 0;
397
+ while (i < n) {
398
+ if (p[i] == ' ' && i > 0 && i + 1 < n && w->col + (int)run > w->best_width &&
399
+ p[i - 1] != ' ' && p[i + 1] != ' ' && p[i - 1] != '\t' && p[i + 1] != '\t') {
400
+ if (run) {
401
+ wr_put(w, p + i - run, run);
402
+ run = 0;
403
+ }
404
+ wr_fold_break(w, fold_col);
405
+ i++; /* the fold consumes the space (libyaml: MOVE without WRITE) */
406
+ continue;
407
+ }
408
+ i++;
409
+ run++;
410
+ }
411
+ if (run) {
412
+ wr_put(w, p + n - run, run);
413
+ }
414
+ }
415
+
416
+ /* libyaml's single_quoted_allowed predicate (emitter.c analyze):
417
+ * disabled ONLY by special characters, a space immediately before a
418
+ * break (space_break), or a break immediately followed by a space
419
+ * (break_space). line_breaks and trailing_space do NOT kill it — so a
420
+ * trailing-newline scalar like "x y z\n" rides single-quoted in
421
+ * libyaml/psych ('x y z\n\n '), not double-quoted. */
422
+ static int writer_sq_allowed(const char* p, uint32_t n) {
423
+ uint32_t i;
424
+ for (i = 0; i < n; i++) {
425
+ unsigned char c = (unsigned char)p[i];
426
+ if (c < 0x20 && c != '\n' && c != '\r') {
427
+ return 0; /* special characters (the breaks ride the two
428
+ adjacency checks below) */
429
+ }
430
+ if (c == 0x7f) {
431
+ return 0;
432
+ }
433
+ if (c == ' ' && i + 1 < n && (p[i + 1] == '\n' || p[i + 1] == '\r')) {
434
+ return 0; /* space_break */
435
+ }
436
+ if ((c == '\n' || c == '\r') && i + 1 < n && p[i + 1] == ' ') {
437
+ return 0; /* break_space */
438
+ }
439
+ }
440
+ return 1;
441
+ }
442
+
443
+ /* The single-quoted twin: '' doubling rides the same walk (a doubled
444
+ * apostrophe is two written bytes; the column tracking through wr_put
445
+ * prices it in automatically). Content breaks render libyaml's
446
+ * write_single_quoted law: the first '\n' of a run writes an extra
447
+ * break (single-quoted clips one raw newline per content newline on
448
+ * re-parse), each break byte writes as-is, the byte after a break run
449
+ * re-indents to the fold column, and a trailing break re-indents
450
+ * before the closing quote (#1268: 'x y z\n\n '). */
451
+ static void emit_sq_folded(yep_writer* w, const char* p, uint32_t n, int fold_col) {
452
+ wr_byte(w, '\'');
453
+ uint32_t run = 0;
454
+ uint32_t i = 0;
455
+ int breaks = 0;
456
+ while (i < n) {
457
+ if (p[i] == '\n' || p[i] == '\r') {
458
+ if (run) {
459
+ wr_put(w, p + i - run, run);
460
+ run = 0;
461
+ }
462
+ if (!breaks && p[i] == '\n') {
463
+ wr_byte(w, '\n');
464
+ }
465
+ wr_byte(w, p[i]);
466
+ breaks = 1;
467
+ i++;
468
+ continue;
469
+ }
470
+ if (breaks) {
471
+ wr_indent(w, fold_col);
472
+ breaks = 0;
473
+ }
474
+ if (p[i] == '\'') {
475
+ if (run) {
476
+ wr_put(w, p + i - run, run);
477
+ run = 0;
478
+ }
479
+ wr_put(w, "''", 2);
480
+ i++;
481
+ continue;
482
+ }
483
+ if (p[i] == ' ' && i > 0 && i + 1 < n && w->col + (int)run > w->best_width &&
484
+ p[i - 1] != ' ' && p[i + 1] != ' ' && p[i - 1] != '\t' && p[i + 1] != '\t') {
485
+ if (run) {
486
+ wr_put(w, p + i - run, run);
487
+ run = 0;
488
+ }
489
+ wr_fold_break(w, fold_col);
490
+ i++;
491
+ continue;
492
+ }
493
+ i++;
494
+ run++;
495
+ }
496
+ if (breaks) {
497
+ wr_indent(w, fold_col);
498
+ } else if (run) {
499
+ wr_put(w, p + n - run, run);
500
+ }
501
+ wr_byte(w, '\'');
502
+ }
503
+
504
+ /* JSON string escapes: \" \\ \b \f \n \r \t and \uXXXX for other
505
+ * controls; raw UTF-8 passes through (RFC 8259). */
506
+ void emit_dq_json(yep_writer* w, const char* p, uint32_t n) {
507
+ wr_byte(w, '"');
508
+ static const char* named[32] = {
509
+ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "\\b", "\\t", "\\n",
510
+ NULL, "\\f", "\\r", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
511
+ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
512
+ };
513
+ static const char hd[] = "0123456789abcdef";
514
+ /* run-batched (the #352 emit_dq shape): clean spans ride one
515
+ * wr_put each — per-byte wr_byte calls were 14% of the json
516
+ * write lane's leaf samples (yeptris#739) */
517
+ uint32_t run = 0;
518
+ for (uint32_t i = 0; i < n; i++) {
519
+ unsigned char c = (unsigned char)p[i];
520
+ if (c >= 0x20 && c != '"' && c != '\\') {
521
+ run++;
522
+ continue;
523
+ }
524
+ if (run) {
525
+ wr_put(w, p + i - run, run);
526
+ run = 0;
527
+ }
528
+ if (c < 32 && named[c] != NULL) {
529
+ wr_put(w, named[c], 2);
530
+ } else if (c == '"' || c == '\\') {
531
+ wr_byte(w, '\\');
532
+ wr_byte(w, (char)c);
533
+ } else {
534
+ char hex[6] = {'\\', 'u', '0', '0', hd[(c >> 4) & 0xf], hd[c & 0xf]};
535
+ wr_put(w, hex, 6);
536
+ }
537
+ }
538
+ if (run) {
539
+ wr_put(w, p + n - run, run);
540
+ }
541
+ wr_byte(w, '"');
542
+ }
543
+
544
+ /* Literal block: header at the cursor, body lines at parent_col+indent.
545
+ * The explicit indicator spells the pad when it is ambiguous because
546
+ * the pad is defined as parent_col+indent everywhere (the contract
547
+ * that keeps it valid; indent=2 gives the historical '2'). */
548
+ static void emit_literal(yep_writer* w, const yep_dnode* n, int parent_col) {
549
+ yep_view vdec = wv(w, n->value);
550
+ const char* p = (const char*)vdec.p;
551
+ uint32_t len = vdec.len;
552
+ uint32_t trail = 0;
553
+ while (trail < len && p[len - 1 - trail] == '\n') {
554
+ trail++;
555
+ }
556
+ uint32_t body = len - trail;
557
+ wr_byte(w, '|');
558
+ if (trail == 0) {
559
+ wr_byte(w, '-');
560
+ } else if (trail > 1) {
561
+ wr_byte(w, '+');
562
+ }
563
+ /* libyaml's indicator rules (#290 family 4): the explicit indent
564
+ * appears when the first body line starts with a space or is
565
+ * blank — the base indent is unambiguous otherwise (the pad is
566
+ * parent_col+indent by contract; F6MC's leading-blank folded
567
+ * bodies). The digit spells the pad (#903: '2' at the default
568
+ * indent, the caller's level otherwise). */
569
+ if (body > 0 && (p[0] == ' ' || p[0] == '\n')) {
570
+ wr_byte(w, (char)('0' + w->indent));
571
+ }
572
+ wr_byte(w, '\n');
573
+ int pad = parent_col + w->indent;
574
+ wr_indent(w, pad);
575
+ for (uint32_t i = 0; i < body; i++) {
576
+ wr_byte(w, p[i]);
577
+ if (p[i] == '\n' && i + 1 < body) {
578
+ if (p[i + 1] == '\n') {
579
+ continue; /* blank interior lines ride unpadded (libyaml) */
580
+ }
581
+ wr_indent(w, pad);
582
+ }
583
+ }
584
+ /* The keep spelling writes exactly the parsed trailing breaks:
585
+ * written N reads N. (The round-32 extra break for tab-carrying
586
+ * ws-only last lines compensated a READER bug -- the tab-content
587
+ * arm consumed its line's own break without counting it toward
588
+ * trailing -- and the reader counts it now; the compensation made
589
+ * every pass GROW one break.) */
590
+ for (uint32_t i = 0; i < trail; i++) {
591
+ wr_byte(w, '\n');
592
+ }
593
+ }
594
+
595
+ /* Canonical scalar (13B): typed words and numbers plain, everything
596
+ * else double-quoted; floats re-print through the shortest printer so
597
+ * canonical output is a fixed point (parse of canonical re-prints
598
+ * identically — the byte-stability gate). The DOM stores only the tag
599
+ * + source text, so the typed arms re-derive the VALUE from the
600
+ * resolver's own tables (#937): the bool table decides true/false
601
+ * (the old length guess spelled every non-4-char true-word false), the
602
+ * int decode spells JSON-unspellable forms (0x1F/0o7) in decimal, and
603
+ * the inf/nan words ride quoted in JSON mode (no JSON infinity). */
604
+ static int json_int_token(const char* p, uint32_t n) {
605
+ /* the strict JSON int token: -?(0|[1-9][0-9]*) — leading zeros
606
+ * and a '+' are YAML-spellable but not JSON (those decode) */
607
+ uint32_t i = 0;
608
+ if (i < n && p[0] == '-') {
609
+ i = 1;
610
+ }
611
+ if (i >= n) {
612
+ return 0;
613
+ }
614
+ if (p[i] == '0') {
615
+ return i + 1 == n;
616
+ }
617
+ for (uint32_t k = i; k < n; k++) {
618
+ if (p[k] < '0' || p[k] > '9') {
619
+ return 0;
620
+ }
621
+ }
622
+ return 1;
623
+ }
624
+
625
+ static void emit_canonical_scalar(yep_writer* w, const yep_dnode* n) {
626
+ yep_view vdec = wv(w, n->value);
627
+ const char* p = (const char*)vdec.p;
628
+ uint32_t len = vdec.len;
629
+ if (n->tag.len == 0) {
630
+ switch (n->tag_id) {
631
+ case YEPTRIS_TAG_NULL:
632
+ if (w->json) {
633
+ wr_put(w, "null", 4);
634
+ } else {
635
+ wr_put(w, "~", 1);
636
+ }
637
+ return;
638
+ case YEPTRIS_TAG_BOOL: {
639
+ int bv = yep_tag_bool_value(p, len);
640
+ if (bv < 0) {
641
+ break; /* not a bool word: quoted (the resolver only
642
+ tags the table's words; defense) */
643
+ }
644
+ wr_put(w, bv ? "true" : "false", bv ? 4u : 5u);
645
+ return;
646
+ }
647
+ case YEPTRIS_TAG_FLOAT: {
648
+ const char* word = yep_tag_float_word(p, len);
649
+ if (word != NULL) {
650
+ uint32_t wl = (uint32_t)strlen(word);
651
+ if (w->json) {
652
+ emit_dq_json(w, word, wl);
653
+ } else {
654
+ wr_put(w, word, wl);
655
+ }
656
+ return;
657
+ }
658
+ char buf[40];
659
+ char* end = NULL;
660
+ char tmp[40];
661
+ uint32_t tl = len < sizeof(tmp) - 1 ? len : (uint32_t)sizeof(tmp) - 1;
662
+ memcpy(tmp, p, tl);
663
+ tmp[tl] = '\0';
664
+ double d = strtod(tmp, &end);
665
+ if (end != NULL && *end == '\0' && end != tmp) {
666
+ /* JSON floats carry the json-gem byte shape so
667
+ * JSON.generate round trips stay byte-identical
668
+ * (yeptris#651); YAML keeps the shortest shape. */
669
+ int wl = w->json ? yep_d2s_json(d, buf) : yep_d2s_shortest(d, buf);
670
+ wr_put(w, buf, (uint32_t)wl);
671
+ return;
672
+ }
673
+ break; /* unparseable view: fall through to quoting */
674
+ }
675
+ case YEPTRIS_TAG_INT:
676
+ if (!w->json || json_int_token(p, len)) {
677
+ /* YAML keeps the source text (stable, lossless); JSON
678
+ * keeps JSON-number-shaped text (big ints stay exact) */
679
+ wr_put(w, p, len);
680
+ return;
681
+ }
682
+ {
683
+ int compat = w->resolver == yep_resolver_compat11();
684
+ int64_t v;
685
+ if (yep_tag_int64(p, len, compat, &v) == 0) {
686
+ char buf[24];
687
+ int nl = snprintf(buf, sizeof buf, "%lld", (long long)v);
688
+ wr_put(w, buf, (uint32_t)nl);
689
+ return;
690
+ }
691
+ }
692
+ break; /* undecodable int text: quoted keeps JSON valid */
693
+ default:
694
+ break;
695
+ }
696
+ }
697
+ if (w->json) {
698
+ emit_dq_json(w, p, len);
699
+ } else {
700
+ emit_dq(w, p, len);
701
+ }
702
+ }
703
+
704
+ /* The fidelity-mode emission route for one scalar (#352): the dry
705
+ * pass derives it exactly once; the wet pass consumes the recorded
706
+ * byte and skips the multiline/blockable/safety analysis entirely. */
707
+ enum { YEP_SC_NOTHING = 0, YEP_SC_PLAIN, YEP_SC_SQ, YEP_SC_DQ, YEP_SC_LITERAL, YEP_SC_TILDE };
708
+ #define YEP_SC_MEMO_MIN 32u /* bytes; derive-below, memoize-above */
709
+
710
+ /* U+0085 is a break (only its \\N escape is byte-stable), U+FEFF raw is
711
+ * the BOM (re-parse would strip it), and U+2028/29 plus the
712
+ * noncharacters are their twins: content carrying any of these forces
713
+ * the double-quoted route BEFORE the plain fast path can take it (the
714
+ * nightly's fuzz_roundtrip crashers). The NEL scan matches the UTF-8
715
+ * PAIR only — a lone 0x85 is a continuation byte (U+315B = E3 85 9B).
716
+ * The block map's explicit-key promotion consults the same predicate:
717
+ * a key whose content demotes to DQ re-parses as a QUOTED key and must
718
+ * ride simple, or round two's render differs (the nightly's round 118). */
719
+
720
+ /* The flow arm below is a per-byte switch ON PURPOSE (#904 item 4's
721
+ * measured skip): the stopset SIMD kernel variant was measured at
722
+ * ~+3% median on flow-json emit (the only shape that enters the arm;
723
+ * 4-sample A/B, build-bench harness) — under the ledger's ~5% bar for
724
+ * touching the hot derive path, and within run noise under a loaded
725
+ * machine. PERF-LEDGER carries the numbers. */
726
+ static uint8_t sc_route(yep_writer* w, const char* p, uint32_t len, int as_key, uint8_t sty_in,
727
+ int has_tag, int no_exotic, int plain_fact) {
728
+ /* the parse-time fact bits (#352 lanes 2-3): a dnode verified clean
729
+ * of the dq-forced set skips that rescan, and a verified plain-safe
730
+ * span skips the safety walk — 0 (mutation-built or JSON classes)
731
+ * keeps the derive */
732
+ if (!no_exotic && yep_scan_dq_forced(p, len)) {
733
+ return YEP_SC_DQ;
734
+ }
735
+ if (w->in_flow && len > 0) {
736
+ /* flow context: the indicators TERMINATE a plain scalar — a
737
+ * raw ']' inside "{}" re-parses as a stray close (the
738
+ * nightly's "555555ta]" explicit-key crasher). Per-byte switch
739
+ * ON PURPOSE: the stopset kernel variant measured under the
740
+ * skip bar (the comment above; PERF-LEDGER has the numbers). */
741
+ for (uint32_t k = 0; k < len; k++) {
742
+ switch (p[k]) {
743
+ case ',':
744
+ case '[':
745
+ case ']':
746
+ case '{':
747
+ case '}':
748
+ case '"': /* flips the flow scanner into quoted mode */
749
+ case '\\': /* opens an escape sequence there */
750
+ case '\'': /* opens flow single-quote mode */
751
+ case '!': /* a tag indicator everywhere — "a!%!!a" rode
752
+ * plain inside a flow-rendered explicit key and
753
+ * the re-parse died in tag scanning (the
754
+ * nightly's run 38139449828) */
755
+ case '&': /* an anchor indicator — "&)J" inside a
756
+ * flow-rendered explicit key opened an anchor
757
+ * scan on ')' and the re-parse died ("did not
758
+ * find expected alphabetic or numeric
759
+ * character"; the nightly's run 38250474732) */
760
+ case '*': /* the alias twin of '&' */
761
+ case ':': /* a separating ':' — "{a: b : c}" died at the
762
+ * second ':' (the completed-pair law, catch 60);
763
+ * the nightly's run 38255134508 */
764
+ case '?': /* the explicit-key twin of ':' */
765
+ return YEP_SC_DQ;
766
+ default:
767
+ break;
768
+ }
769
+ }
770
+ }
771
+ /* the plain verdict is computed AT MOST ONCE: the case-1 arm below
772
+ * re-tests the same bytes when the head check already ran — the
773
+ * #742 profile's second call site (every plain-UNSAFE scalar paid
774
+ * the walk twice) */
775
+ int plain_ok = 0;
776
+ int plain_checked = 0;
777
+ if ((sty_in == 1) && len > 0) {
778
+ plain_ok = plain_fact;
779
+ if (!plain_ok) {
780
+ plain_ok = as_key ? yep_style_plain_key_safe(p, len) : yep_style_plain_safe(p, len);
781
+ }
782
+ plain_checked = 1;
783
+ if (plain_ok) {
784
+ return YEP_SC_PLAIN; /* plain-safe implies no breaks: memchr skipped */
785
+ }
786
+ }
787
+ int multiline = (len > 0 && memchr(p, '\n', len) != NULL);
788
+ int blockable = 0;
789
+ if (multiline && !as_key) {
790
+ /* libyaml's block_allowed law: trailing_space (a trailing
791
+ * blank), space_break (a blank immediately before a break) and
792
+ * special characters kill the block forms (#1264's family-A
793
+ * control: "x \ny" stays DQ, not `|-` with a trailing-space
794
+ * line); the all-whitespace and CR exclusions are the
795
+ * engine's established law */
796
+ int allws = 1;
797
+ int has_cr = 0;
798
+ int space_break = 0;
799
+ int trailing_blank = 0;
800
+ for (uint32_t i = 0; i < len; i++) {
801
+ unsigned char c = (unsigned char)p[i];
802
+ if (c != ' ' && c != '\t' && c != '\n' && c != '\r') {
803
+ allws = 0;
804
+ }
805
+ if (c == '\r') {
806
+ has_cr = 1;
807
+ }
808
+ if ((c == ' ' || c == '\t') && i + 1 < len && (p[i + 1] == '\n' || p[i + 1] == '\r')) {
809
+ space_break = 1;
810
+ }
811
+ }
812
+ if (len > 0) {
813
+ unsigned char last = (unsigned char)p[len - 1];
814
+ trailing_blank = last == ' ' || last == '\t';
815
+ }
816
+ blockable = !allws && !has_cr && !space_break && !trailing_blank;
817
+ }
818
+ uint8_t sty = sty_in;
819
+ if (sty == 4 || sty == 5) {
820
+ /* BLOCK SCALARS ARE ILLEGAL IN FLOW: a flow-rendered explicit
821
+ * key's subtree wrote `yaml: |` + literal content lines and
822
+ * the emission could never re-parse (the nightly's run
823
+ * 38154662070, "? !\n- name: ..." — the forced-flow key
824
+ * subtree carried literal members). In flow, literal/folded
825
+ * values ride DQ. */
826
+ if (w->in_flow) {
827
+ return YEP_SC_DQ;
828
+ }
829
+ if (multiline && as_key) {
830
+ return YEP_SC_DQ;
831
+ }
832
+ if (multiline && blockable) {
833
+ return YEP_SC_LITERAL;
834
+ }
835
+ if (multiline) {
836
+ return YEP_SC_DQ;
837
+ }
838
+ if (len == 0) {
839
+ return YEP_SC_DQ;
840
+ }
841
+ /* A TAGGED block scalar keeps the block form even single-line
842
+ * (psych's !binary emits `!binary |-` + one base64 line; an
843
+ * untagged single-line literal re-emits plain — libyaml parity,
844
+ * the #290 family) */
845
+ if (has_tag) {
846
+ return YEP_SC_LITERAL;
847
+ }
848
+ sty = 1;
849
+ }
850
+ switch (sty) {
851
+ case 1:
852
+ if (len == 0) {
853
+ return as_key ? YEP_SC_DQ : YEP_SC_NOTHING;
854
+ }
855
+ if (!plain_checked) {
856
+ plain_ok = plain_fact;
857
+ if (!plain_ok) {
858
+ plain_ok = as_key ? yep_style_plain_key_safe(p, len) : yep_style_plain_safe(p, len);
859
+ }
860
+ plain_checked = 1;
861
+ }
862
+ if (plain_ok) {
863
+ return YEP_SC_PLAIN;
864
+ }
865
+ if (!multiline) {
866
+ for (uint32_t i = 0; i < len; i++) {
867
+ if ((unsigned char)p[i] < 0x20 || (unsigned char)p[i] == 0x7f) {
868
+ return YEP_SC_DQ;
869
+ }
870
+ }
871
+ return YEP_SC_SQ;
872
+ }
873
+ /* libyaml's analyze keeps single_quoted_allowed through plain
874
+ * line breaks (only special_characters/space_break/break_space
875
+ * kill it), so a multiline plain-unsafe VALUE rides
876
+ * single-quoted — psych's 'x y z\n\n ' shape (#1268). Keys
877
+ * never go multiline-simple, and flow bodies ride the
878
+ * breakless emit_sq, so both stay DQ. */
879
+ if (!as_key && !w->in_flow && writer_sq_allowed(p, len)) {
880
+ return YEP_SC_SQ;
881
+ }
882
+ return YEP_SC_DQ;
883
+ case 2:
884
+ if (!multiline) {
885
+ return YEP_SC_SQ;
886
+ }
887
+ if (!as_key && !w->in_flow && writer_sq_allowed(p, len)) {
888
+ return YEP_SC_SQ;
889
+ }
890
+ return YEP_SC_DQ;
891
+ default:
892
+ return YEP_SC_DQ;
893
+ }
894
+ }
895
+
896
+ static void emit_scalar(yep_writer* w, const yep_dnode* n, int parent_col, int as_key) {
897
+ yep_view vdec = wv(w, n->value);
898
+ const char* p = (const char*)vdec.p;
899
+ uint32_t len = vdec.len;
900
+ if (w->canonical || w->json) {
901
+ emit_canonical_scalar(w, n);
902
+ return;
903
+ }
904
+ (void)0;
905
+ uint8_t route;
906
+ /* The memo pays only for LONG scalars: the derive cost scales with
907
+ * len (safety walk, quote scans) while the memo is a fixed store +
908
+ * cold load — on the short scalars of table-shaped documents the
909
+ * memo measured SLOWER than re-deriving (the #357 first artifact:
910
+ * json-users -36%, scalar-heavy +24%). Below the threshold both
911
+ * passes derive; the consumption-order index covers only the
912
+ * memoized long scalars, in visit order either way. */
913
+ if (w->sc_dec != NULL && len >= YEP_SC_MEMO_MIN) {
914
+ if (w->dry) {
915
+ route =
916
+ sc_route(w, p, len, as_key, n->style, n->tag.len > 0, n->no_exotic, n->plain_ok);
917
+ w->sc_dec[w->sc_i] = route;
918
+ } else {
919
+ route = w->sc_dec[w->sc_i];
920
+ }
921
+ w->sc_i++;
922
+ } else {
923
+ route = sc_route(w, p, len, as_key, n->style, n->tag.len > 0, n->no_exotic, n->plain_ok);
924
+ }
925
+ switch (route) {
926
+ case YEP_SC_NOTHING:
927
+ if (w->flow_item) {
928
+ /* a null flow-SEQ item must stay re-parseable: nothing
929
+ * after '[' reads as a leading comma ("[, x]", rejected by
930
+ * libyaml and Psych alike) — libyaml renders it '~' */
931
+ wr_put(w, "~", 1);
932
+ break;
933
+ }
934
+ break; /* an empty plain value emits as nothing (libyaml's null
935
+ rendering, issue #290) */
936
+ case YEP_SC_PLAIN:
937
+ if (w->block_fold && !as_key && !w->in_flow && len > 0) {
938
+ /* #903: block-context width folding; keys never fold
939
+ * (libyaml: allow_breaks = !simple_key_context) and flow
940
+ * members keep the flow walk */
941
+ emit_plain_folded(w, p, len, parent_col + w->indent);
942
+ } else {
943
+ wr_put(w, p, len);
944
+ }
945
+ break;
946
+ case YEP_SC_SQ:
947
+ if (w->block_fold && !as_key && !w->in_flow && len > 0) {
948
+ emit_sq_folded(w, p, len, parent_col + w->indent);
949
+ } else {
950
+ emit_sq(w, p, len);
951
+ }
952
+ break;
953
+ case YEP_SC_LITERAL:
954
+ emit_literal(w, n, parent_col);
955
+ break;
956
+ default:
957
+ emit_dq(w, p, len);
958
+ break;
959
+ }
960
+ }
961
+
962
+ /* Canonical mode renames anchors to generated names (a0, a1, ...):
963
+ * exotic source names (flow indicators inside them) cannot survive
964
+ * flow context raw, and renaming preserves the binding semantics.
965
+ * Deterministic by definition order -> byte-stable across roundtrips.
966
+ * The emitter's nametab lives in yep_emitter (owner: yep_emit_run). */
967
+ /* An anchor name carrying an indicator byte rides raw fine in block
968
+ * context (the suite's W5VH/2SXE/8XYN round-trip byte-stably), but in
969
+ * FLOW context the bytes flip scanners or terminate the entry — and
970
+ * anchors have no quoting syntax. Such a document has no safe flow
971
+ * spelling: mark it unserializable; serialize fails rather than
972
+ * emitting a form that can never re-parse (the nightly's "&\""/bang/
973
+ * question anchor vein). */
974
+ static void wr_anchor_check(yep_writer* w, const yep_view* name) {
975
+ if (!w->in_flow) {
976
+ return;
977
+ }
978
+ for (uint32_t i = 0; i < name->len; i++) {
979
+ switch (name->p[i]) {
980
+ case '"':
981
+ case '\'':
982
+ case '!':
983
+ case '?':
984
+ case '&':
985
+ case '*':
986
+ case ',':
987
+ case '[':
988
+ case ']':
989
+ case '{':
990
+ case '}':
991
+ case '%':
992
+ case '@':
993
+ case '`':
994
+ case '#':
995
+ w->unserializable = 1;
996
+ return;
997
+ default:
998
+ break;
999
+ }
1000
+ }
1001
+ }
1002
+
1003
+ /* The anchor-name spell laws, shared by every anchor write path (the
1004
+ * node lead AND the line-tail props: the round-45 bonus catch -- a
1005
+ * PS-named anchor on a SEQ spelled raw through emit_props_tail and
1006
+ * the re-parse died on the normalized break). Returns nonzero when
1007
+ * the serialize must fail. */
1008
+ static int anchor_name_unspellable(yep_writer* w, const yep_dnode* n) {
1009
+ yep_view chk = wv(w, n->anchor);
1010
+ if (chk.len == 0) {
1011
+ return 0;
1012
+ }
1013
+ if (chk.p[chk.len - 1] == ':') {
1014
+ /* a SCALAR keeps riding raw only when it spells INLINE
1015
+ * ("k: &n: v" is byte-stable); a BLOCK-style spell puts the
1016
+ * header where the separator should be ("&: |" -- the
1017
+ * nightly's round 44, crash-07ad9ecc) -- there is no spell:
1018
+ * fail the serialize */
1019
+ if (n->kind != 0 || n->style == 4 || n->style == 5) {
1020
+ w->unserializable = 1;
1021
+ return 1;
1022
+ }
1023
+ }
1024
+ /* a NORMALIZE-SUBJECT byte (LS/PS raw, NEL, or a hard break)
1025
+ * re-reads as a folded break: pass2 sees a broken/empty name and
1026
+ * dies. YAML has no quoted anchor names: fail the serialize. */
1027
+ for (size_t ci = 0; ci < chk.len; ci++) {
1028
+ unsigned char cb = (unsigned char)chk.p[ci];
1029
+ if (cb == '\n' || cb == '\r') {
1030
+ w->unserializable = 1;
1031
+ return 1;
1032
+ }
1033
+ if (cb == 0xC2 && ci + 1 < chk.len && (unsigned char)chk.p[ci + 1] == 0x85) {
1034
+ w->unserializable = 1; /* NEL */
1035
+ return 1;
1036
+ }
1037
+ if (cb == 0xE2 && ci + 2 < chk.len && (unsigned char)chk.p[ci + 1] == 0x80 &&
1038
+ ((unsigned char)chk.p[ci + 2] & 0xFE) == 0xA8) {
1039
+ w->unserializable = 1; /* LS/PS */
1040
+ return 1;
1041
+ }
1042
+ }
1043
+ return 0;
1044
+ }
1045
+
1046
+ static void emit_anchor_ex(yep_emitter* em, const yep_dnode* n) {
1047
+ yep_writer* w = &em->w;
1048
+ if (n->anchor.len == 0) {
1049
+ return;
1050
+ }
1051
+ if (anchor_name_unspellable(w, n)) {
1052
+ return;
1053
+ }
1054
+ yep_view adec = wv(w, n->anchor);
1055
+ if (w->json) {
1056
+ /* JSON spells no anchors — but a name the emitter could never
1057
+ * spell still fails the entry (the "{k: &a?b v}" law) */
1058
+ wr_anchor_check(w, &adec);
1059
+ return;
1060
+ }
1061
+ wr_byte(w, '&');
1062
+ if (w->canonical) {
1063
+ uint32_t idx = yep_nametab_get(&em->canon_names, adec);
1064
+ if (idx == YEP_NAMETAB_NIL) {
1065
+ idx = em->canon_names.count;
1066
+ yep_nametab_set(&em->canon_names, adec, idx);
1067
+ }
1068
+ char name[24];
1069
+ int nl = snprintf(name, sizeof(name), "a%u", idx);
1070
+ wr_put(w, name, (uint32_t)nl);
1071
+ } else {
1072
+ wr_anchor_check(w, &adec);
1073
+ wr_put(w, (const char*)adec.p, adec.len);
1074
+ }
1075
+ wr_byte(w, ' ');
1076
+ }
1077
+
1078
+ static void emit_alias_ex(yep_emitter* em, const yep_dnode* n) {
1079
+ yep_writer* w = &em->w;
1080
+ if (w->json) {
1081
+ /* JSON has no alias references: the projection writes null
1082
+ * (bounded — dereferencing would loop on cycles) */
1083
+ wr_put(w, "null", 4);
1084
+ return;
1085
+ }
1086
+ yep_view name_v = wv(w, n->value);
1087
+ if (w->in_flow && !w->canonical) {
1088
+ /* the alias twin of wr_anchor_check: a flow alias is spelled
1089
+ * raw and the re-parse truncates the name -- a trailing ':'
1090
+ * reads as the key/value separator there ("*n:}" names "n",
1091
+ * the block definition "n:" went unmatched: the nightly's
1092
+ * run 39021984786, "alias references an undefined anchor"
1093
+ * 3:15), and quote bytes hit the engine's flow-alias law.
1094
+ * Block aliases ride raw (2SXE/Y2GN round-trip byte-stably). */
1095
+ wr_anchor_check(w, &name_v);
1096
+ if (name_v.len > 0 && name_v.p[name_v.len - 1] == ':') {
1097
+ w->unserializable = 1;
1098
+ }
1099
+ }
1100
+ wr_byte(w, '*');
1101
+ if (w->canonical) {
1102
+ uint32_t idx = yep_nametab_get(&em->canon_names, name_v);
1103
+ char name[24];
1104
+ int nl;
1105
+ if (idx == YEP_NAMETAB_NIL) {
1106
+ nl = snprintf(name, sizeof(name), "%.*s", (int)name_v.len, (const char*)name_v.p);
1107
+ } else {
1108
+ nl = snprintf(name, sizeof(name), "a%u", idx);
1109
+ }
1110
+ wr_put(w, name, (uint32_t)nl);
1111
+ } else {
1112
+ wr_put(w, (const char*)name_v.p, name_v.len);
1113
+ }
1114
+ }
1115
+
1116
+ /* Tag bytes outside ns-tag-char ride %XX (the parse side decodes them
1117
+ * per the URI rule — a decoded newline emitted raw was the nightly's
1118
+ * byte-instability crasher "!%0a"). Uppercase hex, libyaml's form. */
1119
+ static void wr_tag_uri(yep_writer* w, const yep_view* v) {
1120
+ static const char hd[] = "0123456789ABCDEF";
1121
+ const unsigned char* p = (const unsigned char*)v->p;
1122
+ for (uint32_t i = 0; i < v->len; i++) {
1123
+ unsigned char c = p[i];
1124
+ if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
1125
+ c == '-' || c == ';' || c == '/' || c == '?' || c == ':' || c == '@' || c == '&' ||
1126
+ c == '=' || c == '+' || c == '$' || c == ',' || c == '.' || c == '!' || c == '~' ||
1127
+ c == '*' || c == '\'' || c == '(' || c == ')') {
1128
+ wr_byte(w, (char)c);
1129
+ } else {
1130
+ wr_byte(w, '%');
1131
+ wr_byte(w, hd[c >> 4]);
1132
+ wr_byte(w, hd[c & 0xf]);
1133
+ }
1134
+ }
1135
+ }
1136
+
1137
+ /* Explicit tag, verbatim URI form ("!<tag:…> "). Never skipped: a
1138
+ * recorded tag always re-emits (implied-by-style skipping made the
1139
+ * roundtrip byte-unstable: plain+!!str and ""+!!str collided). */
1140
+ /* The tag token without separators: the core namespace rides the
1141
+ * DEFAULT secondary handle (libyaml writes !!str, never
1142
+ * !<tag:yaml.org,2002:str>); a leading-'!' shorthand re-escapes its
1143
+ * interior bangs (a local tag's URI can carry them — re-parsed raw
1144
+ * they read as handles and the meaning flips); everything else is a
1145
+ * verbatim !<URI> wrap. Hosts pass the full core URI — the verbatim
1146
+ * shorthand "!!str" as a node tag collides with a LOCAL tag of the
1147
+ * same bytes (the binding's chevron-key dump regressed there). */
1148
+ static void wr_tag_token(yep_writer* w, const yep_view* tdec) {
1149
+ static const char k_core_ns[] = "tag:yaml.org,2002:";
1150
+ if (tdec->len > sizeof(k_core_ns) - 1 &&
1151
+ memcmp(tdec->p, k_core_ns, sizeof(k_core_ns) - 1) == 0) {
1152
+ yep_view suffix = {tdec->p + sizeof(k_core_ns) - 1, tdec->len - (sizeof(k_core_ns) - 1)};
1153
+ int scan_ok = 1;
1154
+ for (uint32_t si = 0; si < suffix.len; si++) {
1155
+ if (!yep_scan_tag_char((unsigned char)suffix.p[si])) {
1156
+ scan_ok = 0;
1157
+ break;
1158
+ }
1159
+ }
1160
+ /* the shorthand only holds if the suffix re-scans: the parse
1161
+ * side's tag charset terminates on ',' (and flow indicators —
1162
+ * our lenience vs libyaml's URI set), so a suffix carrying one
1163
+ * re-parses truncated and the round-trip dies (the nightly's
1164
+ * run 38132505901, the verbatim tag with an interior ',');
1165
+ * the verbatim !<...> wrap carries those */
1166
+ if (scan_ok) {
1167
+ wr_put(w, "!!", 2);
1168
+ wr_tag_uri(w, &suffix);
1169
+ return;
1170
+ }
1171
+ }
1172
+ if (tdec->len > 0 && tdec->p[0] == '!') {
1173
+ yep_view rest = {tdec->p + 1, tdec->len - 1};
1174
+ /* the LOCAL shorthand re-scans too: the parse side's tag
1175
+ * charset terminates on ',' (our lenience vs libyaml's URI
1176
+ * set), so a suffix carrying one re-parses truncated — the
1177
+ * same law the core-namespace arm gained (catch 47); the
1178
+ * verbatim !<...> wrap carries those (the nightly's run
1179
+ * 38165476712, "!<!<<b,,,,,-,,,,ar> :yam" emitted
1180
+ * "!%3C%3Cb,,,,,-,,,,ar" and died at the first comma) */
1181
+ int scan_ok = 1;
1182
+ for (uint32_t si = 0; si < rest.len; si++) {
1183
+ if (!yep_scan_tag_char((unsigned char)rest.p[si])) {
1184
+ scan_ok = 0;
1185
+ break;
1186
+ }
1187
+ }
1188
+ if (scan_ok) {
1189
+ wr_byte(w, '!');
1190
+ uint32_t run = 0;
1191
+ for (uint32_t i = 0; i < rest.len; i++) {
1192
+ if (rest.p[i] == '!') {
1193
+ if (run > 0) {
1194
+ yep_view seg = {rest.p + i - run, run};
1195
+ wr_tag_uri(w, &seg);
1196
+ run = 0;
1197
+ }
1198
+ wr_put(w, "%21", 3);
1199
+ } else {
1200
+ run++;
1201
+ }
1202
+ }
1203
+ if (run > 0) {
1204
+ yep_view seg = {rest.p + rest.len - run, run};
1205
+ wr_tag_uri(w, &seg);
1206
+ }
1207
+ return;
1208
+ }
1209
+ }
1210
+ wr_byte(w, '!');
1211
+ wr_byte(w, '<');
1212
+ wr_tag_uri(w, tdec);
1213
+ wr_byte(w, '>');
1214
+ }
1215
+
1216
+ static void emit_tag(yep_writer* w, const yep_dnode* n) {
1217
+ if (n->tag.len == 0) {
1218
+ return;
1219
+ }
1220
+ if (w->json) {
1221
+ return; /* JSON spells no tags (the ts probe: "k: !" -> {"k": ! ""}) */
1222
+ }
1223
+ yep_view tdec = wv(w, n->tag);
1224
+ wr_tag_token(w, &tdec);
1225
+ wr_byte(w, ' ');
1226
+ }
1227
+
1228
+ /* Line-tail properties for block collections: "!<t> &a" after
1229
+ * "key:"/"-" — properties may not precede a dash entry directly (the
1230
+ * suite's SY6V rule). */
1231
+ static void emit_props_tail(yep_writer* w, const yep_dnode* n) {
1232
+ if (n->anchor.len > 0 && anchor_name_unspellable(w, n)) {
1233
+ return;
1234
+ }
1235
+ if (w->json) {
1236
+ return; /* JSON spells no properties */
1237
+ }
1238
+ if (n->tag.len > 0) {
1239
+ wr_byte(w, ' ');
1240
+ yep_view tdec2 = wv(w, n->tag);
1241
+ wr_tag_token(w, &tdec2);
1242
+ }
1243
+ if (n->anchor.len > 0) {
1244
+ wr_byte(w, ' ');
1245
+ yep_view adec2 = wv(w, n->anchor);
1246
+ wr_anchor_check(w, &adec2);
1247
+ wr_byte(w, '&');
1248
+ wr_put(w, (const char*)adec2.p, adec2.len);
1249
+ }
1250
+ }
1251
+
1252
+ static void emit_node(yep_emitter* em, uint32_t id, int parent_col, int as_key);
1253
+
1254
+ /* The simple-key law counts the WRITTEN token. A quoted render
1255
+ * expands escapes (a '"' doubles, controls ride \xNN, non-ASCII may);
1256
+ * raw-length predicates let escape-heavy scalars through (the
1257
+ * nightly's run 38145696566: a ~1000-raw key rendering ~3000
1258
+ * written). Conservative factor-4 estimate for every expandable
1259
+ * byte — overestimating only takes the (always-legal) explicit form. */
1260
+ static int key_written_over_limit(yep_writer* w, const yep_dnode* kn) {
1261
+ if (w->json) {
1262
+ return 0; /* JSON has no simple-key law: every key writes (#739) */
1263
+ }
1264
+ yep_view kv_ = wv(w, kn->value);
1265
+ if (kn->anchor.len == 0 && kn->tag.len == 0 && kv_.len <= 255) {
1266
+ /* the exact bound: even at the factor-4 expansion the walk
1267
+ * budgets per byte, 255 raw bytes top out at est = 2 + 1020 —
1268
+ * under the law. Table-shaped documents pay the two field
1269
+ * checks instead of the byte walk (the #742 profile's 22%
1270
+ * lane) */
1271
+ return 0;
1272
+ }
1273
+ uint64_t est = 2; /* the quotes */
1274
+ const unsigned char* q = (const unsigned char*)kv_.p;
1275
+ uint32_t n = kv_.len;
1276
+ /* NO early return on an empty value: the tag arm below must run —
1277
+ * a TAGGED EMPTY key writes ~2300 bytes of escaped tag and the
1278
+ * re-parse's simple-key law rejects it ("the nightly's run
1279
+ * 38200627503") */
1280
+ if (q != NULL) {
1281
+ for (uint32_t i = 0; i < n; i++) {
1282
+ /* a single-quoted render DOUBLES every apostrophe; without
1283
+ * it the estimate missed a 892-char key carrying 137
1284
+ * quotes (rendered 1031, re-parse rejected the simple
1285
+ * key — the nightly's crash-b8a18e43) */
1286
+ est += (q[i] < 0x20 || q[i] >= 0x7F || q[i] == '"' || q[i] == '\\' || q[i] == '\'')
1287
+ ? 4u
1288
+ : 1u;
1289
+ }
1290
+ }
1291
+ if (kn->anchor.len > 0) {
1292
+ /* the key's ANCHOR rides the same written token: the re-parse
1293
+ * counts the '&name' bytes in the simple-key candidate, and
1294
+ * anchor names carry interior colons (Y2GN) — a ~1700-byte
1295
+ * name blew a 2-byte key past the law (the nightly's run
1296
+ * 38206305189) */
1297
+ est += (uint64_t)kn->anchor.len + 2u;
1298
+ }
1299
+ if (kn->tag.len > 0) {
1300
+ /* the key's TAG rides the same written token: wr_tag_uri
1301
+ * escapes every byte outside its URI set as %XX (even '_'),
1302
+ * inflating a ~1000-byte tag past the re-parse's simple-key
1303
+ * law (the nightly's run 38176016091: a ~975-raw tag wrote
1304
+ * ~1030 and the emission never re-parsed) */
1305
+ yep_view tv = wv(w, kn->tag);
1306
+ const unsigned char* t = (const unsigned char*)tv.p;
1307
+ for (uint32_t i = 0; i < tv.len; i++) {
1308
+ unsigned char c = t[i];
1309
+ int plain = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') ||
1310
+ (c >= 'A' && c <= 'Z') || c == '-' || c == ';' || c == '/' || c == '?' ||
1311
+ c == ':' || c == '@' || c == '&' || c == '=' || c == '+' || c == '$' ||
1312
+ c == ',' || c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' ||
1313
+ c == '(' || c == ')';
1314
+ est += plain ? 1u : 3u;
1315
+ }
1316
+ est += 6u; /* the !!/!< > wrapper and the separating space */
1317
+ }
1318
+ return est > 1024u;
1319
+ }
1320
+
1321
+ static void emit_flow(yep_emitter* em, uint32_t id) {
1322
+ yep_writer* w = &em->w;
1323
+ int saved_flow = w->in_flow;
1324
+ w->in_flow = 1;
1325
+ const yep_dom* d = em->doc->dom;
1326
+ const yep_dnode* n = yep_dom_node(d, id);
1327
+ emit_tag(w, n);
1328
+ emit_anchor_ex(em, n);
1329
+ int map = (n->kind == 2);
1330
+ wr_byte(w, map ? '{' : '[');
1331
+ int flow_indent = w->col;
1332
+ if (w->json_pretty && n->count > 0) {
1333
+ w->pretty_depth++;
1334
+ wr_byte(w, '\n');
1335
+ wr_pretty_indent(w, w->pretty_depth);
1336
+ flow_indent = w->col;
1337
+ }
1338
+ uint32_t child = n->first_child;
1339
+ uint32_t idx = 0;
1340
+ while (child != UINT32_MAX) {
1341
+ const yep_dnode* cn = yep_dom_node(d, child);
1342
+ if (idx > 0) {
1343
+ /* 13B: past best_width, break AFTER the previous value
1344
+ * (value boundaries only, never inside a scalar) and
1345
+ * re-indent to the opening bracket's column */
1346
+ if (w->json_pretty) {
1347
+ wr_put(w, ",\n", 2);
1348
+ wr_pretty_indent(w, w->pretty_depth);
1349
+ } else if (w->json_compact) {
1350
+ wr_byte(w, ',');
1351
+ } else if (w->best_width > 0 && w->col > w->best_width) {
1352
+ wr_byte(w, ',');
1353
+ wr_byte(w, '\n');
1354
+ wr_indent(w, flow_indent);
1355
+ } else {
1356
+ wr_put(w, ", ", 2);
1357
+ }
1358
+ }
1359
+ if (map) {
1360
+ int explicit_key = cn->anchor.len > 0 || cn->tag.len > 0 || cn->kind != 0;
1361
+ if (!explicit_key && key_written_over_limit(w, cn)) {
1362
+ { /* the quoted render's span vs the simple-key law */
1363
+ /* the simple-key law: a >1024 key cannot ride as a
1364
+ * flow simple key (the re-parse rejects it) — the
1365
+ * explicit "? key : " form carries it. Strict JSON
1366
+ * accepts keys of any length, so the JSON route
1367
+ * parses them and the YAML emission must re-parse
1368
+ * (the nightly's run 38143486175) */
1369
+ explicit_key = 1;
1370
+ }
1371
+ }
1372
+ if (explicit_key) {
1373
+ wr_put(w, "? ", 2);
1374
+ emit_node(em, child, 0, 1);
1375
+ wr_put(w, " : ", 3);
1376
+ } else {
1377
+ emit_node(em, child, 0, 1);
1378
+ if (w->json_pretty) {
1379
+ wr_put(w, ": ", 2);
1380
+ } else if (w->json_compact) {
1381
+ wr_byte(w, ':');
1382
+ } else {
1383
+ wr_put(w, ": ", 2);
1384
+ }
1385
+ }
1386
+ emit_node(em, cn->next_sibling, 0, 0);
1387
+ child = cn->next_sibling;
1388
+ cn = yep_dom_node(d, child);
1389
+ } else {
1390
+ w->flow_item = 1; /* a null item must ride '~' */
1391
+ emit_node(em, child, 0, 0);
1392
+ w->flow_item = 0;
1393
+ }
1394
+ idx++;
1395
+ child = cn->next_sibling;
1396
+ }
1397
+ if (w->json_pretty && idx > 0) {
1398
+ wr_byte(w, '\n');
1399
+ wr_pretty_indent(w, w->pretty_depth - 1);
1400
+ w->pretty_depth--;
1401
+ }
1402
+ wr_byte(w, map ? '}' : ']');
1403
+ w->in_flow = saved_flow;
1404
+ }
1405
+
1406
+ /* Block map: first key at the cursor (the caller placed it at
1407
+ * content_col = parent_col+2); following keys on new lines there. */
1408
+ static void emit_block_map(yep_emitter* em, uint32_t id, int content_col) {
1409
+ yep_writer* w = &em->w;
1410
+ const yep_dom* d = em->doc->dom;
1411
+ const yep_dnode* n = yep_dom_node(d, id);
1412
+ uint32_t child = n->first_child;
1413
+ uint32_t pair = 0;
1414
+ while (child != UINT32_MAX) {
1415
+ /* #352: the flat plain member specialist — tiny scalar pairs
1416
+ * pay dispatch and props checks, not byte work. Strictly
1417
+ * narrower than the general body below: plain unpropertied
1418
+ * key, plain unpropertied scalar value, both safety-proven by
1419
+ * the exact predicates sc_route consults (no memo touch, so
1420
+ * the dry/wet sc_i streams stay aligned). Anything else falls
1421
+ * through untouched — parity by construction. block_fold
1422
+ * (#903) declines only the members folding can actually
1423
+ * touch (#1257): the fold walk breaks exclusively at an
1424
+ * interior space whose column passes best_width, so a member
1425
+ * is fold-inert — the fused write stays byte-identical —
1426
+ * when folding is off, the width is the unwrap INT_MAX, the
1427
+ * value carries no space at all, or the member line ends
1428
+ * within the width. Fold-possible members fall through to
1429
+ * the general body, which folds. */
1430
+ const yep_dnode* kn0 = yep_dom_node(d, child);
1431
+ const yep_dnode* vn0 = yep_dom_node(d, kn0->next_sibling);
1432
+ if (!w->canonical && !w->json && !w->force_flow && vn0 != NULL && kn0->kind == 0 &&
1433
+ kn0->style == 1 && kn0->anchor.len == 0 && kn0->tag.len == 0 && kn0->count == 0 &&
1434
+ vn0->kind == 0 && vn0->style == 1 && vn0->anchor.len == 0 && vn0->tag.len == 0 &&
1435
+ vn0->count == 0) {
1436
+ yep_view kv = wv(w, kn0->value);
1437
+ yep_view vv = wv(w, vn0->value);
1438
+ /* the member's start column: after a written newline the
1439
+ * cursor rides the indent (content_col); otherwise the
1440
+ * live column (the first member: the caller placed the
1441
+ * cursor at content_col) */
1442
+ int m_start = (pair == 0 || w->last == '\n') ? content_col : w->col;
1443
+ /* the empty value's view is {NULL, 0} (wv) — memchr's
1444
+ * nonnull contract forbids the probe even at len 0 */
1445
+ int fold_inert = !w->block_fold || w->best_width == INT_MAX || vv.p == NULL ||
1446
+ memchr(vv.p, ' ', vv.len) == NULL ||
1447
+ m_start + (int)kv.len + (int)vv.len + 2 <= w->best_width;
1448
+ uint32_t f_ind = 0, f_nl = 0, f_total = 0;
1449
+ int fused = fold_inert && kv.len > 0 && !key_written_over_limit(w, kn0) &&
1450
+ kn0->plain_ok && (vv.len == 0 || vn0->plain_ok);
1451
+ if (fused) {
1452
+ /* fused member write: plain-safe spans carry no breaks,
1453
+ * so the col scan is arithmetic and one reservation
1454
+ * covers the whole member (line + key + ':' + value) */
1455
+ f_ind = pair > 0 ? (uint32_t)content_col : 0u;
1456
+ f_nl = (pair > 0 && w->last != '\n') ? 1u : 0u;
1457
+ f_total = f_nl + f_ind + kv.len + 1u + (vv.len > 0 ? vv.len + 1u : 0u);
1458
+ /* the fixed-window streaming route: the fused write
1459
+ * bypasses wr_put (whose chunked path bounds every
1460
+ * put), and this block ends in continue — so a member
1461
+ * that does not fit the window must DECLINE THE WHOLE
1462
+ * ARM to reach the general body, which emits the
1463
+ * identical bytes through wr_put. cap==0 routes are the
1464
+ * old trusted-count forms: the writer cannot reason
1465
+ * about their capacity, and they keep the arm. */
1466
+ if (!w->dry && !w->grow && w->cap != 0 && w->len + (size_t)f_total + 1 > w->cap) {
1467
+ fused = 0;
1468
+ }
1469
+ }
1470
+ if (fused) {
1471
+ w->last = vv.len > 0 ? (char)vv.p[vv.len - 1] : ':';
1472
+ if (f_nl) {
1473
+ w->col = (int)(f_total - 1u); /* the break resets, then the line */
1474
+ } else {
1475
+ w->col += (int)f_total;
1476
+ }
1477
+ if (w->dry) {
1478
+ w->len += f_total;
1479
+ } else {
1480
+ if (w->grow && w->len + f_total + 1 > w->cap) {
1481
+ if (w->bounded) {
1482
+ w->oom = 1; /* keep counting: the trusted caller reads the size */
1483
+ } else {
1484
+ wr_grow(w, f_total);
1485
+ }
1486
+ }
1487
+ if (w->oom) {
1488
+ w->len += f_total; /* keep counting: the caller fails on oom */
1489
+ } else {
1490
+ /* the fused write bypasses wr_put/wr_byte: keep
1491
+ * the reservation honest (the #739 lane-1 law) */
1492
+ w->reserve =
1493
+ (size_t)f_total <= w->reserve ? w->reserve - (size_t)f_total : 0;
1494
+ char* q = w->p + w->len;
1495
+ if (f_nl) {
1496
+ *q++ = '\n';
1497
+ }
1498
+ for (uint32_t i = 0; i < f_ind; i++) {
1499
+ *q++ = ' ';
1500
+ }
1501
+ memcpy(q, kv.p, kv.len);
1502
+ q += kv.len;
1503
+ *q++ = ':';
1504
+ if (vv.len > 0) {
1505
+ *q++ = ' ';
1506
+ memcpy(q, vv.p, vv.len);
1507
+ }
1508
+ w->len += f_total;
1509
+ wr_maybe_flush(w);
1510
+ }
1511
+ }
1512
+ pair++;
1513
+ child = vn0->next_sibling;
1514
+ continue;
1515
+ }
1516
+ }
1517
+ const yep_dnode* kn = yep_dom_node(d, child);
1518
+ const yep_dnode* vn = yep_dom_node(d, kn->next_sibling);
1519
+ if (pair > 0) {
1520
+ if (w->last != '\n') {
1521
+ wr_byte(w, '\n'); /* keep-chomped bodies own their break */
1522
+ }
1523
+ wr_indent(w, content_col);
1524
+ }
1525
+ int complex_key = (kn->kind != 0);
1526
+ /* a literal/folded key cannot ride the simple form: the value
1527
+ * separator would glue onto the block's CONTENT line (colons
1528
+ * are data there) and the re-parse reads a different tree —
1529
+ * the explicit "? key" form carries it. An EMPTY block-styled
1530
+ * key rides simple: it has no content line for the separator
1531
+ * to glue onto, and sc_route demotes it to the quoted form
1532
+ * anyway (the nightly's run 38177622733, ":\n! |-\n r\n:") */
1533
+ if (!complex_key && kn->style >= 4 && kn->style <= 5 && kn->value.len > 0 &&
1534
+ kn->tag.len > 0 && memchr(wv(w, kn->value).p, '\n', wv(w, kn->value).len) == NULL &&
1535
+ (kn->no_exotic || !yep_scan_dq_forced(wv(w, kn->value).p, wv(w, kn->value).len))) {
1536
+ /* a TAGGED SINGLE-LINE literal/folded key keeps the block
1537
+ * form in sc_route (the #290 law), so the value separator
1538
+ * would glue onto the block's CONTENT line (colons are
1539
+ * data there) and the re-parse reads a different tree —
1540
+ * the explicit "? key" form carries it, and it keeps the
1541
+ * block form there too, so both renders agree. A MULTILINE
1542
+ * tagged key demotes to quoted even in the explicit path
1543
+ * (as_key), so promoting it would UNSTABILIZE it: round
1544
+ * two parses a quoted style and rides simple. Untagged and
1545
+ * empty block styles demote likewise (the nightly's runs
1546
+ * 38177622733 ":\n! |-\n r\n:" and 38181819580
1547
+ * ":\n! |\n r\n:") — and so does content carrying
1548
+ * NEL/BOM/LS/PS/noncharacters (sc_dq_forced): a BOM in a
1549
+ * key's content demoted the explicit form's key to DQ and
1550
+ * round two rode simple, one render behind (the nightly's
1551
+ * round 118) */
1552
+ complex_key = 1;
1553
+ }
1554
+ if (!complex_key && key_written_over_limit(w, kn)) {
1555
+ /* the simple-key law, block side: a >1024 key cannot ride
1556
+ * as a block simple key either — the explicit "? key" form
1557
+ * carries it (the flow member writer gained the same law;
1558
+ * the nightly's run 38143486175) */
1559
+ complex_key = 1;
1560
+ }
1561
+ if (complex_key) {
1562
+ w->force_flow = 1; /* collections as flow keys: compact and
1563
+ free of the block '?' layout edges */
1564
+ wr_put(w, "? ", 2);
1565
+ /* the props emit ONCE: the DQ-promoted path writes its own
1566
+ * (emit_dq is bare), everything else lets emit_node/
1567
+ * emit_flow carry tag+anchor inline — the pre-emit made
1568
+ * every non-DQ explicit key re-emit its props ("? !\n ! |-
1569
+ " — the catch-56 law, explicit-key side) */
1570
+ int dq_promoted = (kn->kind == 0 && key_written_over_limit(w, kn));
1571
+ if (dq_promoted) {
1572
+ emit_props_tail(w, kn);
1573
+ if (kn->anchor.len > 0 || kn->tag.len > 0) {
1574
+ wr_byte(w, '\n');
1575
+ wr_indent(w, content_col + 2);
1576
+ }
1577
+ }
1578
+ if (dq_promoted) {
1579
+ /* the 1024-promoted SCALAR key must ride QUOTED in the
1580
+ * explicit form: plain, its interior ': ' sequences
1581
+ * re-parse through the inline simple-key promotion and
1582
+ * die on the very law that forced the promotion (the
1583
+ * nightly's run 38145696566, the "? licit k:[...]"
1584
+ * emission) */
1585
+ emit_dq(w, (const char*)wv(w, kn->value).p, (uint32_t)wv(w, kn->value).len);
1586
+ } else {
1587
+ emit_node(em, child, content_col, 1);
1588
+ }
1589
+ wr_byte(w, '\n');
1590
+ wr_indent(w, content_col);
1591
+ wr_put(w, ": ", 2);
1592
+ w->force_flow = 0;
1593
+ {
1594
+ /* the value's props ride the ':' line and a nested
1595
+ * block collection takes the fresh-line form, exactly
1596
+ * like the simple arm's path: the explicit twin
1597
+ * skipped both, so an anchored map value lost its
1598
+ * anchor (or glued it to the first key) and a later
1599
+ * alias emitted a dangling reference (the nightly's
1600
+ * run 38371134997, "? &d!se: &base\n name: Esame"
1601
+ * with a complex key forcing the explicit form) */
1602
+ if (!(vn->kind == 0 || vn->kind == 3 || vn->flow || vn->count == 0)) {
1603
+ int seq_val = (vn->kind == 1 && !vn->flow);
1604
+ int val_col = seq_val ? content_col : content_col + w->indent;
1605
+ emit_props_tail(w, vn);
1606
+ wr_byte(w, '\n');
1607
+ wr_indent(w, val_col);
1608
+ emit_node(em, kn->next_sibling, val_col - w->indent, 0);
1609
+ } else {
1610
+ emit_node(em, kn->next_sibling, content_col, 0);
1611
+ }
1612
+ }
1613
+ } else {
1614
+ emit_tag(w, kn);
1615
+ emit_anchor_ex(em, kn);
1616
+ emit_scalar(w, kn, content_col, 1);
1617
+ wr_byte(w, ':');
1618
+ /* empty collections ride the key line flow (k: [] / k: {})
1619
+ * like libyaml — a block-empty has no valid next-line form at
1620
+ * the seq indent (an empty [] at the key's column is not a
1621
+ * legal value; pyyaml rejects it, issue #52's differential).
1622
+ * An implicit-empty plain value rides bare (k:) with no
1623
+ * trailing space — libyaml's null rendering (#290) */
1624
+ if (vn->kind == 0 || vn->kind == 3 || vn->flow || vn->count == 0) {
1625
+ int empty_plain = vn->kind == 0 && vn->style == 1 && vn->anchor.len == 0 &&
1626
+ vn->tag.len == 0 && wv(w, vn->value).len == 0 && !w->canonical &&
1627
+ !w->json;
1628
+ if (!empty_plain) {
1629
+ wr_byte(w, ' ');
1630
+ }
1631
+ emit_node(em, kn->next_sibling, content_col, 0);
1632
+ } else {
1633
+ /* nested block collection: next line. libyaml parity:
1634
+ * a SEQUENCE value sits at the key's column (zero
1635
+ * extra indent); mappings indent one level (issue #95;
1636
+ * the level width is the #903 indent option) */
1637
+ int seq_val = (vn->kind == 1 && !vn->flow);
1638
+ int val_col = seq_val ? content_col : content_col + w->indent;
1639
+ emit_props_tail(w, vn);
1640
+ wr_byte(w, '\n');
1641
+ wr_indent(w, val_col);
1642
+ /* emit_block_seq dashes at parent_col+indent: pass
1643
+ * val_col-indent so the dashes land at val_col exactly */
1644
+ emit_node(em, kn->next_sibling, val_col - w->indent, 0);
1645
+ }
1646
+ }
1647
+ pair++;
1648
+ child = vn->next_sibling;
1649
+ }
1650
+ }
1651
+
1652
+ /* Block seq: "- item" lines at content_col = parent_col+2. */
1653
+ static void emit_block_seq(yep_emitter* em, uint32_t id, int content_col) {
1654
+ yep_writer* w = &em->w;
1655
+ const yep_dom* d = em->doc->dom;
1656
+ const yep_dnode* n = yep_dom_node(d, id);
1657
+ uint32_t child = n->first_child;
1658
+ uint32_t idx = 0;
1659
+ while (child != UINT32_MAX) {
1660
+ const yep_dnode* cn = yep_dom_node(d, child);
1661
+ if (idx > 0) {
1662
+ if (w->last != '\n') {
1663
+ wr_byte(w, '\n'); /* keep-chomped bodies own their break */
1664
+ }
1665
+ wr_indent(w, content_col);
1666
+ }
1667
+ if (cn->kind == 0 && cn->style == 1 && cn->anchor.len == 0 && cn->tag.len == 0 &&
1668
+ wv(w, cn->value).len == 0 && !w->canonical && !w->json) {
1669
+ wr_put(w, "-\n", 2); /* libyaml: a null item is a bare dash */
1670
+ idx++;
1671
+ child = cn->next_sibling;
1672
+ continue;
1673
+ }
1674
+ if (cn->kind != 0 && cn->kind != 3 && !cn->flow && cn->count > 0 &&
1675
+ (cn->anchor.len > 0 || cn->tag.len > 0)) {
1676
+ /* props may not precede a dash: they ride the dash line and
1677
+ * the collection starts on the next line (SY6V). The dash
1678
+ * carries NO trailing space — emit_props_tail adds its own
1679
+ * separator, and "- " + " &a" doubled it (the nightly's run
1680
+ * 38161738783). An EMPTY propertied collection takes the
1681
+ * compact arm: emit_node's empty-form writes the props
1682
+ * itself ("- &a {}"), and the next-line form re-emitted
1683
+ * them ("- &a\n &a {}") — every round grew/duplicated */
1684
+ wr_byte(w, '-');
1685
+ emit_props_tail(w, cn);
1686
+ wr_byte(w, '\n');
1687
+ wr_indent(w, content_col + w->indent);
1688
+ emit_node(em, child, content_col, 0);
1689
+ } else {
1690
+ /* compact: a block collection starts right after "- " */
1691
+ wr_put(w, "- ", 2);
1692
+ if (w->indent > 2 && cn->kind != 0 && cn->kind != 3 && !cn->flow && cn->count > 0) {
1693
+ /* libyaml/PyYAML's indent shape (#903): a nested
1694
+ * block collection's first line rides at the LEVEL
1695
+ * column (dash + indent), not the dash+2 token width
1696
+ * — indent=4 spells "- a: 1" / "- - x"; scalars,
1697
+ * aliases and empty/flow collections keep "- x" */
1698
+ wr_indent(w, w->indent - 2);
1699
+ }
1700
+ emit_node(em, child, content_col, 0);
1701
+ }
1702
+ idx++;
1703
+ child = cn->next_sibling;
1704
+ }
1705
+ }
1706
+
1707
+ static void emit_node(yep_emitter* em, uint32_t id, int parent_col, int as_key) {
1708
+ yep_writer* w = &em->w;
1709
+ const yep_dom* d = em->doc->dom;
1710
+ const yep_dnode* n = yep_dom_node(d, id);
1711
+ if (n == NULL) {
1712
+ return;
1713
+ }
1714
+ if (n->kind == 3) { /* alias */
1715
+ emit_alias_ex(em, n);
1716
+ return;
1717
+ }
1718
+ if ((n->kind == 1 || n->kind == 2) &&
1719
+ (n->flow || w->in_flow || w->canonical || w->json || w->force_flow)) {
1720
+ /* force_flow holds through the subtree: a complex key's nested
1721
+ * collections all render flow (scalars are never collections).
1722
+ * in_flow is the catch-55 law's collection arm: a block-styled
1723
+ * node nested inside a flow member renders FLOW — its block
1724
+ * dashes are not node content there (the nightly's run
1725
+ * 38168927841) */
1726
+ emit_flow(em, id);
1727
+ return;
1728
+ }
1729
+ if (n->kind == 2) { /* mapping */
1730
+ if (n->count == 0) {
1731
+ emit_tag(w, n);
1732
+ emit_anchor_ex(em, n);
1733
+ wr_put(w, "{}", 2);
1734
+ } else {
1735
+ /* the root (parent_col < 0, the caller's -2) rides column
1736
+ * 0; every nesting level adds the indent option (#903) */
1737
+ int base = (parent_col < 0) ? parent_col + 2 : parent_col + w->indent;
1738
+ emit_block_map(em, id, base);
1739
+ }
1740
+ return;
1741
+ }
1742
+ if (n->kind == 1) { /* sequence */
1743
+ if (n->count == 0) {
1744
+ emit_tag(w, n);
1745
+ emit_anchor_ex(em, n);
1746
+ wr_put(w, "[]", 2);
1747
+ } else {
1748
+ int base = (parent_col < 0) ? parent_col + 2 : parent_col + w->indent;
1749
+ emit_block_seq(em, id, base);
1750
+ }
1751
+ return;
1752
+ }
1753
+ emit_tag(w, n);
1754
+ emit_anchor_ex(em, n);
1755
+ if (parent_col < 0 && !w->canonical && !w->json && n->kind == 0 && n->style <= 1) {
1756
+ /* A DOCUMENT-ROOT empty scalar rides the quoted form: libyaml
1757
+ * renders "--- ''" and never a bare marker with nothing after
1758
+ * it. A plain-empty root emitted as NOTHING (the value law of
1759
+ * issue #290, "k:" — kept below for non-root contexts) sheds
1760
+ * the root node entirely; the re-parse of that stream produced
1761
+ * an ANY-styled empty root whose render is "" — and the bytes
1762
+ * diverged on round two (the nightly's r201 fuzz_roundtrip
1763
+ * byte-instability catch, ">\n! \n !<aaa: bbb\n...\n<NEL><NEL>",
1764
+ * whose second document's break-only content parses to a
1765
+ * plain-empty root). Quoting the root's emptiness makes every
1766
+ * empty-root spelling converge on the same fixpoint bytes. */
1767
+ yep_view vdec = wv(w, n->value);
1768
+ if (vdec.len == 0) {
1769
+ emit_dq(w, (const char*)vdec.p, vdec.len);
1770
+ return;
1771
+ }
1772
+ }
1773
+ if (parent_col < 0) {
1774
+ parent_col = 0; /* root scalar: block body at column 2 */
1775
+ }
1776
+ emit_scalar(w, n, parent_col, as_key);
1777
+ }
1778
+
1779
+ /* ============================================================
1780
+ * yeptris#739 slice 3: JSON's own tree walk. In JSON mode every
1781
+ * collection is flow, the separators are fixed, and the YAML
1782
+ * machinery (props lines, style analysis, explicit-key law,
1783
+ * pretty depth) never fires — yet the generic emit_node ->
1784
+ * emit_flow path re-tests all of it per node and looks every
1785
+ * child up twice. This walk emits the same bytes with one
1786
+ * dispatch per node and two per map pair. Pretty output keeps
1787
+ * the generic path: its depth/indent bookkeeping is the point
1788
+ * there.
1789
+ * ============================================================ */
1790
+ static void emit_json_node(yep_emitter* em, uint32_t id);
1791
+
1792
+ static void emit_json_flow(yep_emitter* em, uint32_t id) {
1793
+ yep_writer* w = &em->w;
1794
+ int saved_flow = w->in_flow;
1795
+ w->in_flow = 1;
1796
+ const yep_dom* d = em->doc->dom;
1797
+ const yep_dnode* n = yep_dom_node(d, id);
1798
+ if (n->tag.len > 0) {
1799
+ emit_tag(w, n);
1800
+ }
1801
+ if (n->anchor.len > 0) {
1802
+ emit_anchor_ex(em, n);
1803
+ }
1804
+ int map = (n->kind == 2);
1805
+ wr_byte(w, map ? '{' : '[');
1806
+ uint32_t child = n->first_child;
1807
+ uint32_t idx = 0;
1808
+ while (child != UINT32_MAX) {
1809
+ const yep_dnode* cn = yep_dom_node(d, child);
1810
+ if (idx > 0) {
1811
+ if (w->json_compact) {
1812
+ wr_byte(w, ',');
1813
+ } else {
1814
+ wr_put(w, ", ", 2);
1815
+ }
1816
+ }
1817
+ if (map) {
1818
+ /* the one generic-path rule JSON keeps: a non-scalar key
1819
+ * rides the explicit "? key : " form — same bytes emit_flow
1820
+ * writes. (Propertied scalar keys used to join it; JSON
1821
+ * drops properties, so they ride the plain quoted form.) */
1822
+ if (cn->kind != 0) {
1823
+ wr_put(w, "? ", 2);
1824
+ emit_json_node(em, child);
1825
+ wr_put(w, " : ", 3);
1826
+ } else {
1827
+ emit_json_node(em, child);
1828
+ if (w->json_compact) {
1829
+ wr_byte(w, ':');
1830
+ } else {
1831
+ wr_put(w, ": ", 2);
1832
+ }
1833
+ }
1834
+ uint32_t val = cn->next_sibling;
1835
+ emit_json_node(em, val);
1836
+ const yep_dnode* vn = yep_dom_node(d, val);
1837
+ child = vn != NULL ? vn->next_sibling : UINT32_MAX;
1838
+ } else {
1839
+ emit_json_node(em, child);
1840
+ child = cn->next_sibling;
1841
+ }
1842
+ idx++;
1843
+ }
1844
+ wr_byte(w, map ? '}' : ']');
1845
+ w->in_flow = saved_flow;
1846
+ }
1847
+
1848
+ static void emit_json_node(yep_emitter* em, uint32_t id) {
1849
+ yep_writer* w = &em->w;
1850
+ const yep_dom* d = em->doc->dom;
1851
+ const yep_dnode* n = yep_dom_node(d, id);
1852
+ if (n == NULL) {
1853
+ return;
1854
+ }
1855
+ if (n->kind == 3) { /* alias */
1856
+ emit_alias_ex(em, n);
1857
+ return;
1858
+ }
1859
+ if (n->kind == 1 || n->kind == 2) {
1860
+ emit_json_flow(em, id);
1861
+ return;
1862
+ }
1863
+ if (n->tag.len > 0) {
1864
+ emit_tag(w, n);
1865
+ }
1866
+ if (n->anchor.len > 0) {
1867
+ emit_anchor_ex(em, n);
1868
+ }
1869
+ emit_canonical_scalar(w, n);
1870
+ }
1871
+
1872
+ size_t yep_emit_run(yep_emitter* em, int dry) {
1873
+ yep_writer* w = &em->w;
1874
+ const yep_dom* d = em->doc->dom;
1875
+ w->dry = dry;
1876
+ w->len = 0;
1877
+ w->reserve = 0;
1878
+ w->last = 0;
1879
+ w->force_flow = 0;
1880
+ w->flushed = 0;
1881
+ w->sink_aborted = 0;
1882
+ w->col = 0;
1883
+ w->sc_i = 0;
1884
+ yep_nametab_clear(&em->canon_names);
1885
+ if (w->json) {
1886
+ /* JSON has no multi-document streams and no document marker */
1887
+ if (d->dcount == 1) {
1888
+ const yep_dnode* root = yep_dom_node(d, d->docs[0]);
1889
+ if (w->json_pretty) {
1890
+ emit_node(em, d->docs[0], -2, 0);
1891
+ } else {
1892
+ emit_json_node(em, d->docs[0]);
1893
+ }
1894
+ if (root != NULL && root->kind != 0 && w->last != '\n') {
1895
+ wr_byte(w, '\n');
1896
+ }
1897
+ }
1898
+ return w->flushed + w->len;
1899
+ }
1900
+ int multi = (d->dcount > 1) || w->canonical;
1901
+ for (uint32_t i = 0; i < d->dcount; i++) {
1902
+ const yep_dnode* root = yep_dom_node(d, d->docs[i]);
1903
+ if (multi || w->explicit_doc_start) {
1904
+ /* libyaml parity: a scalar root rides the marker line
1905
+ * ("--- 42"); collections take the marker alone */
1906
+ wr_put(w,
1907
+ (w->explicit_doc_start && root != NULL && root->kind == YEP_DOM_SCALAR &&
1908
+ !root->flow)
1909
+ ? "--- "
1910
+ : "---\n",
1911
+ 4);
1912
+ }
1913
+ if (root != NULL && (root->kind == 1 || root->kind == 2) && !root->flow && !w->canonical &&
1914
+ root->count > 0 && (root->tag.len > 0 || root->anchor.len > 0)) {
1915
+ /* count > 0: an EMPTY propertied collection takes
1916
+ * emit_node's inline empty-form ("! &a {}") — the leading
1917
+ * props line DUPLICATED it ("! &a\n! &a {}") and every
1918
+ * round shed a line (the nightly's run 38167237445; the
1919
+ * catch-56 law, root side) */
1920
+ /* root block-collection props ride their own leading line;
1921
+ * scalars and flow collections carry them inline */
1922
+ if (root->tag.len > 0) {
1923
+ yep_view tdec3 = wv(w, root->tag);
1924
+ wr_tag_token(w, &tdec3);
1925
+ }
1926
+ if (root->anchor.len > 0 && !anchor_name_unspellable(w, root)) {
1927
+ /* the r235 law: the lead line writes the name UNQUOTED
1928
+ * and anchor names have no quoting -- a name the spell
1929
+ * law rejects has no safe lead-line spelling. The r235
1930
+ * nightly's riding-colon names ("&:" and the artifact's
1931
+ * "&k:\"" — run 42739927952, crash-5de6f9ff) re-parsed
1932
+ * as an anchored empty KEY of the follow-on collection
1933
+ * (the anchor lost, s1 != s2, byte growth); the
1934
+ * colon-tail law fails the serialize like every other
1935
+ * anchor write path (the r228 "&: |" law) */
1936
+ if (root->tag.len > 0) {
1937
+ wr_byte(w, ' '); /* props need the separator */
1938
+ }
1939
+ yep_view adec3 = wv(w, root->anchor);
1940
+ wr_byte(w, '&');
1941
+ wr_put(w, (const char*)adec3.p, adec3.len);
1942
+ }
1943
+ wr_byte(w, '\n');
1944
+ }
1945
+ emit_node(em, d->docs[i], -2, 0); /* root content at column 0 */
1946
+ if (w->last != '\n') {
1947
+ wr_byte(w, '\n');
1948
+ }
1949
+ }
1950
+ return w->flushed + w->len;
1951
+ }