1 package CGI
::Ex
::Template
;
3 ###----------------------------------------------------------------###
4 # See the perldoc in CGI/Ex/Template.pod
5 # Copyright 2006 - Paul Seamons #
6 # Distributed under the Perl Artistic License without warranty #
7 ###----------------------------------------------------------------###
10 use constant trace
=> $ENV{'CET_TRACE'} || 0; # enable for low level tracing
13 $SCALAR_OPS $HASH_OPS $LIST_OPS $FILTER_OPS $VOBJS
14 $DIRECTIVES $QR_DIRECTIVE
35 $PACKAGE_EXCEPTION $PACKAGE_ITERATOR $PACKAGE_CONTEXT $PACKAGE_STASH $PACKAGE_PERL_HANDLE
44 $PACKAGE_EXCEPTION = 'CGI::Ex::Template::Exception';
45 $PACKAGE_ITERATOR = 'CGI::Ex::Template::Iterator';
46 $PACKAGE_CONTEXT = 'CGI::Ex::Template::_Context';
47 $PACKAGE_STASH = 'CGI::Ex::Template::_Stash';
48 $PACKAGE_PERL_HANDLE = 'CGI::Ex::Template::EvalPerlHandle';
51 default => ['[%', '%]'], # default
52 template
=> ['[%', '%]'], # default
53 metatext
=> ['%%', '%%'], # Text::MetaText
54 star
=> ['[*', '*]'], # TT alternate
55 php
=> ['<?', '?>'], # PHP
56 asp
=> ['<%', '%>'], # ASP
57 mason
=> ['<%', '>' ], # HTML::Mason
58 html
=> ['<!--', '-->'], # HTML comments
63 as
=> \
&vmethod_as_scalar
,
64 chunk
=> \
&vmethod_chunk
,
65 collapse
=> sub { local $_ = $_[0]; s/^\s+//; s/\s+$//; s/\s+/ /g; $_ },
67 indent
=> \
&vmethod_indent
,
68 int => sub { local $^W; int $_[0] },
69 fmt
=> \
&vmethod_as_scalar
,
70 'format' => \
&vmethod_format
,
71 hash
=> sub { {value
=> $_[0]} },
72 html
=> sub { local $_ = $_[0]; s/&/&/g; s/</</g; s/>/>/g; s/\"/"/g; $_ },
73 lcfirst => sub { lcfirst $_[0] },
74 length => sub { defined($_[0]) ? length($_[0]) : 0 },
75 list
=> sub { [$_[0]] },
76 lower
=> sub { lc $_[0] },
77 match
=> \
&vmethod_match
,
78 new
=> sub { defined $_[0] ? $_[0] : '' },
80 rand => sub { local $^W; rand shift },
81 remove
=> sub { vmethod_replace
(shift, shift, '', 1) },
82 repeat
=> \
&vmethod_repeat
,
83 replace
=> \
&vmethod_replace
,
84 search
=> sub { my ($str, $pat) = @_; return $str if ! defined $str || ! defined $pat; return scalar $str =~ /$pat/ },
86 split => \
&vmethod_split
,
87 stderr
=> sub { print STDERR
$_[0]; '' },
88 substr => sub { my ($str, $i, $len) = @_; defined($len) ? substr($str, $i, $len) : substr($str, $i) },
89 trim
=> sub { local $_ = $_[0]; s/^\s+//; s/\s+$//; $_ },
90 ucfirst => sub { ucfirst $_[0] },
91 upper
=> sub { uc $_[0] },
95 $FILTER_OPS = { # generally - non-dynamic filters belong in scalar ops
96 eval => [\
&filter_eval
, 1],
97 evaltt
=> [\
&filter_eval
, 1],
98 file
=> [\
&filter_redirect
, 1],
99 redirect
=> [\
&filter_redirect
, 1],
103 as
=> \
&vmethod_as_list
,
104 first
=> sub { my ($ref, $i) = @_; return $ref->[0] if ! $i; return [@{$ref}[0 .. $i - 1]]},
105 fmt
=> \
&vmethod_as_list
,
106 grep => sub { my ($ref, $pat) = @_; [grep {/$pat/} @$ref] },
107 hash
=> sub { local $^W; my ($list, $i) = @_; defined($i) ? {map {$i++ => $_} @$list} : {@$list} },
108 join => sub { my ($ref, $join) = @_; $join = ' ' if ! defined $join; local $^W; return join $join, @$ref },
109 last => sub { my ($ref, $i) = @_; return $ref->[-1] if ! $i; return [@{$ref}[-$i .. -1]]},
110 list
=> sub { $_[0] },
111 max
=> sub { $#{ $_[0] } },
112 merge
=> sub { my $ref = shift; return [ @$ref, grep {defined} map {ref eq 'ARRAY' ? @$_ : undef} @_ ] },
113 new
=> sub { local $^W; return [@_] },
114 nsort
=> \
&vmethod_nsort
,
115 pop => sub { pop @{ $_[0] } },
116 push => sub { my $ref = shift; push @$ref, @_; return '' },
117 random
=> sub { my $ref = shift; $ref->[ rand @$ref ] },
118 reverse => sub { [ reverse @{ $_[0] } ] },
119 shift => sub { shift @{ $_[0] } },
120 size
=> sub { scalar @{ $_[0] } },
121 slice
=> sub { my ($ref, $a, $b) = @_; $a ||= 0; $b = $#$ref if ! defined $b; return [@{$ref}[$a .. $b]] },
122 sort => \
&vmethod_sort
,
123 splice => \
&vmethod_splice
,
124 unique
=> sub { my %u; return [ grep { ! $u{$_} ++ } @{ $_[0] } ] },
125 unshift => sub { my $ref = shift; unshift @$ref, @_; return '' },
129 as
=> \
&vmethod_as_hash
,
130 defined => sub { return '' if ! defined $_[1]; defined $_[0]->{ $_[1] } },
131 delete => sub { return '' if ! defined $_[1]; delete $_[0]->{ $_[1] } },
132 each => sub { [%{ $_[0] }] },
133 exists => sub { return '' if ! defined $_[1]; exists $_[0]->{ $_[1] } },
134 fmt
=> \
&vmethod_as_hash
,
135 hash
=> sub { $_[0] },
136 import
=> sub { my ($a, $b) = @_; return '' if ref($b) ne 'HASH'; @{$a}{keys %$b} = values %$b; '' },
137 item
=> sub { my ($h, $k) = @_; return '' if ! defined $k || $k =~ $QR_PRIVATE; $h->{$k} },
138 items
=> sub { [ %{ $_[0] } ] },
139 keys => sub { [keys %{ $_[0] }] },
140 list
=> sub { [$_[0]] },
141 new
=> sub { local $^W; return (@_ == 1 && ref $_[-1] eq 'HASH') ? $_[-1] : {@_} },
142 nsort
=> sub { my $ref = shift; [sort {$ref->{$a} <=> $ref->{$b} } keys %$ref] },
143 pairs
=> sub { [map { {key
=> $_, value
=> $_[0]->{$_}} } keys %{ $_[0] } ] },
144 size
=> sub { scalar keys %{ $_[0] } },
145 sort => sub { my $ref = shift; [sort {lc $ref->{$a} cmp lc $ref->{$b}} keys %$ref] },
146 values => sub { [values %{ $_[0] }] },
154 foreach (values %$VOBJS) {
155 $_->{'Text'} = $_->{'as'};
156 $_->{'Hash'} = $_->{'hash'};
157 $_->{'List'} = $_->{'list'};
161 #name parse_sub play_sub block postdir continue move_to_front
162 BLOCK
=> [\
&parse_BLOCK
, \
&play_BLOCK
, 1, 0, 0, 1],
163 BREAK
=> [sub {}, \
&play_control
],
164 CALL
=> [\
&parse_CALL
, \
&play_CALL
],
165 CASE
=> [\
&parse_CASE
, undef, 0, 0, {SWITCH
=> 1, CASE
=> 1}],
166 CATCH => [\
&parse_CATCH
, undef, 0, 0, {TRY
=> 1, CATCH => 1}],
167 CLEAR
=> [sub {}, \
&play_CLEAR
],
168 '#' => [sub {}, sub {}],
169 DEBUG
=> [\
&parse_DEBUG
, \
&play_DEBUG
],
170 DEFAULT
=> [\
&parse_DEFAULT
, \
&play_DEFAULT
],
171 DUMP
=> [\
&parse_DUMP
, \
&play_DUMP
],
172 ELSE
=> [sub {}, undef, 0, 0, {IF
=> 1, ELSIF
=> 1, UNLESS
=> 1}],
173 ELSIF
=> [\
&parse_IF
, undef, 0, 0, {IF
=> 1, ELSIF
=> 1, UNLESS
=> 1}],
174 END => [undef, sub {}],
175 FILTER
=> [\
&parse_FILTER
, \
&play_FILTER
, 1, 1],
176 '|' => [\
&parse_FILTER
, \
&play_FILTER
, 1, 1],
177 FINAL
=> [sub {}, undef, 0, 0, {TRY
=> 1, CATCH => 1}],
178 FOR
=> [\
&parse_FOREACH
, \
&play_FOREACH
, 1, 1],
179 FOREACH
=> [\
&parse_FOREACH
, \
&play_FOREACH
, 1, 1],
180 GET
=> [\
&parse_GET
, \
&play_GET
],
181 IF
=> [\
&parse_IF
, \
&play_IF
, 1, 1],
182 INCLUDE
=> [\
&parse_INCLUDE
, \
&play_INCLUDE
],
183 INSERT
=> [\
&parse_INSERT
, \
&play_INSERT
],
184 LAST
=> [sub {}, \
&play_control
],
185 MACRO
=> [\
&parse_MACRO
, \
&play_MACRO
],
186 META
=> [undef, sub {}],
187 METADEF
=> [undef, \
&play_METADEF
],
188 NEXT => [sub {}, \
&play_control
],
189 PERL
=> [\
&parse_PERL
, \
&play_PERL
, 1],
190 PROCESS
=> [\
&parse_PROCESS
, \
&play_PROCESS
],
191 RAWPERL
=> [\
&parse_PERL
, \
&play_RAWPERL
, 1],
192 RETURN
=> [sub {}, \
&play_control
],
193 SET
=> [\
&parse_SET
, \
&play_SET
],
194 STOP
=> [sub {}, \
&play_control
],
195 SWITCH
=> [\
&parse_SWITCH
, \
&play_SWITCH
, 1],
196 TAGS
=> [undef, sub {}],
197 THROW
=> [\
&parse_THROW
, \
&play_THROW
],
198 TRY
=> [sub {}, \
&play_TRY
, 1],
199 UNLESS
=> [\
&parse_UNLESS
, \
&play_UNLESS
, 1, 1],
200 USE
=> [\
&parse_USE
, \
&play_USE
],
201 WHILE
=> [\
&parse_IF
, \
&play_WHILE
, 1, 1],
202 WRAPPER
=> [\
&parse_WRAPPER
, \
&play_WRAPPER
, 1, 1],
203 #name #parse_sub #play_sub #block #postdir #continue #move_to_front
205 $QR_DIRECTIVE = qr{ ^ (\w+|\|) (?= $|[\s;\#]) }x;
207 ### setup the operator parsing
209 # type precedence symbols action (undef means play_operator will handle)
210 ['postfix', 99, ['++'], undef ],
211 ['postfix', 99, ['--'], undef ],
212 ['prefix', 98, ['++'], undef ],
213 ['prefix', 98, ['--'], undef ],
214 ['right', 96, ['**', 'pow'], sub { $_[0] ** $_[1] } ],
215 ['prefix', 93, ['!'], sub { ! $_[0] } ],
216 ['prefix', 93, ['-'], sub { @_ == 1 ? 0 - $_[0] : $_[0] - $_[1] } ],
217 ['left', 90, ['*'], sub { $_[0] * $_[1] } ],
218 ['left', 90, ['/'], sub { $_[0] / $_[1] } ],
219 ['left', 90, ['div', 'DIV'], sub { int($_[0] / $_[1]) } ],
220 ['left', 90, ['%', 'mod', 'MOD'], sub { $_[0] % $_[1] } ],
221 ['left', 85, ['+'], sub { $_[0] + $_[1] } ],
222 ['left', 85, ['-'], sub { @_ == 1 ? 0 - $_[0] : $_[0] - $_[1] } ],
223 ['left', 85, ['~', '_'], sub { join "", @_ } ],
224 ['none', 80, ['<'], sub { $_[0] < $_[1] } ],
225 ['none', 80, ['>'], sub { $_[0] > $_[1] } ],
226 ['none', 80, ['<='], sub { $_[0] <= $_[1] } ],
227 ['none', 80, ['>='], sub { $_[0] >= $_[1] } ],
228 ['none', 80, ['lt'], sub { $_[0] lt $_[1] } ],
229 ['none', 80, ['gt'], sub { $_[0] gt $_[1] } ],
230 ['none', 80, ['le'], sub { $_[0] le $_[1] } ],
231 ['none', 80, ['ge'], sub { $_[0] ge $_[1] } ],
232 ['none', 75, ['==', 'eq'], sub { $_[0] eq $_[1] } ],
233 ['none', 75, ['!=', 'ne'], sub { $_[0] ne $_[1] } ],
234 ['left', 70, ['&&'], undef ],
235 ['right', 65, ['||'], undef ],
236 ['none', 60, ['..'], sub { $_[0] .. $_[1] } ],
237 ['ternary', 55, ['?', ':'], undef ],
238 ['assign', 53, ['+='], sub { $_[0] + $_[1] } ],
239 ['assign', 53, ['-='], sub { $_[0] - $_[1] } ],
240 ['assign', 53, ['*='], sub { $_[0] * $_[1] } ],
241 ['assign', 53, ['/='], sub { $_[0] / $_[1] } ],
242 ['assign', 53, ['%='], sub { $_[0] % $_[1] } ],
243 ['assign', 53, ['**='], sub { $_[0]** $_[1] } ],
244 ['assign', 53, ['~=', '_='], sub { $_[0] . $_[1] } ],
245 ['assign', 52, ['='], undef ],
246 ['prefix', 50, ['not', 'NOT'], sub { ! $_[0] } ],
247 ['left', 45, ['and', 'AND'], undef ],
248 ['right', 40, ['or', 'OR'], undef ],
249 ['', 0, ['hash'], sub { return {@_}; } ],
250 ['', 0, ['array'], sub { return [@_] } ],
252 $OP = {map {my $ref = $_; map {$_ => $ref} @{$ref->[2]}} grep {$_->[0] ne 'prefix' } @$OPERATORS}; # all non-prefix
253 $OP_PREFIX = {map {my $ref = $_; map {$_ => $ref} @{$ref->[2]}} grep {$_->[0] eq 'prefix' } @$OPERATORS};
254 $OP_DISPATCH = {map {my $ref = $_; map {$_ => $ref->[3]} @{$ref->[2]}} grep {$_->[3] } @$OPERATORS};
255 $OP_ASSIGN = {map {my $ref = $_; map {$_ => 1} @{$ref->[2]}} grep {$_->[0] eq 'assign' } @$OPERATORS};
256 $OP_POSTFIX = {map {my $ref = $_; map {$_ => 1} @{$ref->[2]}} grep {$_->[0] eq 'postfix'} @$OPERATORS}; # bool is postfix
257 $OP_TERNARY = {map {my $ref = $_; map {$_ => 1} @{$ref->[2]}} grep {$_->[0] eq 'ternary'} @$OPERATORS}; # bool is ternary
258 sub _op_qr
{ # no mixed \w\W operators
260 my $chrs = join '|', reverse sort map {quotemeta $_} grep {++$used{$_} < 2} grep {/^\W{2,}$/} @_;
261 my $chr = join '', sort map {quotemeta $_} grep {++$used{$_} < 2} grep {/^\W$/} @_;
262 my $word = join '|', reverse sort grep {++$used{$_} < 2} grep {/^\w+$/} @_;
263 $chr = "[$chr]" if $chr;
264 $word = "\\b(?:$word)\\b" if $word;
265 return join('|', grep {length} $chrs, $chr, $word) || die "Missing operator regex";
267 sub _build_op_qr
{ _op_qr
(map {@{ $_->[2] }} grep {$_->[0] ne 'prefix'} @$OPERATORS) }
268 sub _build_op_qr_prefix
{ _op_qr
(map {@{ $_->[2] }} grep {$_->[0] eq 'prefix'} @$OPERATORS) }
269 sub _build_op_qr_assign
{ _op_qr
(map {@{ $_->[2] }} grep {$_->[0] eq 'assign'} @$OPERATORS) }
270 $QR_OP = _build_op_qr
();
271 $QR_OP_PREFIX = _build_op_qr_prefix
();
272 $QR_OP_ASSIGN = _build_op_qr_assign
();
274 $QR_COMMENTS = '(?-s: \# .* \s*)*';
275 $QR_FILENAME = '([a-zA-Z]]:/|/)? [\w\-\.]+ (?:/[\w\-\.]+)*';
276 $QR_NUM = '(?:\d*\.\d+ | \d+) (?: [eE][+-]\d+ )?';
277 $QR_AQ_NOTDOT = "(?! \\s* $QR_COMMENTS \\.)";
278 $QR_AQ_SPACE = '(?: \\s+ | \$ | (?=[;+]) )'; # the + comes into play on filenames
279 $QR_PRIVATE = qr/^_/;
282 $EXTRA_COMPILE_EXT = '.sto';
285 ###----------------------------------------------------------------###
289 my $args = ref($_[0]) ? { %{ shift() } } : {@_};
290 my $self = bless $args, $class;
292 ### "enable" debugging - we only support DEBUG_DIRS and DEBUG_UNDEF
293 if ($self->{'DEBUG'}) {
294 $self->{'_debug_dirs'} = 1 if $self->{'DEBUG'} =~ /^\d+$/ ? $self->{'DEBUG'} & 8 : $self->{'DEBUG'} =~ /dirs|all/;
295 $self->{'_debug_undef'} = 1 if $self->{'DEBUG'} =~ /^\d+$/ ? $self->{'DEBUG'} & 2 : $self->{'DEBUG'} =~ /undef|all/;
301 ###----------------------------------------------------------------###
306 local $self->{'_vars'} = shift || {};
307 my $out_ref = shift || $self->throw('undef', "Missing output ref");
308 local $self->{'_top_level'} = delete $self->{'_start_top_level'};
309 my $i = length $$out_ref;
311 ### parse and execute
314 ### load the document
315 $doc = $self->load_parsed_tree($file) || $self->throw('undef', "Zero length content");;
317 ### prevent recursion
318 $self->throw('file', "recursion into '$doc->{name}'")
319 if ! $self->{'RECURSION'} && $self->{'_in'}->{$doc->{'name'}} && $doc->{'name'} ne 'input text';
320 local $self->{'_in'}->{$doc->{'name'}} = 1;
322 ### execute the document
323 if (! @{ $doc->{'_tree'} }) { # no tags found - just return the content
324 $$out_ref = ${ $doc->{'_content'} };
326 local $self->{'_vars'}->{'component'} = $doc;
327 $self->{'_vars'}->{'template'} = $doc if $self->{'_top_level'};
328 $self->execute_tree($doc->{'_tree'}, $out_ref);
329 delete $self->{'_vars'}->{'template'} if $self->{'_top_level'};
333 ### trim whitespace from the beginning and the end of a block or template
334 if ($self->{'TRIM'}) {
335 substr($$out_ref, $i, length($$out_ref) - $i) =~ s{ \s+ $ }{}x; # tail first
336 substr($$out_ref, $i, length($$out_ref) - $i) =~ s{ ^ \s+ }{}x;
339 ### handle exceptions
341 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
342 $err->doc($doc) if $doc && $err->can('doc') && ! $err->doc;
343 die $err if ! $self->{'_top_level'} || $err->type !~ /stop|return/;
349 ###----------------------------------------------------------------###
351 sub load_parsed_tree
{
354 return if ! defined $file;
356 my $doc = {name
=> $file};
358 ### looks like a string reference
360 $doc->{'_content'} = $file;
361 $doc->{'name'} = 'input text';
362 $doc->{'is_str_ref'} = 1;
364 ### looks like a previously cached-in-memory document
365 } elsif ($self->{'_documents'}->{$file}
366 && ( ($self->{'_documents'}->{$file}->{'_cache_time'} == time) # don't stat more than once a second
367 || ($self->{'_documents'}->{$file}->{'modtime'}
368 == (stat $self->{'_documents'}->{$file}->{'_filename'})[9]))) {
369 $doc = $self->{'_documents'}->{$file};
370 $doc->{'_cache_time'} = time;
373 ### looks like a block name of some sort
374 } elsif ($self->{'BLOCKS'}->{$file}) {
375 my $block = $self->{'BLOCKS'}->{$file};
377 ### allow for predefined blocks that are a code or a string
378 if (UNIVERSAL
::isa
($block, 'CODE')) {
381 if (! UNIVERSAL
::isa
($block, 'HASH')) {
382 $self->throw('block', "Unsupported BLOCK type \"$block\"") if ref $block;
384 $block = eval { $self->load_parsed_tree(\
$copy) }
385 || $self->throw('block', 'Parse error on predefined block');
387 $doc->{'_tree'} = $block->{'_tree'} || $self->throw('block', "Invalid block definition (missing tree)");
391 ### go and look on the file system
393 $doc->{'_filename'} = eval { $self->include_filename($file) };
395 ### allow for blocks in other files
396 if ($self->{'EXPOSE_BLOCKS'}
397 && ! $self->{'_looking_in_block_file'}) {
398 local $self->{'_looking_in_block_file'} = 1;
400 while ($file =~ s
|/([^/.]+)$||) {
401 $block_name = length($block_name) ? "$1/$block_name" : $1;
402 my $ref = eval { $self->load_parsed_tree($file) } || next;
403 my $_tree = $ref->{'_tree'};
404 foreach my $node (@$_tree) {
406 next if $node->[0] eq 'METADEF';
407 last if $node->[0] ne 'BLOCK';
408 next if $block_name ne $node->[3];
409 $doc->{'_content'} = $ref->{'_content'};
410 $doc->{'_tree'} = $node->[4];
411 $doc->{'modtime'} = $ref->{'modtime'};
412 $file = $ref->{'name'};
416 die $err if ! $doc->{'_tree'};
417 } elsif ($self->{'DEFAULT'}) {
418 $doc->{'_filename'} = eval { $self->include_filename($self->{'DEFAULT'}) } || die $err;
424 ### no tree yet - look for a file cache
425 if (! $doc->{'_tree'}) {
426 $doc->{'modtime'} = (stat $doc->{'_filename'})[9];
427 if ($self->{'COMPILE_DIR'} || $self->{'COMPILE_EXT'}) {
428 if ($self->{'COMPILE_DIR'}) {
429 $doc->{'_compile_filename'} = $self->{'COMPILE_DIR'} .'/'. $file;
431 $doc->{'_compile_filename'} = $doc->{'_filename'};
433 $doc->{'_compile_filename'} .= $self->{'COMPILE_EXT'} if defined($self->{'COMPILE_EXT'});
434 $doc->{'_compile_filename'} .= $EXTRA_COMPILE_EXT if defined $EXTRA_COMPILE_EXT;
436 if (-e
$doc->{'_compile_filename'} && (stat _
)[9] == $doc->{'modtime'}) {
438 $doc->{'_tree'} = Storable
::retrieve
($doc->{'_compile_filename'});
439 $doc->{'compile_was_used'} = 1;
441 my $str = $self->slurp($doc->{'_filename'});
442 $doc->{'_content'} = \
$str;
445 my $str = $self->slurp($doc->{'_filename'});
446 $doc->{'_content'} = \
$str;
452 ### haven't found a parsed tree yet - parse the content into a tree
453 if (! $doc->{'_tree'}) {
454 if ($self->{'CONSTANTS'}) {
455 my $key = $self->{'CONSTANT_NAMESPACE'} || 'constants';
456 $self->{'NAMESPACE'}->{$key} ||= $self->{'CONSTANTS'};
459 local $self->{'_vars'}->{'component'} = $doc;
460 $doc->{'_tree'} = $self->parse_tree($doc->{'_content'}); # errors die
463 ### cache parsed_tree in memory unless asked not to do so
464 if (! $doc->{'is_str_ref'} && (! defined($self->{'CACHE_SIZE'}) || $self->{'CACHE_SIZE'})) {
465 $self->{'_documents'}->{$file} ||= $doc;
466 $doc->{'_cache_time'} = time;
468 ### allow for config option to keep the cache size down
469 if ($self->{'CACHE_SIZE'}) {
470 my $all = $self->{'_documents'};
471 if (scalar(keys %$all) > $self->{'CACHE_SIZE'}) {
473 foreach my $file (sort {$all->{$b}->{'_cache_time'} <=> $all->{$a}->{'_cache_time'}} keys %$all) {
474 delete($all->{$file}) if ++$n > $self->{'CACHE_SIZE'};
480 ### save a cache on the fileside as asked
481 if ($doc->{'_compile_filename'} && ! $doc->{'compile_was_used'}) {
482 my $dir = $doc->{'_compile_filename'};
486 File
::Path
::mkpath
($dir);
489 Storable
::store
($doc->{'_tree'}, $doc->{'_compile_filename'});
490 utime $doc->{'modtime'}, $doc->{'modtime'}, $doc->{'_compile_filename'};
499 if (! $str_ref || ! defined $$str_ref) {
500 $self->throw('parse.no_string', "No string or undefined during parse");
503 my $STYLE = $self->{'TAG_STYLE'} || 'default';
504 my $START = $self->{'START_TAG'} || $TAGS->{$STYLE}->[0];
505 my $END = $self->{'END_TAG'} || $TAGS->{$STYLE}->[1];
506 my $len_s = length $START;
507 my $len_e = length $END;
509 my @tree; # the parsed tree
510 my $pointer = \
@tree; # pointer to current tree to handle nested blocks
511 my @state; # maintain block levels
512 local $self->{'_state'} = \
@state; # allow for items to introspect (usually BLOCKS)
513 local $self->{'_in_perl'}; # no interpolation in perl
514 my @move_to_front; # items that need to be declared first (usually BLOCKS)
515 my @meta; # place to store any found meta information (to go into METADEF)
516 my $i = 0; # start index
517 my $j = 0; # end index
518 my $last = 0; # previous end index
519 my $post_chomp = 0; # previous post_chomp setting
520 my $continue; # multiple directives in the same tag
521 my $post_op; # found a post-operative DIRECTIVE
522 my $capture; # flag to start capture
527 ### continue looking for information in a semi-colon delimited tag
530 $node = [undef, $i, $j];
532 ### look through the string using index
534 $i = index($$str_ref, $START, $last);
535 last if $i == -1; # no start tag found - we are done
536 if ($last != $i) { # found a text portion - chomp it, interpolate it and store it
537 my $text = substr($$str_ref, $last, $i - $last);
540 if ($post_chomp == 1) { $_last += length($1) if $text =~ s{ ^ ([^\S\n]* \n) }{}x }
541 elsif ($post_chomp == 2) { $_last += length($1) + 1 if $text =~ s{ ^ (\s+) }{ }x }
542 elsif ($post_chomp == 3) { $_last += length($1) if $text =~ s{ ^ (\s+) }{}x }
545 push @$pointer, $text;
546 $self->interpolate_node($pointer, $_last) if $self->{'INTERPOLATE'};
549 $j = index($$str_ref, $END, $i + $len_s);
551 if ($j == -1) { # missing closing tag
552 $last = length($$str_ref);
555 $tag = substr($$str_ref, $i + $len_s, $j - ($i + $len_s));
556 $node = [undef, $i + $len_s, $j];
558 ### take care of whitespace and comments flags
559 my $pre_chomp = $tag =~ s{ ^ ([+=~-]) }{}x ? $1 : $self->{'PRE_CHOMP'};
560 $post_chomp = $tag =~ s{ ([+=~-]) $ }{}x ? $1 : $self->{'POST_CHOMP'};
561 $pre_chomp =~ y/-=~+/1230/ if $pre_chomp;
562 $post_chomp =~ y/-=~+/1230/ if $post_chomp;
563 if ($pre_chomp && $pointer->[-1] && ! ref $pointer->[-1]) {
564 if ($pre_chomp == 1) { $pointer->[-1] =~ s{ (?:\n|^) [^\S\n]* \z }{}x }
565 elsif ($pre_chomp == 2) { $pointer->[-1] =~ s{ (\s+) \z }{ }x }
566 elsif ($pre_chomp == 3) { $pointer->[-1] =~ s{ (\s+) \z }{}x }
567 splice(@$pointer, -1, 1, ()) if ! length $pointer->[-1]; # remove the node if it is zero length
569 if ($tag =~ /^\#/) { # leading # means to comment the entire section
571 push @$pointer, $node;
574 $tag =~ s{ ^ \s+ $QR_COMMENTS }{}ox;
583 ### look for DIRECTIVES
584 if ($tag =~ $QR_DIRECTIVE # find a word
585 && $DIRECTIVES->{$1} ) { # is it a directive
586 $node->[0] = $func = $1;
587 $tag =~ s{ ^ (\w+ | \|) \s* $QR_COMMENTS }{}ox;
589 ### store out this current node level
590 if ($post_op) { # on a post operator - replace the original node with the new one - store the old in the new
591 my @post_op = @$post_op;
594 $node->[4] = [\
@post_op];
596 # do nothing - it will be handled further down
598 push @$pointer, $node;
601 ### anything that behaves as a block ending
602 if ($func eq 'END' || $DIRECTIVES->{$func}->[4]) { # [4] means it is a continuation block (ELSE, CATCH, etc)
604 $self->throw('parse', "Found an $func tag while not in a block", $node);
606 my $parent_node = pop @state;
608 if ($func ne 'END') {
609 pop @$pointer; # we will store the node in the parent instead
610 $parent_node->[5] = $node;
611 my $parent_type = $parent_node->[0];
612 if (! $DIRECTIVES->{$func}->[4]->{$parent_type}) {
613 $self->throw('parse', "Found unmatched nested block", $node, 0);
617 ### restore the pointer up one level (because we hit the end of a block)
618 $pointer = (! @state) ? \
@tree : $state[-1]->[4];
621 if ($func eq 'END') {
622 if ($DIRECTIVES->{$parent_node->[0]}->[5]) { # move things like BLOCKS to front
623 push @move_to_front, $parent_node;
624 if ($pointer->[-1] && ! $pointer->[-1]->[6]) { # capturing doesn't remove the var
625 splice(@$pointer, -1, 1, ());
627 } elsif ($parent_node->[0] =~ /PERL$/) {
628 delete $self->{'_in_perl'};
631 ### continuation block - such as an elsif
633 $node->[3] = eval { $DIRECTIVES->{$func}->[0]->($self, \
$tag, $node) };
635 $err->node($node) if UNIVERSAL
::can
($err, 'node') && ! $err->node;
639 $pointer = $node->[4] ||= [];
642 } elsif ($func eq 'TAGS') {
643 if ($tag =~ / ^ (\w+) /x && $TAGS->{$1}) {
644 $tag =~ s{ ^ (\w+) \s* $QR_COMMENTS }{}ox;
645 ($START, $END) = @{ $TAGS->{$1} };
646 } elsif ($tag =~ s{ ^ (\S+) \s+ (\S+) \s* $QR_COMMENTS }{}ox) {
647 ($START, $END) = ($1, $2);
649 $len_s = length $START;
650 $len_e = length $END;
652 } elsif ($func eq 'META') {
653 my $args = $self->parse_args(\
$tag);
655 if (($hash = $self->play_expr($args->[-1]))
656 && UNIVERSAL
::isa
($hash, 'HASH')) {
657 unshift @meta, %$hash; # first defined win
660 ### all other "normal" tags
662 $node->[3] = eval { $DIRECTIVES->{$func}->[0]->($self, \
$tag, $node) };
664 $err->node($node) if UNIVERSAL
::can
($err, 'node') && ! $err->node;
667 if ($DIRECTIVES->{$func}->[2] && ! $post_op) { # this looks like a block directive
669 $pointer = $node->[4] ||= [];
673 ### allow for bare variable getting and setting
674 } elsif (defined(my $var = $self->parse_expr(\
$tag))) {
675 push @$pointer, $node;
676 if ($tag =~ s{ ^ ($QR_OP_ASSIGN) >? \s* $QR_COMMENTS }{}ox) {
678 $node->[3] = eval { $DIRECTIVES->{'SET'}->[0]->($self, \
$tag, $node, $1, $var) };
680 $err->node($node) if UNIVERSAL
::can
($err, 'node') && ! $err->node;
689 my $all = substr($$str_ref, $i + $len_s, $j - ($i + $len_s));
692 $self->throw('parse', "Not sure how to handle tag \"$all\"", $node);
695 ### we now have the directive to capture for an item like "SET foo = BLOCK" - store it
697 my $parent_node = $capture;
698 push @{ $parent_node->[4] }, $node;
702 ### we are flagged to start capturing the output of the next directive - set it up
704 $continue = $j - length $tag;
705 $node->[2] = $continue;
709 ### semi-colon = end of statement - we will need to continue parsing this tag
710 } elsif ($tag =~ s{ ^ ; \s* $QR_COMMENTS }{}ox) {
711 $continue = $j - length $tag;
712 $node->[2] = $continue;
715 ### looking at a post operator ([% u FOREACH u IN [1..3] %])
716 } elsif ($tag =~ $QR_DIRECTIVE # find a word
717 && $DIRECTIVES->{$1} # is it a directive
718 && $DIRECTIVES->{$1}->[3]) { # it is a post operative directive
719 $continue = $j - length $tag;
720 $node->[2] = $continue;
723 ### unlink TT2 - look for another directive
724 } elsif (length $tag) {
725 #$self->throw('parse', "Found trailing info \"$tag\"", $node);
726 $continue = $j - length $tag;
727 $node->[2] = $continue;
736 if (@move_to_front) {
737 unshift @tree, @move_to_front;
740 unshift @tree, ['METADEF', 0, 0, {@meta}];
744 $self->throw('parse.missing.end', "Missing END", $state[-1], 0);
747 ### pull off the last text portion - if any
748 if ($last != length($$str_ref)) {
749 my $text = substr($$str_ref, $last, length($$str_ref) - $last);
752 if ($post_chomp == 1) { $_last += length($1) if $text =~ s{ ^ ([^\S\n]* \n) }{}x }
753 elsif ($post_chomp == 2) { $_last += length($1) + 1 if $text =~ s{ ^ (\s+) }{ }x }
754 elsif ($post_chomp == 3) { $_last += length($1) if $text =~ s{ ^ (\s+) }{}x }
757 push @$pointer, $text;
758 $self->interpolate_node($pointer, $_last) if $self->{'INTERPOLATE'};
766 my ($self, $tree, $out_ref) = @_;
768 # node contains (0: DIRECTIVE,
771 # 3: parsed tag details,
772 # 4: sub tree for block types
773 # 5: continuation sub trees for sub continuation block types (elsif, else, etc)
774 # 6: flag to capture next directive
775 for my $node (@$tree) {
776 ### text nodes are just the bare text
778 warn "NODE: TEXT\n" if trace
;
779 $$out_ref .= $node if defined $node;
783 warn "NODE: $node->[0] (char $node->[1])\n" if trace
;
784 $$out_ref .= $self->debug_node($node) if $self->{'_debug_dirs'} && ! $self->{'_debug_off'};
786 my $val = $DIRECTIVES->{$node->[0]}->[1]->($self, $node->[3], $node, $out_ref);
787 $$out_ref .= $val if defined $val;
791 ###----------------------------------------------------------------###
796 my $ARGS = shift || {};
798 ### allow for custom auto_quoting (such as hash constructors)
799 if ($ARGS->{'auto_quote'}) {
800 if ($$str_ref =~ $ARGS->{'auto_quote'}) {
802 substr($$str_ref, 0, length($str), '');
803 $$str_ref =~ s{ ^ \s* $QR_COMMENTS }{}ox;
805 ### allow for auto-quoted $foo or ${foo.bar} type constructs
806 } elsif ($$str_ref =~ s{ ^ \$ (\w+ (?:\.\w+)*) \b \s* $QR_COMMENTS }{}ox
807 || $$str_ref =~ s{ ^ \$\{ \s* ([^\}]+) \} \s* $QR_COMMENTS }{}ox) {
809 return $self->parse_expr(\
$name);
813 my $copy = $$str_ref; # copy while parsing to allow for errors
815 ### test for leading prefix operators
817 while ($copy =~ s{ ^ ($QR_OP_PREFIX) \s* $QR_COMMENTS }{}ox) {
818 return if $ARGS->{'auto_quote'}; # auto_quoted thing was too complicated
819 push @{ $has_prefix }, $1;
827 if ($copy =~ s{ ^ 0x ( [a-fA-F0-9]+ ) \s* $QR_COMMENTS }{}ox) {
828 my $number = eval { hex $1 } || 0;
829 push @var, \
$number;
832 ### allow for numbers
833 } elsif ($copy =~ s{ ^ ( $QR_NUM ) \s* $QR_COMMENTS }{}ox) {
835 push @var, \
$number;
838 ### allow for quoted array constructor
839 } elsif ($copy =~ s{ ^ qw (\W) \s* }{}x) {
841 $quote =~ y
|([{<|)]}>|;
842 $copy =~ s{ ^ (.*) \Q$quote\E \s* $QR_COMMENTS }{}sx
843 || $self->throw('parse.missing.array_close', "Missing close \"$quote\"", undef, length($$str_ref) - length($copy));
845 $str =~ s{ ^ \s+ | \s+ $ }{}x;
846 my $arrayref = ['array', split /\s+/, $str];
847 push @var, \
$arrayref;
849 ### looks like a normal variable start
850 } elsif ($copy =~ s{ ^ (\w+) \s* $QR_COMMENTS }{}ox) {
852 $is_namespace = 1 if $self->{'NAMESPACE'} && $self->{'NAMESPACE'}->{$1};
854 ### allow for literal strings
855 } elsif ($copy =~ s{ ^ ([\"\']) (|.*?[^\\]) \1 \s* $QR_COMMENTS }{}sox) {
856 if ($1 eq "'") { # no interpolation on single quoted strings
858 $str =~ s{ \\\' }{\'}xg;
866 $str =~ s/\\([\"\$])/$1/g;
867 my @pieces = $ARGS->{'auto_quote'}
868 ? split(m{ (\$\w+ | \$\{ [^\}]+ \
}) }x
, $str) # autoquoted items get a single $\w+ - no nesting
869 : split(m{ (\$\w+ (?:\.\w+)* | \$\{ [^\}]+ \
}) }x
, $str);
871 foreach my $piece (@pieces) {
872 next if ! ($n++ % 2);
873 next if $piece !~ m{ ^ \$ (\w+ (?:\.\w+)*) $ }x
874 && $piece !~ m{ ^ \$\{ \s* ([^\}]+) \
} $ }x
;
876 $piece = $self->parse_expr(\
$name);
878 @pieces = grep {defined && length} @pieces;
879 if (@pieces == 1 && ! ref $pieces[0]) {
880 push @var, \
$pieces[0];
882 } elsif (! @pieces) {
886 push @var, \
['~', @pieces];
889 if ($ARGS->{'auto_quote'}){
891 return ${ $var[0] } if $is_literal;
896 ### allow for leading $foo or ${foo.bar} type constructs
897 } elsif ($copy =~ s{ ^ \$ (\w+) \b \s* $QR_COMMENTS }{}ox
898 || $copy =~ s{ ^ \$\{ \s* ([^\}]+) \} \s* $QR_COMMENTS }{}ox) {
900 push @var, $self->parse_expr(\
$name);
902 ### looks like an array constructor
903 } elsif ($copy =~ s{ ^ \[ \s* $QR_COMMENTS }{}ox) {
904 local $self->{'_operator_precedence'} = 0; # reset presedence
905 my $arrayref = ['array'];
906 while (defined(my $var = $self->parse_expr(\
$copy))) {
907 push @$arrayref, $var;
908 $copy =~ s{ ^ , \s* $QR_COMMENTS }{}ox;
910 $copy =~ s{ ^ \] \s* $QR_COMMENTS }{}ox
911 || $self->throw('parse.missing.square_bracket', "Missing close \]", undef, length($$str_ref) - length($copy));
912 push @var, \
$arrayref;
914 ### looks like a hash constructor
915 } elsif ($copy =~ s{ ^ \{ \s* $QR_COMMENTS }{}ox) {
916 local $self->{'_operator_precedence'} = 0; # reset precedence
917 my $hashref = ['hash'];
918 while (defined(my $key = $self->parse_expr(\
$copy, {auto_quote
=> qr{ ^ (\w+) $QR_AQ_NOTDOT }xo}))) {
919 $copy =~ s{ ^ = >? \s* $QR_COMMENTS }{}ox;
920 my $val = $self->parse_expr(\
$copy);
921 push @$hashref, $key, $val;
922 $copy =~ s{ ^ , \s* $QR_COMMENTS }{}ox;
924 $copy =~ s{ ^ \} \s* $QR_COMMENTS }{}ox
925 || $self->throw('parse.missing.curly_bracket', "Missing close \} ($copy)", undef, length($$str_ref) - length($copy));
926 push @var, \
$hashref;
928 ### looks like a paren grouper
929 } elsif ($copy =~ s{ ^ \( \s* $QR_COMMENTS }{}ox) {
930 local $self->{'_operator_precedence'} = 0; # reset precedence
931 my $var = $self->parse_expr(\
$copy, {allow_parened_ops
=> 1});
932 $copy =~ s{ ^ \) \s* $QR_COMMENTS }{}ox
933 || $self->throw('parse.missing.paren', "Missing close \)", undef, length($$str_ref) - length($copy));
935 pop(@var); # pull off the trailing args of the paren group
937 ### nothing to find - return failure
942 return if $ARGS->{'auto_quote'}; # auto_quoted thing was too complicated
944 ### looks for args for the initial
945 if ($copy =~ s{ ^ \( \s* $QR_COMMENTS }{}ox) {
946 local $self->{'_operator_precedence'} = 0; # reset precedence
947 my $args = $self->parse_args(\
$copy);
948 $copy =~ s{ ^ \) \s* $QR_COMMENTS }{}ox
949 || $self->throw('parse.missing.paren', "Missing close \)", undef, length($$str_ref) - length($copy));
955 ### allow for nested items
956 while ($copy =~ s{ ^ ( \.(?!\.) | \|(?!\|) ) \s* $QR_COMMENTS }{}ox) {
957 push(@var, $1) if ! $ARGS->{'no_dots'};
959 ### allow for interpolated variables in the middle - one.$foo.two or one.${foo.bar}.two
960 if ($copy =~ s{ ^ \$(\w+) \s* $QR_COMMENTS }{}ox
961 || $copy =~ s{ ^ \$\{ \s* ([^\}]+)\} \s* $QR_COMMENTS }{}ox) {
963 my $var = $self->parse_expr(\
$name);
967 } elsif ($copy =~ s{ ^ (-? \w+) \s* $QR_COMMENTS }{}ox) {
971 $self->throw('parse', "Not sure how to continue parsing on \"$copy\" ($$str_ref)");
974 ### looks for args for the nested item
975 if ($copy =~ s{ ^ \( \s* $QR_COMMENTS }{}ox) {
976 local $self->{'_operator_precedence'} = 0; # reset precedence
977 my $args = $self->parse_args(\
$copy);
978 $copy =~ s{ ^ \) \s* $QR_COMMENTS }{}ox
979 || $self->throw('parse.missing.paren', "Missing close \)", undef, length($$str_ref) - length($copy));
987 ### flatten literals and constants as much as possible
988 my $var = ($is_literal && $#var == 1) ? ${ $var[0] }
989 : $is_namespace ? $self->play_expr(\
@var, {is_namespace_during_compile
=> 1})
992 ### allow for all "operators"
993 if (! $self->{'_operator_precedence'}) {
996 while ($copy =~ s{ ^ ($QR_OP) (\s* $QR_COMMENTS) }{}ox) { ## look for operators - then move along
997 if (! $ARGS->{'allow_parened_ops'} && $OP_ASSIGN->{$1}) {
998 $copy = $1 . $2 . $copy;
1002 local $self->{'_operator_precedence'} = 1;
1005 ### allow for postfix - doesn't check precedence - someday we might change - but not today (only affects post ++ and --)
1006 if ($OP_POSTFIX->{$op}) {
1007 $var = [\
[$op, $var, 1], 0]; # cheat - give a "second value" to postfix ops
1010 ### allow for prefix operator precedence
1011 } elsif ($has_prefix && $OP->{$op}->[1] < $OP_PREFIX->{$has_prefix->[-1]}->[1]) {
1013 if ($#$tree == 1) { # only one operator - keep simple things fast
1014 $var = [\
[$tree->[0], $var, $tree->[1]], 0];
1016 unshift @$tree, $var;
1017 $var = $self->apply_precedence($tree, $found);
1022 $var = [ \
[ $has_prefix->[-1], $var ], 0 ];
1023 if (! @$has_prefix) { undef $has_prefix } else { pop @$has_prefix }
1026 ### add the operator to the tree
1027 my $var2 = $self->parse_expr(\
$copy);
1028 push (@{ $tree ||= [] }, $op, $var2);
1029 $found->{$OP->{$op}->[1]}->{$op} = 1; # found->{precedence}->{op}
1032 ### if we found operators - tree the nodes by operator precedence
1034 if (@$tree == 2) { # only one operator - keep simple things fast
1035 $var = [\
[$tree->[0], $var, $tree->[1]], 0];
1037 unshift @$tree, $var;
1038 $var = $self->apply_precedence($tree, $found);
1043 ### allow for prefix on non-chained variables
1045 $var = [ \
[ $_, $var ], 0 ] for reverse @$has_prefix;
1048 $$str_ref = $copy; # commit the changes
1052 ### this is used to put the parsed variables into the correct operations tree
1053 sub apply_precedence
{
1054 my ($self, $tree, $found) = @_;
1058 ### look at the operators we found in the order we found them
1059 for my $prec (sort keys %$found) {
1060 my $ops = $found->{$prec};
1061 local $found->{$prec};
1062 delete $found->{$prec};
1064 ### split the array on the current operators for this level
1067 for (my $i = 1; $i <= $#$tree; $i += 2) {
1068 next if ! $ops->{ $tree->[$i] };
1069 push @ops, $tree->[$i];
1070 push @exprs, [splice @$tree, 0, $i, ()];
1074 next if ! @exprs; # this iteration didn't have the current operator
1075 push @exprs, $tree if scalar @$tree; # add on any remaining items
1077 ### simplify sub expressions
1078 for my $node (@exprs) {
1080 $node = $node->[0]; # single item - its not a tree
1081 } elsif (@$node == 3) {
1082 $node = [ \
[ $node->[1], $node->[0], $node->[2] ], 0 ]; # single operator - put it straight on
1084 $node = $self->apply_precedence($node, $found); # more complicated - recurse
1088 ### assemble this current level
1091 # 1) items at the same precedence level must all be either right or left or ternary associative
1092 # 2) ternary items cannot share precedence with anybody else.
1093 # 3) there really shouldn't be another operator at the same level as a postfix
1094 my $type = $OP->{$ops[0]}->[0];
1096 if ($type eq 'ternary') {
1097 my $op = $OP->{$ops[0]}->[2]->[0]; # use the first op as what we are using
1099 ### return simple ternary
1101 $self->throw('parse', "Ternary operator mismatch") if $ops[0] ne $op;
1102 $self->throw('parse', "Ternary operator mismatch") if ! $ops[1] || $ops[1] eq $op;
1103 return [ \
[ $op, @exprs ], 0 ];
1107 ### reorder complex ternary - rare case
1108 while ($#ops >= 1) {
1109 ### if we look starting from the back - the first lead ternary op will always be next to its matching op
1110 for (my $i = $#ops; $i >= 0; $i --) {
1111 next if $OP->{$ops[$i]}->[2]->[1] eq $ops[$i];
1112 my ($op, $op2) = splice @ops, $i, 2, (); # remove the pair of operators
1113 my $node = [ \
[$op, @exprs[$i .. $i + 2] ], 0 ];
1114 splice @exprs, $i, 3, $node;
1117 return $exprs[0]; # at this point the ternary has been reduced to a single operator
1119 } elsif ($type eq 'right' || $type eq 'assign') {
1120 my $val = $exprs[-1];
1121 $val = [ \
[ $ops[$_ - 1], $exprs[$_], $val ], 0 ] for reverse (0 .. $#exprs - 1);
1125 my $val = $exprs[0];
1126 $val = [ \
[ $ops[$_ - 1], $val, $exprs[$_] ], 0 ] for (1 .. $#exprs);
1132 $self->throw('parse', "Couldn't apply precedence");
1135 ### look for arguments - both positional and named
1138 my $str_ref = shift;
1139 my $ARGS = shift || {};
1140 my $copy = $$str_ref;
1144 while (length $$str_ref) {
1145 my $copy = $$str_ref;
1146 if (defined(my $name = $self->parse_expr(\
$copy, {auto_quote
=> qr{ ^ (\w+) $QR_AQ_NOTDOT }xo}))
1147 && $copy =~ s{ ^ = >? \s* $QR_COMMENTS }{}ox) {
1148 $self->throw('parse', 'Named arguments not allowed') if $ARGS->{'positional_only'};
1149 my $val = $self->parse_expr(\
$copy);
1150 $copy =~ s{ ^ , \s* $QR_COMMENTS }{}ox;
1151 push @named, $name, $val;
1153 } elsif (defined(my $arg = $self->parse_expr($str_ref))) {
1155 $$str_ref =~ s{ ^ , \s* $QR_COMMENTS }{}ox;
1161 ### allow for named arguments to be added also
1162 push @args, [\
['hash', @named], 0] if scalar @named;
1167 ### allow for looking for $foo or ${foo.bar} in TEXT "nodes" of the parse tree.
1168 sub interpolate_node
{
1169 my ($self, $tree, $offset) = @_;
1170 return if $self->{'_in_perl'};
1172 ### split on variables while keeping the variables
1173 my @pieces = split m{ (?: ^ | (?<! \\)) (\$\w+ (?:\.\w+)* | \$\{ [^\}]+ \
}) }x
, $tree->[-1];
1174 if ($#pieces <= 0) {
1175 $tree->[-1] =~ s{ \\ ([\"\$]) }{$1}xg;
1181 foreach my $piece (@pieces) {
1182 $offset += length $piece; # we track the offset to make sure DEBUG has the right location
1183 if (! ($n++ % 2)) { # odds will always be text chunks
1184 next if ! length $piece;
1185 $piece =~ s{ \\ ([\"\$]) }{$1}xg;
1186 push @sub_tree, $piece;
1187 } elsif ($piece =~ m{ ^ \$ (\w+ (?:\.\w+)*) $ }x
1188 || $piece =~ m{ ^ \$\{ \s* ([^\}]+) \
} $ }x
) {
1190 push @sub_tree, ['GET', $offset - length($piece), $offset, $self->parse_expr(\
$name)];
1192 $self->throw('parse', "Parse error during interpolate node");
1196 ### replace the tree
1197 splice @$tree, -1, 1, @sub_tree;
1200 ###----------------------------------------------------------------###
1203 ### allow for the parse tree to store literals
1204 return $_[1] if ! ref $_[1];
1208 my $ARGS = shift || {};
1211 ### determine the top level of this particular variable access
1213 my $name = $var->[$i++];
1214 my $args = $var->[$i++];
1215 warn "play_expr: begin \"$name\"\n" if trace
;
1217 if (ref $name eq 'SCALAR') { # a scalar literal
1219 } elsif (ref $name eq 'REF') { # operator
1220 return $self->play_operator($$name) if ${ $name }->[0] eq '..';
1221 $ref = $self->play_operator($$name);
1222 } else { # a named variable access (ie via $name.foo)
1223 $name = $self->play_expr($name);
1224 if (defined $name) {
1225 return if $name =~ $QR_PRIVATE; # don't allow vars that begin with _
1226 $ref = $self->{'_vars'}->{$name};
1229 } elsif (defined $name) {
1230 if ($ARGS->{'is_namespace_during_compile'}) {
1231 $ref = $self->{'NAMESPACE'}->{$name};
1233 return if $name =~ $QR_PRIVATE; # don't allow vars that begin with _
1234 $ref = $self->{'_vars'}->{$name};
1235 $ref = $VOBJS->{$name} if ! defined $ref;
1241 while (defined $ref) {
1243 ### check at each point if the rurned thing was a code
1244 if (UNIVERSAL
::isa
($ref, 'CODE')) {
1245 my @results = $ref->($args ? map { $self->play_expr($_) } @$args : ());
1246 if (defined $results[0]) {
1247 $ref = ($#results > 0) ? \
@results : $results[0];
1248 } elsif (defined $results[1]) {
1249 die $results[1]; # TT behavior - why not just throw ?
1256 ### descend one chained level
1257 last if $i >= $#$var;
1258 my $was_dot_call = $ARGS->{'no_dots'} ? 1 : $var->[$i++] eq '.';
1259 $name = $var->[$i++];
1260 $args = $var->[$i++];
1261 warn "play_expr: nested \"$name\"\n" if trace
;
1263 ### allow for named portions of a variable name (foo.$name.bar)
1265 if (ref($name) eq 'ARRAY') {
1266 $name = $self->play_expr($name);
1267 if (! defined($name) || $name =~ $QR_PRIVATE || $name =~ /^\./) {
1272 die "Shouldn't get a ". ref($name) ." during a vivify on chain";
1275 if ($name =~ $QR_PRIVATE) { # don't allow vars that begin with _
1280 ### allow for scalar and filter access (this happens for every non virtual method call)
1282 if ($SCALAR_OPS->{$name}) { # normal scalar op
1283 $ref = $SCALAR_OPS->{$name}->($ref, $args ? map { $self->play_expr($_) } @$args : ());
1285 } elsif ($LIST_OPS->{$name}) { # auto-promote to list and use list op
1286 $ref = $LIST_OPS->{$name}->([$ref], $args ? map { $self->play_expr($_) } @$args : ());
1288 } elsif (my $filter = $self->{'FILTERS'}->{$name} # filter configured in Template args
1289 || $FILTER_OPS->{$name} # predefined filters in CET
1290 || (UNIVERSAL
::isa
($name, 'CODE') && $name) # looks like a filter sub passed in the stash
1291 || $self->list_filters->{$name}) { # filter defined in Template::Filters
1293 if (UNIVERSAL
::isa
($filter, 'CODE')) {
1294 $ref = eval { $filter->($ref) }; # non-dynamic filter - no args
1296 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1299 } elsif (! UNIVERSAL
::isa
($filter, 'ARRAY')) {
1300 $self->throw('filter', "invalid FILTER entry for '$name' (not a CODE ref)");
1302 } elsif (@$filter == 2 && UNIVERSAL
::isa
($filter->[0], 'CODE')) { # these are the TT style filters
1304 my $sub = $filter->[0];
1305 if ($filter->[1]) { # it is a "dynamic filter" that will return a sub
1306 ($sub, my $err) = $sub->($self->context, $args ? map { $self->play_expr($_) } @$args : ());
1307 if (! $sub && $err) {
1308 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1310 } elsif (! UNIVERSAL
::isa
($sub, 'CODE')) {
1311 $self->throw('filter', "invalid FILTER for '$name' (not a CODE ref)")
1312 if ref($sub) !~ /Template::Exception$/;
1316 $ref = $sub->($ref);
1319 $self->throw('filter', $err) if ref($err) !~ /Template::Exception$/;
1322 } else { # this looks like our vmethods turned into "filters" (a filter stored under a name)
1323 $self->throw('filter', 'Recursive filter alias \"$name\"') if $seen_filters{$name} ++;
1324 $var = [$name, 0, '|', @$filter, @{$var}[$i..$#$var]]; # splice the filter into our current tree
1327 if (scalar keys %seen_filters
1328 && $seen_filters{$var->[$i - 5] || ''}) {
1329 $self->throw('filter', "invalid FILTER entry for '".$var->[$i - 5]."' (not a CODE ref)");
1337 ### method calls on objects
1338 if ($was_dot_call && UNIVERSAL
::can
($ref, 'can')) {
1339 my @args = $args ? map { $self->play_expr($_) } @$args : ();
1340 my @results = eval { $ref->$name(@args) };
1342 my $class = ref $ref;
1343 die $@ if ref $@ || $@ !~ /Can\'t locate object method "\Q$name\E" via package "\Q$class\E"/;
1344 } elsif (defined $results[0]) {
1345 $ref = ($#results > 0) ? \
@results : $results[0];
1347 } elsif (defined $results[1]) {
1348 die $results[1]; # TT behavior - why not just throw ?
1353 # didn't find a method by that name - so fail down to hash and array access
1356 ### hash member access
1357 if (UNIVERSAL
::isa
($ref, 'HASH')) {
1358 if ($was_dot_call && exists($ref->{$name}) ) {
1359 $ref = $ref->{$name};
1360 } elsif ($HASH_OPS->{$name}) {
1361 $ref = $HASH_OPS->{$name}->($ref, $args ? map { $self->play_expr($_) } @$args : ());
1362 } elsif ($ARGS->{'is_namespace_during_compile'}) {
1363 return $var; # abort - can't fold namespace variable
1369 } elsif (UNIVERSAL
::isa
($ref, 'ARRAY')) {
1370 if ($name =~ m{ ^ -? $QR_NUM $ }ox) {
1371 $ref = $ref->[$name];
1372 } elsif ($LIST_OPS->{$name}) {
1373 $ref = $LIST_OPS->{$name}->($ref, $args ? map { $self->play_expr($_) } @$args : ());
1382 ### allow for undefinedness
1383 if (! defined $ref) {
1384 if ($self->{'_debug_undef'}) {
1385 my $chunk = $var->[$i - 2];
1386 $chunk = $self->play_expr($chunk) if ref($chunk) eq 'ARRAY';
1387 die "$chunk is undefined\n";
1389 $ref = $self->undefined_any($var);
1397 my ($self, $var, $val, $ARGS) = @_;
1401 ### allow for the parse tree to store literals - the literal is used as a name (like [% 'a' = 'A' %])
1402 $var = [$var, 0] if ! ref $var;
1404 ### determine the top level of this particular variable access
1405 my $ref = $var->[$i++];
1406 my $args = $var->[$i++];
1408 if (ref($ref) eq 'ARRAY') { # named access (ie via $name.foo)
1409 $ref = $self->play_expr($ref);
1410 if (defined $ref && $ref !~ $QR_PRIVATE) { # don't allow vars that begin with _
1412 return $self->{'_vars'}->{$ref} = $val;
1414 $ref = $self->{'_vars'}->{$ref} ||= {};
1419 } else { # all other types can't be set
1422 } elsif (defined $ref) {
1423 return if $ref =~ $QR_PRIVATE; # don't allow vars that begin with _
1425 return $self->{'_vars'}->{$ref} = $val;
1427 $ref = $self->{'_vars'}->{$ref} ||= {};
1431 while (defined $ref) {
1433 ### check at each point if the returned thing was a code
1434 if (UNIVERSAL
::isa
($ref, 'CODE')) {
1435 my @results = $ref->($args ? map { $self->play_expr($_) } @$args : ());
1436 if (defined $results[0]) {
1437 $ref = ($#results > 0) ? \
@results : $results[0];
1438 } elsif (defined $results[1]) {
1439 die $results[1]; # TT behavior - why not just throw ?
1445 ### descend one chained level
1446 last if $i >= $#$var;
1447 my $was_dot_call = $ARGS->{'no_dots'} ? 1 : $var->[$i++] eq '.';
1448 my $name = $var->[$i++];
1449 my $args = $var->[$i++];
1451 ### allow for named portions of a variable name (foo.$name.bar)
1453 if (ref($name) eq 'ARRAY') {
1454 $name = $self->play_expr($name);
1455 if (! defined($name) || $name =~ /^[_.]/) {
1459 die "Shouldn't get a ".ref($name)." during a vivify on chain";
1462 if ($name =~ $QR_PRIVATE) { # don't allow vars that begin with _
1470 ### method calls on objects
1471 } elsif (UNIVERSAL
::can
($ref, 'can')) {
1473 my @args = $args ? map { $self->play_expr($_) } @$args : ();
1478 my @results = eval { $ref->$name(@args) };
1480 if (defined $results[0]) {
1481 $ref = ($#results > 0) ? \
@results : $results[0];
1482 } elsif (defined $results[1]) {
1483 die $results[1]; # TT behavior - why not just throw ?
1487 return if $lvalueish;
1490 my $class = ref $ref;
1491 die $@ if ref $@ || $@ !~ /Can\'t locate object method "\Q$name\E" via package "\Q$class\E"/;
1492 # fall on down to "normal" accessors
1495 ### hash member access
1496 if (UNIVERSAL
::isa
($ref, 'HASH')) {
1498 return $ref->{$name} = $val;
1500 $ref = $ref->{$name} ||= {};
1505 } elsif (UNIVERSAL
::isa
($ref, 'ARRAY')) {
1506 if ($name =~ m{ ^ -? $QR_NUM $ }ox) {
1508 return $ref->[$name] = $val;
1510 $ref = $ref->[$name] ||= {};
1524 ###----------------------------------------------------------------###
1530 if ($OP_DISPATCH->{$tree->[0]}) {
1532 if ($OP_ASSIGN->{$tree->[0]}) {
1533 my $val = $OP_DISPATCH->{$tree->[0]}->( $self->play_expr($tree->[1]), $self->play_expr($tree->[2]) );
1534 $self->set_variable($tree->[1], $val);
1537 return $OP_DISPATCH->{$tree->[0]}->( map { $self->play_expr($tree->[$_]) } 1 .. $#$tree );
1541 my $op = $tree->[0];
1543 ### do custom and short-circuitable operators
1545 my $val = $self->play_expr($tree->[2]);
1546 $self->set_variable($tree->[1], $val);
1549 } elsif ($op eq '||' || $op eq 'or' || $op eq 'OR') {
1550 return $self->play_expr($tree->[1]) || $self->play_expr($tree->[2]) || '';
1552 } elsif ($op eq '&&' || $op eq 'and' || $op eq 'AND') {
1553 my $var = $self->play_expr($tree->[1]) && $self->play_expr($tree->[2]);
1554 return $var ? $var : 0;
1556 } elsif ($op eq '?') {
1558 return $self->play_expr($tree->[1]) ? $self->play_expr($tree->[2]) : $self->play_expr($tree->[3]);
1560 } elsif ($op eq '++') {
1562 my $val = 0 + $self->play_expr($tree->[1]);
1563 $self->set_variable($tree->[1], $val + 1);
1564 return $tree->[2] ? $val : $val + 1; # ->[2] is set to 1 during parsing of postfix ops
1566 } elsif ($op eq '--') {
1568 my $val = 0 + $self->play_expr($tree->[1]);
1569 $self->set_variable($tree->[1], $val - 1);
1570 return $tree->[2] ? $val : $val - 1; # ->[2] is set to 1 during parsing of postfix ops
1573 $self->throw('operator', "Un-implemented operation $op");
1576 ###----------------------------------------------------------------###
1579 my ($self, $tag_ref, $node) = @_;
1581 my $block_name = '';
1582 if ($$tag_ref =~ s{ ^ (\w+ (?: :\w+)*) \s* (?! [\.\|]) }{}x
1583 || $$tag_ref =~ s{ ^ '(|.*?[^\\])' \s* (?! [\.\|]) }{}x
1584 || $$tag_ref =~ s{ ^ "(|.*?[^\\])" \s* (?! [\.\|]) }{}x
1587 ### allow for nested blocks to have nested names
1588 my @names = map {$_->[3]} grep {$_->[0] eq 'BLOCK'} @{ $self->{'_state'} };
1589 $block_name = join("/", @names, $block_name) if scalar @names;
1596 my ($self, $block_name, $node, $out_ref) = @_;
1598 ### store a named reference - but do nothing until something processes it
1599 $self->{'BLOCKS'}->{$block_name} = {
1600 _tree
=> $node->[4],
1601 name
=> $self->{'_vars'}->{'component'}->{'name'} .'/'. $block_name,
1607 sub parse_CALL
{ $DIRECTIVES->{'GET'}->[0]->(@_) }
1609 sub play_CALL
{ $DIRECTIVES->{'GET'}->[1]->(@_); return }
1612 my ($self, $tag_ref) = @_;
1613 return if $$tag_ref =~ s{ ^ DEFAULT \s* }{}x;
1614 return $self->parse_expr($tag_ref);
1618 my ($self, $tag_ref) = @_;
1619 return $self->parse_expr($tag_ref, {auto_quote
=> qr{ ^ (\w+ (?: \.\w+)*) $QR_AQ_SPACE }xo});
1623 my ($self, $undef, $node) = @_;
1624 $self->throw(lc($node->[0]), 'Control exception', $node);
1628 my ($self, $undef, $node, $out_ref) = @_;
1633 my ($self, $tag_ref) = @_;
1634 $$tag_ref =~ s{ ^ (on | off | format) \s* }{}xi || $self->throw('parse', "Unknown DEBUG option");
1636 if ($ret->[0] eq 'format') {
1637 $$tag_ref =~ s{ ^ ([\"\']) (|.*?[^\\]) \1 \s* }{}xs || $self->throw('parse', "Missing format string");
1644 my ($self, $ref) = @_;
1645 if ($ref->[0] eq 'on') {
1646 delete $self->{'_debug_off'};
1647 } elsif ($ref->[0] eq 'off') {
1648 $self->{'_debug_off'} = 1;
1649 } elsif ($ref->[0] eq 'format') {
1650 $self->{'_debug_format'} = $ref->[1];
1654 sub parse_DEFAULT
{ $DIRECTIVES->{'SET'}->[0]->(@_) }
1657 my ($self, $set) = @_;
1659 my ($op, $set, $default) = @$_;
1660 next if ! defined $set;
1661 my $val = $self->play_expr($set);
1663 $default = defined($default) ? $self->play_expr($default) : '';
1664 $self->set_variable($set, $default);
1671 my ($self, $tag_ref) = @_;
1672 my $ref = $self->parse_expr($tag_ref);
1677 my ($self, $ident, $node) = @_;
1678 require Data
::Dumper
;
1679 my $info = $self->node_info($node);
1683 $out = Data
::Dumper
::Dumper
($self->play_expr($ident));
1684 $var = $info->{'text'};
1685 $var =~ s/^[+\-~=]?\s*DUMP\s+//;
1686 $var =~ s/\s*[+\-~=]?$//;
1688 my @were_never_here = (qw(template component), grep {$_ =~ $QR_PRIVATE} keys %{ $self->{'_vars'} });
1689 local @{ $self->{'_vars'} }{ @were_never_here };
1690 delete @{ $self->{'_vars'} }{ @were_never_here };
1691 $out = Data
::Dumper
::Dumper
($self->{'_vars'});
1692 $var = 'EntireStash';
1694 if ($ENV{'REQUEST_METHOD'}) {
1696 $out = "<pre>$out</pre>";
1697 $out =~ s/\$VAR1/$var/;
1698 $out = "<b>DUMP: File \"$info->{file}\" line $info->{line}</b>$out";
1700 $out =~ s/\$VAR1/$var/;
1707 my ($self, $tag_ref) = @_;
1709 if ($$tag_ref =~ s{ ^ ([^\W\d]\w*) \s* = \s* }{}x) {
1713 my $filter = $self->parse_expr($tag_ref);
1714 $filter = '' if ! defined $filter;
1716 return [$name, $filter];
1720 my ($self, $ref, $node, $out_ref) = @_;
1721 my ($name, $filter) = @$ref;
1723 return '' if ! @$filter;
1725 $self->{'FILTERS'}->{$name} = $filter if length $name;
1727 my $sub_tree = $node->[4];
1731 eval { $self->execute_tree($sub_tree, \
$out) };
1732 die $@ if $@ && ref($@) !~ /Template::Exception$/;
1734 my $var = [\
$out, 0, '|', @$filter]; # make a temporary var out of it
1737 return $DIRECTIVES->{'GET'}->[1]->($self, $var, $node, $out_ref);
1741 my ($self, $tag_ref) = @_;
1742 my $items = $self->parse_expr($tag_ref);
1744 if ($$tag_ref =~ s{ ^ (= | [Ii][Nn]\b) \s* }{}x) {
1746 $items = $self->parse_expr($tag_ref);
1748 return [$var, $items];
1752 my ($self, $ref, $node, $out_ref) = @_;
1754 ### get the items - make sure it is an arrayref
1755 my ($var, $items) = @$ref;
1757 $items = $self->play_expr($items);
1758 return '' if ! defined $items;
1760 if (ref($items) !~ /Iterator$/) {
1761 $items = $PACKAGE_ITERATOR->new($items);
1764 my $sub_tree = $node->[4];
1766 local $self->{'_vars'}->{'loop'} = $items;
1768 ### if the FOREACH tag sets a var - then nothing but the loop var gets localized
1770 my ($item, $error) = $items->get_first;
1773 $self->set_variable($var, $item);
1775 ### execute the sub tree
1776 eval { $self->execute_tree($sub_tree, $out_ref) };
1778 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
1779 if ($err->type eq 'next') {
1780 ($item, $error) = $items->get_next;
1783 last if $err->type =~ /last|break/;
1788 ($item, $error) = $items->get_next;
1790 die $error if $error && $error != 3; # Template::Constants::STATUS_DONE;
1791 ### if the FOREACH tag doesn't set a var - then everything gets localized
1794 ### localize variable access for the foreach
1795 my $swap = $self->{'_vars'};
1796 local $self->{'_vars'} = my $copy = {%$swap};
1798 ### iterate use the iterator object
1799 #foreach (my $i = $items->index; $i <= $#$vals; $items->index(++ $i)) {
1800 my ($item, $error) = $items->get_first;
1803 if (ref($item) eq 'HASH') {
1804 @$copy{keys %$item} = values %$item;
1807 ### execute the sub tree
1808 eval { $self->execute_tree($sub_tree, $out_ref) };
1810 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
1811 if ($err->type eq 'next') {
1812 ($item, $error) = $items->get_next;
1815 last if $err->type =~ /last|break/;
1820 ($item, $error) = $items->get_next;
1822 die $error if $error && $error != 3; # Template::Constants::STATUS_DONE;
1829 my ($self, $tag_ref) = @_;
1830 my $ref = $self->parse_expr($tag_ref);
1831 $self->throw('parse', "Missing variable name") if ! defined $ref;
1836 my ($self, $ident, $node) = @_;
1837 my $var = $self->play_expr($ident);
1838 return (! defined $var) ? $self->undefined_get($ident, $node) : $var;
1842 my ($self, $tag_ref) = @_;
1843 return $self->parse_expr($tag_ref);
1847 my ($self, $var, $node, $out_ref) = @_;
1849 my $val = $self->play_expr($var);
1851 my $body_ref = $node->[4] ||= [];
1852 $self->execute_tree($body_ref, $out_ref);
1856 while ($node = $node->[5]) { # ELSE, ELSIF's
1857 if ($node->[0] eq 'ELSE') {
1858 my $body_ref = $node->[4] ||= [];
1859 $self->execute_tree($body_ref, $out_ref);
1862 my $var = $node->[3];
1863 my $val = $self->play_expr($var);
1865 my $body_ref = $node->[4] ||= [];
1866 $self->execute_tree($body_ref, $out_ref);
1873 sub parse_INCLUDE
{ $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
1876 my ($self, $tag_ref, $node, $out_ref) = @_;
1878 ### localize the swap
1879 my $swap = $self->{'_vars'};
1880 local $self->{'_vars'} = {%$swap};
1882 ### localize the blocks
1883 my $blocks = $self->{'BLOCKS'};
1884 local $self->{'BLOCKS'} = {%$blocks};
1886 my $str = $DIRECTIVES->{'PROCESS'}->[1]->($self, $tag_ref, $node, $out_ref);
1891 sub parse_INSERT
{ $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
1894 my ($self, $var, $node, $out_ref) = @_;
1895 my ($names, $args) = @$var;
1897 foreach my $name (@$names) {
1898 my $filename = $self->play_expr($name);
1899 $$out_ref .= $self->_insert($filename);
1906 my ($self, $tag_ref, $node) = @_;
1907 my $copy = $$tag_ref;
1909 my $name = $self->parse_expr(\
$copy, {auto_quote
=> qr{ ^ (\w+) $QR_AQ_NOTDOT }xo});
1910 $self->throw('parse', "Missing macro name") if ! defined $name;
1912 $name = [ $name, 0 ];
1916 if ($copy =~ s{ ^ \( \s* }{}x) {
1917 $args = $self->parse_args(\
$copy, {positional_only
=> 1});
1918 $copy =~ s
{ ^ \
) \s
* }{}x
|| $self->throw('parse.missing', "Missing close ')'");
1921 $node->[6] = 1; # set a flag to keep parsing
1923 return [$name, $args];
1927 my ($self, $ref, $node, $out_ref) = @_;
1928 my ($name, $args) = @$ref;
1930 ### get the sub tree
1931 my $sub_tree = $node->[4];
1932 if (! $sub_tree || ! $sub_tree->[0]) {
1933 $self->set_variable($name, undef);
1935 } elsif ($sub_tree->[0]->[0] eq 'BLOCK') {
1936 $sub_tree = $sub_tree->[0]->[4];
1939 my $self_copy = $self->weak_copy;
1941 ### install a closure in the stash that will handle the macro
1942 $self->set_variable($name, sub {
1944 my $copy = $self_copy->{'_vars'};
1945 local $self_copy->{'_vars'}= {%$copy};
1948 my $named = pop(@_) if $_[-1] && UNIVERSAL
::isa
($_[-1],'HASH') && $#_ > $#$args;
1949 my @positional = @_;
1950 foreach my $var (@$args) {
1951 $self_copy->set_variable($var, shift(@positional));
1953 foreach my $name (sort keys %$named) {
1954 $self_copy->set_variable([$name, 0], $named->{$name});
1957 ### finally - run the sub tree
1959 $self_copy->execute_tree($sub_tree, \
$out);
1967 my ($self, $hash) = @_;
1969 if ($self->{'_top_level'}) {
1970 $ref = $self->{'_vars'}->{'template'} ||= {};
1972 $ref = $self->{'_vars'}->{'component'} ||= {};
1974 foreach my $key (keys %$hash) {
1975 next if $key eq 'name' || $key eq 'modtime';
1976 $ref->{$key} = $hash->{$key};
1981 sub parse_PERL
{ shift-
>{'_in_perl'} = 1; return }
1984 my ($self, $info, $node, $out_ref) = @_;
1985 $self->throw('perl', 'EVAL_PERL not set') if ! $self->{'EVAL_PERL'};
1987 ### fill in any variables
1988 my $perl = $node->[4] || return;
1990 $self->execute_tree($perl, \
$out);
1991 $out = $1 if $out =~ /^(.+)$/s; # blatant untaint - shouldn't use perl anyway
1996 package CGI
::Ex
::Template
::Perl
;
1998 my $context = $self->context;
1999 my $stash = $context->stash;
2001 ### setup a fake handle
2003 tie
*PERLOUT
, $CGI::Ex
::Template
::PACKAGE_PERL_HANDLE
, $out_ref;
2004 my $old_fh = select PERLOUT
;
2009 ### put the handle back
2017 $self->throw('undef', $err) if ref($err) !~ /Template::Exception$/;
2025 my ($self, $tag_ref) = @_;
2026 my $info = [[], []];
2027 while (defined(my $filename = $self->parse_expr($tag_ref, {
2028 auto_quote
=> qr{ ^ ($QR_FILENAME | \w+ (?: :\w+)* ) $QR_AQ_SPACE }xo,
2030 push @{$info->[0]}, $filename;
2031 last if $$tag_ref !~ s{ ^ \+ \s* }{}x;
2034 ### allow for post process variables
2035 while (length $$tag_ref) {
2036 last if $$tag_ref =~ / ^ (\w+) (?: ;|$|\s)/x && $DIRECTIVES->{$1}; ### looks like a directive - we are done
2038 my $var = $self->parse_expr($tag_ref);
2039 last if ! defined $var;
2040 if ($$tag_ref !~ s{ ^ = >? \s* }{}x) {
2041 $self->throw('parse.missing.equals', 'Missing equals while parsing args');
2044 my $val = $self->parse_expr($tag_ref);
2045 push @{$info->[1]}, [$var, $val];
2046 $$tag_ref =~ s{ ^ , \s* $QR_COMMENTS }{}ox if $val;
2053 my ($self, $info, $node, $out_ref) = @_;
2055 my ($files, $args) = @$info;
2059 my ($key, $val) = @$_;
2060 $val = $self->play_expr($val);
2061 if (ref($key) && @$key == 2 && $key->[0] eq 'import' && UNIVERSAL
::isa
($val, 'HASH')) { # import ?! - whatever
2062 foreach my $key (keys %$val) {
2063 $self->set_variable([$key,0], $val->{$key});
2067 $self->set_variable($key, $val);
2070 ### iterate on any passed block or filename
2071 foreach my $ref (@$files) {
2072 next if ! defined $ref;
2073 my $filename = $self->play_expr($ref);
2074 my $out = ''; # have temp item to allow clear to correctly clear
2076 ### normal blocks or filenames
2077 if (! ref $filename) {
2078 eval { $self->_process($filename, $self->{'_vars'}, \
$out) }; # restart the swap - passing it our current stash
2080 ### allow for $template which is used in some odd instances
2082 $self->throw('process', "Unable to process document $filename") if $ref->[0] ne 'template';
2083 $self->throw('process', "Recursion detected in $node->[0] \$template") if $self->{'_process_dollar_template'};
2084 local $self->{'_process_dollar_template'} = 1;
2085 local $self->{'_vars'}->{'component'} = my $doc = $filename;
2086 return if ! $doc->{'_tree'};
2088 ### execute and trim
2089 eval { $self->execute_tree($doc->{'_tree'}, \
$out) };
2090 if ($self->{'TRIM'}) {
2091 $out =~ s{ \s+ $ }{}x;
2092 $out =~ s{ ^ \s+ }{}x;
2095 ### handle exceptions
2097 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2098 $err->doc($doc) if $doc && $err->can('doc') && ! $err->doc;
2103 ### append any output
2106 die $err if ref($err) !~ /Template::Exception$/ || $err->type !~ /return/;
2114 my ($self, $info, $node, $out_ref) = @_;
2115 $self->throw('perl', 'EVAL_PERL not set') if ! $self->{'EVAL_PERL'};
2117 ### fill in any variables
2118 my $tree = $node->[4] || return;
2120 $self->execute_tree($tree, \
$perl);
2121 $perl = $1 if $perl =~ /^(.+)$/s; # blatant untaint - shouldn't use perl anyway
2127 package CGI
::Ex
::Template
::Perl
;
2129 my $context = $self->context;
2130 my $stash = $context->stash;
2137 $$out_ref .= $output;
2140 $self->throw('undef', $err) if ref($err) !~ /Template::Exception$/;
2148 my ($self, $tag_ref, $node, $initial_op, $initial_var) = @_;
2150 my $copy = $$tag_ref;
2154 if ($$tag_ref =~ $QR_DIRECTIVE # find a word
2155 && $DIRECTIVES->{$1}) { # is it a directive - if so set up capturing
2156 $node->[6] = 1; # set a flag to keep parsing
2157 my $val = $node->[4] ||= []; # setup storage
2158 return [[$initial_op, $initial_var, $val]];
2159 } else { # get a normal variable
2160 return [[$initial_op, $initial_var, $self->parse_expr($tag_ref)]];
2164 while (length $$tag_ref) {
2165 my $set = $self->parse_expr($tag_ref);
2166 last if ! defined $set;
2168 if ($$tag_ref =~ s{ ^ ($QR_OP_ASSIGN) >? \s* }{}x) {
2170 if ($$tag_ref =~ $QR_DIRECTIVE # find a word
2171 && $DIRECTIVES->{$1}) { # is it a directive - if so set up capturing
2172 $node->[6] = 1; # set a flag to keep parsing
2173 my $val = $node->[4] ||= []; # setup storage
2174 push @SET, [$op, $set, $val];
2176 } else { # get a normal variable
2177 push @SET, [$op, $set, $self->parse_expr($tag_ref)];
2180 push @SET, ['=', $set, undef];
2187 my ($self, $set, $node) = @_;
2189 my ($op, $set, $val) = @$_;
2190 if (! defined $val) { # not defined
2192 } elsif ($node->[4] && $val == $node->[4]) { # a captured directive
2193 my $sub_tree = $node->[4];
2194 $sub_tree = $sub_tree->[0]->[4] if $sub_tree->[0] && $sub_tree->[0]->[0] eq 'BLOCK';
2196 $self->execute_tree($sub_tree, \
$val);
2197 } else { # normal var
2198 $val = $self->play_expr($val);
2201 if ($OP_DISPATCH->{$op}) {
2203 $val = $OP_DISPATCH->{$op}->($self->play_expr($set), $val);
2206 $self->set_variable($set, $val);
2211 sub parse_SWITCH
{ $DIRECTIVES->{'GET'}->[0]->(@_) }
2214 my ($self, $var, $node, $out_ref) = @_;
2216 my $val = $self->play_expr($var);
2217 $val = '' if ! defined $val;
2218 ### $node->[4] is thrown away
2221 while ($node = $node->[5]) { # CASES
2222 my $var = $node->[3];
2223 if (! defined $var) {
2224 $default = $node->[4];
2228 my $val2 = $self->play_expr($var);
2229 $val2 = [$val2] if ! UNIVERSAL
::isa
($val2, 'ARRAY');
2230 for my $test (@$val2) { # find matching values
2231 next if ! defined $val && defined $test;
2232 next if defined $val && ! defined $test;
2233 if ($val ne $test) { # check string-wise first - then numerical
2234 next if $val !~ m{ ^ -? $QR_NUM $ }ox;
2235 next if $test !~ m{ ^ -? $QR_NUM $ }ox;
2236 next if $val != $test;
2239 my $body_ref = $node->[4] ||= [];
2240 $self->execute_tree($body_ref, $out_ref);
2246 $self->execute_tree($default, $out_ref);
2253 my ($self, $tag_ref, $node) = @_;
2254 my $name = $self->parse_expr($tag_ref, {auto_quote
=> qr{ ^ (\w+ (?: \.\w+)*) $QR_AQ_SPACE }xo});
2255 $self->throw('parse.missing', "Missing name in THROW", $node) if ! $name;
2256 my $args = $self->parse_args($tag_ref);
2257 return [$name, $args];
2261 my ($self, $ref, $node) = @_;
2262 my ($name, $args) = @$ref;
2263 $name = $self->play_expr($name);
2264 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2265 $self->throw($name, \
@args, $node);
2269 my ($self, $foo, $node, $out_ref) = @_;
2272 my $body_ref = $node->[4];
2273 eval { $self->execute_tree($body_ref, \
$out) };
2276 if (! $node->[5]) { # no catch or final
2277 if (! $err) { # no final block and no error
2281 $self->throw('parse.missing', "Missing CATCH block", $node);
2284 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2285 if ($err->type =~ /stop|return/) {
2291 ### loop through the nested catch and final blocks
2294 my $type = $err ? $err->type : '';
2296 while ($node = $node->[5]) { # CATCH
2297 if ($node->[0] eq 'FINAL') {
2298 $final = $node->[4];
2302 my $name = $self->play_expr($node->[3]);
2303 $name = '' if ! defined $name || lc($name) eq 'default';
2304 if ($type =~ / ^ \Q$name\E \b /x
2305 && (! defined($last_found) || length($last_found) < length($name))) { # more specific wins
2306 $catch_body_ref = $node->[4] || [];
2307 $last_found = $name;
2311 ### play the best catch block
2313 if (! $catch_body_ref) {
2317 local $self->{'_vars'}->{'error'} = $err;
2318 local $self->{'_vars'}->{'e'} = $err;
2319 eval { $self->execute_tree($catch_body_ref, \
$out) };
2327 $self->execute_tree($final, \
$out) if $final;
2335 my $ref = $DIRECTIVES->{'IF'}->[0]->(@_);
2336 return [ \
[ '!', $ref ], 0 ];
2339 sub play_UNLESS
{ return $DIRECTIVES->{'IF'}->[1]->(@_) }
2342 my ($self, $tag_ref) = @_;
2345 my $copy = $$tag_ref;
2346 if (defined(my $_var = $self->parse_expr(\
$copy, {auto_quote
=> qr{ ^ (\w+) $QR_AQ_NOTDOT }xo}))
2347 && $copy =~ s{ ^ = >? \s* $QR_COMMENTS }{}ox) {
2353 my $module = $self->parse_expr(\
$copy, {auto_quote
=> qr{ ^ (\w+ (?: (?:\.|::) \w+)*) $QR_AQ_NOTDOT }xo});
2354 $self->throw('parse', "Missing plugin name while parsing $$tag_ref") if ! defined $module;
2355 $module =~ s/\./::/g;
2358 my $open = $copy =~ s{ ^ \( \s* $QR_COMMENTS }{}ox;
2359 $args = $self->parse_args(\
$copy);
2362 $copy =~ s
{ ^ \
) \s
* $QR_COMMENTS }{}ox
|| $self->throw('parse.missing', "Missing close ')'");
2366 return [$var, $module, $args];
2370 my ($self, $ref, $node, $out_ref) = @_;
2371 my ($var, $module, $args) = @$ref;
2373 ### get the stash storage location - default to the module
2374 $var = $module if ! defined $var;
2375 my @var = map {($_, 0, '.')} split /(?:\.|::)/, $var;
2376 pop @var; # remove the trailing '.'
2378 ### look for a plugin_base
2379 my $base = $self->{'PLUGIN_BASE'} || 'Template::Plugin'; # I'm not maintaining plugins - leave that to TT
2380 my $package = $self->{'PLUGINS'}->{$module} ? $self->{'PLUGINS'}->{$module}
2381 : $self->{'PLUGIN_FACTORY'}->{$module} ? $self->{'PLUGIN_FACTORY'}->{$module}
2382 : "${base}::${module}";
2383 my $require = "$package.pm";
2384 $require =~ s
|::|/|g
;
2386 ### try and load the module - fall back to bare module if allowed
2388 if ($self->{'PLUGIN_FACTORY'}->{$module} || eval {require $require}) {
2389 my $shape = $package->load;
2390 my $context = $self->context;
2391 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2392 $obj = $shape->new($context, @args);
2393 } elsif (lc($module) eq 'iterator') { # use our iterator if none found (TT's works just fine)
2394 $obj = $PACKAGE_ITERATOR->new($args ? $self->play_expr($args->[0]) : []);
2395 } elsif (my @packages = grep {lc($package) eq lc($_)} @{ $self->list_plugins({base
=> $base}) }) {
2396 foreach my $package (@packages) {
2397 my $require = "$package.pm";
2398 $require =~ s
|::|/|g
;
2399 eval {require $require} || next;
2400 my $shape = $package->load;
2401 my $context = $self->context;
2402 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2403 $obj = $shape->new($context, @args);
2405 } elsif ($self->{'LOAD_PERL'}) {
2406 my $require = "$module.pm";
2407 $require =~ s
|::|/|g
;
2408 if (eval {require $require}) {
2409 my @args = $args ? map { $self->play_expr($_) } @$args : ();
2410 $obj = $module->new(@args);
2413 if (! defined $obj) {
2414 my $err = "$module: plugin not found";
2415 $self->throw('plugin', $err);
2419 $self->set_variable(\
@var, $obj);
2425 my ($self, $var, $node, $out_ref) = @_;
2426 return '' if ! defined $var;
2428 my $sub_tree = $node->[4];
2430 ### iterate use the iterator object
2431 my $count = $WHILE_MAX;
2432 while (--$count > 0) {
2434 $self->play_expr($var) || last;
2436 ### execute the sub tree
2437 eval { $self->execute_tree($sub_tree, $out_ref) };
2439 if (UNIVERSAL
::isa
($err, $PACKAGE_EXCEPTION)) {
2440 next if $err->type =~ /next/;
2441 last if $err->type =~ /last|break/;
2446 die "WHILE loop terminated (> $WHILE_MAX iterations)\n" if ! $count;
2451 sub parse_WRAPPER
{ $DIRECTIVES->{'INCLUDE'}->[0]->(@_) }
2454 my ($self, $var, $node, $out_ref) = @_;
2455 my $sub_tree = $node->[4] || return;
2457 my ($names, $args) = @$var;
2460 $self->execute_tree($sub_tree, \
$out);
2462 foreach my $name (reverse @$names) {
2463 local $self->{'_vars'}->{'content'} = $out;
2465 $DIRECTIVES->{'INCLUDE'}->[1]->($self, [[$name], $args], $node, \
$out);
2472 ###----------------------------------------------------------------###
2476 $self->{'_vars'} = shift if $#_ == 0;
2477 return $self->{'_vars'} ||= {};
2480 sub include_filename
{
2481 my ($self, $file) = @_;
2482 if ($file =~ m
|^/|) {
2483 $self->throw('file', "$file absolute paths are not allowed (set ABSOLUTE option)") if ! $self->{'ABSOLUTE'};
2484 return $file if -e
$file;
2485 } elsif ($file =~ m{(^|/)\.\./}) {
2486 $self->throw('file', "$file relative paths are not allowed (set RELATIVE option)") if ! $self->{'RELATIVE'};
2487 return $file if -e
$file;
2490 my $paths = $self->{'INCLUDE_PATHS'} ||= do {
2491 # TT does this everytime a file is looked up - we are going to do it just in time - the first time
2492 my $paths = $self->{'INCLUDE_PATH'} || $self->throw('file', "INCLUDE_PATH not set");
2493 $paths = $paths->() if UNIVERSAL
::isa
($paths, 'CODE');
2494 $paths = $self->split_paths($paths) if ! UNIVERSAL
::isa
($paths, 'ARRAY');
2495 $paths; # return of the do
2497 foreach my $path (@$paths) {
2498 return "$path/$file" if -e
"$path/$file";
2501 $self->throw('file', "$file: not found");
2505 my ($self, $path) = @_;
2506 return $path if ref $path;
2507 my $delim = $self->{'DELIMITER'} || ':';
2508 $delim = ($delim eq ':' && $^O eq 'MSWin32') ? qr
|:(?!/)| : qr
|\Q
$delim\E
|;
2509 return [split $delim, $path];
2513 my ($self, $file) = @_;
2514 return $self->slurp($self->include_filename($file));
2518 my ($self, $file) = @_;
2520 open(FH
, "<$file") || $self->throw('file', "$file couldn't be opened: $!");
2521 read FH
, my $txt, -s
$file;
2526 sub process_simple
{
2528 my $in = shift || die "Missing input";
2529 my $swap = shift || die "Missing variable hash";
2530 my $out = shift || die "Missing output string ref";
2533 delete $self->{'_debug_off'};
2534 delete $self->{'_debug_format'};
2535 local $self->{'_start_top_level'} = 1;
2536 $self->_process($in, $swap, $out);
2539 if ($err->type !~ /stop|return|next|last|break/) {
2540 $self->{'error'} = $err;
2548 my ($self, $in, $swap, $out, @ARGS) = @_;
2549 delete $self->{'error'};
2552 $args = ($#ARGS == 0 && UNIVERSAL
::isa
($ARGS[0], 'HASH')) ? {%{$ARGS[0]}} : {@ARGS} if scalar @ARGS;
2553 $self->DEBUG("set binmode\n") if $DEBUG && $args->{'binmode'}; # holdover for TT2 tests
2558 if (UNIVERSAL
::isa
($in, 'SCALAR')) { # reference to a string
2560 } elsif (UNIVERSAL
::isa
($in, 'CODE')) {
2562 $content = \
$content;
2563 } else { # should be a file handle
2566 $content = \
$content;
2569 ### should be a filename
2574 ### prepare block localization
2575 my $blocks = $self->{'BLOCKS'} ||= {};
2582 ### localize the stash
2584 my $var1 = $self->{'_vars'} ||= {};
2585 my $var2 = $self->{'VARIABLES'} || $self->{'PRE_DEFINE'} || {};
2586 $var1->{'global'} ||= {}; # allow for the "global" namespace - that continues in between processing
2587 my $copy = {%$var2, %$var1, %$swap};
2588 local $copy->{'template'};
2590 local $self->{'BLOCKS'} = $blocks = {%$blocks}; # localize blocks - but save a copy to possibly restore
2592 delete $self->{'_debug_off'};
2593 delete $self->{'_debug_format'};
2595 ### handle pre process items that go before every document
2596 if ($self->{'PRE_PROCESS'}) {
2597 foreach my $name (@{ $self->split_paths($self->{'PRE_PROCESS'}) }) {
2599 $self->_process($name, $copy, \
$out);
2600 $output = $out . $output;
2604 ### handle the process config - which loads a template in place of the real one
2605 if (exists $self->{'PROCESS'}) {
2606 ### load the meta data for the top document
2607 my $doc = $self->load_parsed_tree($content) || {};
2608 my $meta = ($doc->{'_tree'} && ref($doc->{'_tree'}->[0]) && $doc->{'_tree'}->[0]->[0] eq 'METADEF')
2609 ? $doc->{'_tree'}->[0]->[3] : {};
2611 $copy->{'template'} = $doc;
2612 @{ $doc }{keys %$meta} = values %$meta;
2614 ### process any other templates
2615 foreach my $name (@{ $self->split_paths($self->{'PROCESS'}) }) {
2616 next if ! length $name;
2617 $self->_process($name, $copy, \
$output);
2620 ### handle "normal" content
2622 local $self->{'_start_top_level'} = 1;
2623 $self->_process($content, $copy, \
$output);
2627 ### handle post process items that go after every document
2628 if ($self->{'POST_PROCESS'}) {
2629 foreach my $name (@{ $self->split_paths($self->{'POST_PROCESS'}) }) {
2630 $self->_process($name, $copy, \
$output);
2636 $err = $self->exception('undef', $err) if ref($err) !~ /Template::Exception$/;
2637 if ($err->type !~ /stop|return|next|last|break/) {
2638 $self->{'error'} = $err;
2645 ### clear blocks as asked (AUTO_RESET) defaults to on
2646 $self->{'BLOCKS'} = $blocks if exists($self->{'AUTO_RESET'}) && ! $self->{'AUTO_RESET'};
2648 ### send the content back out
2649 $out ||= $self->{'OUTPUT'};
2651 if (UNIVERSAL
::isa
($out, 'CODE')) {
2653 } elsif (UNIVERSAL
::can
($out, 'print')) {
2654 $out->print($output);
2655 } elsif (UNIVERSAL
::isa
($out, 'SCALAR')) { # reference to a string
2657 } elsif (UNIVERSAL
::isa
($out, 'ARRAY')) {
2658 push @$out, $output;
2659 } else { # should be a file handle
2662 } elsif ($out) { # should be a filename
2664 if ($out =~ m
|^/|) {
2665 if (! $self->{'ABSOLUTE'}) {
2666 $self->{'error'} = $self->throw('file', "ABSOLUTE paths disabled");
2670 } elsif ($out =~ m
|^\
.\
.?/|) {
2671 if (! $self->{'RELATIVE'}) {
2672 $self->{'error'} = $self->throw('file', "RELATIVE paths disabled");
2677 if (! $self->{'OUTPUT_PATH'}) {
2678 $self->{'error'} = $self->throw('file', "OUTPUT_PATH not set");
2680 $file = $self->{'OUTPUT_PATH'} . '/' . $out;
2685 if (open FH
, ">$file") {
2686 if (my $bm = $args->{'binmode'}) {
2687 if (+$bm == 1) { binmode FH
}
2688 else { binmode FH
, $bm }
2693 $self->{'error'} = $self->throw('file', "$out couldn't be opened for writing: $!");
2700 return if $self->{'error'};
2704 sub error
{ shift-
>{'error'} }
2708 print STDERR
"DEBUG: ", @_;
2711 ###----------------------------------------------------------------###
2714 my ($self, $type, $info, $node) = @_;
2715 return $type if ref($type) =~ /Template::Exception$/;
2716 if (ref($info) eq 'ARRAY') {
2717 my $hash = ref($info->[-1]) eq 'HASH' ? pop(@$info) : {};
2718 if (@$info >= 2 || scalar keys %$hash) {
2720 $hash->{$_} = $info->[$_] for 0 .. $#$info;
2721 $hash->{'args'} = $info;
2723 } elsif (@$info == 1) {
2730 return $PACKAGE_EXCEPTION->new($type, $info, $node);
2733 sub throw
{ die shift-
>exception(@_) }
2737 return bless {_template
=> $self}, $PACKAGE_CONTEXT; # a fake context
2741 my ($self, $ident, $node) = @_;
2742 return $self->{'UNDEFINED_GET'}->($self, $ident, $node) if $self->{'UNDEFINED_GET'};
2747 my ($self, $ident) = @_;
2748 return $self->{'UNDEFINED_ANY'}->($self, $ident) if $self->{'UNDEFINED_ANY'};
2754 return $self->{'_filters'} ||= eval { require Template
::Filters
; $Template::Filters
::FILTERS
} || {};
2759 my $args = shift || {};
2760 my $base = $args->{'base'} || '';
2762 return $self->{'_plugins'}->{$base} ||= do {
2766 my @dirs = grep {-d
$_} map {"$_/$base"} @INC;
2768 foreach my $dir (@dirs) {
2770 File
::Find
::find
(sub {
2771 my $mod = $base .'/'. ($File::Find
::name
=~ m
|^ $dir / (.*\w
) \
.pm
$|x
? $1 : return);
2773 push @plugins, $mod;
2777 \
@plugins; # return of the do
2781 ### get a copy of self without circular refs for use in closures
2785 if (eval { require Scalar
::Util
}
2786 && defined &Scalar
::Util
::weaken
) {
2788 Scalar
::Util
::weaken
($self_copy);
2790 $self_copy = bless {%$self}, ref($self); # hackish way to avoid circular refs on old perls (pre 5.8)
2796 my ($self, $node) = @_;
2797 my $info = $self->node_info($node);
2798 my $format = $self->{'_debug_format'} || $self->{'DEBUG_FORMAT'} || "\n## \$file line \$line : [% \$text %] ##\n";
2799 $format =~ s{\$(file|line|text)}{$info->{$1}}g
;
2804 my ($self, $node) = @_;
2805 my $doc = $self->{'_vars'}->{'component'};
2807 my $j = $node->[2] || return ''; # METADEF can be 0
2808 $doc->{'_content'} ||= do { my $s = $self->slurp($doc->{'_filename'}) ; \
$s };
2809 my $s = substr(${ $doc->{'_content'} }, $i, $j - $i);
2813 file
=> $doc->{'name'},
2814 line
=> $self->get_line_number_by_index($doc, $i),
2819 sub get_line_number_by_index
{
2820 my ($self, $doc, $index) = @_;
2821 ### get the line offsets for the doc
2822 my $lines = $doc->{'line_offsets'} ||= do {
2823 $doc->{'_content'} ||= do { my $s = $self->slurp($doc->{'_filename'}) ; \
$s };
2827 $i = index(${ $doc->{'_content'} }, "\n", $i) + 1;
2833 ### binary search them (this is fast even on big docs)
2834 return $#$lines + 1 if $index > $lines->[-1];
2835 my ($i, $j) = (0, $#$lines);
2837 return $i + 1 if abs($i - $j) <= 1;
2838 my $k = int(($i + $j) / 2);
2839 $j = $k if $lines->[$k] >= $index;
2840 $i = $k if $lines->[$k] <= $index;
2844 ###----------------------------------------------------------------###
2845 ### long virtual methods or filters
2846 ### many of these vmethods have used code from Template/Stash.pm to
2847 ### assure conformance with the TT spec.
2849 sub define_vmethod
{
2850 my ($self, $type, $name, $sub) = @_;
2851 if ( $type =~ /scalar|item/i) { $SCALAR_OPS->{$name} = $sub }
2852 elsif ($type =~ /array|list/i ) { $LIST_OPS->{ $name} = $sub }
2853 elsif ($type =~ /hash/i ) { $HASH_OPS->{ $name} = $sub }
2854 elsif ($type =~ /filter/i ) { $FILTER_OPS->{$name} = $sub }
2856 die "Invalid type vmethod type $type";
2861 sub vmethod_as_scalar
{
2862 my ($str, $pat) = @_;
2863 $pat = '%s' if ! defined $pat;
2865 return sprintf $pat, $str;
2868 sub vmethod_as_list
{
2869 my ($ref, $pat, $sep) = @_;
2870 $pat = '%s' if ! defined $pat;
2871 $sep = ' ' if ! defined $sep;
2873 return join($sep, map {sprintf $pat, $_} @$ref);
2876 sub vmethod_as_hash
{
2877 my ($ref, $pat, $sep) = @_;
2878 $pat = "%s\t%s" if ! defined $pat;
2879 $sep = "\n" if ! defined $sep;
2881 return join($sep, map {sprintf $pat, $_, $ref->{$_}} sort keys %$ref);
2886 my $size = shift || 1;
2888 if ($size < 0) { # chunk from the opposite end
2889 $str = reverse $str;
2891 unshift(@list, scalar reverse $1) while $str =~ /( .{$size} | .+ )/xg;
2893 push(@list, $1) while $str =~ /( .{$size} | .+ )/xg;
2898 sub vmethod_indent
{
2899 my $str = shift; $str = '' if ! defined $str;
2900 my $pre = shift; $pre = 4 if ! defined $pre;
2901 $pre = ' ' x
$pre if $pre =~ /^\d+$/;
2902 $str =~ s/^/$pre/mg;
2906 sub vmethod_format
{
2907 my $str = shift; $str = '' if ! defined $str;
2908 my $pat = shift; $pat = '%s' if ! defined $pat;
2909 return join "\n", map{ sprintf $pat, $_ } split(/\n/, $str);
2913 my ($str, $pat, $global) = @_;
2914 return [] if ! defined $str || ! defined $pat;
2915 my @res = $global ? ($str =~ /$pat/g) : ($str =~ /$pat/);
2916 return (@res >= 2) ? \
@res : (@res == 1) ? $res[0] : '';
2920 my ($list, $field) = @_;
2921 return defined($field)
2922 ? [map {$_->[0]} sort {$a->[1] <=> $b->[1]} map {[$_, (ref $_ eq 'HASH' ? $_->{$field}
2923 : UNIVERSAL
::can
($_, $field) ? $_->$field()
2925 : [sort {$a <=> $b} @$list];
2928 sub vmethod_repeat
{
2929 my ($str, $n, $join) = @_;
2930 return if ! length $str;
2931 $n = 1 if ! defined($n) || ! length $n;
2932 $join = '' if ! defined $join;
2933 return join $join, ($str) x
$n;
2936 ### This method is a combination of my submissions along
2937 ### with work from Andy Wardley, Sergey Martynoff, Nik Clayton, and Josh Rosenbaum
2938 sub vmethod_replace
{
2939 my ($text, $pattern, $replace, $global) = @_;
2940 $text = '' unless defined $text;
2941 $pattern = '' unless defined $pattern;
2942 $replace = '' unless defined $replace;
2943 $global = 1 unless defined $global;
2945 my ($chunk, $start, $end) = @_;
2946 $chunk =~ s
{ \\(\\|\
$) | \
$ (\d
+) }{
2948 : ($2 > $#$start || $2 == 0) ? ''
2949 : substr($text, $start->[$2], $end->[$2] - $start->[$2]);
2954 $text =~ s{$pattern}{ $expand->($replace, [@-], [@+]) }eg;
2956 $text =~ s{$pattern}{ $expand->($replace, [@-], [@+]) }e;
2962 my ($list, $field) = @_;
2963 return defined($field)
2964 ? [map {$_->[0]} sort {$a->[1] cmp $b->[1]} map {[$_, lc(ref $_ eq 'HASH' ? $_->{$field}
2965 : UNIVERSAL
::can
($_, $field) ? $_->$field()
2967 : [map {$_->[0]} sort {$a->[1] cmp $b->[1]} map {[$_, lc $_]} @$list ]; # case insensitive
2970 sub vmethod_splice
{
2971 my ($ref, $i, $len, @replace) = @_;
2972 @replace = @{ $replace[0] } if @replace == 1 && ref $replace[0] eq 'ARRAY';
2974 return [splice @$ref, $i || 0, $len, @replace];
2976 return [splice @$ref, $i || 0];
2981 my ($str, $pat, @args) = @_;
2982 $str = '' if ! defined $str;
2983 return defined $pat ? [split $pat, $str, @args] : [split ' ', $str, @args];
2988 utf8
::encode
($str) if defined &utf8
::encode
;
2989 $str =~ s/([^A-Za-z0-9\-_.!~*\'()])/sprintf('%%%02X', ord($1))/eg;
2994 my $context = shift;
2997 return $context->process(\
$text);
3001 sub filter_redirect
{
3002 my ($context, $file, $options) = @_;
3003 my $path = $context->config->{'OUTPUT_PATH'} || $context->throw('redirect', 'OUTPUT_PATH is not set');
3004 $context->throw('redirect', 'Invalid filename - cannot include "/../"')
3005 if $file =~ m{(^|/)\.\./};
3011 File
::Path
::mkpath
($path) || $context->throw('redirect', "Couldn't mkpath \"$path\": $!");
3014 open (FH
, ">$path/$file") || $context->throw('redirect', "Couldn't open \"$file\": $!");
3015 if (my $bm = (! $options) ? 0 : ref($options) ? $options->{'binmode'} : $options) {
3016 if (+$bm == 1) { binmode FH
}
3017 else { binmode FH
, $bm}
3025 ###----------------------------------------------------------------###
3028 my $obj = UNIVERSAL
::isa
($_[0], __PACKAGE__
) ? shift : __PACKAGE__-
>new;
3030 require Data
::Dumper
;
3031 return Data
::Dumper
::Dumper
($obj->parse_expr(\
$str));
3034 ###----------------------------------------------------------------###
3036 package CGI
::Ex
::Template
::Exception
;
3039 '""' => \
&as_string
,
3040 bool
=> sub { defined shift },
3044 my ($class, $type, $info, $node, $pos, $str_ref) = @_;
3045 return bless [$type, $info, $node, $pos, $str_ref], $class;
3048 sub type
{ shift-
>[0] }
3050 sub info
{ shift-
>[1] }
3054 $self->[2] = shift if $#_ == 0;
3058 sub offset
{ shift-
>[3] || 0 }
3062 $self->[4] = shift if $#_ == 0;
3068 my $msg = $self->type .' error - '. $self->info;
3069 if (my $node = $self->node) {
3070 # $msg .= " (In tag $node->[0] starting at char ".($node->[1] + $self->offset).")";
3075 ###----------------------------------------------------------------###
3077 package CGI
::Ex
::Template
::Iterator
;
3080 my ($class, $items) = @_;
3081 $items = [] if ! defined $items;
3082 if (UNIVERSAL
::isa
($items, 'HASH')) {
3083 $items = [ map { {key
=> $_, value
=> $items->{ $_ }} } sort keys %$items ];
3084 } elsif (UNIVERSAL
::can
($items, 'as_list')) {
3085 $items = $items->as_list;
3086 } elsif (! UNIVERSAL
::isa
($items, 'ARRAY')) {
3089 return bless [$items, 0], $class;
3094 return (undef, 3) if ! @{ $self->[0] };
3095 return ($self->[0]->[$self->[1] = 0], undef);
3100 return (undef, 3) if ++ $self->[1] > $#{ $self->[0] };
3101 return ($self->items->[$self->[1]], undef);
3104 sub items
{ shift-
>[0] }
3106 sub index { shift-
>[1] }
3108 sub max
{ $#{ shift-
>[0] } }
3110 sub size
{ shift-
>max + 1 }
3112 sub count
{ shift-
>index + 1 }
3114 sub number
{ shift-
>index + 1 }
3116 sub first
{ (shift-
>index == 0) || 0 }
3118 sub last { my $self = shift; return ($self->index == $self->max) || 0 }
3122 return undef if $self->index <= 0;
3123 return $self->items->[$self->index - 1];
3128 return undef if $self->index >= $self->max;
3129 return $self->items->[$self->index + 1];
3132 ###----------------------------------------------------------------###
3134 package CGI
::Ex
::Template
::_Context
;
3136 use vars
qw($AUTOLOAD);
3138 sub _template
{ shift-
>{'_template'} || die "Missing _template" }
3140 sub config
{ shift-
>_template }
3144 return $self->{'stash'} ||= bless {_template
=> $self->_template}, $CGI::Ex
::Template
::PACKAGE_STASH
;
3147 sub insert
{ shift-
>_template->_insert(@_) }
3149 sub eval_perl
{ shift-
>_template->{'EVAL_PERL'} }
3154 my $vars = $self->_template->_vars;
3156 $self->_template->_process($ref, $vars, \
$out);
3163 my $args = shift || {};
3165 $self->_template->set_variable($_, $args->{$_}) for keys %$args;
3167 my $out = ''; # have temp item to allow clear to correctly clear
3168 eval { $self->_template->_process($file, $self->{'_vars'}, \
$out) };
3170 die $err if ref($err) !~ /Template::Exception$/ || $err->type !~ /return/;
3177 my ($self, $name, $filter, $is_dynamic) = @_;
3178 $filter = [ $filter, 1 ] if $is_dynamic;
3179 $self->define_vmethod('filter', $name, $filter);
3183 my ($self, $name, $args, $alias) = @_;
3184 my $t = $self->_template;
3188 $filter = $t->{'FILTERS'}->{$name} || $CGI::Ex
::Template
::FILTER_OPS-
>{$name} || $CGI::Ex
::Template
::SCALAR_OPS-
>{$name};
3189 $t->throw('filter', $name) if ! $filter;
3190 } elsif (UNIVERSAL
::isa
($name, 'CODE') || UNIVERSAL
::isa
($name, 'ARRAY')) {
3192 } elsif (UNIVERSAL
::can
($name, 'factory')) {
3193 $filter = $name->factory || $t->throw($name->error);
3195 $t->throw('undef', "$name: filter not found");
3198 if (UNIVERSAL
::isa
($filter, 'ARRAY')) {
3199 $filter = ($filter->[1]) ? $filter->[0]->($t->context, @$args) : $filter->[0];
3200 } elsif ($args && @$args) {
3202 $filter = sub { $sub->(shift, @$args) };
3205 $t->{'FILTERS'}->{$alias} = $filter if $alias;
3210 sub define_vmethod
{ shift-
>_template->define_vmethod(@_) }
3213 my ($self, $type, $info) = @_;
3215 if (UNIVERSAL
::isa
($type, $CGI::Ex
::Template
::PACKAGE_EXCEPTION
)) {
3217 } elsif (defined $info) {
3218 $self->_template->throw($type, $info);
3220 $self->_template->throw('undef', $type);
3224 sub AUTOLOAD
{ shift-
>_template->throw('not_implemented', "The method $AUTOLOAD has not been implemented") }
3228 ###----------------------------------------------------------------###
3230 package CGI
::Ex
::Template
::_Stash
;
3232 use vars
qw($AUTOLOAD);
3234 sub _template
{ shift-
>{'_template'} || die "Missing _template" }
3237 my ($self, $var) = @_;
3239 if ($var =~ /^\w+$/) { $var = [$var, 0] }
3240 else { $var = $self->_template->parse_expr(\
$var, {no_dots
=> 1}) }
3242 return $self->_template->play_expr($var, {no_dots
=> 1});
3246 my ($self, $var, $val) = @_;
3248 if ($var =~ /^\w+$/) { $var = [$var, 0] }
3249 else { $var = $self->_template->parse_expr(\
$var, {no_dots
=> 1}) }
3251 $self->_template->set_variable($var, $val, {no_dots
=> 1});
3255 sub AUTOLOAD
{ shift-
>_template->throw('not_implemented', "The method $AUTOLOAD has not been implemented") }
3259 ###----------------------------------------------------------------###
3261 package CGI
::Ex
::Template
::EvalPerlHandle
;
3264 my ($class, $out_ref) = @_;
3265 return bless [$out_ref], $class;
3270 ${ $self->[0] } .= $_ for grep {defined && length} @_;
3274 ###----------------------------------------------------------------###
3278 ### See the perldoc in CGI/Ex/Template.pod