blib/lib/App/Test/Generator/BenchmarkGenerator.pm

filter: Statementstmt 100% 124 / 124 Branchbran 98.3% 59 / 60 Conditioncond 82.6% 43 / 52 MC/DCmcdc 70.0% 21 / 30 Subroutinesub 100% 14 / 14 Podpod 100% 2 / 2 totaltotal 93.2% 263 / 282 CC 52 SCAR 25.4
CC
52
Cov
96%
_representative_value
20.4
generate
17.0
_build_call
8.0
CRAP 12.6
« lib/App/Test/Generator/Analyzer/ReturnMeta.pm ↑ Summary blib/lib/Devel/App/Test/Generator/LCSAJ/Runtime.pm »
1 package App::Test::Generator::BenchmarkGenerator;
2  
3 18 ▶use 5.036;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 18 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
5 18 ▶use Data::Dumper ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6 18 ▶use Params::Get qw(get_params);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 18 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 18 ▶use Scalar::Util qw(looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 18 our $VERSION = '0.52';
11  
12 18 Readonly my %TYPE_DEFAULTS => (
13 number => 42,
14 integer => 42,
15 float => 3.14,
16 string => "'hello'",
17 boolean => 1,
18 arrayref => '[]',
19 hashref => '{}',
20 );
21  
22 18 Readonly my $BAREWORD_RE => qr/^[A-Za-z_]\w*\z/a;
23  
24 # Narrower than looks_like_number(), which also accepts Inf, NaN and
25 # surrounding whitespace - none of which are valid unquoted Perl source.
26 18 Readonly my $NUMERIC_LITERAL_RE => qr/^-?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?\z/a;
27  
28 =encoding utf8
29  
30 =head1 NAME
31  
32 App::Test::Generator::BenchmarkGenerator - Generate Benchmark harnesses from ATG schemas
33  
34 =head1 VERSION
35  
36 Version 0.52
37  
38 =head1 SYNOPSIS
39  
40 Pattern 1: read a schema file and print the benchmark script.
41  
42 use App::Test::Generator::BenchmarkGenerator;
43 use YAML::XS qw(LoadFile);
44  
45 my $schema = LoadFile('schemas/my_func.yml');
46 my $bg = App::Test::Generator::BenchmarkGenerator->new(schema => $schema);
47 print $bg->generate();
48  
49 Pattern 2: write the schema by hand, for a plain function that takes its
50 arguments in a fixed order, and save the script to a file.
51  
52 my $bg = App::Test::Generator::BenchmarkGenerator->new(
53 schema => {
54 module => 'List::Util',
55 function => 'max',
56 input => {
57 first => { type => 'integer', position => 0, min => 1, max => 9 },
58 second => { type => 'integer', position => 1 },
59 },
60 },
61 );
62  
63 open my $fh, '>', 'benchmarks/max.pl' or die $!;
64 print $fh $bg->generate(); # the call is: List::Util::max(5, 42)
65 close $fh;
66  
67 Pattern 3: compare several kinds of input for an object method.
68 Each entry under C<transforms> becomes one line in the timing table.
69  
70 my $bg = App::Test::Generator::BenchmarkGenerator->new(
71 schema => {
72 module => 'My::Shop',
73 function => 'price',
74 new => { currency => 'GBP' },
75 input => { amount => { type => 'number' } },
76 transforms => {
77 small => { input => { amount => { type => 'number', max => 10 } } },
78 large => { input => { amount => { type => 'number', min => 1000 } } },
79 },
80 },
81 );
82 my $script = $bg->generate();
83 # The script builds: my $obj = My::Shop->new(currency => 'GBP');
84 # and then times: $obj->price(amount => 9)
85 # $obj->price(amount => 1001)
86  
87 Pattern 4: benchmark a Perl built-in function.
88 No C<use> line is written for the special module name C<builtin>.
89  
90 my $bg = App::Test::Generator::BenchmarkGenerator->new(
91 schema => {
92 module => 'builtin',
93 function => 'abs',
94 input => { n => { type => 'number', position => 0 } },
95 },
96 );
97 print $bg->generate(); # the call is: abs(42)
98  
99 =head1 DESCRIPTION
100  
101 Given an ATG YAML schema (as produced by C<extract-schemas> or written by hand),
102 generates a self-contained Perl benchmark script using L<Benchmark/cmpthese>.
103  
104 Each transform defined in the schema becomes one variant in the C<cmpthese> call,
105 with representative input values derived from the transform's type and range
106 constraints. When no transforms are defined, a single C<'default'> variant is
107 emitted using the base input specification.
108  
109 A parameter with a C<position> is passed positionally, in position order; a
110 parameter without one follows as a C<name =E<gt> value> pair, so a routine
111 written as C<my ($first, %opts) = @_> is timed as C<first(5, option =E<gt> 42)>
112 rather than with the option left out. C<sample_max>, when present, caps the
113 numeric value chosen for that parameter while C<max> stays the documented
114 range: a work factor such as a PBKDF2 round count is timed at its default
115 rather than at a maximum that takes minutes per call.
116  
117 The generated script is a plain C<.pl> file suitable for running directly with
118 C<perl>. It is not a test file and has no dependency on any test framework.
119  
120 =head1 METHODS
121  
122 =head2 new
123  
124 Construct a new BenchmarkGenerator for a given ATG schema.
125  
126 my $bg = App::Test::Generator::BenchmarkGenerator->new(schema => $schema);
127  
128 =head3 Arguments
129  
130 =over 4
131  
132 =item * C<schema>
133  
134 A hashref representing the parsed YAML schema for the target function, as
135 produced by C<extract-schemas> or written by hand. Must contain at minimum
136 C<module> and C<function> keys. Required.
137  
138 =back
139  
140 =head3 Returns
141  
142 A blessed C<App::Test::Generator::BenchmarkGenerator> object.
143 Croaks if C<schema> is missing or not a hashref.
144  
145 =head3 EXAMPLE
146  
147 use YAML::XS qw(LoadFile);
148 use App::Test::Generator::BenchmarkGenerator;
149  
150 my $schema = LoadFile('schemas/greet.yml');
151 my $bg = App::Test::Generator::BenchmarkGenerator->new(schema => $schema);
152 print $bg->generate();
153  
154 =head3 MESSAGES
155  
156 =over 4
157  
158 =item C<schema is required>
159  
160 C<schema> was not supplied or was C<undef>.
161  
162 =item C<schema must be a hashref>
163  
164 C<schema> was supplied but is not a plain hashref (e.g. an arrayref or string
165 was passed instead).
166  
167 =back
168  
169 =head3 API SPECIFICATION
170  
171 =head4 input
172  
173 {
174 schema => { type => 'hashref' },
175 }
176  
177 =head4 output
178  
179 {
180 type => 'object',
181 isa => 'App::Test::Generator::BenchmarkGenerator',
182 }
183  
184 The mathematical description is in L</FORMAL SPECIFICATION>.
185  
186 =cut
187  
188 77 ▶sub new {
Subroutine new: called CC=3 SCAR=11.0
Pod documented
189 77 my ($class, @args) = @_;
190 77 my $params = get_params('schema', \@args);
191 74 ▶ croak 'schema is required' unless defined $params->{schema};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $params->{"schema"} 2 72 74
192 72 ▶ croak 'schema must be a hashref' unless ref $params->{schema} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $params->{"schema"} eq "HASH" 7 65 72
193 65 return bless { schema => $params->{schema} }, $class;
194 }
195  
196 =head2 generate
197  
198 Generate the complete benchmark script as a string.
199  
200 my $script = $bg->generate();
201 write_file('benchmarks/greet.pl', $script);
202  
203 =head3 Arguments
204  
205 None beyond C<$self>.
206  
207 =head3 Returns
208  
209 A string containing the complete, self-contained Perl benchmark script
210 using C<Benchmark::cmpthese>. The string is ready to write directly to a
211 C<.pl> file and run with C<perl>.
212  
213 Croaks if the schema is missing a C<module> or C<function> key,
214 or if either name is not a valid Perl name.
215  
216 The object is not changed by this call.
217 You can call C<generate> many times and get the same text each time.
218  
219 =head3 EXAMPLE
220  
221 my $script = $bg->generate();
222 # Write to file
223 open my $fh, '>', 'benchmarks/my_func.pl' or die $!;
224 print $fh $script;
225 close $fh;
226  
227 # Or run immediately:
228 require File::Temp;
229 my $tmp = File::Temp->new(SUFFIX => '.pl');
230 print $tmp $script;
231 system($^X, "$tmp");
232  
233 =head3 MESSAGES
234  
235 =over 4
236  
237 =item C<schema missing module>
238  
239 The schema hashref has no C<module> key.
240  
241 =item C<schema missing function>
242  
243 The schema hashref has no C<function> key.
244  
245 =item C<BenchmarkGenerator: module 'NAME' is not a valid Perl identifier>
246  
247 The C<module> value is not a Perl package name such as C<My::Module>.
248 The special name C<builtin> is always accepted.
249  
250 =item C<BenchmarkGenerator: function 'NAME' is not a valid Perl identifier>
251  
252 The C<function> value is not a Perl name such as C<greet> or C<My::Module::greet>.
253  
254 =item C<BenchmarkGenerator: cannot write a TYPE reference as a literal>
255  
256 A value under C<new> is a code reference, an object or another kind of
257 reference that cannot be written as Perl source. Plain values, arrayrefs
258 and hashrefs are accepted.
259  
260 =back
261  
262 =head3 API SPECIFICATION
263  
264 =head4 input
265  
266 None (reads from the schema passed to C<new>).
267  
268 =head4 output
269  
270 { type => 'string' }
271  
272 The string is the complete benchmark script, ready to write to a file.
273  
274 The mathematical description is in L</FORMAL SPECIFICATION>.
275  
276 =head3 PSEUDOCODE
277  
278 read module, function, input, transforms from schema
279 emit shebang, use strict/warnings, use Benchmark
280 unless module eq 'builtin': emit use $module
281 if schema has 'new' key and not builtin:
282 emit my $obj = Module->new(...)
283 if transforms defined and non-empty:
284 for each transform: build a named variant call
285 else:
286 build a single 'default' variant call
287 emit cmpthese($COUNT, { variant => sub { ... }, ... })
288  
289 =cut
290  
291 60 ▶sub generate {
Subroutine generate: called CC=17 SCAR=28.3
Pod documented
292 60 my $self = $_[0];
293  
294 60 my $schema = $self->{schema};
295 60 ▶ my $module = $schema->{module} // croak 'schema missing module';
Condition100%2/2
$schema->{"module"} // croak("schema missing module")
l!l
573
MC/DC100%1/1
$schema->{"module"} // croak("schema missing module")
$schema->{"module"}
Truth table100%2/2
A
A= $schema->{"module"}
Aresult
11
00
296 57 ▶ my $function = $schema->{function} // croak 'schema missing function';
Condition100%2/2
$schema->{"function"} // croak("schema missing function")
l!l
543
MC/DC100%1/1
$schema->{"function"} // croak("schema missing function")
$schema->{"function"}
Truth table100%2/2
A
A= $schema->{"function"}
Aresult
11
00
297  
298 54 ▶ unless($module eq 'builtin') {
Branch: 1 branch
BranchTrueFalseTotal
unless ($module eq "builtin") 31 23 54
299 31 ▶ croak("BenchmarkGenerator: module '$module' is not a valid Perl identifier")
Branch: 1 branch
BranchTrueFalseTotal
unless $module =~ /^[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/u 1 30 31
300 unless $module =~ /^[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/;
301 }
302 53 ▶ croak("BenchmarkGenerator: function '$function' is not a valid Perl identifier")
Branch: 1 branch
BranchTrueFalseTotal
unless $function =~ /^[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/u 1 52 53
303 unless $function =~ /^[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/;
304 52 my $has_new = exists $schema->{new};
305 52 my %input = %{ _hash_or_empty($schema->{input}) };
306 52 my %xforms = %{ _hash_or_empty($schema->{transforms}) };
307  
308 52 my $is_builtin = ($module eq 'builtin');
309  
310 52 my @lines;
311  
312 52 ▶ push @lines,
Branch: 1 branch
BranchTrueFalseTotal
$is_builtin ? : 23 29 52
313 '#!/usr/bin/env perl',
314 "# Benchmark for $function (" . ($is_builtin ? 'builtin' : "module: $module") . ')',
315 '# Generated by benchmark-generator (App::Test::Generator ' . $VERSION . ')',
316 '# DO NOT EDIT -- regenerate with: benchmark-generator -i SCHEMA.yml',
317 q{},
318 'use strict;',
319 'use warnings;',
320 'use Benchmark qw(cmpthese);';
321  
322 52 ▶ unless($is_builtin) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($is_builtin) 29 23 52
323 29 push @lines, "use $module;";
324 }
325  
326 52 push @lines,
327 q{},
328 'my $COUNT = -3; # seconds per variant (negative = time-based)',
329 q{};
330  
331 52 ▶ if($has_new && !$is_builtin) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_new and not $is_builtin) 10 42 52
Condition100%3/3
$has_new and not $is_builtin
!ll&&!rl&&r
41110
MC/DC100%2/2
$has_new and not $is_builtin
$has_new not $is_builtin
Truth table100%3/3
A and not(B)
A= $has_newB= not $is_builtin
ABresult
0X0
100
111
332 10 my $new_spec = $schema->{new};
333 10 ▶ if(ref $new_spec eq 'HASH' && %$new_spec) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $new_spec eq 'HASH' and %$new_spec) { } 5 5 10
Condition100%3/3
ref $new_spec eq "HASH" and %$new_spec
!ll&&!rl&&r
325
MC/DC100%2/2
ref $new_spec eq "HASH" and %$new_spec
ref $new_spec eq "HASH" %$new_spec
Truth table100%3/3
A and B
A= ref $new_spec eq "HASH"B= %$new_spec
ABresult
0X0
100
111
334 5 my $args = join(', ', map { _quote_key($_) . ' => ' . _quote_value($new_spec->{$_}) } sort keys %$new_spec);
335 4 push @lines, "my \$obj = ${module}->new($args);";
336 } else {
337 5 push @lines, "my \$obj = ${module}->new();";
338 }
339 9 push @lines, q{};
340 }
341  
342 51 push @lines, "printf \"Benchmarking ${function}\\n\\n\";", q{};
343  
344 51 my %variants;
345 51 ▶ if(%xforms) {
Branch: 1 branch
BranchTrueFalseTotal
if (%xforms) { } 15 36 51
346 15 for my $name (sort keys %xforms) {
347 126 my $xform = _hash_or_empty($xforms{$name});
348 my $xinput = exists $xform->{input} && defined $xform->{input}
349 ? _hash_or_empty($xform->{input})
350 126 ▶ : \%input;
Branch: 1 branch
BranchTrueFalseTotal
exists $xform->{'input'} && defined $xform->{'input'} ? : 124 2 126
Condition66%2/3
exists $xform->{"input"} and defined $xform->{"input"}
!ll&&!rl&&r
20124
MC/DC50%1/2
exists $xform->{"input"} and defined $xform->{"input"}
exists $xform->{"input"} defined $xform->{"input"}
Truth table66%2/3
A and B
A= exists $xform->{"input"}B= defined $xform->{"input"}
ABresult
0X0
100
111
351 126 $variants{$name} = _build_call($module, $function, $has_new, $xinput);
352 }
353 } else {
354 36 $variants{'default'} = _build_call($module, $function, $has_new, \%input);
355 }
356  
357 51 push @lines, 'cmpthese($COUNT, {';
358 51 my %label = map { $_ => _quote_string($_) } keys %variants;
359 51 my $name_width = (sort { $b <=> $a } map { length } values %label)[0];
360 51 for my $name (sort keys %variants) {
361 162 my $padded = sprintf "%-*s", $name_width, $label{$name};
362 162 push @lines, "\t$padded => sub { $variants{$name} },";
363 }
364 51 push @lines, '});', q{};
365  
366 51 return join("\n", @lines);
367 }
368  
369 # --------------------------------------------------
370 # _build_call
371 #
372 # Purpose: Build the Perl expression that calls the target function
373 # with representative values derived from the input spec.
374 #
375 # Entry: $module - module name string
376 # $function - function/method name
377 # $has_new - true if schema has 'new:' key (OOP call)
378 # $input - hashref of param name → spec
379 #
380 # Exit: Returns a Perl expression string suitable for use inside
381 # an anonymous sub in a cmpthese() call.
382 # --------------------------------------------------
383 170 ▶sub _build_call {
Subroutine _build_call: called CC=8 SCAR=20.8
384 170 my ($module, $function, $has_new, $input) = @_;
385  
386 # ref() guard: dereferencing an undef spec here would autovivify
387 # it into {} inside the caller's schema.
388 170 ▶ my $has_positions = grep { ref($_) eq 'HASH' && defined $_->{position} } values %$input;
Condition100%3/3
ref $_ eq 'HASH' && defined $_->{'position'}
!ll&&!rl&&r
112237
MC/DC100%2/2
ref $_ eq 'HASH' && defined $_->{'position'}
ref $_ eq 'HASH' defined $_->{'position'}
Truth table100%3/3
A && B
A= ref $_ eq 'HASH'B= defined $_->{'position'}
ABresult
0X0
100
111
389 170 my $call;
390  
391 170 ▶ if($has_positions) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_positions) { } 35 135 170
392 2 my @positional = sort { $a->{position} <=> $b->{position} }
393 35 ▶ grep { ref($_) eq 'HASH' && defined $_->{position} }
Condition66%2/3
ref $_ eq 'HASH' && defined $_->{'position'}
!ll&&!rl&&r
0137
MC/DC50%1/2
ref $_ eq 'HASH' && defined $_->{'position'}
ref $_ eq 'HASH' defined $_->{'position'}
Truth table66%2/3
A && B
A= ref $_ eq 'HASH'B= defined $_->{'position'}
ABresult
0X0
100
111
394 values %$input;
395 # A parameter after the positional ones is a named option
396 # (`sub f { my ($first, %opts) = @_ }`), passed after them as a
397 # key/value pair. Dropping it would benchmark a different call,
398 # and a required option would make every iteration die.
399 1 my @named = map { _quote_key($_) . ' => ' . _representative_value($input->{$_}) }
400 35 ▶ sort grep { !(ref($input->{$_}) eq 'HASH' && defined $input->{$_}{position}) }
Condition66%2/3
ref $input->{$_} eq 'HASH' && defined $input->{$_}{'position'}
!ll&&!rl&&r
0137
MC/DC50%1/2
ref $input->{$_} eq 'HASH' && defined $input->{$_}{'position'}
ref $input->{$_} eq 'HASH' defined $input->{$_}{'position'}
Truth table66%2/3
A && B
A= ref $input->{$_} eq 'HASH'B= defined $input->{$_}{'position'}
ABresult
0X0
100
111
401 keys %$input;
402 35 my $args = join(', ', (map { _representative_value($_) } @positional), @named);
403 35 ▶ $call = $has_new ? "\$obj->$function($args)"
Branch: 2 branches
BranchTrueFalseTotal
$has_new ? : 5 30 35
$module eq 'builtin' ? : 25 5 30
404 : ($module eq 'builtin' ? "$function($args)"
405 : "${module}::$function($args)");
406 } else {
407 135 my @pairs = map { _quote_key($_) . ' => ' . _representative_value($input->{$_}) }
408 sort keys %$input;
409 135 my $args = join(', ', @pairs);
410 135 ▶ $call = $has_new ? "\$obj->$function($args)"
Branch: 1 branch
BranchTrueFalseTotal
$has_new ? : 9 126 135
411 : "${module}::$function($args)";
412 }
413  
414 170 return $call;
415 }
416  
417 # --------------------------------------------------
418 # _representative_value
419 #
420 # Purpose: Return a Perl literal string that is a plausible representative
421 # value for a parameter given its schema spec. The choice is
422 # informed by type, min, max, and enum constraints.
423 #
424 # Entry: $spec - hashref with at minimum a 'type' key
425 #
426 # Exit: Returns a Perl literal string (e.g. '42', "'hello'", 'undef').
427 # --------------------------------------------------
428 211 ▶sub _representative_value {
Subroutine _representative_value: called CC=20 SCAR=30.1
429 211 my ($spec) = @_;
430 211 ▶ return 'undef' unless defined $spec;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $spec 4 207 211
431 207 ▶ $spec = {} unless ref($spec) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $spec eq "HASH" 0 207 207
432  
433 207 ▶ my $type = lc($spec->{type} // 'string');
Condition100%2/2
$spec->{"type"} // "string"
l!l
2052
MC/DC100%1/1
$spec->{"type"} // "string"
$spec->{"type"}
Truth table100%2/2
A
A= $spec->{"type"}
Aresult
11
00
434  
435 207 ▶ if($type eq 'number' || $type eq 'integer' || $type eq 'float') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "number" or $type eq "integer" or $type eq "float") 180 27 207
Condition100%6/6
$type eq "number" or $type eq "integer" or $type eq "float"
l!l&&r!l&&!r
173727
$type eq "number" or $type eq "integer"
l!l&&r!l&&!r
3314034
MC/DC100%3/3
$type eq "number" or $type eq "integer" or $type eq "float"
$type eq "number" $type eq "integer" $type eq "float"
Truth table100%4/4
A or B or C
A= $type eq "number"B= $type eq "integer"C= $type eq "float"
ABCresult
1XX1
01X1
0011
0000
436 180 my $min = $spec->{min};
437 # sample_max caps the value chosen for a work factor (a PBKDF2 round
438 # count at the documented maximum takes minutes per call); max stays
439 # the bound when the parameter documents no sample_max.
440 180 ▶ my $max = defined($spec->{sample_max}) ? $spec->{sample_max} : $spec->{max};
Branch: 1 branch
BranchTrueFalseTotal
defined $spec->{'sample_max'} ? : 2 178 180
441 180 ▶ my $default = $TYPE_DEFAULTS{$type} // 42;
Condition50%1/2
$TYPE_DEFAULTS{$type} // 42
l!l
1800
MC/DC0%0/1
$TYPE_DEFAULTS{$type} // 42
$TYPE_DEFAULTS{$type}
Truth table50%1/2
A
A= $TYPE_DEFAULTS{$type}
Aresult
11
00
442 180 ▶ if(defined $min && looks_like_number($min) && defined $max && looks_like_number($max)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $min and &looks_like_number($min) and defined $max and &looks_like_number($max)) 8 172 180
Condition77%7/9
defined $min and &looks_like_number($min) and defined $max and &looks_like_number($max)
!ll&&!rl&&r
17208
defined $min and &looks_like_number($min) and defined $max
!ll&&!rl&&r
154188
defined $min and &looks_like_number($min)
!ll&&!rl&&r
154026
MC/DC50%2/4
defined $min and &looks_like_number($min) and defined $max and &looks_like_number($max)
defined $min &looks_like_number($min) defined $max &looks_like_number($max)
Truth table60%3/5
A and B and C and D
A= defined $minB= &looks_like_number($min)C= defined $maxD= &looks_like_number($max)
ABCDresult
0XXX0
10XX0
110X0
11100
11111
443 8 return int(($min + $max) / 2);
444 }
445 172 ▶ if(defined $min && looks_like_number($min)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $min and &looks_like_number($min)) 18 154 172
Condition66%2/3
defined $min and &looks_like_number($min)
!ll&&!rl&&r
154018
MC/DC50%1/2
defined $min and &looks_like_number($min)
defined $min &looks_like_number($min)
Truth table66%2/3
A and B
A= defined $minB= &looks_like_number($min)
ABresult
0X0
100
111
446 # pick the type default if it already satisfies >= min, else min+1
447 18 ▶ return $default > $min ? $default : $min + 1;
Branch: 1 branch
BranchTrueFalseTotal
$default > $min ? : 12 6 18
448 }
449 154 ▶ if(defined $max && looks_like_number($max)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $max and &looks_like_number($max)) 18 136 154
Condition66%2/3
defined $max and &looks_like_number($max)
!ll&&!rl&&r
136018
MC/DC50%1/2
defined $max and &looks_like_number($max)
defined $max &looks_like_number($max)
Truth table66%2/3
A and B
A= defined $maxB= &looks_like_number($max)
ABresult
0X0
100
111
450 # pick the type default if it already satisfies <= max, else max-1
451 18 ▶ return $default < $max ? $default : $max - 1;
Branch: 1 branch
BranchTrueFalseTotal
$default < $max ? : 5 13 18
452 }
453 136 return $default;
454 }
455  
456 27 ▶ return $TYPE_DEFAULTS{$type} // "'value'";
Condition100%2/2
$TYPE_DEFAULTS{$type} // "'value'"
l!l
243
MC/DC100%1/1
$TYPE_DEFAULTS{$type} // "'value'"
$TYPE_DEFAULTS{$type}
Truth table100%2/2
A
A= $TYPE_DEFAULTS{$type}
Aresult
11
00
457 }
458  
459 # --------------------------------------------------
460 # _quote_value
461 #
462 # Purpose: Quote a scalar value for use in generated Perl source.
463 #
464 # Entry: $v - undef, number, string, arrayref or hashref
465 #
466 # Exit: Returns a Perl literal string.
467 # Croaks on any other kind of reference.
468 # --------------------------------------------------
469 31 ▶sub _quote_value {
Subroutine _quote_value: called CC=6 SCAR=17.9
470 31 my ($v) = @_;
471 31 ▶ return 'undef' unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 3 28 31
472  
473 28 ▶ if(my $type = ref $v) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $type = ref $v) 2 26 28
474 2 ▶ croak "BenchmarkGenerator: cannot write a $type reference as a literal"
Branch: 1 branch
BranchTrueFalseTotal
unless $type eq "HASH" or $type eq "ARRAY" 1 1 2
Condition66%2/3
$type eq "HASH" or $type eq "ARRAY"
l!l&&r!l&&!r
101
MC/DC50%1/2
$type eq "HASH" or $type eq "ARRAY"
$type eq "HASH" $type eq "ARRAY"
Truth table66%2/3
A or B
A= $type eq "HASH"B= $type eq "ARRAY"
ABresult
1X1
011
000
475 unless $type eq 'HASH' || $type eq 'ARRAY';
476 1 local $Data::Dumper::Terse = 1;
477 1 local $Data::Dumper::Indent = 0;
478 1 local $Data::Dumper::Sortkeys = 1;
479 1 return Data::Dumper::Dumper($v);
480 }
481  
482 26 ▶ return $v if $v =~ $NUMERIC_LITERAL_RE;
Branch: 1 branch
BranchTrueFalseTotal
if $v =~ /$NUMERIC_LITERAL_RE/u 12 14 26
483 14 return _quote_string($v);
484 }
485  
486 # --------------------------------------------------
487 # _quote_string
488 #
489 # Purpose: Single-quote a string for generated Perl source.
490 #
491 # Entry: $s - defined string
492 #
493 # Exit: Returns the quoted literal.
494 # --------------------------------------------------
495 178 ▶sub _quote_string {
Subroutine _quote_string: called CC=1 SCAR=0.0
496 178 my ($s) = @_;
497 178 (my $escaped = $s) =~ s/([\\'])/\\$1/g;
498 178 return "'$escaped'";
499 }
500  
501 # --------------------------------------------------
502 # _quote_key
503 #
504 # Purpose: Render a hash key for the left side of '=>'.
505 #
506 # Entry: $key - parameter or constructor argument name
507 #
508 # Exit: Returns the name unchanged when it is a plain
509 # identifier, otherwise a quoted literal.
510 # --------------------------------------------------
511 134 ▶sub _quote_key {
Subroutine _quote_key: called CC=2 SCAR=6.9
512 134 my ($key) = @_;
513 134 ▶ return $key =~ $BAREWORD_RE ? $key : _quote_string($key);
Branch: 1 branch
BranchTrueFalseTotal
$key =~ /$BAREWORD_RE/u ? : 132 2 134
514 }
515  
516 # --------------------------------------------------
517 # _hash_or_empty
518 #
519 # Purpose: Read a schema section that should be a hashref.
520 #
521 # Entry: $v - any value
522 #
523 # Exit: Returns $v when it is a hashref, else a new
524 # empty hashref.
525 #
526 # Notes: ATG schemas write "no input" as the string
527 # 'undef' (input: undef), which is not a hashref.
528 # --------------------------------------------------
529 354 ▶sub _hash_or_empty {
Subroutine _hash_or_empty: called CC=2 SCAR=6.9
530 354 my ($v) = @_;
531 354 ▶ return ref($v) eq 'HASH' ? $v : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $v eq 'HASH' ? : 309 45 354
532 }
533  
534 =head1 COMMON PITFALLS
535  
536 =over 4
537  
538 =item Schema missing C<module> or C<function>
539  
540 C<generate> croaks immediately if either key is absent. Always ensure the
541 schema has been loaded from a valid ATG YAML file before calling C<generate>.
542  
543 =item Expecting test-framework output
544  
545 The generated script uses C<Benchmark::cmpthese> and prints timing results to
546 STDOUT. It is B<not> a test file and produces no TAP output. Do not run it
547 with C<prove>.
548  
549 =item OOP schemas need a C<new:> key
550  
551 If the function under benchmark is an instance method, the schema must have a
552 C<new:> key (even if its value is an empty hashref C<{}>) so C<generate> emits
553 a C<my $obj = Module->new(...)> constructor call before the C<cmpthese> block.
554 Without it, the variant calls use C<Module::function(...)> form.
555  
556 =item Transforms that omit the C<input> key
557  
558 If a transform's hashref has no C<input> key, C<generate> falls back to the
559 base schema C<input> spec for that variant. This is intentional but may
560 produce identical argument lists across variants if you forgot to add per-
561 transform input overrides.
562  
563 =item A transform C<input> replaces the base C<input>. It is not merged.
564  
565 If the base C<input> has the parameters C<a> and C<b>, and a transform
566 C<input> has only C<a>, then that variant is called with C<a> alone.
567 C<b> is not copied from the base. Repeat every parameter you need inside
568 each transform.
569  
570 =item Only plain data is allowed under C<new>
571  
572 A value under C<new> can be a number, a string, C<undef>, an arrayref or
573 a hashref, nested to any depth. A code reference or an object makes
574 C<generate> croak.
575  
576 =item How C<undef> is handled
577  
578 =over 4
579  
580 =item * C<schema =E<gt> undef> makes C<new> croak with C<schema is required>.
581  
582 =item * A C<module> or C<function> that is C<undef> makes C<generate> croak.
583  
584 =item * A missing or C<undef> C<input> or C<transforms> key means "no
585 parameters" or "no transforms". This is safe.
586  
587 =item * C<new =E<gt> undef> (C<new: ~> in YAML) still counts as "has a
588 constructor". The script calls C<< Module->new() >> with no arguments.
589  
590 =item * An C<undef> value B<inside> C<new> is written as the Perl word C<undef>.
591  
592 =item * A parameter whose specification is C<undef> is passed as the
593 Perl word C<undef>.
594  
595 =back
596  
597 =item The text C<undef> means "no input"
598  
599 Some ATG schema files contain C<input: undef>. YAML reads this as the
600 five-letter string C<"undef">. C<generate> treats that string, and any
601 other C<input> or C<transforms> value that is not a hashref, as "no
602 parameters". Inside a transform, C<input: undef> gives a call with no
603 arguments; it does B<not> fall back to the base C<input>.
604  
605 =item Names that are not plain words are quoted for you
606  
607 Transform names, parameter names and the keys under C<new> can contain
608 any characters. They are quoted and escaped in the generated script when
609 needed. Only C<module> and C<function> must be valid Perl names.
610  
611 =item Which text is written as a number
612  
613 A string under C<new> is written without quotes only when it is a plain
614 decimal number such as C<42>, C<-1.5> or C<2e10>. Everything else,
615 including C<'Inf'>, C<'NaN'> and C<' 12'>, is written as a quoted string.
616 Be careful with a leading zero: C<'007'> is written as C<007>, which Perl
617 reads as an octal number.
618  
619 =back
620  
621 =head1 ENCODING
622  
623 =over 4
624  
625 =item * C<module> and C<function>
626  
627 Use ASCII letters, digits, underscores and C<::> only. Non-ASCII letters
628 may pass the name check, but the generated script has no C<use utf8> line,
629 so Perl will not read such names correctly.
630  
631 =item * Transform names, parameter names and string values under C<new>
632  
633 Full UTF-8 text, including non-ASCII letters and emojis, is copied into
634 the script unchanged. This is safe only if you take two steps yourself:
635 write the script through a UTF-8 file handle
636 (C<< open my $fh, '>:encoding(UTF-8)', $path >>), and remember that the
637 script has no C<use utf8> line, so the running benchmark sees the text as
638 bytes, not as characters. For a benchmark that needs real character
639 strings, add C<use utf8;> to the generated file by hand.
640  
641 =item * Sample argument values
642  
643 These are always ASCII (C<42>, C<3.14>, C<'hello'>, C<[]>, C<{}>).
644 The generator never invents non-ASCII test data.
645  
646 =item * The return value of C<generate>
647  
648 A Perl character string. It is ASCII unless your schema put non-ASCII
649 text into it as described above.
650  
651 =back
652  
653 =head1 LIMITATIONS
654  
655 =over 4
656  
657 =item Representative values are heuristic
658  
659 C<_representative_value> picks a single value based on type and C<min>/C<max>
660 constraints. It does not guarantee the chosen value exercises any particular
661 code path, and it does not use the schema's C<enum> or C<matches> keys.
662  
663 =item No round-trip with C<extract-schemas>
664  
665 The generator reads any conforming ATG YAML schema, but it does not verify
666 that the schema accurately describes the actual function's signature. If the
667 schema is stale, the generated benchmark may pass wrong argument types.
668  
669 =back
670  
671 =head1 SEE ALSO
672  
673 =over 4
674  
675 =item L<Benchmark>
676  
677 =item C<bin/benchmark-generator>
678  
679 =item L<App::Test::Generator>
680  
681 =back
682  
683 =head1 AUTHOR
684  
685 Nigel Horne, C<< <njh at nigelhorne.com> >>
686  
687 =head1 FORMAL SPECIFICATION
688  
689 This section describes each method in Z notation. It is for readers who
690 want an exact, mathematical statement. You do not need it to use the module.
691  
692 How to read it: a name ending in C<?> is an input, a name ending in C<!> is
693 an output, and a name ending in C<'> is the value after the call.
694 The symbol E<0x039E> before the state name means "this call does not change
695 the object".
696  
697 The state of an object is one value, the schema given to C<new>:
698  
699 ┌─ BenchmarkGenerator ──────────────────────────────
700 │ schema : HASHREF
701 ├───────────────────────────────────────────────────
702 │ schema ≠ undef
703 └───────────────────────────────────────────────────
704  
705 =head2 new
706  
707 ┌─ New ─────────────────────────────────────────────
708 │ BenchmarkGenerator′
709 │ schema? : VALUE
710 │ result! : BenchmarkGenerator
711 ├───────────────────────────────────────────────────
712 │ pre schema? ≠ undef ∧ ref(schema?) = 'HASH'
713 │ post schema′ = schema?
714 │ result! = θ BenchmarkGenerator′
715 └───────────────────────────────────────────────────
716  
717 schema? = undef ⇒ croak 'schema is required'
718 ref(schema?) ≠ 'HASH' ⇒ croak 'schema must be a hashref'
719  
720 =head2 generate
721  
722 NAME == { s : STRING | s matches /^[A-Za-z_]\w*(::[A-Za-z_]\w*)*$/ }
723  
724 ┌─ Generate ────────────────────────────────────────
725 │ Ξ BenchmarkGenerator
726 │ result! : STRING
727 │ variants : ℙ STRING
728 ├───────────────────────────────────────────────────
729 │ pre schema.module ≠ undef ∧ schema.function ≠ undef
730 │ schema.module = 'builtin' ∨ schema.module ∈ NAME
731 │ schema.function ∈ NAME
732 │ post schema.transforms = ∅ ⇒ variants = { 'default' }
733 │ schema.transforms ≠ ∅ ⇒ variants = dom schema.transforms
734 │ #variants = max(1, #(dom schema.transforms))
735 │ result! contains exactly one cmpthese(...) call
736 │ ∀ v : variants • result! contains one timed call named v
737 │ schema.module = 'builtin' ⇔ result! has no 'use module' line
738 │ ('new' ∈ dom schema ∧ schema.module ≠ 'builtin')
739 │ ⇔ result! builds $obj with module->new(...)
740 └───────────────────────────────────────────────────
741  
742 =head1 STATE DIAGRAM
743  
744 An object of this class has only one working state. It is created ready
745 to use and it never changes afterwards.
746  
747 new(schema => undef)
748 new(schema => not a hashref)
749 +------------------------------+
750 | action: croak, no object |
751 v |
752 +-------------+ |
753 | NO OBJECT |-----------------------+
754 +-------------+
755 |
756 | new(schema => HASHREF)
757 | action: keep a reference to the schema
758 v
759 +-------------+ generate() [schema is good]
760 | |---------------------------------+
761 | READY | action: return the script |
762 | |<--------------------------------+
763 | |
764 | | generate() [module or function
765 | | missing or not a name]
766 | |---------------------------------+
767 | | action: croak, nothing changes|
768 | |<--------------------------------+
769 +-------------+
770 |
771 | last reference goes away
772 | action: Perl frees the object
773 v
774 +-------------+
775 | GONE |
776 +-------------+
777  
778 Side effects: C<new> and C<generate> write no files and print nothing.
779 The schema that you passed to C<new> is never changed.
780  
781 =head1 LICENCE AND COPYRIGHT
782  
783 Copyright 2026 Nigel Horne.
784  
785 Usage is subject to the terms of GPL2.
786 If you use it,
787 please let me know.
788  
789 =cut
790  
791 18 1;
« lib/App/Test/Generator/Analyzer/ReturnMeta.pm ↑ Summary blib/lib/Devel/App/Test/Generator/LCSAJ/Runtime.pm »