lutaml-model 0.8.202 → 0.8.204

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 (123) hide show
  1. checksums.yaml +4 -4
  2. data/.gitattributes +5 -0
  3. data/.github/workflows/dependent-tests.yml +59 -2
  4. data/.github/workflows/lml-conformance.yml +71 -0
  5. data/.gitignore +7 -0
  6. data/README.adoc +1 -0
  7. data/docs/_guides/lml-cross-language.adoc +128 -0
  8. data/docs/_references/lml-conformance.adoc +78 -0
  9. data/docs/_references/lml-contract.adoc +290 -0
  10. data/docs/_references/plan-schema-spec.adoc +45 -18
  11. data/lib/lutaml/key_value/transform.rb +140 -21
  12. data/lib/lutaml/model/attribute.rb +11 -6
  13. data/lib/lutaml/model/lml/artifact_verifier.rb +205 -0
  14. data/lib/lutaml/model/lml/bundle.rb +171 -0
  15. data/lib/lutaml/model/lml/document.rb +46 -10
  16. data/lib/lutaml/model/lml/document_validator.rb +840 -0
  17. data/lib/lutaml/model/lml/exporter/v1_projector.rb +102 -0
  18. data/lib/lutaml/model/lml/exporter/v2_projector.rb +401 -0
  19. data/lib/lutaml/model/lml/exporter.rb +223 -87
  20. data/lib/lutaml/model/lml/graph_exporter.rb +248 -0
  21. data/lib/lutaml/model/lml/importer.rb +180 -0
  22. data/lib/lutaml/model/lml/mapping_compiler.rb +401 -0
  23. data/lib/lutaml/model/lml/materialization.rb +257 -0
  24. data/lib/lutaml/model/lml/ordered_content.rb +577 -0
  25. data/lib/lutaml/model/lml/portable_json.rb +385 -0
  26. data/lib/lutaml/model/lml/rejected_error.rb +64 -15
  27. data/lib/lutaml/model/lml/round_trip.rb +86 -0
  28. data/lib/lutaml/model/lml/value_declarations.rb +84 -0
  29. data/lib/lutaml/model/lml.rb +61 -0
  30. data/lib/lutaml/model/schema/definitions/attribute.rb +4 -2
  31. data/lib/lutaml/model/schema/registry_generator.rb +1 -1
  32. data/lib/lutaml/model/schema/renderers/member_decls.rb +1 -0
  33. data/lib/lutaml/model/schema/xml_compiler/spec_builder/members.rb +10 -0
  34. data/lib/lutaml/model/sequence.rb +7 -0
  35. data/lib/lutaml/model/serialize/deserialization_context.rb +21 -0
  36. data/lib/lutaml/model/serialize/initialization.rb +19 -9
  37. data/lib/lutaml/model/version.rb +1 -1
  38. data/lib/lutaml/xml/leptris/native_emission.rb +4 -0
  39. data/lib/lutaml/xml/leptris/plan_serializer.rb +14 -9
  40. data/schema/lml/document.schema.json +179 -0
  41. data/scripts/lml/export_choices.rb +57 -0
  42. data/scripts/lml/export_conformance.rb +23 -0
  43. data/scripts/lml/export_mml.rb +253 -0
  44. data/scripts/lml/export_preservation.rb +421 -0
  45. data/scripts/lml/verify_artifacts.rb +31 -0
  46. data/spec/address_person_spec.rb +8 -0
  47. data/spec/address_spec.rb +4 -0
  48. data/spec/fixtures/lml_artifacts/model.json +1 -0
  49. data/spec/fixtures/lml_artifacts/valid.json +1 -0
  50. data/spec/fixtures/lml_artifacts/valid.sha256 +1 -0
  51. data/spec/fixtures/lml_conformance/core/index.json +1 -0
  52. data/spec/fixtures/lml_conformance/core/manifest.json +1 -0
  53. data/spec/fixtures/lml_conformance/core/schema.json +1 -0
  54. data/spec/fixtures/lml_conformance/core/schema.yaml +79 -0
  55. data/spec/fixtures/lml_conformance/float_vectors.generator.rb +60 -0
  56. data/spec/fixtures/lml_conformance/float_vectors.json +21550 -0
  57. data/spec/fixtures/lml_conformance/preservation/index.json +1 -0
  58. data/spec/fixtures/lml_conformance/preservation/manifest.json +1 -0
  59. data/spec/fixtures/lml_conformance/preservation/schema.json +1 -0
  60. data/spec/fixtures/lml_conformance/preservation/schema.yaml +319 -0
  61. data/spec/fixtures/lml_conformance/r2_refusals.generator.rb +153 -0
  62. data/spec/fixtures/lml_conformance/r2_refusals.json +1662 -0
  63. data/spec/fixtures/lml_conformance/ruby_portable_interop.generator.rb +40 -0
  64. data/spec/fixtures/lml_conformance/ruby_portable_interop.json +1 -0
  65. data/spec/fixtures/lml_contract/bundle.json +81 -0
  66. data/spec/fixtures/lml_contract/manifest.json +30 -0
  67. data/spec/fixtures/lml_contract/v1_unit.canonical.json +1 -0
  68. data/spec/fixtures/lml_contract/v1_unit.json +1 -0
  69. data/spec/fixtures/lml_contract/v2_node.canonical.json +1 -0
  70. data/spec/fixtures/lml_contract/v2_node.json +32 -0
  71. data/spec/fixtures/lml_mml/inventory.json +1 -0
  72. data/spec/fixtures/lml_mml/manifest.json +1 -0
  73. data/spec/fixtures/lml_mml/oracle.json +1 -0
  74. data/spec/fixtures/lml_mml/v3-mi-mixed.json +1 -0
  75. data/spec/fixtures/lml_mml/v3-mi-mixed.yaml +970 -0
  76. data/spec/fixtures/lml_mml/v4-mi-mixed.json +1 -0
  77. data/spec/fixtures/lml_mml/v4-mi-mixed.yaml +1516 -0
  78. data/spec/fixtures/lml_mml_materialization/replay.rb +37 -0
  79. data/spec/lutaml/key_value/group_instantiate_spec.rb +204 -1
  80. data/spec/lutaml/model/lml_any_attribute_spec.rb +91 -0
  81. data/spec/lutaml/model/lml_artifact_verifier_spec.rb +86 -0
  82. data/spec/lutaml/model/lml_builtin_types_spec.rb +49 -0
  83. data/spec/lutaml/model/lml_conformance_spec.rb +178 -0
  84. data/spec/lutaml/model/lml_document_spec.rb +279 -0
  85. data/spec/lutaml/model/lml_export_validation_spec.rb +96 -0
  86. data/spec/lutaml/model/lml_exporter_spec.rb +127 -5
  87. data/spec/lutaml/model/lml_graph_exporter_spec.rb +205 -0
  88. data/spec/lutaml/model/lml_importer_spec.rb +290 -0
  89. data/spec/lutaml/model/lml_input_hardening_spec.rb +156 -0
  90. data/spec/lutaml/model/lml_mapping_compiler_spec.rb +256 -0
  91. data/spec/lutaml/model/lml_materialization_spec.rb +138 -0
  92. data/spec/lutaml/model/lml_mml_materialization_spec.rb +54 -0
  93. data/spec/lutaml/model/lml_mml_pilot_spec.rb +150 -0
  94. data/spec/lutaml/model/lml_model_choices_spec.rb +88 -0
  95. data/spec/lutaml/model/lml_ordered_content_spec.rb +243 -0
  96. data/spec/lutaml/model/lml_portable_json_spec.rb +310 -0
  97. data/spec/lutaml/model/lml_preservation_spec.rb +211 -0
  98. data/spec/lutaml/model/lml_review_export_spec.rb +247 -0
  99. data/spec/lutaml/model/lml_review_import_spec.rb +390 -0
  100. data/spec/lutaml/model/lml_review_misc_spec.rb +152 -0
  101. data/spec/lutaml/model/lml_review_round4_spec.rb +200 -0
  102. data/spec/lutaml/model/lml_review_round5_spec.rb +194 -0
  103. data/spec/lutaml/model/lml_ruby_interop_fixture_spec.rb +37 -0
  104. data/spec/lutaml/model/lml_shared_corpus_spec.rb +132 -0
  105. data/spec/lutaml/model/lml_value_declarations_spec.rb +128 -0
  106. data/spec/lutaml/model/schema/class_loader_spec.rb +51 -0
  107. data/spec/lutaml/model/schema/xml_compiler_runtime_spec.rb +20 -0
  108. data/spec/lutaml/model/sequence_spec.rb +48 -0
  109. data/spec/lutaml/model/serialize/deserialization_context_spec.rb +68 -0
  110. data/spec/lutaml/xml/cdata_emission_spec.rb +68 -0
  111. data/spec/spec_helper.rb +4 -5
  112. data/spec/support/lml_any_attribute_fixtures.rb +26 -0
  113. data/spec/support/lml_conformance.rb +292 -0
  114. data/spec/support/lml_corpus.rb +75 -0
  115. data/spec/support/lml_export_fixtures.rb +190 -0
  116. data/spec/support/lml_graph_fixtures.rb +108 -0
  117. data/spec/support/lml_import_fixtures.rb +52 -0
  118. data/spec/support/lml_mapping_fixtures.rb +170 -0
  119. data/spec/support/lml_materialization_fixtures.rb +53 -0
  120. data/spec/support/lml_model_choices_fixtures.rb +150 -0
  121. data/spec/support/lml_order_fixtures.rb +151 -0
  122. metadata +93 -2
  123. data/lib/lutaml/model/schema/schema_builder/nokogiri.rb +0 -41
