blib/lib/XML/XSH2/Functions.pm untested

filter: Statementstmt 0.0% 0 / 3760 Branchbran 0.0% 0 / 2296 Conditioncond 0.0% 0 / 883 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 412 Podpod 0.0% 0 / 334 totaltotal 0.0% 0 / 7685 CC 1149 SCAR 63.3
CC
1149
Cov
0%
insert_node
5112.0
save_doc
2970.0
open_doc
1980.0
CRAP 560.1
1 # -*- cperl -*-
2 # $Id: Functions.pm,v 2.49 2008-01-27 10:48:39 pajas Exp $
3  
4 package XML::XSH2::Functions;
5  
6 #eval "no encoding";
7 #undef $@;
8 use strict;
9 no warnings;
10  
11 use XML::XSH2::Help;
12 use XML::XSH2::Iterators;
13 use IO::File;
14 use File::Spec;
15 use Scalar::Util;
16 use File::Temp qw(tempfile tempdir);
17 use Carp;
18 use URI;
19 use URI::file;
20  
21 use Exporter;
22 use vars qw/@ISA @EXPORT_OK %EXPORT_TAGS $VERSION $REVISION $OUT
23 @PARAM_VARS
24 $_xml_module $_sigint
25 $_xsh $_xpc $_parser @stored_variables
26 $lexical_variables $_newdoc
27 $TRAP_SIGINT $TRAP_SIGPIPE $_die_on_err $_on_exit
28 $_want_returns
29 %_files %_defs %_includes %_ns %_func %COMMANDS
30 $ENCODING $QUERY_ENCODING
31 $INDENT $BACKUPS $SWITCH_TO_NEW_DOCUMENTS $EMPTY_TAGS $SKIP_DTD
32 $QUIET $DEBUG $TEST_MODE $WARNINGS $ERRORS
33 $VALIDATION $RECOVERING $PARSER_EXPANDS_ENTITIES $KEEP_BLANKS
34 $PEDANTIC_PARSER $LOAD_EXT_DTD $PARSER_COMPLETES_ATTRIBUTES
35 $PARSER_EXPANDS_XINCLUDE $MAXPRINTLENGTH
36 $XPATH_AXIS_COMPLETION $STRICT_PWD
37 $XPATH_COMPLETION $DEFAULT_FORMAT $LINE_NUMBERS
38 $RT_LINE $RT_COLUMN $RT_OFFSET $RT_SCRIPT $SCRIPT
39 $BENCHMARK $DUMP $DUMP_APPEND $Xinclude_prefix $HISTFILE
40 $PROMPT
41 /;
42  
43 BEGIN {
44 $VERSION='2.1.7'; # VERSION TEMPLATE
45 $REVISION=q($Revision: 2.49 $);
46 @ISA=qw(Exporter);
47 @PARAM_VARS=qw/$ENCODING
48 $QUERY_ENCODING
49 $INDENT
50 $EMPTY_TAGS
51 $SKIP_DTD
52 $BACKUPS
53 $SWITCH_TO_NEW_DOCUMENTS
54 $QUIET
55 $DEBUG
56 $TEST_MODE
57 $VALIDATION
58 $RECOVERING
59 $PARSER_EXPANDS_ENTITIES
60 $XPATH_AXIS_COMPLETION
61 $XPATH_COMPLETION
62 $KEEP_BLANKS
63 $PEDANTIC_PARSER
64 $LOAD_EXT_DTD
65 $PARSER_COMPLETES_ATTRIBUTES
66 $PARSER_EXPANDS_XINCLUDE
67 $DEFAULT_FORMAT
68 $LINE_NUMBERS
69 $WARNINGS
70 $MAXPRINTLENGTH
71 $HISTFILE
72 $STRICT_PWD
73 $PROMPT
74 /;
75 *XSH_NS=*XML::XSH2::xshNS;
76 *XML::XSH2::Map::XSH_NS=*XML::XSH2::xshNS;
77 *XML::XSH2::Map::OUT=\$OUT;
78 *EMPTY_TAGS=*XML::LibXML::setTagCompression;
79 *SKIP_DTD=*XML::LibXML::skipDTD;
80 *XML::XSH2::Map::PROGRAM_NAME=\$RT_SCRIPT;
81 @EXPORT_OK=(qw(&xsh_init &xsh &xsh_get_output
82 &xsh_set_output &xsh_set_parser
83 &set_quiet &set_debug &set_compile_only_mode
84 &create_doc &open_doc &set_doc
85 &xsh_pwd &out
86 &toUTF8 &fromUTF8 &xsh_set_script
87 &xsh_context_node &xsh_context_var
88 &xsh_xml_parser &xsh_parse_string
89 ),@PARAM_VARS);
90 %EXPORT_TAGS = (
91 default => [@EXPORT_OK],
92 param_vars => [@PARAM_VARS]
93 );
94  
95 $TRAP_SIGINT=0;
96 $_xml_module='XML::XSH2::LibXMLCompat';
97 $INDENT=1;
98 $EMPTY_TAGS=1; # no effect (reseted by XML::LibXML)
99 $SKIP_DTD=0; # no effect (reseted by XML::LibXML)
100 $BACKUPS=1;
101 $SWITCH_TO_NEW_DOCUMENTS=1;
102 $ENCODING='utf-8';
103 $QUERY_ENCODING='utf-8';
104 $QUIET=0;
105 $DEBUG=0;
106 $TEST_MODE=0;
107 $VALIDATION=0;
108 $RECOVERING=0;
109 $PARSER_EXPANDS_ENTITIES=1;
110 $KEEP_BLANKS=1;
111 $PEDANTIC_PARSER=0;
112 $LOAD_EXT_DTD=0;
113 $PARSER_COMPLETES_ATTRIBUTES=1;
114 $PARSER_EXPANDS_XINCLUDE=0;
115 $XPATH_COMPLETION=1;
116 $XPATH_AXIS_COMPLETION='always'; # never / when-empty
117 $DEFAULT_FORMAT='xml';
118 $LINE_NUMBERS=1;
119 $WARNINGS=1;
120 $ERRORS=1;
121 $BENCHMARK=0;
122 $MAXPRINTLENGTH=256;
123 $HISTFILE="$ENV{HOME}/.xsh2_history";
124 $STRICT_PWD=1;
125 $PROMPT='%p> ';
126 *XML::XSH2::Map::CURRENT_SCRIPT=\$RT_SCRIPT;
127  
128 $_newdoc=1;
129 $_die_on_err=1;
130 $_want_returns=0;
131  
132 autoflush STDOUT;
133 autoflush STDERR;
134 $lexical_variables = [];
135 $Xinclude_prefix = 'http://www.w3.org/2001/XInclude';
136 require XML::XSH2::Commands;
137 }
138  
139 sub VERSION {
140 shift if $_[0] eq __PACKAGE__;
141 my $ver = shift;
142 if (defined($ver)) {
143 my @V = split /\./,$VERSION;
144 my @v = split /\./,$ver;
145 for my $component (@v) {
146 croak __PACKAGE__." version $ver required--this is only version $VERSION"
147 if $component > shift @V;
148 }
149 }
150 return $VERSION;
151 }
152  
153  
154 sub min { $_[0] > $_[1] ? $_[1] : $_[0] }
155  
156 sub out {
157 if (ref($OUT) eq 'IO::Scalar') {
158 $OUT->print(@_);
159 } else {
160 foreach (map(fromUTF8($ENCODING,$_), @_)) {
161 my $l = length;
162 my $i = 1;
163 while ($l > $i*$MAXPRINTLENGTH) {
164 print $OUT (substr($_,($i-1)*$MAXPRINTLENGTH,$MAXPRINTLENGTH));
165 $i++;
166 }
167 print $OUT (substr($_,($i-1)*$MAXPRINTLENGTH)); # the rest
168 }
169 }
170 }
171  
172 sub __debug {
173 _err(@_);
174 }
175  
176 sub __bug {
177 _err("BUG: ",@_);
178 }
179  
180 sub _tilde_expand {
181 my ($filename)=@_;
182 $filename=~s{^(\~[^\/]*)}{(glob($1))[0]}eg;
183  
184 # $filename =~ s{ ^ ~ ( [^/]* ) }
185 # { $1
186 # ? (getpwnam($1))[7]
187 # : ( $ENV{HOME} || $ENV{LOGDIR}
188 # || (getpwuid($>))[7]
189 # )
190 # }ex;
191 return $filename;
192 }
193  
194 sub _ev_opts {
195 my ($opts)=@_;
196 return {} unless ref($opts);
197 return $opts if ref($opts) eq 'HASH';
198 my %o;
199 my @opts = @$opts;
200 while (@opts) {
201 my ($t,$n)=split /\//,shift(@opts);
202 my $v=shift @opts;
203 if ($t eq '' or $t eq 'exp') {
204 $o { $n } = _ev($v);
205 } elsif ($t eq 'var') {
206 $o { $n } = $v;
207 } elsif ($t eq 'xpath') {
208 utf8::upgrade($v);
209 $o { $n } = _expand($v);
210 } else { # string
211 $o { $n } = _ev_string($v);
212 }
213 }
214 return \%o;
215 }
216  
217 sub _hash_opts {
218 my ($opts)=@_;
219 return {} unless ref($opts);
220 my %o;
221 my @opts = @$opts;
222 while (@opts) {
223 my ($t,$n)=split /\//,shift(@opts);
224 my $v=shift @opts;
225 $o { $n } = $v;
226 }
227 return \%o;
228 }
229  
230 sub alias_sr {
231 my($src, $dest)=@_;
232 tie($$dest, 'XML::XSH2::VarAlias', $src);
233 }
234  
235 sub lexicalize {
236 my $p="package XML::XSH2::Map; no strict qw(vars); \$Lexical::Alias::SWAP=0; use utf8;";
237 my %seen;
238 for (my $i=$#$lexical_variables; $i>=0; $i--) {
239 foreach my $v (keys %{$lexical_variables->[$i]}) {
240 next if $seen{$v};
241 $seen{$v}=1;
242 $p.="my \$$v; \&XML::XSH2::Functions::alias_sr(\\\$XML::XSH2::Functions::lexical_variables->[$i]{q#$v#}, \\\$$v);"
243 }
244 }
245 # $p.="\n# line $RT_LINE \"$RT_SCRIPT\"\n";
246 return $p.$_[0];
247 }
248  
249 # initialize XSH and XML parsers
250 sub xsh_init {
251 my $module=shift;
252 shift unless ref($_[0]);
253 if (ref($_[0])) {
254 $OUT=$_[0];
255 } else {
256 if (open $OUT, '>&', \*STDOUT) {
257 binmode $OUT;
258 binmode $OUT, ':bytes';
259 } else {
260 $OUT = \*STDOUT;
261 }
262 }
263 set_encoding({},$ENCODING);
264 $_xml_module=$module if $module;
265 eval("require $_xml_module;");
266 if ($@) {
267 _err(
268 "\n------------------------------------------------------------\n",
269 $@,
270 "\n------------------------------------------------------------.\n",
271 "I suspect you have not installed XML::LibXML properly.\n",
272 "Please install and try again. If you are 100% sure you have, send\n",
273 "a full bug report to <pajas".'@'."users.sourceforge.net>\n");
274 exit 1;
275 }
276 my $mod=$_xml_module->module();
277 if ($] >= 5.008) {
278 require Encode;
279 *encodeToUTF8=*Encode::decode;
280 *decodeFromUTF8=*Encode::encode;
281 } else {
282 no strict 'refs';
283 *encodeToUTF8=*{"$mod"."::encodeToUTF8"};
284 *decodeFromUTF8=*{"$mod"."::decodeFromUTF8"};
285 }
286 $_parser = $_xml_module->new_parser();
287  
288 xpc_init();
289 # xsh_rd_parser_init();
290  
291 # create a first document so that we always have non-empty context
292 create_doc('$scratch',"scratch",'xml','scratch.xml');
293 set_local_xpath({},'/');
294 }
295  
296 sub xsh_rd_parser_init {
297 unless ($_xsh) {
298 if (eval { require XML::XSH2::Parser; }) {
299 $_xsh=XML::XSH2::Parser->new();
300 } else {
301 print STDERR "Parsing raw grammar...\n";
302 require XML::XSH2::Grammar;
303 $_xsh=XML::XSH2::Grammar->new();
304 print STDERR "... done.\n";
305 unless ($QUIET) {
306 print STDERR << 'EOF';
307 NOTE: To avoid this, you should regenerate the XML::XSH2::Parser.pm
308 module from XML::XSH2::Grammar.pm module by changing to XML/XSH/
309 directory in your load-path and running the following command:
310  
311 perl -MGrammar -e XML::XSH2::Grammar::compile
312  
313 EOF
314 }
315 }
316 }
317 return $_xsh;
318 }
319  
320 sub set_validation { shift if @_>1; $VALIDATION=$_[0]; 1; }
321 sub set_recovering { shift if @_>1; $RECOVERING=$_[0]; 1; }
322 sub set_expand_entities { shift if @_>1; $PARSER_EXPANDS_ENTITIES=$_[0]; 1; }
323 sub set_keep_blanks { shift if @_>1; $KEEP_BLANKS=$_[0]; 1; }
324 sub set_pedantic_parser { shift if @_>1; $PEDANTIC_PARSER=$_[0]; 1; }
325 sub set_load_ext_dtd { shift if @_>1; $LOAD_EXT_DTD=$_[0]; 1; }
326 sub set_complete_attributes { shift if @_>1; $PARSER_COMPLETES_ATTRIBUTES=$_[0]; 1; }
327 sub set_expand_xinclude { shift if @_>1; $PARSER_EXPANDS_XINCLUDE=$_[0]; 1; }
328 sub set_indent { shift if @_>1; $INDENT=$_[0]; 1; }
329 sub set_empty_tags { shift if @_>1; $EMPTY_TAGS=$_[0]; 1; }
330 sub set_skip_dtd { shift if @_>1; $SKIP_DTD=$_[0]; 1; }
331 sub set_backups { shift if @_>1; $BACKUPS=$_[0]; 1; }
332 sub set_cdonopen { shift if @_>1; $SWITCH_TO_NEW_DOCUMENTS=$_[0]; 1; }
333 sub set_xpath_completion { shift if @_>1; $XPATH_COMPLETION=$_[0]; 1; }
334 sub set_xpath_axis_completion { shift if @_>1; $XPATH_AXIS_COMPLETION=$_[0];
335 if ($XPATH_AXIS_COMPLETION!~/^always|when-empty|never$/) {
336 $XPATH_AXIS_COMPLETION='never';
337 }
338 1; }
339 sub set_line_numbers { shift if @_>1; $LINE_NUMBERS=$_[0]; 1; }
340  
341 sub get_validation { $VALIDATION }
342 sub get_recovering { $RECOVERING }
343 sub get_expand_entities { $PARSER_EXPANDS_ENTITIES }
344 sub get_keep_blanks { $KEEP_BLANKS }
345 sub get_pedantic_parser { $PEDANTIC_PARSER }
346 sub get_load_ext_dtd { $LOAD_EXT_DTD }
347 sub get_complete_attributes { $PARSER_COMPLETES_ATTRIBUTES }
348 sub get_expand_xinclude { $PARSER_EXPANDS_XINCLUDE }
349 sub get_indent { $INDENT }
350 sub get_empty_tags { $EMPTY_TAGS }
351 sub get_skip_dtd { $SKIP_DTD }
352 sub get_backups { $BACKUPS }
353 sub get_cdonopen { $SWITCH_TO_NEW_DOCUMENTS }
354 sub get_xpath_completion { $XPATH_COMPLETION }
355 sub get_xpath_axis_completion { $XPATH_AXIS_COMPLETION }
356 sub get_line_numbers { $LINE_NUMBERS }
357  
358 # initialize global XPathContext
359 sub xpc_init {
360 $_xpc=new_xpath_context();
361 $_ns{xsh}=$XML::XSH2::xshNS;
362 }
363  
364 sub init_XPATH_funcs {
365 my ($xpc,$ns)=@_;
366 foreach my $name (get_XPATH_extensions()) {
367 my $func=$name; $func =~ s/-/_/g;
368 $xpc->registerFunctionNS($name,$ns,\&{"XPATH_$func"});
369 }
370 }
371  
372 sub new_xpath_context {
373 my $xpc;
374 unless (eval { require XML::LibXML::XPathContext;
375 $xpc=XML::LibXML::XPathContext->new();
376 }) {
377 require XML::XSH2::DummyXPathContext;
378 print STDERR ("Warning: XML::LibXML::XPathContext not found!\n".
379 "XSH will lack namespace and function registering functionality!\n\n");
380 return XML::XSH2::DummyXPathContext->new();
381 }
382 $xpc = XML::LibXML::XPathContext->new();
383 $xpc->registerVarLookupFunc(\&xpath_var_lookup,undef);
384 $xpc->registerNs('xsh',$XML::XSH2::xshNS);
385 init_XPATH_funcs($xpc,$XML::XSH2::xshNS);
386 return $xpc;
387 }
388  
389 sub clone_xpc {
390 my $xpc = new_xpath_context();
391 foreach (keys(%_ns)) {
392 $xpc->registerNs($_,$_ns{$_});
393 }
394 foreach (keys(%_func)) {
395 if (/\n/) {
396 my ($name,$ns)=/^(.*)\n((?:.|\n)*)$/;
397 $xpc->registerFunctionNS($name, $ns, $_func{$_});
398 } else {
399 $xpc->registerFunction($_, $_func{$_});
400 }
401 }
402 $xpc->setContextNode($_xpc->getContextNode());
403 return $xpc;
404 }
405  
406 sub xpath_extensions {
407 my $opts = shift;
408 init_XPATH_funcs($_xpc,shift);
409 return 1;
410 }
411  
412 # ===================== XPATH EXT FUNC ================
413  
414 sub get_XPATH_extensions {
415 qw( current doc filename grep id2 if join lc uc ucfirst lcfirst
416 lineno evaluate map matches match max min new-attribute
417 new-cdata new-chunk new-comment new-element new-element-ns new-pi
418 new-text node-type parse path reverse same serialize split sprintf
419 strmax strmin subst substr sum times var document documents lookup span context
420 resolve-uri base-uri document-uri
421 )
422 }
423  
424 sub XPATH_doc {
425 die "Wrong number of arguments for function xsh:doc(nodeset)!\n" if (@_!=1);
426 my ($nodelist)=@_;
427 die "1st argument must be a nodeset in xsh:doc(nodeset)!\n"
428 unless (ref($nodelist) and UNIVERSAL::isa($nodelist,'XML::LibXML::NodeList'));
429 use utf8;
430 return XML::LibXML::NodeList->new(grep { ref($_) } map { $_->ownerDocument } @$nodelist);
431 }
432  
433 sub XPATH_filename {
434 die "Wrong number of arguments for function xsh:filename(nodeset?) or xsh:document-uri(nodeset?)!\n" if (@_>1);
435 my $doc;
436 if (@_) {
437 die "1st argument must be a node in xsh:filename(nodeset?) or xsh:document-uri(nodeset?)!\n"
438 unless (ref($_[0]) and UNIVERSAL::isa($_[0],'XML::LibXML::NodeList'));
439 }
440 if ($_[0]) {
441 return XML::LibXML::Literal->new('') unless $_[0][0];
442 $doc = $_[0][0]->ownerDocument;
443 } else {
444 $doc = $XML::XSH2::Functions::_xpc->getContextNode()->ownerDocument;
445 }
446 use utf8;
447 return XML::LibXML::Literal->new($doc->URI());
448 }
449  
450 sub XPATH_resolve_uri {
451 die "Wrong number of arguments for function xsh:resolve-uri(relative-URI,base-URI?)!\n" if (@_>2 or @_==0);
452 my ($rel,$base)=map literal_value($_), @_;
453 return XML::LibXML::Literal->new(XML::XSH2::Map::resolve_uri($rel,$base)->as_string);
454 }
455  
456 sub XPATH_document_uri {
457 &XPATH_filename;
458 }
459  
460 sub XPATH_base_uri {
461 die "Wrong number of arguments for function xsh:base_uri(node?)!\n" if (@_>1);
462 my $node;
463 if (@_) {
464 die "1st argument must be a node in xsh:base_uri(node?)!\n"
465 unless (ref($_[0]) and UNIVERSAL::isa($_[0],'XML::LibXML::NodeList'));
466 }
467 if ($_[0]) {
468 return XML::LibXML::Literal->new('') unless $_[0][0];
469 $node = $_[0][0];
470 } else {
471 $node = $XML::XSH2::Functions::_xpc->getContextNode();
472 }
473 use utf8;
474 return XML::LibXML::Literal->new($node->baseURI() || '');
475 }
476  
477  
478 sub XPATH_var {
479 die "Wrong number of arguments for function xsh:var(id)!\n" if (@_!=1);
480 my ($id)=literal_value($_[0]);
481 return var_value($id);
482 }
483  
484 sub XPATH_matches {
485 die "Wrong number of arguments for function xsh:matches(string,regexp)!\n" if (@_!=2 and @_!=3);
486 use utf8;
487 my ($string,$regexp,$ignore_case)=@_;
488 $string=literal_value($string);
489 $regexp=literal_value($regexp);
490 $ignore_case=literal_value($ignore_case);
491 return ($ignore_case ?
492 $string=~m{$regexp}i :
493 $string=~m{$regexp}) ?
494 XML::LibXML::Boolean->True :
495 XML::LibXML::Boolean->False;
496 }
497  
498 sub XPATH_substr {
499 die "Wrong number of arguments for function xsh:substr(string,position,[length])!\n" if (@_<2 or @_>3);
500 use utf8;
501 my ($str,$pos,$len)=@_;
502 my $result = (@_ == 2) ?
503 substr(literal_value($str),
504 literal_value($pos)) :
505 substr(literal_value($str),
506 literal_value($pos),
507 literal_value($len));
508 $result = "" unless defined ($result);
509 return $result;
510 }
511  
512 sub XPATH_reverse {
513 die "Wrong number of arguments for function xsh:reverse(string)!\n" if (@_!=1);
514 use utf8;
515 return scalar reverse(literal_value($_[0]));
516 }
517  
518 sub XPATH_lc {
519 die "Wrong number of arguments for function xsh:lc(string)!\n" if (@_!=1);
520 use utf8;
521 return lc(literal_value($_[0]));
522 }
523  
524 sub XPATH_uc {
525 die "Wrong number of arguments for function xsh:uc(string)!\n" if (@_!=1);
526 use utf8;
527 return uc(literal_value($_[0]));
528 }
529  
530 sub XPATH_lcfirst {
531 die "Wrong number of arguments for function xsh:lcfirst(string)!\n" if (@_!=1);
532 use utf8;
533 return lcfirst(literal_value($_[0]));
534 }
535  
536 sub XPATH_ucfirst {
537 die "Wrong number of arguments for function xsh:ucfirst(string)!\n" if (@_!=1);
538 use utf8;
539 return ucfirst(literal_value($_[0]));
540 }
541  
542 sub XPATH_grep {
543 die "Wrong number of arguments for function xsh:grep(list,regexp)!\n" if (@_!=2);
544 my ($nodelist,$regexp)=@_;
545 die "1st argument must be a nodeset in grep(list,regexp)!\n"
546 unless (ref($nodelist) and UNIVERSAL::isa($nodelist,'XML::LibXML::NodeList'));
547 use utf8;
548 [grep { $_->to_literal=~m{$regexp} } @$nodelist];
549 }
550  
551 sub XPATH_same {
552 die "Wrong number of arguments for function xsh:same(node,node)!\n" if (@_!=2);
553 my ($nodea,$nodeb)=@_;
554 die "1st argument must be a node in grep(list,regexp)!\n"
555 unless (ref($nodea) and UNIVERSAL::isa($nodea,'XML::LibXML::NodeList'));
556 die "2nd argument must be a node in grep(list,regexp)!\n"
557 unless (ref($nodeb) and UNIVERSAL::isa($nodeb,'XML::LibXML::NodeList'));
558 return XML::LibXML::Boolean->new($nodea->size() && $nodeb->size() &&
559 $nodea->[0]->isSameNode($nodeb->[0]));
560 }
561  
562 sub XPATH_max {
563 my $r;
564 foreach (cast_objects_to_values(@_)) {
565 next unless /^\s*(-\s*)?(\d+(\.\d*)?|\.\d+)\s*$/;
566 $r = $_ unless defined($r);
567 $r = $_>$r ? $_ : $r;
568 }
569 ; 0+$r;
570 }
571  
572 sub XPATH_strmax {
573 my $r;
574 foreach (cast_objects_to_values(@_)) {
575 $r = $_ unless defined($r);
576 $r = $_ ge $r ? $_ : $r;
577 }
578 ; defined($r) ? $r : "";
579 }
580  
581 sub XPATH_min {
582 my $r;
583 foreach (cast_objects_to_values(@_)) {
584 next unless /^\s*(-\s*)?(\d+(\.\d*)?|\.\d+)\s*$/;
585 $r = $_ unless defined($r);
586 $r = $_ < $r ? $_ : $r;
587 }
588 ;
589 return 0+$r;
590 }
591  
592 sub XPATH_strmin {
593 my $r;
594 foreach (cast_objects_to_values(@_)) {
595 $r = $_ unless defined($r);
596 $r = $_ le $r ? $_ : $r;
597 }
598 ; defined($r) ? $r : "";
599 }
600  
601 sub XPATH_sum {
602 my $r=0;
603 foreach (cast_objects_to_values(@_)) {
604 $r += $_;
605 }
606 ; $r;
607 }
608  
609 sub XPATH_join {
610 my $j=literal_value(shift @_);
611 join $j,cast_objects_to_values(@_);
612 }
613  
614 sub XPATH_serialize {
615 my $result="";
616 foreach my $obj (@_) {
617 if (ref($obj) and
618 UNIVERSAL::isa($obj,'XML::LibXML::NodeList')) {
619 foreach my $node (@$obj) {
620 $result.=$node->toString();
621 }
622 } else {
623 $result.=literal_value($obj);
624 }
625 }
626 $result;
627 }
628  
629 sub XPATH_subst {
630 die "Wrong number of arguments for function xsh:subst(string,regexp,replacement,[options])!\n" if (@_!=3 and @_!=4);
631 use utf8;
632 my ($string,$regexp,$replace,$options)=@_;
633 $string=literal_value($string);
634 $regexp=literal_value($regexp);
635 return $string unless $regexp ne "";
636 $replace=literal_value($replace);
637 $options=literal_value($options);
638 die "Invalid options: $options (should only consist of 'egimsx')!\n"
639 unless ($options =~ /^[egimsx]*$/);
640 $replace =~ s{\\(.)|(/)|(\\)$}{\\$1$2$3}gs;
641 eval "\$string=~s/\$regexp/$replace/$options";
642 return $string;
643 }
644  
645 sub XPATH_parse {
646 use utf8;
647 my $string=join '',map {literal_value($_)} @_;
648 my $dom=xsh_parse_string($string,'xml');
649 if ($dom) {
650 return XML::LibXML::NodeList->new($dom->childNodes());
651 } else {
652 return XML::LibXML::NodeList->new();
653 }
654 }
655  
656 sub XPATH_sprintf {
657 die "Wrong number of arguments for function xsh:sprintf(format-string,...)!\n" if (@_<1);
658 use utf8;
659 my @args=map { literal_value($_) } @_;
660 return sprintf(shift(@args),@args);
661 }
662  
663 sub XPATH_current {
664 die "Wrong number of arguments for function xsh:current()!\n" if (@_);
665 my $ln = xsh_context_node();
666 return XML::LibXML::NodeList->new($ln ? $ln : ());
667 }
668  
669 sub XPATH_path {
670 die "Wrong number of arguments for function xsh:path(nodeset)!\n" if (@_!=1);
671 die "Wrong type of argument 1 for xsh:path(nodeset)!\n" unless (ref($_[0]) and UNIVERSAL::isa($_[0],'XML::LibXML::NodeList'));
672 return "" unless $_[0][0];
673 return
674 XML::LibXML::Literal->new(pwd($_[0][0]));
675 }
676  
677 sub XPATH_node_type {
678 die "Wrong number of arguments for function xsh:node-type(node-set)!\n" if (@_!=1);
679 die "Wrong type of argument 1 for xsh:node-type(node-set)!\n" unless (ref($_[0]) and UNIVERSAL::isa($_[0],'XML::LibXML::NodeList'));
680 return "" unless $_[0][0];
681 return
682 XML::LibXML::Literal->new(node_type($_[0][0]));
683 }
684  
685 sub XPATH_object_type {
686 die "Wrong number of arguments for function xsh:object-type(object)!\n" if (@_!=1);
687 my ($obj)=@_;
688 my $ret;
689 if (!ref($obj)) {
690 $ret = "string"
691 } elsif (UNIVERSAL::isa($obj,"XML::LibXML::NodeList")) {
692 $ret = "nodeset"
693 } elsif (UNIVERSAL::isa($obj,"XML::LibXML::Literal")) {
694 $ret = "string"
695 } elsif (UNIVERSAL::isa($obj,"XML::LibXML::Boolean")) {
696 $ret = "boolean"
697 } elsif (UNIVERSAL::isa($obj,"XML::LibXML::Number")) {
698 $ret = "float"
699 } else {
700 $ret = "unknown"
701 }
702 return XML::LibXML::Literal->new($ret);
703 }
704  
705 sub XPATH_evaluate {
706 die "Wrong number of arguments for function xsh:evaluate(string)!\n"
707 if ((@_==0) or (@_>4));
708 my ($xpath,$node,$size,$pos)=@_;
709 my $old_context;
710 if (@_>1) {
711 $old_context = _save_context();
712 die "Wrong type of argument 1 for xsh:evaluate(string,node?,size?,position?)!\n"
713 unless (ref($node) and UNIVERSAL::isa($node,'XML::LibXML::NodeList'));
714 if (@$node) {
715 _set_context([$node->[0],$size,$pos]);
716 } else {
717 return XML::LibXML::NodeList->new();
718 }
719 }
720 if ($xpath eq "") { return XML::LibXML::NodeList->new() }
721 my $val;
722 eval { $val = $_xpc->find($xpath) };
723 _set_context($old_context) if $old_context;
724 return defined($val) ? $val : XML::LibXML::NodeList->new();
725 }
726  
727 sub XPATH_map {
728 die "Wrong number of arguments for function xsh:map(nodeset,string)!\n"
729 if (@_!=2);
730 die "Wrong type of argument 1 for xsh:map(nodeset,string)!\n"
731 unless (ref($_[0]) and UNIVERSAL::isa($_[0],'XML::LibXML::NodeList'));
732 my ($nl,$xpath)=@_;
733 my $res = XML::LibXML::NodeList->new();
734 unless (@{$nl} and $xpath ne "") { return $res; }
735 return $res if $xpath eq "";
736 # my $xpc = clone_xpc();
737 my $res_el;
738 $_xpc->setContextSize(0+@{$nl}) if $_xpc->can('setContextSize');
739 my $pos=1;
740 foreach my $node (@{$nl}) {
741 $_xpc->setContextPosition($pos++) if $_xpc->can('setContextSize');
742 my $val;
743 eval { $val = $_xpc->find($xpath,$node); };
744 return XML::LibXML::NodeList->new() if $@;
745 next unless (ref($val));
746 push @$res,cast_value_to_objects($val,undef,1);
747 }
748 return $res;
749 }
750  
751 sub XPATH_match {
752 die "Wrong number of arguments for function xsh:match(string,regexp,options?)!\n" if (@_!=2 and @_!=3);
753 use utf8;
754 my ($string,$regexp,$options)=@_;
755 $string=literal_value($string);
756 $regexp=literal_value($regexp);
757 $options=literal_value($options);
758  
759 die "Invalid options: $options (should only consist of 'cgimosx')!\n"
760 unless ($options =~ /^[cgimosx]*$/);
761 my @result = eval "\$string=~/\$regexp/$options";
762 die $@ if $@;
763 my $res = XML::LibXML::NodeList->new();
764 my $res_doc=XML::LibXML::Document->new();
765 my $res_el=$res_doc->createElementNS($XML::XSH2::xshNS,'xsh:result');
766 $res_doc->setDocumentElement($res_el);
767 my $el;
768 foreach my $str (@result) {
769 $el = $res_doc->createElementNS($XML::XSH2::xshNS,'xsh:string');
770 $el->appendText($str);
771 $res_el->appendChild($el);
772 push @$res,$el;
773 }
774 return $res;
775 }
776  
777 sub XPATH_split {
778 die "Wrong number of arguments for function xsh:split(regexp,string)!\n"
779 if (@_!=2);
780 my ($regexp,$string)=@_;
781 $regexp=literal_value($regexp);
782 $string=literal_value($string);
783 my $res = XML::LibXML::NodeList->new();
784 my $res_doc=XML::LibXML::Document->new();
785 my $res_el=$res_doc->createElementNS($XML::XSH2::xshNS,'xsh:result');
786 $res_doc->setDocumentElement($res_el);
787 my $el;
788 foreach my $str (split $regexp,$string) {
789 $el = $res_doc->createElementNS($XML::XSH2::xshNS,'xsh:string');
790 $el->appendText($str);
791 $res_el->appendChild($el);
792 push @$res,$el;
793 }
794 return $res;
795 }
796  
797 sub XPATH_new_attribute {
798 die "Wrong number of arguments for function xsh:new-attributes(string, string, [string, string,...])!\n"
799 unless (@_ and (scalar(@_) % 2 == 0));
800 my %attr=map { literal_value($_) } @_;
801 my $doc = $_xpc->getContextNode;
802 unless (ref($doc) and ref($doc = $doc->ownerDocument())) {
803 die "No context document\n";
804 }
805 return XML::LibXML::NodeList->new(map {$doc->createAttribute($_,$attr{$_})} keys %attr);
806 }
807  
808 sub XPATH_new_element {
809 die "Wrong number of arguments for function xsh:new-element(string, [string,string,...])!\n"
810 unless (scalar(@_)%2);
811 my ($name,%attrs)=map {literal_value($_)} @_;
812 my $doc = $_xpc->getContextNode;
813 unless (ref($doc) and ref($doc = $doc->ownerDocument())) {
814 die "No context document\n";
815 }
816 my $e = $doc->createElement($name);
817 foreach my $aname (keys %attrs) {
818 $e->setAttribute($aname,$attrs{$aname});
819 }
820 return XML::LibXML::NodeList->new($e);
821 }
822  
823 sub XPATH_new_element_ns {
824 die "Wrong number of arguments for function xsh:new-element-ns(string, string, [string,string])!\n"
825 unless (@_ and (scalar(@_)+1)%2);
826 my ($name,$ns,%attrs)=map {literal_value($_)} @_;
827 my $doc = $_xpc->getContextNode;
828 unless (ref($doc) and ref($doc = $doc->ownerDocument())) {
829 die "No context document\n";
830 }
831 # __debug("ns: $ns");
832 my $e=$doc->createElementNS("$ns",$name);
833 # my ($prefix,$name) = split ':',$name;
834 # my $e=XML::LibXML::Element->new($name);
835 # $e->setNamespace("$ns","$prefix",1);
836 foreach my $aname (keys %attrs) {
837 $e->setAttribute($aname,$attrs{$aname});
838 }
839 return XML::LibXML::NodeList->new($e);
840 }
841  
842  
843 sub XPATH_new_text {
844 die "Wrong number of arguments for function xsh:new-text(string)!\n"
845 if (@_!=1);
846 my $text=literal_value(shift);
847 my $doc = $_xpc->getContextNode;
848 unless (ref($doc) and ref($doc = $doc->ownerDocument())) {
849 die "No context document\n";
850 }
851 my $t=$doc->createTextNode($text);
852 return XML::LibXML::NodeList->new($t);
853 }
854  
855 sub XPATH_new_comment {
856 die "Wrong number of arguments for function xsh:new-comment(string)!\n"
857 if (@_!=1);
858 my $text=literal_value(shift);
859 my $doc = $_xpc->getContextNode;
860 unless (ref($doc) and ref($doc = $doc->ownerDocument())) {
861 die "No context document\n";
862 }
863 my $t=$doc->createComment($text);
864 return XML::LibXML::NodeList->new($t);
865 }
866  
867 sub XPATH_new_cdata {
868 die "Wrong number of arguments for function xsh:new-cdata(string)!\n"
869 if (@_!=1);
870 my $name=literal_value(shift);
871 my $doc = $_xpc->getContextNode;
872 unless (ref($doc) and ref($doc = $doc->ownerDocument())) {
873 die "No context document\n";
874 }
875 my $t=$doc->createCDATASection($name);
876 return XML::LibXML::NodeList->new($t);
877 }
878  
879 sub XPATH_new_pi {
880 die "Wrong number of arguments for function xsh:new-pi(string,[ string])!\n"
881 if (!@_ or @_>2);
882 my ($name,$value)=map { literal_value($_) } @_;
883 my $doc = $_xpc->getContextNode;
884 unless (ref($doc) and ref($doc = $doc->ownerDocument())) {
885 die "No context document\n";
886 }
887 my $pi = $doc->createPI($name => $value);
888 return XML::LibXML::NodeList->new($pi);
889 }
890  
891 sub XPATH_new_chunk {
892 die "Wrong number of arguments for function xsh:new-chunk(string,[ string])!\n"
893 if (@_!=1);
894 return XPATH_parse(@_);
895 }
896  
897 sub XPATH_times {
898 die "Wrong number of arguments for function xsh:times(string,float)!\n"
899 if (@_!=2);
900 my ($string,$times)=@_;
901 $times=literal_value($times);
902 $string=literal_value($string);
903 return XML::LibXML::Literal->new($times x $string);
904 }
905  
906 sub XPATH_if {
907 die "Wrong number of arguments for function xsh:if(object,object,object)!\n"
908 if (@_!=3);
909 my ($test, $if, $else)=@_;
910 if (ref($test) and
911 (UNIVERSAL::isa($test,'XML::LibXML::NodeList') and @$test
912 or $test->to_literal->value)
913 or $test) {
914 return $if;
915 } else {
916 return $else;
917 }
918 }
919  
920 sub XPATH_id2 {
921 die "Wrong number of arguments for function xsh:id2(object,string)!\n"
922 if (@_!=2);
923 my ($nl, $id)=@_;
924 die "Wrong type of argument 1 for function xsh:id2(object,string)!\n"
925 if (!ref($nl) or not UNIVERSAL::isa($nl,"XML::LibXML::NodeList"));
926 die "Argument 2 for function xsh:id2(object,string) isn't a valid qname!\n"
927 if ($id =~ /\'/);
928 my $res=XML::LibXML::NodeList->new();
929 if ($nl->[0]) {
930 push @$res, $nl->[0]->findnodes("id('".$id."')");
931 }
932 return $res;
933 }
934  
935 sub XPATH_lineno {
936 die "Wrong number of arguments for function xsh:lineno(node-set)!\n"
937 if (@_!=1);
938 my ($nl, $id)=@_;
939 die "Wrong type of argument 1 for function xsh:lineno(node-set)!\n"
940 if (!ref($nl) or not UNIVERSAL::isa($nl,"XML::LibXML::NodeList"));
941 my $res=-1;
942 if ($nl->[0]) {
943 $res=$nl->[0]->line_number;
944 }
945 return XML::LibXML::Number->new($res);
946 }
947  
948 sub XPATH_document {
949 die "Wrong number of arguments for function xsh:document(string)!\n"
950 if (@_!=1);
951 my $URI = shift;
952 my $abs;
953 my @files = _files();
954 for my $f (@files) {
955 return XML::LibXML::NodeList->new($f->[0])
956 if ($f->[0]->URI eq $URI);
957 }
958 unless (_is_absolute($URI)) {
959 $URI = File::Spec->rel2abs(_tilde_expand($URI));
960 for my $f (@files) {
961 return XML::LibXML::NodeList->new($f->[0])
962 if ($f->[0]->URI eq $URI);
963 }
964 }
965 my $is_URL = _is_url($URI);
966 for my $f (@files) {
967 my $f_URI = $f->[0]->URI;
968 return XML::LibXML::NodeList->new($f->[0])
969 if (_is_url($f_URI) and !$is_URL and $f_URI eq 'file://'.$URI
970 or
971 !_is_url($f_URI) and $is_URL and $URI eq 'file://'.$f_URI);
972 }
973  
974 return XML::LibXML::NodeList->new();
975 }
976  
977 sub XPATH_documents {
978 die "Wrong number of arguments for function xsh:documents()!\n"
979 if (@_!=0);
980 my $res = XML::LibXML::NodeList->new();
981 for my $f (_files()) {
982 $res->push($f->[0]);
983 }
984 return $res;
985 }
986  
987 sub XPATH_lookup {
988 die "Wrong number of arguments for function xsh:lookup(string,string)!\n"
989 if (@_!=2);
990 my $name = shift;
991 my $key = shift;
992 my $res;
993 $name=~s/^\$//;
994 no strict 'refs';
995 my $lex = lex_var($name);
996 if ($lex) {
997 $res = $$lex
998 } elsif (defined(${"XML::XSH2::Map::$name"})) {
999 $res = ${"XML::XSH2::Map::$name"};
1000 } else {
1001 die "xsh:lookup(): variable '\$$name' not defined\n";
1002 }
1003
1004 if (ref($res) eq 'HASH') {
1005 my $val = $res->{to_literal($key)};
1006 if (defined($val)) {
1007 return $val;
1008 } else {
1009 return XML::LibXML::NodeList->new();
1010 }
1011 } else {
1012 return XML::LibXML::NodeList->new();
1013 }
1014 }
1015  
1016 sub XPATH_span {
1017 die "Wrong number of arguments for function xsh:span(node-set,node-set)!\n"
1018 if (@_!=2);
1019 # the first argument is a start node and
1020 # the second is an end node;
1021 # only the first argument is taken from each node-set!
1022 #
1023 # returns span of sibling nodes "between" them (inclusively).
1024 # it is an error if the start and end nodes are not siblings.
1025  
1026 my ($start,$end)=@_;
1027 for my $nl ($start,$end) {
1028 die "Wrong type of argument in function xsh:span(node-set,node-set)!\n"
1029 if (!ref($nl) or not UNIVERSAL::isa($nl,"XML::LibXML::NodeList"));
1030 }
1031 ($start,$end) = map { $_->[0] } ($start,$end);
1032 if ($start and $end) {
1033 if ($start->parentNode->isSameNode($end->parentNode)) {
1034 my @nodes = ();
1035 do {{
1036 push @nodes, $start;
1037 if ($start->isSameNode($end)) {
1038 return XML::LibXML::NodeList->new_from_ref(\@nodes,1);
1039 }
1040 $start = $start->nextSibling();
1041 }} while ($start);
1042 return XML::LibXML::NodeList->new();
1043 } else {
1044 die "Start node and end node are not siblings at xsh:span(node-set,node-set)!\n"
1045 }
1046 } else {
1047 return XML::LibXML::NodeList->new();
1048 }
1049 }
1050  
1051 sub XPATH_context {
1052 die "Wrong number of arguments for function xsh:context(node-set,float,float)!\n"
1053 if (@_<2 or @_>3);
1054 # returns a span of nodes consisting of a given number of nodes
1055 # before the given context node, the context node itself and a given number of nodes
1056 # following the context node
1057  
1058 # $context ... preceding-sibling::node()[position()<$before] | . | following-sibling::node()[position<$after]
1059 my ($context,$before,$after)=@_;
1060 die "Wrong type of argument in function xsh:context(node-set,float,float)!\n"
1061 if (!ref($context) or not UNIVERSAL::isa($context,"XML::LibXML::NodeList"));
1062 $before = int($before);
1063 $after = defined ($after) ? $before : int($after);
1064 return scalar($_xpc->findnodes("preceding-sibling::node()[position()<$before] | . | following-sibling::node()[position()<$after]",$context->[0]));
1065 }
1066  
1067 # ===================== END OF XPATH EXT FUNC ================
1068  
1069 sub get_flags_as_vars {
1070 no strict qw(refs);
1071 use Data::Dumper;
1072 return Data::Dumper->Dump([map eval, @PARAM_VARS],\@PARAM_VARS);
1073 }
1074  
1075 sub list_flags {
1076 my ($opts) = @_;
1077 $opts = _ev_opts($opts);
1078 if ($opts->{variables}) {
1079 no strict qw(refs);
1080 use Data::Dumper;
1081 out(get_flags_as_vars());
1082 } else {
1083 out("validation ".(get_validation() or "0").";\n");
1084 out("recovering ".(get_recovering() or "0").";\n");
1085 out("parser_expands_entities ".(get_expand_entities() or "0").";\n");
1086 out("parser_expands_xinclude ".(get_expand_xinclude() or "0").";\n");
1087 out("keep_blanks ".(get_keep_blanks() or "0").";\n");
1088 out("pedantic_parser ".(get_pedantic_parser() or "0").";\n");
1089 out("load_ext_dtd ".(get_load_ext_dtd() or "0").";\n");
1090 out("complete_attributes ".(get_complete_attributes() or "0").";\n");
1091 out("indent ".(get_indent() or "0").";\n");
1092 out("empty_tags ".(get_empty_tags() or "0").";\n");
1093 out("skip_dtd ".(get_skip_dtd() or "0").";\n");
1094 out(((get_backups() ? "backups" : "nobackups"),";\n"));
1095 out((($QUIET ? "quiet" : "verbose"),";\n"));
1096 out((($DEBUG ? "debug" : "nodebug"),";\n"));
1097 out((($TEST_MODE ? "run-mode" : "test-mode"),";\n"));
1098 out("switch_to_new_documents ".(get_cdonopen() or "0").";\n");
1099 out("encoding '$ENCODING';\n");
1100 out("query_encoding '$QUERY_ENCODING';\n");
1101 out("xpath_completion ".(get_xpath_completion() or "0").";\n");
1102 out("xpath_axis_completion \'".get_xpath_axis_completion()."';\n");
1103 }
1104 }
1105  
1106 sub toUTF8 {
1107 # encode/decode from UTF8 returns undef if string not marked as utf8
1108 # by perl (for example ascii)
1109 # return $_[1];
1110 my $res=eval { encodeToUTF8($_[0],$_[1]) };
1111 if ($@ =~ /^SIGINT/) {
1112 die $@
1113 } else {
1114 undef $@;
1115 }
1116 return defined($res) ? $res : $_[1];
1117 }
1118  
1119 sub fromUTF8 {
1120 # encode/decode from UTF8 returns undef if string not marked as utf8
1121 # by perl (for example ascii)
1122 # return $_[1];
1123 my $res=eval { decodeFromUTF8($_[0],$_[1]) };
1124 if ($@ =~ /^SIGINT/) {
1125 die $@
1126 } else {
1127 undef $@;
1128 }
1129 return defined($res) ? $res : $_[1];
1130 }
1131  
1132 # return true if given string is a XSH command name
1133 sub is_command {
1134 my ($test)=@_;
1135 foreach my $cmd (@XML::XSH2::CompletionList::XSH_COMMANDS) {
1136 return 1 if $cmd eq $test;
1137 }
1138 return 0;
1139 }
1140  
1141 # set current script name
1142 sub xsh_set_script {
1143 $SCRIPT=$_[0];
1144 }
1145  
1146 sub benchtime {
1147 my ($t0,$t1)=@_;
1148 Benchmark::timestr(Benchmark::timediff($t0,$t1));
1149 }
1150  
1151 # evaluate a XSH command
1152 sub xsh {
1153 print STDERR "Benchmark: running script $SCRIPT\n" if $BENCHMARK;
1154 require Benchmark if $BENCHMARK;
1155 my ($t0,$t1);
1156 $t0 = Benchmark->new() if $BENCHMARK;
1157 unless (ref($_xsh)) {
1158 xsh_init();
1159 xsh_rd_parser_init();
1160 }
1161 $t1 = Benchmark->new() if $BENCHMARK;
1162 print STDERR "Benchmark: init xsh took:",benchtime($t1,$t0),"\n" if $BENCHMARK;
1163 if (ref($_xsh)) {
1164 my $code=join "",map toUTF8($QUERY_ENCODING,$_),@_;
1165 return run($code);
1166 } else {
1167 die "XSH init failed!\n";
1168 }
1169 }
1170  
1171 sub run {
1172 my ($code) = @_;
1173 return 1 if ($code=~/^\s*$/);
1174 require Benchmark if $BENCHMARK;
1175 my $t0 = Benchmark->new() if $BENCHMARK;
1176 my $pt = $_xsh->startrule($code);
1177 my $t1 = Benchmark->new() if $BENCHMARK;
1178 print STDERR "Benchmark: xsh parsing took:",benchtime($t1,$t0),"\n" if $BENCHMARK;
1179  
1180 # __debug "Post processing parse tree";
1181 $t0 = Benchmark->new() if $BENCHMARK;
1182 post_process_parse_tree($pt);
1183 $t1 = Benchmark->new() if $BENCHMARK;
1184 print STDERR "Benchmark: compile took:",benchtime($t1,$t0),"\n" if $BENCHMARK;
1185 dump_parse_tree($pt) if defined $DUMP;
1186 $t0 = Benchmark->new() if $BENCHMARK;
1187 my $result=run_commands($pt,1);
1188 $t1 = Benchmark->new() if $BENCHMARK;
1189 print STDERR "Benchmark: execution took:",benchtime($t1,$t0),"\n" if $BENCHMARK;
1190 return $result;
1191 }
1192  
1193 sub dump_parse_tree {
1194 my ($pt) = shift;
1195 use Data::Dumper;
1196 local $Data::Dumper::Purity=1;
1197
1198 my $dump = '';
1199  
1200 unless ($DUMP_APPEND) {
1201 $dump .= <<"EOS";
1202 require XML::XSH2;
1203 XML::XSH2::Functions->VERSION( '$VERSION' );
1204  
1205 EOS
1206  
1207 $dump .= <<'EOS';
1208 {
1209 package XML::XSH2::Functions;
1210  
1211 # initialize context
1212 xsh_init();
1213  
1214 # prepare ARGV
1215 @XML::XSH2::Map::ARGV=@ARGV;
1216 for (@ARGV,@XML::XSH2::Map::ARGV) {
1217 $_=toUTF8($QUERY_ENCODING,$_)
1218 }
1219 # XPath variant of perlish {@ARGV} ($ARGV[1] is the first arg though)
1220 $XML::XSH2::Map::ARGV = XML::LibXML::NodeList->new(
1221 map { cast_value_to_objects($_) } @XML::XSH2::Map::ARGV
1222 );
1223  
1224 EOS
1225 {
1226 local $TEST_MODE;
1227 $dump.= get_flags_as_vars();
1228 }
1229 } else {
1230 $dump.=<<'EOS'
1231 {
1232 package XML::XSH2::Functions;
1233 EOS
1234 }
1235 $dump.= "# script $SCRIPT\n\n";
1236 local $Data::Dumper::Deparse=1;
1237 $dump.= Data::Dumper->Dump([$pt],['parse_tree']);
1238 $dump.= "\nXML::XSH2::Functions::run_commands(\$parse_tree);\n";
1239 $dump.= "};\n\n";
1240 if (ref($DUMP) eq 'SCALAR') {
1241 if ($DUMP_APPEND) {
1242 $$DUMP.=$dump;
1243 } else {
1244 $$DUMP=$dump;
1245 }
1246 } else {
1247 print STDERR "Saving compiled '$SCRIPT' to '$DUMP'\n" unless $QUIET;
1248 open my $f, ($DUMP_APPEND ? '>>' : '>'), $DUMP || die "Can't dump parse tree to '$DUMP': $!";
1249 print {$f} "#!/usr/bin/env perl\n" unless $DUMP_APPEND;
1250 print {$f} $dump;
1251 close $f;
1252 chmod 0755, $DUMP unless $DUMP_APPEND;
1253 }
1254 $DUMP_APPEND = 1;
1255 }
1256  
1257 sub post_process_parse_tree {
1258 my ($pt)=@_;
1259 # __debug "[ $pt";
1260 if (ref($pt) eq 'XML::XSH2::Command') {
1261 # __debug "COMMAND: @$pt\n";
1262 my ($line,$column,$offset,$script,$cmd,@args)=@$pt;
1263 unless (ref($cmd)) {
1264 my $spec = $COMMANDS{$cmd};
1265 $spec = $COMMANDS{$spec} if ($spec and !ref($spec));
1266 if ($spec) {
1267 my ($func,$minargs,$maxargs,$optspec,@extraargs)=@$spec;
1268 my @opts;
1269 # print STDERR ("matched $cmd\n");
1270 while (@args) {
1271 if ($optspec and $args[0]=~/^--(.*)$|^:(.)$/) {
1272 my $opt = defined($1) ? $1 : $optspec->{$2}; # resolve short opt
1273 if (exists($optspec->{$opt})) {
1274 shift(@args);
1275 if ($optspec->{$opt} ne '') {
1276 push @opts, $optspec->{$opt}.'/'.$opt;
1277 push @opts,shift(@args);
1278 } else {
1279 push @opts, '/'.$opt,1;
1280 }
1281 } else {
1282 die "$script: Compile error: unknown option '$args[0]' for command '$cmd' at line $line column $column offset $offset\n";
1283 }
1284 } else {
1285 last;
1286 }
1287 }
1288 if (@args<$minargs) {
1289 die "$script: Compile error: too few arguments (have ",$#args+1,", expect $minargs) for command '$cmd' at line $line column $column offset $offset\n";
1290 } elsif (defined($maxargs) and @args>$maxargs) {
1291 die "$script: Compile error: too many arguments (have ",$#args+1,", expect $maxargs) for command '$cmd' at line $line column $column offset $offset\n";
1292 }
1293 foreach (@args) {
1294 if (ref eq 'ARRAY') {
1295 post_process_parse_tree($_);
1296 }
1297 }
1298 @$pt=($line,$column,$offset,$script,$func,\@opts,@args,@extraargs);
1299 } else {
1300 # print STDERR ("$cmd is a sub call?\n");
1301 @$pt=($line,$column,$offset,$script,'call',{},1,$cmd,@args);
1302 }
1303 }
1304 } elsif (ref($pt) eq 'ARRAY') {
1305 # __debug "Processing array @$pt\n";
1306 for(my $i=0;$i<=$#$pt;$i++) {
1307 post_process_parse_tree($pt->[$i]) if ref($pt);
1308 }
1309 }
1310 # __debug "]";
1311 }
1312  
1313 # setup output stream
1314 sub xsh_set_output {
1315 $OUT=$_[0];
1316 binmode $OUT;
1317 binmode $OUT, ':bytes';
1318 open STDOUT, ">&", $OUT or warn "Can't dup STDOUT\n";
1319 select $OUT;
1320 return 1;
1321 }
1322  
1323 # get output stream
1324 sub xsh_get_output {
1325 return $OUT;
1326 }
1327  
1328 sub cast_objects_to_values {
1329 return map {
1330 if (ref($_)) {
1331 UNIVERSAL::can($_,'textContent') ? $_->textContent() : $_->value();
1332 } else { $_ }
1333 } map {
1334 UNIVERSAL::isa($_,'XML::LibXML::NodeList') ? @$_ : $_;
1335 } @_;
1336 }
1337  
1338 sub create_xsh_result_element {
1339 my $res_doc=XML::LibXML::Document->new();
1340 my $res_el=$res_doc->createElementNS($XML::XSH2::xshNS,'xsh:result');
1341 $res_doc->setDocumentElement($res_el);
1342 return $res_el;
1343 }
1344  
1345 sub cast_value_to_objects {
1346 my ($val, $res_el, $wrap)=@_;
1347 if (UNIVERSAL::isa($val,"XML::LibXML::NodeList")) {
1348 return @$val;
1349 } elsif (UNIVERSAL::isa($val,"XML::LibXML::Node")) {
1350 return ($val);
1351 }
1352 $res_el = create_xsh_result_element() unless (ref($res_el));
1353 my $res_doc = $res_el->ownerDocument;
1354 my $el;
1355 my $res;
1356 if (!ref($val)) {
1357 if ($val =~ /^\s*[+-]?(\d+(\.\d*)?|\.\d+)\s*$/) {
1358 $el = $res_doc->createElementNS($XML::XSH2::xshNS,'xsh:number');
1359 } else {
1360 $el = $res_doc->createElementNS($XML::XSH2::xshNS,'xsh:string');
1361 }
1362 $el->appendText($val);
1363 $res = $el->firstChild;
1364 } elsif (UNIVERSAL::isa($val,"XML::LibXML::Literal")) {
1365 $el = $res_doc->createElementNS($XML::XSH2::xshNS,'xsh:string');
1366 $el->appendText($val->value);
1367 $res = $el->firstChild;
1368 } elsif (UNIVERSAL::isa($val,"XML::LibXML::Boolean")) {
1369 $el = $res_doc->createElementNS($XML::XSH2::xshNS,'xsh:boolean');
1370 $el->appendText($val ? 'true' : '');
1371 $res = $el->firstChild;
1372 } elsif (UNIVERSAL::isa($val,"XML::LibXML::Number")) {
1373 $el = $res_doc->createElementNS($XML::XSH2::xshNS,'xsh:number');
1374 $el->appendText($val->value);
1375 $res = $el->firstChild;
1376 } elsif (ref($val) eq 'ARRAY') {
1377 $el = $res_doc->createElementNS($XML::XSH2::xshNS,'xsh:array');
1378 map { cast_value_to_objects($_,$el) } @$val;
1379 $res=$el;
1380 } else {
1381 die("don't know how to cast object '$val' to nodeset");
1382 return ();
1383 }
1384 $res_el->appendChild($el);
1385 return $wrap ? $el : $res;
1386 }
1387  
1388 sub expr {
1389 my $opts = shift;
1390 &_ev;
1391 }
1392  
1393 # evaluate given XPath or Perl expression
1394 sub _ev {
1395 my ($exp,$map,$in_place)=@_;
1396 return undef unless defined $exp;
1397 utf8::upgrade($exp) unless ref($exp);
1398 if (ref($exp) eq 'ARRAY') {
1399 return run_commands($exp,0,1);
1400 } elsif ($exp =~ /^<<(.)/) {
1401 # inline document
1402 if ($1 eq "{") {
1403 return perl_eval($',$map,$in_place);
1404 } elsif ($1 eq "(") {
1405 my $ret = eval { $_xpc->find(_expand($')); };
1406 _check_err($@,1,1);
1407 if (ref($ret) and UNIVERSAL::isa($ret,'XML::LibXML::Literal')) {
1408 return $ret->value;
1409 } else {
1410 return $ret;
1411 }
1412 } elsif ($1 eq "'") {
1413 return $';
1414 } else {
1415 return _expand($');
1416 }
1417 } elsif ($exp =~ /^(?:\d*\.\d+|\d+)$/) { # a number/float literal
1418 return 0+$exp;
1419 } elsif ($exp =~ /^{/) { # a perl expression
1420 return perl_eval($exp,$map,$in_place);
1421 } elsif ($exp eq "") { # empty
1422 return "";
1423 } else { # an xpath expression
1424 my $ret = eval { $_xpc->find(_expand($exp)); };
1425 _check_err($@,1,1);
1426 if (ref($ret) and UNIVERSAL::isa($ret,'XML::LibXML::Literal')) {
1427 return $ret->value;
1428 } else {
1429 return $ret;
1430 }
1431 }
1432 }
1433  
1434 # Evaluate given XPath or Perl expression to a node-list. Evaluate the
1435 # expression using _ev. If the result is a plain scalar string, it is
1436 # re-evaluated as XPath. If the result is a node or node-list object
1437 # or a perl array containing nodes, it is cast to node-list and
1438 # returned. Otherwise an error is reported.
1439  
1440 sub _ev_nodelist {
1441 my @res = map { cast_value_to_objects($_) } _ev($_[0]);
1442 if (wantarray) {
1443 return @res;
1444 } else {
1445 XML::LibXML::NodeList->new(@res);
1446 }
1447 }
1448  
1449 sub _ev_list {
1450 my $exp = $_[0];
1451 if (ref($exp) eq 'ARRAY') {
1452 $exp = run_commands($exp, 0, 1);
1453 } if ($exp =~ /^<<(.)/) {
1454 # inline document
1455 if ($1 eq "{") {
1456 return perl_eval($');
1457 } else {
1458 $exp = $';
1459 }
1460 } elsif ($exp =~ /^{/) {
1461 return (perl_eval($exp));
1462 } else {
1463 $exp = _expand($exp);
1464 }
1465 my $val = eval { $_xpc->find($exp); };
1466 _check_err($@,1,1);
1467 if (UNIVERSAL::isa($val,"XML::LibXML::NodeList")) {
1468 return @$val;
1469 } elsif (UNIVERSAL::isa($val,"XML::LibXML::Node")) {
1470 return ($val);
1471 }
1472  
1473 return ();
1474 }
1475  
1476  
1477 # evaluate given XPath or Perl expression and return the text content
1478 # of the result
1479 sub _ev_literal {
1480 my ($exp,$map,$in_place)=@_;
1481 return "" if $exp eq "";
1482 my $val = _ev($exp,$map,$in_place);
1483 return to_literal($val);
1484 }
1485  
1486 sub to_literal {
1487 my ($obj)=@_;
1488 if (!ref($obj)) {
1489 my $r=$obj;
1490 utf8::upgrade($r);
1491 return $r;
1492 } else {
1493 if (UNIVERSAL::isa($obj,'XML::LibXML::NodeList')) {
1494 if (wantarray) {
1495 return map { literal_value($_->to_literal) } @$obj;
1496 } elsif ($obj->[0]) {
1497 return literal_value($obj->[0]->to_literal);
1498 } else {
1499 return '';
1500 }
1501 } elsif (UNIVERSAL::isa($obj,'XML::LibXML::Element')) {
1502 return $obj->textContent();
1503 } elsif (UNIVERSAL::isa($obj,'XML::LibXML::Attr')) {
1504 return $obj->getValue();
1505 } elsif (UNIVERSAL::isa($obj,'XML::LibXML::Node')) {
1506 return $obj->getData();
1507 } elsif(ref($obj)=~/^XML::LibXML/) {
1508 return literal_value($obj);
1509 } else {
1510 my $r = "$obj";
1511 utf8::upgrade($r);
1512 return $r;
1513 }
1514 }
1515 }
1516  
1517 # evaluate given XPath or Perl expression and return the text content
1518 # of the result
1519 sub _ev_count {
1520 my ($exp)=@_;
1521 return "" if $exp eq "";
1522 my $result = _ev($exp);
1523 if (!ref($result)) {
1524 return $result;
1525 } else {
1526 if (UNIVERSAL::isa($result,'XML::LibXML::NodeList')) {
1527 return $result->size();
1528 } elsif (UNIVERSAL::isa($result,'XML::LibXML::Node')) {
1529 return 1;
1530 } elsif(ref($result)=~/^XML::LibXML/) {
1531 return literal_value($result);
1532 }
1533 }
1534 }
1535  
1536  
1537 # evaluate given expression to obtain a node-set, take
1538 # and return the owner document of the first node
1539  
1540 sub _ev_doc {
1541 my ($exp)=@_;
1542 $exp = "." if $exp eq "";
1543 my ($node)=_ev_nodelist($exp)->pop();
1544 if ($node) {
1545 return $_xml_module->owner_document($node);
1546 } else {
1547 _warn("Expression '$exp' returns no node");
1548 }
1549 }
1550  
1551 sub _doc {
1552 my ($obj)=@_;
1553 my ($node) = map { cast_value_to_objects($_) } $obj;
1554 if ($node) {
1555 return $_xml_module->owner_document($node);
1556 } else {
1557 _warn("Cannot cast object to a document");
1558 }
1559 }
1560  
1561 sub _ev_string {
1562 my ($exp,$map,$in_place)=@_;
1563 if ($exp=~/^\s*(?:&|<<|{)|[\'\"\[\]\(\)\@]|::|\$/) {
1564 return _ev_literal($exp,$map,$in_place);
1565 } else {
1566 return _expand($exp);
1567 }
1568 }
1569  
1570 sub xsh_parse_string {
1571 my $format=$_[1] || $DEFAULT_FORMAT;
1572 local $VALIDATION=0;
1573 if ($format eq 'xml') {
1574 my $xmldecl;
1575 $xmldecl="<?xml version='1.0' encoding='utf-8'?>" unless $_[0]=~/^\s*\<\?xml /;
1576 return $_xml_module->parse_string($_parser,$xmldecl.$_[0]);
1577 } elsif ($format eq 'html') {
1578 return $_xml_module->parse_html_string($_parser,$_[0]);
1579 } elsif ($format eq 'docbook') {
1580 return $_xml_module->parse_sgml_string($_parser,$_[0]);
1581 }
1582 }
1583  
1584 sub xsh_xml_parser {
1585 xsh_init() unless ref($_parser);
1586 return $_parser;
1587 }
1588  
1589 # store a pointer to an XSH-Grammar parser
1590 sub xsh_set_parser {
1591 $_xsh=$_[0];
1592 return 1;
1593 }
1594  
1595 # print version info
1596 sub print_version {
1597 my $opts = shift;
1598 out("Main program: $::VERSION $::REVISION\n");
1599 out("XML::XSH2::Functions: $VERSION $REVISION\n");
1600 out("XML::LibXML: $XML::LibXML::VERSION\n");
1601 # out($_xml_module->module(),"\t",$_xml_module->version(),"\n");
1602 out("XML::LibXSLT $XML::LibXSLT::VERSION\n")
1603 if defined($XML::LibXSLT::VERSION);
1604 out("XML::LibXML::XPathContext $XML::LibXML::XPathContext::VERSION\n")
1605 if defined($XML::LibXML::XPathContext::VERSION);
1606 return 1;
1607 }
1608  
1609 # print a list of all open files
1610 sub _files {
1611 # out(map { "$_ = $_files{$_}\n" } sort keys %_files);
1612 my @ret;
1613 no strict 'refs';
1614 my %seen;
1615 foreach my $var (keys %{"XML::XSH2::Map::"}) {
1616 my $value = ${"XML::XSH2::Map::".$var};
1617 if (ref($value)) {
1618 $value = $value->[0] if (UNIVERSAL::isa($value,'XML::LibXML::NodeList')
1619 and $value->size()==1);
1620 if (UNIVERSAL::isa($value,'XML::LibXML::Node') and
1621 $_xml_module->is_document($value) and !exists($seen{$$value})) {
1622 push @ret, [$value, $var];
1623 $seen{$$value}=undef;
1624 }
1625 }
1626 }
1627 my $cur_doc = $_xml_module->owner_document(xsh_context_node());
1628 if (!exists($seen{$$cur_doc})) {
1629 push @ret, [$cur_doc, undef];
1630 }
1631 return @ret;
1632 }
1633  
1634  
1635 sub files {
1636 my $opts = shift;
1637 for my $f (_files) {
1638 out((defined($f->[1]) ? "\$".$f->[1] . " := " : ()),
1639 'open ',
1640 ($_xml_module->document_type($f->[0]) eq 'html' ?
1641 '--format html ' : ()),
1642 "'".$f->[0]->URI()."';\n");
1643 }
1644 }
1645  
1646  
1647 sub close_undef_value {
1648 my ($doc,$value)=@_;
1649 if (ref($value)) {
1650 if (UNIVERSAL::isa($value,'XML::LibXML::NodeList')) {
1651 @$value = grep
1652 {eval { $doc->isSameNode($_xml_module->owner_document($_)) ? 0 : 1}}
1653 @$value;
1654 } elsif (UNIVERSAL::isa($value,'XML::LibXML::Node')
1655 and $doc->isSameNode($_xml_module->owner_document($value))) {
1656 undef $value;
1657 }
1658 }
1659 return $value;
1660 }
1661  
1662 sub close_doc {
1663 my ($opts,$exp)=@_;
1664 my $doc = _ev_doc($exp);
1665 no strict 'refs';
1666 foreach my $var (keys %{"XML::XSH2::Map::"}) {
1667 my $value = ${"XML::XSH2::Map::".$var};
1668 next unless defined $value;
1669 undef ${"XML::XSH2::Map::".$var}
1670 unless defined(close_undef_value($doc,$value));
1671 }
1672 foreach my $lex_context (@$lexical_variables) {
1673 my ($name,$value);
1674 while (($name,$value) = each %$lex_context) {
1675 next unless defined $value;
1676 $value = close_undef_value($doc,$value);
1677 unless (defined($value)) {
1678 $lex_context->{$name} = undef
1679 }
1680 }
1681 }
1682 return 1;
1683 }
1684  
1685 sub xpath_var_lookup {
1686 my ($data,$name,$ns)=@_;
1687 no strict;
1688 my $res;
1689 if ($ns ne "") {
1690 $res = $XML::XSH2::Map::NAMESPACED_VARIABLES{$ns." ".$name};
1691 unless (defined ($res)) {
1692 die "Undefined variable '\%$name' in namespace `$ns'\n";
1693 }
1694 } else {
1695 my $lex = lex_var($name);
1696 if ($lex) {
1697 $res = $$lex
1698 } elsif (defined(${"XML::XSH2::Map::$name"})) {
1699 $res = ${"XML::XSH2::Map::$name"};
1700 } else {
1701 die "Undefined variable '\$$name'\n";
1702 }
1703 }
1704 if (ref($res) and UNIVERSAL::isa($res,'XML::LibXML::Node')) {
1705 return XML::LibXML::NodeList->new($res);
1706 } else {
1707 return $res;
1708 }
1709 }
1710  
1711 sub lex_var {
1712 my ($n)=@_;
1713 for (my $i=$#$lexical_variables; $i>=0; $i--) {
1714 return \$lexical_variables->[$i]{$n} if exists($lexical_variables->[$i]{$n});
1715 }
1716 return undef;
1717 }
1718  
1719 # return a value of the given XSH variable
1720 sub var_value {
1721 my ($var) = @_;
1722 if ($var=~/^\$(\$.*)/) {
1723 my $name = var_value($1);
1724 die "Dereferencing $var to a non-ID: $name\n"
1725 if ($name !~ /((?:::)?[a-zA-Z_][a-zA-Z0-9_]*)*/);
1726 return var_value(q($).$name);
1727 } elsif ($var=~/^\$?(.*)/) {
1728 no strict qw(refs);
1729 my $lex = lex_var($1);
1730 if ($lex) {
1731 return $$lex
1732 } elsif (defined(${"XML::XSH2::Map::$1"})) {
1733 return ${"XML::XSH2::Map::$1"};
1734 }
1735 } else {
1736 return undef;
1737 }
1738 }
1739  
1740 sub string_vars {
1741 no strict qw(refs);
1742 return sort grep { defined(${"XML::XSH2::Map::$_"}) } keys %{"XML::XSH2::Map::"};
1743 }
1744  
1745 # print a list of XSH variables and their values
1746 #
1747 # KNOWN BUG: $ARGV doesn't map to the correct i.e. (no) package
1748 #
1749  
1750 sub variables {
1751 my $opts = shift;
1752 no strict 'refs';
1753 foreach (string_vars()) {
1754 my $value = var_value(q($).$_);
1755 if (!defined($value)) {
1756 out(qq(\$$_={ )."undef".qq( };\n));
1757 } elsif (ref($value)) {
1758 out(qq(\$$_={ ).var_value(q($).$_).qq( };\n));
1759 } elsif (0+$value eq $value) {
1760 out(qq(\$$_=).var_value(q($).$_).qq(;\n));
1761 } else {
1762 out(qq(\$$_=\').var_value(q($).$_).qq(\';\n));
1763 }
1764 }
1765 return 1;
1766 }
1767  
1768 sub echo {
1769 my $opts = _ev_opts(shift);
1770 my $val = join(($opts->{nospace} ? "" : " ") ,
1771 (map _ev_string($_),@_)).($opts->{nonl} ? "" : "\n");
1772 $opts->{stderr} ? (print STDERR $val) : out($val);
1773 return 1;
1774 }
1775 sub set_quiet { shift if @_>1; $QUIET=$_[0]; return 1; }
1776 sub set_debug { shift if @_>1; $DEBUG=$_[0]; return 1; }
1777 sub set_compile_only_mode { shift if @_>1; $TEST_MODE=$_[0]; return 1; }
1778  
1779 sub test_enc {
1780 my ($enc)=@_;
1781 if (
1782 defined(toUTF8($enc,'')) and defined(fromUTF8($enc,''))
1783 ) {
1784 # print STDERR "OK\n";
1785 return 1;
1786 } else {
1787 # print STDERR "NOT-OK\n";
1788 _err("Error: Cannot convert between $enc and utf-8\n");
1789 return 0;
1790 }
1791 }
1792  
1793 sub set_encoding {
1794 shift if @_>1; # opts
1795 # print STDERR "ENCOD: @_\n";
1796 my $enc=_ev_string($_[0]);
1797 my $ok=test_enc($enc);
1798 $ENCODING=$enc;
1799 return 1;
1800 # my $ok=test_enc($enc);
1801 # if ($ok) {
1802 # $ENCODING=$enc;
1803 # # $enc = "encoding($enc)" unless $enc eq 'utf8';
1804 # # binmode $OUT;
1805 # # binmode $OUT,":$enc";
1806 # # binmode STDOUT;
1807 # # binmode STDOUT,":$enc";
1808 # # binmode STDERR;
1809 # # binmode STDERR,":$enc";
1810 # # print "Setting encoding to :$enc\n";
1811 # }
1812 # return $ok;
1813 }
1814  
1815 sub set_qencoding {
1816 my ($opts,$exp)=@_;
1817 my $enc=_ev_string($exp);
1818 my $ok=test_enc($enc);
1819 $QUERY_ENCODING=$enc if $ok;
1820 return $ok;
1821 }
1822  
1823 sub sigint {
1824 if ($TRAP_SIGINT) {
1825 print STDERR "\nCtrl-C pressed. \n";
1826 die "SIGINT";
1827 } else {
1828 print STDERR "\nCtrl-C pressed. \n";
1829 exit 1;
1830 }
1831 }
1832  
1833 sub sigpipe {
1834 if ($TRAP_SIGPIPE) {
1835 die "SIGPIPE";
1836 } else {
1837 _err('broken pipe (SIGPIPE)');
1838 exit 1;
1839 }
1840 }
1841  
1842 sub flagsigint {
1843 print STDERR "\nCtrl-C pressed. \n";
1844 $_sigint=1;
1845 }
1846  
1847 sub propagate_flagsigint {
1848 if ($_sigint) {
1849 $_sigint=0;
1850 die 'SIGINT';
1851 }
1852 }
1853  
1854  
1855 sub convertFromDocEncoding ($$\$) {
1856 my ($doc,$encoding,$str)=@_;
1857 return fromUTF8($encoding, toUTF8($_xml_module->doc_encoding($doc), $str));
1858 }
1859  
1860 sub _rt_position {
1861 return "$RT_SCRIPT line $RT_LINE, column $RT_COLUMN,".
1862 ($RT_LINE==1 ? "" : " offset $RT_OFFSET.");
1863 }
1864  
1865 sub _err {
1866 print STDERR @_," at ",_rt_position(),"\n" if $ERRORS;
1867 }
1868  
1869 sub _warn {
1870 print STDERR "Warning: ",@_," at ",_rt_position(),"\n" if $WARNINGS;
1871 }
1872  
1873  
1874 # if the argument is non-void then print it and return 0; return 1 otherwise
1875 sub _check_err {
1876 my ($err,$survive_int,$remove_at)=@_;
1877 if ($err) {
1878 # cleanup the error message
1879 $err =~ s/^XPathContext: error coming back from perl-dispatcher in pm file\.\s*//;
1880 if ($remove_at and !ref($err)) {
1881 $err=~s/ at (?:.|\n)*$//;
1882 }
1883  
1884 if ($err=~/^SIGINT/) {
1885 if ($survive_int) {
1886 $err=~s/ at (?:.|\n)*$//;
1887 _err($err);
1888 return 0;
1889 } elsif (ref($err)) {
1890 die $err; # propagate
1891 } else {
1892 chomp $err;
1893 unless ($err=~/ at (?:.|\n)*$/) {
1894 $err.=" at "._rt_position();
1895 }
1896 die $err."\n"; # propagate
1897 }
1898 } elsif ($_die_on_err) {
1899 if ($err=~/^SIGPIPE/) {
1900 _err('broken pipe (SIGPIPE)');
1901 } elsif (ref($err)) {
1902 die $err; # propagate
1903 } else {
1904 chomp $err;
1905 unless ($err=~/ at (?:.|\n)*$/) {
1906 $err.=" at "._rt_position();
1907 }
1908 die $err."\n"; # propagate
1909 }
1910 } else {
1911 if ($err=~/^SIGPIPE/) {
1912 _err('broken pipe (SIGPIPE)');
1913 } else {
1914 _err($err);
1915 }
1916 return 0;
1917 }
1918 }
1919 return 1;
1920 }
1921  
1922  
1923 # return current node for given document or document root if
1924 # current node is not from the given document
1925 sub xsh_context_node {
1926 return $_xpc->getContextNode;
1927 }
1928  
1929 sub xsh_context_var {
1930 my $node = xsh_context_node();
1931 if ($node) {
1932 return xsh_search_docvar($node);
1933 }
1934 return "";
1935 }
1936  
1937  
1938 # set current node to given XPath
1939 sub set_local_xpath {
1940 my ($opts,$exp)=@_;
1941 $exp = "/" if ($exp eq "");
1942 _set_context([_ev_nodelist($exp)->shift()]);
1943 return 1;
1944 }
1945  
1946 sub cannon_name {
1947 my ($node)=@_;
1948 my $local_name =$node->localname();
1949 my $uri = $node->namespaceURI();
1950 if ($uri ne '') {
1951 my $prefix=$node->prefix;
1952 #if ($prefix eq '') {
1953 my %r = reverse %_ns;
1954 $prefix = $r{ $uri };
1955 if ($prefix ne '') {
1956 return $prefix.':'.$local_name
1957 } elsif(my $parent = $node->parentNode) {
1958 $prefix = $parent->lookupNamespacePrefix($uri);
1959 if ($prefix ne '') {
1960 return $prefix.':'.$local_name
1961 }
1962 }
1963 return '*[name()="'.$node->getName().'"]';
1964 }
1965 return $local_name;
1966 }
1967  
1968 # return XPath identifying a node within its parent's subtree
1969 sub node_address {
1970 my $node = shift || $_xpc->getContextNode();
1971 my $no_parent = shift;
1972 my $name;
1973 if ($_xml_module->is_element($node)) {
1974 $name=cannon_name($node);
1975 } elsif ($_xml_module->is_text($node) or
1976 $_xml_module->is_cdata_section($node)) {
1977 $name="text()";
1978 } elsif ($_xml_module->is_comment($node)) {
1979 $name="comment()";
1980 } elsif ($_xml_module->is_pi($node)) {
1981 $name="processing-instruction()";
1982 } elsif ($_xml_module->is_attribute($node)) {
1983 return "@".cannon_name($node);
1984 }
1985
1986 if (!$no_parent and $node->parentNode) {
1987 my @children;
1988 # if ($_xml_module->is_element($node)) {
1989 # @children=$_xpc->findnodes("./$name",$node->parentNode);
1990 # } else {
1991 my $context = $_xpc->getContextNode;
1992 @children= eval { $_xpc->findnodes("./$name",$node->parentNode) };
1993 # }
1994 if (@children == 1 and $_xml_module->xml_equal($node,$children[0])) {
1995 return "$name";
1996 }
1997 for (my $pos=0;$pos<@children;$pos++) {
1998 return "$name"."[".($pos+1)."]"
1999 if ($_xml_module->xml_equal($node,$children[$pos]));
2000 }
2001 return "??$name??";
2002 } else {
2003 return ();
2004 }
2005 }
2006  
2007 # parent element (even for attributes)
2008 sub tree_parent_node {
2009 my $node=$_[0];
2010 if ($_xml_module->is_attribute($node)) {
2011 return $node->ownerElement();
2012 } else {
2013 return $node->parentNode();
2014 }
2015 }
2016  
2017 # get node's ID
2018 sub node_id {
2019 my ($node)=@_;
2020 if ($node) {
2021 for my $attr ($node->attributes) {
2022 if ($attr->can('isId') and $attr->isId) {
2023 my $value = $attr->value;
2024 return $value if defined $value;
2025 }
2026 }
2027 }
2028 return undef;
2029 }
2030  
2031 # return canonical xpath for the given or current node
2032 sub pwd {
2033 my $node=shift || $_xpc->getContextNode();
2034 my $use_id = shift;
2035 return undef unless ref($node);
2036 return $node->nodePath() if !$STRICT_PWD and UNIVERSAL::can($node,'nodePath');
2037 my @pwd=();
2038 do {
2039 if ($use_id) {
2040 my $id = node_id($node);
2041 if (defined $id) {
2042 return join "/","id('$id')",@pwd;
2043 }
2044 }
2045 unshift @pwd,node_address($node);
2046 $node=tree_parent_node($node);
2047 } while ($node);
2048 my $pwd="/".join "/",@pwd;
2049 return $pwd;
2050 }
2051  
2052 # return canonical xpath for current node (encoded)
2053 sub xsh_pwd {
2054 shift if $_[0] && !ref($_[0]); # package name
2055 &pwd;
2056 }
2057  
2058 # print current node's xpath
2059 sub print_pwd {
2060 my $opts = _ev_opts(shift);
2061
2062 my $pwd=pwd(undef, $opts->{id});
2063 if ($pwd) {
2064 out("$pwd\n");
2065 return $pwd;
2066 } else {
2067 return 0;
2068 }
2069 }
2070  
2071 # return base file-name of a given path
2072 sub _base_filename {
2073 my ($fn)=@_;
2074 ($^O eq 'Win32') ? ($fn =~ m{([^\\]*)$}) : ($fn =~ m{([^/]*)$});
2075 return $1;
2076 }
2077  
2078 # evaluate variable and xpath expresions in a given string
2079 sub _expand {
2080 my ($l,$vars)=@_;
2081 my $k;
2082 no strict;
2083 $l=~/^/o;
2084 while ($l !~ /\G$/gsco) {
2085 if ($l=~/\G\\\$\{/gsco) {
2086 $k.='${';
2087 } elsif ($l=~/\G\$\{(\$?[a-zA-Z_][a-zA-Z0-9_]*)\}/gsco) {
2088 $k.=var_value(q($).$1);
2089 } elsif ($vars and $l=~/\G(\$\$?[a-zA-Z_][a-zA-Z0-9_]*)/gsco) {
2090 $k.=var_value($1);
2091 } elsif ($l=~/\G\$\{\{(.*?)\}\}/gsco) {
2092 $k.=perl_eval($1);
2093 } elsif ($l=~/\G\$\{\((.+?)\)\}/gsco) {
2094 $k.=_ev_literal($1);
2095 } elsif ($l=~/\G(\$(?!\{)|\\(?!\${)|[^\\\$]+)/gsco) {
2096 # skip to the next \ or $
2097 $k.=$1;
2098 }
2099 }
2100 return $k;
2101 }
2102  
2103 # expand one or all parameters (according to return context)
2104 sub expand {
2105 return wantarray ? (map { _expand($_) } @_) : _expand($_[0]);
2106 }
2107  
2108 # return a reference to a variable storage
2109 sub _get_var_ref {
2110 my ($name,$value)=@_;
2111 no strict 'refs';
2112 if ($name=~/^\$(\$.*)/) {
2113 my $prev = $name;
2114 $name = var_value($1);
2115 die "Dereferencing $prev to a non-ID: $name\n"
2116 if ($name !~ /((?:::)?[a-zA-Z_][a-zA-Z0-9_]*)*$/);
2117 return _get_var_ref(q($).$name);
2118 } elsif ($name=~/^\$((?:::)?[a-zA-Z_][a-zA-Z0-9_]*)*$/) {
2119 my $lex = lex_var($1);
2120 return $lex if ($lex);
2121 return $${"XML::XSH2::Map::$1"};
2122 } else {
2123 die "Invalid variable name $name\n"
2124 }
2125 return 1;
2126 }
2127  
2128 # assign a value to a variable
2129 sub _assign {
2130 my ($name,$value,$op)=@_;
2131 no strict 'refs';
2132 if ($name=~/^\$(\$.*)/) {
2133 my $prev = $name;
2134 $name = var_value($1);
2135 die "Dereferencing $prev to a non-ID: $name\n"
2136 if ($name !~ /((?:::)?[a-zA-Z_][a-zA-Z0-9_]*)*$/);
2137 return _assign(q($).$name,$value,$op);
2138 } elsif ($name=~/^\$?((?:::)?[a-zA-Z_][a-zA-Z0-9_]*)*$/) {
2139 $op = '=' unless $op;
2140 my $lex = lex_var($1);
2141 if ($lex) {
2142 eval '$$lex'.$op.'$value'; die $@ if $@;
2143 print STDERR "lexical \$$1=",${"XML::XSH2::Map::$1"},"\n" if $DEBUG;
2144 } else {
2145 eval '${"XML::XSH2::Map::$1"}'.$op.'$value'; die $@ if $@;
2146 print STDERR "\$$1=",${"XML::XSH2::Map::$1"},"\n" if $DEBUG;
2147 }
2148 } else {
2149 die "Invalid variable name $name\n"
2150 }
2151 }
2152  
2153 # undefine global or localized variable
2154 sub _undef {
2155 my ($name)=@_;
2156 no strict 'refs';
2157 if ($name=~/^\$(\$.*)/) {
2158 my $prev = $name;
2159 $name = var_value($1);
2160 die "Dereferencing $prev to a non-ID: $name\n"
2161 if ($name !~ /((?:::)?[a-zA-Z_][a-zA-Z0-9_]*)*$/);
2162 return _undef(q($).$name);
2163 } elsif ($name=~/^\$((?:::)?[a-zA-Z_][a-zA-Z0-9_]*)*$/) {
2164 undef ${"XML::XSH2::Map::$1"};
2165 } else {
2166 die "Invalid variable name $name\n"
2167 }
2168 return 1;
2169 }
2170  
2171 # undefine lexical, global or localized variable
2172 sub undefine {
2173 my ($name)=@_;
2174 if ($name=~/^\$(\$.*)/) {
2175 my $prev = $name;
2176 $name = var_value($1);
2177 die "Dereferencing $prev to a non-ID: $name\n"
2178 if ($name !~ /((?:::)?[a-zA-Z_][a-zA-Z0-9_]*)*$/);
2179 return undefine(q($).$name);
2180 } elsif ($name=~/^\$((?:::)?[a-zA-Z_][a-zA-Z0-9_]*)*$/) {
2181 my $lex = lex_var($1);
2182 if ($lex) {
2183 undef $$lex;
2184 } else {
2185 no strict qw(refs);
2186 undef ${"XML::XSH2::Map::".$1};
2187 }
2188 } else {
2189 die "Invalid variable name $name\n"
2190 }
2191 return 1;
2192 }
2193  
2194 sub literal_value {
2195 return ref($_[0]) ? $_[0]->value() : $_[0];
2196 }
2197  
2198 # evaluate xpath and assign the result to a variable
2199 sub xpath_assign {
2200 my ($exp,$op,$type,$name)=@_;
2201 if ($type eq 'my') {
2202 store_lex_variables(0,$name);
2203 } elsif ($type eq 'local') {
2204 store_variables(0,$name);
2205 }
2206 my $val = _ev($exp);
2207 _assign($name,$val,$op);
2208 return 1;
2209 }
2210  
2211 sub command_assign {
2212 my ($command,$op,$type,$name)=@_;
2213 if ($type eq 'my') {
2214 store_lex_variables(0,$name);
2215 } elsif ($type eq 'local') {
2216 store_variables(0,$name);
2217 }
2218 $op =~ s/\s*:\s*//;
2219 _assign($name,run_commands([$command],0,1),$op);
2220 return 1;
2221 }
2222  
2223 sub make_local {
2224 foreach (@_) {
2225 xpath_assign(undef,'=','local',$_);
2226 }
2227 }
2228  
2229 sub get_stored_nodelists {
2230 return grep { ref($_) } map { @$_ } @stored_variables;
2231 }
2232  
2233 sub store_variables {
2234 my ($new,@vars)=@_;
2235 my $pool;
2236 if ($new) {
2237 $pool=[];
2238 } elsif (@stored_variables and ref($stored_variables[$#stored_variables])) {
2239 $pool=$stored_variables[$#stored_variables];
2240 } else {
2241 _warn "Ignoring attempt to make a local variable outside a localizable context!";
2242 return 0;
2243 }
2244  
2245 foreach (@vars) {
2246 my $value=var_value($_);
2247 push @$pool, $_ => $value;
2248 }
2249 push @stored_variables, $pool if ($new);
2250  
2251 return 1;
2252 }
2253  
2254 sub store_lex_variables {
2255 my $new = shift;
2256 my $pool;
2257 if ($new) {
2258 $pool={};
2259 push @$lexical_variables, $pool;
2260 } elsif (@$lexical_variables) {
2261 $pool=$lexical_variables->[$#$lexical_variables]
2262 } else {
2263 _warn "Ignoring attempt to make a lexical variable outside a lexical context!";
2264 return 0;
2265 }
2266 foreach (@_) {
2267 if (/^\s*\$?([^\$]*)/) {
2268 $pool->{$1} = undef;
2269 } else {
2270 die "Invalid lexical variable name $_\n";
2271 }
2272 }
2273 }
2274  
2275 sub restore_lex_variables {
2276 unless (ref(pop @$lexical_variables)) {
2277 __bug("Lexical variable pool is empty, which was not expected!\n");
2278 }
2279 }
2280  
2281 sub create_block_var {
2282 my ($var,$local) = @_;
2283 if ($local =~ /local/) {
2284 store_variables(1,$var);
2285 } elsif ($local=~/my/) {
2286 store_lex_variables(1,$var);
2287 }
2288 }
2289  
2290 sub destroy_block_var {
2291 if ($_[0] =~ /local/) {
2292 restore_variables();
2293 } elsif ($_[0]=~/my/) {
2294 restore_lex_variables();
2295 }
2296 }
2297  
2298 sub restore_variables {
2299 my $pool=pop @stored_variables;
2300 unless (ref($pool)) {
2301 __bug("Local variable pool is empty, which was not expected!\n");
2302 return 0;
2303 }
2304 while (@$pool) {
2305 my ($value,$name)=(pop(@$pool), pop(@$pool));
2306 if ($name =~ m/^\$/) {
2307 if (defined($value)) {
2308 _assign($name,$value);
2309 } else {
2310 _undef($name);
2311 }
2312 } else {
2313 __bug("Invalid variable name '$_'\n");
2314 }
2315 }
2316 return 1;
2317 }
2318  
2319 sub _prepare_result_nl {
2320 # my ($opts)=@_;
2321 # return undef unless ref($opts);
2322 # my ($append, $var);
2323 # if (exists($opts->{'append-result'})) {
2324 # $append = 1;
2325 # $var = $opts->{'append-result'};
2326 # } elsif (exists($opts->{result})) {
2327 # $append = 0;
2328 # $var = $opts->{result};
2329 # } elsif (exists($opts->{'append-result'})) {
2330 # $append = 1;
2331 # $var = $opts->{'append-result'};
2332 # } else {
2333 # return undef;
2334 # }
2335 # my $rl;
2336 # if ($var ne "") {
2337 # $rl = var_value($var);
2338 # unless ($append and (UNIVERSAL::isa($rl,'XML::LibXML::NodeList') or ref($rl) eq 'ARRAY')) {
2339 # _assign($var,XML::LibXML::NodeList->new());
2340 # $rl = var_value($var);
2341 # }
2342 # }
2343 # return $rl;
2344 if ($_want_returns) {
2345 return XML::LibXML::NodeList->new();
2346 } else {
2347 return undef;
2348 }
2349 }
2350  
2351  
2352 sub count_xpath {
2353 my ($exp)=@_;
2354 my $result = _ev($exp);
2355 if (ref($result)) {
2356 if (UNIVERSAL::isa($result,'XML::LibXML::NodeList')) {
2357 return $result->size();
2358 } elsif (UNIVERSAL::isa($result,'XML::LibXML::Literal')) {
2359 return $result->value();
2360 } elsif (UNIVERSAL::isa($result,'XML::LibXML::Number') or
2361 UNIVERSAL::isa($result,'XML::LibXML::Boolean')) {
2362 return $result->value();
2363 }
2364 } else {
2365 return $result;
2366 }
2367 }
2368  
2369 sub new_doc {
2370 my ($opts,$root_element)=@_;
2371 $opts = _ev_opts($opts);
2372 $root_element = _ev_string($root_element);
2373 my $format= $opts->{format} || $DEFAULT_FORMAT;
2374 create_doc(undef, $root_element, $format);
2375 }
2376  
2377 # create new document
2378 sub create_doc {
2379 my ($id, $root_element, $format, $filename)=@_;
2380 # TODO: $format argument is not used by the grammar
2381 my $doc;
2382 $root_element="<$root_element/>" unless ($root_element=~/^\s*</);
2383 $root_element=~s/^\s+//;
2384 $doc=xsh_parse_string($root_element,$format);
2385 set_doc($id,$doc,$filename) if defined($id);
2386 $_newdoc++;
2387  
2388 _set_context([$doc]) if $SWITCH_TO_NEW_DOCUMENTS;
2389 return $doc;
2390 }
2391  
2392 # bind a document with a given id and filename
2393 sub set_doc {
2394 my ($id,$doc,$file)=@_;
2395 # $_doc{$id}=$doc;
2396 # $_files{$id}=$file;
2397 _assign($id,$doc);
2398 set_doc_URI($doc,$file);
2399 return $doc;
2400 }
2401  
2402 sub set_filename {
2403 my ($opts,$file, $doc)=@_;
2404 $file = _tilde_expand(_ev_string($file));
2405 $doc = _ev_doc(defined($doc) ? $doc : '.');
2406 set_doc_URI($doc,$file);
2407 }
2408  
2409 sub set_doc_URI {
2410 my ($doc,$file)=@_;
2411 $doc->setBaseURI($file)
2412 if (defined($file) and ref($doc) and
2413 UNIVERSAL::can($doc,'setBaseURI'));
2414 return $doc->URI;
2415 }
2416  
2417  
2418 sub xsh_search_docvar {
2419 my ($node)=@_;
2420 my $doc = $_xml_module->owner_document($node);
2421 return undef unless ref($doc);
2422 no strict 'refs';
2423 foreach my $var (keys %{"XML::XSH2::Map::"}) {
2424 my $value = ${"XML::XSH2::Map::".$var};
2425 if (ref($value)) {
2426 $value = $value->[0] if (UNIVERSAL::isa($value,'XML::LibXML::NodeList')
2427 and $value->size()==1);
2428 if (UNIVERSAL::isa($value,'XML::LibXML::Document')
2429 and $value->isSameNode($doc)) {
2430 return "\$".$var;
2431 }
2432 }
2433 }
2434 }
2435  
2436 sub index_doc {
2437 my ($opts,$exp)=@_;
2438 $exp = '.' if $exp eq "";
2439 my $doc = _ev_doc($exp);
2440 my $result;
2441 if ($doc->can('indexElements')) {
2442 $result = $doc->indexElements;
2443 print STDERR $result." elements indexed.\n" unless $QUIET;
2444 } else {
2445 _warn "Indexing not supported by installed version of XML::LibXML\n";
2446 }
2447 return $result;
2448 }
2449  
2450 sub _is_url {
2451 return ($_[0] =~ m(^\s*[[:alnum:]]+://)) ? 1 : 0;
2452 }
2453 sub _is_absolute {
2454 my ($path) = @_;
2455 return ($path eq '-' or
2456 _is_url($path) or
2457 File::Spec->file_name_is_absolute($path)) ? 1 : 0;
2458 }
2459  
2460 # create a new document by parsing a file
2461 sub open_doc {
2462 my ($opts,$src)=@_;
2463 $opts = _ev_opts($opts);
2464  
2465 if (exists($opts->{file})+exists($opts->{pipe})+
2466 exists($opts->{string})>1) {
2467 die "'save' may have only one output flag: --file | ".
2468 "--pipe | --string\n";
2469 }
2470 my $format= $opts->{format} || $DEFAULT_FORMAT;
2471 if ($format !~ /^xml$|^html$/) {
2472 die "Unknown --format for command open: '$format'! Use 'xml' or 'html'.\n";
2473 }
2474  
2475 foreach my $o (qw(switch-to validate recover expand-entities xinclude
2476 keep-blanks pedantic load-ext-dtd complete-attributes)) {
2477 die "Can't use --$o and --no-$o together\n"
2478 if ($opts->{'no-'.$o} and $opts->{$o});
2479 }
2480 local $SWITCH_TO_NEW_DOCUMENTS = 1 if $opts->{'switch-to'};
2481 local $SWITCH_TO_NEW_DOCUMENTS = 0 if $opts->{'no-switch-to'};
2482 local $VALIDATION = 1 if $opts->{validate};
2483 local $VALIDATION = 0 if $opts->{'no-validate'};
2484 local $RECOVERING = 1 if $opts->{recover};
2485 local $RECOVERING = 0 if $opts->{'no-recover'};
2486 local $PARSER_EXPANDS_ENTITIES = 1 if $opts->{'expand-entities'};
2487 local $PARSER_EXPANDS_ENTITIES = 0 if $opts->{'no-expand-entities'};
2488 local $KEEP_BLANKS = 1 if $opts->{'keep-blanks'};
2489 local $KEEP_BLANKS = 0 if $opts->{'no-keep-blanks'};
2490 local $PEDANTIC_PARSER = 1 if $opts->{pedantic};
2491 local $PEDANTIC_PARSER = 0 if $opts->{'no-pedantic'};
2492 local $LOAD_EXT_DTD = 1 if $opts->{'load-ext-dtd'};
2493 local $LOAD_EXT_DTD = 0 if $opts->{'no-load-ext-dtd'};
2494 local $PARSER_COMPLETES_ATTRIBUTES = 1 if $opts->{'complete-attributes'};
2495 local $PARSER_COMPLETES_ATTRIBUTES = 0 if $opts->{'no-complete-attributes'};
2496 local $PARSER_EXPANDS_XINCLUDE = 1 if $opts->{'xinclude'};
2497 local $PARSER_EXPANDS_XINCLUDE = 0 if $opts->{'no-xinclude'};
2498  
2499 my ($source) = grep exists($opts->{$_}),qw(file pipe string);
2500 my $file;
2501 unless ($source eq 'string') {
2502 $file = _tilde_expand(_ev_string($src));
2503 # $file=~s{^(\~[^\/]*)}{(glob($1))[0]}eg;
2504 if ($source eq 'file' and !_is_absolute($file)) {
2505 $file = File::Spec->rel2abs($file);
2506 }
2507 print STDERR "open [$file]\n" if "$DEBUG";
2508 if ($file eq "") {
2509 die "filename is empty (hint: \$variable := open file-name)\n";
2510 }
2511 } else {
2512 $file = _ev_string($src);
2513 print STDERR "open [<STRING>]\n" if "$DEBUG";
2514 if ($file eq "") {
2515 die "string is empty\n";
2516 }
2517 }
2518  
2519 if (($source ne 'file') or
2520 (-f $file) or $file eq "-" or
2521 ($file=~/^[a-z]+:/)) {
2522 unless ("$QUIET") {
2523 if ($source eq 'string') {
2524 print STDERR "parsing string\n";
2525 } else {
2526 print STDERR "parsing $file\n";
2527 }
2528 }
2529 my $doc;
2530 if ($source eq 'pipe') {
2531 open my $F,"$file|" || die "Can't open pipe: $!\n";
2532 $F || die "Cannot open pipe to $file: $!\n";
2533 eval {
2534 if ($format eq 'xml') {
2535 $doc=$_xml_module->parse_fh($_parser,$F);
2536 } elsif ($format eq 'html') {
2537 $doc=$_xml_module->parse_html_fh($_parser,$F);
2538 } elsif ($format eq 'docbook') {
2539 $doc=$_xml_module->parse_sgml_fh($_parser,$F,$QUERY_ENCODING);
2540 }
2541 };
2542 close $F;
2543 _check_err($@,1,1);
2544 } elsif ($source eq 'string') {
2545 my $root_element=$file;
2546 $root_element="<$root_element/>" unless ($root_element=~/^\s*</);
2547 $root_element=~s/^\s+//;
2548 eval {
2549 $doc=xsh_parse_string($root_element,$format);
2550 };
2551 _check_err($@,1,1);
2552 die "Failed to parse string\n" unless (ref($doc));
2553 $_newdoc++;
2554 } else {
2555 eval {
2556 if ($format eq 'xml') {
2557 $doc=$_xml_module->parse_file($_parser,$file);
2558 } elsif ($format eq 'html') {
2559 $doc=$_xml_module->parse_html_file($_parser,$file);
2560 } elsif ($format eq 'docbook') {
2561 $doc=$_xml_module->parse_sgml_file($_parser,$file,$QUERY_ENCODING);
2562 }
2563 };
2564 _check_err($@,1,1);
2565 die "Failed to parse $file as $format\n" unless (ref($doc));
2566 }
2567 print STDERR "done.\n" unless "$QUIET";
2568 _set_context([$doc]) if $SWITCH_TO_NEW_DOCUMENTS;
2569 return $doc;
2570 } else {
2571 die "file doesn't exist: $file\n";
2572 return 0;
2573 }
2574 }
2575  
2576 sub open_io_file {
2577 my ($file)=@_;
2578 if ($file=~/^\s*[|>]/) {
2579 return IO::File->new($file);
2580 } elsif ($file=~/.gz\s*$/) {
2581 return IO::File->new("| gzip -c > $file");
2582 } else {
2583 return IO::File->new(">$file");
2584 }
2585 }
2586  
2587 sub is_xinclude {
2588 my ($node)=@_;
2589 return
2590 $_xml_module->is_xinclude_start($node) ||
2591 ($_xml_module->is_element($node) and
2592 $node->namespaceURI() eq $Xinclude_prefix and
2593 $node->localname() eq 'include');
2594 }
2595  
2596 sub xinclude_start_tag {
2597 my ($xi)=@_;
2598 my %xinc = map { $_->nodeName() => $_->value() } $xi->attributes();
2599 $xinc{parse}='xml' if ($xinc{parse} eq "");
2600 return "<".$xi->nodeName()." xmlns:".$xi->prefix()."=\"".$Xinclude_prefix."\" href=\"".$xinc{href}."\" parse=\"".$xinc{parse}."\">";
2601 }
2602  
2603 sub xinclude_end_tag {
2604 my ($xi)=@_;
2605 return "</".$xi->nodeName().">";
2606 }
2607  
2608 sub xinclude_print {
2609 my ($doc,$F,$node,$enc)=@_;
2610 return unless ref($node);
2611 if ($_xml_module->is_element($node) || $_xml_module->is_document($node)) {
2612 $F->print(fromUTF8($enc,start_tag($node))) if $_xml_module->is_element($node);
2613 my $child=$node->firstChild();
2614 while ($child) {
2615 if (is_xinclude($child)) {
2616 my %xinc = map { $_->nodeName() => $_->value() } $child->attributes();
2617 $xinc{parse}||='xml';
2618 $xinc{encoding}||=$enc; # may be used even to convert included XML
2619 my $elements=0;
2620 my @nodes=();
2621 my $node;
2622 my $expanded=$_xml_module->is_xinclude_start($child);
2623 if ($expanded) {
2624 $node=$child->nextSibling(); # in case of special XINCLUDE node
2625 } else {
2626 $node=$child->firstChild(); # in case of include element from XInclude NS
2627 }
2628 my $nested=0;
2629 while ($node and not($_xml_module->is_xinclude_end($node)
2630 and $nested==0
2631 and $expanded)) {
2632 if ($_xml_module->is_xinclude_start($node)) { $nested++ }
2633 elsif ($_xml_module->is_xinclude_end($node)) { $nested-- }
2634 push @nodes,$node;
2635 $elements++ if $_xml_module->is_element($node);
2636 $node=$node->nextSibling();
2637 }
2638 if ($nested>0) {
2639 print STDERR "Error: Unbalanced nested XInclude nodes.\n",
2640 " Ignoring this XInclude span!\n";
2641 $F->print("<!-- ".fromUTF8($enc,xinclude_start_tag($child))." -->");
2642 } elsif (!$node and $_xml_module->is_xinclude_start($child)) {
2643 print STDERR "Error: XInclude end node not found.\n",
2644 " Ignoring this XInclude span!\n";
2645 $F->print("<!-- ".fromUTF8($enc,xinclude_start_tag($child))." -->");
2646 } elsif ($xinc{parse} ne 'text' and $elements==0) {
2647 print STDERR "Warning: XInclude: No elements found in XInclude span.\n",
2648 " Ignoring whole XInclude span!\n";
2649 $F->print("<!-- ".fromUTF8($enc,xinclude_start_tag($child))." -->");
2650 } elsif ($xinc{parse} ne 'xml' and $elements>1) {
2651 print STDERR "Error: XInclude: More than one element found in XInclude span.\n",
2652 " Ignoring whole XInclude span!\n";
2653 $F->print("<!-- ".fromUTF8($enc,xinclude_start_tag($child))." -->");
2654 } elsif ($xinc{parse} eq 'text' and $elements>0) {
2655 print STDERR "Warning: XInclude: Element(s) found in textual XInclude span.\n",
2656 " Skipping whole XInclude span!\n";
2657 $F->print("<!-- ".fromUTF8($enc,xinclude_start_tag($child))." -->");
2658 } else {
2659 $F->print(fromUTF8($enc,xinclude_start_tag($child)));
2660 save_xinclude_chunk($doc,\@nodes,$xinc{href},$xinc{parse},$xinc{encoding});
2661 $F->print(fromUTF8($enc,xinclude_end_tag($child)));
2662 $child=$node if ($expanded); # jump to XINCLUDE end node
2663 }
2664 } elsif ($_xml_module->is_xinclude_end($child)) {
2665 $F->print("<!-- ".fromUTF8($enc,xinclude_end_tag($child))." -->");
2666 } else {
2667 xinclude_print($doc,$F,$child,$enc); # call recursion
2668 }
2669 $child=$child->nextSibling();
2670 }
2671 $F->print(fromUTF8($enc,end_tag($node))) if $_xml_module->is_element($node);
2672 } else {
2673 $F->print(fromUTF8($enc,$_xml_module->toStringUTF8($node,$INDENT)));
2674 }
2675 }
2676  
2677 sub _xml_decl {
2678 my ($doc,$version,$enc) = @_;
2679 $version=($doc->can('getVersion') ? $doc->getVersion() : '1.0')
2680 if ($doc and !defined $version);
2681 $enc=($doc->can('getEncoding') ? $doc->getEncoding() : undef)
2682 if ($doc and !defined $enc);
2683 return "<?xml version='$version'".(defined($enc) ? " encoding='$enc'?>" : "?>");
2684 }
2685  
2686 sub save_xinclude_chunk {
2687 my ($doc,$nodes,$file,$parse,$enc)=@_;
2688  
2689 return unless @$nodes>0;
2690  
2691 if ($BACKUPS) {
2692 eval { rename $file, $file."~"; };
2693 _check_err($@);
2694 }
2695 my $F=open_io_file($file);
2696 $F || die "Cannot open $file\n";
2697  
2698 if ($parse eq 'text') {
2699 foreach my $node (@$nodes) {
2700 $F->print(fromUTF8($enc,literal_value($node->to_literal)));
2701 }
2702 } else {
2703 $F->print(_xml_decl($doc,undef,$enc),"\n");
2704 foreach my $node (@$nodes) {
2705 xinclude_print($doc,$F,$node,$enc);
2706 }
2707 $F->print("\n");
2708 }
2709 $F->close();
2710 }
2711  
2712 # save a document
2713 sub save_doc {
2714 my ($opts,$exp)=@_;
2715 $opts = _ev_opts($opts);
2716 my ($doc,$node);
2717 if ($opts->{subtree}) {
2718 $exp ||= '.';
2719 ($node)=_ev_nodelist($exp)->pop();
2720 $doc = $_xml_module->owner_document($node) if $node
2721 } else {
2722 $node = $doc = _ev_doc($exp);
2723 }
2724 die "No document to save\n" unless ($node);
2725  
2726 $opts->{file} = _tilde_expand($opts->{file}) if exists($opts->{file});
2727 if (exists($opts->{file})+exists($opts->{pipe})+
2728 exists($opts->{print})+exists($opts->{string})>1) {
2729 die "'save' may have only one output flag: --file | ".
2730 "--pipe | --print | --string\n";
2731 }
2732 foreach my $o (qw(indent skip-dtd empty-tags skip-xmldecl backup)) {
2733 die "Can't use --$o and --no-$o together\n"
2734 if ($opts->{'no-'.$o} and $opts->{$o});
2735 }
2736  
2737 local $INDENT=1 if $opts->{indent};
2738 local $XML::LibXML::skipDTD = 1 if $opts->{'skip-dtd'};
2739 local $XML::LibXML::setTagCompression = 1 if $opts->{'empty-tags'};
2740 local $XML::LibXML::skipXMLDeclaration = 1 if $opts->{'skip-xmldecl'};
2741  
2742 local $INDENT=0 if $opts->{'no-indent'};
2743 local $XML::LibXML::skipDTD = 0 if $opts->{'no-skip-dtd'};
2744 local $XML::LibXML::setTagCompression = 0 if $opts->{'no-empty-tags'};
2745 local $XML::LibXML::skipXMLDeclaration = 0 if $opts->{'no-skip-xmldecl'};
2746  
2747 local $BACKUPS = 0 if $opts->{'no-backup'};
2748 local $BACKUPS = 1 if $opts->{'backup'};
2749  
2750 #__debug("$XML::LibXML::skipXMLDeclaration\n");
2751  
2752 my $format = $DEFAULT_FORMAT;
2753  
2754 if (exists($opts->{format})) {
2755 $format=lc($opts->{format});
2756 }
2757 if (exists($opts->{xinclude})) {
2758 if ($format eq 'html') {
2759 die "'save --xinclude' can only be used with XML format\n"
2760 }
2761 $format = 'xinclude';
2762 }
2763  
2764 die "'save --subtree' can't be used with HTML format\n" if ($format eq 'html' and $opts->{subtree});
2765  
2766 my ($target) = grep exists($opts->{$_}),qw(file pipe string print);
2767 $target = 'file' unless defined $target;
2768 my $file; $file = $opts->{$target} if $target;
2769 if ($target eq 'file') {
2770 if ($file eq "") {
2771 $file=$doc->URI;
2772 } else {
2773 $doc->setBaseURI($file) if $doc->can('setBaseURI');
2774 }
2775 if ($BACKUPS) {
2776 eval { rename $file, $file."~"; };
2777 _check_err($@);
2778 }
2779 }
2780  
2781 my $enc = $opts->{encoding} || $_xml_module->doc_encoding($doc) || 'utf-8';
2782 print STDERR "saving to $target $file as $format (encoding $enc)\n" if "$DEBUG";
2783  
2784 if ($format eq 'xinclude') {
2785 if ($target ne 'file') {
2786 die "Target '".uc($target)."' not supported with 'save --xinclude'\n";
2787 } else {
2788 if ($doc->{subtree}) {
2789 save_xinclude_chunk($doc,[$node],$file,'xml',$enc);
2790 } else {
2791 save_xinclude_chunk($doc,[$doc->childNodes()],$file,'xml',$enc);
2792 }
2793 }
2794 } elsif ($opts->{subtree}) {
2795 die "Unsupported format '$format'\n" unless $format eq 'xml';
2796 my $string =
2797 _xml_decl($doc,undef,$enc)."\n".
2798 (($target ne 'string' and lc($enc) =~ /^utf-?8$/i) ?
2799 $node->toString($INDENT) : fromUTF8($enc,$node->toString($INDENT)))."\n";
2800 if ($target eq 'file') {
2801 open my $F, '>', $file || die "Cannot open file $file\n";
2802 print {$F} ($string);
2803 close $F;
2804 } elsif ($target eq 'pipe') {
2805 $file=~s/^\s*\|?//g;
2806 open my $F,"| $file" || die "Cannot open pipe to $file\n";
2807 print {$F} ($string);
2808 close $F;
2809 } elsif ($target eq 'string') {
2810 return $string;
2811 } elsif ($target eq 'print') {
2812 out($string);
2813 }
2814 } else {
2815 if ($format eq 'xml') {
2816 if (lc($_xml_module->doc_encoding($doc)) ne lc($enc)
2817 and not($_xml_module->doc_encoding($doc) eq "" and
2818 lc($enc) eq 'utf-8')
2819 ) {
2820 $_xml_module->set_encoding($doc,$enc);
2821 }
2822 if ($target eq 'file') {
2823 if ($file=~/\.gz\s*$/) {
2824 $doc->setCompression(6);
2825 } else {
2826 $doc->setCompression(-1);
2827 }
2828 $doc->toFile($file,$INDENT)
2829 or _err("Saving $file failed!"); # should be document-encoding encoded
2830 # TODO: we should set the URL here
2831 } elsif ($target eq 'pipe') {
2832 $file=~s/^\s*\|?//g;
2833 open my $F,"| $file" || die "Cannot open pipe to $file\n";
2834 $doc->toFH($F,$INDENT);
2835 close $F;
2836 } elsif ($target eq 'string') {
2837 return toUTF8($_xml_module->doc_encoding($doc),
2838 $doc->toString($INDENT));
2839 } elsif ($target eq 'print') {
2840 out($doc->toString($INDENT));
2841 }
2842 } elsif ($format eq 'html') {
2843 my $F;
2844 if ($target eq 'string') {
2845 no strict qw(refs);
2846 _assign($1,'');
2847 my $out=
2848 "<!DOCTYPE HTML ".
2849 "PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"
2850 unless ($_xml_module->has_dtd($doc));
2851 $out.=toUTF8($_xml_module->doc_encoding($doc), $doc->toStringHTML());
2852 return $out;
2853 } else {
2854 if ($target eq 'file') {
2855 ($F=open_io_file($file)) || die "Cannot open $file\n";
2856 # TODO: we should set the URL here
2857 } elsif ($target eq 'pipe') {
2858 $file=~s/^\s*\|?//g;
2859 open $F,"| $file";
2860 $F || die "Cannot open pipe to $file\n";
2861 } elsif ($target eq 'print') {
2862 $F=$OUT;
2863 }
2864 $F->print("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n")
2865 unless ($_xml_module->has_dtd($doc));
2866 $F->print(fromUTF8($enc, toUTF8($_xml_module->doc_encoding($doc),
2867 $doc->toStringHTML())));
2868  
2869 $F->close() unless $target eq 'print';
2870 }
2871 } else {
2872 die "Unknown format '$format'\n";
2873 }
2874 }
2875 print STDERR "Document saved into $target '$file'.\n" unless ($@ or $target eq 'print' or "$QUIET");
2876 return 1;
2877 }
2878  
2879  
2880 # create start tag for an element
2881  
2882 ###
2883 ### Workaround of a bug in XML::LibXML:
2884 ### getNamespaces, getName returns prefix only,
2885 ### prefix returns prefix not xmlns, getAttributes contains also namespaces
2886 ### findnodes('namespace::*') returns (namespaces,undef)
2887 ###
2888  
2889 sub start_tag {
2890 my ($element,$fold_attrs)=@_;
2891 return "<".$element->nodeName().
2892 ($fold_attrs ? ((grep { $_->nodeName() ne "xsh:fold" }
2893 $element->attributes()) ? " ..." : "") :
2894 join("",map { " ".$_->nodeName()."=\"".$_->nodeValue()."\"" }
2895 $element->attributes())
2896 )
2897 # findnodes('attribute::*'))
2898 # . join("",map { " xmlns:".$_->getName()."=\"".$_->nodeValue()."\"" }
2899 # $element->can('getNamespaces') ?
2900 # $element->getNamespaces() :
2901 # $element->findnodes('namespace::*')
2902 # )
2903 .($element->hasChildNodes() ? ">" : "/>");
2904 }
2905  
2906 # create close tag for an element
2907 sub end_tag {
2908 my ($element)=@_;
2909 return $element->hasChildNodes() ? "</".$element->getName().">" : "";
2910 }
2911  
2912 # convert a subtree to an XML string to the given depth
2913 sub to_string {
2914 my ($node,$depth,$folding,$fold_attrs)=@_;
2915 my $result;
2916 if ($node) {
2917 if (ref($node) and $_xml_module->is_element($node) and $folding and
2918 $node->hasAttributeNS($XML::XSH2::xshNS,'fold')) {
2919 if ($depth>=0) {
2920 $depth = min($depth,$node->getAttributeNS($XML::XSH2::xshNS,'fold'));
2921 } else {
2922 $depth = $node->getAttributeNS($XML::XSH2::xshNS,'fold');
2923 }
2924 }
2925  
2926 if ($depth<0 and $folding==0) {
2927 $result=ref($node) ? $_xml_module->toStringUTF8($node,$INDENT) : $node;
2928 } elsif (ref($node) and $_xml_module->is_element($node) and $depth==0) {
2929 $result=start_tag($node,$fold_attrs).
2930 ($node->hasChildNodes() ? "...".end_tag($node) : "");
2931 } elsif (ref($node) and $_xml_module->is_document($node) and $depth==0) {
2932 $result=to_string($node,1,$folding,$fold_attrs);
2933 } elsif ($depth>0 or $folding) {
2934 if (!ref($node)) {
2935 $result=$node;
2936 } elsif ($_xml_module->is_element($node)) {
2937 $result= start_tag($node).
2938 join("",map { to_string($_,$depth-1,$folding,$fold_attrs) } $node->childNodes).
2939 end_tag($node);
2940 } elsif ($_xml_module->is_document($node)) {
2941 if ($node->can('getVersion') and $node->can('getEncoding')) {
2942 $result=_xml_decl($node,undef,undef)."\n";
2943 }
2944 $result.=
2945 join("\n",map { to_string($_,$depth-1,$folding,$fold_attrs) }
2946 grep { $SKIP_DTD ? !$_xml_module->is_dtd($_) : 1 } $node->childNodes);
2947 } else {
2948 $result=$_xml_module->toStringUTF8($node,$INDENT);
2949 }
2950 } else {
2951 $result = ref($node) ? $_xml_module->toStringUTF8($node,$INDENT) : $node;
2952 }
2953 }
2954 return $result;
2955 }
2956  
2957 # list nodes matching given XPath argument to a given depth
2958 sub list {
2959 my ($opts,$exp)=@_;
2960 my $opts = _ev_opts($opts);
2961 $opts->{depth} = ($exp eq '' ? 1 : -1) unless exists($opts->{depth});
2962 $exp = '.' if $exp eq '';
2963 if ($opts->{noindent} and $opts->{indent}) {
2964 die "Can't use --indent and --no-indent together\n";
2965 }
2966 local $INDENT=1 if $opts->{indent};
2967 local $INDENT=0 if $opts->{'no-indent'};
2968 my $ql=_ev_nodelist($exp);
2969 foreach my $node (@$ql) {
2970 print STDERR "checking for folding\n" if "$DEBUG";
2971 my $fold=$opts->{fold} &&
2972 ($_xml_module->is_element($node) || $_xml_module->is_document($node)) &&
2973 $node->findvalue("count(.//\@*[local-name()='fold' and namespace-uri()='$XML::XSH2::xshNS'])");
2974 print STDERR "folding: $fold\n" if "$DEBUG";
2975 out (to_string($node,$opts->{depth},$fold,$opts->{'fold-attrs'}),"\n");
2976 }
2977 print STDERR "\nFound ",scalar(@$ql)," node(s).\n" unless "$QUIET";
2978  
2979 return 1;
2980 }
2981  
2982 # list namespaces in scope of the given nodes
2983 sub list_namespaces {
2984 my ($opts,$exp) = @_;
2985 $opts = _ev_opts($opts);
2986 my $ql= ($opts->{registered} and $exp eq "") ? [] : _ev_nodelist(defined $exp ? $exp : '.');
2987 foreach my $node (@$ql) {
2988 my $n=$node;
2989 my %namespaces;
2990 while ($n) {
2991 foreach my $ns ($n->getNamespaces) {
2992 $namespaces{$ns->localname()}=$ns->value()
2993 unless (exists($namespaces{$ns->localname()}));
2994 }
2995 $n=$n->parentNode();
2996 }
2997 out(pwd($node),":\n");
2998 foreach (sort { $a cmp $b } keys %namespaces) {
2999 out(" xmlns", ($_ ne "" ? ":" : ""),
3000 $_,"=\"",
3001 $namespaces{$_},"\"\n");
3002 }
3003 out("\n");
3004 }
3005 if ($opts->{registered}) {
3006 for (sort keys(%_ns)) {
3007 out(qq(register-namespace $_ "$_ns{$_}";\n));
3008 }
3009 }
3010 return 1;
3011 }
3012  
3013 sub mark_fold {
3014 my ($opts,$exp)=@_;
3015 $opts = _ev_opts($opts);
3016 $opts->{depth} = 0 if $opts->{depth} eq "";
3017 $exp = "." if $exp eq "";
3018 foreach my $node (_ev_nodelist($exp)) {
3019 if ($_xml_module->is_element($node)) {
3020 my $doc=$node->ownerDocument;
3021 if ($doc) {
3022 # pre-declare xsh namespace
3023 my $root=$doc->getDocumentElement;
3024 $root->setAttribute('xmlns:xsh',$XML::XSH2::xshNS) if $root;
3025 }
3026 $node->setAttributeNS($XML::XSH2::xshNS,'xsh:fold',$opts->{depth});
3027 }
3028 }
3029 return 1;
3030 }
3031  
3032 sub mark_unfold {
3033 my ($opts,$exp)=@_;
3034 foreach my $node (_ev_nodelist($exp)) {
3035 if ($_xml_module->is_element($node) and $node->hasAttributeNS($XML::XSH2::xshNS,'fold')) {
3036 remove_node($node->getAttributeNodeNS($XML::XSH2::xshNS,'fold'));
3037 }
3038 }
3039 return 1;
3040 }
3041  
3042 # canonicalize nodes matching given XPath
3043 sub c14n {
3044 my ($opts,$exp)=@_;
3045 $opts = _ev_opts($opts);
3046 $exp ||= '.';
3047 my $ql = _ev_nodelist($exp);
3048 foreach my $node (@$ql) {
3049 out($node->toStringC14N($opts->{comments},$opts->{filter}),"\n");
3050 }
3051 print STDERR "\nFound ",scalar(@$ql)," node(s).\n" unless "$QUIET";
3052 return 1;
3053  
3054 }
3055  
3056 # print canonical xpaths identifying nodes matching given XPath
3057 sub locate {
3058 my ($opts,$exp)=@_;
3059 $opts = _ev_opts($opts);
3060 my $ql= _ev_nodelist($exp);
3061 foreach (@$ql) {
3062 out(pwd($_,$opts->{id}),"\n");
3063 }
3064 print STDERR "\nFound ",scalar(@$ql)," node(s).\n" unless "$QUIET";
3065 return 1;
3066 }
3067  
3068 # print line numbers of matching nodes
3069 sub print_lineno {
3070 my ($opts,$exp)=@_;
3071 $opts = _ev_opts($opts);
3072 my $ql=_ev_nodelist($exp);
3073 foreach (@$ql) {
3074 out($_->line_number,"\n");
3075 }
3076 return 1;
3077 }
3078  
3079 # remove nodes matching given XPath from a document and
3080 # remove all their descendants from all nodelists
3081 sub prune {
3082 my ($opts,$exp)=@_;
3083 my $i=0;
3084 my $ql=_ev_nodelist($exp);
3085 foreach my $node (@$ql) {
3086 remove_node($node,get_keep_blanks());
3087 $i++;
3088 }
3089 print STDERR "removed $i node(s)\n" unless "$QUIET";
3090 return $i;
3091 }
3092  
3093 # evaluate given perl expression
3094 sub eval_substitution {
3095 my ($val,$expr)=@_;
3096 local $_ = $val if defined($val);
3097  
3098 eval lexicalize("$expr");
3099 die $@ if $@; # propagate
3100 return $_;
3101 }
3102  
3103 # sort given nodelist according to the given xsh code and perl code
3104 sub perlsort {
3105 my ($opts,$exp)=@_;
3106 my $opts = _hash_opts($opts);
3107 my $list = _ev_nodelist($exp);
3108 my @list;
3109 my $old_context = _save_context();
3110 my $pos=1;
3111 my $rl = _prepare_result_nl();
3112 if ($opts->{compare}) {
3113 foreach (qw(numeric descending)) {
3114 die "sort cannot use --$_ with --compare at the same time\n" if (exists($opts->{$_}));
3115 }
3116 }
3117 eval {
3118 if (defined($opts->{key})) {
3119 foreach my $node (@$list) {
3120 _set_context([$node,0+@$list,$pos]);
3121 push @list,[$node, _ev_literal($opts->{key})];
3122 $pos++;
3123 }
3124 } else {
3125 @list = map { [$_,to_literal($_)] } @$list;
3126 }
3127 if ($opts->{numeric}) {
3128 if ($opts->{descending}) {
3129 @$rl = map { $_->[0] } sort { $b->[1] <=> $a->[1] } @list;
3130 } else {
3131 @$rl = map { $_->[0] } sort { $a->[1] <=> $b->[1] } @list;
3132 }
3133 } elsif ($opts->{compare}) {
3134 @$rl = map { $_->[0] }
3135 sort {
3136 local $XML::XSH2::Map::a = $a->[1];
3137 local $XML::XSH2::Map::b = $b->[1];
3138 my $result=eval lexicalize($opts->{compare});
3139 die $@ if ($@); # propagate
3140 $result;
3141 } @list;
3142 } else {
3143 if ($opts->{descending}) {
3144 if ($opts->{locale}) {
3145 use locale;
3146 @$rl = map { $_->[0] } sort { $b->[1] cmp $a->[1] } @list;
3147 } else {
3148 @$rl = map { $_->[0] } sort { $b->[1] cmp $a->[1] } @list;
3149 }
3150 } else {
3151 if ($opts->{locale}) {
3152 use locale;
3153 @$rl = map { $_->[0] } sort { $a->[1] cmp $b->[1] } @list;
3154 } else {
3155 @$rl = map { $_->[0] } sort { $a->[1] cmp $b->[1] } @list;
3156 }
3157 }
3158 }
3159 };
3160 my $err = $@;
3161 do {
3162 local $SIG{INT}=\&flagsigint;
3163 _set_context($old_context);
3164 propagate_flagsigint();
3165 };
3166 die $err if $err; # propagate
3167  
3168 return $rl;
3169 }
3170  
3171 # Evaluate given expression over every node matching given XPath
3172 # and substitute content with the result.
3173 # The element is passed to the expression by its name or value in the $_
3174 # variable.
3175 sub perlmap {
3176 my ($opts, $mapexp, $exp)=@_;
3177 $opts = _ev_opts($opts);
3178 my $ql=_ev_nodelist($exp);
3179 my $old_context = _save_context();
3180 my $pos=1;
3181 my $size = @$ql;
3182 my $in_place = $opts->{'in-place'};
3183 @$ql = reverse @$ql if $opts->{reverse};
3184 eval {
3185 foreach my $node (@$ql) {
3186 _set_context([$node,$size,$pos++]);
3187 if ($_xml_module->is_attribute($node)) {
3188 my $val = _ev_literal($mapexp, $node->getValue(),$in_place);
3189 $node->setValue($val) if defined $val;
3190 } elsif ($_xml_module->is_element($node)) {
3191 my $value = _ev($mapexp, $node->textContent(),$in_place);
3192 if (defined($value)) {
3193 # prune content
3194 for my $child ($node->childNodes()) {
3195 $child->unbindNode();
3196 }
3197 if (ref($value)) {
3198 if (UNIVERSAL::isa($value,'XML::LibXML::NodeList')) {
3199 foreach my $n (@$value) {
3200 if ($_xml_module->is_document_fragment($n) or
3201 $n->parentNode and
3202 $_xml_module->is_document_fragment($n->parentNode)) {
3203 # it's a fragment
3204 $node->appendChild($n);
3205 } else {
3206 # safely insert a copy
3207 insert_node($n,$node,undef,'into',undef,undef);
3208 }
3209 }
3210 } elsif (UNIVERSAL::isa($value,'XML::LibXML::Node')) {
3211 insert_node($value,$node,undef,'into',undef,undef);
3212 } else {
3213 $node->appendTextNode(to_literal($value));
3214 }
3215 } else {
3216 $node->appendTextNode($value);
3217 }
3218 }
3219 } elsif ($node->can('setData') and $node->can('getData')) {
3220 my $val = _ev_literal($mapexp, $node->getData(),$in_place);
3221 $node->setData($val) if defined $val;
3222 }
3223 }
3224 };
3225 my $err = $@;
3226 {
3227 local $SIG{INT}=\&flagsigint;
3228 _set_context($old_context);
3229 propagate_flagsigint();
3230 }
3231 die $err if $err; # propagate
3232  
3233 return 1;
3234 }
3235  
3236 sub hash {
3237 my ($opts, $mapexp, $exp)=@_;
3238 $opts = _ev_opts($opts);
3239 my $ql=_ev_nodelist($exp);
3240 my $old_context = _save_context();
3241 my $pos=1;
3242 my $size = @$ql;
3243 my $hash = {};
3244 eval {
3245 foreach my $node (@$ql) {
3246 _set_context([$node,$size,$pos++]);
3247 my $key = _ev($mapexp, $node);
3248 if (exists($hash->{$key})) {
3249 $hash->{$key}->push($node);
3250 } else {
3251 $hash->{$key} = XML::LibXML::NodeList->new($node);
3252 }
3253 }
3254 };
3255 my $err = $@;
3256 {
3257 local $SIG{INT}=\&flagsigint;
3258 _set_context($old_context);
3259 propagate_flagsigint();
3260 }
3261 die $err if $err; # propagate
3262  
3263 return $hash;
3264 }
3265  
3266  
3267 #
3268 sub _ev_namespace {
3269 my ($val)=@_;
3270 if (UNIVERSAL::isa($val,'XML::LibXML::NodeList')) {
3271 die "Namespace cannot be specified as a node-set!";
3272 } elsif (ref($val)) {
3273 return to_literal($val);
3274 } else {
3275 return $val;
3276 }
3277 }
3278  
3279 sub perlrename {
3280 my ($opts, $nameexp, $exp)=@_;
3281 $opts = _ev_opts($opts);
3282 my $ns = _ev_namespace($opts->{namespace});
3283 my $ql=_ev_nodelist($exp);
3284 my $old_context = _save_context();
3285 my $pos=1;
3286 my $size = @$ql;
3287 @$ql = reverse @$ql if $opts->{reverse};
3288 my $in_place = $opts->{'in-place'};
3289 eval {
3290 foreach my $node (@$ql) {
3291 _set_context([$node,$size,$pos++]);
3292 if ($_xml_module->is_attribute($node) ||
3293 $_xml_module->is_element($node) ||
3294 $_xml_module->is_pi($node)) {
3295 if ($node->can('setName')) {
3296 my $name=$node->getName();
3297 my $old_name = $name;
3298 $name = _ev_string($nameexp,$name,$in_place);
3299 if (defined $name) {
3300 # If it is an attribute, check there is no attribute
3301 # with the same name already.
3302 if ($_xml_module->is_attribute($node) and
3303 $old_name ne $name and
3304 $node->getOwnerElement()
3305 ->hasAttributeNS($ns || $node->namespaceURI(), $name)) {
3306 _err "Cannot rename attribute '$old_name' to '$name': ",
3307 "An attribute with same name already exists!";
3308 } else {
3309 $node->setName($name);
3310 if (defined($ns) && $node->nodeName=~/^([^:]+):(.*)$/) {
3311 $node->setNamespace($ns,$1,1);
3312 }
3313 }
3314 }
3315 } else {
3316 _err "Node renaming not supported by ",ref($node);
3317 }
3318 }
3319 }
3320 };
3321 my $err = $@;
3322 {
3323 local $SIG{INT}=\&flagsigint;
3324 _set_context($old_context);
3325 propagate_flagsigint();
3326 }
3327 die $err if $err; # propagate
3328  
3329 return 1;
3330 }
3331  
3332  
3333 ############### AUXILIARY FUNCTIONS ###############
3334  
3335 sub set_attr_ns {
3336 my ($node,$ns,$name,$value)=@_;
3337 if ($ns eq "") {
3338 $node->setAttribute($name,$value);
3339 } else {
3340 $node->setAttributeNS("$ns",$name,$value);
3341 }
3342 }
3343  
3344 # return NS prefix used in the given name
3345 sub name_prefix {
3346 if ($_[0]=~/^([^:]+):/) {
3347 return $1;
3348 }
3349 }
3350  
3351 # try to safely clone a node
3352 sub node_copy {
3353 my ($node,$ns,$dest_doc,$dest)=@_;
3354  
3355 my $copy;
3356 if ($_xml_module->is_element($node) and !$node->hasChildNodes) {
3357 # -- prepare NS
3358 $ns=$node->namespaceURI() if ($ns eq "");
3359 my $prefix = name_prefix($node->getName);
3360 if ($ns eq "" and $prefix ne "") {
3361 $ns=$dest->lookupNamespaceURI($prefix);
3362 }
3363 # --
3364 $copy=new_element($dest_doc,$node->getName(),$ns,
3365 [map { [$_->nodeName(),$_->nodeValue(),
3366 $_xml_module->is_attribute($_) ?
3367 $_->namespaceURI() : ""
3368 ] } $node->attributes],$dest);
3369 } elsif ($_xml_module->is_document_fragment($node)) {
3370 $copy=$_parser->parse_xml_chunk($node->toString());
3371 } else {
3372 $copy=$_xml_module->clone_node($dest_doc,$node);
3373 }
3374 }
3375  
3376 # get element-children of a node (e.g. of a document fragment)
3377 sub get_subelements {
3378 my ($docfrag)=@_;
3379 return grep { $_xml_module->is_element($_) } $docfrag->childNodes();
3380 }
3381  
3382 sub get_following_siblings {
3383 my ($node)=@_;
3384 my @siblings;
3385 $node=$node->nextSibling();
3386 while ($node) {
3387 push @siblings,$node;
3388 $node=$node->nextSibling();
3389 }
3390 return @siblings;
3391 }
3392  
3393 # create new document element before the given nodelist
3394 sub new_document_element {
3395 my ($doc,$node,@nodelist)=@_;
3396 $doc->setDocumentElement($node);
3397 foreach my $n (reverse @nodelist) {
3398 $doc->removeChild($n);
3399 $doc->insertAfter($n,$node);
3400 }
3401 }
3402  
3403 # replace document element with a new one
3404 sub replace_document_element {
3405 my ($old, $new)=@_;
3406 my $doc=$_xml_module->owner_document($old);
3407 my @after_nodes = $old->findnodes('following::node()');
3408 $old->unbindNode();
3409 new_document_element($doc,$new,@after_nodes);
3410 }
3411  
3412 # safely insert source node after, before or instead of the
3413 # destination node. Safety means here that nodes inserted on the
3414 # document level are given special care. the source node may only be
3415 # a document fragment, element, text, CDATA, Comment, Entity or
3416 # a PI (i.e. not an attribute).
3417  
3418 sub safe_insert {
3419 my ($source,$dest,$where) = @_;
3420 my $parent=$dest->parentNode();
3421 return unless $parent;
3422 if ($_xml_module->is_document($parent)) {
3423  
3424 # placing a node on the document-level
3425 # SOURCE: Element
3426 if ($_xml_module->is_element($source)) {
3427 if ($where eq 'after') {
3428 if ($parent->getDocumentElement()) {
3429 die("Error: cannot insert another element into /:\n",
3430 " there's one document element already!");
3431 } else {
3432 new_document_element($parent,$source,
3433 get_following_siblings($dest));
3434 }
3435 return 'keep';
3436 } elsif ($where eq 'before') {
3437 if ($parent->getDocumentElement()) {
3438 die("Error: cannot insert another element into /:\n",
3439 " there's one document element already!");
3440 } else {
3441 new_document_element($parent,$source,
3442 $dest,get_following_siblings($dest));
3443 }
3444 return 'keep';
3445 } elsif ($where eq 'replace') {
3446 # maybe we are loosing the document element here !
3447 if ($parent->getDocumentElement()) {
3448 if ($_xml_module->is_element($dest)) {
3449 my @nextnodes = get_following_siblings($dest);
3450 $dest->unbindNode();
3451 new_document_element($parent,$source, @nextnodes);
3452 } else {
3453 die("Error: cannot insert another element into /:\n",
3454 " there's one document element already!");
3455 }
3456 } else {
3457 new_document_element($parent,$source,
3458 $dest,get_following_siblings($dest));
3459 }
3460 return 'remove';
3461 }
3462 } # SOURCE: PI or Comment or DocFragment with PI's or Comments
3463 elsif ($_xml_module->is_pi($source) ||
3464 $_xml_module->is_comment($source) ||
3465 $_xml_module->is_entity_reference($source) ||
3466 $_xml_module->is_document_fragment($source)) {
3467 # placing a node into an element
3468 if ($where eq 'after') {
3469 $parent->insertAfter($source,$dest);
3470 return 'keep';
3471 } elsif ($where eq 'before') {
3472 $parent->insertBefore($source,$dest);
3473 return 'keep';
3474 } elsif ($where eq 'replace') {
3475 # maybe we are loosing the document element here !
3476 $parent->insertBefore($source,$dest);
3477 return 'remove';
3478 }
3479 } else {
3480 die("Error: cannot insert node ",ref($source)," on a document level");
3481 }
3482 } else {
3483 if ($where eq 'after') {
3484 $parent->insertAfter($source,$dest);
3485 return 'keep';
3486 } elsif ($where eq 'before') {
3487 $parent->insertBefore($source,$dest);
3488 return 'keep';
3489 } elsif ($where eq 'replace') {
3490 $parent->insertBefore($source,$dest);
3491 return 'remove';
3492 }
3493 }
3494 }
3495  
3496 sub _expand_fragment {
3497 return $_xml_module->is_document_fragment($_[0]) ?
3498 $_[0]->childNodes : $_[0];
3499 }
3500  
3501 sub _is_attached {
3502 my ($node)=@_;
3503 while ($node and !$_xml_module->is_document_fragment($node)
3504 and !$_xml_module->is_document($node)) {
3505 $node=$node->parentNode;
3506 }
3507 return $node && !$_xml_module->is_document_fragment($node);
3508 }
3509  
3510 sub set_namespace {
3511 my ($opts,$uri)=@_;
3512 $opts = _ev_opts($opts);
3513 $uri = _ev_string($uri);
3514 my $node = $_xpc->getContextNode;
3515 my $prefix = $opts->{prefix};
3516 unless ($_xml_module->is_element($node) ||
3517 $_xml_module->is_attribute($node)) {
3518 die "set_namespace: namespaces can only be set for element and attribute nodes\n";
3519 }
3520 if (defined $prefix) {
3521 my $declaredURI = $node->lookupNamespaceURI($prefix);
3522 if (defined $declaredURI and $declaredURI eq $uri) {
3523 return $node->setNamespace($uri,$prefix);
3524 } else {
3525 die "Namespace error: prefix '$prefix' already used for the namespace '$declaredURI'\n";
3526 }
3527 } else {
3528 if (defined($prefix = $node->lookupNamespacePrefix($uri))) {
3529 return $node->setNamespace($uri,$prefix);
3530 } else {
3531 die "Namespace error: use declare-ns command to declare a prefix for '$uri' first\n";
3532 }
3533 }
3534 }
3535  
3536 sub declare_namespace {
3537 my ($opts,$prefix,$uri)=@_;
3538 $prefix = _ev_string($prefix);
3539 $uri = _ev_string($uri);
3540 my $node = $_xpc->getContextNode;
3541 unless ($_xml_module->is_element($node)) {
3542 die "declare-ns: namespaces can only be declared on element nodes\n";
3543 }
3544 my $declaredURI = $node->lookupNamespaceURI($prefix);
3545 if (defined $declaredURI and $declaredURI ne $uri) {
3546 die "Namespace error: prefix '$prefix' already used for the namespace '$declaredURI'\n";
3547 }
3548 $node->setNamespace($uri,$prefix,0);
3549 }
3550  
3551 sub change_namespace_prefix {
3552 my ($opts,$new,$old)=@_;
3553 $old = _ev_string($old) if $old;
3554 $new = _ev_string($new);
3555 my $node = $_xpc->getContextNode;
3556 if ($node && $_xml_module->is_element($node)) {
3557 $old = $node->prefix unless defined $old;
3558 return $node->setNamespaceDeclPrefix($old,$new);
3559 } else {
3560 _err("The context node is not an element");
3561 }
3562 }
3563  
3564 sub change_namespace_uri {
3565 my ($opts,$uri,$prefix)=@_;
3566 $prefix = _ev_string($prefix) if $prefix;
3567 $uri = _ev_string($uri);
3568 my $node = $_xpc->getContextNode;
3569 if ($node && $_xml_module->is_element($node)) {
3570 $prefix = $node->prefix unless defined $prefix;
3571 return $node->setNamespaceDeclURI($prefix,$uri);
3572 } else {
3573 _err("The context node is not an element");
3574 }
3575 }
3576  
3577 # use the XPathToXML module to build
3578 # up a XML structure
3579 sub xpath_set {
3580 my ($opts,$exp,$value)=@_;
3581 require XML::XSH2::XPathToXML;
3582 my $xtx = XML::XSH2::XPathToXML->new(namespaces => \%_ns,
3583 XPathContext => $_xpc,
3584 node => xsh_context_node(),
3585 );
3586 $value = _ev($value);
3587 $exp = _expand($exp);
3588 if (ref($value) and UNIVERSAL::isa($value,'XML::LibXML::NodeList')) {
3589 my $result = $xtx->createNode($exp);
3590 if ($_xml_module->is_element($result)) {
3591 # if it's an element, try to clone or attach given nodes
3592 foreach my $node (@$value) {
3593 if ($_xml_module->is_document_fragment($node) or
3594 $node->parentNode and
3595 $_xml_module->is_document_fragment($node->parentNode)) {
3596 # it's a fragment
3597 $result->appendChild($node);
3598 } else {
3599 # safely insert a copy
3600 insert_node($node,$result,undef,'into',undef,undef);
3601 }
3602 }
3603 } else {
3604 $result->setValue(to_literal($value));
3605 }
3606 return $result;
3607 } else {
3608 return $xtx->createNode($exp,to_literal($value));
3609 }
3610 }
3611  
3612 # insert given node to given destination performing
3613 # node-type conversion if necessary
3614 sub insert_node {
3615 my ($node,$dest,$dest_doc,$where,$ns,$rl)=@_;
3616 if ($_xml_module->is_document($node)) {
3617 die "Error: Can't insert/copy/move document nodes!\n";
3618 }
3619 if (!defined($dest_doc)) {
3620 $dest_doc = $_xml_module->owner_document($dest);
3621 }
3622 # destination: Attribute
3623 if ($_xml_module->is_attribute($dest)) {
3624 # source: Text, CDATA, Comment, Entity, Element
3625 if ($_xml_module->is_text($node) ||
3626 $_xml_module->is_cdata_section($node) ||
3627 $_xml_module->is_comment($node) ||
3628 $_xml_module->is_element($node) ||
3629 $_xml_module->is_pi($node)) {
3630 my $val = $_xml_module->is_element($node) ?
3631 $node->textContent() : $node->getData();
3632 if ($where eq 'replace' or $where eq 'into') {
3633 $val=~s/^\s+|\s+$//g;
3634 # xcopy will replace the value several times, which may not be intended
3635 set_attr_ns($dest->ownerElement(),$dest->namespaceURI(),$dest->getName(),$val);
3636 push @$rl,$dest->ownerElement()->getAttributeNodeNS($dest->namespaceURI(),$dest->getName()) if defined($rl);
3637 return 'keep'; # as opposed to 'remove'
3638 } elsif ($where eq 'before' or $where eq 'prepend') {
3639 $val=~s/^\s+//g;
3640 set_attr_ns($dest->ownerElement(),$dest->namespaceURI(),$dest->getName(),
3641 $val.$dest->getValue());
3642 push @$rl,$dest->ownerElement()->getAttributeNodeNS($dest->namespaceURI(),$dest->getName()) if defined($rl);
3643 } elsif ($where eq 'after' or $where eq 'append') {
3644 $val=~s/\s+$//g;
3645 set_attr_ns($dest->ownerElement(),$dest->namespaceURI(),$dest->getName(),
3646 $dest->getValue().$val);
3647 push @$rl,$dest->ownerElement()->getAttributeNodeNS($dest->namespaceURI(),$dest->getName()) if defined($rl);
3648 }
3649  
3650 }
3651 # source: Attribute
3652 elsif ($_xml_module->is_attribute($node)) {
3653 my $name=$node->getName();
3654 my $value = $node->getValue();
3655 if ($where eq 'replace' or $where eq 'after' or $where eq 'before') {
3656 # -- prepare NS
3657 $ns=$node->namespaceURI() if ($ns eq "");
3658 if ($ns eq "" and name_prefix($name) ne "") {
3659 $ns=$dest->lookupNamespaceURI(name_prefix($name))
3660 }
3661 # --
3662 my $elem=$dest->ownerElement();
3663 set_attr_ns($elem,"$ns",$name,$value);
3664 push @$rl,$elem->getAttributeNodeNS("$ns",$name) if defined($rl);
3665 if ($where eq 'replace' and $name ne $dest->getName()) {
3666 return 'remove'; # remove the destination node in the end
3667 } else {
3668 return 'keep'; # no need to remove the destination node
3669 }
3670 } else {
3671 # -- prepare NS
3672 $ns=$dest->namespaceURI(); # given value of $ns is ignored here
3673 # --
3674 if ($where eq 'append') {
3675 set_attr_ns($dest->ownerElement(),"$ns",$dest->getName,$dest->getValue().$value);
3676 } elsif ($where eq 'into') {
3677 set_attr_ns($dest->ownerElement(),"$ns",$dest->getName(),$value);
3678 } elsif ($where eq 'prepend') {
3679 set_attr_ns($dest->ownerElement(),"$ns",$dest->getName(),$value.$dest->getValue());
3680 }
3681 push @$rl,$dest->ownerElement()->getAttributeNodeNS("$ns",$dest->getName()) if defined($rl);
3682 }
3683 } else {
3684 _err("Warning: Ignoring incompatible nodes in insert/copy/move operation:\n",
3685 ref($node)," $where ",ref($dest),"!");
3686 return 1;
3687 }
3688 }
3689 # destination: Document
3690 elsif ($_xml_module->is_document($dest)) {
3691 # source: Attribute, Text, CDATA
3692 if ($_xml_module->is_attribute($node) or
3693 $_xml_module->is_text($node) or
3694 $_xml_module->is_cdata_section($node)
3695 ) {
3696 _err("Warning: Ignoring incompatible nodes in insert/copy/move operation:\n",
3697 ref($node)," $where ",ref($dest),"!");
3698 return 1;
3699 } elsif ($_xml_module->is_element($node)) {
3700 # source: Element
3701 my $copy=node_copy($node,$ns,$dest_doc,$dest);
3702 my $destnode;
3703 my $newwhere;
3704 if ($where =~ /^(?:after|append|into)/) {
3705 $newwhere='after';
3706 $destnode=$dest->lastChild();
3707 } elsif ($where =~ /^(?:before|prepend)/) {
3708 $newwhere='before';
3709 $destnode=$dest->firstChild();
3710 } elsif ($where eq 'replace') {
3711 _err("Warning: Ignoring incompatible nodes in insert/copy/move operation:\n",
3712 ref($node)," $where ",ref($dest),"!");
3713 return 1;
3714 }
3715 push @$rl,_expand_fragment($copy) if defined($rl);
3716 if ($destnode) {
3717 return safe_insert($copy,$destnode,$newwhere);
3718 } else {
3719 new_document_element($dest,$copy);
3720 return 1;
3721 }
3722 } else {
3723 # source: Chunk, PI, Comment, Entity
3724 my $copy=node_copy($node,$ns,$dest_doc,$dest);
3725 if ($where =~ /^(?:after|append|into)/) {
3726 # rather than appendChild which does not work
3727 # for Chunks!
3728 $dest->insertAfter($copy,$dest->lastChild());
3729 } elsif ($where =~ /^(?:before|prepend)/) {
3730 $dest->insertBefore($copy,$dest->firstChild());
3731 } elsif ($where eq 'replace') {
3732 _err("Warning: Ignoring incompatible nodes in insert/copy/move operation:\n",
3733 ref($node)," $where ",ref($dest),"!");
3734 return 1;
3735 }
3736 push @$rl,_expand_fragment($copy) if (defined($rl));
3737 }
3738 }
3739 # destination: Element
3740 elsif ($_xml_module->is_element($dest)) {
3741 # source: Attribute
3742 if ($_xml_module->is_attribute($node)) {
3743 # -- prepare NS
3744 $ns=$node->namespaceURI() if ($ns eq "");
3745 if ($ns eq "" and name_prefix($node->getName) ne "") {
3746 $ns=$dest->lookupNamespaceURI(name_prefix($node->getName))
3747 }
3748 # --
3749 if ($where eq 'into' or $where eq 'append' or $where eq 'prepend') {
3750 set_attr_ns($dest,"$ns",$node->getName(),$node->getValue());
3751 push @$rl,$dest->getAttributeNodeNS("$ns",$node->getName()) if defined($rl);
3752 } elsif ($where eq 'replace') {
3753 my $parent=$dest->parentNode();
3754 if ($_xml_module->is_element($parent)) {
3755 set_attr_ns($dest,"$ns",$node->getName(),$node->getValue());
3756 push @$rl,$dest->getAttributeNodeNS("$ns",$node->getName()) if defined($rl);
3757 } else {
3758 _err("Warning: Cannot replace ",ref($node)," with ",ref($parent),
3759 ": parent node is not an element!");
3760 return 1;
3761 }
3762 return 'remove';
3763 } else {
3764 _err("Warning: Ignoring incompatible nodes in insert/copy/move operation:\n",
3765 ref($node)," $where ",ref($dest),"!");
3766 return 1;
3767 # # converting attribute to element
3768 # my $new=new_element($dest_doc,$node->getName(),$ns,$dest);
3769 # $new->appendText($node->getValue());
3770 # my $parent=$dest->parentNode();
3771 # if ($_xml_module->is_element($parent)) {
3772 # if ($where eq 'before' or $where eq 'after') {
3773 # safe_insert($new,$dest,$where);
3774 # }
3775 # } elsif ($where eq 'append') {
3776 # $dest->appendChild($new);
3777 # } elsif ($where eq 'prepend') {
3778 # $dest->insertBefore($new,$dest->firstChild());
3779 # }
3780 }
3781 }
3782 # source: Any but Attribute
3783 else {
3784 my $copy=node_copy($node,$ns,$dest_doc,$dest);
3785 if ($where eq 'after' or $where eq 'before' or $where eq 'replace') {
3786 push @$rl,_expand_fragment($copy) if defined($rl);
3787 return safe_insert($copy,$dest,$where);
3788 } elsif ($where eq 'into' or $where eq 'append') {
3789 $dest->appendChild($copy);
3790 push @$rl,_expand_fragment($copy) if defined($rl);
3791 } elsif ($where eq 'prepend') {
3792 if ($dest->hasChildNodes()) {
3793 $dest->insertBefore($copy,$dest->firstChild());
3794 } else {
3795 $dest->appendChild($copy);
3796 }
3797 push @$rl,_expand_fragment($copy) if defined($rl);
3798 }
3799 }
3800 }
3801 # destination: Text, CDATA, Comment, PI
3802 elsif ($_xml_module->is_text($dest) ||
3803 $_xml_module->is_cdata_section($dest) ||
3804 $_xml_module->is_comment($dest) ||
3805 $_xml_module->is_pi($dest) ||
3806 $_xml_module->is_entity_reference($dest)
3807 ) {
3808 if ($where =~ /^(?:into|append|prepend)$/ and
3809 ($_xml_module->is_entity_reference($dest) ||
3810 $_xml_module->is_entity_reference($node))) {
3811 _err("Warning: Ignoring incompatible nodes in insert/copy/move operation:\n",
3812 ref($node)," $where ",ref($dest),"!");
3813 return 1;
3814 }
3815 if ($where eq 'into') {
3816 my $value=$_xml_module->is_element($node) ?
3817 $node->textContent() : $node->getData();
3818 $value = "" unless defined $value;
3819 $dest->setData($value);
3820 push @$rl,$dest if defined($rl);
3821 } elsif ($where eq 'append') {
3822 my $value=$_xml_module->is_element($node) ?
3823 $node->textContent() : $node->getData();
3824 $dest->setData($dest->getData().$value);
3825 push @$rl,$dest if defined($rl);
3826 } elsif ($where eq 'prepend') {
3827 my $value=$_xml_module->is_element($node) ?
3828 $node->textContent() : $node->getData();
3829 $dest->setData($value.$dest->getData());
3830 push @$rl,$dest if defined($rl);
3831 }
3832 # replace + source: Attribute
3833 elsif ($where eq 'replace' and $_xml_module->is_attribute($node)) {
3834 my $parent=$dest->parentNode();
3835 # -- prepare NS
3836 $ns=$node->namespaceURI() if ($ns eq "");
3837 if ($ns eq "" and name_prefix($node->getName) ne "") {
3838 $ns=$dest->lookupNamespaceURI(name_prefix($node->getName));
3839 }
3840 # --
3841 if ($_xml_module->is_element($parent)) {
3842 set_attr_ns($dest,"$ns",$node->getName(),$node->getValue());
3843 push @$rl,$dest->getAttributeNodeNS("$ns",$node->getName()) if defined($rl);
3844 }
3845 return 'remove';
3846 } else {
3847 my $parent=$dest->parentNode();
3848 my $new;
3849 # source: Attribute
3850 if ($_xml_module->is_attribute($node)) {
3851 _err("Warning: Ignoring incompatible nodes in insert/copy/move operation:\n",
3852 ref($node)," $where ",ref($dest),"!");
3853 return 1;
3854 # # implicit conversion of attribute to element
3855 # # -- prepare NS
3856 # $ns=$node->namespaceURI() if ($ns eq "");
3857 # if ($ns eq "" and name_prefix($node->getName) ne "") {
3858 # $ns=$parent->lookupNamespaceURI(name_prefix($node->getName));
3859 # }
3860 # # --
3861 # $new=new_element($dest_doc,$node->getName(),$ns,$dest);
3862 # $new->appendText($node->getValue());
3863 }
3864 # source: All other
3865 else {
3866 $new=node_copy($node,$ns,$dest_doc,$dest);
3867 }
3868 if ($where =~ /^(?:after|before|replace)$/) {
3869 push @$rl,_expand_fragment($new) if defined $rl;
3870 return safe_insert($new,$dest,$where);
3871 }
3872 }
3873 } else {
3874 print STDERR "Warning: unsupported/unknown destination type: ",ref($dest),"\n";
3875 print STDERR substr($node->toString(),0,200), substr($dest->toString(),0,200),"\n" if ref($dest);
3876 }
3877 return 1;
3878 }
3879  
3880 # parse a string and create attribute nodes
3881 sub create_attributes {
3882 my ($str)=@_;
3883 my (@ret,$value,$name);
3884 while ($str!~/\G$/gsco) {
3885 if ($str=~/\G\s*([^ \n\r\t=]+)=/gsco) {
3886 my $name=$1;
3887 print STDERR "attribute_name=$1\n" if $DEBUG;
3888 if ($str=~/\G\"((?:[^\\\"]|\\.)*)\"/gsco or
3889 $str=~/\G\'((?:[^\\\']|\\.)*)\'/gsco or
3890 $str=~/\G(.*?)(?=\s+[^ \n\r\t=]+=|\s*$)/gsco) {
3891 $value=$1;
3892 $value=~s/\\(.)/$1/g;
3893 print STDERR "creating $name='$value' attribute\n" if $DEBUG;
3894 push @ret,[$name,$value];
3895 } elsif ($str=~/\G(\s*)$/gsco) {
3896 $value=$1;
3897 print STDERR "creating $name='$1' attribute\n" if $DEBUG;
3898 push @ret,[$name,$value];
3899 last;
3900 } else {
3901 die "Invalid attribute specification near '".substr($str,pos($str))."'\n";
3902 }
3903 } elsif ($str =~ /\G(.*)/gsco) {
3904 die "Invalid attribute specification near '$1'\n"
3905 } else {
3906 last;
3907 }
3908 }
3909 return @ret;
3910 }
3911  
3912 sub new_element {
3913 my ($doc,$name,$ns,$attrs,$dest)=@_;
3914 my $el;
3915 my ($prefix,$localname) = $name=~/^([^:>]+):(.*)$/;
3916 if ($prefix ne "" and $ns eq "") {
3917 die "Error: namespace error: undefined namespace prefix `$prefix'\n";
3918 }
3919 if ($dest && $_xml_module->is_element($dest)) {
3920 print STDERR "DEST is element\n" if $DEBUG;
3921 $el=$dest->addNewChild($ns,$name);
3922
3923 if ($prefix eq "" and $ns eq "" and $dest->lookupNamespaceURI(undef) ne "") {
3924 print STDERR "CLEAR Default NS\n" if $DEBUG;
3925 $el->setNamespace('','',1);
3926 } else {
3927 print STDERR "prefix: $prefix, ns: $ns, lookup: ",$dest->lookupNamespaceURI(undef),".\n" if $DEBUG;
3928 print STDERR $dest->toString(1),"\n" if $DEBUG;
3929 }
3930 $el->unbindNode();
3931 } elsif ($ns ne '') {
3932 print STDERR "DEST is not element, NS: $ns\n" if $DEBUG;
3933 $el=$doc->createElementNS($ns,$name);
3934 } else {
3935 print STDERR "DEST is not element no NS\n" if $DEBUG;
3936 $el=$doc->createElement($name);
3937 }
3938 if (ref($attrs)) {
3939 foreach (@$attrs) {
3940 if ($ns ne "" and ($_->[0]=~/^\Q${prefix}\E:/)) {
3941 print STDERR "NS: $ns\n" if $DEBUG;
3942 $el->setAttributeNS($ns,$_->[0],$_->[1]);
3943 } elsif ($_->[0] =~ "xmlns:(.*)") {
3944 print STDERR "xmlns: $1\n" if $DEBUG;
3945 # don't redeclare NS if already declared on destination node
3946 unless ($_->[1] eq $ns or $dest->lookupNamespaceURI($1) eq $_->[2]) {
3947 $el->setNamespace($_->[1],$1,0) unless ($_->[1] eq $ns);
3948 }
3949 } elsif ($_->[0] eq "xmlns") {
3950 print STDERR "xmlns: @$_\n" if $DEBUG;
3951 # don't redeclare NS if already declared on destination node
3952 unless ($->[1] eq $ns or $dest->lookupNamespaceURI('') eq $_->[2]) {
3953 $el->setNamespace($_->[1],'',0) unless ($_->[1] eq $ns);
3954 }
3955 } elsif ($_->[0]=~/^([^:>]+):/) {
3956 my $lprefix=$1;
3957 if ($_->[2] ne "") {
3958 $el->setAttributeNS($_->[2],$_->[0],$_->[1]);
3959 } else {
3960 # add the attribute anyway (may have wrong qname!)
3961 $el->setAttribute($_->[0],$_->[1]);
3962 }
3963 } else {
3964 next if ($_->[0] eq "xmlns:$prefix" and $_->[1] eq $ns);
3965 $el->setAttribute($_->[0],$_->[1]); # what about other namespaces?
3966 }
3967 }
3968 }
3969 return $el;
3970 }
3971  
3972 # create nodes from their textual representation
3973 sub create_nodes {
3974 my ($type,$str,$doc,$ns)=@_;
3975 my @nodes=();
3976 die "No document for create $type $str for.\n" unless ref($doc);
3977 die "Can't create $type from empty specification.\n"
3978 if ($str eq "" and $type !~ /text|cdata|comment/);
3979 # return undef unless ($str ne "" and ref($doc));
3980 if ($type eq 'chunk') {
3981 @nodes=map {$_->childNodes()}
3982 grep {ref($_)} ($_parser->parse_xml_chunk($str));
3983 } else {
3984 if ($type eq 'attribute') {
3985 foreach (create_attributes($str)) {
3986 my $at;
3987 if ($_->[0]=~/^([^:]+):/ and $1 ne 'xmlns') {
3988 $ns = get_registered_ns($1) if $ns eq "";
3989 die "Error: undefined namespace prefix `$1'\n" if ($ns eq "");
3990 $at=$doc->createAttributeNS($ns,$_->[0],$_->[1]);
3991 } else {
3992 $at=$doc->createAttribute($_->[0],$_->[1]);
3993 }
3994 push @nodes,$at;
3995 }
3996 } elsif ($type eq 'element') {
3997 my ($name,$attributes);
3998 if ($str=~/^\<?([^ \t\n\/\<\>]+)(\s+.*)?(?:\/?\>)?\s*$/) {
3999 print STDERR "element_name=$1\n" if $DEBUG;
4000 print STDERR "attributes=$2\n" if $DEBUG;
4001 my ($elt,$att)=($1,$2);
4002 my $el;
4003 if ($elt=~/^([^:>]+):(.*)$/ or $ns ne "") {
4004 print STDERR "Name: $elt\n" if $DEBUG;
4005 if ($ns eq "") {
4006 print STDERR "NS prefix registered as: $ns\n" if $DEBUG;
4007 $ns = get_registered_ns($1) if $ns eq "";
4008 } else {
4009 print STDERR "NS: $ns\n" if $DEBUG;
4010 }
4011 die "Error: undefined namespace prefix `$1'\n" if ($1 ne "" and $ns eq "");
4012 $el=$doc->createElementNS($ns,$elt);
4013 } else {
4014 $el=$doc->createElement($elt);
4015 }
4016 if ($att ne "") {
4017 $att=~s/\/?\>?$//;
4018 foreach (create_attributes($att)) {
4019 print STDERR "atribute: ",$_->[0],"=",$_->[1],"\n" if $DEBUG;
4020 if ($elt=~/^([^:]+):/ and $1 ne 'xmlns') {
4021 print STDERR "NS: $ns\n" if $DEBUG;
4022 die "Error: undefined namespace prefix `$1'\n" if ($ns eq "");
4023 $el->setAttributeNS($ns,$_->[0],$_->[1]);
4024 } else {
4025 $el->setAttribute($_->[0],$_->[1]);
4026 }
4027 }
4028 }
4029 push @nodes,$el;
4030 # __debug("ns: $ns\n".$el->toString());
4031 } else {
4032 print STDERR "invalid element $str\n" unless "$QUIET";
4033 }
4034 } elsif ($type eq 'text') {
4035 push @nodes,$doc->createTextNode($str);
4036 print STDERR "text=$str\n" if $DEBUG;
4037 } elsif ($type eq 'entity_reference') {
4038 push @nodes,$doc->createEntityReference($str);
4039 print STDERR "entity_reference=$str\n" if $DEBUG;
4040 } elsif ($type eq 'cdata') {
4041 push @nodes,$doc->createCDATASection($str);
4042 print STDERR "cdata=$str\n" if $DEBUG;
4043 } elsif ($type eq 'pi') {
4044 my ($name,$data)=($str=~/^\s*(?:\<\?)?(\S+)(?:\s+(.*?)(?:\?\>)?)?$/);
4045 $data = "" unless defined $data;
4046 my $pi = $doc->createPI($name,$data);
4047 print STDERR "pi=<?$name ... $data?>\n" if $DEBUG;
4048 push @nodes,$pi;
4049 # print STDERR "cannot add PI yet\n" if $DEBUG;
4050 } elsif ($type eq 'comment') {
4051 push @nodes,$doc->createComment($str);
4052 print STDERR "comment=$str\n" if $DEBUG;
4053 } else {
4054 die "unknown type: $type\n";
4055 }
4056 }
4057 return @nodes;
4058 }
4059  
4060 sub run_editor {
4061 my ($data,$editor,$encoding)=@_;
4062 ($editor) = grep {$_ ne ""} $editor,$ENV{VISUAL},$ENV{EDITOR},'vi';
4063 $encoding = $QUERY_ENCODING unless $encoding;
4064 my $dir = tempdir( CLEANUP => 1 );
4065 my ($fh, $filename) = tempfile( DIR => $dir );
4066 binmode $fh,'bytes';
4067 $fh->print(fromUTF8($encoding,$data));
4068 $fh->flush if $fh->can('flush');
4069 close($fh);
4070 if (system($editor." ".$filename) == 0) {
4071 open $fh,$filename;
4072 binmode $fh,'bytes';
4073 $data= join "",map toUTF8($encoding,$_),<$fh>;
4074 close $fh;
4075 } else {
4076 $data=undef;
4077 }
4078 unlink $filename;
4079 unlink $dir;
4080 return $data;
4081 }
4082  
4083 sub ask_user {
4084 my ($question, $answers) = @_;
4085 print STDERR $question;
4086 STDERR->flush;
4087 my $reply = <STDIN>;
4088 chomp $reply;
4089 if ($answers ne "") {
4090 while ($reply !~ /^$answers$/) {
4091 print STDERR "Answer ",join("/",split(/\|/,$answers)),": ";
4092 STDERR->flush;
4093 $reply = <STDIN>;
4094 chomp $reply;
4095 }
4096 }
4097 return $reply;
4098 }
4099  
4100 ############### END OF AUXILIARY FUNCTIONS ###############
4101  
4102 sub edit {
4103 my ($opts,$exp,$variable)=@_;
4104 $opts = _ev_opts($opts);
4105 my $rl = _prepare_result_nl();
4106 my $ql;
4107 unless ($variable) {
4108 $exp = '.' if $exp eq '';
4109 $ql =_ev_nodelist($exp);
4110 unless (@$ql) {
4111 _warn("No nodes matching $exp");
4112 return $rl;
4113 }
4114 # prune nodes included in subtrees of already present nodes
4115 # cause they would get replaced anyway
4116 my %n;
4117 $ql = [ grep {
4118 my $d=$_; my $ret=1;
4119 while ($d) {
4120 if (exists ($n{$$d})) { $ret = 0; last; }
4121 else { $d=$d->parentNode; }
4122 }
4123 $n{$$_}=1; $ret } @$ql ];
4124 }
4125 my $data;
4126 my $node_idx = 0;
4127 my $fix;
4128 my $node;
4129 my $nodes = scalar(@$ql) unless $variable;
4130 while ($variable or ($node = $ql->[$node_idx++])) {
4131 if ($variable) {
4132 $data=_ev_literal($exp)
4133 } else {
4134 my $pwd = pwd($node);
4135 if ($fix) {
4136 undef $fix;
4137 } else {
4138 if ($_xml_module->is_attribute($node)) {
4139 $data=$node->value;
4140 } elsif ($_xml_module->is_element($node) or
4141 $_xml_module->is_document($node) or
4142 $_xml_module->is_text_or_cdata($node) or
4143 $_xml_module->is_comment($node) or
4144 $_xml_module->is_pi($node)) {
4145 $data=$_xml_module->toStringUTF8($node,$opts->{noindent} ? 0 :$INDENT);
4146 } else {
4147 die("Cannot edit ".ref($node)."\n");
4148 }
4149 }
4150 $data="<!-- XSH-COMMENT: $pwd ".
4151 ($opts->{all} ? "($node_idx/$nodes) " : "")."-->\n"
4152 .$data unless $opts->{'no-comment'};
4153 }
4154 my $replacement = run_editor($data,$opts->{editor},$opts->{encoding});
4155 $replacement =~ s/^\s*<!-- XSH-COMMENT: [^>]*-->[ \t]*\n?// unless $variable;
4156 chomp $replacement unless $variable;
4157 while ($replacement eq "" and not($opts->{'allow-empty'})) {
4158 if (-t) {
4159 my $response = ask_user("Result is empty! Is that correct? (yes/no/stop): ",
4160 "y|n|s|yes|no|stop");
4161 if ($response =~ /^y/) {
4162 last;
4163 } elsif ($response =~ /^s/) {
4164 return $variable ? $data : $rl;
4165 } else {
4166 $replacement = run_editor($data,$opts->{editor},$opts->{encoding});
4167 $replacement =~ s/^\s*<!-- XSH-COMMENT: [^>]*-->[ \t]*\n?//;
4168 }
4169 } else {
4170 die("Result is empty, ignoring changes!\n".
4171 "Hint: use --allow-empty option or remove command.\n");
4172 }
4173 }
4174 if ($variable) {
4175 if ($exp) {
4176 _assign($exp,$replacement);
4177 }
4178 return $replacement;
4179 } elsif ($_xml_module->is_attribute($node)) {
4180 $node->setValue($replacement) if defined $replacement;
4181 push @$rl, $node if defined $rl;
4182 } else {
4183 local $RECOVERING=$opts->{recover} ? 1 : $RECOVERING;
4184 local $KEEP_BLANKS=$opts->{'keep-blanks'} ? 1 : !$INDENT;
4185 my $chunk;
4186 if ($_xml_module->is_document($node)) {
4187 $chunk = eval { $_xml_module->parse_string($_parser,$replacement) };
4188 } else {
4189 $chunk = eval { $_xml_module->parse_chunk($_parser,$replacement); };
4190 }
4191 if ($@ or not ref($chunk)) {
4192 if (-t) {
4193 my $c = ask_user("$@\n"."Parse error! Press:\n".
4194 " 1 - continue with next node\n".
4195 " 2 - fix the error in the editor\n".
4196 " 3 - restart editor on this node (discarding changes)\n".
4197 " 4 - stop\n\n".
4198 "Your choice: ","1|2|3|4");
4199 if ($c == 1) {
4200 next;
4201 } elsif ($c == 2) {
4202 $data = $replacement;
4203 $fix=1;
4204 redo;
4205 } elsif ($c == 3) {
4206 redo;
4207 } else {
4208 return $rl;
4209 }
4210 } else {
4211 die("$@"."Error parsing result, ignoring changes!\n");
4212 }
4213 }
4214 if ($_xml_module->is_document($node)) {
4215 foreach my $child ($node->childNodes()) {
4216 $child->unbindNode();
4217 }
4218 foreach my $child ($chunk->childNodes()) {
4219 $child->unbindNode();
4220 if ($_xml_module->is_element($child)) {
4221 $node->setDocumentElement($child);
4222 while (my $sibling = $child->nextSibling) {
4223 $sibling->unbindNode();
4224 $node->insertBefore($sibling);
4225 }
4226 } else {
4227 $node->appendChild($child);
4228 }
4229 }
4230 push @$rl, $chunk->childNodes() if defined $rl;
4231 } else {
4232 if (insert_node($chunk,$node,undef,'replace',undef,$rl) eq 'remove') {
4233 remove_node($node);
4234  
4235 }
4236 }
4237 }
4238 } continue {
4239 last if (not(exists($opts->{all})) or $variable);
4240 }
4241 return $rl;
4242 }
4243  
4244 # copy nodes matching one XPath expression to locations determined by
4245 # other XPath expression
4246 sub copy {
4247 my ($opts,$fexp,$where,$texp,$all_to_all)=@_;
4248 my $fl;
4249 $opts = _ev_opts($opts);
4250 $fl=_ev_nodelist($fexp);
4251 unless (@$fl) {
4252 _warn("No nodes matching $fexp");
4253 return 1;
4254 }
4255 # respective copying
4256 my $rl=_prepare_result_nl();
4257 if ($opts->{respective}) {
4258 my @rtl;
4259 my $old_context = _save_context();
4260 eval {
4261 my $pos=1;
4262 my $size = @$fl;
4263 foreach my $fp (@$fl) {
4264 _set_context([$fp,$size,$pos]);
4265 my $tl=_ev_nodelist($texp);
4266 unless (@$tl) {
4267 my $th = ($pos%10 == 1 ? "st" : $pos%10 == 2 ? "nd" : "th");
4268 _warn("No nodes matching $texp for $pos$th node matching $fexp\n");
4269 }
4270 unless ($all_to_all) { @$tl = ($tl->[0]) }
4271 push @rtl, $tl;
4272 $pos++;
4273 }
4274 };
4275 my $err = $@;
4276 do {
4277 local $SIG{INT}=\&flagsigint;
4278 _set_context($old_context);
4279 propagate_flagsigint();
4280 };
4281 die $err if $err; # propagate
4282 my $reverse = $opts->{'preserve-order'} && $where=~/^(after|prepend)$/;
4283 foreach my $fp ($reverse ? reverse @$fl : @$fl) {
4284 my $tl = $reverse ? pop(@rtl) : shift(@rtl);
4285 foreach my $tp (@$tl) {
4286 my $replace=0;
4287 $replace = ((insert_node($fp,$tp,undef,$where,undef,$rl)
4288 eq 'remove') || $replace);
4289 if ($replace) {
4290 remove_node($tp);
4291 }
4292 }
4293 }
4294 } else {
4295 # non-respective copying
4296 my $tl=_ev_nodelist($texp);
4297 unless (@$tl) {
4298 _warn("No nodes matching $texp");
4299 return $rl;
4300 }
4301 if ($all_to_all) {
4302 my $real_fl;
4303 if ($opts->{'preserve-order'} && $where=~/^(after|prepend)$/) {
4304 $real_fl = [ reverse @$fl ];
4305 } else {
4306 $real_fl = $fl;
4307 }
4308 foreach my $tp (@$tl) {
4309 my $replace=0;
4310 foreach my $fp (@$real_fl) {
4311 $replace = ((insert_node($fp,$tp,undef,$where,undef,$rl)
4312 eq 'remove') || $replace);
4313 }
4314 if ($replace) {
4315 remove_node($tp);
4316 }
4317 }
4318 } else {
4319 _warn("Different number of source and destination nodes.\n".
4320 "(Maybe you wanted to call xcopy/xmove?)\n".
4321 "Continuing anyway!") if (@$fl != @$tl);
4322 while (ref(my $fp=shift @$fl) and ref(my $tp=shift @$tl)) {
4323 my $replace=insert_node($fp,$tp,undef,$where,undef,$rl);
4324 if ($replace eq 'remove') {
4325 remove_node($tp);
4326 }
4327 }
4328 }
4329 }
4330 return $rl;
4331 }
4332  
4333  
4334 # create new nodes from an expression and insert them to locations
4335 # identified by XPath
4336 sub insert {
4337 my ($opts,$type,$str,$where,$exp,$to_all)=@_;
4338 $opts = _ev_opts($opts);
4339 $str = _ev_string($str);
4340 my $ns = _ev_namespace($opts->{namespace});
4341 my $tl=_ev_nodelist($exp);
4342 unless (@$tl) {
4343 _warn("Expression '$exp' returns empty node-list");
4344 return 1;
4345 }
4346 my $rl = _prepare_result_nl();
4347 my @nodes;
4348 @nodes=grep {ref($_)} create_nodes($type,$str,$_xml_module->owner_document($tl->[0]),$ns);
4349 unless (@nodes) {
4350 _warn("Expression generates no nodes to insert");
4351 return $rl;
4352 }
4353 if ($to_all) {
4354 foreach my $tp (@$tl) {
4355 my $replace=0;
4356 foreach my $node (@nodes) {
4357 $replace = (insert_node($node,$tp,undef,$where,undef,$rl) eq 'remove') || $replace;
4358 }
4359 if ($replace) {
4360 remove_node($tp);
4361 }
4362 }
4363 } elsif ($tl->[0]) {
4364 foreach my $node (@nodes) {
4365 if (ref($tl->[0])) {
4366 if (insert_node($node,$tl->[0],undef,$where,undef,$rl) eq 'remove') {
4367 remove_node($tl->[0]);
4368 }
4369 }
4370 }
4371 }
4372 return $rl;
4373 }
4374  
4375 # wrap nodes into a given element
4376 sub wrap {
4377 my ($opts,$str,$exp)=@_;
4378 $opts = _ev_opts($opts);
4379 my $ns = _ev_namespace($opts->{namespace});
4380 $str = _ev_string($str);
4381  
4382 my $rl=_prepare_result_nl();
4383 my $ql=_ev_nodelist($exp);
4384 my %moved;
4385 foreach my $node (@$ql) {
4386 next if $moved{$$node};
4387 my ($el) = create_nodes('element',$str,
4388 $_xml_module->owner_document($node),$ns);
4389 if ($opts->{inner}) {
4390 if ($opts->{while} or $opts->{until}) {
4391 die "wrap: cannot use --while or --until together with --inner\n";
4392 }
4393 if ($_xml_module->is_element($node)) {
4394 my @children = $node->childNodes;
4395 $node->appendChild($el);
4396 foreach my $child (@children) {
4397 $child->unbindNode();
4398 $el->appendChild($child);
4399 }
4400 }
4401 } else {
4402 if ($_xml_module->is_attribute($node)) {
4403 if ($opts->{while} or $opts->{until}) {
4404 _warn("wrap: ignoring --while or --until on an attribute");
4405 }
4406 my $parent=$node->ownerElement();
4407 $parent->insertBefore($el,$parent->firstChild());
4408 set_attr_ns($el,$node->namespaceURI(),
4409 $node->getName(),$node->getValue());
4410 $node->unbindNode();
4411 } else {
4412 my $parent = $node->parentNode();
4413 my $last = undef;
4414 unless ($parent) {
4415 die "wrap: cannot wrap node: ".pwd($node)." (node has no parent)\n";
4416 }
4417 # process --while and --until
4418 if (defined $opts->{while} or defined $opts->{until}) {
4419 my $while = $opts->{while};
4420 my $until = $opts->{until};
4421 my $skip_comments = $opts->{'skip-comments'};
4422 my $skip_ws = $opts->{'skip-whitespace'};
4423 my $skip_pi = $opts->{'skip-pi'};
4424 my $next = $node->nextSibling;
4425 # evaluate $opts->{while} in the context of the following sibling
4426 if ($next) {
4427 my $old_context = _save_context();
4428 eval {
4429 # what should the size be? guess number of all following siblings
4430 my $pos=1;
4431 my $size = $node->findvalue('count(following-sibling::node())');
4432 while ($next) {
4433 unless (($skip_ws and $_xml_module->is_text($next) and $next->getData =~ /^\s*$/) or
4434 ($skip_comments and $_xml_module->is_comment($next)) or
4435 ($skip_pi and $_xml_module->is_pi($next))) {
4436 _set_context([$next,$size,$pos]);
4437 if (defined $while) {
4438 last if !_ev_count($while);
4439 }
4440 if (defined $until) {
4441 my $res = _ev_count($until);
4442 last if $res;
4443 }
4444 $last = $next;
4445 $pos++;
4446 }
4447 $next = $next->nextSibling;
4448 }
4449 };
4450 my $err = $@;
4451 do {
4452 local $SIG{INT}=\&flagsigint;
4453 _set_context($old_context);
4454 propagate_flagsigint();
4455 };
4456 }
4457 }
4458 safe_insert($el,$node,'replace');
4459 $el->appendChild($node);
4460 if ($last) {
4461 my $next = $el->nextSibling;
4462 while ($next) {
4463 $next->unbindNode();
4464 $el->appendChild($next);
4465 $moved{$$next}=1;
4466 last if $next->isSameNode($last);
4467 $next = $el->nextSibling;
4468 }
4469 unless ($next) {
4470 _warn("wrap: something went wrong");
4471 }
4472 }
4473 }
4474 }
4475 push @$rl, $el if defined $rl;
4476 }
4477 return $rl;
4478 }
4479  
4480 # wrap span of nodes into a given element
4481 sub wrap_span {
4482 my ($opts,$str,$xp_start,$xp_end)=@_;
4483 $opts = _ev_opts($opts);
4484 $str = _ev_string($str);
4485 my $ns = _ev_namespace($opts->{namespace});
4486 my $rl=_prepare_result_nl();
4487 my $ql_start=_ev_nodelist($xp_start);
4488 my $ql_end=_ev_nodelist($xp_end);
4489 if (@$ql_start != @$ql_end) {
4490 die "Error: there are ".scalar(@$ql_start)." start nodes, ".
4491 " but ".scalar(@$ql_end)." end nodes!\n";
4492 }
4493 for (my $i=0; $i<=$#$ql_start; $i++) {
4494 my $node = $ql_start->[$i];
4495 my $end_node = $ql_end->[$i];
4496 if (not($node->parentNode()) or not($end_node->parentNode())) {
4497 die "Error: cannot wrap document node\n";
4498 }
4499 foreach my $n ($node,$end_node) {
4500 if ($_xml_module->is_attribute($n)) {
4501 die "Error: attribute node ".pwd($n).
4502 " cannot define a node span boundary\n";
4503 }
4504 }
4505 if (not $node->parentNode()->isSameNode($end_node->parentNode())) {
4506 die "Error: start node ".pwd($node)." and end node ".
4507 pwd($end_node)." have different parents\n";
4508 }
4509 my ($el) = create_nodes('element',$str,
4510 $_xml_module->owner_document($node),$ns);
4511 my $parent = $node->parentNode();
4512 my @span;
4513 my $n=$node;
4514 while ($n) {
4515 push @span,$n;
4516 last if ($n->isSameNode($end_node));
4517 $n=$n->nextSibling();
4518 }
4519 die "Error: Node ".pwd($end_node).
4520 " isn't following sibling of ".pwd($node)."!\n" unless $n;
4521 if ($_xml_module->is_document($parent)) {
4522 # check that document element is within the span
4523 my $docel=$parent->getDocumentElement();
4524 my $found=0;
4525 foreach my $n (@span) {
4526 if ($n->isSameNode($docel)) {
4527 $found=1;
4528 last;
4529 }
4530 }
4531 die "Cannot wrap span: ".pwd($node).
4532 " .. ".pwd($end_node)." (document already has a root element)\n"
4533 unless $found;
4534 replace_document_element($docel,$el);
4535 foreach my $n (@span) {
4536 $n->unbindNode();
4537 $el->appendChild($n);
4538 }
4539 } else {
4540 $parent->insertBefore($el,$node);
4541 foreach my $n (@span) {
4542 $n->unbindNode();
4543 $el->appendChild($n);
4544 }
4545 }
4546 push @$rl, $el if defined $rl;
4547 }
4548 return $rl;
4549 }
4550  
4551  
4552 # normalize nodes
4553 sub normalize_nodes {
4554 my ($opts,$exp)=@_;
4555 my $ql=_ev_nodelist($exp);
4556 foreach (@$ql) {
4557 $_->normalize();
4558 }
4559 return 1;
4560 }
4561  
4562 sub _trim_ws {
4563 my ($text)=@_;
4564 $text=~s/^\s*//;
4565 $text=~s/\s*$//;
4566 return $text;
4567 }
4568  
4569 # strip whitespace from given nodes
4570 sub strip_ws {
4571 my ($opts,$exp)=@_;
4572 my $ql=_ev_nodelist($exp);
4573 foreach my $node (@$ql) {
4574 if ($_xml_module->is_text($node)
4575 or
4576 $_xml_module->is_cdata_section($node)
4577 or
4578 $_xml_module->is_comment($node)
4579 ) {
4580 my $data=_trim_ws($node->getData());
4581 if ($data ne "") {
4582 $data = "" unless defined $data;
4583 $node->setData($data);
4584 } else {
4585 $node->unbindNode();
4586 }
4587 } elsif ($_xml_module->is_pi($node)) {
4588 $node->setData(_trim_ws($node->getData($node)));
4589 } elsif ($_xml_module->is_attribute($node)) {
4590 $node->setValue(_trim_ws($node->getValue));
4591 } elsif ($_xml_module->is_element($node) or
4592 $_xml_module->is_document($node)) {
4593 # traverse children, skip comments, strip text nodes
4594 # until first element or PI or text node containing
4595 # a non-ws character
4596 my $child=$node->firstChild();
4597 while ($child) {
4598 if ($_xml_module->is_text($child) or
4599 $_xml_module->is_cdata_section($child)) {
4600 my $data=_trim_ws($child->getData());
4601 if ($data ne "") {
4602 $data = "" unless defined $data;
4603 $child->setData($data);
4604 last;
4605 } else {
4606 $child->unbindNode();
4607 }
4608 } elsif ($_xml_module->is_element($child) or
4609 $_xml_module->is_pi($child)) {
4610 last;
4611 }
4612 $child=$child->nextSibling();
4613 }
4614 # traverse children (upwards), skip comments, strip text nodes
4615 # until first element or PI or text node containing a non-ws
4616 # character
4617 my $child=$node->lastChild();
4618 while ($child) {
4619 if ($_xml_module->is_text($child) or
4620 $_xml_module->is_cdata_section($child)) {
4621 my $data=_trim_ws($child->getData());
4622 if ($data ne "") {
4623 $data = "" unless defined $data;
4624 $child->setData($data);
4625 last;
4626 } else {
4627 $child->unbindNode();
4628 }
4629 } elsif ($_xml_module->is_element($child) or
4630 $_xml_module->is_pi($child)) {
4631 last;
4632 }
4633 $child=$child->previousSibling();
4634 }
4635 }
4636 }
4637 return 1;
4638 }
4639  
4640 # fetch document's DTD
4641 sub get_dtd {
4642 my ($doc)=@_;
4643 my $dtd;
4644 $dtd=$_xml_module->get_dtd($doc,$QUIET);
4645  
4646 return $dtd;
4647 }
4648  
4649 # check document validity
4650 sub validate_doc {
4651 my ($opts,$exp)=@_;
4652 my $doc = _ev_doc($exp);
4653 $opts = _ev_opts($opts);
4654 if ($opts->{dtd}+$opts->{schema}+$opts->{relaxng}>1) {
4655 die "You can only specify one validation schema at a time\n";
4656 }
4657 if (grep(exists($opts->{$_}), qw(file doc string))>1) {
4658 die "You can only specify one of --file, --doc, --string at a time\n";
4659 }
4660 $opts->{dtd} = 1 unless $opts->{schema} or $opts->{relaxng};
4661 if (exists($opts->{public}) ne "" and not $opts->{dtd}) {
4662 die "--public ID can only be used for DTD validation (--dtd)\n";
4663 }
4664 $opts->{file} = _tilde_expand($opts->{file}) if exists($opts->{file});
4665 my $ret = 0;
4666 if ($doc->can('is_valid')) {
4667 if (!$opts->{dtd} or exists($opts->{file}) or exists($opts->{string}) or
4668 exists($opts->{doc}) or exists($opts->{public})) {
4669 if ($opts->{dtd}) {
4670 my $dtd;
4671 eval { XML::LibXML::Dtd->can('new') } ||
4672 die "DTD validation not supported by your version of XML::LibXML\n";
4673 if (exists($opts->{file}) or exists($opts->{public})) {
4674 $dtd=XML::LibXML::Dtd->new($opts->{public},$opts->{file});
4675 } elsif (exists($opts->{string})) {
4676 $dtd=XML::LibXML::Dtd->parse_string($opts->{string});
4677 } else {
4678 die "Can't use --doc with DTD validation\n";
4679 }
4680 if ($opts->{yesno}) {
4681 $ret = $doc->is_valid($dtd);
4682 out(($ret ? "yes\n" : "no\n"));
4683 } else {
4684 $doc->validate($dtd);
4685 $ret = 1;
4686 }
4687 } elsif ($opts->{relaxng}) {
4688 eval { XML::LibXML::RelaxNG->can('new') } ||
4689 die "RelaxNG validation not supported by your version of XML::LibXML\n";
4690 my $rng;
4691 if (exists($opts->{file})) {
4692 $rng=XML::LibXML::RelaxNG->new(location => $opts->{file});
4693 } elsif (exists($opts->{string})) {
4694 $rng=XML::LibXML::RelaxNG->new(string => $opts->{string});
4695 } elsif (exists($opts->{doc})) {
4696 my $rngdoc=_doc($opts->{doc});
4697 unless (ref($rngdoc)) {
4698 die "--doc argument doesn't evaluate to a document!\n";
4699 }
4700 $rng=XML::LibXML::RelaxNG->new(DOM => $rngdoc);
4701 } else {
4702 die "No RelaxNG schema specified\n";
4703 }
4704 eval { $rng->validate($doc) };
4705 $ret = $@ ? 0 : 1;
4706 if ($opts->{yesno}) {
4707 out($ret ? "yes\n" : "no\n");
4708 } else {
4709 die "$@\n" if $@;
4710 }
4711 } elsif ($opts->{schema}) {
4712 eval { XML::LibXML::Schema->can('new') } ||
4713 die "Schema validation not supported by your version of XML::LibXML\n";
4714 my $xsd;
4715 if (exists($opts->{file})) {
4716 $xsd=XML::LibXML::Schema->new(location => $opts->{file});
4717 } elsif (exists($opts->{string})) {
4718 $xsd=XML::LibXML::Schema->new(string => $opts->{string});
4719 } elsif ($opts->{doc}) {
4720 my $xsddoc=_doc($opts->{doc});
4721 unless (ref($xsddoc)) {
4722 die "--doc argument doesn't evaluate to a document!\n";
4723 }
4724 $xsd=XML::LibXML::Schema->new(string => $xsddoc->toString());
4725 } else {
4726 die "No XSD schema specified\n";
4727 }
4728 eval { $xsd->validate($doc) };
4729 $ret = $@ ? 0 : 1;
4730 if ($opts->{yesno}) {
4731 out($ret ? "yes\n" : "no\n");
4732 } else {
4733 die "$@\n" if $@;
4734 }
4735 }
4736 } else {
4737 if ($opts->{yesno}) {
4738 $ret = $doc->is_valid();
4739 out(($ret ? "yes\n" : "no\n"));
4740 } else {
4741 $doc->validate();
4742 $ret = 1;
4743 }
4744 }
4745 } else {
4746 die("Vaidation not supported by ",ref($doc));
4747 }
4748 return $ret;
4749 }
4750  
4751 # process XInclude elements in a document
4752 sub process_xinclude {
4753 my ($opts, $exp)=@_;
4754 my $doc = _ev_doc($exp);
4755 if ($doc) {
4756 $_xml_module->doc_process_xinclude($_parser,$doc);
4757 }
4758 return 1;
4759 }
4760  
4761 # print document's DTD
4762 sub list_dtd {
4763 my $opts = shift;
4764 my $doc = _ev_doc($_[0]);
4765 if ($doc) {
4766 my $dtd=get_dtd($doc);
4767 if ($dtd) {
4768 out($_xml_module->toStringUTF8($dtd),"\n");
4769 }
4770 }
4771 return 1;
4772 }
4773  
4774 # set document's DTD
4775 sub set_dtd {
4776 my $opts = _ev_opts($_[0]);
4777 my $doc = _ev_doc($_[1]);
4778  
4779 if ($doc) {
4780 my $root = $opts->{name};
4781 my $public = $opts->{public};
4782 my $system = $opts->{system};
4783 if ((defined ($public) or defined ($system)) and !defined($root)) {
4784 if ($doc->getDocumentElement) {
4785 $root = $doc->getDocumentElement->nodeName();
4786 } else {
4787 die "No --name not specified and document has no root element\n"
4788 }
4789 }
4790 if ($doc->internalSubset) {
4791 $doc->removeInternalSubset();
4792 }
4793 if ($doc->externalSubset) {
4794 $doc->removeExternalSubset();
4795 }
4796 return 1 unless (defined $root or defined $public or defined $system);
4797 if ($opts->{internal}) {
4798 $doc->setInternalSubset($doc->createInternalSubset($root, $public,
4799 $system));
4800 } else {
4801 $doc->setInternalSubset($doc->createInternalSubset($root, $public,
4802 $system));
4803 }
4804 }
4805 return 1;
4806 }
4807  
4808  
4809 # print document's encoding
4810 sub print_enc {
4811 my ($opts,$doc)=@_;
4812 my $doc = _ev_doc($doc);
4813 if ($doc) {
4814 out($_xml_module->doc_encoding($doc),"\n");
4815 }
4816 return 1;
4817 }
4818  
4819 sub set_doc_enc {
4820 my $opts = shift;
4821 my ($encoding,$doc)=(_ev_literal($_[0]),_ev_doc($_[1]));
4822 if ($doc) {
4823 $_xml_module->set_encoding($doc,$encoding);
4824 }
4825 return 1;
4826 }
4827  
4828 sub set_doc_standalone {
4829 my $opts = shift;
4830 my ($standalone,$doc)=(_ev_literal($_[0]),_ev_doc($_[1]));
4831 $standalone=1 if $standalone=~/yes/i;
4832 $standalone=0 if $standalone=~/no/i;
4833 $_xml_module->set_standalone($doc,$standalone);
4834 return 1;
4835 }
4836  
4837 sub doc_info {
4838 my $opts = shift;
4839 my $doc = _ev_doc($_[0]);
4840 if ($doc) {
4841 # out("type=",$doc->nodeType,"\n");
4842 out("version=",$doc->version(),"\n");
4843 out("encoding=",$doc->encoding(),"\n");
4844 out("standalone=",$doc->standalone(),"\n");
4845 out("compression=",$doc->compression(),"\n");
4846 out("URI=",$doc->URI(),"\n");
4847 }
4848 }
4849  
4850 # create an identical copy of a document
4851 sub clone {
4852 my ($opts,$exp)=@_;
4853 my $doc = _ev_doc($exp);
4854 if ($doc) {
4855 return _clone_xmldoc($doc);
4856 } else {
4857 return undef;
4858 }
4859 }
4860  
4861 # test if $nodea is an ancestor of $nodeb
4862 sub is_ancestor_or_self {
4863 my ($nodea,$nodeb)=@_;
4864 while ($nodeb) {
4865 if ($_xml_module->xml_equal($nodea,$nodeb)) {
4866 return 1;
4867 }
4868 $nodeb=tree_parent_node($nodeb);
4869 }
4870 }
4871  
4872 # remove node and all its surrounding whitespace textual siblings
4873 # from a document; remove all its descendant from all nodelists
4874 # change current element to the nearest ancestor
4875 sub remove_node {
4876 my ($node,$trim_space)=@_;
4877 if (is_ancestor_or_self($node,xsh_context_node())) {
4878 _set_context([tree_parent_node($node)]);
4879 }
4880 my $doc;
4881 $doc=$_xml_module->owner_document($node);
4882 if ($trim_space) {
4883 my $sibling=$node->nextSibling();
4884 if ($sibling and
4885 $_xml_module->is_text($sibling) and
4886 $sibling->getData =~ /^\s+$/) {
4887 # remove_node_from_nodelists($sibling,$doc);
4888 $_xml_module->remove_node($sibling);
4889 }
4890 }
4891 # remove_node_from_nodelists($node,$doc);
4892 $_xml_module->remove_node($node);
4893 }
4894  
4895 # move nodes matching one XPath expression to locations determined by
4896 # other XPath expression
4897 sub move {
4898 my $exp=$_[1]; #source xpath
4899 my $sourcenodes=_ev_nodelist($exp);
4900 my $res=copy(@_);
4901 foreach my $node (@$sourcenodes) {
4902 remove_node($node);
4903 }
4904 return $res;
4905 }
4906  
4907 # call a shell command and print out its output
4908 sub sh_noev {
4909 system($_[0]);
4910 return 1;
4911 }
4912  
4913 sub sh {
4914 my $opts = shift;
4915 my $cmd=join " ",map { _ev_string($_) } @_;
4916 return system(fromUTF8($ENCODING, $cmd));
4917 }
4918  
4919 # print the result of evaluating an XPath expression in scalar context
4920 sub print_count {
4921 my $opts = _ev_opts(shift);
4922 my $count=count_xpath(@_);
4923 out("$count\n") unless $opts->{quiet};
4924 return $count;
4925 }
4926  
4927 sub perl_eval_command {
4928 shift; # opts
4929 &perl_eval;
4930 }
4931  
4932 sub perl_eval {
4933 my ($exp,$map,$in_place)=@_;
4934 select $OUT;
4935 use utf8;
4936 if (wantarray) {
4937 my @result=eval(lexicalize($exp));
4938 die $@ if $@;
4939 return @result;
4940 } elsif (defined $map) {
4941 if (ref($map)) {
4942 $map = to_literal($map);
4943 }
4944 if ($in_place) {
4945 local $_ = $map;
4946 eval(lexicalize($exp));
4947 die $@ if $@;
4948 return $_;
4949 } else {
4950 # abraka dabra: some magic to make $_ read only
4951 local *_ = eval "\\'$map'";
4952 my $result=eval(lexicalize($exp));
4953 die $@ if $@;
4954 return $result;
4955 }
4956 } else {
4957 my $result=eval(lexicalize($exp));
4958 die $@ if $@;
4959 return $result;
4960 }
4961 }
4962  
4963 # evaluate a perl expression
4964 sub print_eval {
4965 my ($expr)=@_;
4966 perl_eval($expr);
4967 return 1;
4968 }
4969  
4970 # change current directory
4971 sub cd {
4972 my $dir = _tilde_expand(_ev_string($_[0]));
4973 unless (chdir $dir) {
4974 print STDERR "Can't change directory to $dir\n";
4975 return 0;
4976 } else {
4977 out("$dir\n") unless "$QUIET";
4978 }
4979 return 1;
4980 }
4981  
4982 # call methods from a list
4983 sub run_commands {
4984 return 0 unless ref($_[0]) eq "ARRAY";
4985 my @cmds=@{$_[0]};
4986 my $top_level=$_[1];
4987 my $want_returns=$_[2];
4988 my $trapsignals=$top_level;
4989 my $result=undef;
4990  
4991 my ($cmd,@params);
4992  
4993 # make sure errors throw exceptions
4994 local $_die_on_err=1 unless ($top_level);
4995 local $_want_returns=1 if ($want_returns);
4996  
4997 store_variables(1);
4998 store_lex_variables(1);
4999 no strict qw(refs);
5000 eval {
5001 local $SIG{INT}=\&sigint if $trapsignals;
5002 local $SIG{PIPE}=\&sigpipe if $trapsignals;
5003 foreach my $run (@cmds) {
5004 if (ref($run) eq 'ARRAY' or ref($run) eq 'XML::XSH2::Command') {
5005 ($RT_LINE,$RT_COLUMN,$RT_OFFSET,$RT_SCRIPT,$cmd,@params)=@$run;
5006 if ($cmd eq "test-mode") { $TEST_MODE=1; $result=1; next; }
5007 if ($cmd eq "run-mode") { $TEST_MODE=0; $result=1; next; }
5008 next if $TEST_MODE;
5009 $result=$cmd->(@params) if defined($cmd);
5010 } else {
5011 $result=0;
5012 }
5013 }
5014 };
5015 my $err = $@;
5016 do {
5017 local $SIG{INT}=\&flagsigint;
5018 restore_lex_variables();
5019 restore_variables();
5020 propagate_flagsigint();
5021 };
5022 if (!$trapsignals and $err =~ /^SIGINT|^SIGPIPE/) {
5023 die $err
5024 } else {
5025 _check_err($err,1);
5026 }
5027 return $result;
5028 }
5029  
5030 sub run_string {
5031 xsh_rd_parser_init() unless $_xsh;
5032 my $pt = $_xsh->startrule($_[0]);
5033 post_process_parse_tree($pt);
5034 return run_commands($pt,0);
5035 }
5036  
5037 sub run_exp {
5038 my ($opts,$exp)=@_;
5039 local $SCRIPT="<eval() called from $RT_SCRIPT line $RT_COLUMN>";
5040 run_string(_ev_literal($exp));
5041 }
5042  
5043 # redirect output and call methods from a list
5044 sub pipe_command {
5045 return 1 if $TEST_MODE;
5046  
5047 local $SIG{PIPE}=sub { };
5048 my ($cmd,$pipe)=@_;
5049  
5050 return 0 unless (ref($cmd) eq 'ARRAY');
5051  
5052 if ($^O eq 'MSWin32') {
5053 _warn("Output redirection not supported on Win32 - ignoring pipe!");
5054 return run_commands($cmd);
5055 }
5056 $pipe = expand($pipe);
5057 if ($pipe eq '') {
5058 die "Error: empty redirection\n";
5059 }
5060 my $out=$OUT;
5061 print STDERR "openning pipe $pipe\n" if $DEBUG;
5062 my $pid;
5063 eval {
5064 use IPC::Open2;
5065 {
5066 local *O = *$out;
5067 my $P;
5068 $pid = open2('>&O',$P,$pipe) || die "cannot open pipe $pipe\n";
5069 $OUT=$P;
5070 ## this is an approach to locate a bug in perl
5071 # local *NEWIN;
5072 # $pid = open2('>&O',\*NEWIN,$pipe) || die "cannot open pipe $pipe\n";
5073 # $OUT=\*NEWIN; #$P;
5074 # my $STDOUT=\*STDOUT;
5075 # for ($STDOUT,$OUT,$out) {
5076 # print STDERR "$_ => ".$_->fileno."\n";
5077 # }
5078 ## print $OUT "FOO\n";
5079 run_commands($cmd);
5080 }
5081 };
5082 # print STDERR "FILENO:",$OUT->fileno,"\n";
5083 # print STDERR `ls -l /proc/$$/fd/`;
5084 my $err=$@;
5085 do {
5086 local $SIG{INT}=\&flagsigint;
5087 if (UNIVERSAL::can($OUT,'flush')) {
5088 flush $OUT;
5089 flush $OUT;
5090 }
5091 close $OUT;
5092 waitpid($pid,0);
5093 $OUT=$out;
5094 flush $OUT if UNIVERSAL::can($OUT,'flush');
5095 propagate_flagsigint();
5096 };
5097 die $err if $err; # propagate
5098 return 1;
5099 }
5100  
5101 # redirect output to a string and call methods from a list
5102 sub string_pipe_command {
5103 my ($cmd,$name)=@_;
5104 return 0 unless (ref($cmd) eq 'ARRAY');
5105 if ($name ne '') {
5106 my $out=$OUT;
5107 print STDERR "Pipe to $name\n" if $DEBUG;
5108 require IO::Scalar;
5109 $OUT=new IO::Scalar;
5110 eval {
5111 run_commands($cmd);
5112 };
5113 my $err;
5114 do {
5115 local $SIG{INT}=\&flagsigint;
5116 _assign($name,${$OUT->sref}) unless $@;
5117 $OUT=$out;
5118 propagate_flagsigint();
5119 };
5120 die $err if $err; # propagate
5121 }
5122 return 0;
5123 }
5124  
5125  
5126 # call methods as long as given XPath returns positive value
5127 sub while_statement {
5128 my ($exp,$command)=@_;
5129 my $result=1;
5130 my $res;
5131 while ($res=_ev_count($exp)) {
5132 eval {
5133 $result = run_commands($command) && $result;
5134 };
5135 if (ref($@) and UNIVERSAL::isa($@,'XML::XSH2::Internal::LoopTerminatingException')) {
5136 if ($@->label =~ /^(?:next|last|redo)$/ and $@->[1]>1) {
5137 $@->[1]--;
5138 die $@; # propagate to a higher level
5139 }
5140 if ($@->label eq 'next') {
5141 next;
5142 } elsif ($@->label eq 'last') {
5143 last;
5144 } elsif ($@->label eq 'redo') {
5145 redo;
5146 } else {
5147 die $@; # propagate
5148 }
5149 } elsif ($@) {
5150 die $@; # propagate
5151 }
5152 }
5153 return $result;
5154 }
5155  
5156 sub throw_exception {
5157 my $opts = shift;
5158 die _ev_literal($_[0])."\n";
5159 }
5160  
5161 sub try_catch {
5162 my ($try,$catch,$var)=@_;
5163 my $result;
5164 eval {
5165 local $TRAP_SIGPIPE=1;
5166 local $SIG{INT}=\&sigint;
5167 local $SIG{PIPE}=\&sigpipe;
5168 # local $_die_on_err=1; # make sure errors cause an exception
5169 $result = run_commands($try);
5170 };
5171 if (ref($@) and UNIVERSAL::isa($@,'XML::XSH2::Internal::UncatchableException')) {
5172 die $@; # propagate
5173 } elsif ($@) {
5174 my $err=$@;
5175 if ($err =~ /^SIGINT/) {
5176 die $err; # propagate sigint
5177 } else {
5178 chomp($err) unless ref($err);
5179 if (ref($var) and @{$var}>1) {
5180 create_block_var(@$var);
5181 _assign($var->[0],$err);
5182 eval {
5183 $result = run_commands($catch);
5184 };
5185 $err = $@;
5186 do {
5187 local $SIG{INT}=\&flagsigint;
5188 destroy_block_var($var->[1]);
5189 propagate_flagsigint();
5190 };
5191 die $err if $err; # propagate
5192 } else {
5193 _assign($var->[0],$@) if ref($var);
5194 $result = run_commands($catch);
5195 }
5196 }
5197 }
5198 return $result;
5199 }
5200  
5201 sub loop_next {
5202 my $opts = shift;
5203 die XML::XSH2::Internal::LoopTerminatingException->new('next',_ev_literal(@_));
5204 }
5205 sub loop_prev {
5206 my $opts = shift;
5207 die XML::XSH2::Internal::LoopTerminatingException->new('prev',_ev_literal(@_));
5208 }
5209 sub loop_redo {
5210 my $opts = shift;
5211 die XML::XSH2::Internal::LoopTerminatingException->new('redo',_ev_literal(@_));
5212 }
5213 sub loop_last {
5214 my $opts = shift;
5215 die XML::XSH2::Internal::LoopTerminatingException->new('last',_ev_literal(@_));
5216 }
5217  
5218 sub _save_context {
5219 return [xsh_context_node(),
5220 $_xpc->can('setContextSize') ?
5221 ($_xpc->getContextSize(),$_xpc->getContextPosition()) :
5222 (undef,undef)];
5223 }
5224  
5225 sub _set_context {
5226 my ($node,$size,$pos)=@{$_[0]};
5227 if ($node) {
5228 $_xpc->setContextNode($node);
5229 if (defined($size) and defined($pos) and $_xpc->can('setContextSize')) {
5230 die "invalid size $size\n" if ($size < -1);
5231 $_xpc->setContextSize($size);
5232 die "invalid position $pos (size is $size)\n" if ($pos < -1 or $pos>$size);
5233 $_xpc->setContextPosition($pos);
5234 }
5235 } else {
5236 die "Trying to change current node to an undefined value\n";
5237 }
5238 }
5239  
5240  
5241 # call methods on every node matching an XPath
5242 sub foreach_statement {
5243 my ($exp,$command,$v)=@_;
5244 my ($var,$local) = ref($v) ? @$v : ();
5245 my $old_context = _save_context();
5246 create_block_var($var,$local) if $var ne "";
5247 eval {
5248 my @ql = ($var ne "") ? _ev_list($exp) : _ev_nodelist($exp);
5249 my $pos=1;
5250 my $size = @ql;
5251 foreach my $node (@ql) {
5252 if ($var ne "") {
5253 _assign($var,$node);
5254 } else {
5255 _set_context([$node,$size,$pos]);
5256 }
5257 eval {
5258 run_commands($command);
5259 };
5260 if (ref($@) and UNIVERSAL::isa($@,'XML::XSH2::Internal::LoopTerminatingException')) {
5261 if ($@->label =~ /^(?:next|last|redo)$/ and $@->[1]>1) {
5262 $@->[1]--;
5263 die $@; # propagate to a higher level
5264 }
5265 if ($@->label eq 'next') {
5266 $pos++;
5267 next;
5268 } elsif ($@->label eq 'last') {
5269 last;
5270 } elsif ($@->label eq 'redo') {
5271 redo;
5272 } else {
5273 die $@; # propagate
5274 }
5275 } elsif ($@) {
5276 die $@; # propagate
5277 }
5278 $pos++;
5279 }
5280 };
5281 my $err = $@;
5282 do {
5283 local $SIG{INT}=\&flagsigint;
5284 _set_context($old_context);
5285 destroy_block_var($local) if ($var ne "");
5286 propagate_flagsigint();
5287 };
5288 die $err if $err; # propagate
5289 return 1;
5290 }
5291  
5292 # run commands if given XPath holds
5293 sub if_statement {
5294 my @cases=@_;
5295 foreach (@cases) {
5296 my ($exp,$command)=@$_;
5297 if (!defined($exp) or _ev_count($exp)) {
5298 return run_commands($command);
5299 }
5300 }
5301 return 1;
5302 }
5303  
5304 # run commands unless given XPath holds
5305 sub unless_statement {
5306 my ($exp,$command,$else)=@_;
5307 unless (_ev_count($exp)) {
5308 return run_commands($command);
5309 } else {
5310 return ref($else) ? run_commands($else->[1]) : 1;
5311 }
5312 }
5313  
5314 sub _clone_xmldoc {
5315 my ($doc)=@_;
5316 if (XML::LibXML::Document->can('cloneNode') ==
5317 XML::LibXML::Node->can('cloneNode')) {
5318 # emulated clone
5319 return $_xml_module->new_parser->parse_string($doc->toString());
5320 } else {
5321  
5322 # native clone (if my patch ever gets into LibXML)
5323 return $doc->cloneNode(1);
5324 }
5325 }
5326  
5327 sub xslt_compile {
5328 my ($as_doc,$stylefile,$want_doc)=@_;
5329 my $styledoc;
5330 if ($as_doc) {
5331 $styledoc = _ev_doc($stylefile);
5332 die "No XSL document: $stylefile\n" unless $styledoc;
5333 } else {
5334 $stylefile = _tilde_expand(_ev_string($stylefile));
5335 if ((-f $stylefile) or ($stylefile=~/^[a-z]+:/)) {
5336 $styledoc = XML::LibXML->new()->parse_file($stylefile);
5337 } else {
5338 die "File not exists '$stylefile'\n";
5339 }
5340 }
5341 require XML::LibXSLT;
5342 my $xsltparser=XML::LibXSLT->new();
5343 my $st = $xsltparser->parse_stylesheet($styledoc);
5344 if ($want_doc) {
5345 return ($st, $styledoc);
5346 } else {
5347 return $st;
5348 }
5349 }
5350  
5351 # transform a document with an XSLT stylesheet
5352 # and create a new document from the result
5353 sub xslt {
5354 my ($opts,$stylefile)=(shift,shift);
5355 my $opts = _ev_opts($opts);
5356  
5357 my $st;
5358 if ($opts->{compile}) {
5359 if (@_ or $opts->{'precompiled'}) {
5360 _warn("Document argument or --precompiled flag given. Ignoring --compile flag!");
5361 } else {
5362 return xslt_compile($opts->{'doc'},$stylefile);
5363 }
5364 }
5365  
5366 if ($opts->{'precompiled'}) {
5367 if ($stylefile =~ /^{/) {
5368 $st = _ev($stylefile);
5369 } elsif ($stylefile =~ /^\$/) {
5370 $st = var_value($stylefile);
5371 } else {
5372 die "Pre-compiled XSLT stylesheet can't be given only as perl expression or a variable: $stylefile\n";
5373 }
5374 unless (ref($st) and UNIVERSAL::isa($st,'XML::LibXSLT::Stylesheet') or
5375 UNIVERSAL::isa($st,'XML::LibXSLT::StylesheetWrapper')) {
5376 die "Pre-compiled XSLT stylesheet doesn't appear to be a XML::LibXSLT::Stylesheet object: $stylefile\n";
5377 }
5378 } else {
5379 print STDERR "compiling\n";
5380 ($st,my $styledoc) = xslt_compile($opts->{doc},$stylefile,1);
5381 die "No XSLT document: $stylefile\n" unless $st;
5382 $stylefile = $styledoc->URI;
5383 }
5384  
5385 my $source;
5386 if (@_) {
5387 $source = shift;
5388 } else {
5389 $source = '.';
5390 }
5391  
5392 my $doc = _ev_doc($source);
5393  
5394 my @params = expand(@_);
5395 print STDERR "running xslt on $doc stylesheet $stylefile params @params\n" if "$DEBUG";
5396 die "No document to process with XSLT: $source\n" unless $doc;
5397 my %params;
5398 foreach my $p (@params) {
5399 $p=$1 while $p=~/^\s*\((.*)\)\s*$/;
5400 if ($p=~/^\s*(\S+?)\s*=\s*(.*?)\s*$/) {
5401 $params{$1}=$2;
5402 } else {
5403 die("Malformed XSLT parameter $p");
5404 }
5405 }
5406 if ($DEBUG) {
5407 print STDERR map { "$_ -> $params{$_} " } keys %params;
5408 print STDERR "\n";
5409 }
5410  
5411 my $rl = $opts->{'string'} ? undef : _prepare_result_nl();
5412 if ($st) {
5413 $stylefile=~s/\..*$//;
5414 my $result = eval {
5415 $st->transform(_clone_xmldoc($doc),%params);
5416 };
5417 if ($result) {
5418 _warn $@ if $@;
5419 } else {
5420 die $@."\n" if $@;
5421 }
5422 if ($opts->{'string'}) {
5423 return $st->output_string($result);
5424 } else {
5425 set_doc_URI($result,
5426 _base_filename($stylefile).
5427 "_transformed_".
5428 _base_filename($result->URI()));
5429 push @$rl,$result if defined $rl;
5430 }
5431 } else {
5432 die "Failed to parse stylesheet '$stylefile'\n";
5433 }
5434 return $rl;
5435 }
5436  
5437 # perform xupdate processing over a document
5438 sub xupdate {
5439 my ($opts,$xupdate_doc,$doc)=map { _ev_doc($_) } @_;
5440 if ($xupdate_doc and $doc) {
5441 require XML::XUpdate::LibXML;
5442 require XML::Normalize::LibXML;
5443 my $xupdate = XML::XUpdate::LibXML->new();
5444 $XML::XUpdate::LibXML::debug=1;
5445 $xupdate->process($doc->getDocumentElement(),$xupdate_doc);
5446 } else {
5447 if ($xupdate_doc) {
5448 die "Expression '$_[0]' returns empty nodeset\n";
5449 } else {
5450 die "Expression '$_[1]' returns empty nodeset\n";
5451 }
5452 return 0;
5453 }
5454 }
5455  
5456 sub call_return {
5457 my $opts = shift;
5458 die XML::XSH2::Internal::SubTerminatingException->new('return',_ev($_[0]));
5459 }
5460  
5461 sub call_command {
5462 my ($opts,$exp,@args)=@_;
5463 my $name = _ev_string($exp);
5464 call($opts,1,$name, @args);
5465 }
5466  
5467 # call a named set of commands
5468 sub call {
5469 my ($opts,$eval_args, $name, @args)=@_;
5470 my $def = $_defs{$name};
5471 if (defined $def) {
5472 my @vars = @$def[2..$#$def];
5473 if (@vars < @args) {
5474 _err("too many arguments [".join(";\n",@args)."] for subroutine '$name @vars'");
5475 } elsif (@vars > @args) {
5476 _err("too few arguments for subroutine '$name @vars'");
5477 }
5478 my $result;
5479 my %vars;
5480 foreach (@args) {
5481 $vars{ shift(@vars) }=$eval_args ? _ev($_) : $_;
5482 }
5483 my $prev_lex_context = $lexical_variables;
5484 $lexical_variables = $def->[1];
5485 store_lex_variables(1,keys(%vars));
5486 eval {
5487 foreach (keys(%vars)) {
5488 _assign($_,$vars{$_});
5489 }
5490 $result = run_commands($def->[0]);
5491 };
5492 my $err = $@;
5493 do {
5494 local $SIG{INT}=\&flagsigint;
5495 restore_lex_variables();
5496 $lexical_variables=$prev_lex_context;
5497 propagate_flagsigint();
5498 };
5499 if (ref($err) and UNIVERSAL::isa($err,'XML::XSH2::Internal::SubTerminatingException')) {
5500 my $ret = $err->[1];
5501 undef $err;
5502 return $ret;
5503 }
5504 die $err if $err; # propagate
5505 return $result;
5506 } else {
5507 die "ERROR: $name not defined\n";
5508 }
5509 }
5510  
5511 sub undefine {
5512 my ($name)=@_;
5513 if ($name =~ /^\s*\$(.*)$/) {
5514 _undef($name);
5515 my $lex = lex_var($1);
5516 if ($lex) {
5517 undef $$lex;
5518 } else {
5519 no strict qw(refs);
5520 undef ${"XML::XSH2::Map::".$1};
5521 }
5522 } else {
5523 delete $_defs{$name};
5524 }
5525 return 1;
5526 }
5527  
5528 # define a named set of commands
5529 sub def {
5530 my ($name,$command,$args)=@_;
5531 $_defs{$name} = [ $command, [ @$lexical_variables ], @$args ];
5532 return 1;
5533 }
5534  
5535 # return a list of all definined subroutines
5536 sub defs {
5537 return sort keys %_defs;
5538 }
5539  
5540 # list all defined subroutines
5541 sub list_defs {
5542 my $opts = shift;
5543 foreach (sort keys (%_defs)) {
5544 out(join(" ",$_,@{ $_defs{$_} }[2..$#{ $_defs{$_} }] ),"\n" );
5545 }
5546 return 1;
5547 }
5548  
5549 # load a file
5550 sub load {
5551 my ($file,$enc)=@_;
5552 my $l;
5553 print STDERR "loading file $file\n" unless "$QUIET";
5554 $enc ||= $QUERY_ENCODING;
5555 if (-f $file and open my $f,"$file") {
5556 if ($] >= 5.008) {
5557 binmode $f,":encoding($enc)";
5558 }
5559 return join "",<$f>;
5560 } else {
5561 die "ERROR: couldn't open input file $file\n";
5562 }
5563 }
5564  
5565 # call XSH to evaluate commands from a given file
5566 sub include {
5567 my ($opts,$f,$conditionally)=@_;
5568 $f=_tilde_expand(_ev_string($f));
5569 # File should be relative to the current script URI.
5570 $f = XML::XSH2::Map::resolve_uri(URI::file->new($f),
5571 URI::file->new($SCRIPT))->file;
5572 $opts=_ev_opts($opts);
5573 if (!$conditionally || !$_includes{$f}) {
5574 $_includes{$f}=1;
5575 my $l=load($f,$opts->{encoding});
5576 local $SCRIPT = $f;
5577 return run($l);
5578 }
5579 }
5580  
5581 # print help
5582  
5583 sub apropos {
5584 my ($opts,$query)=@_;
5585 $query = expand($query);
5586 $opts=_ev_opts($opts);
5587 if ($opts->{fulltext}) {
5588 foreach my $k (sort keys %XML::XSH2::Help::HELP) {
5589 if ($opts->{regexp}) {
5590 out("$k\n") if ($XML::XSH2::Help::HELP{$k}->[0]=~/$query/i);
5591 } else {
5592 out("$k\n") if ($XML::XSH2::Help::HELP{$k}->[0]=~/\b\Q$query\E\b/i);
5593 }
5594 }
5595 } else {
5596 foreach my $k (sort keys %$XML::XSH2::Help::Apropos) {
5597 if ($opts->{regexp}) {
5598 out("$k\n") if (($k." - ".$XML::XSH2::Help::Apropos->{$k})=~/$query/i);
5599 } else {
5600 out("$k\n") if (($k." - ".$XML::XSH2::Help::Apropos->{$k})=~/\b\Q$query\E\b/i);
5601 }
5602 }
5603 }
5604 }
5605  
5606 sub help {
5607 my $opts = shift;
5608 my ($command)=expand @_;
5609 if ($command) {
5610 if (exists($XML::XSH2::Help::HELP{$command})) {
5611 out($XML::XSH2::Help::HELP{$command}->[0]);
5612 } else {
5613 my @possible =
5614 grep { index($_,$command)==0 }
5615 keys(%XML::XSH2::Help::HELP);
5616 my %h = map { $XML::XSH2::Help::HELP{$_} => $_ } @possible;
5617 if (keys(%h) == 1) {
5618 out($XML::XSH2::Help::HELP{$possible[0]}->[0]);
5619 return 1;
5620 } elsif (keys(%h) > 1) {
5621 out("No help available on $command\n");
5622 out("Did you mean some of ", join(', ',@possible)," ?\n");
5623 } else {
5624 out("No help available on $command\n");
5625 return 0;
5626 }
5627 }
5628 } else {
5629 out($XML::XSH2::Help::HELP);
5630 }
5631 return 1;
5632 }
5633  
5634 # load catalog file to the parser
5635 sub load_catalog {
5636 my $opts = shift;
5637 $_xml_module->load_catalog($_parser,_tilde_expand(_ev_string($_[0])));
5638 return 1;
5639 }
5640  
5641 sub stream_process_node {
5642 my ($node,$command,$input)=@_;
5643 my $old_context = _save_context();
5644 eval {
5645 foreach (1) {
5646 _set_context([$node,1,1]);
5647 eval {
5648 run_commands($command);
5649 };
5650 if (ref($@) and UNIVERSAL::isa($@,'XML::XSH2::Internal::LoopTerminatingException')) {
5651 if ($@->label =~ /^(?:next|redo)$/ and $@->[1]>1) {
5652 $@->[1]--;
5653 die $@; # propagate to a higher level
5654 }
5655 if ($@->label eq 'next') {
5656 last;
5657 } elsif ($@->label eq 'redo') {
5658 redo;
5659 } else {
5660 die $@; # propagate
5661 }
5662 } elsif ($@) {
5663 die $@; # propagate
5664 }
5665 }
5666 };
5667 my $err = $@;
5668 do {
5669 local $SIG{INT}=\&flagsigint;
5670 _set_context($old_context);
5671 propagate_flagsigint();
5672 };
5673 die $err if $err; # propagate
5674 }
5675  
5676 sub stream_process {
5677 my ($opts, $process)=@_;
5678 $opts = _ev_opts($opts);
5679  
5680 require XML::Filter::DOMFilter::LibXML;
5681 require XML::LibXML::SAX;
5682 require XML::SAX::Writer;
5683  
5684 if (grep {/^input-/} keys %$opts>1) {
5685 die "Only one --input-xxxx parameter can be specified\n";
5686 }
5687 if (grep {/^output-/} grep { !/^output-encoding/ } keys %$opts>1) {
5688 die "Only one --output-xxxx parameter can be specified\n";
5689 }
5690  
5691 my $out;
5692 my $termout;
5693 $opts->{'input-file'} = _tilde_expand($opts->{'input-file'}) if exists($opts->{'input-file'});
5694 $opts->{'output-file'} = _tilde_expand($opts->{'output-file'}) if exists($opts->{'output-file'});
5695 my $output = $opts->{'output-string'} || $opts->{'output-pipe'} ||
5696 $opts->{'output-file'} || '-';
5697 my $input = $opts->{'input-string'} || $opts->{'input-pipe'} ||
5698 $opts->{'input-file'} || '-';
5699  
5700 if (exists $opts->{'output-file'}) {
5701 open $out,'>'.$output || die "Cannot open output file ".$output."\n";
5702 if ($] >= 5.008) {
5703 binmode ($out,
5704 ($opts->{'output-encoding'} ?
5705 ":encoding(".$opts->{'output-encoding'}.")" : ":utf8"));
5706 }
5707 } elsif (exists $opts->{'output-pipe'}) {
5708 open $out,'| '.$output || die "Cannot open pipe to ".$output."\n";
5709 if ($] >= 5.008) {
5710 binmode ($out,
5711 ($opts->{'output-encoding'} ?
5712 ":encoding(".$opts->{'output-encoding'}.")" : ":utf8"));
5713 }
5714 } elsif (exists $opts->{'output-string'}) {
5715 my $output = $opts->{'output-string'};
5716 if ($output =~ /^\$(\$?[a-zA-Z_][a-zA-Z0-9_]*)$/) {
5717 $out = _get_var_ref($output);
5718 } elsif (ref($OUT)=~/Term::ReadLine/) {
5719 $out = *$OUT;
5720 $termout=1;
5721 } else {
5722 $out = $OUT;
5723 $termout=1;
5724 }
5725 } else {
5726 $out = $output;
5727 }
5728 my $parser=XML::LibXML::SAX
5729 ->new( Handler =>
5730 XML::Filter::DOMFilter::LibXML
5731 ->new(Handler =>
5732 XML::SAX::Writer::XML
5733 ->new(
5734 Output => $out,
5735 Writer => 'XML::SAX::Writer::XMLEnc'
5736 ),
5737 XPathContext => $_xpc,
5738 Process => [
5739 map {
5740 $_->[0] => [\&stream_process_node,$_->[1],
5741 $input] }
5742 @$process
5743 ]
5744 )
5745 );
5746 if (exists $opts->{'input-pipe'}) {
5747 open my $F,"$input|";
5748 $F || die "Cannot open pipe to $input: $!\n";
5749 $parser->parse_fh($F);
5750 close $F;
5751 } elsif (exists $opts->{'input-string'}) {
5752 $parser->parse_string($input);
5753 } else { #file
5754 $parser->parse_uri($input);
5755 }
5756 if (exists $opts->{'output-pipe'}) {
5757 close($out);
5758 }
5759 if ($termout) { out("\n"); }
5760 return 1;
5761 }
5762  
5763 sub iterate {
5764 my ($code,$axis,$nodefilter,$filter)=@_;
5765  
5766 $axis =~ s/::$//;
5767 $axis=~s/-/_/g;
5768  
5769 $filter =~ s/^\[\s*((?:.|\n)*?)\s*\]$/$1/ if defined $filter;
5770 my $test;
5771 if ($nodefilter eq "comment()") {
5772 $test = q{ $_xml_module->is_comment($_[0]) }
5773 } if ($nodefilter eq "text()") {
5774 $test = q{ $_xml_module->is_text_or_cdata($_[0]) }
5775 } elsif ($nodefilter =~ /processing-instruction\((\s*['"]([^'"]+)['"]\s*)?\)$/) {
5776 $test = q{ $_xml_module->is_pi($_[0]) };
5777 $test .= qq{ && (\$_[0]->nodeName eq '$1') } if $1 ne "";
5778 } elsif ($nodefilter eq 'node()') {
5779 $test = '1 ';
5780 } elsif ($nodefilter =~ /^(?:([^:]+):)?(.+)$/) {
5781 $test = q{ $_xml_module->is_element($_[0]) };
5782 $test .= qq{ && (\$_[0]->getLocalName() eq '$2') } unless ($2 eq '*');
5783 if ($1 ne "") {
5784 my $ns = xsh_context_node()->lookupNamespaceURI($1);
5785 die("Unrecognized namespace prefix '$1:'!") if ($ns eq "");
5786 $test .= qq{ && (\$_[0]->namespaceURI() eq '$ns') };
5787 }
5788 }
5789  
5790 die("Position index filter not supported for iteration ([$filter])") if $filter =~ /^\d+$/;
5791 if ($filter ne '') {
5792 $filter =~ s/\\/\\\\/g;
5793 $filter =~ s/'/\\'/g;
5794 $test .= qq{ && \$_xpc->find('$filter',\$_[0]) };
5795 }
5796 $test = "1" if $test eq "";
5797  
5798 my $filter_sub = eval "sub { $test }";
5799 die $@ if $@;
5800 my $iterator;
5801 do {
5802 my $start=xsh_context_node();
5803 $iterator=XML::XSH2::Iterators->create_iterator($start,$axis,$filter_sub);
5804 };
5805 return 1 unless defined $iterator;
5806  
5807 my $old_context=_save_context();
5808  
5809 my $count = 1;
5810 my $pos = 1;
5811 eval {
5812 ITER: while ($iterator->current()) {
5813 _set_context([$iterator->current(),$count,$pos]);
5814 eval {
5815 run_commands($code);
5816 };
5817 if (ref($@) and UNIVERSAL::isa($@,'XML::XSH2::Internal::LoopTerminatingException')) {
5818 if ($@->label =~ /^(?:next|last|redo|prev)$/ and $@->[1]>1) {
5819 $@->[1]--;
5820 die $@; # propagate to a higher level
5821 }
5822 if ($@->label eq 'next') {
5823 $count ++; $pos ++;
5824 $iterator->next() || last;
5825 next;
5826 } elsif ($@->label eq 'prev') {
5827 $pos --;
5828 $iterator->prev() || die("No previous node to iterate to!");
5829 next;
5830 } elsif ($@->label eq 'last') {
5831 last;
5832 } elsif ($@->label eq 'redo') {
5833 redo;
5834 } else {
5835 die $@; # propagate
5836 }
5837 } elsif ($@) {
5838 die $@; # propagate
5839 }
5840 $count ++; $pos ++;
5841 $iterator->next() || last;
5842 }
5843 };
5844 my $err = $@;
5845 do {
5846 local $SIG{INT}=\&flagsigint;
5847 _set_context($old_context);
5848 propagate_flagsigint();
5849 };
5850 die $err if $err; # propagate
5851 return 1;
5852 }
5853  
5854 # quit
5855 sub quit {
5856 my $opts = shift;
5857 if (ref($_on_exit)) {
5858 &{$_on_exit->[0]}($_[0],@{$_on_exit}[1..$#$_on_exit]); # run on exit hook
5859 }
5860 exit(int($_[0]));
5861 }
5862  
5863 sub register_ns {
5864 my $opts = shift;
5865 my $prefix = _ev_string($_[0]);
5866 my $ns = _ev_string($_[1]);
5867  
5868 unless ($prefix=~m{^[-_.[:alpha:]][-_.[:alnum:]]*$}) {
5869 die "Invalid namespace prefix '$prefix'\n";
5870 }
5871 $_ns{$prefix}=$ns;
5872 $_xpc->registerNs($prefix,$ns);
5873 return 1;
5874 }
5875  
5876 sub register_xsh_ns {
5877 my $opts = shift;
5878 register_ns($opts,_ev_string($_[0]),$XML::XSH2::xshNS);
5879 }
5880  
5881 sub register_xhtml_ns {
5882 my $opts = shift;
5883 register_ns($opts,_ev_string($_[0]),'http://www.w3.org/1999/xhtml');
5884 }
5885  
5886 sub unregister_ns {
5887 my ($opts,$exp)=@_;
5888 my $prefix = _ev_string($exp);
5889 delete $_ns{$prefix};
5890 $_xpc->unregisterNs($prefix);
5891 return 1;
5892 }
5893  
5894 sub get_registered_ns {
5895 return $_ns{$_[0]};
5896 }
5897  
5898 sub get_registered_prefix {
5899 my %r = reverse %_ns;
5900 return $r{$_[0]};
5901 }
5902  
5903 sub register_func {
5904 my ($opts,$name,$code)=@_;
5905 $name=_ev_string($name);
5906 my $sub;
5907 if ($code =~ /^\s*{/) {
5908 my $lex = lexicalize("sub $code");
5909 $sub = eval($lex);
5910 } elsif ($code =~/^\s*([A-Za-z_][A-Za-z_0-9]*(::[A-Za-z_][A-Za-z_0-9]*)*)\s*$/) {
5911 if ($2 ne "") {
5912 $sub=\&{"$1"};
5913 } else {
5914 $sub=\&{"XML::XSH2::Map::$1"};
5915 }
5916 } else {
5917 $sub = eval(lexicalize("sub \{ $code \}"));
5918 }
5919 die $@ if $@;
5920 if ($name =~ /^([^:]+):(.*)$/) {
5921 if (exists($_ns{$1})) {
5922 $_func{"$2\n$_ns{$1}"}=$sub;
5923 $_xpc->registerFunctionNS($2, $_ns{$1}, $sub);
5924 } else {
5925 die "Registration failed: unknown namespace prefix $1!\n";
5926 }
5927 } else {
5928 $_func{$name}=$sub;
5929 $_xpc->registerFunction($name, $sub);
5930 }
5931 return 1;
5932 }
5933  
5934 sub unregister_func {
5935 my ($opts,$name)=@_;
5936  
5937 if ($name =~ /^([^:]+):(.*)$/) {
5938 if (exists($_ns{$1})) {
5939 delete $_func{"$2\n$_ns{$1}"};
5940 $_xpc->unregisterFunctionNS($2, $_ns{$1});
5941 } else {
5942 die "Registration failed: unknown namespace prefix $1!\n";
5943 }
5944 } else {
5945 delete $_func{$name};
5946 $_xpc->unregisterFunction($name);
5947 }
5948 return 1;
5949 }
5950  
5951 sub node_type {
5952 my ($node)=@_;
5953 return undef unless $node;
5954 if ($_xml_module->is_element($node)) {
5955 return 'element';
5956 } elsif ($_xml_module->is_attribute($node)) {
5957 return 'attribute';
5958 } elsif ($_xml_module->is_text($node)) {
5959 return 'text';
5960 } elsif ($_xml_module->is_cdata_section($node)) {
5961 return 'cdata';
5962 } elsif ($_xml_module->is_pi($node)) {
5963 return 'pi';
5964 } elsif ($_xml_module->is_entity_reference($node)) {
5965 return 'entity_reference';
5966 } elsif ($_xml_module->is_document($node)) {
5967 return 'document';
5968 } elsif ($_xml_module->is_document_fragment($node)) {
5969 return 'chunk';
5970 } elsif ($_xml_module->is_comment($node)) {
5971 return 'comment';
5972 } elsif ($_xml_module->is_namespace($node)) {
5973 return 'namespace';
5974 } else {
5975 return 'unknown';
5976 }
5977 }
5978  
5979 #######################################################################
5980 #######################################################################
5981  
5982  
5983 package XML::XSH2::Map;
5984  
5985 BEGIN {
5986 import XML::XSH2::Functions ':param_vars';
5987
5988  
5989 *fromUTF8 = *XML::XSH2::Functions::fromUTF8;
5990 *toUTF8 = *XML::XSH2::Functions::toUTF8;
5991 }
5992  
5993 sub call {
5994 XML::XSH2::Functions::call({},0,@_);
5995 }
5996  
5997 sub serialize {
5998 my $exp=$_[0];
5999 my $ql;
6000 if (ref($exp)) {
6001 if (UNIVERSAL::isa($exp,'XML::LibXML::NodeList')) {
6002 $ql=$exp;
6003 } elsif (UNIVERSAL::isa($exp,'XML::LibXML::Node')) {
6004 $ql=[$exp];
6005 } else {
6006 $ql=&XML::XSH2::Functions::_ev_nodelist($exp);
6007 }
6008 } else {
6009 $ql=&XML::XSH2::Functions::_ev_nodelist($exp);
6010 }
6011 my $result='';
6012 foreach (@$ql) {
6013 $result.=$_->toString();
6014 }
6015 return $result;
6016 }
6017  
6018 sub literal {
6019 my $xp=$_[0] || current();
6020 return XML::XSH2::Functions::to_literal(ref($xp) ? $xp : XML::XSH2::Functions::_ev($xp));
6021 }
6022  
6023 sub type {
6024 my ($xp)=@_;
6025 my $ql;
6026 unless (ref($xp)) {
6027 $xp='.' if $xp eq "";
6028 $ql = &XML::XSH2::Functions::_ev_nodelist($xp);
6029 } elsif (ref($xp) eq 'ARRAY' or
6030 UNIVERSAL::isa($xp,'XML::LibXML::NodeList')) {
6031 $ql = $xp;
6032 } else {
6033 $ql = [$xp];
6034 }
6035 my @result;
6036 foreach (@$ql) {
6037 push @result,&XML::XSH2::Functions::node_type($_);
6038 return $result[0] unless (wantarray);
6039 }
6040 return @result;
6041 }
6042  
6043 sub nodelist {
6044 return XML::LibXML::NodeList->new(map {
6045 XML::XSH2::Functions::cast_value_to_objects($_)
6046 } @_);
6047 }
6048  
6049 sub xpath {
6050 my ($exp, $node) = @_;
6051 $node = $node->[0] if (UNIVERSAL::isa($node,'XML::LibXML::NodeList'));
6052 my $r = $XML::XSH2::Functions::_xpc->find($exp,$node);
6053 # my $r = XML::XSH2::Functions::_ev($_[0]);
6054 if (wantarray and ref($r) and UNIVERSAL::isa($r,'XML::LibXML::NodeList')) {
6055 return @$r;
6056 } else {
6057 return $r;
6058 }
6059 }
6060  
6061 *echo = *XML::XSH2::Functions::out;
6062  
6063 sub xsh {
6064 my ($p, $s, $l)=caller;
6065 local $XML::XSH2::Functions::SCRIPT="<xsh() called from $s line $l>";
6066 XML::XSH2::Functions::run_string(join "",XML::XSH2::Functions::cast_objects_to_values(@_));
6067 }
6068  
6069 sub current {
6070 return XML::XSH2::Functions::xsh_context_node();
6071 }
6072  
6073 sub position {
6074 if ($XML::XSH2::Functions::_xpc->can('getContextPosition')) {
6075 return $XML::XSH2::Functions::_xpc->getContextPosition();
6076 } else {
6077 die "Sorry, installed XML::LibXML::XPathContext version doesn't support proximity position\n";
6078 }
6079 }
6080  
6081 *count = *XML::XSH2::Functions::count_xpath;
6082 *xml_list = *serialize;
6083  
6084 sub resolve_uri {
6085 my ($rel,$base)=@_;
6086 if (defined $base) {
6087 return URI->new_abs($rel,URI->new($base)->abs(URI::file->cwd));
6088 } else {
6089 return URI->new_abs($rel,URI::file->cwd);
6090 }
6091 }
6092  
6093 #######################################################################
6094 #######################################################################
6095  
6096 package XML::XSH2::Internal::Exception;
6097  
6098 sub new {
6099 my $class=(ref($_[0]) || $_[0]);
6100 shift;
6101 return bless [@_], $class;
6102 }
6103  
6104 sub set_label {
6105 my ($label)=@_;
6106 return $_[0]->[0]=$label;
6107 }
6108  
6109 sub label {
6110 return $_[0]->[0];
6111 }
6112  
6113 sub value {
6114 my ($index)=@_;
6115 return $_[0]->[$index];
6116 }
6117  
6118 sub set_value {
6119 my ($index,$value)=@_;
6120 return $_[0]->[$index]=$value;
6121 }
6122  
6123 package XML::XSH2::Internal::UncatchableException;
6124 use vars qw(@ISA);
6125 @ISA=qw(XML::XSH2::Internal::Exception);
6126  
6127 package XML::XSH2::Internal::LoopTerminatingException;
6128 use vars qw(@ISA);
6129 @ISA=qw(XML::XSH2::Internal::UncatchableException);
6130  
6131 package XML::XSH2::Internal::SubTerminatingException;
6132 use vars qw(@ISA);
6133 @ISA=qw(XML::XSH2::Internal::UncatchableException);
6134  
6135  
6136 #######################################################################
6137 #######################################################################
6138  
6139 package XML::SAX::Writer::XMLEnc;
6140 use vars qw(@ISA);
6141 @ISA=qw(XML::SAX::Writer::XML);
6142  
6143 sub xml_decl {
6144 my ($self,$data) = @_;
6145 if ($data->{Encoding}) {
6146 $self->{EncodeTo}=$data->{Encoding};
6147 $self->setConverter();
6148 }
6149 $self->SUPER::xml_decl($data);
6150 }
6151  
6152  
6153 # taken from Variable::Alias
6154 package XML::XSH2::VarAlias;
6155 use strict;
6156 use warnings;
6157 use Tie::Scalar;
6158 use vars qw(@ISA);
6159 @ISA=qw(Tie::StdScalar);
6160  
6161 sub TIESCALAR {
6162 return bless $_[1], $_[0];
6163 }
6164  
6165 1;
6166