1 package CGI
::Ex
::Template
;
3 ###----------------------------------------------------------------###
4 # See the perldoc in CGI/Ex/Template.pod
5 # Copyright 2006 - Paul Seamons #
6 # Distributed under the Perl Artistic License without warranty #
7 ###----------------------------------------------------------------###
10 use constant trace
=> $ENV{'CET_TRACE'} || 0; # enable for low level tracing
13 $SCALAR_OPS $HASH_OPS $LIST_OPS $FILTER_OPS $VOBJS
14 $DIRECTIVES $QR_DIRECTIVE
35 $PACKAGE_EXCEPTION $PACKAGE_ITERATOR $PACKAGE_CONTEXT $PACKAGE_STASH $PACKAGE_PERL_HANDLE
44 $PACKAGE_EXCEPTION = 'CGI::Ex::Template::Exception';
45 $PACKAGE_ITERATOR = 'CGI::Ex::Template::Iterator';
46 $PACKAGE_CONTEXT = 'CGI::Ex::Template::_Context';
47 $PACKAGE_STASH = 'CGI::Ex::Template::_Stash';
48 $PACKAGE_PERL_HANDLE = 'CGI::Ex::Template::EvalPerlHandle';
51 default => ['[%', '%]'], # default
52 template
=> ['[%', '%]'], # default
53 metatext
=> ['%%', '%%'], # Text::MetaText
54 star
=> ['[*', '*]'], # TT alternate
55 php
=> ['<?', '?>'], # PHP
56 asp
=> ['<%', '%>'], # ASP
57 mason
=> ['<%', '>' ], # HTML::Mason
58 html
=> ['<!--', '-->'], # HTML comments
63 as
=> \
&vmethod_as_scalar
,
64 chunk
=> \
&vmethod_chunk
,
65 collapse
=> sub { local $_ = $_[0]; s/^\s+//; s/\s+$//; s/\s+/ /g; $_ },
67 indent
=> \
&vmethod_indent
,
68 int => sub { local $^W; int $_[0] },
69 'format' => \
&vmethod_format
,
70 hash
=> sub { {value
=> $_[0]} },
71 html
=> sub { local $_ = $_[0]; s/&/&/g; s/</</g; s/>/>/g; s/\"/"/g; $_ },
72 lcfirst => sub { lcfirst $_[0] },
73 length => sub { defined($_[0]) ? length($_[0]) : 0 },
74 list
=> sub { [$_[0]] },
75 lower
=> sub { lc $_[0] },
76 match
=> \
&vmethod_match
,
77 new
=> sub { defined $_[0] ? $_[0] : '' },
79 rand => sub { local $^W; rand shift },
80 remove
=> sub { vmethod_replace
(shift, shift, '', 1) },
81 repeat
=> \
&vmethod_repeat
,
82 replace
=> \
&vmethod_replace
,
83 search
=> sub { my ($str, $pat) = @_; return $str if ! defined $str || ! defined $pat; return scalar $str =~ /$pat/ },
85 split => \
&vmethod_split
,
86 stderr
=> sub { print STDERR
$_[0]; '' },
87 substr => sub { my ($str, $i, $len) = @_; defined($len) ? substr($str, $i, $len) : substr($str, $i) },
88 trim
=> sub { local $_ = $_[0]; s/^\s+//; s/\s+$//; $_ },
89 ucfirst => sub { ucfirst $_[0] },
90 upper
=> sub { uc $_[0] },
94 $FILTER_OPS = { # generally - non-dynamic filters belong in scalar ops
95 eval => [\
&filter_eval
, 1],
96 evaltt
=> [\
&filter_eval
, 1],
97 file
=> [\
&filter_redirect
, 1],
98 redirect
=> [\
&filter_redirect
, 1],
102 as
=> \
&vmethod_as_list
,
103 first
=> sub { my ($ref, $i) = @_; return $ref->[0] if ! $i; return [@{$ref}[0 .. $i - 1]]},
104 grep => sub { my ($ref, $pat) = @_; [grep {/$pat/} @$ref] },
105 hash
=> sub { local $^W; my ($list, $i) = @_; defined($i) ? {map {$i++ => $_} @$list} : {@$list} },
106 join => sub { my ($ref, $join) = @_; $join = ' ' if ! defined $join; local $^W; return join $join, @$ref },
107 last => sub { my ($ref, $i) = @_; return $ref->[-1] if ! $i; return [@{$ref}[-$i .. -1]]},
108 list
=> sub { $_[0] },
109 max
=> sub { $#{ $_[0] } },
110 merge
=> sub { my $ref = shift; return [ @$ref, grep {defined} map {ref eq 'ARRAY' ? @$_ : undef} @_ ] },
111 new
=> sub { local $^W; return [@_] },
112 nsort
=> \
&vmethod_nsort
,
113 pop => sub { pop @{ $_[0] } },
114 push => sub { my $ref = shift; push @$ref, @_; return '' },
115 random
=> sub { my $ref = shift; $ref->[ rand @$ref ] },
116 reverse => sub { [ reverse @{ $_[0] } ] },
117 shift => sub { shift @{ $_[0] } },
118 size
=> sub { scalar @{ $_[0] } },
119 slice
=> sub { my ($ref, $a, $b) = @_; $a ||= 0; $b = $#$ref if ! defined $b; return [@{$ref}[$a .. $b]] },
120 sort => \
&vmethod_sort
,
121 splice => \
&vmethod_splice
,
122 unique
=> sub { my %u; return [ grep { ! $u{$_} ++ } @{ $_[0] } ] },
123 unshift => sub { my $ref = shift; unshift @$ref, @_; return '' },
127 as
=> \
&vmethod_as_hash
,
128 defined => sub { return '' if ! defined $_[1]; defined $_[0]->{ $_[1] } },
129 delete => sub { return '' if ! defined $_[1]; delete $_[0]->{ $_[1] } },
130 each => sub { [%{ $_[0] }] },
131 exists => sub { return '' if ! defined $_[1]; exists $_[0]->{ $_[1] } },
132 hash
=> sub { $_[0] },
133 import
=> sub { my ($a, $b) = @_; return '' if ref($b) ne 'HASH'; @{$a}{keys %$b} = values %$b; '' },
134 item
=> sub { my ($h, $k) = @_; return '' if ! defined $k || $k =~ $QR_PRIVATE; $h->{$k} },
135 items
=> sub { [ %{ $_[0] } ] },
136 keys => sub { [keys %{ $_[0] }] },
137 list
=> sub { [$_[0]] },
138 new
=> sub { local $^W; return (@_ == 1 && ref $_[-1] eq 'HASH') ? $_[-1] : {@_} },
139 nsort
=> sub { my $ref = shift; [sort {$ref->{$a} <=> $ref->{$b} } keys %$ref] },
140 pairs
=> sub { [map { {key
=> $_, value
=> $_[0]->{$_}} } keys %{ $_[0] } ] },
141 size
=> sub { scalar keys %{ $_[0] } },
142 sort => sub { my $ref = shift; [sort {lc $ref->{$a} cmp lc $ref->{$b}} keys %$ref] },
143 values => sub { [values %{ $_[0] }] },
151 foreach (values %$VOBJS) {
152 $_->{'Text'} = $_->{'as'};
153 $_->{'Hash'} = $_->{'hash'};
154 $_->{'List'} = $_->{'list'};
158 #name parse_sub play_sub block postdir continue move_to_front
159 BLOCK
=> [\
&parse_BLOCK
, \
&play_BLOCK
, 1, 0, 0, 1],
160 BREAK
=> [sub {}, \
&play_control
],
161 CALL
=> [\
&parse_CALL
, \
&play_CALL
],
162 CASE
=> [\
&parse_CASE
, undef, 0, 0, {SWITCH
=> 1, CASE
=> 1}],
163 CATCH => [\
&parse_CATCH
, undef, 0, 0, {TRY
=> 1, CATCH => 1}],
164 CLEAR
=> [sub {}, \
&play_CLEAR
],
165 '#' => [sub {}, sub {}],
166 DEBUG
=> [\
&parse_DEBUG
, \
&play_DEBUG
],
167 DEFAULT
=> [\
&parse_DEFAULT
, \
&play_DEFAULT
],
168 DUMP
=> [\
&parse_DUMP
, \
&play_DUMP
],
169 ELSE
=> [sub {}, undef, 0, 0, {IF
=> 1, ELSIF
=> 1, UNLESS
=> 1}],
170 ELSIF
=> [\
&parse_IF
, undef, 0, 0, {IF
=> 1, ELSIF
=> 1, UNLESS
=> 1}],
171 END => [undef, sub {}],
172 FILTER
=> [\
&parse_FILTER
, \
&play_FILTER
, 1, 1],
173 '|' => [\
&parse_FILTER
, \
&play_FILTER
, 1, 1],
174 FINAL
=> [sub {}, undef, 0, 0, {TRY
=> 1, CATCH => 1}],
175 FOR
=> [\
&parse_FOREACH
, \
&play_FOREACH
, 1, 1],
176 FOREACH
=> [\
&parse_FOREACH
, \
&play_FOREACH
, 1, 1],
177 GET
=> [\
&parse_GET
, \
&play_GET
],
178 IF
=> [\
&parse_IF
, \
&play_IF
, 1, 1],
179 INCLUDE
=> [\
&parse_INCLUDE
, \
&play_INCLUDE
],
180 INSERT
=> [\
&parse_INSERT
, \
&play_INSERT
],
181 LAST
=> [sub {}, \
&play_control
],
182 MACRO
=> [\
&parse_MACRO
, \
&play_MACRO
],
183 META
=> [undef, sub {}],
184 METADEF
=> [undef, \
&play_METADEF
],
185 NEXT => [sub {}, \
&play_control
],
186 PERL
=> [\
&parse_PERL
, \
&play_PERL
, 1],
187 PROCESS
=> [\
&parse_PROCESS
, \
&play_PROCESS
],
188 RAWPERL
=> [\
&parse_PERL
, \
&play_RAWPERL
, 1],
189 RETURN
=> [sub {}, \
&play_control
],
190 SET
=> [\
&parse_SET
, \
&play_SET
],
191 STOP
=> [sub {}, \
&play_control
],
192 SWITCH
=> [\
&parse_SWITCH
, \
&play_SWITCH
, 1],
193 TAGS
=> [undef, sub {}],
194 THROW
=> [\
&parse_THROW
, \
&play_THROW
],
195 TRY
=> [sub {}, \
&play_TRY
, 1],
196 UNLESS
=> [\
&parse_UNLESS
, \
&play_UNLESS
, 1, 1],
197 USE
=> [\
&parse_USE
, \
&play_USE
],
198 WHILE
=> [\
&parse_IF
, \
&play_WHILE
, 1, 1],
199 WRAPPER
=> [\
&parse_WRAPPER
, \
&play_WRAPPER
, 1, 1],
200 #name #parse_sub #play_sub #block #postdir #continue #move_to_front
202 $QR_DIRECTIVE = qr{ ^ (\w+|\|) (?= $|[\s;\#]) }x;
204 ### setup the operator parsing
206 # type precedence symbols action (undef means play_operator will handle)
207 ['postfix', 99, ['++'], undef ],
208 ['postfix', 99, ['--'], undef ],
209 ['prefix', 98, ['++'], undef ],
210 ['prefix', 98, ['--'], undef ],
211 ['right', 96, ['**', 'pow'], sub { $_[0] ** $_[1] } ],
212 ['prefix', 93, ['!'], sub { ! $_[0] } ],
213 ['prefix', 93, ['-'], sub { @_ == 1 ? 0 - $_[0] : $_[0] - $_[1] } ],
214 ['left', 90, ['*'], sub { $_[0] * $_[1] } ],
215 ['left', 90, ['/'], sub { $_[0] / $_[1] } ],
216 ['left', 90, ['div', 'DIV'], sub { int($_[0] / $_[1]) } ],
217 ['left', 90, ['%', 'mod', 'MOD'], sub { $_[0] % $_[1] } ],
218 ['left', 85, ['+'], sub { $_[0] + $_[1] } ],
219 ['left', 85, ['-'], sub { @_ == 1 ? 0 - $_[0] : $_[0] - $_[1] } ],
220 ['left', 85, ['~', '_'], sub { join "", @_ } ],
221 ['none', 80, ['<'], sub { $_[0] < $_[1] } ],
222 ['none', 80, ['>'], sub { $_[0] > $_[1] } ],
223 ['none', 80, ['<='], sub { $_[0] <= $_[1] } ],
224 ['none', 80, ['>='], sub { $_[0] >= $_[1] } ],
225 ['none', 80, ['lt'], sub { $_[0] lt $_[1] } ],
226 ['none', 80, ['gt'], sub { $_[0] gt $_[1] } ],
227 ['none', 80, ['le'], sub { $_[0] le $_[1] } ],
228 ['none', 80, ['ge'], sub { $_[0] ge $_[1] } ],
229 ['none', 75, ['==', 'eq'], sub { $_[0] eq $_[1] } ],
230 ['none', 75, ['!=', 'ne'], sub { $_[0] ne $_[1] } ],
231 ['left', 70, ['&&'], undef ],
232 ['right', 65, ['||'], undef ],
233 ['none', 60, ['..'], sub { $_[0] .. $_[1] } ],
234 ['ternary', 55, ['?', ':'], undef ],
235 ['assign', 53, ['+='], sub { $_[0] + $_[1] } ],
236 ['assign', 53, ['-='], sub { $_[0] - $_[1] } ],
237 ['assign', 53, ['*='], sub { $_[0] * $_[1] } ],
238 ['assign', 53, ['/='], sub { $_[0] / $_[1] } ],
239 ['assign', 53, ['%='], sub { $_[0] % $_[1] } ],
240 ['assign', 53, ['**='], sub { $_[0]** $_[1] } ],
241 ['assign', 53, ['~=', '_='], sub { $_[0] . $_[1] } ],
242 ['assign', 52, ['='], undef ],
243 ['prefix', 50, ['not', 'NOT'], sub { ! $_[0] } ],
244 ['left', 45, ['and', 'AND'], undef ],
245 ['right', 40, ['or', 'OR'], undef ],
246 ['', 0, ['hash'], sub { return {@_}; } ],
247 ['', 0, ['array'], sub { return [@_] } ],
249 $OP = {map {my $ref = $_; map {$_ => $ref} @{$ref->[2]}} grep {$_->[0] ne 'prefix' } @$OPERATORS}; # all non-prefix
250 $OP_PREFIX = {map {my $ref = $_; map {$_ => $ref} @{$ref->[2]}} grep {$_->[0] eq 'prefix' } @$OPERATORS};
251 $OP_DISPATCH = {map {my $ref = $_; map {$_ => $ref->[3]} @{$ref->[2]}} grep {$_->[3] } @$OPERATORS};
252 $OP_ASSIGN = {map {my $ref = $_; map {$_ => 1} @{$ref->[2]}} grep {$_->[0] eq 'assign' } @$OPERATORS};
253 $OP_POSTFIX = {map {my $ref = $_; map {$_ => 1} @{$ref->[2]}} grep {$_->[0] eq 'postfix'} @$OPERATORS}; # bool is postfix
254 $OP_TERNARY = {map {my $ref = $_; map {$_ => 1} @{$ref->[2]}} grep {$_->[0] eq 'ternary'} @$OPERATORS}; # bool is ternary
255 sub _op_qr
{ # no mixed \w\W operators
257 my $chrs = join '|', reverse sort map {quotemeta $_} grep {++$used{$_} < 2} grep {/^\W{2,}$/} @_;
258 my $chr = join '', sort map {quotemeta $_} grep {++$used{$_} < 2} grep {/^\W$/} @_;
259 my $word = join '|', reverse sort grep {++$used{$_} < 2} grep {/^\w+$/} @_;
260 $chr = "[$chr]" if $chr;
261 $word = "\\b(?:$word)\\b" if $word;
262 return join('|', grep {length} $chrs, $chr, $word) || die "Missing operator regex";
264 sub _build_op_qr
{ _op_qr
(map {@{ $_->[2] }} grep {$_->[0] ne 'prefix'} @$OPERATORS) }
265 sub _build_op_qr_prefix
{ _op_qr
(map {@{ $_->[2] }} grep {$_->[0] eq 'prefix'} @$OPERATORS) }
266 sub _build_op_qr_assign
{ _op_qr
(map {@{ $_->[2] }} grep {$_->[0] eq 'assign'} @$OPERATORS) }
267 $QR_OP = _build_op_qr
();
268 $QR_OP_PREFIX = _build_op_qr_prefix
();
269 $QR_OP_ASSIGN = _build_op_qr_assign
();
271 $QR_COMMENTS = '(?-s: \# .* \s*)*';
272 $QR_FILENAME = '([a-zA-Z]]:/|/)? [\w\-\.]+ (?:/[\w\-\.]+)*';
273 $QR_NUM = '(?:\d*\.\d+ | \d+) (?: [eE][+-]\d+ )?';
274 $QR_AQ_NOTDOT = "(?! \\s* $QR_COMMENTS \\.)";
275 $QR_AQ_SPACE = '(?: \\s+ | \$ | (?=[;+]) )'; # the + comes into play on filenames
276 $QR_PRIVATE = qr/^_/;
279 $EXTRA_COMPILE_EXT = '.sto';
282 ###----------------------------------------------------------------###
286 my $args = ref($_[0]) ? { %{ shift() } } : {@_};
287 my $self = bless $args, $class;
289 ### "enable" debugging - we only support DEBUG_DIRS and DEBUG_UNDEF
290 if ($self->{'DEBUG'}) {
291 $self->{'_debug_dirs'} = 1 if $self->{'DEBUG'} =~ /^\d+$/ ? $self->{'DEBUG'} & 8 : $self->{'DEBUG'} =~ /dirs|all/;
292 $self->{'_debug_undef'} = 1 if $self->{'DEBUG'} =~ /^\d+$/ ? $self->{'DEBUG'} & 2 : $self->{'DEBUG'} =~ /undef|all/;
298 ###----------------------------------------------------------------###
303 local $self->{'_vars'} = shift || {};
304 my $out_ref = shift || $self->throw('undef', "Missing output ref");
305 local $self->{'_top_level'} = delete $self->{'_start_top_level'};
306 my $i = length $$out_ref;
308 ### parse and execute
311 ### load the document
312 $doc = $self->load_parsed_tree($file) || $self->throw('undef', "Zero length content");;
314 ### prevent recursion
315 $self->throw('file', "recursion into '$doc->{name}'")
316 if ! $self->{'RECURSION'} && $self->{'_in'}->{$doc->{'name'}} && $doc->{'name'} ne 'input text';
317 local $self->{'_in'}->{$doc->{'name'}} = 1;
319 ### execute the document
320 if (! @{ $doc->{'_tree'} }) { # no tags found - just return the content
321 $$out_ref = ${ $doc->{'_content'} };
323 local $self->{'_vars'}->{'component'} = $doc;
324 $self->{'_vars'}->{'template'} = $doc if $self->{'_top_level'};
325 $self->execute_tree($doc->{'_tree'}, $out_ref);
326 delete $self->{'_vars'}->{'template'} if $self->{'_top_level'};
330 ### trim whitespace from the beginning and the end of a block or template
331 if ($self->{'TRIM'}) {
332 substr($$out_ref, $i, length($$out_ref) - $i) =~ s{ \s+ $ }{}x; # tail first
333 substr($$out_ref, $i, length($$out_ref) - $i) =~ s{ ^ \s+ }{}x;
336 ### handle exceptions
338 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
339 $err->doc($doc) if $doc && $err->can('doc') && ! $err->doc;
340 die $err if ! $self->{'_top_level'} || $err->type !~ /stop|return/;
346 ###----------------------------------------------------------------###
348 sub load_parsed_tree
{
351 return if ! defined $file;
353 my $doc = {name
=> $file};
355 ### looks like a string reference
357 $doc->{'_content'} = $file;
358 $doc->{'name'} = 'input text';
359 $doc->{'is_str_ref'} = 1;
361 ### looks like a previously cached-in-memory document
362 } elsif ($self->{'_documents'}->{$file}
363 && ( ($self->{'_documents'}->{$file}->{'_cache_time'} == time) # don't stat more than once a second
364 || ($self->{'_documents'}->{$file}->{'modtime'}
365 == (stat $self->{'_documents'}->{$file}->{'_filename'})[9]))) {
366 $doc = $self->{'_documents'}->{$file};
367 $doc->{'_cache_time'} = time;
370 ### looks like a block name of some sort
371 } elsif ($self->{'BLOCKS'}->{$file}) {
372 my $block = $self->{'BLOCKS'}->{$file};
374 ### allow for predefined blocks that are a code or a string
375 if (UNIVERSAL
::isa
($block, 'CODE')) {
378 if (! UNIVERSAL
::isa
($block, 'HASH')) {
379 $self->throw('block', "Unsupported BLOCK type \"$block\"") if ref $block;
381 $block = eval { $self->load_parsed_tree(\
$copy) }
382 || $self->throw('block', 'Parse error on predefined block');
384 $doc->{'_tree'} = $block->{'_tree'} || $self->throw('block', "Invalid block definition (missing tree)");
388 ### go and look on the file system
390 $doc->{'_filename'} = eval { $self->include_filename($file) };
392 ### allow for blocks in other files
393 if ($self->{'EXPOSE_BLOCKS'}
394 && ! $self->{'_looking_in_block_file'}) {
395 local $self->{'_looking_in_block_file'} = 1;
397 while ($file =~ s
|/([^/.]+)$||) {
398 $block_name = length($block_name) ? "$1/$block_name" : $1;
399 my $ref = eval { $self->load_parsed_tree($file) } || next;
400 my $_tree = $ref->{'_tree'};
401 foreach my $node (@$_tree) {
403 next if $node->[0] eq 'METADEF';
404 last if $node->[0] ne 'BLOCK';
405 next if $block_name ne $node->[3];
406 $doc->{'_content'} = $ref->{'_content'};
407 $doc->{'_tree'} = $node->[4];
408 $doc->{'modtime'} = $ref->{'modtime'};
409 $file = $ref->{'name'};
413 die $err if ! $doc->{'_tree'};
414 } elsif ($self->{'DEFAULT'}) {
415 $doc->{'_filename'} = eval { $self->include_filename($self->{'DEFAULT'}) } || die $err;
421 ### no tree yet - look for a file cache
422 if (! $doc->{'_tree'}) {
423 $doc->{'modtime'} = (stat $doc->{'_filename'})[9];
424 if ($self->{'COMPILE_DIR'} || $self->{'COMPILE_EXT'}) {
425 if ($self->{'COMPILE_DIR'}) {
426 $doc->{'_compile_filename'} = $self->{'COMPILE_DIR'} .'/'. $file;
428 $doc->{'_compile_filename'} = $doc->{'_filename'};
430 $doc->{'_compile_filename'} .= $self->{'COMPILE_EXT'} if defined($self->{'COMPILE_EXT'});
431 $doc->{'_compile_filename'} .= $EXTRA_COMPILE_EXT if defined $EXTRA_COMPILE_EXT;
433 if (-e
$doc->{'_compile_filename'} && (stat _
)[9] == $doc->{'modtime'}) {
435 $doc->{'_tree'} = Storable
::retrieve
($doc->{'_compile_filename'});
436 $doc->{'compile_was_used'} = 1;
438 my $str = $self->slurp($doc->{'_filename'});
439 $doc->{'_content'} = \
$str;
442 my $str = $self->slurp($doc->{'_filename'});
443 $doc->{'_content'} = \
$str;
449 ### haven't found a parsed tree yet - parse the content into a tree
450 if (! $doc->{'_tree'}) {
451 if ($self->{'CONSTANTS'}) {
452 my $key = $self->{'CONSTANT_NAMESPACE'} || 'constants';
453 $self->{'NAMESPACE'}->{$key} ||= $self->{'CONSTANTS'};
456 local $self->{'_vars'}->{'component'} = $doc;
457 $doc->{'_tree'} = $self->parse_tree($doc->{'_content'}); # errors die
460 ### cache parsed_tree in memory unless asked not to do so
461 if (! $doc->{'is_str_ref'} && (! defined($self->{'CACHE_SIZE'}) || $self->{'CACHE_SIZE'})) {
462 $self->{'_documents'}->{$file} ||= $doc;
463 $doc->{'_cache_time'} = time;
465 ### allow for config option to keep the cache size down
466 if ($self->{'CACHE_SIZE'}) {
467 my $all = $self->{'_documents'};
468 if (scalar(keys %$all) > $self->{'CACHE_SIZE'}) {
470 foreach my $file (sort {$all->{$b}->{'_cache_time'} <=> $all->{$a}->{'_cache_time'}} keys %$all) {
471 delete($all->{$file}) if ++$n > $self->{'CACHE_SIZE'};
477 ### save a cache on the fileside as asked
478 if ($doc->{'_compile_filename'} && ! $doc->{'compile_was_used'}) {
479 my $dir = $doc->{'_compile_filename'};
483 File
::Path
::mkpath
($dir);
486 Storable
::store
($doc->{'_tree'}, $doc->{'_compile_filename'});
487 utime $doc->{'modtime'}, $doc->{'modtime'}, $doc->{'_compile_filename'};
496 if (! $str_ref || ! defined $$str_ref) {
497 $self->throw('parse.no_string', "No string or undefined during parse");
500 my $STYLE = $self->{'TAG_STYLE'} || 'default';
501 my $START = $self->{'START_TAG'} || $TAGS->{$STYLE}->[0];
502 my $END = $self->{'END_TAG'} || $TAGS->{$STYLE}->[1];
503 my $len_s = length $START;
504 my $len_e = length $END;
506 my @tree; # the parsed tree
507 my $pointer = \
@tree; # pointer to current tree to handle nested blocks
508 my @state; # maintain block levels
509 local $self->{'_state'} = \
@state; # allow for items to introspect (usually BLOCKS)
510 local $self->{'_in_perl'}; # no interpolation in perl
511 my @move_to_front; # items that need to be declared first (usually BLOCKS)
512 my @meta; # place to store any found meta information (to go into METADEF)
513 my $i = 0; # start index
514 my $j = 0; # end index
515 my $last = 0; # previous end index
516 my $post_chomp = 0; # previous post_chomp setting
517 my $continue; # multiple directives in the same tag
518 my $post_op; # found a post-operative DIRECTIVE
519 my $capture; # flag to start capture
524 ### continue looking for information in a semi-colon delimited tag
527 $node = [undef, $i, $j];
529 ### look through the string using index
531 $i = index($$str_ref, $START, $last);
532 last if $i == -1; # no start tag found - we are done
533 if ($last != $i) { # found a text portion - chomp it, interpolate it and store it
534 my $text = substr($$str_ref, $last, $i - $last);
537 if ($post_chomp == 1) { $_last += length($1) if $text =~ s{ ^ ([^\S\n]* \n) }{}x }
538 elsif ($post_chomp == 2) { $_last += length($1) + 1 if $text =~ s{ ^ (\s+) }{ }x }
539 elsif ($post_chomp == 3) { $_last += length($1) if $text =~ s{ ^ (\s+) }{}x }
542 push @$pointer, $text;
543 $self->interpolate_node($pointer, $_last) if $self->{'INTERPOLATE'};
546 $j = index($$str_ref, $END, $i + $len_s);
548 if ($j == -1) { # missing closing tag
549 $last = length($$str_ref);
552 $tag = substr($$str_ref, $i + $len_s, $j - ($i + $len_s));
553 $node = [undef, $i + $len_s, $j];
555 ### take care of whitespace and comments flags
556 my $pre_chomp = $tag =~ s{ ^ ([+=~-]) }{}x ? $1 : $self->{'PRE_CHOMP'};
557 $post_chomp = $tag =~ s{ ([+=~-]) $ }{}x ? $1 : $self->{'POST_CHOMP'};
558 $pre_chomp =~ y/-=~+/1230/ if $pre_chomp;
559 $post_chomp =~ y/-=~+/1230/ if $post_chomp;
560 if ($pre_chomp && $pointer->[-1] && ! ref $pointer->[-1]) {
561 if ($pre_chomp == 1) { $pointer->[-1] =~ s{ (?:\n|^) [^\S\n]* \z }{}x }
562 elsif ($pre_chomp == 2) { $pointer->[-1] =~ s{ (\s+) \z }{ }x }
563 elsif ($pre_chomp == 3) { $pointer->[-1] =~ s{ (\s+) \z }{}x }
564 splice(@$pointer, -1, 1, ()) if ! length $pointer->[-1]; # remove the node if it is zero length
566 if ($tag =~ /^\#/) { # leading # means to comment the entire section
568 push @$pointer, $node;
571 $tag =~ s{ ^ \s+ $QR_COMMENTS }{}ox;
580 ### look for DIRECTIVES
581 if ($tag =~ $QR_DIRECTIVE # find a word
582 && $DIRECTIVES->{$1} ) { # is it a directive
583 $node->[0] = $func = $1;
584 $tag =~ s{ ^ (\w+ | \|) \s* $QR_COMMENTS }{}ox;
586 ### store out this current node level
587 if ($post_op) { # on a post operator - replace the original node with the new one - store the old in the new
588 my @post_op = @$post_op;
591 $node->[4] = [\
@post_op];
593 # do nothing - it will be handled further down
595 push @$pointer, $node;
598 ### anything that behaves as a block ending
599 if ($func eq 'END' || $DIRECTIVES->{$func}->[4]) { # [4] means it is a continuation block (ELSE, CATCH, etc)
601 $self->throw('parse', "Found an $func tag while not in a block", $node);
603 my $parent_node = pop @state;
605 if ($func ne 'END') {
606 pop @$pointer; # we will store the node in the parent instead
607 $parent_node->[5] = $node;
608 my $parent_type = $parent_node->[0];
609 if (! $DIRECTIVES->{$func}->[4]->{$parent_type}) {
610 $self->throw('parse', "Found unmatched nested block", $node, 0);
614 ### restore the pointer up one level (because we hit the end of a block)
615 $pointer = (! @state) ? \
@tree : $state[-1]->[4];
618 if ($func eq 'END') {
619 if ($DIRECTIVES->{$parent_node->[0]}->[5]) { # move things like BLOCKS to front
620 push @move_to_front, $parent_node;
621 if ($pointer->[-1] && ! $pointer->[-1]->[6]) { # capturing doesn't remove the var
622 splice(@$pointer, -1, 1, ());
624 } elsif ($parent_node->[0] =~ /PERL$/) {
625 delete $self->{'_in_perl'};
628 ### continuation block - such as an elsif
630 $node->[3] = eval { $DIRECTIVES->{$func}->[0]->($self, \
$tag, $node) };
632 $err->node($node) if UNIVERSAL
::can
($err, 'node') && ! $err->node;
636 $pointer = $node->[4] ||= [];
639 } elsif ($func eq 'TAGS') {
640 if ($tag =~ / ^ (\w+) /x && $TAGS->{$1}) {
641 $tag =~ s{ ^ (\w+) \s* $QR_COMMENTS }{}ox;
642 ($START, $END) = @{ $TAGS->{$1} };
643 } elsif ($tag =~ s{ ^ (\S+) \s+ (\S+) \s* $QR_COMMENTS }{}ox) {
644 ($START, $END) = ($1, $2);
646 $len_s = length $START;
647 $len_e = length $END;
649 } elsif ($func eq 'META') {
650 my $args = $self->parse_args(\
$tag);
652 if (($hash = $self->play_expr($args->[-1]))
653 && UNIVERSAL
::isa
($hash, 'HASH')) {
654 unshift @meta, %$hash; # first defined win
657 ### all other "normal" tags
659 $node->[3] = eval { $DIRECTIVES->{$func}->[0]->($self, \
$tag, $node) };
661 $err->node($node) if UNIVERSAL
::can
($err, 'node') && ! $err->node;
664 if ($DIRECTIVES->{$func}->[2] && ! $post_op) { # this looks like a block directive
666 $pointer = $node->[4] ||= [];
670 ### allow for bare variable getting and setting
671 } elsif (defined(my $var = $self->parse_expr(\
$tag))) {
672 push @$pointer, $node;
673 if ($tag =~ s{ ^ ($QR_OP_ASSIGN) >? \s* $QR_COMMENTS }{}ox) {
675 $node->[3] = eval { $DIRECTIVES->{'SET'}->[0]->($self, \
$tag, $node, $1, $var) };
677 $err->node($node) if UNIVERSAL
::can
($err, 'node') && ! $err->node;
686 my $all = substr($$str_ref, $i + $len_s, $j - ($i + $len_s));
689 $self->throw('parse', "Not sure how to handle tag \"$all\"", $node);
692 ### we now have the directive to capture for an item like "SET foo = BLOCK" - store it
694 my $parent_node = $capture;
695 push @{ $parent_node->[4] }, $node;
699 ### we are flagged to start capturing the output of the next directive - set it up
701 $continue = $j - length $tag;
702 $node->[2] = $continue;
706 ### semi-colon = end of statement - we will need to continue parsing this tag
707 } elsif ($tag =~ s{ ^ ; \s* $QR_COMMENTS }{}ox) {
708 $continue = $j - length $tag;
709 $node->[2] = $continue;
712 ### looking at a post operator ([% u FOREACH u IN [1..3] %])
713 } elsif ($tag =~ $QR_DIRECTIVE # find a word
714 && $DIRECTIVES->{$1} # is it a directive
715 && $DIRECTIVES->{$1}->[3]) { # it is a post operative directive
716 $continue = $j - length $tag;
717 $node->[2] = $continue;
720 ### unlink TT2 - look for another directive
721 } elsif (length $tag) {
722 #$self->throw('parse', "Found trailing info \"$tag\"", $node);
723 $continue = $j - length $tag;
724 $node->[2] = $continue;
733 if (@move_to_front) {
734 unshift @tree, @move_to_front;
737 unshift @tree, ['METADEF', 0, 0, {@meta}];
741 $self->throw('parse.missing.end', "Missing END", $state[-1], 0);
744 ### pull off the last text portion - if any
745 if ($last != length($$str_ref)) {
746 my $text = substr($$str_ref, $last, length($$str_ref) - $last);
749 if ($post_chomp == 1) { $_last += length($1) if $text =~ s{ ^ ([^\S\n]* \n) }{}x }
750 elsif ($post_chomp == 2) { $_last += length($1) + 1 if $text =~ s{ ^ (\s+) }{ }x }
751 elsif ($post_chomp == 3) { $_last += length($1) if $text =~ s{ ^ (\s+) }{}x }
754 push @$pointer, $text;
755 $self->interpolate_node($pointer, $_last) if $self->{'INTERPOLATE'};
763 my ($self, $tree, $out_ref) = @_;
765 # node contains (0: DIRECTIVE,
768 # 3: parsed tag details,
769 # 4: sub tree for block types
770 # 5: continuation sub trees for sub continuation block types (elsif, else, etc)
771 # 6: flag to capture next directive
772 for my $node (@$tree) {
773 ### text nodes are just the bare text
775 warn "NODE: TEXT\n" if trace
;
776 $$out_ref .= $node if defined $node;
780 warn "NODE: $node->[0] (char $node->[1])\n" if trace
;
781 $$out_ref .= $self->debug_node($node) if $self->{'_debug_dirs'} && ! $self->{'_debug_off'};
783 my $val = $DIRECTIVES->{$node->[0]}->[1]->($self, $node->[3], $node, $out_ref);
784 $$out_ref .= $val if defined $val;
788 ###----------------------------------------------------------------###
793 my $ARGS = shift || {};
795 ### allow for custom auto_quoting (such as hash constructors)
796 if ($ARGS->{'auto_quote'}) {
797 if ($$str_ref =~ $ARGS->{'auto_quote'}) {
799 substr($$str_ref, 0, length($str), '');
800 $$str_ref =~ s{ ^ \s* $QR_COMMENTS }{}ox;
802 ### allow for auto-quoted $foo or ${foo.bar} type constructs
803 } elsif ($$str_ref =~ s{ ^ \$ (\w+ (?:\.\w+)*) \b \s* $QR_COMMENTS }{}ox
804 || $$str_ref =~ s{ ^ \$\{ \s* ([^\}]+) \} \s* $QR_COMMENTS }{}ox) {
806 return $self->parse_expr(\
$name);
810 my $copy = $$str_ref; # copy while parsing to allow for errors
812 ### test for leading prefix operators
814 while ($copy =~ s{ ^ ($QR_OP_PREFIX) \s* $QR_COMMENTS }{}ox) {
815 return if $ARGS->{'auto_quote'}; # auto_quoted thing was too complicated
816 push @{ $has_prefix }, $1;
824 if ($copy =~ s{ ^ 0x ( [a-fA-F0-9]+ ) \s* $QR_COMMENTS }{}ox) {
825 my $number = eval { hex $1 } || 0;
826 push @var, \
$number;
829 ### allow for numbers
830 } elsif ($copy =~ s{ ^ ( $QR_NUM ) \s* $QR_COMMENTS }{}ox) {
832 push @var, \
$number;
835 ### allow for quoted array constructor
836 } elsif ($copy =~ s{ ^ qw (\W) \s* }{}x) {
838 $quote =~ y
|([{<|)]}>|;
839 $copy =~ s{ ^ (.*) \Q$quote\E \s* $QR_COMMENTS }{}sx
840 || $self->throw('parse.missing.array_close', "Missing close \"$quote\"", undef, length($$str_ref) - length($copy));
842 $str =~ s{ ^ \s+ | \s+ $ }{}x;
843 my $arrayref = ['array', split /\s+/, $str];
844 push @var, \
$arrayref;
846 ### looks like a normal variable start
847 } elsif ($copy =~ s{ ^ (\w+) \s* $QR_COMMENTS }{}ox) {
849 $is_namespace = 1 if $self->{'NAMESPACE'} && $self->{'NAMESPACE'}->{$1};
851 ### allow for literal strings
852 } elsif ($copy =~ s{ ^ ([\"\']) (|.*?[^\\]) \1 \s* $QR_COMMENTS }{}sox) {
853 if ($1 eq "'") { # no interpolation on single quoted strings
855 $str =~ s{ \\\' }{\'}xg;
863 $str =~ s/\\([\"\$])/$1/g;
864 my @pieces = $ARGS->{'auto_quote'}
865 ? split(m{ (\$\w+ | \$\{ [^\}]+ \
}) }x
, $str) # autoquoted items get a single $\w+ - no nesting
866 : split(m{ (\$\w+ (?:\.\w+)* | \$\{ [^\}]+ \
}) }x
, $str);
868 foreach my $piece (@pieces) {
869 next if ! ($n++ % 2);
870 next if $piece !~ m{ ^ \$ (\w+ (?:\.\w+)*) $ }x
871 && $piece !~ m{ ^ \$\{ \s* ([^\}]+) \
} $ }x
;
873 $piece = $self->parse_expr(\
$name);
875 @pieces = grep {defined && length} @pieces;
876 if (@pieces == 1 && ! ref $pieces[0]) {
877 push @var, \
$pieces[0];
879 } elsif (! @pieces) {
883 push @var, \
['~', @pieces];
886 if ($ARGS->{'auto_quote'}){
888 return ${ $var[0] } if $is_literal;
893 ### allow for leading $foo or ${foo.bar} type constructs
894 } elsif ($copy =~ s{ ^ \$ (\w+) \b \s* $QR_COMMENTS }{}ox
895 || $copy =~ s{ ^ \$\{ \s* ([^\}]+) \} \s* $QR_COMMENTS }{}ox) {
897 push @var, $self->parse_expr(\
$name);
899 ### looks like an array constructor
900 } elsif ($copy =~ s{ ^ \[ \s* $QR_COMMENTS }{}ox) {
901 local $self->{'_operator_precedence'} = 0; # reset presedence
902 my $arrayref = ['array'];
903 while (defined(my $var = $self->parse_expr(\
$copy))) {
904 push @$arrayref, $var;
905 $copy =~ s{ ^ , \s* $QR_COMMENTS }{}ox;
907 $copy =~ s{ ^ \] \s* $QR_COMMENTS }{}ox
908 || $self->throw('parse.missing.square_bracket', "Missing close \]", undef, length($$str_ref) - length($copy));
909 push @var, \
$arrayref;
911 ### looks like a hash constructor
912 } elsif ($copy =~ s{ ^ \{ \s* $QR_COMMENTS }{}ox) {
913 local $self->{'_operator_precedence'} = 0; # reset precedence
914 my $hashref = ['hash'];
915 while (defined(my $key = $self->parse_expr(\
$copy, {auto_quote
=> qr{ ^ (\w+) $QR_AQ_NOTDOT }xo}))) {
916 $copy =~ s{ ^ = >? \s* $QR_COMMENTS }{}ox;
917 my $val = $self->parse_expr(\
$copy);
918 push @$hashref, $key, $val;
919 $copy =~ s{ ^ , \s* $QR_COMMENTS }{}ox;
921 $copy =~ s{ ^ \} \s* $QR_COMMENTS }{}ox
922 || $self->throw('parse.missing.curly_bracket', "Missing close \} ($copy)", undef, length($$str_ref) - length($copy));
923 push @var, \
$hashref;
925 ### looks like a paren grouper
926 } elsif ($copy =~ s{ ^ \( \s* $QR_COMMENTS }{}ox) {
927 local $self->{'_operator_precedence'} = 0; # reset precedence
928 my $var = $self->parse_expr(\
$copy, {allow_parened_ops
=> 1});
929 $copy =~ s{ ^ \) \s* $QR_COMMENTS }{}ox
930 || $self->throw('parse.missing.paren', "Missing close \)", undef, length($$str_ref) - length($copy));
932 pop(@var); # pull off the trailing args of the paren group
934 ### nothing to find - return failure
939 return if $ARGS->{'auto_quote'}; # auto_quoted thing was too complicated
941 ### looks for args for the initial
942 if ($copy =~ s{ ^ \( \s* $QR_COMMENTS }{}ox) {
943 local $self->{'_operator_precedence'} = 0; # reset precedence
944 my $args = $self->parse_args(\
$copy);
945 $copy =~ s{ ^ \) \s* $QR_COMMENTS }{}ox
946 || $self->throw('parse.missing.paren', "Missing close \)", undef, length($$str_ref) - length($copy));
952 ### allow for nested items
953 while ($copy =~ s{ ^ ( \.(?!\.) | \|(?!\|) ) \s* $QR_COMMENTS }{}ox) {
954 push(@var, $1) if ! $ARGS->{'no_dots'};
956 ### allow for interpolated variables in the middle - one.$foo.two or one.${foo.bar}.two
957 if ($copy =~ s{ ^ \$(\w+) \s* $QR_COMMENTS }{}ox
958 || $copy =~ s{ ^ \$\{ \s* ([^\}]+)\} \s* $QR_COMMENTS }{}ox) {
960 my $var = $self->parse_expr(\
$name);
964 } elsif ($copy =~ s{ ^ (-? \w+) \s* $QR_COMMENTS }{}ox) {
968 $self->throw('parse', "Not sure how to continue parsing on \"$copy\" ($$str_ref)");
971 ### looks for args for the nested item
972 if ($copy =~ s{ ^ \( \s* $QR_COMMENTS }{}ox) {
973 local $self->{'_operator_precedence'} = 0; # reset precedence
974 my $args = $self->parse_args(\
$copy);
975 $copy =~ s{ ^ \) \s* $QR_COMMENTS }{}ox
976 || $self->throw('parse.missing.paren', "Missing close \)", undef, length($$str_ref) - length($copy));
984 ### flatten literals and constants as much as possible
985 my $var = ($is_literal && $#var == 1) ? ${ $var[0] }
986 : $is_namespace ? $self->play_expr(\
@var, {is_namespace_during_compile
=> 1})
989 ### allow for all "operators"
990 if (! $self->{'_operator_precedence'}) {
993 while ($copy =~ s{ ^ ($QR_OP) (\s* $QR_COMMENTS) }{}ox) { ## look for operators - then move along
994 if (! $ARGS->{'allow_parened_ops'} && $OP_ASSIGN->{$1}) {
995 $copy = $1 . $2 . $copy;
999 local $self->{'_operator_precedence'} = 1;
1002 ### allow for postfix - doesn't check precedence - someday we might change - but not today (only affects post ++ and --)
1003 if ($OP_POSTFIX->{$op}) {
1004 $var = [\
[$op, $var, 1], 0]; # cheat - give a "second value" to postfix ops
1007 ### allow for prefix operator precedence
1008 } elsif ($has_prefix && $OP->{$op}->[1] < $OP_PREFIX->{$has_prefix->[-1]}->[1]) {
1010 if ($#$tree == 1) { # only one operator - keep simple things fast
1011 $var = [\
[$tree->[0], $var, $tree->[1]], 0];
1013 unshift @$tree, $var;
1014 $var = $self->apply_precedence($tree, $found);
1019 $var = [ \
[ $has_prefix->[-1], $var ], 0 ];
1020 if (! @$has_prefix) { undef $has_prefix } else { pop @$has_prefix }
1023 ### add the operator to the tree
1024 my $var2 = $self->parse_expr(\
$copy);
1025 push (@{ $tree ||= [] }, $op, $var2);
1026 $found->{$OP->{$op}->[1]}->{$op} = 1; # found->{precedence}->{op}
1029 ### if we found operators - tree the nodes by operator precedence
1031 if (@$tree == 2) { # only one operator - keep simple things fast
1032 $var = [\
[$tree->[0], $var, $tree->[1]], 0];
1034 unshift @$tree, $var;
1035 $var = $self->apply_precedence($tree, $found);
1040 ### allow for prefix on non-chained variables
1042 $var = [ \
[ $_, $var ], 0 ] for reverse @$has_prefix;
1045 $$str_ref = $copy; # commit the changes
1049 ### this is used to put the parsed variables into the correct operations tree
1050 sub apply_precedence
{
1051 my ($self, $tree, $found) = @_;
1055 ### look at the operators we found in the order we found them
1056 for my $prec (sort keys %$found) {
1057 my $ops = $found->{$prec};
1058 local $found->{$prec};
1059 delete $found->{$prec};
1061 ### split the array on the current operators for this level
1064 for (my $i = 1; $i <= $#$tree; $i += 2) {
1065 next if ! $ops->{ $tree->[$i] };
1066 push @ops, $tree->[$i];
1067 push @exprs, [splice @$tree, 0, $i, ()];
1071 next if ! @exprs; # this iteration didn't have the current operator
1072 push @exprs, $tree if scalar @$tree; # add on any remaining items
1074 ### simplify sub expressions
1075 for my $node (@exprs) {
1077 $node = $node->[0]; # single item - its not a tree
1078 } elsif (@$node == 3) {
1079 $node = [ \
[ $node->[1], $node->[0], $node->[2] ], 0 ]; # single operator - put it straight on
1081 $node = $self->apply_precedence($node, $found); # more complicated - recurse
1085 ### assemble this current level
1088 # 1) items at the same precedence level must all be either right or left or ternary associative
1089 # 2) ternary items cannot share precedence with anybody else.
1090 # 3) there really shouldn't be another operator at the same level as a postfix
1091 my $type = $OP->{$ops[0]}->[0];
1093 if ($type eq 'ternary') {
1094 my $op = $OP->{$ops[0]}->[2]->[0]; # use the first op as what we are using
1096 ### return simple ternary
1098 $self->throw('parse', "Ternary operator mismatch") if $ops[0] ne $op;
1099 $self->throw('parse', "Ternary operator mismatch") if ! $ops[1] || $ops[1] eq $op;
1100 return [ \
[ $op, @exprs ], 0 ];
1104 ### reorder complex ternary - rare case
1105 while ($#ops >= 1) {
1106 ### if we look starting from the back - the first lead ternary op will always be next to its matching op
1107 for (my $i = $#ops; $i >= 0; $i --) {
1108 next if $OP->{$ops[$i]}->[2]->[1] eq $ops[$i];
1109 my ($op, $op2) = splice @ops, $i, 2, (); # remove the pair of operators
1110 my $node = [ \
[$op, @exprs[$i .. $i + 2] ], 0 ];
1111 splice @exprs, $i, 3, $node;
1114 return $exprs[0]; # at this point the ternary has been reduced to a single operator
1116 } elsif ($type eq 'right' || $type eq 'assign') {
1117 my $val = $exprs[-1];
1118 $val = [ \
[ $ops[$_ - 1], $exprs[$_], $val ], 0 ] for reverse (0 .. $#exprs - 1);
1122 my $val = $exprs[0];
1123 $val = [ \
[ $ops[$_ - 1], $val, $exprs[$_] ], 0 ] for (1 .. $#exprs);
1129 $self->throw('parse', "Couldn't apply precedence");
1132 ### look for arguments - both positional and named
1135 my $str_ref = shift;
1136 my $ARGS = shift || {};
1137 my $copy = $$str_ref;
1141 while (length $$str_ref) {
1142 my $copy = $$str_ref;
1143 if (defined(my $name = $self->parse_expr(\
$copy, {auto_quote
=> qr{ ^ (\w+) $QR_AQ_NOTDOT }xo}))
1144 && $copy =~ s{ ^ = >? \s* $QR_COMMENTS }{}ox) {
1145 $self->throw('parse', 'Named arguments not allowed') if $ARGS->{'positional_only'};
1146 my $val = $self->parse_expr(\
$copy);
1147 $copy =~ s{ ^ , \s* $QR_COMMENTS }{}ox;
1148 push @named, $name, $val;
1150 } elsif (defined(my $arg = $self->parse_expr($str_ref))) {
1152 $$str_ref =~ s{ ^ , \s* $QR_COMMENTS }{}ox;
1158 ### allow for named arguments to be added also
1159 push @args, [\
['hash', @named], 0] if scalar @named;
1164 ### allow for looking for $foo or ${foo.bar} in TEXT "nodes" of the parse tree.
1165 sub interpolate_node
{
1166 my ($self, $tree, $offset) = @_;
1167 return if $self->{'_in_perl'};
1169 ### split on variables while keeping the variables
1170 my @pieces = split m{ (?: ^ | (?<! \\)) (\$\w+ (?:\.\w+)* | \$\{ [^\}]+ \
}) }x
, $tree->[-1];
1171 if ($#pieces <= 0) {
1172 $tree->[-1] =~ s{ \\ ([\"\$]) }{$1}xg;
1178 foreach my $piece (@pieces) {
1179 $offset += length $piece; # we track the offset to make sure DEBUG has the right location
1180 if (! ($n++ % 2)) { # odds will always be text chunks
1181 next if ! length $piece;
1182 $piece =~ s{ \\ ([\"\$]) }{$1}xg;
1183 push @sub_tree, $piece;
1184 } elsif ($piece =~ m{ ^ \$ (\w+ (?:\.\w+)*) $ }x
1185 || $piece =~ m{ ^ \$\{ \s* ([^\}]+) \
} $ }x
) {
1187 push @sub_tree, ['GET', $offset - length($piece), $offset, $self->parse_expr(\
$name)];
1189 $self->throw('parse', "Parse error during interpolate node");
1193 ### replace the tree
1194 splice @$tree, -1, 1, @sub_tree;
1197 ###----------------------------------------------------------------###
1200 ### allow for the parse tree to store literals
1201 return $_[1] if ! ref $_[1];
1205 my $ARGS = shift || {};
1208 ### determine the top level of this particular variable access
1210 my $name = $var->[$i++];
1211 my $args = $var->[$i++];
1212 warn "play_expr: begin \"$name\"\n" if trace
;
1214 if (ref $name eq 'SCALAR') { # a scalar literal
1216 } elsif (ref $name eq 'REF') { # operator
1217 return $self->play_operator($$name) if ${ $name }->[0] eq '..';
1218 $ref = $self->play_operator($$name);
1219 } else { # a named variable access (ie via $name.foo)
1220 $name = $self->play_expr($name);
1221 if (defined $name) {
1222 return if $name =~ $QR_PRIVATE; # don't allow vars that begin with _
1223 $ref = $self->{'_vars'}->{$name};
1226 } elsif (defined $name) {
1227 if ($ARGS->{'is_namespace_during_compile'}) {
1228 $ref = $self->{'NAMESPACE'}->{$name};
1230 return if $name =~ $QR_PRIVATE; # don't allow vars that begin with _
1231 $ref = $self->{'_vars'}->{$name};
1232 $ref = $VOBJS->{$name} if ! defined $ref;
1238 while (defined $ref) {
1240 ### check at each point if the rurned thing was a code
1241 if (UNIVERSAL
::isa
($ref, 'CODE')) {
1242 my @results = $ref->($args ? map { $self->play_expr($_) } @$args : ());
1243 if (defined $results[0]) {
1244 $ref = ($#results > 0) ? \
@results : $results[0];
1245 } elsif (defined $results[1]) {
1246 die $results[1]; # TT behavior - why not just throw ?
1253 ### descend one chained level
1254 last if $i >= $#$var;
1255 my $was_dot_call = $ARGS->{'no_dots'} ? 1 : $var->[$i++] eq '.';
1256 $name = $var->[$i++];
1257 $args = $var->[$i++];
1258 warn "play_expr: nested \"$name\"\n" if trace
;
1260 ### allow for named portions of a variable name (foo.$name.bar)
1262 if (ref($name) eq 'ARRAY') {
1263 $name = $self->play_expr($name);
1264 if (! defined($name) || $name =~ $QR_PRIVATE || $name =~ /^\./) {
1269 die "Shouldn't get a ". ref($name) ." during a vivify on chain";
1272 if ($name =~ $QR_PRIVATE) { # don't allow vars that begin with _
1277 ### allow for scalar and filter access (this happens for every non virtual method call)
1279 if ($SCALAR_OPS->{$name}) { # normal scalar op
1280 $ref = $SCALAR_OPS->{$name}->($ref, $args ? map { $self->play_expr($_) } @$args : ());
1282 } elsif ($LIST_OPS->{$name}) { # auto-promote to list and use list op
1283 $ref = $LIST_OPS->{$name}->([$ref], $args ? map { $self->play_expr($_) } @$args : ());
1285 } elsif (my $filter = $self->{'FILTERS'}->{$name} # filter configured in Template args
1286 || $FILTER_OPS->{$name} # predefined filters in CET
1287 || (UNIVERSAL
::isa
($name, 'CODE') && $name) # looks like a filter sub passed in the stash
1288 || $self->list_filters->{$name}) { # filter defined in Template::Filters
1290 if (UNIVERSAL
::isa
($filter, 'CODE')) {
1291 $ref = eval { $filter->($ref) }; # non-dynamic filter - no args
1293 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1296 } elsif (! UNIVERSAL
::isa
($filter, 'ARRAY')) {
1297 $self->throw('filter', "invalid FILTER entry for '$name' (not a CODE ref)");
1299 } elsif (@$filter == 2 && UNIVERSAL
::isa
($filter->[0], 'CODE')) { # these are the TT style filters
1301 my $sub = $filter->[0];
1302 if ($filter->[1]) { # it is a "dynamic filter" that will return a sub
1303 ($sub, my $err) = $sub->($self->context, $args ? map { $self->play_expr($_) } @$args : ());
1304 if (! $sub && $err) {
1305 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1307 } elsif (! UNIVERSAL
::isa
($sub, 'CODE')) {
1308 $self->throw('filter', "invalid FILTER for '$name' (not a CODE ref)")
1309 if ref($sub) !~ /Template::Exception$/;
1313 $ref = $sub->($ref);
1316 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1319 } else { # this looks like our vmethods turned into "filters" (a filter stored under a name)
1320 $self->throw('filter', 'Recursive filter alias \"$name\"') if $seen_filters{$name} ++;
1321 $var = [$name, 0, '|', @$filter, @{$var}[$i..$#$var]]; # splice the filter into our current tree
1324 if (scalar keys %seen_filters
1325 && $seen_filters{$var->[$i - 5] || ''}) {
1326 $self->throw('filter', "invalid FILTER entry for '".$var->[$i - 5]."' (not a CODE ref)");
1334 ### method calls on objects
1335 if ($was_dot_call && UNIVERSAL
::can
($ref, 'can')) {
1336 my @args = $args ? map { $self->play_expr($_) } @$args : ();
1337 my @results = eval { $ref->$name(@args) };
1339 my $class = ref $ref;
1340 die $@ if ref $@ || $@ !~ /Can\'t locate object method "\Q$name\E" via package "\Q$class\E"/;
1341 } elsif (defined $results[0]) {
1342 $ref = ($#results > 0) ? \
@results : $results[0];
1344 } elsif (defined $results[1]) {
1345 die $results[1]; # TT behavior - why not just throw ?
1350 # didn't find a method by that name - so fail down to hash and array access
1353 ### hash member access
1354 if (UNIVERSAL
::isa
($ref, 'HASH')) {
1355 if ($was_dot_call && exists($ref->{$name}) ) {
1356 $ref = $ref->{$name};
1357 } elsif ($HASH_OPS->{$name}) {
1358 $ref = $HASH_OPS->{$name}->($ref, $args ? map { $self->play_expr($_) } @$args : ());
1359 } elsif ($ARGS->{'is_namespace_during_compile'}) {
1360 return $var; # abort - can't fold namespace variable
1366 } elsif (UNIVERSAL
::isa
($ref, 'ARRAY')) {
1367 if ($name =~ m{ ^ -? $QR_NUM $ }ox) {
1368 $ref = $ref->[$name];
1369 } elsif ($LIST_OPS->{$name}) {
1370 $ref = $LIST_OPS->{$name}->($ref, $args ? map { $self->play_expr($_) } @$args : ());
1379 ### allow for undefinedness
1380 if (! defined $ref) {
1381 if ($self->{'_debug_undef'}) {
1382 my $chunk = $var->[$i - 2];
1383 $chunk = $self->play_expr($chunk) if ref($chunk) eq 'ARRAY';
1384 die "$chunk is undefined\n";
1386 $ref = $self->undefined_any($var);
1394 my ($self, $var, $val, $ARGS) = @_;
1398 ### allow for the parse tree to store literals - the literal is used as a name (like [% 'a' = 'A' %])
1399 $var = [$var, 0] if ! ref $var;
1401 ### determine the top level of this particular variable access
1402 my $ref = $var->[$i++];
1403 my $args = $var->[$i++];
1405 if (ref($ref) eq 'ARRAY') { # named access (ie via $name.foo)
1406 $ref = $self->play_expr($ref);
1407 if (defined $ref && $ref !~ $QR_PRIVATE) { # don't allow vars that begin with _
1409 return $self->{'_vars'}->{$ref} = $val;
1411 $ref = $self->{'_vars'}->{$ref} ||= {};
1416 } else { # all other types can't be set
1419 } elsif (defined $ref) {
1420 return if $ref =~ $QR_PRIVATE; # don't allow vars that begin with _
1422 return $self->{'_vars'}->{$ref} = $val;
1424 $ref = $self->{'_vars'}->{$ref} ||= {};
1428 while (defined $ref) {
1430 ### check at each point if the returned thing was a code
1431 if (UNIVERSAL
::isa
($ref, 'CODE')) {
1432 my @results = $ref->($args ? map { $self->play_expr($_) } @$args : ());
1433 if (defined $results[0]) {
1434 $ref = ($#results > 0) ? \
@results : $results[0];
1435 } elsif (defined $results[1]) {
1436 die $results[1]; # TT behavior - why not just throw ?
1442 ### descend one chained level
1443 last if $i >= $#$var;
1444 my $was_dot_call = $ARGS->{'no_dots'} ? 1 : $var->[$i++] eq '.';
1445 my $name = $var->[$i++];
1446 my $args = $var->[$i++];
1448 ### allow for named portions of a variable name (foo.$name.bar)
1450 if (ref($name) eq 'ARRAY') {
1451 $name = $self->play_expr($name);
1452 if (! defined($name) || $name =~ /^[_.]/) {
1456 die "Shouldn't get a ".ref($name)." during a vivify on chain";
1459 if ($name =~ $QR_PRIVATE) { # don't allow vars that begin with _
1467 ### method calls on objects
1468 } elsif (UNIVERSAL
::can
($ref, 'can')) {
1470 my @args = $args ? map { $self->play_expr($_) } @$args : ();
1475 my @results = eval { $ref->$name(@args) };
1477 if (defined $results[0]) {
1478 $ref = ($#results > 0) ? \
@results : $results[0];
1479 } elsif (defined $results[1]) {
1480 die $results[1]; # TT behavior - why not just throw ?
1484 return if $lvalueish;
1487 my $class = ref $ref;
1488 die $@ if ref $@ || $@ !~ /Can\'t locate object method "\Q$name\E" via package "\Q$class\E"/;
1489 # fall on down to "normal" accessors
1492 ### hash member access
1493 if (UNIVERSAL
::isa
($ref, 'HASH')) {
1495 return $ref->{$name} = $val;
1497 $ref = $ref->{$name} ||= {};
1502 } elsif (UNIVERSAL
::isa
($ref, 'ARRAY')) {
1503 if ($name =~ m{ ^ -? $QR_NUM $ }ox) {
1505 return $ref->[$name] = $val;
1507 $ref = $ref->[$name] ||= {};
1521 ###----------------------------------------------------------------###
1527 if ($OP_DISPATCH->{$tree->[0]}) {
1529 if ($OP_ASSIGN->{$tree->[0]}) {
1530 my $val = $OP_DISPATCH->{$tree->[0]}->( $self->play_expr($tree->[1]), $self->play_expr($tree->[2]) );
1531 $self->set_variable($tree->[1], $val);
1534 return $OP_DISPATCH->{$tree->[0]}->( map { $self->play_expr($tree->[$_]) } 1 .. $#$tree );
1538 my $op = $tree->[0];
1540 ### do custom and short-circuitable operators
1542 my $val = $self->play_expr($tree->[2]);
1543 $self->set_variable($tree->[1], $val);
1546 } elsif ($op eq '||' || $op eq 'or' || $op eq 'OR') {
1547 return $self->play_expr($tree->[1]) || $self->play_expr($tree->[2]) || '';
1549 } elsif ($op eq '&&' || $op eq 'and' || $op eq 'AND') {
1550 my $var = $self->play_expr($tree->[1]) && $self->play_expr($tree->[2]);
1551 return $var ? $var : 0;
1553 } elsif ($op eq '?') {
1555 return $self->play_expr($tree->[1]) ? $self->play_expr($tree->[2]) : $self->play_expr($tree->[3]);
1557 } elsif ($op eq '++') {
1559 my $val = 0 + $self->play_expr($tree->[1]);
1560 $self->set_variable($tree->[1], $val + 1);
1561 return $tree->[2] ? $val : $val + 1; # ->[2] is set to 1 during parsing of postfix ops
1563 } elsif ($op eq '--') {
1565 my $val = 0 + $self->play_expr($tree->[1]);
1566 $self->set_variable($tree->[1], $val - 1);
1567 return $tree->[2] ? $val : $val - 1; # ->[2] is set to 1 during parsing of postfix ops
1570 $self->throw('operator', "Un-implemented operation $op");
1573 ###----------------------------------------------------------------###
1576 my ($self, $tag_ref, $node) = @_;
1578 my $block_name = '';
1579 if ($$tag_ref =~ s{ ^ (\w+ (?: :\w+)*) \s* (?! [\.\|]) }{}x
1580 || $$tag_ref =~ s{ ^ '(|.*?[^\\])' \s* (?! [\.\|]) }{}x
1581 || $$tag_ref =~ s{ ^ "(|.*?[^\\])" \s* (?! [\.\|]) }{}x
1584 ### allow for nested blocks to have nested names
1585 my @names = map {$_->[3]} grep {$_->[0] eq 'BLOCK'} @{ $self->{'_state'} };
1586 $block_name = join("/", @names, $block_name) if scalar @names;
1593 my ($self, $block_name, $node, $out_ref) = @_;
1595 ### store a named reference - but do nothing until something processes it
1596 $self->{'BLOCKS'}->{$block_name} = {
1597 _tree
=> $node->[4],
1598 name
=> $self->{'_vars'}->{'component'}->{'name'} .'/'. $block_name,
1604 sub parse_CALL
{ $DIRECTIVES->{'GET'}->[0]->(@_) }
1606 sub play_CALL
{ $DIRECTIVES->{'GET'}->[1]->(@_); return }
1609 my ($self, $tag_ref) = @_;
1610 return if $$tag_ref =~ s{ ^ DEFAULT \s* }{}x;
1611 return $self->parse_expr($tag_ref);
1615 my ($self, $tag_ref) = @_;
1616 return $self->parse_expr($tag_ref, {auto_quote
=> qr{ ^ (\w+ (?: \.\w+)*) $QR_AQ_SPACE }xo});
1620 my ($self, $undef, $node) = @_;
1621 $self->throw(lc($node->[0]), 'Control exception', $node);
1625 my ($self, $undef, $node, $out_ref) = @_;
1630 my ($self, $tag_ref) = @_;
1631 $$tag_ref =~ s{ ^ (on | off | format) \s* }{}xi || $self->throw('parse', "Unknown DEBUG option");
1633 if ($ret->[0] eq 'format') {
1634 $$tag_ref =~ s{ ^ ([\"\']) (|.*?[^\\]) \1 \s* }{}xs || $self->throw('parse', "Missing format string");
1641 my ($self, $ref) = @_;
1642 if ($ref->[0] eq 'on') {
1643 delete $self->{'_debug_off'};
1644 } elsif ($ref->[0] eq 'off') {
1645 $self->{'_debug_off'} = 1;
1646 } elsif ($ref->[0] eq 'format') {
1647 $self->{'_debug_format'} = $ref->[1];
1651 sub parse_DEFAULT
{ $DIRECTIVES->{'SET'}->[0]->(@_) }
1654 my ($self, $set) = @_;
1656 my ($op, $set, $default) = @$_;
1657 next if ! defined $set;
1658 my $val = $self->play_expr($set);
1660 $default = defined($default) ? $self->play_expr($default) : '';
1661 $self->set_variable($set, $default);
1668 my ($self, $tag_ref) = @_;
1669 my $ref = $self->parse_expr($tag_ref);
1674 my ($self, $ident, $node) = @_;
1675 require Data
::Dumper
;
1676 my $info = $self->node_info($node);
1680 $out = Data
::Dumper
::Dumper
($self->play_expr($ident));
1681 $var = $info->{'text'};
1682 $var =~ s/^[+\-~=]?\s*DUMP\s+//;
1683 $var =~ s/\s*[+\-~=]?$//;
1685 my @were_never_here = (qw(template component), grep {$_ =~ $QR_PRIVATE} keys %{ $self->{'_vars'} });
1686 local @{ $self->{'_vars'} }{ @were_never_here };
1687 delete @{ $self->{'_vars'} }{ @were_never_here };
1688 $out = Data
::Dumper
::Dumper
($self->{'_vars'});
1689 $var = 'EntireStash';
1691 if ($ENV{'REQUEST_METHOD'}) {
1693 $out = "<pre>$out</pre>";
1694 $out =~ s/\$VAR1/$var/;
1695 $out = "<b>DUMP: File \"$info->{file}\" line $info->{line}</b>$out";
1697 $out =~ s/\$VAR1/$var/;
1704 my ($self, $tag_ref) = @_;
1706 if ($$tag_ref =~ s{ ^ ([^\W\d]\w*) \s* = \s* }{}x) {
1710 my $filter = $self->parse_expr($tag_ref);
1711 $filter = '' if ! defined $filter;
1713 return [$name, $filter];
1717 my ($self, $ref, $node, $out_ref) = @_;
1718 my ($name, $filter) = @$ref;
1720 return '' if ! @$filter;
1722 $self->{'FILTERS'}->{$name} = $filter if length $name;
1724 my $sub_tree = $node->[4];
1728 eval { $self->execute_tree($sub_tree, \
$out) };
1729 die $@ if $@ && ref($@) !~ /Template::Exception$/;
1731 my $var = [\
$out, 0, '|', @$filter]; # make a temporary var out of it
1734 return $DIRECTIVES->{'GET'}->[1]->($self, $var, $node, $out_ref);
1738 my ($self, $tag_ref) = @_;
1739 my $items = $self->parse_expr($tag_ref);
1741 if ($$tag_ref =~ s{ ^ (= | [Ii][Nn]\b) \s* }{}x) {
1743 $items = $self->parse_expr($tag_ref);
1745 return [$var, $items];
1749 my ($self, $ref, $node, $out_ref) = @_;
1751 ### get the items - make sure it is an arrayref
1752 my ($var, $items) = @$ref;
1754 $items = $self->play_expr($items);
1755 return '' if ! defined $items;
1757 if (ref($items) !~ /Iterator$/) {
1758 $items = $PACKAGE_ITERATOR->new($items);
1761 my $sub_tree = $node->[4];
1763 local $self->{'_vars'}->{'loop'} = $items;
1765 ### if the FOREACH tag sets a var - then nothing but the loop var gets localized
1767 my ($item, $error) = $items->get_first;
1770 $self->set_variable($var, $item);
1772 ### execute the sub tree
1773 eval { $self->execute_tree($sub_tree, $out_ref) };
1775 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
1776 if ($err->type eq 'next') {
1777 ($item, $error) = $items->get_next;
1780 last if $err->type =~ /last|break/;
1785 ($item, $error) = $items->get_next;
1787 die $error if $error && $error != 3; # Template::Constants::STATUS_DONE;
1788 ### if the FOREACH tag doesn't set a var - then everything gets localized
1791 ### localize variable access for the foreach
1792 my $swap = $self->{'_vars'};
1793 local $self->{'_vars'} = my $copy = {%$swap};
1795 ### iterate use the iterator object
1796 #foreach (my $i = $items->index; $i <= $#$vals; $items->index(++ $i)) {
1797 my ($item, $error) = $items->get_first;
1800 if (ref($item) eq 'HASH') {
1801 @$copy{keys %$item} = values %$item;
1804 ### execute the sub tree
1805 eval { $self->execute_tree($sub_tree, $out_ref) };
1807 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
1808 if ($err->type eq 'next') {
1809 ($item, $error) = $items->get_next;
1812 last if $err->type =~ /last|break/;
1817 ($item, $error) = $items->get_next;
1819 die $error if $error && $error != 3; # Template::Constants::STATUS_DONE;
1826 my ($self, $tag_ref) = @_;
1827 my $ref = $self->parse_expr($tag_ref);
1828 $self->throw('parse', "Missing variable name") if ! defined $ref;
1833 my ($self, $ident, $node) = @_;
1834 my $var = $self->play_expr($ident);
1835 return (! defined $var) ? $self->undefined_get($ident, $node) : $var;
1839 my ($self, $tag_ref) = @_;
1840 return $self->parse_expr($tag_ref);
1844 my ($self, $var, $node, $out_ref) = @_;
1846 my $val = $self->play_expr($var);
1848 my $body_ref = $node->[4] ||= [];
1849 $self->execute_tree($body_ref, $out_ref);
1853 while ($node = $node->[5]) { # ELSE, ELSIF's
1854 if ($node->[0] eq 'ELSE') {
1855 my $body_ref = $node->[4] ||= [];
1856 $self->execute_tree($body_ref, $out_ref);
1859 my $var = $node->[3];
1860 my $val = $self->play_expr($var);
1862 my $body_ref = $node->[4] ||= [];
1863 $self->execute_tree($body_ref, $out_ref);
1870 sub parse_INCLUDE
{ $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
1873 my ($self, $tag_ref, $node, $out_ref) = @_;
1875 ### localize the swap
1876 my $swap = $self->{'_vars'};
1877 local $self->{'_vars'} = {%$swap};
1879 ### localize the blocks
1880 my $blocks = $self->{'BLOCKS'};
1881 local $self->{'BLOCKS'} = {%$blocks};
1883 my $str = $DIRECTIVES->{'PROCESS'}->[1]->($self, $tag_ref, $node, $out_ref);
1888 sub parse_INSERT
{ $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
1891 my ($self, $var, $node, $out_ref) = @_;
1892 my ($names, $args) = @$var;
1894 foreach my $name (@$names) {
1895 my $filename = $self->play_expr($name);
1896 $$out_ref .= $self->_insert($filename);
1903 my ($self, $tag_ref, $node) = @_;
1904 my $copy = $$tag_ref;
1906 my $name = $self->parse_expr(\
$copy, {auto_quote
=> qr{ ^ (\w+) $QR_AQ_NOTDOT }xo});
1907 $self->throw('parse', "Missing macro name") if ! defined $name;
1909 $name = [ $name, 0 ];
1913 if ($copy =~ s{ ^ \( \s* }{}x) {
1914 $args = $self->parse_args(\
$copy, {positional_only
=> 1});
1915 $copy =~ s
{ ^ \
) \s
* }{}x
|| $self->throw('parse.missing', "Missing close ')'");
1918 $node->[6] = 1; # set a flag to keep parsing
1920 return [$name, $args];
1924 my ($self, $ref, $node, $out_ref) = @_;
1925 my ($name, $args) = @$ref;
1927 ### get the sub tree
1928 my $sub_tree = $node->[4];
1929 if (! $sub_tree || ! $sub_tree->[0]) {
1930 $self->set_variable($name, undef);
1932 } elsif ($sub_tree->[0]->[0] eq 'BLOCK') {
1933 $sub_tree = $sub_tree->[0]->[4];
1936 my $self_copy = $self->weak_copy;
1938 ### install a closure in the stash that will handle the macro
1939 $self->set_variable($name, sub {
1941 my $copy = $self_copy->{'_vars'};
1942 local $self_copy->{'_vars'}= {%$copy};
1945 my $named = pop(@_) if $_[-1] && UNIVERSAL
::isa
($_[-1],'HASH') && $#_ > $#$args;
1946 my @positional = @_;
1947 foreach my $var (@$args) {
1948 $self_copy->set_variable($var, shift(@positional));
1950 foreach my $name (sort keys %$named) {
1951 $self_copy->set_variable([$name, 0], $named->{$name});
1954 ### finally - run the sub tree
1956 $self_copy->execute_tree($sub_tree, \
$out);
1964 my ($self, $hash) = @_;
1966 if ($self->{'_top_level'}) {
1967 $ref = $self->{'_vars'}->{'template'} ||= {};
1969 $ref = $self->{'_vars'}->{'component'} ||= {};
1971 foreach my $key (keys %$hash) {
1972 next if $key eq 'name' || $key eq 'modtime';
1973 $ref->{$key} = $hash->{$key};
1978 sub parse_PERL
{ shift-
>{'_in_perl'} = 1; return }
1981 my ($self, $info, $node, $out_ref) = @_;
1982 $self->throw('perl', 'EVAL_PERL not set') if ! $self->{'EVAL_PERL'};
1984 ### fill in any variables
1985 my $perl = $node->[4] || return;
1987 $self->execute_tree($perl, \
$out);
1988 $out = $1 if $out =~ /^(.+)$/s; # blatant untaint - shouldn't use perl anyway
1993 package CGI
::Ex
::Template
::Perl
;
1995 my $context = $self->context;
1996 my $stash = $context->stash;
1998 ### setup a fake handle
2000 tie
*PERLOUT
, $CGI::Ex
::Template
::PACKAGE_PERL_HANDLE
, $out_ref;
2001 my $old_fh = select PERLOUT
;
2006 ### put the handle back
2014 $self->throw('undef', $err) if ref($err) !~ /Template::Exception$/;
2022 my ($self, $tag_ref) = @_;
2023 my $info = [[], []];
2024 while (defined(my $filename = $self->parse_expr($tag_ref, {
2025 auto_quote
=> qr{ ^ ($QR_FILENAME | \w+ (?: :\w+)* ) $QR_AQ_SPACE }xo,
2027 push @{$info->[0]}, $filename;
2028 last if $$tag_ref !~ s{ ^ \+ \s* }{}x;
2031 ### allow for post process variables
2032 while (length $$tag_ref) {
2033 last if $$tag_ref =~ / ^ (\w+) (?: ;|$|\s)/x && $DIRECTIVES->{$1}; ### looks like a directive - we are done
2035 my $var = $self->parse_expr($tag_ref);
2036 last if ! defined $var;
2037 if ($$tag_ref !~ s{ ^ = >? \s* }{}x) {
2038 $self->throw('parse.missing.equals', 'Missing equals while parsing args');
2041 my $val = $self->parse_expr($tag_ref);
2042 push @{$info->[1]}, [$var, $val];
2043 $$tag_ref =~ s{ ^ , \s* $QR_COMMENTS }{}ox if $val;
2050 my ($self, $info, $node, $out_ref) = @_;
2052 my ($files, $args) = @$info;
2056 my ($key, $val) = @$_;
2057 $val = $self->play_expr($val);
2058 if (ref($key) && @$key == 2 && $key->[0] eq 'import' && UNIVERSAL
::isa
($val, 'HASH')) { # import ?! - whatever
2059 foreach my $key (keys %$val) {
2060 $self->set_variable([$key,0], $val->{$key});
2064 $self->set_variable($key, $val);
2067 ### iterate on any passed block or filename
2068 foreach my $ref (@$files) {
2069 next if ! defined $ref;
2070 my $filename = $self->play_expr($ref);
2071 my $out = ''; # have temp item to allow clear to correctly clear
2073 ### normal blocks or filenames
2074 if (! ref $filename) {
2075 eval { $self->_process($filename, $self->{'_vars'}, \
$out) }; # restart the swap - passing it our current stash
2077 ### allow for $template which is used in some odd instances
2079 $self->throw('process', "Unable to process document $filename") if $ref->[0] ne 'template';
2080 $self->throw('process', "Recursion detected in $node->[0] \$template") if $self->{'_process_dollar_template'};
2081 local $self->{'_process_dollar_template'} = 1;
2082 local $self->{'_vars'}->{'component'} = my $doc = $filename;
2083 return if ! $doc->{'_tree'};
2085 ### execute and trim
2086 eval { $self->execute_tree($doc->{'_tree'}, \
$out) };
2087 if ($self->{'TRIM'}) {
2088 $out =~ s{ \s+ $ }{}x;
2089 $out =~ s{ ^ \s+ }{}x;
2092 ### handle exceptions
2094 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2095 $err->doc($doc) if $doc && $err->can('doc') && ! $err->doc;
2100 ### append any output
2103 die $err if ref($err) !~ /Template::Exception$/ || $err->type !~ /return/;
2111 my ($self, $info, $node, $out_ref) = @_;
2112 $self->throw('perl', 'EVAL_PERL not set') if ! $self->{'EVAL_PERL'};
2114 ### fill in any variables
2115 my $tree = $node->[4] || return;
2117 $self->execute_tree($tree, \
$perl);
2118 $perl = $1 if $perl =~ /^(.+)$/s; # blatant untaint - shouldn't use perl anyway
2124 package CGI
::Ex
::Template
::Perl
;
2126 my $context = $self->context;
2127 my $stash = $context->stash;
2134 $$out_ref .= $output;
2137 $self->throw('undef', $err) if ref($err) !~ /Template::Exception$/;
2145 my ($self, $tag_ref, $node, $initial_op, $initial_var) = @_;
2147 my $copy = $$tag_ref;
2151 if ($$tag_ref =~ $QR_DIRECTIVE # find a word
2152 && $DIRECTIVES->{$1}) { # is it a directive - if so set up capturing
2153 $node->[6] = 1; # set a flag to keep parsing
2154 my $val = $node->[4] ||= []; # setup storage
2155 return [[$initial_op, $initial_var, $val]];
2156 } else { # get a normal variable
2157 return [[$initial_op, $initial_var, $self->parse_expr($tag_ref)]];
2161 while (length $$tag_ref) {
2162 my $set = $self->parse_expr($tag_ref);
2163 last if ! defined $set;
2165 if ($$tag_ref =~ s{ ^ ($QR_OP_ASSIGN) >? \s* }{}x) {
2167 if ($$tag_ref =~ $QR_DIRECTIVE # find a word
2168 && $DIRECTIVES->{$1}) { # is it a directive - if so set up capturing
2169 $node->[6] = 1; # set a flag to keep parsing
2170 my $val = $node->[4] ||= []; # setup storage
2171 push @SET, [$op, $set, $val];
2173 } else { # get a normal variable
2174 push @SET, [$op, $set, $self->parse_expr($tag_ref)];
2177 push @SET, ['=', $set, undef];
2184 my ($self, $set, $node) = @_;
2186 my ($op, $set, $val) = @$_;
2187 if (! defined $val) { # not defined
2189 } elsif ($node->[4] && $val == $node->[4]) { # a captured directive
2190 my $sub_tree = $node->[4];
2191 $sub_tree = $sub_tree->[0]->[4] if $sub_tree->[0] && $sub_tree->[0]->[0] eq 'BLOCK';
2193 $self->execute_tree($sub_tree, \
$val);
2194 } else { # normal var
2195 $val = $self->play_expr($val);
2198 if ($OP_DISPATCH->{$op}) {
2200 $val = $OP_DISPATCH->{$op}->($self->play_expr($set), $val);
2203 $self->set_variable($set, $val);
2208 sub parse_SWITCH
{ $DIRECTIVES->{'GET'}->[0]->(@_) }
2211 my ($self, $var, $node, $out_ref) = @_;
2213 my $val = $self->play_expr($var);
2214 $val = '' if ! defined $val;
2215 ### $node->[4] is thrown away
2218 while ($node = $node->[5]) { # CASES
2219 my $var = $node->[3];
2220 if (! defined $var) {
2221 $default = $node->[4];
2225 my $val2 = $self->play_expr($var);
2226 $val2 = [$val2] if ! UNIVERSAL
::isa
($val2, 'ARRAY');
2227 for my $test (@$val2) { # find matching values
2228 next if ! defined $val && defined $test;
2229 next if defined $val && ! defined $test;
2230 if ($val ne $test) { # check string-wise first - then numerical
2231 next if $val !~ m{ ^ -? $QR_NUM $ }ox;
2232 next if $test !~ m{ ^ -? $QR_NUM $ }ox;
2233 next if $val != $test;
2236 my $body_ref = $node->[4] ||= [];
2237 $self->execute_tree($body_ref, $out_ref);
2243 $self->execute_tree($default, $out_ref);
2250 my ($self, $tag_ref, $node) = @_;
2251 my $name = $self->parse_expr($tag_ref, {auto_quote
=> qr{ ^ (\w+ (?: \.\w+)*) $QR_AQ_SPACE }xo});
2252 $self->throw('parse.missing', "Missing name in THROW", $node) if ! $name;
2253 my $args = $self->parse_args($tag_ref);
2254 return [$name, $args];
2258 my ($self, $ref, $node) = @_;
2259 my ($name, $args) = @$ref;
2260 $name = $self->play_expr($name);
2261 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2262 $self->throw($name, \
@args, $node);
2266 my ($self, $foo, $node, $out_ref) = @_;
2269 my $body_ref = $node->[4];
2270 eval { $self->execute_tree($body_ref, \
$out) };
2273 if (! $node->[5]) { # no catch or final
2274 if (! $err) { # no final block and no error
2278 $self->throw('parse.missing', "Missing CATCH block", $node);
2281 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2282 if ($err->type =~ /stop|return/) {
2288 ### loop through the nested catch and final blocks
2291 my $type = $err ? $err->type : '';
2293 while ($node = $node->[5]) { # CATCH
2294 if ($node->[0] eq 'FINAL') {
2295 $final = $node->[4];
2299 my $name = $self->play_expr($node->[3]);
2300 $name = '' if ! defined $name || lc($name) eq 'default';
2301 if ($type =~ / ^ \Q$name\E \b /x
2302 && (! defined($last_found) || length($last_found) < length($name))) { # more specific wins
2303 $catch_body_ref = $node->[4] || [];
2304 $last_found = $name;
2308 ### play the best catch block
2310 if (! $catch_body_ref) {
2314 local $self->{'_vars'}->{'error'} = $err;
2315 local $self->{'_vars'}->{'e'} = $err;
2316 eval { $self->execute_tree($catch_body_ref, \
$out) };
2324 $self->execute_tree($final, \
$out) if $final;
2332 my $ref = $DIRECTIVES->{'IF'}->[0]->(@_);
2333 return [ \
[ '!', $ref ], 0 ];
2336 sub play_UNLESS
{ return $DIRECTIVES->{'IF'}->[1]->(@_) }
2339 my ($self, $tag_ref) = @_;
2342 my $copy = $$tag_ref;
2343 if (defined(my $_var = $self->parse_expr(\
$copy, {auto_quote
=> qr{ ^ (\w+) $QR_AQ_NOTDOT }xo}))
2344 && $copy =~ s{ ^ = >? \s* $QR_COMMENTS }{}ox) {
2350 my $module = $self->parse_expr(\
$copy, {auto_quote
=> qr{ ^ (\w+ (?: (?:\.|::) \w+)*) $QR_AQ_NOTDOT }xo});
2351 $self->throw('parse', "Missing plugin name while parsing $$tag_ref") if ! defined $module;
2352 $module =~ s/\./::/g;
2355 my $open = $copy =~ s{ ^ \( \s* $QR_COMMENTS }{}ox;
2356 $args = $self->parse_args(\
$copy);
2359 $copy =~ s
{ ^ \
) \s
* $QR_COMMENTS }{}ox
|| $self->throw('parse.missing', "Missing close ')'");
2363 return [$var, $module, $args];
2367 my ($self, $ref, $node, $out_ref) = @_;
2368 my ($var, $module, $args) = @$ref;
2370 ### get the stash storage location - default to the module
2371 $var = $module if ! defined $var;
2372 my @var = map {($_, 0, '.')} split /(?:\.|::)/, $var;
2373 pop @var; # remove the trailing '.'
2375 ### look for a plugin_base
2376 my $base = $self->{'PLUGIN_BASE'} || 'Template::Plugin'; # I'm not maintaining plugins - leave that to TT
2377 my $package = $self->{'PLUGINS'}->{$module} ? $self->{'PLUGINS'}->{$module}
2378 : $self->{'PLUGIN_FACTORY'}->{$module} ? $self->{'PLUGIN_FACTORY'}->{$module}
2379 : "${base}::${module}";
2380 my $require = "$package.pm";
2381 $require =~ s
|::|/|g
;
2383 ### try and load the module - fall back to bare module if allowed
2385 if ($self->{'PLUGIN_FACTORY'}->{$module} || eval {require $require}) {
2386 my $shape = $package->load;
2387 my $context = $self->context;
2388 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2389 $obj = $shape->new($context, @args);
2390 } elsif (lc($module) eq 'iterator') { # use our iterator if none found (TT's works just fine)
2391 $obj = $PACKAGE_ITERATOR->new($args ? $self->play_expr($args->[0]) : []);
2392 } elsif (my @packages = grep {lc($package) eq lc($_)} @{ $self->list_plugins({base
=> $base}) }) {
2393 foreach my $package (@packages) {
2394 my $require = "$package.pm";
2395 $require =~ s
|::|/|g
;
2396 eval {require $require} || next;
2397 my $shape = $package->load;
2398 my $context = $self->context;
2399 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2400 $obj = $shape->new($context, @args);
2402 } elsif ($self->{'LOAD_PERL'}) {
2403 my $require = "$module.pm";
2404 $require =~ s
|::|/|g
;
2405 if (eval {require $require}) {
2406 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2407 $obj = $module->new(@args);
2410 if (! defined $obj) {
2411 my $err = "$module: plugin not found";
2412 $self->throw('plugin', $err);
2416 $self->set_variable(\
@var, $obj);
2422 my ($self, $var, $node, $out_ref) = @_;
2423 return '' if ! defined $var;
2425 my $sub_tree = $node->[4];
2427 ### iterate use the iterator object
2428 my $count = $WHILE_MAX;
2429 while (--$count > 0) {
2431 $self->play_expr($var) || last;
2433 ### execute the sub tree
2434 eval { $self->execute_tree($sub_tree, $out_ref) };
2436 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
2437 next if $err->type =~ /next/;
2438 last if $err->type =~ /last|break/;
2443 die "WHILE loop terminated (> $WHILE_MAX iterations)\n" if ! $count;
2448 sub parse_WRAPPER
{ $DIRECTIVES->{'INCLUDE'}->[0]->(@_) }
2451 my ($self, $var, $node, $out_ref) = @_;
2452 my $sub_tree = $node->[4] || return;
2454 my ($names, $args) = @$var;
2457 $self->execute_tree($sub_tree, \
$out);
2459 foreach my $name (reverse @$names) {
2460 local $self->{'_vars'}->{'content'} = $out;
2462 $DIRECTIVES->{'INCLUDE'}->[1]->($self, [[$name], $args], $node, \
$out);
2469 ###----------------------------------------------------------------###
2473 $self->{'_vars'} = shift if $#_ == 0;
2474 return $self->{'_vars'} ||= {};
2477 sub include_filename
{
2478 my ($self, $file) = @_;
2479 if ($file =~ m
|^/|) {
2480 $self->throw('file', "$file absolute paths are not allowed (set ABSOLUTE option)") if ! $self->{'ABSOLUTE'};
2481 return $file if -e
$file;
2482 } elsif ($file =~ m{(^|/)\.\./}) {
2483 $self->throw('file', "$file relative paths are not allowed (set RELATIVE option)") if ! $self->{'RELATIVE'};
2484 return $file if -e
$file;
2487 my $paths = $self->{'INCLUDE_PATHS'} ||= do {
2488 # TT does this everytime a file is looked up - we are going to do it just in time - the first time
2489 my $paths = $self->{'INCLUDE_PATH'} || $self->throw('file', "INCLUDE_PATH not set");
2490 $paths = $paths->() if UNIVERSAL
::isa
($paths, 'CODE');
2491 $paths = $self->split_paths($paths) if ! UNIVERSAL
::isa
($paths, 'ARRAY');
2492 $paths; # return of the do
2494 foreach my $path (@$paths) {
2495 return "$path/$file" if -e
"$path/$file";
2498 $self->throw('file', "$file: not found");
2502 my ($self, $path) = @_;
2503 return $path if ref $path;
2504 my $delim = $self->{'DELIMITER'} || ':';
2505 $delim = ($delim eq ':' && $^O eq 'MSWin32') ? qr
|:(?!/)| : qr
|\Q
$delim\E
|;
2506 return [split $delim, $path];
2510 my ($self, $file) = @_;
2511 return $self->slurp($self->include_filename($file));
2515 my ($self, $file) = @_;
2517 open(FH
, "<$file") || $self->throw('file', "$file couldn't be opened: $!");
2518 read FH
, my $txt, -s
$file;
2523 sub process_simple
{
2525 my $in = shift || die "Missing input";
2526 my $swap = shift || die "Missing variable hash";
2527 my $out = shift || die "Missing output string ref";
2530 delete $self->{'_debug_off'};
2531 delete $self->{'_debug_format'};
2532 local $self->{'_start_top_level'} = 1;
2533 $self->_process($in, $swap, $out);
2536 if ($err->type !~ /stop|return|next|last|break/) {
2537 $self->{'error'} = $err;
2545 my ($self, $in, $swap, $out, @ARGS) = @_;
2546 delete $self->{'error'};
2549 $args = ($#ARGS == 0 && UNIVERSAL
::isa
($ARGS[0], 'HASH')) ? {%{$ARGS[0]}} : {@ARGS} if scalar @ARGS;
2550 $self->DEBUG("set binmode\n") if $DEBUG && $args->{'binmode'}; # holdover for TT2 tests
2555 if (UNIVERSAL
::isa
($in, 'SCALAR')) { # reference to a string
2557 } elsif (UNIVERSAL
::isa
($in, 'CODE')) {
2559 $content = \
$content;
2560 } else { # should be a file handle
2563 $content = \
$content;
2566 ### should be a filename
2571 ### prepare block localization
2572 my $blocks = $self->{'BLOCKS'} ||= {};
2579 ### localize the stash
2581 my $var1 = $self->{'_vars'} ||= {};
2582 my $var2 = $self->{'VARIABLES'} || $self->{'PRE_DEFINE'} || {};
2583 $var1->{'global'} ||= {}; # allow for the "global" namespace - that continues in between processing
2584 my $copy = {%$var2, %$var1, %$swap};
2585 local $copy->{'template'};
2587 local $self->{'BLOCKS'} = $blocks = {%$blocks}; # localize blocks - but save a copy to possibly restore
2589 delete $self->{'_debug_off'};
2590 delete $self->{'_debug_format'};
2592 ### handle pre process items that go before every document
2593 if ($self->{'PRE_PROCESS'}) {
2594 foreach my $name (@{ $self->split_paths($self->{'PRE_PROCESS'}) }) {
2596 $self->_process($name, $copy, \
$out);
2597 $output = $out . $output;
2601 ### handle the process config - which loads a template in place of the real one
2602 if (exists $self->{'PROCESS'}) {
2603 ### load the meta data for the top document
2604 my $doc = $self->load_parsed_tree($content) || {};
2605 my $meta = ($doc->{'_tree'} && ref($doc->{'_tree'}->[0]) && $doc->{'_tree'}->[0]->[0] eq 'METADEF')
2606 ? $doc->{'_tree'}->[0]->[3] : {};
2608 $copy->{'template'} = $doc;
2609 @{ $doc }{keys %$meta} = values %$meta;
2611 ### process any other templates
2612 foreach my $name (@{ $self->split_paths($self->{'PROCESS'}) }) {
2613 next if ! length $name;
2614 $self->_process($name, $copy, \
$output);
2617 ### handle "normal" content
2619 local $self->{'_start_top_level'} = 1;
2620 $self->_process($content, $copy, \
$output);
2624 ### handle post process items that go after every document
2625 if ($self->{'POST_PROCESS'}) {
2626 foreach my $name (@{ $self->split_paths($self->{'POST_PROCESS'}) }) {
2627 $self->_process($name, $copy, \
$output);
2633 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2634 if ($err->type !~ /stop|return|next|last|break/) {
2635 $self->{'error'} = $err;
2642 ### clear blocks as asked (AUTO_RESET) defaults to on
2643 $self->{'BLOCKS'} = $blocks if exists($self->{'AUTO_RESET'}) && ! $self->{'AUTO_RESET'};
2645 ### send the content back out
2646 $out ||= $self->{'OUTPUT'};
2648 if (UNIVERSAL
::isa
($out, 'CODE')) {
2650 } elsif (UNIVERSAL
::can
($out, 'print')) {
2651 $out->print($output);
2652 } elsif (UNIVERSAL
::isa
($out, 'SCALAR')) { # reference to a string
2654 } elsif (UNIVERSAL
::isa
($out, 'ARRAY')) {
2655 push @$out, $output;
2656 } else { # should be a file handle
2659 } elsif ($out) { # should be a filename
2661 if ($out =~ m
|^/|) {
2662 if (! $self->{'ABSOLUTE'}) {
2663 $self->{'error'} = $self->throw('file', "ABSOLUTE paths disabled");
2667 } elsif ($out =~ m
|^\
.\
.?/|) {
2668 if (! $self->{'RELATIVE'}) {
2669 $self->{'error'} = $self->throw('file', "RELATIVE paths disabled");
2674 if (! $self->{'OUTPUT_PATH'}) {
2675 $self->{'error'} = $self->throw('file', "OUTPUT_PATH not set");
2677 $file = $self->{'OUTPUT_PATH'} . '/' . $out;
2682 if (open FH
, ">$file") {
2683 if (my $bm = $args->{'binmode'}) {
2684 if (+$bm == 1) { binmode FH
}
2685 else { binmode FH
, $bm }
2690 $self->{'error'} = $self->throw('file', "$out couldn't be opened for writing: $!");
2697 return if $self->{'error'};
2701 sub error
{ shift-
>{'error'} }
2705 print STDERR
"DEBUG: ", @_;
2708 ###----------------------------------------------------------------###
2711 my ($self, $type, $info, $node) = @_;
2712 return $type if ref($type) =~ /Template::Exception$/;
2713 if (ref($info) eq 'ARRAY') {
2714 my $hash = ref($info->[-1]) eq 'HASH' ? pop(@$info) : {};
2715 if (@$info >= 2 || scalar keys %$hash) {
2717 $hash->{$_} = $info->[$_] for 0 .. $#$info;
2718 $hash->{'args'} = $info;
2720 } elsif (@$info == 1) {
2727 return $PACKAGE_EXCEPTION->new($type, $info, $node);
2730 sub throw
{ die shift-
>exception(@_) }
2734 return bless {_template
=> $self}, $PACKAGE_CONTEXT; # a fake context
2738 my ($self, $ident, $node) = @_;
2739 return $self->{'UNDEFINED_GET'}->($self, $ident, $node) if $self->{'UNDEFINED_GET'};
2744 my ($self, $ident) = @_;
2745 return $self->{'UNDEFINED_ANY'}->($self, $ident) if $self->{'UNDEFINED_ANY'};
2751 return $self->{'_filters'} ||= eval { require Template
::Filters
; $Template::Filters
::FILTERS
} || {};
2756 my $args = shift || {};
2757 my $base = $args->{'base'} || '';
2759 return $self->{'_plugins'}->{$base} ||= do {
2763 my @dirs = grep {-d
$_} map {"$_/$base"} @INC;
2765 foreach my $dir (@dirs) {
2767 File
::Find
::find
(sub {
2768 my $mod = $base .'/'. ($File::Find
::name
=~ m
|^ $dir / (.*\w
) \
.pm
$|x
? $1 : return);
2770 push @plugins, $mod;
2774 \
@plugins; # return of the do
2778 ### get a copy of self without circular refs for use in closures
2782 if (eval { require Scalar
::Util
}
2783 && defined &Scalar
::Util
::weaken
) {
2785 Scalar
::Util
::weaken
($self_copy);
2787 $self_copy = bless {%$self}, ref($self); # hackish way to avoid circular refs on old perls (pre 5.8)
2793 my ($self, $node) = @_;
2794 my $info = $self->node_info($node);
2795 my $format = $self->{'_debug_format'} || $self->{'DEBUG_FORMAT'} || "\n## \$file line \$line : [% \$text %] ##\n";
2796 $format =~ s{\$(file|line|text)}{$info->{$1}}g
;
2801 my ($self, $node) = @_;
2802 my $doc = $self->{'_vars'}->{'component'};
2804 my $j = $node->[2] || return ''; # METADEF can be 0
2805 $doc->{'_content'} ||= do { my $s = $self->slurp($doc->{'_filename'}) ; \
$s };
2806 my $s = substr(${ $doc->{'_content'} }, $i, $j - $i);
2810 file
=> $doc->{'name'},
2811 line
=> $self->get_line_number_by_index($doc, $i),
2816 sub get_line_number_by_index
{
2817 my ($self, $doc, $index) = @_;
2818 ### get the line offsets for the doc
2819 my $lines = $doc->{'line_offsets'} ||= do {
2820 $doc->{'_content'} ||= do { my $s = $self->slurp($doc->{'_filename'}) ; \
$s };
2824 $i = index(${ $doc->{'_content'} }, "\n", $i) + 1;
2830 ### binary search them (this is fast even on big docs)
2831 return $#$lines + 1 if $index > $lines->[-1];
2832 my ($i, $j) = (0, $#$lines);
2834 return $i + 1 if abs($i - $j) <= 1;
2835 my $k = int(($i + $j) / 2);
2836 $j = $k if $lines->[$k] >= $index;
2837 $i = $k if $lines->[$k] <= $index;
2841 ###----------------------------------------------------------------###
2842 ### long virtual methods or filters
2843 ### many of these vmethods have used code from Template/Stash.pm to
2844 ### assure conformance with the TT spec.
2846 sub define_vmethod
{
2847 my ($self, $type, $name, $sub) = @_;
2848 if ( $type =~ /scalar|item/i) { $SCALAR_OPS->{$name} = $sub }
2849 elsif ($type =~ /array|list/i ) { $LIST_OPS->{ $name} = $sub }
2850 elsif ($type =~ /hash/i ) { $HASH_OPS->{ $name} = $sub }
2851 elsif ($type =~ /filter/i ) { $FILTER_OPS->{$name} = $sub }
2853 die "Invalid type vmethod type $type";
2858 sub vmethod_as_scalar
{
2859 my ($str, $pat) = @_;
2860 $pat = '%s' if ! defined $pat;
2862 return sprintf $pat, $str;
2865 sub vmethod_as_list
{
2866 my ($ref, $pat, $sep) = @_;
2867 $pat = '%s' if ! defined $pat;
2868 $sep = ' ' if ! defined $sep;
2870 return join($sep, map {sprintf $pat, $_} @$ref);
2873 sub vmethod_as_hash
{
2874 my ($ref, $pat, $sep) = @_;
2875 $pat = "%s\t%s" if ! defined $pat;
2876 $sep = "\n" if ! defined $sep;
2878 return join($sep, map {sprintf $pat, $_, $ref->{$_}} sort keys %$ref);
2883 my $size = shift || 1;
2885 if ($size < 0) { # chunk from the opposite end
2886 $str = reverse $str;
2888 unshift(@list, scalar reverse $1) while $str =~ /( .{$size} | .+ )/xg;
2890 push(@list, $1) while $str =~ /( .{$size} | .+ )/xg;
2895 sub vmethod_indent
{
2896 my $str = shift; $str = '' if ! defined $str;
2897 my $pre = shift; $pre = 4 if ! defined $pre;
2898 $pre = ' ' x
$pre if $pre =~ /^\d+$/;
2899 $str =~ s/^/$pre/mg;
2903 sub vmethod_format
{
2904 my $str = shift; $str = '' if ! defined $str;
2905 my $pat = shift; $pat = '%s' if ! defined $pat;
2906 return join "\n", map{ sprintf $pat, $_ } split(/\n/, $str);
2910 my ($str, $pat, $global) = @_;
2911 return [] if ! defined $str || ! defined $pat;
2912 my @res = $global ? ($str =~ /$pat/g) : ($str =~ /$pat/);
2913 return (@res >= 2) ? \
@res : (@res == 1) ? $res[0] : '';
2917 my ($list, $field) = @_;
2918 return defined($field)
2919 ? [map {$_->[0]} sort {$a->[1] <=> $b->[1]} map {[$_, (ref $_ eq 'HASH' ? $_->{$field}
2920 : UNIVERSAL
::can
($_, $field) ? $_->$field()
2922 : [sort {$a <=> $b} @$list];
2925 sub vmethod_repeat
{
2926 my ($str, $n, $join) = @_;
2927 return if ! length $str;
2928 $n = 1 if ! defined($n) || ! length $n;
2929 $join = '' if ! defined $join;
2930 return join $join, ($str) x
$n;
2933 ### This method is a combination of my submissions along
2934 ### with work from Andy Wardley, Sergey Martynoff, Nik Clayton, and Josh Rosenbaum
2935 sub vmethod_replace
{
2936 my ($text, $pattern, $replace, $global) = @_;
2937 $text = '' unless defined $text;
2938 $pattern = '' unless defined $pattern;
2939 $replace = '' unless defined $replace;
2940 $global = 1 unless defined $global;
2942 my ($chunk, $start, $end) = @_;
2943 $chunk =~ s
{ \\(\\|\
$) | \
$ (\d
+) }{
2945 : ($2 > $#$start || $2 == 0) ? ''
2946 : substr($text, $start->[$2], $end->[$2] - $start->[$2]);
2951 $text =~ s{$pattern}{ $expand->($replace, [@-], [@+]) }eg;
2953 $text =~ s{$pattern}{ $expand->($replace, [@-], [@+]) }e;
2959 my ($list, $field) = @_;
2960 return defined($field)
2961 ? [map {$_->[0]} sort {$a->[1] cmp $b->[1]} map {[$_, lc(ref $_ eq 'HASH' ? $_->{$field}
2962 : UNIVERSAL
::can
($_, $field) ? $_->$field()
2964 : [map {$_->[0]} sort {$a->[1] cmp $b->[1]} map {[$_, lc $_]} @$list ]; # case insensitive
2967 sub vmethod_splice
{
2968 my ($ref, $i, $len, @replace) = @_;
2969 @replace = @{ $replace[0] } if @replace == 1 && ref $replace[0] eq 'ARRAY';
2971 return [splice @$ref, $i || 0, $len, @replace];
2973 return [splice @$ref, $i || 0];
2978 my ($str, $pat, @args) = @_;
2979 $str = '' if ! defined $str;
2980 return defined $pat ? [split $pat, $str, @args] : [split ' ', $str, @args];
2985 utf8
::encode
($str) if defined &utf8
::encode
;
2986 $str =~ s/([^A-Za-z0-9\-_.!~*\'()])/sprintf('%%%02X', ord($1))/eg;
2991 my $context = shift;
2994 return $context->process(\
$text);
2998 sub filter_redirect
{
2999 my ($context, $file, $options) = @_;
3000 my $path = $context->config->{'OUTPUT_PATH'} || $context->throw('redirect', 'OUTPUT_PATH is not set');
3001 $context->throw('redirect', 'Invalid filename - cannot include "/../"')
3002 if $file =~ m{(^|/)\.\./};
3008 File
::Path
::mkpath
($path) || $context->throw('redirect', "Couldn't mkpath \"$path\": $!");
3011 open (FH
, ">$path/$file") || $context->throw('redirect', "Couldn't open \"$file\": $!");
3012 if (my $bm = (! $options) ? 0 : ref($options) ? $options->{'binmode'} : $options) {
3013 if (+$bm == 1) { binmode FH
}
3014 else { binmode FH
, $bm}
3022 ###----------------------------------------------------------------###
3025 my $obj = UNIVERSAL
::isa
($_[0], __PACKAGE__
) ? shift : __PACKAGE__-
>new;
3027 require Data
::Dumper
;
3028 return Data
::Dumper
::Dumper
($obj->parse_expr(\
$str));
3031 ###----------------------------------------------------------------###
3033 package CGI
::Ex
::Template
::Exception
;
3036 '""' => \
&as_string
,
3037 bool
=> sub { defined shift },
3041 my ($class, $type, $info, $node, $pos, $str_ref) = @_;
3042 return bless [$type, $info, $node, $pos, $str_ref], $class;
3045 sub type
{ shift-
>[0] }
3047 sub info
{ shift-
>[1] }
3051 $self->[2] = shift if $#_ == 0;
3055 sub offset
{ shift-
>[3] || 0 }
3059 $self->[4] = shift if $#_ == 0;
3065 my $msg = $self->type .' error - '. $self->info;
3066 if (my $node = $self->node) {
3067 # $msg .= " (In tag $node->[0] starting at char ".($node->[1] + $self->offset).")";
3072 ###----------------------------------------------------------------###
3074 package CGI
::Ex
::Template
::Iterator
;
3077 my ($class, $items) = @_;
3078 $items = [] if ! defined $items;
3079 if (UNIVERSAL
::isa
($items, 'HASH')) {
3080 $items = [ map { {key
=> $_, value
=> $items->{ $_ }} } sort keys %$items ];
3081 } elsif (UNIVERSAL
::can
($items, 'as_list')) {
3082 $items = $items->as_list;
3083 } elsif (! UNIVERSAL
::isa
($items, 'ARRAY')) {
3086 return bless [$items, 0], $class;
3091 return (undef, 3) if ! @{ $self->[0] };
3092 return ($self->[0]->[$self->[1] = 0], undef);
3097 return (undef, 3) if ++ $self->[1] > $#{ $self->[0] };
3098 return ($self->items->[$self->[1]], undef);
3101 sub items
{ shift-
>[0] }
3103 sub index { shift-
>[1] }
3105 sub max
{ $#{ shift-
>[0] } }
3107 sub size
{ shift-
>max + 1 }
3109 sub count
{ shift-
>index + 1 }
3111 sub number
{ shift-
>index + 1 }
3113 sub first
{ (shift-
>index == 0) || 0 }
3115 sub last { my $self = shift; return ($self->index == $self->max) || 0 }
3119 return undef if $self->index <= 0;
3120 return $self->items->[$self->index - 1];
3125 return undef if $self->index >= $self->max;
3126 return $self->items->[$self->index + 1];
3129 ###----------------------------------------------------------------###
3131 package CGI
::Ex
::Template
::_Context
;
3133 use vars
qw($AUTOLOAD);
3135 sub _template
{ shift-
>{'_template'} || die "Missing _template" }
3137 sub config
{ shift-
>_template }
3141 return $self->{'stash'} ||= bless {_template
=> $self->_template}, $CGI::Ex
::Template
::PACKAGE_STASH
;
3144 sub insert
{ shift-
>_template->_insert(@_) }
3146 sub eval_perl
{ shift-
>_template->{'EVAL_PERL'} }
3151 my $vars = $self->_template->_vars;
3153 $self->_template->_process($ref, $vars, \
$out);
3160 my $args = shift || {};
3162 $self->_template->set_variable($_, $args->{$_}) for keys %$args;
3164 my $out = ''; # have temp item to allow clear to correctly clear
3165 eval { $self->_template->_process($file, $self->{'_vars'}, \
$out) };
3167 die $err if ref($err) !~ /Template::Exception$/ || $err->type !~ /return/;
3174 my ($self, $name, $filter, $is_dynamic) = @_;
3175 $filter = [ $filter, 1 ] if $is_dynamic;
3176 $self->define_vmethod('filter', $name, $filter);
3180 my ($self, $name, $args, $alias) = @_;
3181 my $t = $self->_template;
3185 $filter = $t->{'FILTERS'}->{$name} || $CGI::Ex
::Template
::FILTER_OPS-
>{$name} || $CGI::Ex
::Template
::SCALAR_OPS-
>{$name};
3186 $t->throw('filter', $name) if ! $filter;
3187 } elsif (UNIVERSAL
::isa
($name, 'CODE') || UNIVERSAL
::isa
($name, 'ARRAY')) {
3189 } elsif (UNIVERSAL
::can
($name, 'factory')) {
3190 $filter = $name->factory || $t->throw($name->error);
3192 $t->throw('undef', "$name: filter not found");
3195 if (UNIVERSAL
::isa
($filter, 'ARRAY')) {
3196 $filter = ($filter->[1]) ? $filter->[0]->($t->context, @$args) : $filter->[0];
3197 } elsif ($args && @$args) {
3199 $filter = sub { $sub->(shift, @$args) };
3202 $t->{'FILTERS'}->{$alias} = $filter if $alias;
3207 sub define_vmethod
{ shift-
>_template->define_vmethod(@_) }
3210 my ($self, $type, $info) = @_;
3212 if (UNIVERSAL
::isa
($type, $CGI::Ex
::Template
::PACKAGE_EXCEPTION
)) {
3214 } elsif (defined $info) {
3215 $self->_template->throw($type, $info);
3217 $self->_template->throw('undef', $type);
3221 sub AUTOLOAD
{ shift-
>_template->throw('not_implemented', "The method $AUTOLOAD has not been implemented") }
3225 ###----------------------------------------------------------------###
3227 package CGI
::Ex
::Template
::_Stash
;
3229 use vars
qw($AUTOLOAD);
3231 sub _template
{ shift-
>{'_template'} || die "Missing _template" }
3234 my ($self, $var) = @_;
3236 if ($var =~ /^\w+$/) { $var = [$var, 0] }
3237 else { $var = $self->_template->parse_expr(\
$var, {no_dots
=> 1}) }
3239 return $self->_template->play_expr($var, {no_dots
=> 1});
3243 my ($self, $var, $val) = @_;
3245 if ($var =~ /^\w+$/) { $var = [$var, 0] }
3246 else { $var = $self->_template->parse_expr(\
$var, {no_dots
=> 1}) }
3248 $self->_template->set_variable($var, $val, {no_dots
=> 1});
3252 sub AUTOLOAD
{ shift-
>_template->throw('not_implemented', "The method $AUTOLOAD has not been implemented") }
3256 ###----------------------------------------------------------------###
3258 package CGI
::Ex
::Template
::EvalPerlHandle
;
3261 my ($class, $out_ref) = @_;
3262 return bless [$out_ref], $class;
3267 ${ $self->[0] } .= $_ for grep {defined && length} @_;
3271 ###----------------------------------------------------------------###
3275 ### See the perldoc in CGI/Ex/Template.pod