@@ -0,0 +1,385 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bigdecimal"
4
+ require "json"
5
+
6
+ module Lutaml
7
+ module Model
8
+ module Lml
9
+ # Writer for the `portable-exact-json-v1` wire profile
10
+ # (lutaml-model#1033), the profile the TS and Rust codecs read.
11
+ #
12
+ # `Serializable#to_json` writes `ruby-native-v1`: plain JSON numbers.
13
+ # This opt-in writer starts from that native output and re-spells
14
+ # only the values whose exact value a JSON number cannot carry, by
15
+ # the declared attribute type:
16
+ #
17
+ # * integer, positive_integer, non_negative_integer: a decimal
18
+ # string ("9007199254740993"), never a JSON number.
19
+ # * decimal: a plain decimal string without exponent ("1.5", never
20
+ # BigDecimal's "0.15e1"); signed zero is kept ("-0.0").
21
+ # * float: the canonical float wire string (DocumentValidator
22
+ # .float_wire: "0.1", "1.0e20", "-0.0").
23
+ #
24
+ # Booleans, strings, nil, nested models and collections keep their
25
+ # native JSON shape. Key order is the native order. A `hash`
26
+ # attribute's members have no declared type, so each number is
27
+ # spelled the one way the TS reader accepts as exact: an integer
28
+ # spelling only for a safe integer (|n| <= 2**53-1), every other
29
+ # float exactly as ECMAScript Number::toString spells it ("1e+21",
30
+ # "1.5e-7", "0.1"). A hash member that cannot be held exactly (an
31
+ # Integer beyond 2**53-1, a BigDecimal, -0.0, an integral float
32
+ # beyond 2**53-1, NaN/Infinity, a value that is not JSON data, a
33
+ # key collision or nesting deeper than 200) is refused. In
34
+ # `data`, a non-integer hash number is a Number carrying that
35
+ # spelling; `generate` writes it verbatim.
36
+ #
37
+ # Refused (RejectedError), never silently written: NaN/Infinity
38
+ # (no wire form), mappings whose output this writer cannot type
39
+ # (custom methods, delegates, keyed-collection and root mappings,
40
+ # unions) and a value type whose native output is a
41
+ # JSON number.
42
+ module PortableJson
43
+ PROFILE = "portable-exact-json-v1"
44
+ MAX_SAFE_INTEGER = (2**53) - 1
45
+ # The TS reader refuses a decimal of more digits than this.
46
+ MAX_DECIMAL_DIGITS = 10_000
47
+ HASH_MAX_DEPTH = 200
48
+
49
+ # A JSON number spelled exactly as written (see HashValue).
50
+ class Number
51
+ attr_reader :text
52
+
53
+ def initialize(text)
54
+ @text = text
55
+ end
56
+
57
+ def to_json(*)
58
+ text
59
+ end
60
+
61
+ def ==(other)
62
+ other.is_a?(Number) && other.text == text
63
+ end
64
+ end
65
+
66
+ module_function
67
+
68
+ # @param instance [Lutaml::Model::Serializable]
69
+ # @param pretty [Boolean] JSON.pretty_generate instead of generate
70
+ # @return [String] the instance as portable-exact-json-v1 text
71
+ def generate(instance, pretty: false)
72
+ data = self.data(instance)
73
+ pretty ? ::JSON.pretty_generate(data) : ::JSON.generate(data)
74
+ end
75
+
76
+ # @return [Hash] the portable wire document (string-keyed)
77
+ def data(instance)
78
+ unless instance.is_a?(Lutaml::Model::Serialize)
79
+ raise RejectedError.new(:not_serializable, instance.class.name,
80
+ "portable JSON needs a Serializable instance")
81
+ end
82
+
83
+ native = begin
84
+ ::JSON.parse(instance.to_json)
85
+ rescue ::JSON::JSONError, ::SystemStackError => e
86
+ # NaN/Infinity, a duplicate hash key, nesting past the json
87
+ # gem's limit of 100, or a model graph too deep (or cyclic)
88
+ # for native to_json: no native output, so no portable output.
89
+ raise RejectedError.new(:not_serializable, instance.class.name,
90
+ "no portable wire form: native JSON output failed (#{e.class}: " \
91
+ "#{e.message.to_s[0, 200]})")
92
+ end
93
+ portable_model(instance, native, "")
94
+ end
95
+
96
+ def portable_model(instance, native, location)
97
+ klass = instance.class
98
+ return native unless native.is_a?(::Hash)
99
+
100
+ mapping = klass.mappings_for(:json, instance.lutaml_register)
101
+ reject_mapping!(klass, mapping)
102
+ mapping.mappings.each do |rule|
103
+ reject_rule!(klass, rule)
104
+ key = Array(rule.name).map(&:to_s).find { |name| native.key?(name) }
105
+ next unless key
106
+
107
+ attribute = klass.attributes(instance.lutaml_register)[rule.to]
108
+ next unless attribute
109
+
110
+ native[key] = portable_value(instance, attribute, rule,
111
+ native[key], "#{location}/#{key}")
112
+ end
113
+ native
114
+ end
115
+
116
+ def portable_value(instance, attribute, rule, native, location)
117
+ klass = instance.class
118
+ type = attribute.type(instance.lutaml_register)
119
+ reject_hash_transform!(klass, attribute, rule, type)
120
+ return native if native.nil?
121
+
122
+ value = instance.public_send(rule.to)
123
+
124
+ if attribute.collection?
125
+ return native unless native.is_a?(::Array)
126
+
127
+ items = Array(value)
128
+ unless items.size == native.size
129
+ raise RejectedError.new(:not_serializable, klass.name,
130
+ "#{location}: collection size differs from its native output")
131
+ end
132
+
133
+ return native.each_with_index.map do |item, index|
134
+ portable_item(klass, attribute, items[index], item, "#{location}/#{index}", type)
135
+ end
136
+ end
137
+
138
+ portable_item(klass, attribute, value, native, location, type)
139
+ end
140
+
141
+ def portable_item(klass, attribute, value, native, location, type)
142
+ return native if native.nil?
143
+
144
+ if attribute.union?
145
+ raise RejectedError.new(:unsupported_type, klass.name,
146
+ "#{location}: union attributes have no portable spelling")
147
+ end
148
+
149
+ if value.is_a?(Lutaml::Model::Serialize)
150
+ portable_model(value, native, location)
151
+ else
152
+ scalar(klass, type, native, value, location)
153
+ end
154
+ end
155
+
156
+ def scalar(klass, type, native, value, location)
157
+ return native unless type.is_a?(::Class)
158
+
159
+ if type <= Lutaml::Model::Type::Hash
160
+ hash_member(klass, value, location, 0)
161
+ elsif type <= Lutaml::Model::Type::Integer
162
+ integer(klass, native, location)
163
+ elsif type <= Lutaml::Model::Type::Decimal
164
+ decimal(klass, native, location)
165
+ elsif type <= Lutaml::Model::Type::Float
166
+ float(klass, native, location)
167
+ elsif native.is_a?(::Numeric)
168
+ raise RejectedError.new(:not_serializable, klass.name,
169
+ "#{location}: #{type} writes a JSON number; the portable profile " \
170
+ "carries numbers only as integer, decimal or float strings")
171
+ else
172
+ native
173
+ end
174
+ end
175
+
176
+ # Rebuilds an in-memory `hash` attribute value as portable JSON data.
177
+ def hash_member(klass, value, location, depth)
178
+ if depth > HASH_MAX_DEPTH
179
+ raise RejectedError.new(:not_serializable, klass.name,
180
+ "#{location}: hash nesting is deeper than #{HASH_MAX_DEPTH}")
181
+ end
182
+
183
+ case value
184
+ when nil, true, false then value
185
+ when ::String then hash_string(klass, value, location)
186
+ when ::Symbol then hash_string(klass, value.to_s, location)
187
+ when ::Integer then hash_integer(klass, value, location)
188
+ when ::Float then hash_float(klass, value, location)
189
+ when ::Array
190
+ value.each_with_index.map do |item, index|
191
+ hash_member(klass, item, "#{location}/#{index}", depth + 1)
192
+ end
193
+ when ::Hash then hash_object(klass, value, location, depth)
194
+ else
195
+ raise RejectedError.new(:not_serializable, klass.name,
196
+ "#{location}: #{value.class} in a hash has no portable spelling")
197
+ end
198
+ end
199
+
200
+ def hash_object(klass, value, location, depth)
201
+ value.each_with_object({}) do |(key, item), result|
202
+ unless key.is_a?(::String) || key.is_a?(::Symbol)
203
+ raise RejectedError.new(:not_serializable, klass.name,
204
+ "#{location}: hash key #{RejectedError.show(key)} is not a string")
205
+ end
206
+
207
+ name = hash_string(klass, key.to_s, location)
208
+ if result.key?(name)
209
+ raise RejectedError.new(:not_serializable, klass.name,
210
+ "#{location}: hash key #{RejectedError.show(name)} appears twice")
211
+ end
212
+
213
+ result[name] = hash_member(klass, item, "#{location}/#{name}", depth + 1)
214
+ end
215
+ end
216
+
217
+ def hash_string(klass, value, location)
218
+ return value if value.dup.force_encoding(::Encoding::UTF_8).valid_encoding?
219
+
220
+ raise RejectedError.new(:not_serializable, klass.name,
221
+ "#{location}: a hash string is not valid UTF-8")
222
+ end
223
+
224
+ def hash_integer(klass, value, location)
225
+ return value if value.abs <= MAX_SAFE_INTEGER
226
+
227
+ raise RejectedError.new(:not_serializable, klass.name,
228
+ "#{location}: integer #{value} in a hash is beyond 2**53-1; " \
229
+ "a JSON number cannot hold it exactly")
230
+ end
231
+
232
+ # Spells a float the way ECMAScript Number::toString does, from
233
+ # Ruby's shortest round-trip digits. An integer spelling is only
234
+ # accepted as a safe integer, so an integral float beyond 2**53-1
235
+ # (1e20 is "100000000000000000000" in ECMAScript) and -0.0 (which
236
+ # ECMAScript spells "0") have no exact spelling.
237
+ def hash_float(klass, value, location)
238
+ unless value.finite?
239
+ raise RejectedError.new(:not_serializable, klass.name,
240
+ "#{location}: a non-finite float in a hash has no JSON form")
241
+ end
242
+ if value.zero? && (1.0 / value).negative?
243
+ raise RejectedError.new(:not_serializable, klass.name,
244
+ "#{location}: -0.0 in a hash has no exact JSON spelling")
245
+ end
246
+
247
+ # ECMAScript spells +0.0 as "0", an integer spelling.
248
+ return 0 if value.zero?
249
+
250
+ text = es_number(value)
251
+ return Number.new(text) unless text.match?(/\A-?\d+\z/)
252
+ return text.to_i if text.to_i.abs <= MAX_SAFE_INTEGER
253
+
254
+ raise RejectedError.new(:not_serializable, klass.name,
255
+ "#{location}: float #{text} in a hash is an integer spelling " \
256
+ "beyond 2**53-1; a JSON number cannot hold it exactly")
257
+ end
258
+
259
+ # ECMAScript Number::toString (radix 10) of a finite, nonzero float.
260
+ def es_number(value)
261
+ match = value.abs.to_s.match(/\A(\d+)\.(\d+)(?:e([+-]\d+))?\z/)
262
+ digits = match[1] + match[2]
263
+ point = match[1].length + match[3].to_i
264
+ lead = digits[/\A0*/].length
265
+ digits = digits[lead..]
266
+ point -= lead
267
+ digits = digits.sub(/0+\z/, "")
268
+ (value.negative? ? "-" : "") + es_digits(digits, point)
269
+ end
270
+
271
+ def es_digits(digits, point)
272
+ count = digits.length
273
+ if point.between?(count, 21)
274
+ digits + ("0" * (point - count))
275
+ elsif point.positive? && point <= 21
276
+ "#{digits[0, point]}.#{digits[point..]}"
277
+ elsif point <= 0 && point > -6
278
+ "0.#{'0' * -point}#{digits}"
279
+ else
280
+ exponent = point - 1
281
+ mantissa = count == 1 ? digits : "#{digits[0]}.#{digits[1..]}"
282
+ "#{mantissa}e#{exponent.negative? ? '-' : '+'}#{exponent.abs}"
283
+ end
284
+ end
285
+
286
+ def integer(klass, native, location)
287
+ return native.to_s if native.is_a?(::Integer)
288
+
289
+ unsupported!(klass, "integer", native, location)
290
+ end
291
+
292
+ def decimal(klass, native, location)
293
+ number = case native
294
+ when ::String then BigDecimal(native)
295
+ when ::Integer, ::Float then BigDecimal(native.to_s)
296
+ else unsupported!(klass, "decimal", native, location)
297
+ end
298
+ unless number.finite?
299
+ raise RejectedError.new(:not_serializable, klass.name,
300
+ "#{location}: a non-finite decimal has no portable wire form")
301
+ end
302
+ reject_long_decimal!(klass, number, location)
303
+
304
+ # `to_s("F")` never uses an exponent; it spells -0 as "-0.0".
305
+ number.to_s("F")
306
+ rescue ::ArgumentError
307
+ unsupported!(klass, "decimal", native, location)
308
+ end
309
+
310
+ def float(klass, native, location)
311
+ return unsupported!(klass, "float", native, location) unless native.is_a?(::Numeric)
312
+
313
+ DocumentValidator.float_wire(native)
314
+ rescue ::ArgumentError
315
+ raise RejectedError.new(:not_serializable, klass.name,
316
+ "#{location}: a non-finite float has no portable wire form")
317
+ end
318
+
319
+ # A `hash` attribute is rebuilt from its in-memory value, so an
320
+ # export transform (which only native output sees) would be
321
+ # silently dropped.
322
+ def reject_hash_transform!(klass, attribute, rule, type)
323
+ return unless type.is_a?(::Class) && type <= Lutaml::Model::Type::Hash
324
+ return unless transform?(rule.transform) || transform?(attribute.transform)
325
+
326
+ raise RejectedError.new(:unsupported_mapping, klass.name,
327
+ "#{attribute.name}: a hash attribute with a transform has no portable spelling")
328
+ end
329
+
330
+ def transform?(transform)
331
+ transform.is_a?(::Hash) ? !transform.empty? : !transform.nil?
332
+ end
333
+
334
+ # Counts the digits `to_s("F")` would write without building it:
335
+ # "1e100000000" is 12 bytes in but 100 MB spelled out.
336
+ def reject_long_decimal!(klass, number, location)
337
+ return if number.zero?
338
+
339
+ significant = number.n_significant_digits
340
+ exponent = number.exponent
341
+ digits = if exponent <= 0 then 1 - exponent + significant
342
+ else [exponent, significant].max + 1
343
+ end
344
+ return if digits <= MAX_DECIMAL_DIGITS
345
+
346
+ raise RejectedError.new(:not_serializable, klass.name,
347
+ "#{location}: decimal has about #{digits} digits; the portable " \
348
+ "readers accept at most #{MAX_DECIMAL_DIGITS}")
349
+ end
350
+
351
+ def unsupported!(klass, kind, native, location)
352
+ raise RejectedError.new(:not_serializable, klass.name,
353
+ "#{location}: #{kind} value #{RejectedError.show(native)} " \
354
+ "has no portable spelling")
355
+ end
356
+
357
+ def reject_mapping!(klass, mapping)
358
+ if mapping.respond_to?(:root_name) && mapping.root_name
359
+ reject!(klass, "a root key")
360
+ elsif mapping.respond_to?(:unmapped_attribute) && mapping.unmapped_attribute
361
+ reject!(klass, "map_all")
362
+ elsif mapping.respond_to?(:instance_mapping?) && mapping.instance_mapping?
363
+ reject!(klass, "map_instances/map_key/map_value")
364
+ end
365
+ end
366
+
367
+ def reject_rule!(klass, rule)
368
+ reject!(klass, "custom methods on #{rule.name}") if rule.custom_methods.to_h.any?
369
+ reject!(klass, "a delegate on #{rule.name}") if rule.delegate
370
+ reject!(klass, "child_mappings on #{rule.name}") if present_hash?(rule.child_mappings)
371
+ reject!(klass, "root_mappings on #{rule.name}") if present_hash?(rule.root_mappings)
372
+ end
373
+
374
+ def present_hash?(value)
375
+ value.is_a?(::Hash) && !value.empty?
376
+ end
377
+
378
+ def reject!(klass, what)
379
+ raise RejectedError.new(:unsupported_mapping, klass.name,
380
+ "portable JSON cannot type #{what}")
381
+ end
382
+ end
383
+ end
384
+ end
385
+ end
@@ -3,29 +3,78 @@
3
3
  module Lutaml
