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,796 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "date"
4
+ require "time"
5
+ require "set"
6
+
7
+ # Self-sufficient (the #95 yaml.rb fix, same class): the standalone
8
+ # require "yeptris/psych" must register the Document/FFI machinery —
9
+ # consumers load this face directly under the drop-in.
10
+ require "yeptris"
11
+
12
+ # The Psych drop-in namespace (TODO.impl/15 phase C).
13
+ #
14
+ # `require "yeptris/psych"` loads this namespace WITHOUT touching the
15
+ # top-level Psych constant (co-existence, issue #69); the process-
16
+ # exclusive drop-in rebind is `require "yeptris/psych/drop_in"` (the
17
+ # original stdlib, if loaded first, stays reachable as
18
+ # ::Psych::ORIGINAL). Semantics follow the Psych suite: load is
19
+ # SAFE by default (Psych 5 behavior — plain data only; anything
20
+ # tagged raises), unsafe_load materializes everything the yeptris
21
+ # loader understands, and parse returns the Nodes tree over the
22
+ # document without materializing.
23
+ module Yeptris
24
+ module Psych
25
+ autoload :ClassLoader, "yeptris/psych/class_loader"
26
+ autoload :ScalarScanner, "yeptris/psych/scalar_scanner"
27
+
28
+ # The tag registries (Psych's class-level API, #95 bug 4):
29
+ # load_tags maps a serialized tag to the Class that revives it;
30
+ # dump_tags overrides the emitted tag for a Class. Consulted by
31
+ # the revival visitor (custom tags) and the dumper's tag choice.
32
+ class << self
33
+ def load_tags
34
+ @load_tags ||= {}
35
+ end
36
+
37
+ def load_tags=(tags)
38
+ @load_tags = tags
39
+ end
40
+
41
+ def dump_tags
42
+ @dump_tags ||= {}
43
+ end
44
+
45
+ def dump_tags=(tags)
46
+ @dump_tags = tags
47
+ end
48
+
49
+ # The third registry (stdlib psych carries all three; the rebind
50
+ # broke relaton/lutaml callers that wrote it — the 26x
51
+ # undefined-method report). Keys are normalized tag strings
52
+ # ("tag:DOMAIN:TYPE"), values are [key, block] post-processors.
53
+ def domain_types
54
+ @domain_types ||= {}
55
+ end
56
+
57
+ def domain_types=(types)
58
+ @domain_types = types
59
+ end
60
+
61
+ def add_domain_type(domain, type_tag, &block)
62
+ key = ["tag", domain, type_tag].join(":")
63
+ domain_types[key] = [key, block]
64
+ domain_types["tag:#{type_tag}"] = [key, block]
65
+ end
66
+
67
+ def add_builtin_type(type_tag, &block)
68
+ key = ["tag", "yaml.org,2002", type_tag].join(":")
69
+ domain_types[key] = [key, block]
70
+ end
71
+
72
+ def remove_type(type_tag)
73
+ domain_types.delete type_tag
74
+ end
75
+
76
+ def add_tag(tag, klass)
77
+ load_tags[tag] = klass.name
78
+ dump_tags[klass] = tag
79
+ end
80
+ end
81
+
82
+ # Children load via autoload declared HERE — the immediate parent
83
+ # namespace's file (never internal requires).
84
+ autoload :Handler, "yeptris/psych/handler"
85
+ # Handlers (the Recorder submodule) lives in handler.rb too — its
86
+ # own entry so referencing Psych::Handlers triggers the load
87
+ autoload :Handlers, "yeptris/psych/handler"
88
+ autoload :Parser, "yeptris/psych/parser"
89
+ # #179: the located tree builder (stdlib's class, ported)
90
+ autoload :TreeBuilder, "yeptris/psych/tree_builder"
91
+ autoload :CoderShim, "yeptris/psych/coder_shim"
92
+ autoload :Visitors, "yeptris/psych/visitors"
93
+ # The typed opt-in marker for arbitrary-object dump/load
94
+ # (TODO.restructure/23). Eager by intent: classes include it at
95
+ # declaration time, so the autoload must resolve before any
96
+ # object instance exists.
97
+ autoload :Encodable, "yeptris/psych/encodable"
98
+ class Error < StandardError; end
99
+
100
+ # stdlib psych 5: a *foo with no matching &foo anchor
101
+ class AnchorNotDefined < Error; end
102
+ # Psych's exact interface (issue #32): same constructor arity,
103
+ # same reader set (file/line/column/offset/problem/context), same
104
+ # message shape — drop-in consumers' rescues and constructors
105
+ # keep working after the rebind.
106
+ class SyntaxError < Error
107
+ attr_reader :file, :line, :column, :offset, :problem, :context
108
+
109
+ def initialize(file = nil, line = 0, column = 0, offset = 0, problem = nil, context = nil)
110
+ @file = file
111
+ @line = line
112
+ @column = column
113
+ @offset = offset
114
+ @problem = problem
115
+ @context = context
116
+ where = file ? "(#{file})" : "(<unknown>)"
117
+ detail = context ? "#{problem} #{context}" : problem.to_s
118
+ super("#{where}: #{detail} at line #{line} column #{column}")
119
+ end
120
+
121
+ # Structured lift from the C parser's message (carries
122
+ # "line L, column C" detail).
123
+ def self.from_parse_error(error)
124
+ md = /\bline (\d+),? column (\d+)/.match(error.message)
125
+ new(nil, md ? md[1].to_i : 0, md ? md[2].to_i : 0, 0, error.message)
126
+ end
127
+ end
128
+ class BadAlias < Error; end
129
+ class DisallowedClass < Error
130
+ attr_reader :name
131
+
132
+ def initialize(name)
133
+ super("Tried to load unspecified class: #{name}")
134
+ @name = name
135
+ end
136
+ end
137
+ # Psych spells it Psych::AliasesError; the older name stays as an
138
+ # alias for existing rescues.
139
+ class AliasesError < Error; end
140
+ AliasNotEnabled = AliasesError
141
+
142
+ class << self
143
+ # Psych 5: load is safe — plain data structures only. Tagged
144
+ # nodes raise DisallowedClass unless their class is permitted
145
+ # (Date/Time/Symbol are built in; they are plain data here).
146
+ def load(yaml, permitted_classes: [::Date, ::Time], aliases: false,
147
+ symbolize_names: false, fallback: nil, filename: nil, **)
148
+ res = safe_load(yaml, permitted_classes: permitted_classes, aliases: aliases,
149
+ symbolize_names: symbolize_names)
150
+ if res.nil? && !fallback.nil?
151
+ # stdlib's fallback: answers when the stream is empty or has
152
+ # NO documents — a document whose content IS nil still loads
153
+ # as nil. The safe path cannot tell those two apart, so the
154
+ # corner re-checks the count (only when a fallback rides).
155
+ doc = ::Yeptris::Document.parse(yaml, schema: :compat_11)
156
+ empty = doc.nil? || doc.document_count.zero?
157
+ doc&.free
158
+ return fallback if empty
159
+ end
160
+ res
161
+ end
162
+
163
+ # Full revival over the Nodes tree: !ruby/object, !ruby/struct,
164
+ # !ruby/set, encode_with/init_with, alias identity. Plain-data
165
+ # loads should use load/safe_load (the Materializer fast path).
166
+ def unsafe_load(yaml, **)
167
+ # #178: the marshal fast path. Nodes::Builder's tree is per-node
168
+ # FFI (kind/tag/anchor/value + a walk per container) — the whole
169
+ # 11 MB relaton index paid ~9.6 s there. When the document is
170
+ # plain data (no timestamps/merge keys/tagged revivals), ONE C
171
+ # call materializes the tree as Marshal bytes and Marshal.load
172
+ # builds the objects in C (~1 s end to end). Construct-heavy
173
+ # documents keep the full revival walk below, byte for byte.
174
+ if Yeptris::FFI::MARSHAL && ::Yeptris::Psych.domain_types.empty?
175
+ begin
176
+ doc = ::Yeptris::Document.parse(yaml, schema: :compat_11)
177
+ return nil if doc.nil? || doc.document_count.zero?
178
+
179
+ root = doc.root(0)
180
+ fast = root&.marshal_fast
181
+ unless fast.nil?
182
+ doc.free
183
+ return fast
184
+ end
185
+ tree = Nodes::Builder.document(doc) # ownership: the tree frees
186
+ return Visitors::ToRuby.visit(tree.children.first)
187
+ rescue ::Yeptris::ParseError => e
188
+ doc&.free unless doc&.freed?
189
+ translate_parse_error(e)
190
+ end
191
+ end
192
+ tree = parse(yaml)
193
+ return nil if tree.nil?
194
+
195
+ Visitors::ToRuby.visit(tree.children.first)
196
+ end
197
+
198
+ def deep_symbolize_keys(obj)
199
+ case obj
200
+ when Hash
201
+ obj.each_with_object({}) do |(k, v), out|
202
+ out[k.is_a?(String) ? k.to_sym : k] = deep_symbolize_keys(v)
203
+ end
204
+ when Array then obj.map { |v| deep_symbolize_keys(v) }
205
+ else obj
206
+ end
207
+ end
208
+
209
+ def safe_load(yaml, permitted_classes: [::Date, ::Time], aliases: false,
210
+ symbolize_names: false, **)
211
+ # ONE read at the boundary (read_input): IO-like input must be
212
+ # consumed once — the string rides parse AND the slice below
213
+ source = ::Yeptris.read_input(yaml)
214
+ begin
215
+ doc = Yeptris::Document.parse(source, schema: :compat_11)
216
+ return nil if doc.nil? # the legal empty stream
217
+
218
+ res = force_utf8_scalars(walk_safe(doc.root(0), permitted_classes, aliases, source))
219
+ res = deep_symbolize_keys(res) if symbolize_names
220
+ res
221
+ rescue ::Yeptris::ParseError => e
222
+ doc&.free unless doc&.freed?
223
+ translate_parse_error(e)
224
+ ensure
225
+ doc&.free
226
+ end
227
+ end
228
+
229
+ # A YAML stream is a Unicode character stream: stdlib psych tags
230
+ # non-ASCII scalars UTF-8 even when the input String is BINARY
231
+ # (#135). ASCII-only values keep their (binary) encoding — a
232
+ # re-tag would be observable there and stdlib does not either.
233
+ def force_utf8_scalars(obj)
234
+ case obj
235
+ when ::String
236
+ # valid_encoding? on an ASCII-8BIT string is ALWAYS true
237
+ # (it is bytes) — the discriminator is whether the bytes
238
+ # READ as UTF-8: #135's case (UTF-8 scalars the C side
239
+ # materialized as BINARY) re-tags; DECODED !binary bytes
240
+ # that are not UTF-8 stay BINARY (#168). Binary content that
241
+ # happens to be valid UTF-8 re-tags — noted divergence from
242
+ # stdlib, which keeps BINARY; real payloads (zips, bodies)
243
+ # never are.
244
+ if obj.encoding == ::Encoding::ASCII_8BIT && !obj.ascii_only?
245
+ probe = obj.dup.force_encoding(::Encoding::UTF_8)
246
+ obj.force_encoding(::Encoding::UTF_8) if probe.valid_encoding?
247
+ end
248
+ obj
249
+ when ::Hash
250
+ obj.each { |k, v| force_utf8_scalars(k); force_utf8_scalars(v) }
251
+ when ::Array
252
+ obj.each { |v| force_utf8_scalars(v) }
253
+ else
254
+ obj
255
+ end
256
+ end
257
+
258
+ # stdlib's file-level faces (#135): BOM-tolerant UTF-8 reads with
259
+ # the fallback contract (load_file path, fallback: false default).
260
+ def load_file(path, fallback: false, **kwargs)
261
+ File.open(path, "r:bom|utf-8") { |f| load(f, **kwargs) }
262
+ rescue Errno::ENOENT
263
+ raise unless fallback
264
+
265
+ false
266
+ end
267
+
268
+ def safe_load_file(path, fallback: false, **kwargs)
269
+ File.open(path, "r:bom|utf-8") { |f| safe_load(f, **kwargs) }
270
+ rescue Errno::ENOENT
271
+ raise unless fallback
272
+
273
+ false
274
+ end
275
+
276
+ def unsafe_load_file(path, fallback: false, **kwargs)
277
+ File.open(path, "r:bom|utf-8") { |f| unsafe_load(f, **kwargs) }
278
+ rescue Errno::ENOENT
279
+ raise unless fallback
280
+
281
+ false
282
+ end
283
+
284
+ def parse_file(path, **kwargs)
285
+ File.open(path, "r:bom|utf-8") { |f| parse(f, **kwargs) }
286
+ end
287
+
288
+
289
+
290
+ # stdlib's deprecated safe/dump split — same output here (every
291
+ # value this loader produces is safe data)
292
+ def safe_dump(obj, io = nil, options = {})
293
+ ::Yeptris::Psych.dump(obj, io, options)
294
+ end
295
+
296
+ # stdlib's load_stream (yeptris#881): every document of the
297
+ # stream, in order — the block form yields each loaded document.
298
+ # The engine's stream parse drives the boundaries (--- / ... /
299
+ # implicit documents after a ...); empty documents are nil
300
+ # elements, exactly what stdlib yields.
301
+ #
302
+ # errors: :raise (default) re-raises a bad document as stdlib's
303
+ # family — Psych::SyntaxError (parse() translates the same way).
304
+ # errors: :collect never raises for a bad document: the stream
305
+ # re-walks at marker boundaries (Yeptris::YAML._stream_slices)
306
+ # through this face's own DOM materialization, and the bad
307
+ # document's position carries the SyntaxError marker.
308
+ def load_stream(yaml, errors: :raise, **kwargs, &block)
309
+ unless %i[raise collect].include?(errors)
310
+ raise ArgumentError, "errors: must be :raise or :collect (got #{errors.inspect})"
311
+ end
312
+
313
+ # once, up front: the collect fallback re-parses this text and
314
+ # an IO input would already be at EOF by then
315
+ yaml = ::Yeptris.read_input(yaml).to_s
316
+ docs =
317
+ begin
318
+ # materialize each document's root directly — the stream
319
+ # children share one C document, so their handles would all
320
+ # resolve to the first document's tree. stdlib's block form
321
+ # yields each loaded document's object (#179 round 4).
322
+ doc = ::Yeptris::Document.parse(yaml, schema: :compat_11)
323
+ if doc.nil?
324
+ # the legal empty stream: stdlib answers a stream object
325
+ # with no children; the array face answers []
326
+ []
327
+ else
328
+ begin
329
+ (0...doc.document_count).map { |i| doc.root(i).to_ruby }
330
+ ensure
331
+ doc.free
332
+ end
333
+ end
334
+ rescue ::Yeptris::ParseError => e
335
+ # stdlib's family for a bad document (parse() translates
336
+ # the same way); in collect mode the bad document's
337
+ # position carries the SyntaxError marker instead
338
+ raise SyntaxError.from_parse_error(e) if errors != :collect
339
+
340
+ _collect_stream(yaml)
341
+ end
342
+ docs.each { |d| block.call(d) } if block
343
+ docs
344
+ end
345
+
346
+ # The errors: :collect fallback: parse the marker-boundary
347
+ # slices through this face's own DOM materialization; a failed
348
+ # slice's position carries the SyntaxError marker.
349
+ def _collect_stream(yaml)
350
+ results = []
351
+ ::Yeptris::YAML._stream_slices(yaml).each do |slice|
352
+ begin
353
+ doc = ::Yeptris::Document.parse(slice, schema: :compat_11)
354
+ next if doc.nil?
355
+
356
+ begin
357
+ (0...doc.document_count).each { |i| results << doc.root(i).to_ruby }
358
+ ensure
359
+ doc.free
360
+ end
361
+ rescue ::Yeptris::ParseError => e
362
+ results << SyntaxError.from_parse_error(e)
363
+ end
364
+ end
365
+ results
366
+ end
367
+
368
+ # safe_load_stream: stdlib's surface — the stream form of
369
+ # safe_load. Our load_stream is already safe-by-default
370
+ # (Psych 5 semantics), so this is the yielding wrapper.
371
+ def safe_load_stream(yaml, **kwargs, &block)
372
+ load_stream(yaml, **kwargs, &block)
373
+ end
374
+
375
+ # The first document's node tree (no Ruby materialization).
376
+ def translate_parse_error(e)
377
+ # yeptris rejects *foo without &foo at PARSE time (stdlib
378
+ # raises at visit) — surface it as stdlib's class so
379
+ # consumers' rescues keep working
380
+ raise AnchorNotDefined, e.message if e.message.include?("undefined anchor")
381
+
382
+ raise SyntaxError.from_parse_error(e)
383
+ end
384
+
385
+ def parse(yaml)
386
+ doc = Yeptris::Document.parse(yaml, schema: :compat_11)
387
+ return nil if doc.nil? || doc.document_count.zero?
388
+
389
+ Nodes::Builder.document(doc)
390
+ rescue Yeptris::ParseError => e
391
+ raise SyntaxError.from_parse_error(e)
392
+ end
393
+
394
+ def parse_stream(yaml, &block)
395
+ # stdlib yields each document to a block if one was given (and
396
+ # the stream it returns holds the same children either way).
397
+ # #182: the wrapper is the sole owner of the C memory — the
398
+ # stream merely REFERENCES it; the wrapper's own finalizer
399
+ # handles GC-free. (The block-yielding form is tracked under
400
+ # #179: the current implementation materializes eagerly; the
401
+ # block is only honored as a no-op convenience.)
402
+ doc = Yeptris::Document.parse(yaml, schema: :compat_11)
403
+ return nil if doc.nil? || doc.document_count.zero?
404
+
405
+ stream = Nodes::Stream.new
406
+ (0...doc.document_count).each do |i|
407
+ child = Nodes::Builder.document_stream_child(doc, i)
408
+ stream.children << child
409
+ block.call(child) if block # stdlib's yielding form (#179 round 4)
410
+ end
411
+ # ownership: the DOCUMENT wrapper is the sole owner — its own
412
+ # finalizer (pointer-only closure) frees the C memory; the
413
+ # stream merely references it. A tree-side finalizer closing
414
+ # over the wrapper raced the wrapper's sweep (#182's abort).
415
+ stream.owner = doc
416
+ stream
417
+ rescue Yeptris::ParseError => e
418
+ raise SyntaxError.from_parse_error(e)
419
+ ensure
420
+ # the returned stream OWNS the doc's lifetime (its free delegates
421
+ # to the owner); only free here when the stream wasn't built
422
+ doc&.free if doc && !stream
423
+ end
424
+
425
+ # Arbitrary object graphs through the YAMLTree visitor
426
+ # (anchors, !ruby/ tags); plain data rides the fast builder.
427
+ # options reach the engine's emitter: :line_width is psych's
428
+ # fold-column knob — 0/nil rides the engine default (80; with the
429
+ # engine's #1257 flip, block plain/single-quoted scalars fold
430
+ # there too, matching stdlib Psych's stored-file bytes), a
431
+ # negative value is the unwrap (the engine clamps it to
432
+ # never-fold), :canonical switches the fixed form; :indentation
433
+ # is accepted for Psych parity (the engine's YAML emitter has no
434
+ # indentation knob). The audit round-2 finding — width accepted
435
+ # and discarded — is closed here and in YAMLTree.create.
436
+ def dump(obj, io = nil, options = {})
437
+ # stdlib's Object#to_yaml calls Psych.dump(self, options) —
438
+ # the options hash lands in the io slot positionally; treat a
439
+ # Hash there as options
440
+ if io.is_a?(::Hash)
441
+ options = io
442
+ io = nil
443
+ end
444
+ # scalars take the fast builder; EVERYTHING else (including
445
+ # plain containers — they may nest custom objects) goes
446
+ # through the visitor, which builds the same DOM for plain
447
+ # data anyway
448
+ out =
449
+ case obj
450
+ # DateTime < Date in ruby's hierarchy — the fast scalar
451
+ # path would emit it tag-less iso8601 (re-loading as Time);
452
+ # the visitor carries stdlib's !ruby/object:DateTime tag
453
+ when ::DateTime
454
+ Visitors::YAMLTree.new(options: options).push(obj).finish
455
+ when nil, true, false, ::String, ::Integer, ::Float, ::Symbol, ::Date, ::Time
456
+ Yeptris::YAML.dump(obj, header: true, width: options[:line_width],
457
+ canonical: options[:canonical] ? true : false)
458
+ else
459
+ Visitors::YAMLTree.new(options: options).push(obj).finish
460
+ end
461
+ return out unless io
462
+
463
+ io.write(out)
464
+ io
465
+ end
466
+
467
+ private
468
+
469
+ # yeptris materializes plain data only — there is nothing
470
+ # unsafe it COULD load. The safety walk enforces Psych's
471
+ # contract: aliases need opt-in, explicit non-core tags raise
472
+ # DisallowedClass, and a scalar whose IMPLICIT typing yields a
473
+ # class outside the permitted set raises too (issue #69: a
474
+ # compat_11 date must not become a Date unless Date is
475
+ # permitted — Psych::DisallowedClass semantics).
476
+ #
477
+ # The single-pass slice (#862): the gate walk IS the cost —
478
+ # per-node FFI reads. Three provable facts retire it for clean
479
+ # documents: the parser cannot build an alias without a `*`
480
+ # byte in the source, cannot build an explicit tag without a
481
+ # `!` byte, and the marshal builder REFUSES timestamps and
482
+ # merge keys (its success proves none exist — every
483
+ # timestamp-typed shape is refused, verified per shape). So
484
+ # `marshal_fast` doubles as the probe AND the build in one C
485
+ # call: on a gate-free source its success proves check() could
486
+ # not have raised, and the walk disappears; a refusal or a gate
487
+ # byte falls back to the checked walk, which is byte-for-byte
488
+ # the old path.
489
+ def walk_safe(root, permitted, aliases_enabled, source = nil)
490
+ if root && !source.nil? &&
491
+ !source.include?("*") && !source.include?("!")
492
+ fast = root.marshal_fast
493
+ return fast unless fast.nil?
494
+ end
495
+ check(root, permitted, aliases_enabled) if root
496
+ root.to_ruby
497
+ end
498
+
499
+ PERMITTED_BY_DEFAULT = [TrueClass, FalseClass, NilClass, Integer, Float,
500
+ String, Array, Hash].freeze
501
+
502
+ CORE_TAGS = %w[str int float bool null timestamp seq map merge value
503
+ binary].freeze
504
+
505
+ # Both tag spellings to the "ruby/…" short form: the engine may
506
+ # hand either the "!ruby/symbol" shorthand or the
507
+ # "tag:ruby.yaml.org,2002:…" URI spelling.
508
+ def ruby_tag_short(tag)
509
+ t = tag.sub(/\A!/, "")
510
+ return t if t.start_with?("ruby/")
511
+ t.sub(/\Atag:ruby\.yaml\.org,2002:/, "ruby/")
512
+ end
513
+
514
+ # psych's scanner coercion path — always allowed, no class
515
+ # loader involved (verified against stdlib: !ruby/string with no
516
+ # permitted_classes loads fine)
517
+ RUBY_TAG_PRIMITIVES = %w[ruby/string ruby/integer ruby/float].freeze
518
+
519
+ # The class a !ruby/… tag names (psych's resolve_class face):
520
+ # "ruby/symbol" → Symbol; "ruby/object:Foo" and the collection
521
+ # forms "ruby/hash:Foo" name Foo. Nil = not a class-shaped ruby
522
+ # tag (or unresolvable) — the caller raises DisallowedClass.
523
+ RUBY_TAG_SINGLETONS = {
524
+ "ruby/symbol" => ::Symbol,
525
+ }.freeze
526
+
527
+ def ruby_tag_class(short)
528
+ return RUBY_TAG_SINGLETONS[short] if RUBY_TAG_SINGLETONS.key?(short)
529
+
530
+ rest = short[/\Aruby\/(?:object|hash|array|struct|exception)(?::(.*))?\z/, 1]
531
+ return nil if rest.nil? || rest.empty?
532
+ rest.split("::").inject(Object) do |mod, part|
533
+ return nil unless mod.const_defined?(part, false)
534
+ mod.const_get(part, false)
535
+ end
536
+ end
537
+
538
+ def check(node, permitted, aliases_enabled)
539
+ case node.kind
540
+ when :alias
541
+ raise AliasesError, "Unknown alias" unless aliases_enabled
542
+ when :scalar, :mapping, :sequence
543
+ tag = node.tag
544
+ unless tag.nil?
545
+ # both tag spellings pass: the URI form's last segment and
546
+ # the short "!binary" shorthand (#168's cassettes carry it)
547
+ name = tag.split(":").last.sub(/\A!/, "")
548
+ unless CORE_TAGS.include?(name)
549
+ # #258: !ruby/… tags follow psych's ClassLoader rules —
550
+ # the scalar primitives (string/integer/float) coerce
551
+ # through the scanner and are allowed as-is; !ruby/symbol
552
+ # passes exactly when Symbol is in permitted_classes;
553
+ # class-bearing forms (ruby/object:K, ruby/hash:K, …)
554
+ # pass when K is in permitted_classes
555
+ short = ruby_tag_short(tag)
556
+ unless RUBY_TAG_PRIMITIVES.include?(short)
557
+ klass = ruby_tag_class(short)
558
+ raise DisallowedClass, name if klass.nil?
559
+ raise DisallowedClass, name unless permitted.include?(klass)
560
+ end
561
+ end
562
+ end
563
+ # psych's safe law for the timestamp family (#1305): the gate
564
+ # applies to the RESOLVED class, not the tag. A plain
565
+ # timestamp resolves like psych's scanner — date-only to
566
+ # Date, date+time to Time (ClassLoader::Restricted#time /
567
+ # #date raise DisallowedClass naming the class) — so the
568
+ # decision rides the ONE resolver the materializer itself
569
+ # uses (parse_timestamp); a malformed timestamp text
570
+ # resolves to String there and psych likewise yields a
571
+ # String (no gate — plain data).
572
+ if node.kind == :scalar && node.tag_id == :timestamp
573
+ resolved = ::Yeptris::Materializer.parse_timestamp(node.value.to_s)
574
+ klass = resolved.class
575
+ if (klass == ::Date || klass == ::Time) && !permitted.include?(klass)
576
+ raise DisallowedClass, klass.name
577
+ end
578
+ end
579
+ case node.kind
580
+ when :mapping
581
+ node.each_pair do |k, v|
582
+ check(k, permitted, aliases_enabled)
583
+ check(v, permitted, aliases_enabled)
584
+ end
585
+ when :sequence
586
+ node.each { |e| check(e, permitted, aliases_enabled) }
587
+ end
588
+ end
589
+ end
590
+ end
591
+
592
+ # Psych::Nodes over the yeptris document: the tree IS the parsed
593
+ # document (children are node handles, not copies) — parse cost
594
+ # is the parse, and to_ruby reuses the Materializer.
595
+ module Nodes
596
+ class Node
597
+ include Enumerable
598
+
599
+ attr_reader :children
600
+ # #179: the event marks (0-based), applied by TreeBuilder
601
+ attr_accessor :start_line, :start_column, :end_line, :end_column
602
+ attr_reader :handle # @api private — the Yeptris::Node
603
+ # @api private — the tree builder attaches handles; a writer,
604
+ # never instance_variable_set from outside
605
+ attr_writer :handle
606
+ # The Document owning this tree's C memory; a plain writer —
607
+ # never instance_variable_set from outside (encapsulation law).
608
+ attr_accessor :owner
609
+
610
+ def initialize(handle = nil, children = [])
611
+ @handle = handle
612
+ @children = children
613
+ end
614
+
615
+ # Every node HAS an anchor concept (none by default) — the
616
+ # anchored search needs no type probe, just the model.
617
+ def anchor
618
+ nil
619
+ end
620
+
621
+ def each(&block)
622
+ @children.each(&block)
623
+ end
624
+
625
+ # The Ruby object for this subtree (Materializer semantics).
626
+ def to_ruby
627
+ @handle.to_ruby
628
+ end
629
+ end
630
+
631
+ class Stream < Node
632
+ def free
633
+ @owner&.free
634
+ end
635
+ end
636
+
637
+ # Owns the underlying Yeptris::Document: node handles in the
638
+ # tree stay valid while the tree is reachable; a GC finalizer
639
+ # releases the C memory when it is not.
640
+ class Document < Node
641
+ # The document's root as a Ruby object (the stream-yield face).
642
+ def to_ruby
643
+ children.first&.to_ruby
644
+ end
645
+ attr_reader :version, :tags
646
+
647
+ def initialize(version = [], tags = {})
648
+ super(nil)
649
+ @version = version
650
+ @tags = tags
651
+ end
652
+
653
+ # @api private — attach the document: the tree REFERENCES it
654
+ # (keeping the C memory alive while the tree is reachable);
655
+ # the wrapper's own finalizer is the sole freer (#182: a
656
+ # tree-side finalizer closing over the wrapper raced the
657
+ # wrapper's sweep — SIGABRT under document churn)
658
+ def own(yeptris_doc)
659
+ @owner = yeptris_doc
660
+ self
661
+ end
662
+
663
+ def free
664
+ @owner&.free
665
+ end
666
+ end
667
+
668
+ class Scalar < Node
669
+ attr_reader :value, :tag, :anchor, :plain, :quoted, :style
670
+
671
+ def initialize(value = nil, anchor: nil, tag: nil, plain: true,
672
+ quoted: false, style: :plain)
673
+ super(nil)
674
+ @value = value
675
+ @anchor = anchor
676
+ @tag = tag
677
+ @plain = plain
678
+ @quoted = quoted
679
+ @style = style
680
+ end
681
+ end
682
+
683
+ class Sequence < Node
684
+ attr_reader :anchor, :tag, :style
685
+
686
+ def initialize(anchor: nil, tag: nil, style: :block)
687
+ super(nil, [])
688
+ @anchor = anchor
689
+ @tag = tag
690
+ @style = style
691
+ end
692
+ end
693
+
694
+ class Mapping < Node
695
+ attr_reader :anchor, :tag, :style
696
+
697
+ def initialize(anchor: nil, tag: nil, style: :block)
698
+ super(nil, [])
699
+ @anchor = anchor
700
+ @tag = tag
701
+ @style = style
702
+ end
703
+ end
704
+
705
+ class Alias < Node
706
+ attr_reader :anchor
707
+
708
+ def initialize(anchor)
709
+ super(nil)
710
+ @anchor = anchor
711
+ end
712
+ end
713
+
714
+ # Builds the Nodes tree from a parsed document.
715
+ module Builder
716
+ module_function
717
+
718
+ # parse(): one document, owning the yeptris document
719
+ def document(doc, index = 0)
720
+ document_stream_child(doc, index).own(doc)
721
+ end
722
+
723
+ # parse_stream(): a child document sharing one owner (the
724
+ # stream owns the yeptris document)
725
+ def document_stream_child(doc, index)
726
+ root = doc.root(index)
727
+ # #182's root cause: three per-stream Document wrappers all
728
+ # capture the same c_ptr in their finalizers → three frees.
729
+ # The stream-children WRAPPER owns nothing (the owner wrapper
730
+ # is the real Document; this one just references it). Build
731
+ # a non-owning wrapper with no finalizer.
732
+ d = Document.send(:new, root&.document, false)
733
+ d.children << node(root) if root
734
+ d
735
+ end
736
+
737
+ def node(n)
738
+ case n.kind
739
+ when :mapping
740
+ m = Mapping.new(anchor: n.anchor, tag: n.tag)
741
+ n.each_pair do |k, v|
742
+ m.children << node(k)
743
+ m.children << node(v)
744
+ end
745
+ m.handle = n
746
+ m
747
+ when :sequence
748
+ s = Sequence.new(anchor: n.anchor, tag: n.tag)
749
+ n.each { |e| s.children << node(e) }
750
+ s.handle = n
751
+ s
752
+ when :alias
753
+ a = Alias.new(n.value)
754
+ a.handle = n
755
+ a
756
+ else
757
+ sc = Scalar.new(n.value, anchor: n.anchor, tag: n.tag,
758
+ plain: n.style == :plain, style: n.style)
759
+ sc.handle = n
760
+ sc
761
+ end
762
+ end
763
+ end
764
+ end
765
+ end
766
+ end
767
+
768
+ # The drop-in is OPT-IN (issue #69): `require "yeptris/psych"` loads
769
+ # the namespace only and coexists with stdlib psych in ANY load
770
+ # order (this file never touches ::Psych). The rebind lives in
771
+ # yeptris/psych/drop_in — process-exclusive by nature, since the
772
+ # stdlib cannot be prevented from re-opening whatever ::Psych points
773
+ # at once IT loads.
774
+ # The core extension (stdlib psych/core_ext parity): Object#to_yaml
775
+ # and Object.yaml_tag exist whether the consumer came through stdlib
776
+ # psych first or pure drop-in. Both definitions are compatible —
777
+ # whoever loads last wins, and both call the rebound Psych.dump.
778
+ class Object
779
+ def self.yaml_tag(url)
780
+ ::Yeptris::Psych.add_tag(url, self)
781
+ end
782
+
783
+ def to_yaml(options = {})
784
+ ::Yeptris::Psych.dump(self, options)
785
+ end
786
+ end
787
+
788
+ # 0.4-contract migration signal (issue #95): this require used to
789
+ # rebind ::Psych. It does not anymore, and re-binding it here would
790
+ # regress #69 (any stdlib psych loaded afterwards would explode with
791
+ # a superclass mismatch), so the old path warns instead of acting.
792
+ if defined?(::Psych) && !::Psych.equal?(Yeptris::Psych) && Yeptris.debug?
793
+ warn "yeptris: \"yeptris/psych\" defines the namespace only — it no " \
794
+ "longer rebinds ::Psych. Require \"yeptris/psych/drop_in\" for the " \
795
+ "drop-in rebind, or call Yeptris::Psych explicitly."
796
+ end