lib/Class/Abstract.pm

filter: Statementstmt 100% 80 / 80 Branchbran 100% 28 / 28 Conditioncond 100% 37 / 37 MC/DCmcdc 100% 18 / 18 Subroutinesub 100% 18 / 18 Podpod 100% 3 / 3 totaltotal 100% 184 / 184 CC 29 SCAR 15.2
CC
29
Cov
100%
_direct_isa
9.0
import
6.0
_resolve_class
5.0
CRAP 4.6
↑ Summary
1 package Class::Abstract;
2  
3 # Minimum required Perl version: 5.8.
4 15 ▶use 5.008;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 15 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 15 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 15 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 15 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 15 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 15 ▶use Return::Set qw(set_return);
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 =head1 NAME
13  
14 Class::Abstract - Stop code from making objects of a class that is only a template
15  
16 =head1 VERSION
17  
18 Version 0.04
19  
20 =head1 SYNOPSIS
21  
22 =head2 1. Make a class abstract (the usual way)
23  
24 package Animal;
25 use parent 'Class::Abstract'; # Animal is now abstract
26  
27 package Dog;
28 use parent -norequire, 'Animal'; # Dog is a normal (concrete) class
29  
30 package main;
31 my $dog = Dog->new; # works: you get a Dog object
32 my $bad = Animal->new; # dies: "Cannot instantiate abstract class Animal directly"
33  
34 =head2 2. Make a class abstract with "use"
35  
36 package Vehicle;
37 use Class::Abstract; # same result as: use parent 'Class::Abstract'
38  
39 =head2 3. A child class that stores its own data
40  
41 package Dog;
42 use parent -norequire, 'Animal';
43  
44 sub new {
45 my ($class, %args) = @_;
46 my $self = $class->SUPER::new; # the check happens here
47 $self->{name} = $args{name}; # then add your own data
48 return $self;
49 }
50  
51 package main;
52 my $rex = Dog->new(name => 'Rex');
53  
54 =head2 4. An abstract class that has its own new()
55  
56 package Shape;
57 use parent 'Class::Abstract';
58  
59 sub new {
60 my ($class, %args) = @_;
61 Class::Abstract::check_abstract($class); # dies if $class is Shape
62 return bless { colour => $args{colour} }, $class;
63 }
64  
65 package Circle;
66 use parent -norequire, 'Shape';
67  
68 package main;
69 my $c = Circle->new(colour => 'red'); # works
70 Shape->new(colour => 'red'); # dies
71  
72 =head2 5. Ask whether a class is abstract
73  
74 Animal->is_abstract; # 1
75 Dog->is_abstract; # 0
76 $rex->is_abstract; # 0 (asks about Dog)
77 Class::Abstract->is_abstract('Animal'); # 1
78 Class::Abstract->is_abstract($rex); # 0
79  
80 =head2 6. Make an object of an abstract class inside a test
81  
82 use Test::More;
83  
84 my $animal = do {
85 local $Class::Abstract::BYPASS = 1; # turn the check off for this block only
86 Animal->new;
87 };
88 is( $animal->legs, 4, 'default number of legs' );
89  
90 =head2 7. Use with Sub::Abstract
91  
92 package Animal;
93 use parent 'Class::Abstract'; # nobody can make an Animal directly
94 use Sub::Abstract qw(speak); # every child class must write speak()
95  
96 =head1 DESCRIPTION
97  
98 =head2 What this module does
99  
100 An I<abstract class> is a class that is only a template. It holds code
101 that its child classes share, but it is not complete on its own. You
102 should never make an object of it. You make objects of its child classes
103 instead.
104  
105 Perl has no built-in way to say "this class is abstract". This module
106 adds one. When code tries to make an object of an abstract class, the
107 program dies with a clear error message. Child classes work normally.
108  
109 =head2 Terms used in this document
110  
111 =over 4
112  
113 =item class, package
114  
115 In Perl, a class is a package. C<Animal> and C<Dog> are package names.
116  
117 =item parent class, child class, @ISA
118  
119 Each package has a list called C<@ISA> that names its parent classes.
120 If C<@Dog::ISA> contains C<Animal>, then C<Dog> is a child of C<Animal>,
121 and C<Dog> can use C<Animal>'s methods.
122  
123 =item abstract, concrete
124  
125 A class is I<abstract> when C<Class::Abstract> is in its B<own> C<@ISA>.
126 All other classes are I<concrete> (normal).
127  
128 =item invocant
129  
130 The value on the left of the arrow in a method call. In
131 C<< Dog->new >> the invocant is the string C<'Dog'>. In
132 C<< $rex->speak >> the invocant is the object C<$rex>.
133  
134 =item croak, die
135  
136 Stop the program (or the current C<eval> block) with an error message.
137  
138 =item bypass
139  
140 A setting that turns the check off. See L</Turning the check off>.
141  
142 =item test harness
143  
144 The program that runs test files, for example C<prove> or C<make test>.
145 It sets the environment variable C<HARNESS_ACTIVE>.
146  
147 =back
148  
149 =head2 How to make a class abstract
150  
151 Put C<Class::Abstract> in the class's own C<@ISA>. There are two ways:
152  
153 package Animal;
154 use parent 'Class::Abstract'; # way 1 (recommended)
155  
156 package Vehicle;
157 use Class::Abstract; # way 2
158  
159 Both ways have the same result.
160  
161 =head2 How the check works
162  
163 C<Class::Abstract> gives every class below it a method called C<new()>.
164 When C<new()> runs, it looks at the invocant (the class name on the left
165 of the arrow). If that class has C<Class::Abstract> in its B<own>
166 C<@ISA>, C<new()> dies. If not, C<new()> makes and returns an empty
167 object.
168  
169 This is why child classes work. When C<Dog> calls
170 C<< $class->SUPER::new >>, the invocant is still C<'Dog'>, not
171 C<'Animal'>. C<Dog> does not have C<Class::Abstract> in its own C<@ISA>,
172 so the check passes.
173  
174 =head2 Only the class that asks is abstract
175  
176 Being abstract is B<not> passed down to child classes. If you want an
177 abstract class below another abstract class, list C<Class::Abstract> in
178 that class too:
179  
180 package Animal; use parent 'Class::Abstract'; # abstract
181 package Mammal; use parent 'Class::Abstract', 'Animal'; # also abstract
182 package Dog; use parent -norequire, 'Mammal'; # concrete
183  
184 =head2 Turning the check off
185  
186 Sometimes a test needs an object of an abstract class. Two settings turn
187 the check off. If B<either> one is on, the check is off.
188  
189 =over 4
190  
191 =item 1. The variable C<$Class::Abstract::BYPASS>
192  
193 Set it to a true value. Always use C<local>, so the setting ends at the
194 end of the block:
195  
196 my $animal = do { local $Class::Abstract::BYPASS = 1; Animal->new };
197  
198 =item 2. The setting C<harness_bypass> together with a test harness
199  
200 If C<< $Class::Abstract::config{harness_bypass} >> is true B<and> the
201 environment variable C<HARNESS_ACTIVE> is true, the check is off.
202 C<harness_bypass> is false by default, so the check is B<on> in your
203 tests unless you change it.
204  
205 =back
206  
207 C<$BYPASS> is checked first. If C<$BYPASS> is true, setting
208 C<harness_bypass> to 0 does B<not> turn the check back on.
209  
210 B<Changed in version 0.03:> before 0.03, C<harness_bypass> was 1 by
211 default. That meant the check was B<off> in every test suite. To get
212 the old behaviour back, put this near the top of your test files:
213  
214 $Class::Abstract::config{harness_bypass} = 1;
215  
216 =cut
217  
218 15 our $VERSION = '0.04';
219  
220 # ---------------------------------------------------------------------------
221 # Constants
222 # ---------------------------------------------------------------------------
223  
224 # Self-referential constant: the canonical name of this package.
225 15 Readonly::Scalar my $SELF => __PACKAGE__;
226  
227 # Return::Set schema for import(): it always hands back the class name.
228 15 Readonly::Scalar my $IMPORT_SCHEMA => { type => 'string' };
229  
230 # Every message this module can raise, in one place. Keys are
231 # "<routine>:<condition>" so _resolve_class() can build them from the
232 # routine name. The text is part of the public contract (see MESSAGES):
233 # callers and tests match on it, so change it only in a major release.
234 15 Readonly::Hash my %MESSAGE => (
235 'abstract' => 'Cannot instantiate abstract class %s directly',
236 'new:unblessed' => 'new() invocant must be a class name or blessed object, got %s',
237 'new:undef' => 'new() requires a defined class name as invocant',
238 'check:unblessed' => 'check_abstract() requires a class name or blessed object, got %s',
239 'check:undef' => 'check_abstract() requires a defined class name',
240 'is_abstract:unblessed' => 'is_abstract() requires a class name or object invocant, got %s',
241 'is_abstract:undef' => 'is_abstract() requires a class name or object invocant',
242 'internal:key' => 'Class::Abstract internal error: unknown message key %s',
243 );
244  
245 # ---------------------------------------------------------------------------
246 # Public variables
247 # ---------------------------------------------------------------------------
248  
249 # Set to a true value to suppress all abstract-class croaks globally.
250 # Always use 'local' in tests to prevent state from bleeding between cases.
251 15 our $BYPASS = 0;
252  
253 # Runtime tunables. Modify $config{harness_bypass} to control whether
254 # HARNESS_ACTIVE suppresses enforcement.
255 15 our %config = (
256 # 1 = suppress croaks when HARNESS_ACTIVE is set. Off by default (since
257 # 0.03) so that test suites catch accidental abstract instantiation.
258 harness_bypass => 0,
259 );
260  
261 # ---------------------------------------------------------------------------
262 # PUBLIC INTERFACE
263 # ---------------------------------------------------------------------------
264  
265 =head1 METHODS
266  
267 =head2 import
268  
269 use Class::Abstract;
270  
271 Perl calls C<import()> for you when you write C<use Class::Abstract;>.
272 You do not normally call it yourself.
273  
274 It makes the package that contains the C<use> line abstract. It does
275 this by adding C<'Class::Abstract'> to that package's C<@ISA>. The
276 result is the same as C<use parent 'Class::Abstract'>.
277  
278 =head3 ARGUMENTS
279  
280 None that you pass yourself. Perl passes the string
281 C<'Class::Abstract'> as the first argument. Anything in an import list
282 (for example C<use Class::Abstract qw(x y)>) is ignored.
283  
284 =head3 RETURNS
285  
286 The string C<'Class::Abstract'>. C<use> throws this value away, so you
287 only see it if you call C<< Class::Abstract->import >> yourself.
288  
289 =head3 SIDE EFFECTS
290  
291 Adds C<'Class::Abstract'> to the end of the calling package's C<@ISA>.
292 It does B<nothing> in these cases:
293  
294 =over 4
295  
296 =item * C<'Class::Abstract'> is already in that C<@ISA>. So writing
297 C<use Class::Abstract;> twice is safe.
298  
299 =item * C<import()> was reached through a subclass, for example
300 C<use Animal;> where C<Animal> is abstract. Subclasses inherit
301 C<import()>, and only C<use Class::Abstract;> may make a package abstract.
302  
303 =item * The calling package is C<Class::Abstract> itself. A class cannot
304 be its own parent.
305  
306 =item * Perl cannot tell which package is calling (this can happen in
307 unusual code, such as a C<BEGIN> block inside a string C<eval>). Without
308 this rule, the module would change C<@main::ISA> by mistake.
309  
310 =back
311  
312 It does not change the global variables C<$_>, C<$@> or C<$!>, and it
313 does not touch an C<alarm()> timer. (Before version 0.03 it cleared
314 C<$@>.)
315  
316 =head3 EXAMPLE
317  
318 package Vehicle;
319 use Class::Abstract; # @Vehicle::ISA is now ('Class::Abstract')
320 use Class::Abstract; # no change: it is already there
321  
322 package Car;
323 our @ISA = ('Vehicle'); # Car is concrete
324  
325 package main;
326 my $car = Car->new; # works
327 Vehicle->new; # dies
328  
329 To load the module B<without> making the current package abstract, pass
330 an empty list. Perl then does not call C<import()>:
331  
332 use Class::Abstract (); # main is NOT made abstract
333  
334 =head3 API SPECIFICATION
335  
336 =head4 Input
337  
338 {
339 class => { type => 'string', optional => 0 }, # always 'Class::Abstract'
340 }
341  
342 =head4 Output
343  
344 {
345 type => 'string',
346 }
347  
348 =head3 MESSAGES
349  
350 None. C<import()> never dies and never warns.
351  
352 =cut
353  
354 57 ▶sub import {
Subroutine import: called CC=6 SCAR=17.9
355 57 my ($class) = @_;
356 57 my $caller = caller;
357  
358 # Register the caller only when it is a real package other than this one
359 # and is not already registered (keeps repeated 'use' idempotent).
360 # The defined/length guard stops '' from resolving to @main::ISA.
361 # Subclasses inherit import(), so "use Animal;" would otherwise make the
362 # *user* of Animal abstract. Only "use Class::Abstract" may register.
363 57 ▶ if (($class eq $SELF) && defined($caller) && length($caller) && ($caller ne $SELF) && !_is_direct_abstract($caller)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($class eq $SELF and defined $caller and length $caller and $caller ne $SELF and not _is_direct_abstract($caller)) 41 15 56
Condition100%12/12
$class eq $SELF and defined $caller and length $caller and $caller ne $SELF and not _is_direct_abstract($caller)
!ll&&!rl&&r
9642
$class eq $SELF and defined $caller and length $caller and $caller ne $SELF
!ll&&!rl&&r
7248
$class eq $SELF and defined $caller and length $caller
!ll&&!rl&&r
3450
$class eq $SELF and defined $caller
!ll&&!rl&&r
2154
MC/DC100%5/5
$class eq $SELF and defined $caller and length $caller and $caller ne $SELF and not _is_direct_abstract($caller)
$class eq $SELF defined $caller length $caller $caller ne $SELF not _is_direct_abstract($caller)
Truth table100%6/6
A and B and C and D and not(E)
A= $class eq $SELFB= defined $callerC= length $callerD= $caller ne $SELFE= not _is_direct_abstract($caller)
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
364 # Writing another package's @ISA needs a symbolic reference.
365 15 ▶ no strict 'refs'; ## no critic (ProhibitNoStrict)
Subroutine BEGIN: called CC=1 SCAR=0.0
366 41 push @{"${caller}::ISA"}, $SELF;
367 }
368  
369 # set_return() validates through code that clears $@, which would wipe
370 # an error the caller has not looked at yet. Restore it afterwards.
371 # (Not "local $@": on Perl < 5.14 that can lose a propagating die.)
372 56 my $saved_error = $@;
373 56 my $result = set_return($class, $IMPORT_SCHEMA);
374 52 $@ = $saved_error; ## no critic (RequireLocalizedPunctuationVars)
375  
376 52 return $result;
377 }
378  
379 =head2 new
380  
381 my $obj = ConcreteClass->new;
382 my $obj = ConcreteClass->new(name => 'Rex'); # arguments are ignored
383 my $copy = $obj->new; # new, empty object of the same class
384  
385 Makes a new, empty object, but only for a concrete class.
386  
387 =over 4
388  
389 =item * If the class is abstract, C<new()> dies with an error message.
390  
391 =item * If the class is concrete, C<new()> returns an empty hash
392 reference blessed into that class.
393  
394 =back
395  
396 Child classes usually call this through C<< $class->SUPER::new >> from
397 their own C<new()>. That works because the check looks at the class name
398 on the left of the arrow (the child), not at the class where C<new()> is
399 written.
400  
401 =head3 ARGUMENTS
402  
403 =over 4
404  
405 =item C<$invocant> (required)
406  
407 The class name or object on the left of the arrow. In C<< Dog->new >>
408 it is the string C<'Dog'>. If it is an object, the object's class is
409 used. It must not be C<undef>, the empty
410 string, or a reference that is not an object (such as C<[]> or C<{}>).
411  
412 =item C<%args> (optional)
413  
414 Any other arguments. They are accepted and B<ignored>. This lets a
415 child class pass its arguments to C<SUPER::new> without errors. The
416 child class must store its own data after C<SUPER::new> returns.
417  
418 =back
419  
420 =head3 RETURNS
421  
422 A new, empty hash reference, blessed into the class.
423  
424 =head3 SIDE EFFECTS
425  
426 None, except that C<bless> creates the package in Perl's symbol table if
427 it did not exist yet. (The check itself never creates a package.)
428  
429 It does not change the global variables C<$_>, C<$@> or C<$!>, and it
430 does not touch an C<alarm()> timer.
431  
432 =head3 EXAMPLE
433  
434 package Animal;
435 use parent 'Class::Abstract';
436  
437 package Dog;
438 our @ISA = ('Animal');
439  
440 sub new {
441 my ($class, %args) = @_;
442 my $self = $class->SUPER::new; # the check happens here
443 $self->{name} = $args{name};
444 return $self;
445 }
446  
447 package main;
448 my $rex = Dog->new(name => 'Rex'); # works: Dog is concrete
449  
450 eval { Animal->new }; # dies: Animal is abstract
451 print $@; # Cannot instantiate abstract class Animal directly at ...
452  
453 =head3 API SPECIFICATION
454  
455 =head4 Input
456  
457 {
458 invocant => {
459 type => 'string|object', # class name, or an object of that class
460 optional => 0,
461 min => 1, # a name must not be empty
462 },
463 }
464  
465 =head4 Output
466  
467 {
468 type => 'object', # a hashref blessed into the class
469 }
470  
471 =head3 MESSAGES
472  
473 Message What it means / What to do
474 ------- --------------------------
475 Cannot instantiate abstract class CLASS CLASS is abstract and no bypass is on.
476 directly Make an object of a child class instead.
477  
478 new() invocant must be a class name or new() was called as a plain function
479 blessed object, got TYPE with a reference that is not an object
480 (TYPE is ARRAY, HASH, CODE, ...).
481 Call it as Class->new or $obj->new.
482  
483 new() requires a defined class name as new() was called as a plain function
484 invocant with undef or ''. Pass a class name.
485  
486 =cut
487  
488 308 ▶sub new {
Subroutine new: called CC=1 SCAR=0.0
Pod documented
489 308 my ($invocant) = @_;
490  
491 # Validate the invocant, then refuse abstract classes; both helpers
492 # croak on failure so reaching bless means the class is instantiable.
493 308 my $class = _resolve_class('new', $invocant);
494 278 _enforce($class);
495  
496 226 return bless {}, $class;
497 }
498  
499 =head2 check_abstract
500  
501 Class::Abstract::check_abstract($class);
502  
503 Runs the same check as C<new()>, but does not make an object.
504  
505 Use it when your abstract class writes its B<own> C<new()> and that
506 C<new()> does not call C<< $class->SUPER::new >>. In that case
507 C<Class::Abstract::new()> never runs, so nothing checks the class. Call
508 C<check_abstract()> as the first line of your C<new()> to put the check
509 back.
510  
511 =head3 ARGUMENTS
512  
513 =over 4
514  
515 =item C<$invocant> (required)
516  
517 The class to check: a class name (a string) or an object. If it is an
518 object, the object's class is used. In your own C<new()>, pass the
519 C<$class> variable. It must not be C<undef>, the empty string, or a reference
520 that is not an object.
521  
522 =back
523  
524 =head3 RETURNS
525  
526 Nothing if the class is concrete or a bypass is on: C<undef> in scalar
527 context, or an empty list in list context. Otherwise it dies.
528  
529 =head3 SIDE EFFECTS
530  
531 None. It obeys C<$BYPASS> and C<harness_bypass> in exactly the same way
532 as C<new()>.
533  
534 It does not change the global variables C<$_>, C<$@> or C<$!>, and it
535 does not touch an C<alarm()> timer.
536  
537 =head3 EXAMPLE
538  
539 package Shape;
540 use parent 'Class::Abstract';
541  
542 sub new {
543 my ($class, %args) = @_;
544 Class::Abstract::check_abstract($class); # dies if $class is Shape
545 return bless { sides => $args{sides} }, $class;
546 }
547  
548 package Square;
549 our @ISA = ('Shape');
550  
551 package main;
552 my $sq = Square->new(sides => 4); # works
553 Shape->new(sides => 4); # dies: Shape is abstract
554  
555 =head3 API SPECIFICATION
556  
557 =head4 Input
558  
559 {
560 invocant => {
561 type => 'string|object',
562 optional => 0,
563 min => 1,
564 },
565 }
566  
567 =head4 Output
568  
569 {
570 type => 'undef',
571 }
572  
573 =head3 MESSAGES
574  
575 Message What it means / What to do
576 ------- --------------------------
577 Cannot instantiate abstract class CLASS The same as for new().
578 directly
579  
580 check_abstract() requires a class name The argument was a reference that is
581 or blessed object, got TYPE not an object. Pass $class or $self.
582  
583 check_abstract() requires a defined The argument was undef or ''. This
584 class name usually means "my $class = shift;"
585 is missing from your new().
586  
587 =cut
588  
589 113 ▶sub check_abstract {
Subroutine check_abstract: called CC=1 SCAR=0.0
Pod documented
590 113 my ($invocant) = @_;
591  
592 # Same rules as new(), minus the bless: the caller builds the object.
593 113 _enforce(_resolve_class('check', $invocant));
594  
595 82 return;
596 }
597  
598 =head2 is_abstract
599  
600 my $yes_or_no = SomeClass->is_abstract;
601 my $yes_or_no = $obj->is_abstract;
602 my $yes_or_no = Class::Abstract->is_abstract('SomeClass');
603 my $yes_or_no = Class::Abstract->is_abstract($obj);
604  
605 Tells you whether a class is abstract. It returns C<1> (yes) or C<0>
606 (no).
607  
608 A class is abstract only when C<Class::Abstract> is in its B<own>
609 C<@ISA>, or when the class B<is> C<Class::Abstract>. A child of an
610 abstract class is B<not> abstract, so C<is_abstract()> returns C<0> for
611 it.
612  
613 Every class below C<Class::Abstract> can call this method.
614  
615 =head3 ARGUMENTS
616  
617 =over 4
618  
619 =item C<$self>
620  
621 Required. The class name or object on the left of the arrow. If no target is given (see
622 below), this is the class that is checked.
623  
624 =item C<$target> (optional)
625  
626 A class name or an object to check B<instead of> the invocant. This is
627 how you ask about any class: C<< Class::Abstract->is_abstract('Dog') >>.
628 If C<$target> is C<undef>, it is treated as "not given".
629  
630 =back
631  
632 =head3 RETURNS
633  
634 The integer C<1> if the class is abstract, otherwise the integer C<0>.
635  
636 A class name that does not exist (for example, a spelling mistake) gives
637 C<0>, not an error.
638  
639 =head3 SIDE EFFECTS
640  
641 None. Asking about a class that does not exist does B<not> create it.
642  
643 It does not change the global variables C<$_>, C<$@> or C<$!>, and it
644 does not touch an C<alarm()> timer.
645  
646 =head3 EXAMPLE
647  
648 Animal->is_abstract; # 1
649 Dog->is_abstract; # 0
650  
651 my $rex = Dog->new(name => 'Rex');
652 $rex->is_abstract; # 0 (asks about Dog)
653  
654 Class::Abstract->is_abstract('Animal'); # 1
655 Class::Abstract->is_abstract($rex); # 0 (asks about Dog)
656 Class::Abstract->is_abstract('Anmial'); # 0 (spelling mistake: no such class)
657  
658 =head3 API SPECIFICATION
659  
660 =head4 Input
661  
662 {
663 self => { type => 'string|object', optional => 0, min => 1 },
664 target => { type => 'string|object', optional => 1, min => 1 },
665 }
666  
667 =head4 Output
668  
669 {
670 type => 'integer',
671 min => 0,
672 max => 1,
673 }
674  
675 =head3 MESSAGES
676  
677 Message What it means / What to do
678 ------- --------------------------
679 is_abstract() requires a class name or The class to check was a reference
680 object invocant, got TYPE that is not an object.
681  
682 is_abstract() requires a class name or The class to check was undef or ''.
683 object invocant
684  
685 =cut
686  
687 245 ▶sub is_abstract {
Subroutine is_abstract: called CC=2 SCAR=6.9
Pod documented
688 245 my ($self, $target) = @_;
689  
690 # An explicit target (Class::Abstract->is_abstract('Foo') or ($obj))
691 # wins; otherwise check the invocant itself. Both go through the same
692 # resolver, so an object argument is checked by its class, not by its
693 # stringification ('Foo=HASH(0x...)').
694 245 ▶ my $class = _resolve_class('is_abstract', defined($target) ? $target : $self);
Branch: 1 branch
BranchTrueFalseTotal
defined $target ? : 37 208 245
695  
696 230 return _is_direct_abstract($class);
697 }
698  
699 # ---------------------------------------------------------------------------
700 # PRIVATE SUBROUTINES
701 #
702 # Not exported and not part of the API. The white-box tests (t/function.t,
703 # t/edge_cases.t, t/mutant_killers.t) call and spy on them directly, which
704 # is why they are plain named subs called by name: a spy installed on the
705 # glob is then seen by every caller.
706 # ---------------------------------------------------------------------------
707  
708 # _fail
709 # Purpose : The single place this module raises an error, so message
710 # text lives only in %MESSAGE.
711 # Entry : $key -- a key of %MESSAGE.
712 # @args -- sprintf arguments for that message.
713 # Exit status : Never returns.
714 # Side effects : Throws via croak. Every frame between here and the user
715 # is in this package (or a subclass), so Carp reports the
716 # user's line, not ours.
717 # Notes : A Readonly hash returns undef for a missing key rather
718 # than dying, so a mistyped key would croak with an empty
719 # message. Report the bad key instead.
720 162 ▶sub _fail {
Subroutine _fail: called CC=2 SCAR=6.9
721 162 my ($key, @args) = @_;
722  
723 162 my $template = $MESSAGE{$key};
724 162 ▶ ($template, @args) = ($MESSAGE{'internal:key'}, $key) unless defined $template;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $template 1 161 162
725  
726 162 croak sprintf($template, @args);
727 }
728  
729 # _resolve_class
730 # Purpose : Turn an invocant into a validated class name, applying one
731 # set of rules for every public routine.
732 # Entry : $routine -- message-key prefix: 'new', 'check' or
733 # 'is_abstract'.
734 # $invocant -- class name, blessed object, or junk.
735 # Exit status : Returns a defined, non-empty class-name string.
736 # Croaks if $invocant is an unblessed reference, undef or ''.
737 # Side effects : None.
738 # Notes : blessed() is tested with defined(), not truth, because an
739 # object blessed into package '0' has blessed() eq '0'
740 # (and ref() eq '0'), which plain truth tests misread.
741 699 ▶sub _resolve_class {
Subroutine _resolve_class: called CC=5 SCAR=16.1
742 699 my ($routine, $invocant) = @_;
743  
744 # An object stands in for its class. Any other reference is a caller
745 # error, never a class name.
746 699 my $pkg = blessed($invocant);
747 699 ▶ if (defined $pkg) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $pkg) { } 184 515 699
elsif (ref $invocant) { } 53 462 515
748 184 $invocant = $pkg;
749 } elsif (ref $invocant) {
750 53 _fail("${routine}:unblessed", ref $invocant);
751 }
752  
753 # undef cannot name a package, and '' would silently mean main::.
754 646 ▶ _fail("${routine}:undef") unless defined($invocant) && length($invocant);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $invocant and length $invocant 37 609 646
Condition100%3/3
defined $invocant and length $invocant
!ll&&!rl&&r
1621609
MC/DC100%2/2
defined $invocant and length $invocant
defined $invocant length $invocant
Truth table100%3/3
A and B
A= defined $invocantB= length $invocant
ABresult
0X0
100
111
755  
756 609 return $invocant;
757 }
758  
759 # _bypass_active
760 # Purpose : Decide whether enforcement is switched off.
761 # Entry : None (reads $BYPASS, %config, $ENV{HARNESS_ACTIVE}).
762 # Exit status : 1 if any bypass applies, else 0.
763 # Side effects : None.
764 # Notes : $BYPASS is checked first and short-circuits, so it wins
765 # over harness_bypass (documented under LIMITATIONS).
766 391 ▶sub _bypass_active {
Subroutine _bypass_active: called CC=4 SCAR=13.9
767 391 ▶ return ($BYPASS || ($config{harness_bypass} && $ENV{HARNESS_ACTIVE})) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$Class::Abstract::BYPASS || $Class::Abstract::config{'harness_bypass'} && $ENV{'HARNESS_ACTIVE'} ? : 50 341 391
Condition100%6/6
$Class::Abstract::BYPASS or $Class::Abstract::config{"harness_bypass"} and $ENV{"HARNESS_ACTIVE"}
l!l&&r!l&&!r
419341
$Class::Abstract::config{"harness_bypass"} and $ENV{"HARNESS_ACTIVE"}
!ll&&!rl&&r
33389
MC/DC100%3/3
$Class::Abstract::BYPASS or $Class::Abstract::config{"harness_bypass"} and $ENV{"HARNESS_ACTIVE"}
$Class::Abstract::BYPASS $Class::Abstract::config{"harness_bypass"} $ENV{"HARNESS_ACTIVE"}
Truth table100%4/4
A or B and C
A= $Class::Abstract::BYPASSB= $Class::Abstract::config{"harness_bypass"}C= $ENV{"HARNESS_ACTIVE"}
ABCresult
1XX1
0111
00X0
0100
768 }
769  
770 # _enforce
771 # Purpose : Croak if $class is directly abstract and no bypass is on.
772 # Entry : $class -- an already-validated class name.
773 # Exit status : Returns $class on success; croaks otherwise.
774 # Side effects : None.
775 # Notes : The bypass test runs first so that, with a bypass on,
776 # _is_direct_abstract() is never called. t/function.t
777 # counts those calls, so keep this order.
778 375 ▶sub _enforce {
Subroutine _enforce: called CC=3 SCAR=11.0
779 375 my ($class) = @_;
780 375 ▶ _fail('abstract', $class) if !_bypass_active() && _is_direct_abstract($class);
Branch: 1 branch
BranchTrueFalseTotal
if not _bypass_active() and _is_direct_abstract($class) 63 311 374
Condition100%3/3
not _bypass_active() and _is_direct_abstract($class)
!ll&&!rl&&r
4227063
MC/DC100%2/2
not _bypass_active() and _is_direct_abstract($class)
not _bypass_active() _is_direct_abstract($class)
Truth table100%3/3
not(A) and B
A= not _bypass_active()B= _is_direct_abstract($class)
ABresult
0X0
100
111
781 312 return $class;
782 }
783  
784 # _direct_isa
785 # Purpose : Return a package's own @ISA without creating the package.
786 # The obvious @{"${class}::ISA"} autovivifies the stash, so a
787 # mere is_abstract('Typo::Name') would conjure an empty
788 # package into existence.
789 # Entry : $class -- package name string. '' means main::.
790 # Exit status : An arrayref. It is the live @ISA if the package and its
791 # @ISA exist, otherwise a new empty arrayref.
792 # Side effects : None. The symbol table is only read, never written.
793 # Notes : The old "'" package separator (Foo'Bar) is not recognised.
794 626 ▶sub _direct_isa {
Subroutine _direct_isa: called CC=9 SCAR=22.0
795 626 my ($class) = @_;
796  
797 # Walk the stash tree one '::' segment at a time from main::. Empty
798 # segments (from '::Foo' or 'Foo::') are skipped, as Perl skips them.
799 # A stash entry may hold a non-glob (e.g. an optimised constant), so
800 # check that each entry really is a glob before dereferencing it.
801 626 my $stash = \%main::;
802 626 foreach my $segment (grep { length } split /::/, $class) {
803 1222 my $glob = $stash->{"${segment}::"};
804 1222 ▶ $stash = (defined($glob) && ref(\$glob) eq 'GLOB') ? *{$glob}{HASH} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $glob && ref \$glob eq 'GLOB' ? : 1204 18 1222
Condition100%3/3
defined $glob and ref \$glob eq "GLOB"
!ll&&!rl&&r
1711204
MC/DC100%2/2
defined $glob and ref \$glob eq "GLOB"
defined $glob ref \$glob eq "GLOB"
Truth table100%3/3
A and B
A= defined $globB= ref \$glob eq "GLOB"
ABresult
0X0
100
111
805 1222 ▶ last unless $stash;
Branch: 1 branch
BranchTrueFalseTotal
unless $stash 18 1204 1222
806 }
807  
808 # The package exists only if every segment resolved. *ISA{ARRAY} is
809 # undef until @ISA is first used, so fall back to an empty list.
810 626 ▶ my $isa = $stash ? $stash->{ISA} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$stash ? : 608 18 626
811 626 ▶ return (defined($isa) && ref(\$isa) eq 'GLOB' && *{$isa}{ARRAY}) || [];
Condition100%7/7
defined $isa && ref \$isa eq 'GLOB' && *{$isa;}{'ARRAY'} || []
l!l
58838
defined $isa and ref \$isa eq "GLOB" and *{$isa;}{"ARRAY"}
!ll
38588
defined $isa and ref \$isa eq "GLOB"
!ll&&!rl&&r
371588
MC/DC100%2/2
defined $isa && ref \$isa eq 'GLOB' && *{$isa;}{'ARRAY'} || []
defined $isa ref \$isa eq "GLOB"
Truth table100%3/3
A and B
A= defined $isaB= ref \$isa eq "GLOB"
ABresult
111
0X0
100
812 }
813  
814 # _is_direct_abstract
815 # Purpose : Decide whether a class is directly abstract: it is
816 # Class::Abstract, or Class::Abstract is in its own @ISA.
817 # Entry : $class -- package name string, or undef.
818 # Exit status : Exactly 1 or 0 (never undef or ''); the mutation tests in
819 # t/mutant_killers.t rely on these exact integers.
820 # Side effects : None. $_ is localised by grep.
821 # Notes : Intentionally shallow: a subclass of an abstract class is
822 # concrete unless it opts in too. Undefined @ISA elements
823 # are skipped so that they do not warn.
824 628 ▶sub _is_direct_abstract {
Subroutine _is_direct_abstract: called CC=5 SCAR=16.1
825 628 my ($class) = @_;
826  
827 # undef names nothing; Class::Abstract itself must never be built;
828 # anything else is abstract iff we sit directly in its @ISA.
829 my $abstract = !defined($class) ? 0
830 : ($class eq $SELF) ? 1
831 628 ▶ : (grep { defined($_) && ($_ eq $SELF) } @{ _direct_isa($class) }) ? 1
Branch: 3 branches
BranchTrueFalseTotal
!defined($class) ? : 4 624 628
$class eq $SELF ? : 12 612 624
grep({defined $_ and $_ eq $SELF;} @{_direct_isa($class);}) ? : 106 505 611
Condition100%3/3
defined $_ && $_ eq $SELF
!ll&&!rl&&r
4100452108
MC/DC100%2/2
defined $_ && $_ eq $SELF
defined $_ $_ eq $SELF
Truth table100%3/3
A && B
A= defined $_B= $_ eq $SELF
ABresult
0X0
100
111
832 : 0;
833  
834 627 return $abstract;
835 }
836  
837 15 1;
838  
839 __END__
↑ Summary