blib/lib/YASF.pm

filter: Statementstmt 89.4% 127 / 142 Branchbran 76.4% 52 / 68 Conditioncond 100% 6 / 6 MC/DCmcdc 100% 4 / 4 Subroutinesub 81.4% 22 / 27 Podpod 100% 4 / 4 totaltotal 85.6% 215 / 251 CC 39 SCAR 15.5
CC
39
Cov
86%
_compile
8.6
_expr_to_value
8.0
bind
6.0
CRAP 4.7
↑ Summary
1 ###############################################################################
2 #
3 # This file copyright © 2016 by Randy J. Ray, all rights reserved
4 #
5 # See "LICENSE AND COPYRIGHT" in the POD for terms.
6 #
7 ###############################################################################
8 #
9 # Description: A string-formatter inspired by Python's format()
10 #
11 # Functions: YASF
12 # new
13 # bind
14 # format
15 #
16 # Libraries: None (only core)
17 #
18 # Global Consts: @EXPORT_OK
19 # %NOT_ACCEPTABLE_REF
20 #
21 # Environment: None
22 #
23 ###############################################################################
24  
25 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
27  
28 package YASF;
29 5 $YASF::VERSION = '0.003';
30 5 ▶use 5.008;
Subroutine BEGIN: called CC=1 SCAR=0.0
31 5 use overload fallback => 0,
32 'eq' => \&_eq,
33 'ne' => \&_ne,
34 'lt' => \&_lt,
35 'le' => \&_le,
36 'gt' => \&_gt,
37 'ge' => \&_ge,
38 'cmp' => \&_cmp,
39 q{""} => \&_stringify,
40 5 ▶ q{%} => \&_interpolate;
Subroutine BEGIN: called CC=1 SCAR=0.0
41  
42 5 ▶use Carp qw(carp croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
43 5 ▶use English qw(-no_match_vars);
Subroutine BEGIN: called CC=1 SCAR=0.0
44 5 ▶use Exporter qw(import);
Subroutine BEGIN: called CC=1 SCAR=0.0
45  
46 BEGIN {
47 5 ▶ no strict 'refs'; ## no critic (ProhibitNoStrict)
Subroutine BEGIN: called CC=1 SCAR=0.0
48  
49 5 ▶ for my $method (qw(template binding)) {
Subroutine BEGIN: called CC=2 SCAR=6.9
50 10 ▶ *{$method} = sub { shift->{$method} }
Subroutine __ANON__: called CC=1 SCAR=0.0
51 10 }
52 }
53  
54 5 my %NOT_ACCEPTABLE_REF = (
55 SCALAR => 1,
56 CODE => 1,
57 REF => 1,
58 GLOB => 1,
59 LVALUE => 1,
60 FORMAT => 1,
61 IO => 1,
62 VSTRING => 1,
63 Regexp => 1,
64 );
65  
66 5 our @EXPORT_OK = qw(YASF);
67  
68 ###############################################################################
69 #
70 # Sub Name: YASF
71 #
72 # Description: Shortcut to calling YASF->new($str) with no other args.
73 #
74 # Arguments: NAME IN/OUT TYPE DESCRIPTION
75 # $template in scalar String template for formatter
76 #
77 # Returns: Success: new object
78 # Failure: dies
79 #
80 ###############################################################################
81 ## no critic(ProhibitSubroutinePrototypes)
82 2 ▶sub YASF ($) { return YASF->new(shift); }
Subroutine YASF: called CC=1 SCAR=0.0
Pod documented
83  
84 ###############################################################################
85 #
86 # Sub Name: new
87 #
88 # Description: Class constructor. Creates the basic object and
89 # pre-compiles the template into the form that the formatter
90 # uses.
91 #
92 # Arguments: NAME IN/OUT TYPE DESCRIPTION
93 # $class in scalar Name of class
94 # $template in scalar String template for formatter
95 # @args in scalar Everything else (see code)
96 #
97 # Returns: Success: new object
98 # Failure: dies
99 #
100 ###############################################################################
101 sub new {
102 11 ▶ my ($class, $template, @args) = @_;
Subroutine new: called CC=4 SCAR=13.9
Pod documented
103  
104 11 ▶ croak "${class}::new requires string template argument"
Branch: 1 branch
BranchTrueFalseTotal
unless $template 1 10 11
105 if (! $template);
106  
107 10 ▶ my $args = @args == 1 ? $args[0] : { @args };
Branch: 1 branch
BranchTrueFalseTotal
@args == 1 ? : 0 10 10
108 10 my $self = bless { template => $template, binding => undef }, $class;
109  
110 10 $self->_compile;
111 10 ▶ if ($args->{binding}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"binding"}) 1 9 10
112 1 $self->bind($args->{binding});
113 }
114  
115 10 return $self;
116 }
117  
118 ###############################################################################
119 #
120 # Sub Name: bind
121 #
122 # Description: Add or change object-level bindings
123 #
124 # Arguments: NAME IN/OUT TYPE DESCRIPTION
125 # $self in ref Object of this class
126 # $bindings in ref New bindings
127 #
128 # Globals: %NOT_ACCEPTABLE_REF
129 #
130 # Returns: Success: $self
131 # Failure: dies
132 #
133 ###############################################################################
134 sub bind { ## no critic(ProhibitBuiltinHomonyms)
135 11 ▶ my ($self, $bindings) = @_;
Subroutine bind: called CC=6 SCAR=17.9
Pod documented
136  
137 11 ▶ if ((@_ == 2) && (! defined $bindings)) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 2 and not defined $bindings) { } 1 10 11
Condition100%3/3
@_ == 2 and not defined $bindings
!ll&&!rl&&r
191
MC/DC100%2/2
@_ == 2 and not defined $bindings
@_ == 2 not defined $bindings
Truth table100%3/3
A and not(B)
A= @_ == 2B= not defined $bindings
ABresult
0X0
100
111
138 # The means of unbinding is to call $obj->bind(undef):
139 1 undef $self->{binding};
140 } else {
141 10 ▶ croak 'bind: New bindings must be provided as a parameter'
Branch: 1 branch
BranchTrueFalseTotal
unless $bindings 1 9 10
142 if (! $bindings);
143  
144 9 my $type = ref $bindings;
145 9 ▶ if (! $type) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $type) { } 1 8 9
elsif ($NOT_ACCEPTABLE_REF{$type}) { } 1 7 8
146 1 croak 'New bindings must be a reference (HASH, ARRAY or object)';
147 } elsif ($NOT_ACCEPTABLE_REF{$type}) {
148 1 croak "New bindings reference type ($type) not usable";
149 }
150  
151 7 $self->{binding} = $bindings;
152 }
153  
154 8 return $self;
155 }
156  
157 ###############################################################################
158 #
159 # Sub Name: format
160 #
161 # Description: Front-end to the recursive _format routine, which does the
162 # bulk of the parsing/interpolation of the object's template
163 # against the given bindings.
164 #
165 # Arguments: NAME IN/OUT TYPE DESCRIPTION
166 # $self in ref Object of this class
167 # $bindings in ref Optional, bindings to use in
168 # interpolation. Defaults to
169 # object-level bindings.
170 #
171 # Returns: Success: string
172 # Failure: dies
173 #
174 ###############################################################################
175 sub format { ## no critic(ProhibitBuiltinHomonyms)
176 26 ▶ my ($self, $bindings) = @_;
Subroutine format: called CC=4 SCAR=13.9
Pod documented
177  
178 26 ▶ $bindings ||= $self->binding;
Condition100%3/3
$bindings ||= $self->binding
l!l&&r!l&&!r
2231
MC/DC100%2/2
$bindings ||= $self->binding
$bindings $self->binding
Truth table100%3/3
A ||= B
A= $bindingsB= $self->binding
ABresult
1X1
011
000
179 26 ▶ croak 'format: Bindings are required if object has no internal binding'
Branch: 1 branch
BranchTrueFalseTotal
unless $bindings 1 25 26
180 if (! $bindings);
181  
182 my $value = join q{} =>
183 238 ▶ map { ref() ? $self->_format($bindings, @{$_}) : $_ }
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 125 113 238
184 25 @{$self->{_compiled}};
185  
186 22 return $value;
187 }
188  
189 # Private functions that support the public API:
190  
191 # Compile the template into a tree structure that can be easily traversed for
192 # formatting.
193 sub _compile {
194 10 ▶ my $self = shift;
Subroutine _compile: called CC=8 SCAR=21.5
195  
196 10 my @tokens = $self->_tokenize;
197  
198 10 my @stack = ([]);
199 10 my $level = 0;
200 10 my @opens = ();
201  
202 10 ▶ while (my ($type, $value) = splice @tokens, 0, 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = splice(@tokens, 0, 2)) 123 10 133
203 123 ▶ if ($type eq 'STRING') {
Branch: 3 branches
BranchTrueFalseTotal
if ($type eq 'STRING') { } 57 66 123
elsif ($type eq 'OPEN') { } 33 33 66
elsif ($type eq 'CLOSE') { } 33 0 33
204 57 push @{$stack[$level]}, $value;
205 } elsif ($type eq 'OPEN') {
206 33 push @stack, [];
207 33 $level++;
208 33 push @opens, $value;
209 } elsif ($type eq 'CLOSE') {
210 33 ▶ if ($level) {
Branch: 1 branch
BranchTrueFalseTotal
if ($level) { } 33 0 33
211 33 my $subtree = pop @stack;
212 33 $level--;
213 33 push @{$stack[$level]}, $subtree;
214 33 pop @opens;
215 } else {
216 0 croak "Unmatched closing brace at position $value";
217 }
218 } else {
219 0 croak "Unknown token type: $type\n";
220 }
221 }
222  
223 10 ▶ if ($level) {
Branch: 1 branch
BranchTrueFalseTotal
if ($level) 0 10 10
224 0 ▶ croak sprintf '%d unmatched opening brace%s, last at position %d',
Branch: 1 branch
BranchTrueFalseTotal
$level == 1 ? : 0 0 0
225 $level, $level == 1 ? q{} : 's', pop @opens;
226 }
227  
228 10 $self->{_compiled} = $stack[0];
229 10 return $self;
230 }
231  
232 # Tokenize the object's template into a sequence of (type, value) pairs that
233 # identify the opening and closing braces, and ordinary strings.
234 sub _tokenize {
235 10 ▶ my $self = shift;
Subroutine _tokenize: called CC=5 SCAR=16.2
236  
237 10 my (@list, $base, $pos, $len);
238 10 my $str = $self->template;
239  
240 10 $base = 0;
241 10 ▶ while ($str =~ /(?<!\\)(?=[{}])/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($str =~ /(?<!\\)(?=[{}])/g) 66 10 76
242 66 $pos = pos $str;
243 66 ▶ if ($len = $pos - $base) {
Branch: 1 branch
BranchTrueFalseTotal
if ($len = $pos - $base) 57 9 66
244 57 (my $piece = substr $str, $base, $len) =~ s/\\([{}])/$1/g;
245 57 push @list, 'STRING', $piece;
246 }
247 66 ▶ push @list, ('{' eq substr $str, $pos, 1) ? 'OPEN' : 'CLOSE';
Branch: 1 branch
BranchTrueFalseTotal
'{' eq substr($str, $pos, 1) ? : 33 33 66
248 66 push @list, $pos;
249 66 $base = $pos + 1;
250 }
251  
252 10 ▶ if (length($str) > $base) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $str > $base) 0 10 10
253 0 (my $piece = substr $str, $base) =~ s/\\([{}])/$1/g;
254 0 push @list, 'STRING', $piece;
255 }
256  
257 10 return @list;
258 }
259  
260 # Does the hard and recursive part of the actual formatting. Not actually that
261 # hard, but a little recursive.
262 sub _format {
263 131 ▶ my ($self, $bindings, @elements) = @_;
Subroutine _format: called CC=2 SCAR=6.9
264  
265 # Slight duplication of code from format() here, but it saves having to
266 # keep track of depth and do a conditional on every return.
267 my $expr = join q{} =>
268 131 ▶ map { ref() ? $self->_format($bindings, @{$_}) : $_ } @elements;
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 6 131 137
269  
270 131 return $self->_expr_to_value($bindings, $expr);
271 }
272  
273 # Converts an expression like "a.b.c" into a value from the bindings
274 sub _expr_to_value {
275 131 ▶ my ($self, $bindings, $string) = @_;
Subroutine _expr_to_value: called CC=8 SCAR=20.8
276  
277 131 my ($expr, $format) = split /:/ => $string, 2;
278 # For now, $format is ignored
279 131 my @hier = split /[.]/ => $expr;
280 131 my $node = $bindings;
281  
282 131 for my $key (@hier) {
283 134 ▶ if ($key =~ /^\d+$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key =~ /^\d+$/) { } 19 115 134
284 19 ▶ if (ref $node eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $node eq 'ARRAY') { } 18 1 19
285 18 $node = $node->[$key];
286 } else {
287 1 croak "Key-type mismatch (key $key) in $expr, node is not " .
288 'an ARRAY ref';
289 }
290 } else {
291 115 ▶ if (ref $node eq 'HASH') {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $node eq 'HASH') { } 35 80 115
elsif (ref $node eq 'ARRAY') { } 1 79 80
elsif (ref $node) { } 78 1 79
292 35 $node = $node->{$key};
293 } elsif (ref $node eq 'ARRAY') {
294 1 croak "Key-type mismatch (key $key) in $expr, node is an " .
295 'ARRAY ref when expecting HASH or object';
296 } elsif (ref $node) {
297 78 $node = $node->$key();
298 } else {
299 1 croak "Key-type mismatch (key $key) in $expr, node is not " .
300 'a HASH ref or object';
301 }
302 }
303 }
304  
305 # Because all the key-substitution has been done before this sub is called,
306 # it's probably a bad thing if $node is a ref. It's gonna get stringified
307 # as a ref, which is probably not what the caller intended.
308 128 ▶ if (ref $node) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $node) 1 127 128
309 1 carp "Format expression $expr yielded a reference value rather than " .
310 'a scalar';
311 }
312 128 return $node;
313 }
314  
315 # Actual operator-overload functions:
316  
317 # Handle the object stringification (the "" operator)
318 sub _stringify {
319 4 ▶ my $self = shift;
Subroutine _stringify: called CC=2 SCAR=6.9
320 4 my $binding = $self->binding;
321  
322 4 ▶ return $binding ? $self->format($binding) : $self->template;
Branch: 1 branch
BranchTrueFalseTotal
$binding ? : 3 1 4
323 }
324  
325 # Handle the % interpolation operator
326 sub _interpolate {
327 9 ▶ my ($self, $bindings, $swap) = @_;
Subroutine _interpolate: called CC=2 SCAR=6.9
328  
329 9 ▶ if ($swap) {
Branch: 1 branch
BranchTrueFalseTotal
if ($swap) 1 8 9
330 1 my $class = ref $self;
331 1 croak "$class object must come first in % interpolation";
332 }
333  
334 8 return $self->format($bindings);
335 }
336  
337 # Handle the 'cmp' operator
338 sub _cmp {
339 1 ▶ my ($self, $other, $swap) = @_;
Subroutine _cmp: called CC=2 SCAR=7.2
340  
341 1 ▶ return $swap ?
Branch: 1 branch
BranchTrueFalseTotal
$swap ? : 0 1 1
342 ($other cmp $self->_stringify) : ($self->_stringify cmp $other);
343 }
344  
345 # Handle the 'eq' operator
346 sub _eq {
347 3 ▶ my ($self, $other, $swap) = @_;
Subroutine _eq: called CC=1 SCAR=0.0
348  
349 3 return $self->_stringify eq $other;
350 }
351  
352 # Handle the 'ne' operator
353 sub _ne {
354 0 ▶ my ($self, $other, $swap) = @_;
Subroutine _ne: not called CC=1 SCAR=6.9
355  
356 0 return $self->_stringify ne $other;
357 }
358  
359 # Handle the 'lt' operator
360 sub _lt {
361 0 ▶ my ($self, $other, $swap) = @_;
Subroutine _lt: not called CC=2 SCAR=17.9
362  
363 0 ▶ return $swap ?
Branch: 1 branch
BranchTrueFalseTotal
$swap ? : 0 0 0
364 ($other lt $self->_stringify) : ($self->_stringify lt $other);
365 }
366  
367 # Handle the 'le' operator
368 sub _le {
369 0 ▶ my ($self, $other, $swap) = @_;
Subroutine _le: not called CC=2 SCAR=17.9
370  
371 0 ▶ return $swap ?
Branch: 1 branch
BranchTrueFalseTotal
$swap ? : 0 0 0
372 ($other le $self->_stringify) : ($self->_stringify le $other);
373 }
374  
375 # Handle the 'gt' operator
376 sub _gt {
377 0 ▶ my ($self, $other, $swap) = @_;
Subroutine _gt: not called CC=2 SCAR=17.9
378  
379 0 ▶ return $swap ?
Branch: 1 branch
BranchTrueFalseTotal
$swap ? : 0 0 0
380 ($other gt $self->_stringify) : ($self->_stringify gt $other);
381 }
382  
383 # Handle the 'ge' operator
384 sub _ge {
385 0 ▶ my ($self, $other, $swap) = @_;
Subroutine _ge: not called CC=2 SCAR=17.9
386  
387 0 ▶ return $swap ?
Branch: 1 branch
BranchTrueFalseTotal
$swap ? : 0 0 0
388 ($other ge $self->_stringify) : ($self->_stringify ge $other);
389 }
390  
391 5 1;
392  
393 __END__
↑ Summary