File: XPath.pm

package info (click to toggle)
libhtml-selector-xpath-perl 0.28-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 260 kB
  • sloc: perl: 1,716; makefile: 2
file content (446 lines) | stat: -rw-r--r-- 13,637 bytes parent folder | download
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
package HTML::Selector::XPath;

use strict;
use 5.008_001;
our $VERSION = '0.28';

require Exporter;
our @EXPORT_OK = qw(selector_to_xpath);
*import = \&Exporter::import;

use Carp;

sub selector_to_xpath {
    __PACKAGE__->new(shift)->to_xpath(@_);
}

# XXX: Identifiers should also allow any characters U+00A0 and higher, and any
# escaped characters.
my $ident = qr/(?![0-9]|-[-0-9])[-_a-zA-Z0-9]+/;

my $reg = {
    # tag name/id/class
    element => qr/^([#.]?)([^\s'"#.\/:@,=~>()\[\]|]*)((\|)([a-z0-9\\*_-]*))?/i,
    # attribute presence
    attr1   => qr/^\[ \s* ($ident) \s* \]/x,
    # attribute value match
    attr2   => qr/^\[ \s* ($ident) \s*
        ( [~|*^\$!]? = ) \s*
        (?: ($ident) | "([^"]*)" | '([^']*)') \s* \] /x,
    badattr => qr/^\[/,
    attrN   => qr/^:not\(/i, # we chop off the closing parenthesis below in the code
    pseudo  => qr/^:([-\w]+\(?)/i,
    # adjacency/direct descendance
    combinator => qr/^(\s*[>+~\s](?!,))/i,
    # rule separator
    comma => qr/^\s*,\s*/i,
};

sub new {
    my($class, $exp) = @_;
    bless { expression => $exp }, $class;
}

sub selector {
    my $self = shift;
    $self->{expression} = shift if @_;
    $self->{expression};
}

sub convert_attribute_match {
    my ($left,$op,$right) = @_;
    # negation (e.g. [input!="text"]) isn't implemented in CSS, but include it anyway:
    if ($op eq '!=') {
        "\@$left!='$right'";
    } elsif ($op eq '~=') { # substring attribute match
        "contains(concat(' ', \@$left, ' '), ' $right ')";
    } elsif ($op eq '*=') { # real substring attribute match
        "contains(\@$left, '$right')";
    } elsif ($op eq '|=') {
        "\@$left='$right' or starts-with(\@$left, '$right-')";
    } elsif ($op eq '^=') {
        "starts-with(\@$left,'$^N')";
    } elsif ($op eq '$=') {
        my $n = length($^N) - 1;
        "substring(\@$left,string-length(\@$left)-$n)='$^N'";
    } else { # exact match
        "\@$left='$^N'";
    }
}

sub _generate_child {
    my ($direction,$name,$a,$b) = @_;
    if ($a == 0) { # 0n+b
        $b--;
        "[count($direction-sibling::$name) = $b and parent::*]"
    } elsif ($a > 0) { # an + b
        return "[not((count($direction-sibling::$name)+1)<$b) and ((count($direction-sibling::$name) + 1) - $b) mod $a = 0 and parent::*]"
    } else { # -an + $b
        $a = -$a;
        return "[not((count($direction-sibling::$name)+1)>$b) and (($b - (count($direction-sibling::$name) + 1)) mod $a) = 0 and parent::*]"
    }
}

sub nth_child {
    my ($a,$b) = @_;
    if (@_ == 1) {
        ($a,$b) = (0,$a);
    }
    _generate_child('preceding', '*', $a, $b);
}

sub nth_last_child {
    my ($a,$b) = @_;
    if (@_ == 1) {
        ($a,$b) = (0,$a);
    }
    _generate_child('following', '*', $a, $b);
}

# A hacky recursive descent
# Only descends for :not(...)
sub consume_An_plus_B {
    my( $rrule ) = @_;

    my( $A, $B );

    if( $$rrule =~ s/^odd\s*\)// ) {
        ($A,$B) = (2, 1)
    } elsif( $$rrule =~ s/^even\s*\)// ) {
        ($A,$B) = (2, 0)
    } elsif( $$rrule =~ s/^\s*(-?\d+)\s*\)// ) {
        ($A,$B) = (0, $1)
    } elsif( $$rrule =~ s/^\s*(-?\d*)\s*n\s*(?:\+\s*(\d+))?\s*\)// ) {
        ($A,$B) = ($1, $2 || 0);
        if( ! defined $A ) {
            $A = '0';
        } elsif( $A eq '-') {
            $A = '-1';
        } elsif( $A eq '' ) {
            $A = '1';
        }
    } else {
        croak "Can't parse formula from '$$rrule'";
    }

    return ($A, $B);
}

sub consume {
    my ($self, $rule, %parms) = @_;
    my $root = $parms{root} || '/';

    return [$rule,''] if $rule =~ m!^/!; # If we start with a slash, we're already an XPath?!

    my @parts = ("$root/");
    my $last_rule = '';
    my @next_parts;

    my $wrote_tag;
    my $root_index = 0; # points to the current root
    # Loop through each "unit" of the rule
    while (length $rule && $rule ne $last_rule) {
        $last_rule = $rule;

        $rule =~ s/^\s*|\s*$//g;
        last unless length $rule;

        # Prepend explicit first selector if we have an implicit selector
        # (that is, if we start with a combinator)
        if ($rule =~ /$reg->{combinator}/) {
            $rule = "* $rule";
        }

        # Match elements
        if ($rule =~ s/$reg->{element}//) {
            my ($id_class,$name,$lang) = ($1,$2,$3);

            # to add *[1]/self:: for follow-sibling
            if (@next_parts) {
                push @parts, @next_parts; #, (pop @parts);
                @next_parts = ();
            }

            my $tag = $id_class eq '' ? $name || '*' : '*';

            if (defined $parms{prefix} and not $tag =~ /[*:|]/) {
                $tag = join ':', $parms{prefix}, $tag;
            }

            if (! $wrote_tag++) {
                push @parts, $tag;
            }

            # XXX Shouldn't the RE allow both, ID and class?
            if ($id_class eq '#') { # ID
                push @parts, "[\@id='$name']";
            } elsif ($id_class eq '.') { # class
                push @parts, "[contains(concat(' ', normalize-space(\@class), ' '), ' $name ')]";
            };
        };

        # Match attribute selectors
        if ($rule =~ s/$reg->{attr2}//) {
            push @parts, "[", convert_attribute_match( $1, $2, $^N ), "]";
        } elsif ($rule =~ s/$reg->{attr1}//) {
            # If we have no tag output yet, write the tag:
            if (! $wrote_tag++) {
                push @parts, '*';
            }
            push @parts, "[\@$1]";
        } elsif ($rule =~ $reg->{badattr}) {
            Carp::croak "Invalid attribute-value selector '$rule'";
        }

        # Match negation
        if ($rule =~ s/$reg->{attrN}//) {
            # Now we parse the rest, and after parsing the subexpression
            # has stopped, we must find a matching closing parenthesis:
            if ($rule =~ s/$reg->{attr2}//) {
                push @parts, "[not(", convert_attribute_match( $1, $2, $^N ), ")]";
            } elsif ($rule =~ s/$reg->{attr1}//) {
                push @parts, "[not(\@$1)]";
            } elsif ($rule =~ /$reg->{badattr}/) {
                Carp::croak "Invalid negated attribute-value selector ':not($rule)'";
            } else {
                my( $new_parts, $leftover ) = $self->consume( $rule, %parms );
                shift @$new_parts; # remove '//'
                my $xpath = join '', @$new_parts;

                push @parts, "[not(self::$xpath)]";
                $rule = $leftover;
            }
            $rule =~ s!^\s*\)!!
                or die "Unbalanced parentheses at '$rule'";
        }

        # Ignore pseudoclasses/pseudoelements
        while ($rule =~ s/$reg->{pseudo}//) {
            if ( my @expr = $self->parse_pseudo($1, \$rule) ) {
                push @parts, @expr;
            } elsif ( $1 eq 'disabled') {
                push @parts, '[@disabled]';
            } elsif ( $1 eq 'checked') {
                push @parts, '[@checked]';
            } elsif ( $1 eq 'selected') {
                push @parts, '[@selected]';
            } elsif ( $1 eq 'text') {
                push @parts, '*[@type="text"]';
            } elsif ( $1 eq 'first-child') {
                # Translates to :nth-child(1)
                push @parts, nth_child(1);
            } elsif ( $1 eq 'last-child') {
                push @parts, nth_last_child(1);
            } elsif ( $1 eq 'only-child') {
                push @parts, nth_child(1), nth_last_child(1);
            } elsif ($1 =~ /^lang\($/) {
                $rule =~ s/\s*([\w\-]+)\s*\)//
                    or Carp::croak "Can't parse language part from $rule";
                push @parts, "[\@xml:lang='$1' or starts-with(\@xml:lang, '$1-')]";
            } elsif ($1 =~ /^nth-child\(\s*$/) {
                my( $A, $B ) = consume_An_plus_B(\$rule);
                push @parts, nth_child($A, $B);
            } elsif ($1 =~ /^nth-last-child\(\s*$/) {
                my( $A, $B ) = consume_An_plus_B(\$rule);
                push @parts, nth_last_child($A, $B);
            } elsif ($1 =~ /^first-of-type\s*$/) {
                my $type = $parts[-1];
                push @parts, _generate_child('preceding', $type, 0, 1);

            } elsif ($1 =~ /^nth-of-type\(\s*$/) {
                my( $A, $B ) = consume_An_plus_B(\$rule);
                my $type = $parts[-1];
                push @parts, _generate_child('preceding', $type, $A, $B);

            } elsif ($1 =~ /^last-of-type$/) {
                push @parts, "[last()]";

            # Err?! This one does not really exist in the CSS spec...
            # Why did I add this?
            } elsif ($1 =~ /^contains\($/) {
                if( $rule =~ s/^\s*"([^"]*)"\s*\)// ) {
                    push @parts, qq{[text()[contains(string(.),"$1")]]};
                } elsif( $rule =~ s/^\s*'([^']*)'\s*\)// ) {
                    push @parts, qq{[text()[contains(string(.),"$1")]]};
                } else {
                    return( \@parts, $rule );
                    #die "Malformed string in :contains(): '$rule'";
                };
            } elsif ( $1 eq 'root') {
                # This will give surprising results if you do E > F:root
                $parts[$root_index] = $root;
            } elsif ( $1 eq 'empty') {
                push @parts, "[not(* or text())]";
            } else {
                Carp::croak "Can't translate '$1' pseudo-class";
            }
        }

        # Match combinators (whitespace, >, + and ~)
        if ($rule =~ s/$reg->{combinator}//) {
            my $match = $1;
            if ($match =~ />/) {
                push @parts, "/";
            } elsif ($match =~ /\+/) {
                push @parts, "/following-sibling::*[1]/self::";
            } elsif ($match =~ /\~/) {
                push @parts, "/following-sibling::";
            } elsif ($match =~ /^\s*$/) {
                push @parts, "//"
            } else {
                die "Weird combinator '$match'"
            }

            # new context
            undef $wrote_tag;
        }

        # Match commas
        if ($rule =~ s/$reg->{comma}//) {
            push @parts, " | ", "$root/"; # ending one rule and beginning another
            $root_index = $#parts;
            undef $wrote_tag;
        }
    }
    return \@parts, $rule
}

