Class: Moxml::Adapter::Leptris

Inherits:
Base
  • Object
show all
Extended by:
DocumentParts, Markers, Materialize, Serialize
Defined in:
lib/moxml/adapter/leptris.rb,
lib/moxml/adapter/leptris/markers.rb,
lib/moxml/adapter/leptris/serialize.rb,
lib/moxml/adapter/leptris/sax_bridge.rb,
lib/moxml/adapter/leptris/materialize.rb,
lib/moxml/adapter/leptris/document_parts.rb

Overview

Adapter over the leptris FFI binding (libleptris C library).

libleptris provides DOM parsing, a native XPath 1.0 engine, SAX, and serialization. It has no first-class XML declaration or programmatic DOCTYPE, so those live in CustomizedLeptris value objects stored through NativeAttachment.

Defined Under Namespace

Modules: DocumentParts, Markers, Materialize, Serialize Classes: LeptrisSAXBridge

Constant Summary collapse

DOC_NODE_SUPPORTED =

libleptris 1.9.7 (leptris-ruby 1.9.26): Document#node exposes the libxml2-model document node — prolog/epilog parts in document order. Older bindings keep the flat pre-root PI path.

::Leptris::XML::Document.method_defined?(:node)
DTDATTR_SUPPORTED =

libleptris 1.9.8 (leptris-ruby 1.9.30): plain parse excludes DTD ATTLIST defaults, matching libxml2/Nokogiri semantics; ParseOptions::DTDATTR opts in (leptris/leptris#606).

::Leptris::XML::ParseOptions.const_defined?(:DTDATTR)
BULK_FIELD_READS =

The raw field-read surface for the bulk materializer (issue #143). Bindings without the full set fall back to the generic wrapper walk.

%i[
  leptris_node_children leptris_node_get_type
  leptris_element_name leptris_element_prefix leptris_element_namespace
  leptris_element_namespace_count leptris_element_namespace_decl_prefix
  leptris_element_namespace_decl_uri leptris_element_first_attribute
  leptris_attribute_get_name leptris_attribute_get_value
  leptris_attribute_next leptris_attribute_namespace_uri
  leptris_text_node_get_content leptris_cdata_node_get_content
  leptris_comment_node_get_content leptris_pi_node_get_target
  leptris_pi_node_get_data
].all? { |fn| ::Leptris::XML::FFI.respond_to?(fn) }
NATIVE_XPATH_CACHE =

XPath prefers libleptris' native C engine (three orders of magnitude faster than the Ruby engine) for document-context queries, with a conservative gate: the Ruby engine handles element-context evaluation (native relative-context semantics are not contract-verified), variable references, and expressions whose results are attribute nodes (native returns those without name accessors). Both engines resolve expression prefixes against document-declared namespaces.

XPath::Cache.new(100)
NATIVE_GATE_CACHE =

The gate decision is expression-intrinsic; re-walking the cached AST three times per xpath call cost ~23% of repeated selective queries, so the boolean caches beside it.

XPath::Cache.new(100)

Constants included from Serialize

Serialize::EMPTY_ELEMENT_RE, Serialize::LITERAL_REGIONS

Constants included from DocumentParts

DocumentParts::DOCUMENT_ATTACHMENT_KEYS

Constants included from Materialize

Materialize::EMPTY_FIELDS

Class Method Summary collapse

Methods included from Serialize

next_literal_region, normalize_markup, normalize_serialization, opener_at_offset, raw_serialize, serialize

Methods included from DocumentParts

add_document_child, assemble_document_children, default_declaration_xml, document_has_declaration?, document_node_children, document_pi_nodes, free_document, marker_text_for, native_doctype_xml, serialize_document

Methods included from Markers

entity_bearing?, split_entity_markers

Methods included from Materialize

bulk_materialize?, emit_element_fields, materialize_fields, walk_fields

Methods inherited from Base

actual_native, bulk_materialize?, create_cdata, create_comment, create_declaration, create_doctype, create_element, create_entity_reference, create_namespace, create_processing_instruction, create_text, decode_entities, entity_bearing?, free_document, in_scope_namespaces, materialize_fields, patch_node, patches_children?, preprocess_entities, restore_entities, sax_supported?, wrappers_recyclable?

Methods included from XmlUtils

#encode_entities, #normalize_xml_value, #validate_comment_content, #validate_declaration_encoding, #validate_declaration_standalone, #validate_declaration_version, #validate_element_name, #validate_entity_reference_name, #validate_pi_target, #validate_prefix, #validate_uri

Class Method Details

.add_child(parent, child) ⇒ Object



448
449
450
451
452
453
454
455
456
457
458
459
460
461
# File 'lib/moxml/adapter/leptris.rb', line 448

def add_child(parent, child)
  case parent
  when ::Leptris::XML::Document then add_document_child(parent, child)
  else
    if child.is_a?(CustomizedLeptris::EntityReference)
      marker = parent.document.create_text_node("#{Entity::MARKER}#{child.name};")
      parent.add_child(marker)
      attachments.set(parent.document, :entity_markers, true)
      return child
    end
    child = parent.document.create_text_node(child) if child.is_a?(String)
    parent.add_child(child)
  end
end

.add_next_sibling(node, new_node) ⇒ Object



474
475
476
# File 'lib/moxml/adapter/leptris.rb', line 474

def add_next_sibling(node, new_node)
  node.add_next_sibling(new_node)
end

.add_previous_sibling(node, new_node) ⇒ Object



463
464
465
466
467
468
469
470
471
472
# File 'lib/moxml/adapter/leptris.rb', line 463

def add_previous_sibling(node, new_node)
  # A PI inserted before the root lives at document level in
  # libleptris's model, not in the element tree.
  if new_node.is_a?(::Leptris::XML::ProcessingInstruction) &&
      node.document&.root == node
    node.document.add_pi(new_node.target, new_node.content.to_s)
    return new_node
  end
  node.add_previous_sibling(new_node)
end

.ast_contains_type?(ast, type) ⇒ Boolean

Returns:

  • (Boolean)


716
717
718
719
720
721
722
# File 'lib/moxml/adapter/leptris.rb', line 716

def ast_contains_type?(ast, type)
  return true if ast.type == type

  ast.children.any? do |child|
    child.is_a?(XPath::AST::Node) && ast_contains_type?(child, type)
  end
end

.at_xpath(node, expression, namespaces = {}) ⇒ Object



635
636
637
638
639
640
641
# File 'lib/moxml/adapter/leptris.rb', line 635

def at_xpath(node, expression, namespaces = {})
  native = native_xpath(node, expression, namespaces, first_only: true)
  return native unless native.nil?

  result = engine_xpath(node, expression, namespaces)
  result.is_a?(Array) ? result.first : result
end

.attachmentsObject



64
65
66
# File 'lib/moxml/adapter/leptris.rb', line 64

def attachments
  @attachments ||= Moxml::NativeAttachment.new
end

.attr_matches?(attr_name) ⇒ Boolean

Returns:

  • (Boolean)


171
172
173
# File 'lib/moxml/adapter/leptris.rb', line 171

def attr_matches?(attr_name)
  %w[version encoding standalone].include?(attr_name.to_s)
end

.attribute_element(attr) ⇒ Object



400
401
402
# File 'lib/moxml/adapter/leptris.rb', line 400

def attribute_element(attr)
  attr.element
end

.attribute_name(attr) ⇒ Object



404
405
406
407
408
409
410
# File 'lib/moxml/adapter/leptris.rb', line 404

def attribute_name(attr)
  # leptris Attr names are qualified; the wrapper composes the
  # prefix, so expose the local part.
  return attr.name.split(":", 2)[1] if attr.name.include?(":")

  attr.name.to_s.dup.force_encoding("UTF-8")
end

.attributes(element) ⇒ Object



396
397
398
# File 'lib/moxml/adapter/leptris.rb', line 396

def attributes(element)
  element.attribute_nodes
end

.cdata_content(node) ⇒ Object



559
560
561
# File 'lib/moxml/adapter/leptris.rb', line 559

def cdata_content(node)
  node.content
end

.children(node) ⇒ Object



328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'lib/moxml/adapter/leptris.rb', line 328

def children(node)
  case node
  when ::Leptris::XML::Document
    assemble_document_children(node)
  when CustomizedLeptris::Declaration, CustomizedLeptris::Doctype,
       CustomizedLeptris::EntityReference, CustomizedLeptris::TextSegment,
       CustomizedLeptris::DocumentPI,
       # Terminal node kinds pay an FFI round trip for an empty
       # list; unfiltered recursions visit every text node.
       ::Leptris::XML::Text, ::Leptris::XML::Comment,
       ::Leptris::XML::CDATA, ::Leptris::XML::ProcessingInstruction,
       ::Leptris::XML::Attr
    []
  else
    natives = node.children.to_a
    # Parse records whether the preprocessed source held any
    # entity markers, and the ER builder path flips the flag
    # when it mints one. A false flag lets traversal skip the
    # marker split — including the per-text content fetch that
    # dominates cold children cost. Cross-document moves of
    # marker-bearing text into an entity-free document degrade
    # to literal text.
    return natives if attachments.get(node.document, :entity_markers) == false

    split_entity_markers(natives, node)
  end
end

.comment_content(node) ⇒ Object



567
568
569
# File 'lib/moxml/adapter/leptris.rb', line 567

def comment_content(node)
  node.content
end

.contains_parent_axis?(ast) ⇒ Boolean

Returns:

  • (Boolean)


691
692
693
694
695
696
697
698
# File 'lib/moxml/adapter/leptris.rb', line 691

def contains_parent_axis?(ast)
  return true if ast.type == :parent
  return true if ast.type == :axis && ast.children.first == "parent"

  ast.children.any? do |child|
    child.is_a?(XPath::AST::Node) && contains_parent_axis?(child)
  end
end

.create_document(_native_doc = nil) ⇒ Object



122
123
124
# File 'lib/moxml/adapter/leptris.rb', line 122

def create_document(_native_doc = nil)
  ::Leptris::XML::Document.create
end

.create_native_cdata(content, owner_doc = nil) ⇒ Object



134
135
136
# File 'lib/moxml/adapter/leptris.rb', line 134

def create_native_cdata(content, owner_doc = nil)
  (owner_doc || create_document).create_cdata(content)
end

.create_native_comment(content, owner_doc = nil) ⇒ Object



138
139
140
# File 'lib/moxml/adapter/leptris.rb', line 138

def create_native_comment(content, owner_doc = nil)
  (owner_doc || create_document).create_comment(content)
end

.create_native_declaration(version, encoding, standalone) ⇒ Object



151
152
153
# File 'lib/moxml/adapter/leptris.rb', line 151

def create_native_declaration(version, encoding, standalone)
  CustomizedLeptris::Declaration.new(version, encoding, standalone)
end

.create_native_doctype(name, external_id, system_id) ⇒ Object



147
148
149
# File 'lib/moxml/adapter/leptris.rb', line 147

def create_native_doctype(name, external_id, system_id)
  CustomizedLeptris::Doctype.new(name, external_id, system_id)
end

.create_native_element(name, owner_doc = nil) ⇒ Object



126
127
128
# File 'lib/moxml/adapter/leptris.rb', line 126

def create_native_element(name, owner_doc = nil)
  (owner_doc || create_document).create_element(name.to_s)
end

.create_native_entity_reference(name) ⇒ Object



155
156
157
# File 'lib/moxml/adapter/leptris.rb', line 155

def create_native_entity_reference(name)
  CustomizedLeptris::EntityReference.new(name)
end

.create_native_namespace(element, prefix, uri) ⇒ Object



188
189
190
# File 'lib/moxml/adapter/leptris.rb', line 188

def create_native_namespace(element, prefix, uri)
  element.add_namespace_definition(prefix, uri)
end

.create_native_processing_instruction(target, content) ⇒ Object



142
143
144
145
# File 'lib/moxml/adapter/leptris.rb', line 142

def create_native_processing_instruction(target, content)
  doc = create_document
  doc.create_processing_instruction(target.to_s, content.to_s)
end

.create_native_text(content, owner_doc = nil) ⇒ Object



130
131
132
# File 'lib/moxml/adapter/leptris.rb', line 130

def create_native_text(content, owner_doc = nil)
  (owner_doc || create_document).create_text_node(content)
end

.declaration_attribute(declaration, attr_name) ⇒ Object



163
164
165
# File 'lib/moxml/adapter/leptris.rb', line 163

def declaration_attribute(declaration, attr_name)
  declaration.public_send(attr_name) if attr_matches?(attr_name)
end

.doctype_external_id(node) ⇒ Object



606
607
608
# File 'lib/moxml/adapter/leptris.rb', line 606

def doctype_external_id(node)
  node.is_a?(CustomizedLeptris::Doctype) ? node.external_id : node.public_id
end

.doctype_name(node) ⇒ Object



602
603
604
# File 'lib/moxml/adapter/leptris.rb', line 602

def doctype_name(node)
  node.is_a?(CustomizedLeptris::Doctype) ? node.name : node.root_name
end

.doctype_system_id(node) ⇒ Object



610
611
612
# File 'lib/moxml/adapter/leptris.rb', line 610

def doctype_system_id(node)
  node.system_id
end

.document(node) ⇒ Object



377
378
379
380
381
382
383
# File 'lib/moxml/adapter/leptris.rb', line 377

def document(node)
  case node
  when ::Leptris::XML::Document then node
  when CustomizedLeptris::Declaration, CustomizedLeptris::Doctype then node.parent_doc
  else node.document
  end
end

.dtdattr_parse_options(options) ⇒ Object

nil when DTDATTR is unsupported or not requested — the binding treats a nil options hash as plain defaults.



112
113
114
115
116
# File 'lib/moxml/adapter/leptris.rb', line 112

def dtdattr_parse_options(options)
  return nil unless DTDATTR_SUPPORTED && options[:dtdattr] == true

  ::Leptris::XML::ParseOptions.dtdattr
end

.duplicate_node(node) ⇒ Object



313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/moxml/adapter/leptris.rb', line 313

def duplicate_node(node)
  case node
  when CustomizedLeptris::Declaration
    CustomizedLeptris::Declaration.new(node.version, node.encoding, node.standalone)
  when CustomizedLeptris::Doctype
    CustomizedLeptris::Doctype.new(node.name, node.external_id, node.system_id)
  when CustomizedLeptris::EntityReference
    CustomizedLeptris::EntityReference.new(node.name)
  when CustomizedLeptris::DocumentPI
    CustomizedLeptris::DocumentPI.new(node.target, node.data, node.parent_doc)
  else
    node.dup
  end
end

.engine_xpath(node, expression, namespaces = {}) ⇒ Object



766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
# File 'lib/moxml/adapter/leptris.rb', line 766

def engine_xpath(node, expression, namespaces = {})
  unless node.is_a?(Moxml::Node)
    node = Moxml::Node.wrap(node, Context.new(:leptris))
  end

  ast = XPath::Parser.parse(expression)
  proc = XPath::Compiler.compile_with_cache(ast, namespaces: namespaces)
  result = proc.call(node)

  case result
  when Array, NodeSet
    nodes = result.is_a?(NodeSet) ? result.to_a : result
    seen = {}.compare_by_identity
    nodes.map { |n| n.is_a?(Moxml::Node) ? n.native : n }
      .select do |native|
        if seen.key?(native)
          false
        else
          seen[native] = true
          true
        end
      end
  else
    result
  end
end

.entity_reference_name(node) ⇒ Object



159
160
161
# File 'lib/moxml/adapter/leptris.rb', line 159

def entity_reference_name(node)
  node.name if node.is_a?(CustomizedLeptris::EntityReference)
end

.expression_uses_parent_axis?(expression) ⇒ Boolean

Returns:

  • (Boolean)


684
685
686
687
688
689
# File 'lib/moxml/adapter/leptris.rb', line 684

def expression_uses_parent_axis?(expression)
  ast = XPath::Parser.parse_with_cache(expression)
  contains_parent_axis?(ast)
rescue XPath::SyntaxError
  true
end

.get_attribute(element, name) ⇒ Object



431
432
433
# File 'lib/moxml/adapter/leptris.rb', line 431

def get_attribute(element, name)
  element.attribute_nodes.find { |attr| attr.name == name.to_s }
end

.get_attribute_value(element, name) ⇒ Object



435
436
437
# File 'lib/moxml/adapter/leptris.rb', line 435

def get_attribute_value(element, name)
  element[name.to_s]
end

.has_declaration?(native_doc, _wrapper) ⇒ Boolean

Returns:

  • (Boolean)


176
177
178
179
180
181
# File 'lib/moxml/adapter/leptris.rb', line 176

def has_declaration?(native_doc, _wrapper)
  return true if attachments.get(native_doc, :declaration)

  attachments.key?(native_doc, :had_source_declaration) &&
    attachments.get(native_doc, :had_source_declaration)
end

.inner_text(node) ⇒ Object



536
537
538
539
540
541
542
543
544
545
546
547
548
# File 'lib/moxml/adapter/leptris.rb', line 536

def inner_text(node)
  # moxml semantic: direct text children only — no descendant
  # text (that is #text), no comments. Entity references
  # contribute their serialized form.
  children(node).filter_map do |child|
    case child
    when CustomizedLeptris::EntityReference then "&#{child.name};"
    when ::Leptris::XML::CDATA then child.content
    when ::Leptris::XML::Text, CustomizedLeptris::TextSegment
      child.content.to_s.dup.force_encoding("UTF-8")
    end
  end.join
end

.line_number(node) ⇒ Object



389
390
391
392
393
394
# File 'lib/moxml/adapter/leptris.rb', line 389

def line_number(node)
  return nil unless node.is_a?(::Leptris::XML::Node)

  line = node.line
  line.zero? ? nil : line
end

.namespace(node) ⇒ Object



228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/moxml/adapter/leptris.rb', line 228

def namespace(node)
  # The binding resolves Attr#namespace to the declaration but
  # without the prefix; when the qualified name carries one,
  # prefer the in-scope declaration that binds it so wrappers
  # keep prefix and uri.
  if node.is_a?(::Leptris::XML::Attr) &&
      (prefix = node.prefix || prefix_part(node.name))
    resolved = resolve_prefix_ns(node.element, prefix)
    return resolved if resolved
  end

  ns = node.namespace
  return ns unless ns.nil?

  # Set-side namespaces (created attributes, renamed elements)
  # carry a prefix the native resolver did not bind; resolve
  # through the scope chain so wrapper-level access stays
  # XML-correct.
  owner = node.is_a?(::Leptris::XML::Attr) ? node.element : node
  prefix = if node.is_a?(::Leptris::XML::Attr)
             node.prefix || prefix_part(node.name)
           else
             prefix_part(node.name)
           end
  return nil if prefix.nil?

  resolve_prefix_ns(owner, prefix)
end

.namespace_definitions(element) ⇒ Object



598
599
600
# File 'lib/moxml/adapter/leptris.rb', line 598

def namespace_definitions(element)
  element.namespace_definitions
end

.namespace_prefix(namespace) ⇒ Object



583
584
585
586
587
588
589
590
# File 'lib/moxml/adapter/leptris.rb', line 583

def namespace_prefix(namespace)
  # Attr#namespace is the bare URI string in leptris 1.9+ (the
  # C model: a namespace handle IS the URI); attributes carry
  # their prefix on the Attr itself.
  return nil if namespace.is_a?(String)

  namespace.prefix
end

.namespace_uri(namespace) ⇒ Object



592
593
594
595
596
# File 'lib/moxml/adapter/leptris.rb', line 592

def namespace_uri(namespace)
  return namespace if namespace.is_a?(String)

  namespace.href
end

.native_context_node?(node) ⇒ Boolean

Returns:

  • (Boolean)


679
680
681
682
# File 'lib/moxml/adapter/leptris.rb', line 679

def native_context_node?(node)
  node.is_a?(::Leptris::XML::Document) ||
    node.is_a?(::Leptris::XML::Element)
end

.native_expression?(expression) ⇒ Boolean

Document-context queries without variable references, attribute-node results, or the nokogiri-compat xmlns: reserved prefix convention.

Returns:

  • (Boolean)


703
704
705
706
707
708
709
710
711
712
713
714
# File 'lib/moxml/adapter/leptris.rb', line 703

def native_expression?(expression)
  NATIVE_GATE_CACHE.get_or_set(expression) do
    ast = XPath::Parser.parse_with_cache(expression)
    next false if ast_contains_type?(ast, :variable)
    next false if uses_xmlns_prefix?(ast)
    next false if prefixed_attribute_test?(ast)

    !selects_attribute_results?(ast)
  end
rescue XPath::SyntaxError
  false
end

.native_xpath(node, expression, namespaces, first_only: false) ⇒ Array, ...

Returns native results, or nil when the query must run on the Ruby engine.

Returns:

  • (Array, Object, nil)

    native results, or nil when the query must run on the Ruby engine



645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
# File 'lib/moxml/adapter/leptris.rb', line 645

def native_xpath(node, expression, namespaces, first_only: false)
  return nil unless native_context_node?(node)
  return nil unless native_expression?(expression)
  # The binding reports the root element parentless while moxml
  # roots it at the document, so parent-axis queries from the
  # root element keep the Ruby engine.
  if node.is_a?(::Leptris::XML::Element) &&
      node.document&.root.equal?(node) &&
      expression_uses_parent_axis?(expression)
    return nil
  end

  compiled = NATIVE_XPATH_CACHE.get_or_set(expression) do
    ::Leptris::XML::XPath.compile(expression)
  end
  result = if namespaces && !namespaces.empty?
             compiled.eval(node, namespaces)
           else
             compiled.eval(node)
           end
  case result
  when ::Leptris::XML::NodeSet
    nodes = result.to_a
    first_only ? nodes.first : nodes
  else
    result
  end
rescue ::Leptris::XML::XPathError
  # Not supported by the native engine — the Ruby engine is a
  # full XPath 1.0 implementation, including Moxml's syntax
  # errors for invalid expressions.
  nil
end

.next_sibling(node) ⇒ Object



369
370
371
# File 'lib/moxml/adapter/leptris.rb', line 369

def next_sibling(node)
  node.next_sibling if node.is_a?(::Leptris::XML::Node)
end

.node_name(node) ⇒ Object



299
300
301
302
303
304
# File 'lib/moxml/adapter/leptris.rb', line 299

def node_name(node)
  return node.root_name if node.is_a?(::Leptris::XML::DocType)
  return node.target if node.is_a?(CustomizedLeptris::DocumentPI)

  node.name.to_s.dup.force_encoding("UTF-8")
end

.node_type(node) ⇒ Object



279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/moxml/adapter/leptris.rb', line 279

def node_type(node)
  # Frequency-ordered: elements and text dominate every real
  # document, and Node.wrap dispatches here once per cold
  # wrap. CDATA must precede Text (CDATA < Text in the
  # binding).
  case node
  when ::Leptris::XML::Element then :element
  when ::Leptris::XML::CDATA then :cdata
  when ::Leptris::XML::Text, CustomizedLeptris::TextSegment then :text
  when ::Leptris::XML::Attr then :attribute
  when ::Leptris::XML::Comment then :comment
  when ::Leptris::XML::ProcessingInstruction, CustomizedLeptris::DocumentPI then :processing_instruction
  when ::Leptris::XML::Document then :document
  when ::Leptris::XML::DocType, CustomizedLeptris::Doctype then :doctype
  when CustomizedLeptris::Declaration then :declaration
  when CustomizedLeptris::EntityReference then :entity_reference
  else :unknown
  end
end

.parent(node) ⇒ Object



356
357
358
359
360
361
362
363
364
365
366
367
# File 'lib/moxml/adapter/leptris.rb', line 356

def parent(node)
  case node
  when ::Leptris::XML::Document then nil
  when CustomizedLeptris::Declaration, CustomizedLeptris::Doctype,
       CustomizedLeptris::DocumentPI then node.parent_doc
  when CustomizedLeptris::TextSegment, CustomizedLeptris::EntityReference then node.parent
  else
    # The binding reports the root element as parentless; the
    # moxml contract roots at the document.
    node.parent || (node.document&.root == node ? node.document : nil)
  end
end

.parse(xml, options = {}, _context = nil) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/moxml/adapter/leptris.rb', line 72

def parse(xml, options = {}, _context = nil)
  xml_string = xml.is_a?(IO) || xml.is_a?(StringIO) ? xml.read : xml.to_s
  # The marker flag rides preprocess's own `&` scan — no
  # second full-buffer probe (issue #132 parse-side note).
  processed, entity_markers = Entity.preprocess_with_marker_flag(xml_string)

  # readonly: true (issue #133): the binding memoizes reads and
  # refuses mutations — the parse-and-read lifecycle for
  # multi-pass consumers (comparison, diff, signature).
  # dtdattr: true opts into DTD ATTLIST default materialization
  # (off by default since libleptris 1.9.8, matching libxml2).
  native_doc = begin
    ::Leptris::XML::Document.parse(
      processed,
      readonly: options[:readonly] == true,
      options: dtdattr_parse_options(options),
    )
  rescue ::Leptris::XML::ParseError => e
    # libleptris has no recovery mode that survives unclosed
    # tags; non-strict callers get an empty document, matching
    # the Libxml adapter's non-strict behavior. The fatal
    # error rides the document as parse diagnostics (issue
    # #147) — otherwise nothing says why it came back empty.
    raise Moxml::ParseError.new(e.message) if options[:strict]

    recover_errors = [e.message]
    create_document
  end
  ctx = _context || Context.new(:leptris)
  doc = Document.new(native_doc, ctx)

  record_source_declaration(native_doc, processed)
  attachments.set(native_doc, :entity_markers, entity_markers)
  attachments.set(native_doc, :parse_errors, recover_errors) if recover_errors

  doc
end

.parse_errors(native_doc) ⇒ Object



118
119
120
# File 'lib/moxml/adapter/leptris.rb', line 118

def parse_errors(native_doc)
  attachments.get(native_doc, :parse_errors) || NO_PARSE_ERRORS
end

.prefix_part(name) ⇒ Object



271
272
273
# File 'lib/moxml/adapter/leptris.rb', line 271

def prefix_part(name)
  name.include?(":") ? name.split(":", 2)[0] : nil
end

.prefixed_attribute_test?(ast, parent_axis = nil) ⇒ Boolean

Some released native engines do not match prefixed attribute tests inside predicates (@p:kind='a'); the Ruby engine does. An attribute test is a :test whose parent axis is "attribute"; bare ones (namespace nil) stay native.

Returns:

  • (Boolean)


752
753
754
755
756
757
758
759
760
761
762
763
764
# File 'lib/moxml/adapter/leptris.rb', line 752

def prefixed_attribute_test?(ast, parent_axis = nil)
  if ast.type == :test && parent_axis == "attribute"
    ns = ast.value[:namespace]
    return true if ns && !ns.empty? && ns != "xmlns"
  end

  axis = ast.children.first if ast.type == :axis

  ast.children.any? do |child|
    child.is_a?(XPath::AST::Node) &&
      prefixed_attribute_test?(child, axis || (child.type == :axis ? nil : parent_axis))
  end
end

.previous_sibling(node) ⇒ Object



373
374
375
# File 'lib/moxml/adapter/leptris.rb', line 373

def previous_sibling(node)
  node.previous_sibling if node.is_a?(::Leptris::XML::Node)
end

.processing_instruction_content(node) ⇒ Object



575
576
577
# File 'lib/moxml/adapter/leptris.rb', line 575

def processing_instruction_content(node)
  node.content
end

.processing_instruction_target(node) ⇒ Object



275
276
277
# File 'lib/moxml/adapter/leptris.rb', line 275

def processing_instruction_target(node)
  node.target
end

.remove(node) ⇒ Object



478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
# File 'lib/moxml/adapter/leptris.rb', line 478

def remove(node)
  case node
  when CustomizedLeptris::Declaration
    remove_declaration(node.parent_doc) if node.parent_doc
  when CustomizedLeptris::Doctype
    attachments.delete(node.parent_doc, :doctype) if node.parent_doc
  when CustomizedLeptris::EntityReference
    marker_text_for(node.parent, node.name)&.unlink
  when CustomizedLeptris::DocumentPI
    raise Moxml::NotImplementedError.new(
      "libleptris has no document-level PI removal",
      adapter: :leptris,
      feature: :remove,
    )
  else
    node.unlink
  end
end

.remove_attribute(element, name) ⇒ Object



439
440
441
# File 'lib/moxml/adapter/leptris.rb', line 439

def remove_attribute(element, name)
  element.remove_attribute(name.to_s)
end

.remove_attribute_native(attr) ⇒ Object



443
444
445
446
# File 'lib/moxml/adapter/leptris.rb', line 443

def remove_attribute_native(attr)
  attr.element.remove_attribute(attr.name)
  attr
end

.remove_declaration(native_doc) ⇒ Object



183
184
185
186
# File 'lib/moxml/adapter/leptris.rb', line 183

def remove_declaration(native_doc)
  attachments.delete(native_doc, :declaration)
  attachments.delete(native_doc, :had_source_declaration)
end

.replace(node, new_node) ⇒ Object



497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
# File 'lib/moxml/adapter/leptris.rb', line 497

def replace(node, new_node)
  return node.replace(new_node) if node.is_a?(::Leptris::XML::Element)

  # libleptris only offers element-anchored insertion, so a
  # content node (text/comment/CDATA/PI) is replaced by
  # unlinking and re-inserting: after an element sibling when
  # one exists, else appended (end-of-list) to the parent.
  parent = node.parent
  unless parent
    raise Moxml::DocumentStructureError.new(
      "cannot replace a detached node",
    )
  end

  prev = node.previous_sibling
  node.unlink
  if prev.is_a?(::Leptris::XML::Element)
    prev.add_next_sibling(new_node)
  else
    parent.add_child(new_node)
  end
  new_node
end

.replace_children(node, new_children) ⇒ Object



521
522
523
# File 'lib/moxml/adapter/leptris.rb', line 521

def replace_children(node, new_children)
  node.children = new_children
end

.resolve_prefix_ns(owner, prefix) ⇒ Object

Nearest in-scope declaration of prefix, walking owner then ancestors. Unbound prefix → nil. Returns the Namespace object so wrappers keep prefix and uri.



260
261
262
263
264
265
266
267
268
269
# File 'lib/moxml/adapter/leptris.rb', line 260

def resolve_prefix_ns(owner, prefix)
  current = owner
  while current.is_a?(::Leptris::XML::Element)
    hit = current.namespace_definitions.find { |ns| ns.prefix == prefix }
    return hit if hit

    current = current.parent
  end
  nil
end

.root(document) ⇒ Object



385
386
387
# File 'lib/moxml/adapter/leptris.rb', line 385

def root(document)
  document.root
end

.sax_parse(xml, handler) ⇒ Object



793
794
795
796
797
798
799
# File 'lib/moxml/adapter/leptris.rb', line 793

def sax_parse(xml, handler)
  bridge = LeptrisSAXBridge.new(handler)
  xml_string = xml.is_a?(IO) || xml.is_a?(::StringIO) ? xml.read : xml.to_s
  ::Leptris::XML::SAX::Parser.new(bridge).parse(xml_string)
rescue ::Leptris::XML::ParseError, ::Leptris::XML::Error => e
  handler.on_error(Moxml::ParseError.new(e.message))
end

.selects_attribute_results?(ast) ⇒ Boolean

Returns:

  • (Boolean)


735
736
737
738
739
740
741
742
743
744
745
746
# File 'lib/moxml/adapter/leptris.rb', line 735

def selects_attribute_results?(ast)
  case ast.type
  when :pipe, :union, :filter_expr
    ast.children.any? { |child| selects_attribute_results?(child) }
  when :absolute_path, :relative_path
    step = ast.children.last
    step = step.children.first if step.type == :step_with_predicates
    step.type == :axis && step.children.first == "attribute"
  else
    false
  end
end

.set_attribute(element, name, value) ⇒ Object



412
413
414
# File 'lib/moxml/adapter/leptris.rb', line 412

def set_attribute(element, name, value)
  element[name.to_s] = value.to_s
end

.set_attribute_name(attr, name) ⇒ Object



416
417
418
419
420
421
422
423
424
# File 'lib/moxml/adapter/leptris.rb', line 416

def set_attribute_name(attr, name)
  # Attr is an immutable value object; renames go through the
  # element and yield a fresh native, which the wrapper adopts.
  element = attr.element
  value = attr.value
  element.remove_attribute(attr.name)
  element[name.to_s] = value
  element.attribute_nodes.reverse.find { |candidate| candidate.name == name.to_s }
end

.set_attribute_namespace(attr, namespace) ⇒ Object

Attr is an immutable value object: namespace changes go through the owning element, recreating the attribute with a qualified name, and yield a fresh native for the wrapper.



213
214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'lib/moxml/adapter/leptris.rb', line 213

def set_attribute_namespace(attr, namespace)
  element = attr.element
  local = attr.name.include?(":") ? attr.name.split(":", 2)[1] : attr.name
  value = attr.value
  element.remove_attribute(attr.name)
  prefix = namespace.is_a?(String) ? nil : namespace.prefix
  uri = namespace.is_a?(String) ? namespace : namespace.href
  qualified = prefix.nil? || prefix.empty? ? local : "#{prefix}:#{local}"
  element[qualified] = value
  if prefix && !prefix.empty? && !uri.to_s.empty? && !resolve_prefix_ns(element, prefix)
    element.add_namespace_definition(prefix, uri.to_s)
  end
  element.attribute_nodes.reverse.find { |candidate| candidate.name == qualified }
end

.set_attribute_value(attr, value) ⇒ Object



426
427
428
429
# File 'lib/moxml/adapter/leptris.rb', line 426

def set_attribute_value(attr, value)
  attr.value = value.to_s
  attr
end

.set_cdata_content(node, content) ⇒ Object



563
564
565
# File 'lib/moxml/adapter/leptris.rb', line 563

def set_cdata_content(node, content)
  node.content = content.to_s
end

.set_comment_content(node, content) ⇒ Object



571
572
573
# File 'lib/moxml/adapter/leptris.rb', line 571

def set_comment_content(node, content)
  node.content = content.to_s
end

.set_declaration_attribute(declaration, attr_name, value) ⇒ Object



167
168
169
# File 'lib/moxml/adapter/leptris.rb', line 167

def set_declaration_attribute(declaration, attr_name, value)
  declaration.public_send("#{attr_name}=", value) if attr_matches?(attr_name)
end

.set_namespace(node, namespace) ⇒ Object



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/moxml/adapter/leptris.rb', line 192

def set_namespace(node, namespace)
  return set_attribute_namespace(node, namespace) if node.is_a?(::Leptris::XML::Attr)

  element = node
  prefix = namespace.is_a?(String) ? nil : namespace.prefix
  uri = namespace.is_a?(String) ? namespace : namespace.href
  if prefix.nil? || prefix.empty?
    element.default_namespace = uri.to_s
    # Drop any prefix from the element name: a default namespace
    # never applies to a prefixed name.
    element.name = element.name.split(":", 2)[-1] if element.name.include?(":")
  else
    element.add_namespace_definition(prefix, uri.to_s)
    element.name = "#{prefix}:#{element.name.split(':', 2)[-1]}"
  end
  element
end

.set_node_name(node, name) ⇒ Object



306
307
308
309
310
311
# File 'lib/moxml/adapter/leptris.rb', line 306

def set_node_name(node, name)
  case node
  when ::Leptris::XML::ProcessingInstruction, CustomizedLeptris::DocumentPI then node.target = name
  else node.name = name
  end
end

.set_processing_instruction_content(node, content) ⇒ Object



579
580
581
# File 'lib/moxml/adapter/leptris.rb', line 579

def set_processing_instruction_content(node, content)
  node.data = content.to_s
end

.set_root(doc, element) ⇒ Object



68
69
70
# File 'lib/moxml/adapter/leptris.rb', line 68

def set_root(doc, element)
  doc.root = element
end

.set_text_content(node, content) ⇒ Object



550
551
552
553
554
555
556
557
# File 'lib/moxml/adapter/leptris.rb', line 550

def set_text_content(node, content)
  case node
  when ::Leptris::XML::Document
    node.root&.content = content.to_s
  else
    node.content = content.to_s
  end
end

.text_content(node) ⇒ Object



525
526
527
528
529
530
531
532
533
534
# File 'lib/moxml/adapter/leptris.rb', line 525

def text_content(node)
  case node
  when ::Leptris::XML::Document then node.root ? node.root.content : ""
  when CustomizedLeptris::Declaration, CustomizedLeptris::Doctype,
       CustomizedLeptris::EntityReference
    ""
  when CustomizedLeptris::TextSegment then node.content
  else node.content.to_s
  end
end

.uses_xmlns_prefix?(ast) ⇒ Boolean

xmlns:name is a nokogiri-compat convention addressing elements in the default namespace; only the Ruby engine implements it.

Returns:

  • (Boolean)


727
728
729
730
731
732
733
# File 'lib/moxml/adapter/leptris.rb', line 727

def uses_xmlns_prefix?(ast)
  return true if ast.type == :test && ast.value[:namespace] == "xmlns"

  ast.children.any? do |child|
    child.is_a?(XPath::AST::Node) && uses_xmlns_prefix?(child)
  end
end

.xpath(node, expression, namespaces = {}) ⇒ Object



628
629
630
631
632
633
# File 'lib/moxml/adapter/leptris.rb', line 628

def xpath(node, expression, namespaces = {})
  native = native_xpath(node, expression, namespaces)
  return native unless native.nil?

  engine_xpath(node, expression, namespaces)
end