1 package CGI
::Ex
::Template
;
3 ###----------------------------------------------------------------###
4 # See the perldoc in CGI/Ex/Template.pod
5 # Copyright 2006 - Paul Seamons #
6 # Distributed under the Perl Artistic License without warranty #
7 ###----------------------------------------------------------------###
10 use constant trace
=> $ENV{'CET_TRACE'} || 0; # enable for low level tracing
13 $SCALAR_OPS $HASH_OPS $LIST_OPS $FILTER_OPS $VOBJS
14 $DIRECTIVES $QR_DIRECTIVE
35 $PACKAGE_EXCEPTION $PACKAGE_ITERATOR $PACKAGE_CONTEXT $PACKAGE_STASH $PACKAGE_PERL_HANDLE
44 $PACKAGE_EXCEPTION = 'CGI::Ex::Template::Exception';
45 $PACKAGE_ITERATOR = 'CGI::Ex::Template::Iterator';
46 $PACKAGE_CONTEXT = 'CGI::Ex::Template::_Context';
47 $PACKAGE_STASH = 'CGI::Ex::Template::_Stash';
48 $PACKAGE_PERL_HANDLE = 'CGI::Ex::Template::EvalPerlHandle';
51 default => ['[%', '%]'], # default
52 template
=> ['[%', '%]'], # default
53 metatext
=> ['%%', '%%'], # Text::MetaText
54 star
=> ['[*', '*]'], # TT alternate
55 php
=> ['<?', '?>'], # PHP
56 asp
=> ['<%', '%>'], # ASP
57 mason
=> ['<%', '>' ], # HTML::Mason
58 html
=> ['<!--', '-->'], # HTML comments
63 as
=> \
&vmethod_as_scalar
,
64 chunk
=> \
&vmethod_chunk
,
65 collapse
=> sub { local $_ = $_[0]; s/^\s+//; s/\s+$//; s/\s+/ /g; $_ },
67 indent
=> \
&vmethod_indent
,
68 int => sub { local $^W; int $_[0] },
69 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 my $info = $self->node_info($node);
1685 $out = Data
::Dumper
::Dumper
($self->play_expr($ident));
1686 $var = $info->{'text'};
1687 $var =~ s/^[+\-~=]?\s*DUMP\s+//;
1688 $var =~ s/\s*[+\-~=]?$//;
1690 my @were_never_here = (qw(template component), grep {$_ =~ $QR_PRIVATE} keys %{ $self->{'_vars'} });
1691 local @{ $self->{'_vars'} }{ @were_never_here };
1692 delete @{ $self->{'_vars'} }{ @were_never_here };
1693 $out = Data
::Dumper
::Dumper
($self->{'_vars'});
1694 $var = 'EntireStash';
1696 if ($ENV{'REQUEST_METHOD'}) {
1698 $out = "<pre>$out</pre>";
1699 $out =~ s/\$VAR1/$var/;
1700 $out = "<b>DUMP: File \"$info->{file}\" line $info->{line}</b>$out";
1702 $out =~ s/\$VAR1/$var/;
1709 my ($self, $tag_ref) = @_;
1711 if ($$tag_ref =~ s{ ^ ([^\W\d]\w*) \s* = \s* }{}x) {
1715 my $filter = $self->parse_expr($tag_ref);
1716 $filter = '' if ! defined $filter;
1718 return [$name, $filter];
1722 my ($self, $ref, $node, $out_ref) = @_;
1723 my ($name, $filter) = @$ref;
1725 return '' if ! @$filter;
1727 $self->{'FILTERS'}->{$name} = $filter if length $name;
1729 my $sub_tree = $node->[4];
1733 eval { $self->execute_tree($sub_tree, \
$out) };
1734 die $@ if $@ && ref($@) !~ /Template::Exception$/;
1736 my $var = [\
$out, 0, '|', @$filter]; # make a temporary var out of it
1739 return $DIRECTIVES->{'GET'}->[1]->($self, $var, $node, $out_ref);
1743 my ($self, $tag_ref) = @_;
1744 my $items = $self->parse_expr($tag_ref);
1746 if ($$tag_ref =~ s{ ^ (= | [Ii][Nn]\b) \s* }{}x) {
1748 $items = $self->parse_expr($tag_ref);
1750 return [$var, $items];
1754 my ($self, $ref, $node, $out_ref) = @_;
1756 ### get the items - make sure it is an arrayref
1757 my ($var, $items) = @$ref;
1759 $items = $self->play_expr($items);
1760 return '' if ! defined $items;
1762 if (ref($items) !~ /Iterator$/) {
1763 $items = $PACKAGE_ITERATOR->new($items);
1766 my $sub_tree = $node->[4];
1768 local $self->{'_vars'}->{'loop'} = $items;
1770 ### if the FOREACH tag sets a var - then nothing but the loop var gets localized
1772 my ($item, $error) = $items->get_first;
1775 $self->set_variable($var, $item);
1777 ### execute the sub tree
1778 eval { $self->execute_tree($sub_tree, $out_ref) };
1780 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
1781 if ($err->type eq 'next') {
1782 ($item, $error) = $items->get_next;
1785 last if $err->type =~ /last|break/;
1790 ($item, $error) = $items->get_next;
1792 die $error if $error && $error != 3; # Template::Constants::STATUS_DONE;
1793 ### if the FOREACH tag doesn't set a var - then everything gets localized
1796 ### localize variable access for the foreach
1797 my $swap = $self->{'_vars'};
1798 local $self->{'_vars'} = my $copy = {%$swap};
1800 ### iterate use the iterator object
1801 #foreach (my $i = $items->index; $i <= $#$vals; $items->index(++ $i)) {
1802 my ($item, $error) = $items->get_first;
1805 if (ref($item) eq 'HASH') {
1806 @$copy{keys %$item} = values %$item;
1809 ### execute the sub tree
1810 eval { $self->execute_tree($sub_tree, $out_ref) };
1812 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
1813 if ($err->type eq 'next') {
1814 ($item, $error) = $items->get_next;
1817 last if $err->type =~ /last|break/;
1822 ($item, $error) = $items->get_next;
1824 die $error if $error && $error != 3; # Template::Constants::STATUS_DONE;
1831 my ($self, $tag_ref) = @_;
1832 my $ref = $self->parse_expr($tag_ref);
1833 $self->throw('parse', "Missing variable name") if ! defined $ref;
1838 my ($self, $ident, $node) = @_;
1839 my $var = $self->play_expr($ident);
1840 return (! defined $var) ? $self->undefined_get($ident, $node) : $var;
1844 my ($self, $tag_ref) = @_;
1845 return $self->parse_expr($tag_ref);
1849 my ($self, $var, $node, $out_ref) = @_;
1851 my $val = $self->play_expr($var);
1853 my $body_ref = $node->[4] ||= [];
1854 $self->execute_tree($body_ref, $out_ref);
1858 while ($node = $node->[5]) { # ELSE, ELSIF's
1859 if ($node->[0] eq 'ELSE') {
1860 my $body_ref = $node->[4] ||= [];
1861 $self->execute_tree($body_ref, $out_ref);
1864 my $var = $node->[3];
1865 my $val = $self->play_expr($var);
1867 my $body_ref = $node->[4] ||= [];
1868 $self->execute_tree($body_ref, $out_ref);
1875 sub parse_INCLUDE
{ $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
1878 my ($self, $tag_ref, $node, $out_ref) = @_;
1880 ### localize the swap
1881 my $swap = $self->{'_vars'};
1882 local $self->{'_vars'} = {%$swap};
1884 ### localize the blocks
1885 my $blocks = $self->{'BLOCKS'};
1886 local $self->{'BLOCKS'} = {%$blocks};
1888 my $str = $DIRECTIVES->{'PROCESS'}->[1]->($self, $tag_ref, $node, $out_ref);
1893 sub parse_INSERT
{ $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
1896 my ($self, $var, $node, $out_ref) = @_;
1897 my ($names, $args) = @$var;
1899 foreach my $name (@$names) {
1900 my $filename = $self->play_expr($name);
1901 $$out_ref .= $self->_insert($filename);
1908 my ($self, $tag_ref, $node) = @_;
1909 my $copy = $$tag_ref;
1911 my $name = $self->parse_expr(\
$copy, {auto_quote
=> qr{ ^ (\w+) $QR_AQ_NOTDOT }xo});
1912 $self->throw('parse', "Missing macro name") if ! defined $name;
1914 $name = [ $name, 0 ];
1918 if ($copy =~ s{ ^ \( \s* }{}x) {
1919 $args = $self->parse_args(\
$copy, {positional_only
=> 1});
1920 $copy =~ s
{ ^ \
) \s
* }{}x
|| $self->throw('parse.missing', "Missing close ')'");
1923 $node->[6] = 1; # set a flag to keep parsing
1925 return [$name, $args];
1929 my ($self, $ref, $node, $out_ref) = @_;
1930 my ($name, $args) = @$ref;
1932 ### get the sub tree
1933 my $sub_tree = $node->[4];
1934 if (! $sub_tree || ! $sub_tree->[0]) {
1935 $self->set_variable($name, undef);
1937 } elsif ($sub_tree->[0]->[0] eq 'BLOCK') {
1938 $sub_tree = $sub_tree->[0]->[4];
1941 my $self_copy = $self;
1942 eval {require Scalar
::Util
; Scalar
::Util
::weaken
($self_copy)};
1944 ### install a closure in the stash that will handle the macro
1945 $self->set_variable($name, sub {
1947 my $copy = $self_copy->{'_vars'};
1948 local $self_copy->{'_vars'}= {%$copy};
1951 my $named = pop(@_) if $_[-1] && UNIVERSAL
::isa
($_[-1],'HASH') && $#_ > $#$args;
1952 my @positional = @_;
1953 foreach my $var (@$args) {
1954 $self_copy->set_variable($var, shift(@positional));
1956 foreach my $name (sort keys %$named) {
1957 $self_copy->set_variable([$name, 0], $named->{$name});
1960 ### finally - run the sub tree
1962 $self_copy->execute_tree($sub_tree, \
$out);
1970 my ($self, $hash) = @_;
1972 if ($self->{'_top_level'}) {
1973 $ref = $self->{'_vars'}->{'template'} ||= {};
1975 $ref = $self->{'_vars'}->{'component'} ||= {};
1977 foreach my $key (keys %$hash) {
1978 next if $key eq 'name' || $key eq 'modtime';
1979 $ref->{$key} = $hash->{$key};
1984 sub parse_PERL
{ shift-
>{'_in_perl'} = 1; return }
1987 my ($self, $info, $node, $out_ref) = @_;
1988 $self->throw('perl', 'EVAL_PERL not set') if ! $self->{'EVAL_PERL'};
1990 ### fill in any variables
1991 my $perl = $node->[4] || return;
1993 $self->execute_tree($perl, \
$out);
1994 $out = $1 if $out =~ /^(.+)$/s; # blatant untaint - shouldn't use perl anyway
1999 package CGI
::Ex
::Template
::Perl
;
2001 my $context = $self->context;
2002 my $stash = $context->stash;
2004 ### setup a fake handle
2006 tie
*PERLOUT
, $CGI::Ex
::Template
::PACKAGE_PERL_HANDLE
, $out_ref;
2007 my $old_fh = select PERLOUT
;
2012 ### put the handle back
2020 $self->throw('undef', $err) if ref($err) !~ /Template::Exception$/;
2028 my ($self, $tag_ref) = @_;
2029 my $info = [[], []];
2030 while (defined(my $filename = $self->parse_expr($tag_ref, {
2031 auto_quote
=> qr{ ^ ($QR_FILENAME | \w+ (?: :\w+)* ) $QR_AQ_SPACE }xo,
2033 push @{$info->[0]}, $filename;
2034 last if $$tag_ref !~ s{ ^ \+ \s* }{}x;
2037 ### allow for post process variables
2038 while (length $$tag_ref) {
2039 last if $$tag_ref =~ / ^ (\w+) (?: ;|$|\s)/x && $DIRECTIVES->{$1}; ### looks like a directive - we are done
2041 my $var = $self->parse_expr($tag_ref);
2042 last if ! defined $var;
2043 if ($$tag_ref !~ s{ ^ = >? \s* }{}x) {
2044 $self->throw('parse.missing.equals', 'Missing equals while parsing args');
2047 my $val = $self->parse_expr($tag_ref);
2048 push @{$info->[1]}, [$var, $val];
2049 $$tag_ref =~ s{ ^ , \s* $QR_COMMENTS }{}ox if $val;
2056 my ($self, $info, $node, $out_ref) = @_;
2058 my ($files, $args) = @$info;
2062 my ($key, $val) = @$_;
2063 $val = $self->play_expr($val);
2064 if (ref($key) && @$key == 2 && $key->[0] eq 'import' && UNIVERSAL
::isa
($val, 'HASH')) { # import ?! - whatever
2065 foreach my $key (keys %$val) {
2066 $self->set_variable([$key,0], $val->{$key});
2070 $self->set_variable($key, $val);
2073 ### iterate on any passed block or filename
2074 foreach my $ref (@$files) {
2075 next if ! defined $ref;
2076 my $filename = $self->play_expr($ref);
2077 my $out = ''; # have temp item to allow clear to correctly clear
2079 ### normal blocks or filenames
2080 if (! ref $filename) {
2081 eval { $self->_process($filename, $self->{'_vars'}, \
$out) }; # restart the swap - passing it our current stash
2083 ### allow for $template which is used in some odd instances
2085 $self->throw('process', "Unable to process document $filename") if $ref->[0] ne 'template';
2086 $self->throw('process', "Recursion detected in $node->[0] \$template") if $self->{'_process_dollar_template'};
2087 local $self->{'_process_dollar_template'} = 1;
2088 local $self->{'_vars'}->{'component'} = my $doc = $filename;
2089 return if ! $doc->{'_tree'};
2091 ### execute and trim
2092 eval { $self->execute_tree($doc->{'_tree'}, \
$out) };
2093 if ($self->{'TRIM'}) {
2094 $out =~ s{ \s+ $ }{}x;
2095 $out =~ s{ ^ \s+ }{}x;
2098 ### handle exceptions
2100 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2101 $err->doc($doc) if $doc && $err->can('doc') && ! $err->doc;
2106 ### append any output
2109 die $err if ref($err) !~ /Template::Exception$/ || $err->type !~ /return/;
2117 my ($self, $info, $node, $out_ref) = @_;
2118 $self->throw('perl', 'EVAL_PERL not set') if ! $self->{'EVAL_PERL'};
2120 ### fill in any variables
2121 my $tree = $node->[4] || return;
2123 $self->execute_tree($tree, \
$perl);
2124 $perl = $1 if $perl =~ /^(.+)$/s; # blatant untaint - shouldn't use perl anyway
2130 package CGI
::Ex
::Template
::Perl
;
2132 my $context = $self->context;
2133 my $stash = $context->stash;
2140 $$out_ref .= $output;
2143 $self->throw('undef', $err) if ref($err) !~ /Template::Exception$/;
2151 my ($self, $tag_ref, $node, $initial_op, $initial_var) = @_;
2153 my $copy = $$tag_ref;
2157 if ($$tag_ref =~ $QR_DIRECTIVE # find a word
2158 && $DIRECTIVES->{$1}) { # is it a directive - if so set up capturing
2159 $node->[6] = 1; # set a flag to keep parsing
2160 my $val = $node->[4] ||= []; # setup storage
2161 return [[$initial_op, $initial_var, $val]];
2162 } else { # get a normal variable
2163 return [[$initial_op, $initial_var, $self->parse_expr($tag_ref)]];
2167 while (length $$tag_ref) {
2168 my $set = $self->parse_expr($tag_ref);
2169 last if ! defined $set;
2171 if ($$tag_ref =~ s{ ^ ($QR_OP_ASSIGN) >? \s* }{}x) {
2173 if ($$tag_ref =~ $QR_DIRECTIVE # find a word
2174 && $DIRECTIVES->{$1}) { # is it a directive - if so set up capturing
2175 $node->[6] = 1; # set a flag to keep parsing
2176 my $val = $node->[4] ||= []; # setup storage
2177 push @SET, [$op, $set, $val];
2179 } else { # get a normal variable
2180 push @SET, [$op, $set, $self->parse_expr($tag_ref)];
2183 push @SET, ['=', $set, undef];
2190 my ($self, $set, $node) = @_;
2192 my ($op, $set, $val) = @$_;
2193 if (! defined $val) { # not defined
2195 } elsif ($node->[4] && $val == $node->[4]) { # a captured directive
2196 my $sub_tree = $node->[4];
2197 $sub_tree = $sub_tree->[0]->[4] if $sub_tree->[0] && $sub_tree->[0]->[0] eq 'BLOCK';
2199 $self->execute_tree($sub_tree, \
$val);
2200 } else { # normal var
2201 $val = $self->play_expr($val);
2204 if ($OP_DISPATCH->{$op}) {
2206 $val = $OP_DISPATCH->{$op}->($self->play_expr($set), $val);
2209 $self->set_variable($set, $val);
2214 sub parse_SWITCH
{ $DIRECTIVES->{'GET'}->[0]->(@_) }
2217 my ($self, $var, $node, $out_ref) = @_;
2219 my $val = $self->play_expr($var);
2220 $val = '' if ! defined $val;
2221 ### $node->[4] is thrown away
2224 while ($node = $node->[5]) { # CASES
2225 my $var = $node->[3];
2226 if (! defined $var) {
2227 $default = $node->[4];
2231 my $val2 = $self->play_expr($var);
2232 $val2 = [$val2] if ! UNIVERSAL
::isa
($val2, 'ARRAY');
2233 for my $test (@$val2) { # find matching values
2234 next if ! defined $val && defined $test;
2235 next if defined $val && ! defined $test;
2236 if ($val ne $test) { # check string-wise first - then numerical
2237 next if $val !~ m{ ^ -? $QR_NUM $ }ox;
2238 next if $test !~ m{ ^ -? $QR_NUM $ }ox;
2239 next if $val != $test;
2242 my $body_ref = $node->[4] ||= [];
2243 $self->execute_tree($body_ref, $out_ref);
2249 $self->execute_tree($default, $out_ref);
2256 my ($self, $tag_ref, $node) = @_;
2257 my $name = $self->parse_expr($tag_ref, {auto_quote
=> qr{ ^ (\w+ (?: \.\w+)*) $QR_AQ_SPACE }xo});
2258 $self->throw('parse.missing', "Missing name in THROW", $node) if ! $name;
2259 my $args = $self->parse_args($tag_ref);
2260 return [$name, $args];
2264 my ($self, $ref, $node) = @_;
2265 my ($name, $args) = @$ref;
2266 $name = $self->play_expr($name);
2267 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2268 $self->throw($name, \
@args, $node);
2272 my ($self, $foo, $node, $out_ref) = @_;
2275 my $body_ref = $node->[4];
2276 eval { $self->execute_tree($body_ref, \
$out) };
2279 if (! $node->[5]) { # no catch or final
2280 if (! $err) { # no final block and no error
2284 $self->throw('parse.missing', "Missing CATCH block", $node);
2287 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2288 if ($err->type =~ /stop|return/) {
2294 ### loop through the nested catch and final blocks
2297 my $type = $err ? $err->type : '';
2299 while ($node = $node->[5]) { # CATCH
2300 if ($node->[0] eq 'FINAL') {
2301 $final = $node->[4];
2305 my $name = $self->play_expr($node->[3]);
2306 $name = '' if ! defined $name || lc($name) eq 'default';
2307 if ($type =~ / ^ \Q$name\E \b /x
2308 && (! defined($last_found) || length($last_found) < length($name))) { # more specific wins
2309 $catch_body_ref = $node->[4] || [];
2310 $last_found = $name;
2314 ### play the best catch block
2316 if (! $catch_body_ref) {
2320 local $self->{'_vars'}->{'error'} = $err;
2321 local $self->{'_vars'}->{'e'} = $err;
2322 eval { $self->execute_tree($catch_body_ref, \
$out) };
2330 $self->execute_tree($final, \
$out) if $final;
2338 my $ref = $DIRECTIVES->{'IF'}->[0]->(@_);
2339 return [ \
[ '!', $ref ], 0 ];
2342 sub play_UNLESS
{ return $DIRECTIVES->{'IF'}->[1]->(@_) }
2345 my ($self, $tag_ref) = @_;
2348 my $copy = $$tag_ref;
2349 if (defined(my $_var = $self->parse_expr(\
$copy, {auto_quote
=> qr{ ^ (\w+) $QR_AQ_NOTDOT }xo}))
2350 && $copy =~ s{ ^ = >? \s* $QR_COMMENTS }{}ox) {
2356 my $module = $self->parse_expr(\
$copy, {auto_quote
=> qr{ ^ (\w+ (?: (?:\.|::) \w+)*) $QR_AQ_NOTDOT }xo});
2357 $self->throw('parse', "Missing plugin name while parsing $$tag_ref") if ! defined $module;
2358 $module =~ s/\./::/g;
2361 my $open = $copy =~ s{ ^ \( \s* $QR_COMMENTS }{}ox;
2362 $args = $self->parse_args(\
$copy);
2365 $copy =~ s
{ ^ \
) \s
* $QR_COMMENTS }{}ox
|| $self->throw('parse.missing', "Missing close ')'");
2369 return [$var, $module, $args];
2373 my ($self, $ref, $node, $out_ref) = @_;
2374 my ($var, $module, $args) = @$ref;
2376 ### get the stash storage location - default to the module
2377 $var = $module if ! defined $var;
2378 my @var = map {($_, 0, '.')} split /(?:\.|::)/, $var;
2379 pop @var; # remove the trailing '.'
2381 ### look for a plugin_base
2382 my $base = $self->{'PLUGIN_BASE'} || 'Template::Plugin'; # I'm not maintaining plugins - leave that to TT
2383 my $package = $self->{'PLUGINS'}->{$module} ? $self->{'PLUGINS'}->{$module}
2384 : $self->{'PLUGIN_FACTORY'}->{$module} ? $self->{'PLUGIN_FACTORY'}->{$module}
2385 : "${base}::${module}";
2386 my $require = "$package.pm";
2387 $require =~ s
|::|/|g
;
2389 ### try and load the module - fall back to bare module if allowed
2391 if ($self->{'PLUGIN_FACTORY'}->{$module} || eval {require $require}) {
2392 my $shape = $package->load;
2393 my $context = $self->context;
2394 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2395 $obj = $shape->new($context, @args);
2396 } elsif (lc($module) eq 'iterator') { # use our iterator if none found (TT's works just fine)
2397 $obj = $PACKAGE_ITERATOR->new($args ? $self->play_expr($args->[0]) : []);
2398 } elsif (my @packages = grep {lc($package) eq lc($_)} @{ $self->list_plugins({base
=> $base}) }) {
2399 foreach my $package (@packages) {
2400 my $require = "$package.pm";
2401 $require =~ s
|::|/|g
;
2402 eval {require $require} || next;
2403 my $shape = $package->load;
2404 my $context = $self->context;
2405 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2406 $obj = $shape->new($context, @args);
2408 } elsif ($self->{'LOAD_PERL'}) {
2409 my $require = "$module.pm";
2410 $require =~ s
|::|/|g
;
2411 if (eval {require $require}) {
2412 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2413 $obj = $module->new(@args);
2416 if (! defined $obj) {
2417 my $err = "$module: plugin not found";
2418 $self->throw('plugin', $err);
2422 $self->set_variable(\
@var, $obj);
2428 my ($self, $var, $node, $out_ref) = @_;
2429 return '' if ! defined $var;
2431 my $sub_tree = $node->[4];
2433 ### iterate use the iterator object
2434 my $count = $WHILE_MAX;
2435 while (--$count > 0) {
2437 $self->play_expr($var) || last;
2439 ### execute the sub tree
2440 eval { $self->execute_tree($sub_tree, $out_ref) };
2442 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
2443 next if $err->type =~ /next/;
2444 last if $err->type =~ /last|break/;
2449 die "WHILE loop terminated (> $WHILE_MAX iterations)\n" if ! $count;
2454 sub parse_WRAPPER
{ $DIRECTIVES->{'INCLUDE'}->[0]->(@_) }
2457 my ($self, $var, $node, $out_ref) = @_;
2458 my $sub_tree = $node->[4] || return;
2460 my ($names, $args) = @$var;
2463 $self->execute_tree($sub_tree, \
$out);
2465 foreach my $name (reverse @$names) {
2466 local $self->{'_vars'}->{'content'} = $out;
2468 $DIRECTIVES->{'INCLUDE'}->[1]->($self, [[$name], $args], $node, \
$out);
2475 ###----------------------------------------------------------------###
2479 $self->{'_vars'} = shift if $#_ == 0;
2480 return $self->{'_vars'} ||= {};
2483 sub include_filename
{
2484 my ($self, $file) = @_;
2485 if ($file =~ m
|^/|) {
2486 $self->throw('file', "$file absolute paths are not allowed (set ABSOLUTE option)") if ! $self->{'ABSOLUTE'};
2487 return $file if -e
$file;
2488 } elsif ($file =~ m{(^|/)\.\./}) {
2489 $self->throw('file', "$file relative paths are not allowed (set RELATIVE option)") if ! $self->{'RELATIVE'};
2490 return $file if -e
$file;
2493 my $paths = $self->{'INCLUDE_PATHS'} ||= do {
2494 # TT does this everytime a file is looked up - we are going to do it just in time - the first time
2495 my $paths = $self->{'INCLUDE_PATH'} || $self->throw('file', "INCLUDE_PATH not set");
2496 $paths = $paths->() if UNIVERSAL
::isa
($paths, 'CODE');
2497 $paths = $self->split_paths($paths) if ! UNIVERSAL
::isa
($paths, 'ARRAY');
2498 $paths; # return of the do
2500 foreach my $path (@$paths) {
2501 return "$path/$file" if -e
"$path/$file";
2504 $self->throw('file', "$file: not found");
2508 my ($self, $path) = @_;
2509 return $path if ref $path;
2510 my $delim = $self->{'DELIMITER'} || ':';
2511 $delim = ($delim eq ':' && $^O eq 'MSWin32') ? qr
|:(?!/)| : qr
|\Q
$delim\E
|;
2512 return [split $delim, $path];
2516 my ($self, $file) = @_;
2517 return $self->slurp($self->include_filename($file));
2521 my ($self, $file) = @_;
2523 open(FH
, "<$file") || $self->throw('file', "$file couldn't be opened: $!");
2524 read FH
, my $txt, -s
$file;
2529 sub process_simple
{
2531 my $in = shift || die "Missing input";
2532 my $swap = shift || die "Missing variable hash";
2533 my $out = shift || die "Missing output string ref";
2536 delete $self->{'_debug_off'};
2537 delete $self->{'_debug_format'};
2538 local $self->{'_start_top_level'} = 1;
2539 $self->_process($in, $swap, $out);
2542 if ($err->type !~ /stop|return|next|last|break/) {
2543 $self->{'error'} = $err;
2551 my ($self, $in, $swap, $out, @ARGS) = @_;
2552 delete $self->{'error'};
2555 $args = ($#ARGS == 0 && UNIVERSAL
::isa
($ARGS[0], 'HASH')) ? {%{$ARGS[0]}} : {@ARGS} if scalar @ARGS;
2556 $self->DEBUG("set binmode\n") if $DEBUG && $args->{'binmode'}; # holdover for TT2 tests
2561 if (UNIVERSAL
::isa
($in, 'SCALAR')) { # reference to a string
2563 } elsif (UNIVERSAL
::isa
($in, 'CODE')) {
2565 $content = \
$content;
2566 } else { # should be a file handle
2569 $content = \
$content;
2572 ### should be a filename
2577 ### prepare block localization
2578 my $blocks = $self->{'BLOCKS'} ||= {};
2585 ### localize the stash
2587 my $var1 = $self->{'_vars'} ||= {};
2588 my $var2 = $self->{'VARIABLES'} || $self->{'PRE_DEFINE'} || {};
2589 $var1->{'global'} ||= {}; # allow for the "global" namespace - that continues in between processing
2590 my $copy = {%$var2, %$var1, %$swap};
2591 local $copy->{'template'};
2593 local $self->{'BLOCKS'} = $blocks = {%$blocks}; # localize blocks - but save a copy to possibly restore
2595 delete $self->{'_debug_off'};
2596 delete $self->{'_debug_format'};
2598 ### handle pre process items that go before every document
2599 if ($self->{'PRE_PROCESS'}) {
2600 foreach my $name (@{ $self->split_paths($self->{'PRE_PROCESS'}) }) {
2602 $self->_process($name, $copy, \
$out);
2603 $output = $out . $output;
2607 ### handle the process config - which loads a template in place of the real one
2608 if (exists $self->{'PROCESS'}) {
2609 ### load the meta data for the top document
2610 my $doc = $self->load_parsed_tree($content) || {};
2611 my $meta = ($doc->{'_tree'} && ref($doc->{'_tree'}->[0]) && $doc->{'_tree'}->[0]->[0] eq 'METADEF')
2612 ? $doc->{'_tree'}->[0]->[3] : {};
2614 $copy->{'template'} = $doc;
2615 @{ $doc }{keys %$meta} = values %$meta;
2617 ### process any other templates
2618 foreach my $name (@{ $self->split_paths($self->{'PROCESS'}) }) {
2619 next if ! length $name;
2620 $self->_process($name, $copy, \
$output);
2623 ### handle "normal" content
2625 local $self->{'_start_top_level'} = 1;
2626 $self->_process($content, $copy, \
$output);
2630 ### handle post process items that go after every document
2631 if ($self->{'POST_PROCESS'}) {
2632 foreach my $name (@{ $self->split_paths($self->{'POST_PROCESS'}) }) {
2633 $self->_process($name, $copy, \
$output);
2639 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2640 if ($err->type !~ /stop|return|next|last|break/) {
2641 $self->{'error'} = $err;
2648 ### clear blocks as asked (AUTO_RESET) defaults to on
2649 $self->{'BLOCKS'} = $blocks if exists($self->{'AUTO_RESET'}) && ! $self->{'AUTO_RESET'};
2651 ### send the content back out
2652 $out ||= $self->{'OUTPUT'};
2654 if (UNIVERSAL
::isa
($out, 'CODE')) {
2656 } elsif (UNIVERSAL
::can
($out, 'print')) {
2657 $out->print($output);
2658 } elsif (UNIVERSAL
::isa
($out, 'SCALAR')) { # reference to a string
2660 } elsif (UNIVERSAL
::isa
($out, 'ARRAY')) {
2661 push @$out, $output;
2662 } else { # should be a file handle
2665 } elsif ($out) { # should be a filename
2667 if ($out =~ m
|^/|) {
2668 if (! $self->{'ABSOLUTE'}) {
2669 $self->{'error'} = $self->throw('file', "ABSOLUTE paths disabled");
2673 } elsif ($out =~ m
|^\
.\
.?/|) {
2674 if (! $self->{'RELATIVE'}) {
2675 $self->{'error'} = $self->throw('file', "RELATIVE paths disabled");
2680 if (! $self->{'OUTPUT_PATH'}) {
2681 $self->{'error'} = $self->throw('file', "OUTPUT_PATH not set");
2683 $file = $self->{'OUTPUT_PATH'} . '/' . $out;
2688 if (open FH
, ">$file") {
2689 if (my $bm = $args->{'binmode'}) {
2690 if (+$bm == 1) { binmode FH
}
2691 else { binmode FH
, $bm }
2696 $self->{'error'} = $self->throw('file', "$out couldn't be opened for writing: $!");
2703 return if $self->{'error'};
2707 sub error
{ shift-
>{'error'} }
2711 print STDERR
"DEBUG: ", @_;
2714 ###----------------------------------------------------------------###
2717 my ($self, $type, $info, $node) = @_;
2718 return $type if ref($type) =~ /Template::Exception$/;
2719 if (ref($info) eq 'ARRAY') {
2720 my $hash = ref($info->[-1]) eq 'HASH' ? pop(@$info) : {};
2721 if (@$info >= 2 || scalar keys %$hash) {
2723 $hash->{$_} = $info->[$_] for 0 .. $#$info;
2724 $hash->{'args'} = $info;
2726 } elsif (@$info == 1) {
2733 return $PACKAGE_EXCEPTION->new($type, $info, $node);
2736 sub throw
{ die shift-
>exception(@_) }
2740 return bless {_template
=> $self}, $PACKAGE_CONTEXT; # a fake context
2744 my ($self, $ident, $node) = @_;
2745 return $self->{'UNDEFINED_GET'}->($self, $ident, $node) if $self->{'UNDEFINED_GET'};
2750 my ($self, $ident) = @_;
2751 return $self->{'UNDEFINED_ANY'}->($self, $ident) if $self->{'UNDEFINED_ANY'};
2757 return $self->{'_filters'} ||= eval { require Template
::Filters
; $Template::Filters
::FILTERS
} || {};
2762 my $args = shift || {};
2763 my $base = $args->{'base'} || '';
2765 return $self->{'_plugins'}->{$base} ||= do {
2769 my @dirs = grep {-d
$_} map {"$_/$base"} @INC;
2771 foreach my $dir (@dirs) {
2773 File
::Find
::find
(sub {
2774 my $mod = $base .'/'. ($File::Find
::name
=~ m
|^ $dir / (.*\w
) \
.pm
$|x
? $1 : return);
2776 push @plugins, $mod;
2780 \
@plugins; # return of the do
2785 my ($self, $node) = @_;
2786 my $info = $self->node_info($node);
2787 my $format = $self->{'_debug_format'} || $self->{'DEBUG_FORMAT'} || "\n## \$file line \$line : [% \$text %] ##\n";
2788 $format =~ s{\$(file|line|text)}{$info->{$1}}g
;
2793 my ($self, $node) = @_;
2794 my $doc = $self->{'_vars'}->{'component'};
2796 my $j = $node->[2] || return ''; # METADEF can be 0
2797 $doc->{'_content'} ||= do { my $s = $self->slurp($doc->{'_filename'}) ; \
$s };
2798 my $s = substr(${ $doc->{'_content'} }, $i, $j - $i);
2802 file
=> $doc->{'name'},
2803 line
=> $self->get_line_number_by_index($doc, $i),
2808 sub get_line_number_by_index
{
2809 my ($self, $doc, $index) = @_;
2810 ### get the line offsets for the doc
2811 my $lines = $doc->{'line_offsets'} ||= do {
2812 $doc->{'_content'} ||= do { my $s = $self->slurp($doc->{'_filename'}) ; \
$s };
2816 $i = index(${ $doc->{'_content'} }, "\n", $i) + 1;
2822 ### binary search them (this is fast even on big docs)
2823 return $#$lines + 1 if $index > $lines->[-1];
2824 my ($i, $j) = (0, $#$lines);
2826 return $i + 1 if abs($i - $j) <= 1;
2827 my $k = int(($i + $j) / 2);
2828 $j = $k if $lines->[$k] >= $index;
2829 $i = $k if $lines->[$k] <= $index;
2833 ###----------------------------------------------------------------###
2834 ### long virtual methods or filters
2835 ### many of these vmethods have used code from Template/Stash.pm to
2836 ### assure conformance with the TT spec.
2838 sub define_vmethod
{
2839 my ($self, $type, $name, $sub) = @_;
2840 if ( $type =~ /scalar|item/i) { $SCALAR_OPS->{$name} = $sub }
2841 elsif ($type =~ /array|list/i ) { $LIST_OPS->{ $name} = $sub }
2842 elsif ($type =~ /hash/i ) { $HASH_OPS->{ $name} = $sub }
2843 elsif ($type =~ /filter/i ) { $FILTER_OPS->{$name} = $sub }
2845 die "Invalid type vmethod type $type";
2850 sub vmethod_as_scalar
{
2851 my ($str, $pat) = @_;
2852 $pat = '%s' if ! defined $pat;
2854 return sprintf $pat, $str;
2857 sub vmethod_as_list
{
2858 my ($ref, $pat, $sep) = @_;
2859 $pat = '%s' if ! defined $pat;
2860 $sep = ' ' if ! defined $sep;
2862 return join($sep, map {sprintf $pat, $_} @$ref);
2865 sub vmethod_as_hash
{
2866 my ($ref, $pat, $sep) = @_;
2867 $pat = "%s\t%s" if ! defined $pat;
2868 $sep = "\n" if ! defined $sep;
2870 return join($sep, map {sprintf $pat, $_, $ref->{$_}} sort keys %$ref);
2875 my $size = shift || 1;
2877 if ($size < 0) { # chunk from the opposite end
2878 $str = reverse $str;
2880 unshift(@list, scalar reverse $1) while $str =~ /( .{$size} | .+ )/xg;
2882 push(@list, $1) while $str =~ /( .{$size} | .+ )/xg;
2887 sub vmethod_indent
{
2888 my $str = shift; $str = '' if ! defined $str;
2889 my $pre = shift; $pre = 4 if ! defined $pre;
2890 $pre = ' ' x
$pre if $pre =~ /^\d+$/;
2891 $str =~ s/^/$pre/mg;
2895 sub vmethod_format
{
2896 my $str = shift; $str = '' if ! defined $str;
2897 my $pat = shift; $pat = '%s' if ! defined $pat;
2898 return join "\n", map{ sprintf $pat, $_ } split(/\n/, $str);
2902 my ($str, $pat, $global) = @_;
2903 return [] if ! defined $str || ! defined $pat;
2904 my @res = $global ? ($str =~ /$pat/g) : ($str =~ /$pat/);
2905 return (@res >= 2) ? \
@res : (@res == 1) ? $res[0] : '';
2909 my ($list, $field) = @_;
2910 return defined($field)
2911 ? [map {$_->[0]} sort {$a->[1] <=> $b->[1]} map {[$_, (ref $_ eq 'HASH' ? $_->{$field}
2912 : UNIVERSAL
::can
($_, $field) ? $_->$field()
2914 : [sort {$a <=> $b} @$list];
2917 sub vmethod_repeat
{
2918 my ($str, $n, $join) = @_;
2919 return if ! length $str;
2920 $n = 1 if ! defined($n) || ! length $n;
2921 $join = '' if ! defined $join;
2922 return join $join, ($str) x
$n;
2925 ### This method is a combination of my submissions along
2926 ### with work from Andy Wardley, Sergey Martynoff, Nik Clayton, and Josh Rosenbaum
2927 sub vmethod_replace
{
2928 my ($text, $pattern, $replace, $global) = @_;
2929 $text = '' unless defined $text;
2930 $pattern = '' unless defined $pattern;
2931 $replace = '' unless defined $replace;
2932 $global = 1 unless defined $global;
2934 my ($chunk, $start, $end) = @_;
2935 $chunk =~ s
{ \\(\\|\
$) | \
$ (\d
+) }{
2937 : ($2 > $#$start || $2 == 0) ? ''
2938 : substr($text, $start->[$2], $end->[$2] - $start->[$2]);
2943 $text =~ s{$pattern}{ $expand->($replace, [@-], [@+]) }eg;
2945 $text =~ s{$pattern}{ $expand->($replace, [@-], [@+]) }e;
2951 my ($list, $field) = @_;
2952 return defined($field)
2953 ? [map {$_->[0]} sort {$a->[1] cmp $b->[1]} map {[$_, lc(ref $_ eq 'HASH' ? $_->{$field}
2954 : UNIVERSAL
::can
($_, $field) ? $_->$field()
2956 : [map {$_->[0]} sort {$a->[1] cmp $b->[1]} map {[$_, lc $_]} @$list ]; # case insensitive
2959 sub vmethod_splice
{
2960 my ($ref, $i, $len, @replace) = @_;
2961 @replace = @{ $replace[0] } if @replace == 1 && ref $replace[0] eq 'ARRAY';
2963 return [splice @$ref, $i || 0, $len, @replace];
2965 return [splice @$ref, $i || 0];
2970 my ($str, $pat, @args) = @_;
2971 $str = '' if ! defined $str;
2972 return defined $pat ? [split $pat, $str, @args] : [split ' ', $str, @args];
2977 utf8
::encode
($str) if defined &utf8
::encode
;
2978 $str =~ s/([^A-Za-z0-9\-_.!~*\'()])/sprintf('%%%02X', ord($1))/eg;
2983 my $context = shift;
2986 return $context->process(\
$text);
2990 sub filter_redirect
{
2991 my ($context, $file, $options) = @_;
2992 my $path = $context->config->{'OUTPUT_PATH'} || $context->throw('redirect', 'OUTPUT_PATH is not set');
2993 $context->throw('redirect', 'Invalid filename - cannot include "/../"')
2994 if $file =~ m{(^|/)\.\./};
3000 File
::Path
::mkpath
($path) || $context->throw('redirect', "Couldn't mkpath \"$path\": $!");
3003 open (FH
, ">$path/$file") || $context->throw('redirect', "Couldn't open \"$file\": $!");
3004 if (my $bm = (! $options) ? 0 : ref($options) ? $options->{'binmode'} : $options) {
3005 if (+$bm == 1) { binmode FH
}
3006 else { binmode FH
, $bm}
3014 ###----------------------------------------------------------------###
3017 my $obj = UNIVERSAL
::isa
($_[0], __PACKAGE__
) ? shift : __PACKAGE__-
>new;
3019 require Data
::Dumper
;
3020 return Data
::Dumper
::Dumper
($obj->parse_expr(\
$str));
3023 ###----------------------------------------------------------------###
3025 package CGI
::Ex
::Template
::Exception
;
3028 '""' => \
&as_string
,
3029 bool
=> sub { defined shift },
3033 my ($class, $type, $info, $node, $pos, $str_ref) = @_;
3034 return bless [$type, $info, $node, $pos, $str_ref], $class;
3037 sub type
{ shift-
>[0] }
3039 sub info
{ shift-
>[1] }
3043 $self->[2] = shift if $#_ == 0;
3047 sub offset
{ shift-
>[3] || 0 }
3051 $self->[4] = shift if $#_ == 0;
3057 my $msg = $self->type .' error - '. $self->info;
3058 if (my $node = $self->node) {
3059 # $msg .= " (In tag $node->[0] starting at char ".($node->[1] + $self->offset).")";
3064 ###----------------------------------------------------------------###
3066 package CGI
::Ex
::Template
::Iterator
;
3069 my ($class, $items) = @_;
3070 $items = [] if ! defined $items;
3071 if (UNIVERSAL
::isa
($items, 'HASH')) {
3072 $items = [ map { {key
=> $_, value
=> $items->{ $_ }} } sort keys %$items ];
3073 } elsif (UNIVERSAL
::can
($items, 'as_list')) {
3074 $items = $items->as_list;
3075 } elsif (! UNIVERSAL
::isa
($items, 'ARRAY')) {
3078 return bless [$items, 0], $class;
3083 return (undef, 3) if ! @{ $self->[0] };
3084 return ($self->[0]->[$self->[1] = 0], undef);
3089 return (undef, 3) if ++ $self->[1] > $#{ $self->[0] };
3090 return ($self->items->[$self->[1]], undef);
3093 sub items
{ shift-
>[0] }
3095 sub index { shift-
>[1] }
3097 sub max
{ $#{ shift-
>[0] } }
3099 sub size
{ shift-
>max + 1 }
3101 sub count
{ shift-
>index + 1 }
3103 sub number
{ shift-
>index + 1 }
3105 sub first
{ (shift-
>index == 0) || 0 }
3107 sub last { my $self = shift; return ($self->index == $self->max) || 0 }
3111 return undef if $self->index <= 0;
3112 return $self->items->[$self->index - 1];
3117 return undef if $self->index >= $self->max;
3118 return $self->items->[$self->index + 1];
3121 ###----------------------------------------------------------------###
3123 package CGI
::Ex
::Template
::_Context
;
3125 use vars
qw($AUTOLOAD);
3127 sub _template
{ shift-
>{'_template'} || die "Missing _template" }
3129 sub config
{ shift-
>_template }
3133 return $self->{'stash'} ||= bless {_template
=> $self->_template}, $CGI::Ex
::Template
::PACKAGE_STASH
;
3136 sub insert
{ shift-
>_template->_insert(@_) }
3138 sub eval_perl
{ shift-
>_template->{'EVAL_PERL'} }
3143 my $vars = $self->_template->_vars;
3145 $self->_template->_process($ref, $vars, \
$out);
3152 my $args = shift || {};
3154 $self->_template->set_variable($_, $args->{$_}) for keys %$args;
3156 my $out = ''; # have temp item to allow clear to correctly clear
3157 eval { $self->_template->_process($file, $self->{'_vars'}, \
$out) };
3159 die $err if ref($err) !~ /Template::Exception$/ || $err->type !~ /return/;
3166 my ($self, $name, $filter, $is_dynamic) = @_;
3167 $filter = [ $filter, 1 ] if $is_dynamic;
3168 $self->define_vmethod('filter', $name, $filter);
3172 my ($self, $name, $args, $alias) = @_;
3173 my $t = $self->_template;
3177 $filter = $t->{'FILTERS'}->{$name} || $CGI::Ex
::Template
::FILTER_OPS-
>{$name} || $CGI::Ex
::Template
::SCALAR_OPS-
>{$name};
3178 $t->throw('filter', $name) if ! $filter;
3179 } elsif (UNIVERSAL
::isa
($name, 'CODE') || UNIVERSAL
::isa
($name, 'ARRAY')) {
3181 } elsif (UNIVERSAL
::can
($name, 'factory')) {
3182 $filter = $name->factory || $t->throw($name->error);
3184 $t->throw('undef', "$name: filter not found");
3187 if (UNIVERSAL
::isa
($filter, 'ARRAY')) {
3188 $filter = ($filter->[1]) ? $filter->[0]->($t->context, @$args) : $filter->[0];
3189 } elsif ($args && @$args) {
3191 $filter = sub { $sub->(shift, @$args) };
3194 $t->{'FILTERS'}->{$alias} = $filter if $alias;
3199 sub define_vmethod
{ shift-
>_template->define_vmethod(@_) }
3202 my ($self, $type, $info) = @_;
3204 if (UNIVERSAL
::isa
($type, $CGI::Ex
::Template
::PACKAGE_EXCEPTION
)) {
3206 } elsif (defined $info) {
3207 $self->_template->throw($type, $info);
3209 $self->_template->throw('undef', $type);
3213 sub AUTOLOAD
{ shift-
>_template->throw('not_implemented', "The method $AUTOLOAD has not been implemented") }
3217 ###----------------------------------------------------------------###
3219 package CGI
::Ex
::Template
::_Stash
;
3221 use vars
qw($AUTOLOAD);
3223 sub _template
{ shift-
>{'_template'} || die "Missing _template" }
3226 my ($self, $var) = @_;
3228 if ($var =~ /^\w+$/) { $var = [$var, 0] }
3229 else { $var = $self->_template->parse_expr(\
$var, {no_dots
=> 1}) }
3231 return $self->_template->play_expr($var, {no_dots
=> 1});
3235 my ($self, $var, $val) = @_;
3237 if ($var =~ /^\w+$/) { $var = [$var, 0] }
3238 else { $var = $self->_template->parse_expr(\
$var, {no_dots
=> 1}) }
3240 $self->_template->set_variable($var, $val, {no_dots
=> 1});
3244 sub AUTOLOAD
{ shift-
>_template->throw('not_implemented', "The method $AUTOLOAD has not been implemented") }
3248 ###----------------------------------------------------------------###
3250 package CGI
::Ex
::Template
::EvalPerlHandle
;
3253 my ($class, $out_ref) = @_;
3254 return bless [$out_ref], $class;
3259 ${ $self->[0] } .= $_ for grep {defined && length} @_;
3263 ###----------------------------------------------------------------###
3267 ### See the perldoc in CGI/Ex/Template.pod