summaryrefslogtreecommitdiff
path: root/lib/PPIx/XPath.pm
blob: 05e87434215c058237d13c6397ef93f460e1f2cb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
package PPIx::XPath; 
use strict;
use warnings;
use PPI;
use Carp;
use Scalar::Util qw(reftype blessed);
use Tree::XPathEngine;
use 5.006;
 
our $VERSION='2.01';
 
sub new {
    my ($class,$source) = @_;
 
    croak "PPIx::XPath->new needs a source document" unless defined($source);
 
    my $doc;
    if (blessed($source) && $source->isa('PPI::Node')) {
        $doc = $source;
    }
    elsif (reftype($sourceeq 'SCALAR'
       or (!ref($source) && -f $source)) {
        $doc = PPI::Document->new($source);
    }
    else {
        croak "PPIx::XPath expects either a PPI::Node or a file" .
            " got a: [" .( ref($source) || $source ). ']';
    }
 
    return bless {doc=>$doc},$class;
}
 
# PPIx::XPath 1.0.0 allowed the use of partial package names as node names; 
# this collides with the axis specification of proper XPath. 
# Here we change the "old-style" node names into the new names 
{
    my $legacy_names_rx;my %new_name_for;
    sub clean_xpath_expr {
        my (undef,$expr)=@_;
 
        $expr =~ s{$legacy_names_rx}{$new_name_for{$1}}ge;
 
        return $expr;
    }
 
    my @PPI_Packs;
    # taken from Devel::Symdump 
    my @packages=('PPI');
    while (my $pack=shift(@packages)) {
        my %pack_symbols = do {
            no strict 'refs'## no critic(ProhibitNoStrict) 
            %{*{"$pack\::"}}
        };
        while (my ($key,$val)=each(%pack_symbols)) {
            local *ENTRY=$val;
            if (defined $val && defined *ENTRY{HASH} && $key=~/::$/
                    && $key !~ /^::/
                    && $key ne 'main::' && $key ne '<none>::') {
 
                my $p = "$pack\::$key";$p =~ s{::$}{};
                push @packages,$p;
                $p =~ s{^PPI::}{};
 
                next unless $p=~/::/;
 
                my $newname=$p;
                $newname =~ s{::}{-}g;
                push @PPI_Packs,$p;
                $new_name_for{$p}=$newname;
            }
        }
    }
    $legacy_names_rx='\b('.join('|',
                                sort {length($b<=> length($a)} @PPI_Packs
                            ).')\b';
    $legacy_names_rx=qr{$legacy_names_rx};
}
 
sub match {
    my ($self,$expr) = @_;
 
    $expr=$self->clean_xpath_expr($expr);
 
    Tree::XPathEngine->new()->findnodes($expr,$self->{doc});
}
 
package PPI::Element; 
use strict;
use warnings;
 
sub xpath_get_name              my $pack_name=substr($_[0]->class,5);
                                  $pack_name =~ s/::/-/g;
                                  $pack_name }
sub xpath_get_next_sibling      $_[0]->snext_sibling }
sub xpath_get_previous_sibling  $_[0]->sprevious_sibling }
sub xpath_get_root_node         $_[0]->top }
sub xpath_get_parent_node       $_[0]->parent }
sub xpath_is_element_node       { 1 }
sub xpath_is_attribute_node     { 0 }
sub xpath_is_document_node      { 0 }
sub xpath_get_attributes        {
    return
        PPIx::XPath::Attr->new($_[0],'significant'),
        PPIx::XPath::Attr->new($_[0],'content'),
}
sub xpath_to_literal            "$_[0]" }
sub xpath_get_value             "$_[0]" }
sub xpath_string_value          "$_[0]" }
 
sub xpath_cmp {
    my$a$b)= @_;
    if ( UNIVERSAL::isa( $b'PPIx::XPath::Attr')) {
        # elt <=> att, compare the elt to the att->{elt} 
        # if the elt is the att->{elt} (cmp return 0) then -1, elt is before att 
        return ($a->_xpath_elt_cmp( $b->{parent}) ) || -1 ;
    }
    elsif ( UNIVERSAL::isa( $b'PPI::Document')) {
        # elt <=> document, elt is after document 
        return 1;
    else {
        # 2 elts, compare them 
        return $a->_xpath_elt_cmp( $b);
    }
}
 
