Class: Moxml::Adapter::Leptris

Inherits:
Base
  • Object
show all
Defined in:
lib/moxml/adapter/leptris.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

Classes: LeptrisSAXBridge

Constant Summary collapse

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)
LITERAL_REGIONS =

moxml canonical serialization: apostrophes stay literal (only & < > " are escaped) and empty elements expand when the caller asked for it — matching the other adapters' contract. Runs segment-aware: CDATA content is literal and must not be touched. Regions whose content is literal and must never be rewritten. Scanned positionally (String#index), not with a regex: the scan is linear in the input length, so pathological document content cannot blow up the serializer.

{
  "<!--" => "-->",
  "<![CDATA[" => "]]>",
  "<?" => "?>",
}.freeze
EMPTY_ELEMENT_RE =

All quantifiers are possessive and the bare-part class excludes "/" and ">": the possessive groups can never consume the closing delimiter, so no backtracking is possible and the match is linear even on malformed tags.

%r{<([A-Za-z_][\w.:-]*+)((?:"[^"]*+"|'[^']*+'|[^<>"'/]++)*+)/>}

Class Method Summary collapse

Methods inherited from Base

actual_native, create_cdata, create_comment, create_declaration, create_doctype, create_element, create_entity_reference, create_namespace, create_processing_instruction, create_text, decode_entities, in_scope_namespaces, 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



509
510
511
512
513
514
515
516
517
518
519
520
521
522
# File 'lib/moxml/adapter/leptris.rb', line 509

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



535
536
537
# File 'lib/moxml/adapter/leptris.rb', line 535

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

.add_previous_sibling(node, new_node) ⇒ Object



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

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)


776
777
778
779
780
781
782
# File 'lib/moxml/adapter/leptris.rb', line 776

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



696
697
698
699
700
701
702
# File 'lib/moxml/adapter/leptris.rb', line 696

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



23
24
25
# File 'lib/moxml/adapter/leptris.rb', line 23

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

.attr_matches?(attr_name) ⇒ Boolean

Returns:

  • (Boolean)


108
109
110
# File 'lib/moxml/adapter/leptris.rb', line 108

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

.attribute_element(attr) ⇒ Object



461
462
463
# File 'lib/moxml/adapter/leptris.rb', line 461

def attribute_element(attr)
  attr.element
end

.attribute_name(attr) ⇒ Object



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

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



457
458
459
# File 'lib/moxml/adapter/leptris.rb', line 457

def attributes(element)
  element.attribute_nodes
end

.bulk_materialize?Boolean

Bulk materialization (issue #132): leptris_node_traverse walks the subtree with one FFI call; the only per-node cost is the C->Ruby callback and the property reads below. No Moxml::Node or Attribute wrapper is allocated.

Returns:

  • (Boolean)


236
237
238
# File 'lib/moxml/adapter/leptris.rb', line 236

def bulk_materialize?
  true
end

.cdata_content(node) ⇒ Object



620
621
622
# File 'lib/moxml/adapter/leptris.rb', line 620

def cdata_content(node)
  node.content
end

.children(node) ⇒ Object



363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# File 'lib/moxml/adapter/leptris.rb', line 363

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



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

def comment_content(node)
  node.content
end

.contains_parent_axis?(ast) ⇒ Boolean

Returns:

  • (Boolean)


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

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



59
60
61
# File 'lib/moxml/adapter/leptris.rb', line 59

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

.create_native_cdata(content, owner_doc = nil) ⇒ Object



71
72
73
# File 'lib/moxml/adapter/leptris.rb', line 71

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

.create_native_comment(content, owner_doc = nil) ⇒ Object



75
76
77
# File 'lib/moxml/adapter/leptris.rb', line 75

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

.create_native_declaration(version, encoding, standalone) ⇒ Object



88
89
90
# File 'lib/moxml/adapter/leptris.rb', line 88

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

.create_native_doctype(name, external_id, system_id) ⇒ Object



84
85
86
# File 'lib/moxml/adapter/leptris.rb', line 84

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



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

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

.create_native_entity_reference(name) ⇒ Object



92
93
94
# File 'lib/moxml/adapter/leptris.rb', line 92

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

.create_native_namespace(element, prefix, uri) ⇒ Object



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

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

.create_native_processing_instruction(target, content) ⇒ Object



79
80
81
82
# File 'lib/moxml/adapter/leptris.rb', line 79

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



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

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

.declaration_attribute(declaration, attr_name) ⇒ Object



100
101
102
# File 'lib/moxml/adapter/leptris.rb', line 100

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

.default_declaration_xml(doc, options) ⇒ Object



984
985
986
987
988
# File 'lib/moxml/adapter/leptris.rb', line 984

def default_declaration_xml(doc, options)
  encoding = options[:encoding] || doc.encoding
  encoding = "UTF-8" if encoding.to_s.empty?
  XmlEmitter.declaration_xml("1.0", encoding, nil)
end

.doctype_external_id(node) ⇒ Object



667
668
669
# File 'lib/moxml/adapter/leptris.rb', line 667

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

.doctype_name(node) ⇒ Object



663
664
665
# File 'lib/moxml/adapter/leptris.rb', line 663

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

.doctype_system_id(node) ⇒ Object



671
672
673
# File 'lib/moxml/adapter/leptris.rb', line 671

def doctype_system_id(node)
  node.system_id
end

.document(node) ⇒ Object



438
439
440
441
442
443
444
# File 'lib/moxml/adapter/leptris.rb', line 438

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

.duplicate_node(node) ⇒ Object



348
349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/moxml/adapter/leptris.rb', line 348

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

.element_material_record(node, depth_memo) ⇒ Object



271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/moxml/adapter/leptris.rb', line 271

def element_material_record(node, depth_memo)
  attributes = node.each_attribute.map do |attr|
    # Local name + separate prefix, matching the generic
    # path's resolver semantics (moxml's canonical shape).
    name = attr.name
    prefix = attr.prefix
    name = name.split(":", 2)[1] || name if prefix
    [name, attr.value, attr.namespace_uri, prefix]
  end
  ns = node.namespace
  {
    kind: :element,
    qname: node.name,
    prefix: node.prefix,
    namespace_uri: ns&.href,
    attributes: attributes,
    text: nil,
    depth: material_depth(node, depth_memo),
  }
end

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



808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
# File 'lib/moxml/adapter/leptris.rb', line 808

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_bearing?(native) ⇒ Boolean

Marker presence is a document-level fact: parse records it, the ER builder path flips it, and the split/restore scans consult it. Customized natives only exist as split products of marker-bearing text, so they always report true.

Returns:

  • (Boolean)


220
221
222
223
224
225
226
227
228
229
230
# File 'lib/moxml/adapter/leptris.rb', line 220

def entity_bearing?(native)
  case native
  when CustomizedLeptris::Declaration, CustomizedLeptris::Doctype,
       CustomizedLeptris::EntityReference, CustomizedLeptris::TextSegment,
       CustomizedLeptris::DocumentPI
    true
  else
    doc = native.document
    doc.nil? || attachments.get(doc, :entity_markers) != false
  end
end

.entity_reference_name(node) ⇒ Object



96
97
98
# File 'lib/moxml/adapter/leptris.rb', line 96

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

.expression_uses_parent_axis?(expression) ⇒ Boolean

Returns:

  • (Boolean)


745
746
747
748
749
750
# File 'lib/moxml/adapter/leptris.rb', line 745

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



492
493
494
# File 'lib/moxml/adapter/leptris.rb', line 492

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

.get_attribute_value(element, name) ⇒ Object



496
497
498
# File 'lib/moxml/adapter/leptris.rb', line 496

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

.has_declaration?(native_doc, _wrapper) ⇒ Boolean

Returns:

  • (Boolean)


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

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



597
598
599
600
601
602
603
604
605
606
607
608
609
# File 'lib/moxml/adapter/leptris.rb', line 597

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



450
451
452
453
454
455
# File 'lib/moxml/adapter/leptris.rb', line 450

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

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

.marker_text_for(parent, name) ⇒ Object



990
991
992
993
994
995
996
997
# File 'lib/moxml/adapter/leptris.rb', line 990

def marker_text_for(parent, name)
  return nil unless parent.is_a?(::Leptris::XML::Element)

  marker = "#{Entity::MARKER}#{name};"
  parent.children.to_a.find do |child|
    child.is_a?(::Leptris::XML::Text) && child.content == marker
  end
end

.material_depth(node, memo) ⇒ Object

Binding wrappers are address-stable and #parent is memoized, so each edge is fetched once; depths resolve through the identity-keyed memo.



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

def material_depth(node, memo)
  memo[node] ||= begin
    parent = node.parent
    parent.nil? || parent.is_a?(::Leptris::XML::Document) ? 0 : material_depth(parent, memo) + 1
  end
end

.materialize_records(native, &block) ⇒ Object



240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/moxml/adapter/leptris.rb', line 240

def materialize_records(native, &block)
  doc = native.is_a?(::Leptris::XML::Document) ? native : native.document
  # Marker-bearing text needs the split pipeline (children-level
  # ER expansion); the bulk path has no marker handling.
  return nil if doc.nil? || attachments.get(doc, :entity_markers)

  root = native.is_a?(::Leptris::XML::Document) ? native.root : native
  return nil if root.nil?

  depth_memo = {}.compare_by_identity
  root.traverse do |node|
    record = case node
             when ::Leptris::XML::Element
               element_material_record(node, depth_memo)
             when ::Leptris::XML::CDATA
               # CDATA < Text in the binding: this arm must come
               # first or CDATA content reports as text.
               text_material_record(:cdata, node.content, node, depth_memo)
             when ::Leptris::XML::Text
               text_material_record(:text, node.content, node, depth_memo)
             when ::Leptris::XML::Comment
               text_material_record(:comment, node.content, node, depth_memo)
             when ::Leptris::XML::ProcessingInstruction
               text_material_record(:processing_instruction, node.content, node, depth_memo)
                 .merge(qname: node.target)
             end
    yield(record) if record
  end
  true
end

.namespace(node) ⇒ Object



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/moxml/adapter/leptris.rb', line 165

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



659
660
661
# File 'lib/moxml/adapter/leptris.rb', line 659

def namespace_definitions(element)
  element.namespace_definitions
end

.namespace_prefix(namespace) ⇒ Object



644
645
646
647
648
649
650
651
# File 'lib/moxml/adapter/leptris.rb', line 644

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



653
654
655
656
657
# File 'lib/moxml/adapter/leptris.rb', line 653

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

  namespace.href
end

.native_context_node?(node) ⇒ Boolean

Returns:

  • (Boolean)


740
741
742
743
# File 'lib/moxml/adapter/leptris.rb', line 740

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

.native_doctype_xml(doc) ⇒ Object



999
1000
1001
1002
1003
1004
# File 'lib/moxml/adapter/leptris.rb', line 999

def native_doctype_xml(doc)
  dt = doc.doctype
  return nil unless dt

  XmlEmitter.doctype_xml(dt.root_name, dt.public_id, dt.system_id)
end

.native_expression?(expression) ⇒ Boolean

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

Returns:

  • (Boolean)


764
765
766
767
768
769
770
771
772
773
774
# File 'lib/moxml/adapter/leptris.rb', line 764

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)

    !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



706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
# File 'lib/moxml/adapter/leptris.rb', line 706

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_literal_region(xml, from) ⇒ Object

Nearest literal region at/after from: [position, terminator].



912
913
914
915
916
917
918
919
920
921
922
923
924
925
# File 'lib/moxml/adapter/leptris.rb', line 912

def next_literal_region(xml, from)
  best = nil
  best_terminator = nil
  LITERAL_REGIONS.each do |opener, terminator|
    idx = xml.index(opener, from)
    next if idx.nil?

    if best.nil? || idx < best
      best = idx
      best_terminator = terminator
    end
  end
  best.nil? ? nil : [best, best_terminator]
end

.next_sibling(node) ⇒ Object



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

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

.node_name(node) ⇒ Object



334
335
336
337
338
339
# File 'lib/moxml/adapter/leptris.rb', line 334

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



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# File 'lib/moxml/adapter/leptris.rb', line 314

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

.normalize_markup(markup, needs_apos, needs_expand) ⇒ Object



939
940
941
942
943
944
945
946
947
# File 'lib/moxml/adapter/leptris.rb', line 939

def normalize_markup(markup, needs_apos, needs_expand)
  markup = markup.gsub("&apos;", "'") if needs_apos
  if needs_expand
    markup = markup.gsub(EMPTY_ELEMENT_RE) do
      "<#{Regexp.last_match(1)}#{Regexp.last_match(2)}></#{Regexp.last_match(1)}>"
    end
  end
  markup
end

.normalize_serialization(xml, options) ⇒ Object



887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
# File 'lib/moxml/adapter/leptris.rb', line 887

def normalize_serialization(xml, options)
  needs_apos = xml.include?("&apos;")
  needs_expand = options[:expand_empty] && xml.include?("/>")
  return xml unless needs_apos || needs_expand

  out = +""
  pos = 0
  while pos < xml.length
    opener_at, terminator = next_literal_region(xml, pos)
    if opener_at.nil?
      out << normalize_markup(xml[pos..], needs_apos, needs_expand)
      break
    end

    out << normalize_markup(xml[pos...opener_at], needs_apos, needs_expand)
    search_from = opener_at + opener_at_offset(terminator)
    close = xml.index(terminator, search_from)
    close_end = close.nil? ? xml.length : close + terminator.length
    out << xml[opener_at...close_end]
    pos = close_end
  end
  out
end

.opener_at_offset(terminator) ⇒ Object

Search for a terminator past its opener's overlap-safe offset ("-->" cannot start inside "<!--").



929
930
931
# File 'lib/moxml/adapter/leptris.rb', line 929

def opener_at_offset(terminator)
  terminator == "-->" ? 4 : 0
end

.parent(node) ⇒ Object



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

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



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/moxml/adapter/leptris.rb', line 31

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).
  native_doc = begin
    ::Leptris::XML::Document.parse(processed, readonly: options[:readonly] == true)
  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.
    raise Moxml::ParseError.new(e.message) if options[:strict]

    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)

  doc
