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,668 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The BulkBuilder's `when Date` must not depend on the caller loading
4
+ # stdlib's date (issue #289: a clean `require "yeptris"` raised NameError
5
+ # before the DumpError branch could run). Psych requires date the same way.
6
+ require "date"
7
+
8
+ # Self-sufficient (issue #95): the neutral surface is a valid entry
9
+ # point on its own — lutaml-model requires exactly this file.
10
+ require "yeptris"
11
+
12
+ module Yeptris
13
+ # The neutral Ruby surface (the Psych-compat namespace arrives with
14
+ # the recorder-driven Visitors in phase B; this is the yeptris-native
15
+ # face users target first).
16
+ module YAML
17
+ autoload :Descriptor, "yeptris/yaml/descriptor"
18
+
19
+ module_function
20
+
21
+ # Loads the FIRST document of a YAML stream as native Ruby objects.
22
+ # schema: :compat_11 selects Psych/libyaml implicit typing
23
+ # (yes/no, 0o/octal, sexagesimal); :core_12 (default) is YAML 1.2.
24
+ #
25
+ # The validation keywords (#882) check BEFORE loading and raise
26
+ # Yeptris::Validation::Error carrying the diagnostics on invalid
27
+ # input: `validate:` rides the engine's schema-family walk (true
28
+ # rides :core_12 — the 1.2 families are the validation families;
29
+ # or an explicit :core_12 / :json_12), `json_schema:` validates
30
+ # against JSON Schema draft 2020-12 (schema bytes or a compiled
31
+ # Yeptris::Validation::Schema).
32
+ #
33
+ # This surface keeps the Psych contract for EVERY input — including
34
+ # JSON-shaped ones (`{"a": [1,]}` is legal flow YAML; `"1e3"` is a
35
+ # Psych String). Strict RFC 8259 semantics live on Yeptris::JSON
36
+ # (TODO.restructure/31): defaults follow proof, not benchmarks.
37
+ def load(yaml, schema: :compat_11, validate: nil, json_schema: nil)
38
+ yaml = Yeptris.read_input(yaml)
39
+ yaml = yaml.to_s
40
+ _assert_valid(yaml, validate, json_schema) if validate || json_schema
41
+ docs = _drain_all(yaml, schema)
42
+ docs.empty? ? nil : docs.first
43
+ end
44
+
45
+ # The validation face (#882): every diagnostic the engine reports,
46
+ # as plain Yeptris::Validation::Diagnostic values (empty array =
47
+ # valid). Default is the engine's core-family walk; `json_schema:`
48
+ # switches to JSON Schema draft 2020-12 (bytes or a compiled
49
+ # Yeptris::Validation::Schema), `validate:` picks the schema family
50
+ # explicitly (:core_12 / :json_12). Every document of the stream is
51
+ # validated; paths are root-relative per document.
52
+ def validate(yaml, validate: true, json_schema: nil)
53
+ yaml = Yeptris.read_input(yaml)
54
+ _validation_call(yaml.to_s, validate, json_schema)
55
+ end
56
+
57
+ # The boolean posture of validate: true when the engine reports no
58
+ # diagnostics.
59
+ def valid?(yaml, validate: true, json_schema: nil)
60
+ validate(yaml, validate: validate, json_schema: json_schema).empty?
61
+ end
62
+
63
+ # The load-side gate: raises Yeptris::Validation::Error carrying
64
+ # the diagnostics when the input is invalid; silent otherwise.
65
+ def _assert_valid(yaml, validate, json_schema)
66
+ diags = _validation_call(yaml, validate, json_schema)
67
+ raise Validation::Error, diags unless diags.empty?
68
+ end
69
+
70
+ def _validation_call(yaml, validate, json_schema)
71
+ if json_schema
72
+ Validation.validate_schema(yaml, json_schema)
73
+ else
74
+ # `validate: true` rides :core_12 — the family walk has no
75
+ # :compat_11 face (the engine rejects it; resolve schemas are
76
+ # not validation families).
77
+ Validation.validate_family(yaml, schema: validate == true ? :core_12 : validate)
78
+ end
79
+ end
80
+ private_class_method :_validation_call
81
+ private_class_method :_assert_valid
82
+
83
+ # Psych-semantics safe_load on the native surface (issue #69 —
84
+ # the entry frameworks actually want): plain data only; a leaf
85
+ # whose class is not permitted raises Yeptris::Psych::
86
+ # DisallowedClass; aliases: false raises Yeptris::Psych::
87
+ # AliasesError on alias use. Delegates to the compat namespace's
88
+ # tree walk (correctness first; the fused drain comes later).
89
+ def safe_load(yaml, permitted_classes: [], aliases: false, schema: :compat_11)
90
+ yaml = Yeptris.read_input(yaml)
91
+ Psych.safe_load(yaml.to_s, permitted_classes: permitted_classes, aliases: aliases)
92
+ end
93
+
94
+ # Every document in the stream, in order (the multi-document stream
95
+ # API, yeptris#881 — Psych's load_stream parity). Document boundary
96
+ # detection follows the engine's stream parse: explicit --- / ...
97
+ # markers, implicit documents after a ... terminator, and empty
98
+ # documents — nil elements, exactly what Psych yields for them.
99
+ #
100
+ # errors: :raise (default) raises Yeptris::ParseError on the first
101
+ # bad document — psych's behavior (a stream parse cannot resume
102
+ # past it). errors: :collect never raises for a bad document: the
103
+ # text re-walks at marker boundaries (see _stream_slices) and the
104
+ # bad document's position carries a Yeptris::ParseError marker
105
+ # (skip with results.grep(Yeptris::ParseError)). A stream that
106
+ # parses whole collects to the same plain document array as :raise.
107
+ #
108
+ # With a block, every element — documents and, under :collect,
109
+ # error markers — is yielded in order; the array is returned.
110
+ #
111
+ # The validation keywords (#882) run the whole stream BEFORE
112
+ # loading (the same shapes as load: `validate:` family walk /
113
+ # `json_schema:` JSON Schema 2020-12) and raise
114
+ # Yeptris::Validation::Error on any diagnostics. The engine's
115
+ # report is flat across the stream — diagnostics carry no
116
+ # per-document index (streaming validation is future work, #885) —
117
+ # so the verdict is whole-stream by construction.
118
+ def load_stream(yaml, schema: :compat_11, errors: :raise, validate: nil,
119
+ json_schema: nil, &block)
120
+ unless %i[raise collect].include?(errors)
121
+ raise ArgumentError, "errors: must be :raise or :collect (got #{errors.inspect})"
122
+ end
123
+
124
+ yaml = Yeptris.read_input(yaml)
125
+ yaml = yaml.to_s
126
+ _assert_valid(yaml, validate, json_schema) if validate || json_schema
127
+ docs =
128
+ begin
129
+ docs = _drain_all(yaml, schema)
130
+ # The value drain emits a nil record even for a stream with
131
+ # ZERO documents ("", a blank line, a comment) — stdlib's
132
+ # load_stream answers zero documents there, and the corner
133
+ # must not mask a real empty document ("---\n" IS [nil]).
134
+ # Only the [nil] shape needs the discriminating DOM count,
135
+ # so the good path pays nothing.
136
+ if docs == [nil]
137
+ doc = Document.parse(yaml, schema: schema)
138
+ docs = [] if doc.nil? || doc.document_count.zero?
139
+ doc&.free
140
+ end
141
+ docs
142
+ rescue ParseError
143
+ raise if errors != :collect
144
+
145
+ _collect_stream(yaml, schema)
146
+ end
147
+ docs.each { |d| block.call(d) } if block
148
+ docs
149
+ end
150
+
151
+ # A column-0 --- / ... marker line. A real document boundary in
152
+ # every valid YAML stream (block/scalar content can never carry one
153
+ # unindented), so the scan is exact — it never splits inside a
154
+ # document. Marker-less boundaries (implicit documents after a
155
+ # ...) stay INSIDE their slice, and each slice parses through the
156
+ # full stream face, so nothing is lost there either. Slices keep
157
+ # their marker lines so every slice parses standalone. Used only by
158
+ # the errors: :collect fallback — a stream that parses whole never
159
+ # splits (the fallback's lossy cases are the whole reason #881
160
+ # exists; the good path must stay exact).
161
+ STREAM_MARKER = /\A(?:---|\.\.\.)(?:[ \t]|\r?\n|\z)/
162
+
163
+ # The marker-delimited slices of a stream. A slice that began at a
164
+ # marker line always survives (a trailing bare `---` is an empty
165
+ # document — nil, like psych yields); only a comments/blank-only
166
+ # leading prefix (no document) drops.
167
+ def _stream_slices(yaml)
168
+ slices = []
169
+ current = +""
170
+ markered = false
171
+ yaml.each_line do |line|
172
+ if line.match?(STREAM_MARKER)
173
+ slices << current if markered || !current.strip.empty?
174
+ current = line.dup
175
+ markered = true
176
+ else
177
+ current << line
178
+ end
179
+ end
180
+ slices << current if markered || !current.strip.empty?
181
+ slices
182
+ end
183
+
184
+ # The errors: :collect fallback: parse marker-boundary slices
185
+ # through the full stream face; a failed slice's position carries
186
+ # the ParseError. Documents before the bad one still load — the
187
+ # per-document rescue-and-skip contract, centralized.
188
+ def _collect_stream(yaml, schema)
189
+ results = []
190
+ _stream_slices(yaml).each do |slice|
191
+ begin
192
+ results.concat(_drain_all(slice, schema))
193
+ rescue ParseError => e
194
+ results << e
195
+ end
196
+ end
197
+ results
198
+ end
199
+
200
+ # The engine capability behind each_document (the CBOR.available?
201
+ # pattern): false when the loaded libyeptris predates the stream
202
+ # iterator — the walk itself raises the stale-engine message at use.
203
+ def each_document?
204
+ FFI::STREAM_ITER
205
+ end
206
+
207
+ # The tolerant per-document walk (engine #921): every document of
208
+ # the stream reaches the block IN STREAM ORDER — a valid document
209
+ # yields (document, nil); a failed document yields (nil, error)
210
+ # and the walk CONTINUES at the next line-start marker, so the
211
+ # valid documents after a bad one are kept (load_stream with
212
+ # errors: :raise would drop the whole stream; :collect recovers by
213
+ # a regex slice split, which quoted scalars spanning marker-looking
214
+ # lines can defeat — the engine iterator frames scanner-accurately,
215
+ # so those documents fail as ONE unit instead of splitting).
216
+ # Errors carry the failed document's own line/column and its
217
+ # stream index. Without a block, an Enumerator over the pairs.
218
+ def each_document(yaml, schema: :compat_11, max_depth: 0, &block)
219
+ return enum_for(:each_document, yaml, schema: schema, max_depth: max_depth) unless block
220
+
221
+ yaml = Yeptris.read_input(yaml)
222
+ yaml = yaml.to_s
223
+ opts = FFI::ParseOptions.new
224
+ opts[:schema] = schema == :compat_11 ? FFI::SCHEMA_11_COMPAT : FFI::SCHEMA_12_CORE
225
+ opts[:max_depth] = max_depth
226
+ it = FFI.yeptris_stream_iter_new(yaml, yaml.bytesize, opts)
227
+ doc_p = ::FFI::MemoryPointer.new(:pointer)
228
+ idx_p = ::FFI::MemoryPointer.new(:size_t)
229
+ line_p = ::FFI::MemoryPointer.new(:uint32)
230
+ col_p = ::FFI::MemoryPointer.new(:uint32)
231
+ begin
232
+ loop do
233
+ st = FFI.yeptris_stream_iter_next(it, doc_p, idx_p)
234
+ doc_ptr = doc_p.read_pointer
235
+ break if st == FFI::OK && doc_ptr.null? # the stream is over
236
+
237
+ index = FFI.read_c_size_t(idx_p)
238
+ if st == FFI::OK
239
+ doc = Document.without_finalizer(doc_ptr, yaml)
240
+ begin
241
+ yield doc.to_ruby, nil
242
+ ensure
243
+ doc.free
244
+ end
245
+ else
246
+ FFI.yeptris_stream_iter_status(it, line_p, col_p)
247
+ reason = st == FFI::ERROR_DEPTH ? "depth limit exceeded" : "parse error"
248
+ yield nil,
249
+ ParseError.new(
250
+ "stream document #{index}: #{reason} at line #{line_p.read_uint32}, " \
251
+ "column #{col_p.read_uint32}"
252
+ )
253
+ break if st == FFI::ERROR_MEMORY || st == FFI::ERROR_ENCODING
254
+ end
255
+ end
256
+ ensure
257
+ FFI.yeptris_stream_iter_free(it)
258
+ end
259
+ end
260
+
261
+ # The Marshal fast path when the loaded libyeptris has it (>= 0.1.11
262
+ # era builds), falling back to the columnar drain and finally the
263
+ # record drain — one code path, the fastest the library offers.
264
+ # The marshal lane is refused for sources that may name a quoted
265
+ # symbol: the C builder keeps the quotes in the name (#1304), and
266
+ # the columns/record walks carry the strip law.
267
+ def _drain_all(yaml, schema)
268
+ if FFI::MARSHAL && ValueML.marshal_lane_ok?(yaml)
269
+ result = ValueML.load_all_marshal(yaml, schema: schema, mode: :all)
270
+ return result unless result.nil?
271
+ end
272
+ if FFI::COLUMNS
273
+ ValueML.load_all_columns(yaml, schema: schema)
274
+ else
275
+ ValueML.load_all(yaml, schema: schema)
276
+ end
277
+ end
278
+
279
+ # The Psych-suite port's spelling (spec/psych/): compat typing.
280
+ def parse_yaml(yaml)
281
+ load(yaml)
282
+ end
283
+
284
+ def load_file(path, schema: :compat_11)
285
+ File.open(path, "rb") { |f| load(f, schema: schema) }
286
+ end
287
+
288
+ # Parses without materializing: the first document's root Node.
289
+ def parse(yaml, schema: :core_12)
290
+ doc = Document.parse(yaml, schema: schema)
291
+ return nil if doc.nil? || doc.document_count.zero?
292
+
293
+ doc.root(0)
294
+ end
295
+
296
+ # Serializes a Ruby object graph to YAML via the DOM builder
297
+ # (TODO.impl/11 phase 3). Strings are emitted plain only when the
298
+ # resolver round-trips them as strings — everything else takes a
299
+ # quoted style, so dump(load(x)) == x for the scalar types.
300
+ # width: the emitter's best_width. 0/nil rides the engine default
301
+ # (80, folding — flow collections after a value past the width, and
302
+ # with the #1257 flip also block plain/single-quoted scalars, the
303
+ # psych/libyaml stored-file behavior); a negative width is psych's
304
+ # line_width: -1 unwrap (the engine clamps it to never-fold).
305
+ def dump(obj, canonical: false, header: false, width: nil)
306
+ BulkBuilder.dump(obj, canonical: canonical, header: header, width: width)
307
+ end
308
+
309
+
310
+ # The dump-side mirror of the Materializer's bulk drain (TODO.impl
311
+ # 15 phase D): the tree walks into one flat entry array plus one
312
+ # string blob, and yeptris_document_build raises the DOM in a
313
+ # SINGLE FFI call — per-node FFI is gone. Same semantics as the
314
+ # per-node Builder it replaces (cycle refusal, :symbol scalars,
315
+ # Date/Time iso8601, plain-only-when-it-round-trips strings),
316
+ # with plain_string? pinned to the resolver by a differential
317
+ # spec.
318
+ module BulkBuilder
319
+ SCALAR = Yeptris::FFI::BUILD_SCALAR
320
+ SEQ = Yeptris::FFI::BUILD_SEQ
321
+ MAP = Yeptris::FFI::BUILD_MAP
322
+ STOP = Yeptris::FFI::BUILD_END
323
+ STYLE_PLAIN = 1
324
+ STYLE_SQ = 2
325
+ STYLE_DQ = 3
326
+ STYLE_LIT = 4
327
+ BUILD_TAG = Yeptris::FFI::BUILD_TAG
328
+
329
+ module_function
330
+
331
+ # Psych's exact timestamp spelling (format_time, #300): space
332
+ # separated, nanosecond width, Z for UTC — iso8601 diverged
333
+ def time_text(t)
334
+ t.utc? ? t.strftime("%Y-%m-%d %H:%M:%S.%9N Z") : t.strftime("%Y-%m-%d %H:%M:%S.%9N %:z")
335
+ end
336
+
337
+ # Psych's float spelling (#290): Infinity/NAN ride the YAML words,
338
+ # not Ruby's to_s (which prints "Infinity"/"NaN" — a STRING on
339
+ # reload)
340
+ def float_text(f)
341
+ return ".nan" if f.respond_to?(:nan?) && f.nan?
342
+ case (inf = f.infinite?)
343
+ when 1 then ".inf"
344
+ when -1 then "-.inf"
345
+ else f.to_s
346
+ end
347
+ end
348
+
349
+ # container entries are constant bytes — no pack per op
350
+ MAP_ENTRY = [Yeptris::FFI::BUILD_MAP, 0, 0, 0].pack("CCx2VV").freeze
351
+ SEQ_ENTRY = [Yeptris::FFI::BUILD_SEQ, 0, 0, 0].pack("CCx2VV").freeze
352
+ END_ENTRY = [Yeptris::FFI::BUILD_END, 0, 0, 0].pack("CCx2VV").freeze
353
+ CONT_ENTRY = { Yeptris::FFI::BUILD_MAP => MAP_ENTRY,
354
+ Yeptris::FFI::BUILD_SEQ => SEQ_ENTRY,
355
+ Yeptris::FFI::BUILD_END => END_ENTRY }.freeze
356
+
357
+ def dump(obj, canonical: false, header: false, width: nil)
358
+ # The nil root rides the bare form (psych's dump(nil) == "\n",
359
+ # #290): the engine's r201 quoted-form law ("a document-root
360
+ # empty scalar rides the quoted form" -- the plain form does not
361
+ # re-parse, the roundtrip invariant) renders the built empty
362
+ # scalar as "" -- correct for the engine's generic serializer,
363
+ # wrong for the psych surface. The binding maps an empty stream
364
+ # back to nil on load (load\#docs.empty?\#nil), so the bare form
365
+ # round-trips THROUGH THE BINDING while keeping the engine's
366
+ # invariant untouched.
367
+ return header ? "--- \n" : "\n" if obj.nil? && !canonical
368
+ parts = []
369
+ blob = String.new(encoding: Encoding::BINARY)
370
+ off = [0]
371
+ # one pack per SCALAR; containers reuse frozen constants
372
+ emit = lambda do |op, style, o, len|
373
+ parts << (o.zero? && len.zero? && style.zero? ? CONT_ENTRY[op] :
374
+ [op, style, o, len].pack("CCx2VV"))
375
+ end
376
+ place(obj, emit, blob, off, {})
377
+ doc = Document.create
378
+ buf = ::FFI::MemoryPointer.from_string(parts.join)
379
+ bblob = ::FFI::MemoryPointer.from_string(blob)
380
+ rc = doc.build_entries(buf, parts.length, bblob, blob.bytesize)
381
+ raise DumpError, "document_build failed: #{rc}" unless rc == FFI::OK
382
+ doc.serialize(canonical: canonical, best_width: width || 0,
383
+ explicit_doc_start: header)
384
+ ensure
385
+ doc&.free
386
+ end
387
+
388
+ def place(obj, emit, blob, off, seen)
389
+ case obj
390
+ when Hash
391
+ cycle_guard(obj, seen) do
392
+ emit.call(MAP, 0, 0, 0)
393
+ obj.each do |k, v|
394
+ # Symbol keys emit as bare ":k" plain — the compat
395
+ # reader resolves them back to Symbols; string keys
396
+ # ride the visit_String rules like any other scalar
397
+ # Symbol keys emit as bare ":k" plain — the compat
398
+ # reader resolves them back to Symbols; Integer/Float/
399
+ # bool keys ride plain like their values (Psych emits
400
+ # 1: unquoted — #290 family 5); string keys ride the
401
+ # visit_String rules like any other scalar; NIL keys
402
+ # ride Psych's explicit-`!` empty-scalar form
403
+ # (#300 family 2)
404
+ if k.nil?
405
+ scalar("", STYLE_SQ, emit, blob, off)
406
+ emit.call(BUILD_TAG, 0, off[0], 1)
407
+ blob << "!"
408
+ off[0] += 1
409
+ elsif k.is_a?(Symbol)
410
+ scalar(":#{k}", STYLE_PLAIN, emit, blob, off)
411
+ elsif k.is_a?(String) && k == "<<"
412
+ # stdlib yaml_tree: a literal chevron key carries the
413
+ # explicit !!str tag (single-quoted) so it does not
414
+ # re-load as a merge
415
+ scalar("<<", STYLE_SQ, emit, blob, off)
416
+ emit.call(BUILD_TAG, 0, off[0], 5)
417
+ blob << "!!str"
418
+ off[0] += 5
419
+ elsif k.is_a?(String)
420
+ # keys ride psych's ONE visit_String law — stdlib applies
421
+ # it to keys and values alike, so the reshape words quote
422
+ # in BOTH positions ("n": 1, 'yes': ...; #1264's premise
423
+ # had the psych side inverted: stdlib quotes these keys
424
+ # on every version since 4.0.2). The engine's own
425
+ # plain-key-safety re-check still guards the position.
426
+ style = STYLE_BY_NAME[string_style(k)]
427
+ scalar(k, style, emit, blob, off)
428
+ else
429
+ scalar(k.to_s, STYLE_PLAIN, emit, blob, off)
430
+ end
431
+ place(v, emit, blob, off, seen)
432
+ end
433
+ emit.call(STOP, 0, 0, 0)
434
+ end
435
+ when Array
436
+ cycle_guard(obj, seen) do
437
+ emit.call(SEQ, 0, 0, 0)
438
+ obj.each { |e| place(e, emit, blob, off, seen) }
439
+ emit.call(STOP, 0, 0, 0)
440
+ end
441
+ when String
442
+ if obj.encoding == ::Encoding::ASCII_8BIT && !obj.ascii_only?
443
+ # #168: psych visit_String's binary branch — strict base64
444
+ # + the short !binary tag + literal style (Builder
445
+ # build_string carries the same branch; the tagged-literal
446
+ # writer keeps the block form)
447
+ scalar([obj].pack("m0"), STYLE_LIT, emit, blob, off)
448
+ emit.call(BUILD_TAG, 0, off[0], 7)
449
+ blob << "!binary"
450
+ off[0] += 7
451
+ else
452
+ scalar(obj, STYLE_BY_NAME[string_style(obj)], emit, blob, off)
453
+ end
454
+ when Symbol then scalar(":#{obj}", STYLE_PLAIN, emit, blob, off)
455
+ when Integer then scalar(obj.to_s, STYLE_PLAIN, emit, blob, off)
456
+ when Float then scalar(float_text(obj), STYLE_PLAIN, emit, blob, off)
457
+ when true, false then scalar(obj.to_s, STYLE_PLAIN, emit, blob, off)
458
+ when nil then scalar("", STYLE_PLAIN, emit, blob, off)
459
+ when Time then scalar(time_text(obj), STYLE_PLAIN, emit, blob, off)
460
+ when Date then scalar(obj.iso8601, STYLE_PLAIN, emit, blob, off)
461
+ else
462
+ raise DumpError,
463
+ "cannot dump #{obj.class}: unsupported object " \
464
+ "(custom to_yaml support lands with the Psych Visitors)"
465
+ end
466
+ end
467
+
468
+ def scalar(text, style, emit, blob, off)
469
+ # a BINARY blob absorbs any String bytewise (String#<< on
470
+ # ASCII-8BIT is compatible with every encoding) — the old
471
+ # text.b made a throwaway copy of every scalar before the
472
+ # blob's own copy
473
+ emit.call(SCALAR, style, off[0], text.bytesize)
474
+ blob << text
475
+ off[0] += text.bytesize
476
+ end
477
+
478
+ def key_text(k)
479
+ k = ":#{k}" if k.is_a?(Symbol)
480
+ k.to_s
481
+ end
482
+
483
+ # A plain scalar that the compat resolver re-reads as STR stays
484
+ # plain; anything resolvable (null/bool words, int/float/timestamp
485
+ # shapes, indicators, merge '<<') takes double quotes so the
486
+ # reparse yields String again. Pinned to the C resolver's own
487
+ # verdicts by the differential spec (spec/yaml_spec.rb).
488
+ RESHAPES = %w[~ null Null NULL y Y yes Yes YES n N no No NO true True
489
+ TRUE false False FALSE on On ON off Off OFF <<].freeze
490
+ # the fast lane consults the reshape table per string: an Array
491
+ # scan of 36 words was ~a third of the whole dump walk
492
+ RESHAPES_SET = RESHAPES.each_with_object({}) { |w, h| h[w] = true }.freeze
493
+
494
+ SAFE_WORD = /\A[A-Za-z][A-Za-z0-9_\-.\/ ]*\z/
495
+
496
+ def plain_string?(s)
497
+ # fast lane: letter-started, safe characters incl. spaces — no
498
+ # number/timestamp/indicator shape is possible; only the
499
+ # reshape words need the set lookup
500
+ if SAFE_WORD.match?(s) && !s.end_with?(" ") && !RESHAPES_SET[s]
501
+ return true
502
+ end
503
+ return false if s.empty? || s != s.strip
504
+ return false if s.match?(/[\n\t\u0085\u2028\u2029\uFEFF]/)
505
+ c = s[0]
506
+ return false if "#,[]{}&*!|>'\"%@`".include?(c)
507
+ return false if "-?:".include?(c) && (s.length == 1 || s[1] =~ /[ \t]/)
508
+ return false if s.include?(": ") || s.end_with?(":") || s.include?(" #")
509
+ return false if RESHAPES_SET[s]
510
+ # ints/sexagesimals reshape: the compat resolver accepts any
511
+ # digit start (compat11.c), psych's ScalarScanner likewise —
512
+ # "07:00:00" plain re-reads as Integer, so leading-zero hours
513
+ # quote too (psych dumps them quoted)
514
+ return false if s.match?(/\A[-+]?[0-9][0-9_]*(:[0-5]?[0-9])+\z/)
515
+ return false if s.match?(/\A[-+]?(0|[1-9][0-9_]*)\z/)
516
+ # compat's float grammar REQUIRES the dot ("1e3" re-reads as a
517
+ # String and may dump plain); psych's FLOAT has no trailing
518
+ # [.:] group — "1.2.3" is a String and dumps plain (pinned by
519
+ # spec/yaml_spec.rb)
520
+ return false if s.match?(/\A[-+]?[0-9][0-9_]*\.[0-9_]*([eE][-+]?[0-9]+)?\z/)
521
+ return false if s.match?(/\A[-+]?[0-9][0-9_]*(:[0-5]?[0-9])+\.[0-9_]*\z/)
522
+ return false if s.match?(/\A[-+]?(0x[0-9a-fA-F_]+|0b[01_]+|0o?[0-7_]+)\z/)
523
+ return false if s.match?(/\A[-+]?\.(inf|Inf|INF)\z|\A\.(nan|NaN|NAN)\z/)
524
+ !s.match?(/\A\d{4}-\d\d?-\d\d?([Tt ]|$)/)
525
+ end
526
+
527
+ # Psych parity (psych yaml_tree#visit_String) — the quoting
528
+ # decision for a String, in psych's own order:
529
+ # y/Y/n/N (the 1.1 bool words psych double-quotes) → double
530
+ # a leading non-word character, no " anywhere → double
531
+ # a 1.1 bad-octal shape (0[0-7]*[89]) → single
532
+ # re-loads as something other than String (plain_string?
533
+ # rejects the 1.1 number/bool/null/timestamp shapes) → single
534
+ # needs escapes (control bytes, multiline) → double
535
+ # otherwise → plain
536
+ # psych's literal/folded/binary forms and its !!str tag for
537
+ # "<<" are follow-ups; those strings double-quote today.
538
+ STYLE_BY_NAME = { plain: STYLE_PLAIN, single: STYLE_SQ, double: STYLE_DQ,
539
+ literal: STYLE_LIT }.freeze
540
+
541
+ def string_style(s)
542
+ # psych's visit_String: any interior newline rides a literal
543
+ # block (the C writer's libyaml indicator rules render it) —
544
+ # first, exactly as psych orders it (#290 family 4)
545
+ return :literal if s.match?(/\n(?!\z)/)
546
+ return :double if s == "y" || s == "Y" || s == "n" || s == "N"
547
+ return :double if !s.empty? && !s.include?('"') && s.match?(/\A[^[:word:]]/)
548
+ return :single if s.match?(/\A0[0-7]*[89]/)
549
+ return :plain if plain_string?(s)
550
+ # \n and \r are BREAKS in libyaml, not specials - the emitter's
551
+ # single-quoted law carries them ('x y z\n\n ': single_quoted_
552
+ # allowed survives line breaks, #1264's family A); other C0
553
+ # bytes and DEL need the escapes
554
+ return :double if s.match?(/[\u0085\u2028\u2029\uFEFF]/)
555
+ :single
556
+ end
557
+
558
+ def cycle_guard(obj, seen)
559
+ id = obj.object_id
560
+ raise DumpError, "cycle detected: cannot dump recursive #{obj.class}" if seen[id]
561
+
562
+ seen[id] = true
563
+ out = yield
564
+ seen.delete(id)
565
+ out
566
+ end
567
+ end
568
+
569
+ # From-scratch builder over the public construction API.
570
+ module Builder
571
+ module_function
572
+
573
+ def build(doc, obj, seen = {})
574
+ case obj
575
+ when Hash then build_map(doc, obj, seen)
576
+ when Array then build_seq(doc, obj, seen)
577
+ when String then build_string(doc, obj)
578
+ when Symbol then new_scalar(doc, ":#{obj}")
579
+ when Integer then new_scalar(doc, obj.to_s)
580
+ when Float then new_scalar(doc, BulkBuilder.float_text(obj))
581
+ when true, false then new_scalar(doc, obj.to_s)
582
+ when nil then new_scalar(doc, "")
583
+ when Time then new_scalar(doc, BulkBuilder.time_text(obj))
584
+ when Date then new_scalar(doc, obj.iso8601)
585
+ else
586
+ raise DumpError,
587
+ "cannot dump #{obj.class}: unsupported object " \
588
+ "(custom to_yaml support lands with the Psych Visitors)"
589
+ end
590
+ end
591
+
592
+ def build_map(doc, h, seen)
593
+ cycle_guard(h, seen) do
594
+ m = doc.new_mapping
595
+ h.each do |k, v|
596
+ if k.nil?
597
+ key_node = doc.new_scalar("", :single_quoted)
598
+ key_node.set_tag("!")
599
+ m.map_add_node(key_node, build(doc, v, seen))
600
+ elsif k.is_a?(::String) && k == "<<"
601
+ # stdlib yaml_tree: a literal chevron key carries the
602
+ # explicit !!str tag so it does not re-load as a merge
603
+ key_node = doc.new_scalar("<<", :single_quoted)
604
+ key_node.set_tag("tag:yaml.org,2002:str")
605
+ m.map_add_node(key_node, build(doc, v, seen))
606
+ else
607
+ m.map_add(key_text(k), build(doc, v, seen))
608
+ end
609
+ end
610
+ m
611
+ end
612
+ end
613
+
614
+ def build_seq(doc, a, seen)
615
+ cycle_guard(a, seen) do
616
+ s = doc.new_sequence
617
+ a.each { |e| s.seq_add(build(doc, e, seen)) }
618
+ s
619
+ end
620
+ end
621
+
622
+ # One quoting table (BulkBuilder.string_style — psych's
623
+ # visit_String matrix) serves both builders; this side carries
624
+ # the style onto the per-node DOM.
625
+ def build_string(doc, s)
626
+ # psych 5.5 visit_String's binary branch, verbatim: an
627
+ # ASCII-8BIT string with non-ASCII bytes emits as strict base64
628
+ # (pack('m0'), never wrapped) under the short !binary tag with
629
+ # literal style — the writer keeps the block form for tagged
630
+ # literals (#168). BOTH dump paths converge here (the top-level
631
+ # scalar fast route and the YAMLTree visitor).
632
+ if s.encoding == ::Encoding::ASCII_8BIT && !s.ascii_only?
633
+ bin = new_scalar(doc, [s].pack("m0"), :force_lit)
634
+ bin.set_tag("!binary")
635
+ return bin
636
+ end
637
+ case BulkBuilder.string_style(s)
638
+ when :single then new_scalar(doc, s, :force_str_sq)
639
+ when :double then new_scalar(doc, s, :force_str)
640
+ when :literal then new_scalar(doc, s, :force_lit)
641
+ else new_scalar(doc, s)
642
+ end
643
+ end
644
+
645
+ def key_text(k)
646
+ k = ":#{k}" if k.is_a?(Symbol)
647
+ k.to_s
648
+ end
649
+
650
+ def new_scalar(doc, text, mode = nil)
651
+ doc.new_scalar(text.to_s,
652
+ mode == :force_str ? :double_quoted :
653
+ mode == :force_str_sq ? :single_quoted :
654
+ mode == :force_lit ? :literal : :plain)
655
+ end
656
+
657
+ def cycle_guard(obj, seen)
658
+ id = obj.object_id
659
+ raise DumpError, "cycle detected: cannot dump recursive #{obj.class}" if seen[id]
660
+
661
+ seen[id] = true
662
+ out = yield
663
+ seen.delete(id)
664
+ out
665
+ end
666
+ end
667
+ end
668
+ end