sub _xpath_elt_cmp {
    my ($a,$b)=@_;
 
    # easy cases 
    return  0 if$a == $b);
    return  1 if$a->_xpath_in($b)); # a starts after b 
    return -1 if$b->_xpath_in($a)); # a starts before b 
 
    # ancestors does not include the element itself 
    my @a_pile= ($a$a->_xpath_ancestors);
    my @b_pile= ($b$b->_xpath_ancestors);
 
    # the 2 elements are not in the same twig 
    return undef unless$a_pile[-1] == $b_pile[-1]);
 
    # find the first non common ancestors (they are siblings) 
    my $a_ancpop @a_pile;
    my $b_ancpop @b_pile;
 
    while$a_anc == $b_anc) {
        $a_ancpop @a_pile;
        $b_ancpop @b_pile;
    }
 
    # from there move left and right and figure out the order 
    my$a_prev$a_next$b_prev$b_next)= ($a_anc$a_anc$b_anc$b_anc);
    while () {
        $a_prev$a_prev->sprevious_sibling || return( -1);
        return 1 if$a_prev == $b_next);
        $a_next$a_next->snext_sibling || return( 1);
        return -1 if$a_next == $b_prev);
        $b_prev$b_prev->sprevious_sibling || return( 1);
        return -1 if$b_prev == $a_next);
        $b_next$b_next->snext_sibling || return( -1);
        return 1 if$b_next == $a_prev);
    }
}
 
sub _xpath_in {
    my ($self$ancestor)= @_;
    while ( $self$self->parent) {
        return $self if ( $self ==  $ancestor);
    }
}
 
sub _xpath_ancestors {
    my$self)= @_;
    my @ancestors;
    while ( $self$self->parent) {
        push @ancestors$self;
    }
    return @ancestors;
}
 
package PPI::Token; 
use strict;
use warnings;
 
sub xpath_get_child_nodes       { return }
 
package PPI::Token::Quote::Double; 
use strict;
use warnings;
 
sub xpath_get_attributes        {
    return $_[0]->SUPER::xpath_get_attributes,
        PPIx::XPath::Attr->new($_[0],'interpolations'),
}
 
package PPI::Token::Number; 
use strict;
use warnings;
 
sub xpath_get_attributes        {
    return $_[0]->SUPER::xpath_get_attributes,
        PPIx::XPath::Attr->new($_[0],'base'),
}
 
package PPI::Token::Word; 
use strict;
use warnings;
 
sub xpath_get_attributes        {
    return $_[0]->SUPER::xpath_get_attributes,
        PPIx::XPath::Attr->new($_[0],'method-call'),
}
 
package PPI::Token::Comment; 
use strict;
use warnings;
 
sub xpath_get_attributes        {
    return $_[0]->SUPER::xpath_get_attributes,
        PPIx::XPath::Attr->new($_[0],'line'),
}
 
package PPI::Token::HereDoc; 
use strict;
use warnings;
 
# TODO: add access to the contents of the heredoc (->heredoc method) 
 
sub xpath_get_attributes        {
    return $_[0]->SUPER::xpath_get_attributes,
        PPIx::XPath::Attr->new($_[0],'terminator'),
}
 
package PPI::Token::Prototype; 
use strict;
use warnings;
 
sub xpath_to_literal            $_[0]->prototype }
sub xpath_get_value             $_[0]->prototype }
sub xpath_string_value          $_[0]->prototype }
 
package PPI::Node; 
use strict;
use warnings;
 
sub xpath_get_child_nodes       $_[0]->schildren }
sub xpath_get_attributes        {
    return $_[0]->SUPER::xpath_get_attributes,
        PPIx::XPath::Attr->new($_[0],'scope'),
}
 
package PPI::Token::Attribute; 
use strict;
use warnings;
 
sub xpath_get_attributes        {
    return $_[0]->SUPER::xpath_get_attributes,
        PPIx::XPath::Attr->new($_[0],'identifier'),
        PPIx::XPath::Attr->new($_[0],'parameters'),
}
 
package PPI::Token::Symbol; 
use strict;
use warnings;
 
sub xpath_get_attributes        {
    return $_[0]->SUPER::xpath_get_attributes,
        PPIx::XPath::Attr->new($_[0],'symbol'),
        PPIx::XPath::Attr->new($_[0],'canonical'),
        PPIx::XPath::Attr->new($_[0],'raw_type'),
        PPIx::XPath::Attr->new($_[0],'symbol_typel'),
}
 
package PPI::Statement; 
use strict;
use warnings;
 
sub xpath_get_attributes        {
    return $_[0]->SUPER::xpath_get_attributes,
        PPIx::XPath::Attr->new($_[0],'label'),
        PPIx::XPath::Attr->new($_[0],'stable'),
        PPIx::XPath::Attr->new($_[0],'type'),
}
 
package PPI::Statement::Sub; 
use strict;
use warnings;
 
sub xpath_get_attributes        {
    return $_[0]->SUPER::xpath_get_attributes,
        PPIx::XPath::Attr->new($_[0],'name'),
        PPIx::XPath::Attr->new($_[0],'prototype'),
        PPIx::XPath::Attr->new($_[0],'forward'),
        PPIx::XPath::Attr->new($_[0],'reserved'),
}
 
package PPI::Statement::Package; 
use strict;
use warnings;
 
sub xpath_get_attributes        {
    return $_[0]->SUPER::xpath_get_attributes,
        PPIx::XPath::Attr->new($_[0],'namespace'),
        PPIx::XPath::Attr->new($_[0],'file-scoped'),
}
 
package PPI::Statement::Include; 
use strict;
use warnings;
 
