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

filter: Statementstmt 0.0% 0 / 480 Branchbran 0.0% 0 / 158 Conditioncond 0.0% 0 / 33 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 73 Podpod 0.0% 0 / 58 totaltotal 0.0% 0 / 802 CC 80 SCAR 49.9
CC
80
Cov
0%
_step
756.0
_expr_primary
72.0
_tokenize
42.0
CRAP 147.0
1 ##----------------------------------------------------------------------------
2 ## HTML Object - ~/lib/HTML/Object/XPath.pm
3 ## Version v0.2.0
4 ## Copyright(c) 2021 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <jack@deguest.jp>
6 ## Created 2021/12/04
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;
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(
22 $CACHE $AXES $AXES_KEYS $NC_NAME_RE $QNAME_RE $NC_WILD_RE $QN_WILD_RE
23 $NODE_TYPE_RE $AXIS_NAME_RE $NUMBER_RE $LITERAL_RE $REGEXP_RE $REGEXP_MOD_RE
24 $BASE_CLASS $VERSION
25 );
26 use HTML::Object::XPath::Step;
27 use HTML::Object::XPath::Expr;
28 use HTML::Object::XPath::Function;
29 use HTML::Object::XPath::LocationPath;
30 use HTML::Object::XPath::Variable;
31 use HTML::Object::XPath::Literal;
32 use HTML::Object::XPath::Number;
33 use HTML::Object::XPath::NodeSet;
34 use HTML::Object::XPath::Root;
35 our $VERSION = 'v0.2.0';
36 our $CACHE = {};
37 # Axis name to principal node type mapping
38 our $AXES =
39 {
40 'ancestor' => 'element',
41 'ancestor-or-self' => 'element',
42 'attribute' => 'attribute',
43 'namespace' => 'namespace',
44 'child' => 'element',
45 'descendant' => 'element',
46 'descendant-or-self' => 'element',
47 'following' => 'element',
48 'following-sibling' => 'element',
49 'parent' => 'element',
50 'preceding' => 'element',
51 'preceding-sibling' => 'element',
52 'self' => 'element',
53 };
54 my $AXES_KEYS = join( '|', keys( %$AXES ) );
55 our $NC_NAME_RE = qr/([A-Za-z_][\w\.\-]*)/;
56 our $QNAME_RE = qr/(${NC_NAME_RE}:)?${NC_NAME_RE}/;
57 our $NC_WILD_RE = qr/${NC_NAME_RE}:\*/;
58 our $QN_WILD_RE = qr/\*/;
59 our $NODE_TYPE_RE = qr/((text|comment|processing-instruction|node)\(\))/;
60 our $AXIS_NAME_RE = qr/(${AXES_KEYS})::/;
61 our $NUMBER_RE = qr/\d+(\.\d*)?|\.\d+/;
62 our $LITERAL_RE = qr/\"[^\"]*\"|\'[^\']*\'/;
63 our $REGEXP_RE = qr{(?:m?/(?:\\.|[^/])*/)};
64 our $REGEXP_MOD_RE = qr{(?:[imsx]+)};
65 our $BASE_CLASS = __PACKAGE__;
66 };
67  
68 use strict;
69 use warnings;
70  
71 sub init
72 {
73 my $self = shift( @_ );
74 $self->{_init_strict_use_sub} = 1;
75 $self->SUPER::init( @_ ) || return( $self->pass_error );
76 $self->{context_pos} = undef; # 1 based position in array context
77 $self->{context_set} = $self->new_nodeset;
78 $self->{context_size} = 0; # total size of context
79 $self->clear_namespaces();
80 $self->{cache} = {};
81 $self->{direction} = 'forward';
82 $self->{namespaces} = {};
83 $self->{vars} = {};
84 $self->{_tokpos} = 0;
85 return( $self );
86 }
87  
88 sub clear_namespaces
89 {
90 my $self = shift( @_ );
91 $self->{uses_namespaces} = 0;
92 $self->{namespaces} = {};
93 return( $self );
94 }
95  
96 sub exists
97 {
98 my $self = shift( @_ );
99 my( $path, $context ) = @_;
100 $self = '/' if( !defined( $self ) );
101 my @nodeset = $self->findnodes( $path, $context );
102 return( scalar( @nodeset ) ? 1 : 0 );
103 }
104  
105 sub find
106 {
107 my $self = shift( @_ );
108 # xpath expression and $context is a HTML::Object::Element
109 my( $path, $context ) = @_;
110 # _parse returns an HTML::Object::XPath::Expr object
111 my $parsed_path = $self->_parse( $path );
112 # $parsed_path is an HTML:: Object::XPath::Expr object
113 # $results could be a HTML::Object::XPath::NodeSet or something else like HTML::Object::XPath::Number
114 my $results = $parsed_path->evaluate( $context );
115 if( $self->_is_a( $results, 'HTML::Object::XPath::NodeSet' ) )
116 {
117 return( $results->sort->remove_duplicates );
118 }
119 else
120 {
121 return( $results );
122 }
123 }
124  
125 sub findnodes
126 {
127 my $self = shift( @_ );
128 my( $path, $context ) = @_;
129
130 my $results = $self->find( $path, $context );
131
132 if( $self->_is_a( $results => 'HTML::Object::XPath::NodeSet' ) )
133 {
134 return( wantarray() ? $results->get_nodelist : $results );
135 }
136 # result should be SCALAR
137 else
138 {
139 return( wantarray() ? $self->new_nodeset( $results ) : $results );
140 }
141 }
142  
143 sub findnodes_as_string
144 {
145 my $self = shift( @_ );
146 my( $path, $context ) = @_;
147
148 my $results = $self->find( $path, $context );
149 if( $self->_is_a( $results => 'HTML::Object::XPath::NodeSet' ) )
150 {
151 return( join( '', map{ $_->toString } $results->get_nodelist ) );
152 }
153 elsif( $self->_is_a( $results => 'HTML::Object::XPath::Boolean' ) )
154 {
155 # to behave like XML::LibXML
156 return( '' );
157 }
158 elsif( $self->_is_a( $results => 'HTML::Object::XPath::Node' ) )
159 {
160 return( $results->toString );
161 }
162 else
163 {
164 return( $self->_xml_escape_text( $results->value ) );
165 }
166 }
167  
168 sub findnodes_as_strings
169 {
170 my $self = shift( @_ );
171 my( $path, $context ) = @_;
172 my $results = $self->find( $path, $context );
173
174 if( $self->_is_a( $results => 'HTML::Object::XPath::NodeSet' ) )
175 {
176 return( map{ $_->getValue } $results->get_nodelist );
177 }
178 elsif( $self->_is_a( $results => 'HTML::Object::XPath::Boolean' ) )
179 {
180 # to behave like XML::LibXML
181 return( () );
182 }
183 elsif( $self->_is_a( $results => 'HTML::Object::XPath::Node' ) )
184 {
185 return( $results->getValue );
186 }
187 else
188 {
189 return( $self->_xml_escape_text( $results->value ) );
190 }
191 }
192  
193 sub findvalue
194 {
195 my $self = shift( @_ );
196 my( $path, $context ) = @_;
197 my $results = $self->find( $path, $context );
198 if( $self->_is_a( $results => 'HTML::Object::XPath::NodeSet' ) )
199 {
200 return( $results->to_final_value );
201 }
202 #{ return $results->to_literal; }
203 return( $results->value );
204 }
205  
206 sub findvalues
207 {
208 my $self = shift( @_ );
209 my( $path, $context ) = @_;
210 my $results = $self->find( $path, $context );
211 if( $self->_is_a( $results => 'HTML::Object::XPath::NodeSet' ) )
212 {
213 return( $results->string_values );
214 }
215 return( $results->string_value );
216 }
217  
218 sub get_namespace
219 {
220 my $self = shift( @_ );
221 my( $prefix, $node ) = @_;
222
223 my $ns = $node
224 ? $node->getNamespace( $prefix )
225 : $self->{uses_namespaces}
226 ? $self->{namespaces}->{ $prefix }
227 : $prefix;
228 return( $ns );
229 }
230  
231 sub get_var
232 {
233 my $self = shift( @_ );
234 my $var = shift( @_ );
235 $self->{vars}->{ $var };
236 }
237  
238 sub matches
239 {
240 my $self = shift( @_ );
241 my( $node, $path, $context ) = @_;
242 my @nodes = $self->findnodes( $path, $context );
243 return(1) if( grep{ "$node" eq "$_" } @nodes );
244 return;
245 }
246  
247 sub namespaces { return( shift->_set_get_hash_as_mix_object( 'namespaces', @_ ) ); }
248  
249 sub new_expr { return( shift->_class_for( 'Expr' )->new( @_ ) ); }
250  
251 sub new_function { return( shift->_class_for( 'Function' )->new( @_ ) ); }
252  
253 sub new_literal { return( shift->_class_for( 'Literal' )->new( @_ ) ); }
254  
255 sub new_location_path { return( shift->_class_for( 'LocationPath' )->new( @_ ) ); }
256  
257 sub new_nodeset { return( shift->_class_for( 'NodeSet' )->new( @_ ) ); }
258  
259 sub new_number { return( shift->_class_for( 'Number' )->new( @_ ) ); }
260  
261 sub new_root { return( shift->_class_for( 'Root' )->new( @_ ) ); }
262  
263 sub new_step { return( shift->_class_for( 'Step' )->new( @_ ) ); }
264  
265 sub new_variable { return( shift->_class_for( 'Variable' )->new( @_ ) ); }
266  
267 sub parse { return( shift->_parse( @_ ) ); }
268  
269 sub set_namespace
270 {
271 my $self = shift( @_ );
272 my( $prefix, $expanded ) = @_;
273 $self->{uses_namespaces} = 1;
274 $self->{namespaces}{ $prefix } = $expanded;
275 }
276  
277 sub set_strict_namespaces
278 {
279 my( $self, $strict ) = @_;
280 $self->{strict_namespaces} = $strict;
281 }
282  
283 sub set_var
284 {
285 my $self = shift( @_ );
286 my $var = shift( @_ );
287 my $val = shift( @_ );
288 $self->{vars}->{ $var } = $val;
289 }
290  
291 sub _analyze
292 {
293 my $self = shift( @_ );
294 # Array object
295 my $tokens = shift( @_ );
296 # lexical analysis
297 return( $self->_expr( $tokens ) );
298 }
299  
300 sub _arguments
301 {
302 my( $self, $tokens ) = @_;
303 my $args = $self->new_array;
304 if( $tokens->[ $self->{_tokpos} ] eq ')' )
305 {
306 return( $args );
307 }
308
309 $args->push( $self->_expr( $tokens ) );
310 while( $self->_match( $tokens, qr/\,/ ) )
311 {
312 $args->push( $self->_expr( $tokens ) );
313 }
314 return( $args );
315 }
316  
317 sub _class_for
318 {
319 my( $self, $mod ) = @_;
320 eval( "require ${BASE_CLASS}\::${mod};" );
321 die( $@ ) if( $@ );
322 # ${"${BASE_CLASS}\::${mod}\::DEBUG"} = $self->debug;
323 eval( "\$${BASE_CLASS}\::${mod}\::DEBUG = " . ( $self->debug // 0 ) );
324 return( "${BASE_CLASS}::${mod}" );
325 }
326  
327 sub _expr
328 {
329 my( $self, $tokens ) = @_;
330 # $tokens are an array object of xpath expression token
331 # Returning an HTML::Object::XPath::Expr object
332 return( $self->_expr_or( $tokens ) );
333 }
334  
335 sub _expr_additive
336 {
337 my( $self, $tokens ) = @_;
338
339 my $expr = $self->_expr_multiplicative( $tokens );
340 while( $self->_match( $tokens, qr/[\+\-]/ ) )
341 {
342 my $add_expr = $self->new_expr( $self );
343 $add_expr->set_lhs( $expr );
344 $add_expr->set_op( $self->{_curr_match} );
345
346 my $rhs = $self->_expr_multiplicative( $tokens );
347
348 $add_expr->set_rhs( $rhs );
349 $expr = $add_expr;
350 }
351 return( $expr );
352 }
353  
354 sub _expr_and
355 {
356 my( $self, $tokens ) = @_;
357 my $expr = $self->_expr_match( $tokens );
358 while( $self->_match( $tokens, 'and' ) )
359 {
360 my $and_expr = $self->new_expr( $self );
361 $and_expr->set_lhs( $expr );
362 $and_expr->set_op( 'and' );
363 my $rhs = $self->_expr_match( $tokens );
364 $and_expr->set_rhs( $rhs );
365 $expr = $and_expr;
366 }
367 return( $expr );
368 }
369  
370 sub _expr_equality
371 {
372 my( $self, $tokens ) = @_;
373
374 my $expr = $self->_expr_relational( $tokens );
375 while( $self->_match( $tokens, qr/!?=/ ) )
376 {
377 my $eq_expr = $self->new_expr( $self );
378 $eq_expr->set_lhs( $expr );
379 $eq_expr->set_op( $self->{_curr_match} );
380
381 my $rhs = $self->_expr_relational( $tokens );
382
383 $eq_expr->set_rhs( $rhs );
384 $expr = $eq_expr;
385 }
386 return( $expr );
387 }
388  
389 sub _expr_filter
390 {
391 my( $self, $tokens ) = @_;
392
393 my $expr = $self->_expr_primary( $tokens );
394 while( $self->_match( $tokens, qr/\[/ ) )
395 {
396 # really PredicateExpr...
397 $expr->push_predicate( $self->_expr( $tokens ) );
398 $self->_match( $tokens, qr/\]/, 1 );
399 }
400 return( $expr );
401 }
402  
403 sub _expr_match
404 {
405 my( $self, $tokens ) = @_;
406
407 my $expr = $self->_expr_equality( $tokens );
408  
409 while( $self->_match( $tokens, qr/[=!]~/ ) )
410 {
411 my $match_expr = $self->new_expr( $self );
412 $match_expr->set_lhs( $expr );
413 $match_expr->set_op( $self->{_curr_match} );
414
415 my $rhs = $self->_expr_equality( $tokens );
416
417 $match_expr->set_rhs( $rhs );
418 $expr = $match_expr;
419 }
420 return( $expr );
421 }
422  
423 sub _expr_multiplicative
424 {
425 my( $self, $tokens ) = @_;
426
427 my $expr = $self->_expr_unary( $tokens );
428 while( $self->_match( $tokens, qr/(\*|div|mod)/ ) )
429 {
430 my $mult_expr = $self->new_expr( $self );
431 $mult_expr->set_lhs( $expr );
432 $mult_expr->set_op( $self->{_curr_match} );
433
434 my $rhs = $self->_expr_unary( $tokens );
435
436 $mult_expr->set_rhs( $rhs );
437 $expr = $mult_expr;
438 }
439 return( $expr );
440 }
441  
442 sub _expr_or
443 {
444 my( $self, $tokens ) = @_;
445
446 my $expr = $self->_expr_and( $tokens );
447 while( $self->_match( $tokens, 'or' ) )
448 {
449 my $or_expr = $self->new_expr( $self );
450 $or_expr->set_lhs( $expr );
451 $or_expr->set_op( 'or' );
452  
453 my $rhs = $self->_expr_and( $tokens );
454  
455 $or_expr->set_rhs( $rhs );
456 $expr = $or_expr;
457 }
458 return( $expr );
459 }
460  
461 sub _expr_path
462 {
463 my( $self, $tokens ) = @_;
464 # _expr_path is _location_path | _expr_filter | _expr_filter '//?' _relative_location_path
465 # Since we are being predictive we need to find out which function to call next, then.
466 # LocationPath either starts with "/", "//", ".", ".." or a proper Step.
467 my $expr = $self->new_expr( $self );
468
469 # $test is a fragment of the xpath initially provided and broken down into bits by
470 # HTML::Object::XPath::_tokenize
471 my $test = $tokens->[ $self->{_tokpos} ];
472
473 # Test for AbsoluteLocationPath and AbbreviatedRelativeLocationPath
474 if( $test =~ /^(\/\/?|\.\.?)$/ )
475 {
476 # LocationPath
477 $expr->set_lhs( $self->_location_path( $tokens ) );
478 }
479 # Test for AxisName::...
480 elsif( $self->_is_step( $tokens ) )
481 {
482 $expr->set_lhs( $self->_location_path( $tokens ) );
483 }
484 else
485 {
486 # Not a LocationPath
487 # Use _expr_filter instead:
488 $expr = $self->_expr_filter( $tokens );
489 if( $self->_match( $tokens, qr/\/\/?/ ) )
490 {
491 my $loc_path = $self->new_location_path();
492 $loc_path->push( $expr );
493 if( $self->{_curr_match} eq '//' )
494 {
495 $loc_path->push( $self->new_step( $self, 'descendant-or-self', $self->_class_for( 'Step' )->TEST_NT_NODE ) );
496 }
497 $loc_path->push( $self->_relative_location_path( $tokens ) );
498 my $new_expr = $self->new_expr( $self );
499 $new_expr->set_lhs( $loc_path );
500 return( $new_expr );
501 }
502 }
503 return( $expr );
504 }
505  
506 sub _expr_primary
507 {
508 my( $self, $tokens ) = @_;
509
510 my $expr = $self->new_expr( $self );
511
512 if( $self->_match( $tokens, $LITERAL_RE ) )
513 {
514 # new Literal with $self->{_curr_match}...
515 $self->{_curr_match} =~ m/^(["'])(.*)\1$/;
516 $expr->set_lhs( $self->new_literal( $2 ) );
517 }
518 elsif( $self->_match( $tokens, qr/${REGEXP_RE}${REGEXP_MOD_RE}?/ ) )
519 {
520 # new Literal with $self->{_curr_match} turned into a regexp...
521 my( $regexp, $mod)= $self->{_curr_match} =~ m{($REGEXP_RE)($REGEXP_MOD_RE?)};
522 $regexp =~ s{^m?s*/}{};
523 $regexp =~ s{/$}{};
524 # move the mods inside the regexp
525 if( $mod )
526 {
527 $regexp =~ qr/(?$mod:$regexp)/;
528 }
529 $expr->set_lhs( $self->new_literal( $regexp ) );
530 }
531 elsif( $self->_match( $tokens, $NUMBER_RE ) )
532 {
533 # new Number with $self->{_curr_match}...
534 $expr->set_lhs( $self->new_number( $self->{_curr_match} ) );
535 }
536 elsif( $self->_match( $tokens, qr/\(/ ) )
537 {
538 $expr->set_lhs( $self->_expr( $tokens ) );
539 $self->_match( $tokens, qr/\)/, 1 );
540 }
541 elsif( $self->_match( $tokens, qr/\$$QNAME_RE/ ) )
542 {
543 # new Variable with $self->{_curr_match}...
544 $self->{_curr_match} =~ /^\$(.*)$/;
545 $expr->set_lhs( $self->new_variable( $self, $1 ) );
546 }
547 elsif( $self->_match( $tokens, $QNAME_RE ) )
548 {
549 # check match not Node_Type - done in lexer...
550 # new Function
551 my $func_name = $self->{_curr_match};
552 $self->_match( $tokens, qr/\(/, 1 );
553 $expr->set_lhs(
554 $self->new_function(
555 $self,
556 $func_name,
557 $self->_arguments( $tokens )
558 )
559 );
560 $self->_match( $tokens, qr/\)/, 1 );
561 }
562 else
563 {
564 # die "Not a _expr_primary at ", $tokens->[$self->{_tokpos}], "\n";
565 return( $self->error( "Not a _expr_primary at ", $tokens->[ $self->{_tokpos} ] ) );
566 }
567 return( $expr );
568 }
569  
570 sub _expr_relational
571 {
572 my( $self, $tokens ) = @_;
573
574 my $expr = $self->_expr_additive( $tokens );
575 while( $self->_match( $tokens, qr/(<|>|<=|>=)/ ) )
576 {
577 my $rel_expr = $self->new_expr( $self );
578 $rel_expr->set_lhs( $expr );
579 $rel_expr->set_op( $self->{_curr_match} );
580
581 my $rhs = $self->_expr_additive( $tokens );
582
583 $rel_expr->set_rhs( $rhs );
584 $expr = $rel_expr;
585 }
586 return( $expr );
587 }
588  
589 sub _expr_unary
590 {
591 my( $self, $tokens ) = @_;
592 # $tokens are an array object of expression tokens
593
594 if( $self->_match( $tokens, qr/-/ ) )
595 {
596 my $expr = $self->new_expr( $self );
597 $expr->set_lhs( $self->new_number(0) );
598 $expr->set_op( '-' );
599 $expr->set_rhs( $self->_expr_unary( $tokens ) );
600 return( $expr );
601 }
602 else
603 {
604 return( $self->_expr_union( $tokens ) );
605 }
606 }
607  
608 sub _expr_union
609 {
610 my( $self, $tokens ) = @_;
611 # $tokens are an array object of expression tokens
612
613 my $expr = $self->_expr_path( $tokens );
614 while( $self->_match( $tokens, qr/\|/ ) )
615 {
616 my $un_expr = $self->new_expr( $self );
617 $un_expr->set_lhs( $expr );
618 $un_expr->set_op( '|' );
619
620 my $rhs = $self->_expr_path( $tokens );
621 $un_expr->set_rhs( $rhs );
622 $expr = $un_expr;
623 }
624 return( $expr );
625 }
626  
627 sub _get_context_node { return( $_[0]->{context_set}->get_node( $_[0]->{context_pos} ) ); }
628  
629 sub _get_context_pos { return( shift->{context_pos} ); }
630  
631 sub _get_context_set { return( shift->{context_set} ); }
632  
633 sub _get_context_size { return( shift->{context_set}->size ); }
634  
635 sub _is_step
636 {
637 my( $self, $tokens ) = @_;
638 my $token = $tokens->[ $self->{_tokpos} ];
639 return unless( defined( $token ) );
640  
641 # local $^W = 0;
642 if( ( $token eq 'processing-instruction' ) ||
643 ( $token =~ /^\@($NC_WILD_RE|$QNAME_RE|$QN_WILD_RE)$/o ) ||
644 ( ( $token =~ /^($NC_WILD_RE|$QNAME_RE|$QN_WILD_RE)$/o ) &&
645 ( ( $tokens->[ $self->{_tokpos} + 1 ] || '' ) ne '(' ) ) ||
646 ( $token =~ /^$NODE_TYPE_RE$/o ) ||
647 ( $token =~ /^$AXIS_NAME_RE($NC_WILD_RE|$QNAME_RE|$QN_WILD_RE|$NODE_TYPE_RE)$/o )
648 )
649 {
650 return(1);
651 }
652 else
653 {
654 return;
655 }
656 }
657  
658 sub _location_path
659 {
660 my( $self, $tokens ) = @_;
661 my $loc_path = $self->new_location_path;
662
663 if( $self->_match( $tokens, qr/\// ) )
664 {
665 # root
666 # push @$loc_path, HTML::Object::XPath::Root->new();
667 $loc_path->push( $self->new_root );
668 # Is it a valid token step?
669 if( $self->_is_step( $tokens ) )
670 {
671 # push @$loc_path, $self->_relative_location_path( $tokens);
672 $loc_path->push( $self->_relative_location_path( $tokens ) );
673 }
674 }
675 elsif( $self->_match( $tokens, qr/\/\// ) )
676 {
677 # root
678 $loc_path->push( $self->new_root );
679 my $optimised = $self->_optimise_descendant_or_self( $tokens );
680 if( !$optimised )
681 {
682 $loc_path->push(
683 $self->new_step( $self, 'descendant-or-self', $self->_class_for( 'Step' )->TEST_NT_NODE )
684 );
685 $loc_path->push( $self->_relative_location_path( $tokens ) );
686 }
687 else
688 {
689 $loc_path->push( $optimised, $self->_relative_location_path( $tokens ) );
690 }
691 }
692 else
693 {
694 $loc_path->push( $self->_relative_location_path( $tokens ) );
695 }
696 return( $loc_path );
697 }
698  
699 sub _match
700 {
701 my( $self, $tokens, $match, $fatal ) = @_;
702 # Enabling this debugging section will take a lot more time, because of the
703 # $tokens->length that creates a new Module::Generic::Number every time
704 # and _match gets called a lot
705 $self->{_curr_match} = '';
706 return(0) unless( $self->{_tokpos} < scalar( @$tokens ) );
707 # return(0) unless( $self->{_tokpos} < $tokens->length );
708  
709 # local $^W;
710 if( $tokens->[ $self->{_tokpos} ] =~ /^$match$/ )
711 {
712 $self->{_curr_match} = $tokens->[ $self->{_tokpos} ];
713 $self->{_tokpos}++;
714 return(1);
715 }
716 else
717 {
718 if( $fatal )
719 {
720 die( "Invalid token: ", $tokens->[$self->{_tokpos}], "\n" );
721 # return( $self->error( "Invalid token: ", $tokens->[ $self->{_tokpos} ] ) );
722 }
723 else
724 {
725 return(0);
726 }
727 }
728 }
729  
730 sub _optimise_descendant_or_self
731 {
732 my( $self, $tokens ) = @_;
733
734 my $tokpos = $self->{_tokpos};
735
736 # // must be followed by a Step.
737 if( $tokens->[ $tokpos + 1 ] && $tokens->[ $tokpos + 1 ] eq '[' )
738 {
739 # next token is a predicate
740 return;
741 }
742 elsif( $tokens->[ $tokpos ] =~ /^\.\.?$/ )
743 {
744 # abbreviatedStep - can't optimise.
745 return;
746 }
747 else
748 {
749 my $step = $self->_step( $tokens );
750 if( $step->axis ne 'child' )
751 {
752 # can't optimise axes other than child for now...
753 $self->{_tokpos} = $tokpos;
754 return;
755 }
756 $step->axis( 'descendant' );
757 $step->axis_method( 'axis_descendant' );
758 $self->{_tokpos}--;
759 $tokens->[ $self->{_tokpos} ] = '.';
760 return( $step );
761 }
762 }
763  
764 sub _parse
765 {
766 my $self = shift( @_ );
767 my $path = shift( @_ );
768  
769 # $context is something like: //*[@att2="vv"]
770 # my $context = join( '&&', $path, map { "$_=>$self->{namespaces}->{$_}" } sort keys %{$self->{namespaces}});
771 my $context = $self->namespaces->keys->sort->map(sub{ sprintf( '%s=>%s', $_, $self->namespaces->get( $_ ) ); })->prepend( $path )->join( '&&' );
772
773 return( $CACHE->{ $context } ) if( $CACHE->{ $context } );
774  
775 # my $tokens = $self->_tokenize( $path ) || return( $self->pass_error );
776 # Get an Module::Generic::Array object in return
777 my $tokens = $self->_tokenize( $path );
778  
779 $self->{_tokpos} = 0;
780 my $tree = $self->_analyze( $tokens );
781
782 if( $self->{_tokpos} < $tokens->length )
783 {
784 # didn't manage to parse entire expression - throw an exception
785 die "Parse of expression $path failed - junk after end of expression: $tokens->[$self->{_tokpos}]";
786 # return( $self->error( "Parse of expression $path failed - junk after end of expression: $tokens->[$self->{_tokpos}]" ) );
787 }
788  
789 $tree->{uses_namespaces} = $self->{uses_namespaces};
790 $tree->{strict_namespaces} = $self->{strict_namespaces};
791
792 $CACHE->{ $context } = $tree;
793
794 return( $tree );
795 }
796  
797 sub _relative_location_path
798 {
799 my( $self, $tokens ) = @_;
800 my @steps;
801
802 push( @steps, $self->_step( $tokens ) );
803 while( $self->_match( $tokens, qr/\/\/?/ ) )
804 {
805 if( $self->{_curr_match} eq '//' )
806 {
807 my $optimised = $self->_optimise_descendant_or_self( $tokens);
808 if( !$optimised )
809 {
810 push( @steps, $self->new_step( $self, 'descendant-or-self', $self->_class_for( 'Step' )->TEST_NT_NODE ) );
811 }
812 else
813 {
814 push( @steps, $optimised );
815 }
816 }
817 push( @steps, $self->_step( $tokens ) );
818 if( @steps > 1 &&
819 $steps[-1]->axis eq 'self' &&
820 $steps[-1]->test == $self->_class_for( 'Step' )->TEST_NT_NODE )
821 {
822 pop( @steps );
823 }
824 }
825 return( @steps );
826 }
827  
828 sub _set_context_pos { return( shift->_set_get_scalar( 'context_pos', @_ ) ); }
829  
830 sub _set_context_set { return( shift->_set_get_scalar( 'context_set', @_ ) ); }
831  
832 sub _step
833 {
834 my( $self, $tokens ) = @_;
835 if( $self->_match( $tokens, qr/\./ ) )
836 {
837 # self::node()
838 return( $self->new_step( $self, 'self', $self->_class_for( 'Step' )->TEST_NT_NODE ) );
839 }
840 elsif( $self->_match( $tokens, qr/\.\./ ) )
841 {
842 # parent::node()
843 return( $self->new_step( $self, 'parent', $self->_class_for( 'Step' )->TEST_NT_NODE ) );
844 }
845 else
846 {
847 # AxisSpecifier NodeTest Predicate(s?)
848 my $token = $tokens->[ $self->{_tokpos} ];
849
850 my $step;
851 if( $token eq 'processing-instruction' )
852 {
853 $self->{_tokpos}++;
854 $self->_match( $tokens, qr/\(/, 1 );
855 $self->_match( $tokens, $LITERAL_RE );
856 $self->{_curr_match} =~ /^["'](.*)["']$/;
857 $step = $self->new_step(
858 $self, 'child',
859 $self->_class_for( 'Step' )->TEST_NT_PI,
860 $self->new_literal( $1 )
861 );
862 $self->_match( $tokens, qr/\)/, 1 );
863 }
864 elsif( $token =~ /^\@($NC_WILD_RE|$QNAME_RE|$QN_WILD_RE)$/o )
865 {
866 $self->{_tokpos}++;
867 if( $token eq '@*' )
868 {
869 $step = $self->new_step(
870 $self, 'attribute',
871 $self->_class_for( 'Step' )->TEST_ATTR_ANY,
872 '*'
873 );
874 }
875 elsif( $token =~ /^\@($NC_NAME_RE):\*$/o )
876 {
877 $step = $self->new_step(
878 $self, 'attribute',
879 $self->_class_for( 'Step' )->TEST_ATTR_NCWILD,
880 $1
881 );
882 }
883 elsif( $token =~ /^\@($QNAME_RE)$/o )
884 {
885 $step = $self->new_step(
886 $self, 'attribute',
887 $self->_class_for( 'Step' )->TEST_ATTR_QNAME,
888 $1
889 );
890 }
891 }
892 # ns:*
893 elsif( $token =~ /^($NC_NAME_RE):\*$/o )
894 {
895 $self->{_tokpos}++;
896 $step = $self->new_step(
897 $self, 'child',
898 $self->_class_for( 'Step' )->TEST_NCWILD,
899 $1
900 );
901 }
902 # *
903 elsif( $token =~ /^$QN_WILD_RE$/o )
904 {
905 $self->{_tokpos}++;
906 $step = $self->new_step(
907 $self, 'child',
908 $self->_class_for( 'Step' )->TEST_ANY,
909 $token
910 );
911 }
912 # name:name
913 elsif( $token =~ /^$QNAME_RE$/o )
914 {
915 $self->{_tokpos}++;
916 $step = $self->new_step(
917 $self, 'child',
918 $self->_class_for( 'Step' )->TEST_QNAME,
919 $token
920 );
921 }
922 elsif( $token eq 'comment()' )
923 {
924 $self->{_tokpos}++;
925 $step = $self->new_step(
926 $self, 'child',
927 $self->_class_for( 'Step' )->TEST_NT_COMMENT
928 );
929 }
930 elsif( $token eq 'text()' )
931 {
932 $self->{_tokpos}++;
933 $step = $self->new_step(
934 $self, 'child',
935 $self->_class_for( 'Step' )->TEST_NT_TEXT
936 );
937 }
938 elsif( $token eq 'node()' )
939 {
940 $self->{_tokpos}++;
941 $step = $self->new_step(
942 $self, 'child',
943 $self->_class_for( 'Step' )->TEST_NT_NODE
944 );
945 }
946 elsif( $token eq 'processing-instruction()' )
947 {
948 $self->{_tokpos}++;
949 $step = $self->new_step(
950 $self, 'child',
951 $self->_class_for( 'Step' )->TEST_NT_PI
952 );
953 }
954 elsif( $token =~ /^$AXIS_NAME_RE($NC_WILD_RE|$QNAME_RE|$QN_WILD_RE|$NODE_TYPE_RE)$/o )
955 {
956 my $axis = $1;
957 $self->{_tokpos}++;
958 $token = $2;
959 if( $token eq 'processing-instruction' )
960 {
961 $self->_match( $tokens, qr/\(/, 1 );
962 $self->_match( $tokens, $LITERAL_RE );
963 $self->{_curr_match} =~ /^["'](.*)["']$/;
964 $step = $self->new_step(
965 $self, $axis,
966 $self->_class_for( 'Step' )->TEST_NT_PI,
967 HTML::Object::XPath::Literal->new( $1 )
968 );
969 $self->_match( $tokens, qr/\)/, 1 );
970 }
971 # ns:*
972 elsif( $token =~ /^($NC_NAME_RE):\*$/o )
973 {
974 $step = $self->new_step(
975 $self, $axis,
976 ( ( $axis eq 'attribute' )
977 ? $self->_class_for( 'Step' )->TEST_ATTR_NCWILD
978 : $self->_class_for( 'Step' )->TEST_NCWILD
979 ),
980 $1
981 );
982 }
983 # *
984 elsif( $token =~ /^$QN_WILD_RE$/o )
985 {
986 $step = $self->new_step(
987 $self, $axis,
988 ( ( $axis eq 'attribute' )
989 ? $self->_class_for( 'Step' )->TEST_ATTR_ANY
990 : $self->_class_for( 'Step' )->TEST_ANY
991 ),
992 $token
993 );
994 }
995 # name:name
996 elsif( $token =~ /^$QNAME_RE$/o )
997 {
998 $step = $self->new_step(
999 $self, $axis,
1000 ( ( $axis eq 'attribute' )
1001 ? $self->_class_for( 'Step' )->TEST_ATTR_QNAME
1002 : $self->_class_for( 'Step' )->TEST_QNAME
1003 ),
1004 $token
1005 );
1006 }
1007 elsif( $token eq 'comment()' )
1008 {
1009 $step = $self->new_step(
1010 $self, $axis,
1011 $self->_class_for( 'Step' )->TEST_NT_COMMENT
1012 );
1013 }
1014 elsif( $token eq 'text()' )
1015 {
1016 $step = $self->new_step(
1017 $self, $axis,
1018 $self->_class_for( 'Step' )->TEST_NT_TEXT
1019 );
1020 }
1021 elsif( $token eq 'node()' )
1022 {
1023 $step = $self->new_step(
1024 $self, $axis,
1025 $self->_class_for( 'Step' )->TEST_NT_NODE
1026 );
1027 }
1028 elsif( $token eq 'processing-instruction()' )
1029 {
1030 $step = $self->new_step(
1031 $self, $axis,
1032 $self->_class_for( 'Step' )->TEST_NT_PI
1033 );
1034 }
1035 else
1036 {
1037 die( "Shouldn't get here" );
1038 }
1039 }
1040 else
1041 {
1042 die( "token $token does not match format of a 'Step'\n" );
1043 }
1044
1045 while( $self->_match( $tokens, qr/\[/ ) )
1046 {
1047 push( @{$step->{predicates}}, $self->_expr( $tokens ) );
1048 $self->_match( $tokens, qr/\]/, 1 );
1049 }
1050 return( $step );
1051 }
1052 }
1053  
1054 sub _tokenize
1055 {
1056 my $self = shift( @_ );
1057 my $path = shift( @_ );
1058 my $tokens = $self->new_array;
1059
1060
1061 # Bug: We do not allow "'@' NodeType" which is in the grammar, but I think is just plain stupid.
1062
1063 # used to desambiguate conflicts (for REs)
1064 my $expected = '';
1065  
1066 while( length( $path ) )
1067 {
1068 my $token = '';
1069 if( $expected eq 'RE' && ( $path =~ m{\G\s*($REGEXP_RE $REGEXP_MOD_RE?)\s*}gcxso ) )
1070 {
1071 # special case: regexp expected after =~ or !~, regular parsing rules do not apply
1072 # ( the / is now the regexp delimiter)
1073 $token = $1;
1074 $expected = '';
1075 }
1076 elsif( $path =~ m/\G
1077 \s* # ignore all whitespace
1078 ( # tokens
1079 $LITERAL_RE|
1080 $NUMBER_RE| # digits
1081 \.\.| # parent
1082 \.| # current
1083 ($AXIS_NAME_RE)?$NODE_TYPE_RE| # tests
1084 processing-instruction|
1085 \@($NC_WILD_RE|$QNAME_RE|$QN_WILD_RE)| # attrib
1086 \$$QNAME_RE| # variable reference
1087 ($AXIS_NAME_RE)?($NC_WILD_RE|$QNAME_RE|$QN_WILD_RE)| # NCName,NodeType,Axis::Test
1088 \!=|<=|\-|>=|\/\/|and|or|mod|div| # multi-char seps
1089 =~|\!~| # regexp (not in the XPath spec)
1090 [,\+=\|<>\/\(\[\]\)]| # single char seps
1091 (?<!(\@|\(|\[))\*| # multiply operator rules (see xpath spec)
1092 (?<!::)\*|
1093 $ # end of query
1094 )
1095 \s* # ignore all whitespace
1096 /gcxso )
1097 {
1098 $token = $1;
1099 $expected = ( $token =~ m{^[=!]~$} ) ? 'RE' : '';
1100 }
1101 else
1102 {
1103 $token = '';
1104 last;
1105 }
1106  
1107 if( length( $token ) )
1108 {
1109 # push( @tokens, $token );
1110 $tokens->push( $token );
1111 }
1112 }
1113
1114 if( pos( $path ) < length( $path ) )
1115 {
1116 my $marker = ( '.' x ( pos( $path ) -1 ) );
1117 $path = substr( $path, 0, pos( $path ) + 8 ) . '...';
1118 $path =~ s/\n/ /g;
1119 $path =~ s/\t/ /g;
1120 die "Query:\n", "$path\n", $marker, "^^^\n", "Invalid query somewhere around here (I think)\n";
1121 # return( $self->error( "Query:\n", "$path\n", $marker, "^^^\n", "Invalid query somewhere around here (I think)" ) );
1122 }
1123 return( $tokens );
1124 }
1125  
1126 sub _xml_escape_text
1127 {
1128 my( $self, $text ) = @_;
1129 my $entities = { '&' => '&amp;', '<' => '&lt;', '>' => '&gt;', '"' => '&quote;' };
1130 $text =~ s{([&<>])}{$entities->{$1}}g;
1131 return( $text );
1132 }
1133  
1134 1;
1135 # NOTE: POD
1136 __END__
1137  
1138 =encoding utf-8
1139  
1140 =head1 NAME
1141  
1142 HTML::Object::XPath - HTML Object XPath Class
1143  
1144 =head1 SYNOPSIS
1145  
1146 use HTML::Object;
1147 use HTML::Object::XQuery;
1148 use HTML::Object::XPath;
1149 my $this = HTML::Object::XPath->new || die( HTML::Object::XPath->error, "\n" );
1150  
1151 my $p = HTML::Object->new;
1152 my $doc = $p->parse_file( $path_to_html_file ) || die( $p->error );
1153 # Returns a list of HTML::Object::Element objects matching the select, which is
1154 # converted into a xpath
1155 my @nodes = $doc->find( 'p' );
1156  
1157 # or directly:
1158 use HTML::Object::XPath;
1159 my $xp = use HTML::Object::XPath->new;
1160 my @nodes = $xp->findnodes( $xpath, $element_object );
1161  
1162 =head1 VERSION
1163  
1164 v0.2.0
1165  
1166 =head1 DESCRIPTION
1167  
1168 This module implements the XPath engine used by L<HTML::Object::XQuery> to provide a jQuery-like interface to query the parsed DOM object.
1169  
1170 =head1 METHODS
1171  
1172 =head2 clear_namespaces
1173  
1174 Clears all previously set namespace mappings.
1175  
1176 =head2 exists
1177  
1178 Provided with a C<path> and a C<context> and this returns true if the given path exists.
1179  
1180 =head2 findnodes
1181  
1182 Provided with a C<path> and a C<context> this returns a list of nodes found by C<path>, optionally in context C<context>.
1183  
1184 In scalar context it returns an HTML::Object::XPath::NodeSet object.
1185  
1186 =head2 findnodes_as_string
1187  
1188 Provided with a C<path> and a C<context> and this returns the nodes found as a single string. The result is not guaranteed to be valid HTML though (it could for example be just text if the query returns attribute values).
1189  
1190 =head2 findnodes_as_strings
1191  
1192 Provided with a C<path> and a C<context> and this returns the nodes found as a list of strings, one per node found.
1193  
1194 =head2 findvalue
1195  
1196 Provided with a C<path> and a C<context> and this returns the result as a string (the concatenation of the values of the result nodes).
1197  
1198 =head2 findvalues
1199  
1200 Provided with a C<path> and a C<context> and this returns the values of the result nodes as a list of strings.
1201  
1202 =head2 matches($node, $path, $context)
1203  
1204 Provided with a C<node> L<object|HTML::Object::Element>, C<path> and a C<context> and this returns true if the node matches the path.
1205  
1206 =head2 find
1207  
1208 Provided with a C<path> and a C<context> and this returns either a L<HTML::Object::XPath::NodeSet> object containing the nodes it found (or empty if no nodes matched the path), or one of L<HTML::Object::XPath::Literal> (a string), L<HTML::Object::XPath::Number>, or L<HTML::Object::XPath::Boolean>. It should always return something - and you can use ->isa() to find out what it returned. If you need to check how many nodes it found you should check $nodeset->size.
1209  
1210 See L<HTML::Object::XPath::NodeSet>.
1211  
1212 =head2 get_namespace ($prefix, $node)
1213  
1214 Provided with a C<prefix> and a C<node> L<object|HTML::Object::Element> and this returns the uri associated to the prefix for the node (mostly for internal usage)
1215  
1216 =head2 get_var
1217  
1218 Provided with a variable name, and this returns the value of the XPath variable (mostly for internal usage)
1219  
1220 =head2 getNodeText
1221  
1222 Provided with a C<path> and this returns the text string for a particular node. It returns a string, or C<undef> if the node does not exist.
1223  
1224 =head2 namespaces
1225  
1226 Sets or gets an hash reference of namespace attributes.
1227  
1228 =head2 new_expr
1229  
1230 Create a new L<HTML::Object::XPath::Expr>, passing it whatever argument was provided, and returns the newly instantiated object, or C<undef> upon L<error|Module::Generic/error>
1231  
1232 =head2 new_function
1233  
1234 Create a new L<HTML::Object::XPath::Function> object, passing it whatever argument was provided, and returns the newly instantiated object, or C<undef> upon L<error|Module::Generic/error>
1235  
1236 =head2 new_literal
1237  
1238 Create a new L<HTML::Object::XPath::Literal> object, passing it whatever argument was provided, and returns the newly instantiated object, or C<undef> upon L<error|Module::Generic/error>
1239  
1240 =head2 new_location_path
1241  
1242 Create a new L<HTML::Object::XPath::LocationPath> object, passing it whatever argument was provided, and returns the newly instantiated object, or C<undef> upon L<error|Module::Generic/error>
1243  
1244 =head2 new_nodeset
1245  
1246 Create a new L<HTML::Object::XPath::NodeSet> object, passing it whatever argument was provided, and returns the newly instantiated object, or C<undef> upon L<error|Module::Generic/error>
1247  
1248 =head2 new_number
1249  
1250 Create a new L<HTML::Object::XPath::Number> object, passing it whatever argument was provided, and returns the newly instantiated object, or C<undef> upon L<error|Module::Generic/error>
1251  
1252 =head2 new_root
1253  
1254 Create a new L<HTML::Object::XPath::Root> object, passing it whatever argument was provided, and returns the newly instantiated object, or C<undef> upon L<error|Module::Generic/error>
1255  
1256 =head2 new_step
1257  
1258 Create a new L<HTML::Object::XPath::Step> object, passing it whatever argument was provided, and returns the newly instantiated object, or C<undef> upon L<error|Module::Generic/error>
1259  
1260 =head2 new_variable
1261  
1262 Create a new L<HTML::Object::XPath::Variable> object, passing it whatever argument was provided, and returns the newly instantiated object, or C<undef> upon L<error|Module::Generic/error>
1263  
1264 =head2 set_namespace
1265  
1266 Provided with a C<prefix> and an C<uri> and this sets the namespace prefix mapping to the uri.
1267  
1268 Normally in L<HTML::Object::XPath> the prefixes in XPath node tests take their context from the current node. This means that foo:bar will always match an element <foo:bar> regardless of the namespace that the prefix foo is mapped to (which might even change within the document, resulting in unexpected results). In order to make prefixes in XPath node tests actually map to a real URI, you need to enable that via a call to the set_namespace method of your HTML::Object::XPath object.
1269  
1270 =head2 parse
1271  
1272 Provided with an XPath expression and this returns a new L<HTML::Object::XPath::Expr> object that can then be used repeatedly.
1273  
1274 You can create an XPath expression from a CSS selector expression using L<HTML::selector::XPath>
1275  
1276 =head2 set_strict_namespaces
1277  
1278 Takes a boolean value.
1279  
1280 By default, for historical as well as convenience reasons, L<HTML::Object::XPath> has a slightly non-standard way of dealing with the default namespace.
1281  
1282 If you search for C<//tag> it will return elements C<tag>. As far as I understand it, if the document has a default namespace, this should not return anything. You would have to first do a C<set_namespace>, and then search using the namespace.
1283  
1284 Passing a true value to C<set_strict_namespaces> will activate this behaviour, passing a false value will return it to its default behaviour.
1285  
1286 =head2 set_var
1287  
1288 Provided with a variable name and its value and this sets an XPath variable (that can be used in queries as C<$var>)
1289  
1290 =head1 NODE STRUCTURE
1291  
1292 All nodes have the same first 2 entries in the array: node_parent and node_pos. The type of the node is determined using the ref() function.
1293  
1294 The node_parent always contains an entry for the parent of the current node - except for the root node which has undef in there. And node_pos is the position of this node in the array that it is in (think: $node == $node->[node_parent]->[node_children]->[$node->[node_pos]] )
1295  
1296 Nodes are structured as follows:
1297  
1298 =head2 Root Node
1299  
1300 The L<root node|HTML::Object::Root> is just an element node with no parent.
1301  
1302 [
1303 undef, # node_parent - check for undef to identify root node
1304 undef, # node_pos
1305 undef, # node_prefix
1306 [ ... ], # node_children (see below)
1307 ]
1308  
1309 =head2 L<Element|HTML::Object::Element> Node
1310  
1311 [
1312 $parent, # node_parent
1313 <position in current array>, # node_pos
1314 'xxx', # node_prefix - namespace prefix on this element
1315 [ ... ], # node_children
1316 'yyy', # node_name - element tag name
1317 [ ... ], # node_attribs - attributes on this element
1318 [ ... ], # node_namespaces - namespaces currently in scope
1319 ]
1320  
1321 =head2 L<Attribute|HTML::Object::Attribute> Node
1322  
1323 [
1324 $parent, # node_parent - the element node
1325 <position in current array>, # node_pos
1326 'xxx', # node_prefix - namespace prefix on this element
1327 'href', # node_key - attribute name
1328 'ftp://ftp.com/', # node_value - value in the node
1329 ]
1330  
1331 =head2 L<Text|HTML::Object::Text> Nodes
1332  
1333 [
1334 $parent,
1335 <pos>,
1336 'This is some text' # node_text - the text in the node
1337 ]
1338  
1339 =head2 L<Comment|HTML::Object::Comment> Nodes
1340  
1341 [
1342 $parent,
1343 <pos>,
1344 'This is a comment' # node_comment
1345 ]
1346  
1347 =head1 AUTHOR
1348  
1349 Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>
1350  
1351 =head1 SEE ALSO
1352  
1353 L<HTML::Object::XPath::Boolean>, L<HTML::Object::XPath::Expr>, L<HTML::Object::XPath::Function>, L<HTML::Object::XPath::Literal>, L<HTML::Object::XPath::LocationPath>, L<HTML::Object::XPath::NodeSet>, L<HTML::Object::XPath::Number>, L<HTML::Object::XPath::Root>, L<HTML::Object::XPath::Step>, L<HTML::Object::XPath::Variable>
1354  
1355 L<Mozilla documentation|https://developer.mozilla.org/en-US/docs/Web/XPath/Introduction_to_using_XPath_in_JavaScript>
1356  
1357 =head1 COPYRIGHT & LICENSE
1358  
1359 Copyright(c) 2021 DEGUEST Pte. Ltd.
1360  
1361 You can use, copy, modify and redistribute this package and associated files under the same terms as Perl itself.
1362  
1363 =cut