4
4
  module Model
5
5
  module Lml
6
- # A named rejection from the exporter: the construct is
7
- # constructor-contract, not schema, and has no declarative
8
- # equivalent in the LML document (lutaml-model#1033 design
9
- # decision #3).
6
+ # A named rejection from the exporter or the document validator:
7
+ # the construct is constructor-contract, not schema, or the
8
+ # document does not meet the agreed contract (lutaml-model#1033).
10
9
  class RejectedError < StandardError
11
- attr_reader :reason, :klass, :detail
10
+ # The full error catalogue of the agreed contract. The exporter
11
+ # raises the export-side codes; DocumentValidator raises the
12
+ # document-side codes; importer/generator/gate cards raise the
13
+ # remainder (missing_type_binding, round_trip_mismatch,
14
+ # checksum_mismatch, capability_missing, nonterminating_rational).
15
+ CODES = %i[
16
+ unsupported_version invalid_document duplicate_id
17
+ dangling_reference unknown_type unsupported_type
18
+ missing_type_binding unsupported_format unsupported_mapping
19
+ non_serializable_default lambda_default custom_initialize
20
+ imperative_element_order invalid_ordered_content reserved_member
21
+ nonterminating_rational unknown_discriminator round_trip_mismatch
22
+ checksum_mismatch capability_missing not_serializable
23
+ ].freeze
12
24
 