sub to_xpath {
    my $self = shift;
    my $rule = $self->{expression} or return;
    my %parms = @_;

    my($result,$leftover) = $self->consume( $rule, %parms );
    $leftover
        and die "Invalid rule, couldn't parse '$leftover'";
    return join '', @$result;

}

sub parse_pseudo {
    # nop
}

1;
__END__

=head1 NAME

HTML::Selector::XPath - CSS Selector to XPath compiler

=head1 SYNOPSIS

  use HTML::Selector::XPath;

  my $selector = HTML::Selector::XPath->new("li#main");
  $selector->to_xpath; # //li[@id='main']

  # functional interface
  use HTML::Selector::XPath 'selector_to_xpath';
  my $xpath = selector_to_xpath('div.foo');

  my $relative = selector_to_xpath('div.foo', root => '/html/body/p' );
  # /html/body/p/div[contains(concat(' ', @class, ' '), ' foo ')]

  my $relative = selector_to_xpath('div:root', root => '/html/body/p' );
  # /html/body/p/div

=head1 DESCRIPTION

HTML::Selector::XPath is a utility function to compile full set of
CSS2 and partial CSS3 selectors to the equivalent XPath expression.

=head1 FUNCTIONS and METHODS

=over 4

=item selector_to_xpath

  $xpath = selector_to_xpath($selector, %options);

