lutaml-model 0.8.203 → 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 (112) hide show
  1. checksums.yaml +4 -4
  2. data/.gitattributes +5 -0
  3. data/.github/workflows/lml-conformance.yml +71 -0
  4. data/.gitignore +7 -0
  5. data/README.adoc +1 -0
  6. data/docs/_guides/lml-cross-language.adoc +128 -0
  7. data/docs/_references/lml-conformance.adoc +78 -0
  8. data/docs/_references/lml-contract.adoc +290 -0
  9. data/lib/lutaml/model/lml/artifact_verifier.rb +205 -0
  10. data/lib/lutaml/model/lml/bundle.rb +171 -0
  11. data/lib/lutaml/model/lml/document.rb +46 -10
  12. data/lib/lutaml/model/lml/document_validator.rb +840 -0
  13. data/lib/lutaml/model/lml/exporter/v1_projector.rb +102 -0
  14. data/lib/lutaml/model/lml/exporter/v2_projector.rb +401 -0
  15. data/lib/lutaml/model/lml/exporter.rb +223 -87
  16. data/lib/lutaml/model/lml/graph_exporter.rb +248 -0
  17. data/lib/lutaml/model/lml/importer.rb +180 -0
  18. data/lib/lutaml/model/lml/mapping_compiler.rb +401 -0
  19. data/lib/lutaml/model/lml/materialization.rb +257 -0
  20. data/lib/lutaml/model/lml/ordered_content.rb +577 -0
  21. data/lib/lutaml/model/lml/portable_json.rb +385 -0
  22. data/lib/lutaml/model/lml/rejected_error.rb +64 -15
  23. data/lib/lutaml/model/lml/round_trip.rb +86 -0
  24. data/lib/lutaml/model/lml/value_declarations.rb +84 -0
  25. data/lib/lutaml/model/lml.rb +61 -0
  26. data/lib/lutaml/model/schema/definitions/attribute.rb +4 -2
  27. data/lib/lutaml/model/schema/registry_generator.rb +1 -1
  28. data/lib/lutaml/model/schema/renderers/member_decls.rb +1 -0
  29. data/lib/lutaml/model/schema/xml_compiler/spec_builder/members.rb +10 -0
  30. data/lib/lutaml/model/sequence.rb +7 -0
  31. data/lib/lutaml/model/version.rb +1 -1
  32. data/lib/lutaml/xml/leptris/native_emission.rb +4 -0
  33. data/lib/lutaml/xml/leptris/plan_serializer.rb +14 -9
  34. data/schema/lml/document.schema.json +179 -0
  35. data/scripts/lml/export_choices.rb +57 -0
  36. data/scripts/lml/export_conformance.rb +23 -0
  37. data/scripts/lml/export_mml.rb +253 -0
  38. data/scripts/lml/export_preservation.rb +421 -0
  39. data/scripts/lml/verify_artifacts.rb +31 -0
  40. data/spec/fixtures/lml_artifacts/model.json +1 -0
  41. data/spec/fixtures/lml_artifacts/valid.json +1 -0
  42. data/spec/fixtures/lml_artifacts/valid.sha256 +1 -0
  43. data/spec/fixtures/lml_conformance/core/index.json +1 -0
  44. data/spec/fixtures/lml_conformance/core/manifest.json +1 -0
  45. data/spec/fixtures/lml_conformance/core/schema.json +1 -0
  46. data/spec/fixtures/lml_conformance/core/schema.yaml +79 -0
  47. data/spec/fixtures/lml_conformance/float_vectors.generator.rb +60 -0
  48. data/spec/fixtures/lml_conformance/float_vectors.json +21550 -0
  49. data/spec/fixtures/lml_conformance/preservation/index.json +1 -0
  50. data/spec/fixtures/lml_conformance/preservation/manifest.json +1 -0
  51. data/spec/fixtures/lml_conformance/preservation/schema.json +1 -0
  52. data/spec/fixtures/lml_conformance/preservation/schema.yaml +319 -0
  53. data/spec/fixtures/lml_conformance/r2_refusals.generator.rb +153 -0
  54. data/spec/fixtures/lml_conformance/r2_refusals.json +1662 -0
  55. data/spec/fixtures/lml_conformance/ruby_portable_interop.generator.rb +40 -0
  56. data/spec/fixtures/lml_conformance/ruby_portable_interop.json +1 -0
  57. data/spec/fixtures/lml_contract/bundle.json +81 -0
  58. data/spec/fixtures/lml_contract/manifest.json +30 -0
  59. data/spec/fixtures/lml_contract/v1_unit.canonical.json +1 -0
  60. data/spec/fixtures/lml_contract/v1_unit.json +1 -0
  61. data/spec/fixtures/lml_contract/v2_node.canonical.json +1 -0
  62. data/spec/fixtures/lml_contract/v2_node.json +32 -0
  63. data/spec/fixtures/lml_mml/inventory.json +1 -0
  64. data/spec/fixtures/lml_mml/manifest.json +1 -0
  65. data/spec/fixtures/lml_mml/oracle.json +1 -0
  66. data/spec/fixtures/lml_mml/v3-mi-mixed.json +1 -0
  67. data/spec/fixtures/lml_mml/v3-mi-mixed.yaml +970 -0
  68. data/spec/fixtures/lml_mml/v4-mi-mixed.json +1 -0
  69. data/spec/fixtures/lml_mml/v4-mi-mixed.yaml +1516 -0
  70. data/spec/fixtures/lml_mml_materialization/replay.rb +37 -0
  71. data/spec/lutaml/model/lml_any_attribute_spec.rb +91 -0
  72. data/spec/lutaml/model/lml_artifact_verifier_spec.rb +86 -0
  73. data/spec/lutaml/model/lml_builtin_types_spec.rb +49 -0
  74. data/spec/lutaml/model/lml_conformance_spec.rb +178 -0
  75. data/spec/lutaml/model/lml_document_spec.rb +279 -0
  76. data/spec/lutaml/model/lml_export_validation_spec.rb +96 -0
  77. data/spec/lutaml/model/lml_exporter_spec.rb +127 -5
  78. data/spec/lutaml/model/lml_graph_exporter_spec.rb +205 -0
  79. data/spec/lutaml/model/lml_importer_spec.rb +290 -0
  80. data/spec/lutaml/model/lml_input_hardening_spec.rb +156 -0
  81. data/spec/lutaml/model/lml_mapping_compiler_spec.rb +256 -0
  82. data/spec/lutaml/model/lml_materialization_spec.rb +138 -0
  83. data/spec/lutaml/model/lml_mml_materialization_spec.rb +54 -0
  84. data/spec/lutaml/model/lml_mml_pilot_spec.rb +150 -0
  85. data/spec/lutaml/model/lml_model_choices_spec.rb +88 -0
  86. data/spec/lutaml/model/lml_ordered_content_spec.rb +243 -0
  87. data/spec/lutaml/model/lml_portable_json_spec.rb +310 -0
  88. data/spec/lutaml/model/lml_preservation_spec.rb +211 -0
  89. data/spec/lutaml/model/lml_review_export_spec.rb +247 -0
  90. data/spec/lutaml/model/lml_review_import_spec.rb +390 -0
  91. data/spec/lutaml/model/lml_review_misc_spec.rb +152 -0
  92. data/spec/lutaml/model/lml_review_round4_spec.rb +200 -0
  93. data/spec/lutaml/model/lml_review_round5_spec.rb +194 -0
  94. data/spec/lutaml/model/lml_ruby_interop_fixture_spec.rb +37 -0
  95. data/spec/lutaml/model/lml_shared_corpus_spec.rb +132 -0
  96. data/spec/lutaml/model/lml_value_declarations_spec.rb +128 -0
  97. data/spec/lutaml/model/schema/class_loader_spec.rb +51 -0
  98. data/spec/lutaml/model/schema/xml_compiler_runtime_spec.rb +20 -0
  99. data/spec/lutaml/model/sequence_spec.rb +48 -0
  100. data/spec/lutaml/xml/cdata_emission_spec.rb +68 -0
  101. data/spec/support/lml_any_attribute_fixtures.rb +26 -0
  102. data/spec/support/lml_conformance.rb +292 -0
  103. data/spec/support/lml_corpus.rb +75 -0
  104. data/spec/support/lml_export_fixtures.rb +190 -0
  105. data/spec/support/lml_graph_fixtures.rb +108 -0
  106. data/spec/support/lml_import_fixtures.rb +52 -0
  107. data/spec/support/lml_mapping_fixtures.rb +170 -0
  108. data/spec/support/lml_materialization_fixtures.rb +53 -0
  109. data/spec/support/lml_model_choices_fixtures.rb +150 -0
  110. data/spec/support/lml_order_fixtures.rb +151 -0
  111. metadata +92 -2
  112. data/lib/lutaml/model/schema/schema_builder/nokogiri.rb +0 -41
