blib/lib/YASF.pm

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