Class: Canon::Xml::DataModel

Inherits:
DataModel
  • Object
show all
Defined in:
lib/canon/xml/data_model.rb

Constant Summary collapse

XML_ENCODING_DECL =

Encoding-declaration probe: anchored, and it only ever scans the XML declaration prefix — a document without one bails after a few characters.

/\A\s*<\?xml[^>]*\bencoding\s*=\s*["']([^"']+)["'][^>]*\?>/i

Class Method Summary collapse

Class Method Details

.assign_moxml_namespace_scopes(element, inherited, own_namespaces) ⇒ Object



362
363
364
365
366
367
368
369
370
# File 'lib/canon/xml/data_model.rb', line 362

def self.assign_moxml_namespace_scopes(element, inherited, own_namespaces)
  scope = TreeBuilder::DEFAULT.merge_namespace_scope(inherited,
                                                     own_namespaces[element].to_a)
  TreeBuilder::DEFAULT.attach_namespace_scope(element, scope)

  element.children.each do |child|
    assign_moxml_namespace_scopes(child, scope, own_namespaces) if child.is_a?(Nodes::ElementNode)
  end
end

.build_from_moxml(moxml_doc, preserve_whitespace: false) ⇒ Object



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/canon/xml/data_model.rb', line 244

def self.build_from_moxml(moxml_doc, preserve_whitespace: false)
  root = Nodes::RootNode.new
  skip_types = [Moxml::Doctype]

  if moxml_doc.is_a?(Moxml::Document) && moxml_doc.root
    element = build_moxml_subtree_from_records(moxml_doc.root,
                                               preserve_whitespace: preserve_whitespace)
    root.add_child(element) if element
    TreeBuilder::DEFAULT.add_document_children(root, moxml_doc.children,
                                               moxml_doc.root, skip_types) do |child|
      walk_moxml(child, preserve_whitespace: preserve_whitespace)
    end
  else
    TreeBuilder::DEFAULT.add_document_children(root, moxml_doc.children,
                                               nil, skip_types) do |child|
      walk_moxml(child, preserve_whitespace: preserve_whitespace)
    end
  end

  root
end

.build_from_nokogiri(nokogiri_doc, preserve_whitespace: false) ⇒ Object

-- Nokogiri walk: top-down, scope flows down the recursion --



155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/canon/xml/data_model.rb', line 155

def self.build_from_nokogiri(nokogiri_doc, preserve_whitespace: false)
  root = Nodes::RootNode.new
  skip_types = defined?(Nokogiri) ? [Nokogiri::XML::DTD] : []

  if nokogiri_doc.is_a?(Nokogiri::XML::Document) && nokogiri_doc.root
    root.add_child(walk_nokogiri(nokogiri_doc.root,
                                 preserve_whitespace: preserve_whitespace))
    TreeBuilder::DEFAULT.add_document_children(root, nokogiri_doc.children,
                                               nokogiri_doc.root, skip_types) do |child|
      walk_nokogiri(child, preserve_whitespace: preserve_whitespace)
    end
  else
    TreeBuilder::DEFAULT.add_document_children(root, nokogiri_doc.children,
                                               nil, skip_types) do |child|
      walk_nokogiri(child, preserve_whitespace: preserve_whitespace)
    end
  end

  root
end

.build_moxml_element_from_fields(qname, prefix, namespace_uri, namespaces, attributes, depth, frame_depths, frame_nodes, own_namespaces) ⇒ Object



334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
# File 'lib/canon/xml/data_model.rb', line 334

def self.build_moxml_element_from_fields(qname, prefix, namespace_uri,
                                         namespaces, attributes, depth,
                                         frame_depths, frame_nodes,
                                         own_namespaces)
  # The flat attribute buffer is consumed synchronously — the
  # next record reuses it (no each_slice copy out of the block).
  element = TreeBuilder::DEFAULT.element(
    name: qname,
    prefix: prefix,
    namespace_uri: namespace_uri,
    attributes: attributes,
  )

  # Adopt completed children: they pop in reverse order; reversing
  # once is O(n) (unshift per child would be O(n^2) on wide trees).
  children = []
  while frame_depths.any? && frame_depths.last > depth
    frame_depths.pop
    children << frame_nodes.pop
  end
  children.reverse_each { |child| element.add_child(child) }

  # Copy the declarations out of the reused buffer (most
  # elements declare none — stash nothing for those).
  own_namespaces[element] = namespaces.each_slice(2).to_a unless namespaces.empty?
  element