sub xpath_get_attributes        {
    return $_[0]->SUPER::xpath_get_attributes,
        PPIx::XPath::Attr->new($_[0],'module'),
        PPIx::XPath::Attr->new($_[0],'module-version'),
        PPIx::XPath::Attr->new($_[0],'version'),
        PPIx::XPath::Attr->new($_[0],'version-literal'),
        PPIx::XPath::Attr->new($_[0],'pragma'),
}
 
package PPI::Structure; 
use strict;
use warnings;
 
sub xpath_get_attributes        {
    return $_[0]->SUPER::xpath_get_attributes,
        PPIx::XPath::Attr->new($_[0],'start'),
        PPIx::XPath::Attr->new($_[0],'finish'),
        PPIx::XPath::Attr->new($_[0],'braces'),
}
 
package PPI::Document; 
use strict;
use warnings;
 
sub xpath_get_root_node         $_[0] }
sub xpath_get_parent_node       { return }
sub xpath_is_attribute_node     { 0 }
sub xpath_is_document_node      { 1 }
 
package PPIx::XPath::Attr; 
use strict;
use warnings;
 
sub new {
    my ($class,$parent,$name)=@_;
 
    my $meth=$parent->can($name);
    return unless $meth;
 
    my $value;
    eval {$value=$meth->($parent);1} or return;
 
    return unless defined $value;
 
    return bless {parent=>$parent,name=>$name,value=>$value},$class;
}
 
sub xpath_get_name              $_[0]->{name} }
sub xpath_get_root_node         $_[0]->{parent}->top }
sub xpath_get_parent_node       $_[0]->{parent} }
sub xpath_is_element_node       { 0 }
sub xpath_is_attribute_node     { 1 }
sub xpath_is_document_node      { 0 }
sub xpath_to_literal            $_[0]->{value} }
sub xpath_get_value             $_[0]->{value} }
sub xpath_string_value          $_[0]->{value} }
sub xpath_to_number             { Tree::XPathEngine::Number->new($_[0]->{value}) }
 
sub xpath_cmp($$) {
    my$a$b)= @_;
    if ( UNIVERSAL::isa( $b'PPIx::XPath::Attr')) {
        # 2 attributes, compare their elements, then their name 
        return ($a->{parent}->_xpath_elt_cmp( $b->{parent}) ) 
            || ($a->{namecmp $b->{name});
    }
    elsif ( UNIVERSAL::isa( $b'PPI::Document')) {
        # att <=> document, att is after document 
        return 1;
    }
    else {
        # att <=> elt : compare the att->elt and the elt 
        # if att->elt is the elt (cmp returns 0) then 1 (elt is before att) 
        return ($a->{parent}->_xpath_elt_cmp( $b) ) || 1 ;
    }
}
 
1;
__END__
 
=head1 NAME
 
PPIx::XPath - an XPath implementation for the PDOM
 
=head1 SYNOPSIS
 
  use PPI;
  use PPIx::XPath;
  use Tree::XPathEngine;
 
  my $pdom = PPI::Document->new('some_code.pl');
  my $xpath = Tree::XPathEngine->new();
  my @subs = $xpath->findnodes('//Statement-Sub',$pdom);
  my @vars = $xpath->findnodes('//Token-Symbol',$pdom);
 
Deprecated interface, backward-compatible with C<PPIx::XPath> version
1:
 
  use PPIx::XPath;
 
  my $pxp  = PPIx::XPath->new("some_code.pl");
  my @subs = $pxp->match("//Statement::Sub");
  my $vars = $pxp->match("//Token::Symbol");
 
=head1 DESCRIPTION
 
This module augments L<PPI>'s classes with the methods required by
L<Tree::XPathEngine>, allowing you to perform complex XPath matches
against any PDOM tree.
 
See L<Tree::XPathEngine> for details about its methods.
 
=head2 Mapping the PDOM to the XPath data model
 
=over 4
 
=item *
 
Each node in the PDOM is an element as seen by XPath
 
=item *
 
The name of the element is the class name of the node, minus the
initial C<PPI::>, with C<::> replaced by C<->. That is:
 
  ($xpath_name = substr($pdom_node->class,5)) =~ s/::/-/g;
 
=item *
 
Only "significant" nodes are seen by XPath
 
=item *
 
all scalar-valued accessors of PDOM nodes are visible as attributes
 
=item *
 
"here-docs" contents are I<not> mapped
 
=back
 
=head1 BUGS and LIMITATIONS
 
=over 4
 
=item *
 
"here-docs" contents are I<not> mapped
 
=item *
 
node ordering is slow, because I could not find a way in PPI to
compare two nodes for document order; suggestions are most welcome
 
=back
 
=head1 SEE ALSO
 
L<PPI>
 
L<Tree::XPathEngine>
 
L<http://www.w3.org/TR/xpath> (the XPath specification)
 
=head1 AUTHOR
 
Dan Brook <cpan@broquaint.com> original author
 
Gianni Ceccarelli <dakkar@thenautilus.net> Tree::XPathEngine-based re-implementation
 
=cut