blib/lib/Exporter/ConditionalSubs.pm

filter: Statementstmt 70.8% 51 / 72 Branchbran 59.0% 13 / 22 Conditioncond 27.2% 6 / 22 MC/DCmcdc 0.0% 0 / 9 Subroutinesub 91.6% 11 / 12 Podpod n/a totaltotal 59.1% 81 / 137 CC 22 SCAR 38.4
CC
22
Cov
60%
import
69.1
__ANON__
2.0
BEGIN
1.0
CRAP 46.4
↑ Summary
1 package Exporter::ConditionalSubs;
2  
3 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 3 require Exporter;
7 3 our @ISA = qw( Exporter );
8  
9 3 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 # ABSTRACT: Conditionally export subroutines
12 3 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 3 our $VERSION = 'v1.11.1'; # VERSION
14  
15 #pod =head1 SYNOPSIS
16 #pod
17 #pod Allows subroutines to be conditionally exported. If the condition
18 #pod is satisfied, the subroutine will be exported as usual. But if not,
19 #pod the subroutine will be replaced with a stub that gets optimized away
20 #pod by the compiler. When stubbed out, not even the arguments to the
21 #pod subroutine will get evaluated.
22 #pod
23 #pod This allows for e.g. assertion-like behavior, where subroutine calls
24 #pod can be left in the code but effectively ignored under certain conditions.
25 #pod
26 #pod First create a module that C<ISA> L<Exporter::ConditionalSubs>:
27 #pod
28 #pod package My::Assertions;
29 #pod
30 #pod require Exporter::ConditionalSubs;
31 #pod our @ISA = qw( Exporter::ConditionalSubs );
32 #pod
33 #pod our @EXPORT = ();
34 #pod our @EXPORT_OK = qw( _assert_non_empty );
35 #pod
36 #pod sub _assert_non_empty
37 #pod {
38 #pod carp "Found empty value" unless length(shift // '') > 0;
39 #pod }
40 #pod
41 #pod Then, specify an C<-if> or C<-unless> condition when C<use>ing that module:
42 #pod
43 #pod package My::App;
44 #pod
45 #pod use My::Assertions qw( _assert_non_empty ), -if => $ENV{DEBUG};
46 #pod
47 #pod use My::MoreAssertions -unless => $ENV{RUNTIME} eq 'prod';
48 #pod
49 #pod # Coderefs work too:
50 #pod use My::OtherAssertions -if => sub { ... some logic ... };
51 #pod
52 #pod _assert_non_empty($foo); # this subroutine call might be a no-op
53 #pod
54 #pod
55 #pod This is a subclass of L<Exporter> and works just like it, with the
56 #pod addition of support for the C<-if> and C<-unless> import arguments.
57 #pod
58 #pod =head1 SUBROUTINES
59 #pod
60 #pod =head2 import
61 #pod
62 #pod Works like the L<Exporter> C<import()> function, except that it checks
63 #pod for an optional C<-if> or C<-unless> import arg, followed by either
64 #pod a boolean, or a coderef that returns true/false.
65 #pod
66 #pod If the condition evaluates to true for C<-if>, or false for C<-unless>,
67 #pod then any subs are exported as-is. Otherwise, any subs in C<@EXPORT_OK>
68 #pod are replaced with stubs that get optimized away by the compiler (with
69 #pod one exception - see L</CAVEATS> below).
70 #pod
71 #pod You can specify either C<-if> or C<-unless>, but not both. Croaks if
72 #pod both are specified, or if you specify the same option more than once.
73 #pod
74 #pod =cut
75  
76 sub import
77 11 ▶{
Subroutine import: called CC=22 SCAR=42.4
78 11 my ($package, @args) = @_;
79  
80 # By default we are going to export subs as-is and not optimize them away:
81 11 my $should_export_subs = 1;
82  
83 11 my @export_args = ($package);
84  
85 # Copy args until we come across "-if" or "-unless":
86 #
87 11 ▶ while (@args && ($args[0] || '') !~ /^-(?:if|unless)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args and not +($args[0] || "") =~ /^-(?:if|unless)$/) 18 11 29
Condition80%4/5
@args and not +($args[0] || "") =~ /^-(?:if|unless)$/
!ll&&!rl&&r
3818
$args[0] || ''
l!l
260
MC/DC0%0/2
@args and not +($args[0] || "") =~ /^-(?:if|unless)$/
@args $args[0]
Truth table66%2/3
A and not(B)
A= @argsB= $args[0]
ABresult
0X0
110
101
88 18 push @export_args, shift @args;
89 }
90  
91 # If any args remain, it must be because we found "-if" or "-unless".
92 # We expect the next arg to be the condition boolean or coderef:
93 #
94 11 ▶ if (@args) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args) 8 3 11
95 8 my $thing = shift @args; # i.e. "-if" or "-unless"
96 8 ▶ unless (@args) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@args) 0 8 8
97 0 croak "$package->import failed: " .
98 qq{"$thing" must be followed by boolean or coderef};
99 }
100 8 my $condition = shift @args;
101  
102 # Go ahead and evaluate the condition if it's a coderef:
103 8 ▶ $condition = $condition->() if ref($condition) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $condition eq "CODE" 4 4 8
104  
105 # We might decide against importing subs, depending on the condition:
106 8 ▶ $should_export_subs = $thing eq '-if' ? $condition : !$condition;
Branch: 1 branch
BranchTrueFalseTotal
$thing eq '-if' ? : 4 4 8
107  
108 # Copy any remaining args:
109 #
110 8 ▶ while (@args) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args) 0 8 8
111 0 ▶ if ($args[0] && $args[0] =~ /^-(?:if|unless)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args[0] and $args[0] =~ /^-(?:if|unless)$/) 0 0 0
Condition0%0/3
$args[0] and $args[0] =~ /^-(?:if|unless)$/
!ll&&!rl&&r
000
MC/DC0%0/2
$args[0] and $args[0] =~ /^-(?:if|unless)$/
$args[0] $args[0] =~ /^-(?:if|unless)$/
Truth table0%0/3
A and B
A= $args[0]B= $args[0] =~ /^-(?:if|unless)$/
ABresult
0X0
100
111
112 0 croak "$package->import failed: " .
113 qq{Cannot use "$args[0]" after "$thing"};
114 }
115 0 push @export_args, shift @args;
116 }
117 }
118  
119 # Pulling in B::CallChecker and/or B::Generate to optimize away
120 # the exported symbols can break test coverage metrics generated
121 # by Devel::Cover. We probably want to check coverage on the actual
122 # exports anyway, so if Devel::Cover is in play assume we *should*
123 # export everything:
124 #
125 # (took this conditional logic directly from Devel::Cover)
126 #
127 $should_export_subs = 1 if (
128 $INC{'Devel/Cover.pm'} ||
129 ($ENV{HARNESS_PERL_SWITCHES} || "") =~ /Devel::Cover/ ||
130 11 ▶ ($ENV{PERL5OPT} || "") =~ /Devel::Cover/
Branch: 1 branch
BranchTrueFalseTotal
if $INC{"Devel/Cover.pm"} or ($ENV{"HARNESS_PERL_SWITCHES"} || "") =~ /Devel::Cover/ or ($ENV{"PERL5OPT"} || "") =~ /Devel::Cover/ 11 0 11
Condition20%2/10
$INC{"Devel/Cover.pm"} or ($ENV{"HARNESS_PERL_SWITCHES"} || "") =~ /Devel::Cover/ or ($ENV{"PERL5OPT"} || "") =~ /Devel::Cover/
l!l&&r!l&&!r
1100
$INC{"Devel/Cover.pm"} or ($ENV{"HARNESS_PERL_SWITCHES"} || "") =~ /Devel::Cover/
l!l&&r!l&&!r
1100
$ENV{'HARNESS_PERL_SWITCHES'} || ''
l!l
00
$ENV{'PERL5OPT'} || ''
l!l
00
MC/DC0%0/3
$INC{"Devel/Cover.pm"} or ($ENV{"HARNESS_PERL_SWITCHES"} || "") =~ /Devel::Cover/ or ($ENV{"PERL5OPT"} || "") =~ /Devel::Cover/
$INC{"Devel/Cover.pm"} $ENV{'HARNESS_PERL_SWITCHES'} $ENV{'PERL5OPT'}
Truth table25%1/4
A or B or C
A= $INC{"Devel/Cover.pm"}B= $ENV{'HARNESS_PERL_SWITCHES'}C= $ENV{'PERL5OPT'}
ABCresult
1XX1
01X1
0011
0000
131 );
132  
133 # If the "if" condition is false, or the "unless" condition is true,
134 # replace any exportable subs with something that will get optimized away:
135 #
136 11 my %their_original_coderefs;
137 11 ▶ unless ($should_export_subs) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($should_export_subs) 0 11 11
138  
139 3 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
140 0 my $stash = *{ $package . "::" };
141  
142 0 ▶ my @their_export_oks = @{ ($stash->{EXPORT_OK} || []) };
Condition0%0/2
$stash->{'EXPORT_OK'} || []
l!l
00
MC/DC0%0/1
$stash->{'EXPORT_OK'} || []
$stash->{'EXPORT_OK'}
Truth table0%0/2
A
A= $stash->{'EXPORT_OK'}
Aresult
11
00
143 0 for my $export_name (@their_export_oks) {
144  
145 0 my $globref = $stash->{$export_name};
146 0 ▶ if ($globref && *$globref{CODE}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($globref and *$globref{"CODE"}) 0 0 0
Condition0%0/2
$globref and *$globref{"CODE"}
!ll
00
MC/DC0%0/1
$globref and *$globref{"CODE"}
$globref
Truth table0%0/2
A
A= $globref
Aresult
00
11
147  
148 0 my $symbol = $package . "::" . $export_name;
149  
150 # Save a copy of the original code:
151 0 $their_original_coderefs{$symbol} = \&$symbol;
152  
153 0 require B::CallChecker;
154 0 require B::Generate;
155  
156 # Replace the sub being imported with a void prototype sub
157 # that gets optimized away:
158 #
159 {
160 0 ▶ no warnings 'redefine';
Subroutine BEGIN: called CC=1 SCAR=0.2
161 3 ▶ no warnings 'prototype';
Subroutine BEGIN: called CC=1 SCAR=0.0
162  
163 0 *$symbol = sub () {0};
164  
165 #---------------------------------------------------------
166 #
167 # This section lifted almost as-is from Debug::Show v0.0
168 #
169 # https://metacpan.org/pod/Debug::Show
170 #
171 # Thanks to Zefram
172 #
173 B::CallChecker::cv_set_call_checker(
174 \&$symbol,
175 0 ▶ sub ($$$) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
176 0 my($entersubop, undef, undef) = @_;
177 # B::Generate doesn't offer a way to explicitly free ops.
178 # We ought to be able to implicitly free $entersubop via
179 # constant folding, by something like
180 #
181 # return B::LOGOP->new("and", 0,
182 # B::SVOP->new("const", 0, !1),
183 # $entersubop);
184 #
185 # but empirically that causes memory corruption and it's
186 # not clear why. For the time being, leak $entersubop.
187 0 return B::SVOP->new("const", 0, !1);
188 },
189 0 \!1
190 );
191 #
192 #---------------------------------------------------------
193 }
194 }
195 }
196 }
197  
198 # Let Export handle everything else as usual:
199 11 $package->export_to_level(1, @export_args);
200  
201 # Restore coderefs in the original package with their saved version:
202 #
203 11 ▶ while (my ($symbol, $coderef) = each %their_original_coderefs) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %their_original_coderefs) 0 11 11
204 3 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
205 3 ▶ no warnings 'redefine';
Subroutine BEGIN: called CC=1 SCAR=0.0
206 3 ▶ no warnings 'prototype';
Subroutine BEGIN: called CC=1 SCAR=0.0
207 0 *$symbol = $coderef;
208 }
209 }
210  
211 #pod =head1 CAVEATS
212 #pod
213 #pod This module uses L<B::CallChecker> and L<B::Generate> under the covers
214 #pod to optimize away the exported subroutines. Loading one or the other
215 #pod of those modules can potentially break test coverage metrics generated
216 #pod by L<Devel::Cover> in mysterious ways.
217 #pod
218 #pod To avoid this problem, subroutines are never optimized away
219 #pod if L<Devel::Cover> is in use, and are always exported as-is
220 #pod regardless of any C<-if> or C<-unless> conditions. (You probably
221 #pod want L<Devel::Cover> to assess the coverage of your real exported
222 #pod subroutines in any case.)
223 #pod
224 #pod =head1 SEE ALSO
225 #pod
226 #pod L<Exporter>
227 #pod
228 #pod L<B::CallChecker>
229 #pod
230 #pod L<B::Generate>
231 #pod
232 #pod =head1 ACKNOWLEDGEMENTS
233 #pod
234 #pod Thanks to Grant Street Group L<http://www.grantstreet.com> for funding
235 #pod development of this code.
236 #pod
237 #pod Thanks to Tom Christiansen (C<< <tchrist@perl.com> >>) for help with the
238 #pod symbol table hackery
239 #pod and Larry Leszczynski, C<< <larryl at cpan.org> >> for writing most of
240 #pod the code.
241 #pod
242 #pod Thanks to Zefram (C<< <zefram@fysh.org> >>) for the pointer to his
243 #pod L<Debug::Show> hackery.
244 #pod
245 #pod =cut
246  
247 3 1;
248  
249 __END__
↑ Summary