lib/Template/Parser.pm

filter: Statementstmt 97.3% 332 / 341 Branchbran 86.6% 168 / 194 Conditioncond 78.5% 55 / 70 MC/DCmcdc 63.4% 26 / 41 Subroutinesub 100% 29 / 29 Podpod 11.7% 2 / 17 totaltotal 88.4% 612 / 692 CC 128 SCAR 29.2
CC
128
Cov
92%
split_text
37.6
_parse
27.2
tokenise_directive
18.0
CRAP 18.5
« lib/Template/Plugin/Date.pm ↑ Summary lib/Template/Context.pm »
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 102 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
36 102 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
37 102 ▶use base 'Template::Base';
Subroutine BEGIN: called CC=1 SCAR=0.0
38  
39 102 ▶use Template::Constants qw( :status :chomp );
Subroutine BEGIN: called CC=1 SCAR=0.0
40 102 ▶use Template::Directive;
Subroutine BEGIN: called CC=1 SCAR=0.0
41 102 ▶use Template::Grammar;
Subroutine BEGIN: called CC=1 SCAR=0.0
42  
43 # parser state constants
44 102 ▶use constant CONTINUE => 0;
Subroutine BEGIN: called CC=1 SCAR=0.0
45 102 ▶use constant ACCEPT => 1;
Subroutine BEGIN: called CC=1 SCAR=0.0
46 102 ▶use constant ERROR => 2;
Subroutine BEGIN: called CC=1 SCAR=0.0
47 102 ▶use constant ABORT => 3;
Subroutine BEGIN: called CC=1 SCAR=0.0
48  
49 102 our $VERSION = '3.100';
50 102 ▶our $DEBUG = 0 unless defined $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $Template::Parser::DEBUG 102 0 102
51 102 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 102 our $ANYCASE_BEFORE = qr/\G((?=\s*[=\.]))/;
64 our $ANYCASE_AFTER = {
65 102 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 102 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 102 $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 102 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 102 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 102 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 217 ▶ my $class = shift;
Subroutine new: called CC=12 SCAR=25.3
Pod documented
131 217 ▶ my $config = $_[0] && ref($_[0]) eq 'HASH' ? shift(@_) : { @_ };
Branch: 1 branch
BranchTrueFalseTotal
$_[0] && ref $_[0] eq 'HASH' ? : 215 2 217
Condition100%3/3
$_[0] and ref $_[0] eq "HASH"
!ll&&!rl&&r
11215
MC/DC100%2/2
$_[0] and ref $_[0] eq "HASH"
$_[0] ref $_[0] eq "HASH"
Truth table100%3/3
A and B
A= $_[0]B= ref $_[0] eq "HASH"
ABresult
0X0
100
111
132 217 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 217 ▶ FACTORY => $config->{ FACTORY } || 'Template::Directive',
Condition100%2/2
$config->{'FACTORY'} || 'Template::Directive'
l!l
2215
MC/DC100%1/1
$config->{'FACTORY'} || 'Template::Directive'
$config->{'FACTORY'}
Truth table100%2/2
A
A= $config->{'FACTORY'}
Aresult
11
00
151 }, $class;
152  
153 # update self with any relevant keys in config
154 217 foreach $key (keys %$self) {
155 3472 ▶ $self->{ $key } = $config->{ $key } if defined $config->{ $key };
Branch: 1 branch
BranchTrueFalseTotal
if defined $config->{$key} 104 3368 3472
156 }
157 217 $self->{ FILEINFO } = [ ];
158  
159 # DEBUG config item can be a bitmask
160 217 ▶ if (defined ($debug = $config->{ DEBUG })) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined($debug = $config->{'DEBUG'})) { } 15 202 217
elsif ($Template::Parser::DEBUG == 1) { } 0 202 202
161 15 $self->{ DEBUG } = $debug & ( Template::Constants::DEBUG_PARSER
162 | Template::Constants::DEBUG_FLAGS );
163 15 $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 0 $self->{ DEBUG } = Template::Constants::DEBUG_PARSER;
168 0 $self->{ DEBUG_DIRS } = 0;
169 }
170 # otherwise let $DEBUG be a bitmask
171 else {
172 202 $self->{ DEBUG } = $DEBUG & ( Template::Constants::DEBUG_PARSER
173 | Template::Constants::DEBUG_FLAGS );
174 202 $self->{ DEBUG_DIRS } = $DEBUG & Template::Constants::DEBUG_DIRS;
175 }
176  
177 217 ▶ $grammar = $self->{ GRAMMAR } ||= do {
Condition33%1/3
$self->{"GRAMMAR"} ||= do { require Template::Grammar; "Template::Grammar"->new }
l!l&&r!l&&!r
02170
MC/DC0%0/2
$self->{"GRAMMAR"} ||= do { require Template::Grammar; "Template::Grammar"->new }
$self->{"GRAMMAR"} do { require Template::Grammar; "Template::Grammar"->new }
Truth table33%1/3
A ||= B
A= $self->{"GRAMMAR"}B= do { require Template::Grammar; "Template::Grammar"->new }
ABresult
1X1
011
000
178 217 require Template::Grammar;
179 217 Template::Grammar->new();
180 };
181  
182 # instantiate a FACTORY object
183 217 ▶ unless (ref $self->{ FACTORY }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $self->{"FACTORY"}) 216 1 217
184 216 my $fclass = $self->{ FACTORY };
185 $self->{ FACTORY } = $self->{ FACTORY }->new(
186 NAMESPACE => $config->{ NAMESPACE }
187 )
188 216 ▶ || return $class->error($self->{ FACTORY }->error());
Condition50%1/2
$self->{'FACTORY'}->new('NAMESPACE', $config->{'NAMESPACE'}) || (return $class->error($self->{'FACTORY'}->error))
l!l
2160
MC/DC0%0/1
$self->{'FACTORY'}->new('NAMESPACE', $config->{'NAMESPACE'}) || (return $class->error($self->{'FACTORY'}->error))
$self->{'FACTORY'}->new('NAMESPACE', $config->{'NAMESPACE'})
Truth table50%1/2
A
A= $self->{'FACTORY'}->new('NAMESPACE', $config->{'NAMESPACE'})
Aresult
11
00
189 }
190  
191 # load grammar rules, states and lex table
192 @$self{ qw( LEXTABLE STATES RULES ) }
193 217 = @$grammar{ qw( LEXTABLE STATES RULES ) };
194  
195 217 ▶ $self->new_style($config)
Branch: 1 branch
BranchTrueFalseTotal
$self->new_style($config) or return $class->error($self->error) 0 217 217
196 || return $class->error($self->error());
197  
198 217 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 202 ▶ my ($self, $name) = @_;
Subroutine enter_block: called CC=1 SCAR=0.0
Pod undocumented
210 202 my $blocks = $self->{ IN_BLOCK };
211 202 push(@{ $self->{ IN_BLOCK } }, $name);
212 }
213  
214 sub leave_block {
215 202 ▶ my $self = shift;
Subroutine leave_block: called CC=1 SCAR=0.0
Pod undocumented
216 202 my $label = $self->block_label;
217 202 pop(@{ $self->{ IN_BLOCK } });
218 202 return $label;
219 }
220  
221 sub in_block {
222 17 ▶ my ($self, $name) = @_;
Subroutine in_block: called CC=2 SCAR=6.9
Pod undocumented
223 17 my $blocks = $self->{ IN_BLOCK };
224 17 ▶ return @$blocks && $blocks->[-1] eq $name;
Condition100%3/3
@$blocks && $blocks->[-1] eq $name
!ll&&!rl&&r
1610
MC/DC100%2/2
@$blocks && $blocks->[-1] eq $name
@$blocks $blocks->[-1] eq $name
Truth table100%3/3
A && B
A= @$blocksB= $blocks->[-1] eq $name
ABresult
0X0
100
111
225 }
226  
227 sub block_label {
228 230 ▶ my ($self, $prefix, $suffix) = @_;
Subroutine block_label: called CC=2 SCAR=6.9
Pod undocumented
229 230 my $blocks = $self->{ IN_BLOCK };
230 230 ▶ my $name = @$blocks
Branch: 1 branch
BranchTrueFalseTotal
@$blocks ? : 227 3 230
231 ? $blocks->[-1] . scalar @$blocks
232 : undef;
233 230 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 218 ▶ my ($self, $config) = @_;
Subroutine new_style: called CC=10 SCAR=23.4
Pod undocumented
248 218 ▶ my $styles = $self->{ STYLE } ||= [ ];
Condition100%2/2
$self->{"STYLE"} ||= []
l!l
1217
MC/DC100%1/1
$self->{"STYLE"} ||= []
$self->{"STYLE"}
Truth table100%2/2
A
A= $self->{"STYLE"}
Aresult
11
00
249 218 my ($tagstyle, $tags, $start, $end, $out, $key);
250  
251 # clone new style from previous or default style
252 218 ▶ my $style = { %{ $styles->[-1] || $DEFAULT_STYLE } };
Branch: 1 branch
BranchTrueFalseTotal
$styles->[-1] or $Template::Parser::DEFAULT_STYLE 217 1 218
253  
254 # expand START_TAG and END_TAG from specified TAG_STYLE
255 218 ▶ if ($tagstyle = $config->{ TAG_STYLE }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tagstyle = $config->{"TAG_STYLE"}) 5 213 218
256 return $self->error("Invalid tag style: $tagstyle")
257 5 ▶ unless defined ($tags = $TAG_STYLE->{ $tagstyle });
Branch: 1 branch
BranchTrueFalseTotal
unless defined($tags = $Template::Parser::TAG_STYLE->{$tagstyle}) 0 5 5
258 5 ($start, $end, $out) = @$tags;
259 5 ▶ $config->{ START_TAG } ||= $start;
Condition33%1/3
$config->{"START_TAG"} ||= $start
l!l&&r!l&&!r
050
MC/DC0%0/2
$config->{"START_TAG"} ||= $start
$config->{"START_TAG"} $start
Truth table33%1/3
A ||= B
A= $config->{"START_TAG"}B= $start
ABresult
1X1
011
000
260 5 ▶ $config->{ END_TAG } ||= $end;
Condition33%1/3
$config->{"END_TAG"} ||= $end
l!l&&r!l&&!r
050
MC/DC0%0/2
$config->{"END_TAG"} ||= $end
$config->{"END_TAG"} $end
Truth table33%1/3
A ||= B
A= $config->{"END_TAG"}B= $end
ABresult
1X1
011
000
261 5 ▶ $config->{ OUTLINE_TAG } ||= $out;
Condition66%2/3
$config->{"OUTLINE_TAG"} ||= $out
l!l&&r!l&&!r
023
MC/DC50%1/2
$config->{"OUTLINE_TAG"} ||= $out
$config->{"OUTLINE_TAG"} $out
Truth table66%2/3
A ||= B
A= $config->{"OUTLINE_TAG"}B= $out
ABresult
1X1
011
000
262 }
263  
264 218 foreach $key (keys %$DEFAULT_STYLE) {
265 1962 ▶ $style->{ $key } = $config->{ $key } if defined $config->{ $key };
Branch: 1 branch
BranchTrueFalseTotal
if defined $config->{$key} 110 1852 1962
266 }
267  
268 218 $start = $style->{ START_TAG };
269 218 $end = $style->{ END_TAG };
270 218 $out = $style->{ OUTLINE_TAG };
271 218 $style->{ TEXT_SPLIT } = $self->text_splitter($start, $end, $out);
272  
273 218 push(@$styles, $style);
274 218 return $style;
275 }
276  
277 sub text_splitter {
278 237 ▶ my ($self, $start, $end, $out) = @_;
Subroutine text_splitter: called CC=2 SCAR=6.9
Pod undocumented
279  
280 237 ▶ if (defined $out) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $out) { } 7 230 237
281 7 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 230 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 1 ▶ my $self = shift;
Subroutine old_style: called CC=2 SCAR=7.0
Pod undocumented
320 1 my $styles = $self->{ STYLE };
321 1 ▶ return $self->error('only 1 parser style remaining')
Branch: 1 branch
BranchTrueFalseTotal
unless @$styles > 1 0 1 1
322 unless (@$styles > 1);
323 1 pop @$styles;
324 1 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 1431 ▶ my ($self, $text, $info) = @_;
Subroutine parse: called CC=5 SCAR=16.2
Pod documented
338 1431 my ($tokens, $block);
339  
340 $info->{ DEBUG } = $self->{ DEBUG_DIRS }
341 1431 ▶ unless defined $info->{ DEBUG };
Branch: 1 branch
BranchTrueFalseTotal
unless defined $info->{"DEBUG"} 1431 0 1431
342  
343 # print "info: { ", join(', ', map { "$_ => $info->{ $_ }" } keys %$info), " }\n";
344  
345 # store for blocks defined in the template (see define_block())
346 1431 my $defblock = $self->{ DEFBLOCK } = { };
347 1431 my $metadata = $self->{ METADATA } = [ ];
348 1431 my $variables = $self->{ VARIABLES } = { };
349 1431 $self->{ DEFBLOCKS } = [ ];
350  
351 1431 $self->{ _ERROR } = '';
352  
353 # split file into TEXT/DIRECTIVE chunks
354 1431 ▶ $tokens = $self->split_text($text)
Condition50%1/2
$self->split_text($text) || (return undef)
l!l
14310
MC/DC0%0/1
$self->split_text($text) || (return undef)
$self->split_text($text)
Truth table50%1/2
A
A= $self->split_text($text)
Aresult
11
00
355 || return undef; ## RETURN ##
356  
357 1431 push(@{ $self->{ FILEINFO } }, $info);
358  
359 # parse chunks
360 1431 $block = $self->_parse($tokens, $info);
361  
362 1431 pop(@{ $self->{ FILEINFO } });
363  
364 1431 ▶ return undef unless $block; ## RETURN ##
Branch: 1 branch
BranchTrueFalseTotal
unless $block 3 1428 1431
365  
366 $self->debug("compiled main template document block:\n$block")
367 1428 ▶ if $self->{ DEBUG } & Template::Constants::DEBUG_PARSER;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"DEBUG"} & 64 0 1428 1428
368  
369 return {
370 1428 BLOCK => $block,
371 DEFBLOCKS => $defblock,
372 VARIABLES => $variables,
373 METADATA => { @$metadata },
374 };
375 }
376  
377  
378  
379 #------------------------------------------------------------------------
380 # split_text($text)
381 #
382 # Split input template text into directives and raw text chunks.
383 #------------------------------------------------------------------------
384  
385 sub split_text {
386 1432 ▶ my ($self, $text) = @_;
Subroutine split_text: called CC=37 SCAR=36.3
Pod undocumented
387 1432 my ($pre, $dir, $prelines, $dirlines, $postlines, $chomp, $tags, @tags);
388 1432 my $style = $self->{ STYLE }->[-1];
389 my ($start, $end, $out, $prechomp, $postchomp, $interp ) =
390 1432 @$style{ qw( START_TAG END_TAG OUTLINE_TAG PRE_CHOMP POST_CHOMP INTERPOLATE ) };
391 1432 ▶ my $tags_dir = $self->{ANYCASE} ? qr<TAGS>i : qr<TAGS>;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'ANYCASE'} ? : 117 1315 1432
392 1432 my $split = $style->{ TEXT_SPLIT };
393 1432 my $has_out = defined $out;
394  
395 1432 my @tokens = ();
396 1432 my $line = 1;
397  
398 return \@tokens ## RETURN ##
399 1432 ▶ unless defined $text && length $text;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $text and length $text 8 1424 1432
Condition66%2/3
defined $text and length $text
!ll&&!rl&&r
081424
MC/DC50%1/2
defined $text and length $text
defined $text length $text
Truth table66%2/3
A and B
A= defined $textB= length $text
ABresult
0X0
100
111
400  
401 # extract all directives from the text
402 1424 ▶ while ($text =~ s/$split//) {
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ s/$split//) 4142 1424 5566
403 4142 $pre = $1;
404 4142 ▶ $dir = defined($2) ? $2 : $3;
Branch: 1 branch
BranchTrueFalseTotal
defined $2 ? : 4125 17 4142
405 4142 ▶ $pre = '' unless defined $pre;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pre 0 4142 4142
406 4142 ▶ $dir = '' unless defined $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dir 0 4142 4142
407  
408 4142 $prelines = ($pre =~ tr/\n//); # newlines in preceding text
409 4142 $dirlines = ($dir =~ tr/\n//); # newlines in directive tag
410 4142 $postlines = 0; # newlines chomped after tag
411  
412 4142 for ($dir) {
413 4142 ▶ if (/^\#/) {
Branch: 1 branch
BranchTrueFalseTotal
if (/^\#/) { } 11 4131 4142
414 # comment out entire directive except for any end chomp flag
415 11 ▶ $dir = ($dir =~ /($CHOMP_FLAGS)$/o) ? $1 : '';
Branch: 1 branch
BranchTrueFalseTotal
$dir =~ /($Template::Parser::CHOMP_FLAGS)$/o ? : 4 7 11
416 }
417 else {
418  
419 4131 ▶ if(s/^($CHOMP_FLAGS)?(\s*)//so && $2) {
Branch: 1 branch
BranchTrueFalseTotal
if (s/^($Template::Parser::CHOMP_FLAGS)?(\s*)//os and $2) 4117 14 4131
Condition66%2/3
s/^($Template::Parser::CHOMP_FLAGS)?(\s*)//os and $2
!ll&&!rl&&r
0144117
MC/DC50%1/2
s/^($Template::Parser::CHOMP_FLAGS)?(\s*)//os and $2
s/^($Template::Parser::CHOMP_FLAGS)?(\s*)//os $2
Truth table66%2/3
A and B
A= s/^($Template::Parser::CHOMP_FLAGS)?(\s*)//osB= $2
ABresult
0X0
100
111
420 4117 my $chomped = $2;
421 4117 my $linecount = ($chomped =~ tr/\n//); # newlines in chomped whitespace
422 4117 ▶ $linecount ||= 0;
Condition100%2/2
$linecount ||= 0
l!l
164101
MC/DC100%1/1
$linecount ||= 0
$linecount
Truth table100%2/2
A
A= $linecount
Aresult
11
00
423 4117 $prelines += $linecount;
424 4117 $dirlines -= $linecount;
425 }
426 # PRE_CHOMP: process whitespace before tag
427 4131 ▶ $chomp = $1 ? $1 : $prechomp;
Branch: 1 branch
BranchTrueFalseTotal
$1 ? : 121 4010 4131
428 4131 $chomp =~ tr/-=~+/1230/;
429 4131 ▶ if ($chomp && $pre) {
Branch: 1 branch
BranchTrueFalseTotal
if ($chomp and $pre) 120 4011 4131
Condition100%3/3
$chomp and $pre
!ll&&!rl&&r
399021120
MC/DC100%2/2
$chomp and $pre
$chomp $pre
Truth table100%3/3
A and B
A= $chompB= $pre
ABresult
0X0
100
111
430 # chomp off whitespace and newline preceding directive
431 120 ▶ if ($chomp == CHOMP_ALL) {
Branch: 3 branches
BranchTrueFalseTotal
if ($chomp == 1) { } 111 9 120
elsif ($chomp == 2) { } 6 3 9
elsif ($chomp == 3) { } 3 0 3
432 111 $pre =~ s{ (\r?\n|^) [^\S\n]* \z }{}mx;
433 }
434 elsif ($chomp == CHOMP_COLLAPSE) {
435 6 $pre =~ s{ (\s+) \z }{ }x;
436 }
437 elsif ($chomp == CHOMP_GREEDY) {
438 3 $pre =~ s{ (\s+) \z }{}x;
439 }
440 }
441 }
442  
443 # POST_CHOMP: process whitespace after tag
444 4142 s/\s*($CHOMP_FLAGS)?\s*$//so;
445 4142 ▶ $chomp = $1 ? $1 : $postchomp;
Branch: 1 branch
BranchTrueFalseTotal
$1 ? : 1165 2977 4142
446 4142 $chomp =~ tr/-=~+/1230/;
447 4142 ▶ if ($chomp) {
Branch: 1 branch
BranchTrueFalseTotal
if ($chomp) 2011 2131 4142
448 2011 ▶ if ($chomp == CHOMP_ALL) {
Branch: 3 branches
BranchTrueFalseTotal
if ($chomp == 1) { } 2002 9 2011
elsif ($chomp == 2) { } 6 3 9
elsif ($chomp == 3) { } 3 0 3
449 2002 ▶ $text =~ s{ ^ ([^\S\n]* \n) }{}x
Branch: 1 branch
BranchTrueFalseTotal
$text =~ s/ ^ ([^\S\n]* \n) //x and ++$postlines 1850 152 2002
450 && $postlines++;
451 }
452 elsif ($chomp == CHOMP_COLLAPSE) {
453 6 ▶ $text =~ s{ ^ (\s+) }{ }x
Branch: 1 branch
BranchTrueFalseTotal
$text =~ s/ ^ (\s+) / /x and $postlines += $1 =~ tr/\n// 6 0 6
454 && ($postlines += $1=~y/\n//);
455 }
456 # any trailing whitespace
457 elsif ($chomp == CHOMP_GREEDY) {
458 3 ▶ $text =~ s{ ^ (\s+) }{}x
Branch: 1 branch
BranchTrueFalseTotal
$text =~ s/ ^ (\s+) //x and $postlines += $1 =~ tr/\n// 3 0 3
459 && ($postlines += $1=~y/\n//);
460 }
461 }
462 }
463  
464 # any text preceding the directive can now be added
465 4142 ▶ if (length $pre) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $pre) 2213 1929 4142
466 2213 ▶ push(@tokens, $interp
Branch: 1 branch
BranchTrueFalseTotal
$interp ? : 533 1680 2213
467 ? [ $pre, $line, 'ITEXT' ]
468 : ('TEXT', $pre) );
469 }
470 4142 $line += $prelines;
471  
472 # and now the directive, along with line number information
473 4142 ▶ if (length $dir) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $dir) 4127 15 4142
474 # the TAGS directive is a compile-time switch
475 4127 ▶ if ($dir =~ /^$tags_dir\s+(.*)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dir =~ /^$tags_dir\s+(.*)/) { } 19 4108 4127
476 19 my @tags = split(/\s+/, $1);
477 19 ▶ if (scalar @tags > 1) {
Branch: 2 branches
BranchTrueFalseTotal
if (scalar @tags > 1) { } 8 11 19
elsif ($tags = $$Template::Parser::TAG_STYLE{$tags[0]}) { } 11 0 11
478 8 ($start, $end, $out) = map { quotemeta($_) } @tags;
479 8 $split = $self->text_splitter($start, $end, $out);
480 }
481 elsif ($tags = $TAG_STYLE->{ $tags[0] }) {
482 11 ($start, $end, $out) = @$tags;
483 11 $split = $self->text_splitter($start, $end, $out);
484 }
485 else {
486 0 warn "invalid TAGS style: $tags[0]\n";
487 }
488 }
489 else {
490 # DIRECTIVE is pushed as:
491 # [ $dirtext, $line_no(s), \@tokens ]
492 4108 ▶ push(@tokens,
Branch: 1 branch
BranchTrueFalseTotal
$dirlines ? : 246 3862 4108
493 [ $dir,
494 ($dirlines
495 ? sprintf("%d-%d", $line, $line + $dirlines)
496 : $line),
497 $self->tokenise_directive($dir) ]);
498 }
499 }
500  
501 # update line counter to include directive lines and any extra
502 # newline chomped off the start of the following text
503 4142 $line += $dirlines + $postlines;
504 }
505  
506 # anything remaining in the string is plain text
507 1424 ▶ push(@tokens, $interp
Branch: 2 branches
BranchTrueFalseTotal
if length $text 997 427 1424
$interp ? : 217 780 997
508 ? [ $text, $line, 'ITEXT' ]
509 : ( 'TEXT', $text) )
510 if length $text;
511  
512 1424 return \@tokens; ## RETURN ##
513 }
514  
515  
516  
517 #------------------------------------------------------------------------
518 # interpolate_text($text, $line)
519 #
520 # Examines $text looking for any variable references embedded like
521 # $this or like ${ this }.
522 #------------------------------------------------------------------------
523  
524 sub interpolate_text {
525 910 ▶ my ($self, $text, $line) = @_;
Subroutine interpolate_text: called CC=7 SCAR=19.6
Pod undocumented
526 910 my @tokens = ();
527 910 my ($pre, $var, $dir);
528  
529  
530 910 ▶ while ($text =~
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ / ( (?: \\. | [^\$] ){1,3000} ) # escaped or non-'$' character [$1] | ( \$ (?: # embedded variable [$2] (?: \{ ([^\}]*) \} ) # ${ ... } [$3] | ([\w\.]+) # $word [$4] ) ) /gx) 1414 910 2324
531 /
532 ( (?: \\. | [^\$] ){1,3000} ) # escaped or non-'$' character [$1]
533 |
534 ( \$ (?: # embedded variable [$2]
535 (?: \{ ([^\}]*) \} ) # ${ ... } [$3]
536 |
537 ([\w\.]+) # $word [$4]
538 )
539 )
540 /gx) {
541  
542 1414 ▶ ($pre, $var, $dir) = ($1, $3 || $4, $2);
Condition100%3/3
$3 || $4
l!l&&r!l&&!r
412701103
MC/DC100%2/2
$3 || $4
$3 $4
Truth table100%3/3
A || B
A= $3B= $4
ABresult
1X1
011
000
543  
544 # preceding text
545 1414 ▶ if (defined($pre) && length($pre)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $pre and length $pre) 1103 311 1414
Condition66%2/3
defined $pre and length $pre
!ll&&!rl&&r
31101103
MC/DC50%1/2
defined $pre and length $pre
defined $pre length $pre
Truth table66%2/3
A and B
A= defined $preB= length $pre
ABresult
0X0
100
111
546 1103 $line += $pre =~ tr/\n//;
547 1103 $pre =~ s/\\\$/\$/g;
548 1103 push(@tokens, 'TEXT', $pre);
549 }
550 # $variable reference
551 1414 ▶ if ($var) {
Branch: 2 branches
BranchTrueFalseTotal
if ($var) { } 311 1103 1414
elsif ($dir) { } 0 1103 1103
552 311 $line += $dir =~ tr/\n/ /;
553 311 push(@tokens, [ $dir, $line, $self->tokenise_directive($var) ]);
554 }
555 # other '$' reference - treated as text
556 elsif ($dir) {
557 0 $line += $dir =~ tr/\n//;
558 0 push(@tokens, 'TEXT', $dir);
559 }
560 }
561  
562 910 return \@tokens;
563 }
564  
565  
566  
567 #------------------------------------------------------------------------
568 # tokenise_directive($text)
569 #
570 # Called by the private _parse() method when it encounters a DIRECTIVE
571 # token in the list provided by the split_text() or interpolate_text()
572 # methods. The directive text is passed by parameter.
573 #
574 # The method splits the directive into individual tokens as recognised
575 # by the parser grammar (see Template::Grammar for details). It
576 # constructs a list of tokens each represented by 2 elements, as per
577 # split_text() et al. The first element contains the token type, the
578 # second the token itself.
579 #
580 # The method tokenises the string using a complex (but fast) regex.
581 # For a deeper understanding of the regex magic at work here, see
582 # Jeffrey Friedl's excellent book "Mastering Regular Expressions",
583 # from O'Reilly, ISBN 1-56592-257-3
584 #
585 # Returns a reference to the list of chunks (each one being 2 elements)
586 # identified in the directive text. On error, the internal _ERROR string
587 # is set and undef is returned.
588 #------------------------------------------------------------------------
589  
590 sub tokenise_directive {
591 4419 ▶ my ($self, $text, $line) = @_;
Subroutine tokenise_directive: called CC=18 SCAR=28.9
Pod undocumented
592 4419 my ($token, $uctoken, $type, $lookup);
593 4419 my $lextable = $self->{ LEXTABLE };
594 4419 my $style = $self->{ STYLE }->[-1];
595 4419 my ($anycase, $start, $end) = @$style{ qw( ANYCASE START_TAG END_TAG ) };
596 4419 my @tokens = ( );
597  
598 4419 ▶ while ($text =~
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ m( # strip out any comments (\#[^\n]*) | # a quoted phrase matches in $3 (["']) # $2 - opening quote, ' or " ( # $3 - quoted text buffer (?: # repeat group (no backreference) \\\\ # an escaped backslash \\ | # ...or... \\\2 # an escaped quote \" or \' (match $1) | # ...or... . # any other character | \n )*? # non-greedy repeat ) # end of $3 \2 # match opening quote | # an unquoted number matches in $4 (-?\d+(?:\.\d+)?) # numbers | # filename matches in $5 ( /?\w+(?:(?:/|::?)\w*)+ | /\w+) | # an identifier matches in $6 (\w+) # variable identifier | # an unquoted word or symbol matches in $7 ( [(){}\[\]:;,/\\] # misc parenthesis and symbols # | \-> # arrow operator (for future?) | [+\-*] # math operations | \$\{? # dollar with option left brace | => # like '=' | [=!<>]?= | [!<>] # eqality tests | &&? | \|\|? # boolean ops | \.\.? # n..n sequence | \S+ # something unquoted ) # end of $7 )gmox) 18540 4419 22959
599 /
600 # strip out any comments
601 (\#[^\n]*)
602 |
603 # a quoted phrase matches in $3
604 (["']) # $2 - opening quote, ' or "
605 ( # $3 - quoted text buffer
606 (?: # repeat group (no backreference)
607 \\\\ # an escaped backslash \\
608 | # ...or...
609 \\\2 # an escaped quote \" or \' (match $1)
610 | # ...or...
611 . # any other character
612 | \n
613 )*? # non-greedy repeat
614 ) # end of $3
615 \2 # match opening quote
616 |
617 # an unquoted number matches in $4
618 (-?\d+(?:\.\d+)?) # numbers
619 |
620 # filename matches in $5
621 ( \/?\w+(?:(?:\/|::?)\w*)+ | \/\w+)
622 |
623 # an identifier matches in $6
624 (\w+) # variable identifier
625 |
626 # an unquoted word or symbol matches in $7
627 ( [(){}\[\]:;,\/\\] # misc parenthesis and symbols
628 # | \-> # arrow operator (for future?)
629 | [+\-*] # math operations
630 | \$\{? # dollar with option left brace
631 | => # like '='
632 | [=!<>]?= | [!<>] # eqality tests
633 | &&? | \|\|? # boolean ops
634 | \.\.? # n..n sequence
635 | \S+ # something unquoted
636 ) # end of $7
637 /gmxo) {
638  
639 # ignore comments to EOL
640 18540 ▶ next if $1;
Branch: 1 branch
BranchTrueFalseTotal
if $1 25 18515 18540
641  
642 # quoted string
643 18515 ▶ if (defined ($token = $3)) {
Branch: 5 branches
BranchTrueFalseTotal
if (defined($token = $3)) { } 1439 17076 18515
elsif (defined($token = $4)) { } 774 16302 17076
elsif (defined($token = $5)) { } 26 16276 16302
elsif (defined($token = $6)) { } 9618 6658 16276
elsif (defined($token = $7)) { } 6658 0 6658
644 # double-quoted string may include $variable references
645 1439 ▶ if ($2 eq '"') {
Branch: 1 branch
BranchTrueFalseTotal
if ($2 eq '"') { } 348 1091 1439
646 348 ▶ if ($token =~ /[\$\\]/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($token =~ /[\$\\]/) { } 174 174 348
647 174 $type = 'QUOTED';
648 # unescape " and \ but leave \$ escaped so that
649 # interpolate_text() doesn't incorrectly treat it
650 # as a variable reference
651 # $token =~ s/\\([\\"])/$1/g;
652 174 for ($token) {
653 174 s/\\([^\$nrt])/$1/g;
654 174 s/\\([nrt])/$QUOTED_ESCAPES->{ $1 }/ge;
655 }
656 push(@tokens, ('"') x 2,
657 174 @{ $self->interpolate_text($token) },
658 ('"') x 2);
659 174 next;
660 }
661 else {
662 174 $type = 'LITERAL';
663 174 $token =~ s['][\\']g;
664 174 $token = "'$token'";
665 }
666 }
667 else {
668 1091 $type = 'LITERAL';
669 1091 $token = "'$token'";
670 }
671 }
672 # number
673 elsif (defined ($token = $4)) {
674 774 $type = 'NUMBER';
675 }
676 elsif (defined($token = $5)) {
677 26 $type = 'FILENAME';
678 }
679 elsif (defined($token = $6)) {
680 # Fold potential keywords to UPPER CASE if the ANYCASE option is
681 # set, unless (we've got some preceding tokens and) the previous
682 # token is a DOT op. This prevents the 'last' in 'data.last'
683 # from being interpreted as the LAST keyword.
684 9618 ▶ if ($anycase) {
Branch: 1 branch
BranchTrueFalseTotal
if ($anycase) { } 827 8791 9618
685 # if the token follows a dot or precedes an assignment then
686 # it's not for folding, e.g. the 'wrapper' in this:
687 # [% page = { wrapper='html' }; page.wrapper %]
688 827 ▶ if ((@tokens && $ANYCASE_AFTER->{ $tokens[-2] })
Branch: 1 branch
BranchTrueFalseTotal
if (@tokens and $$Template::Parser::ANYCASE_AFTER{$tokens[-2]} or $text =~ /$Template::Parser::ANYCASE_BEFORE/cg) { } 495 332 827
Condition100%6/6
@tokens and $$Template::Parser::ANYCASE_AFTER{$tokens[-2]} or $text =~ /$Template::Parser::ANYCASE_BEFORE/cg
l!l&&r!l&&!r
281214332
@tokens and $$Template::Parser::ANYCASE_AFTER{$tokens[-2]}
!ll&&!rl&&r
383163281
MC/DC100%3/3
@tokens and $$Template::Parser::ANYCASE_AFTER{$tokens[-2]} or $text =~ /$Template::Parser::ANYCASE_BEFORE/cg
@tokens $$Template::Parser::ANYCASE_AFTER{$tokens[-2]} $text =~ /$Template::Parser::ANYCASE_BEFORE/cg
Truth table100%5/5
A and B or C
A= @tokensB= $$Template::Parser::ANYCASE_AFTER{$tokens[-2]}C= $text =~ /$Template::Parser::ANYCASE_BEFORE/cg
ABCresult
11X1
0X11
1011
0X00
1000
689 || ($text =~ /$ANYCASE_BEFORE/gc)) {
690 # keep the token unmodified
691 495 $uctoken = $token;
692 }
693 else {
694 332 $uctoken = uc $token;
695 }
696 }
697 else {
698 8791 $uctoken = $token;
699 }
700 9618 ▶ if (defined ($type = $lextable->{ $uctoken })) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($type = $lextable->{$uctoken})) { } 2553 7065 9618
701 2553 $token = $uctoken;
702 }
703 else {
704 7065 $type = 'IDENT';
705 }
706 }
707 elsif (defined ($token = $7)) {
708 # reserved words may be in lower case unless case sensitive
709 6658 ▶ $uctoken = $anycase ? uc $token : $token;
Branch: 1 branch
BranchTrueFalseTotal
$anycase ? : 553 6105 6658
710 6658 ▶ unless (defined ($type = $lextable->{ $uctoken })) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined($type = $lextable->{$uctoken})) 0 6658 6658
711 0 $type = 'UNQUOTED';
712 }
713 }
714  
715 18341 push(@tokens, $type, $token);
716  
717 # print(STDERR " +[ $type, $token ]\n")
718 # if $DEBUG;
719 }
720  
721 # print STDERR "tokenise directive() returning:\n [ @tokens ]\n"
722 # if $DEBUG;
723  
724 4419 return \@tokens; ## RETURN ##
725 }
726  
727  
728 #------------------------------------------------------------------------
729 # define_block($name, $block)
730 #
731 # Called by the parser 'defblock' rule when a BLOCK definition is
732 # encountered in the template. The name of the block is passed in the
733 # first parameter and a reference to the compiled block is passed in
734 # the second. This method stores the block in the $self->{ DEFBLOCK }
735 # hash which has been initialised by parse() and will later be used
736 # by the same method to call the store() method on the calling cache
737 # to define the block "externally".
738 #------------------------------------------------------------------------
739  
740 sub define_block {
741 162 ▶ my ($self, $name, $block) = @_;
Subroutine define_block: called CC=4 SCAR=14.0
Pod undocumented
742 my $defblock = $self->{ DEFBLOCK }
743 162 ▶ || return undef;
Condition50%1/2
$self->{'DEFBLOCK'} || (return undef)
l!l
1620
MC/DC0%0/1
$self->{'DEFBLOCK'} || (return undef)
$self->{'DEFBLOCK'}
Truth table50%1/2
A
A= $self->{'DEFBLOCK'}
Aresult
11
00
744  
745 $self->debug("compiled block '$name':\n$block")
746 162 ▶ if $self->{ DEBUG } & Template::Constants::DEBUG_PARSER;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"DEBUG"} & 64 0 162 162
747  
748 162 ▶ warn "Block redefined: $name\n" if exists $defblock->{ $name };
Branch: 1 branch
BranchTrueFalseTotal
if exists $defblock->{$name} 1 161 162
749  
750 162 $defblock->{ $name } = $block;
751  
752 162 return undef;
753 }
754  
755 sub push_defblock {
756 31 ▶ my $self = shift;
Subroutine push_defblock: called CC=2 SCAR=6.9
Pod undocumented
757 31 ▶ my $stack = $self->{ DEFBLOCK_STACK } ||= [];
Condition100%2/2
$self->{"DEFBLOCK_STACK"} ||= []
l!l
283
MC/DC100%1/1
$self->{"DEFBLOCK_STACK"} ||= []
$self->{"DEFBLOCK_STACK"}
Truth table100%2/2
A
A= $self->{"DEFBLOCK_STACK"}
Aresult
11
00
758 31 push(@$stack, $self->{ DEFBLOCK } );
759 31 $self->{ DEFBLOCK } = { };
760 }
761  
762 sub pop_defblock {
763 31 ▶ my $self = shift;
Subroutine pop_defblock: called CC=3 SCAR=11.2
Pod undocumented
764 31 my $defs = $self->{ DEFBLOCK };
765 31 ▶ my $stack = $self->{ DEFBLOCK_STACK } || return $defs;
Condition50%1/2
$self->{'DEFBLOCK_STACK'} || (return $defs)
l!l
310
MC/DC0%0/1
$self->{'DEFBLOCK_STACK'} || (return $defs)
$self->{'DEFBLOCK_STACK'}
Truth table50%1/2
A
A= $self->{'DEFBLOCK_STACK'}
Aresult
11
00
766 31 ▶ return $defs unless @$stack;
Branch: 1 branch
BranchTrueFalseTotal
unless @$stack 0 31 31
767 31 $self->{ DEFBLOCK } = pop @$stack;
768 31 return $defs;
769 }
770  
771  
772 #------------------------------------------------------------------------
773 # add_metadata(\@setlist)
774 #------------------------------------------------------------------------
775  
776 sub add_metadata {
777 26 ▶ my ($self, $setlist) = @_;
Subroutine add_metadata: called CC=2 SCAR=7.0
Pod undocumented
778 my $metadata = $self->{ METADATA }
779 26 ▶ || return undef;
Condition50%1/2
$self->{'METADATA'} || (return undef)
l!l
260
MC/DC0%0/1
$self->{'METADATA'} || (return undef)
$self->{'METADATA'}
Truth table50%1/2
A
A= $self->{'METADATA'}
Aresult
11
00
780  
781 26 push(@$metadata, @$setlist);
782  
783 26 return undef;
784 }
785  
786  
787 #------------------------------------------------------------------------
788 # location()
789 #
790 # Return Perl comment indicating current parser file and line
791 #------------------------------------------------------------------------
792  
793 sub location {
794 3776 ▶ my $self = shift;
Subroutine location: called CC=5 SCAR=16.1
Pod undocumented
795 3776 ▶ return "\n" unless $self->{ FILE_INFO };
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"FILE_INFO"} 13 3763 3776
796 3763 my $line = ${ $self->{ LINE } };
797 3763 my $info = $self->{ FILEINFO }->[-1];
798 my $file = $info->{ path } || $info->{ name }
799 3763 ▶ || '(unknown template)';
Condition100%5/5
$info->{'path'} || $info->{'name'} || '(unknown template)'
l!l
37558
$info->{"path"} or $info->{"name"}
l!l&&r!l&&!r
375148
MC/DC100%2/2
$info->{'path'} || $info->{'name'} || '(unknown template)'
$info->{"path"} $info->{"name"}
Truth table100%3/3
A or B
A= $info->{"path"}B= $info->{"name"}
ABresult
1X1
011
000
800 3763 $line =~ s/\-.*$//; # might be 'n-n'
801 3763 ▶ $line ||= 1;
Condition100%2/2
$line ||= 1
l!l
3591172
MC/DC100%1/1
$line ||= 1
$line
Truth table100%2/2
A
A= $line
Aresult
11
00
802 3763 return "#line $line \"$file\"\n";
803 }
804  
805  
806 #========================================================================
807 # ----- PRIVATE METHODS -----
808 #========================================================================
809  
810 #------------------------------------------------------------------------
811 # _parse(\@tokens, \@info)
812 #
813 # Parses the list of input tokens passed by reference and returns a
814 # Template::Directive::Block object which contains the compiled
815 # representation of the template.
816 #
817 # This is the main parser DFA loop. See embedded comments for
818 # further details.
819 #
820 # On error, undef is returned and the internal _ERROR field is set to
821 # indicate the error. This can be retrieved by calling the error()
822 # method.
823 #------------------------------------------------------------------------
824  
825 sub _parse {
826 1431 ▶ my ($self, $tokens, $info) = @_;
Subroutine _parse: called CC=27 SCAR=33.0
827 1431 my ($token, $value, $text, $line, $inperl);
828 1431 my ($state, $stateno, $status, $action, $lookup, $coderet, @codevars);
829 1431 my ($lhs, $len, $code); # rule contents
830 1431 my $stack = [ [ 0, undef ] ]; # DFA stack
831  
832 # DEBUG
833 # local $" = ', ';
834  
835 # retrieve internal rule and state tables
836 1431 my ($states, $rules) = @$self{ qw( STATES RULES ) };
837  
838 # If we're tracing variable usage then we need to give the factory a
839 # reference to our $self->{ VARIABLES } for it to fill in. This is a
840 # bit of a hack to back-patch this functionality into TT2.
841 $self->{ FACTORY }->trace_vars($self->{ VARIABLES })
842 1431 ▶ if $self->{ TRACE_VARS };
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"TRACE_VARS"} 1 1430 1431
843  
844 # call the grammar set_factory method to install emitter factory
845 1431 $self->{ GRAMMAR }->install_factory($self->{ FACTORY });
846  
847 1431 $line = $inperl = 0;
848 1431 $self->{ LINE } = \$line;
849 1431 $self->{ FILE } = $info->{ name };
850 1431 $self->{ INPERL } = \$inperl;
851  
852 1431 $status = CONTINUE;
853 1431 my $in_string = 0;
854  
855 1431 while(1) {
856 # get state number and state
857 100296 $stateno = $stack->[-1]->[0];
858 100296 $state = $states->[$stateno];
859  
860 # see if any lookaheads exist for the current state
861 100296 ▶ if (exists $state->{'ACTIONS'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $state->{'ACTIONS'}) { } 47920 52376 100296
862  
863 # get next token and expand any directives (i.e. token is an
864 # array ref) onto the front of the token list
865 47920 ▶ while (! defined $token && @$tokens) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $token and @$tokens) 32002 47920 79922
Condition100%3/3
not defined $token and @$tokens
!ll&&!rl&&r
46491142932002
MC/DC100%2/2
not defined $token and @$tokens
not defined $token @$tokens
Truth table100%3/3
not(A) and B
A= not defined $tokenB= @$tokens
ABresult
0X0
100
111
866 32002 $token = shift(@$tokens);
867 32002 ▶ if (ref $token) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $token) { } 5165 26837 32002
868 5165 ($text, $line, $token) = @$token;
869 5165 ▶ if (ref $token) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $token) { } 4416 749 5165
elsif ($token eq 'ITEXT') { } 749 0 749
870 4416 ▶ if ($info->{ DEBUG } && ! $in_string) {
Branch: 1 branch
BranchTrueFalseTotal
if ($info->{'DEBUG'} and not $in_string) { } 15 4401 4416
Condition100%3/3
$info->{"DEBUG"} and not $in_string
!ll&&!rl&&r
4399215
MC/DC100%2/2
$info->{"DEBUG"} and not $in_string
$info->{"DEBUG"} not $in_string
Truth table100%3/3
A and not(B)
A= $info->{"DEBUG"}B= not $in_string
ABresult
0X0
100
111
871 # - - - - - - - - - - - - - - - - - - - - - - - - -
872 # This is gnarly. Look away now if you're easily
873 # frightened. We're pushing parse tokens onto the
874 # pending list to simulate a DEBUG directive like so:
875 # [% DEBUG msg line='20' text='INCLUDE foo' %]
876 # - - - - - - - - - - - - - - - - - - - - - - - - -
877 15 my $dtext = $text;
878 15 $dtext =~ s[(['\\])][\\$1]g;
879 15 unshift(@$tokens,
880 DEBUG => 'DEBUG',
881 IDENT => 'msg',
882 IDENT => 'line',
883 ASSIGN => '=',
884 LITERAL => "'$line'",
885 IDENT => 'text',
886 ASSIGN => '=',
887 LITERAL => "'$dtext'",
888 IDENT => 'file',
889 ASSIGN => '=',
890 LITERAL => "'$info->{ name }'",
891 (';') x 2,
892 @$token,
893 (';') x 2);
894 }
895 else {
896 4401 unshift(@$tokens, @$token, (';') x 2);
897 }
898 4416 $token = undef; # force redo
899 }
900 elsif ($token eq 'ITEXT') {
901 749 ▶ if ($inperl) {
Branch: 1 branch
BranchTrueFalseTotal
if ($inperl) { } 13 736 749
902 # don't perform interpolation in PERL blocks
903 13 $token = 'TEXT';
904 13 $value = $text;
905 }
906 else {
907 unshift(@$tokens,
908 736 @{ $self->interpolate_text($text, $line) });
909 736 $token = undef; # force redo
910 }
911 }
912 }
913 else {
914 # toggle string flag to indicate if we're crossing
915 # a string boundary
916 26837 ▶ $in_string = ! $in_string if $token eq '"';
Branch: 1 branch
BranchTrueFalseTotal
if $token eq "\"" 348 26489 26837
917 26837 $value = shift(@$tokens);
918 }
919 };
920 # clear undefined token to avoid 'undefined variable blah blah'
921 # warnings and let the parser logic pick it up in a minute
922 47920 ▶ $token = '' unless defined $token;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $token 1429 46491 47920
923  
924 # get the next state for the current lookahead token
925 $action = defined ($lookup = $state->{'ACTIONS'}->{ $token })
926 ? $lookup
927 47920 ▶ : defined ($lookup = $state->{'DEFAULT'})
Branch: 2 branches
BranchTrueFalseTotal
defined($lookup = $state->{'ACTIONS'}{$token}) ? : 31437 16483 47920
defined($lookup = $state->{'DEFAULT'}) ? : 16480 3 16483
928 ? $lookup
929 : undef;
930 }
931 else {
932 # no lookahead actions
933 52376 $action = $state->{'DEFAULT'};
934 }
935  
936 # ERROR: no ACTION
937 100296 ▶ last unless defined $action;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $action 3 100293 100296
938  
939 # - - - - - - - - - - - - - - - - - - - - - - - - - - - -
940 # shift (+ive ACTION)
941 # - - - - - - - - - - - - - - - - - - - - - - - - - - - -
942 100293 ▶ if ($action > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($action > 0) 28276 72017 100293
943 28276 push(@$stack, [ $action, $value ]);
944 28276 $token = $value = undef;
945 28276 redo;
946 };
947  
948 # - - - - - - - - - - - - - - - - - - - - - - - - - - - -
949 # reduce (-ive ACTION)
950 # - - - - - - - - - - - - - - - - - - - - - - - - - - - -
951 72017 ($lhs, $len, $code) = @{ $rules->[ -$action ] };
952  
953 # no action imples ACCEPTance
954 72017 ▶ $action
Branch: 1 branch
BranchTrueFalseTotal
$action or $status = 1 1428 70589 72017
955 or $status = ACCEPT;
956  
957 # use dummy sub if code ref doesn't exist
958 72017 ▶ if ( !$code ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $code) { } 23321 48696 72017
959 23321 ▶ $coderet = $len ? $stack->[ -$len ]->[1] : undef;
Branch: 1 branch
BranchTrueFalseTotal
$len ? : 23090 231 23321
960 } else {
961 # $code = sub { $_[1] }
962 # unless $code;
963  
964 @codevars = $len
965 48696 ▶ ? map { $_->[1] } @$stack[ -$len .. -1 ]
Branch: 1 branch
BranchTrueFalseTotal
$len ? : 46609 2087 48696
966 : ();
967  
968 48696 eval {
969 48696 $coderet = &$code( $self, @codevars );
970 };
971 48696 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 48696 48696
972 0 my $err = $@;
973 0 chomp $err;
974 0 return $self->_parse_error($err);
975 }
976 }
977  
978  
979 # reduce stack by $len
980 72017 splice(@$stack, -$len, $len);
981  
982 # ACCEPT
983 72017 ▶ return $coderet ## RETURN ##
Branch: 1 branch
BranchTrueFalseTotal
if $status == 1 1428 70589 72017
984 if $status == ACCEPT;
985  
986 # ABORT
987 return undef ## RETURN ##
988 70589 ▶ if $status == ABORT;
Branch: 1 branch
BranchTrueFalseTotal
if $status == 3 0 70589 70589
989  
990 # ERROR
991 last
992 70589 ▶ if $status == ERROR;
Branch: 1 branch
BranchTrueFalseTotal
if $status == 2 0 70589 70589
993 }
994 continue {
995 70589 push(@$stack, [ $states->[ $stack->[-1][0] ]->{'GOTOS'}->{ $lhs },
996 $coderet ]),
997 }
998  
999 # ERROR ## RETURN ##
1000 3 ▶ return $self->_parse_error('unexpected end of input')
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 1 2 3
1001 unless defined $value;
1002  
1003 # munge text of last directive to make it readable
1004 # $text =~ s/\n/\\n/g;
1005  
1006 2 ▶ return $self->_parse_error("unexpected end of directive", $text)
Branch: 1 branch
BranchTrueFalseTotal
if $value eq ";" 0 2 2
1007 if $value eq ';'; # end of directive SEPARATOR
1008  
1009 2 return $self->_parse_error("unexpected token ($value)", $text);
1010 }
1011  
1012  
1013  
1014 #------------------------------------------------------------------------
1015 # _parse_error($msg, $dirtext)
1016 #
1017 # Method used to handle errors encountered during the parse process
1018 # in the _parse() method.
1019 #------------------------------------------------------------------------
1020  
1021 sub _parse_error {
1022 3 ▶ my ($self, $msg, $text) = @_;
Subroutine _parse_error: called CC=4 SCAR=14.0
1023 3 my $line = $self->{ LINE };
1024 3 ▶ $line = ref($line) ? $$line : $line;
Branch: 1 branch
BranchTrueFalseTotal
ref $line ? : 3 0 3
1025 3 ▶ $line = 'unknown' unless $line;
Branch: 1 branch
BranchTrueFalseTotal
unless $line 0 3 3
1026  
1027 3 ▶ $msg .= "\n [% $text %]"
Branch: 1 branch
BranchTrueFalseTotal
if defined $text 2 1 3
1028 if defined $text;
1029  
1030 3 return $self->error("line $line: $msg");
1031 }
1032  
1033 102 1;
1034  
1035 __END__
« lib/Template/Plugin/Date.pm ↑ Summary lib/Template/Context.pm »