blib/lib/XML/Compile/Translate/Reader.pm untested

filter: Statementstmt 0.0% 0 / 708 Branchbran 0.0% 0 / 306 Conditioncond 0.0% 0 / 433 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 54 Podpod 0.0% 0 / 43 totaltotal 0.0% 0 / 1544 CC 149 SCAR 45.3
CC
149
Cov
0%
makeBuiltin
306.0
makeBlockHandler
240.0
makeChoice
210.0
CRAP 92.9
1 # Copyrights 2006-2018 by [Mark Overmeer <markov@cpan.org>].
2 # For other contributors see ChangeLog.
3 # See the manual pages for details on the licensing terms.
4 # Pod stripped from pm file by OODoc 2.02.
5 # This code is part of distribution XML-Compile. Meta-POD processed with
6 # OODoc into POD and HTML manual-pages. See README.md
7 # Copyright Mark Overmeer. Licensed under the same terms as Perl itself.
8  
9 package XML::Compile::Translate::Reader;
10 use vars '$VERSION';
11 $VERSION = '1.60';
12  
13 use base 'XML::Compile::Translate';
14  
15 use strict;
16 use warnings;
17 no warnings 'once', 'recursion';
18  
19 use Log::Report 'xml-compile';
20  
21 use List::Util qw/first/;
22 use Scalar::Util qw/weaken blessed/;
23  
24 use XML::Compile::Util qw/pack_type odd_elements type_of_node SCHEMA2001i/;
25 use XML::Compile::Iterator ();
26  
27  
28 # Each action implementation returns a code reference, which will be
29 # used to do the run-time work. The mechanism of `closures' is used to
30 # keep the important information. Be sure that you understand closures
31 # before you attempt to change anything.
32  
33 # The returned reader subroutines will always be called
34 # my @pairs = $reader->($tree);
35  
36 # Some error messages are labeled with 'misfit' which is used to indicate
37 # that the structure of found data is not conforming the needs. For optional
38 # blocks, these errors are caught and un-done.
39  
40 sub actsAs($) {$_[1] eq 'READER'}
41 sub makeTagUnqualified(@) {$_[3]} # ($self, $path, $node, $local, $ns)
42 sub makeTagQualified(@) {$_[3]} # same params
43  
44 sub typemapToHooks($$)
45 { my ($self, $hooks, $typemap) = @_;
46 while(my($type, $action) = each %$typemap)
47 { defined $action or next;
48 my $hook;
49 if(!ref $action)
50 { my $class = $action;
51 no strict 'refs';
52 keys %{$class.'::'}
53 or error __x"class {pkg} for typemap {type} is not loaded"
54 , pkg => $class, type => $type;
55  
56 $class->can('fromXML')
57 or error __x"class {pkg} does not implement fromXML(), required for typemap {type}"
58 , pkg => $class, type => $type;
59  
60 trace "created reader hook for type $type to class $class";
61 $hook = sub { $class->fromXML($_[1], $type) };
62 }
63 elsif(ref $action eq 'CODE')
64 { $hook = sub { $action->(READER => $_[1], $type) };
65 trace "created reader hook for type $type to CODE";
66 }
67 else
68 { my $object = $action;
69 $object->can('fromXML')
70 or error __x"object of class {pkg} does not implement fromXML(), required for typemap {type}"
71 , pkg => ref($object), type => $type;
72  
73 trace "created reader hook for type $type to object";
74 $hook = sub {$object->fromXML($_[1], $type)};
75 }
76  
77 push @$hooks, +{action => 'READER', type => $type, after => $hook};
78 }
79 $hooks;
80 }
81  
82 sub makeElementWrapper
83 { my ($self, $path, $processor) = @_;
84 # no copy of $_[0], because it may be a large string
85 sub { my $tree;
86 if(blessed $_[0] && $_[0]->isa('XML::LibXML::Iterator'))
87 { $tree = $_[0];
88 }
89 else
90 { my $xml = XML::Compile->dataToXML($_[0])
91 or return ();
92 $xml = $xml->documentElement
93 if $xml->isa('XML::LibXML::Document');
94 $tree = XML::Compile::Iterator->new($xml, 'top',
95 sub { $_[0]->isa('XML::LibXML::Element') } );
96 }
97  
98 my $data = ($processor->($tree))[-1];
99 unless(defined $data)
100 { my $node = $tree->node;
101 error __x"data not recognized, found a `{type}' at {where}"
102 , type => type_of_node $node, where => $node->nodePath;
103 }
104 $data;
105 };
106 }
107  
108 sub makeAttributeWrapper
109 { my ($self, $path, $processor) = @_;
110  
111 sub { my $attr = shift;
112 ref $attr && $attr->isa('XML::LibXML::Attr')
113 or error __x"expects an attribute node, but got `{something}' at {path}"
114 , something => (ref $attr || $attr), path => $path;
115  
116 my $node = XML::LibXML::Element->new('dummy');
117 $node->addChild($attr);
118  
119 $processor->($node);
120 };
121 }
122  
123 sub makeWrapperNs # no namespaces in the HASH
124 { my ($self, $path, $processor, $index, $filter) = @_;
125 $processor;
126 }
127  
128 #
129 ## Element
130 #
131  
132 sub makeSequence($@)
133 { my ($self, $path, @pairs) = @_;
134 if(@pairs==2)
135 { my ($take, $action) = @pairs;
136 my $code
137 = (ref $action eq 'BLOCK' || ref $action eq 'ANY')
138 ? sub { $action->($_[0]) }
139 : sub { $action->($_[0] && $_[0]->currentType eq $take ? $_[0]:undef)};
140 return bless $code, 'BLOCK';
141 }
142  
143 bless
144 sub { my $tree = shift;
145 my @res;
146 my @do = @pairs;
147  
148 while(@do)
149 { my ($take, $do) = (shift @do, shift @do);
150 push @res, ref $do eq 'BLOCK'
151 || ref $do eq 'ANY'
152 || (defined $tree && $tree->currentType eq $take)
153 ? $do->($tree) : $do->(undef);
154 }
155  
156 @res;
157 }, 'BLOCK';
158 }
159  
160 sub makeChoice($@)
161 { my ($self, $path, %do) = @_;
162 my @specials;
163 foreach my $el (keys %do)
164 { push @specials, delete $do{$el}
165 if ref $do{$el} eq 'BLOCK' || ref $do{$el} eq 'ANY';
166 }
167  
168 if(keys %do==1 && !@specials)
169 { my ($option, $action) = %do;
170 return bless
171 sub { my $tree = shift;
172 my $type = defined $tree ? $tree->currentType : '';
173 return $action->($tree)
174 if $type eq $option;
175  
176 try { $action->(undef) }; # minOccurs=0
177 $@ or return ();
178  
179 $type
180 or error __x"element `{tag}' expected for choice at {path}"
181 , tag => $option, path => $path, _class => 'misfit';
182  
183 error __x"single choice option `{option}' at `{type}' at {path}"
184 , option => $option, type => $type, path => $path
185 , _class => 'misfit';
186 }, 'BLOCK';
187 }
188  
189 @specials or return bless
190 sub { my $tree = shift;
191 my $type = defined $tree ? $tree->currentType : undef;
192 my $elem = defined $type ? $do{$type} : undef;
193 return $elem->($tree) if $elem;
194  
195 # very silly situation: some people use a minOccurs within
196 # a choice, instead on choice itself. That always succeeds.
197 foreach my $some (values %do)
198 { try { $some->(undef) };
199 $@ or return ();
200 }
201  
202 $type
203 or error __x"no element left to pick choice at {path}"
204 , path => $path, _class => 'misfit';
205  
206 trace "choose element from @{[sort keys %do]}";
207 error __x"no applicable choice for `{tag}' at {path}"
208 , tag => $type, path => $path, _class => 'misfit';
209 }, 'BLOCK';
210  
211 return bless
212 sub { my $tree = shift;
213 my $type = defined $tree ? $tree->currentType : undef;
214 my $elem = defined $type ? $do{$type} : undef;
215 return $elem->($tree) if $elem;
216  
217 my @special_errors;
218 foreach (@specials)
219 { my @d = try { $_->($tree) };
220 return @d if !$@ && @d;
221 push @special_errors, $@->wasFatal->message if $@;
222 }
223  
224 foreach my $some (values %do, @specials)
225 { try { $some->(undef) };
226 $@ or return ();
227 }
228  
229 $type
230 or error __x"choice needs more elements at {path}"
231 , path => $path, _class => 'misfit';
232  
233  
234 my @elems = sort keys %do;
235 trace "choose element from @elems or fix special at $path" if @elems;
236 trace "failed specials in choice: $_" for @special_errors;
237  
238 error __x"no applicable choice for `{tag}' at {path}"
239 , tag => $type, path => $path, _class => 'misfit';
240 }, 'BLOCK';
241 }
242  
243 sub makeAll($@)
244 { my ($self, $path, %pairs) = @_;
245 my %specials;
246 foreach my $el (keys %pairs)
247 { $specials{$el} = delete $pairs{$el}
248 if ref $pairs{$el} eq 'BLOCK' || ref $pairs{$el} eq 'ANY';
249 }
250  
251 if(!%specials && keys %pairs==1)
252 { my ($take, $do) = %pairs;
253 return bless
254 sub { my $tree = shift;
255 $do->($tree && $tree->currentType eq $take ? $tree : undef);
256 }, 'BLOCK';
257 }
258  
259 keys %specials or return bless
260 sub { my $tree = shift;
261 my %do = %pairs;
262 my @res;
263 while(1)
264 { my $type = $tree && $tree->currentType or last;
265 my $do = delete $do{$type} or last; # already seen?
266 push @res, $do->($tree);
267 }
268  
269 # saw all of all?
270 push @res, $_->(undef)
271 for values %do;
272  
273 @res;
274 }, 'BLOCK';
275  
276 # an 'all' block with nested structures or any is quite nasty. Don't
277 # forget that 'all' can have maxOccurs > 1 !
278 bless
279 sub { my $tree = shift;
280 my %do = %pairs;
281 my %spseen;
282 my @res;
283 PARTICLE:
284 while(1)
285 { my $type = $tree->currentType or last;
286 if(my $do = delete $do{$type})
287 { push @res, $do->($tree);
288 next PARTICLE;
289 }
290  
291 foreach (keys %specials)
292 { next if $spseen{$_};
293 my @d = try { $specials{$_}->($tree) };
294 next if $@;
295  
296 $spseen{$_}++;
297 push @res, @d;
298 next PARTICLE;
299 }
300  
301 last;
302 }
303 @res or return ();
304  
305 # saw all of all?
306 push @res, $_->(undef)
307 for values %do;
308  
309 push @res, $_->(undef)
310 for map {$spseen{$_} ? () : $specials{$_}} keys %specials;
311  
312 @res;
313 }, 'BLOCK';
314 }
315  
316 sub makeBlockHandler
317 { my ($self, $path, $label, $min, $max, $process, $kind, $multi) = @_;
318  
319 # flatten the HASH: when a block appears only once, there will
320 # not be an additional nesting in the output tree.
321 if($max ne 'unbounded' && $max==1)
322 {
323 return ($label => $process) if $min==1;
324  
325 my $code =
326 sub { my $tree = shift or return ();
327 my $starter = $tree->currentChild or return ();
328 my @pairs = try { $process->($tree) };
329 if($@->wasFatal(class => 'misfit'))
330 { my $ending = $tree->currentChild;
331 $@->reportAll if !$ending || $ending!=$starter;
332 return ();
333 }
334 elsif($@) {$@->reportAll}
335 @pairs;
336 };
337 return ($label => bless($code, 'BLOCK'));
338 }
339  
340 if($max ne 'unbounded' && $min>=$max)
341 { my $code =
342 sub { my $tree = shift;
343 my @res;
344 while(@res < $min)
345 { my @pairs = $process->($tree);
346 push @res, {@pairs};
347 }
348 ($multi => \@res);
349 };
350 return ($label => bless($code, 'BLOCK'));
351 }
352  
353 if($min==0)
354 { my $code =
355 sub { my $tree = shift or return ();
356 my @res;
357 while($max eq 'unbounded' || @res < $max)
358 { my $starter = $tree->currentChild or last;
359 my @pairs = try { $process->($tree) };
360 if($@->wasFatal(class => 'misfit'))
361 { # misfit error is ok, if nothing consumed
362 trace "misfit $label ($min..$max) ".$@->wasFatal->message;
363 my $ending = $tree->currentChild;
364 $@->reportAll if !$ending || $ending!=$starter;
365 last;
366 }
367 elsif($@) {$@->reportAll}
368  
369 @pairs or last;
370 push @res, {@pairs};
371 }
372  
373 @res ? ($multi => \@res) : ();
374 };
375 return ($label => bless($code, 'BLOCK'));
376 }
377  
378 my $code =
379 sub { my $tree = shift or error __xn
380 "block with `{name}' is required at least once at {path}"
381 , "block with `{name}' is required at least {_count} times at {path}"
382 , $min, name => $label, path => $path;
383  
384 my @res;
385 while(@res < $min)
386 { my @pairs = $process->($tree);
387 push @res, {@pairs};
388 }
389 while($max eq 'unbounded' || @res < $max)
390 { my $starter = $tree->currentChild or last;
391 my @pairs = try { $process->($tree) };
392 if($@->wasFatal(class => 'misfit'))
393 { # misfit error is ok, if nothing consumed
394 trace "misfit $label ($min..) ".$@->wasFatal->message;
395 my $ending = $tree->currentChild;
396 $@->reportAll if !$ending || $ending!=$starter;
397 last;
398 }
399 elsif($@) {$@->reportAll};
400  
401 @pairs or last;
402 push @res, {@pairs};
403 }
404 ($multi => \@res);
405 };
406  
407 ($label => bless($code, 'BLOCK'));
408 }
409  
410 sub makeElementHandler
411 { my ($self, $path, $label, $min, $max, $required, $optional) = @_;
412 $max eq "0" and return sub {}; # max can be "unbounded", hence strcmp
413  
414 if($max ne 'unbounded' && $max==1)
415 { return $min==1
416 ? sub { my $tree = shift;
417 my @pairs = $required->(defined $tree ? $tree->descend :undef);
418 $tree->nextChild if defined $tree;
419 ($label => $pairs[1]);
420 }
421 : sub { my $tree = shift or return ();
422 $tree->currentChild or return ();
423 my @pairs = $optional->($tree->descend);
424 $tree->nextChild;
425 @pairs or return ();
426 ($label => $pairs[1]);
427 };
428 }
429
430 if($max ne 'unbounded' && $min>=$max)
431 { return
432 sub { my $tree = shift;
433 my @res;
434 while(@res < $min)
435 { my @pairs = $required->(defined $tree ? $tree->descend:undef);
436 push @res, $pairs[1];
437 $tree->nextChild if defined $tree;
438 }
439 @res ? ($label => \@res) : ();
440 };
441 }
442  
443 if(!defined $required)
444 { return
445 sub { my $tree = shift or return ();
446 my @res;
447 while($max eq 'unbounded' || @res < $max)
448 { $tree->currentChild or last;
449 my @pairs = $optional->($tree->descend);
450 @pairs or last;
451 push @res, $pairs[1];
452 $tree->nextChild;
453 }
454 @res ? ($label => \@res) : ();
455 };
456 }
457  
458 sub { my $tree = shift;
459 my @res;
460 while(@res < $min)
461 { my @pairs = $required->(defined $tree ? $tree->descend : undef);
462 push @res, $pairs[1];
463 $tree->nextChild if defined $tree;
464 }
465 while(defined $tree && ($max eq 'unbounded' || @res < $max))
466 { $tree->currentChild or last;
467 my @pairs = $optional->($tree->descend);
468 @pairs or last;
469 push @res, $pairs[1];
470 $tree->nextChild;
471 }
472 ($label => \@res);
473 };
474 }
475  
476 sub makeRequired
477 { my ($self, $path, $label, $do) = @_;
478  
479 my $req =
480 sub { my $tree = shift; # can be undef
481 my @pairs = $do->($tree);
482 @pairs
483 or error __x"data for element or block starting with `{tag}' missing at {path}"
484 , tag => $label, path => $path, _class => 'misfit';
485 @pairs;
486 };
487 ref $do eq 'BLOCK' ? bless($req, 'BLOCK') : $req;
488 }
489  
490 sub makeElementHref
491 { my ($self, $path, $ns, $childname, $do) = @_;
492  
493 sub { my $tree = shift;
494  
495 return ($childname => $tree->node)
496 if defined $tree
497 && $tree->nodeType eq $childname
498 && $tree->node->hasAttribute('href');
499  
500 $do->($tree);
501 };
502 }
503  
504 sub makeElement
505 { my ($self, $path, $ns, $childname, $do) = @_;
506 sub { my $tree = shift;
507 my $value = defined $tree && $tree->nodeType eq $childname
508 ? $do->($tree) : $do->(undef);
509 defined $value ? ($childname => $value) : ();
510 };
511 }
512  
513 sub makeElementDefault
514 { my ($self, $path, $ns, $childname, $do, $default) = @_;
515  
516 my $mode = $self->{default_values};
517 $mode eq 'IGNORE'
518 and return sub
519 { my $tree = shift or return ();
520 return () if $tree->nodeType ne $childname
521 || $tree->node->textContent eq '';
522 $do->($tree);
523 };
524  
525 my $def = $do->($default);
526  
527 $mode eq 'EXTEND'
528 and return sub
529 { my $tree = shift;
530 return ($childname => $def)
531 if !defined $tree
532 || $tree->nodeType ne $childname
533 || $tree->node->textContent eq '';
534  
535 $do->($tree);
536 };
537  
538 $mode eq 'MINIMAL'
539 and return sub
540 { my $tree = shift or return ();
541 return () if $tree->nodeType ne $childname
542 || $tree->node->textContent eq '';
543 my $v = $do->($tree);
544 undef $v if defined $v && $v eq $def;
545 ($childname => $v);
546 };
547  
548 error __x"illegal default_values mode `{mode}'", mode => $mode;
549 }
550  
551 sub makeElementFixed
552 { my ($self, $path, $ns, $childname, $do, $fixed) = @_;
553 my ($tag, $fix) = $do->($fixed);
554  
555 sub { my $tree = shift;
556 my ($label, $value)
557 = $tree && $tree->nodeType eq $childname ? $do->($tree) : ();
558  
559 defined $value
560 or return ($tag => $fix);
561  
562 $value eq $fix
563 or error __x"element `{name}' must have fixed value `{fixed}', got `{value}' at {path}"
564 , name => $childname, fixed => $fix, value => $value
565 , path => $path;
566  
567 ($label => $value);
568 };
569 }
570  
571 sub makeElementAbstract
572 { my ($self, $path, $ns, $childname, $do, $tag) = @_;
573 sub { my $tree = shift or return ();
574 $tree->nodeType eq $childname or return ();
575  
576 error __x"abstract element `{name}' used at {path}"
577 , name => $childname, path => $path;
578 };
579 }
580  
581 #
582 # complexType and complexType/ComplexContent
583 #
584  
585 # Be warned that the location reported in 'path' may not be the actual
586 # location, caused by the cashing of compiled schema components. The
587 # path you see is the first path where that element was encountered.
588 sub _not_processed($$)
589 { my ($child, $path) = @_;
590 error __x"element `{name}' not processed for {path} at {where}"
591 , name => type_of_node($child), path => $path
592 , _class => 'misfit', where => $child->nodePath;
593 }
594  
595 sub makeComplexElement
596 { my ($self, $path, $tag, $elems, $attrs, $attrs_any,undef,$is_nillable) = @_;
597 #my @e = @$elems; my @a = @$attrs;
598  
599 my @elems = odd_elements @$elems;
600 my @attrs = (odd_elements(@$attrs), @$attrs_any);
601  
602 $is_nillable and return
603 sub { my $tree = shift or return ();
604 my $node = $tree->node;
605 my %complex =
606 ( ($tree->nodeNil ? (_ => 'NIL') : (map $_->($tree), @elems))
607 , (map $_->($node), @attrs)
608 );
609  
610 _not_processed $tree->currentChild, $path
611 if $tree->currentChild;
612  
613 ($tag => \%complex);
614 };
615  
616 @elems > 1 || @attrs and return
617 sub { my $tree = shift or return ();
618 my $node = $tree->node;
619 my %complex = ((map $_->($tree), @elems), (map $_->($node), @attrs));
620  
621 _not_processed $tree->currentChild, $path
622 if $tree->currentChild;
623  
624 ($tag => \%complex);
625 };
626  
627 @elems || return
628 sub { my $tree = shift or return ();
629 _not_processed $tree->currentChild, $path
630 if $tree->currentChild;
631  
632 ($tag => {});
633 };
634  
635 my $el = shift @elems;
636 sub { my $tree = shift or return ();
637 my %complex = $el->($tree);
638  
639 _not_processed $tree->currentChild, $path
640 if $tree->currentChild;
641  
642 ($tag => \%complex);
643 };
644 }
645  
646 #
647 # complexType/simpleContent
648 #
649  
650 sub makeTaggedElement
651 { my ($self, $path, $tag, $st, $attrs, $attrs_any,undef,$is_nillable) = @_;
652 my @attrs = (odd_elements(@$attrs), @$attrs_any);
653  
654 sub { my $tree = shift or return ();
655 my $simple = $is_nillable && ref $tree && $tree->nodeNil ? 'NIL' : $st->($tree);
656 ref $tree or return ($tag => {_ => $simple});
657 my $node = $tree->node;
658 my @pairs = map $_->($node), @attrs;
659 defined $simple || @pairs ? ($tag => {_ => $simple, @pairs}) : ();
660 };
661 }
662  
663 #
664 # complexType mixed or complexContent mixed
665 #
666  
667 sub makeMixedElement
668 { my ($self, $path, $tag, $elems, $attrs, $attrs_any,undef,$is_nillable) = @_;
669 my @attrs = (odd_elements(@$attrs), @$attrs_any);
670 my $mixed = $self->{mixed_elements}
671 or panic "how to handle mixed?";
672 $is_nillable and panic "nillable mixed not yet supported";
673  
674 ref $mixed eq 'CODE'
675 ? sub { my $tree = shift or return;
676 my $node = $tree->node or return;
677 my @v = $mixed->($path, $node);
678 @v ? ($tag => $v[0]) : ();
679 }
680  
681 : $mixed eq 'XML_NODE'
682 ? sub {$_[0] ? ($tag => $_[0]->node) : () }
683  
684 : $mixed eq 'ATTRIBUTES'
685 ? sub { my $tree = shift or return;
686 my $node = $tree->node;
687 my @pairs = map $_->($node), @attrs;
688 ($tag => { _ => $node, @pairs
689 , _MIXED_ELEMENT_MODE => 'ATTRIBUTES'});
690 }
691 : $mixed eq 'TEXTUAL'
692 ? sub { my $tree = shift or return;
693 my $node = $tree->node;
694 my @pairs = map $_->($node), @attrs;
695 ($tag => { _ => $node->textContent, @pairs
696 , _MIXED_ELEMENT_MODE => 'TEXTUAL'});
697 }
698 : $mixed eq 'XML_STRING'
699 ? sub { my $tree = shift or return;
700 my $node = $tree->node or return;
701 ($tag => $node->toString);
702 }
703 : $mixed eq 'STRUCTURAL'
704  
705 # this cannot be reached, because handled somewhere else
706 ? panic "mixed structural handled as normal element"
707  
708 : error __x"unknown mixed_elements value `{value}'", value => $mixed;
709 }
710  
711 #
712 # simpleType
713 #
714  
715 sub makeSimpleElement
716 { my ( $self, $path, $tag, $st, undef, undef, $comptype, $is_nillable) = @_;
717  
718 $is_nillable
719 ? sub { my $tree = shift or return $st->(undef);
720 my $value = (ref $tree && $tree->nodeNil) ? 'NIL' : $st->($tree);
721 defined $value ? ($tag => $value) : ();
722 }
723 : sub { my $value = $st->(@_);
724 defined $value ? ($tag => $value) : ();
725 };
726  
727 }
728  
729 sub default_anytype_handler($$)
730 { my ($path, $node) = @_;
731 ref $node or return $node;
732 (first{ UNIVERSAL::isa($_, 'XML::LibXML::Element') } $node->childNodes)
733 ? $node : $node->textContent;
734 }
735  
736 sub makeBuiltin
737 { my ($self, $path, $node, $type, $def, $check_values) = @_;
738  
739 if($type =~ m/}anyType$/)
740 {
741 if(my $a = $self->{any_type})
742 { return sub {
743 my $node
744 = ref $_[0] && UNIVERSAL::isa($_[0], 'XML::Compile::Iterator')
745 ? $_[0]->node : $_[0];
746 $a->( $path, $node, \&default_anytype_handler)};
747 }
748 else
749 { return sub
750 { ref $_[0] or return $_[0];
751 my $node = UNIVERSAL::isa($_[0], 'XML::Compile::Iterator')
752 ? $_[0]->node : $_[0];
753 (first{ UNIVERSAL::isa($_, 'XML::LibXML::Element') }
754 $node->childNodes) ? $node : $node->textContent;
755 };
756 }
757 }
758  
759 my $check = $check_values ? $def->{check} : undef;
760 my $parse = $def->{parse};
761 my $err = $path eq $type
762 ? N__"illegal value `{value}' for type {type}"
763 : N__"illegal value `{value}' for type {type} at {path}";
764  
765 $check
766 ? ( defined $parse
767 ? sub { my $value = ref $_[0] ? $_[0]->textContent : $_[0];
768 defined $value or return undef;
769 return $parse->($value, $_[1]||$_[0])
770 if $check->($value);
771 error __x$err, value => $value, type => $type, path => $path;
772 }
773 : sub { my $value = ref $_[0] ? $_[0]->textContent : $_[0];
774 defined $value or return undef;
775 return $value if $check->($value);
776 error __x$err, value => $value, type => $type, path => $path;
777 }
778 )
779  
780 : ( defined $parse
781 ? sub { my $value = ref $_[0] ? $_[0]->textContent : $_[0];
782 defined $value or return undef;
783 $parse->($value, $_[1]||$_[0]);
784 }
785 : sub { ref $_[0] ? shift->textContent : $_[0] }
786 );
787 }
788  
789 sub makeList
790 { my ($self, $path, $st) = @_;
791 sub { my $tree = shift;
792 defined $tree or return undef;
793 my $node
794 = UNIVERSAL::isa($tree, 'XML::LibXML::Node') ? $tree
795 : ref $tree ? $tree->node : undef;
796 my $v = ref $tree ? $tree->textContent : $tree;
797 my @v = grep defined, map $st->($_, $node), split " ", $v;
798 @v ? \@v : undef;
799 };
800 }
801  
802 sub makeFacetsList
803 { my ($self, $path, $st, $info, $early, $late) = @_;
804 my @e = grep defined, @$early;
805 my @l = grep defined, @$late;
806  
807 # enumeration and pattern are probably rare
808 @e or return sub {
809 my $values = $st->(@_) or return;
810 $_->($values) for @l;
811 $values;
812 };
813  
814 sub { defined $_[0] or return undef;
815 my $list = ref $_[0] ? $_[0]->textContent : $_[0];
816 $_->($list) for @e;
817 my $values = $st->($_[0]) or return;
818 $_->($values) for @l;
819 $values;
820 };
821 }
822  
823 sub makeFacets
824 { my ($self, $path, $st, $info, $early, $late) = @_;
825 @$early || @$late or return $st;
826  
827 unless(@$early)
828 { return sub {
829 my $v = $st->(shift);
830 defined $v or return undef;
831 $v = $_->($v) for @$late;
832 $v;
833 };
834 }
835  
836 sub {
837 my $v = shift;
838 if(@$early)
839 { return if !defined $v;
840 $v = $_->($v) for @$early;
841 }
842 $v = $st->($v);
843 defined $v or return undef;
844 $v = $_->($v) for @$late;
845 $v;
846 };
847 }
848  
849 sub makeUnion
850 { my ($self, $path, @types) = @_;
851 sub { my $tree = shift or return undef;
852 for(@types) { my $v = try { $_->($tree) }; $@ or return $v }
853 my $text = $tree->textContent;
854  
855 substr $text, 20, -5, '...' if length($text) > 50;
856 error __x"no match for `{text}' in union at {path}"
857 , text => $text, path => $path;
858 };
859 }
860  
861 # Attributes
862  
863 sub makeAttributeRequired
864 { my ($self, $path, $ns, $tag, $label, $do) = @_;
865 sub { my $node = $_[0]->getAttributeNodeNS($ns, $tag);
866 defined $node
867 or error __x"attribute `{name}' is required at {path}"
868 , name => $tag, path => $path;
869  
870 defined $node or return ();
871 my $value = $do->($node);
872 defined $value ? ($label => $value) : ();
873 };
874 }
875  
876 sub makeAttributeProhibited
877 { my ($self, $path, $ns, $tag, $label, $do) = @_;
878 sub { my $node = $_[0]->getAttributeNodeNS($ns, $tag);
879 defined $node or return ();
880 error __x"attribute `{name}' is prohibited at {path}"
881 , name => $tag, path => $path;
882 ();
883 };
884 }
885  
886 sub makeAttribute
887 { my ($self, $path, $ns, $tag, $label, $do) = @_;
888 sub { my $node = $_[0]->getAttributeNodeNS($ns, $tag);
889 defined $node or return ();
890 my $val = $do->($node);
891 defined $val ? ($label => $val) : ();
892 };
893 }
894  
895 sub makeAttributeDefault
896 { my ($self, $path, $ns, $tag, $label, $do, $default) = @_;
897  
898 my $mode = $self->{default_values};
899 $mode eq 'IGNORE'
900 and return sub
901 { my $node = $_[0]->getAttributeNodeNS($ns, $tag);
902 defined $node ? ($label => $do->($node)) : () };
903  
904 my $def = $do->($default);
905  
906 $mode eq 'EXTEND'
907 and return sub
908 { my $node = $_[0]->getAttributeNodeNS($ns, $tag);
909 ($label => ($node ? $do->($node) : $def))
910 };
911  
912 $mode eq 'MINIMAL'
913 and return sub
914 { my $node = $_[0]->getAttributeNodeNS($ns, $tag);
915 my $v = $node ? $do->($node) : $def;
916 !defined $v || $v eq $def ? () : ($label => $v);
917 };
918  
919 error __x"illegal default_values mode `{mode}'", mode => $mode;
920 }
921  
922 sub makeAttributeFixed
923 { my ($self, $path, $ns, $tag, $label, $do, $fixed) = @_;
924 my $def = $do->($fixed);
925  
926 sub { my $node = $_[0]->getAttributeNodeNS($ns, $tag)
927 or return ($label => $def);
928  
929 my $value = $do->($node);
930 defined $value && $value eq $def
931 or error __x"value of attribute `{tag}' is fixed to `{fixed}', not `{value}' at {path}"
932 , tag => $tag, fixed => $def, value => $value, path => $path;
933  
934 ($label => $def);
935 };
936 }
937  
938 # SubstitutionGroups
939  
940 sub makeSubstgroup
941 { my ($self, $path, $base, %do) = @_;
942 keys %do or return bless sub { () }, 'BLOCK';
943  
944 bless
945 sub { my $tree = shift;
946 my $type = ($tree ? $tree->currentType : undef)
947 or error __x"no data for substitution group {type} at {path}"
948 , type => $base, path => $path, class => 'misfit';
949  
950 my $do = $do{$type} or return ();
951 my @subst = $do->[1]($tree->descend);
952 @subst or return ();
953  
954 $tree->nextChild;
955 ($do->[0] => $subst[1]); # key-rewrite
956 }, 'BLOCK';
957 }
958  
959 # anyAttribute
960  
961 sub makeAnyAttribute
962 { my ($self, $path, $handler, $yes, $no, $process) = @_;
963 return () unless defined $handler;
964  
965 my %yes = map +($_ => 1), @{$yes || []};
966 my %no = map +($_ => 1), @{$no || []};
967  
968 # Takes all, before filtering
969 my $all =
970 sub { my @result;
971 foreach my $attr ($_[0]->attributes)
972 { $attr->isa('XML::LibXML::Attr') or next;
973 my $ns = $attr->namespaceURI || $_[0]->namespaceURI || '';
974 next if keys %yes && !$yes{$ns};
975 next if keys %no && $no{$ns};
976  
977 push @result, pack_type($ns, $attr->localName) => $attr;
978 }
979 @result;
980 };
981  
982 weaken $self;
983  
984 # Create filter if requested
985 my $run = $handler eq 'TAKE_ALL' ? $all
986 : ref $handler ne 'CODE'
987 ? error(__x"any_attribute handler `{got}' not understood", got => $handler)
988 : sub { my @attrs = $all->(@_);
989 my @result;
990 while(@attrs)
991 { my ($type, $data) = (shift @attrs, shift @attrs);
992 my ($label, $out) = $handler->($type, $data, $path, $self);
993 push @result, $label, $out if defined $label;
994 }
995 @result;
996 };
997  
998 bless $run, 'ANY';
999 }
1000  
1001 # anyElement
1002  
1003 sub makeAnyElement
1004 { my ($self, $path, $handler, $yes, $no, $process, $min, $max) = @_;
1005 $handler ||= 'SKIP_ALL';
1006  
1007 my %yes = map +($_ => 1), @{$yes || []};
1008 my %no = map +($_ => 1), @{$no || []};
1009  
1010 # Takes all, before filtering
1011 my $any = ($max eq 'unbounded' || $max > 1)
1012 ? sub
1013 { my $tree = shift or return ();
1014 my $count = 0;
1015 my %result;
1016 while( (my $child = $tree->currentChild)
1017 && ($max eq 'unbounded' || $count < $max))
1018 { my $ns = $child->namespaceURI || '';
1019 $yes{$ns} or last if keys %yes;
1020 $no{$ns} and last if keys %no;
1021  
1022 my $k = pack_type $ns, $child->localName;
1023 push @{$result{$k}}, $child;
1024 $count++;
1025 $tree->nextChild;
1026 }
1027  
1028 $count >= $min
1029 or error __x"too few any elements, requires {min} and got {found}"
1030 , min => $min, found => $count;
1031  
1032 %result;
1033 }
1034 : sub
1035 { my $tree = shift or return ();
1036 my $child = $tree->currentChild or return ();
1037 my $ns = $child->namespaceURI || '';
1038  
1039 (!keys %yes || $yes{$ns}) && !(keys %no && $no{$ns})
1040 or return ();
1041  
1042 $tree->nextChild;
1043 (type_of_node($child), $child);
1044 };
1045
1046 bless $any, 'ANY';
1047  
1048 # I would like to weaken here, but "ANY" needs the whole compiler structure
1049 # intact: someone has to catch it.
1050 # weaken $self;
1051  
1052 # Create filter if requested
1053 my $run
1054 = $handler eq 'TAKE_ALL' ? $any
1055 : $handler eq 'SKIP_ALL' ? sub { $any->(@_); () }
1056 : ref $handler ne 'CODE'
1057 ? error(__x"any_element handler `{got}' not understood", got => $handler)
1058 : sub { my @elems = $any->(@_);
1059 my @result;
1060 while(@elems)
1061 { my ($type, $data) = (shift @elems, shift @elems);
1062 my ($label, $out) = $handler->($type, $data, $path, $self);
1063 push @result, $label, $out if defined $label;
1064 }
1065 @result;
1066 };
1067  
1068 bless $run, 'ANY';
1069 }
1070  
1071 # xsi:type handling
1072  
1073 sub makeXsiTypeSwitch($$$$)
1074 { my ($self, $where, $elem, $default_type, $types) = @_;
1075  
1076 sub {
1077 my $tree = shift or return;
1078 my $node = $tree->node or return;
1079 my $type = $node->getAttributeNS(SCHEMA2001i, 'type');
1080 my ($alt, $code);
1081 if($type)
1082 { my ($pre, $local) = $type =~ /(.*?)\:(.*)/ ? ($1, $2) : ('',$type);
1083 $alt = pack_type $node->lookupNamespaceURI($pre), $local;
1084 $code = $types->{$alt}
1085 or error __x"specified xsi:type list for `{default}' does not contain `{got}'"
1086 , default => $default_type, got => $type;
1087 }
1088 else
1089 { ($alt, $code) = ($default_type, $types->{$default_type});
1090 }
1091  
1092 my ($t, $d) = $code->($tree);
1093 defined $t or return ();
1094  
1095 $d = { _ => $d } if ref $d ne 'HASH';
1096 $d->{XSI_TYPE} ||= $alt;
1097 ($t, $d);
1098 };
1099 }
1100  
1101 # any kind of hook
1102  
1103 sub makeHook($$$$$$$)
1104 { my ($self, $path, $r, $tag, $before, $replace, $after, $fulltype) = @_;
1105 return $r unless $before || $replace || $after;
1106  
1107 return sub { ($_[0]->node->localName => 'SKIPPED') }
1108 if $replace && grep $_ eq 'SKIP', @$replace;
1109  
1110 my @replace = $replace ? map $self->_decodeReplace($path,$_),@$replace : ();
1111 my @before = $before ? map $self->_decodeBefore($path,$_), @$before : ();
1112 my @after = $after ? map $self->_decodeAfter($path,$_), @$after : ();
1113  
1114 weaken $self;
1115  
1116 sub
1117 { my $tree = shift or return ();
1118 my $xml = $tree->node;
1119 foreach (@before)
1120 { $xml = $_->($xml, $path, $fulltype);
1121 defined $xml or return ();
1122 }
1123  
1124 my $process = sub { $r->($tree->descend($xml)) };
1125 my @h = @replace
1126 ? map $_->($xml, $self, $path, $tag, $process, $fulltype), @replace
1127 : $process->();
1128  
1129 @h or return ();
1130 my $h = @h==1 ? $h[0] : $h[1]; # detect simpleType
1131 foreach my $after (@after)
1132 { $h = $after->($xml, $h, $path, $fulltype);
1133 defined $h or return ();
1134 }
1135 ($tag => $h);
1136 };
1137 }
1138  
1139 sub _decodeBefore($$)
1140 { my ($self, $path, $call) = @_;
1141 return $call if ref $call eq 'CODE';
1142  
1143 $call eq 'PRINT_PATH' ? sub {print "$_[1]\n"; $_[0] }
1144 : error __x"labeled before hook `{call}' undefined for READER", call=>$call;
1145 }
1146  
1147 sub _decodeReplace($$)
1148 { my ($self, $path, $call) = @_;
1149 return $call if ref $call eq 'CODE';
1150  
1151 $call eq 'XML_NODE' ? sub { ($_[3] => $_[0]) } # don't parse XML
1152 : error __x"labeled replace hook `{call}' undefined for READER",call=>$call;
1153 }
1154  
1155 my %after =
1156 ( PRINT_PATH => sub {print "$_[2]\n"; $_[1] }
1157 , INCLUDE_PATH => sub { my $h = $_[1];
1158 $h = { _ => $h } if ref $h ne 'HASH';
1159 $h->{_PATH} = $_[0];
1160 $h;
1161 }
1162 , XML_NODE => sub { my $h = $_[1];
1163 $h = { _ => $h } if ref $h ne 'HASH';
1164 $h->{_XML_NODE} = $_[0];
1165 $h;
1166 }
1167 , ELEMENT_ORDER => sub { my ($xml, $h) = @_;
1168 $h = { _ => $h } if ref $h ne 'HASH';
1169 my @order = map type_of_node($_)
1170 , grep $_->isa('XML::LibXML::Element'), $xml->childNodes;
1171 $h->{_ELEMENT_ORDER} = \@order;
1172 $h;
1173 }
1174 , ATTRIBUTE_ORDER => sub { my ($xml, $h) = @_;
1175 $h = { _ => $h } if ref $h ne 'HASH';
1176 my @order = map $_->nodeName, $xml->attributes;
1177 $h->{_ATTRIBUTE_ORDER} = \@order;
1178 $h;
1179 }
1180 , NODE_TYPE => sub { my ($xml, $h) = @_;
1181 $h = { _ => $h } if ref $h ne 'HASH';
1182 $h->{_NODE_TYPE} = type_of_node $xml;
1183 $h;
1184 }
1185 );
1186  
1187 sub _decodeAfter($$)
1188 { my ($self, $path, $call) = @_;
1189 return $call if ref $call eq 'CODE';
1190  
1191 # The 'after' can be called on a single. In that case, turn it into
1192 # a HASH for additional information.
1193 my $dec = $after{$call}
1194 or error __x"labeled after hook `{call}' undefined for READER"
1195 , call=> $call;
1196  
1197 $dec;
1198 }
1199  
1200 sub makeBlocked($$$)
1201 { my ($self, $where, $class, $type) = @_;
1202 my $err_type = $self->prefixed($type) || $type;
1203  
1204 # errors are produced in class=misfit to allow other choices to succeed.
1205 $class eq 'anyType'
1206 ? { st => sub { error __x"use of `{type}' blocked at {where}"
1207 , type => $err_type, where => $where, _class => 'misfit';
1208 }}
1209 : $class eq 'simpleType'
1210 ? { st => sub { error __x"use of {class} `{type}' blocked at {where}"
1211 , class => $class, type => $err_type, where => $where
1212 , _class => 'misfit';
1213 }}
1214 : $class eq 'complexType'
1215 ? { elems => [] }
1216 : $class eq 'ref'
1217 ? { st => sub { error __x"use of referenced `{type}' blocked at {where}"
1218 , type => $err_type, where => $where, _class => 'misfit';
1219 }}
1220 : panic "blocking of $class for $type not implemented";
1221 }
1222  
1223 #-----------------------------------
1224  
1225  
1226 1;