blib/lib/Template/Parser.pm untested

filter: Statementstmt 0.0% 0 / 369 Branchbran 0.0% 0 / 164 Conditioncond 0.0% 0 / 102 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 30 Podpod 0.0% 0 / 19 totaltotal 0.0% 0 / 684 CC 82 SCAR 56.3
CC
82
Cov
0%
split_text
650.0
_parse
506.0
tokenise_directive
210.0
CRAP 279.1
1 #============================================================= -*-Perl-*-
2 #
3 # Template::Parser
4 #
5 # DESCRIPTION
6 # This module implements a LALR(1) parser and associated support
7 # methods to parse template documents into the appropriate "compiled"
8 # format. Much of the parser DFA code (see _parse() method) is based
9 # on Francois Desarmenien's Parse::Yapp module. Kudos to him.
10 #
11 # AUTHOR
12 # Andy Wardley <abw@wardley.org>
13 #
14 # COPYRIGHT
15 # Copyright (C) 1996-2022 Andy Wardley. All Rights Reserved.
16 #
17 # This module is free software; you can redistribute it and/or
18 # modify it under the same terms as Perl itself.
19 #
20 # The following copyright notice appears in the Parse::Yapp
21 # documentation.
22 #
23 # The Parse::Yapp module and its related modules and shell
24 # scripts are copyright (c) 1998 Francois Desarmenien,
25 # France. All rights reserved.
26 #
27 # You may use and distribute them under the terms of either
28 # the GNU General Public License or the Artistic License, as
29 # specified in the Perl README file.
30 #
31 #============================================================================
32  
33 package Template::Parser;
34  
35 use strict;
36 use warnings;
37 use base 'Template::Base';
38  
39 use Template::Constants qw( :status :chomp );
40 use Template::Directive;
41 use Template::Grammar;
42  
43 # parser state constants
44 use constant CONTINUE => 0;
45 use constant ACCEPT => 1;
46 use constant ERROR => 2;
47 use constant ABORT => 3;
48  
49 our $VERSION = '3.105';
50 our $DEBUG = 0 unless defined $DEBUG;
51 our $ERROR = '';
52  
53 # The ANYCASE option can cause conflicts when reserved words are used as
54 # variable names, hash keys, template names, plugin names, etc. The
55 #
56 # $ANYCASE_BEFORE regex identifies where such a word precedes an assignment,
57 # either as a variable (C<wrapper = 'html'>) or hash key (C<{ wrapper => 'html' }).
58 # In that case it is treated as a simple words rather than being the lower case
59 # equivalent of the upper case keyword (e.g. WRAPPER).
60 #
61 # $ANYCASE_AFTER is used to identify when such a word follows a symbols that
62 # suggests it can't be a keyword, e.g. after BLOCK INCLUDE WRAPPER, USE, etc.
63 our $ANYCASE_BEFORE = qr/\G((?=\s*[=\.]))/;
64 our $ANYCASE_AFTER = {
65 map { $_ => 1 }
66 qw(
67 GET SET CALL DEFAULT INSERT INCLUDE PROCESS WRAPPER BLOCK USE
68 PLUGIN FILTER MACRO IN TO STEP AND OR NOT DIV MOD DOT
69 IF UNLESS ELSIF FOR WHILE SWITCH CASE META THROW CATCH VIEW
70 CMPOP BINOP COMMA
71 ),
72 '(', '[', '{'
73 # not sure about ASSIGN as it breaks C<header_html = include header>
74 };
75  
76  
77 #========================================================================
78 # -- COMMON TAG STYLES --
79 #========================================================================
80  
81 our $TAG_STYLE = {
82 'outline' => [ '\[%', '%\]', '%%' ], # NEW! Outline tag
83 'default' => [ '\[%', '%\]' ],
84 'template1' => [ '[\[%]%', '%[\]%]' ],
85 'metatext' => [ '%%', '%%' ],
86 'html' => [ '<!--', '-->' ],
87 'mason' => [ '<%', '>' ],
88 'asp' => [ '<%', '%>' ],
89 'php' => [ '<\?', '\?>' ],
90 'star' => [ '\[\*', '\*\]' ],
91 };
92 $TAG_STYLE->{ template } = $TAG_STYLE->{ tt2 } = $TAG_STYLE->{ default };
93  
94  
95 our $DEFAULT_STYLE = {
96 START_TAG => $TAG_STYLE->{ default }->[0],
97 END_TAG => $TAG_STYLE->{ default }->[1],
98 OUTLINE_TAG => $TAG_STYLE->{ default }->[2],
99 # TAG_STYLE => 'default',
100 ANYCASE => 0,
101 INTERPOLATE => 0,
102 PRE_CHOMP => 0,
103 POST_CHOMP => 0,
104 V1DOLLAR => 0,
105 EVAL_PERL => 0,
106 };
107  
108 our $QUOTED_ESCAPES = {
109 n => "\n",
110 r => "\r",
111 t => "\t",
112 };
113  
114 # note that '-' must come first so Perl doesn't think it denotes a range
115 our $CHOMP_FLAGS = qr/[-=~+]/;
116  
117  
118  
119 #========================================================================
120 # ----- PUBLIC METHODS -----
121 #========================================================================
122  
123 #------------------------------------------------------------------------
124 # new(\%config)
125 #
126 # Constructor method.
127 #------------------------------------------------------------------------
128  
129 sub new {
130 my $class = shift;
131 my $config = $_[0] && ref($_[0]) eq 'HASH' ? shift(@_) : { @_ };
132 my ($tagstyle, $debug, $start, $end, $defaults, $grammar, $hash, $key, $udef);
133  
134 my $self = bless {
135 START_TAG => undef,
136 END_TAG => undef,
137 OUTLINE_TAG => undef,
138 TAG_STYLE => 'default',
139 ANYCASE => 0,
140 INTERPOLATE => 0,
141 PRE_CHOMP => 0,
142 POST_CHOMP => 0,
143 V1DOLLAR => 0,
144 EVAL_PERL => 0,
145 FILE_INFO => 1,
146 GRAMMAR => undef,
147 _ERROR => '',
148 IN_BLOCK => [ ],
149 TRACE_VARS => $config->{ TRACE_VARS },
150 FACTORY => $config->{ FACTORY } || 'Template::Directive',
151 }, $class;
152  
153 # update self with any relevant keys in config
154 foreach $key (keys %$self) {
155 $self->{ $key } = $config->{ $key } if defined $config->{ $key };
156 }
157 $self->{ FILEINFO } = [ ];
158  
159 # DEBUG config item can be a bitmask
160 if (defined ($debug = $config->{ DEBUG })) {
161 $self->{ DEBUG } = $debug & ( Template::Constants::DEBUG_PARSER
162 | Template::Constants::DEBUG_FLAGS );
163 $self->{ DEBUG_DIRS } = $debug & Template::Constants::DEBUG_DIRS;
164 }
165 # package variable can be set to 1 to support previous behaviour
166 elsif ($DEBUG == 1) {
167 $self->{ DEBUG } = Template::Constants::DEBUG_PARSER;
168 $self->{ DEBUG_DIRS } = 0;
169 }
170 # otherwise let $DEBUG be a bitmask
171 else {
172 $self->{ DEBUG } = $DEBUG & ( Template::Constants::DEBUG_PARSER
173 | Template::Constants::DEBUG_FLAGS );
174 $self->{ DEBUG_DIRS } = $DEBUG & Template::Constants::DEBUG_DIRS;
175 }
176  
177 $grammar = $self->{ GRAMMAR } ||= do {
178 require Template::Grammar;
179 Template::Grammar->new();
180 };
181  
182 # instantiate a FACTORY object
183 unless (ref $self->{ FACTORY }) {
184 my $fclass = $self->{ FACTORY };
185 $self->{ FACTORY } = $self->{ FACTORY }->new(
186 NAMESPACE => $config->{ NAMESPACE }
187 )
188 || return $class->error($self->{ FACTORY }->error());
189 }
190  
191 # load grammar rules, states and lex table
192 @$self{ qw( LEXTABLE STATES RULES ) }
193 = @$grammar{ qw( LEXTABLE STATES RULES ) };
194  
195 $self->new_style($config)
196 || return $class->error($self->error());
197  
198 return $self;
199 }
200  
201 #-----------------------------------------------------------------------
202 # These methods are used to track nested IF and WHILE blocks. Each
203 # generated if/while block is given a label indicating the directive
204 # type and nesting depth, e.g. FOR0, WHILE1, FOR2, WHILE3, etc. The
205 # NEXT and LAST directives use the innermost label, e.g. last WHILE3;
206 #-----------------------------------------------------------------------
207  
208 sub enter_block {
209 my ($self, $name) = @_;
210 my $blocks = $self->{ IN_BLOCK };
211 push(@{ $self->{ IN_BLOCK } }, $name);
212 }
213  
214 sub leave_block {
215 my $self = shift;
216 my $label = $self->block_label;
217 pop(@{ $self->{ IN_BLOCK } });
218 return $label;
219 }
220  
221 sub in_block {
222 my ($self, $name) = @_;
223 my $blocks = $self->{ IN_BLOCK };
224 return @$blocks && $blocks->[-1] eq $name;
225 }
226  
227 sub block_label {
228 my ($self, $prefix, $suffix) = @_;
229 my $blocks = $self->{ IN_BLOCK };
230 my $name = @$blocks
231 ? $blocks->[-1] . scalar @$blocks
232 : undef;
233 return join('', grep { defined $_ } $prefix, $name, $suffix);
234 }
235  
236  
237  
238 #------------------------------------------------------------------------
239 # new_style(\%config)
240 #
241 # Install a new (stacked) parser style. This feature is currently
242 # experimental but should mimic the previous behaviour with regard to
243 # TAG_STYLE, START_TAG, END_TAG, etc.
244 #------------------------------------------------------------------------
245  
246 sub new_style {
247 my ($self, $config) = @_;
248 my $styles = $self->{ STYLE } ||= [ ];
249 my ($tagstyle, $tags, $start, $end, $out, $key);
250  
251 # clone new style from previous or default style
252 my $style = { %{ $styles->[-1] || $DEFAULT_STYLE } };
253  
254 # expand START_TAG and END_TAG from specified TAG_STYLE
255 if ($tagstyle = $config->{ TAG_STYLE }) {
256 return $self->error("Invalid tag style: $tagstyle")
257 unless defined ($tags = $TAG_STYLE->{ $tagstyle });
258 ($start, $end, $out) = @$tags;
259 $config->{ START_TAG } ||= $start;
260 $config->{ END_TAG } ||= $end;
261 $config->{ OUTLINE_TAG } ||= $out;
262 }
263  
264 foreach $key (keys %$DEFAULT_STYLE) {
265 $style->{ $key } = $config->{ $key } if defined $config->{ $key };
266 }
267  
268 $start = $style->{ START_TAG };
269 $end = $style->{ END_TAG };
270 $out = $style->{ OUTLINE_TAG };
271 $style->{ TEXT_SPLIT } = $self->text_splitter($start, $end, $out);
272  
273 push(@$styles, $style);
274 return $style;
275 }
276  
277 sub text_splitter {
278 my ($self, $start, $end, $out) = @_;
279  
280 if (defined $out) {
281 return qr/
282 \A(.*?) # $1 - start of line up to directive
283 (?:
284 (?:
285 ^$out # outline tag at start of line
286 (.*? # $2 - content of that line
287 (?:\n|$) # end of that line or file
288 )
289 )
290 |
291 (?:
292 $start # start of tag
293 (.*?) # $3 - tag contents
294 $end # end of tag
295 )
296 )
297 /msx;
298 }
299 else {
300 return qr/
301 ^(.*?) # $1 - start of line up to directive
302 (?:
303 $start # start of tag
304 (.*?) # $2 - tag contents
305 $end # end of tag
306 )
307 /sx;
308 }
309 }
310  
311 #------------------------------------------------------------------------
312 # old_style()
313 #
314 # Pop the current parser style and revert to the previous one. See
315 # new_style(). ** experimental **
316 #------------------------------------------------------------------------
317  
318 sub old_style {
319 my $self = shift;
320 my $styles = $self->{ STYLE };
321 return $self->error('only 1 parser style remaining')
322 unless (@$styles > 1);
323 pop @$styles;
324 return $styles->[-1];
325 }
326  
327  
328 #------------------------------------------------------------------------
329 # parse($text, $data)
330 #
331 # Parses the text string, $text and returns a hash array representing
332 # the compiled template block(s) as Perl code, in the format expected
333 # by Template::Document.
334 #------------------------------------------------------------------------
335  
336 sub parse {
337 my ($self, $text, $info) = @_;
338 my ($tokens, $block);
339  
340 $info->{ DEBUG } //= $self->{ DEBUG_DIRS };
341  
342 # print "info: { ", join(', ', map { "$_ => $info->{ $_ }" } keys %$info), " }\n";
343  
344 # store for blocks defined in the template (see define_block())
345 my $defblock = $self->{ DEFBLOCK } = { };
346 my $metadata = $self->{ METADATA } = [ ];
347 my $variables = $self->{ VARIABLES } = { };
348 $self->{ DEFBLOCKS } = [ ];
349  
350 $self->{ _ERROR } = '';
351  
352 # split file into TEXT/DIRECTIVE chunks
353 $tokens = $self->split_text($text)
354 || return undef; ## RETURN ##
355  
356 push(@{ $self->{ FILEINFO } }, $info);
357  
358 # parse chunks
359 $block = $self->_parse($tokens, $info);
360  
361 pop(@{ $self->{ FILEINFO } });
362  
363 return undef unless $block; ## RETURN ##
364  
365 $self->debug("compiled main template document block:\n$block")
366 if $self->{ DEBUG } & Template::Constants::DEBUG_PARSER;
367  
368 return {
369 BLOCK => $block,
370 DEFBLOCKS => $defblock,
371 VARIABLES => $variables,
372 METADATA => { @$metadata },
373 };
374 }
375  
376  
377  
378 #------------------------------------------------------------------------
379 # split_text($text)
380 #
381 # Split input template text into directives and raw text chunks.
382 #------------------------------------------------------------------------
383  
384 sub split_text {
385 my ($self, $text) = @_;
386 my ($pre, $dir, $prelines, $dirlines, $postlines, $chomp, $tags, @tags);
387 my $style = $self->{ STYLE }->[-1];
388 my ($start, $end, $out, $prechomp, $postchomp, $interp ) =
389 @$style{ qw( START_TAG END_TAG OUTLINE_TAG PRE_CHOMP POST_CHOMP INTERPOLATE ) };
390 my $tags_dir = $self->{ANYCASE} ? qr<TAGS>i : qr<TAGS>;
391 my $split = $style->{ TEXT_SPLIT };
392 my $has_out = defined $out;
393  
394 my @tokens = ();
395 my $line = 1;
396  
397 return \@tokens ## RETURN ##
398 unless defined $text && length $text;
399  
400 # extract all directives from the text
401 while ($text =~ s/$split//) {
402 $pre = $1 // '';
403 $dir = $2 // $3 // '';
404  
405 $prelines = ($pre =~ tr/\n//); # newlines in preceding text
406 $dirlines = ($dir =~ tr/\n//); # newlines in directive tag
407 $postlines = 0; # newlines chomped after tag
408  
409 for ($dir) {
410 if (/^\#/) {
411 # comment out entire directive except for any end chomp flag
412 #
413 # Handle comments containing nested tag pairs, e.g.:
414 # [%# [% foo %] %]
415 # The tokenizer splits at the first END_TAG, so the
416 # directive text may contain unbalanced START_TAGs.
417 # For each one, consume the matching END_TAG from
418 # the remaining template text.
419 my $nested = () = /$start/g;
420 while ($nested > 0 && $text =~ s/\A(.*?)$end//s) {
421 my $extra = $1;
422 $dirlines += ($extra =~ tr/\n//);
423 $nested--;
424 $nested += () = $extra =~ /$start/g;
425 }
426 $dir = ($dir =~ /($CHOMP_FLAGS)$/o) ? $1 : '';
427 }
428 else {
429  
430 if(s/^($CHOMP_FLAGS)?(\s*)//so && $2) {
431 my $chomped = $2;
432 my $linecount = ($chomped =~ tr/\n//); # newlines in chomped whitespace
433 $linecount ||= 0;
434 $prelines += $linecount;
435 $dirlines -= $linecount;
436 }
437 # PRE_CHOMP: process whitespace before tag
438 $chomp = $1 ? $1 : $prechomp;
439 $chomp =~ tr/-=~+/1230/;
440 if ($chomp && $pre) {
441 # chomp off whitespace and newline preceding directive
442 if ($chomp == CHOMP_ALL) {
443 $pre =~ s{ (\r?\n|^) [^\S\n]* \z }{}mx;
444 }
445 elsif ($chomp == CHOMP_COLLAPSE) {
446 $pre =~ s{ (\s+) \z }{ }x;
447 }
448 elsif ($chomp == CHOMP_GREEDY) {
449 $pre =~ s{ (\s+) \z }{}x;
450 }
451 }
452 }
453  
454 # POST_CHOMP: process whitespace after tag
455 s/\s*($CHOMP_FLAGS)?\s*$//so;
456 $chomp = $1 ? $1 : $postchomp;
457 $chomp =~ tr/-=~+/1230/;
458 if ($chomp) {
459 if ($chomp == CHOMP_ALL) {
460 $text =~ s{ ^ ([^\S\n]* \n) }{}x
461 && $postlines++;
462 }
463 elsif ($chomp == CHOMP_COLLAPSE) {
464 $text =~ s{ ^ (\s+) }{ }x
465 && ($postlines += $1=~y/\n//);
466 }
467 # any trailing whitespace
468 elsif ($chomp == CHOMP_GREEDY) {
469 $text =~ s{ ^ (\s+) }{}x
470 && ($postlines += $1=~y/\n//);
471 }
472 }
473 }
474  
475 # any text preceding the directive can now be added
476 if (length $pre) {
477 push(@tokens, $interp
478 ? [ $pre, $line, 'ITEXT' ]
479 : ('TEXT', $pre) );
480 }
481 $line += $prelines;
482  
483 # and now the directive, along with line number information
484 if (length $dir) {
485 # the TAGS directive is a compile-time switch
486 if ($dir =~ /^$tags_dir\s+(.*)/) {
487 my @tags = split(/\s+/, $1);
488 if (scalar @tags > 1) {
489 ($start, $end, $out) = map { quotemeta($_) } @tags;
490 $split = $self->text_splitter($start, $end, $out);
491 }
492 elsif ($tags = $TAG_STYLE->{ $tags[0] }) {
493 ($start, $end, $out) = @$tags;
494 $split = $self->text_splitter($start, $end, $out);
495 }
496 else {
497 warn "invalid TAGS style: $tags[0]\n";
498 }
499 }
500 else {
501 # DIRECTIVE is pushed as:
502 # [ $dirtext, $line_no(s), \@tokens ]
503 push(@tokens,
504 [ $dir,
505 ($dirlines
506 ? sprintf("%d-%d", $line, $line + $dirlines)
507 : $line),
508 $self->tokenise_directive($dir) ]);
509 }
510 }
511  
512 # update line counter to include directive lines and any extra
513 # newline chomped off the start of the following text
514 $line += $dirlines + $postlines;
515 }
516  
517 # anything remaining in the string is plain text
518 push(@tokens, $interp
519 ? [ $text, $line, 'ITEXT' ]
520 : ( 'TEXT', $text) )
521 if length $text;
522  
523 return \@tokens; ## RETURN ##
524 }
525  
526  
527  
528 #------------------------------------------------------------------------
529 # interpolate_text($text, $line)
530 #
531 # Examines $text looking for any variable references embedded like
532 # $this or like ${ this }.
533 #------------------------------------------------------------------------
534  
535 sub interpolate_text {
536 my ($self, $text, $line) = @_;
537 my @tokens = ();
538 my ($pre, $var, $dir);
539  
540  
541 while ($text =~
542 /
543 ( (?: \\. | [^\$] ){1,3000} ) # escaped or non-'$' character [$1]
544 |
545 ( \$ (?: # embedded variable [$2]
546 (?: \{ ([^\}]*) \} ) # ${ ... } [$3]
547 |
548 ([\w\.]+) # $word [$4]
549 )
550 )
551 /gx) {
552  
553 ($pre, $var, $dir) = ($1, $3 || $4, $2);
554  
555 # preceding text
556 if (defined($pre) && length($pre)) {
557 $line += $pre =~ tr/\n//;
558 $pre =~ s/\\\$/\$/g;
559 push(@tokens, 'TEXT', $pre);
560 }
561 # $variable reference
562 if ($var) {
563 $line += $dir =~ tr/\n/ /;
564 push(@tokens, [ $dir, $line, $self->tokenise_directive($var) ]);
565 }
566 # other '$' reference - treated as text
567 elsif ($dir) {
568 $line += $dir =~ tr/\n//;
569 push(@tokens, 'TEXT', $dir);
570 }
571 }
572  
573 return \@tokens;
574 }
575  
576  
577  
578 #------------------------------------------------------------------------
579 # tokenise_directive($text)
580 #
581 # Called by the private _parse() method when it encounters a DIRECTIVE
582 # token in the list provided by the split_text() or interpolate_text()
583 # methods. The directive text is passed by parameter.
584 #
585 # The method splits the directive into individual tokens as recognised
586 # by the parser grammar (see Template::Grammar for details). It
587 # constructs a list of tokens each represented by 2 elements, as per
588 # split_text() et al. The first element contains the token type, the
589 # second the token itself.
590 #
591 # The method tokenises the string using a complex (but fast) regex.
592 # For a deeper understanding of the regex magic at work here, see
593 # Jeffrey Friedl's excellent book "Mastering Regular Expressions",
594 # from O'Reilly, ISBN 1-56592-257-3
595 #
596 # Returns a reference to the list of chunks (each one being 2 elements)
597 # identified in the directive text. On error, the internal _ERROR string
598 # is set and undef is returned.
599 #------------------------------------------------------------------------
600  
601 sub tokenise_directive {
602 my ($self, $text, $line) = @_;
603 my ($token, $uctoken, $type, $lookup);
604 my $lextable = $self->{ LEXTABLE };
605 my $style = $self->{ STYLE }->[-1];
606 my ($anycase, $start, $end) = @$style{ qw( ANYCASE START_TAG END_TAG ) };
607 my @tokens = ( );
608  
609 while ($text =~
610 /
611 # strip out any comments
612 (\#[^\n]*)
613 |
614 # a quoted phrase matches in $3
615 (["']) # $2 - opening quote, ' or "
616 ( # $3 - quoted text buffer
617 (?: # repeat group (no backreference)
618 \\\\ # an escaped backslash \\
619 | # ...or...
620 \\\2 # an escaped quote \" or \' (match $1)
621 | # ...or...
622 . # any other character
623 | \n
624 )*? # non-greedy repeat
625 ) # end of $3
626 \2 # match opening quote
627 |
628 # an unquoted number matches in $4
629 (-?\d+(?:\.\d+)?) # numbers
630 |
631 # filename matches in $5
632 ( \/?\w+(?:(?:\/|::?)\w*)+ | \/\w+)
633 |
634 # an identifier matches in $6
635 (\w+) # variable identifier
636 |
637 # an unquoted word or symbol matches in $7
638 ( [(){}\[\]:;,\/\\] # misc parenthesis and symbols
639 # | \-> # arrow operator (for future?)
640 | [+\-*] # math operations
641 | \$\{? # dollar with option left brace
642 | => # like '='
643 | [=!<>]?= | [!<>] # eqality tests
644 | &&? | \|\|? # boolean ops
645 | \.\.? # n..n sequence
646 | \S+ # something unquoted
647 ) # end of $7
648 /gmxo) {
649  
650 # ignore comments to EOL
651 next if $1;
652  
653 # quoted string
654 if (defined ($token = $3)) {
655 # double-quoted string may include $variable references
656 if ($2 eq '"') {
657 if ($token =~ /[\$\\]/) {
658 $type = 'QUOTED';
659 # unescape " and \ but leave \$ escaped so that
660 # interpolate_text() doesn't incorrectly treat it
661 # as a variable reference
662 # $token =~ s/\\([\\"])/$1/g;
663 for ($token) {
664 s/\\([^\$nrt])/$1/g;
665 s/\\([nrt])/$QUOTED_ESCAPES->{ $1 }/ge;
666 }
667 push(@tokens, ('"') x 2,
668 @{ $self->interpolate_text($token) },
669 ('"') x 2);
670 next;
671 }
672 else {
673 $type = 'LITERAL';
674 $token =~ s['][\\']g;
675 $token = "'$token'";
676 }
677 }
678 else {
679 $type = 'LITERAL';
680 $token = "'$token'";
681 }
682 }
683 # number
684 elsif (defined ($token = $4)) {
685 $type = 'NUMBER';
686 }
687 elsif (defined($token = $5)) {
688 $type = 'FILENAME';
689 }
690 elsif (defined($token = $6)) {
691 # Fold potential keywords to UPPER CASE if the ANYCASE option is
692 # set, unless (we've got some preceding tokens and) the previous
693 # token is a DOT op. This prevents the 'last' in 'data.last'
694 # from being interpreted as the LAST keyword.
695 if ($anycase) {
696 # if the token follows a dot or precedes an assignment then
697 # it's not for folding, e.g. the 'wrapper' in this:
698 # [% page = { wrapper='html' }; page.wrapper %]
699 if ((@tokens && $ANYCASE_AFTER->{ $tokens[-2] })
700 || ($text =~ /$ANYCASE_BEFORE/gc)) {
701 # keep the token unmodified
702 $uctoken = $token;
703 }
704 else {
705 $uctoken = uc $token;
706 }
707 }
708 else {
709 $uctoken = $token;
710 }
711 if (defined ($type = $lextable->{ $uctoken })) {
712 $token = $uctoken;
713 }
714 else {
715 $type = 'IDENT';
716 }
717 }
718 elsif (defined ($token = $7)) {
719 # reserved words may be in lower case unless case sensitive
720 $uctoken = $anycase ? uc $token : $token;
721 unless (defined ($type = $lextable->{ $uctoken })) {
722 $type = 'UNQUOTED';
723 }
724 }
725  
726 push(@tokens, $type, $token);
727  
728 # print(STDERR " +[ $type, $token ]\n")
729 # if $DEBUG;
730 }
731  
732 # print STDERR "tokenise directive() returning:\n [ @tokens ]\n"
733 # if $DEBUG;
734  
735 return \@tokens; ## RETURN ##
736 }
737  
738  
739 #------------------------------------------------------------------------
740 # define_block($name, $block)
741 #
742 # Called by the parser 'defblock' rule when a BLOCK definition is
743 # encountered in the template. The name of the block is passed in the
744 # first parameter and a reference to the compiled block is passed in
745 # the second. This method stores the block in the $self->{ DEFBLOCK }
746 # hash which has been initialised by parse() and will later be used
747 # by the same method to call the store() method on the calling cache
748 # to define the block "externally".
749 #------------------------------------------------------------------------
750  
751 sub define_block {
752 my ($self, $name, $block) = @_;
753 my $defblock = $self->{ DEFBLOCK }
754 || return undef;
755  
756 $self->debug("compiled block '$name':\n$block")
757 if $self->{ DEBUG } & Template::Constants::DEBUG_PARSER;
758  
759 warn "Block redefined: $name\n" if exists $defblock->{ $name };
760  
761 $defblock->{ $name } = $block;
762  
763 return undef;
764 }
765  
766 sub push_defblock {
767 my $self = shift;
768 my $stack = $self->{ DEFBLOCK_STACK } ||= [];
769 push(@$stack, $self->{ DEFBLOCK } );
770 $self->{ DEFBLOCK } = { };
771 }
772  
773 sub pop_defblock {
774 my $self = shift;
775 my $defs = $self->{ DEFBLOCK };
776 my $stack = $self->{ DEFBLOCK_STACK } || return $defs;
777 return $defs unless @$stack;
778 $self->{ DEFBLOCK } = pop @$stack;
779 return $defs;
780 }
781  
782  
783 #------------------------------------------------------------------------
784 # add_metadata(\@setlist)
785 #------------------------------------------------------------------------
786  
787 sub add_metadata {
788 my ($self, $setlist) = @_;
789 my $metadata = $self->{ METADATA }
790 || return undef;
791  
792 push(@$metadata, @$setlist);
793  
794 return undef;
795 }
796  
797  
798 #------------------------------------------------------------------------
799 # location()
800 #
801 # Return Perl comment indicating current parser file and line
802 #------------------------------------------------------------------------
803  
804 sub location {
805 my $self = shift;
806 return "\n" unless $self->{ FILE_INFO };
807 my $line = ${ $self->{ LINE } };
808 my $info = $self->{ FILEINFO }->[-1];
809 my $file = $info->{ path } || $info->{ name }
810 || '(unknown template)';
811 $line =~ s/\-.*$//; # might be 'n-n'
812 $line ||= 1;
813 return "#line $line \"$file\"\n";
814 }
815  
816  
817 #========================================================================
818 # ----- PRIVATE METHODS -----
819 #========================================================================
820  
821 #------------------------------------------------------------------------
822 # _parse(\@tokens, \@info)
823 #
824 # Parses the list of input tokens passed by reference and returns a
825 # Template::Directive::Block object which contains the compiled
826 # representation of the template.
827 #
828 # This is the main parser DFA loop. See embedded comments for
829 # further details.
830 #
831 # On error, undef is returned and the internal _ERROR field is set to
832 # indicate the error. This can be retrieved by calling the error()
833 # method.
834 #------------------------------------------------------------------------
835  
836 sub _parse {
837 my ($self, $tokens, $info) = @_;
838 my ($token, $value, $text, $line, $inperl);
839 my ($state, $stateno, $status, $action, $lookup, $coderet, @codevars);
840 my ($lhs, $len, $code); # rule contents
841 my $stack = [ [ 0, undef ] ]; # DFA stack
842  
843 # DEBUG
844 # local $" = ', ';
845  
846 # retrieve internal rule and state tables
847 my ($states, $rules) = @$self{ qw( STATES RULES ) };
848  
849 # If we're tracing variable usage then we need to give the factory a
850 # reference to our $self->{ VARIABLES } for it to fill in. This is a
851 # bit of a hack to back-patch this functionality into TT2.
852 $self->{ FACTORY }->trace_vars($self->{ VARIABLES })
853 if $self->{ TRACE_VARS };
854  
855 # call the grammar set_factory method to install emitter factory
856 $self->{ GRAMMAR }->install_factory($self->{ FACTORY });
857  
858 $line = $inperl = 0;
859 $self->{ LINE } = \$line;
860 $self->{ FILE } = $info->{ name };
861 $self->{ INPERL } = \$inperl;
862  
863 $status = CONTINUE;
864 my $in_string = 0;
865  
866 while(1) {
867 # get state number and state
868 $stateno = $stack->[-1]->[0];
869 $state = $states->[$stateno];
870  
871 # see if any lookaheads exist for the current state
872 if (exists $state->{'ACTIONS'}) {
873  
874 # get next token and expand any directives (i.e. token is an
875 # array ref) onto the front of the token list
876 while (! defined $token && @$tokens) {
877 $token = shift(@$tokens);
878 if (ref $token) {
879 ($text, $line, $token) = @$token;
880 if (ref $token) {
881 if ($info->{ DEBUG } && ! $in_string) {
882 # - - - - - - - - - - - - - - - - - - - - - - - - -
883 # This is gnarly. Look away now if you're easily
884 # frightened. We're pushing parse tokens onto the
885 # pending list to simulate a DEBUG directive like so:
886 # [% DEBUG msg line='20' text='INCLUDE foo' %]
887 # - - - - - - - - - - - - - - - - - - - - - - - - -
888 my $dtext = $text;
889 $dtext =~ s[(['\\])][\\$1]g;
890 unshift(@$tokens,
891 DEBUG => 'DEBUG',
892 IDENT => 'msg',
893 IDENT => 'line',
894 ASSIGN => '=',
895 LITERAL => "'$line'",
896 IDENT => 'text',
897 ASSIGN => '=',
898 LITERAL => "'$dtext'",
899 IDENT => 'file',
900 ASSIGN => '=',
901 LITERAL => "'$info->{ name }'",
902 (';') x 2,
903 @$token,
904 (';') x 2);
905 }
906 else {
907 unshift(@$tokens, @$token, (';') x 2);
908 }
909 $token = undef; # force redo
910 }
911 elsif ($token eq 'ITEXT') {
912 if ($inperl) {
913 # don't perform interpolation in PERL blocks
914 $token = 'TEXT';
915 $value = $text;
916 }
917 else {
918 unshift(@$tokens,
919 @{ $self->interpolate_text($text, $line) });
920 $token = undef; # force redo
921 }
922 }
923 }
924 else {
925 # toggle string flag to indicate if we're crossing
926 # a string boundary
927 $in_string = ! $in_string if $token eq '"';
928 $value = shift(@$tokens);
929 }
930 };
931 # clear undefined token to avoid 'undefined variable blah blah'
932 # warnings and let the parser logic pick it up in a minute
933 $token //= '';
934  
935 # get the next state for the current lookahead token
936 $action = defined ($lookup = $state->{'ACTIONS'}->{ $token })
937 ? $lookup
938 : defined ($lookup = $state->{'DEFAULT'})
939 ? $lookup
940 : undef;
941 }
942 else {
943 # no lookahead actions
944 $action = $state->{'DEFAULT'};
945 }
946  
947 # ERROR: no ACTION
948 last unless defined $action;
949  
950 # - - - - - - - - - - - - - - - - - - - - - - - - - - - -
951 # shift (+ive ACTION)
952 # - - - - - - - - - - - - - - - - - - - - - - - - - - - -
953 if ($action > 0) {
954 push(@$stack, [ $action, $value ]);
955 $token = $value = undef;
956 redo;
957 };
958  
959 # - - - - - - - - - - - - - - - - - - - - - - - - - - - -
960 # reduce (-ive ACTION)
961 # - - - - - - - - - - - - - - - - - - - - - - - - - - - -
962 ($lhs, $len, $code) = @{ $rules->[ -$action ] };
963  
964 # no action imples ACCEPTance
965 $action
966 or $status = ACCEPT;
967  
968 # use dummy sub if code ref doesn't exist
969 if ( !$code ) {
970 $coderet = $len ? $stack->[ -$len ]->[1] : undef;
971 } else {
972 # $code = sub { $_[1] }
973 # unless $code;
974  
975 @codevars = $len
976 ? map { $_->[1] } @$stack[ -$len .. -1 ]
977 : ();
978  
979 eval {
980 $coderet = &$code( $self, @codevars );
981 };
982 if ($@) {
983 my $err = $@;
984 chomp $err;
985 return $self->_parse_error($err);
986 }
987 }
988  
989  
990 # reduce stack by $len
991 splice(@$stack, -$len, $len);
992  
993 # ACCEPT
994 return $coderet ## RETURN ##
995 if $status == ACCEPT;
996  
997 # ABORT
998 return undef ## RETURN ##
999 if $status == ABORT;
1000  
1001 # ERROR
1002 last
1003 if $status == ERROR;
1004 }
1005 continue {
1006 push(@$stack, [ $states->[ $stack->[-1][0] ]->{'GOTOS'}->{ $lhs },
1007 $coderet ]),
1008 }
1009  
1010 # ERROR ## RETURN ##
1011 return $self->_parse_error('unexpected end of input')
1012 unless defined $value;
1013  
1014 # munge text of last directive to make it readable
1015 # $text =~ s/\n/\\n/g;
1016  
1017 return $self->_parse_error("unexpected end of directive", $text)
1018 if $value eq ';'; # end of directive SEPARATOR
1019  
1020 return $self->_parse_error("unexpected token ($value)", $text);
1021 }
1022  
1023  
1024  
1025 #------------------------------------------------------------------------
1026 # _parse_error($msg, $dirtext)
1027 #
1028 # Method used to handle errors encountered during the parse process
1029 # in the _parse() method.
1030 #------------------------------------------------------------------------
1031  
1032 sub _parse_error {
1033 my ($self, $msg, $text) = @_;
1034 my $line = $self->{ LINE };
1035 $line = ref($line) ? $$line : $line;
1036 $line = 'unknown' unless $line;
1037  
1038 $msg .= "\n [% $text %]"
1039 if defined $text;
1040  
1041 return $self->error("line $line: $msg");
1042 }
1043  
1044 1;
1045  
1046 __END__