/usr/share/perl5/Template/Alloy/Parse.pm is in libtemplate-alloy-perl 1.020-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 | package Template::Alloy::Parse;
=head1 NAME
Template::Alloy::Parse - Common parsing role for creating AST from templates
=cut
use strict;
use warnings;
use base qw(Exporter);
use Template::Alloy;
use Template::Alloy::Operator qw($QR_OP $QR_OP_ASSIGN $QR_OP_PREFIX
$OP $OP_ASSIGN $OP_PREFIX $OP_POSTFIX);
our $VERSION = $Template::Alloy::VERSION;
our @EXPORT_OK = qw(define_directive define_syntax
$ALIASES $DIRECTIVES $TAGS $QR_DIRECTIVE $QR_COMMENTS);
sub new { die "This class is a role for use by packages such as Template::Alloy" }
###----------------------------------------------------------------###
our $TAGS = {
asp => ['<%', '%>' ], # ASP
default => ['\[%', '%\]' ], # default
html => ['<!--', '-->' ], # HTML comments
mason => ['<%', '>' ], # HTML::Mason
metatext => ['%%', '%%' ], # Text::MetaText
php => ['<\?', '\?>' ], # PHP
star => ['\[\*', '\*\]' ], # TT alternate
template => ['\[%', '%\]' ], # Normal Template Toolkit
template1 => ['[\[%]%', '%[%\]]'], # TT1
tt2 => ['\[%', '%\]' ], # TT2
};
our $SYNTAX = {
alloy => sub { shift->parse_tree_tt3(@_) },
js => sub { shift->parse_tree_js(@_) },
jsr => sub { shift->parse_tree_jsr(@_) },
ht => sub { my $self = shift; local $self->{'V2EQUALS'} = 0; local $self->{'EXPR'} = 0; $self->parse_tree_hte(@_) },
hte => sub { my $self = shift; local $self->{'V2EQUALS'} = 0; $self->parse_tree_hte(@_) },
tt3 => sub { shift->parse_tree_tt3(@_) },
tt2 => sub { my $self = shift; local $self->{'V2PIPE'} = 1; $self->parse_tree_tt3(@_) },
tt1 => sub { my $self = shift; local $self->{'V2PIPE'} = 1; local $self->{'V1DOLLAR'} = 1; $self->parse_tree_tt3(@_) },
tmpl => sub { shift->parse_tree_tmpl(@_) },
velocity => sub { shift->parse_tree_velocity(@_) },
};
our $DIRECTIVES = {
#name parse_sub play_sub block postdir continue no_interp
BLOCK => [\&parse_BLOCK, \&play_BLOCK, 1],
BREAK => [sub {}, \&play_control],
CALL => [\&parse_CALL, \&play_CALL],
CASE => [\&parse_CASE, undef, 0, 0, {SWITCH => 1, CASE => 1}],
CATCH => [\&parse_CATCH, undef, 0, 0, {TRY => 1, CATCH => 1}],
CLEAR => [sub {}, \&play_CLEAR],
'#' => [sub {}, sub {}],
COMMENT => [sub {}, sub {}, 1],
CONFIG => [\&parse_CONFIG, \&play_CONFIG],
DEBUG => [\&parse_DEBUG, \&play_DEBUG],
DEFAULT => [\&parse_DEFAULT, \&play_DEFAULT],
DUMP => [\&parse_DUMP, \&play_DUMP],
ELSE => [sub {}, undef, 0, 0, {IF => 1, ELSIF => 1, UNLESS => 1}],
ELSIF => [\&parse_IF, undef, 0, 0, {IF => 1, ELSIF => 1, UNLESS => 1}],
END => [sub {}, sub {}],
EVAL => [\&parse_EVAL, \&play_EVAL],
FILTER => [\&parse_FILTER, \&play_FILTER, 1, 1],
'|' => [\&parse_FILTER, \&play_FILTER, 1, 1],
FINAL => [sub {}, undef, 0, 0, {TRY => 1, CATCH => 1}],
FOR => [\&parse_FOR, \&play_FOR, 1, 1],
FOREACH => [\&parse_FOR, \&play_FOR, 1, 1],
GET => [\&parse_GET, \&play_GET],
IF => [\&parse_IF, \&play_IF, 1, 1],
INCLUDE => [\&parse_INCLUDE, \&play_INCLUDE],
INSERT => [\&parse_INSERT, \&play_INSERT],
JS => [sub {}, \&play_JS, 1, 0, 0, 1],
LAST => [sub {}, \&play_control],
LOOP => [\&parse_LOOP, \&play_LOOP, 1, 1],
MACRO => [\&parse_MACRO, \&play_MACRO],
META => [\&parse_META, \&play_META],
NEXT => [sub {}, \&play_control],
PERL => [sub {}, \&play_PERL, 1, 0, 0, 1],
PROCESS => [\&parse_PROCESS, \&play_PROCESS],
RAWPERL => [sub {}, \&play_RAWPERL, 1, 0, 0, 1],
RETURN => [\&parse_RETURN, \&play_control],
SET => [\&parse_SET, \&play_SET],
STOP => [sub {}, \&play_control],
SWITCH => [\&parse_SWITCH, \&play_SWITCH, 1],
TAGS => [\&parse_TAGS, sub {}],
THROW => [\&parse_THROW, \&play_THROW],
TRY => [sub {}, \&play_TRY, 1],
UNLESS => [\&parse_UNLESS, \&play_UNLESS, 1, 1],
USE => [\&parse_USE, \&play_USE],
VIEW => [\&parse_VIEW, \&play_VIEW, 1],
WHILE => [\&parse_WHILE, \&play_WHILE, 1, 1],
WRAPPER => [\&parse_WRAPPER, \&play_WRAPPER, 1, 1],
#name parse_sub play_sub block postdir continue no_interp
};
our $ALIASES = {
EVALUATE => 'EVAL',
};
our $QR_DIRECTIVE = '( [a-zA-Z]+\b | \| )';
our $QR_COMMENTS = '(?-s: \# .* \s*)*';
our $QR_FILENAME = '([a-zA-Z]]:/|/)? [\w\.][\w\-\.]* (?:/[\w\-\.]+)*';
our $QR_BLOCK = '\w+\b (?: :\w+\b)* )';
our $QR_NUM = '(?:\d*\.\d+ | \d+) (?: [eE][+-]?\d+ )?';
our $QR_AQ_SPACE = '(?: \\s+ | \$ | (?=;) )';
our $_escapes = {n => "\n", r => "\r", t => "\t", '"' => '"', '\\' => '\\', '$' => '$'};
our $QR_ESCAPES = qr{[nrt\"\$\\]};
sub define_directive {
my ($self, $name, $args) = @_;
$DIRECTIVES->{$name} = [@{ $args }{qw(parse_sub play_sub is_block is_postop continues no_interp)}];
return 1;
}
sub define_syntax {
my ($self, $name, $sub) = @_;
$SYNTAX->{$name} = $sub;
return 1;
}
###----------------------------------------------------------------###
sub parse_tree {
my $syntax = $_[0]->{'SYNTAX'} || 'alloy';
my $meth = $SYNTAX->{$syntax} || $_[0]->throw('config', "Unknown SYNTAX \"$syntax\"");
return $meth->(@_);
}
###----------------------------------------------------------------###
sub parse_expr {
my $self = shift;
my $str_ref = shift;
my $ARGS = shift || {};
my $is_aq = $ARGS->{'auto_quote'} ? 1 : 0;
my $mark = pos $$str_ref;
### allow for custom auto_quoting (such as hash constructors)
if ($is_aq) {
if ($$str_ref =~ m{ \G \s* $QR_COMMENTS $ARGS->{'auto_quote'} }gcx) {
return $1;
### allow for ${foo.bar} type constructs
} elsif ($$str_ref =~ m{ \G \$\{ }gcx) {
my $var = $self->parse_expr($str_ref);
$$str_ref =~ m{ \G \s* $QR_COMMENTS \} }gcxo
|| $self->throw('parse', 'Missing close "}" from "${"', undef, pos($$str_ref));
return $var;
### allow for auto-quoted $foo
} elsif ($$str_ref =~ m{ \G \$ }gcx) {
return $self->parse_expr($str_ref)
|| $self->throw('parse', "Missing variable", undef, pos($$str_ref));
}
}
$$str_ref =~ m{ \G \s* $QR_COMMENTS }gcxo;
### allow for macro definer
if ($$str_ref =~ m{ \G -> \s* }gcxo) { # longest token would be nice - until then this comes before prefix
local $self->{'_operator_precedence'} = 0; # reset presedence
my $args;
if ($$str_ref =~ m{ \G \( \s* }gcx) {
$args = $self->parse_args($str_ref, {positional_only => 1});
$$str_ref =~ m{ \G \) \s* }gcx || $self->throw('parse.missing', "Missing close ')'", undef, pos($$str_ref));
}
$$str_ref =~ m{ \G \{ $QR_COMMENTS }gcx || $self->throw('parse.missing', "Missing open '{'", undef, pos($$str_ref));
local $self->{'END_TAG'} = qr{ \} }x;
my $tree = $self->parse_tree_tt3($str_ref, 'one_tag_only');
return [[undef, '->', $args || [['this',0]], $tree]];
}
### test for leading prefix operators
my $has_prefix;
while (! $is_aq && $$str_ref =~ m{ \G ($QR_OP_PREFIX) }gcxo) {
push @{ $has_prefix }, $1;
$$str_ref =~ m{ \G \s* $QR_COMMENTS }gcxo;
}
my @var;
my $is_literal;
my $is_namespace;
my $already_parsed_args;
### allow hex
if ($$str_ref =~ m{ \G 0x ( [a-fA-F0-9]+ ) }gcx) {
my $number = eval { hex $1 } || 0;
push @var, \ $number;
$is_literal = 1;
### allow for numbers
} elsif ($$str_ref =~ m{ \G ( $QR_NUM ) }gcx) {
my $number = 0 + $1;
push @var, \ $number;
$is_literal = 1;
### allow for quoted array constructor
} elsif (! $is_aq && $$str_ref =~ m{ \G qw ([^\w\s]) \s* }gcxo) {
my $quote = $1;
$quote =~ y|([{<|)]}>|;
$$str_ref =~ m{ \G (.*?) (?<!\\) \Q$quote\E }gcxs
|| $self->throw('parse.missing.array_close', "Missing close \"$quote\"", undef, pos($$str_ref));
my $str = $1;
$str =~ s{ ^ \s+ }{}x;
$str =~ s{ \s+ $ }{}x;
$str =~ s{ \\ \Q$quote\E }{$quote}gx;
push @var, [undef, '[]', split /\s+/, $str];
### looks like a normal variable start
} elsif ($$str_ref =~ m{ \G (\w+) }gcx) {
push @var, $1;
$is_namespace = 1 if $self->{'NAMESPACE'} && $self->{'NAMESPACE'}->{$1};
### allow for regex constructor
} elsif (! $is_aq && $$str_ref =~ m{ \G / }gcx) {
$$str_ref =~ m{ \G (.*?) (?<! \\) / ([msixeg]*) }gcxs
|| $self->throw('parse', 'Unclosed regex tag "/"', undef, pos($$str_ref));
my ($str, $opts) = ($1, $2);
$self->throw('parse', 'e option not allowed on regex', undef, pos($$str_ref)) if $opts =~ /e/;
$self->throw('parse', 'g option not supported on regex', undef, pos($$str_ref)) if $opts =~ /g/;
$str =~ s|\\n|\n|g;
$str =~ s|\\t|\t|g;
$str =~ s|\\r|\r|g;
$str =~ s|\\\/|\/|g;
$str =~ s|\\\$|\$|g;
$self->throw('parse', "Invalid regex: $@", undef, pos($$str_ref)) if ! eval { "" =~ /$str/; 1 };
push @var, [undef, 'qr', $str, $opts];
### allow for single quoted strings
} elsif ($$str_ref =~ m{ \G \' (.*?) (?<! \\) \' }gcxs) {
my $str = $1;
$str =~ s{ \\\' }{\'}xg;
return $str if $is_aq;
push @var, \ $str;
$is_literal = 1;
### allow for double quoted strings
} elsif ($$str_ref =~ m{ \G \" }gcx) {
my @pieces;
while ($$str_ref =~ m{ \G (.*?) ([\"\$\\]) }gcxs) {
my ($str, $item) = ($1, $2);
if (length $str) {
if (defined($pieces[-1]) && ! ref($pieces[-1])) { $pieces[-1] .= $str; } else { push @pieces, $str }
}
if ($item eq '\\') {
my $chr = ($$str_ref =~ m{ \G ($QR_ESCAPES) }gcxo) ? $_escapes->{$1} : '\\';
if (defined($pieces[-1]) && ! ref($pieces[-1])) { $pieces[-1] .= $chr; } else { push @pieces, $chr }
next;
} elsif ($item eq '"') {
last;
} elsif ($self->{'AUTO_EVAL'}) {
if (defined($pieces[-1]) && ! ref($pieces[-1])) { $pieces[-1] .= '$'; } else { push @pieces, '$' }
next;
}
my $not = $$str_ref =~ m{ \G ! }gcx;
my $mark = pos($$str_ref);
my $ref;
if ($$str_ref =~ m{ \G \{ }gcx) {
local $self->{'_operator_precedence'} = 0; # allow operators
$ref = $self->parse_expr($str_ref);
$$str_ref =~ m{ \G \s* $QR_COMMENTS \} }gcxo
|| $self->throw('parse', 'Missing close }', undef, pos($$str_ref));
} else {
local $self->{'_operator_precedence'} = 1; # no operators
$ref = $self->parse_expr($str_ref)
|| $self->throw('parse', "Error while parsing for interpolated string", undef, pos($$str_ref));
}
if (! $not && $self->{'SHOW_UNDEFINED_INTERP'}) {
$ref = [[undef, '//', $ref, '$'.substr($$str_ref, $mark, pos($$str_ref)-$mark)], 0];
}
push @pieces, $ref if defined $ref;
}
if (! @pieces) { # [% "" %]
return '' if $is_aq;
push @var, \ '';
$is_literal = 1;
} elsif (@pieces == 1 && ref $pieces[0]) { # [% "$foo" %] or [% "${ 1 + 2 }" %]
return $pieces[0] if $is_aq;
push @var, @{ $pieces[0] };
$already_parsed_args = 1;
} elsif ($self->{'AUTO_EVAL'}) {
push @var, [undef, '~', @pieces], 0, '|', 'eval', 0;
return \@var if $is_aq;
$already_parsed_args = 1;
} elsif (@pieces == 1) { # [% "foo" %]
return $pieces[0] if $is_aq;
push @var, \ $pieces[0];
$is_literal = 1;
} else { # [% "foo $bar baz" %]
push @var, [undef, '~', @pieces];
return [$var[0], 0] if $is_aq;
}
### allow for leading $foo type constructs
} elsif ($$str_ref =~ m{ \G \$ (\w+) \b }gcx) {
if ($self->{'V1DOLLAR'}) {
push @var, $1;
$is_namespace = 1 if $self->{'NAMESPACE'} && $self->{'NAMESPACE'}->{$1};
} else {
push @var, [$1, 0];
}
### allow for ${foo.bar} type constructs
} elsif ($$str_ref =~ m{ \G \$\{ }gcx) {
push @var, $self->parse_expr($str_ref);
$$str_ref =~ m{ \G \s* $QR_COMMENTS \} }gcxo
|| $self->throw('parse', 'Missing close "}" from "${"', undef, pos($$str_ref));
### looks like an array constructor
} elsif (! $is_aq && $$str_ref =~ m{ \G \[ }gcx) {
local $self->{'_operator_precedence'} = 0; # reset presedence
my $arrayref = [undef, '[]'];
while (defined(my $var = $self->parse_expr($str_ref))) {
push @$arrayref, $var;
$$str_ref =~ m{ \G \s* $QR_COMMENTS , }gcxo;
}
$$str_ref =~ m{ \G \s* $QR_COMMENTS \] }gcxo
|| $self->throw('parse.missing.square_bracket', "Missing close \]", undef, pos($$str_ref));
push @var, $arrayref;
### looks like a hash constructor
} elsif (! $is_aq && $$str_ref =~ m{ \G \{ }gcx) {
local $self->{'_operator_precedence'} = 0; # reset precedence
my $hashref = [undef, '{}'];
while (defined(my $key = $self->parse_expr($str_ref, {auto_quote => "(\\w+\\b) (?! \\.) \\s* $QR_COMMENTS"}))) {
$$str_ref =~ m{ \G \s* $QR_COMMENTS (?: = >? | [:,]) }gcxo;
my $val = $self->parse_expr($str_ref);
push @$hashref, $key, $val;
$$str_ref =~ m{ \G \s* $QR_COMMENTS , }gcxo;
}
$$str_ref =~ m{ \G \s* $QR_COMMENTS \} }gcxo
|| $self->throw('parse.missing.curly_bracket', "Missing close \}", undef, pos($$str_ref));
push @var, $hashref;
### looks like a paren grouper or a context specifier
} elsif (! $is_aq && $$str_ref =~ m{ \G ([\$\@]?) \( }gcx) {
local $self->{'_operator_precedence'} = 0; # reset precedence
my $ctx = $1;
my $var = $self->parse_expr($str_ref, {allow_parened_ops => 1});
$$str_ref =~ m{ \G \s* $QR_COMMENTS \) }gcxo
|| $self->throw('parse.missing.paren', "Missing close \) in group", undef, pos($$str_ref));
$self->throw('parse', 'Paren group cannot be followed by an open paren', undef, pos($$str_ref))
if $$str_ref =~ m{ \G \( }gcx;
$already_parsed_args = 1;
if (! ref $var) {
push @var, \$var, 0;
$is_literal = 1;
} elsif (! defined $var->[0]) {
push @var, $var, 0;
} else {
push @var, @$var;
}
if ($ctx) {
my $copy = [@var];
@var = ([undef, "$ctx()", $copy], 0);
}
### nothing to find - return failure
} else {
pos($$str_ref) = $mark if $is_aq || $has_prefix;
return;
}
# auto_quoted thing was too complicated
if ($is_aq) {
pos($$str_ref) = $mark;
return;
}
### looks for args for the initial
if ($already_parsed_args) {
# do nothing
} elsif ($$str_ref =~ m{ \G \( }gcxo) {
local $self->{'_operator_precedence'} = 0; # reset precedence
my $args = $self->parse_args($str_ref, {is_parened => 1});
$$str_ref =~ m{ \G \s* $QR_COMMENTS \) }gcxo
|| $self->throw('parse.missing.paren', "Missing close \) in args", undef, pos($$str_ref));
push @var, $args;
} else {
push @var, 0;
}
### allow for nested items
while ($$str_ref =~ m{ \G \s* $QR_COMMENTS ( \.(?!\.) | \|(?!\|) ) }gcx) {
if ($1 eq '|' && $self->{'V2PIPE'}) {
pos($$str_ref) -= 1;
last;
}
push(@var, $1) if ! $ARGS->{'no_dots'};
$$str_ref =~ m{ \G \s* $QR_COMMENTS }gcxo;
### allow for interpolated variables in the middle - one.$foo.two
if ($$str_ref =~ m{ \G \$ (\w+) \b }gcxo) {
push @var, $self->{'V1DOLLAR'} ? $1 : [$1, 0];
### or one.${foo.bar}.two
} elsif ($$str_ref =~ m{ \G \$\{ }gcx) {
push @var, $self->parse_expr($str_ref);
$$str_ref =~ m{ \G \s* $QR_COMMENTS \} }gcxo
|| $self->throw('parse', 'Missing close "}" from "${"', undef, pos($$str_ref));
### allow for names (foo.bar or foo.0 or foo.-1)
} elsif ($$str_ref =~ m{ \G (-? \w+) }gcx) {
push @var, $1;
} else {
$self->throw('parse', "Not sure how to continue parsing", undef, pos($$str_ref));
}
### looks for args for the nested item
if ($$str_ref =~ m{ \G \( }gcx) {
local $self->{'_operator_precedence'} = 0; # reset precedence
my $args = $self->parse_args($str_ref, {is_parened => 1});
$$str_ref =~ m{ \G \s* $QR_COMMENTS \) }gcxo
|| $self->throw('parse.missing.paren', "Missing close \) in args of nested item", undef, pos($$str_ref));
push @var, $args;
} else {
push @var, 0;
}
}
### flatten literals and constants as much as possible
my $var;
if ($is_literal) {
$var = ${ $var[0] };
if ($#var != 1) {
$var[0] = [undef, '~', $var];
$var = \@var;
}
} elsif ($is_namespace) {
my $name = $var[0];
local $self->{'_vars'}->{$name} = $self->{'NAMESPACE'}->{$name};
$var = $self->play_expr(\@var, {is_namespace_during_compile => 1});
} else {
$var = \@var;
}
### allow for all "operators"
if (! $self->{'_operator_precedence'}) {
my $tree;
my $found;
while (1) {
my $mark = pos $$str_ref;
$$str_ref =~ m{ \G \s* $QR_COMMENTS }gcxo;
if ($self->{'_end_tag'} && $$str_ref =~ m{ \G [+=~-]? $self->{'_end_tag'} }gcx) {
pos($$str_ref) = $mark;
last;
} elsif ($$str_ref !~ m{ \G ($QR_OP) }gcxo) {
pos($$str_ref) = $mark;
last;
}
if ($OP_ASSIGN->{$1} && ! $ARGS->{'allow_parened_ops'}) { # only allow assignment in parens
pos($$str_ref) = $mark;
last;
}
local $self->{'_operator_precedence'} = 1;
my $op = $1;
$op = 'eq' if $op eq '==' && (! defined($self->{'V2EQUALS'}) || $self->{'V2EQUALS'});
$op = 'ne' if $op eq '!=' && (! defined($self->{'V2EQUALS'}) || $self->{'V2EQUALS'});
### allow for postfix - doesn't check precedence - someday we might change - but not today (only affects post ++ and --)
if ($OP_POSTFIX->{$op}) {
$var = [[undef, $op, $var, 1], 0]; # cheat - give a "second value" to postfix ops
next;
### allow for prefix operator precedence
} elsif ($has_prefix && $OP->{$op}->[1] < $OP_PREFIX->{$has_prefix->[-1]}->[1]) {
if ($tree) {
if ($#$tree == 1) { # only one operator - keep simple things fast
$var = [[undef, $tree->[0], $var, $tree->[1]], 0];
} else {
unshift @$tree, $var;
$var = $self->apply_precedence($tree, $found, $str_ref);
}
undef $tree;
undef $found;
}
$var = [[undef, $has_prefix->[-1], $var ], 0];
pop @$has_prefix;
$has_prefix = undef if ! @$has_prefix;
}
### add the operator to the tree
my $var2 = $self->parse_expr($str_ref);
$self->throw('parse', 'Missing variable after "'.$op.'"', undef, pos($$str_ref)) if ! defined $var2;
push (@{ $tree ||= [] }, $op, $var2);
$found->{$OP->{$op}->[1]}->{$op} = 1; # found->{precedence}->{op}
}
### if we found operators - tree the nodes by operator precedence
if ($tree) {
if (@$tree == 2) { # only one operator - keep simple things fast
if ($OP->{$tree->[0]}->[0] eq 'assign' && $tree->[0] =~ /(.+)=/) {
$var = [[undef, '=', $var, [[undef, $1, $var, $tree->[1]], 0]], 0]; # "a += b" => "a = a + b"
} else {
$var = [[undef, $tree->[0], $var, $tree->[1]], 0];
}
} else {
unshift @$tree, $var;
$var = $self->apply_precedence($tree, $found, $str_ref);
}
}
}
### allow for prefix on non-chained variables
if ($has_prefix) {
$var = [[undef, $_, $var], 0] for reverse @$has_prefix;
}
return $var;
}
### this is used to put the parsed variables into the correct operations tree
sub apply_precedence {
my ($self, $tree, $found, $str_ref) = @_;
my @var;
my $trees;
### look at the operators we found in the order we found them
for my $prec (sort keys %$found) {
my $ops = $found->{$prec};
local $found->{$prec};
delete $found->{$prec};
### split the array on the current operators for this level
my @ops;
my @exprs;
for (my $i = 1; $i <= $#$tree; $i += 2) {
next if ! $ops->{ $tree->[$i] };
push @ops, $tree->[$i];
push @exprs, [splice @$tree, 0, $i, ()];
shift @$tree;
$i = -1;
}
next if ! @exprs; # this iteration didn't have the current operator
push @exprs, $tree if scalar @$tree; # add on any remaining items
### simplify sub expressions
for my $node (@exprs) {
if (@$node == 1) {
$node = $node->[0]; # single item - its not a tree
} elsif (@$node == 3) {
$node = [[undef, $node->[1], $node->[0], $node->[2]], 0]; # single operator - put it straight on
} else {
$node = $self->apply_precedence($node, $found, $str_ref); # more complicated - recurse
}
}
### assemble this current level
### some rules:
# 1) items at the same precedence level must all be either right or left or ternary associative
# 2) ternary items cannot share precedence with anybody else.
# 3) there really shouldn't be another operator at the same level as a postfix
my $type = $OP->{$ops[0]}->[0];
if ($type eq 'ternary') {
my $op = $OP->{$ops[0]}->[2]->[0]; # use the first op as what we are using
### return simple ternary
if (@exprs == 3) {
$self->throw('parse', "Ternary operator mismatch", undef, pos($$str_ref)) if $ops[0] ne $op;
$self->throw('parse', "Ternary operator mismatch", undef, pos($$str_ref)) if ! $ops[1] || $ops[1] eq $op;
return [[undef, $op, @exprs], 0];
}
### reorder complex ternary - rare case
while ($#ops >= 1) {
### if we look starting from the back - the first lead ternary op will always be next to its matching op
for (my $i = $#ops; $i >= 0; $i --) {
next if $OP->{$ops[$i]}->[2]->[1] eq $ops[$i];
my ($op, $op2) = splice @ops, $i, 2, (); # remove the pair of operators
my $node = [[undef, $op, @exprs[$i .. $i + 2]], 0];
splice @exprs, $i, 3, $node;
}
}
return $exprs[0]; # at this point the ternary has been reduced to a single operator
} elsif ($type eq 'right' || $type eq 'assign') {
my $val = $exprs[-1];
for (reverse (0 .. $#exprs - 1)) {
if ($type eq 'assign' && $ops[$_ - 1] =~ /(.+)=$/) {
$val = [[undef, '=', $exprs[$_], [[undef, $1, $exprs[$_], $val], 0]], 0];
} else {
$val = [[undef, $ops[$_ - 1], $exprs[$_], $val], 0];
}
}
return $val;
} else {
my $val = $exprs[0];
$val = [[undef, $ops[$_ - 1], $val, $exprs[$_]], 0] for (1 .. $#exprs);
return $val;
}
}
$self->throw('parse', "Couldn't apply precedence", undef, pos($$str_ref));
}
### look for arguments - both positional and named
sub parse_args {
my $self = shift;
my $str_ref = shift;
my $ARGS = shift || {};
my @args;
my @named;
my $name;
my $end = $self->{'_end_tag'} || '(?!)';
while (1) {
my $mark = pos $$str_ref;
### look to see if the next thing is a directive or a closing tag
if (! $ARGS->{'is_parened'}
&& ! $ARGS->{'require_arg'}
&& $$str_ref =~ m{ \G \s* $QR_COMMENTS $QR_DIRECTIVE (?: \s+ | (?: \s* $QR_COMMENTS (?: ;|[+=~-]?$end))) }gcxo
&& ((pos($$str_ref) = $mark) || 1) # always revert
&& $DIRECTIVES->{$self->{'ANYCASE'} ? uc($1) : $1} # looks like a directive - we are done
) {
last;
}
if ($$str_ref =~ m{ \G [+=~-]? $end }gcx) {
pos($$str_ref) = $mark;
last;
}
### find the initial arg
my $name;
if ($ARGS->{'allow_bare_filenames'}) {
$name = $self->parse_expr($str_ref, {auto_quote => "
($QR_FILENAME # file name
| $QR_BLOCK # or block
(?= [+=~-]? $end # an end tag
| \\s*[+,;] # followed by explicit + , or ;
| \\s+ (?! [\\s=]) # or space not before an =
) \\s* $QR_COMMENTS"});
# filenames can be separated with a "+" - why a "+" ?
if ($$str_ref =~ m{ \G \+ (?! \s* $QR_COMMENTS [+=~-]? $end) }gcxo) {
push @args, $name;
$ARGS->{'require_arg'} = 1;
next;
}
}
if (! defined $name) {
$name = $self->parse_expr($str_ref);
if (! defined $name) {
if ($ARGS->{'require_arg'} && ! @args && ! $ARGS->{'positional_only'} && ! @named) {
$self->throw('parse', 'Argument required', undef, pos($$str_ref));
} else {
last;
}
}
}
$$str_ref =~ m{ \G \s* $QR_COMMENTS }gcxo;
### see if it is named or positional
if ($$str_ref =~ m{ \G \s* $QR_COMMENTS = >? }gcxo) {
$self->throw('parse', 'Named arguments not allowed', undef, $mark) if $ARGS->{'positional_only'};
my $val = $self->parse_expr($str_ref);
$name = $name->[0] if ref($name) && @$name == 2 && ! $name->[1]; # strip a level of indirection on named arguments
push @named, $name, $val;
} else {
push @args, $name;
}
### look for trailing comma
$ARGS->{'require_arg'} = ($$str_ref =~ m{ \G \s* $QR_COMMENTS , }gcxo) || 0;
}
### allow for named arguments to be added at the front (if asked)
if ($ARGS->{'named_at_front'}) {
unshift @args, [[undef, '{}', @named], 0];
} elsif (scalar @named) { # only add at end - if there are some
push @args, [[undef, '{}', @named], 0]
}
return \@args;
}
###----------------------------------------------------------------###
sub parse_BLOCK {
my ($self, $str_ref, $node) = @_;
my $end = $self->{'_end_tag'} || '(?!)';
my $block_name = $self->parse_expr($str_ref, {auto_quote => "
($QR_FILENAME # file name
| $QR_BLOCK # or block
(?= [+=~-]? $end # an end tag
| \\s*[+,;] # followed by explicit + , or ;
| \\s+ (?! [\\s=]) # or space not before an =
) \\s* $QR_COMMENTS"});
return '' if ! defined $block_name;
my $prepend = join "/", map {$_->[3]} grep {ref($_) && $_->[0] eq 'BLOCK'} @{ $self->{'_state'} || {} };
return $prepend ? "$prepend/$block_name" : $block_name;
}
sub parse_CALL { $DIRECTIVES->{'GET'}->[0]->(@_) }
sub parse_CASE {
my ($self, $str_ref) = @_;
return if $$str_ref =~ m{ \G DEFAULT \s* }gcx;
return $self->parse_expr($str_ref);
}
sub parse_CATCH {
my ($self, $str_ref) = @_;
return $self->parse_expr($str_ref, {auto_quote => "(\\w+\\b (?: \\.\\w+\\b)*) $QR_AQ_SPACE \\s* $QR_COMMENTS"});
}
sub parse_CONFIG {
my ($self, $str_ref) = @_;
my %ctime = map {$_ => 1} @Template::Alloy::CONFIG_COMPILETIME;
my %rtime = map {$_ => 1} @Template::Alloy::CONFIG_RUNTIME;
my $mark = pos($$str_ref);
my $config = $self->parse_args($str_ref, {named_at_front => 1, is_parened => 1});
my $ref = $config->[0]->[0];
for (my $i = 2; $i < @$ref; $i += 2) {
my $key = $ref->[$i] = uc $ref->[$i];
my $val = $ref->[$i + 1];
if ($ctime{$key}) {
$self->{$key} = $self->play_expr($val);
if ($key eq 'INTERPOLATE') {
$self->{'_start_tag'} = (! $self->{'INTERPOLATE'}) ? $self->{'START_TAG'} : qr{(?: $self->{'START_TAG'} | (\$))}sx;
}
} elsif (! $rtime{$key}) {
$self->throw('parse', "Unknown CONFIG option \"$key\"", undef, pos($$str_ref));
}
}
for (my $i = 1; $i < @$config; $i++) {
my $key = $config->[$i] = uc $config->[$i]->[0];
if ($ctime{$key}) {
$config->[$i] = "CONFIG $key = ".(defined($self->{$key}) ? $self->{$key} : 'undef');
} elsif (! $rtime{$key}) {
$self->throw('parse', "Unknown CONFIG option \"$key\"", undef, pos($$str_ref));
}
}
return $config;
}
sub parse_DEBUG {
my ($self, $str_ref) = @_;
$$str_ref =~ m{ \G ([Oo][Nn] | [Oo][Ff][Ff] | [Ff][Oo][Rr][Mm][Aa][Tt]) \s* }gcx
|| $self->throw('parse', "Unknown DEBUG option", undef, pos($$str_ref));
my $ret = [lc($1)];
if ($ret->[0] eq 'format') {
$$str_ref =~ m{ \G ([\"\']) (|.*?[^\\]) \1 \s* }gcxs
|| $self->throw('parse', "Missing format string", undef, pos($$str_ref));
$ret->[1] = $2;
}
return $ret;
}
sub parse_DEFAULT { $DIRECTIVES->{'SET'}->[0]->(@_) }
sub parse_DUMP {
my ($self, $str_ref) = @_;
return $self->parse_args($str_ref, {named_at_front => 1});
}
sub parse_EVAL {
my ($self, $str_ref) = @_;
return $self->parse_args($str_ref, {named_at_front => 1});
}
sub parse_FILTER {
my ($self, $str_ref) = @_;
my $name = '';
if ($$str_ref =~ m{ \G ([^\W\d]\w*) \s* = \s* }gcx) {
$name = $1;
}
my $filter = $self->parse_expr($str_ref);
$filter = '' if ! defined $filter;
return [$name, $filter];
}
sub parse_FOR {
my ($self, $str_ref) = @_;
my $items = $self->parse_expr($str_ref);
my $var;
if ($$str_ref =~ m{ \G \s* $QR_COMMENTS (= | [Ii][Nn]\b) \s* }gcxo) {
$var = [@$items];
$items = $self->parse_expr($str_ref);
}
return [$var, $items];
}
sub parse_GET {
my ($self, $str_ref) = @_;
my $ref = $self->parse_expr($str_ref);
$self->throw('parse', "Missing variable name", undef, pos($$str_ref)) if ! defined $ref;
if ($self->{'AUTO_FILTER'}) {
$ref = [[undef, '~', $ref], 0] if ! ref $ref;
push @$ref, '|', $self->{'AUTO_FILTER'}, 0 if @$ref < 3 || $ref->[-3] ne '|';
}
return $ref;
}
sub parse_IF {
my ($self, $str_ref) = @_;
return $self->parse_expr($str_ref);
}
sub parse_INCLUDE { $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
sub parse_INSERT { $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
sub parse_LOOP {
my ($self, $str_ref, $node) = @_;
return $self->parse_expr($str_ref)
|| $self->throw('parse', 'Missing variable on LOOP directive', undef, pos($$str_ref));
}
sub parse_MACRO {
my ($self, $str_ref, $node) = @_;
my $name = $self->parse_expr($str_ref, {auto_quote => "(\\w+\\b) (?! \\.)"});
$self->throw('parse', "Missing macro name", undef, pos($$str_ref)) if ! defined $name;
if (! ref $name) {
$name = [ $name, 0 ];
}
my $args;
if ($$str_ref =~ m{ \G \( \s* }gcx) {
$args = $self->parse_args($str_ref, {positional_only => 1});
$$str_ref =~ m{ \G \) \s* }gcx || $self->throw('parse.missing', "Missing close ')'", undef, pos($$str_ref));
} elsif ($self->{'V1DOLLAR'}) { # allow for Velocity style macro args (no parens - but dollars are fine)
while ($$str_ref =~ m{ \G (\s+ \$) }gcx) {
my $lead = $1;
my $arg = $self->parse_expr($str_ref);
if (! defined $arg) {
pos($$str_ref) -= length($lead);
last;
}
push @$args, $arg;
}
}
$node->[6] = 1; # set a flag to keep parsing
return [$name, $args];
}
sub parse_META {
my ($self, $str_ref) = @_;
my $args = $self->parse_args($str_ref, {named_at_front => 1});
my $hash;
return [%$hash] if ($hash = $self->play_expr($args->[0])) && UNIVERSAL::isa($hash, 'HASH');
return undef;
}
sub parse_PROCESS {
my ($self, $str_ref) = @_;
return $self->parse_args($str_ref, {
named_at_front => 1,
allow_bare_filenames => 1,
require_arg => 1,
});
}
sub parse_RETURN {
my ($self, $str_ref) = @_;
my $ref = $self->parse_expr($str_ref); # optional return value
return $ref;
}
sub parse_SET {
my ($self, $str_ref, $node, $initial_op, $initial_var) = @_;
my @SET;
my $func;
if ($initial_op) {
if ($initial_op eq '='
&& $$str_ref =~ m{ \G \s* $QR_COMMENTS $QR_DIRECTIVE }gcx # find a word
&& ((pos($$str_ref) -= length($1)) || 1) # always revert
&& $DIRECTIVES->{$self->{'ANYCASE'} ? uc $1 : $1}) { # make sure its a directive - if so set up capturing
$node->[6] = 1; # set a flag to keep parsing
my $val = $node->[4] ||= []; # setup storage
return [[$initial_op, $initial_var, $val]];
} else { # get a normal variable
my $val = $self->parse_expr($str_ref);
if ($initial_op =~ /(.+)=$/) {
$initial_op = '=';
$val = [[undef, $1, $initial_var, $val], 0];
}
return [[$initial_op, $initial_var, $val]];
}
}
while (1) {
my $set = $self->parse_expr($str_ref);
last if ! defined $set;
if ($$str_ref =~ m{ \G \s* $QR_COMMENTS ($QR_OP_ASSIGN) >? }gcx) {
my $op = $1;
if ($op eq '='
&& $$str_ref =~ m{ \G \s* $QR_COMMENTS $QR_DIRECTIVE }gcx # find a word
&& ((pos($$str_ref) -= length($1)) || 1) # always revert
&& $DIRECTIVES->{$self->{'ANYCASE'} ? uc $1 : $1}) { # make sure its a directive - if so set up capturing
$node->[6] = 1; # set a flag to keep parsing
my $val = $node->[4] ||= []; # setup storage
if ($op =~ /(.+)=$/) {
$op = '=';
$val = [[undef, $1, $set, $val], 0];
}
push @SET, [$op, $set, $val];
last;
} else { # get a normal variable
push @SET, [$op, $set, $self->parse_expr($str_ref)];
}
} else {
push @SET, ['=', $set, undef];
}
}
return \@SET;
}
sub parse_SWITCH { $DIRECTIVES->{'GET'}->[0]->(@_) }
sub parse_TAGS {
my ($self, $str_ref, $node) = @_;
my ($start, $end);
if ($$str_ref =~ m{ \G (\w+) }gcxs) {
my $ref = $TAGS->{lc $1} || $self->throw('parse', "Invalid TAGS name \"$1\"", undef, pos($$str_ref));
($start, $end) = @$ref;
} else {
local $self->{'_operator_precedence'} = 1; # prevent operator matching
$start = $$str_ref =~ m{ \G (?= \s* $QR_COMMENTS [\'\"\/]) }gcx
? $self->parse_expr($str_ref)
: $self->parse_expr($str_ref, {auto_quote => "(\\S+) \\s+ $QR_COMMENTS"})
|| $self->throw('parse', "Invalid opening tag in TAGS", undef, pos($$str_ref));
$end = $$str_ref =~ m{ \G (?= \s* $QR_COMMENTS [\'\"\/]) }gcx
? $self->parse_expr($str_ref)
: $self->parse_expr($str_ref, {auto_quote => "(\\S+) \\s* $QR_COMMENTS"})
|| $self->throw('parse', "Invalid closing tag in TAGS", undef, pos($$str_ref));
for my $tag ($start, $end) {
$tag = $self->play_expr($tag);
$tag = quotemeta($tag) if ! ref $tag;
}
}
return [$start, $end];
}
sub parse_THROW {
my ($self, $str_ref, $node) = @_;
my $name = $self->parse_expr($str_ref, {auto_quote => "(\\w+\\b (?: \\.\\w+\\b)*) $QR_AQ_SPACE \\s* $QR_COMMENTS"});
$self->throw('parse.missing', "Missing name in THROW", $node, pos($$str_ref)) if ! $name;
my $args = $self->parse_args($str_ref, {named_at_front => 1});
return [$name, $args];
}
sub parse_UNLESS {
my $ref = $DIRECTIVES->{'IF'}->[0]->(@_);
return [[undef, '!', $ref], 0];
}
sub parse_USE {
my ($self, $str_ref) = @_;
my $var;
my $mark = pos $$str_ref;
if (defined(my $_var = $self->parse_expr($str_ref, {auto_quote => "(\\w+\\b) (?! \\.) \\s* $QR_COMMENTS"}))
&& ($$str_ref =~ m{ \G = >? \s* $QR_COMMENTS }gcxo # make sure there is assignment
|| ((pos($$str_ref) = $mark) && 0)) # otherwise we need to rollback
) {
$var = $_var;
}
my $module = $self->parse_expr($str_ref, {auto_quote => "(\\w+\\b (?: (?:\\.|::) \\w+\\b)*) (?! \\.) \\s* $QR_COMMENTS"});
$self->throw('parse', "Missing plugin name while parsing $$str_ref", undef, pos($$str_ref)) if ! defined $module;
$module =~ s/\./::/g;
my $args;
my $open = $$str_ref =~ m{ \G \( \s* $QR_COMMENTS }gcxo;
$args = $self->parse_args($str_ref, {is_parened => $open, named_at_front => 1});
if ($open) {
$$str_ref =~ m{ \G \) \s* $QR_COMMENTS }gcxo || $self->throw('parse.missing', "Missing close ')'", undef, pos($$str_ref));
}
return [$var, $module, $args];
}
sub parse_VIEW {
my ($self, $str_ref) = @_;
my $ref = $self->parse_args($str_ref, {
named_at_front => 1,
require_arg => 1,
});
return $ref;
}
sub parse_WHILE { $DIRECTIVES->{'IF'}->[0]->(@_) }
sub parse_WRAPPER { $DIRECTIVES->{'PROCESS'}->[0]->(@_) }
###----------------------------------------------------------------###
sub dump_parse_tree {
my $self = shift;
$self = $self->new if ! ref $self;
my $str = shift;
my $ref = ref($str) ? $str : \$str;
my $sub;
my $nest;
$sub = sub {
my ($tree, $indent) = @_;
my $out = "[\n";
foreach my $node (@$tree) {
if (! ref($node) || (! $node->[4] && ! $node->[5])) {
$out .= "$indent ".$self->ast_string($node).",\n";
next;
}
$out .= "$indent " . $nest->($node, "$indent ");
}
$out .= "$indent]";
};
$nest = sub {
my ($node, $indent) = @_;
my $out = $self->ast_string([@{$node}[0..3]]);
chop $out;
if ($node->[4]) {
$out .= ", ";
$out .= $sub->($node->[4], "$indent");
}
if ($node->[5]) {
$out .= ", ". $nest->($node->[5], "$indent") . $indent;
} elsif (@$node >= 6) {
$out .= ", ". $self->ast_string($node->[5]);
}
if (@$node >= 7) { $out.= ", ". $self->ast_string($node->[6]) };
$out .= "],\n";
return $out;
};
return $sub->($self->parse_tree($ref), '') ."\n";
}
sub dump_parse_expr {
my $self = shift;
$self = $self->new if ! ref $self;
my $str = shift;
my $ref = ref($str) ? $str : \$str;
return $self->ast_string($self->parse_expr($ref));
}
###----------------------------------------------------------------###
1;
__END__
=head1 DESCRIPTION
The Template::Alloy::Parse role is reponsible for storing the majority
of directive parsing code, as well as for delegating to the TT, HTE,
Tmpl, and Velocity roles for finding variables and directives.
=head1 ROLE METHODS
=over 4
=item parse_tree
Used by load_tree. This is the main grammar engine of the program. It
delegates to the syntax found in $self->{'SYNTAX'} (defaults to 'alloy')
and calls the function found in the $SYNTAX hashref. The majority
of these syntaxes use methods found in the $DIRECTIVES hashref
to parse different DIRECTIVE types for each particular syntax.
A template that looked like the following:
Foo
[%- GET foo -%]
[%- GET bar -%]
Bar
would parse to the following AST:
[
'Foo',
['GET', 6, 15, ['foo', 0]],
['GET', 22, 31, ['bar', 0]],
'Bar',
]
The "GET" words represent the directive used. The 6, 15 represent the
beginning and ending characters of the directive in the document. The
remaining items are the variables necessary for running the particular
directive.
=item parse_expr
Used to parse a variable, an expression, a literal string, or a
number. It returns a parsed variable tree. Samples of parsed
variables can be found in the VARIABLE PARSE TREE section.
my $str = "1 + 2 * 3";
my $ast = $self->parse_expr(\$str);
# $ast looks like [[undef, '+', 1, [[undef, '*', 2, 3], 0]], 0]
=item C<parse_args>
Allow for the multitudinous ways that TT parses arguments. This
allows for positional as well as named arguments. Named arguments can
be separated with a "=" or "=>", and positional arguments should be
separated by " " or ",". This only returns an array of parsed
variables. To get the actual values, you must call play_expr on each
value.
=item C<dump_parse_tree>
This method allows for returning a string of perl code representing
the AST of the parsed tree.
It is mainly used for testing.
=item C<dump_parse_expr>
This method allows for returning a Data::Dumper dump of a parsed
variable. It is mainly used for testing.
=item C<parse_*>
Methods by these names are used by parse_tree to parse the template.
These are the grammar. They are used by all of the various template
syntaxes Unless otherwise mentioned, these methods are not exposed via
the role.
=back
=head1 VARIABLE PARSE TREE
Template::Alloy parses templates into an tree of operations (an AST
or abstract syntax tree). Even variable access is parsed into a tree.
This is done in a manner somewhat similar to the way that TT operates
except that nested variables such as foo.bar|baz contain the '.' or
'|' in between each name level. Operators are parsed and stored as
part of the variable (it may be more appropriate to say we are parsing
a term or an expression).
The following table shows a variable or expression and the corresponding parsed tree
(this is what the parse_expr method would return).
one [ 'one', 0 ]
one() [ 'one', [] ]
one.two [ 'one', 0, '.', 'two', 0 ]
one|two [ 'one', 0, '|', 'two', 0 ]
one.$two [ 'one', 0, '.', ['two', 0 ], 0 ]
one(two) [ 'one', [ ['two', 0] ] ]
one.${two().three} [ 'one', 0, '.', ['two', [], '.', 'three', 0], 0]
2.34 2.34
"one" "one"
1 + 2 [ [ undef, '+', 1, 2 ], 0]
a + b [ [ undef, '+', ['a', 0], ['b', 0] ], 0 ]
"one"|length [ [ undef, '~', "one" ], 0, '|', 'length', 0 ]
"one $a two" [ [ undef, '~', 'one ', ['a', 0], ' two' ], 0 ]
[0, 1, 2] [ [ undef, '[]', 0, 1, 2 ], 0 ]
[0, 1, 2].size [ [ undef, '[]', 0, 1, 2 ], 0, '.', 'size', 0 ]
['a', a, $a ] [ [ undef, '[]', 'a', ['a', 0], [['a', 0], 0] ], 0]
{a => 'b'} [ [ undef, '{}', 'a', 'b' ], 0 ]
{a => 'b'}.size [ [ undef, '{}', 'a', 'b' ], 0, '.', 'size', 0 ]
{$a => b} [ [ undef, '{}', ['a', 0], ['b', 0] ], 0 ]
a * (b + c) [ [ undef, '*', ['a', 0], [ [undef, '+', ['b', 0], ['c', 0]], 0 ]], 0 ]
(a + b) [ [ undef, '+', ['a', 0], ['b', 0] ]], 0 ]
(a + b) * c [ [ undef, '*', [ [undef, '+', ['a', 0], ['b', 0] ], 0 ], ['c', 0] ], 0 ]
a ? b : c [ [ undef, '?', ['a', 0], ['b', 0], ['c', 0] ], 0 ]
a || b || c [ [ undef, '||', ['a', 0], [ [undef, '||', ['b', 0], ['c', 0] ], 0 ] ], 0 ]
! a [ [ undef, '!', ['a', 0] ], 0 ]
Some notes on the parsing.
Operators are parsed as part of the variable and become part of the variable tree.
Operators are stored in the variable tree using an operator identity array which
contains undef as the first value, the operator, and the operator arguments. This
allows for quickly descending the parsed variable tree and determining that the next
node is an operator.
Parenthesis () can be used at any point in an expression to disambiguate precedence.
"Variables" that appear to be literal strings or literal numbers
are returned as the literal (no operator tree).
The following perl can be typed at the command line to view the parsed variable tree:
perl -e 'use Template::Alloy; print Template::Alloy->dump_parse_expr("foo.bar + 2")."\n"'
Also the following can be included in a template to view the output in a template:
[% USE cet = Template::Alloy %]
[%~ cet.dump_parse_expr('foo.bar + 2').replace('\s+', ' ') %]
=head1 AUTHOR
Paul Seamons <paul@seamons.com>
=head1 LICENSE
This module may be distributed under the same terms as Perl itself.
=cut
|