@@ -0,0 +1,577 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "rejected_error"
4
+
5
+ module Lutaml
6
+ module Model
7
+ module Lml
8
+ # Per-instance document order of an `ordered` / mixed XML model as
9
+ # portable data (lutaml-model#1033, "Format mappings and
10
+ # per-instance order").
11
+ #
12
+ # The reserved instance member +__lml_content+ holds an ordered list
13
+ # of tokens that, not grouped member traversal, control serialization
14
+ # order:
15
+ #
16
+ # {"kind" => "element", "attribute" => "em", "index" => 0}
17
+ # {"kind" => "text", "attribute" => "body", "index" => 2}
18
+ # {"kind" => "text", "literal" => "hello "}
19
+ # {"kind" => "cdata", "literal" => "<raw>"}
20
+ #
21
+ # Element tokens address the +index+-th value of a mapped element
22
+ # member (a scalar member has index 0). Mapped text tokens address
23
+ # the +index+-th value of the map_content member. Namespace identity
24
+ # is not repeated per token: it belongs to the addressed member's
25
+ # mapping rule, and is restored from the descriptor on apply.
26
+ #
27
+ # descriptor = OrderedContent.descriptor_for(Para, mapping: mapping)
28
+ # tokens = OrderedContent.capture(descriptor, para) # Ruby -> data
29
+ # OrderedContent.apply(descriptor, tokens, other_para) # data -> Ruby
30
+ #
31
+ # Comments and processing instructions in element_order have no
32
+ # token and are refused (+invalid_ordered_content+) rather than
33
+ # dropped. Elements in element_order that no rule maps are not model
34
+ # data (Ruby serialization omits them too) and are skipped.
35
+ module OrderedContent
36
+ MEMBER = "__lml_content"
37
+ VERSION = 1
38
+ KINDS = %w[element text cdata].freeze
39
+ TOKEN_KEYS = %w[kind attribute index literal].freeze
40
+ NATIVE_ORDER_OWNERS = %w[
41
+ Lutaml::Xml::Serialization::InstanceMethods
42
+ Lutaml::Xml::XmlOrderable
43
+ ].freeze
44
+ CDATA_NAME = "#cdata-section"
45
+ TEXT_NAME = "text"
46
+
47
+ # One element member: the rules (aliases) mapping it, and the
48
+ # namespace its elements carry.
49
+ ElementMember = Struct.new(:attribute, :names, :namespace_uri,
50
+ :prefix, :collection, :discriminator,
51
+ keyword_init: true) do
52
+ def collection?
53
+ collection
54
+ end
55
+ end
56
+
57
+ # The content (map_content) member, if any.
58
+ ContentMember = Struct.new(:attribute, :collection, :cdata,
59
+ keyword_init: true) do
60
+ def collection?
61
+ collection
62
+ end
63
+ end
64
+
65
+ # Immutable description of how one class/mapping maps to tokens.
66
+ class Descriptor
67
+ attr_reader :klass, :member, :elements, :content, :element_attributes
68
+
69
+ def initialize(klass:, mixed:, elements:, content:)
70
+ @klass = klass
71
+ @member = MEMBER
72
+ @mixed = mixed
73
+ @elements = elements.freeze
74
+ @content = content&.freeze
75
+ @element_attributes = elements.map(&:attribute).uniq.freeze
76
+ freeze
77
+ end
78
+
79
+ def mixed?
80
+ @mixed
81
+ end
82
+ end
83
+
84
+ class << self
85
+ # Build the descriptor for +klass+'s XML +mapping+, or nil when
86
+ # the mapping carries no per-instance order (neither `ordered`
87
+ # nor mixed content). Raises RejectedError for imperative order
88
+ # generation (+imperative_element_order+) and for a source
89
+ # member that collides with the reserved name (+reserved_member+).
90
+ def descriptor_for(klass, mapping:, register: nil)
91
+ return nil unless mapping.ordered? || mapping.mixed_content?
92
+
93
+ reject_reserved_member!(klass, mapping)
94
+ reject_imperative_order!(klass, mapping)
95
+
96
+ rules = mapping.mappings.reject(&:attribute?)
97
+ content_rule = rules.find { |rule| rule.name.nil? }
98
+ elements = element_members(klass, mapping, rules, register)
99
+
100
+ Descriptor.new(
101
+ klass: klass,
102
+ mixed: mapping.mixed_content? || false,
103
+ elements: elements,
104
+ content: content_member(klass, content_rule),
105
+ )
106
+ end
107
+
108
+ # Ruby element_order -> token list. Returns nil when the
109
+ # instance carries no element_order (it will serialize in
110
+ # mapping order), so "absent" stays distinct from "empty".
111
+ def capture(descriptor, instance)
112
+ order = instance.element_order
113
+ return nil if order.nil?
114
+
115
+ state = CaptureState.new(descriptor, instance)
116
+ order.each { |entry| state.visit(entry) }
117
+ state.finish
118
+ end
119
+
120
+ # Check +tokens+ against +descriptor+, and against +instance+'s
121
+ # member values when given. Raises +invalid_ordered_content+.
122
+ # Returns the normalized (string-keyed, frozen) token list.
123
+ def validate!(descriptor, tokens, instance: nil)
124
+ unless tokens.is_a?(Array)
125
+ fail_invalid!(descriptor, "", "#{MEMBER} must be an array")
126
+ end
127
+
128
+ seen = {}
129
+ normalized = tokens.each_with_index.map do |token, position|
130
+ normalize_token(descriptor, token, "/#{position}").tap do |tok|
131
+ check_reference(descriptor, tok, "/#{position}", seen, instance)
132
+ end
133
+ end
134
+ normalized.freeze
135
+ end
136
+
137
+ # Token list -> Lutaml::Xml::Element order entries, assigned to
138
+ # +instance.element_order+ (and returned). A nil +tokens+ leaves
139
+ # the instance without a recorded order.
140
+ def apply(descriptor, tokens, instance)
141
+ if tokens.nil?
142
+ instance.element_order = nil
143
+ return nil
144
+ end
145
+
146
+ normalized = validate!(descriptor, tokens, instance: instance)
147
+ require_ascending!(descriptor, normalized)
148
+ require_serializable_text!(descriptor, normalized, instance)
149
+ instance.element_order = normalized.map do |token|
150
+ build_entry(descriptor, token, instance)
151
+ end
152
+ end
153
+
154
+ def fail!(reason, klass, detail)
155
+ raise RejectedError.new(reason, klass, detail)
156
+ end
157
+
158
+ def fail_invalid!(descriptor, pointer, detail)
159
+ fail!(:invalid_ordered_content, descriptor.klass,
160
+ "#{MEMBER}#{pointer}: #{detail}")
161
+ end
162
+
163
+ private
164
+
165
+ # Ruby serialization consumes each member's values in value
166
+ # order, so references to one member must ascend; capture always
167
+ # produces that. A permutation would need the member values
168
+ # reordered, which apply never does behind the caller's back.
169
+ def require_ascending!(descriptor, tokens)
170
+ last = {}
171
+ tokens.each_with_index do |token, position|
172
+ next unless token.key?("attribute")
173
+
174
+ key = [token["kind"] == "element", token["attribute"]]
175
+ if last.key?(key) && token["index"] < last[key]
176
+ fail_invalid!(descriptor, "/#{position}",
177
+ "#{token['attribute']}[#{token['index']}] follows a later index; " \
178
+ "references to one member must ascend")
179
+ end
180
+ last[key] = token["index"]
181
+ end
182
+ end
183
+
184
+ # When the number of text and CDATA entries equals the number of
185
+ # content values, Ruby serialization replaces entry i with value
186
+ # i, so a literal there is silently overridden (OrderedApplier
187
+ # #process_text_node). Otherwise each entry keeps its own text.
188
+ # Refuse tokens that would be overridden rather than diverge;
189
+ # capture always emits references in the matching case.
190
+ def require_serializable_text!(descriptor, tokens, instance)
191
+ content = descriptor.content
192
+ return unless content
193
+
194
+ texts = tokens.each_with_index.reject { |tok, _| tok["kind"] == "element" }
195
+ return unless texts.size == member_values(instance, content.attribute).size
196
+
197
+ texts.each do |token, position|
198
+ next if token.key?("attribute")
199
+
200
+ fail_invalid!(descriptor, "/#{position}",
201
+ "literal #{token['kind']} token would be overridden: the order has " \
202
+ "#{texts.size} text entries for #{texts.size} content values, so " \
203
+ "serialization substitutes each value; reference #{content.attribute}[i] instead")
204
+ end
205
+ end
206
+
207
+ def reject_reserved_member!(klass, mapping)
208
+ collides = klass.attributes.key?(MEMBER.to_sym) ||
209
+ mapping.mappings.any? do |rule|
210
+ rule.to.to_s == MEMBER || Array(rule.name).map(&:to_s).include?(MEMBER)
211
+ end
212
+ return unless collides
213
+
214
+ fail!(:reserved_member, klass,
215
+ "#{MEMBER} is reserved for ordered content")
216
+ end
217
+
218
+ # An order-generating callback is Ruby code deciding which
219
+ # elements come out and where. Rules with a custom +with:+
220
+ # method on an element or content member, and a class that
221
+ # redefines element_order itself, cannot be expressed as tokens.
222
+ def reject_imperative_order!(klass, mapping)
223
+ mapping.mappings.each do |rule|
224
+ next if rule.attribute?
225
+ next if rule.custom_methods.nil? || rule.custom_methods.empty?
226
+
227
+ fail!(:imperative_element_order, klass,
228
+ "#{RejectedError.show(rule.name)} maps through custom methods " \
229
+ "#{RejectedError.show(rule.custom_methods.keys)}")
230
+ end
231
+
232
+ %i[element_order element_order=].each do |name|
233
+ next unless klass.method_defined?(name)
234
+
235
+ owner = klass.instance_method(name).owner
236
+ next if native_order_owner?(owner)
237
+
238
+ fail!(:imperative_element_order, klass,
239
+ "#{name} is overridden by #{owner}")
240
+ end
241
+ end
242
+
243
+ def native_order_owner?(owner)
244
+ NATIVE_ORDER_OWNERS.include?(owner.name)
245
+ end
246
+
247
+ def element_members(klass, mapping, rules, register)
248
+ rules.reject { |rule| rule.name.nil? }
249
+ .group_by { |rule| rule.to.to_s }
250
+ .flat_map do |attribute, group|
251
+ group.map do |rule|
252
+ build_element_member(klass, mapping, rule, attribute, register)
253
+ end
254
+ end
255
+ end
256
+
257
+ def build_element_member(klass, mapping, rule, attribute, register)
258
+ attr = klass.attributes[rule.to]
259
+ if attr.nil?
260
+ fail!(:invalid_ordered_content, klass,
261
+ "rule #{RejectedError.show(rule.name)} maps unknown attribute #{attribute}")
262
+ end
263
+
264
+ ns = element_namespace(klass, mapping, rule, attr, register)
265
+ ElementMember.new(
266
+ attribute: attribute,
267
+ names: Array(rule.name).map(&:to_s).freeze,
268
+ namespace_uri: ns[:uri],
269
+ prefix: ns[:prefix],
270
+ collection: attr.collection? || false,
271
+ discriminator: rule.when_attribute.empty? ? nil : rule.when_attribute,
272
+ ).freeze
273
+ end
274
+
275
+ # The namespace a rule's elements carry. A model-typed member
276
+ # takes its element namespace from the child model's own mapping
277
+ # when the rule declares none.
278
+ def element_namespace(_klass, mapping, rule, attr, register)
279
+ ns = rule.resolve_namespace(
280
+ attr: attr, register: register,
281
+ parent_ns_uri: mapping.namespace_uri,
282
+ parent_ns_class: mapping.namespace_class,
283
+ form_default: mapping.namespace_class&.element_form_default || :unqualified,
284
+ parent_prefix: mapping.namespace_prefix
285
+ )
286
+ return ns if ns[:uri] || rule.namespace_set?
287
+
288
+ child = attr.type(register || :default)
289
+ return ns unless child.is_a?(::Class) && child <= ::Lutaml::Model::Serialize
290
+
291
+ child_mapping = child.mappings_for(:xml, register)
292
+ { uri: child_mapping.namespace_uri, prefix: child_mapping.namespace_prefix }
293
+ end
294
+
295
+ def content_member(klass, rule)
296
+ return nil unless rule
297
+
298
+ attr = klass.attributes[rule.to]
299
+ return nil unless attr
300
+
301
+ ContentMember.new(attribute: rule.to.to_s,
302
+ collection: attr.collection? || false,
303
+ cdata: rule.cdata ? true : false)
304
+ end
305
+
306
+ def normalize_token(descriptor, token, pointer)
307
+ unless token.is_a?(::Hash)
308
+ fail_invalid!(descriptor, pointer, "token must be an object")
309
+ end
310
+
311
+ tok = token.transform_keys(&:to_s)
312
+ extra = tok.keys - TOKEN_KEYS
313
+ unless extra.empty?
314
+ fail_invalid!(descriptor, pointer, "unknown keys #{RejectedError.show(extra)}")
315
+ end
316
+
317
+ kind = tok["kind"]
318
+ unless KINDS.include?(kind)
319
+ fail_invalid!(descriptor, pointer, "unknown kind #{RejectedError.show(kind)}")
320
+ end
321
+
322
+ check_shape(descriptor, tok, pointer)
323
+ tok.freeze
324
+ end
325
+
326
+ def check_shape(descriptor, tok, pointer)
327
+ has_attribute = tok.key?("attribute")
328
+ has_literal = tok.key?("literal")
329
+ if tok["kind"] == "element"
330
+ if has_literal || !has_attribute || !tok.key?("index")
331
+ fail_invalid!(descriptor, pointer,
332
+ "element token needs attribute and index only")
333
+ end
334
+ elsif has_attribute == has_literal
335
+ fail_invalid!(descriptor, pointer,
336
+ "#{tok['kind']} token needs exactly one of attribute+index or literal")
337
+ end
338
+
339
+ if has_attribute && !(tok["attribute"].is_a?(String) && valid_index?(tok["index"]))
340
+ fail_invalid!(descriptor, pointer,
341
+ "attribute must be a string and index a non-negative integer")
342
+ end
343
+ return unless has_literal && (!tok["literal"].is_a?(String) || tok.key?("index"))
344
+
345
+ fail_invalid!(descriptor, pointer, "literal must be a string without index")
346
+ end
347
+
348
+ def valid_index?(index)
349
+ index.is_a?(Integer) && index >= 0
350
+ end
351
+
352
+ def check_reference(descriptor, tok, pointer, seen, instance)
353
+ return unless tok.key?("attribute")
354
+
355
+ attribute = tok["attribute"]
356
+ index = tok["index"]
357
+ if tok["kind"] == "element"
358
+ member = descriptor.elements.find { |e| e.attribute == attribute }
359
+ unless member
360
+ fail_invalid!(descriptor, pointer,
361
+ "#{attribute} is not a mapped element member")
362
+ end
363
+ key = [:element, attribute, index]
364
+ collection = member.collection?
365
+ else
366
+ content = descriptor.content
367
+ unless content && content.attribute == attribute
368
+ fail_invalid!(descriptor, pointer,
369
+ "#{attribute} is not the mapped content member")
370
+ end
371
+ key = [:content, attribute, index]
372
+ collection = content.collection?
373
+ end
374
+
375
+ if seen[key]
376
+ fail_invalid!(descriptor, pointer,
377
+ "duplicate reference to #{attribute}[#{index}] (first at #{seen[key]})")
378
+ end
379
+ seen[key] = pointer
380
+
381
+ if !collection && index != 0
382
+ fail_invalid!(descriptor, pointer,
383
+ "scalar member #{attribute} only has index 0")
384
+ end
385
+ check_index_exists(descriptor, attribute, index, pointer, instance) if instance
386
+ end
387
+
388
+ def check_index_exists(descriptor, attribute, index, pointer, instance)
389
+ values = member_values(instance, attribute)
390
+ return if index < values.size
391
+
392
+ fail_invalid!(descriptor, pointer,
393
+ "#{attribute}[#{index}] does not exist (#{values.size} value(s))")
394
+ end
395
+
396
+ def member_values(instance, attribute)
397
+ value = instance.public_send(attribute)
398
+ case value
399
+ when nil then []
400
+ when ::Array then value
401
+ else [value]
402
+ end
403
+ end
404
+
405
+ def build_entry(descriptor, token, instance)
406
+ case token["kind"]
407
+ when "element" then element_entry(descriptor, token)
408
+ when "text" then text_entry(descriptor, token, instance, cdata: false)
409
+ else text_entry(descriptor, token, instance, cdata: true)
410
+ end
411
+ end
412
+
413
+ def element_entry(descriptor, token)
414
+ member = descriptor.elements.find { |e| e.attribute == token["attribute"] }
415
+ ::Lutaml::Xml::Element.new(
416
+ "Element", member.names.first,
417
+ node_type: :element,
418
+ namespace_uri: member.namespace_uri,
419
+ namespace_prefix: member.prefix
420
+ )
421
+ end
422
+
423
+ def text_entry(_descriptor, token, instance, cdata:)
424
+ text = if token.key?("literal")
425
+ token["literal"]
426
+ else
427
+ member_values(instance, token["attribute"])[token["index"]].to_s
428
+ end
429
+ ::Lutaml::Xml::Element.new(
430
+ "Text", cdata ? CDATA_NAME : TEXT_NAME,
431
+ text_content: text, node_type: cdata ? :cdata : :text
432
+ )
433
+ end
434
+ end
435
+
436
+ # Walks one instance's element_order once, producing tokens.
437
+ class CaptureState
438
+ def initialize(descriptor, instance)
439
+ @descriptor = descriptor
440
+ @instance = instance
441
+ @tokens = []
442
+ @next_index = ::Hash.new(0)
443
+ @text_index = 0
444
+ @content_values = content_values
445
+ @text_nodes = instance.element_order.count do |e|
446
+ e.respond_to?(:node_type) && e.node_type == :text
447
+ end
448
+ end
449
+
450
+ def visit(entry)
451
+ unless entry.respond_to?(:node_type)
452
+ OrderedContent.fail!(:invalid_ordered_content, @descriptor.klass,
453
+ "#{MEMBER}: element_order entry #{RejectedError.show(entry)} is not an order entry")
454
+ end
455
+
456
+ case entry.node_type
457
+ when :element then visit_element(entry)
458
+ when :text then visit_text(entry)
459
+ when :cdata then add("kind" => "cdata", "literal" => entry.text_content.to_s)
460
+ else
461
+ OrderedContent.fail!(:invalid_ordered_content, @descriptor.klass,
462
+ "#{MEMBER}: #{entry.node_type} nodes have no token")
463
+ end
464
+ end
465
+
466
+ # Tokens for members element_order never mentioned (added after
467
+ # parsing) follow in declaration order, as Ruby serialization
468
+ # appends them; a count above the member's size is stale.
469
+ def finish
470
+ @descriptor.element_attributes.each do |attribute|
471
+ size = values_for(attribute).size
472
+ used = @next_index[[:element, attribute]]
473
+ if used > size
474
+ OrderedContent.fail!(:invalid_ordered_content, @descriptor.klass,
475
+ "#{MEMBER}: element_order lists #{used} #{attribute} " \
476
+ "element(s) but the member has #{size}")
477
+ end
478
+ (used...size).each do |i|
479
+ add("kind" => "element", "attribute" => attribute, "index" => i)
480
+ end
481
+ end
482
+ finish_content
483
+ @tokens.freeze
484
+ end
485
+
486
+ private
487
+
488
+ def finish_content
489
+ content = @descriptor.content
490
+ return unless content
491
+
492
+ (@text_index...@content_values.size).each do |i|
493
+ add("kind" => "text", "attribute" => content.attribute, "index" => i)
494
+ end
495
+ end
496
+
497
+ def add(token)
498
+ @tokens << token.freeze
499
+ end
500
+
501
+ def values_for(attribute)
502
+ OrderedContent.send(:member_values, @instance, attribute)
503
+ end
504
+
505
+ def content_values
506
+ content = @descriptor.content
507
+ return [] unless content
508
+
509
+ values_for(content.attribute)
510
+ end
511
+
512
+ def visit_element(entry)
513
+ member = match_member(entry)
514
+ return unless member
515
+
516
+ key = [:element, member.attribute]
517
+ index = @next_index[key]
518
+ @next_index[key] += 1
519
+ add("kind" => "element", "attribute" => member.attribute, "index" => index)
520
+ end
521
+
522
+ def visit_text(entry)
523
+ text = entry.text_content.to_s
524
+ # Element-only (`ordered`) content: indentation between
525
+ # elements is not content.
526
+ return if !@descriptor.mixed? && text.strip.empty?
527
+
528
+ index = @text_index
529
+ @text_index += 1
530
+ if mapped_text?(index, text)
531
+ add("kind" => "text", "attribute" => @descriptor.content.attribute,
532
+ "index" => index)
533
+ else
534
+ add("kind" => "text", "literal" => text)
535
+ end
536
+ end
537
+
538
+ # A text node maps to the content member when the member holds
539
+ # the same string at that text position; a scalar member only
540
+ # when the order has a single text node.
541
+ def mapped_text?(index, text)
542
+ content = @descriptor.content
543
+ return false unless content
544
+ return false if !content.collection? && (@text_nodes != 1 || index != 0)
545
+
546
+ value = @content_values[index]
547
+ !value.nil? && value.to_s == text
548
+ end
549
+
550
+ def match_member(entry)
551
+ candidates = @descriptor.elements.select do |member|
552
+ member.names.include?(entry.name.to_s) && namespace_match?(member, entry)
553
+ end
554
+ return candidates.first if candidates.size <= 1
555
+
556
+ pick_by_discriminator(candidates, entry)
557
+ end
558
+
559
+ def namespace_match?(member, entry)
560
+ entry.namespace_uri.nil? || member.namespace_uri.nil? ||
561
+ member.namespace_uri == entry.namespace_uri
562
+ end
563
+
564
+ def pick_by_discriminator(candidates, entry)
565
+ attrs = entry.attributes || {}
566
+ discriminated = candidates.find do |member|
567
+ pairs = member.discriminator
568
+ pairs && !pairs.empty? &&
569
+ pairs.all? { |name, expected| attrs[name.to_s].to_s == expected.to_s && !attrs[name.to_s].nil? }
570
+ end
571
+ discriminated || candidates.find { |m| m.discriminator.nil? || m.discriminator.empty? } || candidates.first
572
+ end
573
+ end
574
+ end
575
+ end
576
+ end
577
+ end