13
- # +reason+ is one of:
14
- # :lambda_default — a default given as a Proc
15
- # :custom_initialize — the model overrides `initialize`
16
- # :imperative_element_order — ordered content with no
17
- # declarative sequence
18
- # :unknown_type — a type with no registry name
19
- # :not_serializable — the class does not include
20
- # Serializable
21
- def initialize(reason, klass, detail = nil)
25
+ # Value rendering for detail strings. Hash#inspect changed format
26
+ # in Ruby 3.4, so containers are spelled here and the same
27
+ # rejection reads identically on every Ruby.
28
+ def self.show(value)
29
+ case value
30
+ when ::Hash then "{#{value.map { |k, v| "#{show(k)} => #{show(v)}" }.join(', ')}}"
31
+ when ::Array then "[#{value.map { |item| show(item) }.join(', ')}]"
32
+ else value.inspect
33
+ end
34
+ end
35
+
36
+ attr_reader :reason, :klass, :detail, :location, :model_id,
37
+ :attribute, :format, :rule
38
+
39
+ # True when the rejection came from reading a document in (import,
40
+ # parse, materialise) rather than writing one out.
41
+ def import?
42
+ @import
43
+ end
44
+
45
+ # +reason+ is one of CODES (legacy callers pass the export-side
46
+ # subset). +klass+ and +detail+ keep their legacy meaning; the
47
+ # keywords locate a validator finding: +location+ is a JSON
48
+ # pointer into the document, +model_id+ the "Name@register" ID.
49
+ def initialize(reason, klass = nil, detail = nil, location: nil,
50
+ model_id: nil, attribute: nil, format: nil, rule: nil,
51
+ import: false)
22
52
  @reason = reason
