Expand.pm

filter: Statementstmt 86.7% 131 / 151 Branchbran 60.0% 18 / 30 Conditioncond 62.5% 5 / 8 MC/DCmcdc 25.0% 1 / 4 Subroutinesub 83.8% 26 / 31 Podpod 100% 3 / 3 totaltotal 81.0% 184 / 227 CC 24 SCAR 13.7
CC
24
Cov
81%
_explode_format_list
12.0
_traverse
7.0
parse
6.1
CRAP 3.9
« Expand/Permutation.pm ↑ Summary Expand/Segment.pm »
1 package Text::Glob::Expand;
2 2 ▶use Text::Glob::Expand::Segment;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 2 ▶use Text::Glob::Expand::Permutation;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use Scalar::Util qw(refaddr);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use Sub::Exporter -setup => {
Subroutine BEGIN: called CC=1 SCAR=0.1
9 exports => {
10 1 ▶ explode => sub { \&_explode_list },
Subroutine __ANON__: called CC=1 SCAR=0.0
11 0 ▶ explode_format => sub { \&_explode_format_list },
Subroutine __ANON__: not called CC=1 SCAR=6.9
12 },
13 2 };
14  
15  
16 2 our $VERSION = '1.1.1'; # VERSION
17  
18 # Cache ->_explode results here
19 2 our %CACHE;
20  
21 # and queue cached items for deletion
22 2 our @CACHE_QUEUE;
23  
24 # when the number of cached items exceeds this.
25 2 our $MAX_CACHING = 100;
26  
27 ######################################################################
28 # Private functions - read the POD to understand the terms.
29  
30  
31 # @partitions = _partition $depth, @segments;
32 #
33 # This function groups a list of segments (Text::Glob::Expand::Segment
34 # instances) by the brace-expression they came from, using their depth
35 # attributes to infer which segments go together.
36 #
37 # It works by discarding elements below the desired $depth value,
38 # and using the gaps to split the remainder into groups.
39 #
40 # For example, if we ignore the segments' string attribute for the
41 # moment and just consider their depths, given an expression like
42 # this:
43 #
44 # a{a{a,a}a}a{a}a{a{a}a}a
45 #
46 # We get depths like this:
47 #
48 # @segments = (0, 1, 2, 2, 1, 0, 1, 0, 1, 2, 1, 0)
49 #
50 # and results like this:
51 #
52 # _partition 0, @segments # -> ([1, 2, 2, 1], [1], [1, 2, 1])
53 # _partition 1, @segments # -> ([2, 2], [2])
54 # _partition 2, @segments # -> ()
55 #
56 # Note, this is designed to be used internally by the ->_transform
57 # method, and so it does not try to check the validity and consistency
58 # of the data.
59 94 ▶sub _partition {
Subroutine _partition: called CC=6 SCAR=18.0
60 94 my $depth = shift;
61  
62 94 my @partitions; # An accumulator for partitions
63 94 my $partition = []; # The current partition under construction
64  
65 94 foreach my $elem (@_) {
66 250 ▶ if ($elem->depth > $depth) {
Branch: 1 branch
BranchTrueFalseTotal
if ($elem->depth > $depth) { } 96 154 250
67 # Add element this to the current partition
68 96 push @$partition, $elem;
69 }
70 else {
71 # Start a new partition. If there is a non-empty
72 # partition in construction, save it, then empty it.
73 154 ▶ push @partitions, $partition
Branch: 1 branch
BranchTrueFalseTotal
if $partition and @$partition 60 94 154
Condition66%2/3
$partition and @$partition
!ll&&!rl&&r
09460
MC/DC50%1/2
$partition and @$partition
$partition @$partition
Truth table66%2/3
A and B
A= $partitionB= @$partition
ABresult
0X0
100
111
74 if $partition
75 && @$partition;
76 154 $partition = [];
77 }
78 }
79  
80 # Save the last partition, if not empty
81 94 ▶ push @partitions, $partition
Branch: 1 branch
BranchTrueFalseTotal
if @$partition 0 94 94
82 if @$partition;
83  
84 94 return @partitions;
85 }
86  
87 ######################################################################
88 # Private methods
89  
90 # $permutations = $obj->_traverse(@expression)
91 #
92 # This method traverses a sub-expression and recursively expands them
93 # into all possible permutations, returning an arrayref to the
94 # resulting list of lists (of Text::Glob::Expand::Segment instances).
95 #
96 # If no arguments are given, it returns an empty arrayref.
97 146 ▶sub _traverse {
Subroutine _traverse: called CC=7 SCAR=19.5
98 146 my $self = shift;
99  
100 # Trivial case.
101 146 ▶ return [] unless @_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 0 146 146
102  
103 # Since @expression contains the elements of a glob expression,
104 # each parameter param can be one of two things: a string segment
105 # or a brace-expression.
106  
107 # Take the first element, and process the rest recursively.
108 146 my $first = shift;
109  
110 146 ▶ if (ref $first eq 'Text::Glob::Expand::Segment') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $first eq 'Text::Glob::Expand::Segment') { } 118 28 146
111 # $first is a string segment - in which case we recursively
112 # expand the the remaining arguments (if any) into their
113 # permutations and prepend $first to each of the permutations.
114  
115 118 ▶ return [[$first]] unless @_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 34 84 118
116  
117 84 my $exploded = $self->_traverse(@_);
118 84 unshift @$_, $first for @$exploded;
119 84 return $exploded;
120 }
121 else {
122 # $first is an brace-expression (an arrayref of alternative
123 # sub-expressions) - in which case we take out each
124 # alternative sub-expression $seq, concatenate it with with
125 # the remaining arguments into a new expression, and
126 # recursively expand the permutations of that expression.
127 #
128 # After processing them all, we return a concatenated list of
129 # all the permutations.
130 28 my @exploded;
131 28 foreach my $seq (@$first) {
132 48 ▶ die "unexpected scalar '$seq'" if !ref $seq;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $seq 0 48 48
133 48 my $exploded2 = $self->_traverse(@$seq, @_);
134 48 push @exploded, @$exploded2;
135 }
136 28 return \@exploded;
137 }
138 }
139  
140  
141 # $root = $obj->_transform($depth, $permutation)
142 #
143 # $permutation is an arrayref of segments (Text::Glob::Expand::Segment
144 # instances) representing a permutation generated from a
145 # Text::Glob::Expand expression (i.e. one of the elements in the
146 # result from from _traverse).
147 #
148 # $depth is a depth to partition it by (in hindsight, perhaps this
149 # could be computed from the first element's depth?).
150 #
151 # The result $root is the root node of a tree structure describing the
152 # structure of the permutation (a Text::Glob::Expand::Permutation
153 # instance), by using the segments' depth attribute. This tree is
154 # designed to allow the placeholders in formats to be mapped to
155 # expansions.
156 #
157 # See the POD within Text::Glob::Expand::Permutation for a description of
158 # the structure of this result.
159 #
160 # For example, this glob expression:
161 #
162 # "a{b{c,d,}e,f}g"
163 #
164 # Generates this set of permutations:
165 #
166 # "abceg", "abdeg", "abeg", "afg"
167 #
168 # Permutations are generated by _traverse in terms of arrays of
169 # Text::Glob::Expand::Segment instances. The first permutation above
170 # would look like this (omitting blessings):
171 #
172 # $permutation = [['a', 0], ['b', 1], ['c', 2], ['e', 1], ['g', 0]]
173 #
174 # This then gets passed to _transform to turn it into a
175 # Text::Glob::Expand::Permutation instance:
176 #
177 # $root = $glob->_transform(0, $permutation)
178 #
179 # The structure of $root would be:
180 #
181 # ["abceg", ["bce", ["c"]]]
182 #
183 # This is then relatively easily used to expand a format like "%1 %1.1
184 # %1.1.1" into "abcdeg bce c".
185 #
186 94 ▶sub _transform {
Subroutine _transform: called CC=2 SCAR=6.9
187 94 my $self = shift;
188 94 my $depth = shift;
189 94 my $permutation = shift;
190  
191 # Concatenate the strings from all the Text::Glob::Expand::Segment
192 # instances in $permutation into one.
193 94 my $flat = join '', map { $_->[0] } @$permutation;
194  
195 # Group the segments deeper than $depth recursively
196 94 ▶ if (my @deeper = _partition $depth, @$permutation) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@deeper) = _partition($depth, @$permutation)) 50 44 94
197 return bless (
198 50 [$flat, map { $self->_transform($depth+1, $_)} @deeper],
199 'Text::Glob::Expand::Permutation',
200 );
201 }
202  
203 # Bless the result, to add convenience methods for the user.
204 44 return bless [$flat], 'Text::Glob::Expand::Permutation';
205 }
206  
207  
208 # $permutations = $obj->_explode
209 #
210 # This generates all the permutations implied by the parsed glob
211 # expression.
212 #
213 # The return value is an array of Text::Glob::Expand::Permutation
214 # instances.
215 14 ▶sub _explode {
Subroutine _explode: called CC=1 SCAR=0.0
216 14 my $self = shift;
217  
218 # Permute all the alternatives in the parsed glob expression
219 # into a giant list of permutations of segments.
220 14 my $exploded = $self->_traverse(@$self);
221  
222 # Transform that into an array of tree descriptions of each
223 # permutation's composition (i.e. Text::Glob::Expand::Permutation
224 # instances).
225 14 return [map { $self->_transform(0, $_) } @$exploded];
226 }
227  
228  
229 ######################################################################
230 # Public methods - see POD for documentation.
231  
232  
233 7 ▶sub parse {
Subroutine parse: called CC=6 SCAR=18.0
Pod documented
234 7 my $class = shift;
235 7 my $str = shift; # The expression to parse
236  
237 # This function defines a simple state-machine to parse
238 # expressions. See the documentation for an explanation of the
239 # parsing rules. The comments below assume you have read that.
240  
241 # Each character in the expression is examined in turn in a
242 # for-loop. The current value is stored in $_, and the character
243 # index in $pos.
244 7 my $pos;
245  
246 # The depth of brace-nesting at $pos is stored in $depth.
247 7 my $depth = 0;
248  
249 # Empty Text::Glob::Expand::Segment instances are created using
250 # this closure. (We use a closure simply as it more convenient
251 # than a constructor method.)
252 7 ▶ my $new_segment = sub { bless ['', $depth], 'Text::Glob::Expand::Segment' };
Subroutine __ANON__: called CC=1 SCAR=0.0
253  
254  
255 # (Note, expressions and brace-expressions are implemented as
256 # arrayrefs, and so the [] constructor is used for them.)
257  
258  
259 # The implementation is stack-based. It uses three stacks as follows.
260  
261 # First: a stack @c_stack to store intermediate parsed values. We
262 # construct new string segments on the top of this stack as they
263 # are encountered. At the end of an expression the top N are
264 # popped off and used to construct the expression data structure.
265 #
266 # We initialise it with a single empty segment, since the
267 # top-level expression always contains at least one.
268 7 my @c_stack = $new_segment->();
269  
270 # Second: a stack called @alt_count is used to count how many
271 # alternatives have been parsed in the current brace
272 # (i.e. comma-delimited sub-expressions). It determines how many
273 # elements on @c_stack belong to it.
274 7 my @alt_count = ();
275  
276 # Third and final: a stack called @seq_count is used to count how
277 # many sequential elements (segments or brace-expressions) have
278 # been parsed in the current sub-expression. As above, it
279 # determines how many of the top elements on @c_stack belong to
280 # it.
281 #
282 # We initialise it to 1, since there is always at least one
283 # segment in the top level expression.
284 7 my @seq_count = (1);
285  
286  
287 # Some helper closures follow. These are invoked by the state
288 # machine to build the data as a side-effect.
289  
290 33 ▶ my $add_char = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
291 # Append the current character ($_) to the segment under
292 # construction on the top of @c_stack. (The string is the
293 # zeroth element of the segment array.)
294  
295 33 $c_stack[-1][0] .= $_;
296 7 };
297  
298  
299 13 ▶ my $start_brace = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
300 # Called when an opening brace is seen.
301  
302 13 ++$depth;
303 13 ++$seq_count[-1]; # Increment the current sequence counter,
304  
305 13 push @alt_count, 1; # Start a new alternative list
306 13 push @c_stack, $new_segment->(); # Start a new sub-expression
307 13 push @seq_count, 1;
308 7 };
309  
310  
311 9 ▶ my $new_alternative = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
312 # Called when a comma delimiter is seen.
313  
314 # Finish the last alternative: replace the appropriate number
315 # of elements from @c_stack with a sub-expression arrayref
316 # created from them.
317 9 my $num_elems = pop @seq_count;
318 9 push @c_stack, [splice @c_stack, -$num_elems];
319  
320 9 ++$alt_count[-1]; # Increment the number of alternatives seen
321 9 push @seq_count, 1; # and start a new sub-expression
322 9 push @c_stack, $new_segment->();
323 7 };
324  
325  
326 13 ▶ my $end_brace = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
327 # Called when a closing brace is seen.
328  
329 13 --$depth;
330  
331 # Finish the current alternative: replace the appropriate
332 # number of elements from @c_stack with a sub-expression
333 # arrayref created from them.
334 13 my $num_elems = pop @seq_count;
335 13 push @c_stack, [splice @c_stack, -$num_elems];
336  
337 # Finish the current brace: replace the appropriate
338 # number of elements from @c_stack with a brace-expression
339 # arrayref created from them.
340 13 $num_elems = pop @alt_count;
341 13 push @c_stack, [splice @c_stack, -$num_elems], $new_segment->();
342  
343 # Increment the sequence counter
344 13 ++$seq_count[-1];
345 7 };
346  
347  
348 # Define the states in our parser as a hash.
349 #
350 # State names are mapped to a hash of transition definitions for
351 # that state.
352 #
353 # Each transition has a single character which triggers it,
354 # mapped to a code-ref which returns the name of the next state
355 # (and optionally performs some side effect).
356 #
357 # Except for '' which is the default transition, used when none of
358 # the others match.
359 #
360 # Since the whole expression muse be parsed, there is no terminal
361 # state. Termination is implicit when the end of the string is
362 # reached. FIXME this means brace-matching is not properly
363 # handled.
364 my $states = {
365 start => {
366 0 ▶ '\\' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
367 0 'escape'
368 },
369 13 ▶ '{' => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
370 13 $start_brace->();
371 13 'start';
372 },
373 13 ▶ '}' => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
374 13 $end_brace->();
375 13 'start';
376 },
377 9 ▶ ',' => sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
378 @alt_count # This has a value added at the start of each brace
379 9 ▶ or die "unexpected comma outside of a brace-expression";
Branch: 1 branch
BranchTrueFalseTotal
@alt_count or die "unexpected comma outside of a brace-expression" 9 0 9
380 9 $new_alternative->();
381 9 'start';
382 },
383 33 ▶ '' => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
384 33 $add_char->();
385 33 'start';
386 }
387 },
388  
389 # This state is purely to handle escaping.
390 escape => {
391 0 ▶ '' => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
392 0 $add_char->();
393 0 'start';
394 },
395 }
396 7 };
397  
398  
399 7 my $state = 'start'; # Set the initial state.
400  
401 # Iterate over the length of the string
402 7 for $pos (0..length($str)-1) { ## no critic RequireLexicalLoopIterators
403 68 ▶ my $table = $states->{$state}
Branch: 1 branch
BranchTrueFalseTotal
my $table = $states->{$state} or die "no such state '${state}'" 68 0 68
404 or die "no such state '$state'";
405  
406 # We use this for-loop as a mechanism to alias $_ to the
407 # character at $pos
408 68 for (substr $str, $pos, 1) {
409  
410 # Get the action for this transition
411 my $action =
412 $table->{$_} ||
413 68 ▶ $table->{''} ||
Condition60%3/5
$table->{$_} || $table->{''} || die("no handler for state '${state}' looking at '${_}' pos $pos")
l!l
680
$table->{$_} or $table->{""}
l!l&&r!l&&!r
35330
MC/DC0%0/2
$table->{$_} || $table->{''} || die("no handler for state '${state}' looking at '${_}' pos $pos")
$table->{$_} $table->{""}
Truth table66%2/3
A or B
A= $table->{$_}B= $table->{""}
ABresult
1X1
011
000
414 die "no handler for state '$state' looking at '$_' pos $pos";
415  
416 # Invoke it
417 68 $state = $action->();
418 }
419 }
420  
421 # When we get here, @c_stack will contain the fully-parsed expression.
422 7 return bless \@c_stack, __PACKAGE__;
423 };
424  
425  
426  
427 # This is a wrapper around the real implementation in ->_explode. It
428 # caches the results and re-uses them when possible.
429 14 ▶sub explode {
Subroutine explode: called CC=4 SCAR=15.7
Pod documented
430 14 my $self = shift;
431  
432 # This clause handles caching of results from ->_explode
433 14 ▶ if ($MAX_CACHING > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Text::Glob::Expand::MAX_CACHING > 0) 14 0 14
434 # Look ourselves up in the cache, are we there?
435 14 my $id = refaddr $self;
436 14 my $exploded = $CACHE{$id};
437  
438 # If yes, just return the same as last time.
439 14 ▶ return $exploded
Branch: 1 branch
BranchTrueFalseTotal
if $exploded 0 14 14
440 if $exploded;
441  
442 # Otherwise delegate to the full implementation
443 14 $exploded = $self->_explode(@$self);
444  
445 # And add the results to the cache, unless we've surpassed the
446 # limit on caching.
447 14 unshift @CACHE_QUEUE, $id;
448 14 ▶ if (@CACHE_QUEUE > $MAX_CACHING) {
Branch: 1 branch
BranchTrueFalseTotal
if (@Text::Glob::Expand::CACHE_QUEUE > $Text::Glob::Expand::MAX_CACHING) 0 14 14
449 0 delete @CACHE{splice @CACHE_QUEUE, $MAX_CACHING};
450 }
451  
452 # Finally, return the new results.
453 14 return $exploded;
454 }
455  
456 # If we get here, there is no caching, so empty the cache (in case
457 # $MAX_CACHING just changed).
458 0 %CACHE = ();
459 0 @CACHE_QUEUE = ();
460  
461 # And merely delegate to the full implementation.
462 0 return $self->_explode(@$self);
463 }
464  
465  
466 # A convenience method which explodes and expands in one step.
467 7 ▶sub explode_format {
Subroutine explode_format: called CC=1 SCAR=0.0
Pod documented
468 7 my $self = shift;
469 7 my $format = shift;
470  
471 # Get the exploded result, and expand all the values using $format
472 7 my $exploded = $self->explode;
473 7 return {map { $_->text => $_->expand($format) } @$exploded};
474 }
475  
476  
477  
478 ######################################################################
479 # Exportable functions
480  
481 # FIXME document
482 # FIXME test these
483  
484 # A convenience function which explodes to a list of strings
485 0 ▶sub _explode_list {
Subroutine _explode_list: not called CC=1 SCAR=6.9
486  
487 return map {
488 0 my $glob = __PACKAGE__->parse($_);
489 map {
490 0 $_->text;
491 0 } @{ $glob->explode };
492 } @_;
493 }
494  
495  
496 # A convenience function which explodes to a list of formatted strings
497 0 ▶sub _explode_format_list {
Subroutine _explode_format_list: not called CC=3 SCAR=24.8
498 0 ▶ @_ or croak "you must supply a format parameter";
Branch: 1 branch
BranchTrueFalseTotal
@_ or croak("you must supply a format parameter") 0 0 0
499  
500 0 ▶ defined (my $format = shift)
Branch: 1 branch
BranchTrueFalseTotal
defined(my $format = shift()) or croak("format parameter is undefined") 0 0 0
501 or croak "format parameter is undefined";
502  
503 return map {
504 0 my $glob = __PACKAGE__->parse($_);
505 map {
506 0 $_->expand($format);
507 0 } @{ $glob->explode };
508 } @_;
509 }
510  
511  
512 2 ▶no Scalar::Util;
Subroutine BEGIN: called CC=1 SCAR=0.0
513 2 ▶no Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
514 2 1; # Magic true value required at end of module
515 __END__
« Expand/Permutation.pm ↑ Summary Expand/Segment.pm »