blib/lib/Object/Result.pm

filter: Statementstmt 90.5% 202 / 223 Branchbran 62.2% 51 / 82 Conditioncond 62.5% 20 / 32 MC/DCmcdc 31.5% 6 / 19 Subroutinesub 95.2% 40 / 42 Podpod n/a totaltotal 80.1% 319 / 398 CC 54 SCAR 22.0
CC
54
Cov
81%
_die_on_invalid_syntax
33.7
_transform_result
20.3
_croak_failure
11.2
CRAP 9.0
↑ Summary
1 package Object::Result;
2  
3 13 ▶use 5.014; use warnings; use autodie;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 13 our $VERSION = '0.000002';
6  
7 13 ▶use Method::Signatures;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 13 ▶use Keyword::Simple;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 13 ▶use Hash::Util::FieldHash 'fieldhash';
Subroutine BEGIN: called CC=1 SCAR=0.0
10 13 ▶use PPI;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 # Storage for all inside-out result objects...
13 13 fieldhash my %impl_of;
14  
15 # Create the new keyword in the caller scope...
16 13 ▶method import {
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine import: called CC=2 SCAR=7.1
Branch: 1 branch
BranchTrueFalseTotal
if scalar @_ > 0 0 13 13
17 13 ▶ Keyword::Simple::define 'result', func ($src_ref) {
Subroutine __ANON__: called CC=3 SCAR=11.3
Branch: 2 branches
BranchTrueFalseTotal
unless scalar @_ > 0 0 13 13
if scalar @_ > 1 0 13 13
18 13 ${$src_ref} = _inject_result($src_ref);
19 13 };
20 }
21  
22 # Remove the keyword upon request...
23 13 ▶method unimport {
Subroutine BEGIN: called CC=1 SCAR=2.6
Subroutine unimport: not called CC=2 SCAR=12.4
Branch: 1 branch
BranchTrueFalseTotal
if scalar @_ > 0 0 0 0
24 0 Keyword::Simple::undefine 'result';
25 }
26  
27  
28 # Parse source cleanly and convert new syntax to old...
29 13 ▶func _inject_result ($src_ref) {
Subroutine BEGIN: called CC=1 SCAR=0.1
Subroutine _inject_result: called CC=6 SCAR=18.7
Branch: 2 branches
BranchTrueFalseTotal
unless scalar @_ > 0 0 13 13
if scalar @_ > 1 0 13 13
30 13 state $WS = qr{ (?: \s++ | \# [^\n]*+ \n )*+ }x;
31  
32 # Check for missing argument (i.e. immediate semicolon or end-of-block)...
33 13 my ($block) = ${$src_ref} =~ m{\A $WS ([;\}]) }xms;
34  
35 # Otherwise parse trailing source and extract top-level structure...
36 13 my ($doc, $post_block_line_number);
37 13 ▶ if (!$block) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($block) 13 0 13
38 # Convert empty block to <FAIL> block...
39 13 ${$src_ref} =~ s{\A $WS \{ $WS \} }{ {<FAIL>} }xms;
40  
41 # Extract structure...
42 13 $doc = PPI::Document->new($src_ref);
43 13 $doc->index_locations;
44  
45 # First significant element should be a block...
46 13 $block = $doc->schild(0)->schild(0)->remove;
47  
48 # Determine line number after block replacement...
49 13 $post_block_line_number = (caller 1)[2] + $block->location->[0] + $block =~ tr/\n// - 1;
50 }
51  
52 # If block, convert to a ctor call)...
53 13 ▶ if (ref($block) && $block->isa("PPI::Structure::Block")) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $block and $block->isa('PPI::Structure::Block')) { } 13 0 13
Condition33%1/3
ref $block and $block->isa("PPI::Structure::Block")
!ll&&!rl&&r
0013
MC/DC0%0/2
ref $block and $block->isa("PPI::Structure::Block")
ref $block $block->isa("PPI::Structure::Block")
Truth table33%1/3
A and B
A= ref $blockB= $block->isa("PPI::Structure::Block")
ABresult
0X0
100
111
54 13 return _transform_result->($block)
55 . "\n#line $post_block_line_number\n" . $doc;
56 }
57  
58 # Or a syntax error...
59 else {
60 0 _die_on_invalid_syntax($block);
61 }
62 }
63  
64 13 ▶func _die_on_invalid_syntax ($block) {
Subroutine BEGIN: called CC=1 SCAR=3.9
Subroutine _die_on_invalid_syntax: not called CC=6 SCAR=35.2
Branch: 2 branches
BranchTrueFalseTotal
unless scalar @_ > 0 0 0 0
if scalar @_ > 1 0 0 0
65 0 state $reclassify = {
66 Word => 'identifier',
67 DashedWord => 'identifier',
68 Magic => 'variable',
69 ArrayIndex => 'array index',
70 Cast => 'operator',
71 Single => 'character string',
72 Double => 'character string',
73 Interpolate => 'character string',
74 Words => 'list constructor',
75 Transliterate => 'transliteration',
76 Match => 'regex match',
77 Substitute => 'regex substitution',
78 Data => 'end of source code',
79 End => 'end of source code',
80 Unknown => 'a syntax error',
81 };
82 # Classify what we actually got...
83 0 ▶ my $unexpected_construct = ref($block) || 'end of statement';
Condition0%0/2
ref $block || 'end of statement'
l!l
00
MC/DC0%0/1
ref $block || 'end of statement'
ref $block
Truth table0%0/2
A
A= ref $block
Aresult
11
00
84  
85 # Make classification more readable...
86 0 $unexpected_construct =~ s{.*::}{};
87 0 ▶ $unexpected_construct = $reclassify->{$unexpected_construct} // $unexpected_construct;
Condition0%0/3
$reclassify->{$unexpected_construct} // $unexpected_construct
l!l&&r!l&&!r
000
MC/DC0%0/2
$reclassify->{$unexpected_construct} // $unexpected_construct
$reclassify->{$unexpected_construct} $unexpected_construct
Truth table0%0/3
A // B
A= $reclassify->{$unexpected_construct}B= $unexpected_construct
ABresult
1X1
011
000
88 0 ▶ $unexpected_construct =~ s{Constructor}{$block =~ /^\{/ ? 'hashref' : 'arrayref' }e;
Branch: 1 branch
BranchTrueFalseTotal
$block =~ /^{/u ? : 0 0 0
89 0 $block =~ s{\n.*}{...}xms;
90  
91 # Report the error...
92 0 _croak(
93 "Invalid syntax for 'result' statement.\n",
94 "Expected block but found \L$unexpected_construct\E ('$block') instead"
95 );
96 }
97  
98 # Default behaviour on any use of a <FAIL> object...
99 13 ▶method _default_fail ($requested_coercion, ...) {
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine _default_fail: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @_ > 0 0 8 8
100 8 my $object_impl = $impl_of{$self};
101  
102 # Work out what to report...
103 my $call_desc
104 8 = sprintf( "call to %s() at %s line %s", @{$object_impl->{'<CONTEXT>'}}[3,1,2] );
105  
106 # Report it...
107 8 _croak( "Object returned by $call_desc\ncan't be used as $requested_coercion" );
108 }
109  
110 # Default behaviour for <BOOL> coercion...
111 13 ▶method _default_bool (...) {
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine _default_bool: called CC=1 SCAR=0.0
112 3 return 1;
113 }
114  
115 # This converts the 'result' block back to standard Perl 5...
116 13 ▶func _transform_result ($block) {
Subroutine BEGIN: called CC=1 SCAR=0.1
Subroutine _transform_result: called CC=19 SCAR=30.1
Branch: 2 branches
BranchTrueFalseTotal
unless scalar @_ > 0 0 13 13
if scalar @_ > 1 0 13 13
117 # Initialize the ctor args with explicit empty list to allow leading commas thereafter...
118 13 my $transformed_block = q{()};
119  
120 # Extract and iterate components insode block...
121 13 my @tokens = $block->schild(0)->schildren;
122 TOKEN:
123 13 ▶ while (my $token = shift @tokens) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $token = shift @tokens) 71 13 84
124  
125 # Consolidate <TYPE> coercions that were parsed as 3 tokens...
126 71 ▶ if ($token eq '<' && @tokens >= 2 && $tokens[1] eq '>') {
Branch: 1 branch
BranchTrueFalseTotal
if ($token eq "<" and @tokens >= 2 and $tokens[1] eq ">") 10 61 71
Condition66%4/6
$token eq "<" and @tokens >= 2 and $tokens[1] eq ">"
!ll&&!rl&&r
61010
$token eq "<" and @tokens >= 2
!ll&&!rl&&r
61010
MC/DC33%1/3
$token eq "<" and @tokens >= 2 and $tokens[1] eq ">"
$token eq "<" @tokens >= 2 $tokens[1] eq ">"
Truth table50%2/4
A and B and C
A= $token eq "<"B= @tokens >= 2C= $tokens[1] eq ">"
ABCresult
0XX0
10X0
1100
1111
127 10 $token = join(q{}, "$token", splice(@tokens, 0, 2));
128 }
129  
130 # Classify token and trailing context...
131 71 ▶ my $next_token_type = substr($tokens[0]//q{}, 0, 1);
Condition100%2/2
$tokens[0] // ""
l!l
6011
MC/DC100%1/1
$tokens[0] // ""
$tokens[0]
Truth table100%2/2
A
A= $tokens[0]
Aresult
11
00
132 71 ▶ my $token_type = $token =~ / < [^)]* > /x ? 'coercion'
Branch: 2 branches
BranchTrueFalseTotal
$token =~ / < [^)]* > /ux ? : 27 44 71
$token->isa('PPI::Token::Word') ? : 10 34 44
133 : $token->isa('PPI::Token::Word') ? 'named'
134 : 'other';
135  
136 # Handle <FAIL>...
137 71 ▶ if ($token eq '<FAIL>') {
Branch: 3 branches
BranchTrueFalseTotal
if ($token eq '<FAIL>') { } 6 65 71
elsif ($token_type ne 'other' and not @tokens) { } 0 65 65
elsif ($token_type ne 'other' and not $next_token_type =~ /[(\{]/u) { } 0 99 99
138 6 ▶ my $MSG = $next_token_type eq '{' ? 'eval'.shift(@tokens) : q{};
Branch: 1 branch
BranchTrueFalseTotal
$next_token_type eq '{' ? : 2 4 6
139 6 my $CROAK_FAILURE
140 = qq{ Object::Result::_croak_failure(\$self,errmsg=>\$errmsg,msg=>[$MSG]) };
141  
142 6 $transformed_block
143 .= q[ , do{ my $errmsg = $@ // $! // @?; my $tested; ]
144 . q[ '<BOOL>' => method (...) { $tested++; 0 }, ]
145 . qq[ '<AUTOLOAD>' => method (...) { \$tested++; $CROAK_FAILURE }, ]
146 . qq[ '<DEFAULT>' => method (...) { \$tested++; $CROAK_FAILURE }, ]
147 . qq[ '<DESTROY>' => method (...) { $CROAK_FAILURE if !\$tested }, ]
148 . q[ } ]
149 ;
150 6 next TOKEN;
151 }
152  
153 # Handle syntax errors...
154 ▶ elsif ($token_type ne 'other' && !@tokens) {
Condition66%2/3
$token_type ne "other" and not @tokens
!ll&&!rl&&r
34310
MC/DC0%0/2
$token_type ne "other" and not @tokens
$token_type ne "other" not @tokens
Truth table66%2/3
A and not(B)
A= $token_type ne "other"B= not @tokens
ABresult
0X0
100
111
155 0 _croak("Missing definition for $token() method");
156 }
157 ▶ elsif ($token_type ne 'other' && $next_token_type !~ /[(\{]/) {
Condition66%2/3
$token_type ne "other" and not $next_token_type =~ /[(\{]/u
!ll&&!rl&&r
34310
MC/DC0%0/2
$token_type ne "other" and not $next_token_type =~ /[(\{]/u
$token_type ne "other" not $next_token_type =~ /[(\{]/u
Truth table66%2/3
A and not(B)
A= $token_type ne "other"B= not $next_token_type =~ /[(\{]/u
ABresult
0X0
100
111
158 0 _croak(
159 "Invalid definition for $token() method\n",
160 "Expected parameter list or method block, but found '$next_token_type'"
161 );
162 }
163  
164 # Handle all <TYPE> coercions (with relaxed default parameter checking)...
165 65 ▶ if ($token_type eq 'coercion') {
Branch: 2 branches
BranchTrueFalseTotal
if ($token_type eq 'coercion') { } 21 44 65
elsif ($token_type eq 'named') { } 10 34 44
166 21 $transformed_block .= " , '$token' => method ";
167 21 ▶ $transformed_block .= '(...)' if $next_token_type ne '(';
Branch: 1 branch
BranchTrueFalseTotal
if $next_token_type ne "(" 20 1 21
168 }
169  
170 # Handle bareword method names...
171 elsif ($token_type eq 'named') {
172 10 $transformed_block .= " , $token => method ";
173 }
174  
175 # Pass anything else through unchanged...
176 else {
177 34 $transformed_block .= $token;
178 }
179 }
180  
181 # The transformed code needs Method::Signatures to function, so prepend it...
182 13 return "{ use Method::Signatures; return Object::Result::_build_result { $transformed_block } }";
183 }
184  
185 # This builds type coercion subroutines...
186 13 ▶func _handler_for (@op_names) {
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine _handler_for: called CC=1 SCAR=0.0
187 # Convert each operator name to <OPNAME>...
188 130 @op_names = map {"<$_>"} @op_names;
189  
190 # Each type coercion is a method...
191 89 ▶ return method (...) {
Subroutine __ANON__: called CC=2 SCAR=6.9
192 89 @_ = $self;
193  
194 # Find implementation of coercion or else default to normal behaviour...
195 13 ▶ use List::Util 'first';
Subroutine BEGIN: called CC=1 SCAR=0.0
196 89 my $object_impl = $impl_of{$self};
197 89 ▶ my $op_name = first {exists $object_impl->{$_}} @op_names;
Subroutine __ANON__: called CC=1 SCAR=0.0
198  
199 # Fall back on <DEFAULT> handler...
200 89 ▶ if (!defined $op_name) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $op_name) 61 28 89
201 61 $op_name = '<DEFAULT>';
202 61 my $call_desc = sprintf( "call to %s() at %s line %s", @{$object_impl->{'<CONTEXT>'}}[3,1,2] );
203 61 push @_, $op_names[0], $call_desc;
204 }
205  
206 # Grab the handler (if any)...
207 89 my $method_impl = $object_impl->{$op_name};
208  
209 # Fake out any error messages...
210 13 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
211 89 *{$object_impl->{'<CONTEXT>'}[0].'::__ANON__'} = $op_name;
212  
213 # Execute the implementation of the coercion...
214 89 goto &{$method_impl};
215 130 };
216 }
217  
218 # Ctor for Object::Result::Object objects...
219 13 ▶func _build_result ($hash_ref) {
Subroutine BEGIN: called CC=1 SCAR=0.1
Subroutine _build_result: called CC=5 SCAR=16.1
Branch: 2 branches
BranchTrueFalseTotal
unless scalar @_ > 0 0 13 13
if scalar @_ > 1 0 13 13
220 # The result object has to know where it was produced and how to fail...
221 13 $hash_ref->{ '<CONTEXT>' } = [ caller 1 ];
222 13 ▶ $hash_ref->{ '<DEFAULT>' } //= \&_default_fail;
Condition100%2/2
$hash_ref->{"<DEFAULT>"} //= \&Object::Result::_default_fail
l!l
76
MC/DC100%1/1
$hash_ref->{"<DEFAULT>"} //= \&Object::Result::_default_fail
$hash_ref->{"<DEFAULT>"}
Truth table100%2/2
A
A= $hash_ref->{"<DEFAULT>"}
Aresult
11
00
223 13 ▶ $hash_ref->{ '<BOOL>' } //= \&_default_bool;
Condition100%2/2
$hash_ref->{"<BOOL>"} //= \&Object::Result::_default_bool
l!l
94
MC/DC100%1/1
$hash_ref->{"<BOOL>"} //= \&Object::Result::_default_bool
$hash_ref->{"<BOOL>"}
Truth table100%2/2
A
A= $hash_ref->{"<BOOL>"}
Aresult
11
00
224  
225 # It's an inside-out object...
226 13 my $newobj = bless \do{my $scalar}, 'Object::Result::Object';
227  
228 # So it's internal data is cached inside the module...
229 13 $impl_of{$newobj} = $hash_ref;
230  
231 # And it just returns an empty blessed scalar...
232 13 return $newobj;
233 }
234  
235 # Be invisible to carp and croak and lazy about importing them...
236 13 $Carp::Internal{ (__PACKAGE__) }++;
237  
238 13 ▶func _croak (@msg) {
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine _croak: called CC=1 SCAR=0.0
239 9 require Carp;
240 9 Carp::croak( @msg );
241 }
242  
243 # Generate exceptions for <FAIL>...
244 13 ▶method _croak_failure (:$errmsg, :$msg) {
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine _croak_failure: called CC=10 SCAR=24.2
Branch: 2 branches
BranchTrueFalseTotal
if keys %args 0 50 50
if scalar @_ > 4 0 50 50
245 50 state $TRAILING_AT_LINE
246 = qr{ \s++ at \s++ .+? \s++ line \s++ \d++ [\s\S]*+ \Z }xms;
247  
248 # Skip immediate caller unconditionally
249 50 require Carp;
250 50 local $Carp::CarpLevel = 1;
251  
252 # Define message...
253 50 @$msg = grep { defined } @$msg;
254  
255 # Handle non-strings...
256 50 ▶ if ( @$msg == 1 && ref($msg->[0]) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$msg == 1 and ref $msg->[0]) 0 50 50
Condition66%2/3
@$msg == 1 and ref $msg->[0]
!ll&&!rl&&r
30200
MC/DC0%0/2
@$msg == 1 and ref $msg->[0]
@$msg == 1 ref $msg->[0]
Truth table66%2/3
A and B
A= @$msg == 1B= ref $msg->[0]
ABresult
0X0
100
111
257 0 Carp::croak @$msg;
258 }
259  
260 # Clean up message and locator...
261 50 my $carp_where = Carp::shortmess( '' );
262 50 $carp_where =~ s{\A .* \s at \s }{}xms;
263  
264 50 ▶ my $carp_what = @$msg ? join( q{}, @$msg ) : $errmsg;
Branch: 1 branch
BranchTrueFalseTotal
@$msg ? : 20 30 50
265 50 $carp_what =~ s{ $TRAILING_AT_LINE }{}xms;
266 50 $carp_what =~ s{ \s+ }{ }xms;
267 50 ▶ if (length($carp_what) > 78) {
Branch: 2 branches
BranchTrueFalseTotal
if (length $carp_what > 78) { } 0 50 50
elsif (length $carp_what > 0) { } 30 20 50
268 0 $carp_what =~ s{ (?<last> .{1,73} ) \Z
269 | (?<line> .{1,72} ) \s+
270 | (?<line> .{1,72} [^\w\s] )
271 }
272 0 ▶ { ': ' . (exists $+{line} ? "$+{line}\n" : $+{last}) }gexms;
Branch: 1 branch
BranchTrueFalseTotal
exists $+{'line'} ? : 0 0 0
273 0 $carp_what = ":\n$carp_what\n:";
274 }
275 elsif (length($carp_what) > 0) {
276 30 $carp_what = " $carp_what";
277 }
278  
279 # Handle non-messages...
280 die sprintf(
281 "Call to %s() at %s line %s failed%s\nFailure detected at %s\n",
282 50 ▶ @{$impl_of{$self}{'<CONTEXT>'}}[3,1,2],
Branch: 1 branch
BranchTrueFalseTotal
$carp_what ? : 30 20 50
283 ($carp_what ? " because:\n$carp_what" : q{}),
284 $carp_where,
285 );
286 }
287  
288 # The class of all result objects...
289 13 package Object::Result::Object {
290 13 ▶ use Method::Signatures;
Subroutine BEGIN: called CC=1 SCAR=0.0
291  
292 # Be invisible to carp and croak...
293 13 $Carp::Internal{ (__PACKAGE__) }++;
294  
295 # Overload all possible coercions to call the corresponding type converter...
296 use overload (
297 13 q{""} => Object::Result::_handler_for(qw[ STR ]),
298 q{bool} => Object::Result::_handler_for(qw[ BOOL ]),
299 q{int} => Object::Result::_handler_for(qw[ INT ]),
300 q{0+} => Object::Result::_handler_for(qw[ NUM ]),
301 q{qr} => Object::Result::_handler_for(qw[ REGEXP REGEXPREF REGEX REGEXREF ]),
302 q{${}} => Object::Result::_handler_for(qw[ SCALAR SCALARREF ]),
303 q{@{}} => Object::Result::_handler_for(qw[ ARRAY ARRAYREF ]),
304 q{%{}} => Object::Result::_handler_for(qw[ HASH HASHREF ]),
305 q{&{}} => Object::Result::_handler_for(qw[ CODE CODEREF SUB SUBREF ]),
306 q{*{}} => Object::Result::_handler_for(qw[ GLOB GLOBREF ]),
307  
308 # With the usual magic autogeneration...
309 fallback => 1,
310 13 ▶ );
Subroutine BEGIN: called CC=1 SCAR=0.0
311  
312 # All methods must be autoloaded, since each result object may have different methods...
313 13 ▶ func AUTOLOAD ($self, ...) {
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine AUTOLOAD: called CC=4 SCAR=13.9
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @_ > 0 0 22 22
314 # Work out the method name...
315 22 our $AUTOLOAD;
316 22 my $method_name = $AUTOLOAD =~ s/.*:://r;
317  
318 # Find the corresponding implementation for the object...
319 22 my $object_impl = $impl_of{$self};
320 22 ▶ my $method_impl = $object_impl->{$method_name} // $object_impl->{'<AUTOLOAD>'};
Condition100%3/3
$object_impl->{$method_name} // $object_impl->{"<AUTOLOAD>"}
l!l&&r!l&&!r
1651
MC/DC100%2/2
$object_impl->{$method_name} // $object_impl->{"<AUTOLOAD>"}
$object_impl->{$method_name} $object_impl->{"<AUTOLOAD>"}
Truth table100%3/3
A // B
A= $object_impl->{$method_name}B= $object_impl->{"<AUTOLOAD>"}
ABresult
1X1
011
000
321 22 ▶ if (!defined $method_impl) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $method_impl) 1 21 22
322 1 my $call_desc = sprintf( "call to %s() at %s line %s", @{$object_impl->{'<CONTEXT>'}}[3,1,2] );
323 1 Object::Result::_croak(
324 "Object returned by $call_desc\ndoesn't have method $method_name()"
325 );
326 }
327  
328 # Fake out any internal error messages...
329 13 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
330 21 *{$object_impl->{'<CONTEXT>'}[0].'::__ANON__'} = $method_name;
331  
332 # Execute the method implementation...
333 21 goto &{$method_impl};
334 }
335  
336 # Because we have an AUTOLOAD(), we need this separate...
337 13 ▶ func DESTROY ($self) {
Subroutine BEGIN: called CC=1 SCAR=0.1
Subroutine DESTROY: called CC=4 SCAR=13.9
Branch: 2 branches
BranchTrueFalseTotal
unless scalar @_ > 0 0 13 13
if scalar @_ > 1 0 13 13
338 13 my $object_impl = $impl_of{$self};
339  
340 # Execute destructor, faking out error messages...
341 13 ▶ if (exists $object_impl->{'<DESTROY>'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $object_impl->{"<DESTROY>"}) 6 7 13
342 13 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
343 6 *{$object_impl->{'<CONTEXT>'}[0].'::__ANON__'} = '<DESTROY>';
344 6 goto &{$object_impl->{'<DESTROY>'}};
345 }
346 }
347 }
348  
349 13 1; # Magic true value required at end of module
350 __END__
351  
352 =head1 NAME
353  
354 Object::Result - Allow subs to build and return objects on-the-fly
355  
356  
357 =head1 VERSION
358  
359 This document describes Object::Result version 0.000002
360  
361  
362 =head1 SYNOPSIS
363  
364 use Object::Result;
365  
366 sub get_time {
367 # Return an object indicating failure...
368 if (!load Time::HiRes => 'time') {
369 result { <FAIL> }
370 }
371  
372 # Set up some lexical state information...
373 my $time = time();
374  
375 # Return an object with methods that use that information...
376 result {
377 # Named methods for returned object...
378 timestamp { return scalar localtime($time) }
379  
380 delay (Num $offset) { $time += $offset }
381  
382 # Coercions for returned object...
383 <STR> { $self->timestamp; } # String --> timestamp method
384 <NUM> { time() - $time; } # Number --> age of object
385 <BOOL> { $self < 60; } # True for the first minute
386 }
387 };
388  
389  
390 # And later...
391  
392 # Get back an object...
393 my $now = get_time();
394  
395 # Use it (as a string, as an object, as a number)...
396 say "It's $now";
397 say $now->timestamp;
398 say 'Recent' if $now < 0.1;
399  
400 # Change the object's internal state...
401 $now->delay(50);
402  
403 # Use the object as a (dynamically valued) boolean...
404 while ($now) {
405 sleep 5;
406 say "Are we there yet?";
407 }
408  
409  
410  
411 =head1 DESCRIPTION
412  
413 This module adds a new keyword to Perl: C<result>
414  
415 That keyword acts like a C<return>, but instead of a list of values to
416 return, it takes a single block which specifies the behaviour
417 (i.e. the methods and operator overloading) of an object to be returned.
418  
419 The intention is to make it much less onerous to return clean,
420 properly encapsulated objects...instead of returning lists of values
421 or references to arrays or hashes.
422  
423 For example, instead of:
424  
425 my ($ID, $name, $uptime, $load, $users, $location, $contact)
426 = get_server_status($server_ID);
427  
428 if ($uptime) {
429 say "$ID ($name) load: $load";
430 }
431  
432 or:
433  
434 my $server = get_server_status($server_ID);
435  
436 if ($server->{uptime}) {
437 say "$server->{ID} ($server->{name) load: $server->{load}";
438 }
439  
440 you can arrange the API to be object-based:
441  
442 my $server = get_server_status($server_ID);
443  
444 if ($server->is_up) {
445 say $server->describe, ' load: ', $server->load;
446 }
447  
448 The real advantage is that, inside the module providing
449 C<get_server_status()> you don't have to define a separate class
450 implementing the objects returned by that subroutine. More importantly,
451 if you have a dozen subroutines returning specialized objects, you don't
452 have to define a dozen separate classes to support them.
453  
454  
455 =head2 RATIONALE
456  
457 I<(Skip straight ahead to L<INTERFACE> if you already get it...or just
458 don't care why this approach is better.)>
459  
460 Subroutines that return lists of values make client code brittle: it's far too
461 easy to mess up the unpacking:
462  
463 my ($ID, $name, $uptime, $users, $load, $contact, $location)
464 = get_server_status($server_ID);
465  
466 Subroutines that return hash references aren't much better: they do keep
467 all the information together, and eliminate the order dependency of unpacking
468 it, but it's also very easy to misspell a key and thereby create a silent bug:
469  
470 my $server = get_server_status($server_ID);
471  
472 if ($server->{up_time}) {
473 say "$server->{id} ($server->{name) load: $server->{load}";
474 }
475  
476 Like hashrefs, properly encapsulated objects keep all the returned
477 information together and allow it to be retrieved by name, but they can
478 also provide extra methods to simplify common tasks, and the OO syntax
479 makes it a fatal error to misspell any access attempt:
480  
481 my $server = get_server_status($server_ID);
482  
483 if ($server->up_time) {
484 say $server->describe, ' load: ', $server->lode;
485 }
486 # dies with: "No such method 'lode' at demo.pl line 27"
487  
488 The only downside is that object-based return values are tedious to set
489 up. If you have multiple subroutines in your API, each of them may need
490 to return a unique type of object, which means you have to define as
491 many distinct support classes as you have subroutines. And even with
492 helper modules (such as Moose or Object::InsideOut) that's a substantial
493 amount of extra work:
494  
495 sub get_server_status ($server_ID) {
496 my $status_ref = _acquire_status_somehow_for($server_ID);
497  
498 return GSS::Result->new(status => $status_ref);
499 }
500  
501 # Class implementing result objects for get_server_status()...
502 package GSS::Result {
503 use Moose;
504  
505 has status => (is => 'ro', required => 1);
506  
507 sub ID { my $self = shift; $self->status->{ID} }
508 sub name { my $self = shift; $self->status->{name} }
509 sub uptime { my $self = shift; $self->status->{uptime} }
510 sub load { my $self = shift; $self->status->{load} }
511 sub users { my $self = shift; $self->status->{users} }
512 sub location { my $self = shift; $self->status->{location} }
513 sub contact { my $self = shift; $self->status->{contact} }
514  
515 sub is_up { my $self = shift; $self->uptime > 0 }
516  
517 sub describe {
518 my $self = shift;
519 $self->ID . ' (' . $self->name . ')';
520 }
521 }
522  
523 The Object::Result module allows you to have your cake
524 (per-subroutine return objects) without requiring quite
525 so much baking (of per-subroutine support clases).
526  
527  
528 =head1 INTERFACE
529  
530 The module lexically inserts a new keyword (C<result>) into any scope
531 when it is loaded.
532  
533 That keyword takes a single block of code containing zero or more method
534 specifications, and builds an object which supplies those methods. The
535 keyword then causes the surrounding subroutine to immediately return
536 that object.
537  
538  
539 =head2 Defining named methods
540  
541 To define a normal named method for the result object, specify its
542 name followed by a block implementing its body. For example, to
543 specify that the result object has two methods: C<succeeded()> and
544 C<fitness()>:
545  
546 result {
547 succeeded { return $outcome > 0 }
548 fitness { return $outcome * $sample->{metric} }
549 }
550  
551 Methods may be specifed with parameter lists (which are implemented
552 by the Method::Signatures module):
553  
554 result {
555 succeeded (Num $threshold = 0) {
556 return $outcome > $threshold
557 }
558  
559 fitness {
560 return $outcome * $sample->{metric}
561 }
562 }
563  
564 If not specified with a parameter list, C<result> methods are assumed to
565 take no arguments (which is Method::Signatures' default behaviour).
566  
567  
568 =head1 Data storage for result objects
569  
570 Result methods get their information (e.g. C<$outcome> and C<$sample>)
571 from the lexical variables declared in the surrounding subroutine.
572 For example:
573  
574 sub estimate_fitness ($sample, $environment) {
575 my $outcome = $sample->{metric} < $environment->{max_impact}
576 ? $environment->{fitness_func}->($sample->{max})
577 : $environment->{max_survivability};
578  
579 result {
580 succeeded (Num $threshold = 0) {
581 return $outcome > $threshold
582 }
583  
584 fitness {
585 return $outcome * $sample->{metric}
586 }
587 }
588 }
589  
590 In other words, the various methods defined in the C<result> block
591 become closures over the variables inside the surrounding subroutine,
592 and the result object can use those variables as its private storage
593 (i.e. its attributes/fields).
594  
595 For example, the full C<get_server_status()> subroutine shown earlier in
596 L<RATIONALE> could be implemented as:
597  
598 sub get_server_status ($server_ID) {
599 my $status_ref = _acquire_status_somehow_for($server_ID);
600  
601 result {
602 ID { $status_ref->{ID} }
603 name { $status_ref->{name} }
604 uptime { $status_ref->{uptime} }
605 load { $status_ref->{load} }
606 users { $status_ref->{users} }
607 location { $status_ref->{location} }
608 contact { $status_ref->{contact} }
609 is_up { $status_ref->{uptime} > 0 }
610 describe { "$status_ref->{ID} ($status_ref->{name})" }
611 }
612  
613 using the lexical C<$status_ref> as the object's attribute storage.
614  
615 Note that methods can also modify this private data, so the result
616 object from C<get_server_status()> could also support subsequent
617 annotations on the result:
618  
619 sub get_server_status ($server_ID) {
620 my $status_ref = _acquire_status_somehow_for($server_ID);
621 my @annotations;
622  
623 result {
624 # All the methods defined in the previous version, plus...
625  
626 add_note ($msg) { push @annotations, $msg; }
627 get_notes { return @annotations; }
628  
629 }
630  
631  
632 =head2 Coercions
633  
634 Perl allows classes to specify coercive overloadings, so that their
635 objects can then be treated as if they were booleans, strings, numbers,
636 integers, or references to scalars, arrays, hashes, regexes, subroutines,
637 or typeglobs.
638  
639 The C<result> keyword supports this kind of type-coercion too. Coercion
640 methods can be specified by naming the specific type in angle brackets.
641 For example, C<get_server_status()> could return a result object that is
642 true only if the server is up, and which stringifies to a printable
643 summary of the status, like so:
644  
645 sub get_server_status ($server_ID) {
646 my $status_ref = _acquire_status_somehow_for($server_ID);
647  
648 result {
649 # All the methods defined in the previous version, plus...
650  
651 <BOOL> { return $status_ref->{uptime} > 0; }
652 <STR> { return $self->describe . ': ' $self->load; }
653 }
654  
655 Note that, because all methods (named or coercive) are implemented
656 via the Method::Signatures module, they automagically get a
657 C<$self> variable.
658  
659 The following coercions are supported:
660  
661 Treat object as boolean: <BOOL>
662 Treat object as string: <STR>
663 Treat object as integer: <INT>
664 Treat object as number: <NUM>
665 Treat object as scalar ref: <SCALAR>
666 Treat object as array ref: <ARRAY>
667 Treat object as hash ref: <HASH>
668 Treat object as typeblob ref/filehandle: <GLOB>
669 Treat object as regex: <REGEXP> or <REGEX>
670 Treat object as subroutine ref: <CODE> or <SUB>
671  
672 In addition, the coercions to reference types can have the suffix C<REF>
673 appended to their names (e.g. C<< <HASHREF> >>, C<< <ARRAYREF> >>,
674 C<< <SUBREF> >>, etc.)
675  
676 Coercion methods take no arguments (except the implicit C<$self>) and
677 are expected to return either a value of the appropriate type, or some
678 other object with a suitable coercion overloading (i.e. the same
679 requirements as for coercions specified via C<use overload>).
680  
681 By default, if a result object is asked for a particular coercion (apart
682 from boolean; see L<"Boolean coercions">), but did not have that
683 coercion explicitly defined, then the result object immediately throws
684 an exception. See L<"Default coercions"> for a way to change this
685 behaviour.
686  
687  
688 head3 Boolean coercions
689  
690 By default, any result object that has at least one method or coercion
691 defined will evaluate true in a boolean context...as if they all had the
692 following coercion implicitly defined:
693  
694 result {
695 <BOOL> { return 1 }
696 ...
697 }
698  
699 However, as a special case, result objects with no methods at all:
700  
701 result { }
702  
703 always evaluate false (besides having several other useful features; see
704 L<"Result objects for failure signalling">).
705  
706 You can override these default boolean coercion behaviours simply by
707 defining an explicit C<< <BOOL> >> coercion yourself:
708  
709 result {
710 <BOOL> { return defined $outcome }
711 ...
712 }
713  
714 Or, if a result object has other methods, but should nevertheless always
715 evaluate false, you can define that explicitly too:
716  
717 result {
718 <BOOL> { return 0 }
719 ...
720 }
721  
722 Note, however, that in such cases it may be more effective to use a
723 L<I<failure object>|"Result objects for failure signalling">.
724  
725  
726 =head3 Default coercions
727  
728 Although "missing" coercions default to throwing an exception,
729 it's also possible to specify that something else should happen when an
730 unimplemented coercion is requested...by using the C<< <DEFAULT> >> specifier.
731  
732 For example, to convert the normal exception-throwing response
733 into merely warning about an unimplemented coercion:
734  
735 result {
736 # Actual methods and coercions here
737  
738 <DEFAULT> ($requested_coercion, $obj_origin) {
739 carp "Can't convert result of $obj_origin to $requested_coercion";
740 }
741 }
742  
743 Or to revert the object to Perl's built-in behaviours
744 (i.e. address-as-integer in a numeric context,
745 C<"REFTYPE=CLASSNAME(0xADDRESS)"> in a string context, etc.)
746 you could specify:
747  
748 result {
749 # Actual methods and coercions here
750  
751 <DEFAULT> { return $self }
752 }
753  
754 As the first example implies, the C<< <DEFAULT> >> coercion method
755 is passed two extra arguments apart from the usual C<$self>. The first
756 argument is a string containing the name of the missing coercion that
757 was requested: C<< '<STR>' >>, or C<< '<NUM>' >>, or C<< '<HASH>' >>,
758 etc. The second argument is a string indicating the origin of the result
759 object being coerced. That second argument is of the form:
760  
761 'call to __SUBNAME__() at __FILE__ line __LINE__'
762  
763 and may be useful for generating more informative warnings or errors
764 within a C<< <DEFAULT> >> coercion.
765  
766  
767 =head2 Cleaning up result objects
768  
769 If a result object manages some external resource, you can also set
770 up a destructor for that object, using the C<< <DESTROY> >> pseudo-coercion:
771  
772 sub open_output_file ($filename) {
773 open my $fh, '>', $filename or croak $!;
774  
775 result {
776 write (@whatever) { print @whatever; }
777 writeln (@whatever) { say @whatever; }
778  
779 <BOOL> { return not $fh->eof }
780 <GLOB> { return $fh }
781  
782 # Make sure file is flushed before closing...
783 <DESTROY> {
784 $fh->flush();
785 $fh->close();
786 }
787 }
788 }
789  
790  
791 =head2 Result objects for failure signalling
792  
793 The default behaviour of missing coercions provides an easy way to
794 produce so-called I<"contingent exceptions"> (a.k.a. I<"failure
795 objects">).
796  
797 In particular, a C<result> statement of the form:
798  
799 result { <FAIL> }
800  
801 or its exact equivalent, an "empty" C<result>:
802  
803 result { }
804  
805 returns an object that evaluates false in boolean contexts and throws an
806 exception when used in any other way (i.e. whenever it has a method
807 called on it, or it is used as a string, number, regex, or reference).
808 The result object also throws an exception if it is destroyed without
809 having been tested in a boolean context.
810  
811 That is, the two forms shown above are equivalent to something like:
812  
813 {
814 my $tested_as_boolean = 0;
815 my $error_msg = $@ // $! // $?;
816 result {
817 <BOOL> { $tested_as_boolean++; return 0; }
818 <DEFAULT> { croak $error_msg; }
819 <DESTROY> { croak $error_msg if !$tested_as_boolean; }
820 }
821 }
822  
823 If you want the exceptions to throw something else, you can give the
824 C<< <FAIL> >> specifier a block, which will then be called instead
825 to generate the argument(s) to C<<croak()>:
826  
827 # Throw a different string as the exception...
828 result {
829 <FAIL> { "Could not load file: $!" }
830 }
831  
832 # Throw an exception object...
833 result {
834 <FAIL> { X::File::NoLoad->new($!) }
835 }
836  
837 I<Failure objects> such as these are a useful way of signalling errors,
838 because the client code can test the result object (in which case it
839 evaluates false like a typical C<undef> or C<0> or C<""> failure value):
840  
841 my $status = get_server_status();
842  
843 if ($status) { # 'if' test fails if sub returned failure object
844 say $status;
845 }
846  
847 Or the client code can decide not to bother testing it, in which case it
848 dies when used in any non-boolean way (or not used at all):
849  
850 my $status = get_server_status();
851  
852 say $status; # Dies here if sub returned failure object
853  
854 Thus the exception-on-failure is contingent: it will be thrown if the
855 object is used in (almost) any way, unless the failure object has been
856 "defused" by testing it for in a boolean context.
857  
858  
859 =head1 DIAGNOSTICS
860  
861 =head2 Compile-time diagnostics
862  
863 =over
864  
865 =item C<"Invalid syntax for 'result' statement. Expected block but found %s">
866  
867 The C<result> keyword take a single block after it.
868 You put something else there instead.
869  
870 Maybe you just needed a regular C<return>, instead of C<result>?
871  
872  
873 =item C<"Missing definition for %s method">
874  
875 You declared the name of a method or coercion within the C<result>'s block,
876 but didn't give it an implementation (i.e. a block of code for it to execute).
877  
878  
879 =item C<"Invalid definition for %s method. Expected parameter list or method block, but found %s">
880  
881 You declared the name of a method or coercion within the C<result>'s
882 block, so the module next expected to see either a parameter list
883 specification or else a block implementing the method or coercion.
884 It reported the syntax error, because it found something else instead
885 immediately after the method name.
886  
887 =back
888  
889 =head2 Run-time diagnostics
890  
891 =over
892  
893 =item C<"Object returned by %s can't be used as %s">
894  
895 You tried to coerce a result object returned by C<result>
896 to some other type (a number, a string, a reference, etc.)
897 but the C<result> block didn't explicitly specify that coercion.
898  
899 Add the appropriate coercion specification to the C<result> block.
900  
901 Or, if you just wanted the vanilla Perl behaviours when coercing
902 such result objects, add:
903  
904 <DEFAULT> { $self }
905  
906 to the C<result> block.
907  
908  
909 =item C<"Call to %s failed: %s Failure detected at %s">
910  
911 You called a subroutine that returned a I<failure object>
912 (i.e. a C<< result {<FAIL>} >>).
913  
914 Such I<failure objects> can only be tested for their boolean value.
915 Doing anything else with them (or nothing at all with them) will produce
916 this exception...because that's what C<< <FAIL> >> is supposed to do.
917  
918 =back
919  
920  
921 =head1 CONFIGURATION AND ENVIRONMENT
922  
923 Object::Result requires no configuration files or environment variables.
924  
925  
926 =head1 DEPENDENCIES
927  
928 =over
929  
930 =item Keyword::Simple
931  
932 To install the C<result> keyword.
933  
934 =item PPI
935  
936 To parse the new C<result>-block syntax cleanly.
937  
938 =item Method::Signatures
939  
940 To support signatures on methods declared within a
941 C<result> block. Also used internally within the module's
942 own implementation.
943  
944 =back
945  
946  
947 =head1 INCOMPATIBILITIES
948  
949 None reported.
950  
951  
952 =head1 BUGS AND LIMITATIONS
953  
954 No bugs have been reported.
955  
956 Please report any bugs or feature requests to
957 C<bug-object-result@rt.cpan.org>, or through the web interface at
958 L<http://rt.cpan.org>.
959  
960  
961 =head1 AUTHOR
962  
963 Damian Conway C<< <DCONWAY@CPAN.org> >>
964  
965  
966 =head1 LICENCE AND COPYRIGHT
967  
968 Copyright (c) 2014, Damian Conway C<< <DCONWAY@CPAN.org> >>. All rights reserved.
969  
970 This module is free software; you can redistribute it and/or
971 modify it under the same terms as Perl itself. See L<perlartistic>.
972  
973  
974 =head1 DISCLAIMER OF WARRANTY
975  
976 BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
977 FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
978 OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
979 PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
980 EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
981 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
982 ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
983 YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
984 NECESSARY SERVICING, REPAIR, OR CORRECTION.
985  
986 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
987 WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
988 REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
989 LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
990 OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
991 THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
992 RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
993 FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
994 SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
995 SUCH DAMAGES.
↑ Summary