23
53
  @klass = klass
24
54
  @detail = detail
25
- message = "cannot export #{klass} to LML: #{reason}"
55
+ @location = location
56
+ @model_id = model_id
57
+ @attribute = attribute
58
+ @format = format
59
+ @rule = rule
60
+ @import = import
61
+ message = if klass && import then "cannot import #{klass} from LML: #{reason}"
62
+ elsif klass then "cannot export #{klass} to LML: #{reason}"
63
+ else "invalid LML: #{reason}"
64
+ end
26
65
  message += " (#{detail})" if detail
66
+ message += " at #{location}" if location
27
67
  super(message)
28
68
  end
69
+
70
+ # The same rejection worded for the import side.
71
+ def as_import
72
+ return self if import?
73
+
74
+ self.class.new(reason, klass, detail, location: location, model_id: model_id,
75
+ attribute: attribute, format: format, rule: rule,
76
+ import: true)
77
+ end
29
78
  end
30
79
  end
31
80
  end
@@ -9,11 +9,97 @@ module Lutaml
9
9
  # canonical forms must be identical (equal checksums). 1:1-ness
10
10
  # is the design's spine; a drift here means the document lost a
11
11
  # declaration on the way out.
12
+ #
13
+ # `verify_materialization` is the bundle-level gate: it imports a
14
+ # bundle into fresh classes (no source constants), exports those
15
+ # classes again and requires the same declarations and checksum.
12
16
  class RoundTrip
