lib/App/Test/Generator/BenchmarkGenerator.pm

Structural Coverage (Approximate)

TER1 (Statement): 100.00%
TER2 (Branch): 96.88%
TER3 (LCSAJ): 100.0% (8/8)
Approximate LCSAJ segments: 65

LCSAJ Legend

● Covered — this LCSAJ path was executed during testing.

● Not covered — this LCSAJ path was never executed. These are the paths to focus on.

Multiple dots on a line indicate that multiple control-flow paths begin at that line. Hovering over any dot shows:

        start → end → jump
        

Uncovered paths show [NOT COVERED] in the tooltip.

Mutant Testing Legend

Survived (tests missed this) Killed (tests detected this) No mutation
    1: package App::Test::Generator::BenchmarkGenerator;
    2: 
    3: use 5.036;
    4: use Carp qw(croak);
    5: use Data::Dumper ();
    6: use Params::Get qw(get_params);
    7: use Readonly;
    8: 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: =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.

Mutants (Total: 2, Killed: 2, Survived: 0)

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: sub new { 189: my ($class, @args) = @_; 190: my $params = get_params('schema', \@args); 191: croak 'schema is required' unless defined $params->{schema}; 192: croak 'schema must be a hashref' unless ref $params->{schema} eq 'HASH'; 193: 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.

Mutants (Total: 1, Killed: 1, Survived: 0)

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:

Mutants (Total: 1, Killed: 1, Survived: 0)

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>.

Mutants (Total: 1, Killed: 1, Survived: 0)

248: The special name C<builtin> is always accepted. 249:

Mutants (Total: 1, Killed: 1, Survived: 0)

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:

Mutants (Total: 1, Killed: 1, Survived: 0)

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

Mutants (Total: 2, Killed: 2, Survived: 0)

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: sub generate { ●292 → 298 → 302 292: my $self = $_[0]; 293: 294: my $schema = $self->{schema}; 295: my $module = $schema->{module} // croak 'schema missing module'; 296: my $function = $schema->{function} // croak 'schema missing function'; 297: 298: unless($module eq 'builtin') { 299: croak("BenchmarkGenerator: module '$module' is not a valid Perl identifier") 300: unless $module =~ /^[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/; 301: }

Mutants (Total: 1, Killed: 1, Survived: 0)

●302 → 322 → 326 302: croak("BenchmarkGenerator: function '$function' is not a valid Perl identifier") 303: unless $function =~ /^[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/; 304: my $has_new = exists $schema->{new}; 305: my %input = %{ _hash_or_empty($schema->{input}) }; 306: my %xforms = %{ _hash_or_empty($schema->{transforms}) }; 307: 308: my $is_builtin = ($module eq 'builtin'); 309: 310: my @lines; 311: 312: 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{},

Mutants (Total: 2, Killed: 2, Survived: 0)

318: 'use strict;', 319: 'use warnings;', 320: 'use Benchmark qw(cmpthese);'; 321: 322: unless($is_builtin) { 323: push @lines, "use $module;"; 324: } 325: ●326 → 331 → 342 326: push @lines, 327: q{}, 328: 'my $COUNT = -3; # seconds per variant (negative = time-based)', 329: q{}; 330: 331: if($has_new && !$is_builtin) { 332: my $new_spec = $schema->{new}; 333: if(ref $new_spec eq 'HASH' && %$new_spec) {

Mutants (Total: 2, Killed: 2, Survived: 0)

334: my $args = join(', ', map { _quote_key($_) . ' => ' . _quote_value($new_spec->{$_}) } sort keys %$new_spec); 335: push @lines, "my \$obj = ${module}->new($args);"; 336: } else { 337: push @lines, "my \$obj = ${module}->new();";

Mutants (Total: 1, Killed: 1, Survived: 0)

338: } 339: push @lines, q{}; 340: } 341:

Mutants (Total: 1, Killed: 1, Survived: 0)

●342 → 345 → 357 342: push @lines, "printf \"Benchmarking ${function}\\n\\n\";", q{};

Mutants (Total: 2, Killed: 2, Survived: 0)

343: 344: my %variants;

Mutants (Total: 1, Killed: 1, Survived: 0)

345: if(%xforms) { 346: for my $name (sort keys %xforms) {

Mutants (Total: 5, Killed: 5, Survived: 0)

347: my $xform = _hash_or_empty($xforms{$name}); 348: my $xinput = exists $xform->{input} && defined $xform->{input}

Mutants (Total: 1, Killed: 1, Survived: 0)

349: ? _hash_or_empty($xform->{input}) 350: : \%input;

Mutants (Total: 5, Killed: 5, Survived: 0)

351: $variants{$name} = _build_call($module, $function, $has_new, $xinput); 352: }

Mutants (Total: 2, Killed: 2, Survived: 0)

353: } else { 354: $variants{'default'} = _build_call($module, $function, $has_new, \%input); 355: }

Mutants (Total: 2, Killed: 2, Survived: 0)

356: ●357 → 360 → 364 357: push @lines, 'cmpthese($COUNT, {'; 358: my %label = map { $_ => _quote_string($_) } keys %variants; 359: my $name_width = (sort { $b <=> $a } map { length } values %label)[0]; 360: for my $name (sort keys %variants) { 361: my $padded = sprintf "%-*s", $name_width, $label{$name}; 362: push @lines, "\t$padded => sub { $variants{$name} },"; 363: } 364: push @lines, '});', q{}; 365: 366: return join("\n", @lines); 367: } 368: 369: # --------------------------------------------------

Mutants (Total: 2, Killed: 2, Survived: 0)

370: # _build_call

Mutants (Total: 2, Killed: 2, Survived: 0)

371: # 372: # Purpose: Build the Perl expression that calls the target function

Mutants (Total: 2, Killed: 2, Survived: 0)

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 → 391 → 414 384: 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: my $has_positions = grep { ref($_) eq 'HASH' && defined $_->{position} } values %$input; 389: my $call; 390: 391: if($has_positions) { 392: my @positional = sort { $a->{position} <=> $b->{position} } 393: 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: my @named = map { _quote_key($_) . ' => ' . _representative_value($input->{$_}) } 400: sort grep { !(ref($input->{$_}) eq 'HASH' && defined $input->{$_}{position}) } 401: keys %$input; 402: my $args = join(', ', (map { _representative_value($_) } @positional), @named); 403: $call = $has_new ? "\$obj->$function($args)" 404: : ($module eq 'builtin' ? "$function($args)" 405: : "${module}::$function($args)"); 406: } else { 407: my @pairs = map { _quote_key($_) . ' => ' . _representative_value($input->{$_}) } 408: sort keys %$input; 409: my $args = join(', ', @pairs); 410: $call = $has_new ? "\$obj->$function($args)" 411: : "${module}::$function($args)"; 412: } 413: 414: 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 → 435 → 456 429: my ($spec) = @_; 430: return 'undef' unless defined $spec; 431: $spec = {} unless ref($spec) eq 'HASH'; 432: 433: my $type = lc($spec->{type} // 'string'); 434: 435: if($type eq 'number' || $type eq 'integer' || $type eq 'float') { 436: 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: my $max = defined($spec->{sample_max}) ? $spec->{sample_max} : $spec->{max}; 441: my $default = $TYPE_DEFAULTS{$type} // 42; 442: if(defined $min && looks_like_number($min) && defined $max && looks_like_number($max)) { 443: return int(($min + $max) / 2); 444: } 445: if(defined $min && looks_like_number($min)) { 446: # pick the type default if it already satisfies >= min, else min+1 447: return $default > $min ? $default : $min + 1; 448: } 449: if(defined $max && looks_like_number($max)) { 450: # pick the type default if it already satisfies <= max, else max-1 451: return $default < $max ? $default : $max - 1; 452: } 453: return $default; 454: } 455: 456: 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 → 473 → 482 470: my ($v) = @_; 471: return 'undef' unless defined $v; 472: 473: if(my $type = ref $v) { 474: croak "BenchmarkGenerator: cannot write a $type reference as a literal" 475: unless $type eq 'HASH' || $type eq 'ARRAY'; 476: local $Data::Dumper::Terse = 1; 477: local $Data::Dumper::Indent = 0; 478: local $Data::Dumper::Sortkeys = 1; 479: return Data::Dumper::Dumper($v); 480: } 481: 482: return $v if $v =~ $NUMERIC_LITERAL_RE; 483: 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: my ($s) = @_; 497: (my $escaped = $s) =~ s/([\\'])/\\$1/g; 498: 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: my ($key) = @_; 513: 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: my ($v) = @_; 531: return ref($v) eq 'HASH' ? $v : {}; 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: 1;