1 package CGI
::Ex
::Template
;
3 ###----------------------------------------------------------------###
4 # See the perldoc in CGI/Ex/Template.pod
5 # Copyright 2007 - 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
34 $PACKAGE_EXCEPTION $PACKAGE_ITERATOR $PACKAGE_CONTEXT $PACKAGE_STASH $PACKAGE_PERL_HANDLE
35 $MAX_EVAL_RECURSE $MAX_MACRO_RECURSE
48 $PACKAGE_EXCEPTION = 'CGI::Ex::Template::Exception';
49 $PACKAGE_ITERATOR = 'CGI::Ex::Template::Iterator';
50 $PACKAGE_CONTEXT = 'CGI::Ex::Template::_Context';
51 $PACKAGE_STASH = 'CGI::Ex::Template::_Stash';
52 $PACKAGE_PERL_HANDLE = 'CGI::Ex::Template::EvalPerlHandle';
55 asp
=> ['<%', '%>' ], # ASP
56 default => ['\[%', '%\]' ], # default
57 html
=> ['<!--', '-->' ], # HTML comments
58 mason
=> ['<%', '>' ], # HTML::Mason
59 metatext
=> ['%%', '%%' ], # Text::MetaText
60 php
=> ['<\?', '\?>' ], # PHP
61 star
=> ['\[\*', '\*\]' ], # TT alternate
62 template
=> ['\[%', '%\]' ], # Normal Template Toolkit
63 template1
=> ['[\[%]%', '%[%\]]'], # allow TT1 style
64 tt2
=> ['\[%', '%\]' ], # TT2
69 chunk
=> \
&vmethod_chunk
,
70 collapse
=> sub { local $_ = $_[0]; s/^\s+//; s/\s+$//; s/\s+/ /g; $_ },
71 defined => sub { defined $_[0] ? 1 : '' },
72 indent
=> \
&vmethod_indent
,
73 int => sub { local $^W; int $_[0] },
74 fmt
=> \
&vmethod_fmt_scalar
,
75 'format' => \
&vmethod_format
,
76 hash
=> sub { {value
=> $_[0]} },
77 html
=> sub { local $_ = $_[0]; s/&/&/g; s/</</g; s/>/>/g; s/\"/"/g; s/\'/'/g; $_ },
78 item
=> sub { $_[0] },
79 lcfirst => sub { lcfirst $_[0] },
80 length => sub { defined($_[0]) ? length($_[0]) : 0 },
81 list
=> sub { [$_[0]] },
82 lower
=> sub { lc $_[0] },
83 match
=> \
&vmethod_match
,
84 new
=> sub { defined $_[0] ? $_[0] : '' },
86 rand => sub { local $^W; rand shift },
87 remove
=> sub { vmethod_replace
(shift, shift, '', 1) },
88 repeat
=> \
&vmethod_repeat
,
89 replace
=> \
&vmethod_replace
,
90 search
=> sub { my ($str, $pat) = @_; return $str if ! defined $str || ! defined $pat; return $str =~ /$pat/ },
92 split => \
&vmethod_split
,
93 stderr
=> sub { print STDERR
$_[0]; '' },
94 substr => \
&vmethod_substr
,
95 trim
=> sub { local $_ = $_[0]; s/^\s+//; s/\s+$//; $_ },
96 ucfirst => sub { ucfirst $_[0] },
97 upper
=> sub { uc $_[0] },
102 $FILTER_OPS = { # generally - non-dynamic filters belong in scalar ops
103 eval => [\
&filter_eval
, 1],
104 evaltt
=> [\
&filter_eval
, 1],
105 file
=> [\
&filter_redirect
, 1],
106 redirect
=> [\
&filter_redirect
, 1],
110 defined => sub { return 1 if @_ == 1; defined $_[0]->[ defined($_[1]) ? $_[1] : 0 ] },
111 first
=> sub { my ($ref, $i) = @_; return $ref->[0] if ! $i; return [@{$ref}[0 .. $i - 1]]},
112 fmt
=> \
&vmethod_fmt_list
,
113 grep => sub { local $^W; my ($ref, $pat) = @_; [grep {/$pat/} @$ref] },
114 hash
=> sub { local $^W; my $list = shift; return {@$list} if ! @_; my $i = shift || 0; return {map {$i++ => $_} @$list} },
115 import
=> sub { my $ref = shift; push @$ref, grep {defined} map {ref eq 'ARRAY' ? @$_ : undef} @_; '' },
116 item
=> sub { $_[0]->[ $_[1] || 0 ] },
117 join => sub { my ($ref, $join) = @_; $join = ' ' if ! defined $join; local $^W; return join $join, @$ref },
118 last => sub { my ($ref, $i) = @_; return $ref->[-1] if ! $i; return [@{$ref}[-$i .. -1]]},
119 list
=> sub { $_[0] },
120 max
=> sub { local $^W; $#{ $_[0] } },
121 merge
=> sub { my $ref = shift; return [ @$ref, grep {defined} map {ref eq 'ARRAY' ? @$_ : undef} @_ ] },
122 new
=> sub { local $^W; return [@_] },
124 nsort
=> \
&vmethod_nsort
,
125 pick
=> \
&vmethod_pick
,
126 pop => sub { pop @{ $_[0] } },
127 push => sub { my $ref = shift; push @$ref, @_; return '' },
128 reverse => sub { [ reverse @{ $_[0] } ] },
129 shift => sub { shift @{ $_[0] } },
130 size
=> sub { local $^W; scalar @{ $_[0] } },
131 slice
=> sub { my ($ref, $a, $b) = @_; $a ||= 0; $b = $#$ref if ! defined $b; return [@{$ref}[$a .. $b]] },
132 sort => \
&vmethod_sort
,
133 splice => \
&vmethod_splice
,
134 unique
=> sub { my %u; return [ grep { ! $u{$_}++ } @{ $_[0] } ] },
135 unshift => sub { my $ref = shift; unshift @$ref, @_; return '' },
139 defined => sub { return 1 if @_ == 1; defined $_[0]->{ defined($_[1]) ? $_[1] : '' } },
140 delete => sub { my $h = shift; delete @{ $h }{map {defined($_) ? $_ : ''} @_}; '' },
141 each => sub { [%{ $_[0] }] },
142 exists => sub { exists $_[0]->{ defined($_[1]) ? $_[1] : '' } },
143 fmt
=> \
&vmethod_fmt_hash
,
144 hash
=> sub { $_[0] },
145 import
=> sub { my ($a, $b) = @_; @{$a}{keys %$b} = values %$b if ref($b) eq 'HASH'; '' },
146 item
=> sub { my ($h, $k) = @_; $k = '' if ! defined $k; $k =~ $QR_PRIVATE ? undef : $h->{$k} },
147 items
=> sub { [ %{ $_[0] } ] },
148 keys => sub { [keys %{ $_[0] }] },
149 list
=> \
&vmethod_list_hash
,
150 new
=> sub { local $^W; return (@_ == 1 && ref $_[-1] eq 'HASH') ? $_[-1] : {@_} },
152 nsort
=> sub { my $ref = shift; [sort { $ref->{$a} <=> $ref->{$b}} keys %$ref] },
153 pairs
=> sub { [map { {key
=> $_, value
=> $_[0]->{$_}} } sort keys %{ $_[0] } ] },
154 size
=> sub { scalar keys %{ $_[0] } },
155 sort => sub { my $ref = shift; [sort {lc $ref->{$a} cmp lc $ref->{$b}} keys %$ref] },
156 values => sub { [values %{ $_[0] }] },
164 foreach (values %$VOBJS) {
165 $_->{'Text'} = $_->{'as'};
166 $_->{'Hash'} = $_->{'hash'};
167 $_->{'List'} = $_->{'list'};
171 #name parse_sub play_sub block postdir continue move_to_front
172 BLOCK
=> [\
&parse_BLOCK
, \
&play_BLOCK
, 1, 0, 0, 1],
173 BREAK
=> [sub {}, \
&play_control
],
174 CALL
=> [\
&parse_CALL
, \
&play_CALL
],
175 CASE
=> [\
&parse_CASE
, undef, 0, 0, {SWITCH
=> 1, CASE
=> 1}],
176 CATCH => [\
&parse_CATCH
, undef, 0, 0, {TRY
=> 1, CATCH => 1}],
177 CLEAR
=> [sub {}, \
&play_CLEAR
],
178 '#' => [sub {}, sub {}],
179 CONFIG
=> [\
&parse_CONFIG
, \
&play_CONFIG
],
180 DEBUG
=> [\
&parse_DEBUG
, \
&play_DEBUG
],
181 DEFAULT
=> [\
&parse_DEFAULT
, \
&play_DEFAULT
],
182 DUMP
=> [\
&parse_DUMP
, \
&play_DUMP
],
183 ELSE
=> [sub {}, undef, 0, 0, {IF
=> 1, ELSIF
=> 1, UNLESS
=> 1}],
184 ELSIF
=> [\
&parse_IF
, undef, 0, 0, {IF
=> 1, ELSIF
=> 1, UNLESS
=> 1}],
185 END => [undef, sub {}],
186 FILTER
=> [\
&parse_FILTER
, \
&play_FILTER
, 1, 1],
187 '|' => [\
&parse_FILTER
, \
&play_FILTER
, 1, 1],
188 FINAL
=> [sub {}, undef, 0, 0, {TRY
=> 1, CATCH => 1}],
189 FOR
=> [\
&parse_FOREACH
, \
&play_FOREACH
, 1, 1],
190 FOREACH
=> [\
&parse_FOREACH
, \
&play_FOREACH
, 1, 1],
191 GET
=> [\
&parse_GET
, \
&play_GET
],
192 IF
=> [\
&parse_IF
, \
&play_IF
, 1, 1],
193 INCLUDE
=> [\
&parse_INCLUDE
, \
&play_INCLUDE
],
194 INSERT
=> [\
&parse_INSERT
, \
&play_INSERT
],
195 LAST
=> [sub {}, \
&play_control
],
196 MACRO
=> [\
&parse_MACRO
, \
&play_MACRO
],
197 META
=> [undef, \
&play_META
],
198 NEXT => [sub {}, \
&play_control
],
199 PERL
=> [\
&parse_PERL
, \
&play_PERL
, 1],
200 PROCESS
=> [\
&parse_PROCESS
, \
&play_PROCESS
],
201 RAWPERL
=> [\
&parse_PERL
, \
&play_RAWPERL
, 1],
202 RETURN
=> [sub {}, \
&play_control
],
203 SET
=> [\
&parse_SET
, \
&play_SET
],
204 STOP
=> [sub {}, \
&play_control
],
205 SWITCH
=> [\
&parse_SWITCH
, \
&play_SWITCH
, 1],
206 TAGS
=> [undef, sub {}],
207 THROW
=> [\
&parse_THROW
, \
&play_THROW
],
208 TRY
=> [sub {}, \
&play_TRY
, 1],
209 UNLESS
=> [\
&parse_UNLESS
, \
&play_UNLESS
, 1, 1],
210 USE
=> [\
&parse_USE
, \
&play_USE
],
211 VIEW
=> [\
&parse_VIEW
, \
&play_VIEW
, 1],
212 WHILE
=> [\
&parse_WHILE
, \
&play_WHILE
, 1, 1],
213 WRAPPER
=> [\
&parse_WRAPPER
, \
&play_WRAPPER
, 1, 1],
214 #name #parse_sub #play_sub #block #postdir #continue #move_to_front
217 ### setup the operator parsing
219 # type precedence symbols action (undef means play_operator will handle)
220 ['prefix', 99, ['\\'], undef ],
221 ['postfix', 98, ['++'], undef ],
222 ['postfix', 98, ['--'], undef ],
223 ['prefix', 97, ['++'], undef ],
224 ['prefix', 97, ['--'], undef ],
225 ['right', 96, ['**', 'pow'], sub { $_[0] ** $_[1] } ],
226 ['prefix', 93, ['!'], sub { ! $_[0] } ],
227 ['prefix', 93, ['-'], sub { @_ == 1 ? 0 - $_[0] : $_[0] - $_[1] } ],
228 ['left', 90, ['*'], sub { $_[0] * $_[1] } ],
229 ['left', 90, ['/'], sub { $_[0] / $_[1] } ],
230 ['left', 90, ['div', 'DIV'], sub { int($_[0] / $_[1]) } ],
231 ['left', 90, ['%', 'mod', 'MOD'], sub { $_[0] % $_[1] } ],
232 ['left', 85, ['+'], sub { $_[0] + $_[1] } ],
233 ['left', 85, ['-'], sub { @_ == 1 ? 0 - $_[0] : $_[0] - $_[1] } ],
234 ['left', 85, ['~', '_'], undef ],
235 ['none', 80, ['<'], sub { $_[0] < $_[1] } ],
236 ['none', 80, ['>'], sub { $_[0] > $_[1] } ],
237 ['none', 80, ['<='], sub { $_[0] <= $_[1] } ],
238 ['none', 80, ['>='], sub { $_[0] >= $_[1] } ],
239 ['none', 80, ['lt'], sub { $_[0] lt $_[1] } ],
240 ['none', 80, ['gt'], sub { $_[0] gt $_[1] } ],
241 ['none', 80, ['le'], sub { $_[0] le $_[1] } ],
242 ['none', 80, ['ge'], sub { $_[0] ge $_[1] } ],
243 ['none', 75, ['==', 'eq'], sub { $_[0] eq $_[1] } ],
244 ['none', 75, ['!=', 'ne'], sub { $_[0] ne $_[1] } ],
245 ['left', 70, ['&&'], undef ],
246 ['right', 65, ['||'], undef ],
247 ['none', 60, ['..'], sub { $_[0] .. $_[1] } ],
248 ['ternary', 55, ['?', ':'], undef ],
249 ['assign', 53, ['+='], sub { $_[0] + $_[1] } ],
250 ['assign', 53, ['-='], sub { $_[0] - $_[1] } ],
251 ['assign', 53, ['*='], sub { $_[0] * $_[1] } ],
252 ['assign', 53, ['/='], sub { $_[0] / $_[1] } ],
253 ['assign', 53, ['%='], sub { $_[0] % $_[1] } ],
254 ['assign', 53, ['**='], sub { $_[0] ** $_[1] } ],
255 ['assign', 53, ['~=', '_='], sub { $_[0] . $_[1] } ],
256 ['assign', 52, ['='], undef ],
257 ['prefix', 50, ['not', 'NOT'], sub { ! $_[0] } ],
258 ['left', 45, ['and', 'AND'], undef ],
259 ['right', 40, ['or', 'OR'], undef ],
261 $OP = {map {my $ref = $_; map {$_ => $ref} @{$ref->[2]}} grep {$_->[0] ne 'prefix' } @$OPERATORS}; # all non-prefix
262 $OP_PREFIX = {map {my $ref = $_; map {$_ => $ref} @{$ref->[2]}} grep {$_->[0] eq 'prefix' } @$OPERATORS};
263 $OP_DISPATCH = {map {my $ref = $_; map {$_ => $ref->[3]} @{$ref->[2]}} grep {$_->[3] } @$OPERATORS};
264 $OP_ASSIGN = {map {my $ref = $_; map {$_ => 1} @{$ref->[2]}} grep {$_->[0] eq 'assign' } @$OPERATORS};
265 $OP_POSTFIX = {map {my $ref = $_; map {$_ => 1} @{$ref->[2]}} grep {$_->[0] eq 'postfix'} @$OPERATORS}; # bool is postfix
266 $OP_TERNARY = {map {my $ref = $_; map {$_ => 1} @{$ref->[2]}} grep {$_->[0] eq 'ternary'} @$OPERATORS}; # bool is ternary
267 sub _op_qr
{ # no mixed \w\W operators
269 my $chrs = join '|', reverse sort map {quotemeta $_} grep {++$used{$_} < 2} grep {! /\{\}|\[\]/} grep {/^\W{2,}$/} @_;
270 my $chr = join '', sort map {quotemeta $_} grep {++$used{$_} < 2} grep {/^\W$/} @_;
271 my $word = join '|', reverse sort grep {++$used{$_} < 2} grep {/^\w+$/} @_;
272 $chr = "[$chr]" if $chr;
273 $word = "\\b(?:$word)\\b" if $word;
274 return join('|', grep {length} $chrs, $chr, $word) || die "Missing operator regex";
276 sub _build_op_qr
{ _op_qr
(map {@{ $_->[2] }} grep {$_->[0] ne 'prefix'} @$OPERATORS) }
277 sub _build_op_qr_prefix
{ _op_qr
(map {@{ $_->[2] }} grep {$_->[0] eq 'prefix'} @$OPERATORS) }
278 sub _build_op_qr_assign
{ _op_qr
(map {@{ $_->[2] }} grep {$_->[0] eq 'assign'} @$OPERATORS) }
279 $QR_OP = _build_op_qr
();
280 $QR_OP_PREFIX = _build_op_qr_prefix
();
281 $QR_OP_ASSIGN = _build_op_qr_assign
();
283 $QR_DIRECTIVE = '( [a-zA-Z]+\b | \| )';
284 $QR_COMMENTS = '(?-s: \# .* \s*)*';
285 $QR_FILENAME = '([a-zA-Z]]:/|/)? [\w\.][\w\-\.]* (?:/[\w\-\.]+)*';
286 $QR_NUM = '(?:\d*\.\d+ | \d+) (?: [eE][+-]\d+ )?';
287 $QR_AQ_SPACE = '(?: \\s+ | \$ | (?=;) )';
288 $QR_PRIVATE = qr/^[_.]/;
291 $EXTRA_COMPILE_EXT = '.sto';
292 $MAX_EVAL_RECURSE = 50;
293 $MAX_MACRO_RECURSE = 50;
296 @CONFIG_COMPILETIME = qw(ANYCASE INTERPOLATE PRE_CHOMP POST_CHOMP V1DOLLAR V2PIPE);
297 @CONFIG_RUNTIME = qw(DUMP);
299 eval {require Scalar
::Util
};
302 ###----------------------------------------------------------------###
306 my $args = ref($_[0]) ? { %{ shift() } } : {@_};
308 ### allow for lowercase args
309 if (my @keys = grep {/^[a-z][a-z_]+$/} keys %$args) {
310 @{ $args }{ map { uc $_ } @keys } = delete @{ $args }{ @keys };
313 my $self = bless $args, $class;
315 ### "enable" debugging - we only support DEBUG_DIRS and DEBUG_UNDEF
316 if ($self->{'DEBUG'}) {
317 $self->{'_debug_dirs'} = 1 if $self->{'DEBUG'} =~ /^\d+$/ ? $self->{'DEBUG'} & 8 : $self->{'DEBUG'} =~ /dirs|all/;
318 $self->{'_debug_undef'} = 1 if $self->{'DEBUG'} =~ /^\d+$/ ? $self->{'DEBUG'} & 2 : $self->{'DEBUG'} =~ /undef|all/;
324 ###----------------------------------------------------------------###
329 local $self->{'_vars'} = shift || {};
330 my $out_ref = shift || $self->throw('undef', "Missing output ref");
331 local $self->{'_top_level'} = delete $self->{'_start_top_level'};
332 my $i = length $$out_ref;
334 ### parse and execute
337 ### handed us a precompiled document
338 if (ref($file) eq 'HASH' && $file->{'_tree'}) {
341 ### load the document
343 $doc = $self->load_parsed_tree($file) || $self->throw('undef', "Zero length content");;
346 ### prevent recursion
347 $self->throw('file', "recursion into '$doc->{name}'")
348 if ! $self->{'RECURSION'} && $self->{'_in'}->{$doc->{'name'}} && $doc->{'name'} ne 'input text';
349 local $self->{'_in'}->{$doc->{'name'}} = 1;
351 ### execute the document
352 if (! @{ $doc->{'_tree'} }) { # no tags found - just return the content
353 $$out_ref = ${ $doc->{'_content'} };
355 local $self->{'_component'} = $doc;
356 local $self->{'_template'} = $self->{'_top_level'} ? $doc : $self->{'_template'};
357 local @{ $self }{@CONFIG_RUNTIME} = @{ $self }{@CONFIG_RUNTIME};
358 $self->execute_tree($doc->{'_tree'}, $out_ref);
361 ### trim whitespace from the beginning and the end of a block or template
362 if ($self->{'TRIM'}) {
363 substr($$out_ref, $i, length($$out_ref) - $i) =~ s{ \s+ $ }{}x; # tail first
364 substr($$out_ref, $i, length($$out_ref) - $i) =~ s{ ^ \s+ }{}x;
368 ### handle exceptions
370 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
371 $err->doc($doc) if $doc && $err->can('doc') && ! $err->doc;
372 die $err if ! $self->{'_top_level'} || $err->type !~ /stop|return/;
378 ###----------------------------------------------------------------###
380 sub load_parsed_tree
{
383 return if ! defined $file;
385 my $doc = {name
=> $file};
386 my $ref = $self->{'_documents'}->{$file};
388 ### looks like a string reference
390 $doc->{'_content'} = $file;
391 $doc->{'name'} = 'input text';
392 $doc->{'_is_str_ref'} = 1;
394 ### looks like a previously cached-in-memory document
396 && ( time - $ref->{'cache_time'} < ($self->{'STAT_TTL'} || $STAT_TTL) # don't stat more than once a second
397 || $ref->{'modtime'} == (stat $ref->{'_filename'})[9] # otherwise see if the file was modified
399 $doc = $self->{'_documents'}->{$file};
402 ### looks like a block name of some sort
403 } elsif ($self->{'BLOCKS'}->{$file}) {
404 my $block = $self->{'BLOCKS'}->{$file};
406 ### allow for predefined blocks that are a code or a string
407 if (UNIVERSAL
::isa
($block, 'CODE')) {
410 if (! UNIVERSAL
::isa
($block, 'HASH')) {
411 $self->throw('block', "Unsupported BLOCK type \"$block\"") if ref $block;
413 $block = eval { $self->load_parsed_tree(\
$copy) }
414 || $self->throw('block', 'Parse error on predefined block');
416 $doc->{'_tree'} = $block->{'_tree'} || $self->throw('block', "Invalid block definition (missing tree)");
419 ### handle cached not_founds
420 } elsif ($self->{'_not_found'}->{$file}
421 && ((time - $self->{'_not_found'}->{$file}->{'cache_time'}
422 < ($self->{'NEGATIVE_STAT_TTL'} || $self->{'STAT_TTL'} || $STAT_TTL)) # negative cache for a second
423 || do { delete $self->{'_not_found'}->{$file}; 0 } # clear cache on failure
425 die $self->{'_not_found'}->{$file}->{'exception'};
427 ### go and look on the file system
429 $doc->{'_filename'} = eval { $self->include_filename($file) };
431 ### allow for blocks in other files
432 if ($self->{'EXPOSE_BLOCKS'}
433 && ! $self->{'_looking_in_block_file'}) {
434 local $self->{'_looking_in_block_file'} = 1;
436 while ($file =~ s
|/([^/.]+)$||) {
437 $block_name = length($block_name) ? "$1/$block_name" : $1;
438 my $ref = eval { $self->load_parsed_tree($file) } || next;
439 my $_tree = $ref->{'_tree'};
440 foreach my $node (@$_tree) {
442 next if $node->[0] eq 'META';
443 last if $node->[0] ne 'BLOCK';
444 next if $block_name ne $node->[3];
445 $doc->{'_content'} = $ref->{'_content'};
446 $doc->{'_tree'} = $node->[4];
447 $doc->{'modtime'} = $ref->{'modtime'};
448 $file = $ref->{'name'};
452 $err = '' if ! $doc->{'_tree'};
453 } elsif ($self->{'DEFAULT'}) {
454 $err = '' if ($doc->{'_filename'} = eval { $self->include_filename($self->{'DEFAULT'}) });
457 ### cache the negative error
458 if (! defined($self->{'NEGATIVE_STAT_TTL'}) || $self->{'NEGATIVE_STAT_TTL'}) {
459 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
460 $self->{'_not_found'}->{$file} = {
462 exception
=> $self->exception($err->type, $err->info." (cached)"),
469 ### no tree yet - look for a file cache
470 if (! $doc->{'_tree'}) {
471 $doc->{'modtime'} = (stat $doc->{'_filename'})[9];
472 if ($self->{'COMPILE_DIR'} || $self->{'COMPILE_EXT'}) {
473 if ($self->{'COMPILE_DIR'}) {
474 $doc->{'_compile_filename'} = $self->{'COMPILE_DIR'} .'/'. $file;
476 $doc->{'_compile_filename'} = $doc->{'_filename'};
478 $doc->{'_compile_filename'} .= $self->{'COMPILE_EXT'} if defined($self->{'COMPILE_EXT'});
479 $doc->{'_compile_filename'} .= $EXTRA_COMPILE_EXT if defined $EXTRA_COMPILE_EXT;
481 if (-e
$doc->{'_compile_filename'} && (stat _
)[9] == $doc->{'modtime'}) {
483 $doc->{'_tree'} = Storable
::retrieve
($doc->{'_compile_filename'});
484 $doc->{'compile_was_used'} = 1;
486 my $str = $self->slurp($doc->{'_filename'});
487 $doc->{'_content'} = \
$str;
490 my $str = $self->slurp($doc->{'_filename'});
491 $doc->{'_content'} = \
$str;
497 ### haven't found a parsed tree yet - parse the content into a tree
498 if (! $doc->{'_tree'}) {
499 if ($self->{'CONSTANTS'}) {
500 my $key = $self->{'CONSTANT_NAMESPACE'} || 'constants';
501 $self->{'NAMESPACE'}->{$key} ||= $self->{'CONSTANTS'};
504 local $self->{'_component'} = $doc;
505 $doc->{'_tree'} = eval { $self->parse_tree($doc->{'_content'}) }
506 || do { my $e = $@; $e->doc($doc) if UNIVERSAL
::can
($e, 'doc') && ! $e->doc; die $e }; # errors die
509 ### cache parsed_tree in memory unless asked not to do so
510 if (! $doc->{'_is_str_ref'} && (! defined($self->{'CACHE_SIZE'}) || $self->{'CACHE_SIZE'})) {
511 $self->{'_documents'}->{$file} ||= $doc;
512 $doc->{'cache_time'} = time;
514 ### allow for config option to keep the cache size down
515 if ($self->{'CACHE_SIZE'}) {
516 my $all = $self->{'_documents'};
517 if (scalar(keys %$all) > $self->{'CACHE_SIZE'}) {
519 foreach my $file (sort {$all->{$b}->{'cache_time'} <=> $all->{$a}->{'cache_time'}} keys %$all) {
520 delete($all->{$file}) if ++$n > $self->{'CACHE_SIZE'};
526 ### save a cache on the fileside as asked
527 if ($doc->{'_compile_filename'} && ! $doc->{'compile_was_used'}) {
528 my $dir = $doc->{'_compile_filename'};
532 File
::Path
::mkpath
($dir);
535 Storable
::store
($doc->{'_tree'}, $doc->{'_compile_filename'});
536 utime $doc->{'modtime'}, $doc->{'modtime'}, $doc->{'_compile_filename'};
542 ###----------------------------------------------------------------###
547 if (! $str_ref || ! defined $$str_ref) {
548 $self->throw('parse.no_string', "No string or undefined during parse");
551 my $STYLE = $self->{'TAG_STYLE'} || 'default';
552 my $START = $self->{'START_TAG'} || $TAGS->{$STYLE}->[0];
553 my $END = $self->{'END_TAG'} || $TAGS->{$STYLE}->[1];
554 local $self->{'_end_tag'} = $END;
556 local @{ $self }{@CONFIG_COMPILETIME} = @{ $self }{@CONFIG_COMPILETIME};
558 my @tree; # the parsed tree
559 my $pointer = \
@tree; # pointer to current tree to handle nested blocks
560 my @state; # maintain block levels
561 local $self->{'_state'} = \
@state; # allow for items to introspect (usually BLOCKS)
562 local $self->{'_in_perl'}; # no interpolation in perl
563 my @in_view; # let us know if we are in a view
564 my @move_to_front; # items that need to be declared first (usually BLOCKS)
565 my @meta; # place to store any found meta information (to go into META)
566 my $post_chomp = 0; # previous post_chomp setting
567 my $continue = 0; # flag for multiple directives in the same tag
568 my $post_op; # found a post-operative DIRECTIVE
569 my $capture; # flag to start capture
573 local pos $$str_ref = 0;
576 ### continue looking for information in a semi-colon delimited tag
578 $node = [undef, pos($$str_ref), undef];
580 ### look through the string using index
582 $$str_ref =~ m{ \G (.*?) $START }gcxs
585 ### found a text portion - chomp it, interpolate it and store it
589 if ($text =~ m{ ($END) }xs) {
590 my $char = pos($$str_ref) + $-[1] + 1;
591 $self->throw('parse', "Found unmatched closing tag \"$1\"", undef, $char);
594 my $_last = pos $$str_ref;
596 if ($post_chomp == 1) { $_last += length($1) if $text =~ s{ ^ ([^\S\n]* \n) }{}x }
597 elsif ($post_chomp == 2) { $_last += length($1) + 1 if $text =~ s{ ^ (\s+) }{ }x }
598 elsif ($post_chomp == 3) { $_last += length($1) if $text =~ s{ ^ (\s+) }{}x }
601 push @$pointer, $text;
602 $self->interpolate_node($pointer, $_last) if $self->{'INTERPOLATE'};
606 $node = [undef, pos($$str_ref), undef];
608 ### take care of whitespace and comments flags
609 my $pre_chomp = $$str_ref =~ m{ \G ([+=~-]) }gcx ? $1 : $self->{'PRE_CHOMP'};
610 $pre_chomp =~ y/-=~+/1230/ if $pre_chomp;
611 if ($pre_chomp && $pointer->[-1] && ! ref $pointer->[-1]) {
612 if ($pre_chomp == 1) { $pointer->[-1] =~ s{ (?:\n|^) [^\S\n]* \z }{}x }
613 elsif ($pre_chomp == 2) { $pointer->[-1] =~ s{ (\s+) \z }{ }x }
614 elsif ($pre_chomp == 3) { $pointer->[-1] =~ s{ (\s+) \z }{}x }
615 splice(@$pointer, -1, 1, ()) if ! length $pointer->[-1]; # remove the node if it is zero length
617 if ($$str_ref =~ m{ \G \# }gcx) { # leading # means to comment the entire section
618 $$str_ref =~ m{ \G (.*?) ([+~=-]?) ($END) }gcxs # brute force - can't comment tags with nested %]
619 || $self->throw('parse', "Missing closing tag", undef, pos($$str_ref));
621 $node->[2] = pos($$str_ref) - length($3);
622 push @$pointer, $node;
625 $post_chomp ||= $self->{'POST_CHOMP'};
626 $post_chomp =~ y/-=~+/1230/ if $post_chomp;
629 $$str_ref =~ m{ \G \s* $QR_COMMENTS }gcxo;
632 ### look for DIRECTIVES
633 if ($$str_ref =~ m{ \G $QR_DIRECTIVE }gcxo # find a word
634 && ($func = $self->{'ANYCASE'} ? uc($1) : $1)
635 && ($DIRECTIVES->{$func}
636 || ((pos($$str_ref) -= length $1) && 0))
637 ) { # is it a directive
639 $$str_ref =~ m{ \G \s* $QR_COMMENTS }gcx;
641 ### store out this current node level
642 if ($post_op) { # on a post operator - replace the original node with the new one - store the old in the new
643 my @post_op = @$post_op;
646 $node->[4] = [\
@post_op];
648 # do nothing - it will be handled further down
650 push @$pointer, $node;
653 ### anything that behaves as a block ending
654 if ($func eq 'END' || $DIRECTIVES->{$func}->[4]) { # [4] means it is a continuation block (ELSE, CATCH, etc)
656 $self->throw('parse', "Found an $func tag while not in a block", $node, pos($$str_ref));
658 my $parent_node = pop @state;
660 if ($func ne 'END') {
661 pop @$pointer; # we will store the node in the parent instead
662 $parent_node->[5] = $node;
663 my $parent_type = $parent_node->[0];
664 if (! $DIRECTIVES->{$func}->[4]->{$parent_type}) {
665 $self->throw('parse', "Found unmatched nested block", $node, pos($$str_ref));
669 ### restore the pointer up one level (because we hit the end of a block)
670 $pointer = (! @state) ? \
@tree : $state[-1]->[4];
673 if ($func eq 'END') {
674 if ($DIRECTIVES->{$parent_node->[0]}->[5]) { # move things like BLOCKS to front
675 if ($parent_node->[0] eq 'BLOCK'
676 && defined($parent_node->[3])
678 push @{ $in_view[-1] }, $parent_node;
680 push @move_to_front, $parent_node;
682 if ($pointer->[-1] && ! $pointer->[-1]->[6]) { # capturing doesn't remove the var
683 splice(@$pointer, -1, 1, ());
685 } elsif ($parent_node->[0] =~ /PERL$/) {
686 delete $self->{'_in_perl'};
687 } elsif ($parent_node->[0] eq 'VIEW') {
688 my $ref = { map {($_->[3] => $_->[4])} @{ pop @in_view }};
689 unshift @{ $parent_node->[3] }, $ref;
692 ### continuation block - such as an elsif
694 $node->[3] = eval { $DIRECTIVES->{$func}->[0]->($self, $str_ref, $node) };
696 $err->node($node) if UNIVERSAL
::can
($err, 'node') && ! $err->node;
700 $pointer = $node->[4] ||= [];
703 } elsif ($func eq 'TAGS') {
705 if ($$str_ref =~ m{ \G (\w+) \s* $QR_COMMENTS }gcxs) {
706 my $ref = $TAGS->{lc $1} || $self->throw('parse', "Invalid TAGS name \"$1\"", undef, pos($$str_ref));
707 ($START, $END) = @$ref;
710 local $self->{'_operator_precedence'} = 1; # prevent operator matching
711 $START = $$str_ref =~ m{ \G (?= [\'\"\/]) }gcx
712 ? $self->parse_expr($str_ref)
713 : $self->parse_expr($str_ref, {auto_quote
=> "(\\S+) \\s+ $QR_COMMENTS"})
714 || $self->throw('parse', "Invalid opening tag in TAGS", undef, pos($$str_ref));
715 $END = $$str_ref =~ m{ \G (?= [\'\"\/]) }gcx
716 ? $self->parse_expr($str_ref)
717 : $self->parse_expr($str_ref, {auto_quote
=> "(\\S+) \\s* $QR_COMMENTS"})
718 || $self->throw('parse', "Invalid closing tag in TAGS", undef, pos($$str_ref));
719 for my $tag ($START, $END) {
720 $tag = $self->play_expr($tag);
721 $tag = quotemeta($tag) if ! ref $tag;
725 $node->[2] = pos $$str_ref;
727 ### allow for one more closing tag of the old style
728 if ($$str_ref =~ m{ \G ([+~=-]?) $self->{'_end_tag'} }gcxs
) {
729 $post_chomp = $1 || $self->{'POST_CHOMP'};
730 $post_chomp =~ y/-=~+/1230/ if $post_chomp;
733 $self->{'_end_tag'} = $END; # need to keep track so parse_expr knows when to stop
737 $self->{'_end_tag'} = $END;
739 } elsif ($func eq 'META') {
740 my $args = $self->parse_args($str_ref, {named_at_front
=> 1});
742 if (($hash = $self->play_expr($args->[0]))
743 && UNIVERSAL
::isa
($hash, 'HASH')) {
744 unshift @meta, %$hash; # first defined win
747 ### all other "normal" tags
749 $node->[3] = eval { $DIRECTIVES->{$func}->[0]->($self, $str_ref, $node) };
751 $err->node($node) if UNIVERSAL
::can
($err, 'node') && ! $err->node;
754 if ($DIRECTIVES->{$func}->[2] && ! $post_op) { # this looks like a block directive
756 $pointer = $node->[4] ||= [];
758 push @in_view, [] if $func eq 'VIEW';
761 ### allow for bare variable getting and setting
762 } elsif (defined(my $var = $self->parse_expr($str_ref))) {
763 push @$pointer, $node;
764 if ($$str_ref =~ m{ \G ($QR_OP_ASSIGN) >? (?! [+=~-]? $END) \s* $QR_COMMENTS }gcx) {
766 $node->[3] = eval { $DIRECTIVES->{'SET'}->[0]->($self, $str_ref, $node, $1, $var) };
768 $err->node($node) if UNIVERSAL
::can
($err, 'node') && ! $err->node;
776 ### handle empty tags [% %]
777 } elsif ($$str_ref =~ m{ \G (?: ; \s* $QR_COMMENTS)? ([+=~-]?) ($END) }gcxs) {
779 $post_chomp = $1 || $self->{'POST_CHOMP'};
780 $post_chomp =~ y/-=~+/1230/ if $post_chomp;
781 $node->[2] = pos($$str_ref) - length($end);
787 $self->throw('parse', "Not sure how to handle tag", $node, pos($$str_ref));
790 ### we now have the directive to capture for an item like "SET foo = BLOCK" - store it
792 my $parent_node = $capture;
793 push @{ $parent_node->[4] }, $node;
797 ### look for the closing tag again
798 if ($$str_ref =~ m{ \G (?: ; \s* $QR_COMMENTS)? ([+=~-]?) ($END) }gcxs) {
800 $post_chomp = $1 || $self->{'POST_CHOMP'};
801 $post_chomp =~ y/-=~+/1230/ if $post_chomp;
803 $node->[2] = pos($$str_ref) - length($end);
809 ### we always continue - and always record our position now
811 $node->[2] = pos $$str_ref;
813 ### we are flagged to start capturing the output of the next directive - set it up
818 ### semi-colon = end of statement - we will need to continue parsing this tag
819 } elsif ($$str_ref =~ m{ \G ; \s* $QR_COMMENTS }gcxo) {
823 ### looking at a post operator ([% u FOREACH u IN [1..3] %])
824 $mark = pos $$str_ref;
825 if ($$str_ref =~ m{ \G $QR_DIRECTIVE }gcxo # find a word without advancing position
826 && ($func = $self->{'ANYCASE'} ? uc($1) : $1)
827 && (($DIRECTIVES->{$func} # and its a directive
828 && $DIRECTIVES->{$func}->[3]) # that can be post operative
829 || ((pos($$str_ref) = $mark) && 0)) # otherwise rollback
831 $post_op = $node; # store flag so next loop puts items in this node
832 pos($$str_ref) = $mark;
840 if (@move_to_front) {
841 unshift @tree, @move_to_front;
844 unshift @tree, ['META', 0, 0, {@meta}];
848 $self->throw('parse.missing.end', "Missing END", $state[-1], 0);
851 ### pull off the last text portion - if any
852 if (pos($$str_ref) != length($$str_ref)) {
853 my $text = substr $$str_ref, pos($$str_ref);
855 if ($text =~ m{ ($END) }xs) {
856 my $char = pos($$str_ref) + $-[1] + 1;
857 $self->throw('parse', "Found unmatched closing tag \"$1\"", undef, $char);
860 my $_last = pos($$str_ref);
862 if ($post_chomp == 1) { $_last += length($1) if $text =~ s{ ^ ([^\S\n]* \n) }{}x }
863 elsif ($post_chomp == 2) { $_last += length($1) + 1 if $text =~ s{ ^ (\s+) }{ }x }
864 elsif ($post_chomp == 3) { $_last += length($1) if $text =~ s{ ^ (\s+) }{}x }
867 push @$pointer, $text;
868 $self->interpolate_node($pointer, $_last) if $self->{'INTERPOLATE'};
878 my $ARGS = shift || {};
879 my $is_aq = $ARGS->{'auto_quote'} ? 1 : 0;
880 my $mark = pos $$str_ref;
882 ### allow for custom auto_quoting (such as hash constructors)
884 if ($$str_ref =~ m{ \G $ARGS->{'auto_quote'} }gcx
) {
887 ### allow for auto-quoted $foo
888 } elsif ($$str_ref =~ m{ \G \$ (\w+\b (?:\.\w+\b)*) \s* $QR_COMMENTS }gcxo) {
890 if ($$str_ref !~ m{ \G \( }gcx || $name =~ /^(?:qw|m|\d)/) {
891 return $self->parse_expr(\
$name);
893 ### this is a little cryptic/odd - but TT allows items in
894 ### autoquote position to only be prefixed by a $ - gross
895 ### so we will defer to the regular parsing - but after the $
896 pos($$str_ref) = $mark + 1;
897 $is_aq = undef; # but don't allow operators - false flag handed down
899 ### allow for ${foo.bar} type constructs
900 } elsif ($$str_ref =~ m{ \G \$\{ \s* }gcx) {
901 my $var = $self->parse_expr($str_ref);
902 $$str_ref =~ m{ \G \s* \} \s
* $QR_COMMENTS }gcxo
903 || $self->throw('parse', 'Missing close "}" from "${"', undef, pos($$str_ref));
909 ### test for leading prefix operators
911 while (! $is_aq && $$str_ref =~ m{ \G ($QR_OP_PREFIX) }gcxo) {
912 push @{ $has_prefix }, $1;
913 $$str_ref =~ m{ \G \s* $QR_COMMENTS }gcxo;
919 my $already_parsed_args;
922 if ($$str_ref =~ m{ \G 0x ( [a-fA-F0-9]+ ) \s* $QR_COMMENTS }gcxo) {
923 my $number = eval { hex $1 } || 0;
924 push @var, \
$number;
927 ### allow for numbers
928 } elsif ($$str_ref =~ m{ \G ( $QR_NUM ) \s* $QR_COMMENTS }gcxo) {
930 push @var, \
$number;
933 ### allow for quoted array constructor
934 } elsif (! $is_aq && $$str_ref =~ m{ \G qw ([^\w\s]) \s* }gcxo) {
936 $quote =~ y
|([{<|)]}>|;
937 $$str_ref =~ m{ \G (.*?) (?<!\\) \Q$quote\E \s* $QR_COMMENTS }gcxs
938 || $self->throw('parse.missing.array_close', "Missing close \"$quote\"", undef, pos($$str_ref));
940 $str =~ s{ ^ \s+ }{}x;
941 $str =~ s{ \s+ $ }{}x;
942 $str =~ s{ \\ \Q$quote\E }{$quote}gx;
943 push @var, [undef, '[]', split /\s+/, $str];
945 ### allow for regex constructor
946 } elsif (! $is_aq && $$str_ref =~ m{ \G / }gcx) {
947 $$str_ref =~ m{ \G (.*?) (?<! \\) / ([msixeg]*) \s* $QR_COMMENTS }gcxos
948 || $self->throw('parse', 'Unclosed regex tag "/"', undef, pos($$str_ref));
949 my ($str, $opts) = ($1, $2);
950 $self->throw('parse', 'e option not allowed on regex', undef, pos($$str_ref)) if $opts =~ /e/;
951 $self->throw('parse', 'g option not supported on regex', undef, pos($$str_ref)) if $opts =~ /g/;
957 $self->throw('parse', "Invalid regex: $@", undef, pos($$str_ref)) if ! eval { "" =~ /$str/; 1 };
958 push @var, [undef, 'qr', $str, $opts];
960 ### looks like a normal variable start
961 } elsif ($$str_ref =~ m{ \G (\w+) \s* $QR_COMMENTS }gcxo) {
963 $is_namespace = 1 if $self->{'NAMESPACE'} && $self->{'NAMESPACE'}->{$1};
965 ### allow for literal strings
966 } elsif ($$str_ref =~ m{ \G ([\"\']) }gcx) {
968 $$str_ref =~ m{ \G (.*?) (?<! \\) $quote \s* $QR_COMMENTS }gcxs
969 || $self->throw('parse', "Unclosed quoted string ($1)", undef, pos($$str_ref));
971 if ($quote eq "'") { # no interpolation on single quoted strings
972 $str =~ s{ \\\' }{\'}xg;
981 ? split(m{ (?: ^ | (?<!\\)) (\$\w+ | \$\{ .*? (?<!\\) \}) }x
, $str) # autoquoted items get a single $\w+ - no nesting
982 : split(m{ (?: ^ | (?<!\\)) (\$\w+ (?:\.\w+)* | \$\{ .*? (?<!\\) \}) }x
, $str);
984 foreach my $piece (@pieces) {
985 $piece =~ s/\\\$/\$/g;
987 next if ! ($n++ % 2);
988 next if $piece !~ m{ ^ \$ (\w+ (?:\.\w+)*) $ }x
989 && $piece !~ m{ ^ \$\{ \s* (.*?) (?<!\\) \} $ }x
;
991 $name =~ s/\\\}/\}/g;
992 $piece = $self->parse_expr(\
$name);
994 @pieces = grep {defined && length} @pieces;
995 if (@pieces == 1 && ! ref $pieces[0]) {
996 push @var, \
$pieces[0];
998 } elsif (! @pieces) {
1002 push @var, [undef, '~', @pieces];
1006 return ${ $var[0] } if $is_literal;
1011 ### allow for leading $foo type constructs
1012 } elsif ($$str_ref =~ m{ \G \$ (\w+) \b \s* $QR_COMMENTS }gcxo) {
1013 if ($self->{'V1DOLLAR'}) {
1015 $is_namespace = 1 if $self->{'NAMESPACE'} && $self->{'NAMESPACE'}->{$1};
1020 ### allow for ${foo.bar} type constructs
1021 } elsif ($$str_ref =~ m{ \G \$\{ \s* }gcx) {
1022 push @var, $self->parse_expr($str_ref);
1023 $$str_ref =~ m{ \G \s* \} \s
* $QR_COMMENTS }gcxo
1024 || $self->throw('parse', 'Missing close "}" from "${"', undef, pos($$str_ref));
1026 ### looks like an array constructor
1027 } elsif (! $is_aq && $$str_ref =~ m{ \G \[ \s* $QR_COMMENTS }gcxo) {
1028 local $self->{'_operator_precedence'} = 0; # reset presedence
1029 my $arrayref = [undef, '[]'];
1030 while (defined(my $var = $self->parse_expr($str_ref))) {
1031 push @$arrayref, $var;
1032 $$str_ref =~ m{ \G , \s* $QR_COMMENTS }gcxo;
1034 $$str_ref =~ m{ \G \] \s* $QR_COMMENTS }gcxo
1035 || $self->throw('parse.missing.square_bracket', "Missing close \]", undef, pos($$str_ref));
1036 push @var, $arrayref;
1038 ### looks like a hash constructor
1039 } elsif (! $is_aq && $$str_ref =~ m{ \G \{ \s* $QR_COMMENTS }gcxo) {
1040 local $self->{'_operator_precedence'} = 0; # reset precedence
1041 my $hashref = [undef, '{}'];
1042 while (defined(my $key = $self->parse_expr($str_ref, {auto_quote
=> "(\\w+\\b) (?! \\.) \\s* $QR_COMMENTS"}))) {
1043 $$str_ref =~ m{ \G = >? \s* $QR_COMMENTS }gcxo;
1044 my $val = $self->parse_expr($str_ref);
1045 push @$hashref, $key, $val;
1046 $$str_ref =~ m{ \G , \s* $QR_COMMENTS }gcxo;
1048 $$str_ref =~ m{ \G \} \s
* $QR_COMMENTS }gcxo
1049 || $self->throw('parse.missing.curly_bracket', "Missing close \}", undef, pos($$str_ref));
1050 push @var, $hashref;
1052 ### looks like a paren grouper
1053 } elsif (! $is_aq && $$str_ref =~ m{ \G \( \s* $QR_COMMENTS }gcxo) {
1054 local $self->{'_operator_precedence'} = 0; # reset precedence
1055 my $var = $self->parse_expr($str_ref, {allow_parened_ops
=> 1});
1057 $$str_ref =~ m{ \G \) \s* $QR_COMMENTS }gcxo
1058 || $self->throw('parse.missing.paren', "Missing close \)", undef, pos($$str_ref));
1060 $self->throw('parse', 'Paren group cannot be followed by an open paren', undef, pos($$str_ref))
1061 if $$str_ref =~ m{ \G \( }gcx;
1063 $already_parsed_args = 1;
1065 push @var, \
$var, 0;
1067 } elsif (! defined $var->[0]) {
1073 ### nothing to find - return failure
1075 pos($$str_ref) = $mark if $is_aq || $has_prefix;
1079 # auto_quoted thing was too complicated
1081 pos($$str_ref) = $mark;
1085 ### looks for args for the initial
1086 if ($already_parsed_args) {
1088 } elsif ($$str_ref =~ m{ \G \( \s* $QR_COMMENTS }gcxo) {
1089 local $self->{'_operator_precedence'} = 0; # reset precedence
1090 my $args = $self->parse_args($str_ref, {is_parened
=> 1});
1091 $$str_ref =~ m{ \G \) \s* $QR_COMMENTS }gcxo
1092 || $self->throw('parse.missing.paren', "Missing close \)", undef, pos($$str_ref));
1099 ### allow for nested items
1100 while ($$str_ref =~ m{ \G ( \.(?!\.) | \|(?!\|) ) }gcx) {
1101 if ($1 eq '|' && $self->{'V2PIPE'}) {
1102 pos($$str_ref) -= 1;
1106 push(@var, $1) if ! $ARGS->{'no_dots'};
1108 $$str_ref =~ m{ \G \s* $QR_COMMENTS }gcxo;
1110 ### allow for interpolated variables in the middle - one.$foo.two
1111 if ($$str_ref =~ m{ \G \$ (\w+) \b \s* $QR_COMMENTS }gcxo) {
1112 push @var, $self->{'V1DOLLAR'} ? $1 : [$1, 0];
1114 ### or one.${foo.bar}.two
1115 } elsif ($$str_ref =~ m{ \G \$\{ \s* }gcx) {
1116 push @var, $self->parse_expr($str_ref);
1117 $$str_ref =~ m{ \G \s* \} \s
* $QR_COMMENTS }gcxo
1118 || $self->throw('parse', 'Missing close "}" from "${"', undef, pos($$str_ref));
1121 } elsif ($$str_ref =~ m{ \G (-? \w+) \s* $QR_COMMENTS }gcxo) {
1125 $self->throw('parse', "Not sure how to continue parsing", undef, pos($$str_ref));
1128 ### looks for args for the nested item
1129 if ($$str_ref =~ m{ \G \( \s* $QR_COMMENTS }gcxo) {
1130 local $self->{'_operator_precedence'} = 0; # reset precedence
1131 my $args = $self->parse_args($str_ref, {is_parened
=> 1});
1132 $$str_ref =~ m{ \G \) \s* $QR_COMMENTS }gcxo
1133 || $self->throw('parse.missing.paren', "Missing close \)", undef, pos($$str_ref));
1141 ### flatten literals and constants as much as possible
1144 $var = ${ $var[0] };
1146 $var[0] = [undef, '~', $var];
1149 } elsif ($is_namespace) {
1150 $var = $self->play_expr(\
@var, {is_namespace_during_compile
=> 1});
1155 ### allow for all "operators"
1156 if (! $self->{'_operator_precedence'} && defined $is_aq) {
1160 my $mark = pos $$str_ref;
1161 if ($self->{'_end_tag'} && $$str_ref =~ m{ \G [+=~-]? $self->{'_end_tag'} }gcx
) {
1162 pos($$str_ref) = $mark;
1164 } elsif ($$str_ref !~ m{ \G ($QR_OP) }gcxo) {
1165 pos($$str_ref) = $mark;
1168 if ($OP_ASSIGN->{$1} && ! $ARGS->{'allow_parened_ops'}) { # only allow assignment in parens
1169 pos($$str_ref) = $mark;
1172 local $self->{'_operator_precedence'} = 1;
1174 $$str_ref =~ m{ \G \s* $QR_COMMENTS }gcxo;
1176 ### allow for postfix - doesn't check precedence - someday we might change - but not today (only affects post ++ and --)
1177 if ($OP_POSTFIX->{$op}) {
1178 $var = [[undef, $op, $var, 1], 0]; # cheat - give a "second value" to postfix ops
1181 ### allow for prefix operator precedence
1182 } elsif ($has_prefix && $OP->{$op}->[1] < $OP_PREFIX->{$has_prefix->[-1]}->[1]) {
1184 if ($#$tree == 1) { # only one operator - keep simple things fast
1185 $var = [[undef, $tree->[0], $var, $tree->[1]], 0];
1187 unshift @$tree, $var;
1188 $var = $self->apply_precedence($tree, $found);
1193 $var = [[undef, $has_prefix->[-1], $var ], 0];
1194 if (! @$has_prefix) { undef $has_prefix } else { pop @$has_prefix }
1197 ### add the operator to the tree
1198 my $var2 = $self->parse_expr($str_ref, {from_here
=> 1});
1199 $self->throw('parse', 'Missing variable after "'.$op.'"', undef, pos($$str_ref)) if ! defined $var2;
1200 push (@{ $tree ||= [] }, $op, $var2);
1201 $found->{$OP->{$op}->[1]}->{$op} = 1; # found->{precedence}->{op}
1204 ### if we found operators - tree the nodes by operator precedence
1206 if (@$tree == 2) { # only one operator - keep simple things fast
1207 $var = [[undef, $tree->[0], $var, $tree->[1]], 0];
1209 unshift @$tree, $var;
1210 $var = $self->apply_precedence($tree, $found);
1215 ### allow for prefix on non-chained variables
1217 $var = [[undef, $_, $var], 0] for reverse @$has_prefix;
1223 ### this is used to put the parsed variables into the correct operations tree
1224 sub apply_precedence
{
1225 my ($self, $tree, $found) = @_;
1229 ### look at the operators we found in the order we found them
1230 for my $prec (sort keys %$found) {
1231 my $ops = $found->{$prec};
1232 local $found->{$prec};
1233 delete $found->{$prec};
1235 ### split the array on the current operators for this level
1238 for (my $i = 1; $i <= $#$tree; $i += 2) {
1239 next if ! $ops->{ $tree->[$i] };
1240 push @ops, $tree->[$i];
1241 push @exprs, [splice @$tree, 0, $i, ()];
1245 next if ! @exprs; # this iteration didn't have the current operator
1246 push @exprs, $tree if scalar @$tree; # add on any remaining items
1248 ### simplify sub expressions
1249 for my $node (@exprs) {
1251 $node = $node->[0]; # single item - its not a tree
1252 } elsif (@$node == 3) {
1253 $node = [[undef, $node->[1], $node->[0], $node->[2]], 0]; # single operator - put it straight on
1255 $node = $self->apply_precedence($node, $found); # more complicated - recurse
1259 ### assemble this current level
1262 # 1) items at the same precedence level must all be either right or left or ternary associative
1263 # 2) ternary items cannot share precedence with anybody else.
1264 # 3) there really shouldn't be another operator at the same level as a postfix
1265 my $type = $OP->{$ops[0]}->[0];
1267 if ($type eq 'ternary') {
1268 my $op = $OP->{$ops[0]}->[2]->[0]; # use the first op as what we are using
1270 ### return simple ternary
1272 $self->throw('parse', "Ternary operator mismatch") if $ops[0] ne $op;
1273 $self->throw('parse', "Ternary operator mismatch") if ! $ops[1] || $ops[1] eq $op;
1274 return [[undef, $op, @exprs], 0];
1278 ### reorder complex ternary - rare case
1279 while ($#ops >= 1) {
1280 ### if we look starting from the back - the first lead ternary op will always be next to its matching op
1281 for (my $i = $#ops; $i >= 0; $i --) {
1282 next if $OP->{$ops[$i]}->[2]->[1] eq $ops[$i];
1283 my ($op, $op2) = splice @ops, $i, 2, (); # remove the pair of operators
1284 my $node = [[undef, $op, @exprs[$i .. $i + 2]], 0];
1285 splice @exprs, $i, 3, $node;
1288 return $exprs[0]; # at this point the ternary has been reduced to a single operator
1290 } elsif ($type eq 'right' || $type eq 'assign') {
1291 my $val = $exprs[-1];
1292 $val = [[undef, $ops[$_ - 1], $exprs[$_], $val], 0] for reverse (0 .. $#exprs - 1);
1296 my $val = $exprs[0];
1297 $val = [[undef, $ops[$_ - 1], $val, $exprs[$_]], 0] for (1 .. $#exprs);
1303 $self->throw('parse', "Couldn't apply precedence");
1306 ### look for arguments - both positional and named
1309 my $str_ref = shift;
1310 my $ARGS = shift || {};
1315 my $end = $self->{'_end_tag'} || '(?!)';
1317 my $mark = pos $$str_ref;
1319 ### look to see if the next thing is a directive or a closing tag
1320 if (! $ARGS->{'is_parened'}
1321 && ! $ARGS->{'require_arg'}
1322 && $$str_ref =~ m{ \G $QR_DIRECTIVE (?: \s+ | (?: \s* $QR_COMMENTS (?: ;|[+=~-]?$end))) }gcxo
1323 && ((pos($$str_ref) = $mark) || 1) # always revert
1324 && $DIRECTIVES->{$self->{'ANYCASE'} ? uc($1) : $1} # looks like a directive - we are done
1328 if ($$str_ref =~ m{ \G [+=~-]? $end }gcx) {
1329 pos($$str_ref) = $mark;
1333 ### find the initial arg
1335 if ($ARGS->{'allow_bare_filenames'}) {
1336 $name = $self->parse_expr($str_ref, {auto_quote
=> "
1337 ($QR_FILENAME # file name
1338 | \\w+\\b (?: :\\w+\\b)* ) # or block
1339 (?= [+=~-]? $end # an end tag
1340 | \\s*[+,;] # followed by explicit + , or ;
1341 | \\s+ (?! [\\s=]) # or space not before an =
1342 ) \\s* $QR_COMMENTS"});
1343 # filenames can be separated with a "+" - why a "+" ?
1344 if ($$str_ref =~ m{ \G \+ (?! [+=~-]? $end) \s* $QR_COMMENTS }gcxo) {
1346 $ARGS->{'require_arg'} = 1;
1350 if (! defined $name) {
1351 $name = $self->parse_expr($str_ref);
1352 if (! defined $name) {
1353 if ($ARGS->{'require_arg'} && ! @args && ! $ARGS->{'positional_only'} && ! @named) {
1354 $self->throw('parse', 'Argument required', undef, pos($$str_ref));
1361 $$str_ref =~ m{ \G \s* $QR_COMMENTS }gcxo;
1363 ### see if it is named or positional
1364 if ($$str_ref =~ m{ \G = >? \s* $QR_COMMENTS }gcxo) {
1365 $self->throw('parse', 'Named arguments not allowed', undef, $mark) if $ARGS->{'positional_only'};
1366 my $val = $self->parse_expr($str_ref);
1367 $name = $name->[0] if ref($name) && @$name == 2 && ! $name->[1]; # strip a level of indirection on named arguments
1368 push @named, $name, $val;
1373 ### look for trailing comma
1374 $ARGS->{'require_arg'} = ($$str_ref =~ m{ \G , \s* $QR_COMMENTS }gcxo) || 0;
1377 ### allow for named arguments to be added at the front (if asked)
1378 if ($ARGS->{'named_at_front'}) {
1379 unshift @args, [[undef, '{}', @named], 0];
1380 } elsif (scalar @named) { # only add at end - if there are some
1381 push @args, [[undef, '{}', @named], 0]
1387 ### allow for looking for $foo or ${foo.bar} in TEXT "nodes" of the parse tree.
1388 sub interpolate_node
{
1389 my ($self, $tree, $offset) = @_;
1390 return if $self->{'_in_perl'};
1392 ### split on variables while keeping the variables
1393 my @pieces = split m{ (?: ^ | (?<! \\)) (\$\w+ (?:\.\w+)* | \$\{ .*? (?<!\\) \}) }x
, $tree->[-1];
1394 if ($#pieces <= 0) {
1395 $tree->[-1] =~ s{ \\ ([\"\$]) }{$1}xg;
1401 foreach my $piece (@pieces) {
1402 $offset += length $piece; # we track the offset to make sure DEBUG has the right location
1403 $piece =~ s{ \\ ([\"\$]) }{$1}xg;
1404 if (! ($n++ % 2)) { # odds will always be text chunks
1405 next if ! length $piece;
1406 push @sub_tree, $piece;
1407 } elsif ($piece =~ m{ ^ \$ (\w+ (?:\.\w+)*) $ }x
1408 || $piece =~ m{ ^ \$\{ \s* (.*?) (?<!\\) \} $ }x
) {
1410 $name =~ s/\\\}/\}/g;
1411 push @sub_tree, ['GET', $offset - length($piece), $offset, $self->parse_expr(\
$name)];
1413 $self->throw('parse', "Parse error during interpolate node");
1417 ### replace the tree
1418 splice @$tree, -1, 1, @sub_tree;
1421 ###----------------------------------------------------------------###
1424 my ($self, $tree, $out_ref) = @_;
1426 # node contains (0: DIRECTIVE,
1429 # 3: parsed tag details,
1430 # 4: sub tree for block types
1431 # 5: continuation sub trees for sub continuation block types (elsif, else, etc)
1432 # 6: flag to capture next directive
1433 for my $node (@$tree) {
1434 ### text nodes are just the bare text
1436 warn "NODE: TEXT\n" if trace
;
1437 $$out_ref .= $node if defined $node;
1441 warn "NODE: $node->[0] (char $node->[1])\n" if trace
;
1442 $$out_ref .= $self->debug_node($node) if $self->{'_debug_dirs'} && ! $self->{'_debug_off'};
1444 my $val = $DIRECTIVES->{$node->[0]}->[1]->($self, $node->[3], $node, $out_ref);
1445 $$out_ref .= $val if defined $val;
1450 ### allow for the parse tree to store literals
1451 return $_[1] if ! ref $_[1];
1455 my $ARGS = shift || {};
1458 ### determine the top level of this particular variable access
1460 use CGI
::Ex
::Dump
qw(debug dex_trace);
1462 if ref $var ne 'ARRAY';
1463 my $name = $var->[$i++];
1464 my $args = $var->[$i++];
1465 warn "play_expr: begin \"$name\"\n" if trace
;
1467 if (! defined $name->[0]) { # operator
1468 return $self->play_operator($name) if wantarray && $name->[1] eq '..';
1469 $ref = $self->play_operator($name);
1470 } else { # a named variable access (ie via $name.foo)
1471 $name = $self->play_expr($name);
1472 if (defined $name) {
1473 return if $name =~ $QR_PRIVATE; # don't allow vars that begin with _
1474 return \
$self->{'_vars'}->{$name} if $i >= $#$var && $ARGS->{'return_ref'} && ! ref $self->{'_vars'}->{$name};
1475 $ref = $self->{'_vars'}->{$name};
1478 } elsif (defined $name) {
1479 if ($ARGS->{'is_namespace_during_compile'}) {
1480 $ref = $self->{'NAMESPACE'}->{$name};
1482 return if $name =~ $QR_PRIVATE; # don't allow vars that begin with _
1483 return \
$self->{'_vars'}->{$name} if $i >= $#$var && $ARGS->{'return_ref'} && ! ref $self->{'_vars'}->{$name};
1484 $ref = $self->{'_vars'}->{$name};
1485 $ref = ($name eq 'template' || $name eq 'component') ? $self->{"_$name"} : $VOBJS->{$name} if ! defined $ref;
1491 while (defined $ref) {
1493 ### check at each point if the rurned thing was a code
1494 if (UNIVERSAL
::isa
($ref, 'CODE')) {
1495 return $ref if $i >= $#$var && $ARGS->{'return_ref'};
1496 my @results = $ref->($args ? map { $self->play_expr($_) } @$args : ());
1497 if (defined $results[0]) {
1498 $ref = ($#results > 0) ? \
@results : $results[0];
1499 } elsif (defined $results[1]) {
1500 die $results[1]; # TT behavior - why not just throw ?
1507 ### descend one chained level
1508 last if $i >= $#$var;
1509 my $was_dot_call = $ARGS->{'no_dots'} ? 1 : $var->[$i++] eq '.';
1510 $name = $var->[$i++];
1511 $args = $var->[$i++];
1512 warn "play_expr: nested \"$name\"\n" if trace
;
1514 ### allow for named portions of a variable name (foo.$name.bar)
1516 if (ref($name) eq 'ARRAY') {
1517 $name = $self->play_expr($name);
1518 if (! defined($name) || $name =~ $QR_PRIVATE || $name =~ /^\./) {
1523 die "Shouldn't get a ". ref($name) ." during a vivify on chain";
1526 if ($name =~ $QR_PRIVATE) { # don't allow vars that begin with _
1531 ### allow for scalar and filter access (this happens for every non virtual method call)
1533 if ($SCALAR_OPS->{$name}) { # normal scalar op
1534 $ref = $SCALAR_OPS->{$name}->($ref, $args ? map { $self->play_expr($_) } @$args : ());
1536 } elsif ($LIST_OPS->{$name}) { # auto-promote to list and use list op
1537 $ref = $LIST_OPS->{$name}->([$ref], $args ? map { $self->play_expr($_) } @$args : ());
1539 } elsif (my $filter = $self->{'FILTERS'}->{$name} # filter configured in Template args
1540 || $FILTER_OPS->{$name} # predefined filters in CET
1541 || (UNIVERSAL
::isa
($name, 'CODE') && $name) # looks like a filter sub passed in the stash
1542 || $self->list_filters->{$name}) { # filter defined in Template::Filters
1544 if (UNIVERSAL
::isa
($filter, 'CODE')) {
1545 $ref = eval { $filter->($ref) }; # non-dynamic filter - no args
1547 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1550 } elsif (! UNIVERSAL
::isa
($filter, 'ARRAY')) {
1551 $self->throw('filter', "invalid FILTER entry for '$name' (not a CODE ref)");
1553 } elsif (@$filter == 2 && UNIVERSAL
::isa
($filter->[0], 'CODE')) { # these are the TT style filters
1555 my $sub = $filter->[0];
1556 if ($filter->[1]) { # it is a "dynamic filter" that will return a sub
1557 ($sub, my $err) = $sub->($self->context, $args ? map { $self->play_expr($_) } @$args : ());
1558 if (! $sub && $err) {
1559 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1561 } elsif (! UNIVERSAL
::isa
($sub, 'CODE')) {
1562 $self->throw('filter', "invalid FILTER for '$name' (not a CODE ref)")
1563 if ref($sub) !~ /Template::Exception$/;
1567 $ref = $sub->($ref);
1570 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1573 } else { # this looks like our vmethods turned into "filters" (a filter stored under a name)
1574 $self->throw('filter', 'Recursive filter alias \"$name\"') if $seen_filters{$name} ++;
1575 $var = [$name, 0, '|', @$filter, @{$var}[$i..$#$var]]; # splice the filter into our current tree
1578 if (scalar keys %seen_filters
1579 && $seen_filters{$var->[$i - 5] || ''}) {
1580 $self->throw('filter', "invalid FILTER entry for '".$var->[$i - 5]."' (not a CODE ref)");
1588 ### method calls on objects
1589 if ($was_dot_call && UNIVERSAL
::can
($ref, 'can')) {
1590 return $ref if $i >= $#$var && $ARGS->{'return_ref'};
1591 my @args = $args ? map { $self->play_expr($_) } @$args : ();
1592 my @results = eval { $ref->$name(@args) };
1594 my $class = ref $ref;
1595 die $@ if ref $@ || $@ !~ /Can\'t locate object method "\Q$name\E" via package "\Q$class\E"/;
1596 } elsif (defined $results[0]) {
1597 $ref = ($#results > 0) ? \
@results : $results[0];
1599 } elsif (defined $results[1]) {
1600 die $results[1]; # TT behavior - why not just throw ?
1605 # didn't find a method by that name - so fail down to hash and array access
1608 ### hash member access
1609 if (UNIVERSAL
::isa
($ref, 'HASH')) {
1610 if ($was_dot_call && exists($ref->{$name}) ) {
1611 return \
$ref->{$name} if $i >= $#$var && $ARGS->{'return_ref'} && ! ref $ref->{$name};
1612 $ref = $ref->{$name};
1613 } elsif ($HASH_OPS->{$name}) {
1614 $ref = $HASH_OPS->{$name}->($ref, $args ? map { $self->play_expr($_) } @$args : ());
1615 } elsif ($ARGS->{'is_namespace_during_compile'}) {
1616 return $var; # abort - can't fold namespace variable
1618 return \
$ref->{$name} if $i >= $#$var && $ARGS->{'return_ref'};
1623 } elsif (UNIVERSAL
::isa
($ref, 'ARRAY')) {
1624 if ($name =~ m{ ^ -? $QR_NUM $ }ox) {
1625 return \
$ref->[$name] if $i >= $#$var && $ARGS->{'return_ref'} && ! ref $ref->[$name];
1626 $ref = $ref->[$name];
1627 } elsif ($LIST_OPS->{$name}) {
1628 $ref = $LIST_OPS->{$name}->($ref, $args ? map { $self->play_expr($_) } @$args : ());
1637 ### allow for undefinedness
1638 if (! defined $ref) {
1639 if ($self->{'_debug_undef'}) {
1640 my $chunk = $var->[$i - 2];
1641 $chunk = $self->play_expr($chunk) if ref($chunk) eq 'ARRAY';
1642 die "$chunk is undefined\n";
1644 $ref = $self->undefined_any($var);
1651 sub is_empty_named_args
{
1652 my ($self, $hash_ident) = @_;
1653 # [[undef, '{}', 'key1', 'val1', 'key2, 'val2'], 0]
1654 return @{ $hash_ident->[0] } <= 2;
1658 my ($self, $var, $val, $ARGS) = @_;
1662 ### allow for the parse tree to store literals - the literal is used as a name (like [% 'a' = 'A' %])
1663 $var = [$var, 0] if ! ref $var;
1665 ### determine the top level of this particular variable access
1666 my $ref = $var->[$i++];
1667 my $args = $var->[$i++];
1669 ### non-named types can't be set
1670 return if ref($ref) ne 'ARRAY' || ! defined $ref->[0];
1672 # named access (ie via $name.foo)
1673 $ref = $self->play_expr($ref);
1674 if (defined $ref && $ref !~ $QR_PRIVATE) { # don't allow vars that begin with _
1676 return $self->{'_vars'}->{$ref} = $val;
1678 $ref = $self->{'_vars'}->{$ref} ||= {};
1683 } elsif (defined $ref) {
1684 return if $ref =~ $QR_PRIVATE; # don't allow vars that begin with _
1686 return $self->{'_vars'}->{$ref} = $val;
1688 $ref = $self->{'_vars'}->{$ref} ||= {};
1692 while (defined $ref) {
1694 ### check at each point if the returned thing was a code
1695 if (UNIVERSAL
::isa
($ref, 'CODE')) {
1696 my @results = $ref->($args ? map { $self->play_expr($_) } @$args : ());
1697 if (defined $results[0]) {
1698 $ref = ($#results > 0) ? \
@results : $results[0];
1699 } elsif (defined $results[1]) {
1700 die $results[1]; # TT behavior - why not just throw ?
1706 ### descend one chained level
1707 last if $i >= $#$var;
1708 my $was_dot_call = $ARGS->{'no_dots'} ? 1 : $var->[$i++] eq '.';
1709 my $name = $var->[$i++];
1710 my $args = $var->[$i++];
1712 ### allow for named portions of a variable name (foo.$name.bar)
1714 if (ref($name) eq 'ARRAY') {
1715 $name = $self->play_expr($name);
1716 if (! defined($name) || $name =~ /^[_.]/) {
1720 die "Shouldn't get a ".ref($name)." during a vivify on chain";
1723 if ($name =~ $QR_PRIVATE) { # don't allow vars that begin with _
1731 ### method calls on objects
1732 } elsif (UNIVERSAL
::can
($ref, 'can')) {
1734 my @args = $args ? map { $self->play_expr($_) } @$args : ();
1739 my @results = eval { $ref->$name(@args) };
1741 if (defined $results[0]) {
1742 $ref = ($#results > 0) ? \
@results : $results[0];
1743 } elsif (defined $results[1]) {
1744 die $results[1]; # TT behavior - why not just throw ?
1748 return if $lvalueish;
1751 my $class = ref $ref;
1752 die $@ if ref $@ || $@ !~ /Can\'t locate object method "\Q$name\E" via package "\Q$class\E"/;
1753 # fall on down to "normal" accessors
1756 ### hash member access
1757 if (UNIVERSAL
::isa
($ref, 'HASH')) {
1759 return $ref->{$name} = $val;
1761 $ref = $ref->{$name} ||= {};
1766 } elsif (UNIVERSAL
::isa
($ref, 'ARRAY')) {
1767 if ($name =~ m{ ^ -? $QR_NUM $ }ox) {
1769 return $ref->[$name] = $val;
1771 $ref = $ref->[$name] ||= {};
1785 ###----------------------------------------------------------------###
1788 my ($self, $tree) = @_;
1789 ### $tree looks like [undef, '+', 4, 5]
1791 if ($OP_DISPATCH->{$tree->[1]}) {
1793 if ($OP_ASSIGN->{$tree->[1]}) {
1794 my $val = $OP_DISPATCH->{$tree->[1]}->($self->play_expr($tree->[2]), $self->play_expr($tree->[3]));
1795 $self->set_variable($tree->[2], $val);
1798 return $OP_DISPATCH->{$tree->[1]}->(@$tree == 3 ? $self->play_expr($tree->[2]) : ($self->play_expr($tree->[2]), $self->play_expr($tree->[3])));
1802 my $op = $tree->[1];
1804 ### do custom and short-circuitable operators
1806 my $val = $self->play_expr($tree->[3]);
1807 $self->set_variable($tree->[2], $val);
1810 } elsif ($op eq '||' || $op eq 'or' || $op eq 'OR') {
1811 return $self->play_expr($tree->[2]) || $self->play_expr($tree->[3]) || '';
1813 } elsif ($op eq '&&' || $op eq 'and' || $op eq 'AND') {
1814 my $var = $self->play_expr($tree->[2]) && $self->play_expr($tree->[3]);
1815 return $var ? $var : 0;
1817 } elsif ($op eq '?') {
1819 return $self->play_expr($tree->[2]) ? $self->play_expr($tree->[3]) : $self->play_expr($tree->[4]);
1821 } elsif ($op eq '~' || $op eq '_') {
1824 $s .= $self->play_expr($tree->[$_]) for 2 .. $#$tree;
1827 } elsif ($op eq '[]') {
1828 return [map {$self->play_expr($tree->[$_])} 2 .. $#$tree];
1830 } elsif ($op eq '{}') {
1833 push @e, $self->play_expr($tree->[$_]) for 2 .. $#$tree;
1836 } elsif ($op eq '++') {
1838 my $val = 0 + $self->play_expr($tree->[2]);
1839 $self->set_variable($tree->[2], $val + 1);
1840 return $tree->[3] ? $val : $val + 1; # ->[3] is set to 1 during parsing of postfix ops
1842 } elsif ($op eq '--') {
1844 my $val = 0 + $self->play_expr($tree->[2]);
1845 $self->set_variable($tree->[2], $val - 1);
1846 return $tree->[3] ? $val : $val - 1; # ->[3] is set to 1 during parsing of postfix ops
1848 } elsif ($op eq '\\') {
1849 my $var = $tree->[2];
1851 my $ref = $self->play_expr($var, {return_ref
=> 1});
1852 return $ref if ! ref $ref;
1853 return sub { sub { $$ref } } if ref $ref eq 'SCALAR' || ref $ref eq 'REF';
1855 my $self_copy = $self;
1856 eval {require Scalar
::Util
; Scalar
::Util
::weaken
($self_copy)};
1858 my $last = ['temp deref key', $var->[-1] ? [@{ $var->[-1] }] : 0];
1859 return sub { sub { # return a double sub so that the current play_expr will return a coderef
1860 local $self_copy->{'_vars'}->{'temp deref key'} = $ref;
1861 $last->[-1] = (ref $last->[-1] ? [@{ $last->[-1] }, @_] : [@_]) if @_;
1862 return $self->play_expr($last);
1864 } elsif ($op eq 'qr') {
1865 return $tree->[3] ? qr{(?$tree->[3]:$tree->[2])} : qr{$tree->[2]};
1868 $self->throw('operator', "Un-implemented operation $op");
1871 ###----------------------------------------------------------------###
1874 my ($self, $str_ref, $node) = @_;
1876 my $end = $self->{'_end_tag'} || '(?!)';
1877 my $block_name = $self->parse_expr($str_ref, {auto_quote
=> "
1878 ($QR_FILENAME # file name
1879 | \\w+\\b (?: :\\w+\\b)* ) # or block
1880 (?= [+=~-]? $end # an end tag
1881 | \\s*[+,;] # followed by explicit + , or ;
1882 | \\s+ (?! [\\s=]) # or space not before an =
1883 ) \\s* $QR_COMMENTS"});
1885 return '' if ! defined $block_name;
1887 my $prepend = join "/", map {$_->[3]} grep {ref($_) && $_->[0] eq 'BLOCK'} @{ $self->{'_state'} || {} };
1888 return $prepend ? "$prepend/$block_name" : $block_name;
1892 my ($self, $block_name, $node, $out_ref) = @_;
1894 ### store a named reference - but do nothing until something processes it
1895 $self->{'BLOCKS'}->{$block_name} = {
1896 _tree
=> $node->[4],
1897 name
=> $self->{'_component'}->{'name'} .'/'. $block_name,
1903 sub parse_CALL
{ $DIRECTIVES->{'GET'}->[0]->(@_) }
1905 sub play_CALL
{ $DIRECTIVES->{'GET'}->[1]->(@_); return }
1908 my ($self, $str_ref) = @_;
1909 return if $$str_ref =~ m{ \G DEFAULT \s* }gcx;
1910 return $self->parse_expr($str_ref);
1914 my ($self, $str_ref) = @_;
1915 return $self->parse_expr($str_ref, {auto_quote
=> "(\\w+\\b (?: \\.\\w+\\b)*) $QR_AQ_SPACE \\s* $QR_COMMENTS"});
1919 my ($self, $undef, $node) = @_;
1920 $self->throw(lc($node->[0]), 'Control exception', $node);
1924 my ($self, $undef, $node, $out_ref) = @_;
1929 my ($self, $str_ref) = @_;
1931 my %ctime = map {$_ => 1} @CONFIG_COMPILETIME;
1932 my %rtime = map {$_ => 1} @CONFIG_RUNTIME;
1934 my $config = $self->parse_args($str_ref, {named_at_front
=> 1, is_parened
=> 1});
1935 my $ref = $config->[0]->[0];
1936 for (my $i = 2; $i < @$ref; $i += 2) {
1937 my $key = $ref->[$i] = uc $ref->[$i];
1938 my $val = $ref->[$i + 1];
1940 splice @$ref, $i, 2, (); # remove the options
1941 $self->{$key} = $self->play_expr($val);
1943 } elsif (! $rtime{$key}) {
1944 $self->throw('parse', "Unknown CONFIG option \"$key\"", undef, pos($$str_ref));
1947 for (my $i = 1; $i < @$config; $i++) {
1948 my $key = $config->[$i] = uc $config->[$i]->[0];
1950 $config->[$i] = "CONFIG $key = ".(defined($self->{$key}) ? $self->{$key} : 'undef');
1951 } elsif (! $rtime{$key}) {
1952 $self->throw('parse', "Unknown CONFIG option \"$key\"", undef, pos($$str_ref));
1959 my ($self, $config) = @_;
1961 my %rtime = map {$_ => 1} @CONFIG_RUNTIME;
1963 ### do runtime config - not many options get these
1964 my ($named, @the_rest) = @$config;
1965 $named = $self->play_expr($named);
1966 @{ $self }{keys %$named} = @{ $named }{keys %$named};
1968 ### show what current values are
1969 return join("\n", map { $rtime{$_} ? ("CONFIG $_ = ".(defined($self->{$_}) ? $self->{$_} : 'undef')) : $_ } @the_rest);
1973 my ($self, $str_ref) = @_;
1974 $$str_ref =~ m{ \G ([Oo][Nn] | [Oo][Ff][Ff] | [Ff][Oo][Rr][Mm][Aa][Tt]) \s* }gcx
1975 || $self->throw('parse', "Unknown DEBUG option", undef, pos($$str_ref));
1977 if ($ret->[0] eq 'format') {
1978 $$str_ref =~ m{ \G ([\"\']) (|.*?[^\\]) \1 \s* }gcxs
1979 || $self->throw('parse', "Missing format string", undef, pos($$str_ref));
1986 my ($self, $ref) = @_;
1987 if ($ref->[0] eq 'on') {
1988 delete $self->{'_debug_off'};
1989 } elsif ($ref->[0] eq 'off') {
1990 $self->{'_debug_off'} = 1;
1991 } elsif ($ref->[0] eq 'format') {
1992 $self->{'_debug_format'} = $ref->[1];
1996 sub parse_DEFAULT
{ $DIRECTIVES->{'SET'}->[0]->(@_) }
1999 my ($self, $set) = @_;
2001 my ($op, $set, $default) = @$_;
2002 next if ! defined $set;
2003 my $val = $self->play_expr($set);
2005 $default = defined($default) ? $self->play_expr($default) : '';
2006 $self->set_variable($set, $default);
2013 my ($self, $str_ref) = @_;
2014 return $self->parse_args($str_ref, {named_at_front
=> 1});
2018 my ($self, $dump, $node) = @_;
2020 my $conf = $self->{'DUMP'};
2021 return if ! $conf && defined $conf; # DUMP => 0
2022 $conf = {} if ref $conf ne 'HASH';
2024 ### allow for handler override
2025 my $handler = $conf->{'handler'};
2027 require Data
::Dumper
;
2028 my $obj = Data
::Dumper-
>new([]);
2030 foreach my $prop (keys %$conf) { $obj->$prop($conf->{$prop}) if $prop =~ /^\w+$/ && ($meth = $obj->can($prop)) }
2031 my $sort = defined($conf->{'Sortkeys'}) ? $obj->Sortkeys : 1;
2032 $obj->Sortkeys(sub { my $h = shift; [grep {$_ !~ $QR_PRIVATE} ($sort ? sort keys %$h : keys %$h)] });
2033 $handler = sub { $obj->Values([@_]); $obj->Dump }
2036 my ($named, @dump) = @$dump;
2037 push @dump, $named if ! $self->is_empty_named_args($named); # add named args back on at end - if there are some
2038 $_ = $self->play_expr($_) foreach @dump;
2040 ### look for the text describing what to dump
2041 my $info = $self->node_info($node);
2044 $out = $handler->(@dump && @dump == 1 ? $dump[0] : \
@dump);
2045 my $name = $info->{'text'};
2046 $name =~ s/^[+=~-]?\s*DUMP\s+//;
2047 $name =~ s/\s*[+=~-]?$//;
2048 $out =~ s/\$VAR1/$name/;
2049 } elsif (defined($conf->{'EntireStash'}) && ! $conf->{'EntireStash'}) {
2052 $out = $handler->($self->{'_vars'});
2053 $out =~ s/\$VAR1/EntireStash/g;
2056 if ($conf->{'html'} || (! defined($conf->{'html'}) && $ENV{'REQUEST_METHOD'})) {
2057 $out = $SCALAR_OPS->{'html'}->($out);
2058 $out = "<pre>$out</pre>";
2059 $out = "<b>DUMP: File \"$info->{file}\" line $info->{line}</b>$out" if $conf->{'header'} || ! defined $conf->{'header'};
2061 $out = "DUMP: File \"$info->{file}\" line $info->{line}\n $out" if $conf->{'header'} || ! defined $conf->{'header'};
2068 my ($self, $str_ref) = @_;
2070 if ($$str_ref =~ m{ \G ([^\W\d]\w*) \s* = \s* }gcx) {
2074 my $filter = $self->parse_expr($str_ref);
2075 $filter = '' if ! defined $filter;
2077 return [$name, $filter];
2081 my ($self, $ref, $node, $out_ref) = @_;
2082 my ($name, $filter) = @$ref;
2084 return '' if ! @$filter;
2086 $self->{'FILTERS'}->{$name} = $filter if length $name;
2088 my $sub_tree = $node->[4];
2092 eval { $self->execute_tree($sub_tree, \
$out) };
2093 die $@ if $@ && ref($@) !~ /Template::Exception$/;
2095 my $var = [[undef, '~', $out], 0, '|', @$filter]; # make a temporary var out of it
2098 return $DIRECTIVES->{'GET'}->[1]->($self, $var, $node, $out_ref);
2102 my ($self, $str_ref) = @_;
2103 my $items = $self->parse_expr($str_ref);
2105 if ($$str_ref =~ m{ \G (= | [Ii][Nn]\b) \s* }gcx) {
2107 $items = $self->parse_expr($str_ref);
2109 return [$var, $items];
2113 my ($self, $ref, $node, $out_ref) = @_;
2115 ### get the items - make sure it is an arrayref
2116 my ($var, $items) = @$ref;
2118 $items = $self->play_expr($items);
2119 return '' if ! defined $items;
2121 if (ref($items) !~ /Iterator$/) {
2122 $items = $PACKAGE_ITERATOR->new($items);
2125 my $sub_tree = $node->[4];
2127 local $self->{'_vars'}->{'loop'} = $items;
2129 ### if the FOREACH tag sets a var - then nothing but the loop var gets localized
2131 my ($item, $error) = $items->get_first;
2134 $self->set_variable($var, $item);
2136 ### execute the sub tree
2137 eval { $self->execute_tree($sub_tree, $out_ref) };
2139 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
2140 if ($err->type eq 'next') {
2141 ($item, $error) = $items->get_next;
2144 last if $err->type =~ /last|break/;
2149 ($item, $error) = $items->get_next;
2151 die $error if $error && $error != 3; # Template::Constants::STATUS_DONE;
2152 ### if the FOREACH tag doesn't set a var - then everything gets localized
2155 ### localize variable access for the foreach
2156 my $swap = $self->{'_vars'};
2157 local $self->{'_vars'} = my $copy = {%$swap};
2159 ### iterate use the iterator object
2160 #foreach (my $i = $items->index; $i <= $#$vals; $items->index(++ $i)) {
2161 my ($item, $error) = $items->get_first;
2164 if (ref($item) eq 'HASH') {
2165 @$copy{keys %$item} = values %$item;
2168 ### execute the sub tree
2169 eval { $self->execute_tree($sub_tree, $out_ref) };
2171 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
2172 if ($err->type eq 'next') {
2173 ($item, $error) = $items->get_next;
2176 last if $err->type =~ /last|break/;
2181 ($item, $error) = $items->get_next;
2183 die $error if $error && $error != 3; # Template::Constants::STATUS_DONE;
2190 my ($self, $str_ref) = @_;
2191 my $ref = $self->parse_expr($str_ref);
2192 $self->throw('parse', "Missing variable name", undef, pos($$str_ref)) if ! defined $ref;
2197 my ($self, $ident, $node) = @_;
2198 my $var = $self->play_expr($ident);
2199 return (! defined $var) ? $self->undefined_get($ident, $node) : $var;
2203 my ($self, $str_ref) = @_;
2204 return $self->parse_expr($str_ref);
2208 my ($self, $var, $node, $out_ref) = @_;
2210 my $val = $self->play_expr($var);
2212 my $body_ref = $node->[4] ||= [];
2213 $self->execute_tree($body_ref, $out_ref);
2217 while ($node = $node->[5]) { # ELSE, ELSIF's
2218 if ($node->[0] eq 'ELSE') {
2219 my $body_ref = $node->[4] ||= [];
2220 $self->execute_tree($body_ref, $out_ref);
2223 my $var = $node->[3];
2224 my $val = $self->play_expr($var);
2226 my $body_ref = $node->[4] ||= [];
2227 $self->execute_tree($body_ref, $out_ref);
2234 sub parse_INCLUDE
{ $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
2237 my ($self, $str_ref, $node, $out_ref) = @_;
2239 ### localize the swap
2240 my $swap = $self->{'_vars'};
2241 local $self->{'_vars'} = {%$swap};
2243 ### localize the blocks
2244 my $blocks = $self->{'BLOCKS'};
2245 local $self->{'BLOCKS'} = {%$blocks};
2247 my $str = $DIRECTIVES->{'PROCESS'}->[1]->($self, $str_ref, $node, $out_ref);
2252 sub parse_INSERT
{ $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
2255 my ($self, $args, $node, $out_ref) = @_;
2257 my ($named, @files) = @$args;
2259 foreach my $name (@files) {
2260 my $filename = $self->play_expr($name);
2261 $$out_ref .= $self->_insert($filename);
2268 my ($self, $str_ref, $node) = @_;
2270 my $name = $self->parse_expr($str_ref, {auto_quote
=> "(\\w+\\b) (?! \\.) \\s* $QR_COMMENTS"});
2271 $self->throw('parse', "Missing macro name", undef, pos($$str_ref)) if ! defined $name;
2273 $name = [ $name, 0 ];
2277 if ($$str_ref =~ m{ \G \( \s* }gcx) {
2278 $args = $self->parse_args($str_ref, {positional_only
=> 1});
2279 $$str_ref =~ m{ \G \) \s* }gcx || $self->throw('parse.missing', "Missing close ')'", undef, pos($$str_ref));
2282 $node->[6] = 1; # set a flag to keep parsing
2283 return [$name, $args];
2287 my ($self, $ref, $node, $out_ref) = @_;
2288 my ($name, $args) = @$ref;
2290 ### get the sub tree
2291 my $sub_tree = $node->[4];
2292 if (! $sub_tree || ! $sub_tree->[0]) {
2293 $self->set_variable($name, undef);
2295 } elsif ($sub_tree->[0]->[0] eq 'BLOCK') {
2296 $sub_tree = $sub_tree->[0]->[4];
2299 my $self_copy = $self;
2300 eval {require Scalar
::Util
; Scalar
::Util
::weaken
($self_copy)};
2302 ### install a closure in the stash that will handle the macro
2303 $self->set_variable($name, sub {
2305 my $copy = $self_copy->{'_vars'};
2306 local $self_copy->{'_vars'}= {%$copy};
2308 ### prevent recursion
2309 local $self_copy->{'_macro_recurse'} = $self_copy->{'_macro_recurse'} || 0;
2310 $self_copy->throw('macro_recurse', "MAX_MACRO_RECURSE $MAX_MACRO_RECURSE reached")
2311 if ++$self_copy->{'_macro_recurse'} > ($self_copy->{'MAX_MACRO_RECURSE'} || $MAX_MACRO_RECURSE);
2315 my $named = pop(@_) if $_[-1] && UNIVERSAL
::isa
($_[-1],'HASH') && $#_ > $#$args;
2316 my @positional = @_;
2317 foreach my $var (@$args) {
2318 $self_copy->set_variable($var, shift(@positional));
2320 foreach my $name (sort keys %$named) {
2321 $self_copy->set_variable([$name, 0], $named->{$name});
2324 ### finally - run the sub tree
2326 $self_copy->execute_tree($sub_tree, \
$out);
2334 my ($self, $hash) = @_;
2336 my @keys = keys %$hash;
2339 if ($self->{'_top_level'}) {
2340 $ref = $self->{'_template'} ||= {};
2342 $ref = $self->{'_component'} ||= {};
2345 @{ $ref }{ @keys } = @{ $hash }{ @keys };
2349 sub parse_PERL
{ shift-
>{'_in_perl'} = 1; return }
2352 my ($self, $info, $node, $out_ref) = @_;
2353 $self->throw('perl', 'EVAL_PERL not set') if ! $self->{'EVAL_PERL'};
2355 ### fill in any variables
2356 my $perl = $node->[4] || return;
2358 $self->execute_tree($perl, \
$out);
2359 $out = $1 if $out =~ /^(.+)$/s; # blatant untaint - shouldn't use perl anyway
2364 package CGI
::Ex
::Template
::Perl
;
2366 my $context = $self->context;
2367 my $stash = $context->stash;
2369 ### setup a fake handle
2371 tie
*PERLOUT
, $CGI::Ex
::Template
::PACKAGE_PERL_HANDLE
, $out_ref;
2372 my $old_fh = select PERLOUT
;
2377 ### put the handle back
2385 $self->throw('undef', $err) if ref($err) !~ /Template::Exception$/;
2393 my ($self, $str_ref) = @_;
2395 return $self->parse_args($str_ref, {
2396 named_at_front
=> 1,
2397 allow_bare_filenames
=> 1,
2403 my ($self, $info, $node, $out_ref) = @_;
2405 my ($args, @files) = @$info;
2408 # [[undef, '{}', 'key1', 'val1', 'key2', 'val2'], 0]
2410 foreach (my $i = 2; $i < @$args; $i+=2) {
2411 my $key = $args->[$i];
2412 my $val = $self->play_expr($args->[$i+1]);
2413 if (ref($key) && @$key == 2 && $key->[0] eq 'import' && UNIVERSAL
::isa
($val, 'HASH')) { # import ?! - whatever
2414 foreach my $key (keys %$val) {
2415 $self->set_variable([$key,0], $val->{$key});
2419 $self->set_variable($key, $val);
2422 ### iterate on any passed block or filename
2423 foreach my $ref (@files) {
2424 next if ! defined $ref;
2425 my $filename = $self->play_expr($ref);
2426 my $out = ''; # have temp item to allow clear to correctly clear
2428 ### normal blocks or filenames
2429 if (! ref $filename) {
2430 eval { $self->_process($filename, $self->{'_vars'}, \
$out) }; # restart the swap - passing it our current stash
2432 ### allow for $template which is used in some odd instances
2435 if ($ref->[0] eq 'template') {
2438 $doc = $self->play_expr($ref);
2439 if (ref($doc) ne 'HASH' || ! $doc->{'_tree'}) {
2440 $self->throw('process', "Passed item doesn't appear to be a valid document");
2443 $self->throw('process', "Recursion detected in $node->[0] \$template") if $self->{'_process_dollar_template'};
2444 local $self->{'_process_dollar_template'} = 1;
2445 local $self->{'_component'} = $filename;
2446 return if ! $doc->{'_tree'};
2448 ### execute and trim
2449 eval { $self->execute_tree($doc->{'_tree'}, \
$out) };
2450 if ($self->{'TRIM'}) {
2451 $out =~ s{ \s+ $ }{}x;
2452 $out =~ s{ ^ \s+ }{}x;
2455 ### handle exceptions
2457 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2458 $err->doc($doc) if $doc && $err->can('doc') && ! $err->doc;
2463 ### append any output
2466 die $err if ref($err) !~ /Template::Exception$/ || $err->type !~ /return/;
2474 my ($self, $info, $node, $out_ref) = @_;
2475 $self->throw('perl', 'EVAL_PERL not set') if ! $self->{'EVAL_PERL'};
2477 ### fill in any variables
2478 my $tree = $node->[4] || return;
2480 $self->execute_tree($tree, \
$perl);
2481 $perl = $1 if $perl =~ /^(.+)$/s; # blatant untaint - shouldn't use perl anyway
2487 package CGI
::Ex
::Template
::Perl
;
2489 my $context = $self->context;
2490 my $stash = $context->stash;
2497 $$out_ref .= $output;
2500 $self->throw('undef', $err) if ref($err) !~ /Template::Exception$/;
2508 my ($self, $str_ref, $node, $initial_op, $initial_var) = @_;
2513 if ($$str_ref =~ m{ \G $QR_DIRECTIVE }gcx # find a word
2514 && ((pos($$str_ref) -= length($1)) || 1) # always revert
2515 && $DIRECTIVES->{$self->{'ANYCASE'} ? uc $1 : $1}) { # make sure its a directive - if so set up capturing
2516 $node->[6] = 1; # set a flag to keep parsing
2517 my $val = $node->[4] ||= []; # setup storage
2518 return [[$initial_op, $initial_var, $val]];
2519 } else { # get a normal variable
2520 return [[$initial_op, $initial_var, $self->parse_expr($str_ref)]];
2525 my $set = $self->parse_expr($str_ref);
2526 last if ! defined $set;
2528 if ($$str_ref =~ m{ \G ($QR_OP_ASSIGN) >? \s* }gcx) {
2530 if ($$str_ref =~ m{ \G $QR_DIRECTIVE }gcx # find a word
2531 && ((pos($$str_ref) -= length($1)) || 1) # always revert
2532 && $DIRECTIVES->{$self->{'ANYCASE'} ? uc $1 : $1}) { # make sure its a directive - if so set up capturing
2533 $node->[6] = 1; # set a flag to keep parsing
2534 my $val = $node->[4] ||= []; # setup storage
2535 push @SET, [$op, $set, $val];
2537 } else { # get a normal variable
2538 push @SET, [$op, $set, $self->parse_expr($str_ref)];
2541 push @SET, ['=', $set, undef];
2549 my ($self, $set, $node) = @_;
2551 my ($op, $set, $val) = @$_;
2552 if (! defined $val) { # not defined
2554 } elsif ($node->[4] && $val == $node->[4]) { # a captured directive
2555 my $sub_tree = $node->[4];
2556 $sub_tree = $sub_tree->[0]->[4] if $sub_tree->[0] && $sub_tree->[0]->[0] eq 'BLOCK';
2558 $self->execute_tree($sub_tree, \
$val);
2559 } else { # normal var
2560 $val = $self->play_expr($val);
2563 if ($OP_DISPATCH->{$op}) {
2565 $val = $OP_DISPATCH->{$op}->($self->play_expr($set), $val);
2568 $self->set_variable($set, $val);
2573 sub parse_SWITCH
{ $DIRECTIVES->{'GET'}->[0]->(@_) }
2576 my ($self, $var, $node, $out_ref) = @_;
2578 my $val = $self->play_expr($var);
2579 $val = '' if ! defined $val;
2580 ### $node->[4] is thrown away
2583 while ($node = $node->[5]) { # CASES
2584 my $var = $node->[3];
2585 if (! defined $var) {
2586 $default = $node->[4];
2590 my $val2 = $self->play_expr($var);
2591 $val2 = [$val2] if ! UNIVERSAL
::isa
($val2, 'ARRAY');
2592 for my $test (@$val2) { # find matching values
2593 next if ! defined $val && defined $test;
2594 next if defined $val && ! defined $test;
2595 if ($val ne $test) { # check string-wise first - then numerical
2596 next if $val !~ m{ ^ -? $QR_NUM $ }ox;
2597 next if $test !~ m{ ^ -? $QR_NUM $ }ox;
2598 next if $val != $test;
2601 my $body_ref = $node->[4] ||= [];
2602 $self->execute_tree($body_ref, $out_ref);
2608 $self->execute_tree($default, $out_ref);
2615 my ($self, $str_ref, $node) = @_;
2616 my $name = $self->parse_expr($str_ref, {auto_quote
=> "(\\w+\\b (?: \\.\\w+\\b)*) $QR_AQ_SPACE \\s* $QR_COMMENTS"});
2617 $self->throw('parse.missing', "Missing name in THROW", $node, pos($$str_ref)) if ! $name;
2618 my $args = $self->parse_args($str_ref, {named_at_front
=> 1});
2619 return [$name, $args];
2623 my ($self, $ref, $node) = @_;
2624 my ($name, $args) = @$ref;
2626 $name = $self->play_expr($name);
2628 my ($named, @args) = @$args;
2629 push @args, $named if ! $self->is_empty_named_args($named); # add named args back on at end - if there are some
2631 @args = map { $self->play_expr($_) } @args;
2632 $self->throw($name, \
@args, $node);
2636 my ($self, $foo, $node, $out_ref) = @_;
2639 my $body_ref = $node->[4];
2640 eval { $self->execute_tree($body_ref, \
$out) };
2643 if (! $node->[5]) { # no catch or final
2644 if (! $err) { # no final block and no error
2648 $self->throw('parse.missing', "Missing CATCH block", $node);
2651 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2652 if ($err->type =~ /stop|return/) {
2658 ### loop through the nested catch and final blocks
2661 my $type = $err ? $err->type : '';
2663 while ($node = $node->[5]) { # CATCH
2664 if ($node->[0] eq 'FINAL') {
2665 $final = $node->[4];
2669 my $name = $self->play_expr($node->[3]);
2670 $name = '' if ! defined $name || lc($name) eq 'default';
2671 if ($type =~ / ^ \Q$name\E \b /x
2672 && (! defined($last_found) || length($last_found) < length($name))) { # more specific wins
2673 $catch_body_ref = $node->[4] || [];
2674 $last_found = $name;
2678 ### play the best catch block
2680 if (! $catch_body_ref) {
2684 local $self->{'_vars'}->{'error'} = $err;
2685 local $self->{'_vars'}->{'e'} = $err;
2686 eval { $self->execute_tree($catch_body_ref, \
$out) };
2694 $self->execute_tree($final, \
$out) if $final;
2702 my $ref = $DIRECTIVES->{'IF'}->[0]->(@_);
2703 return [[undef, '!', $ref], 0];
2706 sub play_UNLESS
{ return $DIRECTIVES->{'IF'}->[1]->(@_) }
2709 my ($self, $str_ref) = @_;
2712 my $mark = pos $$str_ref;
2713 if (defined(my $_var = $self->parse_expr($str_ref, {auto_quote
=> "(\\w+\\b) (?! \\.) \\s* $QR_COMMENTS"}))
2714 && ($$str_ref =~ m{ \G = >? \s* $QR_COMMENTS }gcxo # make sure there is assignment
2715 || ((pos($$str_ref) = $mark) && 0)) # otherwise we need to rollback
2720 my $module = $self->parse_expr($str_ref, {auto_quote
=> "(\\w+\\b (?: (?:\\.|::) \\w+\\b)*) (?! \\.) \\s* $QR_COMMENTS"});
2721 $self->throw('parse', "Missing plugin name while parsing $$str_ref", undef, pos($$str_ref)) if ! defined $module;
2722 $module =~ s/\./::/g;
2725 my $open = $$str_ref =~ m{ \G \( \s* $QR_COMMENTS }gcxo;
2726 $args = $self->parse_args($str_ref, {is_parened
=> $open, named_at_front
=> 1});
2729 $$str_ref =~ m{ \G \) \s* $QR_COMMENTS }gcxo || $self->throw('parse.missing', "Missing close ')'", undef, pos($$str_ref));
2732 return [$var, $module, $args];
2736 my ($self, $ref, $node, $out_ref) = @_;
2737 my ($var, $module, $args) = @$ref;
2739 ### get the stash storage location - default to the module
2740 $var = $module if ! defined $var;
2741 my @var = map {($_, 0, '.')} split /(?:\.|::)/, $var;
2742 pop @var; # remove the trailing '.'
2744 my ($named, @args) = @$args;
2745 push @args, $named if ! $self->is_empty_named_args($named); # add named args back on at end - if there are some
2747 ### look for a plugin_base
2748 my $BASE = $self->{'PLUGIN_BASE'} || 'Template::Plugin'; # I'm not maintaining plugins - leave that to TT
2751 foreach my $base (ref($BASE) eq 'ARRAY' ? @$BASE : $BASE) {
2752 my $package = $self->{'PLUGINS'}->{$module} ? $self->{'PLUGINS'}->{$module}
2753 : $self->{'PLUGIN_FACTORY'}->{$module} ? $self->{'PLUGIN_FACTORY'}->{$module}
2754 : "${base}::${module}";
2755 my $require = "$package.pm";
2756 $require =~ s
|::|/|g
;
2758 ### try and load the module - fall back to bare module if allowed
2759 if ($self->{'PLUGIN_FACTORY'}->{$module} || eval {require $require}) {
2760 my $shape = $package->load;
2761 my $context = $self->context;
2762 $obj = $shape->new($context, map { $self->play_expr($_) } @args);
2763 } elsif (lc($module) eq 'iterator') { # use our iterator if none found (TT's works just fine)
2764 $obj = $PACKAGE_ITERATOR->new($args[0]);
2765 } elsif (my @packages = grep {lc($package) eq lc($_)} @{ $self->list_plugins({base
=> $base}) }) {
2766 foreach my $package (@packages) {
2767 my $require = "$package.pm";
2768 $require =~ s
|::|/|g
;
2769 eval {require $require} || next;
2770 my $shape = $package->load;
2771 my $context = $self->context;
2772 $obj = $shape->new($context, map { $self->play_expr($_) } @args);
2774 } elsif ($self->{'LOAD_PERL'}) {
2775 my $require = "$module.pm";
2776 $require =~ s
|::|/|g
;
2777 if (eval {require $require}) {
2778 $obj = $module->new(map { $self->play_expr($_) } @args);
2782 if (! defined $obj) {
2783 my $err = "$module: plugin not found";
2784 $self->throw('plugin', $err);
2788 $self->set_variable(\
@var, $obj);
2794 my ($self, $str_ref) = @_;
2796 my $ref = $self->parse_args($str_ref, {
2797 named_at_front
=> 1,
2805 my ($self, $ref, $node, $out_ref) = @_;
2807 my ($blocks, $args, $name) = @$ref;
2810 # [[undef, '{}', 'key1', 'val1', 'key2', 'val2'], 0]
2813 foreach (my $i = 2; $i < @$args; $i+=2) {
2814 my $key = $args->[$i];
2815 my $val = $self->play_expr($args->[$i+1]);
2817 if (@$key == 2 && ! ref($key->[0]) && ! $key->[1]) {
2820 $self->set_variable($key, $val);
2821 next; # what TT does
2824 $hash->{$key} = $val;
2827 ### prepare the blocks
2828 my $prefix = $hash->{'prefix'} || (ref($name) && @$name == 2 && ! $name->[1] && ! ref($name->[0])) ? "$name->[0]/" : '';
2829 foreach my $key (keys %$blocks) {
2830 $blocks->{$key} = {name
=> "${prefix}${key}", _tree
=> $blocks->{$key}};
2832 $hash->{'blocks'} = $blocks;
2835 if (! eval { require Template
::View
}) {
2836 $self->throw('view', 'Could not load Template::View library');
2838 my $view = Template
::View-
>new($self->context, $hash)
2839 || $self->throw('view', $Template::View
::ERROR
);
2842 my $old_view = $self->play_expr(['view', 0]);
2843 $self->set_variable($name, $view);
2844 $self->set_variable(['view', 0], $view);
2848 $self->execute_tree($node->[4], \
$out);
2852 $self->set_variable(['view', 0], $old_view);
2858 sub parse_WHILE
{ $DIRECTIVES->{'IF'}->[0]->(@_) }
2861 my ($self, $var, $node, $out_ref) = @_;
2862 return '' if ! defined $var;
2864 my $sub_tree = $node->[4];
2866 ### iterate use the iterator object
2867 my $count = $WHILE_MAX;
2868 while (--$count > 0) {
2870 $self->play_expr($var) || last;
2872 ### execute the sub tree
2873 eval { $self->execute_tree($sub_tree, $out_ref) };
2875 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
2876 next if $err->type =~ /next/;
2877 last if $err->type =~ /last|break/;
2882 die "WHILE loop terminated (> $WHILE_MAX iterations)\n" if ! $count;
2887 sub parse_WRAPPER
{ $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
2890 my ($self, $args, $node, $out_ref) = @_;
2891 my $sub_tree = $node->[4] || return;
2893 my ($named, @files) = @$args;
2896 $self->execute_tree($sub_tree, \
$out);
2898 foreach my $name (reverse @files) {
2899 local $self->{'_vars'}->{'content'} = $out;
2901 $DIRECTIVES->{'INCLUDE'}->[1]->($self, [$named, $name], $node, \
$out);
2908 ###----------------------------------------------------------------###
2912 $self->{'_vars'} = shift if $#_ == 0;
2913 return $self->{'_vars'} ||= {};
2916 sub include_filename
{
2917 my ($self, $file) = @_;
2918 if ($file =~ m
|^/|) {
2919 $self->throw('file', "$file absolute paths are not allowed (set ABSOLUTE option)") if ! $self->{'ABSOLUTE'};
2920 return $file if -e
$file;
2921 } elsif ($file =~ m{(^|/)\.\./}) {
2922 $self->throw('file', "$file relative paths are not allowed (set RELATIVE option)") if ! $self->{'RELATIVE'};
2923 return $file if -e
$file;
2926 my $paths = $self->{'INCLUDE_PATHS'} ||= do {
2927 # TT does this everytime a file is looked up - we are going to do it just in time - the first time
2928 my $paths = $self->{'INCLUDE_PATH'} || [];
2929 $paths = $paths->() if UNIVERSAL
::isa
($paths, 'CODE');
2930 $paths = $self->split_paths($paths) if ! UNIVERSAL
::isa
($paths, 'ARRAY');
2931 $paths; # return of the do
2933 foreach my $path (@$paths) {
2934 return "$path/$file" if -e
"$path/$file";
2937 $self->throw('file', "$file: not found");
2941 my ($self, $path) = @_;
2942 return $path if ref $path;
2943 my $delim = $self->{'DELIMITER'} || ':';
2944 $delim = ($delim eq ':' && $^O eq 'MSWin32') ? qr
|:(?!/)| : qr
|\Q
$delim\E
|;
2945 return [split $delim, $path];
2949 my ($self, $file) = @_;
2950 return $self->slurp($self->include_filename($file));
2954 my ($self, $file) = @_;
2956 open(FH
, "<$file") || $self->throw('file', "$file couldn't be opened: $!");
2957 read FH
, my $txt, -s
$file;
2962 sub process_simple
{
2964 my $in = shift || die "Missing input";
2965 my $swap = shift || die "Missing variable hash";
2966 my $out = shift || die "Missing output string ref";
2969 delete $self->{'_debug_off'};
2970 delete $self->{'_debug_format'};
2971 local $self->{'_start_top_level'} = 1;
2972 $self->_process($in, $swap, $out);
2975 if ($err->type !~ /stop|return|next|last|break/) {
2976 $self->{'error'} = $err;
2984 my ($self, $in, $swap, $out, @ARGS) = @_;
2985 delete $self->{'error'};
2988 $args = ($#ARGS == 0 && UNIVERSAL
::isa
($ARGS[0], 'HASH')) ? {%{$ARGS[0]}} : {@ARGS} if scalar @ARGS;
2989 $self->DEBUG("set binmode\n") if $DEBUG && $args->{'binmode'}; # holdover for TT2 tests
2994 if (UNIVERSAL
::isa
($in, 'SCALAR')) { # reference to a string
2996 } elsif (UNIVERSAL
::isa
($in, 'CODE')) {
2998 $content = \
$content;
2999 } else { # should be a file handle
3002 $content = \
$content;
3005 ### should be a filename
3010 ### prepare block localization
3011 my $blocks = $self->{'BLOCKS'} ||= {};
3018 ### localize the stash
3020 my $var1 = $self->{'_vars'} ||= {};
3021 my $var2 = $self->{'VARIABLES'} || $self->{'PRE_DEFINE'} || {};
3022 $var1->{'global'} ||= {}; # allow for the "global" namespace - that continues in between processing
3023 my $copy = {%$var2, %$var1, %$swap};
3025 local $self->{'BLOCKS'} = $blocks = {%$blocks}; # localize blocks - but save a copy to possibly restore
3026 local $self->{'_template'};
3028 delete $self->{'_debug_off'};
3029 delete $self->{'_debug_format'};
3031 ### handle pre process items that go before every document
3033 if ($self->{'PRE_PROCESS'}) {
3034 $self->_load_template_meta($content);
3035 foreach my $name (@{ $self->split_paths($self->{'PRE_PROCESS'}) }) {
3036 $self->_process($name, $copy, \
$pre);
3040 ### process the central file now - catching errors to allow for the ERROR config
3042 ### handle the PROCESS config - which loads another template in place of the real one
3043 if (exists $self->{'PROCESS'}) {
3044 $self->_load_template_meta($content);
3045 foreach my $name (@{ $self->split_paths($self->{'PROCESS'}) }) {
3046 next if ! length $name;
3047 $self->_process($name, $copy, \
$output);
3050 ### handle "normal" content
3052 local $self->{'_start_top_level'} = 1;
3053 $self->_process($content, $copy, \
$output);
3057 ### catch errors with ERROR config
3059 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
3060 die $err if $err->type =~ /stop|return/;
3061 my $catch = $self->{'ERRORS'} || $self->{'ERROR'} || die $err;
3062 $catch = {default => $catch} if ! ref $catch;
3063 my $type = $err->type;
3066 foreach my $name (keys %$catch) {
3067 my $_name = (! defined $name || lc($name) eq 'default') ? '' : $name;
3068 if ($type =~ / ^ \Q$_name\E \b /x
3069 && (! defined($last_found) || length($last_found) < length($_name))) { # more specific wins
3070 $last_found = $_name;
3071 $file = $catch->{$name};
3075 ### found error handler - try it out
3076 if (defined $file) {
3078 local $copy->{'error'} = local $copy->{'e'} = $err;
3079 $self->_process($file, $copy, \
$output);
3083 ### handle wrapper directives
3084 if (exists $self->{'WRAPPER'}) {
3085 $self->_load_template_meta($content);
3086 foreach my $name (reverse @{ $self->split_paths($self->{'WRAPPER'}) }) {
3087 next if ! length $name;
3088 local $copy->{'content'} = $output;
3090 $self->_process($name, $copy, \
$out);
3095 $output = $pre . $output if length $pre;
3097 ### handle post process items that go after every document
3098 if ($self->{'POST_PROCESS'}) {
3099 $self->_load_template_meta($content);
3100 foreach my $name (@{ $self->split_paths($self->{'POST_PROCESS'}) }) {
3101 $self->_process($name, $copy, \
$output);
3107 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
3108 if ($err->type !~ /stop|return|next|last|break/) {
3109 $self->{'error'} = $err;
3116 ### clear blocks as asked (AUTO_RESET) defaults to on
3117 $self->{'BLOCKS'} = $blocks if exists($self->{'AUTO_RESET'}) && ! $self->{'AUTO_RESET'};
3119 ### send the content back out
3120 $out ||= $self->{'OUTPUT'};
3122 if (UNIVERSAL
::isa
($out, 'CODE')) {
3124 } elsif (UNIVERSAL
::can
($out, 'print')) {
3125 $out->print($output);
3126 } elsif (UNIVERSAL
::isa
($out, 'SCALAR')) { # reference to a string
3128 } elsif (UNIVERSAL
::isa
($out, 'ARRAY')) {
3129 push @$out, $output;
3130 } else { # should be a file handle
3133 } elsif ($out) { # should be a filename
3135 if ($out =~ m
|^/|) {
3136 if (! $self->{'ABSOLUTE'}) {
3137 $self->{'error'} = $self->throw('file', "ABSOLUTE paths disabled");
3141 } elsif ($out =~ m
|^\
.\
.?/|) {
3142 if (! $self->{'RELATIVE'}) {
3143 $self->{'error'} = $self->throw('file', "RELATIVE paths disabled");
3148 if (! $self->{'OUTPUT_PATH'}) {
3149 $self->{'error'} = $self->throw('file', "OUTPUT_PATH not set");
3151 $file = $self->{'OUTPUT_PATH'} . '/' . $out;
3156 if (open FH
, ">$file") {
3157 if (my $bm = $args->{'binmode'}) {
3158 if (+$bm == 1) { binmode FH
}
3159 else { binmode FH
, $bm }
3164 $self->{'error'} = $self->throw('file', "$out couldn't be opened for writing: $!");
3171 return if $self->{'error'};
3175 sub error
{ shift-
>{'error'} }
3179 print STDERR
"DEBUG: ", @_;
3182 sub _load_template_meta
{
3184 return if $self->{'_template'}; # only do once as need
3186 ### load the meta data for the top document
3187 ### this is needed by some of the custom handlers such as PRE_PROCESS and POST_PROCESS
3188 my $content = shift;
3189 my $doc = $self->{'_template'} = $self->load_parsed_tree($content) || {};
3190 my $meta = ($doc->{'_tree'} && ref($doc->{'_tree'}->[0]) && $doc->{'_tree'}->[0]->[0] eq 'META')
3191 ? $doc->{'_tree'}->[0]->[3] : {};
3193 $self->{'_template'} = $doc;
3194 @{ $doc }{keys %$meta} = values %$meta;
3200 ###----------------------------------------------------------------###
3206 return $type if ref($type) =~ /Template::Exception$/;
3207 if (ref($info) eq 'ARRAY') {
3208 my $hash = ref($info->[-1]) eq 'HASH' ? pop(@$info) : {};
3209 if (@$info >= 2 || scalar keys %$hash) {
3211 $hash->{$_} = $info->[$_] for 0 .. $#$info;
3212 $hash->{'args'} = $info;
3214 } elsif (@$info == 1) {
3221 return $PACKAGE_EXCEPTION->new($type, $info, @_);
3224 sub throw
{ die shift-
>exception(@_) }
3228 return bless {_template
=> $self}, $PACKAGE_CONTEXT; # a fake context
3232 my ($self, $ident, $node) = @_;
3233 return $self->{'UNDEFINED_GET'}->($self, $ident, $node) if $self->{'UNDEFINED_GET'};
3238 my ($self, $ident) = @_;
3239 return $self->{'UNDEFINED_ANY'}->($self, $ident) if $self->{'UNDEFINED_ANY'};
3245 return $self->{'_filters'} ||= eval { require Template
::Filters
; $Template::Filters
::FILTERS
} || {};
3250 my $args = shift || {};
3251 my $base = $args->{'base'} || '';
3253 return $self->{'_plugins'}->{$base} ||= do {
3257 my @dirs = grep {-d
$_} map {"$_/$base"} @INC;
3259 foreach my $dir (@dirs) {
3261 File
::Find
::find
(sub {
3262 my $mod = $base .'/'. ($File::Find
::name
=~ m
|^ $dir / (.*\w
) \
.pm
$|x
? $1 : return);
3264 push @plugins, $mod;
3268 \
@plugins; # return of the do
3273 my ($self, $node) = @_;
3274 my $info = $self->node_info($node);
3275 my $format = $self->{'_debug_format'} || $self->{'DEBUG_FORMAT'} || "\n## \$file line \$line : [% \$text %] ##\n";
3276 $format =~ s{\$(file|line|text)}{$info->{$1}}g
;
3281 my ($self, $node) = @_;
3282 my $doc = $self->{'_component'};
3284 my $j = $node->[2] || return ''; # META can be 0
3285 $doc->{'_content'} ||= do { my $s = $self->slurp($doc->{'_filename'}) ; \
$s };
3286 my $s = substr(${ $doc->{'_content'} }, $i, $j - $i);
3290 file
=> $doc->{'name'},
3291 line
=> $self->get_line_number_by_index($doc, $i),
3296 sub get_line_number_by_index
{
3297 my ($self, $doc, $index, $include_char) = @_;
3298 return 1 if $index <= 0;
3300 ### get the line offsets for the doc
3301 my $lines = $doc->{'_line_offsets'} ||= do {
3302 $doc->{'_content'} ||= do { my $s = $self->slurp($doc->{'_filename'}) ; \
$s };
3306 $i = index(${ $doc->{'_content'} }, "\n", $i) + 1;
3313 ### binary search them (this is fast even on big docs)
3314 my ($i, $j) = (0, $#$lines);
3315 if ($index > $lines->[-1]) {
3319 last if abs($i - $j) <= 1;
3320 my $k = int(($i + $j) / 2);
3321 $j = $k if $lines->[$k] >= $index;
3322 $i = $k if $lines->[$k] <= $index;
3325 return $include_char ? ($i + 1, $index - $lines->[$i]) : $i + 1;
3328 ###----------------------------------------------------------------###
3329 ### long virtual methods or filters
3330 ### many of these vmethods have used code from Template/Stash.pm to
3331 ### assure conformance with the TT spec.
3333 sub define_vmethod
{
3334 my ($self, $type, $name, $sub) = @_;
3335 if ( $type =~ /scalar|item/i) { $SCALAR_OPS->{$name} = $sub }
3336 elsif ($type =~ /array|list/i ) { $LIST_OPS->{ $name} = $sub }
3337 elsif ($type =~ /hash/i ) { $HASH_OPS->{ $name} = $sub }
3338 elsif ($type =~ /filter/i ) { $FILTER_OPS->{$name} = $sub }
3340 die "Invalid type vmethod type $type";
3345 sub vmethod_fmt_scalar
{
3346 my $str = shift; $str = '' if ! defined $str;
3347 my $pat = shift; $pat = '%s' if ! defined $pat;
3349 return @_ ? sprintf($pat, $_[0], $str)
3350 : sprintf($pat, $str);
3353 sub vmethod_fmt_list
{
3354 my $ref = shift || return '';
3355 my $pat = shift; $pat = '%s' if ! defined $pat;
3356 my $sep = shift; $sep = ' ' if ! defined $sep;
3358 return @_ ? join($sep, map {sprintf $pat, $_[0], $_} @$ref)
3359 : join($sep, map {sprintf $pat, $_} @$ref);
3362 sub vmethod_fmt_hash
{
3363 my $ref = shift || return '';
3364 my $pat = shift; $pat = "%s\t%s" if ! defined $pat;
3365 my $sep = shift; $sep = "\n" if ! defined $sep;
3367 return ! @_ ? join($sep, map {sprintf $pat, $_, $ref->{$_}} sort keys %$ref)
3368 : @_ == 1 ? join($sep, map {sprintf $pat, $_[0], $_, $ref->{$_}} sort keys %$ref) # don't get to pick - it applies to the key
3369 : join($sep, map {sprintf $pat, $_[0], $_, $_[1], $ref->{$_}} sort keys %$ref);
3374 my $size = shift || 1;
3376 if ($size < 0) { # chunk from the opposite end
3377 $str = reverse $str;
3379 unshift(@list, scalar reverse $1) while $str =~ /( .{$size} | .+ )/xg;
3381 push(@list, $1) while $str =~ /( .{$size} | .+ )/xg;
3386 sub vmethod_indent
{
3387 my $str = shift; $str = '' if ! defined $str;
3388 my $pre = shift; $pre = 4 if ! defined $pre;
3389 $pre = ' ' x
$pre if $pre =~ /^\d+$/;
3390 $str =~ s/^/$pre/mg;
3394 sub vmethod_format
{
3395 my $str = shift; $str = '' if ! defined $str;
3396 my $pat = shift; $pat = '%s' if ! defined $pat;
3398 return join "\n", map{ sprintf $pat, $_[0], $_ } split(/\n/, $str);
3400 return join "\n", map{ sprintf $pat, $_ } split(/\n/, $str);
3404 sub vmethod_list_hash
{
3405 my ($hash, $what) = @_;
3406 $what = 'pairs' if ! $what || $what !~ /^(keys|values|each|pairs)$/;
3407 return $HASH_OPS->{$what}->($hash);
3412 my ($str, $pat, $global) = @_;
3413 return [] if ! defined $str || ! defined $pat;
3414 my @res = $global ? ($str =~ /$pat/g) : ($str =~ /$pat/);
3415 return @res ? \
@res : '';
3419 my ($list, $field) = @_;
3420 return defined($field)
3421 ? [map {$_->[0]} sort {$a->[1] <=> $b->[1]} map {[$_, (ref $_ eq 'HASH' ? $_->{$field}
3422 : UNIVERSAL
::can
($_, $field) ? $_->$field()
3424 : [sort {$a <=> $b} @$list];
3432 my @ind = map { $ref->[ rand @$ref ] } 1 .. $n;
3433 return $n == 1 ? $ind[0] : \
@ind;
3436 sub vmethod_repeat
{
3437 my ($str, $n, $join) = @_;
3438 return '' if ! defined $str || ! length $str;
3439 $n = 1 if ! defined($n) || ! length $n;
3440 $join = '' if ! defined $join;
3441 return join $join, ($str) x
$n;
3444 ### This method is a combination of my submissions along
3445 ### with work from Andy Wardley, Sergey Martynoff, Nik Clayton, and Josh Rosenbaum
3446 sub vmethod_replace
{
3447 my ($text, $pattern, $replace, $global) = @_;
3448 $text = '' unless defined $text;
3449 $pattern = '' unless defined $pattern;
3450 $replace = '' unless defined $replace;
3451 $global = 1 unless defined $global;
3453 my ($chunk, $start, $end) = @_;
3454 $chunk =~ s
{ \\(\\|\
$) | \
$ (\d
+) }{
3456 : ($2 > $#$start || $2 == 0) ? ''
3457 : substr($text, $start->[$2], $end->[$2] - $start->[$2]);
3462 $text =~ s{$pattern}{ $expand->($replace, [@-], [@+]) }eg;
3464 $text =~ s{$pattern}{ $expand->($replace, [@-], [@+]) }e;
3470 my ($list, $field) = @_;
3471 return defined($field)
3472 ? [map {$_->[0]} sort {$a->[1] cmp $b->[1]} map {[$_, lc(ref $_ eq 'HASH' ? $_->{$field}
3473 : UNIVERSAL
::can
($_, $field) ? $_->$field()
3475 : [map {$_->[0]} sort {$a->[1] cmp $b->[1]} map {[$_, lc $_]} @$list ]; # case insensitive
3478 sub vmethod_splice
{
3479 my ($ref, $i, $len, @replace) = @_;
3480 @replace = @{ $replace[0] } if @replace == 1 && ref $replace[0] eq 'ARRAY';
3482 return [splice @$ref, $i || 0, $len, @replace];
3483 } elsif (defined $i) {
3484 return [splice @$ref, $i];
3486 return [splice @$ref];
3491 my ($str, $pat, $lim) = @_;
3492 $str = '' if ! defined $str;
3493 if (defined $lim) { return defined $pat ? [split $pat, $str, $lim] : [split ' ', $str, $lim] }
3494 else { return defined $pat ? [split $pat, $str ] : [split ' ', $str ] }
3497 sub vmethod_substr
{
3498 my ($str, $i, $len, $replace) = @_;
3500 return substr($str, $i) if ! defined $len;
3501 return substr($str, $i, $len) if ! defined $replace;
3502 substr($str, $i, $len, $replace);
3508 utf8
::encode
($str) if defined &utf8
::encode
;
3509 $str =~ s/([^A-Za-z0-9\-_.!~*\'()])/sprintf('%%%02X', ord($1))/eg;
3515 utf8
::encode
($str) if defined &utf8
::encode
;
3516 $str =~ s/([^;\/?:@&=+\$,A-Za-z0-9\-_.!~*\'()])/sprintf
('%%%02X', ord($1))/eg
;
3521 my $context = shift;
3524 ### prevent recursion
3525 my $t = $context->_template;
3526 local $t->{'_eval_recurse'} = $t->{'_eval_recurse'} || 0;
3527 $context->throw('eval_recurse', "MAX_EVAL_RECURSE $MAX_EVAL_RECURSE reached")
3528 if ++$t->{'_eval_recurse'} > ($t->{'MAX_EVAL_RECURSE'} || $MAX_EVAL_RECURSE);
3532 return $context->process(\
$text);
3536 sub filter_redirect
{
3537 my ($context, $file, $options) = @_;
3538 my $path = $context->config->{'OUTPUT_PATH'} || $context->throw('redirect', 'OUTPUT_PATH is not set');
3539 $context->throw('redirect', 'Invalid filename - cannot include "/../"')
3540 if $file =~ m{(^|/)\.\./};
3546 File
::Path
::mkpath
($path) || $context->throw('redirect', "Couldn't mkpath \"$path\": $!");
3549 open (FH
, ">$path/$file") || $context->throw('redirect', "Couldn't open \"$file\": $!");
3550 if (my $bm = (! $options) ? 0 : ref($options) ? $options->{'binmode'} : $options) {
3551 if (+$bm == 1) { binmode FH
}
3552 else { binmode FH
, $bm}
3560 ###----------------------------------------------------------------###
3563 my $obj = UNIVERSAL
::isa
($_[0], __PACKAGE__
) ? shift : __PACKAGE__-
>new;
3565 require Data
::Dumper
;
3566 return Data
::Dumper
::Dumper
($obj->parse_tree(\
$str));
3569 sub dump_parse_expr
{
3570 my $obj = UNIVERSAL
::isa
($_[0], __PACKAGE__
) ? shift : __PACKAGE__-
>new;
3572 require Data
::Dumper
;
3573 return Data
::Dumper
::Dumper
($obj->parse_expr(\
$str));
3576 ###----------------------------------------------------------------###
3578 package CGI
::Ex
::Template
::Exception
;
3581 '""' => \
&as_string
,
3582 bool
=> sub { defined shift },
3586 my ($class, $type, $info, $node, $pos, $doc) = @_;
3587 return bless [$type, $info, $node, $pos, $doc], $class;
3590 sub type
{ shift-
>[0] }
3592 sub info
{ shift-
>[1] }
3596 $self->[2] = shift if @_;
3602 $self->[3] = shift if @_;
3608 $self->[4] = shift if @_;
3614 if ($self->type =~ /^parse/) {
3615 if (my $doc = $self->doc) {
3616 my ($line, $char) = CGI
::Ex
::Template-
>get_line_number_by_index($doc, $self->offset, 'include_char');
3617 return $self->type ." error - $doc->{'name'} line $line char $char: ". $self->info;
3619 return $self->type .' error - '. $self->info .' (At char '. $self->offset .')';
3622 return $self->type .' error - '. $self->info;
3626 ###----------------------------------------------------------------###
3628 package CGI
::Ex
::Template
::Iterator
;
3631 my ($class, $items) = @_;
3632 $items = [] if ! defined $items;
3633 if (UNIVERSAL
::isa
($items, 'HASH')) {
3634 $items = [ map { {key
=> $_, value
=> $items->{ $_ }} } sort keys %$items ];
3635 } elsif (UNIVERSAL
::can
($items, 'as_list')) {
3636 $items = $items->as_list;
3637 } elsif (! UNIVERSAL
::isa
($items, 'ARRAY')) {
3640 return bless [$items, 0], $class;
3645 return (undef, 3) if ! @{ $self->[0] };
3646 return ($self->[0]->[$self->[1] = 0], undef);
3651 return (undef, 3) if ++ $self->[1] > $#{ $self->[0] };
3652 return ($self->items->[$self->[1]], undef);
3655 sub items
{ shift-
>[0] }
3657 sub index { shift-
>[1] }
3659 sub max
{ $#{ shift-
>[0] } }
3661 sub size
{ shift-
>max + 1 }
3663 sub count
{ shift-
>index + 1 }
3665 sub number
{ shift-
>index + 1 }
3667 sub first
{ (shift-
>index == 0) || 0 }
3669 sub last { my $self = shift; return ($self->index == $self->max) || 0 }
3673 return undef if $self->index <= 0;
3674 return $self->items->[$self->index - 1];
3679 return undef if $self->index >= $self->max;
3680 return $self->items->[$self->index + 1];
3683 ###----------------------------------------------------------------###
3685 package CGI
::Ex
::Template
::_Context
;
3687 use vars
qw($AUTOLOAD);
3689 sub _template
{ shift-
>{'_template'} || die "Missing _template" }
3692 my ($self, $name) = @_;
3693 return $self->_template->{'BLOCKS'}->{$name} || $self->_template->load_parsed_tree($name);
3696 sub config
{ shift-
>_template }
3700 return $self->{'stash'} ||= bless {_template
=> $self->_template}, $CGI::Ex
::Template
::PACKAGE_STASH
;
3703 sub insert
{ shift-
>_template->_insert(@_) }
3705 sub eval_perl
{ shift-
>_template->{'EVAL_PERL'} }
3710 my $args = shift || {};
3712 $self->_template->set_variable($_, $args->{$_}) for keys %$args;
3715 $self->_template->_process($ref, $self->_template->_vars, \
$out);
3722 my $args = shift || {};
3724 my $t = $self->_template;
3726 my $swap = $t->{'_vars'};
3727 local $t->{'_vars'} = {%$swap};
3729 $t->set_variable($_, $args->{$_}) for keys %$args;
3731 my $out = ''; # have temp item to allow clear to correctly clear
3732 eval { $t->_process($ref, $t->_vars, \
$out) };
3734 die $err if ref($err) !~ /Template::Exception$/ || $err->type !~ /return/;
3741 my ($self, $name, $filter, $is_dynamic) = @_;
3742 $filter = [ $filter, 1 ] if $is_dynamic;
3743 $self->define_vmethod('filter', $name, $filter);
3747 my ($self, $name, $args, $alias) = @_;
3748 my $t = $self->_template;
3752 $filter = $t->{'FILTERS'}->{$name} || $CGI::Ex
::Template
::FILTER_OPS-
>{$name} || $CGI::Ex
::Template
::SCALAR_OPS-
>{$name};
3753 $t->throw('filter', $name) if ! $filter;
3754 } elsif (UNIVERSAL
::isa
($name, 'CODE') || UNIVERSAL
::isa
($name, 'ARRAY')) {
3756 } elsif (UNIVERSAL
::can
($name, 'factory')) {
3757 $filter = $name->factory || $t->throw($name->error);
3759 $t->throw('undef', "$name: filter not found");
3762 if (UNIVERSAL
::isa
($filter, 'ARRAY')) {
3763 $filter = ($filter->[1]) ? $filter->[0]->($t->context, @$args) : $filter->[0];
3764 } elsif ($args && @$args) {
3766 $filter = sub { $sub->(shift, @$args) };
3769 $t->{'FILTERS'}->{$alias} = $filter if $alias;
3774 sub define_vmethod
{ shift-
>_template->define_vmethod(@_) }
3777 my ($self, $type, $info) = @_;
3779 if (UNIVERSAL
::isa
($type, $CGI::Ex
::Template
::PACKAGE_EXCEPTION
)) {
3781 } elsif (defined $info) {
3782 $self->_template->throw($type, $info);
3784 $self->_template->throw('undef', $type);
3788 sub AUTOLOAD
{ shift-
>_template->throw('not_implemented', "The method $AUTOLOAD has not been implemented") }
3792 ###----------------------------------------------------------------###
3794 package CGI
::Ex
::Template
::_Stash
;
3796 use vars
qw($AUTOLOAD);
3798 sub _template
{ shift-
>{'_template'} || die "Missing _template" }
3801 my ($self, $var) = @_;
3803 if ($var =~ /^\w+$/) { $var = [$var, 0] }
3804 else { $var = $self->_template->parse_expr(\
$var, {no_dots
=> 1}) }
3806 return $self->_template->play_expr($var, {no_dots
=> 1});
3810 my ($self, $var, $val) = @_;
3812 if ($var =~ /^\w+$/) { $var = [$var, 0] }
3813 else { $var = $self->_template->parse_expr(\
$var, {no_dots
=> 1}) }
3815 $self->_template->set_variable($var, $val, {no_dots
=> 1});
3819 sub AUTOLOAD
{ shift-
>_template->throw('not_implemented', "The method $AUTOLOAD has not been implemented") }
3823 ###----------------------------------------------------------------###
3825 package CGI
::Ex
::Template
::EvalPerlHandle
;
3828 my ($class, $out_ref) = @_;
3829 return bless [$out_ref], $class;
3834 ${ $self->[0] } .= $_ for grep {defined && length} @_;
3838 ###----------------------------------------------------------------###
3842 ### See the perldoc in CGI/Ex/Template.pod