13
17
  def self.verify(document, register: nil)
14
18
  new(document, register: register).verify
15
19
  end
16
20
 
21
+ # @param source [Bundle, Hash, String] the bundle to reconstruct
22
+ # @param namespace [Module, nil] named holder for the generated
23
+ # classes; nil uses a transient one removed afterwards
24
+ # @param type_bindings [Hash{String=>Class}] trusted value types
25
+ # @return [Bundle] the re-exported bundle, equal to the input
26
+ # @raise [RejectedError] :round_trip_mismatch when it differs
27
+ def self.verify_materialization(source, namespace: nil, type_bindings: {})
28
+ expected = Importer.bundle(source)
29
+ return reconstruct(expected, namespace, type_bindings) if namespace
30
+
31
+ holder_name = "LmlVerify#{object_id.abs}#{Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond)}"
32
+ holder = Module.new
33
+ Object.const_set(holder_name, holder)
34
+ begin
35
+ reconstruct(expected, holder, type_bindings)
36
+ ensure
37
+ Object.send(:remove_const, holder_name)
38
+ end
39
+ end
40
+
41
+ def self.reconstruct(expected, namespace, type_bindings)
42
+ classes = Importer.import(expected, namespace: namespace, type_bindings: type_bindings)
43
+ actual = reexport_in_known_registers(expected, classes)
44
+ return actual if actual == expected
45
+
46
+ raise RejectedError.new(:round_trip_mismatch, expected.roots.join(", "),
47
+ "the bundle does not re-derive from its materialization " \
48
+ "(#{expected.checksum.slice(0, 20)} vs #{actual.checksum.slice(0, 20)})")
49
+ end
50
+
51
+ # Mappings that import other models resolve their register by id
52
+ # and fail with a NoMethodError on a register this process does
53
+ # not know; bundles whose models need no such lookup still verify.
54
+ def self.reexport_in_known_registers(expected, classes)
55
+ reexport(expected, classes)
56
+ rescue NoMethodError => e
57
+ unknown = unregistered_ids(expected)
58
+ raise unless register_lookup_failure?(e) && unknown.any?
59
+
60
+ raise RejectedError.new(:invalid_document, unknown.first,
61
+ "register #{RejectedError.show(unknown.first.rpartition('@').last)} is not registered")
62
+ end
63
+
64
+ # The lookup dereferences the missing register (`nil.id`); any
65
+ # other NoMethodError is a genuine bug and must surface as itself.
66
+ def self.register_lookup_failure?(error)
67
+ error.receiver.nil? && error.name == :id
68
+ end
69
+
70
+ def self.unregistered_ids(expected)
71
+ expected.models.keys.reject do |id|
72
+ register = id.rpartition("@").last
73
+ register == "default" || Lutaml::Model::GlobalRegister.lookup(register)
74
+ end
75
+ end
76
+
77
+ # Class names differ per materialization (the namespace is a
78
+ # prefix), so the re-export runs in the bundle's own identifier
79
+ # space: the exporter names each generated class by the id it
80
+ # was materialized from.
81
+ def self.reexport(expected, classes)
82
+ models = classes.each_with_object({}) do |(id, klass), map|
83
+ model = id.rpartition("@").first
84
+ map[klass] = model
85
+ map[klass.name] = model
86
+ end
87
+ names = ->(klass) { models.fetch(klass) { klass.is_a?(::String) ? klass : klass.name } }
88
+ roots = expected.roots.map { |id| [classes.fetch(id), id.rpartition("@").last] }
89
+ generated = GraphExporter.export(
90
+ roots,
91
+ projector: Exporter.graph_projector(names: names),
92
+ resolver: ->(model, register) { classes["#{model}@#{register}"] },
93
+ names: names,
94
+ )
95
+ Bundle.new(**generated.to_h.transform_keys(&:to_sym)
96
+ .slice(:roots, :models, :value_types, :capabilities))
97
+ end
98
+
99
+ private_class_method :reconstruct, :reexport,
100
+ :reexport_in_known_registers, :register_lookup_failure?,
101
+ :unregistered_ids
102
+
17
103
  def initialize(document, register: nil)
