blib/lib/HTML/Object/XPath/Step.pm untested

filter: Statementstmt 0.0% 0 / 313 Branchbran 0.0% 0 / 148 Conditioncond 0.0% 0 / 62 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 42 Podpod 0.0% 0 / 34 totaltotal 0.0% 0 / 599 CC 75 SCAR 46.6
CC
75
Cov
0%
node_test
462.0
as_string
72.0
as_xml
72.0
CRAP 105.7
1 ##----------------------------------------------------------------------------
2 ## HTML Object - ~/lib/HTML/Object/XPath/Step.pm
3 ## Version v0.2.0
4 ## Copyright(c) 2021 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <jack@deguest.jp>
6 ## Created 2021/12/05
7 ## Modified 2022/09/18
8 ## All rights reserved.
9 ##
10 ##
11 ## This program is free software; you can redistribute it and/or modify it
12 ## under the same terms as Perl itself.
13 ##----------------------------------------------------------------------------
14 package HTML::Object::XPath::Step;
15 BEGIN
16 {
17 use strict;
18 use warnings;
19 warnings::register_categories( 'HTML::Object' );
20 use parent qw( Module::Generic );
21 use vars qw( $BASE_CLASS $DEBUG $VERSION );
22 use constant {
23 # Full name
24 TEST_QNAME => 0,
25 # NCName:*
26 TEST_NCWILD => 1,
27 # *
28 TEST_ANY => 2,
29 # @ns:attrib
30 TEST_ATTR_QNAME => 3,
31 # @nc:*
32 TEST_ATTR_NCWILD => 4,
33 # @*
34 TEST_ATTR_ANY => 5,
35 # comment()
36 TEST_NT_COMMENT => 6,
37 # text()
38 TEST_NT_TEXT => 7,
39 # processing-instruction()
40 TEST_NT_PI => 8,
41 # node()
42 TEST_NT_NODE => 9,
43 };
44 our $BASE_CLASS = 'HTML::Object::XPath';
45 our $DEBUG = 0;
46 our $VERSION = 'v0.2.0';
47 };
48  
49 use strict;
50 use warnings;
51  
52 sub init
53 {
54 my $self = shift( @_ );
55 # HTML::Object::XPath class
56 $self->{pp} = shift( @_ );
57 $self->{axis} = shift( @_ );
58 $self->{test} = shift( @_ );
59 $self->{literal} = shift( @_ );
60 $self->{predicates} = [];
61 $self->{axis_method} = 'axis_' . $self->{axis};
62 $self->{axis_method} =~ tr/-/_/;
63 # my( $pp, $axis, $test, $literal) = @_;
64 my $axis_method = "axis_$self->{axis}";
65 $axis_method =~ tr/-/_/;
66 $self->{_init_strict_use_sub} = 1;
67 $self->SUPER::init( @_ ) || return( $self->pass_error );
68 return( $self );
69 }
70  
71 sub as_string
72 {
73 my $self = shift( @_ );
74 my $string = $self->{axis} . '::';
75 my $test = $self->{test};
76 if( $test == TEST_NT_PI )
77 {
78 $string .= 'processing-instruction(';
79 if( $self->{literal}->value )
80 {
81 $string .= $self->{literal}->as_string;
82 }
83 $string .= ')';
84 }
85 elsif ($test == TEST_NT_COMMENT )
86 {
87 $string .= 'comment()';
88 }
89 elsif ($test == TEST_NT_TEXT )
90 {
91 $string .= 'text()';
92 }
93 elsif ($test == TEST_NT_NODE )
94 {
95 $string .= 'node()';
96 }
97 elsif ($test == TEST_NCWILD || $test == TEST_ATTR_NCWILD )
98 {
99 $string .= $self->{literal} . ':*';
100 }
101 else
102 {
103 $string .= $self->{literal};
104 }
105  
106 foreach( @{$self->{predicates}} )
107 {
108 next unless( defined( $_ ) );
109 $string .= '[' . $_->as_string . ']';
110 }
111 return( $string );
112 }
113  
114 sub as_xml
115 {
116 my $self = shift( @_ );
117 my $string = "<Step>\n";
118 $string .= "<Axis>" . $self->{axis} . "</Axis>\n";
119 my $test = $self->{test};
120  
121 $string .= "<Test>";
122  
123 if( $test == TEST_NT_PI )
124 {
125 $string .= '<processing-instruction';
126 if( $self->{literal}->value )
127 {
128 $string .= '>';
129 $string .= $self->{literal}->as_string;
130 $string .= '</processing-instruction>';
131 }
132 else
133 {
134 $string .= '/>';
135 }
136 }
137 elsif( $test == TEST_NT_COMMENT )
138 {
139 $string .= '<comment/>';
140 }
141 elsif( $test == TEST_NT_TEXT )
142 {
143 $string .= '<text/>';
144 }
145 elsif( $test == TEST_NT_NODE )
146 {
147 $string .= '<node/>';
148 }
149 elsif( $test == TEST_NCWILD || $test == TEST_ATTR_NCWILD )
150 {
151 $string .= '<namespace-prefix>' . $self->{literal} . '</namespace-prefix>';
152 }
153 else
154 {
155 $string .= '<nametest>' . $self->{literal} . '</nametest>';
156 }
157 $string .= "</Test>\n";
158  
159 foreach( @{$self->{predicates}} )
160 {
161 next unless( defined( $_ ) );
162 $string .= "<Predicate>\n" . $_->as_xml() . "</Predicate>\n";
163 }
164 $string .= "</Step>\n";
165 return( $string );
166 }
167  
168 sub axis { return( shift->_set_get_scalar( 'axis', @_ ) ); }
169  
170 sub axis_ancestor
171 {
172 my $self = shift( @_ );
173 my( $context, $results ) = @_;
174 my $parent = $context->getParentNode;
175  
176 # START:
177 # return( $results ) unless( $parent );
178 # if( $self->node_test( $parent ) )
179 # {
180 # $results->push( $parent );
181 # }
182 # $parent = $parent->getParentNode;
183 # goto( START );
184 while( $parent )
185 {
186 if( $self->node_test( $parent ) )
187 {
188 $results->push( $parent );
189 }
190 $parent = $parent->getParentNode;
191 }
192 return( $results );
193 }
194  
195 sub axis_ancestor_or_self
196 {
197 my $self = shift( @_ );
198 my( $context, $results ) = @_;
199  
200 # START:
201 # return $results unless $context;
202 # if( $self->node_test( $context ) )
203 # {
204 # $results->push( $context );
205 # }
206 # $context = $context->getParentNode;
207 # goto START;
208 while( $context )
209 {
210 if( $self->node_test( $context ) )
211 {
212 $results->push( $context );
213 }
214 $context = $context->getParentNode;
215 }
216 return( $results );
217 }
218  
219 sub axis_attribute
220 {
221 my $self = shift( @_ );
222 my( $context, $results ) = @_;
223  
224 foreach my $attrib ( @{$context->getAttributes} )
225 {
226 if( $self->test_attribute( $attrib ) )
227 {
228 $results->push( $attrib );
229 }
230 }
231 }
232  
233 sub axis_child
234 {
235 my $self = shift( @_ );
236 my( $context, $results ) = @_;
237 my $children = $context->getChildNodes;
238  
239 foreach my $node ( @{$context->getChildNodes} )
240 {
241 if( $self->node_test( $node ) )
242 {
243 $results->push( $node );
244 }
245 }
246 }
247  
248 sub axis_descendant
249 {
250 my $self = shift( @_ );
251 my( $context, $results ) = @_;
252  
253 my @queue = $context->getChildNodes;
254  
255 while( @queue )
256 {
257 my $node = shift( @queue );
258 if( $self->node_test( $node ) )
259 {
260 $results->push( $node );
261 }
262 else
263 {
264 # Node failed the test.
265 }
266 push( @queue, $node->getChildNodes );
267 }
268 }
269  
270 sub axis_descendant_or_self
271 {
272 my $self = shift( @_ );
273 my( $context, $results ) = @_;
274  
275 # Use a queue (FIFO) instead of a stack (LIFO) for traversal.
276 # push/shift (BFS) vs unshift/shift (DFS) yields the same node set for
277 # descendant-or-self since all nodes are visited regardless of order.
278 # BFS is O(1) per enqueue (push appends), whereas DFS via unshift is
279 # O(n) per step because it must shift all existing elements rightward.
280 # On a document with many siblings, this makes a significant difference
281 # in both CPU time and peak memory (the queue never grows beyond the
282 # width of the widest level, vs a DFS stack that holds entire subtrees).
283 my @queue = ( $context );
284  
285 while( @queue )
286 {
287 my $node = shift( @queue );
288 if( $self->node_test( $node ) )
289 {
290 $results->push( $node );
291 }
292 push( @queue, $node->getChildNodes );
293 }
294 }
295  
296 sub axis_following
297 {
298 my $self = shift( @_ );
299 my( $context, $results ) = @_;
300  
301 my $elt = $context->getNextSibling || _next_sibling_of_an_ancestor_of( $context );
302 while( $elt )
303 {
304 if( $self->node_test( $elt ) )
305 {
306 $results->push( $elt );
307 }
308 $elt = $elt->getFirstChild || $elt->getNextSibling || _next_sibling_of_an_ancestor_of( $elt );
309 }
310 }
311  
312 sub axis_following_sibling
313 {
314 my $self = shift( @_ );
315 my( $context, $results ) = @_;
316  
317 # warn "in axis_following_sibling";
318 while( $context = $context->getNextSibling )
319 {
320 if( $self->node_test( $context ) )
321 {
322 $results->push( $context );
323 }
324 }
325 }
326  
327 sub axis_method { return( shift->_set_get_scalar( 'axis_method', @_ ) ); }
328  
329 sub axis_namespace
330 {
331 my $self = shift( @_ );
332 my( $context, $results ) = @_;
333  
334 return( $results ) unless( $context->isElementNode );
335 foreach my $ns ( @{$context->getNamespaces} )
336 {
337 if( $self->test_namespace( $ns ) )
338 {
339 $results->push( $ns );
340 }
341 }
342 }
343  
344 sub axis_parent
345 {
346 my $self = shift( @_ );
347 my( $context, $results ) = @_;
348  
349 my $parent = $context->getParentNode;
350 return( $results ) unless( $parent );
351 if( $self->node_test( $parent ) )
352 {
353 $results->push( $parent );
354 }
355 }
356  
357 sub axis_preceding
358 {
359 my $self = shift( @_ );
360 my( $context, $results ) = @_;
361  
362 my $elt = $context->getPreviousSibling || _previous_sibling_of_an_ancestor_of( $context );
363 while( $elt )
364 {
365 if( $self->node_test( $elt ) )
366 {
367 $results->push( $elt );
368 }
369 $elt = $elt->getLastChild || $elt->getPreviousSibling || _previous_sibling_of_an_ancestor_of( $elt );
370 }
371 }
372  
373 sub axis_preceding_sibling
374 {
375 my $self = shift( @_ );
376 my( $context, $results ) = @_;
377 while( $context = $context->getPreviousSibling )
378 {
379 if( $self->node_test( $context ) )
380 {
381 $results->push( $context );
382 }
383 }
384 }
385  
386 sub axis_self
387 {
388 my $self = shift( @_ );
389 my( $context, $results ) = @_;
390  
391 if( $self->node_test( $context ) )
392 {
393 $results->push( $context );
394 }
395 }
396  
397 sub evaluate
398 {
399 my $self = shift( @_ );
400 # context nodeset
401 my $from = shift( @_ );
402  
403 if( $from && !$from->isa( 'HTML::Object::XPath::NodeSet' ) )
404 {
405 my $from_nodeset = $self->new_nodeset();
406 $from_nodeset->push( $from );
407 $from = $from_nodeset;
408 }
409 # warn "Step::evaluate called with ", $from->size, " length nodeset\n";
410  
411 my $saved_context = $self->{pp}->_get_context_set;
412 my $saved_pos = $self->{pp}->_get_context_pos;
413 $self->{pp}->_set_context_set( $from );
414  
415 my $initial_nodeset = $self->new_nodeset();
416  
417 # See spec section 2.1, paragraphs 3,4,5:
418 # The node-set selected by the location step is the node-set
419 # that results from generating an initial node set from the
420 # axis and node-test, and then filtering that node-set by
421 # each of the predicates in turn.
422  
423 # Make each node in the nodeset be the context node, one by one
424 for( my $i = 1; $i <= $from->size; $i++ )
425 {
426 $self->{pp}->_set_context_pos( $i );
427 # Capture the intermediate NodeSet in a lexical variable and release
428 # it immediately after appending its nodes to $initial_nodeset.
429 # Without this, the temporary NodeSet returned by evaluate_node()
430 # would stay alive until the end of the for() scope, causing
431 # accumulated memory pressure when $from is large (e.g. after a
432 # descendant-or-self step that returns every node in the document).
433 {
434 my $tmp = $self->evaluate_node( $from->get_node( $i ) );
435 $initial_nodeset->append( $tmp );
436 }
437 }
438  
439 # warn "Step::evaluate initial nodeset size: ", $initial_nodeset->size, "\n";
440  
441 $self->{pp}->_set_context_set( $saved_context );
442 $self->{pp}->_set_context_pos( $saved_pos );
443 return( $initial_nodeset );
444 }
445  
446 # Evaluate the step against a particular node
447 sub evaluate_node
448 {
449 my $self = shift( @_ );
450 my $context = shift( @_ );
451 # warn "Evaluate node: $self->{axis}\n";
452 # warn "Node: ", $context->[node_name], "\n";
453 my $method = $self->{axis_method};
454  
455 my $results = $self->new_nodeset();
456 no strict 'refs';
457 eval{ $self->$method( $context, $results ); };
458 if( $@ )
459 {
460 die( "axis $method not implemented [$@]\n" );
461 }
462  
463 # warn("results: ", join('><', map {$_->string_value} @$results), "\n");
464 # filter initial nodeset by each predicate
465 foreach my $predicate ( @{$self->{predicates}} )
466 {
467 $results = $self->filter_by_predicate( $results, $predicate );
468 }
469 return( $results );
470 }
471  
472 sub filter_by_predicate
473 {
474 my $self = shift( @_ );
475 my( $nodeset, $predicate ) = @_;
476  
477 # See spec section 2.4, paragraphs 2 & 3:
478 # For each node in the node-set to be filtered, the predicate Expr
479 # is evaluated with that node as the context node, with the number
480 # of nodes in the node set as the context size, and with the
481 # proximity position of the node in the node set with respect to
482 # the axis as the context position.
483 # use ref because nodeset has a bool context
484 if( !ref( $nodeset ) )
485 {
486 die( "No nodeset!!!" );
487 }
488  
489 # warn "Filter by predicate: $predicate\n";
490  
491 my $newset = $self->new_nodeset();
492  
493 for( my $i = 1; $i <= $nodeset->size; $i++ )
494 {
495 # set context set each time 'cos a loc-path in the expr could change it
496 $self->{pp}->_set_context_set( $nodeset );
497 $self->{pp}->_set_context_pos( $i );
498 my $result = $predicate->evaluate( $nodeset->get_node( $i ) );
499 if( $result->isa( 'HTML::Object::XPath::Boolean' ) )
500 {
501 if( $result->value )
502 {
503 $newset->push( $nodeset->get_node( $i ) );
504 }
505 }
506 elsif( $result->isa( 'HTML::Object::XPath::Number' ) )
507 {
508 if( $result->value == $i )
509 {
510 $newset->push( $nodeset->get_node( $i ) );
511 last;
512 }
513 }
514 else
515 {
516 if( $result->to_boolean->value )
517 {
518 $newset->push( $nodeset->get_node( $i ) );
519 }
520 }
521 }
522 return( $newset );
523 }
524  
525 sub literal { return( shift->_set_get_scalar( 'literal', @_ ) ); }
526  
527 sub new_nodeset { return( shift->_class_for( 'NodeSet' )->new( @_ ) ); }
528  
529 sub node_test
530 {
531 my $self = shift( @_ );
532 my $node = shift( @_ );
533 my $test_types = [qw( TEST_QNAME TEST_NCWILD TEST_ANY TEST_ATTR_QNAME TEST_ATTR_NCWILD TEST_ATTR_ANY TEST_NT_COMMENT TEST_NT_TEXT TEST_NT_PI TEST_NT_NODE )];
534  
535 # if node passes test, return true
536 my $test = $self->{test};
537  
538 return(1) if( $test == TEST_NT_NODE );
539  
540 if( $test == TEST_ANY )
541 {
542 return(1) if( $node->isElementNode && defined( $node->getName ) );
543 }
544  
545 # local $^W;
546 if( $test == TEST_NCWILD )
547 {
548 return unless( $node->isElementNode );
549 return( $self->_match_ns( $node ) );
550 }
551 elsif( $test == TEST_QNAME )
552 {
553 return unless( $node->isElementNode );
554 if( $self->{literal} =~ /:/ || $self->{pp}->{strict_namespaces} )
555 {
556 my( $prefix, $name ) = _name2prefix_and_local_name( $self->{literal} );
557 return(1) if( ( $name eq $node->getLocalName ) && $self->_match_ns( $node ) );
558 }
559 else
560 {
561 return(1) if( $node->getName eq $self->{literal} );
562 }
563 }
564 elsif( $test == TEST_NT_TEXT )
565 {
566 return(1) if( $node->isTextNode );
567 }
568 elsif( $test == TEST_NT_COMMENT )
569 {
570 return(1) if( $node->isCommentNode );
571 }
572 elsif( $test == TEST_NT_PI && !$self->{literal} )
573 {
574 return(1) if( $node->isPINode );
575 }
576 elsif( $test == TEST_NT_PI )
577 {
578 return unless( $node->isPINode );
579 if( my $val = $self->{literal}->value )
580 {
581 return(1) if( $node->getTarget eq $val );
582 }
583 else
584 {
585 return(1);
586 }
587 }
588 # fallthrough returns false
589 return;
590 }
591  
592 sub test { return( shift->_set_get_scalar( 'test', @_ ) ); }
593  
594 sub test_attribute
595 {
596 my $self = shift( @_ );
597 my $node = shift( @_ );
598 my $test = $self->{test};
599 return(1) if( ( $test == TEST_ATTR_ANY ) || ( $test == TEST_NT_NODE ) );
600  
601 if( $test == TEST_ATTR_NCWILD )
602 {
603 return(1) if( $self->_match_ns( $node ) );
604 }
605 elsif( $test == TEST_ATTR_QNAME )
606 {
607 if( $self->{literal} =~ /:/ )
608 {
609 my( $prefix, $name ) = _name2prefix_and_local_name( $self->{literal} );
610 return(1) if( ( $name eq $node->getLocalName ) && ( $self->_match_ns( $node ) ) );
611 }
612 else
613 {
614 return(1) if( $node->getName eq $self->{literal} );
615 }
616 }
617 # fallthrough returns false
618 return;
619 }
620  
621 sub test_namespace
622 {
623 my $self = shift( @_ );
624 my $node = shift( @_ );
625 # Not sure if this is correct. The spec seems very unclear on what
626 # constitutes a namespace test... bah!
627 my $test = $self->{test};
628 # True for all nodes of principal type
629 return(1) if( $test == TEST_ANY );
630  
631 if( $test == TEST_ANY )
632 {
633 return(1);
634 }
635 elsif( $self->{literal} eq $node->getExpanded )
636 {
637 return(1);
638 }
639 return;
640 }
641  
642 sub _class_for
643 {
644 my( $self, $mod ) = @_;
645 eval( "require ${BASE_CLASS}\::${mod};" );
646 die( $@ ) if( $@ );
647 # ${"${BASE_CLASS}\::${mod}\::DEBUG"} = $DEBUG;
648 eval( "\$${BASE_CLASS}\::${mod}\::DEBUG = " . ( $DEBUG // 0 ) );
649 return( "${BASE_CLASS}::${mod}" );
650 }
651  
652 sub _match_ns
653 {
654 my( $self, $node ) = @_;
655 my $pp = $self->{pp};
656 my $prefix = _name2prefix( $self->{literal} );
657 my( $match_ns, $node_ns );
658 if( $pp->{uses_namespaces} || $pp->{strict_namespaces} )
659 {
660 $match_ns = $pp->get_namespace( $prefix );
661 if( $match_ns || $pp->{strict_namespaces} )
662 {
663 $node_ns = $node->getNamespace->getValue;
664 }
665 # non-standard behaviour: if the query prefix is not declared
666 # compare the 2 prefixes
667 else
668 {
669 $match_ns = $prefix;
670 $node_ns = _name2prefix( $node->getName );
671 }
672 }
673 else
674 {
675 $match_ns = $prefix;
676 $node_ns = _name2prefix( $node->getName );
677 }
678 return( $match_ns eq $node_ns );
679 }
680  
681 sub _name2prefix
682 {
683 my $name = shift( @_ );
684 if( $name =~ m{^(.*?):} )
685 {
686 return( $1 );
687 }
688 else
689 {
690 return( '' );
691 }
692 }
693  
694 sub _name2prefix_and_local_name
695 {
696 my $name = shift( @_ );
697 return( $name =~ /:/ ? split( ':', $name, 2 ) : ( '', $name ) );
698 }
699  
700 sub _next_sibling_of_an_ancestor_of
701 {
702 my $elt = shift( @_ );
703 # NOTE: return 0 instead of undef ?
704 $elt = $elt->getParentNode || return;
705 my $next_elt;
706 while( !( $next_elt= $elt->getNextSibling ) )
707 {
708 $elt= $elt->getParentNode;
709 return unless( $elt && $elt->can( 'getNextSibling' ) );
710 }
711 return( $next_elt );
712 }
713  
714 sub _previous_sibling_of_an_ancestor_of
715 {
716 my $elt = shift( @_ );
717 # NOTE: Should we return 0 instead of undef ?
718 $elt = $elt->getParentNode || return;
719 my $next_elt;
720 while( !( $next_elt = $elt->getPreviousSibling ) )
721 {
722 $elt = $elt->getParentNode;
723 # so we do not have to write a getPreviousSibling
724 return unless( $elt->getParentNode );
725 }
726 return( $next_elt );
727 }
728  
729 1;
730 # NOTE: POD
731 __END__