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,253 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Yeptris
4
+ # The schema-descriptor materialization (issue #238; the C ABI lives
5
+ # in yeptris/schema.h and docs/schema-abi.md). One native pass fills
6
+ # typed columns against a caller-compiled descriptor; the
7
+ # intermediate generic document never exists.
8
+ module Schema
9
+ module_function
10
+
11
+ KIND = { scalar: 0, sequence: 1, mapping: 2, callback: 3 }.freeze
12
+ TYPE = { str: 0, int: 1, float: 2, bool: 3, null: 4, any: 5 }.freeze
13
+ REQUIRED = 1 << 0
14
+ FIRST_WINS = 1 << 1 # duplicates within one mapping: first kept
15
+
16
+ # The :any verdict (#238's headroom): the resolver's own typing,
17
+ # one 24-byte record per value — Integer/Float/true/false/nil, a
18
+ # zero-copy String for str/timestamp spans
19
+ ANY_SIZE = 24 # yeptris_value.h's YeptrisValue: kind@0 tag_id@1
20
+ # is_key@2 b@3 off@4 len@8 p@16 — the C layout, ABI-pinned
21
+ ANY_KIND = { 1 => :null, 2 => :bool, 3 => :int, 4 => :float,
22
+ 5 => :str, 6 => :timestamp }.freeze
23
+
24
+ class Error < Yeptris::Error; end
25
+
26
+ # #238's executed headroom (ST_ANY/FIRST_WINS) rides the C tag
27
+ # AFTER v0.6.12; probe the engine rather than trusting versions
28
+ class << self
29
+ def headroom_supported?
30
+ return @headroom_supported unless @headroom_supported.nil?
31
+ @headroom_supported = begin
32
+ load("x: 1\n",
33
+ desc: [{ kind: :mapping, child_index: 1, child_count: 1 },
34
+ { wire_name: "x", kind: :scalar, type: :any }]) && true
35
+ rescue Error, Yeptris::ParseError, Yeptris::Error
36
+ false
37
+ end
38
+ end
39
+ end
40
+ class RequiredMissing < Error; end
41
+
42
+ ELEMENT_SIZE = { 0 => 16, 1 => 8, 2 => 8, 3 => 1, 4 => 1, 5 => ANY_SIZE }.freeze # by TYPE value
43
+
44
+ # A materialized span: zero-copy off/len into the source plus the
45
+ # node's byte offset (the CALLBACK escape hatch).
46
+ Span = Struct.new(:offset, :length, :node_offset) do
47
+ def bytes_from(source)
48
+ source.byteslice(offset, length)
49
+ end
50
+ end
51
+
52
+ # desc: a flat array of node hashes, the C ABI 1:1 —
53
+ # { wire_name:, kind:, type:, required:, child_index:, child_count: }
54
+ # (kind/type symbolic; wire_name nil = the root). Returns one typed
55
+ # Ruby array per node: Integer/Float/true/false/nil/String for
56
+ # scalars and sequence elements (document order), Span for
57
+ # callbacks.
58
+ def load(source, schema: :core_12, desc:, capacity: 64)
59
+ source = Yeptris.read_input(source).to_s
60
+ schema_id = schema == :compat_11 ? FFI::SCHEMA_11_COMPAT : FFI::SCHEMA_12_CORE
61
+ plans = compile(desc)
62
+ loop do
63
+ result = run(source, schema_id, plans, capacity)
64
+ return result unless result == :grow
65
+ capacity *= 2
66
+ end
67
+ end
68
+
69
+ # #184 (lutaml-model KV path): zip Schema columns into record
70
+ # hashes ready for Serializable.instantiate. Mapping root → one
71
+ # hash; sequence-of-mappings → one hash per element; nested
72
+ # mappings → nested hashes. Returns Array<Hash> always. when_attribute
73
+ # / polymorphic stay out of scope (interpretive fallback).
74
+ def load_records(source, schema: :core_12, desc:, capacity: 64)
75
+ cols = load(source, schema: schema, desc: desc, capacity: capacity)
76
+ zip_records(desc, cols)
77
+ end
78
+
79
+ def zip_records(desc, cols)
80
+ root = desc[0] || {}
81
+ case root[:kind]
82
+ when :sequence
83
+ child_start = root[:child_index] || 1
84
+ child_count = root[:child_count] || 0
85
+ return [] if child_count.zero?
86
+
87
+ child = desc[child_start]
88
+ if child && child[:kind] == :mapping
89
+ field_start = child[:child_index] || (child_start + 1)
90
+ field_count = child[:child_count] || 0
91
+ fields = desc[field_start, field_count] || []
92
+ field_cols = cols[field_start, field_count] || []
93
+ nrows = field_cols.map(&:length).max || 0
94
+ Array.new(nrows) do |r|
95
+ h = {}
96
+ fields.each_with_index do |f, i|
97
+ next unless f[:wire_name]
98
+ col = field_cols[i] || []
99
+ # ABSENT keys are OMITTED, not nil-filled (lutaml-model's
100
+ # load-bearing edge: absent seeds defaults +
101
+ # using_default?; explicit nil is a present value with
102
+ # different render semantics). The C columns fill in
103
+ # document order — col.length > r means present.
104
+ next if col.length <= r
105
+
106
+ h[f[:wire_name].to_sym] = materialize_field(f, desc, cols, col[r])
107
+ end
108
+ h
109
+ end
110
+ else
111
+ (cols[child_start] || []).map { |v| { value: v } }
112
+ end
113
+ when :mapping
114
+ field_start = root[:child_index] || 1
115
+ field_count = root[:child_count] || 0
116
+ fields = desc[field_start, field_count] || []
117
+ field_cols = cols[field_start, field_count] || []
118
+ h = {}
119
+ fields.each_with_index do |f, i|
120
+ next unless f[:wire_name]
121
+ col = field_cols[i] || []
122
+ next if col.empty? # absent: omitted, not nil-filled (#184)
123
+
124
+ h[f[:wire_name].to_sym] = materialize_field(f, desc, cols, col[0])
125
+ end
126
+ [h]
127
+ else
128
+ [{ value: cols[0]&.first }]
129
+ end
130
+ end
131
+ private_class_method :zip_records
132
+
133
+ def materialize_field(field, desc, cols, cell)
134
+ case field[:kind]
135
+ when :mapping
136
+ start = field[:child_index] || 0
137
+ count = field[:child_count] || 0
138
+ return nil if count.zero? || cell.nil?
139
+
140
+ nested = {}
141
+ desc[start, count]&.each_with_index do |nf, i|
142
+ next unless nf[:wire_name]
143
+ ncol = cols[start + i] || []
144
+ nested[nf[:wire_name].to_sym] = ncol.is_a?(Array) ? (ncol[0] rescue cell) : cell
145
+ end
146
+ nested
147
+ when :sequence
148
+ cell.is_a?(Array) ? cell : Array(cell)
149
+ else
150
+ cell
151
+ end
152
+ end
153
+ private_class_method :materialize_field
154
+
155
+ def compile(desc)
156
+ desc.map do |n|
157
+ { kind: KIND.fetch(n.fetch(:kind)),
158
+ type: TYPE.fetch(n[:type] || :str),
159
+ wire: n[:wire_name],
160
+ flags: (n[:required] ? REQUIRED : 0) | (n[:first_wins] ? FIRST_WINS : 0),
161
+ child_index: n[:child_index] || 0,
162
+ child_count: n[:child_count] || 0 }
163
+ end
164
+ end
165
+ private_class_method :compile
166
+
167
+ def run(source, schema_id, plans, capacity) # rubocop:disable Metrics/MethodLength
168
+ n = plans.length
169
+ desc_buf = ::FFI::MemoryPointer.new(FFI::DescNode, n, true)
170
+ wires = []
171
+ plans.each_with_index do |p, i|
172
+ node = FFI::DescNode.new(desc_buf + i * FFI::DescNode.size)
173
+ if p[:wire]
174
+ wires << (wire = ::FFI::MemoryPointer.from_string(p[:wire]))
175
+ node[:wire_name] = wire
176
+ end
177
+ node[:kind] = p[:kind]
178
+ node[:type_tag] = p[:type]
179
+ node[:flags] = p[:flags]
180
+ node[:child_index] = p[:child_index]
181
+ node[:child_count] = p[:child_count]
182
+ node[:reserved] = 0
183
+ end
184
+ cols_buf = ::FFI::MemoryPointer.new(FFI::SchemaColumn, n, true)
185
+ data_ptrs = []
186
+ plans.each_with_index do |p, i|
187
+ col = FFI::SchemaColumn.new(cols_buf + i * FFI::SchemaColumn.size)
188
+ elem = ELEMENT_SIZE.fetch(p[:type], 16)
189
+ data = ::FFI::MemoryPointer.new(elem, capacity, true)
190
+ data_ptrs << data
191
+ col[:data] = data
192
+ col[:capacity] = capacity
193
+ col[:count] = 0
194
+ end
195
+
196
+ src = ::FFI::MemoryPointer.from_string(source) # NUL-safe copy for the C side
197
+ st = FFI.yeptris_schema_load(src, source.bytesize, schema_id, desc_buf, n,
198
+ FFI::DESC_ABI, cols_buf)
199
+ case st
200
+ when FFI::OK
201
+ plans.each_with_index.map { |p, i| drain(cols_buf, i, p, source) }
202
+ when FFI::ERROR_MEMORY
203
+ :grow
204
+ when FFI::SCHEMA_ERROR
205
+ msg = FFI.last_error_message
206
+ raise RequiredMissing, msg
207
+ else
208
+ raise Yeptris::ParseError, FFI.last_error_message
209
+ end
210
+ end
211
+ private_class_method :run
212
+
213
+ def drain(cols_buf, i, plan, source)
214
+ col = FFI::SchemaColumn.new(cols_buf + i * FFI::SchemaColumn.size)
215
+ count = col[:count]
216
+ data = col[:data]
217
+ case plan[:kind]
218
+ when KIND[:callback]
219
+ Array.new(count) do |k|
220
+ off = data.get_uint32(k * 16)
221
+ len = data.get_uint32(k * 16 + 4)
222
+ node_off = data.get_uint32(k * 16 + 8)
223
+ Span.new(off, len, node_off)
224
+ end
225
+ else
226
+ type = plan[:type]
227
+ Array.new(count) do |k|
228
+ case type
229
+ when TYPE[:int] then data.get_int64(k * 8)
230
+ when TYPE[:float] then data.get_double(k * 8)
231
+ when TYPE[:bool] then data.get_uchar(k) == 1
232
+ when TYPE[:null] then nil
233
+ when TYPE[:any]
234
+ rec = k * ANY_SIZE
235
+ case ANY_KIND[data.get_uint8(rec)]
236
+ when :int then data.get_int64(rec + 16)
237
+ when :float then data.get_double(rec + 16)
238
+ when :bool then data.get_uint8(rec + 3) == 1
239
+ when :null then nil
240
+ else # str/timestamp: the zero-copy span
241
+ source.byteslice(data.get_uint32(rec + 4), data.get_uint32(rec + 8))
242
+ end
243
+ else
244
+ off = data.get_uint32(k * 16)
245
+ len = data.get_uint32(k * 16 + 4)
246
+ source.byteslice(off, len)
247
+ end
248
+ end
249
+ end
250
+ end
251
+ private_class_method :drain
252
+ end
253
+ end
@@ -0,0 +1,320 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Yeptris
4
+ # The validation face (engine validate.h; issue #882, binding
5
+ # TODO item 6). Two checks over one engine pass:
6
+ #
7
+ # * the SCHEMA-FAMILY walk (`validate` with a schema symbol) —
8
+ # explicit-tag consistency, mapping-key uniqueness by canonical
9
+ # form, and (under :json_12) the spec 10.2 JSON-production rules;
10
+ # * JSON SCHEMA draft 2020-12 (`validate` with `json_schema:`) —
11
+ # one-shot over schema bytes, or against a compiled
12
+ # {Yeptris::Validation::Schema} handle (parse once, validate
13
+ # many; #885 item 3).
14
+ #
15
+ # Diagnostics cross the FFI boundary once, as plain Ruby values
16
+ # ({Diagnostic}): no C pointer ever leaks out of this module.
17
+ module Validation
18
+ # Raised for an instance that carries diagnostics. The full report
19
+ # rides `diagnostics` (plain {Diagnostic} values, never pointers).
20
+ class Error < ::Yeptris::Error
21
+ attr_reader :diagnostics
22
+
23
+ def initialize(diagnostics)
24
+ @diagnostics = diagnostics
25
+ first = diagnostics.first
26
+ detail = first ? "#{first.keyword} at #{first.path}: #{first.detail}" : "no diagnostics"
27
+ super("validation failed (#{diagnostics.size} diagnostics): #{detail}")
28
+ end
29
+ end
30
+
31
+ # The code -> keyword table (validate.h's YeptrisDiagCode). The
32
+ # 2020-12 walk's codes name their JSON Schema keyword; the
33
+ # schema-family walk's codes name the violated YAML rule.
34
+ KEYWORD = {
35
+ FFI::DIAG_NONE => "none",
36
+ FFI::DIAG_TAG_MISMATCH => "tag-mismatch",
37
+ FFI::DIAG_KEY_NOT_STRING => "key-not-string",
38
+ FFI::DIAG_NON_JSON_TYPE => "non-json-type",
39
+ FFI::DIAG_DUPLICATE_KEY => "duplicate-key",
40
+ FFI::DIAG_TYPE => "type",
41
+ FFI::DIAG_REQUIRED => "required",
42
+ FFI::DIAG_ENUM => "enum",
43
+ FFI::DIAG_CONST => "const",
44
+ FFI::DIAG_PATTERN => "pattern",
45
+ FFI::DIAG_MINIMUM => "minimum",
46
+ FFI::DIAG_MAXIMUM => "maximum",
47
+ FFI::DIAG_EXCLUSIVE_MINIMUM => "exclusiveMinimum",
48
+ FFI::DIAG_EXCLUSIVE_MAXIMUM => "exclusiveMaximum",
49
+ FFI::DIAG_MIN_LENGTH => "minLength",
50
+ FFI::DIAG_MAX_LENGTH => "maxLength",
51
+ FFI::DIAG_MIN_ITEMS => "minItems",
52
+ FFI::DIAG_MAX_ITEMS => "maxItems",
53
+ FFI::DIAG_UNIQUE_ITEMS => "uniqueItems",
54
+ FFI::DIAG_ADDITIONAL_PROPERTY => "additionalProperties",
55
+ FFI::DIAG_ANY_OF => "anyOf",
56
+ FFI::DIAG_ONE_OF => "oneOf",
57
+ FFI::DIAG_NOT => "not",
58
+ FFI::DIAG_REF => "$ref",
59
+ FFI::DIAG_FALSE_SCHEMA => "false",
60
+ FFI::DIAG_DEPTH => "depth",
61
+ FFI::DIAG_LIMIT => "limit",
62
+ FFI::DIAG_MULTIPLE_OF => "multipleOf",
63
+ FFI::DIAG_MIN_PROPERTIES => "minProperties",
64
+ FFI::DIAG_MAX_PROPERTIES => "maxProperties",
65
+ FFI::DIAG_CONTAINS => "contains",
66
+ FFI::DIAG_MIN_CONTAINS => "minContains",
67
+ FFI::DIAG_MAX_CONTAINS => "maxContains",
68
+ FFI::DIAG_DEPENDENT_REQUIRED => "dependentRequired",
69
+ }.freeze
70
+
71
+ # One structured diagnostic: the engine's yeptris_diagnostic read
72
+ # into plain Ruby at drain time (a value class — ==, eql?, hash —
73
+ # never an FFI wrapper).
74
+ class Diagnostic
75
+ attr_reader :code, :path, :detail, :line, :col, :offset
76
+
77
+ def initialize(code:, path:, detail:, line: 0, col: 0, offset: 0)
78
+ @code = code
79
+ @path = path
80
+ @detail = detail
81
+ @line = line
82
+ @col = col
83
+ @offset = offset
84
+ end
85
+
86
+ # The violated keyword ("type", "minimum", "duplicate-key", ...).
87
+ def keyword
88
+ KEYWORD.fetch(code, "unknown-#{code}")
89
+ end
90
+
91
+ # The JSON-pointer instance path ("/a/b/0", ~0/~1 escaped) split
92
+ # into its unescaped segments; the root is [].
93
+ def path_array
94
+ return [] if path.empty?
95
+
96
+ path.split("/")[1..].map { |s| s.gsub("~1", "/").gsub("~0", "~") }
97
+ end
98
+
99
+ # The engine's bounded explanation ("3 is less than the minimum 10").
100
+ def message
101
+ detail
102
+ end
103
+
104
+ alias to_s message
105
+
106
+ def ==(other)
107
+ other.is_a?(Diagnostic) && code == other.code && path == other.path &&
108
+ detail == other.detail && line == other.line && col == other.col &&
109
+ offset == other.offset
110
+ end
111
+ alias eql? ==
112
+
113
+ def hash
114
+ [code, path, detail, line, col, offset].hash
115
+ end
116
+
117
+ def to_h
118
+ { code: code, keyword: keyword, path: path, path_array: path_array,
119
+ detail: detail, message: message, line: line, col: col, offset: offset }
120
+ end
121
+
122
+ def inspect
123
+ "#<#{self.class.name} #{keyword} path=#{path.inspect} line=#{line} " \
124
+ "col=#{col} detail=#{detail.inspect}>"
125
+ end
126
+ end
127
+
128
+ # The compiled schema (yeptris_schema_compile): the schema bytes,
129
+ # its DOM, and the pattern kernel's programs retained behind one
130
+ # opaque handle — parse ONCE, validate many streams against it.
131
+ # Ownership mirrors Yeptris::Document: an explicit #free and a GC
132
+ # finalizer flip the same freed flag (the pointer-only finalizer —
133
+ # it captures the raw address, never the wrapper, so no
134
+ # use-after-free race).
135
+ class Schema
136
+ # Shared between the instance and its finalizer (the
137
+ # leptris-ruby double-free fix).
138
+ Freed = Struct.new(:state) # :alive | :freed
139
+
140
+ attr_reader :c_ptr
141
+
142
+ # Compiles JSON Schema bytes (JSON is YAML flow — a YAML-shaped
143
+ # mapping schema compiles too). Raises ArgumentError for empty
144
+ # bytes (the engine's "hold no document") and ParseError for
145
+ # bytes that do not parse.
146
+ def self.compile(bytes)
147
+ raise ::ArgumentError, "schema bytes are required" if bytes.nil?
148
+ bytes = ::Yeptris.read_input(bytes).to_s
149
+ raise ::ArgumentError, "schema bytes hold no document" if bytes.empty?
150
+
151
+ ptr = FFI.yeptris_schema_compile(bytes, bytes.bytesize)
152
+ raise ::Yeptris::ParseError,
153
+ "schema compile failed: #{FFI.last_error_message}" if ptr.null?
154
+
155
+ new(ptr)
156
+ end
157
+
158
+ # Block form: the handle frees when the block exits (valid or not).
159
+ def self.open(bytes)
160
+ schema = compile(bytes)
161
+ begin
162
+ yield schema
163
+ ensure
164
+ schema.free
165
+ end
166
+ end
167
+
168
+ # @api private — produced by .compile; a raw pointer argument is
169
+ # not a caller surface (the same contract as Document).
170
+ def initialize(c_ptr)
171
+ unless c_ptr.is_a?(::FFI::Pointer)
172
+ raise ArgumentError,
173
+ "a schema FFI pointer is required — build schemas with " \
174
+ "Yeptris::Validation::Schema.compile"
175
+ end
176
+
177
+ @c_ptr = c_ptr
178
+ @freed = Freed.new(:alive)
179
+ ObjectSpace.define_finalizer(self, self.class.finalize(c_ptr)) unless c_ptr.null?
180
+ end
181
+
182
+ # Validates one instance stream against the retained model.
183
+ # Returns the diagnostics array (empty = valid).
184
+ def validate(bytes)
185
+ ensure_alive!
186
+ bytes = ::Yeptris.read_input(bytes).to_s
187
+ report = ::FFI::MemoryPointer.new(:pointer)
188
+ st = FFI.yeptris_schema_validate(@c_ptr, bytes, bytes.bytesize, report)
189
+ Validation.consume_report(st, report, "schema validate")
190
+ end
191
+
192
+ def valid?(bytes)
193
+ validate(bytes).empty?
194
+ end
195
+
196
+ def ensure_alive!
197
+ raise ::Yeptris::FreedError, "schema is freed" if @freed.state == :freed
198
+ end
199
+
200
+ def free
201
+ return if @freed.state == :freed
202
+
203
+ @freed.state = :freed
204
+ ObjectSpace.undefine_finalizer(self)
205
+ FFI.yeptris_schema_free(@c_ptr)
206
+ end
207
+
208
+ def freed?
209
+ @freed.state == :freed
210
+ end
211
+
212
+ # Pointer-only finalizer (Document's law): no Ruby objects, no
213
+ # wrapper — a finalizer closing over the wrapper races its sweep.
214
+ def self.finalize(c_ptr)
215
+ proc { FFI.yeptris_schema_free(c_ptr) }
216
+ end
217
+ end
218
+
219
+ class << self
220
+ # The schema-family walk over the engine's own front door
221
+ # (encodings, BOM, every document of the stream). schema: one of
222
+ # :core_12, :compat_11, :json_12. Returns the diagnostics array.
223
+ def validate_family(bytes, schema: :core_12)
224
+ require_engine!
225
+ bytes = ::Yeptris.read_input(bytes).to_s
226
+ report = ::FFI::MemoryPointer.new(:pointer)
227
+ st = FFI.yeptris_validate(bytes, bytes.bytesize, schema_id(schema), report)
228
+ consume_report(st, report, "validate")
229
+ end
230
+
231
+ # JSON Schema validation: `schema` is a compiled
232
+ # {Yeptris::Validation::Schema} (validate many) or schema bytes
233
+ # (one-shot). Returns the diagnostics array.
234
+ def validate_schema(bytes, schema)
235
+ require_engine!
236
+ case schema
237
+ when Schema then schema.validate(bytes)
238
+ when String then one_shot(bytes, schema)
239
+ else
240
+ raise ::ArgumentError,
241
+ "json_schema: must be a Yeptris::Validation::Schema or schema " \
242
+ "bytes (got #{schema.class})"
243
+ end
244
+ end
245
+
246
+ # The engine's whole-report drain shared by every face: maps the
247
+ # status, drains the diagnostics into plain values, frees the
248
+ # report — exactly once, on every path.
249
+ def consume_report(status, report, action)
250
+ ptr = report.read_pointer
251
+ diags = drain_report(ptr)
252
+ return diags if status == FFI::OK || status == FFI::SCHEMA_ERROR
253
+
254
+ raise ::ArgumentError, "#{action}: #{FFI.last_error_message}" if status == FFI::ERROR_ARG
255
+
256
+ raise ::Yeptris::ParseError, "#{action} failed: #{FFI.last_error_message}"
257
+ ensure
258
+ FFI.yeptris_validate_report_free(ptr) unless ptr.null?
259
+ end
260
+
261
+ # The schema symbol -> YeptrisSchema id (resolve.h's enum) for
262
+ # the VALIDATION family walks: only the YAML 1.2 families are
263
+ # validation families — the engine rejects :compat_11 with
264
+ # "schema 1 is not a validation family", surfaced here as the
265
+ # same ArgumentError the other bad symbols take.
266
+ def schema_id(name)
267
+ case name
268
+ when :core_12 then FFI::SCHEMA_12_CORE
269
+ when :json_12 then FFI::SCHEMA_12_JSON
270
+ when :compat_11
271
+ raise ::ArgumentError,
272
+ "schema: :compat_11 is not a validation family — the walk " \
273
+ "covers the YAML 1.2 families (:core_12, :json_12)"
274
+ else
275
+ raise ::ArgumentError,
276
+ "schema: must be :core_12, :compat_11, or :json_12 (got #{name.inspect})"
277
+ end
278
+ end
279
+
280
+ private
281
+
282
+ def one_shot(bytes, schema_bytes)
283
+ bytes = ::Yeptris.read_input(bytes).to_s
284
+ schema_bytes = schema_bytes.to_s
285
+ report = ::FFI::MemoryPointer.new(:pointer)
286
+ st = FFI.yeptris_json_schema_validate(schema_bytes, schema_bytes.bytesize,
287
+ bytes, bytes.bytesize, report)
288
+ consume_report(st, report, "json schema validate")
289
+ end
290
+
291
+ # drain before free: the diagnostics are read into plain Ruby
292
+ # while the report is still alive. The texts re-tag UTF-8 (the
293
+ # binding's string discipline — #135: engine materializations
294
+ # ride UTF-8, not the raw BINARY read).
295
+ def drain_report(report)
296
+ return [] if report.null?
297
+
298
+ FFI.yeptris_validate_report_count(report).times.map do |i|
299
+ d = FFI::CDiagnostic.new(FFI.yeptris_validate_report_at(report, i))
300
+ Diagnostic.new(
301
+ code: d[:code],
302
+ path: d.pointer.get_string(FFI::CDiagnostic.offset_of(:path))
303
+ .force_encoding(::Encoding::UTF_8),
304
+ detail: d.pointer.get_string(FFI::CDiagnostic.offset_of(:detail))
305
+ .force_encoding(::Encoding::UTF_8),
306
+ line: d[:line], col: d[:col], offset: d[:offset]
307
+ )
308
+ end
309
+ end
310
+
311
+ def require_engine!
312
+ return if FFI::VALIDATION
313
+
314
+ raise ::Yeptris::Error,
315
+ "yeptris: the validation face needs libyeptris 0.6.59+; the " \
316
+ "loaded library predates it. Update the engine library."
317
+ end
318
+ end
319
+ end
320
+ end