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

filter: Statementstmt 0.0% 0 / 513 Branchbran 0.0% 0 / 256 Conditioncond 0.0% 0 / 243 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 58 Podpod 0.0% 0 / 49 totaltotal 0.0% 0 / 1119 CC 129 SCAR 55.4
CC
129
Cov
0%
_perlAny
1056.0
_xmlAny
342.0
makeFacets
272.0
CRAP 255.5
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::Template;
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 XML::Compile::Util
22 qw/odd_elements even_elements SCHEMA2001i pack_type unpack_type/;
23 use List::Util qw/max first/;
24  
25 use vars '$VERSION'; # OODoc adds $VERSION to the script
26 $VERSION ||= 'undef';
27  
28  
29 sub makeTagQualified
30 { my ($self, $path, $node, $local, $ns) = @_;
31 my $prefix = $self->_registerNSprefix('', $ns, 1);
32  
33 # it is certainly not correct to do a keyRewrite here, but it works :(
34 $self->{_output} eq 'PERL' ? $self->keyRewrite($ns, $local)
35 : length $prefix ? "$prefix:$local"
36 : $local;
37 }
38  
39 sub makeTagUnqualified
40 { my ($self, $path, $node, $local, $ns) = @_;
41 # $name =~ s/.*\://;
42 return $self->keyRewrite($ns, $local)
43 if $self->{_output} eq 'PERL';
44  
45 my $prefix = $self->_registerNSprefix('', $ns, 1);
46 length $prefix ? "$prefix:$local" : $local;
47 }
48  
49 # Detect recursion. Based on type is best, but some schema's do not
50 # have named types, so tags are indexed as well.
51 my (%recurse_type, %reuse_type, %recurse_tag, %reuse_tag);
52  
53 sub compile($@)
54 { my ($self, $type, %args) = @_;
55 $self->{_output} = $args{output};
56 (%recurse_type, %reuse_type, %recurse_tag, %reuse_tag) = ();
57 $self->SUPER::compile($type, %args);
58 }
59  
60 sub actsAs($)
61 { my ($self, $as) = @_;
62 ($as eq 'READER' && $self->{_output} eq 'PERL')
63 || ($as eq 'WRITER' && $self->{_output} eq 'XML')
64 }
65  
66 sub makeWrapperNs($$$$$)
67 { my ($self, $path, $processor, $index, $filter) = @_;
68  
69 my @entries;
70 $filter = sub {1} if ref $filter ne 'CODE';
71  
72 foreach my $entry (sort {$a->{prefix} cmp $b->{prefix}} values %$index)
73 { $entry->{used} or next;
74 my ($prefix, $uri) = @{$entry}{'prefix', 'uri'};
75 $filter->($uri, $prefix) or next;
76 push @entries, [ $uri, $prefix ];
77 $entry->{used} = 0;
78 }
79  
80 sub { my $data = $processor->(@_) or return ();
81 if($self->{include_namespaces})
82 { $data->{"xmlns:$_->[1]"} = $_->[0] for @entries;
83 }
84 $data;
85 };
86 }
87  
88 sub typemapToHooks($$)
89 { my ($self, $hooks, $typemap) = @_;
90  
91 while(my($type, $action) = each %$typemap)
92 { defined $action or next;
93  
94 my ($struct, $example)
95 = $action =~ s/^[\\]?\&/\$/
96 ? ( "call on converter function with object"
97 , "$action->('WRITER', \$object, '$type', \$doc)")
98 : $action =~ m/^\$/
99 ? ( "call on converter with object"
100 , "$action->toXML(\$object, '$type', \$doc)")
101 : ( [ "calls toXML() on $action objects", " with $type and doc" ]
102 , "bless({}, '$action')" );
103  
104 my $details =
105 { struct => $struct
106 , example => $example
107 };
108  
109 push @$hooks, { type => $type, replace => sub { $details} };
110 }
111  
112 $hooks;
113 }
114  
115 sub makeElementWrapper
116 { my ($self, $path, $processor) = @_;
117 sub { $processor->() };
118 }
119 *makeAttributeWrapper = \&makeElementWrapper;
120  
121 sub _block($@)
122 { my ($self, $block, $path, @pairs) = @_;
123 bless
124 sub { my @elems = map { $_->() } odd_elements @pairs;
125 my @tags = map { $_->{tag} } @elems;
126  
127 local $" = ', ';
128 my $struct = @tags ? "$block of @tags"
129 : "empty $block from ".join(" ", even_elements @pairs);
130  
131 my @lines;
132 while(length $struct > 65)
133 { $struct =~ s/(.{1,60}|\S+)(?:\s+|$)//;
134 push @lines, $1;
135 }
136 push @lines, $struct
137 if length $struct;
138 $lines[$_] =~ s/^/ / for 1..$#lines;
139  
140 { tag => $block
141 , elems => \@elems
142 , struct => \@lines
143 };
144 }, 'BLOCK';
145 }
146  
147 sub makeSequence { my $self = shift; $self->_block(sequence => @_) }
148 sub makeChoice { my $self = shift; $self->_block(choice => @_) }
149 sub makeAll { my $self = shift; $self->_block(all => @_) }
150  
151 sub makeBlockHandler
152 { my ($self, $path, $label, $min, $max, $proc, $kind, $multi) = @_;
153  
154 my $code =
155 sub { my $data = $proc->();
156 my $occur
157 = $max eq 'unbounded' && $min==0 ? 'occurs any number of times'
158 : $max ne 'unbounded' && $max==1 && $min==0 ? 'is optional'
159 : $max ne 'unbounded' && $max==1 && $min==1 ? '' # the usual case
160 : "occurs $min <= # <= $max times";
161  
162 $data->{occur} ||= $occur if $occur;
163 if($max ne 'unbounded' && $max==1)
164 { bless $data, 'BLOCK';
165 }
166 else
167 { $data->{tag} = $multi;
168 $data->{is_array} = 1;
169 bless $data, 'REP-BLOCK';
170 }
171 $data;
172 };
173 ($label => $code);
174 }
175  
176 sub makeElementHandler
177 { my ($self, $path, $label, $min, $max, $req, $opt) = @_;
178 sub { my $data = $opt->() or return;
179 my $occur
180 = $max eq 'unbounded' && $min==0 ? 'occurs any number of times'
181 : $max ne 'unbounded' && $max==1 && $min==0 ? 'is optional'
182 : $max ne 'unbounded' && $max==1 && $min==1 ? '' # the usual case
183 : "occurs $min <= # <= $max times";
184 $data->{occur} ||= $occur if $occur;
185 $data->{is_array} = $max eq 'unbounded' || $max > 1;
186 $data;
187 };
188 }
189  
190 sub makeRequired
191 { my ($self, $path, $label, $do) = @_;
192 $do;
193 }
194  
195 sub makeElementHref
196 { my ($self, $path, $ns, $childname, $do) = @_;
197 $do;
198 }
199  
200 sub makeElement
201 { my ($self, $path, $ns, $childname, $do) = @_;
202 sub { my $h = $do->(@_);
203 $h->{_NAME} = $childname;
204 $h;
205 };
206 }
207  
208 sub makeElementDefault
209 { my ($self, $path, $ns, $childname, $do, $default) = @_;
210 sub { my $h = $do->(@_);
211 $h->{occur} = "defaults to '$default'";
212 $h->{example} = $default;
213 $h;
214 };
215 }
216  
217 sub makeElementFixed
218 { my ($self, $path, $ns, $childname, $do, $fixed) = @_;
219 sub { my $h = $do->(@_);
220 $h->{occur} = "fixed to '$fixed'";
221 $h->{example} = $fixed;
222 $h;
223 };
224 }
225  
226 sub makeElementAbstract
227 { my ($self, $path, $ns, $childname, $do) = @_;
228 # sub { () };
229 sub {
230 my $h = $do->(@_);
231 $h->{_NAME} = $childname;
232 $h->{occur} = "ABSTRACT";
233 $h;
234 };
235 }
236  
237 sub makeComplexElement
238 { my ($self, $path, $tag, $elems, $attrs, $any_attr, $type, $is_nillable)=@_;
239 my @elem_parts = odd_elements @$elems;
240 my @attr_parts = (odd_elements(@$attrs), @$any_attr);
241  
242 sub { my (@attrs, @elems);
243 my $is_pseudo_type = $type !~ m/^{/; # like "unnamed complex"
244  
245 if((!$is_pseudo_type && $recurse_type{$type}) || $recurse_tag{$tag})
246 { return
247 +{ kind => 'complex'
248 , struct => 'probably a recursive complex'
249 , tag => $tag
250 , _TYPE => $type
251 };
252 }
253  
254 if((!$is_pseudo_type && $reuse_type{$type}) || $reuse_tag{$tag})
255 { return
256 +{ kind => 'complex'
257 , struct => 'complex structure shown above'
258 , tag => $tag
259 , _TYPE => $type
260 };
261 }
262  
263 $recurse_type{$type}++; $recurse_tag{$tag}++;
264 $reuse_type{$type}++; $reuse_tag{$tag}++;
265 push @elems, $_->() for @elem_parts;
266 push @attrs, $_->() for @attr_parts;
267  
268 $recurse_type{$type}--; $recurse_tag{$tag}--;
269  
270 +{ kind => 'complex'
271 , struct => ($is_nillable ? "is nillable, as: $tag => NIL" : undef)
272 , tag => $tag
273 , attrs => \@attrs
274 , elems => \@elems
275 , _TYPE => $type
276 };
277 };
278 }
279  
280 sub makeTaggedElement
281 { my ($self, $path, $tag, $st, $attrs, $attrs_any, $type, $is_nillable) = @_;
282 my @parts = (odd_elements(@$attrs), @$attrs_any);
283  
284 sub { my @attrs = map $_->(), @parts;
285 my %simple = $st->();
286  
287 my @struct = 'string content of the container';
288 push @struct, $simple{struct} if $simple{struct};
289 push @struct, 'is nillable, hence value or NIL' if $is_nillable;
290  
291 my %content =
292 ( tag => '_'
293 , struct => \@struct
294 , example => ($simple{example} || 'Hello, World!')
295 );
296 $content{_TYPE} = $simple{_TYPE} if $simple{_TYPE};
297  
298 +{ kind => 'tagged'
299 , struct => "$tag is simple value with attributes"
300 , tag => $tag
301 , attrs => \@attrs
302 , elems => [ \%content ]
303 , _TYPE => $type
304 };
305 };
306 }
307  
308 sub makeMixedElement
309 { my ($self, $path, $tag, $elems, $attrs, $attrs_any, $type, $is_nillable)=@_;
310 my @parts = (odd_elements(@$attrs), @$attrs_any);
311  
312 my @struct = 'mixed content cannot be processed automatically';
313 push @struct, 'is nillable' if $is_nillable;
314  
315 my %mixed =
316 ( tag => '_'
317 , struct => \@struct
318 , example => "XML::LibXML::Element->new('$tag')"
319 );
320  
321 unless(@parts) # show simpler alternative
322 { $mixed{tag} = $tag;
323 $mixed{type} = $type;
324 return sub { \%mixed };
325 }
326  
327 sub { my @attrs = map $_->(), @parts;
328 +{ kind => 'mixed'
329 , struct => "$tag has a mixed content"
330 , tag => $tag
331 , elems => [ \%mixed ]
332 , attrs => \@attrs
333 , _TYPE => $type
334 };
335 };
336 }
337  
338 sub makeSimpleElement
339 { my ($self, $path, $tag, $st, undef, undef, $type, $is_nillable) = @_;
340 sub { my @struct;
341 push @struct, 'is nillable, hence value or NIL' if $is_nillable;
342 +{ kind => 'simple'
343 , struct => \@struct
344 , tag => $tag
345 , $st->()
346 };
347 };
348 }
349  
350 sub makeBuiltin
351 { my ($self, $path, $node, $type, $def, $check_values) = @_;
352 sub { (_TYPE=> $type, example => $def->{example}) };
353 }
354  
355 sub makeList
356 { my ($self, $path, $st) = @_;
357 sub { my %d = $st->();
358 $d{struct} = 'a list of values, where each';
359 my $example = $d{example};
360 if($self->{_output} eq 'PERL')
361 { $example = qq("$example") if $example =~ m/[^0-9.]/;
362 $d{example} = "[ $example , ... ]";
363 }
364 else
365 { $d{example} = "$example $example ...";
366 }
367 %d };
368 }
369  
370 sub makeFacetsList
371 { my ($self, $path, $st, $info) = @_;
372 $self->makeFacets($path, $st, $info);
373 }
374  
375 sub _ff($@)
376 { my ($self,$type) = (shift, shift);
377 my @lines = $type.':';
378 while(@_)
379 { my $facet = shift;
380 $facet =~ s/\t/\t/g;
381 $facet = qq{"$facet"} if $facet =~ m/\s/;
382 push @lines, ' ' if length($lines[-1]) + length($facet) > 55;
383 $lines[-1] .= ' '.$facet;
384 }
385 @lines;
386 }
387  
388 sub makeFacets
389 { my ($self, $path, $st, $info) = @_;
390 my @comment;
391 foreach my $k (sort keys %$info)
392 { my $v = $info->{$k};
393 push @comment
394 , $k eq 'enumeration' ? $self->_ff('Enum', sort @$v)
395 : $k eq 'pattern' ? $self->_ff('Pattern', @$v)
396 : $k eq 'length' ? "fixed length of $v"
397 : $k eq 'maxLength' ? "length <= $v"
398 : $k eq 'minLength' ? "length >= $v"
399 : $k eq 'totalDigits' ? "total digits is $v"
400 : $k eq 'maxScale' ? "scale <= $v"
401 : $k eq 'minScale' ? "scale >= $v"
402 : $k eq 'maxInclusive' ? "value <= $v"
403 : $k eq 'maxExclusive' ? "value < $v"
404 : $k eq 'minInclusive' ? "value >= $v"
405 : $k eq 'minExclusive' ? "value > $v"
406 : $k eq 'fractionDigits' ? "faction digits is $v"
407 : $k eq 'whiteSpace' ? "white-space $v"
408 : "restriction? $k = $v";
409 }
410  
411 my %facet = (facets => \@comment, $st->());
412  
413 if(my $enum = $info->{enumeration})
414 { $facet{example} = $enum->[0];
415 }
416  
417 sub { %facet };
418 }
419  
420 sub makeUnion
421 { my ($self, $path, @types) = @_;
422 sub { my @choices = map { +{$_->()} } @types;
423 +( kind => 'union'
424 , struct => "one of the following (union)"
425 , choice => \@choices
426 , example => $choices[0]->{example}
427 );
428 };
429 }
430  
431 sub makeAttributeRequired
432 { my ($self, $path, $ns, $tag, $label, $do) = @_;
433  
434 sub { +{ kind => 'attr'
435 , tag => $label
436 , occur => "attribute $tag is required"
437 , $do->()
438 };
439 };
440 }
441  
442 sub makeAttributeProhibited
443 { my ($self, $path, $ns, $tag, $label, $do) = @_;
444 ();
445 }
446  
447 sub makeAttribute
448 { my ($self, $path, $ns, $tag, $label, $do) = @_;
449 sub { +{ kind => 'attr'
450 , tag => $tag
451 , occur => "becomes an attribute"
452 , $do->()
453 };
454 };
455 }
456  
457 sub makeAttributeDefault
458 { my ($self, $path, $ns, $tag, $label, $do) = @_;
459 sub {
460 +{ kind => 'attr'
461 , tag => $tag
462 , occur => "attribute $tag has default"
463 , $do->()
464 };
465 };
466 }
467  
468 sub makeAttributeFixed
469 { my ($self, $path, $ns, $tag, $label, $do, $fixed) = @_;
470 my $value = $fixed->value;
471  
472 sub { +{ kind => 'attr'
473 , tag => $tag
474 , occur => "attribute $tag is fixed"
475 , example => $value
476 };
477 };
478 }
479  
480 sub makeSubstgroup
481 { my ($self, $path, $type, @todo) = @_;
482  
483 sub {
484 my (@example_tags, $example_nest, %tags);
485 my @do = @todo;
486 my $group = $do[1][0];
487  
488 while(@do)
489 { my ($type, $info) = (shift @do, shift @do);
490 my ($label, $call) = @$info;
491 my $processed = $call->();
492 my $show = '';
493 if($processed->{kind} eq 'substitution group')
494 { # substr extended by subst, which already is formatted.
495 # need to extract only the indicated type info.
496 my $s = $processed->{struct} || [];
497 /^ $label (.*)/ and $show = $1 for @$s;
498 }
499 elsif(my $type = $processed->{_TYPE})
500 { $show = $self->prefixed($type);
501 }
502  
503 if($processed->{occur} && $processed->{occur} eq 'ABSTRACT')
504 { $show .= ' (abstract)';
505 }
506 else
507 { # some complication to always produce the same tag for
508 # regression tests... Instance uses a HASH...
509 push @example_tags, $label;
510 $example_nest ||= $processed->{kind} eq 'simple'
511 ? ($processed->{example} || '...') : '{...}';
512 }
513
514 $tags{$label} = $show;
515 }
516  
517 my $longest = max map length, keys %tags;
518 my @lines = map sprintf(" %-${longest}s %s", $_, $tags{$_}),
519 sort keys %tags;
520  
521 my $example_tag = (sort @example_tags)[0];
522 my $example = $example_tag ? "{ $example_tag => $example_nest }"
523 : "undef # only abstract types known";
524  
525 my $name = $self->prefixed($type);
526  
527 +{ kind => 'substitution group'
528 , tag => $group
529 , struct => [ "substitutionGroup $name", @lines ]
530 , example => $example
531 };
532 };
533 }
534  
535 sub makeXsiTypeSwitch($$$$)
536 { my ($self, $where, $elem, $default_type, $types) = @_;
537 my @types = map " ".$self->prefixed($_), sort keys %$types;
538 my $deftype = $self->prefixed($default_type);
539  
540 sub { +{ kind => 'xsi:type switch'
541 , tag => $elem
542 , struct => [ 'xsi:type alternatives:', @types ]
543 , example => "{ XSI_TYPE => '$deftype', %data }"
544 }
545 };
546 }
547  
548 sub makeAnyAttribute
549 { my ($self, $path, $handler, $yes, $no, $process) = @_;
550 $yes ||= []; $no ||= [];
551 $yes = [ map {$self->prefixed("{$_}") || $_} @$yes];
552 $no = [ map {$self->prefixed("{$_}") || $_} @$no];
553 my $occurs = @$yes ? "in @$yes" : @$no ? "not in @$no" : 'in any namespace';
554 bless sub { +{kind => 'attr' , struct => "any attribute $occurs"
555 , tag => 'ANYATTR', example => 'AnySimple'} }, 'ANY';
556 }
557  
558 sub makeAnyElement
559 { my ($self, $path, $handler, $yes, $no, $process, $min, $max) = @_;
560 $yes ||= []; $no ||= [];
561 $yes = [ map {$self->prefixed("{$_}") || $_} @$yes];
562 $no = [ map {$self->prefixed("{$_}") || $_} @$no];
563 my $where = @$yes ? "in @$yes" : @$no ? "not in @$no" : 'in any namespace';
564  
565 my $data = +{ kind => 'element', struct => "any element $where"
566 , tag => "ANY", example => 'Anything' };
567 my $occur
568 = $max eq 'unbounded' && $min==0 ? 'occurs any number of times'
569 : $max ne 'unbounded' && $max==1 && $min==0 ? 'is optional'
570 : $max ne 'unbounded' && $max==1 && $min==1 ? '' # the usual case
571 : "occurs $min <= # <= $max times";
572 $data->{occur} ||= $occur if $occur;
573 $data->{is_array} = $max eq 'unbounded' || $max > 1;
574  
575 bless sub { +$data }, 'ANY';
576 }
577  
578 sub makeHook($$$$$$$)
579 { my ($self, $path, $r, $tag, $before, $replace, $after, $fulltype) = @_;
580  
581 return $r unless $before || $replace || $after;
582  
583 error __x"template only supports one production (replace) hook"
584 if $replace && @$replace > 1;
585  
586 return sub {()} if $replace && grep {$_ eq 'SKIP'} @$replace;
587  
588 my @replace = $replace ? map {$self->_decodeReplace($path,$_)} @$replace:();
589 my @before = $before ? map {$self->_decodeBefore($path,$_) } @$before :();
590 my @after = $after ? map {$self->_decodeAfter($path,$_) } @$after :();
591  
592 sub
593 { my $doc = XML::LibXML::Document->new;
594 for(@before) { $_->($doc, $path, undef) or return }
595  
596 my $xml = @replace ? $replace[0]->($doc, $path, $r) : $r->();
597 defined $xml or return ();
598  
599 for(@after) { $xml = $_->($doc, $path, $xml) or return }
600 $xml;
601 }
602 }
603  
604 sub _decodeBefore($$)
605 { my ($self, $path, $call) = @_;
606 return $call if ref $call eq 'CODE';
607 error __x"labeled before hook `{name}' undefined", name => $call;
608 }
609  
610 sub _decodeReplace($$)
611 { my ($self, $path, $call) = @_;
612 return $call if ref $call eq 'CODE';
613  
614 if($call eq 'COLLAPSE')
615 { return sub
616 { my ($tag, $path, $do) = @_;
617 my $h = $do->();
618 $h->{elems} = [ { struct => [ 'content collapsed' ]
619 , kind => 'collapsed' } ];
620 delete $h->{attrs};
621 $h;
622 };
623 }
624  
625 # SKIP already handled
626 error __x"labeled replace hook `{name}' undefined", name => $call;
627 }
628  
629 sub _decodeAfter($$)
630 { my ($self, $path, $call) = @_;
631 return $call if ref $call eq 'CODE';
632 error __x"labeled after hook `{name}' undefined", name => $call;
633 }
634  
635  
636 ###
637 ### toPerl
638 ###
639  
640 sub toPerl($%)
641 { my ($self, $ast, %args) = @_;
642 $ast or return undef;
643  
644 my @lines;
645 if($ast->{kind})
646 { my $name = $ast->{_NAME} || $ast->{tag};
647 my $pref = $self->prefixed($name);
648 push @lines, defined $pref
649 ? ("# Describing $ast->{kind} $pref", "# $name")
650 : "# Describing $ast->{kind} $name";
651 }
652  
653 push @lines
654 , "#"
655 , "# Produced by ".__PACKAGE__." version $VERSION"
656 , "# on ".localtime()
657 , "#"
658 , "# BE WARNED: in most cases, the example below cannot be used without"
659 , "# interpretation. The comments will guide you."
660 , "#"
661 unless $args{skip_header};
662  
663 # add info about name-spaces
664 foreach my $nsdecl (grep /^xmlns\:/, sort keys %$ast)
665 { push @lines, sprintf "# %-15s %s", $nsdecl, $ast->{$nsdecl} || '(none)';
666 }
667 push @lines, '' if @lines;
668
669 # produce data tree
670 push @lines, $self->_perlAny($ast, \%args);
671  
672 # remove leading 'type =>'
673 for(my $linenr = 0; $linenr < @lines; $linenr++)
674 { next if $lines[$linenr] =~ m/^\s*\#/;
675 next unless $lines[$linenr] =~ s/.*? \=\>\s*//;
676 $lines[$linenr] =~ m/\S/ or splice @lines, $linenr, 1;
677 last;
678 }
679  
680 my $lines = join "\n", @lines;
681 $lines =~ s/\,?\s*$/\n/;
682 $lines;
683 }
684  
685 my %seen;
686 sub _perlAny($$);
687 sub _perlAny($$)
688 { my ($self, $ast, $args) = @_;
689  
690 my @lines;
691 if($ast->{_TYPE} && $args->{show_type})
692 { my $pref = $self->prefixed($ast->{_TYPE});
693 if($pref)
694 { push @lines # not perfect, but a good attempt
695 , $pref =~ m/^[aiou]/i && $pref !~ m/^(uni|eu)/i
696 ? "# is an $pref" : "# is a $pref";
697 }
698 }
699  
700 if($ast->{struct} && $args->{show_struct})
701 { my $struct = $ast->{struct};
702 my @struct = ref $struct ? @$struct : $struct;
703 s/^/# /gm for @struct;
704 push @lines, @struct;
705 }
706  
707 push @lines, "# $ast->{occur}"
708 if $ast->{occur} && $args->{show_occur};
709  
710 if($ast->{facets} && $args->{show_facets})
711 { my $facets = $ast->{facets};
712 my @facets = ref $facets ? @$facets : $facets;
713 s/^/# /gm for @facets;
714 push @lines, @facets;
715 }
716  
717 my @childs;
718 push @childs, @{$ast->{attrs}} if $ast->{attrs};
719 push @childs, @{$ast->{elems}} if $ast->{elems};
720 push @childs, $ast->{body} if $ast->{body};
721  
722 my @subs;
723 foreach my $child (@childs)
724 { my @sub = $self->_perlAny($child, $args);
725 @sub or next;
726  
727 # last line is code and gets comma
728 $sub[-1] =~ s/\,?\s*$/,/
729 if $sub[-1] !~ m/\#\s/;
730  
731 if(ref $ast ne 'BLOCK')
732 { s/^(.)/$args->{indent}$1/ for @sub;
733 }
734  
735 # seperator blank, sometimes
736 unshift @sub, ''
737 if $sub[0] =~ m/^\s*[#{]/ # }
738 || (@subs && $subs[-1] =~ m/[}\]]\,\s*$/);
739  
740 push @subs, @sub;
741 }
742  
743 if(ref $ast eq 'REP-BLOCK')
744 { # repeated block
745 @subs or @subs = '';
746 $subs[0] =~ s/^ /{ / or $subs[0] =~ s/^\s*$/{/;
747 if($subs[-1] =~ m/\#\s/) { push @subs, "}," }
748 else { $subs[-1] =~ s/$/ },/ }
749 }
750  
751 # XML does not permit difficult tags, but we still check.
752 my $tag = $ast->{tag} || '';
753 if(defined $tag && $tag !~ m/^[\w_][\w\d_]*$/)
754 { $tag =~ s/\\/\\\\/g;
755 $tag =~ s/'/\\'/g;
756 $tag = qq{'$tag'};
757 }
758  
759 my $kind = $ast->{kind} || '';
760 if(ref $ast eq 'REP-BLOCK')
761 { s/^(.)/ $1/ for @subs;
762 $subs[0] =~ s/^ ?/[/;
763 push @lines, "$tag => ", @subs , ']';
764 }
765 elsif(ref $ast eq 'BLOCK')
766 { push @lines, @subs;
767 }
768 elsif(@subs)
769 { length $subs[0] or shift @subs;
770 if($ast->{is_array})
771 { s/^(.)/ $1/ for @subs;
772 $subs[0] =~ s/^[ ]{0,3}/[ {/;
773 if($subs[-1] =~ m/\#\s/) { push @subs, "}, ], " }
774 else {$subs[-1] .= ' }, ], ' }
775 push @lines, "$tag =>", @subs;
776 }
777 else
778 { $subs[0] =~ s/^ /{ /;
779 if($subs[-1] =~ m/\#\s/) { push @subs, "}, " }
780 else {$subs[-1] .= ' },' }
781 push @lines, "$tag =>", @subs;
782 }
783 }
784 elsif($kind eq 'complex' || $kind eq 'mixed') # empty complex-type
785 { # if there is an "occurs", then there can always be more than one
786 push @lines, $tag.' => '.($ast->{occur} ? '[{},]' : '{}');
787 }
788 elsif($kind eq 'collapsed') {;}
789 elsif($kind eq 'union') # union type
790 { foreach my $union ( @{$ast->{choice}} )
791 { # remove examples
792 my @l = grep { m/^#/ } $self->_perlAny($union, $args);
793 s/^\#/# -/ for $l[0];
794 s/^\#/# / for @l[1..$#l];
795 push @lines, @l;
796 }
797 }
798 elsif(!exists $ast->{example})
799 { push @lines, "$tag => 'TEMPLATE-ERROR $ast->{kind}'";
800 }
801  
802 my $example = $ast->{example};
803 if(defined $example)
804 { $example = qq{"$example"} # in quotes unless
805 if $example !~ m/^[+-]?\d+(?:\.\d+)?$/ # numeric or
806 && $example !~ m/^\$/ # variable or
807 && $example !~ m/^bless\b/ # constructor or
808 && $example !~ m/^\$?[\w:]*\-\>/ # method call example
809 && $example !~ m/^\{.*\}$/ # anon HASH example
810 && $example !~ m/^\[.*\]$/; # anon ARRAY example
811  
812 push @lines, "$tag => "
813 . ($ast->{is_array} ? "[ $example, ]" : $example);
814 }
815 @lines;
816 }
817  
818 ###
819 ### toXML
820 ###
821  
822 sub toXML($$%)
823 { my ($self, $doc, $ast, %args) = @_;
824 my $xml = $self->_xmlAny($doc, $ast, "\n$args{indent}", \%args);
825  
826 UNIVERSAL::isa($xml, 'XML::LibXML::Element')
827 or return $xml;
828  
829 # add comment
830 my $pkg = __PACKAGE__;
831 my $now = localtime();
832  
833 my $header = $doc->createComment( <<_HEADER . ' ' );
834  
835 BE WARNED: in most cases, the example below cannot be used without
836 interpretation. The comments will guide you.
837 Produced by $pkg version $VERSION
838 on $now
839 _HEADER
840  
841 unless($args{skip_header})
842 { $xml->insertBefore($header, $xml->firstChild);
843 $xml->insertBefore($doc->createTextNode("\n "), $header);
844 }
845  
846 # I use xsi:type myself, too late for the usual "used" counter
847 $ast->{'xmlns:xsi'} ||= SCHEMA2001i
848 if $args{show_type};
849  
850 # add info about name-spaces
851 foreach (sort keys %$ast)
852 { if( m/^xmlns\:(.*)/ )
853 { $xml->setNamespace($ast->{$_}, $1, 0);
854 }
855 }
856  
857 $xml;
858 }
859  
860 sub _xmlAny($$$$);
861 sub _xmlAny($$$$)
862 { my ($self, $doc, $ast, $indent, $args) = @_;
863 my @res;
864 my $xsi = $self->_registerNSprefix('xsi', SCHEMA2001i, 1)
865 if $args->{show_type};
866  
867 my @comment;
868 if($ast->{struct} && $args->{show_struct})
869 { my $struct = $ast->{struct};
870 push @comment, ref $struct ? @$struct : $struct;
871 }
872  
873 push @comment, $ast->{occur}
874 if $ast->{occur} && $args->{show_occur};
875  
876 if($ast->{facets} && $args->{show_facets})
877 { my $facets = $ast->{facets};
878 push @comment, ref $facets eq 'ARRAY' ? @$facets : $facets;
879 }
880  
881 if(defined $ast->{kind} && $ast->{kind} eq 'union')
882 { push @comment, map " $_->{type}", @{$ast->{choice}};
883 }
884  
885 my @attrs = @{$ast->{attrs} || []};
886 foreach my $attr (@attrs)
887 { push @res, $doc->createAttribute($attr->{tag}, $attr->{example});
888 my ($ns, $local) = unpack_type $attr->{_TYPE};
889 my $prefix = $self->_registerNSprefix('', $ns, 1);
890 push @comment, "attr $attr->{tag} has type $prefix:$local"
891 if $args->{show_type};
892 }
893  
894 my $nest_indent = $indent.$args->{indent};
895 if(@comment)
896 { my $comment = ' '.join("$nest_indent ", @comment) .' ';
897 push @res
898 , $doc->createTextNode($indent)
899 , $doc->createComment($comment);
900 }
901  
902 my @elems = @{$ast->{elems} || []};
903 foreach my $elem (@elems)
904 { if(ref $elem eq 'BLOCK' || ref $elem eq 'REP-BLOCK')
905 { push @res, $self->_xmlAny($doc, $elem, $indent, $args);
906 }
907 elsif($elem->{tag} eq '_')
908 { push @res, $doc->createTextNode($indent.$elem->{example});
909 }
910 else
911 { my $node = $self->_xmlAny($doc, $elem, $nest_indent, $args);
912 push @res, $doc->createTextNode($indent)
913 if $node->isa('XML::LibXML::Element');
914 push @res, $node;
915 }
916 }
917  
918 (my $outdent = $indent) =~ s/$args->{indent}$//; # sorry
919  
920 if(my $example = $ast->{example})
921 { push @res, $doc->createTextNode
922 (@comment ? "$indent$example$outdent" : $example)
923 }
924  
925 if($ast->{_TYPE} && $args->{show_type})
926 { my $pref = $self->prefixed($ast->{_TYPE});
927 push @res, $doc->createAttribute("$xsi:type" => $pref);
928 }
929  
930 return @res
931 if wantarray;
932  
933 my $node = $doc->createElement($ast->{tag});
934 $node->addChild($_) for @res;
935 $node->appendText($outdent) if @elems;
936 $node;
937 }
938  
939 sub makeBlocked($$$)
940 { my ($self, $where, $class, $type) = @_;
941 panic "namespace blocking not yet supported for Templates";
942 }
943  
944  
945 1;