Shortcut for C<< HTML::Selector::XPath->new(shift)->to_xpath(@_) >>.
Exported upon request.

=item new

  $sel = HTML::Selector::XPath->new($selector, %options);

Creates a new object.

=item to_xpath

  $xpath = $sel->to_xpath;
  $xpath = $sel->to_xpath(root => "."); # ./foo instead of //foo

Returns the translated XPath expression. You can optionally pass
C<root> parameter, to specify which root to start the expression. It
defaults to C</>.

The optional C<prefix> option allows you to specify a namespace
prefix for the generated XPath expression.

=back

=head1 SUBCLASSING NOTES

=over 4

=item parse_pseudo

This method is called during xpath construction when we encounter a pseudo
selector (something that begins with comma). It is passed the selector and
a reference to the string we are parsing. It should return one or more
xpath sub-expressions to add to the parts if the selector is handled,
otherwise return an empty list.

=back

=head1 CAVEATS

=head2 CSS SELECTOR VALIDATION

This module doesn't validate whether the original CSS Selector
expression is valid. For example,

  div.123foo

is an invalid CSS selector (class names should not begin with
numbers), but this module ignores that and tries to generate
an equivalent XPath expression anyway.

=head1 COPYRIGHT

Tatsuhiko Miyagawa 2006-2011

Max Maischein 2011-

=head1 AUTHOR

Tatsuhiko Miyagawa E<lt>miyagawa@bulknews.netE<gt>

Most of the logic is based on Joe Hewitt's getElementsBySelector.js on
L<http://www.joehewitt.com/blog/2006-03-20.php> and Andrew Dupont's
patch to Prototype.js on L<http://dev.rubyonrails.org/ticket/5171>,
but slightly modified using Aristotle Pegaltzis' CSS to XPath
translation table per L<http://plasmasturm.org/log/444/>

Also see

L<http://www.mail-archive.com/www-archive@w3.org/msg00906.html>

and

L<http://kilianvalkhof.com/2008/css-xhtml/the-css3-not-selector/>

=head1 LICENSE

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

=head1 SEE ALSO

L<http://www.w3.org/TR/REC-CSS2/selector.html>
L<http://use.perl.org/~miyagawa/journal/31090>
L<https://en.wikibooks.org/wiki/XPath/CSS_Equivalents>

=cut