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
35 $PACKAGE_EXCEPTION $PACKAGE_ITERATOR $PACKAGE_CONTEXT $PACKAGE_STASH $PACKAGE_PERL_HANDLE
44 $PACKAGE_EXCEPTION = 'CGI::Ex::Template::Exception';
45 $PACKAGE_ITERATOR = 'CGI::Ex::Template::Iterator';
46 $PACKAGE_CONTEXT = 'CGI::Ex::Template::_Context';
47 $PACKAGE_STASH = 'CGI::Ex::Template::_Stash';
48 $PACKAGE_PERL_HANDLE = 'CGI::Ex::Template::EvalPerlHandle';
51 default => ['[%', '%]'], # default
52 template
=> ['[%', '%]'], # default
53 metatext
=> ['%%', '%%'], # Text::MetaText
54 star
=> ['[*', '*]'], # TT alternate
55 php
=> ['<?', '?>'], # PHP
56 asp
=> ['<%', '%>'], # ASP
57 mason
=> ['<%', '>' ], # HTML::Mason
58 html
=> ['<!--', '-->'], # HTML comments
63 as
=> \
&vmethod_as_scalar
,
64 chunk
=> \
&vmethod_chunk
,
65 collapse
=> sub { local $_ = $_[0]; s/^\s+//; s/\s+$//; s/\s+/ /g; $_ },
67 indent
=> \
&vmethod_indent
,
68 int => sub { local $^W; int $_[0] },
69 fmt
=> \
&vmethod_as_scalar
,
70 'format' => \
&vmethod_format
,
71 hash
=> sub { {value
=> $_[0]} },
72 html
=> sub { local $_ = $_[0]; s/&/&/g; s/</</g; s/>/>/g; s/\"/"/g; $_ },
73 lcfirst => sub { lcfirst $_[0] },
74 length => sub { defined($_[0]) ? length($_[0]) : 0 },
75 list
=> sub { [$_[0]] },
76 lower
=> sub { lc $_[0] },
77 match
=> \
&vmethod_match
,
78 new
=> sub { defined $_[0] ? $_[0] : '' },
80 rand => sub { local $^W; rand shift },
81 remove
=> sub { vmethod_replace
(shift, shift, '', 1) },
82 repeat
=> \
&vmethod_repeat
,
83 replace
=> \
&vmethod_replace
,
84 search
=> sub { my ($str, $pat) = @_; return $str if ! defined $str || ! defined $pat; return scalar $str =~ /$pat/ },
86 split => \
&vmethod_split
,
87 stderr
=> sub { print STDERR
$_[0]; '' },
88 substr => sub { my ($str, $i, $len) = @_; defined($len) ? substr($str, $i, $len) : substr($str, $i) },
89 trim
=> sub { local $_ = $_[0]; s/^\s+//; s/\s+$//; $_ },
90 ucfirst => sub { ucfirst $_[0] },
91 upper
=> sub { uc $_[0] },
95 $FILTER_OPS = { # generally - non-dynamic filters belong in scalar ops
96 eval => [\
&filter_eval
, 1],
97 evaltt
=> [\
&filter_eval
, 1],
98 file
=> [\
&filter_redirect
, 1],
99 redirect
=> [\
&filter_redirect
, 1],
103 as
=> \
&vmethod_as_list
,
104 first
=> sub { my ($ref, $i) = @_; return $ref->[0] if ! $i; return [@{$ref}[0 .. $i - 1]]},
105 fmt
=> \
&vmethod_as_list
,
106 grep => sub { my ($ref, $pat) = @_; [grep {/$pat/} @$ref] },
107 hash
=> sub { local $^W; my ($list, $i) = @_; defined($i) ? {map {$i++ => $_} @$list} : {@$list} },
108 join => sub { my ($ref, $join) = @_; $join = ' ' if ! defined $join; local $^W; return join $join, @$ref },
109 last => sub { my ($ref, $i) = @_; return $ref->[-1] if ! $i; return [@{$ref}[-$i .. -1]]},
110 list
=> sub { $_[0] },
111 max
=> sub { $#{ $_[0] } },
112 merge
=> sub { my $ref = shift; return [ @$ref, grep {defined} map {ref eq 'ARRAY' ? @$_ : undef} @_ ] },
113 new
=> sub { local $^W; return [@_] },
114 nsort
=> \
&vmethod_nsort
,
115 pop => sub { pop @{ $_[0] } },
116 push => sub { my $ref = shift; push @$ref, @_; return '' },
117 random
=> sub { my $ref = shift; $ref->[ rand @$ref ] },
118 reverse => sub { [ reverse @{ $_[0] } ] },
119 shift => sub { shift @{ $_[0] } },
120 size
=> sub { scalar @{ $_[0] } },
121 slice
=> sub { my ($ref, $a, $b) = @_; $a ||= 0; $b = $#$ref if ! defined $b; return [@{$ref}[$a .. $b]] },
122 sort => \
&vmethod_sort
,
123 splice => \
&vmethod_splice
,
124 unique
=> sub { my %u; return [ grep { ! $u{$_} ++ } @{ $_[0] } ] },
125 unshift => sub { my $ref = shift; unshift @$ref, @_; return '' },
129 as
=> \
&vmethod_as_hash
,
130 defined => sub { return '' if ! defined $_[1]; defined $_[0]->{ $_[1] } },
131 delete => sub { return '' if ! defined $_[1]; delete $_[0]->{ $_[1] } },
132 each => sub { [%{ $_[0] }] },
133 exists => sub { return '' if ! defined $_[1]; exists $_[0]->{ $_[1] } },
134 fmt
=> \
&vmethod_as_hash
,
135 hash
=> sub { $_[0] },
136 import
=> sub { my ($a, $b) = @_; return '' if ref($b) ne 'HASH'; @{$a}{keys %$b} = values %$b; '' },
137 item
=> sub { my ($h, $k) = @_; return '' if ! defined $k || $k =~ $QR_PRIVATE; $h->{$k} },
138 items
=> sub { [ %{ $_[0] } ] },
139 keys => sub { [keys %{ $_[0] }] },
140 list
=> sub { [$_[0]] },
141 new
=> sub { local $^W; return (@_ == 1 && ref $_[-1] eq 'HASH') ? $_[-1] : {@_} },
142 nsort
=> sub { my $ref = shift; [sort {$ref->{$a} <=> $ref->{$b} } keys %$ref] },
143 pairs
=> sub { [map { {key
=> $_, value
=> $_[0]->{$_}} } keys %{ $_[0] } ] },
144 size
=> sub { scalar keys %{ $_[0] } },
145 sort => sub { my $ref = shift; [sort {lc $ref->{$a} cmp lc $ref->{$b}} keys %$ref] },
146 values => sub { [values %{ $_[0] }] },
154 foreach (values %$VOBJS) {
155 $_->{'Text'} = $_->{'as'};
156 $_->{'Hash'} = $_->{'hash'};
157 $_->{'List'} = $_->{'list'};
161 #name parse_sub play_sub block postdir continue move_to_front
162 BLOCK
=> [\
&parse_BLOCK
, \
&play_BLOCK
, 1, 0, 0, 1],
163 BREAK
=> [sub {}, \
&play_control
],
164 CALL
=> [\
&parse_CALL
, \
&play_CALL
],
165 CASE
=> [\
&parse_CASE
, undef, 0, 0, {SWITCH
=> 1, CASE
=> 1}],
166 CATCH => [\
&parse_CATCH
, undef, 0, 0, {TRY
=> 1, CATCH => 1}],
167 CLEAR
=> [sub {}, \
&play_CLEAR
],
168 '#' => [sub {}, sub {}],
169 DEBUG
=> [\
&parse_DEBUG
, \
&play_DEBUG
],
170 DEFAULT
=> [\
&parse_DEFAULT
, \
&play_DEFAULT
],
171 DUMP
=> [\
&parse_DUMP
, \
&play_DUMP
],
172 ELSE
=> [sub {}, undef, 0, 0, {IF
=> 1, ELSIF
=> 1, UNLESS
=> 1}],
173 ELSIF
=> [\
&parse_IF
, undef, 0, 0, {IF
=> 1, ELSIF
=> 1, UNLESS
=> 1}],
174 END => [undef, sub {}],
175 FILTER
=> [\
&parse_FILTER
, \
&play_FILTER
, 1, 1],
176 '|' => [\
&parse_FILTER
, \
&play_FILTER
, 1, 1],
177 FINAL
=> [sub {}, undef, 0, 0, {TRY
=> 1, CATCH => 1}],
178 FOR
=> [\
&parse_FOREACH
, \
&play_FOREACH
, 1, 1],
179 FOREACH
=> [\
&parse_FOREACH
, \
&play_FOREACH
, 1, 1],
180 GET
=> [\
&parse_GET
, \
&play_GET
],
181 IF
=> [\
&parse_IF
, \
&play_IF
, 1, 1],
182 INCLUDE
=> [\
&parse_INCLUDE
, \
&play_INCLUDE
],
183 INSERT
=> [\
&parse_INSERT
, \
&play_INSERT
],
184 LAST
=> [sub {}, \
&play_control
],
185 MACRO
=> [\
&parse_MACRO
, \
&play_MACRO
],
186 META
=> [undef, sub {}],
187 METADEF
=> [undef, \
&play_METADEF
],
188 NEXT => [sub {}, \
&play_control
],
189 PERL
=> [\
&parse_PERL
, \
&play_PERL
, 1],
190 PROCESS
=> [\
&parse_PROCESS
, \
&play_PROCESS
],
191 RAWPERL
=> [\
&parse_PERL
, \
&play_RAWPERL
, 1],
192 RETURN
=> [sub {}, \
&play_control
],
193 SET
=> [\
&parse_SET
, \
&play_SET
],
194 STOP
=> [sub {}, \
&play_control
],
195 SWITCH
=> [\
&parse_SWITCH
, \
&play_SWITCH
, 1],
196 TAGS
=> [undef, sub {}],
197 THROW
=> [\
&parse_THROW
, \
&play_THROW
],
198 TRY
=> [sub {}, \
&play_TRY
, 1],
199 UNLESS
=> [\
&parse_UNLESS
, \
&play_UNLESS
, 1, 1],
200 USE
=> [\
&parse_USE
, \
&play_USE
],
201 WHILE
=> [\
&parse_IF
, \
&play_WHILE
, 1, 1],
202 WRAPPER
=> [\
&parse_WRAPPER
, \
&play_WRAPPER
, 1, 1],
203 #name #parse_sub #play_sub #block #postdir #continue #move_to_front
205 $QR_DIRECTIVE = qr{ ^ (\w+|\|) (?= $|[\s;\#]) }x;
207 ### setup the operator parsing
209 # type precedence symbols action (undef means play_operator will handle)
210 ['postfix', 99, ['++'], undef ],
211 ['postfix', 99, ['--'], undef ],
212 ['prefix', 98, ['++'], undef ],
213 ['prefix', 98, ['--'], undef ],
214 ['right', 96, ['**', 'pow'], sub { $_[0] ** $_[1] } ],
215 ['prefix', 93, ['!'], sub { ! $_[0] } ],
216 ['prefix', 93, ['-'], sub { @_ == 1 ? 0 - $_[0] : $_[0] - $_[1] } ],
217 ['left', 90, ['*'], sub { $_[0] * $_[1] } ],
218 ['left', 90, ['/'], sub { $_[0] / $_[1] } ],
219 ['left', 90, ['div', 'DIV'], sub { int($_[0] / $_[1]) } ],
220 ['left', 90, ['%', 'mod', 'MOD'], sub { $_[0] % $_[1] } ],
221 ['left', 85, ['+'], sub { $_[0] + $_[1] } ],
222 ['left', 85, ['-'], sub { @_ == 1 ? 0 - $_[0] : $_[0] - $_[1] } ],
223 ['left', 85, ['~', '_'], sub { join "", @_ } ],
224 ['none', 80, ['<'], sub { $_[0] < $_[1] } ],
225 ['none', 80, ['>'], sub { $_[0] > $_[1] } ],
226 ['none', 80, ['<='], sub { $_[0] <= $_[1] } ],
227 ['none', 80, ['>='], sub { $_[0] >= $_[1] } ],
228 ['none', 80, ['lt'], sub { $_[0] lt $_[1] } ],
229 ['none', 80, ['gt'], sub { $_[0] gt $_[1] } ],
230 ['none', 80, ['le'], sub { $_[0] le $_[1] } ],
231 ['none', 80, ['ge'], sub { $_[0] ge $_[1] } ],
232 ['none', 75, ['==', 'eq'], sub { $_[0] eq $_[1] } ],
233 ['none', 75, ['!=', 'ne'], sub { $_[0] ne $_[1] } ],
234 ['left', 70, ['&&'], undef ],
235 ['right', 65, ['||'], undef ],
236 ['none', 60, ['..'], sub { $_[0] .. $_[1] } ],
237 ['ternary', 55, ['?', ':'], undef ],
238 ['assign', 53, ['+='], sub { $_[0] + $_[1] } ],
239 ['assign', 53, ['-='], sub { $_[0] - $_[1] } ],
240 ['assign', 53, ['*='], sub { $_[0] * $_[1] } ],
241 ['assign', 53, ['/='], sub { $_[0] / $_[1] } ],
242 ['assign', 53, ['%='], sub { $_[0] % $_[1] } ],
243 ['assign', 53, ['**='], sub { $_[0]** $_[1] } ],
244 ['assign', 53, ['~=', '_='], sub { $_[0] . $_[1] } ],
245 ['assign', 52, ['='], undef ],
246 ['prefix', 50, ['not', 'NOT'], sub { ! $_[0] } ],
247 ['left', 45, ['and', 'AND'], undef ],
248 ['right', 40, ['or', 'OR'], undef ],
249 ['', 0, ['hash'], sub { return {@_}; } ],
250 ['', 0, ['array'], sub { return [@_] } ],
252 $OP = {map {my $ref = $_; map {$_ => $ref} @{$ref->[2]}} grep {$_->[0] ne 'prefix' } @$OPERATORS}; # all non-prefix
253 $OP_PREFIX = {map {my $ref = $_; map {$_ => $ref} @{$ref->[2]}} grep {$_->[0] eq 'prefix' } @$OPERATORS};
254 $OP_DISPATCH = {map {my $ref = $_; map {$_ => $ref->[3]} @{$ref->[2]}} grep {$_->[3] } @$OPERATORS};
255 $OP_ASSIGN = {map {my $ref = $_; map {$_ => 1} @{$ref->[2]}} grep {$_->[0] eq 'assign' } @$OPERATORS};
256 $OP_POSTFIX = {map {my $ref = $_; map {$_ => 1} @{$ref->[2]}} grep {$_->[0] eq 'postfix'} @$OPERATORS}; # bool is postfix
257 $OP_TERNARY = {map {my $ref = $_; map {$_ => 1} @{$ref->[2]}} grep {$_->[0] eq 'ternary'} @$OPERATORS}; # bool is ternary
258 sub _op_qr
{ # no mixed \w\W operators
260 my $chrs = join '|', reverse sort map {quotemeta $_} grep {++$used{$_} < 2} grep {/^\W{2,}$/} @_;
261 my $chr = join '', sort map {quotemeta $_} grep {++$used{$_} < 2} grep {/^\W$/} @_;
262 my $word = join '|', reverse sort grep {++$used{$_} < 2} grep {/^\w+$/} @_;
263 $chr = "[$chr]" if $chr;
264 $word = "\\b(?:$word)\\b" if $word;
265 return join('|', grep {length} $chrs, $chr, $word) || die "Missing operator regex";
267 sub _build_op_qr
{ _op_qr
(map {@{ $_->[2] }} grep {$_->[0] ne 'prefix'} @$OPERATORS) }
268 sub _build_op_qr_prefix
{ _op_qr
(map {@{ $_->[2] }} grep {$_->[0] eq 'prefix'} @$OPERATORS) }
269 sub _build_op_qr_assign
{ _op_qr
(map {@{ $_->[2] }} grep {$_->[0] eq 'assign'} @$OPERATORS) }
270 $QR_OP = _build_op_qr
();
271 $QR_OP_PREFIX = _build_op_qr_prefix
();
272 $QR_OP_ASSIGN = _build_op_qr_assign
();
274 $QR_COMMENTS = '(?-s: \# .* \s*)*';
275 $QR_FILENAME = '([a-zA-Z]]:/|/)? [\w\-\.]+ (?:/[\w\-\.]+)*';
276 $QR_NUM = '(?:\d*\.\d+ | \d+) (?: [eE][+-]\d+ )?';
277 $QR_AQ_NOTDOT = "(?! \\s* $QR_COMMENTS \\.)";
278 $QR_AQ_SPACE = '(?: \\s+ | \$ | (?=[;+]) )'; # the + comes into play on filenames
279 $QR_PRIVATE = qr/^[_.]/;
282 $EXTRA_COMPILE_EXT = '.sto';
284 eval {require Scalar
::Util
};
287 ###----------------------------------------------------------------###
291 my $args = ref($_[0]) ? { %{ shift() } } : {@_};
292 my $self = bless $args, $class;
294 ### "enable" debugging - we only support DEBUG_DIRS and DEBUG_UNDEF
295 if ($self->{'DEBUG'}) {
296 $self->{'_debug_dirs'} = 1 if $self->{'DEBUG'} =~ /^\d+$/ ? $self->{'DEBUG'} & 8 : $self->{'DEBUG'} =~ /dirs|all/;
297 $self->{'_debug_undef'} = 1 if $self->{'DEBUG'} =~ /^\d+$/ ? $self->{'DEBUG'} & 2 : $self->{'DEBUG'} =~ /undef|all/;
303 ###----------------------------------------------------------------###
308 local $self->{'_vars'} = shift || {};
309 my $out_ref = shift || $self->throw('undef', "Missing output ref");
310 local $self->{'_top_level'} = delete $self->{'_start_top_level'};
311 my $i = length $$out_ref;
313 ### parse and execute
316 ### load the document
317 $doc = $self->load_parsed_tree($file) || $self->throw('undef', "Zero length content");;
319 ### prevent recursion
320 $self->throw('file', "recursion into '$doc->{name}'")
321 if ! $self->{'RECURSION'} && $self->{'_in'}->{$doc->{'name'}} && $doc->{'name'} ne 'input text';
322 local $self->{'_in'}->{$doc->{'name'}} = 1;
324 ### execute the document
325 if (! @{ $doc->{'_tree'} }) { # no tags found - just return the content
326 $$out_ref = ${ $doc->{'_content'} };
328 local $self->{'_vars'}->{'component'} = $doc;
329 $self->{'_vars'}->{'template'} = $doc if $self->{'_top_level'};
330 $self->execute_tree($doc->{'_tree'}, $out_ref);
331 delete $self->{'_vars'}->{'template'} if $self->{'_top_level'};
335 ### trim whitespace from the beginning and the end of a block or template
336 if ($self->{'TRIM'}) {
337 substr($$out_ref, $i, length($$out_ref) - $i) =~ s{ \s+ $ }{}x; # tail first
338 substr($$out_ref, $i, length($$out_ref) - $i) =~ s{ ^ \s+ }{}x;
341 ### handle exceptions
343 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
344 $err->doc($doc) if $doc && $err->can('doc') && ! $err->doc;
345 die $err if ! $self->{'_top_level'} || $err->type !~ /stop|return/;
351 ###----------------------------------------------------------------###
353 sub load_parsed_tree
{
356 return if ! defined $file;
358 my $doc = {name
=> $file};
360 ### looks like a string reference
362 $doc->{'_content'} = $file;
363 $doc->{'name'} = 'input text';
364 $doc->{'is_str_ref'} = 1;
366 ### looks like a previously cached-in-memory document
367 } elsif ($self->{'_documents'}->{$file}
368 && ( ($self->{'_documents'}->{$file}->{'_cache_time'} == time) # don't stat more than once a second
369 || ($self->{'_documents'}->{$file}->{'modtime'}
370 == (stat $self->{'_documents'}->{$file}->{'_filename'})[9]))) {
371 $doc = $self->{'_documents'}->{$file};
372 $doc->{'_cache_time'} = time;
375 ### looks like a block name of some sort
376 } elsif ($self->{'BLOCKS'}->{$file}) {
377 my $block = $self->{'BLOCKS'}->{$file};
379 ### allow for predefined blocks that are a code or a string
380 if (UNIVERSAL
::isa
($block, 'CODE')) {
383 if (! UNIVERSAL
::isa
($block, 'HASH')) {
384 $self->throw('block', "Unsupported BLOCK type \"$block\"") if ref $block;
386 $block = eval { $self->load_parsed_tree(\
$copy) }
387 || $self->throw('block', 'Parse error on predefined block');
389 $doc->{'_tree'} = $block->{'_tree'} || $self->throw('block', "Invalid block definition (missing tree)");
393 ### go and look on the file system
395 $doc->{'_filename'} = eval { $self->include_filename($file) };
397 ### allow for blocks in other files
398 if ($self->{'EXPOSE_BLOCKS'}
399 && ! $self->{'_looking_in_block_file'}) {
400 local $self->{'_looking_in_block_file'} = 1;
402 while ($file =~ s
|/([^/.]+)$||) {
403 $block_name = length($block_name) ? "$1/$block_name" : $1;
404 my $ref = eval { $self->load_parsed_tree($file) } || next;
405 my $_tree = $ref->{'_tree'};
406 foreach my $node (@$_tree) {
408 next if $node->[0] eq 'METADEF';
409 last if $node->[0] ne 'BLOCK';
410 next if $block_name ne $node->[3];
411 $doc->{'_content'} = $ref->{'_content'};
412 $doc->{'_tree'} = $node->[4];
413 $doc->{'modtime'} = $ref->{'modtime'};
414 $file = $ref->{'name'};
418 die $err if ! $doc->{'_tree'};
419 } elsif ($self->{'DEFAULT'}) {
420 $doc->{'_filename'} = eval { $self->include_filename($self->{'DEFAULT'}) } || die $err;
426 ### no tree yet - look for a file cache
427 if (! $doc->{'_tree'}) {
428 $doc->{'modtime'} = (stat $doc->{'_filename'})[9];
429 if ($self->{'COMPILE_DIR'} || $self->{'COMPILE_EXT'}) {
430 if ($self->{'COMPILE_DIR'}) {
431 $doc->{'_compile_filename'} = $self->{'COMPILE_DIR'} .'/'. $file;
433 $doc->{'_compile_filename'} = $doc->{'_filename'};
435 $doc->{'_compile_filename'} .= $self->{'COMPILE_EXT'} if defined($self->{'COMPILE_EXT'});
436 $doc->{'_compile_filename'} .= $EXTRA_COMPILE_EXT if defined $EXTRA_COMPILE_EXT;
438 if (-e
$doc->{'_compile_filename'} && (stat _
)[9] == $doc->{'modtime'}) {
440 $doc->{'_tree'} = Storable
::retrieve
($doc->{'_compile_filename'});
441 $doc->{'compile_was_used'} = 1;
443 my $str = $self->slurp($doc->{'_filename'});
444 $doc->{'_content'} = \
$str;
447 my $str = $self->slurp($doc->{'_filename'});
448 $doc->{'_content'} = \
$str;
454 ### haven't found a parsed tree yet - parse the content into a tree
455 if (! $doc->{'_tree'}) {
456 if ($self->{'CONSTANTS'}) {
457 my $key = $self->{'CONSTANT_NAMESPACE'} || 'constants';
458 $self->{'NAMESPACE'}->{$key} ||= $self->{'CONSTANTS'};
461 local $self->{'_vars'}->{'component'} = $doc;
462 $doc->{'_tree'} = $self->parse_tree($doc->{'_content'}); # errors die
465 ### cache parsed_tree in memory unless asked not to do so
466 if (! $doc->{'is_str_ref'} && (! defined($self->{'CACHE_SIZE'}) || $self->{'CACHE_SIZE'})) {
467 $self->{'_documents'}->{$file} ||= $doc;
468 $doc->{'_cache_time'} = time;
470 ### allow for config option to keep the cache size down
471 if ($self->{'CACHE_SIZE'}) {
472 my $all = $self->{'_documents'};
473 if (scalar(keys %$all) > $self->{'CACHE_SIZE'}) {
475 foreach my $file (sort {$all->{$b}->{'_cache_time'} <=> $all->{$a}->{'_cache_time'}} keys %$all) {
476 delete($all->{$file}) if ++$n > $self->{'CACHE_SIZE'};
482 ### save a cache on the fileside as asked
483 if ($doc->{'_compile_filename'} && ! $doc->{'compile_was_used'}) {
484 my $dir = $doc->{'_compile_filename'};
488 File
::Path
::mkpath
($dir);
491 Storable
::store
($doc->{'_tree'}, $doc->{'_compile_filename'});
492 utime $doc->{'modtime'}, $doc->{'modtime'}, $doc->{'_compile_filename'};
501 if (! $str_ref || ! defined $$str_ref) {
502 $self->throw('parse.no_string', "No string or undefined during parse");
505 my $STYLE = $self->{'TAG_STYLE'} || 'default';
506 my $START = $self->{'START_TAG'} || $TAGS->{$STYLE}->[0];
507 my $END = $self->{'END_TAG'} || $TAGS->{$STYLE}->[1];
508 my $len_s = length $START;
509 my $len_e = length $END;
511 my @tree; # the parsed tree
512 my $pointer = \
@tree; # pointer to current tree to handle nested blocks
513 my @state; # maintain block levels
514 local $self->{'_state'} = \
@state; # allow for items to introspect (usually BLOCKS)
515 local $self->{'_in_perl'}; # no interpolation in perl
516 my @move_to_front; # items that need to be declared first (usually BLOCKS)
517 my @meta; # place to store any found meta information (to go into METADEF)
518 my $i = 0; # start index
519 my $j = 0; # end index
520 my $last = 0; # previous end index
521 my $post_chomp = 0; # previous post_chomp setting
522 my $continue; # multiple directives in the same tag
523 my $post_op; # found a post-operative DIRECTIVE
524 my $capture; # flag to start capture
529 ### continue looking for information in a semi-colon delimited tag
532 $node = [undef, $i, $j];
534 ### look through the string using index
536 $i = index($$str_ref, $START, $last);
537 last if $i == -1; # no start tag found - we are done
538 if ($last != $i) { # found a text portion - chomp it, interpolate it and store it
539 my $text = substr($$str_ref, $last, $i - $last);
542 if ($post_chomp == 1) { $_last += length($1) if $text =~ s{ ^ ([^\S\n]* \n) }{}x }
543 elsif ($post_chomp == 2) { $_last += length($1) + 1 if $text =~ s{ ^ (\s+) }{ }x }
544 elsif ($post_chomp == 3) { $_last += length($1) if $text =~ s{ ^ (\s+) }{}x }
547 push @$pointer, $text;
548 $self->interpolate_node($pointer, $_last) if $self->{'INTERPOLATE'};
551 $j = index($$str_ref, $END, $i + $len_s);
553 if ($j == -1) { # missing closing tag
554 $last = length($$str_ref);
557 $tag = substr($$str_ref, $i + $len_s, $j - ($i + $len_s));
558 $node = [undef, $i + $len_s, $j];
560 ### take care of whitespace and comments flags
561 my $pre_chomp = $tag =~ s{ ^ ([+=~-]) }{}x ? $1 : $self->{'PRE_CHOMP'};
562 $post_chomp = $tag =~ s{ ([+=~-]) $ }{}x ? $1 : $self->{'POST_CHOMP'};
563 $pre_chomp =~ y/-=~+/1230/ if $pre_chomp;
564 $post_chomp =~ y/-=~+/1230/ if $post_chomp;
565 if ($pre_chomp && $pointer->[-1] && ! ref $pointer->[-1]) {
566 if ($pre_chomp == 1) { $pointer->[-1] =~ s{ (?:\n|^) [^\S\n]* \z }{}x }
567 elsif ($pre_chomp == 2) { $pointer->[-1] =~ s{ (\s+) \z }{ }x }
568 elsif ($pre_chomp == 3) { $pointer->[-1] =~ s{ (\s+) \z }{}x }
569 splice(@$pointer, -1, 1, ()) if ! length $pointer->[-1]; # remove the node if it is zero length
571 if ($tag =~ /^\#/) { # leading # means to comment the entire section
573 push @$pointer, $node;
576 $tag =~ s{ ^ \s+ $QR_COMMENTS }{}ox;
585 ### look for DIRECTIVES
586 if ($tag =~ $QR_DIRECTIVE # find a word
587 && $DIRECTIVES->{$1} ) { # is it a directive
588 $node->[0] = $func = $1;
589 $tag =~ s{ ^ (\w+ | \|) \s* $QR_COMMENTS }{}ox;
591 ### store out this current node level
592 if ($post_op) { # on a post operator - replace the original node with the new one - store the old in the new
593 my @post_op = @$post_op;
596 $node->[4] = [\
@post_op];
598 # do nothing - it will be handled further down
600 push @$pointer, $node;
603 ### anything that behaves as a block ending
604 if ($func eq 'END' || $DIRECTIVES->{$func}->[4]) { # [4] means it is a continuation block (ELSE, CATCH, etc)
606 $self->throw('parse', "Found an $func tag while not in a block", $node);
608 my $parent_node = pop @state;
610 if ($func ne 'END') {
611 pop @$pointer; # we will store the node in the parent instead
612 $parent_node->[5] = $node;
613 my $parent_type = $parent_node->[0];
614 if (! $DIRECTIVES->{$func}->[4]->{$parent_type}) {
615 $self->throw('parse', "Found unmatched nested block", $node, 0);
619 ### restore the pointer up one level (because we hit the end of a block)
620 $pointer = (! @state) ? \
@tree : $state[-1]->[4];
623 if ($func eq 'END') {
624 if ($DIRECTIVES->{$parent_node->[0]}->[5]) { # move things like BLOCKS to front
625 push @move_to_front, $parent_node;
626 if ($pointer->[-1] && ! $pointer->[-1]->[6]) { # capturing doesn't remove the var
627 splice(@$pointer, -1, 1, ());
629 } elsif ($parent_node->[0] =~ /PERL$/) {
630 delete $self->{'_in_perl'};
633 ### continuation block - such as an elsif
635 $node->[3] = eval { $DIRECTIVES->{$func}->[0]->($self, \
$tag, $node) };
637 $err->node($node) if UNIVERSAL
::can
($err, 'node') && ! $err->node;
641 $pointer = $node->[4] ||= [];
644 } elsif ($func eq 'TAGS') {
645 if ($tag =~ / ^ (\w+) /x && $TAGS->{$1}) {
646 $tag =~ s{ ^ (\w+) \s* $QR_COMMENTS }{}ox;
647 ($START, $END) = @{ $TAGS->{$1} };
648 } elsif ($tag =~ s{ ^ (\S+) \s+ (\S+) \s* $QR_COMMENTS }{}ox) {
649 ($START, $END) = ($1, $2);
651 $len_s = length $START;
652 $len_e = length $END;
654 } elsif ($func eq 'META') {
655 my $args = $self->parse_args(\
$tag);
657 if (($hash = $self->play_expr($args->[-1]))
658 && UNIVERSAL
::isa
($hash, 'HASH')) {
659 unshift @meta, %$hash; # first defined win
662 ### all other "normal" tags
664 $node->[3] = eval { $DIRECTIVES->{$func}->[0]->($self, \
$tag, $node) };
666 $err->node($node) if UNIVERSAL
::can
($err, 'node') && ! $err->node;
669 if ($DIRECTIVES->{$func}->[2] && ! $post_op) { # this looks like a block directive
671 $pointer = $node->[4] ||= [];
675 ### allow for bare variable getting and setting
676 } elsif (defined(my $var = $self->parse_expr(\
$tag))) {
677 push @$pointer, $node;
678 if ($tag =~ s{ ^ ($QR_OP_ASSIGN) >? \s* $QR_COMMENTS }{}ox) {
680 $node->[3] = eval { $DIRECTIVES->{'SET'}->[0]->($self, \
$tag, $node, $1, $var) };
682 $err->node($node) if UNIVERSAL
::can
($err, 'node') && ! $err->node;
691 my $all = substr($$str_ref, $i + $len_s, $j - ($i + $len_s));
694 $self->throw('parse', "Not sure how to handle tag \"$all\"", $node);
697 ### we now have the directive to capture for an item like "SET foo = BLOCK" - store it
699 my $parent_node = $capture;
700 push @{ $parent_node->[4] }, $node;
704 ### we are flagged to start capturing the output of the next directive - set it up
706 $continue = $j - length $tag;
707 $node->[2] = $continue;
711 ### semi-colon = end of statement - we will need to continue parsing this tag
712 } elsif ($tag =~ s{ ^ ; \s* $QR_COMMENTS }{}ox) {
713 $continue = $j - length $tag;
714 $node->[2] = $continue;
717 ### looking at a post operator ([% u FOREACH u IN [1..3] %])
718 } elsif ($tag =~ $QR_DIRECTIVE # find a word
719 && $DIRECTIVES->{$1} # is it a directive
720 && $DIRECTIVES->{$1}->[3]) { # it is a post operative directive
721 $continue = $j - length $tag;
722 $node->[2] = $continue;
725 ### unlink TT2 - look for another directive
726 } elsif (length $tag) {
727 #$self->throw('parse', "Found trailing info \"$tag\"", $node);
728 $continue = $j - length $tag;
729 $node->[2] = $continue;
738 if (@move_to_front) {
739 unshift @tree, @move_to_front;
742 unshift @tree, ['METADEF', 0, 0, {@meta}];
746 $self->throw('parse.missing.end', "Missing END", $state[-1], 0);
749 ### pull off the last text portion - if any
750 if ($last != length($$str_ref)) {
751 my $text = substr($$str_ref, $last, length($$str_ref) - $last);
754 if ($post_chomp == 1) { $_last += length($1) if $text =~ s{ ^ ([^\S\n]* \n) }{}x }
755 elsif ($post_chomp == 2) { $_last += length($1) + 1 if $text =~ s{ ^ (\s+) }{ }x }
756 elsif ($post_chomp == 3) { $_last += length($1) if $text =~ s{ ^ (\s+) }{}x }
759 push @$pointer, $text;
760 $self->interpolate_node($pointer, $_last) if $self->{'INTERPOLATE'};
768 my ($self, $tree, $out_ref) = @_;
770 # node contains (0: DIRECTIVE,
773 # 3: parsed tag details,
774 # 4: sub tree for block types
775 # 5: continuation sub trees for sub continuation block types (elsif, else, etc)
776 # 6: flag to capture next directive
777 for my $node (@$tree) {
778 ### text nodes are just the bare text
780 warn "NODE: TEXT\n" if trace
;
781 $$out_ref .= $node if defined $node;
785 warn "NODE: $node->[0] (char $node->[1])\n" if trace
;
786 $$out_ref .= $self->debug_node($node) if $self->{'_debug_dirs'} && ! $self->{'_debug_off'};
788 my $val = $DIRECTIVES->{$node->[0]}->[1]->($self, $node->[3], $node, $out_ref);
789 $$out_ref .= $val if defined $val;
793 ###----------------------------------------------------------------###
798 my $ARGS = shift || {};
800 ### allow for custom auto_quoting (such as hash constructors)
801 if ($ARGS->{'auto_quote'}) {
802 if ($$str_ref =~ $ARGS->{'auto_quote'}) {
804 substr($$str_ref, 0, length($str), '');
805 $$str_ref =~ s{ ^ \s* $QR_COMMENTS }{}ox;
807 ### allow for auto-quoted $foo or ${foo.bar} type constructs
808 } elsif ($$str_ref =~ s{ ^ \$ (\w+ (?:\.\w+)*) \b \s* $QR_COMMENTS }{}ox
809 || $$str_ref =~ s{ ^ \$\{ \s* ([^\}]+) \} \s* $QR_COMMENTS }{}ox) {
811 return $self->parse_expr(\
$name);
815 my $copy = $$str_ref; # copy while parsing to allow for errors
817 ### test for leading prefix operators
819 while ($copy =~ s{ ^ ($QR_OP_PREFIX) \s* $QR_COMMENTS }{}ox) {
820 return if $ARGS->{'auto_quote'}; # auto_quoted thing was too complicated
821 push @{ $has_prefix }, $1;
829 if ($copy =~ s{ ^ 0x ( [a-fA-F0-9]+ ) \s* $QR_COMMENTS }{}ox) {
830 my $number = eval { hex $1 } || 0;
831 push @var, \
$number;
834 ### allow for numbers
835 } elsif ($copy =~ s{ ^ ( $QR_NUM ) \s* $QR_COMMENTS }{}ox) {
837 push @var, \
$number;
840 ### allow for quoted array constructor
841 } elsif ($copy =~ s{ ^ qw (\W) \s* }{}x) {
843 $quote =~ y
|([{<|)]}>|;
844 $copy =~ s{ ^ (.*) \Q$quote\E \s* $QR_COMMENTS }{}sx
845 || $self->throw('parse.missing.array_close', "Missing close \"$quote\"", undef, length($$str_ref) - length($copy));
847 $str =~ s{ ^ \s+ | \s+ $ }{}x;
848 my $arrayref = ['array', split /\s+/, $str];
849 push @var, \
$arrayref;
851 ### looks like a normal variable start
852 } elsif ($copy =~ s{ ^ (\w+) \s* $QR_COMMENTS }{}ox) {
854 $is_namespace = 1 if $self->{'NAMESPACE'} && $self->{'NAMESPACE'}->{$1};
856 ### allow for literal strings
857 } elsif ($copy =~ s{ ^ ([\"\']) (|.*?[^\\]) \1 \s* $QR_COMMENTS }{}sox) {
858 if ($1 eq "'") { # no interpolation on single quoted strings
860 $str =~ s{ \\\' }{\'}xg;
868 $str =~ s/\\([\"\$])/$1/g;
869 my @pieces = $ARGS->{'auto_quote'}
870 ? split(m{ (\$\w+ | \$\{ [^\}]+ \
}) }x
, $str) # autoquoted items get a single $\w+ - no nesting
871 : split(m{ (\$\w+ (?:\.\w+)* | \$\{ [^\}]+ \
}) }x
, $str);
873 foreach my $piece (@pieces) {
874 next if ! ($n++ % 2);
875 next if $piece !~ m{ ^ \$ (\w+ (?:\.\w+)*) $ }x
876 && $piece !~ m{ ^ \$\{ \s* ([^\}]+) \
} $ }x
;
878 $piece = $self->parse_expr(\
$name);
880 @pieces = grep {defined && length} @pieces;
881 if (@pieces == 1 && ! ref $pieces[0]) {
882 push @var, \
$pieces[0];
884 } elsif (! @pieces) {
888 push @var, \
['~', @pieces];
891 if ($ARGS->{'auto_quote'}){
893 return ${ $var[0] } if $is_literal;
898 ### allow for leading $foo or ${foo.bar} type constructs
899 } elsif ($copy =~ s{ ^ \$ (\w+) \b \s* $QR_COMMENTS }{}ox
900 || $copy =~ s{ ^ \$\{ \s* ([^\}]+) \} \s* $QR_COMMENTS }{}ox) {
902 push @var, $self->parse_expr(\
$name);
904 ### looks like an array constructor
905 } elsif ($copy =~ s{ ^ \[ \s* $QR_COMMENTS }{}ox) {
906 local $self->{'_operator_precedence'} = 0; # reset presedence
907 my $arrayref = ['array'];
908 while (defined(my $var = $self->parse_expr(\
$copy))) {
909 push @$arrayref, $var;
910 $copy =~ s{ ^ , \s* $QR_COMMENTS }{}ox;
912 $copy =~ s{ ^ \] \s* $QR_COMMENTS }{}ox
913 || $self->throw('parse.missing.square_bracket', "Missing close \]", undef, length($$str_ref) - length($copy));
914 push @var, \
$arrayref;
916 ### looks like a hash constructor
917 } elsif ($copy =~ s{ ^ \{ \s* $QR_COMMENTS }{}ox) {
918 local $self->{'_operator_precedence'} = 0; # reset precedence
919 my $hashref = ['hash'];
920 while (defined(my $key = $self->parse_expr(\
$copy, {auto_quote
=> qr{ ^ (\w+) $QR_AQ_NOTDOT }xo}))) {
921 $copy =~ s{ ^ = >? \s* $QR_COMMENTS }{}ox;
922 my $val = $self->parse_expr(\
$copy);
923 push @$hashref, $key, $val;
924 $copy =~ s{ ^ , \s* $QR_COMMENTS }{}ox;
926 $copy =~ s{ ^ \} \s* $QR_COMMENTS }{}ox
927 || $self->throw('parse.missing.curly_bracket', "Missing close \} ($copy)", undef, length($$str_ref) - length($copy));
928 push @var, \
$hashref;
930 ### looks like a paren grouper
931 } elsif ($copy =~ s{ ^ \( \s* $QR_COMMENTS }{}ox) {
932 local $self->{'_operator_precedence'} = 0; # reset precedence
933 my $var = $self->parse_expr(\
$copy, {allow_parened_ops
=> 1});
934 $copy =~ s{ ^ \) \s* $QR_COMMENTS }{}ox
935 || $self->throw('parse.missing.paren', "Missing close \)", undef, length($$str_ref) - length($copy));
937 pop(@var); # pull off the trailing args of the paren group
939 ### nothing to find - return failure
944 return if $ARGS->{'auto_quote'}; # auto_quoted thing was too complicated
946 ### looks for args for the initial
947 if ($copy =~ s{ ^ \( \s* $QR_COMMENTS }{}ox) {
948 local $self->{'_operator_precedence'} = 0; # reset precedence
949 my $args = $self->parse_args(\
$copy);
950 $copy =~ s{ ^ \) \s* $QR_COMMENTS }{}ox
951 || $self->throw('parse.missing.paren', "Missing close \)", undef, length($$str_ref) - length($copy));
957 ### allow for nested items
958 while ($copy =~ s{ ^ ( \.(?!\.) | \|(?!\|) ) \s* $QR_COMMENTS }{}ox) {
959 push(@var, $1) if ! $ARGS->{'no_dots'};
961 ### allow for interpolated variables in the middle - one.$foo.two or one.${foo.bar}.two
962 if ($copy =~ s{ ^ \$(\w+) \s* $QR_COMMENTS }{}ox
963 || $copy =~ s{ ^ \$\{ \s* ([^\}]+)\} \s* $QR_COMMENTS }{}ox) {
965 my $var = $self->parse_expr(\
$name);
969 } elsif ($copy =~ s{ ^ (-? \w+) \s* $QR_COMMENTS }{}ox) {
973 $self->throw('parse', "Not sure how to continue parsing on \"$copy\" ($$str_ref)");
976 ### looks for args for the nested item
977 if ($copy =~ s{ ^ \( \s* $QR_COMMENTS }{}ox) {
978 local $self->{'_operator_precedence'} = 0; # reset precedence
979 my $args = $self->parse_args(\
$copy);
980 $copy =~ s{ ^ \) \s* $QR_COMMENTS }{}ox
981 || $self->throw('parse.missing.paren', "Missing close \)", undef, length($$str_ref) - length($copy));
989 ### flatten literals and constants as much as possible
990 my $var = ($is_literal && $#var == 1) ? ${ $var[0] }
991 : $is_namespace ? $self->play_expr(\
@var, {is_namespace_during_compile
=> 1})
994 ### allow for all "operators"
995 if (! $self->{'_operator_precedence'}) {
998 while ($copy =~ s{ ^ ($QR_OP) (\s* $QR_COMMENTS) }{}ox) { ## look for operators - then move along
999 if (! $ARGS->{'allow_parened_ops'} && $OP_ASSIGN->{$1}) {
1000 $copy = $1 . $2 . $copy;
1004 local $self->{'_operator_precedence'} = 1;
1007 ### allow for postfix - doesn't check precedence - someday we might change - but not today (only affects post ++ and --)
1008 if ($OP_POSTFIX->{$op}) {
1009 $var = [\
[$op, $var, 1], 0]; # cheat - give a "second value" to postfix ops
1012 ### allow for prefix operator precedence
1013 } elsif ($has_prefix && $OP->{$op}->[1] < $OP_PREFIX->{$has_prefix->[-1]}->[1]) {
1015 if ($#$tree == 1) { # only one operator - keep simple things fast
1016 $var = [\
[$tree->[0], $var, $tree->[1]], 0];
1018 unshift @$tree, $var;
1019 $var = $self->apply_precedence($tree, $found);
1024 $var = [ \
[ $has_prefix->[-1], $var ], 0 ];
1025 if (! @$has_prefix) { undef $has_prefix } else { pop @$has_prefix }
1028 ### add the operator to the tree
1029 my $var2 = $self->parse_expr(\
$copy);
1030 push (@{ $tree ||= [] }, $op, $var2);
1031 $found->{$OP->{$op}->[1]}->{$op} = 1; # found->{precedence}->{op}
1034 ### if we found operators - tree the nodes by operator precedence
1036 if (@$tree == 2) { # only one operator - keep simple things fast
1037 $var = [\
[$tree->[0], $var, $tree->[1]], 0];
1039 unshift @$tree, $var;
1040 $var = $self->apply_precedence($tree, $found);
1045 ### allow for prefix on non-chained variables
1047 $var = [ \
[ $_, $var ], 0 ] for reverse @$has_prefix;
1050 $$str_ref = $copy; # commit the changes
1054 ### this is used to put the parsed variables into the correct operations tree
1055 sub apply_precedence
{
1056 my ($self, $tree, $found) = @_;
1060 ### look at the operators we found in the order we found them
1061 for my $prec (sort keys %$found) {
1062 my $ops = $found->{$prec};
1063 local $found->{$prec};
1064 delete $found->{$prec};
1066 ### split the array on the current operators for this level
1069 for (my $i = 1; $i <= $#$tree; $i += 2) {
1070 next if ! $ops->{ $tree->[$i] };
1071 push @ops, $tree->[$i];
1072 push @exprs, [splice @$tree, 0, $i, ()];
1076 next if ! @exprs; # this iteration didn't have the current operator
1077 push @exprs, $tree if scalar @$tree; # add on any remaining items
1079 ### simplify sub expressions
1080 for my $node (@exprs) {
1082 $node = $node->[0]; # single item - its not a tree
1083 } elsif (@$node == 3) {
1084 $node = [ \
[ $node->[1], $node->[0], $node->[2] ], 0 ]; # single operator - put it straight on
1086 $node = $self->apply_precedence($node, $found); # more complicated - recurse
1090 ### assemble this current level
1093 # 1) items at the same precedence level must all be either right or left or ternary associative
1094 # 2) ternary items cannot share precedence with anybody else.
1095 # 3) there really shouldn't be another operator at the same level as a postfix
1096 my $type = $OP->{$ops[0]}->[0];
1098 if ($type eq 'ternary') {
1099 my $op = $OP->{$ops[0]}->[2]->[0]; # use the first op as what we are using
1101 ### return simple ternary
1103 $self->throw('parse', "Ternary operator mismatch") if $ops[0] ne $op;
1104 $self->throw('parse', "Ternary operator mismatch") if ! $ops[1] || $ops[1] eq $op;
1105 return [ \
[ $op, @exprs ], 0 ];
1109 ### reorder complex ternary - rare case
1110 while ($#ops >= 1) {
1111 ### if we look starting from the back - the first lead ternary op will always be next to its matching op
1112 for (my $i = $#ops; $i >= 0; $i --) {
1113 next if $OP->{$ops[$i]}->[2]->[1] eq $ops[$i];
1114 my ($op, $op2) = splice @ops, $i, 2, (); # remove the pair of operators
1115 my $node = [ \
[$op, @exprs[$i .. $i + 2] ], 0 ];
1116 splice @exprs, $i, 3, $node;
1119 return $exprs[0]; # at this point the ternary has been reduced to a single operator
1121 } elsif ($type eq 'right' || $type eq 'assign') {
1122 my $val = $exprs[-1];
1123 $val = [ \
[ $ops[$_ - 1], $exprs[$_], $val ], 0 ] for reverse (0 .. $#exprs - 1);
1127 my $val = $exprs[0];
1128 $val = [ \
[ $ops[$_ - 1], $val, $exprs[$_] ], 0 ] for (1 .. $#exprs);
1134 $self->throw('parse', "Couldn't apply precedence");
1137 ### look for arguments - both positional and named
1140 my $str_ref = shift;
1141 my $ARGS = shift || {};
1142 my $copy = $$str_ref;
1146 while (length $$str_ref) {
1147 my $copy = $$str_ref;
1148 if (defined(my $name = $self->parse_expr(\
$copy, {auto_quote
=> qr{ ^ (\w+) $QR_AQ_NOTDOT }xo}))
1149 && $copy =~ s{ ^ = >? \s* $QR_COMMENTS }{}ox) {
1150 $self->throw('parse', 'Named arguments not allowed') if $ARGS->{'positional_only'};
1151 my $val = $self->parse_expr(\
$copy);
1152 $copy =~ s{ ^ , \s* $QR_COMMENTS }{}ox;
1153 push @named, $name, $val;
1155 } elsif (defined(my $arg = $self->parse_expr($str_ref))) {
1157 $$str_ref =~ s{ ^ , \s* $QR_COMMENTS }{}ox;
1163 ### allow for named arguments to be added also
1164 push @args, [\
['hash', @named], 0] if scalar @named;
1169 ### allow for looking for $foo or ${foo.bar} in TEXT "nodes" of the parse tree.
1170 sub interpolate_node
{
1171 my ($self, $tree, $offset) = @_;
1172 return if $self->{'_in_perl'};
1174 ### split on variables while keeping the variables
1175 my @pieces = split m{ (?: ^ | (?<! \\)) (\$\w+ (?:\.\w+)* | \$\{ [^\}]+ \
}) }x
, $tree->[-1];
1176 if ($#pieces <= 0) {
1177 $tree->[-1] =~ s{ \\ ([\"\$]) }{$1}xg;
1183 foreach my $piece (@pieces) {
1184 $offset += length $piece; # we track the offset to make sure DEBUG has the right location
1185 if (! ($n++ % 2)) { # odds will always be text chunks
1186 next if ! length $piece;
1187 $piece =~ s{ \\ ([\"\$]) }{$1}xg;
1188 push @sub_tree, $piece;
1189 } elsif ($piece =~ m{ ^ \$ (\w+ (?:\.\w+)*) $ }x
1190 || $piece =~ m{ ^ \$\{ \s* ([^\}]+) \
} $ }x
) {
1192 push @sub_tree, ['GET', $offset - length($piece), $offset, $self->parse_expr(\
$name)];
1194 $self->throw('parse', "Parse error during interpolate node");
1198 ### replace the tree
1199 splice @$tree, -1, 1, @sub_tree;
1202 ###----------------------------------------------------------------###
1205 ### allow for the parse tree to store literals
1206 return $_[1] if ! ref $_[1];
1210 my $ARGS = shift || {};
1213 ### determine the top level of this particular variable access
1215 my $name = $var->[$i++];
1216 my $args = $var->[$i++];
1217 warn "play_expr: begin \"$name\"\n" if trace
;
1219 if (ref $name eq 'SCALAR') { # a scalar literal
1221 } elsif (ref $name eq 'REF') { # operator
1222 return $self->play_operator($$name) if ${ $name }->[0] eq '..';
1223 $ref = $self->play_operator($$name);
1224 } else { # a named variable access (ie via $name.foo)
1225 $name = $self->play_expr($name);
1226 if (defined $name) {
1227 return if $name =~ $QR_PRIVATE; # don't allow vars that begin with _
1228 $ref = $self->{'_vars'}->{$name};
1231 } elsif (defined $name) {
1232 if ($ARGS->{'is_namespace_during_compile'}) {
1233 $ref = $self->{'NAMESPACE'}->{$name};
1235 return if $name =~ $QR_PRIVATE; # don't allow vars that begin with _
1236 $ref = $self->{'_vars'}->{$name};
1237 $ref = $VOBJS->{$name} if ! defined $ref;
1243 while (defined $ref) {
1245 ### check at each point if the rurned thing was a code
1246 if (UNIVERSAL
::isa
($ref, 'CODE')) {
1247 my @results = $ref->($args ? map { $self->play_expr($_) } @$args : ());
1248 if (defined $results[0]) {
1249 $ref = ($#results > 0) ? \
@results : $results[0];
1250 } elsif (defined $results[1]) {
1251 die $results[1]; # TT behavior - why not just throw ?
1258 ### descend one chained level
1259 last if $i >= $#$var;
1260 my $was_dot_call = $ARGS->{'no_dots'} ? 1 : $var->[$i++] eq '.';
1261 $name = $var->[$i++];
1262 $args = $var->[$i++];
1263 warn "play_expr: nested \"$name\"\n" if trace
;
1265 ### allow for named portions of a variable name (foo.$name.bar)
1267 if (ref($name) eq 'ARRAY') {
1268 $name = $self->play_expr($name);
1269 if (! defined($name) || $name =~ $QR_PRIVATE || $name =~ /^\./) {
1274 die "Shouldn't get a ". ref($name) ." during a vivify on chain";
1277 if ($name =~ $QR_PRIVATE) { # don't allow vars that begin with _
1282 ### allow for scalar and filter access (this happens for every non virtual method call)
1284 if ($SCALAR_OPS->{$name}) { # normal scalar op
1285 $ref = $SCALAR_OPS->{$name}->($ref, $args ? map { $self->play_expr($_) } @$args : ());
1287 } elsif ($LIST_OPS->{$name}) { # auto-promote to list and use list op
1288 $ref = $LIST_OPS->{$name}->([$ref], $args ? map { $self->play_expr($_) } @$args : ());
1290 } elsif (my $filter = $self->{'FILTERS'}->{$name} # filter configured in Template args
1291 || $FILTER_OPS->{$name} # predefined filters in CET
1292 || (UNIVERSAL
::isa
($name, 'CODE') && $name) # looks like a filter sub passed in the stash
1293 || $self->list_filters->{$name}) { # filter defined in Template::Filters
1295 if (UNIVERSAL
::isa
($filter, 'CODE')) {
1296 $ref = eval { $filter->($ref) }; # non-dynamic filter - no args
1298 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1301 } elsif (! UNIVERSAL
::isa
($filter, 'ARRAY')) {
1302 $self->throw('filter', "invalid FILTER entry for '$name' (not a CODE ref)");
1304 } elsif (@$filter == 2 && UNIVERSAL
::isa
($filter->[0], 'CODE')) { # these are the TT style filters
1306 my $sub = $filter->[0];
1307 if ($filter->[1]) { # it is a "dynamic filter" that will return a sub
1308 ($sub, my $err) = $sub->($self->context, $args ? map { $self->play_expr($_) } @$args : ());
1309 if (! $sub && $err) {
1310 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1312 } elsif (! UNIVERSAL
::isa
($sub, 'CODE')) {
1313 $self->throw('filter', "invalid FILTER for '$name' (not a CODE ref)")
1314 if ref($sub) !~ /Template::Exception$/;
1318 $ref = $sub->($ref);
1321 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1324 } else { # this looks like our vmethods turned into "filters" (a filter stored under a name)
1325 $self->throw('filter', 'Recursive filter alias \"$name\"') if $seen_filters{$name} ++;
1326 $var = [$name, 0, '|', @$filter, @{$var}[$i..$#$var]]; # splice the filter into our current tree
1329 if (scalar keys %seen_filters
1330 && $seen_filters{$var->[$i - 5] || ''}) {
1331 $self->throw('filter', "invalid FILTER entry for '".$var->[$i - 5]."' (not a CODE ref)");
1339 ### method calls on objects
1340 if ($was_dot_call && UNIVERSAL
::can
($ref, 'can')) {
1341 my @args = $args ? map { $self->play_expr($_) } @$args : ();
1342 my @results = eval { $ref->$name(@args) };
1344 my $class = ref $ref;
1345 die $@ if ref $@ || $@ !~ /Can\'t locate object method "\Q$name\E" via package "\Q$class\E"/;
1346 } elsif (defined $results[0]) {
1347 $ref = ($#results > 0) ? \
@results : $results[0];
1349 } elsif (defined $results[1]) {
1350 die $results[1]; # TT behavior - why not just throw ?
1355 # didn't find a method by that name - so fail down to hash and array access
1358 ### hash member access
1359 if (UNIVERSAL
::isa
($ref, 'HASH')) {
1360 if ($was_dot_call && exists($ref->{$name}) ) {
1361 $ref = $ref->{$name};
1362 } elsif ($HASH_OPS->{$name}) {
1363 $ref = $HASH_OPS->{$name}->($ref, $args ? map { $self->play_expr($_) } @$args : ());
1364 } elsif ($ARGS->{'is_namespace_during_compile'}) {
1365 return $var; # abort - can't fold namespace variable
1371 } elsif (UNIVERSAL
::isa
($ref, 'ARRAY')) {
1372 if ($name =~ m{ ^ -? $QR_NUM $ }ox) {
1373 $ref = $ref->[$name];
1374 } elsif ($LIST_OPS->{$name}) {
1375 $ref = $LIST_OPS->{$name}->($ref, $args ? map { $self->play_expr($_) } @$args : ());
1384 ### allow for undefinedness
1385 if (! defined $ref) {
1386 if ($self->{'_debug_undef'}) {
1387 my $chunk = $var->[$i - 2];
1388 $chunk = $self->play_expr($chunk) if ref($chunk) eq 'ARRAY';
1389 die "$chunk is undefined\n";
1391 $ref = $self->undefined_any($var);
1399 my ($self, $var, $val, $ARGS) = @_;
1403 ### allow for the parse tree to store literals - the literal is used as a name (like [% 'a' = 'A' %])
1404 $var = [$var, 0] if ! ref $var;
1406 ### determine the top level of this particular variable access
1407 my $ref = $var->[$i++];
1408 my $args = $var->[$i++];
1410 if (ref($ref) eq 'ARRAY') { # named access (ie via $name.foo)
1411 $ref = $self->play_expr($ref);
1412 if (defined $ref && $ref !~ $QR_PRIVATE) { # don't allow vars that begin with _
1414 return $self->{'_vars'}->{$ref} = $val;
1416 $ref = $self->{'_vars'}->{$ref} ||= {};
1421 } else { # all other types can't be set
1424 } elsif (defined $ref) {
1425 return if $ref =~ $QR_PRIVATE; # don't allow vars that begin with _
1427 return $self->{'_vars'}->{$ref} = $val;
1429 $ref = $self->{'_vars'}->{$ref} ||= {};
1433 while (defined $ref) {
1435 ### check at each point if the returned thing was a code
1436 if (UNIVERSAL
::isa
($ref, 'CODE')) {
1437 my @results = $ref->($args ? map { $self->play_expr($_) } @$args : ());
1438 if (defined $results[0]) {
1439 $ref = ($#results > 0) ? \
@results : $results[0];
1440 } elsif (defined $results[1]) {
1441 die $results[1]; # TT behavior - why not just throw ?
1447 ### descend one chained level
1448 last if $i >= $#$var;
1449 my $was_dot_call = $ARGS->{'no_dots'} ? 1 : $var->[$i++] eq '.';
1450 my $name = $var->[$i++];
1451 my $args = $var->[$i++];
1453 ### allow for named portions of a variable name (foo.$name.bar)
1455 if (ref($name) eq 'ARRAY') {
1456 $name = $self->play_expr($name);
1457 if (! defined($name) || $name =~ /^[_.]/) {
1461 die "Shouldn't get a ".ref($name)." during a vivify on chain";
1464 if ($name =~ $QR_PRIVATE) { # don't allow vars that begin with _
1472 ### method calls on objects
1473 } elsif (UNIVERSAL
::can
($ref, 'can')) {
1475 my @args = $args ? map { $self->play_expr($_) } @$args : ();
1480 my @results = eval { $ref->$name(@args) };
1482 if (defined $results[0]) {
1483 $ref = ($#results > 0) ? \
@results : $results[0];
1484 } elsif (defined $results[1]) {
1485 die $results[1]; # TT behavior - why not just throw ?
1489 return if $lvalueish;
1492 my $class = ref $ref;
1493 die $@ if ref $@ || $@ !~ /Can\'t locate object method "\Q$name\E" via package "\Q$class\E"/;
1494 # fall on down to "normal" accessors
1497 ### hash member access
1498 if (UNIVERSAL
::isa
($ref, 'HASH')) {
1500 return $ref->{$name} = $val;
1502 $ref = $ref->{$name} ||= {};
1507 } elsif (UNIVERSAL
::isa
($ref, 'ARRAY')) {
1508 if ($name =~ m{ ^ -? $QR_NUM $ }ox) {
1510 return $ref->[$name] = $val;
1512 $ref = $ref->[$name] ||= {};
1526 ###----------------------------------------------------------------###
1532 if ($OP_DISPATCH->{$tree->[0]}) {
1534 if ($OP_ASSIGN->{$tree->[0]}) {
1535 my $val = $OP_DISPATCH->{$tree->[0]}->( $self->play_expr($tree->[1]), $self->play_expr($tree->[2]) );
1536 $self->set_variable($tree->[1], $val);
1539 return $OP_DISPATCH->{$tree->[0]}->( map { $self->play_expr($tree->[$_]) } 1 .. $#$tree );
1543 my $op = $tree->[0];
1545 ### do custom and short-circuitable operators
1547 my $val = $self->play_expr($tree->[2]);
1548 $self->set_variable($tree->[1], $val);
1551 } elsif ($op eq '||' || $op eq 'or' || $op eq 'OR') {
1552 return $self->play_expr($tree->[1]) || $self->play_expr($tree->[2]) || '';
1554 } elsif ($op eq '&&' || $op eq 'and' || $op eq 'AND') {
1555 my $var = $self->play_expr($tree->[1]) && $self->play_expr($tree->[2]);
1556 return $var ? $var : 0;
1558 } elsif ($op eq '?') {
1560 return $self->play_expr($tree->[1]) ? $self->play_expr($tree->[2]) : $self->play_expr($tree->[3]);
1562 } elsif ($op eq '++') {
1564 my $val = 0 + $self->play_expr($tree->[1]);
1565 $self->set_variable($tree->[1], $val + 1);
1566 return $tree->[2] ? $val : $val + 1; # ->[2] is set to 1 during parsing of postfix ops
1568 } elsif ($op eq '--') {
1570 my $val = 0 + $self->play_expr($tree->[1]);
1571 $self->set_variable($tree->[1], $val - 1);
1572 return $tree->[2] ? $val : $val - 1; # ->[2] is set to 1 during parsing of postfix ops
1575 $self->throw('operator', "Un-implemented operation $op");
1578 ###----------------------------------------------------------------###
1581 my ($self, $tag_ref, $node) = @_;
1583 my $block_name = '';
1584 if ($$tag_ref =~ s{ ^ (\w+ (?: :\w+)*) \s* (?! [\.\|]) }{}x
1585 || $$tag_ref =~ s{ ^ '(|.*?[^\\])' \s* (?! [\.\|]) }{}x
1586 || $$tag_ref =~ s{ ^ "(|.*?[^\\])" \s* (?! [\.\|]) }{}x
1589 ### allow for nested blocks to have nested names
1590 my @names = map {$_->[3]} grep {$_->[0] eq 'BLOCK'} @{ $self->{'_state'} };
1591 $block_name = join("/", @names, $block_name) if scalar @names;
1598 my ($self, $block_name, $node, $out_ref) = @_;
1600 ### store a named reference - but do nothing until something processes it
1601 $self->{'BLOCKS'}->{$block_name} = {
1602 _tree
=> $node->[4],
1603 name
=> $self->{'_vars'}->{'component'}->{'name'} .'/'. $block_name,
1609 sub parse_CALL
{ $DIRECTIVES->{'GET'}->[0]->(@_) }
1611 sub play_CALL
{ $DIRECTIVES->{'GET'}->[1]->(@_); return }
1614 my ($self, $tag_ref) = @_;
1615 return if $$tag_ref =~ s{ ^ DEFAULT \s* }{}x;
1616 return $self->parse_expr($tag_ref);
1620 my ($self, $tag_ref) = @_;
1621 return $self->parse_expr($tag_ref, {auto_quote
=> qr{ ^ (\w+ (?: \.\w+)*) $QR_AQ_SPACE }xo});
1625 my ($self, $undef, $node) = @_;
1626 $self->throw(lc($node->[0]), 'Control exception', $node);
1630 my ($self, $undef, $node, $out_ref) = @_;
1635 my ($self, $tag_ref) = @_;
1636 $$tag_ref =~ s{ ^ (on | off | format) \s* }{}xi || $self->throw('parse', "Unknown DEBUG option");
1638 if ($ret->[0] eq 'format') {
1639 $$tag_ref =~ s{ ^ ([\"\']) (|.*?[^\\]) \1 \s* }{}xs || $self->throw('parse', "Missing format string");
1646 my ($self, $ref) = @_;
1647 if ($ref->[0] eq 'on') {
1648 delete $self->{'_debug_off'};
1649 } elsif ($ref->[0] eq 'off') {
1650 $self->{'_debug_off'} = 1;
1651 } elsif ($ref->[0] eq 'format') {
1652 $self->{'_debug_format'} = $ref->[1];
1656 sub parse_DEFAULT
{ $DIRECTIVES->{'SET'}->[0]->(@_) }
1659 my ($self, $set) = @_;
1661 my ($op, $set, $default) = @$_;
1662 next if ! defined $set;
1663 my $val = $self->play_expr($set);
1665 $default = defined($default) ? $self->play_expr($default) : '';
1666 $self->set_variable($set, $default);
1673 my ($self, $tag_ref) = @_;
1674 my $ref = $self->parse_expr($tag_ref);
1679 my ($self, $ident, $node) = @_;
1680 require Data
::Dumper
;
1681 local $Data::Dumper
::Sortkeys
= 1;
1682 my $info = $self->node_info($node);
1686 $out = Data
::Dumper
::Dumper
($self->play_expr($ident));
1687 $var = $info->{'text'};
1688 $var =~ s/^[+\-~=]?\s*DUMP\s+//;
1689 $var =~ s/\s*[+\-~=]?$//;
1691 my @were_never_here = (qw(template component), grep {$_ =~ $QR_PRIVATE} keys %{ $self->{'_vars'} });
1692 local @{ $self->{'_vars'} }{ @were_never_here };
1693 delete @{ $self->{'_vars'} }{ @were_never_here };
1694 $out = Data
::Dumper
::Dumper
($self->{'_vars'});
1695 $var = 'EntireStash';
1697 if ($ENV{'REQUEST_METHOD'}) {
1699 $out = "<pre>$out</pre>";
1700 $out =~ s/\$VAR1/$var/;
1701 $out = "<b>DUMP: File \"$info->{file}\" line $info->{line}</b>$out";
1703 $out =~ s/\$VAR1/$var/;
1710 my ($self, $tag_ref) = @_;
1712 if ($$tag_ref =~ s{ ^ ([^\W\d]\w*) \s* = \s* }{}x) {
1716 my $filter = $self->parse_expr($tag_ref);
1717 $filter = '' if ! defined $filter;
1719 return [$name, $filter];
1723 my ($self, $ref, $node, $out_ref) = @_;
1724 my ($name, $filter) = @$ref;
1726 return '' if ! @$filter;
1728 $self->{'FILTERS'}->{$name} = $filter if length $name;
1730 my $sub_tree = $node->[4];
1734 eval { $self->execute_tree($sub_tree, \
$out) };
1735 die $@ if $@ && ref($@) !~ /Template::Exception$/;
1737 my $var = [\
$out, 0, '|', @$filter]; # make a temporary var out of it
1740 return $DIRECTIVES->{'GET'}->[1]->($self, $var, $node, $out_ref);
1744 my ($self, $tag_ref) = @_;
1745 my $items = $self->parse_expr($tag_ref);
1747 if ($$tag_ref =~ s{ ^ (= | [Ii][Nn]\b) \s* }{}x) {
1749 $items = $self->parse_expr($tag_ref);
1751 return [$var, $items];
1755 my ($self, $ref, $node, $out_ref) = @_;
1757 ### get the items - make sure it is an arrayref
1758 my ($var, $items) = @$ref;
1760 $items = $self->play_expr($items);
1761 return '' if ! defined $items;
1763 if (ref($items) !~ /Iterator$/) {
1764 $items = $PACKAGE_ITERATOR->new($items);
1767 my $sub_tree = $node->[4];
1769 local $self->{'_vars'}->{'loop'} = $items;
1771 ### if the FOREACH tag sets a var - then nothing but the loop var gets localized
1773 my ($item, $error) = $items->get_first;
1776 $self->set_variable($var, $item);
1778 ### execute the sub tree
1779 eval { $self->execute_tree($sub_tree, $out_ref) };
1781 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
1782 if ($err->type eq 'next') {
1783 ($item, $error) = $items->get_next;
1786 last if $err->type =~ /last|break/;
1791 ($item, $error) = $items->get_next;
1793 die $error if $error && $error != 3; # Template::Constants::STATUS_DONE;
1794 ### if the FOREACH tag doesn't set a var - then everything gets localized
1797 ### localize variable access for the foreach
1798 my $swap = $self->{'_vars'};
1799 local $self->{'_vars'} = my $copy = {%$swap};
1801 ### iterate use the iterator object
1802 #foreach (my $i = $items->index; $i <= $#$vals; $items->index(++ $i)) {
1803 my ($item, $error) = $items->get_first;
1806 if (ref($item) eq 'HASH') {
1807 @$copy{keys %$item} = values %$item;
1810 ### execute the sub tree
1811 eval { $self->execute_tree($sub_tree, $out_ref) };
1813 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
1814 if ($err->type eq 'next') {
1815 ($item, $error) = $items->get_next;
1818 last if $err->type =~ /last|break/;
1823 ($item, $error) = $items->get_next;
1825 die $error if $error && $error != 3; # Template::Constants::STATUS_DONE;
1832 my ($self, $tag_ref) = @_;
1833 my $ref = $self->parse_expr($tag_ref);
1834 $self->throw('parse', "Missing variable name") if ! defined $ref;
1839 my ($self, $ident, $node) = @_;
1840 my $var = $self->play_expr($ident);
1841 return (! defined $var) ? $self->undefined_get($ident, $node) : $var;
1845 my ($self, $tag_ref) = @_;
1846 return $self->parse_expr($tag_ref);
1850 my ($self, $var, $node, $out_ref) = @_;
1852 my $val = $self->play_expr($var);
1854 my $body_ref = $node->[4] ||= [];
1855 $self->execute_tree($body_ref, $out_ref);
1859 while ($node = $node->[5]) { # ELSE, ELSIF's
1860 if ($node->[0] eq 'ELSE') {
1861 my $body_ref = $node->[4] ||= [];
1862 $self->execute_tree($body_ref, $out_ref);
1865 my $var = $node->[3];
1866 my $val = $self->play_expr($var);
1868 my $body_ref = $node->[4] ||= [];
1869 $self->execute_tree($body_ref, $out_ref);
1876 sub parse_INCLUDE
{ $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
1879 my ($self, $tag_ref, $node, $out_ref) = @_;
1881 ### localize the swap
1882 my $swap = $self->{'_vars'};
1883 local $self->{'_vars'} = {%$swap};
1885 ### localize the blocks
1886 my $blocks = $self->{'BLOCKS'};
1887 local $self->{'BLOCKS'} = {%$blocks};
1889 my $str = $DIRECTIVES->{'PROCESS'}->[1]->($self, $tag_ref, $node, $out_ref);
1894 sub parse_INSERT
{ $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
1897 my ($self, $var, $node, $out_ref) = @_;
1898 my ($names, $args) = @$var;
1900 foreach my $name (@$names) {
1901 my $filename = $self->play_expr($name);
1902 $$out_ref .= $self->_insert($filename);
1909 my ($self, $tag_ref, $node) = @_;
1910 my $copy = $$tag_ref;
1912 my $name = $self->parse_expr(\
$copy, {auto_quote
=> qr{ ^ (\w+) $QR_AQ_NOTDOT }xo});
1913 $self->throw('parse', "Missing macro name") if ! defined $name;
1915 $name = [ $name, 0 ];
1919 if ($copy =~ s{ ^ \( \s* }{}x) {
1920 $args = $self->parse_args(\
$copy, {positional_only
=> 1});
1921 $copy =~ s
{ ^ \
) \s
* }{}x
|| $self->throw('parse.missing', "Missing close ')'");
1924 $node->[6] = 1; # set a flag to keep parsing
1926 return [$name, $args];
1930 my ($self, $ref, $node, $out_ref) = @_;
1931 my ($name, $args) = @$ref;
1933 ### get the sub tree
1934 my $sub_tree = $node->[4];
1935 if (! $sub_tree || ! $sub_tree->[0]) {
1936 $self->set_variable($name, undef);
1938 } elsif ($sub_tree->[0]->[0] eq 'BLOCK') {
1939 $sub_tree = $sub_tree->[0]->[4];
1942 my $self_copy = $self;
1943 eval {require Scalar
::Util
; Scalar
::Util
::weaken
($self_copy)};
1945 ### install a closure in the stash that will handle the macro
1946 $self->set_variable($name, sub {
1948 my $copy = $self_copy->{'_vars'};
1949 local $self_copy->{'_vars'}= {%$copy};
1952 my $named = pop(@_) if $_[-1] && UNIVERSAL
::isa
($_[-1],'HASH') && $#_ > $#$args;
1953 my @positional = @_;
1954 foreach my $var (@$args) {
1955 $self_copy->set_variable($var, shift(@positional));
1957 foreach my $name (sort keys %$named) {
1958 $self_copy->set_variable([$name, 0], $named->{$name});
1961 ### finally - run the sub tree
1963 $self_copy->execute_tree($sub_tree, \
$out);
1971 my ($self, $hash) = @_;
1973 if ($self->{'_top_level'}) {
1974 $ref = $self->{'_vars'}->{'template'} ||= {};
1976 $ref = $self->{'_vars'}->{'component'} ||= {};
1978 foreach my $key (keys %$hash) {
1979 next if $key eq 'name' || $key eq 'modtime';
1980 $ref->{$key} = $hash->{$key};
1985 sub parse_PERL
{ shift-
>{'_in_perl'} = 1; return }
1988 my ($self, $info, $node, $out_ref) = @_;
1989 $self->throw('perl', 'EVAL_PERL not set') if ! $self->{'EVAL_PERL'};
1991 ### fill in any variables
1992 my $perl = $node->[4] || return;
1994 $self->execute_tree($perl, \
$out);
1995 $out = $1 if $out =~ /^(.+)$/s; # blatant untaint - shouldn't use perl anyway
2000 package CGI
::Ex
::Template
::Perl
;
2002 my $context = $self->context;
2003 my $stash = $context->stash;
2005 ### setup a fake handle
2007 tie
*PERLOUT
, $CGI::Ex
::Template
::PACKAGE_PERL_HANDLE
, $out_ref;
2008 my $old_fh = select PERLOUT
;
2013 ### put the handle back
2021 $self->throw('undef', $err) if ref($err) !~ /Template::Exception$/;
2029 my ($self, $tag_ref) = @_;
2030 my $info = [[], []];
2031 while (defined(my $filename = $self->parse_expr($tag_ref, {
2032 auto_quote
=> qr{ ^ ($QR_FILENAME | \w+ (?: :\w+)* ) $QR_AQ_SPACE }xo,
2034 push @{$info->[0]}, $filename;
2035 last if $$tag_ref !~ s{ ^ \+ \s* }{}x;
2038 ### allow for post process variables
2039 while (length $$tag_ref) {
2040 last if $$tag_ref =~ / ^ (\w+) (?: ;|$|\s)/x && $DIRECTIVES->{$1}; ### looks like a directive - we are done
2042 my $var = $self->parse_expr($tag_ref);
2043 last if ! defined $var;
2044 if ($$tag_ref !~ s{ ^ = >? \s* }{}x) {
2045 $self->throw('parse.missing.equals', 'Missing equals while parsing args');
2048 my $val = $self->parse_expr($tag_ref);
2049 push @{$info->[1]}, [$var, $val];
2050 $$tag_ref =~ s{ ^ , \s* $QR_COMMENTS }{}ox if $val;
2057 my ($self, $info, $node, $out_ref) = @_;
2059 my ($files, $args) = @$info;
2063 my ($key, $val) = @$_;
2064 $val = $self->play_expr($val);
2065 if (ref($key) && @$key == 2 && $key->[0] eq 'import' && UNIVERSAL
::isa
($val, 'HASH')) { # import ?! - whatever
2066 foreach my $key (keys %$val) {
2067 $self->set_variable([$key,0], $val->{$key});
2071 $self->set_variable($key, $val);
2074 ### iterate on any passed block or filename
2075 foreach my $ref (@$files) {
2076 next if ! defined $ref;
2077 my $filename = $self->play_expr($ref);
2078 my $out = ''; # have temp item to allow clear to correctly clear
2080 ### normal blocks or filenames
2081 if (! ref $filename) {
2082 eval { $self->_process($filename, $self->{'_vars'}, \
$out) }; # restart the swap - passing it our current stash
2084 ### allow for $template which is used in some odd instances
2086 $self->throw('process', "Unable to process document $filename") if $ref->[0] ne 'template';
2087 $self->throw('process', "Recursion detected in $node->[0] \$template") if $self->{'_process_dollar_template'};
2088 local $self->{'_process_dollar_template'} = 1;
2089 local $self->{'_vars'}->{'component'} = my $doc = $filename;
2090 return if ! $doc->{'_tree'};
2092 ### execute and trim
2093 eval { $self->execute_tree($doc->{'_tree'}, \
$out) };
2094 if ($self->{'TRIM'}) {
2095 $out =~ s{ \s+ $ }{}x;
2096 $out =~ s{ ^ \s+ }{}x;
2099 ### handle exceptions
2101 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2102 $err->doc($doc) if $doc && $err->can('doc') && ! $err->doc;
2107 ### append any output
2110 die $err if ref($err) !~ /Template::Exception$/ || $err->type !~ /return/;
2118 my ($self, $info, $node, $out_ref) = @_;
2119 $self->throw('perl', 'EVAL_PERL not set') if ! $self->{'EVAL_PERL'};
2121 ### fill in any variables
2122 my $tree = $node->[4] || return;
2124 $self->execute_tree($tree, \
$perl);
2125 $perl = $1 if $perl =~ /^(.+)$/s; # blatant untaint - shouldn't use perl anyway
2131 package CGI
::Ex
::Template
::Perl
;
2133 my $context = $self->context;
2134 my $stash = $context->stash;
2141 $$out_ref .= $output;
2144 $self->throw('undef', $err) if ref($err) !~ /Template::Exception$/;
2152 my ($self, $tag_ref, $node, $initial_op, $initial_var) = @_;
2154 my $copy = $$tag_ref;
2158 if ($$tag_ref =~ $QR_DIRECTIVE # find a word
2159 && $DIRECTIVES->{$1}) { # is it a directive - if so set up capturing
2160 $node->[6] = 1; # set a flag to keep parsing
2161 my $val = $node->[4] ||= []; # setup storage
2162 return [[$initial_op, $initial_var, $val]];
2163 } else { # get a normal variable
2164 return [[$initial_op, $initial_var, $self->parse_expr($tag_ref)]];
2168 while (length $$tag_ref) {
2169 my $set = $self->parse_expr($tag_ref);
2170 last if ! defined $set;
2172 if ($$tag_ref =~ s{ ^ ($QR_OP_ASSIGN) >? \s* }{}x) {
2174 if ($$tag_ref =~ $QR_DIRECTIVE # find a word
2175 && $DIRECTIVES->{$1}) { # is it a directive - if so set up capturing
2176 $node->[6] = 1; # set a flag to keep parsing
2177 my $val = $node->[4] ||= []; # setup storage
2178 push @SET, [$op, $set, $val];
2180 } else { # get a normal variable
2181 push @SET, [$op, $set, $self->parse_expr($tag_ref)];
2184 push @SET, ['=', $set, undef];
2191 my ($self, $set, $node) = @_;
2193 my ($op, $set, $val) = @$_;
2194 if (! defined $val) { # not defined
2196 } elsif ($node->[4] && $val == $node->[4]) { # a captured directive
2197 my $sub_tree = $node->[4];
2198 $sub_tree = $sub_tree->[0]->[4] if $sub_tree->[0] && $sub_tree->[0]->[0] eq 'BLOCK';
2200 $self->execute_tree($sub_tree, \
$val);
2201 } else { # normal var
2202 $val = $self->play_expr($val);
2205 if ($OP_DISPATCH->{$op}) {
2207 $val = $OP_DISPATCH->{$op}->($self->play_expr($set), $val);
2210 $self->set_variable($set, $val);
2215 sub parse_SWITCH
{ $DIRECTIVES->{'GET'}->[0]->(@_) }
2218 my ($self, $var, $node, $out_ref) = @_;
2220 my $val = $self->play_expr($var);
2221 $val = '' if ! defined $val;
2222 ### $node->[4] is thrown away
2225 while ($node = $node->[5]) { # CASES
2226 my $var = $node->[3];
2227 if (! defined $var) {
2228 $default = $node->[4];
2232 my $val2 = $self->play_expr($var);
2233 $val2 = [$val2] if ! UNIVERSAL
::isa
($val2, 'ARRAY');
2234 for my $test (@$val2) { # find matching values
2235 next if ! defined $val && defined $test;
2236 next if defined $val && ! defined $test;
2237 if ($val ne $test) { # check string-wise first - then numerical
2238 next if $val !~ m{ ^ -? $QR_NUM $ }ox;
2239 next if $test !~ m{ ^ -? $QR_NUM $ }ox;
2240 next if $val != $test;
2243 my $body_ref = $node->[4] ||= [];
2244 $self->execute_tree($body_ref, $out_ref);
2250 $self->execute_tree($default, $out_ref);
2257 my ($self, $tag_ref, $node) = @_;
2258 my $name = $self->parse_expr($tag_ref, {auto_quote
=> qr{ ^ (\w+ (?: \.\w+)*) $QR_AQ_SPACE }xo});
2259 $self->throw('parse.missing', "Missing name in THROW", $node) if ! $name;
2260 my $args = $self->parse_args($tag_ref);
2261 return [$name, $args];
2265 my ($self, $ref, $node) = @_;
2266 my ($name, $args) = @$ref;
2267 $name = $self->play_expr($name);
2268 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2269 $self->throw($name, \
@args, $node);
2273 my ($self, $foo, $node, $out_ref) = @_;
2276 my $body_ref = $node->[4];
2277 eval { $self->execute_tree($body_ref, \
$out) };
2280 if (! $node->[5]) { # no catch or final
2281 if (! $err) { # no final block and no error
2285 $self->throw('parse.missing', "Missing CATCH block", $node);
2288 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2289 if ($err->type =~ /stop|return/) {
2295 ### loop through the nested catch and final blocks
2298 my $type = $err ? $err->type : '';
2300 while ($node = $node->[5]) { # CATCH
2301 if ($node->[0] eq 'FINAL') {
2302 $final = $node->[4];
2306 my $name = $self->play_expr($node->[3]);
2307 $name = '' if ! defined $name || lc($name) eq 'default';
2308 if ($type =~ / ^ \Q$name\E \b /x
2309 && (! defined($last_found) || length($last_found) < length($name))) { # more specific wins
2310 $catch_body_ref = $node->[4] || [];
2311 $last_found = $name;
2315 ### play the best catch block
2317 if (! $catch_body_ref) {
2321 local $self->{'_vars'}->{'error'} = $err;
2322 local $self->{'_vars'}->{'e'} = $err;
2323 eval { $self->execute_tree($catch_body_ref, \
$out) };
2331 $self->execute_tree($final, \
$out) if $final;
2339 my $ref = $DIRECTIVES->{'IF'}->[0]->(@_);
2340 return [ \
[ '!', $ref ], 0 ];
2343 sub play_UNLESS
{ return $DIRECTIVES->{'IF'}->[1]->(@_) }
2346 my ($self, $tag_ref) = @_;
2349 my $copy = $$tag_ref;
2350 if (defined(my $_var = $self->parse_expr(\
$copy, {auto_quote
=> qr{ ^ (\w+) $QR_AQ_NOTDOT }xo}))
2351 && $copy =~ s{ ^ = >? \s* $QR_COMMENTS }{}ox) {
2357 my $module = $self->parse_expr(\
$copy, {auto_quote
=> qr{ ^ (\w+ (?: (?:\.|::) \w+)*) $QR_AQ_NOTDOT }xo});
2358 $self->throw('parse', "Missing plugin name while parsing $$tag_ref") if ! defined $module;
2359 $module =~ s/\./::/g;
2362 my $open = $copy =~ s{ ^ \( \s* $QR_COMMENTS }{}ox;
2363 $args = $self->parse_args(\
$copy);
2366 $copy =~ s
{ ^ \
) \s
* $QR_COMMENTS }{}ox
|| $self->throw('parse.missing', "Missing close ')'");
2370 return [$var, $module, $args];
2374 my ($self, $ref, $node, $out_ref) = @_;
2375 my ($var, $module, $args) = @$ref;
2377 ### get the stash storage location - default to the module
2378 $var = $module if ! defined $var;
2379 my @var = map {($_, 0, '.')} split /(?:\.|::)/, $var;
2380 pop @var; # remove the trailing '.'
2382 ### look for a plugin_base
2383 my $BASE = $self->{'PLUGIN_BASE'} || 'Template::Plugin'; # I'm not maintaining plugins - leave that to TT
2386 foreach my $base (ref($BASE) eq 'ARRAY' ? @$BASE : $BASE) {
2387 my $package = $self->{'PLUGINS'}->{$module} ? $self->{'PLUGINS'}->{$module}
2388 : $self->{'PLUGIN_FACTORY'}->{$module} ? $self->{'PLUGIN_FACTORY'}->{$module}
2389 : "${base}::${module}";
2390 my $require = "$package.pm";
2391 $require =~ s
|::|/|g
;
2393 ### try and load the module - fall back to bare module if allowed
2394 if ($self->{'PLUGIN_FACTORY'}->{$module} || eval {require $require}) {
2395 my $shape = $package->load;
2396 my $context = $self->context;
2397 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2398 $obj = $shape->new($context, @args);
2399 } elsif (lc($module) eq 'iterator') { # use our iterator if none found (TT's works just fine)
2400 $obj = $PACKAGE_ITERATOR->new($args ? $self->play_expr($args->[0]) : []);
2401 } elsif (my @packages = grep {lc($package) eq lc($_)} @{ $self->list_plugins({base
=> $base}) }) {
2402 foreach my $package (@packages) {
2403 my $require = "$package.pm";
2404 $require =~ s
|::|/|g
;
2405 eval {require $require} || next;
2406 my $shape = $package->load;
2407 my $context = $self->context;
2408 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2409 $obj = $shape->new($context, @args);
2411 } elsif ($self->{'LOAD_PERL'}) {
2412 my $require = "$module.pm";
2413 $require =~ s
|::|/|g
;
2414 if (eval {require $require}) {
2415 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2416 $obj = $module->new(@args);
2420 if (! defined $obj) {
2421 my $err = "$module: plugin not found";
2422 $self->throw('plugin', $err);
2426 $self->set_variable(\
@var, $obj);
2432 my ($self, $var, $node, $out_ref) = @_;
2433 return '' if ! defined $var;
2435 my $sub_tree = $node->[4];
2437 ### iterate use the iterator object
2438 my $count = $WHILE_MAX;
2439 while (--$count > 0) {
2441 $self->play_expr($var) || last;
2443 ### execute the sub tree
2444 eval { $self->execute_tree($sub_tree, $out_ref) };
2446 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
2447 next if $err->type =~ /next/;
2448 last if $err->type =~ /last|break/;
2453 die "WHILE loop terminated (> $WHILE_MAX iterations)\n" if ! $count;
2458 sub parse_WRAPPER
{ $DIRECTIVES->{'INCLUDE'}->[0]->(@_) }
2461 my ($self, $var, $node, $out_ref) = @_;
2462 my $sub_tree = $node->[4] || return;
2464 my ($names, $args) = @$var;
2467 $self->execute_tree($sub_tree, \
$out);
2469 foreach my $name (reverse @$names) {
2470 local $self->{'_vars'}->{'content'} = $out;
2472 $DIRECTIVES->{'INCLUDE'}->[1]->($self, [[$name], $args], $node, \
$out);
2479 ###----------------------------------------------------------------###
2483 $self->{'_vars'} = shift if $#_ == 0;
2484 return $self->{'_vars'} ||= {};
2487 sub include_filename
{
2488 my ($self, $file) = @_;
2489 if ($file =~ m
|^/|) {
2490 $self->throw('file', "$file absolute paths are not allowed (set ABSOLUTE option)") if ! $self->{'ABSOLUTE'};
2491 return $file if -e
$file;
2492 } elsif ($file =~ m{(^|/)\.\./}) {
2493 $self->throw('file', "$file relative paths are not allowed (set RELATIVE option)") if ! $self->{'RELATIVE'};
2494 return $file if -e
$file;
2497 my $paths = $self->{'INCLUDE_PATHS'} ||= do {
2498 # TT does this everytime a file is looked up - we are going to do it just in time - the first time
2499 my $paths = $self->{'INCLUDE_PATH'} || $self->throw('file', "INCLUDE_PATH not set");
2500 $paths = $paths->() if UNIVERSAL
::isa
($paths, 'CODE');
2501 $paths = $self->split_paths($paths) if ! UNIVERSAL
::isa
($paths, 'ARRAY');
2502 $paths; # return of the do
2504 foreach my $path (@$paths) {
2505 return "$path/$file" if -e
"$path/$file";
2508 $self->throw('file', "$file: not found");
2512 my ($self, $path) = @_;
2513 return $path if ref $path;
2514 my $delim = $self->{'DELIMITER'} || ':';
2515 $delim = ($delim eq ':' && $^O eq 'MSWin32') ? qr
|:(?!/)| : qr
|\Q
$delim\E
|;
2516 return [split $delim, $path];
2520 my ($self, $file) = @_;
2521 return $self->slurp($self->include_filename($file));
2525 my ($self, $file) = @_;
2527 open(FH
, "<$file") || $self->throw('file', "$file couldn't be opened: $!");
2528 read FH
, my $txt, -s
$file;
2533 sub process_simple
{
2535 my $in = shift || die "Missing input";
2536 my $swap = shift || die "Missing variable hash";
2537 my $out = shift || die "Missing output string ref";
2540 delete $self->{'_debug_off'};
2541 delete $self->{'_debug_format'};
2542 local $self->{'_start_top_level'} = 1;
2543 $self->_process($in, $swap, $out);
2546 if ($err->type !~ /stop|return|next|last|break/) {
2547 $self->{'error'} = $err;
2555 my ($self, $in, $swap, $out, @ARGS) = @_;
2556 delete $self->{'error'};
2559 $args = ($#ARGS == 0 && UNIVERSAL
::isa
($ARGS[0], 'HASH')) ? {%{$ARGS[0]}} : {@ARGS} if scalar @ARGS;
2560 $self->DEBUG("set binmode\n") if $DEBUG && $args->{'binmode'}; # holdover for TT2 tests
2565 if (UNIVERSAL
::isa
($in, 'SCALAR')) { # reference to a string
2567 } elsif (UNIVERSAL
::isa
($in, 'CODE')) {
2569 $content = \
$content;
2570 } else { # should be a file handle
2573 $content = \
$content;
2576 ### should be a filename
2581 ### prepare block localization
2582 my $blocks = $self->{'BLOCKS'} ||= {};
2589 ### localize the stash
2591 my $var1 = $self->{'_vars'} ||= {};
2592 my $var2 = $self->{'VARIABLES'} || $self->{'PRE_DEFINE'} || {};
2593 $var1->{'global'} ||= {}; # allow for the "global" namespace - that continues in between processing
2594 my $copy = {%$var2, %$var1, %$swap};
2595 local $copy->{'template'};
2597 local $self->{'BLOCKS'} = $blocks = {%$blocks}; # localize blocks - but save a copy to possibly restore
2599 delete $self->{'_debug_off'};
2600 delete $self->{'_debug_format'};
2602 ### handle pre process items that go before every document
2603 if ($self->{'PRE_PROCESS'}) {
2604 foreach my $name (@{ $self->split_paths($self->{'PRE_PROCESS'}) }) {
2606 $self->_process($name, $copy, \
$out);
2607 $output = $out . $output;
2611 ### handle the process config - which loads a template in place of the real one
2612 if (exists $self->{'PROCESS'}) {
2613 ### load the meta data for the top document
2614 my $doc = $self->load_parsed_tree($content) || {};
2615 my $meta = ($doc->{'_tree'} && ref($doc->{'_tree'}->[0]) && $doc->{'_tree'}->[0]->[0] eq 'METADEF')
2616 ? $doc->{'_tree'}->[0]->[3] : {};
2618 $copy->{'template'} = $doc;
2619 @{ $doc }{keys %$meta} = values %$meta;
2621 ### process any other templates
2622 foreach my $name (@{ $self->split_paths($self->{'PROCESS'}) }) {
2623 next if ! length $name;
2624 $self->_process($name, $copy, \
$output);
2627 ### handle "normal" content
2629 local $self->{'_start_top_level'} = 1;
2630 $self->_process($content, $copy, \
$output);
2634 ### handle post process items that go after every document
2635 if ($self->{'POST_PROCESS'}) {
2636 foreach my $name (@{ $self->split_paths($self->{'POST_PROCESS'}) }) {
2637 $self->_process($name, $copy, \
$output);
2643 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2644 if ($err->type !~ /stop|return|next|last|break/) {
2645 $self->{'error'} = $err;
2652 ### clear blocks as asked (AUTO_RESET) defaults to on
2653 $self->{'BLOCKS'} = $blocks if exists($self->{'AUTO_RESET'}) && ! $self->{'AUTO_RESET'};
2655 ### send the content back out
2656 $out ||= $self->{'OUTPUT'};
2658 if (UNIVERSAL
::isa
($out, 'CODE')) {
2660 } elsif (UNIVERSAL
::can
($out, 'print')) {
2661 $out->print($output);
2662 } elsif (UNIVERSAL
::isa
($out, 'SCALAR')) { # reference to a string
2664 } elsif (UNIVERSAL
::isa
($out, 'ARRAY')) {
2665 push @$out, $output;
2666 } else { # should be a file handle
2669 } elsif ($out) { # should be a filename
2671 if ($out =~ m
|^/|) {
2672 if (! $self->{'ABSOLUTE'}) {
2673 $self->{'error'} = $self->throw('file', "ABSOLUTE paths disabled");
2677 } elsif ($out =~ m
|^\
.\
.?/|) {
2678 if (! $self->{'RELATIVE'}) {
2679 $self->{'error'} = $self->throw('file', "RELATIVE paths disabled");
2684 if (! $self->{'OUTPUT_PATH'}) {
2685 $self->{'error'} = $self->throw('file', "OUTPUT_PATH not set");
2687 $file = $self->{'OUTPUT_PATH'} . '/' . $out;
2692 if (open FH
, ">$file") {
2693 if (my $bm = $args->{'binmode'}) {
2694 if (+$bm == 1) { binmode FH
}
2695 else { binmode FH
, $bm }
2700 $self->{'error'} = $self->throw('file', "$out couldn't be opened for writing: $!");
2707 return if $self->{'error'};
2711 sub error
{ shift-
>{'error'} }
2715 print STDERR
"DEBUG: ", @_;
2718 ###----------------------------------------------------------------###
2721 my ($self, $type, $info, $node) = @_;
2722 return $type if ref($type) =~ /Template::Exception$/;
2723 if (ref($info) eq 'ARRAY') {
2724 my $hash = ref($info->[-1]) eq 'HASH' ? pop(@$info) : {};
2725 if (@$info >= 2 || scalar keys %$hash) {
2727 $hash->{$_} = $info->[$_] for 0 .. $#$info;
2728 $hash->{'args'} = $info;
2730 } elsif (@$info == 1) {
2737 return $PACKAGE_EXCEPTION->new($type, $info, $node);
2740 sub throw
{ die shift-
>exception(@_) }
2744 return bless {_template
=> $self}, $PACKAGE_CONTEXT; # a fake context
2748 my ($self, $ident, $node) = @_;
2749 return $self->{'UNDEFINED_GET'}->($self, $ident, $node) if $self->{'UNDEFINED_GET'};
2754 my ($self, $ident) = @_;
2755 return $self->{'UNDEFINED_ANY'}->($self, $ident) if $self->{'UNDEFINED_ANY'};
2761 return $self->{'_filters'} ||= eval { require Template
::Filters
; $Template::Filters
::FILTERS
} || {};
2766 my $args = shift || {};
2767 my $base = $args->{'base'} || '';
2769 return $self->{'_plugins'}->{$base} ||= do {
2773 my @dirs = grep {-d
$_} map {"$_/$base"} @INC;
2775 foreach my $dir (@dirs) {
2777 File
::Find
::find
(sub {
2778 my $mod = $base .'/'. ($File::Find
::name
=~ m
|^ $dir / (.*\w
) \
.pm
$|x
? $1 : return);
2780 push @plugins, $mod;
2784 \
@plugins; # return of the do
2789 my ($self, $node) = @_;
2790 my $info = $self->node_info($node);
2791 my $format = $self->{'_debug_format'} || $self->{'DEBUG_FORMAT'} || "\n## \$file line \$line : [% \$text %] ##\n";
2792 $format =~ s{\$(file|line|text)}{$info->{$1}}g
;
2797 my ($self, $node) = @_;
2798 my $doc = $self->{'_vars'}->{'component'};
2800 my $j = $node->[2] || return ''; # METADEF can be 0
2801 $doc->{'_content'} ||= do { my $s = $self->slurp($doc->{'_filename'}) ; \
$s };
2802 my $s = substr(${ $doc->{'_content'} }, $i, $j - $i);
2806 file
=> $doc->{'name'},
2807 line
=> $self->get_line_number_by_index($doc, $i),
2812 sub get_line_number_by_index
{
2813 my ($self, $doc, $index) = @_;
2814 ### get the line offsets for the doc
2815 my $lines = $doc->{'line_offsets'} ||= do {
2816 $doc->{'_content'} ||= do { my $s = $self->slurp($doc->{'_filename'}) ; \
$s };
2820 $i = index(${ $doc->{'_content'} }, "\n", $i) + 1;
2826 ### binary search them (this is fast even on big docs)
2827 return $#$lines + 1 if $index > $lines->[-1];
2828 my ($i, $j) = (0, $#$lines);
2830 return $i + 1 if abs($i - $j) <= 1;
2831 my $k = int(($i + $j) / 2);
2832 $j = $k if $lines->[$k] >= $index;
2833 $i = $k if $lines->[$k] <= $index;
2837 ###----------------------------------------------------------------###
2838 ### long virtual methods or filters
2839 ### many of these vmethods have used code from Template/Stash.pm to
2840 ### assure conformance with the TT spec.
2842 sub define_vmethod
{
2843 my ($self, $type, $name, $sub) = @_;
2844 if ( $type =~ /scalar|item/i) { $SCALAR_OPS->{$name} = $sub }
2845 elsif ($type =~ /array|list/i ) { $LIST_OPS->{ $name} = $sub }
2846 elsif ($type =~ /hash/i ) { $HASH_OPS->{ $name} = $sub }
2847 elsif ($type =~ /filter/i ) { $FILTER_OPS->{$name} = $sub }
2849 die "Invalid type vmethod type $type";
2854 sub vmethod_as_scalar
{
2855 my $str = shift; $str = '' if ! defined $str;
2856 my $pat = shift; $pat = '%s' if ! defined $pat;
2858 return @_ ? sprintf($pat, $_[0], $str)
2859 : sprintf($pat, $str);
2862 sub vmethod_as_list
{
2863 my $ref = shift || return '';
2864 my $pat = shift; $pat = '%s' if ! defined $pat;
2865 my $sep = shift; $sep = ' ' if ! defined $sep;
2867 return @_ ? join($sep, map {sprintf $pat, $_[0], $_} @$ref)
2868 : join($sep, map {sprintf $pat, $_} @$ref);
2871 sub vmethod_as_hash
{
2872 my $ref = shift || return '';
2873 my $pat = shift; $pat = "%s\t%s" if ! defined $pat;
2874 my $sep = shift; $sep = "\n" if ! defined $sep;
2876 return ! @_ ? join($sep, map {sprintf $pat, $_, $ref->{$_}} sort keys %$ref)
2877 : @_ == 1 ? join($sep, map {sprintf $pat, $_[0], $_, $ref->{$_}} sort keys %$ref) # don't get to pick - it applies to the key
2878 : join($sep, map {sprintf $pat, $_[0], $_, $_[1], $ref->{$_}} sort keys %$ref);
2883 my $size = shift || 1;
2885 if ($size < 0) { # chunk from the opposite end
2886 $str = reverse $str;
2888 unshift(@list, scalar reverse $1) while $str =~ /( .{$size} | .+ )/xg;
2890 push(@list, $1) while $str =~ /( .{$size} | .+ )/xg;
2895 sub vmethod_indent
{
2896 my $str = shift; $str = '' if ! defined $str;
2897 my $pre = shift; $pre = 4 if ! defined $pre;
2898 $pre = ' ' x
$pre if $pre =~ /^\d+$/;
2899 $str =~ s/^/$pre/mg;
2903 sub vmethod_format
{
2904 my $str = shift; $str = '' if ! defined $str;
2905 my $pat = shift; $pat = '%s' if ! defined $pat;
2907 return join "\n", map{ sprintf $pat, $_[0], $_ } split(/\n/, $str);
2909 return join "\n", map{ sprintf $pat, $_ } split(/\n/, $str);
2914 my ($str, $pat, $global) = @_;
2915 return [] if ! defined $str || ! defined $pat;
2916 my @res = $global ? ($str =~ /$pat/g) : ($str =~ /$pat/);
2917 return (@res >= 2) ? \
@res : (@res == 1) ? $res[0] : '';
2921 my ($list, $field) = @_;
2922 return defined($field)
2923 ? [map {$_->[0]} sort {$a->[1] <=> $b->[1]} map {[$_, (ref $_ eq 'HASH' ? $_->{$field}
2924 : UNIVERSAL
::can
($_, $field) ? $_->$field()
2926 : [sort {$a <=> $b} @$list];
2929 sub vmethod_repeat
{
2930 my ($str, $n, $join) = @_;
2931 return if ! length $str;
2932 $n = 1 if ! defined($n) || ! length $n;
2933 $join = '' if ! defined $join;
2934 return join $join, ($str) x
$n;
2937 ### This method is a combination of my submissions along
2938 ### with work from Andy Wardley, Sergey Martynoff, Nik Clayton, and Josh Rosenbaum
2939 sub vmethod_replace
{
2940 my ($text, $pattern, $replace, $global) = @_;
2941 $text = '' unless defined $text;
2942 $pattern = '' unless defined $pattern;
2943 $replace = '' unless defined $replace;
2944 $global = 1 unless defined $global;
2946 my ($chunk, $start, $end) = @_;
2947 $chunk =~ s
{ \\(\\|\
$) | \
$ (\d
+) }{
2949 : ($2 > $#$start || $2 == 0) ? ''
2950 : substr($text, $start->[$2], $end->[$2] - $start->[$2]);
2955 $text =~ s{$pattern}{ $expand->($replace, [@-], [@+]) }eg;
2957 $text =~ s{$pattern}{ $expand->($replace, [@-], [@+]) }e;
2963 my ($list, $field) = @_;
2964 return defined($field)
2965 ? [map {$_->[0]} sort {$a->[1] cmp $b->[1]} map {[$_, lc(ref $_ eq 'HASH' ? $_->{$field}
2966 : UNIVERSAL
::can
($_, $field) ? $_->$field()
2968 : [map {$_->[0]} sort {$a->[1] cmp $b->[1]} map {[$_, lc $_]} @$list ]; # case insensitive
2971 sub vmethod_splice
{
2972 my ($ref, $i, $len, @replace) = @_;
2973 @replace = @{ $replace[0] } if @replace == 1 && ref $replace[0] eq 'ARRAY';
2975 return [splice @$ref, $i || 0, $len, @replace];
2977 return [splice @$ref, $i || 0];
2982 my ($str, $pat, @args) = @_;
2983 $str = '' if ! defined $str;
2984 return defined $pat ? [split $pat, $str, @args] : [split ' ', $str, @args];
2989 utf8
::encode
($str) if defined &utf8
::encode
;
2990 $str =~ s/([^A-Za-z0-9\-_.!~*\'()])/sprintf('%%%02X', ord($1))/eg;
2995 my $context = shift;
2998 return $context->process(\
$text);
3002 sub filter_redirect
{
3003 my ($context, $file, $options) = @_;
3004 my $path = $context->config->{'OUTPUT_PATH'} || $context->throw('redirect', 'OUTPUT_PATH is not set');
3005 $context->throw('redirect', 'Invalid filename - cannot include "/../"')
3006 if $file =~ m{(^|/)\.\./};
3012 File
::Path
::mkpath
($path) || $context->throw('redirect', "Couldn't mkpath \"$path\": $!");
3015 open (FH
, ">$path/$file") || $context->throw('redirect', "Couldn't open \"$file\": $!");
3016 if (my $bm = (! $options) ? 0 : ref($options) ? $options->{'binmode'} : $options) {
3017 if (+$bm == 1) { binmode FH
}
3018 else { binmode FH
, $bm}
3026 ###----------------------------------------------------------------###
3029 my $obj = UNIVERSAL
::isa
($_[0], __PACKAGE__
) ? shift : __PACKAGE__-
>new;
3031 require Data
::Dumper
;
3032 return Data
::Dumper
::Dumper
($obj->parse_tree(\
$str));
3035 sub dump_parse_expr
{
3036 my $obj = UNIVERSAL
::isa
($_[0], __PACKAGE__
) ? shift : __PACKAGE__-
>new;
3038 require Data
::Dumper
;
3039 return Data
::Dumper
::Dumper
($obj->parse_expr(\
$str));
3042 ###----------------------------------------------------------------###
3044 package CGI
::Ex
::Template
::Exception
;
3047 '""' => \
&as_string
,
3048 bool
=> sub { defined shift },
3052 my ($class, $type, $info, $node, $pos, $str_ref) = @_;
3053 return bless [$type, $info, $node, $pos, $str_ref], $class;
3056 sub type
{ shift-
>[0] }
3058 sub info
{ shift-
>[1] }
3062 $self->[2] = shift if $#_ == 0;
3066 sub offset
{ shift-
>[3] || 0 }
3070 $self->[4] = shift if $#_ == 0;
3076 my $msg = $self->type .' error - '. $self->info;
3077 if (my $node = $self->node) {
3078 # $msg .= " (In tag $node->[0] starting at char ".($node->[1] + $self->offset).")";
3083 ###----------------------------------------------------------------###
3085 package CGI
::Ex
::Template
::Iterator
;
3088 my ($class, $items) = @_;
3089 $items = [] if ! defined $items;
3090 if (UNIVERSAL
::isa
($items, 'HASH')) {
3091 $items = [ map { {key
=> $_, value
=> $items->{ $_ }} } sort keys %$items ];
3092 } elsif (UNIVERSAL
::can
($items, 'as_list')) {
3093 $items = $items->as_list;
3094 } elsif (! UNIVERSAL
::isa
($items, 'ARRAY')) {
3097 return bless [$items, 0], $class;
3102 return (undef, 3) if ! @{ $self->[0] };
3103 return ($self->[0]->[$self->[1] = 0], undef);
3108 return (undef, 3) if ++ $self->[1] > $#{ $self->[0] };
3109 return ($self->items->[$self->[1]], undef);
3112 sub items
{ shift-
>[0] }
3114 sub index { shift-
>[1] }
3116 sub max
{ $#{ shift-
>[0] } }
3118 sub size
{ shift-
>max + 1 }
3120 sub count
{ shift-
>index + 1 }
3122 sub number
{ shift-
>index + 1 }
3124 sub first
{ (shift-
>index == 0) || 0 }
3126 sub last { my $self = shift; return ($self->index == $self->max) || 0 }
3130 return undef if $self->index <= 0;
3131 return $self->items->[$self->index - 1];
3136 return undef if $self->index >= $self->max;
3137 return $self->items->[$self->index + 1];
3140 ###----------------------------------------------------------------###
3142 package CGI
::Ex
::Template
::_Context
;
3144 use vars
qw($AUTOLOAD);
3146 sub _template
{ shift-
>{'_template'} || die "Missing _template" }
3148 sub config
{ shift-
>_template }
3152 return $self->{'stash'} ||= bless {_template
=> $self->_template}, $CGI::Ex
::Template
::PACKAGE_STASH
;
3155 sub insert
{ shift-
>_template->_insert(@_) }
3157 sub eval_perl
{ shift-
>_template->{'EVAL_PERL'} }
3162 my $vars = $self->_template->_vars;
3164 $self->_template->_process($ref, $vars, \
$out);
3171 my $args = shift || {};
3173 $self->_template->set_variable($_, $args->{$_}) for keys %$args;
3175 my $out = ''; # have temp item to allow clear to correctly clear
3176 eval { $self->_template->_process($file, $self->{'_vars'}, \
$out) };
3178 die $err if ref($err) !~ /Template::Exception$/ || $err->type !~ /return/;
3185 my ($self, $name, $filter, $is_dynamic) = @_;
3186 $filter = [ $filter, 1 ] if $is_dynamic;
3187 $self->define_vmethod('filter', $name, $filter);
3191 my ($self, $name, $args, $alias) = @_;
3192 my $t = $self->_template;
3196 $filter = $t->{'FILTERS'}->{$name} || $CGI::Ex
::Template
::FILTER_OPS-
>{$name} || $CGI::Ex
::Template
::SCALAR_OPS-
>{$name};
3197 $t->throw('filter', $name) if ! $filter;
3198 } elsif (UNIVERSAL
::isa
($name, 'CODE') || UNIVERSAL
::isa
($name, 'ARRAY')) {
3200 } elsif (UNIVERSAL
::can
($name, 'factory')) {
3201 $filter = $name->factory || $t->throw($name->error);
3203 $t->throw('undef', "$name: filter not found");
3206 if (UNIVERSAL
::isa
($filter, 'ARRAY')) {
3207 $filter = ($filter->[1]) ? $filter->[0]->($t->context, @$args) : $filter->[0];
3208 } elsif ($args && @$args) {
3210 $filter = sub { $sub->(shift, @$args) };
3213 $t->{'FILTERS'}->{$alias} = $filter if $alias;
3218 sub define_vmethod
{ shift-
>_template->define_vmethod(@_) }
3221 my ($self, $type, $info) = @_;
3223 if (UNIVERSAL
::isa
($type, $CGI::Ex
::Template
::PACKAGE_EXCEPTION
)) {
3225 } elsif (defined $info) {
3226 $self->_template->throw($type, $info);
3228 $self->_template->throw('undef', $type);
3232 sub AUTOLOAD
{ shift-
>_template->throw('not_implemented', "The method $AUTOLOAD has not been implemented") }
3236 ###----------------------------------------------------------------###
3238 package CGI
::Ex
::Template
::_Stash
;
3240 use vars
qw($AUTOLOAD);
3242 sub _template
{ shift-
>{'_template'} || die "Missing _template" }
3245 my ($self, $var) = @_;
3247 if ($var =~ /^\w+$/) { $var = [$var, 0] }
3248 else { $var = $self->_template->parse_expr(\
$var, {no_dots
=> 1}) }
3250 return $self->_template->play_expr($var, {no_dots
=> 1});
3254 my ($self, $var, $val) = @_;
3256 if ($var =~ /^\w+$/) { $var = [$var, 0] }
3257 else { $var = $self->_template->parse_expr(\
$var, {no_dots
=> 1}) }
3259 $self->_template->set_variable($var, $val, {no_dots
=> 1});
3263 sub AUTOLOAD
{ shift-
>_template->throw('not_implemented', "The method $AUTOLOAD has not been implemented") }
3267 ###----------------------------------------------------------------###
3269 package CGI
::Ex
::Template
::EvalPerlHandle
;
3272 my ($class, $out_ref) = @_;
3273 return bless [$out_ref], $class;
3278 ${ $self->[0] } .= $_ for grep {defined && length} @_;
3282 ###----------------------------------------------------------------###
3286 ### See the perldoc in CGI/Ex/Template.pod