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,401 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "lutaml/model"
4
+ require_relative "rejected_error"
5
+ require_relative "ordered_content"
6
+
7
+ module Lutaml
8
+ module Model
9
+ module Lml
10
+ # Rebuilds the XML / JSON / YAML mapping policies of a materialized
11
+ # Ruby declaration graph from a validated neutral LML bundle
12
+ # (lutaml-model#1033, card 03b).
13
+ #
14
+ # classes = Materialization.build(bundle, ...) # attributes (03a)
15
+ # MappingCompiler.apply(classes, bundle) # mappings (here)
16
+ #
17
+ # Two phases keep a refusal from leaving half-declared classes:
18
+ # `plan` translates every model's mapping documents into DSL calls
19
+ # (raising a named RejectedError for anything with no declarative
20
+ # Ruby form) and only then `declare` runs the DSL. Nothing is
21
+ # evaluated from the document: rule keys are matched against a
22
+ # closed list, policy names against closed tables, and namespaces
23
+ # become fresh Lutaml::Xml::Namespace classes built from the
24
+ # document's uri/prefix strings.
25
+ #
26
+ # Order data is not stored in the mapping: a model that declares an
27
+ # +ordered_content+ descriptor gets an +ordered+ XML mapping (unless
28
+ # the document already says mixed), after which OrderedContent
29
+ # captures and applies the per-instance tokens.
30
+ class MappingCompiler
31
+ XML_FORMAT_KEYS = %w[root namespace rules ordered mixed_content
32
+ sequence].freeze
33
+ KEY_VALUE_FORMAT_KEYS = %w[namespace rules].freeze
34
+ XML_RULE_KEYS = %w[kind name to namespace cdata render
35
+ discriminator].freeze
36
+ KEY_VALUE_RULE_KEYS = %w[key to render child_mappings
37
+ discriminator].freeze
38
+ XML_KINDS = %w[attribute element content any_attribute].freeze
39
+ RENDER_KEYS = %w[nil empty default].freeze
40
+ # Render policy name -> map_* option, per slot. The slot's
41
+ # "natural" policy is the plain `true`; Ruby reads the rest as
42
+ # symbols (see MappingRule#render_as).
43
+ RENDER_NIL = { "omit" => false, "as_nil" => true,
44
+ "as_empty" => :as_empty, "as_blank" => :as_blank }.freeze
45
+ RENDER_EMPTY = { "omit" => false, "as_empty" => true,
46
+ "as_nil" => :as_nil, "as_blank" => :as_blank }.freeze
47
+ FORMATS = %w[xml json yaml].freeze
48
+
49
+ Plan = Struct.new(:id, :klass, :format, :steps)
50
+
51
+ # @param model_map [Hash{String=>Class}] model id => class, as
52
+ # returned by Materialization.build
53
+ # @param bundle [Hash, #to_h] a validated bundle (string keys)
54
+ # @return [Hash{String=>Class}] model_map, with mappings declared
55
+ def self.apply(model_map, bundle)
56
+ new(model_map, bundle).apply
57
+ end
58
+
59
+ def initialize(model_map, bundle)
60
+ @model_map = model_map
61
+ @bundle = bundle.respond_to?(:to_h) ? bundle.to_h : bundle
62
+ @namespaces = {}
63
+ end
64
+
65
+ def apply
66
+ plans = models.flat_map { |id, document| plan_model(id, document) }
67
+ plans.each { |plan| declare(plan) }
68
+ @model_map
69
+ end
70
+
71
+ private
72
+
73
+ def models
74
+ (@bundle["models"] || {}).sort_by { |id, _| id }
75
+ end
76
+
77
+ def fail!(reason, detail, id, **context)
78
+ raise RejectedError.new(reason, nil, detail, model_id: id, **context)
79
+ end
80
+
81
+ # -- planning ---------------------------------------------------
82
+
83
+ def plan_model(id, document)
84
+ klass = @model_map.fetch(id) do
85
+ fail!(:dangling_reference, "no class for model #{id} in the model map", id)
86
+ end
87
+ reject_reserved!(id, document)
88
+ check_ordered_descriptor(id, document)
89
+ (document["mappings"] || {}).sort_by { |format, _| format }.map do |format, mapping|
90
+ plan_format(id, document, klass, format, mapping)
91
+ end
92
+ end
93
+
94
+ def reject_reserved!(id, document)
95
+ reserved = document["attributes"].to_a.any? { |a| a["name"] == OrderedContent::MEMBER }
96
+ return unless reserved
97
+
98
+ fail!(:reserved_member, "#{OrderedContent::MEMBER} is reserved for ordered content", id)
99
+ end
100
+
101
+ def check_ordered_descriptor(id, document)
102
+ return unless document.key?("ordered_content")
103
+
104
+ descriptor = document["ordered_content"]
105
+ return if descriptor.is_a?(::Hash) && descriptor["member"] == OrderedContent::MEMBER &&
106
+ descriptor["version"] == OrderedContent::VERSION
107
+
108
+ fail!(:invalid_ordered_content,
109
+ "expected {member: #{OrderedContent::MEMBER}, version: #{OrderedContent::VERSION}}", id)
110
+ end
111
+
112
+ def plan_format(id, document, klass, format, mapping)
113
+ unless FORMATS.include?(format)
114
+ fail!(:unsupported_format, "format #{format}", id, format: format)
115
+ end
116
+ if klass.mappings.key?(format.to_sym)
117
+ fail!(:unsupported_mapping, "#{format} mapping already declared on the class", id,
118
+ format: format)
119
+ end
120
+
121
+ steps = if format == "xml"
122
+ xml_steps(id, document, mapping)
123
+ else
124
+ key_value_steps(id, document, mapping, format)
125
+ end
126
+ Plan.new(id, klass, format, steps)
127
+ end
128
+
129
+ def only_keys!(id, node, allowed, format, where)
130
+ extra = node.keys - allowed
131
+ return if extra.empty?
132
+
133
+ fail!(:unsupported_mapping, "#{where}: no declarative form for #{extra.sort.join(', ')}", id,
134
+ format: format)
135
+ end
136
+
137
+ def attribute_names(document)
138
+ document["attributes"].to_a.map { |a| a["name"] }
139
+ end
140
+
141
+ # -- XML ----------------------------------------------------------
142
+
143
+ def xml_steps(id, document, mapping)
144
+ only_keys!(id, mapping, XML_FORMAT_KEYS, "xml", "mapping")
145
+ reject_sequence!(id, mapping)
146
+ steps = []
147
+ root = mapping["root"]
148
+ unless root.nil? || (root.is_a?(::Hash) && (root["element"].nil? || root["element"].is_a?(::String)))
149
+ fail!(:invalid_document, "xml root must be an object with a string element", id, format: "xml")
150
+ end
151
+ steps << [:element, [root["element"]], {}] if root && root["element"]
152
+ steps.concat(order_steps(document, mapping))
153
+ steps.concat(namespace_steps(id, mapping["namespace"], "xml"))
154
+ known = attribute_names(document)
155
+ mapping.fetch("rules", []).each_with_index do |rule, index|
156
+ steps << xml_rule_step(id, rule, index, known, parent_namespace: mapping["namespace"])
157
+ end
158
+ steps
159
+ end
160
+
161
+ def reject_sequence!(id, mapping)
162
+ return if mapping["sequence"].nil? || mapping["sequence"].empty?
163
+
164
+ fail!(:unsupported_mapping, "sequence/choice compositors have no Ruby reconstruction yet", id,
165
+ format: "xml")
166
+ end
167
+
168
+ # mixed (root.mixed or mixed_content) implies ordered; a model
169
+ # that declares per-instance order data needs an ordered mapping.
170
+ def order_steps(document, mapping)
171
+ mixed = mapping["mixed_content"] || mapping["root"]&.fetch("mixed", nil)
172
+ return [[:mixed_content, [], {}]] if mixed
173
+ return [[:ordered, [], {}]] if mapping["ordered"] || document.key?("ordered_content")
174
+
175
+ []
176
+ end
177
+
178
+ def xml_rule_step(id, rule, index, known, parent_namespace: nil)
179
+ where = "rules/#{index}"
180
+ only_keys!(id, rule, XML_RULE_KEYS, "xml", where)
181
+ kind = rule["kind"]
182
+ unless XML_KINDS.include?(kind)
183
+ fail!(:unsupported_mapping, "#{where}: rule kind #{RejectedError.show(kind)}", id, format: "xml")
184
+ end
185
+ return any_attribute_step(id, rule, known, where) if kind == "any_attribute"
186
+
187
+ to = target(id, rule, known, where, "xml", required: kind != "content")
188
+ options = { to: to }.compact
189
+ options.merge!(render_options(id, rule["render"], where, "xml"))
190
+ return content_step(id, rule, options, where) if kind == "content"
191
+
192
+ rule_step(id, rule, kind, options, where, parent_namespace: parent_namespace)
193
+ end
194
+
195
+ def any_attribute_step(id, rule, known, where)
196
+ only_keys!(id, rule, %w[kind to], "xml", where)
197
+ [:map_all_attributes, [], { to: target(id, rule, known, where, "xml") }]
198
+ end
199
+
200
+ def content_step(id, rule, options, where)
201
+ reject_content_extras!(id, rule, where)
202
+ options[:cdata] = true if rule["cdata"]
203
+ [:map_content, [], options]
204
+ end
205
+
206
+ def reject_content_extras!(id, rule, where)
207
+ extras = %w[name discriminator namespace].select { |key| rule.key?(key) }
208
+ return if extras.empty?
209
+
210
+ fail!(:unsupported_mapping, "#{where}: content rule cannot carry #{extras.join(', ')}", id,
211
+ format: "xml")
212
+ end
213
+
214
+ def rule_step(id, rule, kind, options, where, parent_namespace: nil)
215
+ names = names_of(id, rule["name"], where, "xml")
216
+ if kind == "attribute"
217
+ fail!(:unsupported_mapping, "#{where}: cdata on an attribute", id, format: "xml") if rule["cdata"]
218
+ fail!(:unsupported_mapping, "#{where}: discriminator on an attribute", id, format: "xml") if rule["discriminator"]
219
+ else
220
+ options[:cdata] = true if rule["cdata"]
221
+ poly = polymorphic(id, rule["discriminator"], where, "xml")
222
+ options[:polymorphic] = poly if poly
223
+ end
224
+ namespace_option(id, rule["namespace"], where, options, attribute: kind == "attribute", parent_namespace: parent_namespace)
225
+ [kind == "attribute" ? :map_attribute : :map_element, [names], options]
226
+ end
227
+
228
+ # Attributes in their model namespace use explicit qualified form.
229
+ # The Ruby DSL cannot express an unrelated rule namespace.
230
+ def namespace_option(id, node, where, options, attribute: false, parent_namespace: nil)
231
+ return if node.nil?
232
+
233
+ case node["mode"]
234
+ when "inherit" then nil
235
+ when "unqualified" then options[:namespace] = nil
236
+ when "uri"
237
+ unless attribute && parent_namespace&.fetch("mode", nil) == "uri" &&
238
+ node["uri"] == parent_namespace["uri"]
239
+ fail!(:unsupported_mapping,
240
+ "#{where}: rule-level URI requires an attribute in the declared model namespace",
241
+ id, format: "xml")
242
+ end
243
+ options[:form] = :qualified
244
+ else
245
+ fail!(:unsupported_mapping,
246
+ "#{where}: rule-level namespace #{node['mode']} is not expressible in the Ruby mapping DSL",
247
+ id, format: "xml")
248
+ end
249
+ end
250
+
251
+ def names_of(id, names, where, format)
252
+ unless names.is_a?(::Array) && !names.empty? && names.all?(::String)
253
+ fail!(:invalid_document, "#{where}: name/key must be a non-empty string array", id, format: format)
254
+ end
255
+ names.length == 1 ? names.first : names
256
+ end
257
+
258
+ def target(id, rule, known, where, format, required: true)
259
+ to = rule["to"]
260
+ if to.nil?
261
+ return nil unless required
262
+
263
+ fail!(:unsupported_mapping, "#{where}: rule has no `to` (custom with: methods are executable)", id,
264
+ format: format)
265
+ end
266
+ unless known.include?(to)
267
+ fail!(:dangling_reference, "#{where}: `to` #{RejectedError.show(to)} is not an attribute of the model", id,
268
+ format: format)
269
+ end
270
+ to.to_sym
271
+ end
272
+
273
+ # -- key-value ----------------------------------------------------
274
+
275
+ def key_value_steps(id, document, mapping, format)
276
+ only_keys!(id, mapping, KEY_VALUE_FORMAT_KEYS, format, "mapping")
277
+ namespace_steps(id, mapping["namespace"], format)
278
+ known = attribute_names(document)
279
+ mapping.fetch("rules", []).each_with_index.map do |rule, index|
280
+ key_value_rule_step(id, rule, index, known, format)
281
+ end
282
+ end
283
+
284
+ def key_value_rule_step(id, rule, index, known, format)
285
+ where = "rules/#{index}"
286
+ only_keys!(id, rule, KEY_VALUE_RULE_KEYS, format, where)
287
+ options = { to: target(id, rule, known, where, format) }
288
+ options.merge!(render_options(id, rule["render"], where, format))
289
+ poly = polymorphic(id, rule["discriminator"], where, format)
290
+ options[:polymorphic] = poly if poly
291
+ options[:child_mappings] = symbolize(rule["child_mappings"]) if rule["child_mappings"]
292
+ [:map, [names_of(id, rule["key"], where, format)], options]
293
+ end
294
+
295
+ def symbolize(node)
296
+ case node
297
+ when ::Hash then node.to_h { |key, value| [key.to_sym, symbolize(value)] }
298
+ when ::Array then node.map { |item| symbolize(item) }
299
+ when ::String then node.to_sym
300
+ else node
301
+ end
302
+ end
303
+
304
+ # -- shared pieces ------------------------------------------------
305
+
306
+ def namespace_steps(id, node, format)
307
+ return [] if node.nil? || node["mode"] == "inherit"
308
+ return [[:namespace, [:blank], {}]] if node["mode"] == "unqualified" && format == "xml"
309
+
310
+ if node["mode"] == "uri" && format == "xml"
311
+ return [[:namespace, [namespace_class(node["uri"], node["prefix"])], {}]]
312
+ end
313
+
314
+ fail!(:unsupported_mapping, "namespace #{node['mode']} on a #{format} mapping", id, format: format)
315
+ end
316
+
317
+ def namespace_class(uri, prefix)
318
+ unless prefix.nil? || prefix.is_a?(::String)
319
+ fail!(:invalid_document, "namespace prefix must be a string", nil, format: "xml")
320
+ end
321
+ @namespaces[[uri, prefix]] ||= Class.new(Lutaml::Xml::Namespace) do
322
+ uri(uri)
323
+ prefix_default(prefix) if prefix
324
+ end
325
+ end
326
+
327
+ # render {nil, empty, default}: absent slots keep the documented
328
+ # Ruby default (never guessed truthiness).
329
+ def render_options(id, render, where, format)
330
+ return {} if render.nil?
331
+
332
+ extra = render.keys - RENDER_KEYS
333
+ unless extra.empty?
334
+ fail!(:unsupported_mapping, "#{where}: render #{extra.sort.join(', ')}", id, format: format)
335
+ end
336
+ options = {}
337
+ options[:render_nil] = render_policy(id, RENDER_NIL, render["nil"], where, format) if render.key?("nil")
338
+ options[:render_empty] = render_policy(id, RENDER_EMPTY, render["empty"], where, format) if render.key?("empty")
339
+ if render.key?("default")
340
+ unless [true, false].include?(render["default"])
341
+ fail!(:unsupported_mapping, "#{where}: render default must be boolean", id, format: format)
342
+ end
343
+ options[:render_default] = render["default"]
344
+ end
345
+ options
346
+ end
347
+
348
+ def render_policy(id, table, name, where, format)
349
+ return table.fetch(name) if table.key?(name)
350
+
351
+ fail!(:unsupported_mapping, "#{where}: render policy #{RejectedError.show(name)}", id, format: format)
352
+ end
353
+
354
+ # Ruby resolves class_map values with Object.const_get(string),
355
+ # so a polymorphic target must be an installed, reachable
356
+ # constant; an anonymous or detached class has no such name.
357
+ def polymorphic(id, discriminator, where, format)
358
+ return nil if discriminator.nil?
359
+
360
+ cases = discriminator["cases"].to_h do |wire, target_id|
361
+ [wire, constant_name(id, target_id, where, format)]
362
+ end
363
+ # String key: Ruby looks the wire value up with `value[attribute]`
364
+ # on parsed (string-keyed) data, so a symbol never matches.
365
+ { attribute: discriminator["attribute"], class_map: cases }
366
+ end
367
+
368
+ def constant_name(id, target_id, where, format)
369
+ klass = @model_map[target_id]
370
+ if klass.nil?
371
+ fail!(:unknown_discriminator, "#{where}: case target #{target_id} is not in the model map", id,
372
+ format: format)
373
+ end
374
+ name = klass.name
375
+ return name if installed_constant?(name, klass)
376
+
377
+ fail!(:unsupported_mapping,
378
+ "#{where}: polymorphic target #{target_id} needs an installed constant " \
379
+ "(Ruby resolves class_map by Object.const_get)", id, format: format)
380
+ end
381
+
382
+ def installed_constant?(name, klass)
383
+ !name.nil? && Object.const_get(name).equal?(klass)
384
+ rescue NameError
385
+ false
386
+ end
387
+
388
+ # -- declaration --------------------------------------------------
389
+
390
+ def declare(plan)
391
+ steps = plan.steps
392
+ plan.klass.public_send(plan.format) do
393
+ steps.each { |name, args, options| public_send(name, *args, **options) }
394
+ end
395
+ rescue Lutaml::Model::IncorrectMappingArgumentsError, Lutaml::Xml::Error::InvalidNamespaceError => e
396
+ raise RejectedError.new(:unsupported_mapping, nil, e.message, model_id: plan.id, format: plan.format)
397
+ end
398
+ end
399
+ end
400
+ end
401
+ end
@@ -0,0 +1,257 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "lutaml/model"
4
+ require_relative "rejected_error"
5
+
6
+ module Lutaml
7
+ module Model
8
+ module Lml
9
+ # Allocates and links a fresh Ruby declaration graph from a
10
+ # validated neutral LML bundle (lutaml-model#1033, card 03a).
11
+ #
12
+ # Two passes make nested and cyclic models work without the source
13
+ # constants: every model id first gets an empty Serializable class
14
+ # (allocate), then attributes are declared against those class
15
+ # objects (link). Types resolve only through the bundle itself, the
16
+ # builtin registry, or the trusted +type_bindings+ map supplied by
17
+ # the caller; nothing is evaluated or required from the document and
18
+ # no global constant lookup is used.
19
+ #
20
+ # Mappings (xml/json/yaml) belong to MappingCompiler.apply.
21
+ class Materialization
22
+ ATTRIBUTE_KEYS = %w[name type required collection default
23
+ initialize_empty values].freeze
24
+ CONST_PATH = /\A[A-Z]\w*(::[A-Z]\w*)*\z/
25
+
26
+ # @param bundle [Hash] a validated bundle (string keys)
27
+ # @param namespace [Module, nil] holder for the generated
28
+ # constants; nil leaves the classes anonymous
29
+ # @param type_bindings [Hash{String=>Class}] trusted classes by
30
+ # value-type id (and custom collection class name)
31
+ # @return [Hash{String=>Class}] model id => generated class
32
+ def self.build(bundle, namespace: nil, type_bindings: {})
33
+ new(bundle, namespace: namespace, type_bindings: type_bindings).build
34
+ end
35
+
36
+ def initialize(bundle, namespace:, type_bindings:)
37
+ @bundle = bundle
38
+ @namespace = namespace
39
+ @bindings = type_bindings || {}
40
+ end
41
+
42
+ def build
43
+ models = @bundle["models"] || {}
44
+ ids = models.keys.sort
45
+ classes = ids.to_h { |id| [id, allocate(id, models[id])] }
46
+ ids.each { |id| link(id, models[id], classes) }
47
+ classes.freeze
48
+ Materialization.install(classes, models, @namespace) if @namespace
49
+ classes
50
+ end
51
+
52
+ # Installs the already built and linked +classes+ under
53
+ # +namespace+, all or nothing, and returns an Installation whose
54
+ # #rollback removes exactly what was installed.
55
+ #
56
+ # Only the first segment of each model name touches the target
57
+ # namespace, and it must be free: an existing constant (module,
58
+ # class or any other value) is a duplicate_id, never descended
59
+ # into. Every deeper segment lands in a holder this install
60
+ # created, parents before children whatever the id sort order
61
+ # ("A::B@default" sorts before "A@default"). All checks run
62
+ # before the first const_set.
63
+ def self.install(classes, models, namespace)
64
+ names = classes.keys.to_h { |id| [id, models.fetch(id)["model"].to_s] }
65
+ check_free(names, namespace)
66
+ installation = Installation.new(namespace)
67
+ holders = {}
68
+ names.sort_by { |id, name| [name.count(":"), id] }.each do |id, name|
69
+ place(name, classes.fetch(id), holders, installation)
70
+ end
71
+ installation
72
+ rescue StandardError
73
+ installation&.rollback
74
+ raise
75
+ end
76
+
77
+ def self.check_free(names, namespace)
78
+ seen = {}
79
+ names.each do |id, name|
80
+ if seen.key?(name)
81
+ raise RejectedError.new(:duplicate_id, id, "#{name} is declared by more than one model")
82
+ end
83
+
84
+ seen[name] = true
85
+ top = name.split("::").first
86
+ if namespace.const_defined?(top, false)
87
+ raise RejectedError.new(:duplicate_id, id, "#{top} already exists in the target namespace")
88
+ end
89
+ end
90
+ end
91
+ private_class_method :check_free
92
+
93
+ def self.place(name, klass, holders, installation)
94
+ *parents, leaf = name.split("::")
95
+ holder = nil
96
+ parents.each_with_index do |part, depth|
97
+ path = parents.first(depth + 1).join("::")
98
+ holders[path] ||= installation.define(holder, part, Module.new)
99
+ holder = holders[path]
100
+ end
101
+ installation.define(holder, leaf, klass)
102
+ holders[name] = klass
103
+ end
104
+ private_class_method :place
105
+
106
+ # The constants one install put into the target namespace.
107
+ class Installation
108
+ def initialize(namespace)
109
+ @namespace = namespace
110
+ @names = []
111
+ end
112
+
113
+ # const_set +object+ as +name+ under +holder+ (the namespace
114
+ # itself for a top-level name).
115
+ def define(holder, name, object)
116
+ (holder || @namespace).const_set(name, object)
117
+ @names << name unless holder
118
+ object
119
+ end
120
+
121
+ def rollback
122
+ @names.each do |name|
123
+ @namespace.send(:remove_const, name) if @namespace.const_defined?(name, false)
124
+ end
125
+ @names = []
126
+ end
127
+ end
128
+
129
+ private
130
+
131
+ def allocate(id, document)
132
+ klass = Class.new(Lutaml::Model::Serializable)
133
+ name = document["model"].to_s
134
+ unless name.match?(CONST_PATH)
135
+ raise RejectedError.new(:invalid_document, id, "model name #{RejectedError.show(name)} is not a Ruby constant path")
136
+ end
137
+
138
+ klass
139
+ end
140
+
141
+ def link(id, document, classes)
142
+ document["attributes"].to_a.each do |attr|
143
+ declare(id, classes[id], attr, classes)
144
+ end
145
+ groups = document.dig("choices", "groups")
146
+ return unless groups
147
+
148
+ classes[id].choice_attributes = groups.map { |group| build_choice(classes[id], group) }
149
+ end
150
+
151
+ def build_choice(klass, group)
152
+ maximum = group["max"].nil? ? Float::INFINITY : group["max"]
153
+ choice = Lutaml::Model::Choice.new(klass, group["min"], maximum,
154
+ format: group["format"]&.to_sym)
155
+ group["members"].each do |member|
156
+ if member.key?("choice")
157
+ choice.attributes << build_choice(klass, member["choice"])
158
+ else
159
+ attribute = klass.attributes.fetch(member["attribute"].to_sym)
160
+ attribute.options[:choice] = choice
161
+ choice.attributes << attribute
162
+ end
163
+ end
164
+ choice
165
+ end
166
+
167
+ def declare(id, klass, attr, classes)
168
+ extra = attr.keys - ATTRIBUTE_KEYS
169
+ unless extra.empty?
170
+ raise RejectedError.new(:invalid_document, id,
171
+ "attribute #{attr['name']}: unhandled key(s) #{extra.sort.join(', ')}")
172
+ end
173
+
174
+ type = resolve_type(id, attr, classes)
175
+ options = attribute_options(id, attr)
176
+ klass.attribute(attr["name"].to_sym, type, **options)
177
+ end
178
+
179
+ def attribute_options(id, attr)
180
+ options = {}
181
+ options[:required] = true if attr["required"]
182
+ options[:initialize_empty] = true if attr["initialize_empty"]
183
+ options[:values] = enum_values(attr) if attr["values"]
184
+ options[:collection] = collection_option(id, attr["collection"]) if attr["collection"]
185
+ options[:default] = default_value(attr) if attr.dig("default", "present")
186
+ options
187
+ end
188
+
189
+ def default_value(attr)
190
+ value = attr["default"]["value"]
191
+ float_attribute?(attr) ? Float(value) : value
192
+ end
193
+
194
+ # Float enum members travel as canonical strings; the attribute
195
+ # holds Floats, as the exporter that wrote them did.
196
+ def enum_values(attr)
197
+ values = attr["values"].to_a
198
+ return values unless float_attribute?(attr)
199
+
200
+ values.map { |value| value && Float(value) }
201
+ end
202
+
203
+ def float_attribute?(attr)
204
+ attr.dig("type", "kind") == "builtin" && attr.dig("type", "name") == "float"
205
+ end
206
+
207
+ def collection_option(id, spec)
208
+ return true if spec == true
209
+
210
+ min = spec["min"] || 0
211
+ max = spec["max"]
212
+ return min..(max || Float::INFINITY) unless spec["class"]
213
+
214
+ unless min.zero? && max.nil?
215
+ raise RejectedError.new(:unsupported_mapping, id,
216
+ "a custom collection class cannot carry a min/max range")
217
+ end
218
+
219
+ binding_for(id, spec["class"])
220
+ end
221
+
222
+ def resolve_type(id, attr, classes)
223
+ type = attr["type"]
224
+ case type["kind"]
225
+ when "builtin" then builtin(id, type["name"])
226
+ when "model"
227
+ classes.fetch(type["id"]) do
228
+ raise RejectedError.new(:dangling_reference, id, "attribute #{attr['name']} -> #{type['id']}")
229
+ end
230
+ when "value" then binding_for(id, type["id"])
231
+ else raise RejectedError.new(:unknown_type, id, "attribute #{attr['name']}: kind #{RejectedError.show(type['kind'])}")
232
+ end
233
+ end
234
+
235
+ def builtin(id, name)
236
+ return name.to_sym if builtin_names.include?(name.to_s)
237
+
238
+ raise RejectedError.new(:unknown_type, id, "unknown builtin #{RejectedError.show(name)}")
239
+ end
240
+
241
+ def builtin_names
242
+ @builtin_names ||= begin
243
+ registry = TypeRegistry.new
244
+ Type.register_builtin_types_in(registry)
245
+ registry.types.keys.map(&:to_s)
246
+ end
247
+ end
248
+
249
+ def binding_for(id, key)
250
+ @bindings.fetch(key) do
251
+ raise RejectedError.new(:missing_type_binding, id, "no trusted binding for #{key}")
252
+ end
253
+ end
254
+ end
255
+ end
256
+ end
257
+ end