end

.prefix_part(name) ⇒ Object



208
209
210
# File 'lib/moxml/adapter/leptris.rb', line 208

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

.previous_sibling(node) ⇒ Object



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

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

.processing_instruction_content(node) ⇒ Object



636
637
638
# File 'lib/moxml/adapter/leptris.rb', line 636

def processing_instruction_content(node)
  node.content
end

.processing_instruction_target(node) ⇒ Object



212
213
214
# File 'lib/moxml/adapter/leptris.rb', line 212

def processing_instruction_target(node)
  node.target
end

.raw_serialize(node, options) ⇒ Object



842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
# File 'lib/moxml/adapter/leptris.rb', line 842

def raw_serialize(node, options)
  # CDATA must precede Text in this chain: CDATA < Text in the
  # binding, so a Text branch first would swallow CDATA nodes.
  case node
  when CustomizedLeptris::Declaration, CustomizedLeptris::Doctype,
       CustomizedLeptris::EntityReference, CustomizedLeptris::DocumentPI
    return node.to_xml
  when ::Leptris::XML::CDATA
    return XmlEmitter.cdata(node.content)
  when ::Leptris::XML::Comment
    return "<!--#{node.content}-->"
  when ::Leptris::XML::ProcessingInstruction
    content = node.content.to_s
    return content.empty? ? "<?#{node.target}?>" : "<?#{node.target} #{content}?>"
  when ::Leptris::XML::Text, CustomizedLeptris::TextSegment
    return XmlEmitter.escape_text(node.content.to_s)
  when ::Leptris::XML::Document
    return serialize_document(node, options)
  end

  include_decl = options.fetch(:declaration) do
    options[:no_declaration] ? false : document_has_declaration?(node)
  end
  node.to_xml(
    indent: options.fetch(:indent, 0),
    no_decl: !include_decl,
    encoding: options[:encoding],
  )