end

.build_moxml_subtree_from_records(moxml_element, preserve_whitespace: false) ⇒ Object



266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# File 'lib/canon/xml/data_model.rb', line 266

def self.build_moxml_subtree_from_records(moxml_element,
preserve_whitespace: false)
  # Parallel depth/node stacks: one [depth, node] pair per record
  # cost two Arrays per node; depths are Integers (immediate
  # values), so two parallel arrays allocate nothing per record.
  frame_depths = []
  frame_nodes = []
  own_namespaces = {}.compare_by_identity

  # materialize_fields: the zero-allocation hot path (moxml#143).
  # Flat reused buffers — attributes stride 4, namespaces stride
  # 2 — valid only inside the block, so the element builder
  # consumes them synchronously before the next record reuses
  # the buffer.
  moxml_element.materialize_fields do |kind, qname, prefix, namespace_uri, namespaces, attributes, text, depth|
    # The record contract is root-subtree-only since moxml 0.5.11
    # (moxml#140). Older 0.5.x releases — still allowed by canon's
    # gemspec floor — leaked epilog document-level records at depth
    # 0, which the document-children enumeration also covers; one
    # integer compare per record keeps those working.
    next if depth.zero? && kind != :element

    # Relative-namespace validation rides the stream (the
    # namespaces buffer is the element's own declarations) — no
    # separate wrapper-tree walk per parse.
    if kind == :element
      i = 1
      while i < namespaces.size
        href = namespaces[i]
        if !href.nil? && !href.empty? && relative_uri?(href)
          raise Canon::Error,
                "Relative namespace URI not allowed: #{href}"
        end
        i += 2
      end
    end

    node = case kind
           when :element
             build_moxml_element_from_fields(
               qname, prefix, namespace_uri, namespaces, attributes,
               depth, frame_depths, frame_nodes, own_namespaces
             )
           when :text, :cdata
             content = text.to_s
             TreeBuilder::DEFAULT.text(content,
                                       keep: WhitespacePolicy.keep_dom_text?(
                                         content, preserve_whitespace: preserve_whitespace
                                       ))
           when :comment
             TreeBuilder::DEFAULT.comment(text)
           when :processing_instruction
             TreeBuilder::DEFAULT.processing_instruction(qname, text || "")
           end

    if node
      frame_depths << depth
      frame_nodes << node
    end
  end

  return nil if frame_nodes.empty?

  top = frame_nodes.last
  assign_moxml_namespace_scopes(top, nil, own_namespaces)
  top
end

.check_for_relative_namespace_uris(doc) ⇒ Object



131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/canon/xml/data_model.rb', line 131

def self.check_for_relative_namespace_uris(doc)
  doc.traverse do |node|
    next unless node.is_a?(Nokogiri::XML::Element)

    node.namespace_definitions.each do |ns|
      next if ns.href.nil? || ns.href.empty?
      if relative_uri?(ns.href)
        raise Canon::Error,
              "Relative namespace URI not allowed: #{ns.href}"
      end
    end
  end
end

.extract_xml_encoding(xml_string) ⇒ Object



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/canon/xml/data_model.rb', line 87

def self.extract_xml_encoding(xml_string)
  # A valid UTF-8 string matches directly (the regex is
  # ASCII-only); anything else still needs the BINARY view so a
  # broken byte sequence cannot raise mid-probe. The validity is
  # tested by the match itself, not a full-document scan: invalid
  # bytes outside the scanned prefix never raise, and invalid
  # bytes inside it fall back to the BINARY retry.
  if xml_string.encoding.name == "UTF-8"
    begin
      return xml_string[XML_ENCODING_DECL, 1]
    rescue ArgumentError
      xml_string = xml_string.dup.force_encoding("BINARY")
    end
  else
    xml_string = xml_string.dup.force_encoding("BINARY")
  end

  xml_string[XML_ENCODING_DECL, 1]
end

.from_moxml_xml(xml_string, preserve_whitespace:) ⇒ Object

