blib/lib/HP/Handy.pm untested

filter: Statementstmt 0.0% 0 / 1031 Branchbran 0.0% 0 / 658 Conditioncond 0.0% 0 / 338 MC/DCmcdc 0.0% 0 / 196 Subroutinesub 0.0% 0 / 38 Podpod 0.0% 0 / 31 totaltotal 0.0% 0 / 2292 CC 260 SCAR 85.2
CC
260
Cov
0%
_eval_expr
12882.0
_eval_tokens
650.0
_eval_for
342.0
CRAP 5013.8
1 package HP::Handy;
2 ######################################################################
3 #
4 # HP::Handy - A tiny Jinja2-compatible template engine for Perl 5.5.3+
5 #
6 # https://metacpan.org/dist/HP-Handy
7 #
8 # Copyright (c) 2026 INABA Hitoshi <ina@cpan.org>
9 ######################################################################
10 #
11 # Compatible : Perl 5.005_03 and later
12 # Platform : Windows and UNIX/Linux
13 #
14 ######################################################################
15  
16 use 5.00503; # Universal Consensus 1998 for primetools
17 # Perl 5.005_03 compatibility for historical toolchains
18 # use 5.008001; # Lancaster Consensus 2013 for toolchains
19  
20 use strict;
21 BEGIN { if ($] < 5.006 && !defined(&warnings::import)) { $INC{'warnings.pm'} = 'stub'; eval 'package warnings; sub import {}' } }
22 use warnings; local $^W = 1;
23 BEGIN { pop @INC if $INC[-1] eq '.' }
24  
25 use Carp qw(croak);
26 use File::Spec;
27 use vars qw($VERSION);
28 $VERSION = '0.01';
29 $VERSION = $VERSION;
30 # $VERSION self-assignment suppresses "used only once" warning under strict.
31  
32 ###############################################################################
33 # Built-in filters
34 ###############################################################################
35 my %FILTERS = (
36 'upper' => sub { my $s = defined $_[0] ? $_[0] : ''; $s =~ tr/a-z/A-Z/; $s },
37 'lower' => sub { my $s = defined $_[0] ? $_[0] : ''; $s =~ tr/A-Z/a-z/; $s },
38 'trim' => sub { my $s = defined $_[0] ? $_[0] : ''; $s =~ s/^\s+|\s+$//g; $s },
39 'length' => sub {
40 return 0 unless defined $_[0];
41 ref($_[0]) eq 'ARRAY' ? scalar @{$_[0]}
42 : ref($_[0]) eq 'HASH' ? scalar keys %{$_[0]}
43 : length($_[0])
44 },
45 'reverse' => sub {
46 return '' unless defined $_[0];
47 ref($_[0]) eq 'ARRAY' ? [ reverse @{$_[0]} ]
48 : scalar reverse("$_[0]")
49 },
50 'escape' => \&_html_escape,
51 'e' => \&_html_escape,
52 'safe' => sub { bless \(my $s = defined $_[0] ? $_[0] : ''), 'HP::Handy::SafeString' },
53 'default' => sub { (defined $_[0] && $_[0] ne '') ? $_[0] : $_[1] },
54 'd' => sub { (defined $_[0] && $_[0] ne '') ? $_[0] : $_[1] },
55 'replace' => sub {
56 my ($s, $from, $to) = @_;
57 $s = defined $s ? $s : '';
58 $from = defined $from ? $from : '';
59 $to = defined $to ? $to : '';
60 $s =~ s/\Q$from\E/$to/g;
61 $s
62 },
63 'truncate' => sub {
64 my ($s, $len, $end) = @_;
65 $s = defined $s ? $s : '';
66 $len = defined $len ? int($len) : 255;
67 $end = defined $end ? $end : '...';
68 (length($s) > $len) ? substr($s, 0, $len) . $end : $s
69 },
70 'join' => sub {
71 my ($list, $sep) = @_;
72 $sep = defined $sep ? $sep : '';
73 ref($list) eq 'ARRAY' ? join($sep, @$list) : (defined $list ? $list : '')
74 },
75 'first' => sub { ref($_[0]) eq 'ARRAY' && @{$_[0]} ? $_[0][0] : undef },
76 'last' => sub { ref($_[0]) eq 'ARRAY' && @{$_[0]} ? $_[0][-1] : undef },
77 'list' => sub { ref($_[0]) eq 'ARRAY' ? $_[0] : [defined $_[0] ? $_[0] : ()] },
78 'abs' => sub { abs(defined $_[0] ? $_[0] : 0) },
79 'int' => sub { int(defined $_[0] ? $_[0] : 0) },
80 'float' => sub { defined $_[0] ? ($_[0] + 0.0) : 0.0 },
81 'string' => sub { defined $_[0] ? "$_[0]" : '' },
82 'title' => sub {
83 my $s = defined $_[0] ? $_[0] : '';
84 $s =~ s/\b([a-z])/uc($1)/ge;
85 $s
86 },
87 'capitalize' => sub {
88 my $s = defined $_[0] ? lc($_[0]) : '';
89 $s =~ s/^([a-z])/uc($1)/e;
90 $s
91 },
92 'urlencode' => sub {
93 my $s = defined $_[0] ? $_[0] : '';
94 $s =~ s/([^A-Za-z0-9\-_.~])/sprintf('%%%02X', ord($1))/ge;
95 $s
96 },
97 'wordcount' => sub {
98 my $s = defined $_[0] ? $_[0] : '';
99 my @w = split /\s+/, $s;
100 @w = grep { $_ ne '' } @w;
101 scalar @w
102 },
103 'batch' => sub {
104 my ($list, $size, $fill) = @_;
105 return [] unless ref($list) eq 'ARRAY';
106 $size = int($size || 1);
107 $size = 1 if $size < 1;
108 my @result;
109 my @flat = @$list;
110 while (@flat) {
111 my @chunk = splice(@flat, 0, $size);
112 if (defined $fill) {
113 push @chunk, $fill while @chunk < $size;
114 }
115 push @result, \@chunk;
116 }
117 \@result
118 },
119 'slice' => sub {
120 my ($list, $slices) = @_;
121 return [] unless ref($list) eq 'ARRAY';
122 $slices = int($slices || 1);
123 $slices = 1 if $slices < 1;
124 my $total = scalar @$list;
125 my $per = int($total / $slices);
126 my $extra = $total % $slices;
127 my @result;
128 my $idx = 0;
129 for my $i (0 .. $slices - 1) {
130 my $n = $per + ($i < $extra ? 1 : 0);
131 push @result, [ @{$list}[$idx .. $idx + $n - 1] ];
132 $idx += $n;
133 }
134 \@result
135 },
136 'sort' => sub {
137 my ($list, $attr) = @_;
138 return [] unless ref($list) eq 'ARRAY';
139 if (defined $attr) {
140 return [ sort { _get_attr($a, $attr) cmp _get_attr($b, $attr) } @$list ];
141 }
142 [ sort @$list ]
143 },
144 'unique' => sub {
145 return [] unless ref($_[0]) eq 'ARRAY';
146 my %seen;
147 [ grep { !$seen{$_}++ } @{$_[0]} ]
148 },
149 'min' => sub {
150 return undef unless ref($_[0]) eq 'ARRAY' && @{$_[0]};
151 my $m = $_[0][0];
152 for (@{$_[0]}) { $m = $_ if $_ < $m }
153 $m
154 },
155 'max' => sub {
156 return undef unless ref($_[0]) eq 'ARRAY' && @{$_[0]};
157 my $m = $_[0][0];
158 for (@{$_[0]}) { $m = $_ if $_ > $m }
159 $m
160 },
161 'sum' => sub {
162 return 0 unless ref($_[0]) eq 'ARRAY';
163 my $s = 0; $s += $_ for @{$_[0]}; $s
164 },
165 'map' => sub {
166 my ($list, $attr) = @_;
167 return [] unless ref($list) eq 'ARRAY';
168 [ map { _get_attr($_, $attr) } @$list ]
169 },
170 'select' => sub {
171 my ($list, $attr) = @_;
172 return [] unless ref($list) eq 'ARRAY';
173 [ grep { _get_attr($_, $attr) } @$list ]
174 },
175 'reject' => sub {
176 my ($list, $attr) = @_;
177 return [] unless ref($list) eq 'ARRAY';
178 [ grep { !_get_attr($_, $attr) } @$list ]
179 },
180 'count' => sub { ref($_[0]) eq 'ARRAY' ? scalar @{$_[0]} : 0 },
181 'pprint' => sub { _to_json($_[0]) },
182 'nl2br' => sub {
183 my $s = defined $_[0] ? $_[0] : '';
184 $s =~ s/\n/<br>\n/g;
185 $s
186 },
187 'striptags' => sub {
188 my $s = defined $_[0] ? $_[0] : '';
189 $s =~ s/<[^>]*>//g;
190 $s
191 },
192 'format' => sub {
193 my ($s, $fmt) = @_;
194 defined $s ? sprintf($fmt, $s) : ''
195 },
196 'center' => sub {
197 my ($s, $width) = @_;
198 $s = defined $s ? $s : '';
199 $width = defined $width ? int($width) : 80;
200 my $pad = $width - length($s);
201 return $s if $pad <= 0;
202 my $left = int($pad / 2);
203 my $right = $pad - $left;
204 (' ' x $left) . $s . (' ' x $right)
205 },
206 'indent' => sub {
207 my ($s, $width, $first) = @_;
208 $s = defined $s ? $s : '';
209 $width = defined $width ? int($width) : 4;
210 $first = defined $first ? $first : 0;
211 my $pad = ' ' x $width;
212 my @lines = split /\n/, $s, -1;
213 for my $i (0 .. $#lines) {
214 $lines[$i] = $pad . $lines[$i] if $i > 0 || $first;
215 }
216 join("\n", @lines)
217 },
218 'xmlattr' => sub {
219 my $h = $_[0];
220 return '' unless ref($h) eq 'HASH';
221 join(' ', map {
222 my $v = defined $h->{$_} ? $h->{$_} : '';
223 $v =~ s/&/&amp;/g; $v =~ s/"/&quot;/g;
224 "$_=\"$v\""
225 } sort keys %$h)
226 },
227 'tojson' => sub {
228 my $v = $_[0];
229 _to_json($v)
230 },
231 'forceescape' => \&_html_escape,
232 );
233  
234 ###############################################################################
235 # Built-in tests (is_xxx)
236 ###############################################################################
237 my %TESTS = (
238 'defined' => sub { defined $_[0] },
239 'none' => sub { !defined $_[0] },
240 'string' => sub { defined $_[0] && !ref($_[0]) },
241 'number' => sub { defined $_[0] && !ref($_[0]) && $_[0] =~ /^-?(?:\d+\.?\d*|\.\d+)$/ },
242 'sequence' => sub { ref($_[0]) eq 'ARRAY' },
243 'mapping' => sub { ref($_[0]) eq 'HASH' },
244 'iterable' => sub { ref($_[0]) eq 'ARRAY' || ref($_[0]) eq 'HASH' },
245 'callable' => sub { ref($_[0]) eq 'CODE' },
246 'odd' => sub { defined $_[0] && int($_[0]) % 2 != 0 },
247 'even' => sub { defined $_[0] && int($_[0]) % 2 == 0 },
248 'divisibleby' => sub { defined $_[0] && defined $_[1] && $_[1] != 0 && int($_[0]) % int($_[1]) == 0 },
249 'upper' => sub { defined $_[0] && $_[0] eq uc($_[0]) && $_[0] =~ /[A-Z]/ },
250 'lower' => sub { defined $_[0] && $_[0] eq lc($_[0]) && $_[0] =~ /[a-z]/ },
251 'equalto' => sub { defined $_[0] && defined $_[1] && $_[0] eq $_[1] },
252 'ne' => sub { !(defined $_[0] && defined $_[1] && $_[0] eq $_[1]) },
253 'lt' => sub { defined $_[0] && defined $_[1] && $_[0] < $_[1] },
254 'le' => sub { defined $_[0] && defined $_[1] && $_[0] <= $_[1] },
255 'gt' => sub { defined $_[0] && defined $_[1] && $_[0] > $_[1] },
256 'ge' => sub { defined $_[0] && defined $_[1] && $_[0] >= $_[1] },
257 'in' => sub {
258 my ($val, $container) = @_;
259 return 0 unless defined $val && defined $container;
260 if (ref($container) eq 'ARRAY') { return (grep { defined $_ && $_ eq $val } @$container) ? 1 : 0 }
261 if (ref($container) eq 'HASH') { return exists $container->{$val} ? 1 : 0 }
262 return index($container, $val) >= 0 ? 1 : 0
263 },
264 );
265  
266 ###############################################################################
267 # Constructor
268 ###############################################################################
269 sub new {
270 my ($class, %args) = @_;
271 my $self = {
272 template_dir => defined $args{template_dir} ? $args{template_dir} : '.',
273 auto_escape => defined $args{auto_escape} ? $args{auto_escape} : 1,
274 trim_blocks => defined $args{trim_blocks} ? $args{trim_blocks} : 0,
275 lstrip_blocks => defined $args{lstrip_blocks} ? $args{lstrip_blocks} : 0,
276 block_start => defined $args{block_start} ? $args{block_start} : '{%',
277 block_end => defined $args{block_end} ? $args{block_end} : '%}',
278 var_start => defined $args{var_start} ? $args{var_start} : '{{',
279 var_end => defined $args{var_end} ? $args{var_end} : '}}',
280 comment_start => defined $args{comment_start} ? $args{comment_start} : '{#',
281 comment_end => defined $args{comment_end} ? $args{comment_end} : '#}',
282 _filters => { %FILTERS },
283 _tests => { %TESTS },
284 _blocks => {}, # block name => template string (for inheritance)
285 _macros => {}, # macro name => { args=>[], defaults=>[], body=>'' }
286 _extends => '', # parent template name
287 };
288 bless $self, $class;
289 return $self;
290 }
291  
292 ###############################################################################
293 # add_filter - Register a custom filter
294 ###############################################################################
295 sub add_filter {
296 my ($self, $name, $code) = @_;
297 croak "add_filter: name required" unless defined $name;
298 croak "add_filter: code must be coderef" unless ref($code) eq 'CODE';
299 $self->{_filters}{$name} = $code;
300 return $self;
301 }
302  
303 ###############################################################################
304 # add_test - Register a custom test
305 ###############################################################################
306 sub add_test {
307 my ($self, $name, $code) = @_;
308 croak "add_test: name required" unless defined $name;
309 croak "add_test: code must be coderef" unless ref($code) eq 'CODE';
310 $self->{_tests}{$name} = $code;
311 return $self;
312 }
313  
314 ###############################################################################
315 # render_file - Render a template file with variables
316 ###############################################################################
317 sub render_file {
318 my ($self, $filename, $vars) = @_;
319 $vars = {} unless defined $vars;
320 my $source = $self->_load_file($filename);
321 return $self->_render($source, $vars, $filename);
322 }
323  
324 ###############################################################################
325 # render_string - Render a template string with variables
326 ###############################################################################
327 sub render_string {
328 my ($self, $source, $vars) = @_;
329 $vars = {} unless defined $vars;
330 return $self->_render($source, $vars, '<string>');
331 }
332  
333 ###############################################################################
334 # _load_file - Read template from disk
335 ###############################################################################
336 sub _load_file {
337 my ($self, $filename) = @_;
338  
339 # Prevent path traversal
340 if ($filename =~ /\.\./) {
341 croak "HP::Handy: path traversal not allowed in '$filename'";
342 }
343  
344 my $path;
345 if (File::Spec->file_name_is_absolute($filename)) {
346 $path = $filename;
347 }
348 else {
349 $path = File::Spec->catfile($self->{template_dir}, $filename);
350 }
351  
352 local *HPHANDY_FH;
353 open(HPHANDY_FH, "< $path") or croak "HP::Handy: cannot open '$path': $!";
354 local $/;
355 my $source = <HPHANDY_FH>;
356 close(HPHANDY_FH);
357 return defined $source ? $source : '';
358 }
359  
360 ###############################################################################
361 # _render - Core rendering engine
362 ###############################################################################
363 sub _render {
364 my ($self, $source, $vars, $filename) = @_;
365 $filename = defined $filename ? $filename : '<string>';
366  
367 # Reset per-render state
368 $self->{_blocks} = {};
369 $self->{_macros} = {};
370 $self->{_extends} = '';
371  
372 # First pass: collect blocks and macros, detect extends
373 $source = $self->_preprocess($source, $vars);
374  
375 # If extends was found, do inheritance (iteratively for multi-level)
376 while ($self->{_extends} ne '') {
377 my $parent_src = $self->_load_file($self->{_extends});
378 $self->{_extends} = '';
379 # Collect parent blocks/macros without overwriting child definitions
380 $parent_src = $self->_preprocess_parent($parent_src, $vars);
381 # Apply child blocks to parent template
382 $source = $self->_apply_inheritance($parent_src, $vars);
383 # Now resolve all known blocks so deeper levels see merged content.
384 # For each block in _blocks, expand any other known blocks inside it.
385 my $merged = 1;
386 my $passes = 10;
387 while ($merged && $passes-- > 0) {
388 $merged = 0;
389 for my $bname (keys %{$self->{_blocks}}) {
390 my $prev = $self->{_blocks}{$bname};
391 my $val = $prev;
392 my $lim2 = 10;
393 while ($lim2-- > 0) {
394 my $prev2 = $val;
395 $val =~ s/\{%-?\s*block\s+(\w+)\s*-?%\}((?:(?!\{%-?\s*block\b)[\s\S])*?)\{%-?\s*endblock(?:\s+\1)?\s*-?%\}/
396 exists $self->{_blocks}{$1} ? $self->{_blocks}{$1} : "\x00BLK\x01$1\x01$2\x00EBLK\x00"
397 /gse;
398 last if $val eq $prev2;
399 }
400 $val =~ s/\x00BLK\x01(\w+)\x01(.*?)\x00EBLK\x00/$2/gs;
401 $val =~ s/\{%-?\s*endblock(?:\s+\w+)?\s*-?%\}//g;
402 if ($val ne $prev) {
403 $self->{_blocks}{$bname} = $val;
404 $merged = 1;
405 }
406 }
407 }
408 }
409  
410 return $self->_eval_template($source, $vars, $filename);
411 }
412  
413 ###############################################################################
414 # _preprocess - Scan for extends/block/macro; strip them for non-inherited use
415 ###############################################################################
416 sub _preprocess {
417 my ($self, $source, $vars) = @_;
418  
419 # Detect {% extends "..." %}
420 if ($source =~ s/\{%-?\s*extends\s+["']([^"']+)["']\s*-?%\}[ \t]*\n?//) {
421 $self->{_extends} = $1;
422 }
423  
424 # Collect {% macro name(args) %}...{% endmacro %}
425 while ($source =~ s/\{%-?\s*macro\s+(\w+)\s*\(([^)]*)\)\s*-?%\}(.*?)\{%-?\s*endmacro\s*-?%\}//s) {
426 my ($mname, $argstr, $body) = ($1, $2, $3);
427 my (@args, @defaults);
428 for my $a (split /\s*,\s*/, $argstr) {
429 $a =~ s/^\s+|\s+$//g;
430 next if $a eq '';
431 if ($a =~ /^(\w+)\s*=\s*(.+)$/) {
432 push @args, $1;
433 push @defaults, $2;
434 }
435 else {
436 push @args, $a;
437 push @defaults, undef;
438 }
439 }
440 $self->{_macros}{$mname} = { args => \@args, defaults => \@defaults, body => $body };
441 }
442  
443 # Collect {% block name %}...{% endblock %} from child
444 while ($source =~ s/\{%-?\s*block\s+(\w+)\s*-?%\}(.*?)\{%-?\s*endblock(?:\s+\1)?\s*-?%\}/$self->_store_block($1, $2)/se) {}
445  
446 return $source;
447 }
448  
449 sub _store_block {
450 my ($self, $name, $content) = @_;
451 $self->{_blocks}{$name} = $content unless exists $self->{_blocks}{$name};
452 return '';
453 }
454  
455  
456 # _preprocess_parent - Scan parent for extends/macro; collect NEW blocks only
457 # (does NOT strip block tags -- those must survive for _apply_inheritance)
458 sub _preprocess_parent {
459 my ($self, $source, $vars) = @_;
460  
461 # Detect {% extends "..." %} in parent (for multi-level)
462 if ($source =~ s/\{%-?\s*extends\s+["']([^"']+)["']\s*-?%\}[ \t]*\n?//) {
463 $self->{_extends} = $1;
464 }
465  
466 # Collect macros from parent (without overwriting child macros)
467 while ($source =~ s/\{%-?\s*macro\s+(\w+)\s*\(([^)]*)\)\s*-?%\}(.*?)\{%-?\s*endmacro\s*-?%\}//s) {
468 my ($mname, $argstr, $body) = ($1, $2, $3);
469 next if exists $self->{_macros}{$mname};
470 my (@args, @defaults);
471 for my $a (split /\s*,\s*/, $argstr) {
472 $a =~ s/^\s+|\s+$//g;
473 next if $a eq "";
474 if ($a =~ /^(\w+)\s*=\s*(.+)$/) {
475 push @args, $1;
476 push @defaults, $2;
477 }
478 else {
479 push @args, $a;
480 push @defaults, undef;
481 }
482 }
483 $self->{_macros}{$mname} = { args => \@args, defaults => \@defaults, body => $body };
484 }
485  
486 # Collect NEW blocks (without overwriting child blocks).
487 # Expand already-known child blocks within the body before storing.
488 my $tmp = $source;
489 while ($tmp =~ s/\{%-?\s*block\s+(\w+)\s*-?%\}(.*)\{%-?\s*endblock(?:\s+\1)?\s*-?%\}/
490 $self->_store_block_expanded($1, $2)
491 /se) {}
492  
493 return $source; # keep block tags intact for _apply_inheritance
494 }
495  
496 sub _store_block_expanded {
497 my ($self, $name, $body) = @_;
498 unless (exists $self->{_blocks}{$name}) {
499 # Expand already-resolved child blocks inside this body.
500 # Use _apply_inheritance logic on the snippet.
501 my $expanded = $body;
502 my $lim = 10;
503 while ($lim-- > 0) {
504 my $prev = $expanded;
505 # Replace innermost (non-nested) blocks that are known
506 $expanded =~ s/\{%-?\s*block\s+(\w+)\s*-?%\}((?:(?!\{%-?\s*block\b)[\s\S])*?)\{%-?\s*endblock(?:\s+\1)?\s*-?%\}/
507 exists $self->{_blocks}{$1} ? $self->{_blocks}{$1} : "__BLK__" . $1 . "__SEP__" . $2 . "__EBLK__"
508 /gse;
509 last if $expanded eq $prev;
510 }
511 # Clean up any un-expanded block tags
512 $expanded =~ s/__BLK__(\w+)__SEP__(.*?)__EBLK__/$2/gs;
513 $expanded =~ s/\{%-?\s*endblock(?:\s+\w+)?\s*-?%\}//g;
514 $self->{_blocks}{$name} = $expanded;
515 }
516 return '';
517 }
518  
519  
520 ###############################################################################
521 # _apply_inheritance - Render parent with child blocks
522 ###############################################################################
523 sub _apply_inheritance {
524 my ($self, $parent_src, $vars) = @_;
525  
526 # Iteratively substitute innermost (non-nested) blocks first.
527 # A block body that contains no other {% block %} tags is "innermost".
528 my $limit = 20;
529 while ($limit-- > 0) {
530 my $changed = 0;
531 $parent_src =~ s/\{%-?\s*block\s+(\w+)\s*-?%\}((?:(?!\{%-?\s*block\b)[\s\S])*?)\{%-?\s*endblock(?:\s+\1)?\s*-?%\}/
532 do { $changed = 1; exists $self->{_blocks}{$1} ? $self->{_blocks}{$1} : $2 }
533 /gse;
534 last unless $changed;
535 }
536  
537 # Remove any orphaned {% endblock %} left from outer block substitutions
538 $parent_src =~ s/\{%-?\s*endblock(?:\s+\w+)?\s*-?%\}//g;
539  
540 return $parent_src;
541 }
542  
543 ###############################################################################
544 # _eval_template - Evaluate template directives recursively
545 ###############################################################################
546 sub _eval_template {
547 my ($self, $source, $vars, $filename) = @_;
548 $filename = defined $filename ? $filename : '<string>';
549  
550 # Apply trim_blocks / lstrip_blocks
551 if ($self->{trim_blocks}) {
552 $source =~ s/(%\}|#\})[ \t]*\n/$1\n/g; # already minimal; remove newline after tag
553 $source =~ s/(%\}|#\})\n/$1/g;
554 }
555 if ($self->{lstrip_blocks}) {
556 $source =~ s/^[ \t]*(\{[%#])/$1/mg;
557 }
558  
559 my $bs = quotemeta($self->{block_start});
560 my $be = quotemeta($self->{block_end});
561 my $vs = quotemeta($self->{var_start});
562 my $ve = quotemeta($self->{var_end});
563 my $cs = quotemeta($self->{comment_start});
564 my $ce = quotemeta($self->{comment_end});
565  
566 # Protect {% raw %}...{% endraw %} blocks BEFORE comment stripping,
567 # so that {# ... #} inside raw blocks is preserved as-is.
568 my @raw_chunks;
569 my $raw_ph = "\x00RAW\x00";
570 my $bs_re = quotemeta($self->{block_start});
571 my $be_re = quotemeta($self->{block_end});
572 $source =~ s/${bs_re}-?\s*raw\s*-?${be_re}(.*?)${bs_re}-?\s*endraw\s*-?${be_re}/
573 my $idx = scalar @raw_chunks;
574 push @raw_chunks, $1;
575 "${raw_ph}${idx}\x00"
576 /gse;
577  
578 # Remove comments (after raw protection so {# #} inside raw is safe)
579 $source =~ s/$cs.*?$ce//gs;
580  
581 # Tokenise into chunks
582 # Tokens: [ 'text', $str ] or [ 'var', $expr ] or [ 'tag', $stmt ]
583 my @tokens = $self->_tokenize($source);
584  
585 # Restore raw chunks in text tokens
586 for my $tok (@tokens) {
587 if ($tok->[0] eq 'text' && $tok->[1] =~ /\Q$raw_ph\E/) {
588 $tok->[1] =~ s/\Q${raw_ph}\E(\d+)\x00/$raw_chunks[$1]/g;
589 }
590 }
591  
592 return $self->_eval_tokens(\@tokens, $vars, 0, $filename);
593 }
594  
595 ###############################################################################
596 # _tokenize - Split source into text/var/tag tokens
597 ###############################################################################
598 sub _tokenize {
599 my ($self, $source) = @_;
600  
601 my $bs = $self->{block_start}; # {%
602 my $be = $self->{block_end}; # %}
603 my $vs = $self->{var_start}; # {{
604 my $ve = $self->{var_end}; # }}
605  
606 # Build split pattern
607 my $qbs = quotemeta($bs); my $qbe = quotemeta($be);
608 my $qvs = quotemeta($vs); my $qve = quotemeta($ve);
609  
610 my @tokens;
611 my $pos = 0;
612 my $len = length($source);
613  
614 while ($pos < $len) {
615 # Find next tag start
616 my $var_pos = index($source, $vs, $pos);
617 my $block_pos = index($source, $bs, $pos);
618  
619 # No more tags
620 if ($var_pos < 0 && $block_pos < 0) {
621 push @tokens, [ 'text', substr($source, $pos) ];
622 last;
623 }
624  
625 # Determine which comes first
626 my $next;
627 if ($var_pos >= 0 && ($block_pos < 0 || $var_pos <= $block_pos)) {
628 $next = $var_pos;
629 my $end = index($source, $ve, $next + length($vs));
630 if ($end < 0) {
631 push @tokens, [ 'text', substr($source, $pos) ];
632 last;
633 }
634 if ($next > $pos) {
635 push @tokens, [ 'text', substr($source, $pos, $next - $pos) ];
636 }
637 my $raw_expr = substr($source, $next + length($vs), $end - $next - length($vs));
638 # Whitespace control dash: "{{- expr -}}"
639 # The dash must be the very first/last non-whitespace character AND
640 # must be followed/preceded by whitespace (not part of the expression).
641 # Rule: if raw_expr starts with "-" followed by space/end, it's WS control.
642 # "-5" or "-x" is a negative expression, NOT whitespace control.
643 my $strip_left = ($raw_expr =~ /^-(?:\s|$)/);
644 my $strip_right = ($raw_expr =~ /(?:^|\s)-\s*$/);
645 my $expr = $raw_expr;
646 $expr =~ s/^\s+|\s+$//g;
647 $expr =~ s/^-\s+// if $strip_left; # remove leading "- "
648 $expr =~ s/\s+-$// if $strip_right; # remove trailing " -"
649 # Strip whitespace from preceding text token if {{- }}
650 if ($strip_left && @tokens && $tokens[-1][0] eq 'text') {
651 $tokens[-1][1] =~ s/\s+$//;
652 splice @tokens, -1 if $tokens[-1][1] eq '';
653 }
654 push @tokens, [ 'var', $expr, $strip_right ];
655 $pos = $end + length($ve);
656 # Strip leading whitespace from next text if {{ -}}
657 if ($strip_right && $pos < $len) {
658 my $rest = substr($source, $pos);
659 my $stripped = $rest;
660 $stripped =~ s/^\s+//;
661 $pos += length($rest) - length($stripped);
662 }
663 }
664 else {
665 $next = $block_pos;
666 my $end = index($source, $be, $next + length($bs));
667 if ($end < 0) {
668 push @tokens, [ 'text', substr($source, $pos) ];
669 last;
670 }
671 if ($next > $pos) {
672 # Whitespace control: {% - strips preceding whitespace
673 my $text_before = substr($source, $pos, $next - $pos);
674 my $stmt_raw = substr($source, $next + length($bs), $end - $next - length($bs));
675 if ($stmt_raw =~ /^-/) {
676 $text_before =~ s/\s+$//;
677 }
678 push @tokens, [ 'text', $text_before ] if $text_before ne '';
679 }
680 my $stmt_full = substr($source, $next + length($bs), $end - $next - length($bs));
681 my $rstrip_tag = ($stmt_full =~ /\s*-\s*$/);
682 my $stmt = $stmt_full;
683 $stmt =~ s/^\s+|\s+$//g;
684 $stmt =~ s/^-\s*|\s*-$//g;
685 push @tokens, [ 'tag', $stmt ];
686 $pos = $end + length($be);
687 # Whitespace control: -%} strips following whitespace
688 if ($rstrip_tag && $pos < $len) {
689 substr($source, $pos) =~ s/^\s+//;
690 $pos = $len - length($source) + $pos if $source =~ s/^(\s+)//;
691 # Simpler: just advance pos past leading whitespace
692 my $rest = substr($source, $pos);
693 my $stripped = $rest;
694 $stripped =~ s/^\s+//;
695 $pos += length($rest) - length($stripped);
696 }
697 # trim_blocks: eat newline after %}
698 if (!$rstrip_tag && $self->{trim_blocks} && $pos < $len && substr($source, $pos, 1) eq "\n") {
699 $pos++;
700 }
701 }
702 }
703 return @tokens;
704 }
705  
706 ###############################################################################
707 # _eval_tokens - Execute a token list and return rendered string
708 ###############################################################################
709 sub _eval_tokens {
710 my ($self, $tokens, $vars, $start, $filename) = @_;
711 $start = 0 unless defined $start;
712  
713 my $out = '';
714 my $i = $start;
715  
716 while ($i <= $#$tokens) {
717 my ($type, $content) = @{$tokens->[$i]};
718  
719 if ($type eq 'text') {
720 $out .= $content;
721 $i++;
722 }
723 elsif ($type eq 'var') {
724 my $val = $self->_eval_expr($content, $vars);
725 if (ref($val) eq 'HP::Handy::SafeString') {
726 $val = $$val;
727 }
728 elsif ($self->{auto_escape} && defined $val && !ref($val)) {
729 $val = _html_escape($val);
730 }
731 $out .= defined $val ? $val : '';
732 $i++;
733 }
734 elsif ($type eq 'tag') {
735 my $stmt = $content;
736  
737 # --- set ---
738 if ($stmt =~ /^set\s+(\w+)\s*=\s*(.+)$/) {
739 my ($vname, $expr) = ($1, $2);
740 $vars->{$vname} = $self->_eval_expr($expr, $vars);
741 $i++;
742 }
743 # --- set block (multi-line) ---
744 elsif ($stmt =~ /^set\s+(\w+)\s*$/) {
745 my $vname = $1;
746 my ($body, $ni) = $self->_collect_until($tokens, $i + 1, 'endset');
747 $vars->{$vname} = $self->_eval_tokens($tokens, $vars, $i + 1, $filename);
748 # re-render just the body tokens
749 my @body_tokens = @{$tokens}[$i+1 .. $ni-1];
750 $vars->{$vname} = $self->_eval_tokens(\@body_tokens, $vars, 0, $filename);
751 $i = $ni + 1;
752 }
753 # --- if / elif / else / endif ---
754 elsif ($stmt =~ /^if\s+(.+)$/) {
755 my $cond_expr = $1;
756 my ($result, $ni) = $self->_eval_if($tokens, $i, $vars, $filename);
757 $out .= $result;
758 $i = $ni;
759 }
760 # --- for / endfor ---
761 elsif ($stmt =~ /^for\s+(.+?)\s+in\s+(.+?)(?:\s+if\s+(.+))?$/) {
762 my ($loop_var, $iter_expr, $cond_expr) = ($1, $2, $3);
763 my ($result, $ni) = $self->_eval_for($tokens, $i, $vars, $loop_var, $iter_expr, $cond_expr, $filename);
764 $out .= $result;
765 $i = $ni;
766 }
767 # --- include ---
768 elsif ($stmt =~ /^include\s+["']([^"']+)["'](?:\s+ignore\s+missing)?$/) {
769 my $inc_file = $1;
770 my $inc_src;
771 eval { $inc_src = $self->_load_file($inc_file) };
772 if ($@) {
773 $inc_src = '' if $stmt =~ /ignore\s+missing/;
774 croak $@ unless $stmt =~ /ignore\s+missing/;
775 }
776 $out .= $self->_eval_template($inc_src, { %$vars }, $inc_file) if defined $inc_src;
777 $i++;
778 }
779 # --- call macro ---
780 elsif ($stmt =~ /^(\w+)\s*\(([^)]*)\)$/ && exists $self->{_macros}{$1}) {
781 my ($mname, $argstr) = ($1, $2);
782 $out .= $self->_call_macro($mname, $argstr, $vars, $filename);
783 $i++;
784 }
785 # --- raw / endraw ---
786 elsif ($stmt eq 'raw') {
787 my ($raw, $ni) = $self->_collect_raw($tokens, $i + 1);
788 $out .= $raw;
789 $i = $ni + 1;
790 }
791 # --- with / endwith ---
792 elsif ($stmt =~ /^with(?:\s+(.+))?$/) {
793 my $assigns = $1;
794 my %local_vars = %$vars;
795 if (defined $assigns) {
796 for my $pair (_split_args($assigns)) {
797 if ($pair =~ /^(\w+)\s*=\s*(.+)$/) {
798 $local_vars{$1} = $self->_eval_expr($2, { %local_vars });
799 }
800 }
801 }
802 my ($body_tokens_ref, $ni) = $self->_collect_until($tokens, $i + 1, 'endwith');
803 $out .= $self->_eval_tokens($body_tokens_ref, { %local_vars }, 0, $filename);
804 $i = $ni + 1;
805 }
806 # --- block (standalone, no inheritance) ---
807 elsif ($stmt =~ /^block\s+(\w+)$/) {
808 my $bname = $1;
809 my ($body_tokens_ref, $ni) = $self->_collect_until($tokens, $i + 1, "endblock $bname", 'endblock');
810 if (exists $self->{_blocks}{$bname}) {
811 $out .= $self->_eval_template($self->{_blocks}{$bname}, $vars, $filename);
812 }
813 else {
814 $out .= $self->_eval_tokens($body_tokens_ref, $vars, 0, $filename);
815 }
816 $i = $ni + 1;
817 }
818 # skip endxxx tags (consumed by their openers above)
819 elsif ($stmt =~ /^end(if|for|block|macro|raw|with|set)/ || $stmt =~ /^(else|elif)/) {
820 $i++;
821 }
822 else {
823 # Unknown tag: pass through as-is for forward compatibility
824 $out .= $self->{block_start} . ' ' . $stmt . ' ' . $self->{block_end};
825 $i++;
826 }
827 }
828 else {
829 $i++;
830 }
831 }
832 return $out;
833 }
834  
835 ###############################################################################
836 # _eval_if - Evaluate if/elif/else/endif block
837 ###############################################################################
838 sub _eval_if {
839 my ($self, $tokens, $start, $vars, $filename) = @_;
840  
841 # Collect all branches: [ [cond_expr, [tokens...]], ..., [undef, [tokens...]] ]
842 my @branches;
843 my $cur_cond = $tokens->[$start][1];
844 $cur_cond =~ s/^if\s+//;
845 my @cur_body;
846 my $depth = 1;
847 my $i = $start + 1;
848  
849 while ($i <= $#$tokens) {
850 my ($type, $content) = @{$tokens->[$i]};
851 if ($type eq 'tag') {
852 if ($content =~ /^if\b/) {
853 $depth++;
854 push @cur_body, $tokens->[$i];
855 }
856 elsif ($content eq 'endif') {
857 $depth--;
858 if ($depth == 0) {
859 push @branches, [ $cur_cond, [@cur_body] ];
860 $i++;
861 last;
862 }
863 else {
864 push @cur_body, $tokens->[$i];
865 }
866 }
867 elsif ($depth == 1 && $content =~ /^elif\s+(.+)$/) {
868 push @branches, [ $cur_cond, [@cur_body] ];
869 $cur_cond = $1;
870 @cur_body = ();
871 }
872 elsif ($depth == 1 && $content eq 'else') {
873 push @branches, [ $cur_cond, [@cur_body] ];
874 $cur_cond = undef;
875 @cur_body = ();
876 }
877 else {
878 push @cur_body, $tokens->[$i];
879 }
880 }
881 else {
882 push @cur_body, $tokens->[$i];
883 }
884 $i++;
885 }
886 push @branches, [ $cur_cond, [@cur_body] ] if @cur_body || !defined $cur_cond;
887  
888 my $result = '';
889 for my $branch (@branches) {
890 my ($cond, $body) = @$branch;
891 if (!defined $cond || $self->_eval_expr($cond, $vars)) {
892 $result = $self->_eval_tokens($body, $vars, 0, $filename);
893 last;
894 }
895 }
896 return ($result, $i);
897 }
898  
899 ###############################################################################
900 # _eval_for - Evaluate for loop
901 ###############################################################################
902 sub _eval_for {
903 my ($self, $tokens, $start, $vars, $loop_var, $iter_expr, $cond_expr, $filename) = @_;
904  
905 # Collect loop body tokens (until endfor at depth 1)
906 my (@body_tokens, @else_tokens);
907 my $in_else = 0;
908 my $depth = 1;
909 my $i = $start + 1;
910  
911 while ($i <= $#$tokens) {
912 my ($type, $content) = @{$tokens->[$i]};
913 if ($type eq 'tag') {
914 if ($content =~ /^(?:for|if|block|macro|with)\b/) { $depth++ }
915 elsif ($content =~ /^end(?:for|if|block|macro|with)/) {
916 $depth--;
917 if ($depth == 0 && $content eq 'endfor') { $i++; last }
918 }
919 elsif ($depth == 1 && $content eq 'else') {
920 $in_else = 1; $i++; next;
921 }
922 }
923 if ($in_else) { push @else_tokens, $tokens->[$i] }
924 else { push @body_tokens, $tokens->[$i] }
925 $i++;
926 }
927  
928 # Evaluate iterable
929 my $iter = $self->_eval_expr($iter_expr, $vars);
930 my @items;
931 if (ref($iter) eq 'ARRAY') {
932 @items = @$iter;
933 }
934 elsif (ref($iter) eq 'HASH') {
935 @items = map { [ $_, $iter->{$_} ] } sort keys %$iter;
936 }
937 elsif (defined $iter) {
938 @items = ($iter);
939 }
940  
941 # Apply loop filter
942 if (defined $cond_expr) {
943 my @filtered;
944 for my $item (@items) {
945 my %loop_vars = %$vars;
946 $self->_assign_loop_var(\%loop_vars, $loop_var, $item);
947 push @filtered, $item if $self->_eval_expr($cond_expr, \%loop_vars);
948 }
949 @items = @filtered;
950 }
951  
952 if (!@items) {
953 return ($self->_eval_tokens(\@else_tokens, $vars, 0, $filename), $i);
954 }
955  
956 my $total = scalar @items;
957 my $result = '';
958  
959 for my $idx (0 .. $#items) {
960 my %loop_vars = %$vars;
961 $self->_assign_loop_var(\%loop_vars, $loop_var, $items[$idx]);
962  
963 # loop special variable
964 $loop_vars{loop} = {
965 index => $idx + 1,
966 index0 => $idx,
967 revindex => $total - $idx,
968 revindex0 => $total - $idx - 1,
969 first => ($idx == 0) ? 1 : 0,
970 last => ($idx == $#items) ? 1 : 0,
971 length => $total,
972 depth => 1,
973 depth0 => 0,
974 odd => ($idx % 2 == 0) ? 0 : 1,
975 even => ($idx % 2 == 0) ? 1 : 0,
976 changed => sub { my $attr = shift; _loop_changed($attr, $items[$idx], $idx > 0 ? $items[$idx-1] : undef) },
977 };
978  
979 $result .= $self->_eval_tokens(\@body_tokens, \%loop_vars, 0, $filename);
980 }
981  
982 return ($result, $i);
983 }
984  
985 sub _assign_loop_var {
986 my ($self, $vars, $loop_var, $item) = @_;
987 # Tuple unpacking: "k, v" in "for k, v in ..."
988 if ($loop_var =~ /^(\w+)\s*,\s*(\w+)$/) {
989 my ($k, $v) = ($1, $2);
990 if (ref($item) eq 'ARRAY') {
991 $vars->{$k} = $item->[0];
992 $vars->{$v} = $item->[1];
993 }
994 else {
995 $vars->{$k} = $item;
996 $vars->{$v} = undef;
997 }
998 }
999 else {
1000 $vars->{$loop_var} = $item;
1001 }
1002 }
1003  
1004 sub _loop_changed {
1005 my ($attr, $cur, $prev) = @_;
1006 return 1 unless defined $prev;
1007 my $cv = _get_attr($cur, $attr);
1008 my $pv = _get_attr($prev, $attr);
1009 return (!defined $cv && !defined $pv) ? 0
1010 : (!defined $cv || !defined $pv) ? 1
1011 : $cv ne $pv ? 1 : 0;
1012 }
1013  
1014 ###############################################################################
1015 # _collect_until - Collect tokens until end tag (depth-aware)
1016 ###############################################################################
1017 sub _collect_until {
1018 my ($self, $tokens, $start, @end_tags) = @_;
1019 my %ends = map { $_ => 1 } @end_tags;
1020 my @body;
1021 my $depth = 1;
1022 my $i = $start;
1023  
1024 # Map each opener tag to its closer. We track depth only for
1025 # openers whose closer matches one of the @end_tags we are looking for,
1026 # plus any nested use of the SAME opener.
1027 my %opener_to_closer = (
1028 'if' => 'endif',
1029 'for' => 'endfor',
1030 'block' => 'endblock',
1031 'macro' => 'endmacro',
1032 'with' => 'endwith',
1033 'raw' => 'endraw',
1034 'set' => 'endset',
1035 );
1036 my %closer_to_opener = reverse %opener_to_closer;
1037  
1038 while ($i <= $#$tokens) {
1039 my ($type, $content) = @{$tokens->[$i]};
1040 if ($type eq 'tag') {
1041 my $bare = $content; $bare =~ s/\s.*//;
1042 if (exists $ends{$content}) {
1043 $depth--;
1044 last if $depth == 0;
1045 }
1046 elsif (exists $opener_to_closer{$bare}) {
1047 # Push only when the closer of THIS opener is in @end_tags
1048 # (i.e. same kind of nesting as what we're looking for)
1049 my $closer = $opener_to_closer{$bare};
1050 if (exists $ends{$closer}) {
1051 $depth++;
1052 }
1053 }
1054 }
1055 push @body, $tokens->[$i];
1056 $i++;
1057 }
1058 return (\@body, $i);
1059 }
1060  
1061 ###############################################################################
1062 # _collect_raw - Collect raw text tokens until endraw
1063 ###############################################################################
1064 sub _collect_raw {
1065 my ($self, $tokens, $start) = @_;
1066 my $raw = '';
1067 my $i = $start;
1068 while ($i <= $#$tokens) {
1069 my ($type, $content) = @{$tokens->[$i]};
1070 last if $type eq 'tag' && $content eq 'endraw';
1071 $raw .= $content;
1072 $i++;
1073 }
1074 return ($raw, $i);
1075 }
1076  
1077 ###############################################################################
1078 # _call_macro - Call a defined macro
1079 ###############################################################################
1080 sub _call_macro {
1081 my ($self, $mname, $argstr, $vars, $filename) = @_;
1082 my $macro = $self->{_macros}{$mname};
1083 return '' unless defined $macro;
1084  
1085 # Parse positional args
1086 my @arg_vals = _split_args($argstr);
1087 my %macro_vars = %$vars;
1088  
1089 my @margs = @{ $macro->{args} };
1090 my @mdefaults = @{ $macro->{defaults} };
1091  
1092 for my $idx (0 .. $#margs) {
1093 if ($idx < @arg_vals) {
1094 $macro_vars{$margs[$idx]} = $self->_eval_expr($arg_vals[$idx], $vars);
1095 }
1096 elsif (defined $mdefaults[$idx]) {
1097 $macro_vars{$margs[$idx]} = $self->_eval_expr($mdefaults[$idx], $vars);
1098 }
1099 else {
1100 $macro_vars{$margs[$idx]} = undef;
1101 }
1102 }
1103  
1104 # varargs / kwargs accessible as special vars
1105 $macro_vars{varargs} = [];
1106 $macro_vars{kwargs} = {};
1107  
1108 return $self->_eval_template($macro->{body}, { %macro_vars }, $filename);
1109 }
1110  
1111 ###############################################################################
1112 # _eval_expr - Evaluate a Jinja2 expression
1113 ###############################################################################
1114 sub _eval_expr {
1115 my ($self, $expr, $vars) = @_;
1116 $expr =~ s/^\s+|\s+$//g;
1117 return undef unless defined $expr && $expr ne '';
1118  
1119 # Literal: None / True / False
1120 return undef if $expr eq 'none' || $expr eq 'None' || $expr eq 'undefined';
1121 return 1 if $expr eq 'true' || $expr eq 'True';
1122 return 0 if $expr eq 'false' || $expr eq 'False';
1123  
1124 # Literal: integer / float
1125 return $expr + 0 if $expr =~ /^-?\d+(\.\d+)?$/;
1126  
1127 # Unary minus: -expr (where expr is not a literal number)
1128 if ($expr =~ /^-(.+)$/ && $1 !~ /^\d/) {
1129 my $val = $self->_eval_expr($1, $vars);
1130 return defined $val ? -$val : undef;
1131 }
1132  
1133 # Literal: string
1134 if ($expr =~ /^"((?:[^"\\]|\\.)*)"$/ || $expr =~ /^'((?:[^'\\]|\\.)*)'$/) {
1135 my $s = $1;
1136 $s =~ s/\\n/\n/g; $s =~ s/\\t/\t/g; $s =~ s/\\r/\r/g;
1137 $s =~ s/\\(.)/$1/g;
1138 return $s;
1139 }
1140  
1141 # Literal: [] list
1142 if ($expr =~ /^\[(.+)\]$/) {
1143 my @elems = _split_args($1);
1144 return [ map { $self->_eval_expr($_, $vars) } @elems ];
1145 }
1146  
1147 # Literal: {} dict
1148 if ($expr =~ /^\{(.+)\}$/) {
1149 return $self->_eval_dict($1, $vars);
1150 }
1151  
1152 # Literal: range() -- only when no pipe follows (e.g. range(3) but not range(3)|join)
1153 if ($expr =~ /^range\(([^|]*)\)$/) {
1154 return $self->_eval_range($1, $vars);
1155 }
1156  
1157 # Conditional expression: a if cond else b
1158 if ($expr =~ /^(.+?)\s+if\s+(.+?)\s+else\s+(.+)$/) {
1159 my ($a, $cond, $b) = ($1, $2, $3);
1160 return $self->_eval_expr($cond, $vars) ? $self->_eval_expr($a, $vars) : $self->_eval_expr($b, $vars);
1161 }
1162  
1163 # 'not' operator
1164 if ($expr =~ /^not\s+(.+)$/) {
1165 return $self->_eval_expr($1, $vars) ? 0 : 1;
1166 }
1167  
1168 # 'in' / 'not in' operator
1169 if ($expr =~ /^(.+?)\s+not\s+in\s+(.+)$/) {
1170 return $TESTS{in}->($self->_eval_expr($1, $vars), $self->_eval_expr($2, $vars)) ? 0 : 1;
1171 }
1172 if ($expr =~ /^(.+?)\s+in\s+(.+)$/) {
1173 return $TESTS{in}->($self->_eval_expr($1, $vars), $self->_eval_expr($2, $vars));
1174 }
1175  
1176 # Boolean operators: and / or
1177 if ($expr =~ /^(.+?)\s+or\s+(.+)$/) {
1178 my $a = $self->_eval_expr($1, $vars);
1179 return $a if $a;
1180 return $self->_eval_expr($2, $vars);
1181 }
1182 if ($expr =~ /^(.+?)\s+and\s+(.+)$/) {
1183 my $a = $self->_eval_expr($1, $vars);
1184 return $a ? $self->_eval_expr($2, $vars) : $a;
1185 }
1186  
1187 # Filter pipeline: expr | filter1 | filter2(arg)
1188 # Must be checked before comparison operators so that ">" inside
1189 # filter arg strings (e.g. replace("-->","x")) is not misread.
1190 if ($expr =~ /^(.+?)\s*\|\s*(\w+)(.*)$/) {
1191 my ($lhs, $fname, $rest) = ($1, $2, $3);
1192 my $val = $self->_eval_expr($lhs, $vars);
1193  
1194 my $fargs_str = '';
1195 my $remaining = '';
1196 if ($rest =~ /^\s*\(/) {
1197 # Find matching closing paren, respecting quotes and nesting
1198 my $depth2 = 0; my $in_sq2 = 0; my $in_dq2 = 0;
1199 my $found2 = -1;
1200 my $rs = $rest; $rs =~ s/^\s*//;
1201 for my $ci (0 .. length($rs) - 1) {
1202 my $c = substr($rs, $ci, 1);
1203 if (!$in_sq2 && !$in_dq2 && $c eq "'") { $in_sq2 = 1; next }
1204 if ($in_sq2 && $c eq "'") { $in_sq2 = 0; next }
1205 if (!$in_sq2 && !$in_dq2 && $c eq '"') { $in_dq2 = 1; next }
1206 if ($in_dq2 && $c eq '"') { $in_dq2 = 0; next }
1207 if (!$in_sq2 && !$in_dq2) {
1208 if ($c eq '(') { $depth2++ }
1209 elsif ($c eq ')') { $depth2--; if ($depth2 == 0) { $found2 = $ci; last } }
1210 }
1211 }
1212 if ($found2 >= 0) {
1213 $fargs_str = substr($rs, 1, $found2 - 1);
1214 $remaining = substr($rs, $found2 + 1);
1215 }
1216 }
1217 elsif ($rest =~ /^\s*(\|.+)$/) {
1218 $remaining = $1;
1219 }
1220  
1221 my @fargs;
1222 if ($fargs_str ne '') {
1223 @fargs = map { $self->_eval_expr($_, $vars) } _split_args($fargs_str);
1224 }
1225  
1226 my $fn = $self->{_filters}{$fname};
1227 $val = $fn ? $fn->($val, @fargs) : $val;
1228  
1229 # Continue pipeline
1230 if ($remaining =~ s/^\s*\|\s*//) {
1231 return $self->_eval_expr("__PIPEVAL__ | $remaining", { %$vars, '__PIPEVAL__' => $val });
1232 }
1233 return $val;
1234 }
1235  
1236 # Comparison operators
1237 if ($expr =~ /^(.+?)\s*(==|!=|>=|<=|>|<)\s*(.+)$/) {
1238 my ($lhs, $op, $rhs) = ($1, $2, $3);
1239 my $l = $self->_eval_expr($lhs, $vars);
1240 my $r = $self->_eval_expr($rhs, $vars);
1241 return 0 unless defined $l && defined $r;
1242 my $numeric = ($l =~ /^-?(?:\d+\.?\d*|\.\d+)$/ && $r =~ /^-?(?:\d+\.?\d*|\.\d+)$/);
1243 if ($op eq '==') { return $numeric ? ($l == $r ? 1 : 0) : ($l eq $r ? 1 : 0) }
1244 if ($op eq '!=') { return $numeric ? ($l != $r ? 1 : 0) : ($l ne $r ? 1 : 0) }
1245 if ($op eq '>') { return $l > $r ? 1 : 0 }
1246 if ($op eq '<') { return $l < $r ? 1 : 0 }
1247 if ($op eq '>=') { return $l >= $r ? 1 : 0 }
1248 if ($op eq '<=') { return $l <= $r ? 1 : 0 }
1249 }
1250  
1251 # Arithmetic: match ** and // before single-char operators
1252 if ($expr =~ /^(.+?)\s*(\*\*|\/\/)\s*(.+)$/) {
1253 my ($lhs, $op, $rhs) = ($1, $2, $3);
1254 my $l = $self->_eval_expr($lhs, $vars);
1255 my $r = $self->_eval_expr($rhs, $vars);
1256 if (defined $l && defined $r) {
1257 if ($op eq '//') { return $r != 0 ? int($l / $r) : undef }
1258 if ($op eq '**') { return $l ** $r }
1259 }
1260 return undef;
1261 }
1262  
1263 # Arithmetic: scan for operator at depth-0 (respects parentheses)
1264 {
1265 my $depth3 = 0; my $in_sq3 = 0; my $in_dq3 = 0;
1266 my $op_pos = -1; my $op_char = '';
1267 for my $ci (0 .. length($expr) - 1) {
1268 my $c = substr($expr, $ci, 1);
1269 if (!$in_sq3 && !$in_dq3 && $c eq "'") { $in_sq3 = 1; next }
1270 if ($in_sq3 && $c eq "'") { $in_sq3 = 0; next }
1271 if (!$in_sq3 && !$in_dq3 && $c eq '"') { $in_dq3 = 1; next }
1272 if ($in_dq3 && $c eq '"') { $in_dq3 = 0; next }
1273 next if $in_sq3 || $in_dq3;
1274 if ($c eq '(' || $c eq '[' || $c eq '{') { $depth3++; next }
1275 if ($c eq ')' || $c eq ']' || $c eq '}') { $depth3--; next }
1276 next if $depth3 != 0;
1277 if ($c =~ /^[+\-*\/%~]$/) {
1278 next if $ci == 0;
1279 my $prev = substr($expr, $ci - 1, 1);
1280 next if $prev =~ /^[+\-*\/%~(]$/ || $prev eq "";
1281 next if $c eq '*' && $ci + 1 < length($expr) && substr($expr, $ci + 1, 1) eq '*';
1282 next if $c eq '/' && $ci + 1 < length($expr) && substr($expr, $ci + 1, 1) eq '/';
1283 $op_pos = $ci; $op_char = $c;
1284 last;
1285 }
1286 }
1287 if ($op_pos > 0) {
1288 my $lhs = substr($expr, 0, $op_pos);
1289 my $rhs = substr($expr, $op_pos + 1);
1290 $lhs =~ s/\s+$//; $rhs =~ s/^\s+//;
1291 my $l = $self->_eval_expr($lhs, $vars);
1292 my $r = $self->_eval_expr($rhs, $vars);
1293 if (defined $l && defined $r) {
1294 if ($op_char eq '+') {
1295 return ($l =~ /^-?\d/ && $r =~ /^-?\d/) ? $l + $r : $l . $r;
1296 }
1297 if ($op_char eq '~') { return $l . $r }
1298 if ($op_char eq '-') { return $l - $r }
1299 if ($op_char eq '*') { return $l * $r }
1300 if ($op_char eq '/') { return $r != 0 ? $l / $r : undef }
1301 if ($op_char eq '%') { return $r != 0 ? $l % $r : undef }
1302 }
1303 }
1304 }
1305  
1306 # Parenthesised expression -- must be before is/is not so that
1307 # (expr is test) does not mis-parse the leading "(" as part of lhs.
1308 if ($expr =~ /^\((.+)\)$/) {
1309 return $self->_eval_expr($1, $vars);
1310 }
1311  
1312 # is / is not test
1313 if ($expr =~ /^(.+?)\s+is\s+not\b\s+(\w+)(?:\s+(.+))?$/) {
1314 my ($lhs, $test, $arg) = ($1, $2, $3);
1315 my $val = $self->_eval_expr($lhs, $vars);
1316 my $targ = defined $arg ? $self->_eval_expr($arg, $vars) : undef;
1317 my $fn = $self->{_tests}{$test};
1318 return $fn ? ($fn->($val, $targ) ? 0 : 1) : 1;
1319 }
1320 if ($expr =~ /^(.+?)\s+is\s+(\w+)(?:\s+(.+))?$/) {
1321 my ($lhs, $test, $arg) = ($1, $2, $3);
1322 my $val = $self->_eval_expr($lhs, $vars);
1323 my $targ = defined $arg ? $self->_eval_expr($arg, $vars) : undef;
1324 my $fn = $self->{_tests}{$test};
1325 return $fn ? ($fn->($val, $targ) ? 1 : 0) : 0;
1326 }
1327  
1328 # Attribute access: obj.attr or obj["key"] or obj['key']
1329 if ($expr =~ /^(.+?)\.(\w+)(?:\(([^)]*)\))?$/) {
1330 my ($obj_expr, $attr, $call_args) = ($1, $2, $3);
1331 my $obj = $self->_eval_expr($obj_expr, $vars);
1332 if (defined $call_args) {
1333 # Method call (filters on object)
1334 my $fn = $self->{_filters}{$attr};
1335 my @args = map { $self->_eval_expr($_, $vars) } _split_args($call_args);
1336 return $fn ? $fn->($obj, @args) : undef;
1337 }
1338 return _get_attr($obj, $attr);
1339 }
1340  
1341 if ($expr =~ /^(.+?)\[["'](\w+)["']\]$/) {
1342 my ($obj_expr, $key) = ($1, $2);
1343 my $obj = $self->_eval_expr($obj_expr, $vars);
1344 return _get_attr($obj, $key);
1345 }
1346  
1347 if ($expr =~ /^(.+?)\[(-?\d+)\]$/) {
1348 my ($obj_expr, $idx) = ($1, $2);
1349 my $obj = $self->_eval_expr($obj_expr, $vars);
1350 return ref($obj) eq 'ARRAY' ? $obj->[$idx] : undef;
1351 }
1352  
1353 # Slice: list[start:end]
1354 if ($expr =~ /^(.+?)\[(-?\d*):(-?\d*)\]$/) {
1355 my ($obj_expr, $s, $e) = ($1, $2, $3);
1356 my $obj = $self->_eval_expr($obj_expr, $vars);
1357 return undef unless ref($obj) eq 'ARRAY';
1358 my $len = scalar @$obj;
1359 my $si = ($s ne '') ? int($s) : 0;
1360 my $ei = ($e ne '') ? int($e) : $len;
1361 $si += $len if $si < 0;
1362 $ei += $len if $ei < 0;
1363 $si = 0 if $si < 0;
1364 $ei = $len if $ei > $len;
1365 return [ @{$obj}[$si .. $ei - 1] ];
1366 }
1367  
1368 # Function/macro call: name(args)
1369 if ($expr =~ /^(\w+)\s*\(([^)]*)\)$/) {
1370 my ($fname, $argstr) = ($1, $2);
1371 # Macro call
1372 if (exists $self->{_macros}{$fname}) {
1373 return $self->_call_macro($fname, $argstr, $vars, '<expr>');
1374 }
1375 # Built-in functions
1376 if ($fname eq 'range') {
1377 return $self->_eval_range($argstr, $vars);
1378 }
1379 }
1380  
1381 # Variable lookup
1382 if ($expr =~ /^(\w+)$/) {
1383 return exists $vars->{$expr} ? $vars->{$expr} : undef;
1384 }
1385  
1386 return undef;
1387 }
1388  
1389 ###############################################################################
1390 # _eval_dict - Parse and evaluate a dict literal { key: val, ... }
1391 ###############################################################################
1392 sub _eval_dict {
1393 my ($self, $inner, $vars) = @_;
1394 my %h;
1395 # Simple k:v split (no nested dicts)
1396 for my $pair (_split_args($inner)) {
1397 if ($pair =~ /^(.+?)\s*:\s*(.+)$/) {
1398 my $k = $self->_eval_expr($1, $vars);
1399 my $v = $self->_eval_expr($2, $vars);
1400 $h{$k} = $v if defined $k;
1401 }
1402 }
1403 return { %h };
1404 }
1405  
1406 ###############################################################################
1407 # _eval_range - Evaluate range(stop) / range(start, stop[, step])
1408 ###############################################################################
1409 sub _eval_range {
1410 my ($self, $args_str, $vars) = @_;
1411 my @args = map { $self->_eval_expr($_, $vars) } _split_args($args_str);
1412 my ($start, $stop, $step);
1413 if (@args == 1) { ($start, $stop, $step) = (0, int($args[0]), 1) }
1414 elsif (@args == 2) { ($start, $stop, $step) = (int($args[0]), int($args[1]), 1) }
1415 else { ($start, $stop, $step) = (int($args[0]), int($args[1]), int($args[2] || 1)) }
1416 $step = 1 if $step == 0;
1417 my @result;
1418 if ($step > 0) { for (my $n = $start; $n < $stop; $n += $step) { push @result, $n } }
1419 else { for (my $n = $start; $n > $stop; $n += $step) { push @result, $n } }
1420 return [ @result ];
1421 }
1422  
1423 ###############################################################################
1424 # _get_attr - Get attribute from hash or array
1425 ###############################################################################
1426 sub _get_attr {
1427 my ($obj, $attr) = @_;
1428 return undef unless defined $obj;
1429 if (ref($obj) eq 'HASH') {
1430 return exists $obj->{$attr} ? $obj->{$attr} : undef;
1431 }
1432 if (ref($obj) eq 'ARRAY') {
1433 return $attr =~ /^-?\d+$/ ? $obj->[$attr] : scalar @$obj;
1434 }
1435 return undef;
1436 }
1437  
1438 ###############################################################################
1439 # _split_args - Split comma-separated arguments (respects nested parens/quotes)
1440 ###############################################################################
1441 sub _split_args {
1442 my ($str) = @_;
1443 return () unless defined $str && $str =~ /\S/;
1444 my @args;
1445 my $cur = '';
1446 my $depth = 0;
1447 my $in_sq = 0;
1448 my $in_dq = 0;
1449  
1450 for my $ch (split //, $str) {
1451 if (!$in_sq && !$in_dq && $ch eq "'") { $in_sq = 1; $cur .= $ch; next }
1452 if ($in_sq && $ch eq "'") { $in_sq = 0; $cur .= $ch; next }
1453 if (!$in_sq && !$in_dq && $ch eq '"') { $in_dq = 1; $cur .= $ch; next }
1454 if ($in_dq && $ch eq '"') { $in_dq = 0; $cur .= $ch; next }
1455 if (!$in_sq && !$in_dq) {
1456 if ($ch eq '(' || $ch eq '[' || $ch eq '{') { $depth++ }
1457 elsif ($ch eq ')' || $ch eq ']' || $ch eq '}') { $depth-- }
1458 elsif ($ch eq ',' && $depth == 0) {
1459 $cur =~ s/^\s+|\s+$//g;
1460 push @args, $cur;
1461 $cur = '';
1462 next;
1463 }
1464 }
1465 $cur .= $ch;
1466 }
1467 $cur =~ s/^\s+|\s+$//g;
1468 push @args, $cur if $cur ne '';
1469 return @args;
1470 }
1471  
1472 ###############################################################################
1473 # _html_escape - Escape HTML special characters
1474 ###############################################################################
1475 sub _html_escape {
1476 my ($s) = @_;
1477 return '' unless defined $s;
1478 $s =~ s/&/&amp;/g;
1479 $s =~ s/</&lt;/g;
1480 $s =~ s/>/&gt;/g;
1481 $s =~ s/"/&quot;/g;
1482 $s =~ s/'/&#39;/g;
1483 return $s;
1484 }
1485  
1486 ###############################################################################
1487 # _to_json - Minimal JSON serializer (no external dependency)
1488 ###############################################################################
1489 sub _to_json {
1490 my ($val) = @_;
1491 return 'null' unless defined $val;
1492 return 'true' if ref($val) eq 'SCALAR' && $$val == 1;
1493 return 'false' if ref($val) eq 'SCALAR' && $$val == 0;
1494 if (ref($val) eq 'ARRAY') {
1495 return '[' . join(',', map { _to_json($_) } @$val) . ']';
1496 }
1497 if (ref($val) eq 'HASH') {
1498 return '{' . join(',', map {
1499 _to_json($_) . ':' . _to_json($val->{$_})
1500 } sort keys %$val) . '}';
1501 }
1502 if ($val =~ /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/) {
1503 return $val;
1504 }
1505 $val =~ s/\\/\\\\/g;
1506 $val =~ s/"/\\"/g;
1507 $val =~ s/\n/\\n/g;
1508 $val =~ s/\r/\\r/g;
1509 $val =~ s/\t/\\t/g;
1510 return "\"$val\"";
1511 }
1512  
1513 ###############################################################################
1514 # Back to main package -- demo when run directly
1515 ###############################################################################
1516  
1517 # Run as script: perl lib/HP/Handy.pm
1518 unless (caller) {
1519 my $tmpl = HP::Handy->new(auto_escape => 1);
1520  
1521 my $source = <<'TMPL';
1522 <!DOCTYPE html>
1523 <html>
1524 <head><meta charset="utf-8"><title>HP::Handy Demo</title>
1525 <style>body{font-family:sans-serif;max-width:600px;margin:40px auto;padding:0 20px}
1526 h1{color:#336699}table{border-collapse:collapse;width:100%}
1527 td { padding: 6px 10px; border: 1px solid #ccc }
1528 th { padding: 6px 10px; border: 1px solid #ccc }
1529 tr:nth-child(even) { background: #f8f8f8 }
1530 </style>
1531 </head>
1532 <body>
1533 <h1>HP::Handy Demo</h1>
1534 <p>Version: {{ version }}</p>
1535  
1536 <h2>Variable and Filter</h2>
1537 <p>Hello, {{ name | upper }}!</p>
1538 <p>Escaped: {{ snippet }}</p>
1539  
1540 <h2>For Loop</h2>
1541 <table>
1542 <tr><th>#</th><th>Item</th><th>First?</th><th>Last?</th></tr>
1543 {% for item in items %}
1544 <tr>
1545 <td>{{ loop.index }}</td>
1546 <td>{{ item }}</td>
1547 <td>{{ "yes" if loop.first else "no" }}</td>
1548 <td>{{ "yes" if loop.last else "no" }}</td>
1549 </tr>
1550 {% endfor %}
1551 </table>
1552  
1553 <h2>Conditional</h2>
1554 {% if score >= 90 %}
1555 <p>Grade: A</p>
1556 {% elif score >= 70 %}
1557 <p>Grade: B</p>
1558 {% else %}
1559 <p>Grade: C</p>
1560 {% endif %}
1561  
1562 <h2>Set and Default Filter</h2>
1563 {% set greeting = "Konnichiwa" %}
1564 <p>{{ greeting | default("Hello") }}</p>
1565 <p>Missing: {{ missing | default("(none)") }}</p>
1566 </body>
1567 </html>
1568 TMPL
1569  
1570 my $html = $tmpl->render_string($source, {
1571 version => $HP::Handy::VERSION,
1572 name => 'World',
1573 snippet => '<script>alert("xss")</script>',
1574 items => [ 'Perl', 'Python', 'Ruby', 'JavaScript' ],
1575 score => 85,
1576 });
1577  
1578 print $html;
1579 }
1580  
1581  
1582 ###############################################################################
1583 # HP::Handy::SafeString - trusted HTML string (bypasses auto_escape)
1584 ###############################################################################
1585 package HP::Handy::SafeString;
1586 use overload
1587 q("") => sub { ${$_[0]} },
1588 fallback => 1;
1589  
1590 package HP::Handy;
1591  
1592 1;
1593  
1594 __END__