end

.remove(node) ⇒ Object



539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
# File 'lib/moxml/adapter/leptris.rb', line 539

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



500
501
502
# File 'lib/moxml/adapter/leptris.rb', line 500

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

.remove_attribute_native(attr) ⇒ Object



504
505
506
507
# File 'lib/moxml/adapter/leptris.rb', line 504

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

.remove_declaration(native_doc) ⇒ Object



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

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

.replace(node, new_node) ⇒ Object



558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
# File 'lib/moxml/adapter/leptris.rb', line 558

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



582
583
584
# File 'lib/moxml/adapter/leptris.rb', line 582

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.



197
198
199
200
201
202
203
204
205
206
# File 'lib/moxml/adapter/leptris.rb', line 197

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



446
447
448
# File 'lib/moxml/adapter/leptris.rb', line 446

def root(document)
  document.root
end

.sax_parse(xml, handler) ⇒ Object



1006
1007
1008
1009
1010
1011
1012
# File 'lib/moxml/adapter/leptris.rb', line 1006

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)


795
796
797
798
799
800
801
802
803
804
805
806
# File 'lib/moxml/adapter/leptris.rb', line 795

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

.serialize(node, options = {}) ⇒ Object



835
836
837
838
839
840
# File 'lib/moxml/adapter/leptris.rb', line 835

