blib/lib/Object/PadX/Enum.pm

filter: Statementstmt 98.7% 163 / 165 Branchbran 76.9% 40 / 52 Conditioncond 62.5% 5 / 8 MC/DCmcdc 40.0% 2 / 5 Subroutinesub 100% 24 / 24 Podpod n/a totaltotal 92.1% 234 / 254 CC 37 SCAR 15.4
CC
37
Cov
92%
_finalize_enum
12.0
_begin_enum
8.0
_split_versioned_pkg
4.6
CRAP 4.6
↑ Summary
1 package Object::PadX::Enum 0.02;
2  
3 13 ▶use v5.22;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 8 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 8 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 8 ▶use Object::Pad 0.825 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 8 ▶use Object::Pad::MOP::Class qw( :experimental(mop) );
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 # Loaded for its XS keyword registrations
11 8 require XSLoader;
12 8 XSLoader::load( __PACKAGE__, our $VERSION );
13  
14 =encoding UTF-8
15  
16 =for highlighter language=perl
17  
18 =head1 NAME
19  
20 C<Object::PadX::Enum> - syntactic sugar for enum-like singleton-bearing C<Object::Pad> classes
21  
22 =head1 SYNOPSIS
23  
24 use Object::PadX::Enum;
25  
26 enum Raptor {
27 item VELOCIRAPTOR ( max_speed_kmh => 60, max_weight_kg => 15, max_height_cm => 50 );
28 item DEINONYCHUS ( max_speed_kmh => 50, max_weight_kg => 80, max_height_cm => 87 );
29 item UTAHRAPTOR ( max_speed_kmh => 35, max_weight_kg => 500, max_height_cm => 150 );
30 item MICRORAPTOR ( max_speed_kmh => 40, max_weight_kg => 1, max_height_cm => 30 );
31 item DROMAEOSAURUS ( max_speed_kmh => 60, max_weight_kg => 15, max_height_cm => 50 );
32  
33 field $max_speed_kmh :param :reader;
34 field $max_weight_kg :param :reader;
35 field $max_height_cm :param :reader;
36  
37 method speed_per_kg { return $max_speed_kmh / $max_weight_kg }
38 method speed_per_cm { return $max_speed_kmh / $max_height_cm }
39  
40 method fastest :common {
41 my ( $top ) = sort { $b->max_speed_kmh <=> $a->max_speed_kmh } $class->values;
42 return $top;
43 }
44 }
45  
46 say Raptor->VELOCIRAPTOR->max_speed_kmh; # 60
47 say Raptor->DEINONYCHUS->speed_per_kg; # 0.625
48 say Raptor->from_ordinal(2)->name; # UTAHRAPTOR
49 say Raptor->from_name("MICRORAPTOR")->speed_per_cm; # 1.33333333333333
50 say 'Fastest in absolute terms: ', Raptor->fastest->name; # VELOCIRAPTOR or DROMAEOSAURUS (tie)
51  
52 =head1 DESCRIPTION
53  
54 C<Object::PadX::Enum> adds two keywords on top of L<Object::Pad>:
55  
56 =over 4
57  
58 =item * C<enum NAME ATTRS? { ... }>
59  
60 Declares a class (using L<Object::Pad>'s C<class> machinery) and auto-injects
61 C<$ordinal :reader> and C<name :reader> fields. The C<name> reader returns the
62 identifier under which the singleton was declared (e.g. C<"RED">). Inside the
63 block, all normal C<Object::Pad> constructs (C<field>, C<method>, C<ADJUST>,
64 ...) are available, plus the C<item> keyword.
65  
66 The following class-level attributes are accepted:
67  
68 =over 4
69  
70 =item C<:isa(CLASS)>, C<:isa(CLASS VERSION)>
71  
72 =item C<:extends(CLASS)>, C<:extends(CLASS VERSION)>
73  
74 Declares a superclass; equivalent to L<Object::Pad>'s C<:isa>. The package is
75 loaded automatically. If a VERSION is given, C<< CLASS->VERSION(VERSION) >> is
76 called to enforce it.
77  
78 An C<enum> may inherit from another C<enum>. Fields, methods, roles and
79 C<ADJUST> phasers from the parent are inherited normally. The parent's
80 B<items> are I<not> inherited: the child has its own ordinal-zero-based item
81 sequence, and accessing a parent item name on the child raises an error. The
82 child's C<values>, C<from_ordinal> and C<from_name> see only the child's
83 items. A parent enum must be finalized (i.e. its declaration must have
84 already executed at runtime) before a child enum that inherits from it; in
85 practice this is satisfied by normal source ordering and C<use> ordering.
86  
87 =item C<:does(ROLE)>, C<:does(ROLE VERSION)>
88  
89 Composes a role into the enum class. May be repeated for multiple roles. The
90 role package is loaded automatically.
91  
92 =back
93  
94 The class attributes C<:abstract>, C<:strict>, C<:repr> and C<:lexical_new>
95 are not supported. C<:abstract> is semantically incompatible with C<item>
96 (singletons cannot be constructed for an abstract class); the others have no
97 public L<Object::Pad::MOP::Class> entry point and would require reaching into
98 private Object::Pad internals.
99  
100 =item * C<item NAME ( ARGS );>
101  
102 Declares a named singleton instance of the enclosing C<enum>. C<ARGS> is the
103 key/value list passed to the auto-generated constructor; the parentheses (and
104 the arg list) are optional, so C<item FOO;> is equivalent to C<item FOO();>.
105  
106 =back
107  
108 After the C<enum> block closes, the following class-level methods are
109 installed on the enum class for each declared singleton C<NAME>:
110  
111 $singleton = ClassName->NAME; # the named singleton
112 @all = ClassName->values; # all singletons in declaration order
113 $byord = ClassName->from_ordinal(0);
114 $byname = ClassName->from_name("RED");
115  
116 Direct construction via C<< ClassName->new(...) >> is blocked after the
117 C<enum> block closes; the only ways to obtain a singleton are the per-item
118 accessor, C<from_name>, and C<from_ordinal>. Subclasses (whether plain
119 C<class> or another C<enum>) may still call C<new> on themselves; the block
120 applies only to direct invocation on the enum class itself.
121  
122 =head1 CAVEATS
123  
124 =over 4
125  
126 =item *
127  
128 User C<field>s require explicit C<:param> if you intend to set them via
129 C<item> args. C<Object::PadX::Enum> does I<not> inject C<:param> automatically.
130  
131 =item *
132  
133 Singletons are constructed at the runtime of the compilation unit that
134 contains the C<enum> declaration, after that unit's C<UNITCHECK> phase. They
135 are therefore not visible from earlier C<BEGIN>/C<UNITCHECK> blocks of the
136 same unit. Normal runtime code (including code inside C<do BLOCK> and
137 C<eval "STRING"> blocks executed during main runtime) sees them as expected.
138  
139 =item *
140  
141 C<enum>-level C<:abstract>, C<:strict>, C<:repr> and C<:lexical_new> are not
142 supported. See the description of the C<enum> keyword above for the rationale;
143 C<:isa> and C<:does> I<are> supported.
144  
145 =item *
146  
147 The names C<values>, C<from_ordinal>, C<from_name>, C<ordinal> and C<name> are
148 reserved and must not be used as C<item> names.
149  
150 =back
151  
152 =cut
153  
154 # Per-class state captured during compilation.
155 # $Pending{$class} = { meta => $meta, items => [ [ $name, \@args, $line ], ... ], seen => { $name => 1 } }
156 8 my %Pending;
157  
158 # Permanent per-class registry of finalized enum item names, in declaration
159 # order. Populated by `_finalize_enum`. Queried by descendant enum finalizes
160 # (to shadow inherited item accessors) and could be useful for introspection
161 # in the future. Keys are class names; values are arrayrefs of item names.
162 my %EnumItems;
163  
164 8 my %RESERVED_ITEM_NAMES = map { $_ => 1 } qw(
165 values from_ordinal from_name ordinal name
166 new BUILD DOES META
167 );
168  
169 sub import {
170 20 ▶ my $class = shift;
Subroutine import: called CC=1 SCAR=0.0
171 20 my $caller = caller;
172  
173 20 $^H{ 'Object::PadX::Enum/enum' } = 1;
174 20 $^H{ 'Object::PadX::Enum/item' } = 1;
175  
176 20 Object::Pad->import_into( $caller );
177 }
178  
179 # Attributes that have a documented public-MOP entry point.
180 8 my %ENUM_ATTR_HANDLERS = (
181 isa => \&_attr_isa,
182 extends => \&_attr_isa,
183 does => \&_attr_does,
184 );
185  
186 # Attributes that exist on Object::Pad's `class` keyword but are deliberately
187 # rejected here. The message explains why so users aren't left guessing.
188 8 my %ENUM_ATTR_REJECTED = (
189 abstract => "':abstract' is incompatible with enum: singleton values cannot be constructed for an abstract class",
190 strict => "':strict' is not supported on enum (no public Object::Pad MOP entry point); declare a plain 'class' instead",
191 repr => "':repr' is not supported on enum (no public Object::Pad MOP entry point); declare a plain 'class' instead",
192 lexical_new => "':lexical_new' is not supported on enum (no public Object::Pad MOP entry point); declare a plain 'class' instead",
193 );
194  
195 # Load $pkg via `require`, mirroring Object::Pad's :isa/:does autoload. Returns
196 # silently on success; croaks on failure.
197 sub _require_package {
198 14 ▶ my ( $pkg, $for ) = @_;
Subroutine _require_package: called CC=3 SCAR=11.2
199  
200 # Skip require for packages already defined inline (no .pm needed).
201 8 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
202 14 ▶ keys %{ "${pkg}::" } and return;
Branch: 1 branch
BranchTrueFalseTotal
keys %{"${pkg}::";} and return 13 1 14
203  
204 1 ( my $file = "$pkg.pm" ) =~ s{::}{/}g;
205 1 ▶ eval { require $file; 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require $file; 1 } } or croak("Failed to load package '${pkg}' for ${for}: $@") 1 0 1
206 or croak "Failed to load package '$pkg' for $for: $@";
207  
208 0 return;
209 }
210  
211 # Parse "Pkg" or "Pkg VER" into ($pkg, $ver). $ver is undef when absent.
212 sub _split_versioned_pkg {
213 14 ▶ my ( $raw, $attr_name ) = @_;
Subroutine _split_versioned_pkg: called CC=4 SCAR=15.2
214  
215 14 ▶ defined $raw && length $raw
Branch: 1 branch
BranchTrueFalseTotal
defined $raw and length $raw or croak("Attribute ':${attr_name}' requires a value") 0 14 14
Condition33%1/3
defined $raw and length $raw
!ll&&!rl&&r
0014
MC/DC0%0/2
defined $raw and length $raw
defined $raw length $raw
Truth table33%1/3
A and B
A= defined $rawB= length $raw
ABresult
0X0
100
111
216 or croak "Attribute ':$attr_name' requires a value";
217  
218 14 my ( $pkg, $ver, $extra ) = split /\s+/, $raw, 3;
219 14 ▶ defined $extra
Branch: 1 branch
BranchTrueFalseTotal
defined $extra and croak("Attribute ':$attr_name($raw)' has too many parts; expected 'PACKAGE' or 'PACKAGE VERSION'") 0 14 14
220 and croak "Attribute ':$attr_name($raw)' has too many parts; expected 'PACKAGE' or 'PACKAGE VERSION'";
221  
222 14 return ( $pkg, $ver );
223 }
224  
225 sub _attr_isa {
226 11 ▶ my ( $state, $value ) = @_;
Subroutine _attr_isa: called CC=3 SCAR=11.0
227  
228 exists $state->{ isa }
229 11 ▶ and croak "Multiple ':isa' / ':extends' attributes on enum '$state->{name}'";
Branch: 1 branch
BranchTrueFalseTotal
exists $state->{"isa"} and croak(qq[Multiple ':isa' / ':extends' attributes on enum '$state->{"name"}']) 1 10 11
230  
231 10 my ( $pkg, $ver ) = _split_versioned_pkg( $value, 'isa' );
232 10 _require_package( $pkg, "':isa($pkg)' on enum '$state->{name}'" );
233 9 ▶ defined $ver and $pkg->VERSION( $ver );
Branch: 1 branch
BranchTrueFalseTotal
defined $ver and $pkg->VERSION($ver) 2 7 9
234  
235 8 $state->{ isa } = $pkg;
236 8 return;
237 }
238  
239 sub _attr_does {
240 4 ▶ my ( $state, $value ) = @_;
Subroutine _attr_does: called CC=2 SCAR=7.0
241  
242 4 my ( $pkg, $ver ) = _split_versioned_pkg( $value, 'does' );
243 4 _require_package( $pkg, "':does($pkg)' on enum '$state->{name}'" );
244 4 ▶ defined $ver and $pkg->VERSION( $ver );
Branch: 1 branch
BranchTrueFalseTotal
defined $ver and $pkg->VERSION($ver) 0 4 4
245  
246 4 push @{ $state->{ roles } }, $pkg;
247 4 return;
248 }
249  
250 # Called by XS at compile-time when `enum NAME ATTRS? {` is encountered.
251 sub _begin_enum {
252 28 ▶ my ( $name, $attrs ) = @_;
Subroutine _begin_enum: called CC=8 SCAR=20.8
253  
254 28 ▶ exists $Pending{ $name }
Branch: 1 branch
BranchTrueFalseTotal
exists $Pending{$name} and croak("Cannot declare enum '${name}'; already being defined") 0 28 28
255 and croak "Cannot declare enum '$name'; already being defined";
256  
257 28 my $state = { name => $name, roles => [] };
258 28 ▶ for my $pair ( @{ $attrs // [] } ) {
Condition50%1/2
$attrs // []
l!l
280
MC/DC0%0/1
$attrs // []
$attrs
Truth table50%1/2
A
A= $attrs
Aresult
11
00
259 19 my ( $attr, $value ) = @$pair;
260  
261 19 ▶ if ( my $msg = $ENUM_ATTR_REJECTED{ $attr } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $msg = $ENUM_ATTR_REJECTED{$attr}) 3 16 19
262 3 croak "$msg (enum '$name')";
263 }
264  
265 16 ▶ my $handler = $ENUM_ATTR_HANDLERS{ $attr }
Branch: 1 branch
BranchTrueFalseTotal
my $handler = $ENUM_ATTR_HANDLERS{$attr} or croak("Unrecognised attribute ':${attr}' on enum '${name}'") 1 15 16
266 or croak "Unrecognised attribute ':$attr' on enum '$name'";
267  
268 15 $handler->( $state, $value );
269 }
270  
271 21 my @begin_args = ( $name );
272 exists $state->{ isa }
273 21 ▶ and push @begin_args, ( isa => $state->{ isa } );
Branch: 1 branch
BranchTrueFalseTotal
exists $state->{"isa"} and push @begin_args, ("isa", $state->{"isa"}) 7 14 21
274  
275 21 my $meta = Object::Pad::MOP::Class->begin_class( @begin_args );
276  
277 21 $meta->add_role( $_ ) for @{ $state->{ roles } };
278  
279 # $ordinal and $_name are reader-only (not :param) so user item args cannot
280 # override them; both are stamped after construction in _finalize_enum.
281 21 ▶ $meta->add_field( '$ordinal', reader => 'ordinal' );
Subroutine ordinal: called CC=1 SCAR=0.0
282 21 ▶ $meta->add_field( '$_name', reader => 'name' );
Subroutine name: called CC=1 SCAR=0.0
283  
284 21 $Pending{ $name } = { meta => $meta, items => [], seen => {} };
285  
286 21 return;
287 }
288  
289 # Called at runtime, in source order, for each `item NAME(args)` statement.
290 sub _register_item {
291 36 ▶ my ( $class, $name, $line, @args ) = @_;
Subroutine _register_item: called CC=4 SCAR=13.9
292  
293 36 ▶ my $entry = $Pending{ $class }
Branch: 1 branch
BranchTrueFalseTotal
my $entry = $Pending{$class} or croak("Internal error: item '${name}' for unknown enum '${class}' at line $line") 0 33 33
294 or croak "Internal error: item '$name' for unknown enum '$class' at line $line";
295  
296 36 ▶ $entry->{ seen }{ $name }
Branch: 1 branch
BranchTrueFalseTotal
$entry->{"seen"}{$name} and croak("Duplicate item '${name}' in enum '${class}' at line $line") 1 32 33
297 and croak "Duplicate item '$name' in enum '$class' at line $line";
298  
299 35 ▶ $RESERVED_ITEM_NAMES{ $name }
Branch: 1 branch
BranchTrueFalseTotal
$RESERVED_ITEM_NAMES{$name} and croak("item name '${name}' is reserved in enum '${class}' at line $line") 2 30 32
300 and croak "item name '$name' is reserved in enum '$class' at line $line";
301  
302 30 push @{ $entry->{ items } }, [ $name, \@args, $line ];
303 30 $entry->{ seen }{ $name } = 1;
304  
305 30 return;
306 }
307  
308 # Called at runtime, once, after all item statements for the enum have run.
309 sub _finalize_enum {
310 18 ▶ my ( $class ) = @_;
Subroutine _finalize_enum: called CC=12 SCAR=24.9
311  
312 18 ▶ my $entry = delete $Pending{ $class }
Branch: 1 branch
BranchTrueFalseTotal
my $entry = delete $Pending{$class} or croak("Internal error: _finalize_enum on unknown enum '${class}'") 0 18 18
313 or croak "Internal error: _finalize_enum on unknown enum '$class'";
314  
315 18 my $meta = $entry->{ meta };
316 18 my $ord_field = $meta->get_field( '$ordinal' );
317 18 my $name_field = $meta->get_field( '$_name' );
318 18 my @ordered;
319  
320 18 my $n = 0;
321 18 for my $item ( @{ $entry->{ items } } ) {
322 29 my ( $name, $args, $line ) = @$item;
323  
324 29 my $instance = eval { $class->new( @$args ) };
325 29 ▶ $@ and croak "Failed to construct enum value '$name' of '$class' at line $line: $@";
Branch: 1 branch
BranchTrueFalseTotal
$@ and croak("Failed to construct enum value '${name}' of '${class}' at line ${line}: $@") 0 29 29
326  
327 # Stamp the ordinal and name after construction so they aren't user-facing :params.
328 29 $ord_field->value( $instance ) = $n;
329 29 $name_field->value( $instance ) = $name;
330  
331 29 push @ordered, [ $name, $instance ];
332 29 $n++;
333 }
334  
335 8 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
336 8 ▶ no warnings 'redefine';
Subroutine BEGIN: called CC=1 SCAR=0.0
337  
338 18 my %own_names;
339 18 for my $pair ( @ordered ) {
340 29 my ( $name, $instance ) = @$pair;
341 29 $own_names{ $name } = 1;
342 29 ▶ *{ "${class}::${name}" } = sub { $instance };
Subroutine __ANON__: called CC=1 SCAR=0.0
343 }
344  
345 18 *{ "${class}::values" } = sub {
346 5 ▶ return map { $_->[1] } @ordered;
Subroutine __ANON__: called CC=1 SCAR=0.0
347 18 };
348  
349 18 *{ "${class}::from_ordinal" } = sub {
350 6 ▶ my ( undef, $idx ) = @_;
Subroutine __ANON__: called CC=4 SCAR=13.9
351 6 ▶ defined $idx or return undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $idx or return undef 0 6 6
352 6 ▶ $idx >= 0 && $idx < @ordered or return undef;
Branch: 1 branch
BranchTrueFalseTotal
$idx >= 0 and $idx < @ordered or return undef 2 4 6
Condition100%3/3
$idx >= 0 and $idx < @ordered
!ll&&!rl&&r
114
MC/DC100%2/2
$idx >= 0 and $idx < @ordered
$idx >= 0 $idx < @ordered
Truth table100%3/3
A and B
A= $idx >= 0B= $idx < @ordered
ABresult
0X0
100
111
353 4 return $ordered[ $idx ][ 1 ];
354 18 };
355  
356 18 *{ "${class}::from_name" } = sub {
357 6 ▶ my ( undef, $want ) = @_;
Subroutine __ANON__: called CC=4 SCAR=13.9
358 6 ▶ defined $want or return undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $want or return undef 0 6 6
359 6 for my $pair ( @ordered ) {
360 13 ▶ return $pair->[1] if $pair->[0] eq $want;
Branch: 1 branch
BranchTrueFalseTotal
if $pair->[0] eq $want 4 9 13
361 }
362 2 return undef;
363 18 };
364  
365 # Shadow ancestor enum items not redefined locally. A child enum inherits
366 # fields/methods from a parent enum but loses the parent's items: accessing
367 # a parent item name on the child raises a clear error rather than
368 # returning the parent's singleton via MRO.
369 18 require mro;
370 18 my $linear = mro::get_linear_isa( $class );
371 18 my %shadowed;
372 18 for my $ancestor ( @$linear ) {
373 44 ▶ next if $ancestor eq $class;
Branch: 1 branch
BranchTrueFalseTotal
if $ancestor eq $class 18 26 44
374 26 ▶ my $ancestor_items = $EnumItems{ $ancestor } or next;
Branch: 1 branch
BranchTrueFalseTotal
my $ancestor_items = $EnumItems{$ancestor} or next 22 4 26
375 4 for my $aname ( @$ancestor_items ) {
376 8 ▶ next if $own_names{ $aname };
Branch: 1 branch
BranchTrueFalseTotal
if $own_names{$aname} 1 7 8
377 7 ▶ next if $shadowed{ $aname };
Branch: 1 branch
BranchTrueFalseTotal
if $shadowed{$aname} 0 7 7
378 7 $shadowed{ $aname } = $ancestor;
379 7 my $msg = "'$aname' is not an item of '$class' (inherited from '$ancestor', shadowed)";
380 7 ▶ *{ "${class}::${aname}" } = sub { croak $msg };
Subroutine __ANON__: called CC=1 SCAR=0.0
381 }
382 }
383  
384 # Register before installing the `new` override so any descendant enum
385 # whose finalize runs later (and which calls our `new` via MRO) sees us in
386 # the registry.
387 18 $EnumItems{ $class } = [ map { $_->[0] } @ordered ];
388  
389 # Block external construction. Capture the original Object::Pad-generated
390 # `new` so subclass enums (and plain subclasses) can pass through during
391 # their own construction; only direct calls on the enum class itself are
392 # rejected.
393 18 my @item_names = map { $_->[0] } @ordered;
394 18 my $orig_new = \&{ "${class}::new" };
395  
396 18 my $new_msg = "Cannot construct new instances of enum class '$class' directly";
397 18 ▶ if ( @item_names ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@item_names) 16 2 18
398 16 $new_msg .= '; use one of: ' . join( ', ', @item_names );
399 16 $new_msg .= " (or ${class}->from_name / ${class}->from_ordinal)";
400 }
401  
402 18 *{ "${class}::new" } = sub {
403 5 ▶ my $invocant = shift;
Subroutine __ANON__: called CC=2 SCAR=7.1
404 5 ▶ $invocant ne $class
Branch: 1 branch
BranchTrueFalseTotal
$invocant ne $class and return $invocant->$orig_new(@_) 0 5 5
405 and return $invocant->$orig_new( @_ );
406 5 croak $new_msg;
407 18 };
408  
409 18 return;
410 }
411  
412 8 0x55AA;
↑ Summary