| File: | blib/lib/App/Test/Generator/BenchmarkGenerator.pm |
| Coverage: | 95.1% |
| line | stmt | bran | cond | sub | time | code |
|---|---|---|---|---|---|---|
| 1 | package App::Test::Generator::BenchmarkGenerator; | |||||
| 2 | ||||||
| 3 | 17 17 | 59353 33 | use 5.036; | |||
| 4 | 17 17 17 | 24 14 329 | use Carp qw(croak); | |||
| 5 | 17 17 17 | 1551 20153 134 | use Data::Dumper (); | |||
| 6 | 17 17 17 | 1716 66347 344 | use Params::Get qw(get_params); | |||
| 7 | 17 17 17 | 31 8 223 | use Readonly; | |||
| 8 | 17 17 17 | 24 12 10620 | use Scalar::Util qw(looks_like_number); | |||
| 9 | ||||||
| 10 | our $VERSION = '0.52'; | |||||
| 11 | ||||||
| 12 | 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 | 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 | Readonly my $NUMERIC_LITERAL_RE => qr/^-?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?\z/a; | |||||
| 27 | ||||||
| 28 | =encoding utf8 | |||||
| 29 | ||||||
| 30 - 186 | =head1 NAME
App::Test::Generator::BenchmarkGenerator - Generate Benchmark harnesses from ATG schemas
=head1 VERSION
Version 0.52
=head1 SYNOPSIS
Pattern 1: read a schema file and print the benchmark script.
use App::Test::Generator::BenchmarkGenerator;
use YAML::XS qw(LoadFile);
my $schema = LoadFile('schemas/my_func.yml');
my $bg = App::Test::Generator::BenchmarkGenerator->new(schema => $schema);
print $bg->generate();
Pattern 2: write the schema by hand, for a plain function that takes its
arguments in a fixed order, and save the script to a file.
my $bg = App::Test::Generator::BenchmarkGenerator->new(
schema => {
module => 'List::Util',
function => 'max',
input => {
first => { type => 'integer', position => 0, min => 1, max => 9 },
second => { type => 'integer', position => 1 },
},
},
);
open my $fh, '>', 'benchmarks/max.pl' or die $!;
print $fh $bg->generate(); # the call is: List::Util::max(5, 42)
close $fh;
Pattern 3: compare several kinds of input for an object method.
Each entry under C<transforms> becomes one line in the timing table.
my $bg = App::Test::Generator::BenchmarkGenerator->new(
schema => {
module => 'My::Shop',
function => 'price',
new => { currency => 'GBP' },
input => { amount => { type => 'number' } },
transforms => {
small => { input => { amount => { type => 'number', max => 10 } } },
large => { input => { amount => { type => 'number', min => 1000 } } },
},
},
);
my $script = $bg->generate();
# The script builds: my $obj = My::Shop->new(currency => 'GBP');
# and then times: $obj->price(amount => 9)
# $obj->price(amount => 1001)
Pattern 4: benchmark a Perl built-in function.
No C<use> line is written for the special module name C<builtin>.
my $bg = App::Test::Generator::BenchmarkGenerator->new(
schema => {
module => 'builtin',
function => 'abs',
input => { n => { type => 'number', position => 0 } },
},
);
print $bg->generate(); # the call is: abs(42)
=head1 DESCRIPTION
Given an ATG YAML schema (as produced by C<extract-schemas> or written by hand),
generates a self-contained Perl benchmark script using L<Benchmark/cmpthese>.
Each transform defined in the schema becomes one variant in the C<cmpthese> call,
with representative input values derived from the transform's type and range
constraints. When no transforms are defined, a single C<'default'> variant is
emitted using the base input specification.
A parameter with a C<position> is passed positionally, in position order; a
parameter without one follows as a C<name =E<gt> value> pair, so a routine
written as C<my ($first, %opts) = @_> is timed as C<first(5, option =E<gt> 42)>
rather than with the option left out. C<sample_max>, when present, caps the
numeric value chosen for that parameter while C<max> stays the documented
range: a work factor such as a PBKDF2 round count is timed at its default
rather than at a maximum that takes minutes per call.
The generated script is a plain C<.pl> file suitable for running directly with
C<perl>. It is not a test file and has no dependency on any test framework.
=head1 METHODS
=head2 new
Construct a new BenchmarkGenerator for a given ATG schema.
my $bg = App::Test::Generator::BenchmarkGenerator->new(schema => $schema);
=head3 Arguments
=over 4
=item * C<schema>
A hashref representing the parsed YAML schema for the target function, as
produced by C<extract-schemas> or written by hand. Must contain at minimum
C<module> and C<function> keys. Required.
=back
=head3 Returns
A blessed C<App::Test::Generator::BenchmarkGenerator> object.
Croaks if C<schema> is missing or not a hashref.
=head3 EXAMPLE
use YAML::XS qw(LoadFile);
use App::Test::Generator::BenchmarkGenerator;
my $schema = LoadFile('schemas/greet.yml');
my $bg = App::Test::Generator::BenchmarkGenerator->new(schema => $schema);
print $bg->generate();
=head3 MESSAGES
=over 4
=item C<schema is required>
C<schema> was not supplied or was C<undef>.
=item C<schema must be a hashref>
C<schema> was supplied but is not a plain hashref (e.g. an arrayref or string
was passed instead).
=back
=head3 API SPECIFICATION
=head4 input
{
schema => { type => 'hashref' },
}
=head4 output
{
type => 'object',
isa => 'App::Test::Generator::BenchmarkGenerator',
}
The mathematical description is in L</FORMAL SPECIFICATION>.
=cut | |||||
| 187 | ||||||
| 188 | sub new { | |||||
| 189 | 75 | 888891 | my ($class, @args) = @_; | |||
| 190 | 75 | 139 | my $params = get_params('schema', \@args); | |||
| 191 | 72 | 1029 | croak 'schema is required' unless defined $params->{schema}; | |||
| 192 | 70 | 112 | croak 'schema must be a hashref' unless ref $params->{schema} eq 'HASH'; | |||
| 193 | 63 | 138 | return bless { schema => $params->{schema} }, $class; | |||
| 194 | } | |||||
| 195 | ||||||
| 196 - 289 | =head2 generate
Generate the complete benchmark script as a string.
my $script = $bg->generate();
write_file('benchmarks/greet.pl', $script);
=head3 Arguments
None beyond C<$self>.
=head3 Returns
A string containing the complete, self-contained Perl benchmark script
using C<Benchmark::cmpthese>. The string is ready to write directly to a
C<.pl> file and run with C<perl>.
Croaks if the schema is missing a C<module> or C<function> key,
or if either name is not a valid Perl name.
The object is not changed by this call.
You can call C<generate> many times and get the same text each time.
=head3 EXAMPLE
my $script = $bg->generate();
# Write to file
open my $fh, '>', 'benchmarks/my_func.pl' or die $!;
print $fh $script;
close $fh;
# Or run immediately:
require File::Temp;
my $tmp = File::Temp->new(SUFFIX => '.pl');
print $tmp $script;
system($^X, "$tmp");
=head3 MESSAGES
=over 4
=item C<schema missing module>
The schema hashref has no C<module> key.
=item C<schema missing function>
The schema hashref has no C<function> key.
=item C<BenchmarkGenerator: module 'NAME' is not a valid Perl identifier>
The C<module> value is not a Perl package name such as C<My::Module>.
The special name C<builtin> is always accepted.
=item C<BenchmarkGenerator: function 'NAME' is not a valid Perl identifier>
The C<function> value is not a Perl name such as C<greet> or C<My::Module::greet>.
=item C<BenchmarkGenerator: cannot write a TYPE reference as a literal>
A value under C<new> is a code reference, an object or another kind of
reference that cannot be written as Perl source. Plain values, arrayrefs
and hashrefs are accepted.
=back
=head3 API SPECIFICATION
=head4 input
None (reads from the schema passed to C<new>).
=head4 output
{ type => 'string' }
The string is the complete benchmark script, ready to write to a file.
The mathematical description is in L</FORMAL SPECIFICATION>.
=head3 PSEUDOCODE
read module, function, input, transforms from schema
emit shebang, use strict/warnings, use Benchmark
unless module eq 'builtin': emit use $module
if schema has 'new' key and not builtin:
emit my $obj = Module->new(...)
if transforms defined and non-empty:
for each transform: build a named variant call
else:
build a single 'default' variant call
emit cmpthese($COUNT, { variant => sub { ... }, ... })
=cut | |||||
| 290 | ||||||
| 291 | sub generate { | |||||
| 292 | 60 | 351 | my $self = $_[0]; | |||
| 293 | ||||||
| 294 | 60 | 63 | my $schema = $self->{schema}; | |||
| 295 | 60 | 93 | my $module = $schema->{module} // croak 'schema missing module'; | |||
| 296 | 57 | 87 | my $function = $schema->{function} // croak 'schema missing function'; | |||
| 297 | ||||||
| 298 | 54 | 58 | unless($module eq 'builtin') { | |||
| 299 | 31 | 98 | croak("BenchmarkGenerator: module '$module' is not a valid Perl identifier") | |||
| 300 | unless $module =~ /^[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/; | |||||
| 301 | } | |||||
| 302 | 53 | 292 | croak("BenchmarkGenerator: function '$function' is not a valid Perl identifier") | |||
| 303 | unless $function =~ /^[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/; | |||||
| 304 | 52 | 46 | my $has_new = exists $schema->{new}; | |||
| 305 | 52 52 | 35 74 | my %input = %{ _hash_or_empty($schema->{input}) }; | |||
| 306 | 52 52 | 51 80 | my %xforms = %{ _hash_or_empty($schema->{transforms}) }; | |||
| 307 | ||||||
| 308 | 52 | 58 | my $is_builtin = ($module eq 'builtin'); | |||
| 309 | ||||||
| 310 | 52 | 35 | my @lines; | |||
| 311 | ||||||
| 312 | 52 | 158 | push @lines, | |||
| 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 | 53 | unless($is_builtin) { | |||
| 323 | 29 | 24 | push @lines, "use $module;"; | |||
| 324 | } | |||||
| 325 | ||||||
| 326 | 52 | 68 | push @lines, | |||
| 327 | q{}, | |||||
| 328 | 'my $COUNT = -3; # seconds per variant (negative = time-based)', | |||||
| 329 | q{}; | |||||
| 330 | ||||||
| 331 | 52 | 74 | if($has_new && !$is_builtin) { | |||
| 332 | 10 | 9 | my $new_spec = $schema->{new}; | |||
| 333 | 10 | 21 | if(ref $new_spec eq 'HASH' && %$new_spec) { | |||
| 334 | 5 11 | 12 92 | my $args = join(', ', map { _quote_key($_) . ' => ' . _quote_value($new_spec->{$_}) } sort keys %$new_spec); | |||
| 335 | 4 | 15 | push @lines, "my \$obj = ${module}->new($args);"; | |||
| 336 | } else { | |||||
| 337 | 5 | 4 | push @lines, "my \$obj = ${module}->new();"; | |||
| 338 | } | |||||
| 339 | 9 | 9 | push @lines, q{}; | |||
| 340 | } | |||||
| 341 | ||||||
| 342 | 51 | 66 | push @lines, "printf \"Benchmarking ${function}\\n\\n\";", q{}; | |||
| 343 | ||||||
| 344 | 51 | 30 | my %variants; | |||
| 345 | 51 | 53 | if(%xforms) { | |||
| 346 | 15 | 44 | for my $name (sort keys %xforms) { | |||
| 347 | 126 | 92 | my $xform = _hash_or_empty($xforms{$name}); | |||
| 348 | my $xinput = exists $xform->{input} && defined $xform->{input} | |||||
| 349 | ? _hash_or_empty($xform->{input}) | |||||
| 350 | 126 | 150 | : \%input; | |||
| 351 | 126 | 82 | $variants{$name} = _build_call($module, $function, $has_new, $xinput); | |||
| 352 | } | |||||
| 353 | } else { | |||||
| 354 | 36 | 50 | $variants{'default'} = _build_call($module, $function, $has_new, \%input); | |||
| 355 | } | |||||
| 356 | ||||||
| 357 | 51 | 48 | push @lines, 'cmpthese($COUNT, {'; | |||
| 358 | 51 162 | 52 104 | my %label = map { $_ => _quote_string($_) } keys %variants; | |||
| 359 | 51 405 162 | 56 186 129 | my $name_width = (sort { $b <=> $a } map { length } values %label)[0]; | |||
| 360 | 51 | 63 | for my $name (sort keys %variants) { | |||
| 361 | 162 | 147 | my $padded = sprintf "%-*s", $name_width, $label{$name}; | |||
| 362 | 162 | 137 | push @lines, "\t$padded => sub { $variants{$name} },"; | |||
| 363 | } | |||||
| 364 | 51 | 44 | push @lines, '});', q{}; | |||
| 365 | ||||||
| 366 | 51 | 160 | 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 | sub _build_call { | |||||
| 384 | 170 | 6263 | 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 160 | 149 227 | my $has_positions = grep { ref($_) eq 'HASH' && defined $_->{position} } values %$input; | |||
| 389 | 170 | 96 | my $call; | |||
| 390 | ||||||
| 391 | 170 | 112 | if($has_positions) { | |||
| 392 | 2 | 4 | my @positional = sort { $a->{position} <=> $b->{position} } | |||
| 393 | 35 38 | 30 70 | grep { ref($_) eq 'HASH' && defined $_->{position} } | |||
| 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 | 1 | my @named = map { _quote_key($_) . ' => ' . _representative_value($input->{$_}) } | |||
| 400 | 35 38 | 35 71 | sort grep { !(ref($input->{$_}) eq 'HASH' && defined $input->{$_}{position}) } | |||
| 401 | keys %$input; | |||||
| 402 | 35 37 | 44 36 | my $args = join(', ', (map { _representative_value($_) } @positional), @named); | |||
| 403 | 35 | 80 | $call = $has_new ? "\$obj->$function($args)" | |||
| 404 | : ($module eq 'builtin' ? "$function($args)" | |||||
| 405 | : "${module}::$function($args)"); | |||||
| 406 | } else { | |||||
| 407 | 135 122 | 106 91 | my @pairs = map { _quote_key($_) . ' => ' . _representative_value($input->{$_}) } | |||
| 408 | sort keys %$input; | |||||
| 409 | 135 | 111 | my $args = join(', ', @pairs); | |||
| 410 | 135 | 126 | $call = $has_new ? "\$obj->$function($args)" | |||
| 411 | : "${module}::$function($args)"; | |||||
| 412 | } | |||||
| 413 | ||||||
| 414 | 170 | 159 | 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 | sub _representative_value { | |||||
| 429 | 211 | 18571 | my ($spec) = @_; | |||
| 430 | 211 | 166 | return 'undef' unless defined $spec; | |||
| 431 | 207 | 169 | $spec = {} unless ref($spec) eq 'HASH'; | |||
| 432 | ||||||
| 433 | 207 | 614 | my $type = lc($spec->{type} // 'string'); | |||
| 434 | ||||||
| 435 | 207 | 308 | if($type eq 'number' || $type eq 'integer' || $type eq 'float') { | |||
| 436 | 180 | 92 | 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 | 157 | my $max = defined($spec->{sample_max}) ? $spec->{sample_max} : $spec->{max}; | |||
| 441 | 180 | 211 | my $default = $TYPE_DEFAULTS{$type} // 42; | |||
| 442 | 180 | 514 | if(defined $min && looks_like_number($min) && defined $max && looks_like_number($max)) { | |||
| 443 | 8 | 21 | return int(($min + $max) / 2); | |||
| 444 | } | |||||
| 445 | 172 | 155 | if(defined $min && looks_like_number($min)) { | |||
| 446 | # pick the type default if it already satisfies >= min, else min+1 | |||||
| 447 | 18 | 30 | return $default > $min ? $default : $min + 1; | |||
| 448 | } | |||||
| 449 | 154 | 137 | if(defined $max && looks_like_number($max)) { | |||
| 450 | # pick the type default if it already satisfies <= max, else max-1 | |||||
| 451 | 18 | 37 | return $default < $max ? $default : $max - 1; | |||
| 452 | } | |||||
| 453 | 136 | 137 | return $default; | |||
| 454 | } | |||||
| 455 | ||||||
| 456 | 27 | 45 | return $TYPE_DEFAULTS{$type} // "'value'"; | |||
| 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 | sub _quote_value { | |||||
| 470 | 31 | 6583 | my ($v) = @_; | |||
| 471 | 31 | 34 | return 'undef' unless defined $v; | |||
| 472 | ||||||
| 473 | 28 | 30 | if(my $type = ref $v) { | |||
| 474 | 2 | 21 | croak "BenchmarkGenerator: cannot write a $type reference as a literal" | |||
| 475 | unless $type eq 'HASH' || $type eq 'ARRAY'; | |||||
| 476 | 1 | 3 | local $Data::Dumper::Terse = 1; | |||
| 477 | 1 | 3 | local $Data::Dumper::Indent = 0; | |||
| 478 | 1 | 2 | local $Data::Dumper::Sortkeys = 1; | |||
| 479 | 1 | 8 | return Data::Dumper::Dumper($v); | |||
| 480 | } | |||||
| 481 | ||||||
| 482 | 26 | 34 | return $v if $v =~ $NUMERIC_LITERAL_RE; | |||
| 483 | 14 | 58 | 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 | sub _quote_string { | |||||
| 496 | 178 | 127 | my ($s) = @_; | |||
| 497 | 178 | 142 | (my $escaped = $s) =~ s/([\\'])/\\$1/g; | |||
| 498 | 178 | 188 | 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 | sub _quote_key { | |||||
| 512 | 134 | 70 | my ($key) = @_; | |||
| 513 | 134 | 151 | return $key =~ $BAREWORD_RE ? $key : _quote_string($key); | |||
| 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 | sub _hash_or_empty { | |||||
| 530 | 354 | 185 | my ($v) = @_; | |||
| 531 | 354 | 327 | return ref($v) eq 'HASH' ? $v : {}; | |||
| 532 | } | |||||
| 533 | ||||||
| 534 - 789 | =head1 COMMON PITFALLS
=over 4
=item Schema missing C<module> or C<function>
C<generate> croaks immediately if either key is absent. Always ensure the
schema has been loaded from a valid ATG YAML file before calling C<generate>.
=item Expecting test-framework output
The generated script uses C<Benchmark::cmpthese> and prints timing results to
STDOUT. It is B<not> a test file and produces no TAP output. Do not run it
with C<prove>.
=item OOP schemas need a C<new:> key
If the function under benchmark is an instance method, the schema must have a
C<new:> key (even if its value is an empty hashref C<{}>) so C<generate> emits
a C<my $obj = Module->new(...)> constructor call before the C<cmpthese> block.
Without it, the variant calls use C<Module::function(...)> form.
=item Transforms that omit the C<input> key
If a transform's hashref has no C<input> key, C<generate> falls back to the
base schema C<input> spec for that variant. This is intentional but may
produce identical argument lists across variants if you forgot to add per-
transform input overrides.
=item A transform C<input> replaces the base C<input>. It is not merged.
If the base C<input> has the parameters C<a> and C<b>, and a transform
C<input> has only C<a>, then that variant is called with C<a> alone.
C<b> is not copied from the base. Repeat every parameter you need inside
each transform.
=item Only plain data is allowed under C<new>
A value under C<new> can be a number, a string, C<undef>, an arrayref or
a hashref, nested to any depth. A code reference or an object makes
C<generate> croak.
=item How C<undef> is handled
=over 4
=item * C<schema =E<gt> undef> makes C<new> croak with C<schema is required>.
=item * A C<module> or C<function> that is C<undef> makes C<generate> croak.
=item * A missing or C<undef> C<input> or C<transforms> key means "no
parameters" or "no transforms". This is safe.
=item * C<new =E<gt> undef> (C<new: ~> in YAML) still counts as "has a
constructor". The script calls C<< Module->new() >> with no arguments.
=item * An C<undef> value B<inside> C<new> is written as the Perl word C<undef>.
=item * A parameter whose specification is C<undef> is passed as the
Perl word C<undef>.
=back
=item The text C<undef> means "no input"
Some ATG schema files contain C<input: undef>. YAML reads this as the
five-letter string C<"undef">. C<generate> treats that string, and any
other C<input> or C<transforms> value that is not a hashref, as "no
parameters". Inside a transform, C<input: undef> gives a call with no
arguments; it does B<not> fall back to the base C<input>.
=item Names that are not plain words are quoted for you
Transform names, parameter names and the keys under C<new> can contain
any characters. They are quoted and escaped in the generated script when
needed. Only C<module> and C<function> must be valid Perl names.
=item Which text is written as a number
A string under C<new> is written without quotes only when it is a plain
decimal number such as C<42>, C<-1.5> or C<2e10>. Everything else,
including C<'Inf'>, C<'NaN'> and C<' 12'>, is written as a quoted string.
Be careful with a leading zero: C<'007'> is written as C<007>, which Perl
reads as an octal number.
=back
=head1 ENCODING
=over 4
=item * C<module> and C<function>
Use ASCII letters, digits, underscores and C<::> only. Non-ASCII letters
may pass the name check, but the generated script has no C<use utf8> line,
so Perl will not read such names correctly.
=item * Transform names, parameter names and string values under C<new>
Full UTF-8 text, including non-ASCII letters and emojis, is copied into
the script unchanged. This is safe only if you take two steps yourself:
write the script through a UTF-8 file handle
(C<< open my $fh, '>:encoding(UTF-8)', $path >>), and remember that the
script has no C<use utf8> line, so the running benchmark sees the text as
bytes, not as characters. For a benchmark that needs real character
strings, add C<use utf8;> to the generated file by hand.
=item * Sample argument values
These are always ASCII (C<42>, C<3.14>, C<'hello'>, C<[]>, C<{}>).
The generator never invents non-ASCII test data.
=item * The return value of C<generate>
A Perl character string. It is ASCII unless your schema put non-ASCII
text into it as described above.
=back
=head1 LIMITATIONS
=over 4
=item Representative values are heuristic
C<_representative_value> picks a single value based on type and C<min>/C<max>
constraints. It does not guarantee the chosen value exercises any particular
code path, and it does not use the schema's C<enum> or C<matches> keys.
=item No round-trip with C<extract-schemas>
The generator reads any conforming ATG YAML schema, but it does not verify
that the schema accurately describes the actual function's signature. If the
schema is stale, the generated benchmark may pass wrong argument types.
=back
=head1 SEE ALSO
=over 4
=item L<Benchmark>
=item C<bin/benchmark-generator>
=item L<App::Test::Generator>
=back
=head1 AUTHOR
Nigel Horne, C<< <njh at nigelhorne.com> >>
=head1 FORMAL SPECIFICATION
This section describes each method in Z notation. It is for readers who
want an exact, mathematical statement. You do not need it to use the module.
How to read it: a name ending in C<?> is an input, a name ending in C<!> is
an output, and a name ending in C<'> is the value after the call.
The symbol E<0x039E> before the state name means "this call does not change
the object".
The state of an object is one value, the schema given to C<new>:
ââ BenchmarkGenerator ââââââââââââââââââââââââââââââ
â schema : HASHREF
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
â schema â undef
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
=head2 new
ââ New âââââââââââââââââââââââââââââââââââââââââââââ
â BenchmarkGeneratorâ²
â schema? : VALUE
â result! : BenchmarkGenerator
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
â pre schema? â undef â§ ref(schema?) = 'HASH'
â post schemaâ² = schema?
â result! = θ BenchmarkGeneratorâ²
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
schema? = undef â croak 'schema is required'
ref(schema?) â 'HASH' â croak 'schema must be a hashref'
=head2 generate
NAME == { s : STRING | s matches /^[A-Za-z_]\w*(::[A-Za-z_]\w*)*$/ }
ââ Generate ââââââââââââââââââââââââââââââââââââââââ
â Î BenchmarkGenerator
â result! : STRING
â variants : â STRING
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
â pre schema.module â undef â§ schema.function â undef
â schema.module = 'builtin' ⨠schema.module â NAME
â schema.function â NAME
â post schema.transforms = â
â variants = { 'default' }
â schema.transforms â â
â variants = dom schema.transforms
â #variants = max(1, #(dom schema.transforms))
â result! contains exactly one cmpthese(...) call
â â v : variants ⢠result! contains one timed call named v
â schema.module = 'builtin' â result! has no 'use module' line
â ('new' â dom schema â§ schema.module â 'builtin')
â â result! builds $obj with module->new(...)
ââââââââââââââââââââââââââââââââââââââââââââââââââââ
=head1 STATE DIAGRAM
An object of this class has only one working state. It is created ready
to use and it never changes afterwards.
new(schema => undef)
new(schema => not a hashref)
+------------------------------+
| action: croak, no object |
v |
+-------------+ |
| NO OBJECT |-----------------------+
+-------------+
|
| new(schema => HASHREF)
| action: keep a reference to the schema
v
+-------------+ generate() [schema is good]
| |---------------------------------+
| READY | action: return the script |
| |<--------------------------------+
| |
| | generate() [module or function
| | missing or not a name]
| |---------------------------------+
| | action: croak, nothing changes|
| |<--------------------------------+
+-------------+
|
| last reference goes away
| action: Perl frees the object
v
+-------------+
| GONE |
+-------------+
Side effects: C<new> and C<generate> write no files and print nothing.
The schema that you passed to C<new> is never changed.
=head1 LICENCE AND COPYRIGHT
Copyright 2026 Nigel Horne.
Usage is subject to the terms of GPL2.
If you use it,
please let me know.
=cut | |||||
| 790 | ||||||
| 791 | 1; | |||||