def serialize(node, options = {})
  # Entity restoration belongs to the wrapper layer
  # (Node#to_xml runs adapter.restore_entities for every
  # adapter); doing it here scanned the output a second time.
  normalize_serialization(raw_serialize(node, options), options)
end

.serialize_document(doc, options) ⇒ Object

Documents compose from their parts: the native serializer only walks the root subtree, so declaration, DOCTYPE, PIs and document-level text are assembled around it explicitly.



952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
# File 'lib/moxml/adapter/leptris.rb', line 952

def serialize_document(doc, options)
  # Nokogiri's document shape: every top-level part is
  # newline-terminated, at any indent — declaration, DOCTYPE,
  # document PIs, the root element, trailing newline after it.
  # Document-level text is content, not structure: no added
  # newline.
  parts = []

  include_decl = !options[:no_declaration] && options.fetch(:declaration) do
    document_has_declaration?(doc)
  end
  if include_decl
    declaration = attachments.get(doc, :declaration)
    parts << (declaration ? declaration.to_xml : default_declaration_xml(doc, options)) << "\n"
  end

  doctype = attachments.get(doc, :doctype)
  parts << doctype.to_xml << "\n" if doctype

  native = native_doctype_xml(doc)
  parts << native << "\n" if native

  document_pi_nodes(doc).each { |pi| parts << pi.to_xml << "\n" }

  parts << raw_serialize(doc.root, options) << "\n" if doc.root

  texts = attachments.get(doc, :document_text)
  texts&.each { |text| parts << XmlEmitter.escape_text(text.content.to_s) }

  parts.join