-- moxml record stream: post-order frames adopt children -- One flattened record stream (moxml#132/#138) instead of a wrapper walk, so document conversion costs no Moxml::Node allocation per node. Own namespace declarations ride an identity-keyed stash; assign_moxml_namespace_scopes expands them to in-scope scopes afterwards (post-order arrival means scopes cannot flow down during the stream).



226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/canon/xml/data_model.rb', line 226

def self.from_moxml_xml(xml_string, preserve_whitespace:)
  # strict: false keeps the Nokogiri-engine contract — malformed
  # input yields a recovered document plus diagnostics instead of
  # an exception (moxml 0.5.15 defaults strict to true; issue
  # #147 rides recover errors on Document#parse_errors).
  doc = Canon::XmlParsing.moxml_context.parse(xml_string,
                                              readonly: true,
                                              strict: false)
  result = build_from_moxml(doc, preserve_whitespace: preserve_whitespace)
  result.parse_errors = doc.parse_errors if doc.parse_errors.any?
  # Canon owns this document's full lifecycle: the canon tree holds
  # no engine references once built, so release the native tree now
  # instead of waiting for the GC finalizer (moxml#134; no-op on
  # GC-managed adapters).
  doc.free
  result
end

.from_nokogiri_xml(xml_string, preserve_whitespace:) ⇒ Object

--- Nokogiri path ---



121
122
123
124
125
126
127
128
129
# File 'lib/canon/xml/data_model.rb', line 121

def self.from_nokogiri_xml(xml_string, preserve_whitespace:)
  doc = Nokogiri::XML(xml_string, &:nonet)
  check_for_relative_namespace_uris(doc)
  result = build_from_nokogiri(doc,
                               preserve_whitespace: preserve_whitespace)
  errors = Array(doc.errors).map(&:to_s)
  result.parse_errors = errors if errors.any?
  result
end

.from_xml(xml_string, preserve_whitespace: false) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
# File 'lib/canon/xml/data_model.rb', line 9

def self.from_xml(xml_string, preserve_whitespace: false)
  normalized_xml = normalize_encoding(xml_string)

  if Canon::XmlBackend.nokogiri?
    from_nokogiri_xml(normalized_xml,
                      preserve_whitespace: preserve_whitespace)
  else
    from_moxml_xml(normalized_xml,
                   preserve_whitespace: preserve_whitespace)
  end
end

.normalize_encoding(xml_string) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/canon/xml/data_model.rb', line 21

def self.normalize_encoding(xml_string)
  return xml_string unless xml_string.is_a?(String)

  declared_encoding = extract_xml_encoding(xml_string)

  if declared_encoding
    if declared_encoding.upcase != "UTF-8"
      utf8_reinterpreted = try_utf8_reinterpretation(xml_string)
      if utf8_reinterpreted
        return update_xml_declaration(xml_string,
                                      "UTF-8")
      end

      return transcode_to_utf8(xml_string, declared_encoding)
    end
  elsif xml_string.encoding.name != "UTF-8"
    reinterpreted = try_utf8_reinterpretation(xml_string)
    return reinterpreted if reinterpreted

    return transcode_to_utf8(xml_string, xml_string.encoding.name)
  end

  xml_string
end

.parse(xml_string) ⇒ Object



107
108
109
# File 'lib/canon/xml/data_model.rb', line 107

def self.parse(xml_string)
  from_xml(xml_string)
end

.relative_uri?(uri) ⇒ Boolean

Returns:

  • (Boolean)


115
116
117
# File 'lib/canon/xml/data_model.rb', line 115

def self.relative_uri?(uri)
  uri !~ %r{^[a-zA-Z][a-zA-Z0-9+.-]*:}
end

.serialize(node) ⇒ Object



111
112
113
# File 'lib/canon/xml/data_model.rb', line 111

def self.serialize(node)
  node.to_s
end

.transcode_to_utf8(xml_string, source_encoding) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/canon/xml/data_model.rb', line 52

def self.transcode_to_utf8(xml_string, source_encoding)
  if source_encoding != "UTF-8"
    forced = xml_string.dup.force_encoding(source_encoding)
    if forced.valid_encoding?
      utf8_check = xml_string.dup.force_encoding("UTF-8")
      if utf8_check.valid_encoding?
        return xml_string.dup.force_encoding("UTF-8")
      end

      return forced.encode("UTF-8", source_encoding,
                           invalid: :replace,
                           undef: :replace,
                           replace: "?")
    end
  end

  xml_string.dup.force_encoding("UTF-8")
rescue EncodingError
  xml_string
end

.try_utf8_reinterpretation(xml_string) ⇒ Object



73
74
75
76
77
78
79
80
# File 'lib/canon/xml/data_model.rb', line 73

def self.try_utf8_reinterpretation(xml_string)
  return xml_string if xml_string.encoding.name == "UTF-8"

  forced = xml_string.dup.force_encoding("UTF-8")
  return forced if forced.valid_encoding?

  nil
end

.update_xml_declaration(xml_string, new_encoding) ⇒ Object



46
47
48
49
50
# File 'lib/canon/xml/data_model.rb', line 46

def self.update_xml_declaration(xml_string, new_encoding)
  xml_string.sub(/\bencoding\s*=\s*["'][^"']+["']/i) do |_match|
    %(encoding="#{new_encoding}")
  end
end

.walk_moxml(node, preserve_whitespace: false, inherited_namespaces: nil) ⇒ Object

-- moxml wrapper walk: fragments and user-supplied nodes --



374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
# File 'lib/canon/xml/data_model.rb', line 374

def self.walk_moxml(node, preserve_whitespace: false,
inherited_namespaces: nil)
  case node
  when Moxml::Element
    scope = TreeBuilder::DEFAULT.merge_namespace_scope(
      inherited_namespaces,
      node.namespace_definitions.map { |ns| [ns.prefix, ns.uri] },
    )
    flat_attributes = []
    node.attributes.each do |attr|
      flat_attributes << attr.name << attr.value <<
        attr.namespace&.uri << attr.namespace&.prefix
    end
    element = TreeBuilder::DEFAULT.element(
      name: node.name,
      prefix: node.namespace&.prefix,
      namespace_uri: node.namespace&.uri,
      attributes: flat_attributes,
      namespace_scope: scope,
    )
    node.children.each do |child|
      built = walk_moxml(child,
                         preserve_whitespace: preserve_whitespace,
                         inherited_namespaces: scope)
      element.add_child(built) if built
    end
    element
  when Moxml::Text, Moxml::Cdata
    TreeBuilder::DEFAULT.text(node.content,
                              keep: WhitespacePolicy.keep_dom_text?(
                                node.content,
                                preserve_whitespace: preserve_whitespace,
                                element_parent: node.parent.is_a?(Moxml::Element),
                              ))
  when Moxml::Comment
    TreeBuilder::DEFAULT.comment(node.content)
  when Moxml::ProcessingInstruction
    TreeBuilder::DEFAULT.processing_instruction(node.target, node.content)
  end
end

.walk_nokogiri(node, preserve_whitespace:, inherited_namespaces: nil) ⇒ Object



176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/canon/xml/data_model.rb', line 176

def self.walk_nokogiri(node, preserve_whitespace:,
inherited_namespaces: nil)
  case node
  when Nokogiri::XML::Element
    scope = TreeBuilder::DEFAULT.merge_namespace_scope(
      inherited_namespaces,
      node.namespace_definitions.map { |ns| [ns.prefix, ns.href] },
    )
    flat_attributes = []
    node.attribute_nodes.each do |attr|
      flat_attributes << attr.name << attr.value <<
        attr.namespace&.href << attr.namespace&.prefix
    end
    element = TreeBuilder::DEFAULT.element(
      name: node.name,
      prefix: node.namespace&.prefix,
      namespace_uri: node.namespace&.href,
      attributes: flat_attributes,
      namespace_scope: scope,
    )
    node.children.each do |child|
      built = walk_nokogiri(child,
                            preserve_whitespace: preserve_whitespace,
                            inherited_namespaces: scope)
      element.add_child(built) if built
    end
    element
  when Nokogiri::XML::Text, Nokogiri::XML::CDATA
    TreeBuilder::DEFAULT.text(node.content,
                              keep: WhitespacePolicy.keep_dom_text?(
                                node.content,
                                preserve_whitespace: preserve_whitespace,
                                element_parent: node.parent.is_a?(Nokogiri::XML::Element),
                              ),
                              original: node.to_xml)
  when Nokogiri::XML::Comment
    TreeBuilder::DEFAULT.comment(node.content)
  when Nokogiri::XML::ProcessingInstruction
    TreeBuilder::DEFAULT.processing_instruction(node.name, node.content)
  end
end