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

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