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
36 $MAX_EVAL_RECURSE $MAX_MACRO_RECURSE
45 $PACKAGE_EXCEPTION = 'CGI::Ex::Template::Exception';
46 $PACKAGE_ITERATOR = 'CGI::Ex::Template::Iterator';
47 $PACKAGE_CONTEXT = 'CGI::Ex::Template::_Context';
48 $PACKAGE_STASH = 'CGI::Ex::Template::_Stash';
49 $PACKAGE_PERL_HANDLE = 'CGI::Ex::Template::EvalPerlHandle';
50 $MAX_EVAL_RECURSE = 50;
51 $MAX_MACRO_RECURSE = 50;
54 asp
=> ['<%', '%>' ], # ASP
55 default => ['\[%', '%\]' ], # default
56 html
=> ['<!--', '-->' ], # HTML comments
57 mason
=> ['<%', '>' ], # HTML::Mason
58 metatext
=> ['%%', '%%' ], # Text::MetaText
59 php
=> ['<\?', '\?>' ], # PHP
60 star
=> ['\[\*', '\*\]' ], # TT alternate
61 template1
=> ['[\[%]%', '%[%\]]'], # allow TT1 style
66 as
=> \
&vmethod_as_scalar
,
67 chunk
=> \
&vmethod_chunk
,
68 collapse
=> sub { local $_ = $_[0]; s/^\s+//; s/\s+$//; s/\s+/ /g; $_ },
69 defined => sub { defined $_[0] ? 1 : '' },
70 indent
=> \
&vmethod_indent
,
71 int => sub { local $^W; int $_[0] },
72 fmt
=> \
&vmethod_as_scalar
,
73 'format' => \
&vmethod_format
,
74 hash
=> sub { {value
=> $_[0]} },
75 html
=> sub { local $_ = $_[0]; s/&/&/g; s/</</g; s/>/>/g; s/\"/"/g; $_ },
76 item
=> sub { $_[0] },
77 lcfirst => sub { lcfirst $_[0] },
78 length => sub { defined($_[0]) ? length($_[0]) : 0 },
79 list
=> sub { [$_[0]] },
80 lower
=> sub { lc $_[0] },
81 match
=> \
&vmethod_match
,
82 new
=> sub { defined $_[0] ? $_[0] : '' },
84 rand => sub { local $^W; rand shift },
85 remove
=> sub { vmethod_replace
(shift, shift, '', 1) },
86 repeat
=> \
&vmethod_repeat
,
87 replace
=> \
&vmethod_replace
,
88 search
=> sub { my ($str, $pat) = @_; return $str if ! defined $str || ! defined $pat; return $str =~ /$pat/ },
90 split => \
&vmethod_split
,
91 stderr
=> sub { print STDERR
$_[0]; '' },
92 substr => \
&vmethod_substr
,
93 trim
=> sub { local $_ = $_[0]; s/^\s+//; s/\s+$//; $_ },
94 ucfirst => sub { ucfirst $_[0] },
95 upper
=> sub { uc $_[0] },
99 $FILTER_OPS = { # generally - non-dynamic filters belong in scalar ops
100 eval => [\
&filter_eval
, 1],
101 evaltt
=> [\
&filter_eval
, 1],
102 file
=> [\
&filter_redirect
, 1],
103 redirect
=> [\
&filter_redirect
, 1],
107 as
=> \
&vmethod_as_list
,
108 defined => sub { return 1 if @_ == 1; defined $_[0]->[ defined($_[1]) ? $_[1] : 0 ] },
109 first
=> sub { my ($ref, $i) = @_; return $ref->[0] if ! $i; return [@{$ref}[0 .. $i - 1]]},
110 fmt
=> \
&vmethod_as_list
,
111 grep => sub { local $^W; my ($ref, $pat) = @_; [grep {/$pat/} @$ref] },
112 hash
=> sub { local $^W; my $list = shift; return {@$list} if ! @_; my $i = shift || 0; return {map {$i++ => $_} @$list} },
113 import
=> sub { my $ref = shift; push @$ref, grep {defined} map {ref eq 'ARRAY' ? @$_ : undef} @_; '' },
114 item
=> sub { $_[0]->[ $_[1] || 0 ] },
115 join => sub { my ($ref, $join) = @_; $join = ' ' if ! defined $join; local $^W; return join $join, @$ref },
116 last => sub { my ($ref, $i) = @_; return $ref->[-1] if ! $i; return [@{$ref}[-$i .. -1]]},
117 list
=> sub { $_[0] },
118 max
=> sub { local $^W; $#{ $_[0] } },
119 merge
=> sub { my $ref = shift; return [ @$ref, grep {defined} map {ref eq 'ARRAY' ? @$_ : undef} @_ ] },
120 new
=> sub { local $^W; return [@_] },
122 nsort
=> \
&vmethod_nsort
,
123 pop => sub { pop @{ $_[0] } },
124 push => sub { my $ref = shift; push @$ref, @_; return '' },
125 random
=> sub { my $ref = shift; $ref->[ rand @$ref ] },
126 reverse => sub { [ reverse @{ $_[0] } ] },
127 shift => sub { shift @{ $_[0] } },
128 size
=> sub { local $^W; scalar @{ $_[0] } },
129 slice
=> sub { my ($ref, $a, $b) = @_; $a ||= 0; $b = $#$ref if ! defined $b; return [@{$ref}[$a .. $b]] },
130 sort => \
&vmethod_sort
,
131 splice => \
&vmethod_splice
,
132 unique
=> sub { my %u; return [ grep { ! $u{$_}++ } @{ $_[0] } ] },
133 unshift => sub { my $ref = shift; unshift @$ref, @_; return '' },
137 as
=> \
&vmethod_as_hash
,
138 defined => sub { return 1 if @_ == 1; defined $_[0]->{ defined($_[1]) ? $_[1] : '' } },
139 delete => sub { my $h = shift; my @v = delete @{ $h }{map {defined($_) ? $_ : ''} @_}; @_ == 1 ? $v[0] : \
@v },
140 each => sub { [%{ $_[0] }] },
141 exists => sub { exists $_[0]->{ defined($_[1]) ? $_[1] : '' } },
142 fmt
=> \
&vmethod_as_hash
,
143 hash
=> sub { $_[0] },
144 import
=> sub { my ($a, $b) = @_; @{$a}{keys %$b} = values %$b if ref($b) eq 'HASH'; '' },
145 item
=> sub { my ($h, $k) = @_; $k = '' if ! defined $k; $k =~ $QR_PRIVATE ? undef : $h->{$k} },
146 items
=> sub { [ %{ $_[0] } ] },
147 keys => sub { [keys %{ $_[0] }] },
148 list
=> \
&vmethod_list_hash
,
149 new
=> sub { local $^W; return (@_ == 1 && ref $_[-1] eq 'HASH') ? $_[-1] : {@_} },
151 nsort
=> sub { my $ref = shift; [sort { $ref->{$a} <=> $ref->{$b}} keys %$ref] },
152 pairs
=> sub { [map { {key
=> $_, value
=> $_[0]->{$_}} } sort keys %{ $_[0] } ] },
153 size
=> sub { scalar keys %{ $_[0] } },
154 sort => sub { my $ref = shift; [sort {lc $ref->{$a} cmp lc $ref->{$b}} keys %$ref] },
155 values => sub { [values %{ $_[0] }] },
163 foreach (values %$VOBJS) {
164 $_->{'Text'} = $_->{'as'};
165 $_->{'Hash'} = $_->{'hash'};
166 $_->{'List'} = $_->{'list'};
170 #name parse_sub play_sub block postdir continue move_to_front
171 BLOCK
=> [\
&parse_BLOCK
, \
&play_BLOCK
, 1, 0, 0, 1],
172 BREAK
=> [sub {}, \
&play_control
],
173 CALL
=> [\
&parse_CALL
, \
&play_CALL
],
174 CASE
=> [\
&parse_CASE
, undef, 0, 0, {SWITCH
=> 1, CASE
=> 1}],
175 CATCH => [\
&parse_CATCH
, undef, 0, 0, {TRY
=> 1, CATCH => 1}],
176 CLEAR
=> [sub {}, \
&play_CLEAR
],
177 '#' => [sub {}, sub {}],
178 DEBUG
=> [\
&parse_DEBUG
, \
&play_DEBUG
],
179 DEFAULT
=> [\
&parse_DEFAULT
, \
&play_DEFAULT
],
180 DUMP
=> [\
&parse_DUMP
, \
&play_DUMP
],
181 ELSE
=> [sub {}, undef, 0, 0, {IF
=> 1, ELSIF
=> 1, UNLESS
=> 1}],
182 ELSIF
=> [\
&parse_IF
, undef, 0, 0, {IF
=> 1, ELSIF
=> 1, UNLESS
=> 1}],
183 END => [undef, sub {}],
184 FILTER
=> [\
&parse_FILTER
, \
&play_FILTER
, 1, 1],
185 '|' => [\
&parse_FILTER
, \
&play_FILTER
, 1, 1],
186 FINAL
=> [sub {}, undef, 0, 0, {TRY
=> 1, CATCH => 1}],
187 FOR
=> [\
&parse_FOREACH
, \
&play_FOREACH
, 1, 1],
188 FOREACH
=> [\
&parse_FOREACH
, \
&play_FOREACH
, 1, 1],
189 GET
=> [\
&parse_GET
, \
&play_GET
],
190 IF
=> [\
&parse_IF
, \
&play_IF
, 1, 1],
191 INCLUDE
=> [\
&parse_INCLUDE
, \
&play_INCLUDE
],
192 INSERT
=> [\
&parse_INSERT
, \
&play_INSERT
],
193 LAST
=> [sub {}, \
&play_control
],
194 MACRO
=> [\
&parse_MACRO
, \
&play_MACRO
],
195 META
=> [undef, \
&play_META
],
196 NEXT => [sub {}, \
&play_control
],
197 PERL
=> [\
&parse_PERL
, \
&play_PERL
, 1],
198 PROCESS
=> [\
&parse_PROCESS
, \
&play_PROCESS
],
199 RAWPERL
=> [\
&parse_PERL
, \
&play_RAWPERL
, 1],
200 RETURN
=> [sub {}, \
&play_control
],
201 SET
=> [\
&parse_SET
, \
&play_SET
],
202 STOP
=> [sub {}, \
&play_control
],
203 SWITCH
=> [\
&parse_SWITCH
, \
&play_SWITCH
, 1],
204 TAGS
=> [undef, sub {}],
205 THROW
=> [\
&parse_THROW
, \
&play_THROW
],
206 TRY
=> [sub {}, \
&play_TRY
, 1],
207 UNLESS
=> [\
&parse_UNLESS
, \
&play_UNLESS
, 1, 1],
208 USE
=> [\
&parse_USE
, \
&play_USE
],
209 WHILE
=> [\
&parse_IF
, \
&play_WHILE
, 1, 1],
210 WRAPPER
=> [\
&parse_WRAPPER
, \
&play_WRAPPER
, 1, 1],
211 #name #parse_sub #play_sub #block #postdir #continue #move_to_front
214 ### setup the operator parsing
216 # type precedence symbols action (undef means play_operator will handle)
217 ['prefix', 99, ['\\'], undef ],
218 ['postfix', 98, ['++'], undef ],
219 ['postfix', 98, ['--'], undef ],
220 ['prefix', 97, ['++'], undef ],
221 ['prefix', 97, ['--'], undef ],
222 ['right', 96, ['**', 'pow'], sub { $_[0] ** $_[1] } ],
223 ['prefix', 93, ['!'], sub { ! $_[0] } ],
224 ['prefix', 93, ['-'], sub { @_ == 1 ? 0 - $_[0] : $_[0] - $_[1] } ],
225 ['left', 90, ['*'], sub { $_[0] * $_[1] } ],
226 ['left', 90, ['/'], sub { $_[0] / $_[1] } ],
227 ['left', 90, ['div', 'DIV'], sub { int($_[0] / $_[1]) } ],
228 ['left', 90, ['%', 'mod', 'MOD'], sub { $_[0] % $_[1] } ],
229 ['left', 85, ['+'], sub { $_[0] + $_[1] } ],
230 ['left', 85, ['-'], sub { @_ == 1 ? 0 - $_[0] : $_[0] - $_[1] } ],
231 ['left', 85, ['~', '_'], undef ],
232 ['none', 80, ['<'], sub { $_[0] < $_[1] } ],
233 ['none', 80, ['>'], sub { $_[0] > $_[1] } ],
234 ['none', 80, ['<='], sub { $_[0] <= $_[1] } ],
235 ['none', 80, ['>='], sub { $_[0] >= $_[1] } ],
236 ['none', 80, ['lt'], sub { $_[0] lt $_[1] } ],
237 ['none', 80, ['gt'], sub { $_[0] gt $_[1] } ],
238 ['none', 80, ['le'], sub { $_[0] le $_[1] } ],
239 ['none', 80, ['ge'], sub { $_[0] ge $_[1] } ],
240 ['none', 75, ['==', 'eq'], sub { $_[0] eq $_[1] } ],
241 ['none', 75, ['!=', 'ne'], sub { $_[0] ne $_[1] } ],
242 ['left', 70, ['&&'], undef ],
243 ['right', 65, ['||'], undef ],
244 ['none', 60, ['..'], sub { $_[0] .. $_[1] } ],
245 ['ternary', 55, ['?', ':'], undef ],
246 ['assign', 53, ['+='], sub { $_[0] + $_[1] } ],
247 ['assign', 53, ['-='], sub { $_[0] - $_[1] } ],
248 ['assign', 53, ['*='], sub { $_[0] * $_[1] } ],
249 ['assign', 53, ['/='], sub { $_[0] / $_[1] } ],
250 ['assign', 53, ['%='], sub { $_[0] % $_[1] } ],
251 ['assign', 53, ['**='], sub { $_[0] ** $_[1] } ],
252 ['assign', 53, ['~=', '_='], sub { $_[0] . $_[1] } ],
253 ['assign', 52, ['='], undef ],
254 ['prefix', 50, ['not', 'NOT'], sub { ! $_[0] } ],
255 ['left', 45, ['and', 'AND'], undef ],
256 ['right', 40, ['or', 'OR'], undef ],
257 ['', 0, ['{}'], undef ],
258 ['', 0, ['[]'], undef ],
260 $OP = {map {my $ref = $_; map {$_ => $ref} @{$ref->[2]}} grep {$_->[0] ne 'prefix' } @$OPERATORS}; # all non-prefix
261 $OP_PREFIX = {map {my $ref = $_; map {$_ => $ref} @{$ref->[2]}} grep {$_->[0] eq 'prefix' } @$OPERATORS};
262 $OP_DISPATCH = {map {my $ref = $_; map {$_ => $ref->[3]} @{$ref->[2]}} grep {$_->[3] } @$OPERATORS};
263 $OP_ASSIGN = {map {my $ref = $_; map {$_ => 1} @{$ref->[2]}} grep {$_->[0] eq 'assign' } @$OPERATORS};
264 $OP_POSTFIX = {map {my $ref = $_; map {$_ => 1} @{$ref->[2]}} grep {$_->[0] eq 'postfix'} @$OPERATORS}; # bool is postfix
265 $OP_TERNARY = {map {my $ref = $_; map {$_ => 1} @{$ref->[2]}} grep {$_->[0] eq 'ternary'} @$OPERATORS}; # bool is ternary
266 sub _op_qr
{ # no mixed \w\W operators
268 my $chrs = join '|', reverse sort map {quotemeta $_} grep {++$used{$_} < 2} grep {! /\{\}|\[\]/} grep {/^\W{2,}$/} @_;
269 my $chr = join '', sort map {quotemeta $_} grep {++$used{$_} < 2} grep {/^\W$/} @_;
270 my $word = join '|', reverse sort grep {++$used{$_} < 2} grep {/^\w+$/} @_;
271 $chr = "[$chr]" if $chr;
272 $word = "\\b(?:$word)\\b" if $word;
273 return join('|', grep {length} $chrs, $chr, $word) || die "Missing operator regex";
275 sub _build_op_qr
{ _op_qr
(map {@{ $_->[2] }} grep {$_->[0] ne 'prefix'} @$OPERATORS) }
276 sub _build_op_qr_prefix
{ _op_qr
(map {@{ $_->[2] }} grep {$_->[0] eq 'prefix'} @$OPERATORS) }
277 sub _build_op_qr_assign
{ _op_qr
(map {@{ $_->[2] }} grep {$_->[0] eq 'assign'} @$OPERATORS) }
278 $QR_OP = _build_op_qr
();
279 $QR_OP_PREFIX = _build_op_qr_prefix
();
280 $QR_OP_ASSIGN = _build_op_qr_assign
();
282 $QR_DIRECTIVE = '( [a-zA-Z]+\b | \| )';
283 $QR_COMMENTS = '(?-s: \# .* \s*)*';
284 $QR_FILENAME = '([a-zA-Z]]:/|/)? [\w\-\.]+ (?:/[\w\-\.]+)*';
285 $QR_NUM = '(?:\d*\.\d+ | \d+) (?: [eE][+-]\d+ )?';
286 $QR_AQ_NOTDOT = "(?! \\s* $QR_COMMENTS \\.)";
287 $QR_AQ_SPACE = '(?: \\s+ | \$ | (?=[;+]) )'; # the + comes into play on filenames
288 $QR_PRIVATE = qr/^[_.]/;
291 $EXTRA_COMPILE_EXT = '.sto2';
293 eval {require Scalar
::Util
};
296 ###----------------------------------------------------------------###
300 my $args = ref($_[0]) ? { %{ shift() } } : {@_};
302 ### allow for lowercase args
303 if (my @keys = grep {/^[a-z][a-z_]+$/} keys %$args) {
304 @{ $args }{ map { uc $_ } @keys } = delete @{ $args }{ @keys };
307 my $self = bless $args, $class;
309 ### "enable" debugging - we only support DEBUG_DIRS and DEBUG_UNDEF
310 if ($self->{'DEBUG'}) {
311 $self->{'_debug_dirs'} = 1 if $self->{'DEBUG'} =~ /^\d+$/ ? $self->{'DEBUG'} & 8 : $self->{'DEBUG'} =~ /dirs|all/;
312 $self->{'_debug_undef'} = 1 if $self->{'DEBUG'} =~ /^\d+$/ ? $self->{'DEBUG'} & 2 : $self->{'DEBUG'} =~ /undef|all/;
318 ###----------------------------------------------------------------###
323 local $self->{'_vars'} = shift || {};
324 my $out_ref = shift || $self->throw('undef', "Missing output ref");
325 local $self->{'_top_level'} = delete $self->{'_start_top_level'};
326 my $i = length $$out_ref;
328 ### parse and execute
331 ### load the document
332 $doc = $self->load_parsed_tree($file) || $self->throw('undef', "Zero length content");;
334 ### prevent recursion
335 $self->throw('file', "recursion into '$doc->{name}'")
336 if ! $self->{'RECURSION'} && $self->{'_in'}->{$doc->{'name'}} && $doc->{'name'} ne 'input text';
337 local $self->{'_in'}->{$doc->{'name'}} = 1;
339 ### execute the document
340 if (! @{ $doc->{'_tree'} }) { # no tags found - just return the content
341 $$out_ref = ${ $doc->{'_content'} };
343 local $self->{'_vars'}->{'component'} = $doc;
344 $self->{'_vars'}->{'template'} = $doc if $self->{'_top_level'};
345 $self->execute_tree($doc->{'_tree'}, $out_ref);
346 delete $self->{'_vars'}->{'template'} if $self->{'_top_level'};
350 ### trim whitespace from the beginning and the end of a block or template
351 if ($self->{'TRIM'}) {
352 substr($$out_ref, $i, length($$out_ref) - $i) =~ s{ \s+ $ }{}x; # tail first
353 substr($$out_ref, $i, length($$out_ref) - $i) =~ s{ ^ \s+ }{}x;
356 ### handle exceptions
358 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
359 $err->doc($doc) if $doc && $err->can('doc') && ! $err->doc;
360 die $err if ! $self->{'_top_level'} || $err->type !~ /stop|return/;
366 ###----------------------------------------------------------------###
368 sub load_parsed_tree
{
371 return if ! defined $file;
373 my $doc = {name
=> $file};
375 ### looks like a string reference
377 $doc->{'_content'} = $file;
378 $doc->{'name'} = 'input text';
379 $doc->{'is_str_ref'} = 1;
381 ### looks like a previously cached-in-memory document
382 } elsif ($self->{'_documents'}->{$file}
383 && ( ($self->{'_documents'}->{$file}->{'_cache_time'} == time) # don't stat more than once a second
384 || ($self->{'_documents'}->{$file}->{'modtime'}
385 == (stat $self->{'_documents'}->{$file}->{'_filename'})[9]))) {
386 $doc = $self->{'_documents'}->{$file};
387 $doc->{'_cache_time'} = time;
390 ### looks like a block name of some sort
391 } elsif ($self->{'BLOCKS'}->{$file}) {
392 my $block = $self->{'BLOCKS'}->{$file};
394 ### allow for predefined blocks that are a code or a string
395 if (UNIVERSAL
::isa
($block, 'CODE')) {
398 if (! UNIVERSAL
::isa
($block, 'HASH')) {
399 $self->throw('block', "Unsupported BLOCK type \"$block\"") if ref $block;
401 $block = eval { $self->load_parsed_tree(\
$copy) }
402 || $self->throw('block', 'Parse error on predefined block');
404 $doc->{'_tree'} = $block->{'_tree'} || $self->throw('block', "Invalid block definition (missing tree)");
408 ### go and look on the file system
410 $doc->{'_filename'} = eval { $self->include_filename($file) };
412 ### allow for blocks in other files
413 if ($self->{'EXPOSE_BLOCKS'}
414 && ! $self->{'_looking_in_block_file'}) {
415 local $self->{'_looking_in_block_file'} = 1;
417 while ($file =~ s
|/([^/.]+)$||) {
418 $block_name = length($block_name) ? "$1/$block_name" : $1;
419 my $ref = eval { $self->load_parsed_tree($file) } || next;
420 my $_tree = $ref->{'_tree'};
421 foreach my $node (@$_tree) {
423 next if $node->[0] eq 'META';
424 last if $node->[0] ne 'BLOCK';
425 next if $block_name ne $node->[3];
426 $doc->{'_content'} = $ref->{'_content'};
427 $doc->{'_tree'} = $node->[4];
428 $doc->{'modtime'} = $ref->{'modtime'};
429 $file = $ref->{'name'};
433 die $err if ! $doc->{'_tree'};
434 } elsif ($self->{'DEFAULT'}) {
435 $doc->{'_filename'} = eval { $self->include_filename($self->{'DEFAULT'}) } || die $err;
441 ### no tree yet - look for a file cache
442 if (! $doc->{'_tree'}) {
443 $doc->{'modtime'} = (stat $doc->{'_filename'})[9];
444 if ($self->{'COMPILE_DIR'} || $self->{'COMPILE_EXT'}) {
445 if ($self->{'COMPILE_DIR'}) {
446 $doc->{'_compile_filename'} = $self->{'COMPILE_DIR'} .'/'. $file;
448 $doc->{'_compile_filename'} = $doc->{'_filename'};
450 $doc->{'_compile_filename'} .= $self->{'COMPILE_EXT'} if defined($self->{'COMPILE_EXT'});
451 $doc->{'_compile_filename'} .= $EXTRA_COMPILE_EXT if defined $EXTRA_COMPILE_EXT;
453 if (-e
$doc->{'_compile_filename'} && (stat _
)[9] == $doc->{'modtime'}) {
455 $doc->{'_tree'} = Storable
::retrieve
($doc->{'_compile_filename'});
456 $doc->{'compile_was_used'} = 1;
458 my $str = $self->slurp($doc->{'_filename'});
459 $doc->{'_content'} = \
$str;
462 my $str = $self->slurp($doc->{'_filename'});
463 $doc->{'_content'} = \
$str;
469 ### haven't found a parsed tree yet - parse the content into a tree
470 if (! $doc->{'_tree'}) {
471 if ($self->{'CONSTANTS'}) {
472 my $key = $self->{'CONSTANT_NAMESPACE'} || 'constants';
473 $self->{'NAMESPACE'}->{$key} ||= $self->{'CONSTANTS'};
476 local $self->{'_vars'}->{'component'} = $doc;
477 $doc->{'_tree'} = $self->parse_tree($doc->{'_content'}); # errors die
480 ### cache parsed_tree in memory unless asked not to do so
481 if (! $doc->{'is_str_ref'} && (! defined($self->{'CACHE_SIZE'}) || $self->{'CACHE_SIZE'})) {
482 $self->{'_documents'}->{$file} ||= $doc;
483 $doc->{'_cache_time'} = time;
485 ### allow for config option to keep the cache size down
486 if ($self->{'CACHE_SIZE'}) {
487 my $all = $self->{'_documents'};
488 if (scalar(keys %$all) > $self->{'CACHE_SIZE'}) {
490 foreach my $file (sort {$all->{$b}->{'_cache_time'} <=> $all->{$a}->{'_cache_time'}} keys %$all) {
491 delete($all->{$file}) if ++$n > $self->{'CACHE_SIZE'};
497 ### save a cache on the fileside as asked
498 if ($doc->{'_compile_filename'} && ! $doc->{'compile_was_used'}) {
499 my $dir = $doc->{'_compile_filename'};
503 File
::Path
::mkpath
($dir);
506 Storable
::store
($doc->{'_tree'}, $doc->{'_compile_filename'});
507 utime $doc->{'modtime'}, $doc->{'modtime'}, $doc->{'_compile_filename'};
513 ###----------------------------------------------------------------###
518 if (! $str_ref || ! defined $$str_ref) {
519 $self->throw('parse.no_string', "No string or undefined during parse");
522 my $STYLE = $self->{'TAG_STYLE'} || 'default';
523 my $START = $self->{'START_TAG'} || $TAGS->{$STYLE}->[0];
524 my $END = $self->{'END_TAG'} || $TAGS->{$STYLE}->[1];
525 local $self->{'_end_tag'} = $END;
527 my @tree; # the parsed tree
528 my $pointer = \
@tree; # pointer to current tree to handle nested blocks
529 my @state; # maintain block levels
530 local $self->{'_state'} = \
@state; # allow for items to introspect (usually BLOCKS)
531 local $self->{'_in_perl'}; # no interpolation in perl
532 my @move_to_front; # items that need to be declared first (usually BLOCKS)
533 my @meta; # place to store any found meta information (to go into META)
534 my $post_chomp = 0; # previous post_chomp setting
535 my $continue = 0; # flag for multiple directives in the same tag
536 my $post_op; # found a post-operative DIRECTIVE
537 my $capture; # flag to start capture
541 local pos $$str_ref = 0;
544 ### continue looking for information in a semi-colon delimited tag
546 $node = [undef, pos($$str_ref), undef];
548 ### look through the string using index
550 $$str_ref =~ m{ \G (.*?) $START }gcxs
553 ### found a text portion - chomp it, interpolate it and store it
557 if ($text =~ m{ ($END) }xs) {
558 my $char = pos($$str_ref) + $-[1] + 1;
559 $self->throw('parse', "Found unmatched closing tag \"$1\"", undef, $char);
562 my $_last = pos $$str_ref;
564 if ($post_chomp == 1) { $_last += length($1) if $text =~ s{ ^ ([^\S\n]* \n) }{}x }
565 elsif ($post_chomp == 2) { $_last += length($1) + 1 if $text =~ s{ ^ (\s+) }{ }x }
566 elsif ($post_chomp == 3) { $_last += length($1) if $text =~ s{ ^ (\s+) }{}x }
569 push @$pointer, $text;
570 $self->interpolate_node($pointer, $_last) if $self->{'INTERPOLATE'};
574 $node = [undef, pos($$str_ref), undef];
576 ### take care of whitespace and comments flags
577 my $pre_chomp = $$str_ref =~ m{ \G ([+=~-]) }gcx ? $1 : $self->{'PRE_CHOMP'};
578 $pre_chomp =~ y/-=~+/1230/ if $pre_chomp;
579 if ($pre_chomp && $pointer->[-1] && ! ref $pointer->[-1]) {
580 if ($pre_chomp == 1) { $pointer->[-1] =~ s{ (?:\n|^) [^\S\n]* \z }{}x }
581 elsif ($pre_chomp == 2) { $pointer->[-1] =~ s{ (\s+) \z }{ }x }
582 elsif ($pre_chomp == 3) { $pointer->[-1] =~ s{ (\s+) \z }{}x }
583 splice(@$pointer, -1, 1, ()) if ! length $pointer->[-1]; # remove the node if it is zero length
585 if ($$str_ref =~ m{ \G \# }gcx) { # leading # means to comment the entire section
586 $$str_ref =~ m{ \G (.*?) ($END) }gcxs # brute force - can't comment tags with nested %]
587 || $self->throw('parse', "Missing closing tag", undef, pos($$str_ref));
589 $node->[2] = pos($$str_ref) - length($2);
590 push @$pointer, $node;
593 $$str_ref =~ m{ \G \s* $QR_COMMENTS }gcxo;
596 ### look for DIRECTIVES
597 if ($$str_ref =~ m{ \G $QR_DIRECTIVE }gcxo # find a word
598 && ($func = $self->{'ANYCASE'} ? uc($1) : $1)
599 && ($DIRECTIVES->{$func}
600 || ((pos($$str_ref) -= length $1) && 0))
601 ) { # is it a directive
603 $$str_ref =~ m{ \G \s* $QR_COMMENTS }gcx;
605 ### store out this current node level
606 if ($post_op) { # on a post operator - replace the original node with the new one - store the old in the new
607 my @post_op = @$post_op;
610 $node->[4] = [\
@post_op];
612 # do nothing - it will be handled further down
614 push @$pointer, $node;
617 ### anything that behaves as a block ending
618 if ($func eq 'END' || $DIRECTIVES->{$func}->[4]) { # [4] means it is a continuation block (ELSE, CATCH, etc)
620 $self->throw('parse', "Found an $func tag while not in a block", $node, pos($$str_ref));
622 my $parent_node = pop @state;
624 if ($func ne 'END') {
625 pop @$pointer; # we will store the node in the parent instead
626 $parent_node->[5] = $node;
627 my $parent_type = $parent_node->[0];
628 if (! $DIRECTIVES->{$func}->[4]->{$parent_type}) {
629 $self->throw('parse', "Found unmatched nested block", $node, 0);
633 ### restore the pointer up one level (because we hit the end of a block)
634 $pointer = (! @state) ? \
@tree : $state[-1]->[4];
637 if ($func eq 'END') {
638 if ($DIRECTIVES->{$parent_node->[0]}->[5]) { # move things like BLOCKS to front
639 push @move_to_front, $parent_node;
640 if ($pointer->[-1] && ! $pointer->[-1]->[6]) { # capturing doesn't remove the var
641 splice(@$pointer, -1, 1, ());
643 } elsif ($parent_node->[0] =~ /PERL$/) {
644 delete $self->{'_in_perl'};
647 ### continuation block - such as an elsif
649 $node->[3] = eval { $DIRECTIVES->{$func}->[0]->($self, $str_ref, $node) };
651 $err->node($node) if UNIVERSAL
::can
($err, 'node') && ! $err->node;
655 $pointer = $node->[4] ||= [];
658 } elsif ($func eq 'TAGS') {
662 \s
* $QR_COMMENTS # optional comments
663 ([+~=-]?) ($END) # forced close
665 my $ref = $TAGS->{lc $1} || $self->throw('parse', "Invalid TAGS name \"$1\"", undef, pos($$str_ref));
666 ($START, $END) = @$ref;
667 ($post_chomp, $end) = ($2, $3);
669 } elsif ($$str_ref =~ m
{
670 \G
(\S
+) \s
+ (\S
+) # two non-space things
671 (?:\s
+(un
|)quoted
?)? # optional unquoted adjective
672 \s
* $QR_COMMENTS # optional comments
673 ([+~=-]?) ($END) # forced close
675 ($START, $END, my $unquote, $post_chomp, $end) = ($1, $2, $3, $4, $5);
677 if ($unquote) { eval { "" =~ /$_/; 1 } || $self->throw('parse', "Invalid TAGS \"$_\": $@", undef, pos($$str_ref)) }
678 else { $_ = quotemeta $_ }
681 $self->throw('parse', "Invalid TAGS", undef, pos($$str_ref));
683 $post_chomp ||= $self->{'POST_CHOMP'};
684 $post_chomp =~ y/-=~+/1230/ if $post_chomp;
686 $node->[2] = pos($$str_ref) - length($end);
690 $self->{'_end_tag'} = $END; # need to keep track so parse_expr knows when to stop
693 } elsif ($func eq 'META') {
694 my $args = $self->parse_args($str_ref);
696 if (($hash = $self->play_expr($args->[-1]))
697 && UNIVERSAL
::isa
($hash, 'HASH')) {
698 unshift @meta, %$hash; # first defined win
701 ### all other "normal" tags
703 $node->[3] = eval { $DIRECTIVES->{$func}->[0]->($self, $str_ref, $node) };
705 $err->node($node) if UNIVERSAL
::can
($err, 'node') && ! $err->node;
708 if ($DIRECTIVES->{$func}->[2] && ! $post_op) { # this looks like a block directive
710 $pointer = $node->[4] ||= [];
715 # $node->[0] = 'GET';
716 # $node->[2] = $node->[1] + 5;
717 # $node->[3] = ['one',0];
718 # $$str_ref =~ m{ $END }gcx;
719 # push @$pointer, $node;
722 ### allow for bare variable getting and setting
723 } elsif (defined(my $var = $self->parse_expr($str_ref))) {
724 push @$pointer, $node;
725 if ($$str_ref =~ m{ \G ($QR_OP_ASSIGN) >? \s* $QR_COMMENTS }gcxo) {
727 $node->[3] = eval { $DIRECTIVES->{'SET'}->[0]->($self, $str_ref, $node, $1, $var) };
729 $err->node($node) if UNIVERSAL
::can
($err, 'node') && ! $err->node;
737 ### now look for the closing tag
738 } elsif ($$str_ref =~ m{ \G ([+=~-]?) ($END) }gcxs) {
740 $post_chomp = $1 || $self->{'POST_CHOMP'};
741 $post_chomp =~ y/-=~+/1230/ if $post_chomp;
743 $node->[2] = pos($$str_ref) - length($end);
748 my $all = substr($$str_ref, $node->[1], pos($$str_ref) - $node->[1]);
751 $self->throw('parse', "Not sure how to handle tag \"$all\"", $node);
754 ### we now have the directive to capture for an item like "SET foo = BLOCK" - store it
756 my $parent_node = $capture;
757 push @{ $parent_node->[4] }, $node;
761 ### look for the closing tag again
762 if ($$str_ref =~ m{ \G ([+=~-]?) ($END) }gcxs) {
764 $post_chomp = $1 || $self->{'POST_CHOMP'};
765 $post_chomp =~ y/-=~+/1230/ if $post_chomp;
767 $node->[2] = pos($$str_ref) - length($end);
773 ### we always continue - and always record our position now
775 $node->[2] = pos $$str_ref;
777 ### we are flagged to start capturing the output of the next directive - set it up
782 ### semi-colon = end of statement - we will need to continue parsing this tag
783 } elsif ($$str_ref =~ m{ \G ; \s* $QR_COMMENTS }gcxo) {
787 ### looking at a post operator ([% u FOREACH u IN [1..3] %])
788 $mark = pos $$str_ref;
789 if ($$str_ref =~ m{ \G $QR_DIRECTIVE }gcxo # find a word without advancing position
790 && ($func = $self->{'ANYCASE'} ? uc($1) : $1)
791 && (($DIRECTIVES->{$func} # and its a directive
792 && $DIRECTIVES->{$func}->[3]) # that can be post operative
793 || ((pos($$str_ref) = $mark) && 0)) # otherwise rollback
795 $post_op = $node; # store flag so next loop puts items in this node
796 pos($$str_ref) = $mark;
804 if (@move_to_front) {
805 unshift @tree, @move_to_front;
808 unshift @tree, ['META', 0, 0, {@meta}];
812 $self->throw('parse.missing.end', "Missing END", $state[-1], 0);
815 ### pull off the last text portion - if any
816 if (pos($$str_ref) != length($$str_ref)) {
817 my $text = substr $$str_ref, pos($$str_ref);
819 if ($text =~ m{ ($END) }xs) {
820 my $char = pos($$str_ref) + $-[1] + 1;
821 $self->throw('parse', "Found unmatched closing tag \"$1\"", undef, $char);
824 my $_last = pos($$str_ref);
826 if ($post_chomp == 1) { $_last += length($1) if $text =~ s{ ^ ([^\S\n]* \n) }{}x }
827 elsif ($post_chomp == 2) { $_last += length($1) + 1 if $text =~ s{ ^ (\s+) }{ }x }
828 elsif ($post_chomp == 3) { $_last += length($1) if $text =~ s{ ^ (\s+) }{}x }
831 push @$pointer, $text;
832 $self->interpolate_node($pointer, $_last) if $self->{'INTERPOLATE'};
842 my $ARGS = shift || {};
843 my $is_aq = $ARGS->{'auto_quote'} ? 1 : 0;
845 ### allow for custom auto_quoting (such as hash constructors)
847 if ($$str_ref =~ m{ \G $ARGS->{'auto_quote'} \s
* $QR_COMMENTS }gcx
) {
850 ### allow for auto-quoted $foo or ${foo.bar} type constructs
851 } elsif ($$str_ref =~ m{ \G \$ (\w+ (?:\.\w+)*) \b \s* $QR_COMMENTS }gcxo) {
853 return $self->parse_expr(\
$name);
855 } elsif ($$str_ref =~ m{ \G \$\{ \s* }gcx) {
856 my $var = $self->parse_expr($str_ref);
857 $$str_ref =~ m{ \G \s* \} \s
* $QR_COMMENTS }gcxo
858 || $self->throw('parse', 'Missing close "}" from "${"', undef, pos($$str_ref));
864 ### test for leading prefix operators
866 my $mark = pos $$str_ref;
867 while (! $is_aq && $$str_ref =~ m{ \G ($QR_OP_PREFIX) }gcxo) {
868 push @{ $has_prefix }, $1;
869 $$str_ref =~ m{ \G \s* $QR_COMMENTS }gcxo;
877 if ($$str_ref =~ m{ \G 0x ( [a-fA-F0-9]+ ) \s* $QR_COMMENTS }gcxo) {
878 my $number = eval { hex $1 } || 0;
879 push @var, \
$number;
882 ### allow for numbers
883 } elsif ($$str_ref =~ m{ \G ( $QR_NUM ) \s* $QR_COMMENTS }gcxo) {
885 push @var, \
$number;
888 ### allow for quoted array constructor
889 } elsif (! $is_aq && $$str_ref =~ m{ \G qw (\W) \s* }gcxo) {
891 $quote =~ y
|([{<|)]}>|;
892 $$str_ref =~ m{ \G (.*?) \Q$quote\E \s* $QR_COMMENTS }gcxs
893 || $self->throw('parse.missing.array_close', "Missing close \"$quote\"", undef, pos($$str_ref));
895 $str =~ s{ ^ \s+ | \s+ $ }{}x;
896 push @var, [undef, '[]', split /\s+/, $str];
898 ### looks like a normal variable start
899 } elsif ($$str_ref =~ m{ \G (\w+) \s* $QR_COMMENTS }gcxo) {
901 $is_namespace = 1 if $self->{'NAMESPACE'} && $self->{'NAMESPACE'}->{$1};
903 ### allow for literal strings
904 } elsif ($$str_ref =~ m{ \G ([\"\']) (|.*?[^\\]) \1 \s* $QR_COMMENTS }gcxos) {
905 if ($1 eq "'") { # no interpolation on single quoted strings
907 $str =~ s{ \\\' }{\'}xg;
916 my @pieces = $ARGS->{'auto_quote'}
917 ? split(m{ (?: ^ | (?<!\\)) (\$\w+ | \$\{ .*? (?<!\\) \}) }x
, $str) # autoquoted items get a single $\w+ - no nesting
918 : split(m{ (?: ^ | (?<!\\)) (\$\w+ (?:\.\w+)* | \$\{ .*? (?<!\\) \}) }x
, $str);
920 foreach my $piece (@pieces) {
921 $piece =~ s/\\\$/\$/g;
922 next if ! ($n++ % 2);
923 next if $piece !~ m{ ^ \$ (\w+ (?:\.\w+)*) $ }x
924 && $piece !~ m{ ^ \$\{ \s* (.*?) (?<!\\) \} $ }x
;
926 $name =~ s/\\\}/\}/g;
927 $piece = $self->parse_expr(\
$name);
929 @pieces = grep {defined && length} @pieces;
930 if (@pieces == 1 && ! ref $pieces[0]) {
931 push @var, \
$pieces[0];
933 } elsif (! @pieces) {
937 push @var, [undef, '~', @pieces];
941 #$$str_ref = $copy; # TODO ?
942 return ${ $var[0] } if $is_literal;
947 ### allow for leading $foo type constructs
948 } elsif ($$str_ref =~ m{ \G \$ (\w+) \b \s* $QR_COMMENTS }gcxo) {
949 if ($self->{'V1DOLLAR'}) {
951 $is_namespace = 1 if $self->{'NAMESPACE'} && $self->{'NAMESPACE'}->{$1};
956 ### allow for ${foo.bar} type constructs
957 } elsif ($$str_ref =~ m{ \G \$\{ \s* }gcx) {
958 push @var, $self->parse_expr($str_ref);
959 $$str_ref =~ m{ \G \s* \} \s
* $QR_COMMENTS }gcxo
960 || $self->throw('parse', 'Missing close "}" from "${"', undef, pos($$str_ref));
962 ### looks like an array constructor
963 } elsif (! $is_aq && $$str_ref =~ m{ \G \[ \s* $QR_COMMENTS }gcxo) {
964 local $self->{'_operator_precedence'} = 0; # reset presedence
965 my $arrayref = [undef, '[]'];
966 while (defined(my $var = $self->parse_expr($str_ref))) {
967 push @$arrayref, $var;
968 $$str_ref =~ m{ \G , \s* $QR_COMMENTS }gcxo;
970 $$str_ref =~ m{ \G \] \s* $QR_COMMENTS }gcxo
971 || $self->throw('parse.missing.square_bracket', "Missing close \]", undef, pos($$str_ref));
972 push @var, $arrayref;
974 ### looks like a hash constructor
975 } elsif (! $is_aq && $$str_ref =~ m{ \G \{ \s* $QR_COMMENTS }gcxo) {
976 local $self->{'_operator_precedence'} = 0; # reset precedence
977 my $hashref = [undef, '{}'];
978 while (defined(my $key = $self->parse_expr($str_ref, {auto_quote
=> "(\\w+) $QR_AQ_NOTDOT"}))) {
979 $$str_ref =~ m{ \G = >? \s* $QR_COMMENTS }gcxo;
980 my $val = $self->parse_expr($str_ref);
981 push @$hashref, $key, $val;
982 $$str_ref =~ m{ \G , \s* $QR_COMMENTS }gcxo;
984 $$str_ref =~ m{ \G \} \s
* $QR_COMMENTS }gcxo
985 || $self->throw('parse.missing.curly_bracket', "Missing close \}", undef, pos($$str_ref));
988 ### looks like a paren grouper
989 } elsif (! $is_aq && $$str_ref =~ m{ \G \( \s* $QR_COMMENTS }gcxo) {
990 local $self->{'_operator_precedence'} = 0; # reset precedence
991 my $var = $self->parse_expr($str_ref, {allow_parened_ops
=> 1});
993 $$str_ref =~ m{ \G \) \s* $QR_COMMENTS }gcxo
994 || $self->throw('parse.missing.paren', "Missing close \)", undef, pos($$str_ref));
996 pop @var; # pull off the trailing args of the paren group
997 # TODO - we could forward lookahed for a period or pipe
999 ### nothing to find - return failure
1004 return if $is_aq; # auto_quoted thing was too complicated
1006 ### looks for args for the initial
1007 if ($$str_ref =~ m{ \G \( \s* $QR_COMMENTS }gcxo) {
1008 local $self->{'_operator_precedence'} = 0; # reset precedence
1009 my $args = $self->parse_args($str_ref, {is_parened
=> 1});
1010 $$str_ref =~ m{ \G \) \s* $QR_COMMENTS }gcxo
1011 || $self->throw('parse.missing.paren', "Missing close \)", undef, pos($$str_ref));
1017 ### allow for nested items
1018 while ($$str_ref =~ m{ \G ( \.(?!\.) | \|(?!\|) ) \s* $QR_COMMENTS }gcxo) {
1019 push(@var, $1) if ! $ARGS->{'no_dots'};
1021 ### allow for interpolated variables in the middle - one.$foo.two
1022 if ($$str_ref =~ m{ \G \$ (\w+) \b \s* $QR_COMMENTS }gcxo) {
1023 push @var, $self->{'V1DOLLAR'} ? $1 : [$1, 0];
1025 ### or one.${foo.bar}.two
1026 } elsif ($$str_ref =~ m{ \G \$\{ \s* }gcx) {
1027 push @var, $self->parse_expr($str_ref);
1028 $$str_ref =~ m{ \G \s* \} \s
* $QR_COMMENTS }gcxo
1029 || $self->throw('parse', 'Missing close "}" from "${"', undef, pos($$str_ref));
1032 } elsif ($$str_ref =~ m{ \G (-? \w+) \s* $QR_COMMENTS }gcxo) {
1036 $self->throw('parse', "Not sure how to continue parsing", undef, pos($$str_ref));
1039 ### looks for args for the nested item
1040 if ($$str_ref =~ m{ \G \( \s* $QR_COMMENTS }gcxo) {
1041 local $self->{'_operator_precedence'} = 0; # reset precedence
1042 my $args = $self->parse_args($str_ref, {is_parened
=> 1});
1043 $$str_ref =~ m{ \G \) \s* $QR_COMMENTS }gcxo
1044 || $self->throw('parse.missing.paren', "Missing close \)", undef, pos($$str_ref));
1052 ### flatten literals and constants as much as possible
1055 $var = ${ $var[0] };
1057 $var[0] = [undef, '~', $var];
1060 } elsif ($is_namespace) {
1061 $var = $self->play_expr(\
@var, {is_namespace_during_compile
=> 1});
1066 ### allow for all "operators"
1067 if (! $self->{'_operator_precedence'}) {
1071 my $mark = pos $$str_ref;
1072 if ($self->{'_end_tag'} && $$str_ref =~ m{ \G [+=~-]? $self->{'_end_tag'} }gcx
) {
1073 pos($$str_ref) = $mark;
1075 } elsif ($$str_ref !~ m{ \G ($QR_OP) }gcxo) {
1076 pos($$str_ref) = $mark;
1079 if ($OP_ASSIGN->{$1} && ! $ARGS->{'allow_parened_ops'}) { # only allow assignment in parens
1080 pos($$str_ref) = $mark;
1083 local $self->{'_operator_precedence'} = 1;
1085 $$str_ref =~ m{ \G \s* $QR_COMMENTS }gcxo;
1087 ### allow for postfix - doesn't check precedence - someday we might change - but not today (only affects post ++ and --)
1088 if ($OP_POSTFIX->{$op}) {
1089 $var = [[undef, $op, $var, 1], 0]; # cheat - give a "second value" to postfix ops
1092 ### allow for prefix operator precedence
1093 } elsif ($has_prefix && $OP->{$op}->[1] < $OP_PREFIX->{$has_prefix->[-1]}->[1]) {
1095 if ($#$tree == 1) { # only one operator - keep simple things fast
1096 $var = [[undef, $tree->[0], $var, $tree->[1]], 0];
1098 unshift @$tree, $var;
1099 $var = $self->apply_precedence($tree, $found);
1104 $var = [[undef, $has_prefix->[-1], $var ], 0];
1105 if (! @$has_prefix) { undef $has_prefix } else { pop @$has_prefix }
1108 ### add the operator to the tree
1109 my $var2 = $self->parse_expr($str_ref, {from_here
=> 1});
1110 $self->throw('parse', 'Missing variable after "'.$op.'"', undef, pos($$str_ref)) if ! defined $var2;
1111 push (@{ $tree ||= [] }, $op, $var2);
1112 $found->{$OP->{$op}->[1]}->{$op} = 1; # found->{precedence}->{op}
1115 ### if we found operators - tree the nodes by operator precedence
1117 if (@$tree == 2) { # only one operator - keep simple things fast
1118 $var = [[undef, $tree->[0], $var, $tree->[1]], 0];
1120 unshift @$tree, $var;
1121 $var = $self->apply_precedence($tree, $found);
1126 ### allow for prefix on non-chained variables
1128 $var = [[undef, $_, $var], 0] for reverse @$has_prefix;
1134 ### this is used to put the parsed variables into the correct operations tree
1135 sub apply_precedence
{
1136 my ($self, $tree, $found) = @_;
1140 ### look at the operators we found in the order we found them
1141 for my $prec (sort keys %$found) {
1142 my $ops = $found->{$prec};
1143 local $found->{$prec};
1144 delete $found->{$prec};
1146 ### split the array on the current operators for this level
1149 for (my $i = 1; $i <= $#$tree; $i += 2) {
1150 next if ! $ops->{ $tree->[$i] };
1151 push @ops, $tree->[$i];
1152 push @exprs, [splice @$tree, 0, $i, ()];
1156 next if ! @exprs; # this iteration didn't have the current operator
1157 push @exprs, $tree if scalar @$tree; # add on any remaining items
1159 ### simplify sub expressions
1160 for my $node (@exprs) {
1162 $node = $node->[0]; # single item - its not a tree
1163 } elsif (@$node == 3) {
1164 $node = [[undef, $node->[1], $node->[0], $node->[2]], 0]; # single operator - put it straight on
1166 $node = $self->apply_precedence($node, $found); # more complicated - recurse
1170 ### assemble this current level
1173 # 1) items at the same precedence level must all be either right or left or ternary associative
1174 # 2) ternary items cannot share precedence with anybody else.
1175 # 3) there really shouldn't be another operator at the same level as a postfix
1176 my $type = $OP->{$ops[0]}->[0];
1178 if ($type eq 'ternary') {
1179 my $op = $OP->{$ops[0]}->[2]->[0]; # use the first op as what we are using
1181 ### return simple ternary
1183 $self->throw('parse', "Ternary operator mismatch") if $ops[0] ne $op;
1184 $self->throw('parse', "Ternary operator mismatch") if ! $ops[1] || $ops[1] eq $op;
1185 return [[undef, $op, @exprs], 0];
1189 ### reorder complex ternary - rare case
1190 while ($#ops >= 1) {
1191 ### if we look starting from the back - the first lead ternary op will always be next to its matching op
1192 for (my $i = $#ops; $i >= 0; $i --) {
1193 next if $OP->{$ops[$i]}->[2]->[1] eq $ops[$i];
1194 my ($op, $op2) = splice @ops, $i, 2, (); # remove the pair of operators
1195 my $node = [[undef, $op, @exprs[$i .. $i + 2]], 0];
1196 splice @exprs, $i, 3, $node;
1199 return $exprs[0]; # at this point the ternary has been reduced to a single operator
1201 } elsif ($type eq 'right' || $type eq 'assign') {
1202 my $val = $exprs[-1];
1203 $val = [[undef, $ops[$_ - 1], $exprs[$_], $val], 0] for reverse (0 .. $#exprs - 1);
1207 my $val = $exprs[0];
1208 $val = [[undef, $ops[$_ - 1], $val, $exprs[$_]], 0] for (1 .. $#exprs);
1214 $self->throw('parse', "Couldn't apply precedence");
1217 ### look for arguments - both positional and named
1220 my $str_ref = shift;
1221 my $ARGS = shift || {};
1226 my $mark = pos $$str_ref;
1227 if (! $ARGS->{'is_parened'}
1228 && $$str_ref =~ m{ \G $QR_DIRECTIVE (?: \s+ | (?: \s* $QR_COMMENTS (?: ;|[+=~-]?$self->{'_end_tag'}))) }gcxo
1229 && ((pos($$str_ref) = $mark) || 1) # always revert
1230 && $DIRECTIVES->{$self->{'ANYCASE'} ? uc($1) : $1} # looks like a directive - we are done
1235 if (defined(my $name = $self->parse_expr($str_ref, {auto_quote
=> "(\\w+) $QR_AQ_NOTDOT"}))
1236 && ($$str_ref =~ m{ \G = >? \s* $QR_COMMENTS }gcxo # see if we also match assignment
1237 || ((pos $$str_ref = $mark) && 0)) # if not - we need to rollback
1239 $self->throw('parse', 'Named arguments not allowed', undef, $mark) if $ARGS->{'positional_only'};
1240 my $val = $self->parse_expr($str_ref);
1241 $$str_ref =~ m{ \G , \s* $QR_COMMENTS }gcxo;
1242 push @named, $name, $val;
1243 } elsif (defined(my $arg = $self->parse_expr($str_ref))) {
1245 $$str_ref =~ m{ \G , \s* $QR_COMMENTS }gcxo;
1251 ### allow for named arguments to be added also
1252 push @args, [[undef, '{}', @named], 0] if scalar @named;
1257 ### allow for looking for $foo or ${foo.bar} in TEXT "nodes" of the parse tree.
1258 sub interpolate_node
{
1259 my ($self, $tree, $offset) = @_;
1260 return if $self->{'_in_perl'};
1262 ### split on variables while keeping the variables
1263 my @pieces = split m{ (?: ^ | (?<! \\)) (\$\w+ (?:\.\w+)* | \$\{ .*? (?<!\\) \}) }x
, $tree->[-1];
1264 if ($#pieces <= 0) {
1265 $tree->[-1] =~ s{ \\ ([\"\$]) }{$1}xg;
1271 foreach my $piece (@pieces) {
1272 $offset += length $piece; # we track the offset to make sure DEBUG has the right location
1273 $piece =~ s{ \\ ([\"\$]) }{$1}xg;
1274 if (! ($n++ % 2)) { # odds will always be text chunks
1275 next if ! length $piece;
1276 push @sub_tree, $piece;
1277 } elsif ($piece =~ m{ ^ \$ (\w+ (?:\.\w+)*) $ }x
1278 || $piece =~ m{ ^ \$\{ \s* (.*?) (?<!\\) \} $ }x
) {
1280 $name =~ s/\\\}/\}/g;
1281 push @sub_tree, ['GET', $offset - length($piece), $offset, $self->parse_expr(\
$name)];
1283 $self->throw('parse', "Parse error during interpolate node");
1287 ### replace the tree
1288 splice @$tree, -1, 1, @sub_tree;
1291 ###----------------------------------------------------------------###
1294 my ($self, $tree, $out_ref) = @_;
1296 # node contains (0: DIRECTIVE,
1299 # 3: parsed tag details,
1300 # 4: sub tree for block types
1301 # 5: continuation sub trees for sub continuation block types (elsif, else, etc)
1302 # 6: flag to capture next directive
1303 for my $node (@$tree) {
1304 ### text nodes are just the bare text
1306 warn "NODE: TEXT\n" if trace
;
1307 $$out_ref .= $node if defined $node;
1311 warn "NODE: $node->[0] (char $node->[1])\n" if trace
;
1312 $$out_ref .= $self->debug_node($node) if $self->{'_debug_dirs'} && ! $self->{'_debug_off'};
1314 my $val = $DIRECTIVES->{$node->[0]}->[1]->($self, $node->[3], $node, $out_ref);
1315 $$out_ref .= $val if defined $val;
1320 ### allow for the parse tree to store literals
1321 return $_[1] if ! ref $_[1];
1325 my $ARGS = shift || {};
1328 ### determine the top level of this particular variable access
1330 my $name = $var->[$i++];
1331 my $args = $var->[$i++];
1332 warn "play_expr: begin \"$name\"\n" if trace
;
1334 if (! defined $name->[0]) { # operator
1335 return $self->play_operator($name) if wantarray && $name->[1] eq '..';
1336 $ref = $self->play_operator($name);
1337 } else { # a named variable access (ie via $name.foo)
1338 $name = $self->play_expr($name);
1339 if (defined $name) {
1340 return if $name =~ $QR_PRIVATE; # don't allow vars that begin with _
1341 return \
$self->{'_vars'}->{$name} if $i >= $#$var && $ARGS->{'return_ref'} && ! ref $self->{'_vars'}->{$name};
1342 $ref = $self->{'_vars'}->{$name};
1345 } elsif (defined $name) {
1346 if ($ARGS->{'is_namespace_during_compile'}) {
1347 $ref = $self->{'NAMESPACE'}->{$name};
1349 return if $name =~ $QR_PRIVATE; # don't allow vars that begin with _
1350 return \
$self->{'_vars'}->{$name} if $i >= $#$var && $ARGS->{'return_ref'} && ! ref $self->{'_vars'}->{$name};
1351 $ref = $self->{'_vars'}->{$name};
1352 $ref = $VOBJS->{$name} if ! defined $ref;
1358 while (defined $ref) {
1360 ### check at each point if the rurned thing was a code
1361 if (UNIVERSAL
::isa
($ref, 'CODE')) {
1362 return $ref if $i >= $#$var && $ARGS->{'return_ref'};
1363 my @results = $ref->($args ? map { $self->play_expr($_) } @$args : ());
1364 if (defined $results[0]) {
1365 $ref = ($#results > 0) ? \
@results : $results[0];
1366 } elsif (defined $results[1]) {
1367 die $results[1]; # TT behavior - why not just throw ?
1374 ### descend one chained level
1375 last if $i >= $#$var;
1376 my $was_dot_call = $ARGS->{'no_dots'} ? 1 : $var->[$i++] eq '.';
1377 $name = $var->[$i++];
1378 $args = $var->[$i++];
1379 warn "play_expr: nested \"$name\"\n" if trace
;
1381 ### allow for named portions of a variable name (foo.$name.bar)
1383 if (ref($name) eq 'ARRAY') {
1384 $name = $self->play_expr($name);
1385 if (! defined($name) || $name =~ $QR_PRIVATE || $name =~ /^\./) {
1390 die "Shouldn't get a ". ref($name) ." during a vivify on chain";
1393 if ($name =~ $QR_PRIVATE) { # don't allow vars that begin with _
1398 ### allow for scalar and filter access (this happens for every non virtual method call)
1400 if ($SCALAR_OPS->{$name}) { # normal scalar op
1401 $ref = $SCALAR_OPS->{$name}->($ref, $args ? map { $self->play_expr($_) } @$args : ());
1403 } elsif ($LIST_OPS->{$name}) { # auto-promote to list and use list op
1404 $ref = $LIST_OPS->{$name}->([$ref], $args ? map { $self->play_expr($_) } @$args : ());
1406 } elsif (my $filter = $self->{'FILTERS'}->{$name} # filter configured in Template args
1407 || $FILTER_OPS->{$name} # predefined filters in CET
1408 || (UNIVERSAL
::isa
($name, 'CODE') && $name) # looks like a filter sub passed in the stash
1409 || $self->list_filters->{$name}) { # filter defined in Template::Filters
1411 if (UNIVERSAL
::isa
($filter, 'CODE')) {
1412 $ref = eval { $filter->($ref) }; # non-dynamic filter - no args
1414 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1417 } elsif (! UNIVERSAL
::isa
($filter, 'ARRAY')) {
1418 $self->throw('filter', "invalid FILTER entry for '$name' (not a CODE ref)");
1420 } elsif (@$filter == 2 && UNIVERSAL
::isa
($filter->[0], 'CODE')) { # these are the TT style filters
1422 my $sub = $filter->[0];
1423 if ($filter->[1]) { # it is a "dynamic filter" that will return a sub
1424 ($sub, my $err) = $sub->($self->context, $args ? map { $self->play_expr($_) } @$args : ());
1425 if (! $sub && $err) {
1426 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1428 } elsif (! UNIVERSAL
::isa
($sub, 'CODE')) {
1429 $self->throw('filter', "invalid FILTER for '$name' (not a CODE ref)")
1430 if ref($sub) !~ /Template::Exception$/;
1434 $ref = $sub->($ref);
1437 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1440 } else { # this looks like our vmethods turned into "filters" (a filter stored under a name)
1441 $self->throw('filter', 'Recursive filter alias \"$name\"') if $seen_filters{$name} ++;
1442 $var = [$name, 0, '|', @$filter, @{$var}[$i..$#$var]]; # splice the filter into our current tree
1445 if (scalar keys %seen_filters
1446 && $seen_filters{$var->[$i - 5] || ''}) {
1447 $self->throw('filter', "invalid FILTER entry for '".$var->[$i - 5]."' (not a CODE ref)");
1455 ### method calls on objects
1456 if ($was_dot_call && UNIVERSAL
::can
($ref, 'can')) {
1457 return $ref if $i >= $#$var && $ARGS->{'return_ref'};
1458 my @args = $args ? map { $self->play_expr($_) } @$args : ();
1459 my @results = eval { $ref->$name(@args) };
1461 my $class = ref $ref;
1462 die $@ if ref $@ || $@ !~ /Can\'t locate object method "\Q$name\E" via package "\Q$class\E"/;
1463 } elsif (defined $results[0]) {
1464 $ref = ($#results > 0) ? \
@results : $results[0];
1466 } elsif (defined $results[1]) {
1467 die $results[1]; # TT behavior - why not just throw ?
1472 # didn't find a method by that name - so fail down to hash and array access
1475 ### hash member access
1476 if (UNIVERSAL
::isa
($ref, 'HASH')) {
1477 if ($was_dot_call && exists($ref->{$name}) ) {
1478 return \
$ref->{$name} if $i >= $#$var && $ARGS->{'return_ref'} && ! ref $ref->{$name};
1479 $ref = $ref->{$name};
1480 } elsif ($HASH_OPS->{$name}) {
1481 $ref = $HASH_OPS->{$name}->($ref, $args ? map { $self->play_expr($_) } @$args : ());
1482 } elsif ($ARGS->{'is_namespace_during_compile'}) {
1483 return $var; # abort - can't fold namespace variable
1485 return \
$ref->{$name} if $i >= $#$var && $ARGS->{'return_ref'};
1490 } elsif (UNIVERSAL
::isa
($ref, 'ARRAY')) {
1491 if ($name =~ m{ ^ -? $QR_NUM $ }ox) {
1492 return \
$ref->[$name] if $i >= $#$var && $ARGS->{'return_ref'} && ! ref $ref->[$name];
1493 $ref = $ref->[$name];
1494 } elsif ($LIST_OPS->{$name}) {
1495 $ref = $LIST_OPS->{$name}->($ref, $args ? map { $self->play_expr($_) } @$args : ());
1504 ### allow for undefinedness
1505 if (! defined $ref) {
1506 if ($self->{'_debug_undef'}) {
1507 my $chunk = $var->[$i - 2];
1508 $chunk = $self->play_expr($chunk) if ref($chunk) eq 'ARRAY';
1509 die "$chunk is undefined\n";
1511 $ref = $self->undefined_any($var);
1519 my ($self, $var, $val, $ARGS) = @_;
1523 ### allow for the parse tree to store literals - the literal is used as a name (like [% 'a' = 'A' %])
1524 $var = [$var, 0] if ! ref $var;
1526 ### determine the top level of this particular variable access
1527 my $ref = $var->[$i++];
1528 my $args = $var->[$i++];
1530 ### non-named types can't be set
1531 return if ref($ref) ne 'ARRAY' || ! defined $ref->[0];
1533 # named access (ie via $name.foo)
1534 $ref = $self->play_expr($ref);
1535 if (defined $ref && $ref !~ $QR_PRIVATE) { # don't allow vars that begin with _
1537 return $self->{'_vars'}->{$ref} = $val;
1539 $ref = $self->{'_vars'}->{$ref} ||= {};
1544 } elsif (defined $ref) {
1545 return if $ref =~ $QR_PRIVATE; # don't allow vars that begin with _
1547 return $self->{'_vars'}->{$ref} = $val;
1549 $ref = $self->{'_vars'}->{$ref} ||= {};
1553 while (defined $ref) {
1555 ### check at each point if the returned thing was a code
1556 if (UNIVERSAL
::isa
($ref, 'CODE')) {
1557 my @results = $ref->($args ? map { $self->play_expr($_) } @$args : ());
1558 if (defined $results[0]) {
1559 $ref = ($#results > 0) ? \
@results : $results[0];
1560 } elsif (defined $results[1]) {
1561 die $results[1]; # TT behavior - why not just throw ?
1567 ### descend one chained level
1568 last if $i >= $#$var;
1569 my $was_dot_call = $ARGS->{'no_dots'} ? 1 : $var->[$i++] eq '.';
1570 my $name = $var->[$i++];
1571 my $args = $var->[$i++];
1573 ### allow for named portions of a variable name (foo.$name.bar)
1575 if (ref($name) eq 'ARRAY') {
1576 $name = $self->play_expr($name);
1577 if (! defined($name) || $name =~ /^[_.]/) {
1581 die "Shouldn't get a ".ref($name)." during a vivify on chain";
1584 if ($name =~ $QR_PRIVATE) { # don't allow vars that begin with _
1592 ### method calls on objects
1593 } elsif (UNIVERSAL
::can
($ref, 'can')) {
1595 my @args = $args ? map { $self->play_expr($_) } @$args : ();
1600 my @results = eval { $ref->$name(@args) };
1602 if (defined $results[0]) {
1603 $ref = ($#results > 0) ? \
@results : $results[0];
1604 } elsif (defined $results[1]) {
1605 die $results[1]; # TT behavior - why not just throw ?
1609 return if $lvalueish;
1612 my $class = ref $ref;
1613 die $@ if ref $@ || $@ !~ /Can\'t locate object method "\Q$name\E" via package "\Q$class\E"/;
1614 # fall on down to "normal" accessors
1617 ### hash member access
1618 if (UNIVERSAL
::isa
($ref, 'HASH')) {
1620 return $ref->{$name} = $val;
1622 $ref = $ref->{$name} ||= {};
1627 } elsif (UNIVERSAL
::isa
($ref, 'ARRAY')) {
1628 if ($name =~ m{ ^ -? $QR_NUM $ }ox) {
1630 return $ref->[$name] = $val;
1632 $ref = $ref->[$name] ||= {};
1646 ###----------------------------------------------------------------###
1649 my ($self, $tree) = @_;
1650 ### $tree looks like [undef, '+', 4, 5]
1652 if ($OP_DISPATCH->{$tree->[1]}) {
1654 if ($OP_ASSIGN->{$tree->[1]}) {
1655 my $val = $OP_DISPATCH->{$tree->[1]}->($self->play_expr($tree->[2]), $self->play_expr($tree->[3]));
1656 $self->set_variable($tree->[2], $val);
1659 return $OP_DISPATCH->{$tree->[1]}->(@$tree == 3 ? $self->play_expr($tree->[2]) : ($self->play_expr($tree->[2]), $self->play_expr($tree->[3])));
1663 my $op = $tree->[1];
1665 ### do custom and short-circuitable operators
1667 my $val = $self->play_expr($tree->[3]);
1668 $self->set_variable($tree->[2], $val);
1671 } elsif ($op eq '||' || $op eq 'or' || $op eq 'OR') {
1672 return $self->play_expr($tree->[2]) || $self->play_expr($tree->[3]) || '';
1674 } elsif ($op eq '&&' || $op eq 'and' || $op eq 'AND') {
1675 my $var = $self->play_expr($tree->[2]) && $self->play_expr($tree->[3]);
1676 return $var ? $var : 0;
1678 } elsif ($op eq '?') {
1680 return $self->play_expr($tree->[2]) ? $self->play_expr($tree->[3]) : $self->play_expr($tree->[4]);
1682 } elsif ($op eq '~' || $op eq '_') {
1685 $s .= $self->play_expr($tree->[$_]) for 2 .. $#$tree;
1688 } elsif ($op eq '[]') {
1689 return [map {$self->play_expr($tree->[$_])} 2 .. $#$tree];
1691 } elsif ($op eq '{}') {
1694 push @e, $self->play_expr($tree->[$_]) for 2 .. $#$tree;
1697 } elsif ($op eq '++') {
1699 my $val = 0 + $self->play_expr($tree->[2]);
1700 $self->set_variable($tree->[2], $val + 1);
1701 return $tree->[3] ? $val : $val + 1; # ->[3] is set to 1 during parsing of postfix ops
1703 } elsif ($op eq '--') {
1705 my $val = 0 + $self->play_expr($tree->[2]);
1706 $self->set_variable($tree->[2], $val - 1);
1707 return $tree->[3] ? $val : $val - 1; # ->[3] is set to 1 during parsing of postfix ops
1709 } elsif ($op eq '\\') {
1710 my $var = $tree->[2];
1712 my $ref = $self->play_expr($var, {return_ref
=> 1});
1713 return $ref if ! ref $ref;
1714 return sub { sub { $$ref } } if ref $ref eq 'SCALAR' || ref $ref eq 'REF';
1716 my $self_copy = $self;
1717 eval {require Scalar
::Util
; Scalar
::Util
::weaken
($self_copy)};
1719 my $last = ['temp deref key', $var->[-1] ? [@{ $var->[-1] }] : 0];
1720 return sub { sub { # return a double sub so that the current play_expr will return a coderef
1721 local $self_copy->{'_vars'}->{'temp deref key'} = $ref;
1722 $last->[-1] = (ref $last->[-1] ? [@{ $last->[-1] }, @_] : [@_]) if @_;
1723 return $self->play_expr($last);
1727 $self->throw('operator', "Un-implemented operation $op");
1730 ###----------------------------------------------------------------###
1733 my ($self, $str_ref, $node) = @_;
1735 my $block_name = '';
1736 if ($$str_ref =~ m{ \G (\w+ (?: :\w+)*) \s* (?! [\.\|]) }gcx
1737 || $$str_ref =~ m{ \G '(|.*?[^\\])' \s* (?! [\.\|]) }gcx
1738 || $$str_ref =~ m{ \G "(|.*?[^\\])" \s* (?! [\.\|]) }gcx
1741 ### allow for nested blocks to have nested names
1742 my @names = map {$_->[3]} grep {$_->[0] eq 'BLOCK'} @{ $self->{'_state'} };
1743 $block_name = join("/", @names, $block_name) if scalar @names;
1750 my ($self, $block_name, $node, $out_ref) = @_;
1752 ### store a named reference - but do nothing until something processes it
1753 $self->{'BLOCKS'}->{$block_name} = {
1754 _tree
=> $node->[4],
1755 name
=> $self->{'_vars'}->{'component'}->{'name'} .'/'. $block_name,
1761 sub parse_CALL
{ $DIRECTIVES->{'GET'}->[0]->(@_) }
1763 sub play_CALL
{ $DIRECTIVES->{'GET'}->[1]->(@_); return }
1766 my ($self, $str_ref) = @_;
1767 return if $$str_ref =~ m{ \G DEFAULT \s* }gcx;
1768 return $self->parse_expr($str_ref);
1772 my ($self, $str_ref) = @_;
1773 return $self->parse_expr($str_ref, {auto_quote
=> "(\\w+ (?: \\.\\w+)*) $QR_AQ_SPACE"});
1777 my ($self, $undef, $node) = @_;
1778 $self->throw(lc($node->[0]), 'Control exception', $node);
1782 my ($self, $undef, $node, $out_ref) = @_;
1787 my ($self, $str_ref) = @_;
1788 $$str_ref =~ m{ \G ([Oo][Nn] | [Oo][Ff][Ff] | [Ff][Oo][Rr][Mm][Aa][Tt]) \s* }gcx
1789 || $self->throw('parse', "Unknown DEBUG option", undef, pos($$str_ref));
1791 if ($ret->[0] eq 'format') {
1792 $$str_ref =~ m{ \G ([\"\']) (|.*?[^\\]) \1 \s* }gcxs
1793 || $self->throw('parse', "Missing format string", undef, pos($$str_ref));
1800 my ($self, $ref) = @_;
1801 if ($ref->[0] eq 'on') {
1802 delete $self->{'_debug_off'};
1803 } elsif ($ref->[0] eq 'off') {
1804 $self->{'_debug_off'} = 1;
1805 } elsif ($ref->[0] eq 'format') {
1806 $self->{'_debug_format'} = $ref->[1];
1810 sub parse_DEFAULT
{ $DIRECTIVES->{'SET'}->[0]->(@_) }
1813 my ($self, $set) = @_;
1815 my ($op, $set, $default) = @$_;
1816 next if ! defined $set;
1817 my $val = $self->play_expr($set);
1819 $default = defined($default) ? $self->play_expr($default) : '';
1820 $self->set_variable($set, $default);
1827 my ($self, $str_ref) = @_;
1828 my $ref = $self->parse_expr($str_ref);
1833 my ($self, $ident, $node) = @_;
1834 require Data
::Dumper
;
1835 local $Data::Dumper
::Sortkeys
= 1;
1836 my $info = $self->node_info($node);
1840 $out = Data
::Dumper
::Dumper
($self->play_expr($ident));
1841 $var = $info->{'text'};
1842 $var =~ s/^[+\-~=]?\s*DUMP\s+//;
1843 $var =~ s/\s*[+\-~=]?$//;
1845 my @were_never_here = (qw(template component), grep {$_ =~ $QR_PRIVATE} keys %{ $self->{'_vars'} });
1846 local @{ $self->{'_vars'} }{ @were_never_here };
1847 delete @{ $self->{'_vars'} }{ @were_never_here };
1848 $out = Data
::Dumper
::Dumper
($self->{'_vars'});
1849 $var = 'EntireStash';
1851 if ($ENV{'REQUEST_METHOD'}) {
1853 $out = "<pre>$out</pre>";
1854 $out =~ s/\$VAR1/$var/;
1855 $out = "<b>DUMP: File \"$info->{file}\" line $info->{line}</b>$out";
1857 $out =~ s/\$VAR1/$var/;
1864 my ($self, $str_ref) = @_;
1866 if ($$str_ref =~ m{ \G ([^\W\d]\w*) \s* = \s* }gcx) {
1870 my $filter = $self->parse_expr($str_ref);
1871 $filter = '' if ! defined $filter;
1873 return [$name, $filter];
1877 my ($self, $ref, $node, $out_ref) = @_;
1878 my ($name, $filter) = @$ref;
1880 return '' if ! @$filter;
1882 $self->{'FILTERS'}->{$name} = $filter if length $name;
1884 my $sub_tree = $node->[4];
1888 eval { $self->execute_tree($sub_tree, \
$out) };
1889 die $@ if $@ && ref($@) !~ /Template::Exception$/;
1891 my $var = [[undef, '~', $out], 0, '|', @$filter]; # make a temporary var out of it
1894 return $DIRECTIVES->{'GET'}->[1]->($self, $var, $node, $out_ref);
1898 my ($self, $str_ref) = @_;
1899 my $items = $self->parse_expr($str_ref);
1901 if ($$str_ref =~ m{ \G (= | [Ii][Nn]\b) \s* }gcx) {
1903 $items = $self->parse_expr($str_ref);
1905 return [$var, $items];
1909 my ($self, $ref, $node, $out_ref) = @_;
1911 ### get the items - make sure it is an arrayref
1912 my ($var, $items) = @$ref;
1914 $items = $self->play_expr($items);
1915 return '' if ! defined $items;
1917 if (ref($items) !~ /Iterator$/) {
1918 $items = $PACKAGE_ITERATOR->new($items);
1921 my $sub_tree = $node->[4];
1923 local $self->{'_vars'}->{'loop'} = $items;
1925 ### if the FOREACH tag sets a var - then nothing but the loop var gets localized
1927 my ($item, $error) = $items->get_first;
1930 $self->set_variable($var, $item);
1932 ### execute the sub tree
1933 eval { $self->execute_tree($sub_tree, $out_ref) };
1935 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
1936 if ($err->type eq 'next') {
1937 ($item, $error) = $items->get_next;
1940 last if $err->type =~ /last|break/;
1945 ($item, $error) = $items->get_next;
1947 die $error if $error && $error != 3; # Template::Constants::STATUS_DONE;
1948 ### if the FOREACH tag doesn't set a var - then everything gets localized
1951 ### localize variable access for the foreach
1952 my $swap = $self->{'_vars'};
1953 local $self->{'_vars'} = my $copy = {%$swap};
1955 ### iterate use the iterator object
1956 #foreach (my $i = $items->index; $i <= $#$vals; $items->index(++ $i)) {
1957 my ($item, $error) = $items->get_first;
1960 if (ref($item) eq 'HASH') {
1961 @$copy{keys %$item} = values %$item;
1964 ### execute the sub tree
1965 eval { $self->execute_tree($sub_tree, $out_ref) };
1967 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
1968 if ($err->type eq 'next') {
1969 ($item, $error) = $items->get_next;
1972 last if $err->type =~ /last|break/;
1977 ($item, $error) = $items->get_next;
1979 die $error if $error && $error != 3; # Template::Constants::STATUS_DONE;
1986 my ($self, $str_ref) = @_;
1987 my $ref = $self->parse_expr($str_ref);
1988 $self->throw('parse', "Missing variable name", undef, pos($$str_ref)) if ! defined $ref;
1993 my ($self, $ident, $node) = @_;
1994 my $var = $self->play_expr($ident);
1995 return (! defined $var) ? $self->undefined_get($ident, $node) : $var;
1999 my ($self, $str_ref) = @_;
2000 return $self->parse_expr($str_ref);
2004 my ($self, $var, $node, $out_ref) = @_;
2006 my $val = $self->play_expr($var);
2008 my $body_ref = $node->[4] ||= [];
2009 $self->execute_tree($body_ref, $out_ref);
2013 while ($node = $node->[5]) { # ELSE, ELSIF's
2014 if ($node->[0] eq 'ELSE') {
2015 my $body_ref = $node->[4] ||= [];
2016 $self->execute_tree($body_ref, $out_ref);
2019 my $var = $node->[3];
2020 my $val = $self->play_expr($var);
2022 my $body_ref = $node->[4] ||= [];
2023 $self->execute_tree($body_ref, $out_ref);
2030 sub parse_INCLUDE
{ $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
2033 my ($self, $str_ref, $node, $out_ref) = @_;
2035 ### localize the swap
2036 my $swap = $self->{'_vars'};
2037 local $self->{'_vars'} = {%$swap};
2039 ### localize the blocks
2040 my $blocks = $self->{'BLOCKS'};
2041 local $self->{'BLOCKS'} = {%$blocks};
2043 my $str = $DIRECTIVES->{'PROCESS'}->[1]->($self, $str_ref, $node, $out_ref);
2048 sub parse_INSERT
{ $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
2051 my ($self, $var, $node, $out_ref) = @_;
2052 my ($names, $args) = @$var;
2054 foreach my $name (@$names) {
2055 my $filename = $self->play_expr($name);
2056 $$out_ref .= $self->_insert($filename);
2063 my ($self, $str_ref, $node) = @_;
2065 my $name = $self->parse_expr($str_ref, {auto_quote
=> "(\\w+) $QR_AQ_NOTDOT"});
2066 $self->throw('parse', "Missing macro name", undef, pos($$str_ref)) if ! defined $name;
2068 $name = [ $name, 0 ];
2072 if ($$str_ref =~ m{ \G \( \s* }gcx) {
2073 $args = $self->parse_args($str_ref, {positional_only
=> 1});
2074 $$str_ref =~ m{ \G \) \s* }gcx || $self->throw('parse.missing', "Missing close ')'", undef, pos($$str_ref));
2077 $node->[6] = 1; # set a flag to keep parsing
2078 return [$name, $args];
2082 my ($self, $ref, $node, $out_ref) = @_;
2083 my ($name, $args) = @$ref;
2085 ### get the sub tree
2086 my $sub_tree = $node->[4];
2087 if (! $sub_tree || ! $sub_tree->[0]) {
2088 $self->set_variable($name, undef);
2090 } elsif ($sub_tree->[0]->[0] eq 'BLOCK') {
2091 $sub_tree = $sub_tree->[0]->[4];
2094 my $self_copy = $self;
2095 eval {require Scalar
::Util
; Scalar
::Util
::weaken
($self_copy)};
2097 ### install a closure in the stash that will handle the macro
2098 $self->set_variable($name, sub {
2100 my $copy = $self_copy->{'_vars'};
2101 local $self_copy->{'_vars'}= {%$copy};
2103 ### prevent recursion
2104 local $self_copy->{'_macro_recurse'} = $self_copy->{'_macro_recurse'} || 0;
2105 $self_copy->throw('macro_recurse', "MAX_MACRO_RECURSE $MAX_MACRO_RECURSE reached")
2106 if ++$self_copy->{'_macro_recurse'} > ($self_copy->{'MAX_MACRO_RECURSE'} || $MAX_MACRO_RECURSE);
2110 my $named = pop(@_) if $_[-1] && UNIVERSAL
::isa
($_[-1],'HASH') && $#_ > $#$args;
2111 my @positional = @_;
2112 foreach my $var (@$args) {
2113 $self_copy->set_variable($var, shift(@positional));
2115 foreach my $name (sort keys %$named) {
2116 $self_copy->set_variable([$name, 0], $named->{$name});
2119 ### finally - run the sub tree
2121 $self_copy->execute_tree($sub_tree, \
$out);
2129 my ($self, $hash) = @_;
2131 if ($self->{'_top_level'}) {
2132 $ref = $self->{'_vars'}->{'template'} ||= {};
2134 $ref = $self->{'_vars'}->{'component'} ||= {};
2136 foreach my $key (keys %$hash) {
2137 next if $key eq 'name' || $key eq 'modtime';
2138 $ref->{$key} = $hash->{$key};
2143 sub parse_PERL
{ shift-
>{'_in_perl'} = 1; return }
2146 my ($self, $info, $node, $out_ref) = @_;
2147 $self->throw('perl', 'EVAL_PERL not set') if ! $self->{'EVAL_PERL'};
2149 ### fill in any variables
2150 my $perl = $node->[4] || return;
2152 $self->execute_tree($perl, \
$out);
2153 $out = $1 if $out =~ /^(.+)$/s; # blatant untaint - shouldn't use perl anyway
2158 package CGI
::Ex
::Template
::Perl
;
2160 my $context = $self->context;
2161 my $stash = $context->stash;
2163 ### setup a fake handle
2165 tie
*PERLOUT
, $CGI::Ex
::Template
::PACKAGE_PERL_HANDLE
, $out_ref;
2166 my $old_fh = select PERLOUT
;
2171 ### put the handle back
2179 $self->throw('undef', $err) if ref($err) !~ /Template::Exception$/;
2187 my ($self, $str_ref) = @_;
2188 my $info = [[], []];
2189 while (defined(my $filename = $self->parse_expr($str_ref, {
2190 auto_quote
=> "($QR_FILENAME | \\w+ (?: :\\w+)* ) $QR_AQ_SPACE",
2192 push @{$info->[0]}, $filename;
2193 last if $$str_ref !~ m{ \G \+ \s* $QR_COMMENTS }gcxo;
2196 ### we can almost use parse_args - except we allow for nested key names (foo.bar) here
2198 my $mark = pos $$str_ref;
2199 if ($$str_ref =~ m{ \G $QR_DIRECTIVE (?: \s+ | (?: \s* $QR_COMMENTS (?: ;|[+=~-]?$self->{'_end_tag'}))) }gcxo
) {
2200 pos($$str_ref) = $mark;
2201 last if $DIRECTIVES->{$self->{'ANYCASE'} ? uc $1 : $1}; # looks like a directive - we are done
2203 if ($$str_ref =~ m{ \G [+=~-]? $self->{'_end_tag'} }gcx
) {
2204 pos($$str_ref) = $mark;
2208 my $var = $self->parse_expr($str_ref);
2210 last if ! defined $var;
2211 if ($$str_ref !~ m{ \G = >? \s* }gcx) {
2212 $self->throw('parse.missing.equals', 'Missing equals while parsing args', undef, pos($$str_ref));
2215 my $val = $self->parse_expr($str_ref);
2216 push @{$info->[1]}, [$var, $val];
2217 $$str_ref =~ m{ \G , \s* $QR_COMMENTS }gcxo if $val;
2224 my ($self, $info, $node, $out_ref) = @_;
2226 my ($files, $args) = @$info;
2231 my $val = $self->play_expr($_->[1]);
2232 if (ref($key) && @$key == 2 && $key->[0] eq 'import' && UNIVERSAL
::isa
($val, 'HASH')) { # import ?! - whatever
2233 foreach my $key (keys %$val) {
2234 $self->set_variable([$key,0], $val->{$key});
2238 $self->set_variable($key, $val);
2241 ### iterate on any passed block or filename
2242 foreach my $ref (@$files) {
2243 next if ! defined $ref;
2244 my $filename = $self->play_expr($ref);
2245 my $out = ''; # have temp item to allow clear to correctly clear
2247 ### normal blocks or filenames
2248 if (! ref $filename) {
2249 eval { $self->_process($filename, $self->{'_vars'}, \
$out) }; # restart the swap - passing it our current stash
2251 ### allow for $template which is used in some odd instances
2253 $self->throw('process', "Unable to process document $filename") if $ref->[0] ne 'template';
2254 $self->throw('process', "Recursion detected in $node->[0] \$template") if $self->{'_process_dollar_template'};
2255 local $self->{'_process_dollar_template'} = 1;
2256 local $self->{'_vars'}->{'component'} = my $doc = $filename;
2257 return if ! $doc->{'_tree'};
2259 ### execute and trim
2260 eval { $self->execute_tree($doc->{'_tree'}, \
$out) };
2261 if ($self->{'TRIM'}) {
2262 $out =~ s{ \s+ $ }{}x;
2263 $out =~ s{ ^ \s+ }{}x;
2266 ### handle exceptions
2268 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2269 $err->doc($doc) if $doc && $err->can('doc') && ! $err->doc;
2274 ### append any output
2277 die $err if ref($err) !~ /Template::Exception$/ || $err->type !~ /return/;
2285 my ($self, $info, $node, $out_ref) = @_;
2286 $self->throw('perl', 'EVAL_PERL not set') if ! $self->{'EVAL_PERL'};
2288 ### fill in any variables
2289 my $tree = $node->[4] || return;
2291 $self->execute_tree($tree, \
$perl);
2292 $perl = $1 if $perl =~ /^(.+)$/s; # blatant untaint - shouldn't use perl anyway
2298 package CGI
::Ex
::Template
::Perl
;
2300 my $context = $self->context;
2301 my $stash = $context->stash;
2308 $$out_ref .= $output;
2311 $self->throw('undef', $err) if ref($err) !~ /Template::Exception$/;
2319 my ($self, $str_ref, $node, $initial_op, $initial_var) = @_;
2324 if ($$str_ref =~ m{ \G $QR_DIRECTIVE }gcx # find a word
2325 && ((pos($$str_ref) -= length($1)) || 1) # always revert
2326 && $DIRECTIVES->{$self->{'ANYCASE'} ? uc $1 : $1}) { # make sure its a directive - if so set up capturing
2327 $node->[6] = 1; # set a flag to keep parsing
2328 my $val = $node->[4] ||= []; # setup storage
2329 return [[$initial_op, $initial_var, $val]];
2330 } else { # get a normal variable
2331 return [[$initial_op, $initial_var, $self->parse_expr($str_ref)]];
2336 my $set = $self->parse_expr($str_ref);
2337 last if ! defined $set;
2339 if ($$str_ref =~ m{ \G ($QR_OP_ASSIGN) >? \s* }gcx) {
2341 if ($$str_ref =~ m{ \G $QR_DIRECTIVE }gcx # find a word
2342 && ((pos($$str_ref) -= length($1)) || 1) # always revert
2343 && $DIRECTIVES->{$self->{'ANYCASE'} ? uc $1 : $1}) { # make sure its a directive - if so set up capturing
2344 $node->[6] = 1; # set a flag to keep parsing
2345 my $val = $node->[4] ||= []; # setup storage
2346 push @SET, [$op, $set, $val];
2348 } else { # get a normal variable
2349 push @SET, [$op, $set, $self->parse_expr($str_ref)];
2352 push @SET, ['=', $set, undef];
2359 my ($self, $set, $node) = @_;
2361 my ($op, $set, $val) = @$_;
2362 if (! defined $val) { # not defined
2364 } elsif ($node->[4] && $val == $node->[4]) { # a captured directive
2365 my $sub_tree = $node->[4];
2366 $sub_tree = $sub_tree->[0]->[4] if $sub_tree->[0] && $sub_tree->[0]->[0] eq 'BLOCK';
2368 $self->execute_tree($sub_tree, \
$val);
2369 } else { # normal var
2370 $val = $self->play_expr($val);
2373 if ($OP_DISPATCH->{$op}) {
2375 $val = $OP_DISPATCH->{$op}->($self->play_expr($set), $val);
2378 $self->set_variable($set, $val);
2383 sub parse_SWITCH
{ $DIRECTIVES->{'GET'}->[0]->(@_) }
2386 my ($self, $var, $node, $out_ref) = @_;
2388 my $val = $self->play_expr($var);
2389 $val = '' if ! defined $val;
2390 ### $node->[4] is thrown away
2393 while ($node = $node->[5]) { # CASES
2394 my $var = $node->[3];
2395 if (! defined $var) {
2396 $default = $node->[4];
2400 my $val2 = $self->play_expr($var);
2401 $val2 = [$val2] if ! UNIVERSAL
::isa
($val2, 'ARRAY');
2402 for my $test (@$val2) { # find matching values
2403 next if ! defined $val && defined $test;
2404 next if defined $val && ! defined $test;
2405 if ($val ne $test) { # check string-wise first - then numerical
2406 next if $val !~ m{ ^ -? $QR_NUM $ }ox;
2407 next if $test !~ m{ ^ -? $QR_NUM $ }ox;
2408 next if $val != $test;
2411 my $body_ref = $node->[4] ||= [];
2412 $self->execute_tree($body_ref, $out_ref);
2418 $self->execute_tree($default, $out_ref);
2425 my ($self, $str_ref, $node) = @_;
2426 my $name = $self->parse_expr($str_ref, {auto_quote
=> "(\\w+ (?: \\.\\w+)*) $QR_AQ_SPACE"});
2427 $self->throw('parse.missing', "Missing name in THROW", $node, pos($$str_ref)) if ! $name;
2428 my $args = $self->parse_args($str_ref);
2429 return [$name, $args];
2433 my ($self, $ref, $node) = @_;
2434 my ($name, $args) = @$ref;
2435 $name = $self->play_expr($name);
2436 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2437 $self->throw($name, \
@args, $node);
2441 my ($self, $foo, $node, $out_ref) = @_;
2444 my $body_ref = $node->[4];
2445 eval { $self->execute_tree($body_ref, \
$out) };
2448 if (! $node->[5]) { # no catch or final
2449 if (! $err) { # no final block and no error
2453 $self->throw('parse.missing', "Missing CATCH block", $node);
2456 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2457 if ($err->type =~ /stop|return/) {
2463 ### loop through the nested catch and final blocks
2466 my $type = $err ? $err->type : '';
2468 while ($node = $node->[5]) { # CATCH
2469 if ($node->[0] eq 'FINAL') {
2470 $final = $node->[4];
2474 my $name = $self->play_expr($node->[3]);
2475 $name = '' if ! defined $name || lc($name) eq 'default';
2476 if ($type =~ / ^ \Q$name\E \b /x
2477 && (! defined($last_found) || length($last_found) < length($name))) { # more specific wins
2478 $catch_body_ref = $node->[4] || [];
2479 $last_found = $name;
2483 ### play the best catch block
2485 if (! $catch_body_ref) {
2489 local $self->{'_vars'}->{'error'} = $err;
2490 local $self->{'_vars'}->{'e'} = $err;
2491 eval { $self->execute_tree($catch_body_ref, \
$out) };
2499 $self->execute_tree($final, \
$out) if $final;
2507 my $ref = $DIRECTIVES->{'IF'}->[0]->(@_);
2508 return [[undef, '!', $ref], 0];
2511 sub play_UNLESS
{ return $DIRECTIVES->{'IF'}->[1]->(@_) }
2514 my ($self, $str_ref) = @_;
2517 my $mark = pos $$str_ref;
2518 if (defined(my $_var = $self->parse_expr($str_ref, {auto_quote
=> "(\\w+) $QR_AQ_NOTDOT"}))
2519 && ($$str_ref =~ m{ \G = >? \s* $QR_COMMENTS }gcxo # make sure there is assignment
2520 || ((pos $$str_ref = $mark) && 0)) # otherwise we need to rollback
2525 my $module = $self->parse_expr($str_ref, {auto_quote
=> "(\\w+ (?: (?:\\.|::) \\w+)*) $QR_AQ_NOTDOT"});
2526 $self->throw('parse', "Missing plugin name while parsing $$str_ref", undef, pos($$str_ref)) if ! defined $module;
2527 $module =~ s/\./::/g;
2530 my $open = $$str_ref =~ m{ \G \( \s* $QR_COMMENTS }gcxo;
2531 $args = $self->parse_args($str_ref, {is_parened
=> $open});
2534 $$str_ref =~ m{ \G \) \s* $QR_COMMENTS }gcxo || $self->throw('parse.missing', "Missing close ')'", undef, pos($$str_ref));
2537 return [$var, $module, $args];
2541 my ($self, $ref, $node, $out_ref) = @_;
2542 my ($var, $module, $args) = @$ref;
2544 ### get the stash storage location - default to the module
2545 $var = $module if ! defined $var;
2546 my @var = map {($_, 0, '.')} split /(?:\.|::)/, $var;
2547 pop @var; # remove the trailing '.'
2549 ### look for a plugin_base
2550 my $BASE = $self->{'PLUGIN_BASE'} || 'Template::Plugin'; # I'm not maintaining plugins - leave that to TT
2553 foreach my $base (ref($BASE) eq 'ARRAY' ? @$BASE : $BASE) {
2554 my $package = $self->{'PLUGINS'}->{$module} ? $self->{'PLUGINS'}->{$module}
2555 : $self->{'PLUGIN_FACTORY'}->{$module} ? $self->{'PLUGIN_FACTORY'}->{$module}
2556 : "${base}::${module}";
2557 my $require = "$package.pm";
2558 $require =~ s
|::|/|g
;
2560 ### try and load the module - fall back to bare module if allowed
2561 if ($self->{'PLUGIN_FACTORY'}->{$module} || eval {require $require}) {
2562 my $shape = $package->load;
2563 my $context = $self->context;
2564 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2565 $obj = $shape->new($context, @args);
2566 } elsif (lc($module) eq 'iterator') { # use our iterator if none found (TT's works just fine)
2567 $obj = $PACKAGE_ITERATOR->new($args ? $self->play_expr($args->[0]) : []);
2568 } elsif (my @packages = grep {lc($package) eq lc($_)} @{ $self->list_plugins({base
=> $base}) }) {
2569 foreach my $package (@packages) {
2570 my $require = "$package.pm";
2571 $require =~ s
|::|/|g
;
2572 eval {require $require} || next;
2573 my $shape = $package->load;
2574 my $context = $self->context;
2575 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2576 $obj = $shape->new($context, @args);
2578 } elsif ($self->{'LOAD_PERL'}) {
2579 my $require = "$module.pm";
2580 $require =~ s
|::|/|g
;
2581 if (eval {require $require}) {
2582 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2583 $obj = $module->new(@args);
2587 if (! defined $obj) {
2588 my $err = "$module: plugin not found";
2589 $self->throw('plugin', $err);
2593 $self->set_variable(\
@var, $obj);
2599 my ($self, $var, $node, $out_ref) = @_;
2600 return '' if ! defined $var;
2602 my $sub_tree = $node->[4];
2604 ### iterate use the iterator object
2605 my $count = $WHILE_MAX;
2606 while (--$count > 0) {
2608 $self->play_expr($var) || last;
2610 ### execute the sub tree
2611 eval { $self->execute_tree($sub_tree, $out_ref) };
2613 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
2614 next if $err->type =~ /next/;
2615 last if $err->type =~ /last|break/;
2620 die "WHILE loop terminated (> $WHILE_MAX iterations)\n" if ! $count;
2625 sub parse_WRAPPER
{ $DIRECTIVES->{'INCLUDE'}->[0]->(@_) }
2628 my ($self, $var, $node, $out_ref) = @_;
2629 my $sub_tree = $node->[4] || return;
2631 my ($names, $args) = @$var;
2634 $self->execute_tree($sub_tree, \
$out);
2636 foreach my $name (reverse @$names) {
2637 local $self->{'_vars'}->{'content'} = $out;
2639 $DIRECTIVES->{'INCLUDE'}->[1]->($self, [[$name], $args], $node, \
$out);
2646 ###----------------------------------------------------------------###
2650 $self->{'_vars'} = shift if $#_ == 0;
2651 return $self->{'_vars'} ||= {};
2654 sub include_filename
{
2655 my ($self, $file) = @_;
2656 if ($file =~ m
|^/|) {
2657 $self->throw('file', "$file absolute paths are not allowed (set ABSOLUTE option)") if ! $self->{'ABSOLUTE'};
2658 return $file if -e
$file;
2659 } elsif ($file =~ m{(^|/)\.\./}) {
2660 $self->throw('file', "$file relative paths are not allowed (set RELATIVE option)") if ! $self->{'RELATIVE'};
2661 return $file if -e
$file;
2664 my $paths = $self->{'INCLUDE_PATHS'} ||= do {
2665 # TT does this everytime a file is looked up - we are going to do it just in time - the first time
2666 my $paths = $self->{'INCLUDE_PATH'} || $self->throw('file', "INCLUDE_PATH not set");
2667 $paths = $paths->() if UNIVERSAL
::isa
($paths, 'CODE');
2668 $paths = $self->split_paths($paths) if ! UNIVERSAL
::isa
($paths, 'ARRAY');
2669 $paths; # return of the do
2671 foreach my $path (@$paths) {
2672 return "$path/$file" if -e
"$path/$file";
2675 $self->throw('file', "$file: not found");
2679 my ($self, $path) = @_;
2680 return $path if ref $path;
2681 my $delim = $self->{'DELIMITER'} || ':';
2682 $delim = ($delim eq ':' && $^O eq 'MSWin32') ? qr
|:(?!/)| : qr
|\Q
$delim\E
|;
2683 return [split $delim, $path];
2687 my ($self, $file) = @_;
2688 return $self->slurp($self->include_filename($file));
2692 my ($self, $file) = @_;
2694 open(FH
, "<$file") || $self->throw('file', "$file couldn't be opened: $!");
2695 read FH
, my $txt, -s
$file;
2700 sub process_simple
{
2702 my $in = shift || die "Missing input";
2703 my $swap = shift || die "Missing variable hash";
2704 my $out = shift || die "Missing output string ref";
2707 delete $self->{'_debug_off'};
2708 delete $self->{'_debug_format'};
2709 local $self->{'_start_top_level'} = 1;
2710 $self->_process($in, $swap, $out);
2713 if ($err->type !~ /stop|return|next|last|break/) {
2714 $self->{'error'} = $err;
2722 my ($self, $in, $swap, $out, @ARGS) = @_;
2723 delete $self->{'error'};
2726 $args = ($#ARGS == 0 && UNIVERSAL
::isa
($ARGS[0], 'HASH')) ? {%{$ARGS[0]}} : {@ARGS} if scalar @ARGS;
2727 $self->DEBUG("set binmode\n") if $DEBUG && $args->{'binmode'}; # holdover for TT2 tests
2732 if (UNIVERSAL
::isa
($in, 'SCALAR')) { # reference to a string
2734 } elsif (UNIVERSAL
::isa
($in, 'CODE')) {
2736 $content = \
$content;
2737 } else { # should be a file handle
2740 $content = \
$content;
2743 ### should be a filename
2748 ### prepare block localization
2749 my $blocks = $self->{'BLOCKS'} ||= {};
2756 ### localize the stash
2758 my $var1 = $self->{'_vars'} ||= {};
2759 my $var2 = $self->{'VARIABLES'} || $self->{'PRE_DEFINE'} || {};
2760 $var1->{'global'} ||= {}; # allow for the "global" namespace - that continues in between processing
2761 my $copy = {%$var2, %$var1, %$swap};
2762 local $copy->{'template'};
2764 local $self->{'BLOCKS'} = $blocks = {%$blocks}; # localize blocks - but save a copy to possibly restore
2766 delete $self->{'_debug_off'};
2767 delete $self->{'_debug_format'};
2769 ### handle pre process items that go before every document
2770 if ($self->{'PRE_PROCESS'}) {
2771 foreach my $name (@{ $self->split_paths($self->{'PRE_PROCESS'}) }) {
2773 $self->_process($name, $copy, \
$out);
2774 $output = $out . $output;
2778 ### handle the process config - which loads a template in place of the real one
2779 if (exists $self->{'PROCESS'}) {
2780 ### load the meta data for the top document
2781 my $doc = $self->load_parsed_tree($content) || {};
2782 my $meta = ($doc->{'_tree'} && ref($doc->{'_tree'}->[0]) && $doc->{'_tree'}->[0]->[0] eq 'META')
2783 ? $doc->{'_tree'}->[0]->[3] : {};
2785 $copy->{'template'} = $doc;
2786 @{ $doc }{keys %$meta} = values %$meta;
2788 ### process any other templates
2789 foreach my $name (@{ $self->split_paths($self->{'PROCESS'}) }) {
2790 next if ! length $name;
2791 $self->_process($name, $copy, \
$output);
2794 ### handle "normal" content
2796 local $self->{'_start_top_level'} = 1;
2797 $self->_process($content, $copy, \
$output);
2801 ### handle post process items that go after every document
2802 if ($self->{'POST_PROCESS'}) {
2803 foreach my $name (@{ $self->split_paths($self->{'POST_PROCESS'}) }) {
2804 $self->_process($name, $copy, \
$output);
2810 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2811 if ($err->type !~ /stop|return|next|last|break/) {
2812 $self->{'error'} = $err;
2819 ### clear blocks as asked (AUTO_RESET) defaults to on
2820 $self->{'BLOCKS'} = $blocks if exists($self->{'AUTO_RESET'}) && ! $self->{'AUTO_RESET'};
2822 ### send the content back out
2823 $out ||= $self->{'OUTPUT'};
2825 if (UNIVERSAL
::isa
($out, 'CODE')) {
2827 } elsif (UNIVERSAL
::can
($out, 'print')) {
2828 $out->print($output);
2829 } elsif (UNIVERSAL
::isa
($out, 'SCALAR')) { # reference to a string
2831 } elsif (UNIVERSAL
::isa
($out, 'ARRAY')) {
2832 push @$out, $output;
2833 } else { # should be a file handle
2836 } elsif ($out) { # should be a filename
2838 if ($out =~ m
|^/|) {
2839 if (! $self->{'ABSOLUTE'}) {
2840 $self->{'error'} = $self->throw('file', "ABSOLUTE paths disabled");
2844 } elsif ($out =~ m
|^\
.\
.?/|) {
2845 if (! $self->{'RELATIVE'}) {
2846 $self->{'error'} = $self->throw('file', "RELATIVE paths disabled");
2851 if (! $self->{'OUTPUT_PATH'}) {
2852 $self->{'error'} = $self->throw('file', "OUTPUT_PATH not set");
2854 $file = $self->{'OUTPUT_PATH'} . '/' . $out;
2859 if (open FH
, ">$file") {
2860 if (my $bm = $args->{'binmode'}) {
2861 if (+$bm == 1) { binmode FH
}
2862 else { binmode FH
, $bm }
2867 $self->{'error'} = $self->throw('file', "$out couldn't be opened for writing: $!");
2874 return if $self->{'error'};
2878 sub error
{ shift-
>{'error'} }
2882 print STDERR
"DEBUG: ", @_;
2885 ###----------------------------------------------------------------###
2888 my ($self, $type, $info, $node) = @_;
2889 return $type if ref($type) =~ /Template::Exception$/;
2890 if (ref($info) eq 'ARRAY') {
2891 my $hash = ref($info->[-1]) eq 'HASH' ? pop(@$info) : {};
2892 if (@$info >= 2 || scalar keys %$hash) {
2894 $hash->{$_} = $info->[$_] for 0 .. $#$info;
2895 $hash->{'args'} = $info;
2897 } elsif (@$info == 1) {
2904 return $PACKAGE_EXCEPTION->new($type, $info, $node);
2907 sub throw
{ die shift-
>exception(@_) }
2911 return bless {_template
=> $self}, $PACKAGE_CONTEXT; # a fake context
2915 my ($self, $ident, $node) = @_;
2916 return $self->{'UNDEFINED_GET'}->($self, $ident, $node) if $self->{'UNDEFINED_GET'};
2921 my ($self, $ident) = @_;
2922 return $self->{'UNDEFINED_ANY'}->($self, $ident) if $self->{'UNDEFINED_ANY'};
2928 return $self->{'_filters'} ||= eval { require Template
::Filters
; $Template::Filters
::FILTERS
} || {};
2933 my $args = shift || {};
2934 my $base = $args->{'base'} || '';
2936 return $self->{'_plugins'}->{$base} ||= do {
2940 my @dirs = grep {-d
$_} map {"$_/$base"} @INC;
2942 foreach my $dir (@dirs) {
2944 File
::Find
::find
(sub {
2945 my $mod = $base .'/'. ($File::Find
::name
=~ m
|^ $dir / (.*\w
) \
.pm
$|x
? $1 : return);
2947 push @plugins, $mod;
2951 \
@plugins; # return of the do
2956 my ($self, $node) = @_;
2957 my $info = $self->node_info($node);
2958 my $format = $self->{'_debug_format'} || $self->{'DEBUG_FORMAT'} || "\n## \$file line \$line : [% \$text %] ##\n";
2959 $format =~ s{\$(file|line|text)}{$info->{$1}}g
;
2964 my ($self, $node) = @_;
2965 my $doc = $self->{'_vars'}->{'component'};
2967 my $j = $node->[2] || return ''; # META can be 0
2968 $doc->{'_content'} ||= do { my $s = $self->slurp($doc->{'_filename'}) ; \
$s };
2969 my $s = substr(${ $doc->{'_content'} }, $i, $j - $i);
2973 file
=> $doc->{'name'},
2974 line
=> $self->get_line_number_by_index($doc, $i),
2979 sub get_line_number_by_index
{
2980 my ($self, $doc, $index) = @_;
2981 ### get the line offsets for the doc
2982 my $lines = $doc->{'line_offsets'} ||= do {
2983 $doc->{'_content'} ||= do { my $s = $self->slurp($doc->{'_filename'}) ; \
$s };
2987 $i = index(${ $doc->{'_content'} }, "\n", $i) + 1;
2993 ### binary search them (this is fast even on big docs)
2994 return $#$lines + 1 if $index > $lines->[-1];
2995 my ($i, $j) = (0, $#$lines);
2997 return $i + 1 if abs($i - $j) <= 1;
2998 my $k = int(($i + $j) / 2);
2999 $j = $k if $lines->[$k] >= $index;
3000 $i = $k if $lines->[$k] <= $index;
3004 ###----------------------------------------------------------------###
3005 ### long virtual methods or filters
3006 ### many of these vmethods have used code from Template/Stash.pm to
3007 ### assure conformance with the TT spec.
3009 sub define_vmethod
{
3010 my ($self, $type, $name, $sub) = @_;
3011 if ( $type =~ /scalar|item/i) { $SCALAR_OPS->{$name} = $sub }
3012 elsif ($type =~ /array|list/i ) { $LIST_OPS->{ $name} = $sub }
3013 elsif ($type =~ /hash/i ) { $HASH_OPS->{ $name} = $sub }
3014 elsif ($type =~ /filter/i ) { $FILTER_OPS->{$name} = $sub }
3016 die "Invalid type vmethod type $type";
3021 sub vmethod_as_scalar
{
3022 my $str = shift; $str = '' if ! defined $str;
3023 my $pat = shift; $pat = '%s' if ! defined $pat;
3025 return @_ ? sprintf($pat, $_[0], $str)
3026 : sprintf($pat, $str);
3029 sub vmethod_as_list
{
3030 my $ref = shift || return '';
3031 my $pat = shift; $pat = '%s' if ! defined $pat;
3032 my $sep = shift; $sep = ' ' if ! defined $sep;
3034 return @_ ? join($sep, map {sprintf $pat, $_[0], $_} @$ref)
3035 : join($sep, map {sprintf $pat, $_} @$ref);
3038 sub vmethod_as_hash
{
3039 my $ref = shift || return '';
3040 my $pat = shift; $pat = "%s\t%s" if ! defined $pat;
3041 my $sep = shift; $sep = "\n" if ! defined $sep;
3043 return ! @_ ? join($sep, map {sprintf $pat, $_, $ref->{$_}} sort keys %$ref)
3044 : @_ == 1 ? join($sep, map {sprintf $pat, $_[0], $_, $ref->{$_}} sort keys %$ref) # don't get to pick - it applies to the key
3045 : join($sep, map {sprintf $pat, $_[0], $_, $_[1], $ref->{$_}} sort keys %$ref);
3050 my $size = shift || 1;
3052 if ($size < 0) { # chunk from the opposite end
3053 $str = reverse $str;
3055 unshift(@list, scalar reverse $1) while $str =~ /( .{$size} | .+ )/xg;
3057 push(@list, $1) while $str =~ /( .{$size} | .+ )/xg;
3062 sub vmethod_indent
{
3063 my $str = shift; $str = '' if ! defined $str;
3064 my $pre = shift; $pre = 4 if ! defined $pre;
3065 $pre = ' ' x
$pre if $pre =~ /^\d+$/;
3066 $str =~ s/^/$pre/mg;
3070 sub vmethod_format
{
3071 my $str = shift; $str = '' if ! defined $str;
3072 my $pat = shift; $pat = '%s' if ! defined $pat;
3074 return join "\n", map{ sprintf $pat, $_[0], $_ } split(/\n/, $str);
3076 return join "\n", map{ sprintf $pat, $_ } split(/\n/, $str);
3080 sub vmethod_list_hash
{
3081 my ($hash, $what) = @_;
3082 $what = 'pairs' if ! $what || $what !~ /^(keys|values|each|pairs)$/;
3083 return $HASH_OPS->{$what}->($hash);
3088 my ($str, $pat, $global) = @_;
3089 return [] if ! defined $str || ! defined $pat;
3090 my @res = $global ? ($str =~ /$pat/g) : ($str =~ /$pat/);
3091 return @res ? \
@res : '';
3095 my ($list, $field) = @_;
3096 return defined($field)
3097 ? [map {$_->[0]} sort {$a->[1] <=> $b->[1]} map {[$_, (ref $_ eq 'HASH' ? $_->{$field}
3098 : UNIVERSAL
::can
($_, $field) ? $_->$field()
3100 : [sort {$a <=> $b} @$list];
3103 sub vmethod_repeat
{
3104 my ($str, $n, $join) = @_;
3105 return '' if ! defined $str || ! length $str;
3106 $n = 1 if ! defined($n) || ! length $n;
3107 $join = '' if ! defined $join;
3108 return join $join, ($str) x
$n;
3111 ### This method is a combination of my submissions along
3112 ### with work from Andy Wardley, Sergey Martynoff, Nik Clayton, and Josh Rosenbaum
3113 sub vmethod_replace
{
3114 my ($text, $pattern, $replace, $global) = @_;
3115 $text = '' unless defined $text;
3116 $pattern = '' unless defined $pattern;
3117 $replace = '' unless defined $replace;
3118 $global = 1 unless defined $global;
3120 my ($chunk, $start, $end) = @_;
3121 $chunk =~ s
{ \\(\\|\
$) | \
$ (\d
+) }{
3123 : ($2 > $#$start || $2 == 0) ? ''
3124 : substr($text, $start->[$2], $end->[$2] - $start->[$2]);
3129 $text =~ s{$pattern}{ $expand->($replace, [@-], [@+]) }eg;
3131 $text =~ s{$pattern}{ $expand->($replace, [@-], [@+]) }e;
3137 my ($list, $field) = @_;
3138 return defined($field)
3139 ? [map {$_->[0]} sort {$a->[1] cmp $b->[1]} map {[$_, lc(ref $_ eq 'HASH' ? $_->{$field}
3140 : UNIVERSAL
::can
($_, $field) ? $_->$field()
3142 : [map {$_->[0]} sort {$a->[1] cmp $b->[1]} map {[$_, lc $_]} @$list ]; # case insensitive
3145 sub vmethod_splice
{
3146 my ($ref, $i, $len, @replace) = @_;
3147 @replace = @{ $replace[0] } if @replace == 1 && ref $replace[0] eq 'ARRAY';
3149 return [splice @$ref, $i || 0, $len, @replace];
3150 } elsif (defined $i) {
3151 return [splice @$ref, $i];
3153 return [splice @$ref];
3158 my ($str, $pat, $lim) = @_;
3159 $str = '' if ! defined $str;
3160 if (defined $lim) { return defined $pat ? [split $pat, $str, $lim] : [split ' ', $str, $lim] }
3161 else { return defined $pat ? [split $pat, $str ] : [split ' ', $str ] }
3164 sub vmethod_substr
{
3165 my ($str, $i, $len, $replace) = @_;
3167 return substr($str, $i) if ! defined $len;
3168 return substr($str, $i, $len) if ! defined $replace;
3169 substr($str, $i, $len, $replace);
3175 utf8
::encode
($str) if defined &utf8
::encode
;
3176 $str =~ s/([^A-Za-z0-9\-_.!~*\'()])/sprintf('%%%02X', ord($1))/eg;
3181 my $context = shift;
3184 ### prevent recursion
3185 my $t = $context->_template;
3186 local $t->{'_eval_recurse'} = $t->{'_eval_recurse'} || 0;
3187 $context->throw('eval_recurse', "MAX_EVAL_RECURSE $MAX_EVAL_RECURSE reached")
3188 if ++$t->{'_eval_recurse'} > ($t->{'MAX_EVAL_RECURSE'} || $MAX_EVAL_RECURSE);
3192 return $context->process(\
$text);
3196 sub filter_redirect
{
3197 my ($context, $file, $options) = @_;
3198 my $path = $context->config->{'OUTPUT_PATH'} || $context->throw('redirect', 'OUTPUT_PATH is not set');
3199 $context->throw('redirect', 'Invalid filename - cannot include "/../"')
3200 if $file =~ m{(^|/)\.\./};
3206 File
::Path
::mkpath
($path) || $context->throw('redirect', "Couldn't mkpath \"$path\": $!");
3209 open (FH
, ">$path/$file") || $context->throw('redirect', "Couldn't open \"$file\": $!");
3210 if (my $bm = (! $options) ? 0 : ref($options) ? $options->{'binmode'} : $options) {
3211 if (+$bm == 1) { binmode FH
}
3212 else { binmode FH
, $bm}
3220 ###----------------------------------------------------------------###
3223 my $obj = UNIVERSAL
::isa
($_[0], __PACKAGE__
) ? shift : __PACKAGE__-
>new;
3225 require Data
::Dumper
;
3226 return Data
::Dumper
::Dumper
($obj->parse_tree(\
$str));
3229 sub dump_parse_expr
{
3230 my $obj = UNIVERSAL
::isa
($_[0], __PACKAGE__
) ? shift : __PACKAGE__-
>new;
3232 require Data
::Dumper
;
3233 return Data
::Dumper
::Dumper
($obj->parse_expr(\
$str));
3236 ###----------------------------------------------------------------###
3238 package CGI
::Ex
::Template
::Exception
;
3241 '""' => \
&as_string
,
3242 bool
=> sub { defined shift },
3246 my ($class, $type, $info, $node, $pos, $str_ref) = @_;
3247 return bless [$type, $info, $node, $pos, $str_ref], $class;
3250 sub type
{ shift-
>[0] }
3252 sub info
{ shift-
>[1] }
3256 $self->[2] = shift if $#_ == 0;
3260 sub offset
{ shift-
>[3] || 0 }
3264 $self->[4] = shift if $#_ == 0;
3270 my $msg = $self->type .' error - '. $self->info;
3271 if (my $node = $self->node) {
3272 # $msg .= " (In tag $node->[0] starting at char ".($node->[1] + $self->offset).")";
3274 if ($self->type =~ /^parse/) {
3275 $msg .= " (At char ".$self->offset.")";
3280 ###----------------------------------------------------------------###
3282 package CGI
::Ex
::Template
::Iterator
;
3285 my ($class, $items) = @_;
3286 $items = [] if ! defined $items;
3287 if (UNIVERSAL
::isa
($items, 'HASH')) {
3288 $items = [ map { {key
=> $_, value
=> $items->{ $_ }} } sort keys %$items ];
3289 } elsif (UNIVERSAL
::can
($items, 'as_list')) {
3290 $items = $items->as_list;
3291 } elsif (! UNIVERSAL
::isa
($items, 'ARRAY')) {
3294 return bless [$items, 0], $class;
3299 return (undef, 3) if ! @{ $self->[0] };
3300 return ($self->[0]->[$self->[1] = 0], undef);
3305 return (undef, 3) if ++ $self->[1] > $#{ $self->[0] };
3306 return ($self->items->[$self->[1]], undef);
3309 sub items
{ shift-
>[0] }
3311 sub index { shift-
>[1] }
3313 sub max
{ $#{ shift-
>[0] } }
3315 sub size
{ shift-
>max + 1 }
3317 sub count
{ shift-
>index + 1 }
3319 sub number
{ shift-
>index + 1 }
3321 sub first
{ (shift-
>index == 0) || 0 }
3323 sub last { my $self = shift; return ($self->index == $self->max) || 0 }
3327 return undef if $self->index <= 0;
3328 return $self->items->[$self->index - 1];
3333 return undef if $self->index >= $self->max;
3334 return $self->items->[$self->index + 1];
3337 ###----------------------------------------------------------------###
3339 package CGI
::Ex
::Template
::_Context
;
3341 use vars
qw($AUTOLOAD);
3343 sub _template
{ shift-
>{'_template'} || die "Missing _template" }
3345 sub config
{ shift-
>_template }
3349 return $self->{'stash'} ||= bless {_template
=> $self->_template}, $CGI::Ex
::Template
::PACKAGE_STASH
;
3352 sub insert
{ shift-
>_template->_insert(@_) }
3354 sub eval_perl
{ shift-
>_template->{'EVAL_PERL'} }
3359 my $vars = $self->_template->_vars;
3361 $self->_template->_process($ref, $vars, \
$out);
3368 my $args = shift || {};
3370 $self->_template->set_variable($_, $args->{$_}) for keys %$args;
3372 my $out = ''; # have temp item to allow clear to correctly clear
3373 eval { $self->_template->_process($file, $self->{'_vars'}, \
$out) };
3375 die $err if ref($err) !~ /Template::Exception$/ || $err->type !~ /return/;
3382 my ($self, $name, $filter, $is_dynamic) = @_;
3383 $filter = [ $filter, 1 ] if $is_dynamic;
3384 $self->define_vmethod('filter', $name, $filter);
3388 my ($self, $name, $args, $alias) = @_;
3389 my $t = $self->_template;
3393 $filter = $t->{'FILTERS'}->{$name} || $CGI::Ex
::Template
::FILTER_OPS-
>{$name} || $CGI::Ex
::Template
::SCALAR_OPS-
>{$name};
3394 $t->throw('filter', $name) if ! $filter;
3395 } elsif (UNIVERSAL
::isa
($name, 'CODE') || UNIVERSAL
::isa
($name, 'ARRAY')) {
3397 } elsif (UNIVERSAL
::can
($name, 'factory')) {
3398 $filter = $name->factory || $t->throw($name->error);
3400 $t->throw('undef', "$name: filter not found");
3403 if (UNIVERSAL
::isa
($filter, 'ARRAY')) {
3404 $filter = ($filter->[1]) ? $filter->[0]->($t->context, @$args) : $filter->[0];
3405 } elsif ($args && @$args) {
3407 $filter = sub { $sub->(shift, @$args) };
3410 $t->{'FILTERS'}->{$alias} = $filter if $alias;
3415 sub define_vmethod
{ shift-
>_template->define_vmethod(@_) }
3418 my ($self, $type, $info) = @_;
3420 if (UNIVERSAL
::isa
($type, $CGI::Ex
::Template
::PACKAGE_EXCEPTION
)) {
3422 } elsif (defined $info) {
3423 $self->_template->throw($type, $info);
3425 $self->_template->throw('undef', $type);
3429 sub AUTOLOAD
{ shift-
>_template->throw('not_implemented', "The method $AUTOLOAD has not been implemented") }
3433 ###----------------------------------------------------------------###
3435 package CGI
::Ex
::Template
::_Stash
;
3437 use vars
qw($AUTOLOAD);
3439 sub _template
{ shift-
>{'_template'} || die "Missing _template" }
3442 my ($self, $var) = @_;
3444 if ($var =~ /^\w+$/) { $var = [$var, 0] }
3445 else { $var = $self->_template->parse_expr(\
$var, {no_dots
=> 1}) }
3447 return $self->_template->play_expr($var, {no_dots
=> 1});
3451 my ($self, $var, $val) = @_;
3453 if ($var =~ /^\w+$/) { $var = [$var, 0] }
3454 else { $var = $self->_template->parse_expr(\
$var, {no_dots
=> 1}) }
3456 $self->_template->set_variable($var, $val, {no_dots
=> 1});
3460 sub AUTOLOAD
{ shift-
>_template->throw('not_implemented', "The method $AUTOLOAD has not been implemented") }
3464 ###----------------------------------------------------------------###
3466 package CGI
::Ex
::Template
::EvalPerlHandle
;
3469 my ($class, $out_ref) = @_;
3470 return bless [$out_ref], $class;
3475 ${ $self->[0] } .= $_ for grep {defined && length} @_;
3479 ###----------------------------------------------------------------###
3483 ### See the perldoc in CGI/Ex/Template.pod