end

.set_attribute(element, name, value) ⇒ Object



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

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

.set_attribute_name(attr, name) ⇒ Object



477
478
479
480
481
482
483
484
485
# File 'lib/moxml/adapter/leptris.rb', line 477

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.



150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/moxml/adapter/leptris.rb', line 150

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



487
488
489
490
# File 'lib/moxml/adapter/leptris.rb', line 487

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

.set_cdata_content(node, content) ⇒ Object



624
625
626
# File 'lib/moxml/adapter/leptris.rb', line 624

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

.set_comment_content(node, content) ⇒ Object



632
633
634
# File 'lib/moxml/adapter/leptris.rb', line 632

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

.set_declaration_attribute(declaration, attr_name, value) ⇒ Object



104
105
106
# File 'lib/moxml/adapter/leptris.rb', line 104

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



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/moxml/adapter/leptris.rb', line 129

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



341
342
343
344
345
346
# File 'lib/moxml/adapter/leptris.rb', line 341

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



640
641
642
# File 'lib/moxml/adapter/leptris.rb', line 640

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

.set_root(doc, element) ⇒ Object



27
28
29
# File 'lib/moxml/adapter/leptris.rb', line 27

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

.set_text_content(node, content) ⇒ Object



611
612
613
614
615
616
617
618
# File 'lib/moxml/adapter/leptris.rb', line 611

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

.split_entity_markers(natives, parent) ⇒ Object

Expand marker-bearing text nodes into the child sequence the moxml contract exposes: text, EntityReference, text, ...



393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
# File 'lib/moxml/adapter/leptris.rb', line 393

def split_entity_markers(natives, parent)
  result = []
  natives.each do |child|
    # FFI Text#content returns a fresh unfrozen BINARY string:
    # retag in place (dup would be a throwaway allocation), but
    # before include? — BINARY.include? with the UTF-8 marker raises
    if child.is_a?(::Leptris::XML::Text)
      content = child.content
      content.force_encoding("UTF-8")
    end
    if content&.include?(Entity::MARKER)
      content.scan(/([^#{Entity::MARKER}]*)(?:#{Entity::MARKER}([\w.:-]+);)?/o) do
        text_part = Regexp.last_match(1)
        name = Regexp.last_match(2)
        result << CustomizedLeptris::TextSegment.new(text_part, parent) unless text_part.empty?
        result << CustomizedLeptris::EntityReference.new(name) if name
      end
    else
      result << child
    end
  end
  result
end

.text_content(node) ⇒ Object



586
587
588
589
590
591
592
593
594
595
# File 'lib/moxml/adapter/leptris.rb', line 586

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

.text_material_record(kind, text, node, depth_memo) ⇒ Object



292
293
294
295
296
297
298
299
300
301
302
# File 'lib/moxml/adapter/leptris.rb', line 292

def text_material_record(kind, text, node, depth_memo)
  {
    kind: kind,
    qname: nil,
    prefix: nil,
    namespace_uri: nil,
    attributes: Materializer::EMPTY_ATTRIBUTES,
    text: text,
    depth: material_depth(node, depth_memo),
  }
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)


787
788
789
790
791
792
793
# File 'lib/moxml/adapter/leptris.rb', line 787

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



689
690
691
692
693
694
# File 'lib/moxml/adapter/leptris.rb', line 689

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

  engine_xpath(node, expression, namespaces)
end