18
104
  @document = document
19
105
  @register = register
@@ -0,0 +1,84 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lutaml
4
+ module Model
5
+ module Lml
6
+ # Caller-owned declarations for trusted named scalar classes. This is
7
+ # data, not an inference about Ruby callbacks or an executable binding.
8
+ class ValueDeclarations
9
+ VERSION = 1
10
+ attr_reader :version
11
+
12
+ def initialize(entries, version: VERSION)
13
+ unless version.is_a?(::Integer) && version == VERSION
14
+ raise RejectedError.new(:unsupported_version, nil, "unsupported named-value declaration registry version")
15
+ end
16
+ unless entries.is_a?(::Hash)
17
+ raise RejectedError.new(:invalid_document, nil, "named-value declarations require a class-keyed Hash")
18
+ end
19
+
20
+ @version = version
21
+ @entries = entries.each_with_object({}) do |(klass, definition), out|
22
+ unless klass.is_a?(::Class) && klass < Lutaml::Model::Type::Value && klass.name && !klass.name.empty?
23
+ raise RejectedError.new(:unsupported_type, nil, "named-value declaration keys must be named scalar classes")
24
+ end
25
+
26
+ spec = data_copy(definition)
27
+ tree = DocumentValidator.validate!({
28
+ "lml_bundle" => 1, "roots" => [], "models" => {},
29
+ "value_types" => { "#{klass.name}@default" => spec }, "capabilities" => []
30
+ }, kind: :bundle)
31
+ out[klass] = freeze_tree(tree.fetch("value_types").fetch("#{klass.name}@default"))
32
+ end.freeze
33
+ freeze
34
+ end
35
+
36
+ # Class identity is exact: names, aliases, subclasses and strings never
37
+ # gain a declaration merely because their spelling resembles a key.
38
+ def fetch(klass)
39
+ @entries[klass]
40
+ end
41
+
42
+ def to_h
43
+ { "version" => version,
44
+ "types" => @entries.sort_by { |klass, _| klass.name }.to_h { |klass, spec| [klass.name, spec] } }
45
+ end
46
+
47
+ private
48
+
49
+ def data_copy(value, depth = 0)
50
+ if depth >= DocumentValidator::MAX_DEPTH
51
+ raise RejectedError.new(:invalid_document, nil, "named-value declaration nesting exceeds limit")
52
+ end
53
+
54
+ case value
55
+ when ::Hash
56
+ value.to_h do |key, item|
57
+ unless key.is_a?(::String)
58
+ raise RejectedError.new(:invalid_document, nil, "named-value declaration keys must be strings")
59
+ end
60
+
61
+ [key.dup, data_copy(item, depth + 1)]
62
+ end
63
+ when ::Array then value.map { |item| data_copy(item, depth + 1) }
64
+ when ::String then value.dup
65
+ when ::Integer, ::Float, true, false, nil then value
66
+ else
67
+ raise RejectedError.new(:invalid_document, nil, "named-value declarations contain data only")
68
+ end
69
+ end
70
+
71
+ def freeze_tree(value)
72
+ case value
73
+ when ::Hash then value.each do |key, item|
74
+ key.freeze
75
+ freeze_tree(item)
76
+ end
77
+ when ::Array then value.each { |item| freeze_tree(item) }
78
+ end
79
+ value.freeze
80
+ end
81
+ end
82
+ end
83
+ end
84
+ end