TER1 (Statement): 88.28%
TER2 (Branch): 76.57%
TER3 (LCSAJ): 100.0% (351/351)
Approximate LCSAJ segments: 2669
● 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.
1: package App::Test::Generator::SchemaExtractor; 2: 3: use strict; 4: use warnings; 5: use autodie qw(:all); 6: 7: use App::Test::Generator::Model::Method; 8: use App::Test::Generator::Analyzer::Complexity; 9: use App::Test::Generator::Analyzer::Return; 10: use App::Test::Generator::Analyzer::ReturnMeta; 11: use App::Test::Generator::Analyzer::SideEffect; 12: use App::Test::Generator::Provenance qw( 13: SOURCE_VALIDATOR SOURCE_INPUT_SPEC SOURCE_POD 14: SOURCE_CODE SOURCE_SIGNATURE SOURCE_FIELD 15: ); 16: 17: use Carp qw(carp croak); 18: use PPI; 19: use Pod::Simple::Text; 20: use File::Basename; 21: use File::Path qw(make_path); 22: use Params::Get; 23: use Safe; 24: use Scalar::Util qw(looks_like_number refaddr reftype); 25: use YAML::XS; 26: use IPC::Open3; 27: use JSON::MaybeXS qw(encode_json decode_json); 28: use Readonly; 29: use Symbol qw(gensym); 30: 31: # -------------------------------------------------- 32: # Confidence score thresholds for input and output analysis 33: # -------------------------------------------------- 34: Readonly my $CONFIDENCE_HIGH_THRESHOLD => 60; 35: Readonly my $CONFIDENCE_MEDIUM_THRESHOLD => 35; 36: Readonly my $CONFIDENCE_LOW_THRESHOLD => 15; 37: 38: # -------------------------------------------------- 39: # Confidence level label strings 40: # -------------------------------------------------- 41: Readonly my $LEVEL_HIGH => 'high'; 42: Readonly my $LEVEL_MEDIUM => 'medium'; 43: Readonly my $LEVEL_LOW => 'low'; 44: Readonly my $LEVEL_VERY_LOW => 'very_low'; 45: Readonly my $LEVEL_NONE => 'none'; 46: 47: # -------------------------------------------------- 48: # Analysis limits 49: # -------------------------------------------------- 50: Readonly my $DEFAULT_MAX_PARAMETERS => 20; 51: Readonly my $DEFAULT_CONFIDENCE_THRESH => 0.5; 52: Readonly my $POD_WALK_LIMIT => 200; 53: Readonly my $SIGNATURE_TIMEOUT_SECS => 3; 54: Readonly my $MEMORY_LIMIT_BYTES => 50_000_000; 55: 56: # -------------------------------------------------- 57: # Patterns for rejecting dangerous signature expressions 58: # in _compile_signature_isolated 59: # -------------------------------------------------- 60: Readonly my $UNSAFE_KEYWORD_RE => qr/\b(?:system|exec|open|fork|require|do|eval|qx)\b/; 61: Readonly my $UNSAFE_CHAR_RE => qr/[`{};]/; 62: 63: # -------------------------------------------------- 64: # strict_pod levels â integer values stored internally 65: # but referred to by name everywhere in code 66: # -------------------------------------------------- 67: Readonly my $STRICT_POD_OFF => 0; 68: Readonly my $STRICT_POD_WARN => 1; 69: Readonly my $STRICT_POD_FATAL => 2; 70: 71: # -------------------------------------------------- 72: # Numeric boundary values for test hint generation 73: # -------------------------------------------------- 74: Readonly my $INT32_MAX => 2_147_483_647; 75: 76: # -------------------------------------------------- 77: # Boolean return score thresholds 78: # -------------------------------------------------- 79: Readonly my $BOOLEAN_SCORE_THRESHOLD => 30; 80: 81: =head1 NAME 82: 83: App::Test::Generator::SchemaExtractor - Extract test schemas from Perl modules 84: 85: =head1 VERSION 86: 87: Version 0.52 88: 89: =cut 90: 91: our $VERSION = '0.52'; 92: 93: =head1 SYNOPSIS 94: 95: use App::Test::Generator::SchemaExtractor; 96: 97: my $extractor = App::Test::Generator::SchemaExtractor->new( 98: input_file => 'lib/MyModule.pm', 99: output_dir => 'schemas/', 100: verbose => 1, 101: ); 102: 103: my $schemas = $extractor->extract_all(); 104: 105: =head1 DESCRIPTION 106: 107: App::Test::Generator::SchemaExtractor analyzes Perl modules and generates 108: structured YAML schema files suitable for automated test generation by L<App::Test::Generator>. 109: This module employs 110: static analysis techniques to infer parameter types, constraints, and 111: method behaviors directly from your source code. 112: 113: =head2 Analysis Methods 114: 115: The extractor combines multiple analysis approaches for a comprehensive schema generation: 116: 117: =over 4 118: 119: =item * B<POD Documentation Analysis> 120: 121: Parses embedded documentation to extract: 122: - Parameter names, types, and descriptions from =head2 sections 123: - Method signatures with positional parameters 124: - Return value specifications from "Returns:" sections 125: - Constraints (ranges, patterns, required/optional status) 126: (in a formal C<=head4 Input> spec, C<required =E<gt> 1> means 127: C<optional: 0> and an explicit C<optional> flag wins; a bare list of 128: C<name =E<gt> { ... }> entries with no outer braces contributes only 129: its top-level C<required> flags) 130: - Semantic type detection (email, URL, filename) 131: 132: =item * B<Code Pattern Detection> 133: 134: Analyzes source code using PPI to identify: 135: - Method signatures and parameter extraction patterns 136: - Type validation (ref(), isa(), blessed()) 137: - Constraint patterns (length checks, numeric comparisons, regex matches) 138: - Return statement analysis and value type inference 139: - Object instantiation requirements and accessor methods 140: 141: =item * B<Signature Analysis> 142: 143: Examines method declarations for: 144: - Parameter names and positional information 145: - Instance vs. class method detection 146: - Method modifiers (Moose-style before/after/around) 147: - Various parameter declaration styles (shift, @_ assignment) 148: 149: =item * B<Heuristic Inference> 150: 151: Applies Perl-specific domain knowledge: 152: - Boolean return detection from method names (is_*, has_*, can_*) 153: - Common Perl idioms and coding patterns 154: - Context awareness (scalar vs list, wantarray usage) 155: - Object-oriented patterns (constructors, accessors, chaining) 156: 157: =back 158: 159: =head2 Generated Schema Structure 160: 161: The extracted schemas follow this YAML structure: 162: 163: function: method_name 164: module: Package::Name 165: input: 166: param1: 167: type: string 168: min: 3 169: max: 50 170: optional: 0 171: position: 0 172: param2: 173: type: integer 174: min: 0 175: max: 100 176: optional: 1 177: position: 1 178: output: 179: type: boolean 180: value: 1 181: new: Package::Name # if object instantiation required 182: config: 183: test_empty: 1 184: test_nuls: 0 185: test_undef: 0 186: test_non_ascii: 0 187: 188: =head2 Advanced Detection Capabilities 189: 190: =over 4 191: 192: =item * B<Accessor Method Detection> 193: 194: Automatically identifies getter, setter, and combined accessor methods 195: by analyzing common patterns like C<return $self-E<gt>{property}> and 196: C<$self-E<gt>{property} = $value>. 197: 198: =item * B<Params::Get Integration> 199: 200: Recognises parameters extracted via C<Params::Get::get_params('key', \@_)>, 201: treating the quoted key as a named parameter equivalent to a traditional 202: C<my ($self, $key) = @_> signature. This prevents false positives from 203: C<--strict-pod> when the method body never declares an explicit C<$key> 204: variable. 205: 206: =item * B<Direct-Index Self Style> 207: 208: Recognises C<my $self = $_[0]> as a valid method-invocant pattern. Parameters 209: at C<$_[1]>, C<$_[2]>, etc. are extracted as positional parameters. Without 210: this, the signature fallback would incorrectly pick up C<my (...) = @_> from 211: inner closures defined in the method body and treat those variables as the 212: outer method's parameters. 213: 214: =item * B<Boolean Return Inference> 215: 216: Detects boolean-returning methods through multiple signals: 217: - Method name patterns (is_*, has_*, can_*) 218: - Return patterns (consistent 1/0 returns) 219: - POD descriptions ("returns true on success") 220: - Ternary operators with boolean results 221: 222: =item * B<Context Awareness> 223: 224: Identifies methods that use C<wantarray> and can return different 225: values in scalar vs list context. 226: 227: =item * B<Object Lifecycle Management> 228: 229: Detects instance methods requiring object instantiation and 230: automatically adds the C<new> field to schemas. 231: 232: =item * B<Enhanced Object Detection> 233: 234: The extractor includes sophisticated object detection capabilities that go beyond simple instance method identification: 235: 236: =over 4 237: 238: =item * B<Factory Method Recognition> 239: 240: Automatically identifies methods that create and return object instances, such as methods named C<create_*>, C<make_*>, C<build_*>, or C<get_*>. Factory methods are correctly classified as class methods that don't require pre-existing objects for testing. 241: 242: =item * B<Singleton Pattern Detection> 243: 244: Recognizes singleton patterns through multiple signals: method names like C<instance> or C<get_instance>, static variables holding instance references, lazy initialization patterns (C<$instance ||= new()>), and consistent return of the same instance variable. 245: 246: =item * B<Constructor Parameter Analysis> 247: 248: Examines C<new> methods to determine required and optional parameters, validation requirements, and default values. This enables test generators to provide appropriate constructor arguments when object instantiation is needed. 249: 250: A constructor that rejects an empty arrayref, or calls methods on (or 251: checks C<blessed> on) the elements of a required arrayref parameter, needs 252: live objects that a YAML fixture cannot hold. Its C<new> schema gets a 253: C<skip> reason such as C<needs a non-empty arrayref of live objects in 254: 'databases'>, and its instance methods are emitted with C<new: ~> so 255: harnesses skip them. 256: 257: =item * B<Inheritance Relationship Handling> 258: 259: Detects parent classes through C<use parent>, C<use base>, and C<@ISA> declarations. Identifies when methods use C<SUPER::> calls and determines whether the current class or a parent class constructor should be used for object instantiation. 260: 261: =item * B<External Object Dependency Detection> 262: 263: Identifies when methods create or depend on objects from other classes, enabling proper test setup with mock objects or real dependencies. 264: 265: =back 266: 267: These enhancements ensure that generated test schemas accurately reflect the object-oriented structure of the code, leading to more meaningful and effective test generation. 268: 269: =back 270: 271: =head2 Confidence Scoring 272: 273: Each generated schema includes detailed confidence assessments: 274: 275: =over 4 276: 277: =item * B<High Confidence> 278: 279: Multiple independent analysis sources converge on consistent, 280: well-constrained parameters with explicit validation logic and 281: comprehensive documentation. 282: 283: =item * B<Medium Confidence> 284: 285: Reasonable evidence from code patterns or partial documentation, 286: but may lack comprehensive constraints or have some ambiguities. 287: 288: =item * B<Low Confidence> 289: 290: Minimal evidence - primarily based on naming conventions, 291: default assumptions, or single-source analysis. 292: 293: =item * B<Very Low Confidence> 294: 295: Barely any detectable signals - schema should be thoroughly 296: reviewed before use in test generation. 297: 298: =back 299: 300: =head2 Use Cases 301: 302: =over 4 303: 304: =item * B<Automated Test Generation> 305: 306: Generate comprehensive test suites with L<App::Test::Generator> using 307: extracted schemas as input. The schemas provide the necessary structure 308: for generating both positive and negative test cases. 309: 310: =item * B<API Documentation Generation> 311: 312: Supplement existing documentation with automatically inferred interface 313: specifications, parameter requirements, and return types. 314: 315: =item * B<Code Quality Assessment> 316: 317: Identify methods with poor documentation, inconsistent parameter handling, 318: or unclear interfaces that may benefit from refactoring. 319: 320: =item * B<Refactoring Assistance> 321: 322: Detect method dependencies, object instantiation requirements, and 323: parameter usage patterns to inform refactoring decisions. 324: 325: =item * B<Legacy Code Analysis> 326: 327: Quickly understand the interface contracts of legacy Perl codebases 328: without extensive manual code reading. 329: 330: =back 331: 332: =head2 Integration with Testing Ecosystem 333: 334: The generated schemas are specifically designed to work with the 335: L<App::Test::Generator> ecosystem: 336: 337: # Extract schemas from your module 338: my $extractor = App::Test::Generator::SchemaExtractor->new(...); 339: my $schemas = $extractor->extract_all(); 340: 341: # Use with test generator (typically as separate steps) 342: # fuzz-harness-generator -r schemas/method_name.yml 343: 344: =head2 Limitations and Considerations 345: 346: =over 4 347: 348: =item * B<Dynamic Code Patterns> 349: 350: Highly dynamic code (string evals, AUTOLOAD, symbolic references) 351: may not be fully detected by static analysis. 352: 353: =item * B<Complex Validation Logic> 354: 355: Sophisticated validation involving multiple parameters or external 356: dependencies may require manual schema refinement. 357: 358: =item * B<Confidence Heuristics> 359: 360: Confidence scores are based on heuristics and should be reviewed 361: by developers familiar with the codebase. 362: 363: =item * B<Perl Idiom Recognition> 364: 365: Some Perl-specific idioms may require custom pattern recognition 366: beyond the built-in detectors. 367: 368: =item * B<Documentation Dependency> 369: 370: Analysis quality improves significantly with comprehensive POD 371: documentation following consistent patterns. 372: 373: =item * B<Multi-Package Files> 374: 375: Only the first package in a file is analysed. A file that declares 376: additional packages, such as a small error class, is still extracted, but 377: its schemas carry a C<skip> reason so generated harnesses are not run 378: against it. Perl 5.38 C<class> blocks are not detected in such a file: 379: the C<class>/C<method> scan reads the whole source, so it runs only when 380: the file declares at most one C<package>. 381: 382: =back 383: 384: =head2 Best Practices for Optimal Results 385: 386: =over 4 387: 388: =item * B<Comprehensive POD Documentation> 389: 390: Write detailed POD with explicit parameter documentation using 391: consistent patterns like C<$param - type (constraints), description>. 392: 393: =item * B<Consistent Coding Patterns> 394: 395: Use consistent parameter validation patterns and method signatures 396: throughout your codebase. 397: 398: =item * B<Schema Review Process> 399: 400: Review and refine automatically generated schemas, particularly 401: those with low confidence scores. 402: 403: =item * B<Descriptive Naming> 404: 405: Use descriptive method and parameter names that clearly indicate 406: purpose and expected types. 407: 408: =item * B<Progressive Enhancement> 409: 410: Start with automatically generated schemas and progressively 411: refine them based on test results and code understanding. 412: 413: =back 414: 415: The module is particularly valuable for large codebases where manual schema 416: creation would be prohibitively time-consuming, and for maintaining test 417: coverage as code evolves through continuous integration pipelines. 418: 419: =head2 Advanced Type Detection 420: 421: The schema extractor includes enhanced type detection capabilities that identify specialized Perl types beyond basic strings and integers. 422: L<DateTime> and L<Time::Piece> objects are detected through isa() checks and method call patterns, while date strings (ISO 8601, YYYY-MM-DD) and UNIX timestamps are recognized through regex validation and numeric range checks. 423: File handles and file paths are identified via I/O operations and file test operators, coderefs are detected through ref() checks and invocation patterns, and enum-like parameters are extracted from validation code including regex patterns (C</^(a|b|c)$/>), hash lookups, grep statements, and if/elsif chains. 424: These detected types are preserved in the generated YAML schemas with appropriate semantic annotations, enabling test generators to create more accurate and meaningful test cases. 425: 426: =head3 Example Advanced Type Schema 427: 428: For a method like: 429: 430: sub process_event { 431: my ($self, $timestamp, $status, $callback) = @_; 432: croak unless $timestamp > 1000000000; 433: croak unless $status =~ /^(active|pending|complete)$/; 434: croak unless ref($callback) eq 'CODE'; 435: $callback->($timestamp, $status); 436: } 437: 438: The extractor generates: 439: 440: --- 441: function: process_event 442: module: MyModule 443: input: 444: timestamp: 445: type: integer 446: # min: 0 447: # max: 2147483647 448: position: 0 449: _note: Unix timestamp 450: semantic: unix_timestamp 451: status: 452: type: string 453: enum: 454: - active 455: - pending 456: - complete 457: position: 1 458: _note: 'Must be one of: active, pending, complete' 459: callback: 460: type: coderef 461: position: 2 462: _note: 'CODE reference - provide sub { } in tests' 463: 464: =head1 RELATIONSHIP DETECTION 465: 466: The schema extractor detects relationships and dependencies between parameters, 467: enabling more sophisticated validation and test generation. 468: 469: =head2 Relationship Types 470: 471: =over 4 472: 473: =item * B<mutually_exclusive> 474: 475: Parameters that cannot be used together. 476: 477: die if $file && $content; # Can't specify both 478: 479: Generated schema: 480: 481: relationships: 482: - type: mutually_exclusive 483: params: [file, content] 484: description: Cannot specify both file and content 485: 486: =item * B<required_group> 487: 488: At least one parameter from the group must be specified (OR logic). 489: 490: die unless $id || $name; # Must provide one 491: 492: Generated schema: 493: 494: relationships: 495: - type: required_group 496: params: [id, name] 497: logic: or 498: description: Must specify either id or name 499: 500: =item * B<conditional_requirement> 501: 502: If one parameter is specified, another becomes required (IF-THEN logic). 503: 504: die if $async && !$callback; # async requires callback 505: 506: Generated schema: 507: 508: relationships: 509: - type: conditional_requirement 510: if: async 511: then_required: callback 512: description: When async is specified, callback is required 513: 514: =item * B<dependency> 515: 516: One parameter depends on another being present. 517: 518: die "Port requires host" if $port && !$host; 519: 520: Generated schema: 521: 522: relationships: 523: - type: dependency 524: param: port 525: requires: host 526: description: port requires host to be specified 527: 528: =item * B<value_constraint> 529: 530: Specific value requirements between parameters. 531: 532: die if $ssl && $port != 443; # ssl requires port 443 533: 534: Generated schema: 535: 536: relationships: 537: - type: value_constraint 538: if: ssl 539: then: port 540: operator: == 541: value: 443 542: description: When ssl is specified, port must equal 443 543: 544: =item * B<value_conditional> 545: 546: Parameter required when another has a specific value. 547: 548: die if $mode eq 'secure' && !$key; 549: 550: Generated schema: 551: 552: relationships: 553: - type: value_conditional 554: if: mode 555: equals: secure 556: then_required: key 557: description: When mode equals 'secure', key is required 558: 559: =back 560: 561: =head2 Default Value Extraction 562: 563: The extractor comprehensively extracts default values from both code and POD documentation: 564: 565: =head3 Code Pattern Recognition 566: 567: Extracts defaults from multiple Perl idioms: 568: 569: =over 4 570: 571: =item * Logical OR operator: C<$param = $param || 'default'> 572: 573: =item * Defined-or operator: C<$param //= 'default'> 574: 575: =item * Ternary operator: C<$param = defined $param ? $param : 'default'> 576: 577: =item * Unless conditional: C<$param = 'default' unless defined $param> 578: 579: =item * Chained defaults: C<$param = $param || $self->{_default} || 'fallback'> 580: 581: =item * Multi-line patterns: C<$param = {} unless $param> 582: 583: =back 584: 585: =head3 POD Pattern Recognition 586: 587: Extracts defaults from documentation: 588: 589: =over 4 590: 591: =item * Standard format: C<Default: 'value'> 592: 593: =item * Alternative format: C<Defaults to: 'value'> 594: 595: =item * Inline format: C<Optional, default: 'value'> 596: 597: =item * Parameter lists: C<$param - type, default 'value'> 598: 599: =back 600: 601: =head3 Value Processing 602: 603: Properly handles: 604: 605: =over 4 606: 607: =item * String literals with quotes and escape sequences 608: 609: =item * Numeric values (integers and floats) 610: 611: =item * Boolean values (true/false converted to 1/0) 612: 613: =item * Empty data structures ([] and {}) 614: 615: =item * Special values (undef, __PACKAGE__) 616: 617: =item * Complex expressions (preserved as-is when unevaluatable) 618: 619: =item * Quote operators (q{}, qq{}, qw{}) 620: 621: =back 622: 623: =head3 Type Inference 624: 625: When a parameter has a default value but no explicit type annotation, 626: the type is automatically inferred from the default: 627: 628: $options = {} # inferred as hashref 629: $items = [] # inferred as arrayref 630: $count = 42 # inferred as integer 631: $ratio = 3.14 # inferred as number 632: $enabled = 1 # inferred as boolean 633: 634: =head2 Context-Aware Return Analysis 635: 636: The extractor provides comprehensive analysis of method return behavior, 637: including context sensitivity, error handling conventions, and method chaining patterns. 638: 639: When a method's POD contains a C<=head4 Output> block in 640: L<Params::Validate::Strict> schema format, the C<type> declared there is 641: used as the authoritative output type and takes precedence over all 642: heuristic code analysis: 643: 644: =head4 Output 645: 646: { 647: type => 'hashref', 648: } 649: 650: This is the recommended way to document methods whose return type would 651: otherwise be misidentified (e.g. a method that returns C<$self-E<gt>{cache}> 652: where the cache happens to hold a hashref). 653: 654: Using parentheses as the outer container emits C<type: array>, indicating a 655: list-returning method. L<App::Test::Generator> 0.39+ (with L<Test::Returns> 656: 0.03+) captures these results in list context automatically: 657: 658: =head4 Output 659: 660: ( 661: { 662: type => 'hashref', 663: }, 664: ... 665: ) 666: 667: =head3 List vs Scalar Context Detection 668: 669: Automatically detects methods that return different values based on calling context: 670: 671: sub get_items { 672: my $self = $_[0]; 673: return wantarray ? @items : scalar(@items); 674: } 675: 676: Detection captures: 677: 678: =over 4 679: 680: =item * C<_context_aware> flag - Method uses wantarray 681: 682: =item * C<_list_context> - Type returned in list context (e.g., 'array') 683: 684: =item * C<_scalar_context> - Type returned in scalar context (e.g., 'integer') 685: 686: =back 687: 688: Recognizes both ternary operator patterns and conditional return patterns. 689: 690: =head3 Void Context Methods 691: 692: Identifies methods that don't return meaningful values: 693: 694: =over 4 695: 696: =item * Setters (C<set_*> methods) 697: 698: =item * Mutators (C<add_*, remove_*, delete_*, clear_*, reset_*, update_*>) 699: 700: =item * Loggers (C<log, debug, warn, error, info>) 701: 702: =item * Methods with only empty returns 703: 704: =back 705: 706: Example: 707: 708: sub set_name { 709: my ($self, $name) = @_; 710: $self->{name} = $name; 711: return; # Void context 712: } 713: 714: Sets C<_void_context> flag and C<type =E<gt> 'void'>. 715: 716: =head3 Method Chaining Detection 717: 718: Identifies chainable methods that return C<$self> for fluent interfaces: 719: 720: sub set_width { 721: my ($self, $width) = @_; 722: $self->{width} = $width; 723: return $self; # Chainable 724: } 725: 726: Detection provides: 727: 728: =over 4 729: 730: =item * C<_returns_self> - Returns invocant for chaining 731: 732: =item * C<class> - The class name being returned 733: 734: =back 735: 736: Also detects chaining documentation in POD (keywords: "chainable", "fluent interface", 737: "returns self", "method chaining"). 738: 739: =head3 Error Return Conventions 740: 741: Analyzes how methods signal errors: 742: 743: B<Pattern Detection:> 744: 745: =over 4 746: 747: =item * C<undef_on_error> - Explicit C<return undef if/unless condition> 748: 749: =item * C<implicit_undef> - Bare C<return if/unless condition> 750: 751: =item * C<empty_list> - C<return ()> for list context errors 752: 753: =item * C<zero_on_error> - Returns 0/false for boolean error indication 754: 755: =item * C<exception_handling> - Uses eval blocks with error checking 756: 757: =back 758: 759: B<Example Analysis:> 760: 761: sub fetch_user { 762: my ($self, $id) = @_; 763: 764: return undef unless $id; # undef_on_error 765: return undef if $id < 0; # undef_on_error 766: 767: return $self->{users}{$id}; 768: } 769: 770: Results in: 771: 772: _error_return: 'undef' 773: _success_failure_pattern: 1 774: _error_handling: { 775: undef_on_error: ['$id', '$id < 0'] 776: } 777: 778: B<Success/Failure Pattern:> 779: 780: Methods that return different types for success vs. failure are flagged with 781: C<_success_failure_pattern>. Common patterns: 782: 783: =over 4 784: 785: =item * Returns value on success, undef on failure 786: 787: =item * Returns true on success, false on failure 788: 789: =item * Returns data on success, empty list on failure 790: 791: =back 792: 793: =head3 Success Indicator Detection 794: 795: Methods that always return true (typically for side effects): 796: 797: sub update_status { 798: my ($self, $status) = @_; 799: $self->{status} = $status; 800: return 1; # Success indicator 801: } 802: 803: Sets C<_success_indicator> flag when method consistently returns 1. 804: 805: =head3 Schema Output 806: 807: Enhanced return analysis adds these fields to method schemas: 808: 809: output: 810: type: boolean # Inferred return type 811: _context_aware: 1 # Uses wantarray 812: _list_context: 813: type: array 814: _scalar_context: 815: type: integer 816: _returns_self: 1 # Returns $self 817: _void_context: 1 # No meaningful return 818: _success_indicator: 1 # Always returns true 819: _error_return: undef # How errors are signaled 820: _success_failure_pattern: 1 # Mixed return types 821: _error_handling: # Detailed error patterns 822: undef_on_error: [...] 823: exception_handling: 1 824: 825: This comprehensive analysis enables: 826: 827: =over 4 828: 829: =item * Better test generation (testing both contexts, error paths) 830: 831: =item * Documentation generation (clear error conventions) 832: 833: =item * API design validation (consistent error handling) 834: 835: =item * Contract specification (precise return behavior) 836: 837: =back 838: 839: =head2 Example 840: 841: For a method like: 842: 843: sub connect { 844: my ($self, $host, $port, $ssl, $file, $content) = @_; 845: 846: die if $file && $content; # mutually exclusive 847: die unless $host || $file; # required group 848: die "Port requires host" if $port && !$host; # dependency 849: die if $ssl && $port != 443; # value constraint 850: 851: # ... connection logic 852: } 853: 854: The extractor generates: 855: 856: relationships: 857: - type: mutually_exclusive 858: params: [file, content] 859: description: Cannot specify both file and content 860: - type: required_group 861: params: [host, file] 862: logic: or 863: description: Must specify either host or file 864: - type: dependency 865: param: port 866: requires: host 867: description: port requires host to be specified 868: - type: value_constraint 869: if: ssl 870: then: port 871: operator: == 872: value: 443 873: description: When ssl is specified, port must equal 443 874: 875: =head1 MODERN PERL FEATURES 876: 877: This module adds support for: 878: 879: =head2 Subroutine Signatures (Perl 5.20+) 880: 881: sub connect($host, $port = 3306, %options) { 882: ... 883: } 884: 885: Extracts: required params, optional params with defaults, slurpy params 886: 887: =head2 Type Constraints (Perl 5.36+) 888: 889: sub calculate($x :Int, $y :Num) { 890: ... 891: } 892: 893: Recognizes: Int, Num, Str, Bool, ArrayRef, HashRef, custom classes 894: 895: =head3 Subroutine Attributes 896: 897: sub get_value :lvalue :Returns(Int) { 898: ... 899: } 900: 901: Detects: :lvalue, :method, :Returns(Type), custom attributes 902: 903: =head2 Postfix Dereferencing (Perl 5.20+) 904: 905: my @array = $arrayref->@*; 906: my %hash = $hashref->%*; 907: my @slice = $arrayref->@[1,3,5]; 908: 909: Tracks usage of modern dereferencing syntax 910: 911: =head2 Field Declarations (Perl 5.38+) 912: 913: field $host :param = 'localhost'; 914: field $port :param(port_number) = 3306; 915: field $logger :param :isa(Log::Any); 916: 917: Extracts fields and maps them to parameters 918: 919: =head2 Modern Perl Features Support 920: 921: The schema extractor supports modern Perl syntax introduced in versions 5.20, 5.36, and 5.38+. 922: 923: =head3 Subroutine Signatures (Perl 5.20+) 924: 925: Automatically extracts parameters from native Perl signatures: 926: 927: use feature 'signatures'; 928: 929: sub connect($host, $port = 3306, $database = undef) { 930: ... 931: } 932: 933: Extracted schema includes: 934: 935: =over 4 936: 937: =item * Parameter positions 938: 939: =item * Optional vs required parameters 940: 941: =item * Default values from signature 942: 943: =item * Slurpy parameters (@array, %hash) 944: 945: =back 946: 947: B<Example:> 948: 949: # Signature with defaults 950: sub process($file, %options) { ... } 951: 952: # Extracts: 953: # $file: position 0, required 954: # %options: named: 1, optional, slurpy hash 955: 956: =head3 Type Constraints in Signatures (Perl 5.36+) 957: 958: Recognizes type constraints in signature parameters: 959: 960: sub calculate($x :Int, $y :Num, $name :Str = "result") { 961: return $x + $y; 962: } 963: 964: Supported constraint types: 965: 966: =over 4 967: 968: =item * C<:Int, :Integer> -> integer 969: 970: =item * C<:Num, :Number> -> number 971: 972: =item * C<:Str, :String> -> string 973: 974: =item * C<:Bool, :Boolean> -> boolean 975: 976: =item * C<:ArrayRef, :Array> -> arrayref 977: 978: =item * C<:HashRef, :Hash> -> hashref 979: 980: =item * C<:ClassName> -> object with isa constraint 981: 982: =back 983: 984: Type constraints are combined with defaults when both are present. 985: 986: =head3 Subroutine Attributes 987: 988: Extracts and documents subroutine attributes: 989: 990: sub get_value :lvalue { 991: my $self = shift; 992: return $self->{value}; 993: } 994: 995: sub calculate :Returns(Int) :method { 996: my ($self, $x, $y) = @_; 997: return $x + $y; 998: } 999: 1000: Recognized attributes stored in C<_attributes> field: 1001: 1002: =over 4 1003: 1004: =item * C<:lvalue> - Method can be assigned to 1005: 1006: =item * C<:method> - Explicitly marked as method 1007: 1008: =item * C<:Returns(Type)> - Declares return type 1009: 1010: =item * Custom attributes with values: C<:MyAttr(value)> 1011: 1012: =back 1013: 1014: =head3 Postfix Dereferencing (Perl 5.20+) 1015: 1016: Detects usage of postfix dereferencing syntax: 1017: 1018: use feature 'postderef'; 1019: 1020: sub process_array { 1021: my ($self, $arrayref) = @_; 1022: my @array = $arrayref->@*; # Array dereference 1023: my @slice = $arrayref->@[1,3,5]; # Array slice 1024: return @array; 1025: } 1026: 1027: sub process_hash { 1028: my ($self, $hashref) = @_; 1029: my %hash = $hashref->%*; # Hash dereference 1030: return keys %hash; 1031: } 1032: 1033: Tracked features stored in C<_modern_features>: 1034: 1035: =over 4 1036: 1037: =item * C<array_deref> - Uses C<-E<gt>@*> 1038: 1039: =item * C<hash_deref> - Uses C<-E<gt>%*> 1040: 1041: =item * C<scalar_deref> - Uses C<-E<gt>$*> 1042: 1043: =item * C<code_deref> - Uses C<-E<gt>&*> 1044: 1045: =item * C<array_slice> - Uses C<-E<gt>@[...]> 1046: 1047: =item * C<hash_slice> - Uses C<-E<gt>%{...}> 1048: 1049: =back 1050: 1051: =head3 Field Declarations (Perl 5.38+) 1052: 1053: Extracts field declarations from class syntax and maps them to method parameters: 1054: 1055: use feature 'class'; 1056: 1057: class DatabaseConnection { 1058: field $host :param = 'localhost'; 1059: field $port :param = 3306; 1060: field $username :param(user); 1061: field $password :param; 1062: field $logger :param :isa(Log::Any); 1063: 1064: method connect() { 1065: # Fields available as instance variables 1066: } 1067: } 1068: 1069: Field attributes: 1070: 1071: =over 4 1072: 1073: =item * C<:param> - Field is a constructor parameter (uses field name) 1074: 1075: =item * C<:param(name)> - Field maps to parameter with different name 1076: 1077: =item * C<:isa(Class)> - Type constraint for the field 1078: 1079: =item * Default values in field declarations 1080: 1081: =back 1082: 1083: Extracted schema includes both field information in C<_fields> and merged parameter 1084: information in C<input>, allowing proper validation of class constructors. 1085: 1086: =head3 Mixed Modern and Traditional Syntax 1087: 1088: The extractor handles code that mixes modern and traditional syntax: 1089: 1090: sub modern($x, $y = 5) { 1091: # Modern signature with default 1092: } 1093: 1094: sub traditional { 1095: my ($self, $x, $y) = @_; 1096: $y //= 5; # Traditional default in code 1097: # Both extract same parameter information 1098: } 1099: 1100: Priority order for parameter information: 1101: 1102: =over 4 1103: 1104: =item 1. Signature declarations (highest priority) 1105: 1106: =item 2. Field declarations (for class methods) 1107: 1108: =item 3. POD documentation 1109: 1110: =item 4. Code analysis (lowest priority) 1111: 1112: =back 1113: 1114: This ensures that explicit declarations in signatures take precedence over 1115: inferred information from code analysis. 1116: 1117: =head3 Backwards Compatibility 1118: 1119: All modern Perl feature detection is optional and automatic: 1120: 1121: =over 4 1122: 1123: =item * Traditional C<sub> declarations continue to work 1124: 1125: =item * Code without modern features extracts parameters as before 1126: 1127: =item * Modern features are additive - they enhance rather than replace existing extraction 1128: 1129: =item * Each parameter carries one C<_source> value -- C<validator>, C<input_spec>, C<pod>, C<code>, C<signature> or C<field> -- which the harness uses for its type-checking decisions 1130: 1131: =item * Each constraint that can come from more than one place also carries its own provenance in C<_constraint_source>, a hashref keyed by C<min>, C<max>, C<memberof>, C<matches>, C<nomatch> and C<notmemberof>. A minimum documented in POD and a maximum enforced by the code on the same field therefore stay separate decisions: the documented one is a hint for valid data, the enforced one is a check 1132: 1133: =back 1134: 1135: =head2 _yamltest_hints 1136: 1137: Each method schema returned by L</extract_all> now optionally includes a 1138: C<_yamltest_hints> key, which provides guidance for automated test generation 1139: based on the code analysis. 1140: 1141: This is intended to help L<App::Test::Generator> create meaningful tests, 1142: including boundary and invalid input cases, without manually specifying them. 1143: 1144: The structure is a hashref with the following keys: 1145: 1146: =over 4 1147: 1148: =item * boundary_values 1149: 1150: An arrayref of numeric values that represent boundaries detected from 1151: comparisons in the code. These are derived from literals in statements 1152: like C<$x < 0> or C<$y >= 255>. The generator can use these to create 1153: boundary tests. 1154: 1155: Example: 1156: 1157: _yamltest_hints: 1158: boundary_values: [0, 1, 100, 255] 1159: 1160: =item * invalid_inputs 1161: 1162: An arrayref of values that are likely to be rejected by the method, 1163: based on checks like C<defined>, empty strings, or numeric validations. 1164: 1165: Example: 1166: 1167: _yamltest_hints: 1168: invalid_inputs: [undef, '', -1] 1169: 1170: =item * equivalence_classes 1171: 1172: An arrayref intended to capture detected equivalence classes or patterns 1173: among inputs. Currently this is empty by default, but future enhancements 1174: may populate it based on detected input groupings. 1175: 1176: Example: 1177: 1178: _yamltest_hints: 1179: equivalence_classes: [] 1180: 1181: =back 1182: 1183: =head3 Usage 1184: 1185: When calling C<extract_all>, each method schema will include 1186: C<_yamltest_hints> if any hints were detected: 1187: 1188: my $schemas = $extractor->extract_all; 1189: my $hints = $schemas->{example_method}->{_yamltest_hints}; 1190: 1191: You can then feed these hints into automated test generators to produce 1192: negative tests, boundary tests, and parameter-specific test cases. 1193: 1194: =head3 Notes 1195: 1196: =over 4 1197: 1198: =item * Hints are inferred heuristically from code and validation statements. 1199: 1200: =item * Not all inputs are guaranteed to be detected; the feature is additive 1201: and will never remove information from the schema. 1202: 1203: =item * Currently, equivalence classes are not populated, but the field exists 1204: for future extension. 1205: 1206: =item * Boundary and invalid input hints are deduplicated to avoid repeated 1207: test values. 1208: 1209: =back 1210: 1211: =head3 Examples 1212: 1213: Given a method like: 1214: 1215: sub example { 1216: my ($x) = @_; 1217: die "negative" if $x < 0; 1218: return unless defined($x); 1219: return $x * 2; 1220: } 1221: 1222: After running: 1223: 1224: my $extractor = App::Test::Generator::SchemaExtractor->new( 1225: input_file => 'TestHints.pm', 1226: output_dir => '/tmp', 1227: quiet => 1, 1228: ); 1229: 1230: my $schemas = $extractor->extract_all; 1231: 1232: The schema for the method "example" will include: 1233: 1234: $schemas->{example} = { 1235: function => 'example', 1236: _confidence => { 1237: input => 'unknown', 1238: output => 'unknown', 1239: }, 1240: input => { 1241: x => { 1242: type => 'scalar', 1243: optional => 0, 1244: } 1245: }, 1246: output => { 1247: type => 'scalar', 1248: }, 1249: _yamltest_hints => { 1250: boundary_values => [0, 1], 1251: invalid_inputs => [undef, -1], 1252: equivalence_classes => [], 1253: }, 1254: _notes => '...', 1255: _analysis => { 1256: input_confidence => 'low', 1257: output_confidence => 'unknown', 1258: confidence_factors => { 1259: input => {...}, 1260: output => {...}, 1261: }, 1262: overall_confidence => 'low', 1263: }, 1264: _fields => {}, 1265: _modern_features => {}, 1266: _attributes => {}, 1267: }; 1268: 1269: =head1 METHODS 1270: 1271: =head2 new 1272: 1273: Construct a new SchemaExtractor for a given Perl source file. 1274: 1275: my $extractor = App::Test::Generator::SchemaExtractor->new( 1276: input_file => 'lib/MyModule.pm', # Required 1277: output_dir => 'schemas/', # Optional - only needed if writing schemas 1278: verbose => 1, # Default: 0 1279: include_private => 1, # Default: 0 1280: max_parameters => 50, # Default: 20 1281: confidence_threshold => 0.7, # Default: 0.5 1282: strict_pod => 0|1|2, # Default: 0 (off) 1283: allow_signature_exec => 1, # Default: 0 (off) 1284: ); 1285: 1286: =head3 Arguments 1287: 1288: =over 4 1289: 1290: =item * C<$input_file> 1291: 1292: Path to the Perl source file to analyse. Required. Must exist on disk. 1293: 1294: =item * C<output_dir> 1295: 1296: Directory to write generated schema YAML files. Optional - only 1297: required if C<_write_schema> will be called. Callers passing 1298: C<no_write =E<gt> 1> to C<extract_all> do not need to supply it. 1299: 1300: =item * C<verbose> 1301: 1302: Print progress messages to stdout during analysis. Optional, default 0. 1303: 1304: =item * C<include_private> 1305: 1306: Include methods whose names begin with C<_> in the analysis. Optional, 1307: default 0. Methods whose name begins with C<_new>, C<_init>, or 1308: C<_build> are always included regardless of this setting (a prefix 1309: match, so e.g. C<_build_attribute> and C<_init_logger> qualify too, 1310: matching common Moose builder/initializer naming conventions). 1311: 1312: =item * C<max_parameters> 1313: 1314: Safety limit on the number of parameters analysed per method to prevent 1315: runaway processing on pathological code. Optional, default 20. 1316: 1317: =item * C<confidence_threshold> 1318: 1319: Minimum confidence score (0.0-1.0) below which a schema is marked with 1320: C<_low_confidence =E<gt> 1>. Optional, default 0.5. 1321: 1322: =item * C<strict_pod> 1323: 1324: Controls POD/code agreement validation. C<0> disables validation, 1325: C<1> emits warnings, C<2> croaks on first disagreement. Also accepts 1326: the strings C<off>, C<warn>, and C<fatal>. Optional, default 0. 1327: 1328: =item * C<allow_signature_exec> 1329: 1330: Opt-in flag allowing extraction of parameter types from a 1331: L<Type::Params> C<signature_for()> declaration. This requires actually 1332: running the C<signature_for> expression (sliced from the target 1333: module's own source) in a forked C<perl -T> process, since 1334: L<Type::Params> types are runtime objects that cannot be introspected 1335: statically. Every other extraction path in this module is static 1336: (L<PPI>-only) analysis that never executes any of the target module's 1337: code; this is the one exception. Optional, default 0 (the 1338: C<signature_for> path is silently skipped, with a warning under 1339: C<verbose>, when off). Only enable this for modules whose code you 1340: already trust enough to execute. 1341: 1342: =back 1343: 1344: =head3 Returns 1345: 1346: A blessed hashref. Croaks if C<input_file> is missing or does not 1347: exist on disk. 1348: 1349: =head3 Side effects 1350: 1351: Reads and parses the input file using L<PPI> at construction time. 1352: 1353: =head3 API specification 1354: 1355: =head4 input 1356: 1357: { 1358: input_file => { type => SCALAR },Mutants (Total: 1, Killed: 1, Survived: 0)
1359: output_dir => { type => SCALAR, optional => 1 }, 1360: verbose => { type => SCALAR, optional => 1 }, 1361: include_private => { type => SCALAR, optional => 1 }, 1362: max_parameters => { type => SCALAR, optional => 1 },
Mutants (Total: 2, Killed: 2, Survived: 0)
1363: confidence_threshold => { type => SCALAR, optional => 1 }, 1364: strict_pod => { type => SCALAR, optional => 1 }, 1365: allow_signature_exec => { type => SCALAR, optional => 1 }, 1366: } 1367: 1368: =head4 output 1369: 1370: { 1371: type => OBJECT, 1372: isa => 'App::Test::Generator::SchemaExtractor', 1373: } 1374: 1375: =cut 1376: 1377: sub new { ●1378 → 1399 → 1403 1378: my $class = shift; 1379: 1380: # Handle hash or hashref arguments 1381: my $params = Params::Get::get_params('input_file', @_) || {}; 1382: 1383: croak(__PACKAGE__, ': input_file required') unless exists $params->{input_file}; 1384: 1385: my $self = { 1386: input_file => $params->{input_file}, 1387: # output_dir is optional â only required if _write_schema will be called. 1388: # Callers using extract_all(no_write => 1) do not need to supply it. 1389: output_dir => $params->{output_dir}, 1390: verbose => $params->{verbose} // 0, 1391: include_private => $params->{include_private} // 0, # include _private methods 1392: confidence_threshold => $params->{confidence_threshold} // $DEFAULT_CONFIDENCE_THRESH, 1393: max_parameters => $params->{max_parameters} // $DEFAULT_MAX_PARAMETERS, # safety limit 1394: strict_pod => _validate_strictness_level($params->{strict_pod}), # Enable strict POD checking 1395: allow_signature_exec => $params->{allow_signature_exec} // 0, # opt-in: execute Type::Params signature_for() exprs from the target module 1396: }; 1397: 1398: # Validate input file exists 1399: unless (-f $self->{input_file}) { 1400: croak(__PACKAGE__, ": Input file '$self->{input_file}' does not exist"); 1401: } 1402: 1403: return bless $self, $class; 1404: } 1405: 1406: =head2 extract_all 1407: 1408: Extract schemas for all qualifying methods in the module and return 1409: them as a hashref. 1410: 1411: my $schemas = $extractor->extract_all(); 1412: 1413: # Suppress writing .yml files to disk 1414: my $schemas = $extractor->extract_all(no_write => 1); 1415: 1416: =head3 Arguments 1417: 1418: =over 4 1419: 1420: =item * C<no_write> 1421: 1422: When true, schema files are not written to C<output_dir>. The returned 1423: hashref is still fully populated. Useful when the caller wants to 1424: inspect or augment schemas before deciding whether to write them. 1425: Optional, default 0. 1426: 1427: =back 1428: 1429: =head3 Returns 1430: 1431: A hashref mapping method name strings to schema hashrefs. Each schema 1432: contains at minimum the keys C<function>, C<module>, C<input>, 1433: C<output>, and C<_analysis>. See L</Generated Schema Structure> for 1434: the full structure. 1435: 1436: =head3 Side effects 1437: 1438: Parses the input file with L<PPI>. Writes one YAML file per method to 1439: C<output_dir> unless C<no_write> is set. Creates C<output_dir> if it 1440: does not exist and writing is enabled. 1441: 1442: =head3 Notes 1443: 1444: Private methods (names beginning with C<_>) are excluded unless 1445: C<include_private =E<gt> 1> was passed to C<new>. Duplicate method 1446: names are deduplicated with a warning logged to stdout in verbose mode. 1447: 1448: POD/code agreement validation is applied if C<strict_pod> was set in 1449: C<new>. At level 2 (fatal), the first disagreement causes an immediate 1450: croak. 1451: 1452: =head3 API specification 1453: 1454: =head4 input 1455: 1456: { 1457: self => { type => OBJECT, isa => 'App::Test::Generator::SchemaExtractor' }, 1458: no_write => { type => SCALAR, optional => 1 }, 1459: } 1460: 1461: =head4 output 1462: 1463: { 1464: type => HASHREF, 1465: keys => { 1466: '*' => { 1467: type => HASHREF, 1468: keys => { 1469: function => { type => SCALAR }, 1470: module => { type => SCALAR }, 1471: input => { type => HASHREF }, 1472: output => { type => HASHREF },
Mutants (Total: 2, Killed: 2, Survived: 0)
1473: _analysis => { type => HASHREF }, 1474: }, 1475: }, 1476: }, 1477: } 1478: 1479: =cut 1480: 1481: sub extract_all { ●1482 → 1505 → 1525 1482: my $self = shift; 1483: my $params = Params::Get::get_params(undef, @_) || {}; 1484: 1485: $self->_log("Parsing $self->{input_file}..."); 1486: $self->_log('Strict POD mode: ' . (qw(off warn fatal))[$self->{strict_pod}]); 1487: 1488: # $! is not meaningful here â PPI does not set errno on failure 1489: my $document = PPI::Document->new($self->{input_file}) 1490: or croak "Failed to parse $self->{input_file}"; 1491: 1492: # Store document for later use 1493: $self->{_document} = $document; 1494: 1495: my $package_name = $self->_extract_package_name($document); 1496: $self->{_package_name} //= $package_name; 1497: $self->_log("Package: $package_name"); 1498: 1499: my $methods = $self->_find_methods($document); 1500: $self->_log('Found ' . scalar(@$methods) . ' methods (pre-dedup)');
Mutants (Total: 1, Killed: 1, Survived: 0)
1501: 1502: my %schemas; 1503: my %delegates; 1504: my $ctor_body;
Mutants (Total: 2, Killed: 2, Survived: 0)
1505: foreach my $method (@{$methods}) { 1506: $self->_log("\nAnalyzing method: $method->{name}");
Mutants (Total: 2, Killed: 2, Survived: 0)
1507: 1508: my $schema = $self->_analyze_method($method);
1509: $schemas{$method->{name}} = $schema; 1510: $schema->{'module'} = $package_name;Mutants (Total: 3, Killed: 0, Survived: 3)
- NUM_BOUNDARY_1508_61_<: Numeric boundary flip > to <
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_1508_61_>=: Numeric boundary flip > to >=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_1508_61_<=: Numeric boundary flip > to <=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );Mutants (Total: 2, Killed: 2, Survived: 0)
1511: $ctor_body = $method->{body} if($method->{name} eq 'new'); 1512: 1513: my $target = $self->_delegated_method($method->{body}); 1514: $delegates{$method->{name}} = $target if defined($target); 1515: } 1516: 1517: # Second pass: enrich instance-method schemas with constructor args so the 1518: # fuzz harness can build $self automatically. The new() schema (if present) 1519: # provides type info; we generate one representative value per required param. 1520: # Enrichable: new: {} (no-arg ctor) or new: {hash} (with args). 1521: # Unenrichable (coderef/object params): leave new: as the package-name string 1522: # so _write_schema still emits new: ~ and self-fuzz.t keeps skipping those. 1523: # An arrayref of live objects can be stood in for when the constructor's 1524: # POD names the class the elements must be: see _constructor_object_stubs(). ●1525 → 1526 → 1553 1525: my $object_stubs = {}; 1526: if (exists $schemas{new}) { 1527: my ($new_method) = grep { $_->{name} eq 'new' } @{$methods}; 1528: $object_stubs = _constructor_object_stubs( 1529: $schemas{new}, 1530: $new_method ? $new_method->{pod} : undef, 1531: $ctor_body, 1532: ); 1533: $self->_log(' STUB: stood in for ' . join(', ', sort keys %{$object_stubs})) if %{$object_stubs}; 1534: 1535: my $ctor_args = $self->_ctor_representative_args($schemas{new}); 1536: if (defined $ctor_args) { 1537: for my $method_name (keys %schemas) { 1538: next if $method_name eq 'new'; 1539: my $schema = $schemas{$method_name}; 1540: next unless exists $schema->{new} && defined $schema->{new}; 1541: $schema->{new} = $ctor_args; 1542: $self->_log(" ENRICH: $method_name new: enriched with ctor args"); 1543: } 1544: } 1545: } 1546: 1547: # A constructor that insists on a non-empty arrayref of live objects 1548: # cannot be built from YAML: no generated array is made of blessed 1549: # instances whose methods it can call. Database::Join->new is the case 1550: # that exposed this. Recording the precondition on new() itself lets 1551: # callers skip that constructor and, through the block below, gives the 1552: # instance methods new: ~ as well. ●1553 → 1553 → 1568 1553: if($ctor_body && $schemas{new} 1554: && (my $reason = _constructor_requires_live_objects($ctor_body, $schemas{new}))) { 1555: $schemas{new}{skip} = $reason unless %{$object_stubs}; 1556: $self->_log(" UNBUILDABLE: new: $reason") unless %{$object_stubs}; 1557: }
Mutants (Total: 1, Killed: 1, Survived: 0)
1558: 1559: # A constructor whose input includes an object it will call methods on, 1560: # with no can/isa saying how to stand one in, cannot be built from YAML 1561: # either. Database::BI::Model::Boundary takes a cache and a user agent, 1562: # Geocode a geocoder and a cache, DataSource a cache and translations: 1563: # a generated string is not an object, and the constructors rightly 1564: # refuse one. The same applies to a data directory they read files 1565: # from. Reporting the precondition on new() also makes every instance 1566: # method new: ~ below, so the fuzzer skips the whole family rather than 1567: # failing the object construction at every call. ●1568 → 1568 → 1583 1568: if($ctor_body && $schemas{new} 1569: && (my $reason = _constructor_needs_live_dependencies($schemas{new}))) { 1570: # A stand-in for the documented object list makes the constructor 1571: # buildable: the objects it cannot stand in for are optional, so a 1572: # call that omits them is valid. 1573: $schemas{new}{skip} //= $reason unless %{$object_stubs}; 1574: $self->_log(" UNBUILDABLE: new: $reason") unless %{$object_stubs}; 1575: }
Mutants (Total: 1, Killed: 1, Survived: 0)
1576: 1577: # A constructor can refuse to build the package itself: an abstract base 1578: # class croaks on direct instantiation, and a constructor that croaks over 1579: # an argument the extractor cannot supply cannot be built either. Either 1580: # way no harness can get a $self, so the instance methods are not fuzzable 1581: # this way: leaving new: as the package name makes _write_schema emit 1582: # new: ~, which callers report as skipped rather than failed. ●1583 → 1583 → 1603 1583: if($ctor_body && $schemas{new} && _constructor_refuses_direct_instantiation($ctor_body, $schemas{new})) { 1584: # The class itself cannot be constructed, so its new() is expected to 1585: # die rather than return an object. 1586: $schemas{new}{output} = { _STATUS => 'DIES' }; 1587: for my $method_name (keys %schemas) { 1588: next if($method_name eq 'new'); 1589: my $schema = $schemas{$method_name};
Mutants (Total: 1, Killed: 1, Survived: 0)
1590: next unless(exists($schema->{new}) && defined($schema->{new})); 1591: $schema->{new} = $package_name; 1592: $self->_log(" UNBUILDABLE: $method_name new: ~ ($package_name refuses to be built)"); 1593: } 1594: } 1595: 1596: # Third pass: contracts the type inference cannot see in the signature. 1597: # A routine can document behaviour in its body that changes what the 1598: # harness may assert: an abstract method always dies, a routine returning 1599: # a list must be called in list context, one that returns nothing has no
1600: # output to validate, and a parameter checked against a pattern rejects 1601: # values outside it. A routine that reads a file it is given cannot be 1602: # fuzzed with a synthesized value at all. ●1603 → 1603 → 1823 1603: foreach my $method (@{$methods}) { 1604: my $schema = $schemas{$method->{name}}; 1605: next unless($schema && ref($schema->{output}) eq 'HASH'); 1606: # A comment is prose, not code: an example signature written in one 1607: # must not change how the routine is called. 1608: my $body = _strip_comments($method->{body} // '', $method->{node}); 1609: 1610: # A routine that takes a variadic list or an argument hash receives its 1611: # documentation as named arguments: a table row's order is not a call 1612: # order for it. Database::Join::aggregate forwards @args to get_params, 1613: # and calling it positionally tested the argument count instead of the 1614: # documented keys. Scalar arguments before the slurpy are positional 1615: # (`my ($password, %opts) = @_`), and the documentation after them 1616: # describes the named options passed after those arguments, as 1617: # Database::BI::Password::hash_password does. 1618: # A plain positional signature has no slurpy and keeps every 1619: # position: only the arguments left over after a slurpy are named.Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_1599_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
1620: if($body =~ /\bmy\s*(?:\(([^)]*)\)|(%\w+))\s*=\s*\@_/s) { 1621: my $declared = $1; 1622: if(!defined($declared) || ($declared =~ /[\@%]\w+/)) { 1623: my @prefix; 1624: for my $decl (split(/\s*,\s*/, $declared // '')) { 1625: last if($decl =~ /^\s*[\@%]/); 1626: push @prefix, $1 if($decl =~ /^\s*\$(?!self\b|class\b)(\w+)/); 1627: }
Mutants (Total: 2, Killed: 2, Survived: 0)
1628: 1629: # Keep the leading scalars positional (by name where the merge 1630: # found one, by position otherwise) and say that every remaining 1631: # documented name is a named option after them. 1632: my %keep = map { $prefix[$_] => $_ } 0 .. $#prefix; 1633: for my $param (keys %{ $schema->{input} // {} }) { 1634: my $spec = $schema->{input}{$param}; 1635: my $pos = exists($keep{$param}) ? delete($keep{$param}) : $spec->{position}; 1636: if(defined($pos) && ($pos < @prefix)) { 1637: $spec->{position} = $pos; 1638: delete $spec->{named}; 1639: } else { 1640: delete $spec->{position}; 1641: $spec->{named} = 1 if @prefix; 1642: } 1643: } 1644: } 1645: } 1646: 1647: if($body =~ /\bcroak\b[^;\n]*must be implemented by subclass/) { 1648: $schema->{output}{_STATUS} = 'DIES'; 1649: } elsif(($body =~ /\breturn\s+@\{/) && (($method->{pod} // '') =~ /\b(?:a\s+)?list\s+of\b|\breturns?\s+a\s+list\b/i)) { 1650: # Called in scalar context a list return yields its count, so the 1651: # harness has to capture the list. Only when the POD says the 1652: # routine returns a list, not an arrayref. 1653: $schema->{output}{type} = 'array'; 1654: } elsif(($body =~ /\breturn\s*;/) && ($body !~ /\breturn\s+[^\s;]/)) { 1655: # The routine returns nothing: say so, rather than omitting the 1656: # type. 'void' is the documented way to describe that (see 1657: # _detect_void_context), and the harness validates no return 1658: # value for it. 1659: $schema->{output}{type} = 'void'; 1660: } elsif($body =~ /\breturn\s+\\?[A-Z]\w*(?:::\w+)+(?:->)?\w*\s*\(/) { 1661: # Delegated to another package: its result type is not visible here. 1662: delete $schema->{output}{type}; 1663: } 1664: 1665: # A routine that only croaks is unsupported by design: every call is 1666: # an error, so the harness expects a death for each one. Database::Join 1667: # documents query(), group_by() and execute() that way. 1668: if(_always_croaks($body)) { 1669: $schema->{output} = { _STATUS => 'DIES' }; 1670: } 1671: 1672: # A routine that hands a database handle back to its caller, or leaves 1673: # it on the object's SQLite cache for the next call, holds a 1674: # descriptor on purpose, so the check that nothing leaked does not 1675: # apply (the harness reads config 'check_fds'). 1676: if(_keeps_database_handle($body, $method->{pod} // '')) { 1677: $schema->{_analysis}{side_effects}{keeps_fd} = 1; 1678: } 1679: 1680: if(my $skip = _requires_input_file($body, $schema->{input})) { 1681: $schema->{skip} = $skip; 1682: } 1683: 1684: # A hashref whose POD gives the whole value a shape it must have 1685: # ("hashref of { country code => place rank }", "the existing model 1686: # store") is a precondition, not just a type: a generated hash has 1687: # arbitrary keys, so check_ranks rejects the invented country code
Mutants (Total: 1, Killed: 1, Survived: 0)
1688: # and the model-store routines are handed a string where their 1689: # documented store has a hash. A hashref option that merely 1690: # describes what some entries mean (resolve_values' cache) is not 1691: # this: arbitrary keys are legal there, so it is still fuzzed. 1692: if((my $pod = $method->{pod} // '') =~ /(?:HASHREF|hashref)\s+of\s*\{|(?:HASHREF|hashref)[^\n]*\bmodel store\b/i) { 1693: $schema->{skip} //= 'needs a hashref in the shape its POD documents; a generated hash has arbitrary keys'; 1694: } 1695: 1696: # Settings that name a database, a user and a password describe a 1697: # live server, not a value a fixture can carry: there is no database 1698: # here to connect to, and the routine croaks when it cannot. 1699: # DataSource::mariadb_tables documents exactly that settings hash. 1700: if((my $pod = $method->{pod} // '') =~ /HASHREF[^\n]*\{[^}]*\bdatabase\b[^}]*\b(?:username|password)\b/i) { 1701: $schema->{skip} //= 'needs a live database connection, which a fuzzer cannot provide'; 1702: } 1703: 1704: # A method that reads required keys out of a constructor hashref cannot 1705: # be given a working object: the harness has no schema to put there. 1706: if(ref($schema->{new}) eq 'HASH' && %{$schema->{new}}) { 1707: foreach my $param (keys %{$schema->{new}}) { 1708: my $p = quotemeta($param); 1709: # Read directly, or through a local copy of the hashref. 1710: my $reads_keys = ($body =~ /\$self->\{\s*['"]?$p['"]?\s*\}->\{/) 1711: || ($body =~ /my\s+\$(\w+)\s*=\s*\$self->\{\s*['"]?$p['"]?\s*\}/ && $body =~ /\$$1->\{/); 1712: next unless($reads_keys && ($body =~ /\bcroak\b/)); 1713: $schema->{new} = $self->{_package_name} if($self->{_package_name}); 1714: last; 1715: } 1716: } 1717: 1718: _next_parameter: foreach my $param_name (keys %{$schema->{input} // {}}) { 1719: my $spec = $schema->{input}{$param_name}; 1720: next unless(ref($spec) eq 'HASH'); 1721: my $p = quotemeta($param_name); 1722: 1723: if($body =~ /ref\(\s*\$args\{\s*['"]?$p['"]?\s*\}\s*\)\s*(?:ne|eq)\s*['"]CODE['"]/ 1724: || $body =~ /\$args\{\s*['"]?$p['"]?\s*\}\s*->\s*\(/) { 1725: $spec->{type} = 'coderef'; 1726: next _next_parameter; 1727: } 1728: 1729: # The value is checked against a file-level constant set: the module 1730: # member list is the documented domain, e.g. add_evidence's category. 1731: if($body =~ /my\s+\$(\w+)\s*=\s*\$args\{\s*['"]?$p['"]?\s*\}/) { 1732: my $var = $1; 1733: if($body =~ /[\$%](\w+)\s*\{\s*\$$var\s*\}/) { 1734: my $const = $1; 1735: my $source = $self->{_document} ? $self->{_document}->serialize : ''; 1736: if($source =~ /%$const\s*(?:=|=>)\s*.*?qw\s*[\(\{\[]([^\)\}\]]+)[\)\}\]]/s) { 1737: my @values = split(' ', $1); 1738: $spec->{memberof} = \@values if(@values); 1739: } 1740: } 1741: } 1742: 1743: # A routine that accepts a value by matching it against patterns and 1744: # croaks when none of them match is a validator for that parameter: 1745: # the union of the patterns is the accepted domain, so a value 1746: # outside it is expected to die. parse_zone's UTC, local and 1747: # offset alternatives are three such patterns. 1748: my @accepted; 1749: my @subjects = ( 1750: qr/\$$p\b/, 1751: qr/\$args\{\s*['"]?$p['"]?\s*\}/, 1752: );
Mutants (Total: 3, Killed: 3, Survived: 0)
1753: foreach my $subject (@subjects) {
Mutants (Total: 1, Killed: 1, Survived: 0)
1754: while($body =~ /$subject\s*=~\s*\/([^\/\n]+)\//g) { 1755: my $pattern = $1; 1756: my $at = $-[0]; 1757: my $from = rindex($body, ';', $at); 1758: $from = 0 if($from < 0); 1759: my $prefix = substr($body, $from, $at - $from);
1760: # Only a pattern that guards a returned value (or a croak 1761: # unless it matches) says the value is accepted. A test 1762: # used for anything else, such as deciding whether to append 1763: # a word, describes no domain. `return X unless match` 1764: # returns for every value that does NOT match, so there the 1765: # pattern names a rejection, not an accepted domain. 1766: my $accepts = $prefix =~ /\breturn\b[^;]*\bunless\b/ 1767: ? 0 1768: : ($prefix =~ /\breturn\b/ || $prefix =~ /\b(?:croak|die|confess)\b[^;]*\bunless\b/); 1769: if(!$accepts && ($prefix =~ /\bif\s*\([^;{}]*$/)) { 1770: # A block opened by an if whose condition is the match, 1771: # e.g. `if (my ($s, $h) = $spec =~ /.../) { return ... }`. 1772: my $brace = index($body, '{', $+[0]); 1773: if($brace >= 0) { 1774: my $close = index($body, "\n\t}", $brace);Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_1759_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 2, Killed: 2, Survived: 0)
1775: my $block = substr($body, $brace, 1776: (($close >= 0) ? $close - $brace : 400)); 1777: $accepts = ($block =~ /\breturn\b/) ? 1 : 0; 1778: } 1779: } 1780: next unless($accepts); 1781: # A pattern in a croak's own condition names a rejected 1782: # value, not an accepted one. 1783: next if($prefix =~ /\b(?:croak|die|confess)\b[^;]*\bif\b/); 1784: if(!_pattern_is_self_contained($pattern)) { 1785: $self->_log(" CODE: $param_name matches '$pattern', which depends on run-time variables; not recorded"); 1786: next; 1787: } 1788: push @accepted, $pattern; 1789: } 1790: } 1791: 1792: my $croaks_about_param = 0; 1793: foreach my $subject (@subjects) { 1794: next unless($body =~ /\b(?:croak|die|confess)\b[^;]*$subject/s); 1795: $croaks_about_param = 1; 1796: last; 1797: } 1798: 1799: my $pattern; 1800: if($body =~ /\$args\{\s*['"]?$p['"]?\s*\}\s*=~\s*\/([^\/\n]+)\//) { 1801: $pattern = $1; 1802: } elsif($body =~ /\$$p\b\s*=~\s*\/([^\/\n]+)\//) { 1803: $pattern = $1; 1804: } 1805: if(@accepted && $croaks_about_param) { 1806: my %seen; 1807: @accepted = grep { !$seen{$_}++ } @accepted; 1808: $spec->{matches} = (@accepted == 1) 1809: ? $accepted[0] 1810: : join('|', map { "(?:$_)" } @accepted); 1811: $spec->{_source} = SOURCE_VALIDATOR; 1812: } elsif(defined($pattern) && _pattern_is_self_contained($pattern) 1813: && ($body =~ /\bcroak\b[^;\n]*(?:not a valid|invalid)/i)) { 1814: $spec->{matches} = $pattern; 1815: $spec->{_source} = SOURCE_VALIDATOR; 1816: } 1817: } 1818: } 1819: 1820: # A constructor that parses a file it is given cannot be built by the 1821: # harness either, so its instance methods get new: ~ like any other 1822: # unbuildable class. ●1823 → 1823 → 1837 1823: if($schemas{new} && $schemas{new}{skip}) { 1824: for my $method_name (keys %schemas) { 1825: next if($method_name eq 'new');
Mutants (Total: 1, Killed: 1, Survived: 0)
1826: my $schema = $schemas{$method_name}; 1827: next unless(exists($schema->{new}) && defined($schema->{new})); 1828: $schema->{new} = $package_name; 1829: $self->_log(" UNBUILDABLE: $method_name new: ~ ($package_name constructor is not auto-buildable)"); 1830: } 1831: } 1832: 1833: # A routine whose whole body is `return $self->other(\@_)` has 1834: # exactly other()'s input contract. CGI::Info::get_cookie is such a 1835: # forwarder, and without this it looked like it took no parameters at all, 1836: # so the harness called it with none and died on the required cookie_name. ●1837 → 1837 → 1873 1837: for my $method_name (sort keys %delegates) { 1838: my $target = $delegates{$method_name}; 1839: next if $method_name eq $target; 1840: my $target_schema = $schemas{$target}; 1841: next unless $target_schema; 1842: 1843: my $schema = $schemas{$method_name}; 1844: next unless $schema; 1845: 1846: # The forwarded call's result is this routine's result, so the 1847: # documented output type is the target's too (selectall_hashref is a 1848: # deprecated alias of selectall_arrayref), whether or not the target
Mutants (Total: 1, Killed: 1, Survived: 0)
1849: # takes arguments. 1850: if(ref($target_schema->{output}) eq 'HASH' && %{$target_schema->{output}}) { 1851: $schema->{output} = { %{$target_schema->{output}} }; 1852: } 1853: 1854: next unless ref($target_schema->{input}) eq 'HASH' 1855: && scalar(keys %{$target_schema->{input}}); 1856: next if ref($schema->{input}) eq 'HASH' && scalar(keys %{$schema->{input}}); 1857: 1858: $schema->{input} = { 1859: map { $_ => { %{$target_schema->{input}{$_}} } } sort keys %{$target_schema->{input}}
Mutants (Total: 1, Killed: 1, Survived: 0)
1860: }; 1861: $schema->{_confidence}{input} = { 1862: 'level' => 'medium', 1863: 'factors' => [ "Forwarded to $target()" ] 1864: }; 1865: push @{$schema->{_notes}}, "input inherited from $target(), which this routine forwards \@_ to"; 1866: $self->_log(" DELEGATE: $method_name input inherited from $target"); 1867: }
Mutants (Total: 2, Killed: 2, Survived: 0)
1868: 1869: # A multi-package file is analysed as its primary package, but it is not 1870: # fuzzed: the helper package's routines are deliberately excluded, and 1871: # the primary package's routines may not be fuzzable without it. Mark 1872: # them skipped rather than letting the harness fail on every routine. ●1873 → 1873 → 1880 1873: if($self->{_multiple_packages}) { 1874: for my $method_name (keys %schemas) { 1875: $schemas{$method_name}{skip} //= 1876: "multi-package file; only the primary package $package_name is extracted"; 1877: } 1878: } 1879: ●1880 → 1880 → 1886 1880: unless ($params->{no_write}) {
Mutants (Total: 1, Killed: 1, Survived: 0)
1881: for my $method_name (keys %schemas) { 1882: $self->_write_schema($method_name, $schemas{$method_name}); 1883: } 1884: } 1885: 1886: return \%schemas; 1887: } 1888: 1889: # -------------------------------------------------- 1890: # _delegated_method 1891: # 1892: # Purpose: Detect a routine whose whole body 1893: # forwards its arguments to another 1894: # method of the same object. 1895: # 1896: # Entry: $code - the subroutine's source text. 1897: # 1898: # Exit: Returns the name of the method it 1899: # forwards to, or undef when the routine 1900: # does anything else. 1901: # 1902: # Side effects: None. 1903: #
Mutants (Total: 1, Killed: 1, Survived: 0)
1904: # Notes: Only the bare `return $self->other(\@_)` 1905: # shape counts. Such a forwarder has 1906: # exactly the target's input contract, 1907: # which extract_all() copies so that the 1908: # harness passes the right arguments 1909: # (CGI::Info::get_cookie -> cookie). 1910: # -------------------------------------------------- 1911: sub _delegated_method { 1912: my ($self, $code) = @_; 1913: 1914: return unless defined($code); 1915: 1916: (my $body = $code) =~ s/\A\s*sub\s+\w+\s*//; 1917: $body =~ s/\s+/ /g; 1918: 1919: # A deprecated alias warns first, then forwards; the warning does not 1920: # change what the routine returns (Database::Join::selectall_hashref). 1921: return $body =~ /\A\{ (?:my \$self = shift; )?(?:carp\s+(?:'[^']*'|"[^"]*")\s*; )?return \$self->(\w+)\(\s*\\?\@_\s*\); \}\z/ ? $1 : undef; 1922: } 1923: 1924: # -------------------------------------------------- 1925: # _extract_package_name 1926: # 1927: # Purpose: Extract the Perl package name from a 1928: # PPI document, or from the cached value 1929: # stored at construction time. 1930: # 1931: # Entry: $document - a PPI::Document, or undef
Mutants (Total: 1, Killed: 1, Survived: 0)
1932: # to use $self->{_document}. 1933: # 1934: # Exit: Returns the package namespace string, 1935: # or an empty string if no package 1936: # statement is found. 1937: # 1938: # Side effects: Stores the package name in
1939: # $self->{_package_name} if not already 1940: # set. 1941: # 1942: # Notes: A file may declare more than one package (a 1943: # main class plus a small error class). The 1944: # first package is the primary one; routines 1945: # owned by later packages are ignored rather 1946: # than aborting the extraction. 1947: # -------------------------------------------------- 1948: sub _extract_package_name { ●1949 → 1951 → 1954 1949: my ($self, $document) = @_; 1950: 1951: if(!defined($document)) { 1952: $document = $self->{_document}; 1953: } ●1954 → 1955 → 1959 1954: my $pkgs = $document->find('PPI::Statement::Package') || []; 1955: if(@$pkgs == 0) { 1956: my $package_stmt = $document->find_first('PPI::Statement::Package'); 1957: return $package_stmt ? $package_stmt->namespace() : ''; 1958: } ●1959 → 1960 → 1964 1959: $self->{_package_name} //= $pkgs->[0]->namespace();Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_1938_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes1960: if(@$pkgs > 1) { 1961: $self->{_multiple_packages} = 1; 1962: $self->_log(" Multiple packages; analyzing " . $pkgs->[0]->namespace() . " only"); 1963: } 1964: return $pkgs->[0]->namespace(); 1965: } 1966: 1967: # True when a node belongs to the primary (first) package of the document. 1968: # PPI nodes carry a location, so each routine belongs to the last package 1969: # declaration at or before its line. A single-package file trivially passes. 1970: sub _in_primary_package { ●1971 → 1979 → 1986 1971: my ($self, $node, $pkgs) = @_; 1972: 1973: return 1 unless($pkgs && @$pkgs > 1); 1974: 1975: my $loc = eval { $node->location }; 1976: return 1 unless(ref($loc) eq 'ARRAY'); 1977: 1978: my $owner = $pkgs->[0];Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_1959_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes1979: for my $pkg (@$pkgs) { 1980: my $pkg_loc = eval { $pkg->location }; 1981: next unless(ref($pkg_loc) eq 'ARRAY'); 1982: last if($pkg_loc->[0] > $loc->[0]); 1983: $owner = $pkg; 1984: }Mutants (Total: 3, Killed: 0, Survived: 3)
- NUM_BOUNDARY_1978_42_>: Numeric boundary flip < to >
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_1978_42_<=: Numeric boundary flip < to <=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_1978_42_>=: Numeric boundary flip < to >=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );Mutants (Total: 1, Killed: 1, Survived: 0)
1985: 1986: my $primary = $self->{_package_name} // $pkgs->[0]->namespace(); 1987: return $owner->namespace() eq $primary; 1988: } 1989: 1990: # -------------------------------------------------- 1991: # _find_methods 1992: # 1993: # Purpose: Locate all subroutine and method 1994: # declarations in a PPI document, 1995: # including Moose-style method modifiers
1996: # and Perl 5.38 class/method syntax. 1997: # 1998: # Entry: $document - a PPI::Document. 1999: # 2000: # Exit: Returns an arrayref of method hashrefs, 2001: # each containing: name, node, body, pod, 2002: # type, and optionally modifier, class, 2003: # and fields keys. 2004: # Private methods (names beginning with 2005: # _) are excluded unless include_private 2006: # was set in new(), except for _new, 2007: # _init, and _build which are always 2008: # included. 2009: # 2010: # Side effects: Logs progress and warnings to stdout 2011: # when verbose is set. 2012: # 2013: # Notes: Duplicate method names are silentlyMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_1995_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
2014: # deduplicated â the second occurrence 2015: # is dropped with a verbose warning. 2016: # Class/method detection is regex-based 2017: # and may misbehave on complex code. 2018: # -------------------------------------------------- 2019: sub _find_methods { ●2020 → 2033 → 2062 2020: my ($self, $document) = @_; 2021: 2022: my $subs = $document->find('PPI::Statement::Sub') || []; 2023: my $pkgs = $document->find('PPI::Statement::Package') || []; 2024: # Only fetch statements that begin with a Moose modifier keyword â 2025: # fetching ALL PPI::Statement nodes on a large file returns thousands 2026: # of nodes and then discards nearly all of them in the loop below. 2027: my $sub_decls = $document->find(sub { 2028: $_[1]->isa('PPI::Statement') 2029: && $_[1]->content =~ /^\s*(?:before|after|around)\b/ 2030: }) || [];
Mutants (Total: 1, Killed: 1, Survived: 0)
2031: 2032: my @methods; 2033: foreach my $sub (@$subs) { 2034: my $name = $sub->name(); 2035: 2036: next unless defined $name; # Skip anonymous routines 2037: # A file may define helper packages after the main one; their subs 2038: # are not part of the module under test.
2039: next unless $self->_in_primary_package($sub, $pkgs);Mutants (Total: 4, Killed: 0, Survived: 4)
- NUM_BOUNDARY_2038_28_>: Numeric boundary flip < to >
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_2038_28_<=: Numeric boundary flip < to <=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_2038_28_>=: Numeric boundary flip < to >=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- COND_INV_2038_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes2040: next if $name =~ /^(BEGIN|END|DESTROY|AUTOLOAD|CHECK|INIT|UNITCHECK)$/; 2041: next if $name =~ /::/; # cross-package sub (e.g. sub DB::DB { }) 2042: 2043: # Skip private methods unless explicitly included, or they're special 2044: if ($name =~ /^_/ && $name !~ /^_(new|init|build)/) { 2045: next unless $self->{include_private}; 2046: } 2047: 2048: # Get the POD before this sub 2049: my $pod = $self->_extract_pod_before($sub); 2050: 2051: push @methods, { 2052: name => $name, 2053: node => $sub, 2054: body => $sub->content(), 2055: pod => $pod, 2056: type => 'sub',Mutants (Total: 3, Killed: 0, Survived: 3)
- NUM_BOUNDARY_2039_28_>: Numeric boundary flip < to >
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_2039_28_<=: Numeric boundary flip < to <=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_2039_28_>=: Numeric boundary flip < to >=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );2057: }; 2058: } 2059: 2060: # Look for class { method } syntax (Perl 5.38+). The regex scans the 2061: # whole document, so it is only safe when there is a single package. ●2062 → 2063 → 2075 2062: my $content = $document->content(); 2063: if (@$pkgs <= 1 && $content =~ /\bclass\b/) { 2064: $self->_log(' Detecting class/method syntax...'); 2065: # Strip POD blocks and line comments before the regex scan so that 2066: # patterns like class Name { inside documentation examples or 2067: # the comment # find "class Name {" blocks don't produce 2068: # spurious method names (e.g. the keyword 'if'). 2069: (my $code_only = $content) =~ s/^=\w[^\n]*.*?^=cut[^\n]*\n//gms; 2070: $code_only =~ s/\s*#[^\n]*//g; 2071: $self->_extract_class_methods($code_only, \@methods); 2072: } 2073: 2074: # Process method modifiers (Moose) ●2075 → 2075 → 2105 2075: foreach my $decl (@$sub_decls) { 2076: next unless $self->_in_primary_package($decl, $pkgs); 2077: my $content = $decl->content; 2078: if ($content =~ /^\s*(before|after|around)\s+['"]?(\w+)['"]?\b/) { 2079: my ($modifier, $method_name) = ($1, $2); 2080: my $full_name = "${modifier}_$method_name"; 2081: 2082: # Look for the actual sub definition that follows 2083: my $next_sib = $decl->next_sibling; 2084: while ($next_sib && !$next_sib->isa('PPI::Statement::Sub')) { 2085: $next_sib = $next_sib->next_sibling; 2086: } 2087: 2088: if ($next_sib && $next_sib->isa('PPI::Statement::Sub')) { 2089: my $pod = $self->_extract_pod_before($decl); # POD might be before modifier 2090: push @methods, { 2091: name => $full_name, 2092: node => $next_sib, 2093: body => $next_sib->content, 2094: pod => $pod, 2095: type => 'modifier', 2096: original_method => $method_name, 2097: modifier => $modifier, 2098: }; 2099: $self->_log(" Found method modifier: $full_name"); 2100: }Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_2056_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 2, Killed: 2, Survived: 0)
2101: } 2102: } 2103: 2104: # Prevent silent duplicate method overwrites 2105: my %seen; 2106: @methods = grep { 2107: my $n = $_->{name}; 2108: if ($seen{$n}++) { 2109: $self->_log(" WARNING: duplicate method '$n' ignored"); 2110: 0; 2111: } else { 2112: 1; 2113: } 2114: } @methods; 2115: 2116: return \@methods; 2117: } 2118: 2119: # -------------------------------------------------- 2120: # _extract_class_methods 2121: # 2122: # Purpose: Extract method declarations from 2123: # Perl 5.38 class { method {} } syntax 2124: # by regex-based scanning of the class 2125: # body content.
Mutants (Total: 2, Killed: 2, Survived: 0)
2126: # 2127: # Entry: $content - full document source string. 2128: # $methods - arrayref to push discovered 2129: # method hashrefs onto 2130: # (modified in place).
Mutants (Total: 2, Killed: 2, Survived: 0)
2131: # 2132: # Exit: Returns nothing. Appends to $methods. 2133: #
Mutants (Total: 2, Killed: 2, Survived: 0)
2134: # Side effects: Logs class and method discoveries 2135: # to stdout when verbose is set. 2136: # 2137: # Notes: This is experimental â regex-based 2138: # class body parsing may misbehave on 2139: # complex or nested class declarations. 2140: # Class body boundaries are tracked by 2141: # simple brace counting, which will 2142: # fail on unbalanced braces in strings 2143: # or heredocs. 2144: # -------------------------------------------------- 2145: sub _extract_class_methods { ●2146 → 2152 → 0 2146: my ($self, $content, $methods) = @_; 2147: 2148: # EXPERIMENTAL: regex-based parsing, may misbehave on complex code 2149: 2150: # Simple pattern: find "class Name {" blocks 2151: # This won't handle all edge cases but will work for simple classes 2152: while ($content =~ /class\s+(\w+)\s*\{/g) { 2153: my $class_name = $1; 2154: my $start_pos = pos($content); 2155: 2156: # Find the matching closing brace. $start_pos is just after the 2157: # opening '{' consumed by the regex above, so back up one 2158: # character to hand the brace itself to extract_bracketed. 2159: require Text::Balanced; 2160: my $extracted = Text::Balanced::extract_bracketed(substr($content, $start_pos - 1), '{}'); 2161: 2162: next unless defined $extracted; # unbalanced braces, skip class 2163: 2164: my $class_body = substr($extracted, 1, length($extracted) - 2); 2165: 2166: $self->_log(" Found class $class_name"); 2167: 2168: # Extract field declarations from class 2169: my $fields = $self->_extract_field_declarations($class_body); 2170: 2171: # Find methods in the class body 2172: while ($class_body =~ /method\s+(\w+)\s*(\([^)]*\))?\s*\{/g) { 2173: my ($method_name, $sig_with_parens) = ($1, $2 || '()'); 2174: 2175: # Skip private unless configured 2176: if ($method_name =~ /^_/ && $method_name !~ /^_(new|init|build)/) { 2177: next unless $self->{include_private}; 2178: } 2179: 2180: # Reconstruct as sub for analysis 2181: my $signature = $sig_with_parens; 2182: $signature =~ s/^\(//; 2183: $signature =~ s/\)$//; 2184: 2185: # Build a fake sub declaration 2186: my $fake_sub = "sub $method_name($signature) { }"; 2187: 2188: push @$methods, { 2189: name => $method_name, 2190: node => undef, 2191: body => $fake_sub, # Just the signature for now 2192: is_stub => 1, 2193: pod => '', 2194: type => 'method', 2195: class => $class_name, 2196: fields => $fields, 2197: }; 2198: 2199: $self->_log(" Found method $method_name in class $class_name"); 2200: } 2201: }
2202: } 2203: 2204: # -------------------------------------------------- 2205: # _extract_pod_before 2206: # 2207: # Purpose: Collect the POD documentation that 2208: # appears immediately before a 2209: # subroutine in the PPI document, byMutants (Total: 4, Killed: 1, Survived: 3)
- NUM_BOUNDARY_2201_25_<: Numeric boundary flip > to <
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_2201_25_>=: Numeric boundary flip > to >=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_2201_25_<=: Numeric boundary flip > to <=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );Mutants (Total: 1, Killed: 1, Survived: 0)
2210: # walking backwards through siblings. 2211: # 2212: # Entry: $sub - a PPI node (typically a 2213: # PPI::Statement::Sub). 2214: # 2215: # Exit: Returns a string containing all POD 2216: # content found before the sub, with 2217: # inline parameter comments converted
2218: # to =item format. Returns an emptyMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_2217_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes2219: # string if no POD is found. 2220: # 2221: # Side effects: None. 2222: # 2223: # Notes: Stops walking backwards on the first 2224: # non-POD, non-whitespace, non-separator, 2225: # non-include node encountered. 2226: # Walking is capped at $POD_WALK_LIMIT 2227: # steps to prevent runaway processing 2228: # on pathological documents. 2229: # -------------------------------------------------- 2230: sub _extract_pod_before { ●2231 → 2242 → 2281 2231: my ($self, $sub) = @_; 2232: 2233: my $name = eval { $sub->can('name') ? $sub->name : undef }; 2234: my $pod = ''; 2235: my $current = $sub->previous_sibling(); 2236: my $skipped_declaration = 0; 2237: my $steps = 0; 2238:Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_2218_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes2239: # Walk backwards collecting POD.Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_2238_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes2240: # Stop after the first pod token so that a =cut before =head1 METHODS 2241: # prevents class-level POD from being mistaken for method-specific POD. 2242: while($current && $steps++ < $POD_WALK_LIMIT) { 2243: if ($current->isa('PPI::Token::Pod')) { 2244: my $content = $current->content(); 2245: # A file-scoped declaration may sit between a routine's POD and 2246: # its sub (Mutation::Feedback declares a regex constant there). 2247: # Accept such a POD block only when it documents this routine. 2248: if(!$skipped_declaration 2249: || (defined($name) && $content =~ /^=head[1-6]\s+\Q$name\E\b/m)) { 2250: $pod = $content . $pod; 2251: } 2252: last; # Only take the immediately adjacent pod block 2253: } elsif ($current->isa('PPI::Token::Comment')) { 2254: # Include comments that might contain parameter info 2255: my $comment = $current->content(); 2256: if ($comment =~ /#\s*(?:param|arg|input)\s+\$(\w+)\s*:\s*(.+)/i) { 2257: $pod .= "=item \$$1\n$2\n\n"; 2258: } 2259: } elsif ($current->isa('PPI::Token::Whitespace') || 2260: $current->isa('PPI::Token::Separator')) { 2261: # Skip whitespace and separators 2262: } elsif ($current->isa('PPI::Statement::Include')) { 2263: # allow 'use strict', 'use warnings' between POD and sub 2264: } elsif ($current->isa('PPI::Statement::Variable') 2265: && $current->content() =~ /\A\s*(?:my|our)\b/ 2266: && $current->content() !~ /\bsub\b/) {Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_2239_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
2267: # A simple file-scoped declaration: the POD is still this
Mutants (Total: 1, Killed: 1, Survived: 0)
2268: # routine's documentation. 2269: $skipped_declaration = 1; 2270: } else { 2271: # Hit non-POD, non-whitespace - stop
2272: last; 2273: } 2274: $current = $current->previous_sibling(); 2275: } 2276: 2277: # A POD token can span several routines (and the module-level sectionsMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_2271_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
2278: # before the first one). Keep the section that documents this routine, 2279: # stopping at the next heading that belongs to another method. Headings 2280: # such as SYNOPSIS or NOTES belong to the routine and must be kept. ●2281 → 2281 → 2318 2281: if($pod && defined($name) && $pod =~ /^=head([1-6])\s+\Q$name\E\b/m) { 2282: my ($level, $start) = ($1, $-[0]); 2283: my $section = substr($pod, $start); 2284: 2285: my $method_names = {}; 2286: if(my $doc = eval { $sub->document }) { 2287: $method_names = $self->{_pod_method_names}{refaddr($doc)} ||= do { 2288: my %names; 2289: my $subs = $doc->find('PPI::Statement::Sub'); 2290: for my $method (@{ $subs || [] }) { 2291: my $method_name = eval { $method->name }; 2292: $names{$method_name} = 1 if defined($method_name); 2293: } 2294: \%names; 2295: }; 2296: } 2297: 2298: my $cut; 2299: while($section =~ /^=head([1-6])\s+(.+?)\s*$/mg) { 2300: my ($heading_level, $title) = ($1, $2); 2301: next if($-[0] == 0); # the routine's own heading 2302: if($heading_level < $level 2303: || ($heading_level == $level && $method_names->{$title})) { 2304: $cut = $-[0]; 2305: last; 2306: }
2307: }Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_2306_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
2308: if(defined($cut)) { 2309: $section = substr($section, 0, $cut); 2310: $section =~ s/\s+\z//; 2311: } 2312: $pod = $section; 2313: } 2314: 2315: # A helper documented in its own later block rather than above its sub 2316: # (`=head2 Date normalisation (standalone helper)` followed by 2317: # `date_normalise($value, $pattern) -> ...`) is documented just the same. ●2318 → 2318 → 2323 2318: if(defined($name) && $pod !~ /^=head[1-6]\s+\Q$name\E\b/m) { 2319: my $named = $self->_pod_section_naming_routine($sub, $name); 2320: $pod = $named if defined($named) && length($named); 2321: } 2322: 2323: return $pod; 2324: } 2325: 2326: # -------------------------------------------------- 2327: # _pod_section_naming_routine 2328: # 2329: # Purpose: Find a POD section that documents 2330: # a routine in its own text rather than 2331: # in its heading.
Mutants (Total: 1, Killed: 1, Survived: 0)
2332: # 2333: # Entry: $sub - the PPI statement for the routine.
2334: # $name - the routine's name. 2335: #Mutants (Total: 4, Killed: 1, Survived: 3)
- NUM_BOUNDARY_2333_26_<: Numeric boundary flip > to <
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_2333_26_>=: Numeric boundary flip > to >=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_2333_26_<=: Numeric boundary flip > to <=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );Mutants (Total: 1, Killed: 1, Survived: 0)
2336: # Exit: Returns the section text, from its heading 2337: # to the next heading at the same or a higher 2338: # level, or undef when no section names the 2339: # routine. 2340: # 2341: # Side effects: None. 2342: # 2343: # Notes: A section counts when a line starts with 2344: # the routine name and its argument list, which 2345: # is how these helper blocks show the call. 2346: # -------------------------------------------------- 2347: sub _pod_section_naming_routine { ●2348 → 2358 → 2362 2348: my ($self, $sub, $name) = @_; 2349: 2350: my $doc = eval { $sub->document } or return undef; 2351: my $tokens = $doc->find('PPI::Token::Pod') or return undef; 2352: 2353: my $text = join('', map { $_->content . "\n" } @$tokens); 2354:
Mutants (Total: 1, Killed: 1, Survived: 0)
2355: # Every heading with its offset, so a section runs to the next heading 2356: # at the same or a higher level. 2357: my @heads; 2358: while($text =~ /^=head([1-6])\s+(.+?)\s*$/mg) {
Mutants (Total: 2, Killed: 2, Survived: 0)
2359: push @heads, [ $-[0], $1 + 0, $2 ]; 2360: } 2361: ●2362 → 2362 → 2387 2362: for my $i (0 .. $#heads) { 2363: my ($start, $level) = @{ $heads[$i] }; 2364: my $end = length($text); 2365: for my $j ($i + 1 .. $#heads) { 2366: next unless $heads[$j][1] <= $level; 2367: $end = $heads[$j][0]; 2368: last; 2369: } 2370: my $section = substr($text, $start, $end - $start); 2371: 2372: # The routine's call stands at the top of its section, before any 2373: # subsection; a passing mention deeper in another section's examples 2374: # does not make that section its documentation. 2375: # A section headed with the routine's own name documents it (modules 2376: # that keep every method's POD in one block after the subs have no 2377: # room for a synopsis line); otherwise the call line must stand at 2378: # the top of the section. 2379: my ($synopsis) = $section =~ /\A(.*?)(?=^=head[3-6]\b|\z)/ms; 2380: next unless (($heads[$i][2] // '') =~ /\A\Q$name\E\b/) 2381: || (defined($synopsis) && $synopsis =~ /^\s*\Q$name\E\s*\(/m); 2382: 2383: $section =~ s/\s+\z//; 2384: return $section; 2385: } 2386: 2387: return undef; 2388: } 2389: 2390: # -------------------------------------------------- 2391: # _pod_documents_file_write 2392: # 2393: # Purpose: Decide whether a routine's POD documents 2394: # creating or writing a file as part of 2395: # its contract, so the generated schema can 2396: # turn off the harness's leftover-file 2397: # check for it. 2398: # Entry: $pod - the routine's raw POD text, or 2399: # undef when it has none. 2400: # Exit: Returns 1 if the SIDE EFFECTS section
Mutants (Total: 1, Killed: 1, Survived: 0)
2401: # says a file is created, written,
Mutants (Total: 1, Killed: 1, Survived: 0)
2402: # overwritten or updated; 0 otherwise. 2403: # Side effects: None. 2404: # Notes: Only the SIDE EFFECTS section is examined.
Mutants (Total: 1, Killed: 1, Survived: 0)
2405: # A file mentioned while describing an 2406: # argument or an example is not a 2407: # documented side effect.
2408: # -------------------------------------------------- 2409: sub _pod_documents_file_write { 2410: my ($self, $pod) = @_; 2411: 2412: return 0 unless defined($pod) && length($pod); 2413: 2414: my ($section) = $pod =~ /^=head[1-4]\s+SIDE\s+EFFECTS\b(.*?)(?=^=head[1-4]\b|\z)/mis; 2415: return 0 unless defined($section) && length($section);Mutants (Total: 1, Killed: 0, Survived: 1)
- NUM_BOUNDARY_2407_45_==: Numeric boundary flip != to ==
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );Mutants (Total: 1, Killed: 1, Survived: 0)
2416:
Mutants (Total: 1, Killed: 1, Survived: 0)
2417: return 1 if $section =~ /\b(?:creates?|writes?|rewrites?|overwrites?|updates?)\b[^.\n]*\bfiles?\b/i; 2418: return 1 if $section =~ /\bfiles?\b[^.\n]*\b(?:is|are)\s+(?:created|written|rewritten|overwritten|updated)\b/i; 2419: 2420: return 0;
Mutants (Total: 1, Killed: 1, Survived: 0)
2421: } 2422: 2423: # -------------------------------------------------- 2424: # _analyze_method 2425: # 2426: # Purpose: Perform full multi-source analysis of 2427: # a single method and produce a complete 2428: # schema hashref, combining POD analysis, 2429: # code pattern detection, signature 2430: # analysis, validator schema extraction, 2431: # confidence scoring, relationship 2432: # detection, and modern Perl feature 2433: # extraction. 2434: #
Mutants (Total: 1, Killed: 1, Survived: 0)
2435: # Entry: $method - a method hashref as produced 2436: # by _find_methods, containing
Mutants (Total: 1, Killed: 1, Survived: 0)
2437: # at minimum: name, body, pod. 2438: #
Mutants (Total: 1, Killed: 1, Survived: 0)
2439: # Exit: Returns a schema hashref containing: 2440: # function, input, output, _confidence, 2441: # _analysis, _notes, and optionally: 2442: # new, accessor, relationships, 2443: # _yamltest_hints, _attributes, 2444: # _modern_features, _fields, _model, 2445: # _low_confidence. 2446: # 2447: # Side effects: Logs progress to stdout when verbose 2448: # is set. May carp or croak if 2449: # strict_pod is enabled and POD/code 2450: # disagreements are found. 2451: # 2452: # Notes: This is the central analysis entry 2453: # point â it orchestrates all other 2454: # analysis helpers and merges their 2455: # results. The non-invasive reasoning 2456: # layer (Model::Method, Analyzer::*) 2457: # runs after the main schema is built 2458: # and attaches metadata only. 2459: # -------------------------------------------------- 2460: sub _analyze_method { ●2461 → 2471 → 2475 2461: my ($self, $method) = @_; 2462: my $code = $method->{body}; 2463: my $pod = $method->{pod}; 2464: 2465: # Extract modern features 2466: my $attributes = $self->_extract_subroutine_attributes($code); 2467: my $postfix_derefs = $self->_analyze_postfix_dereferencing($code); 2468: my $fields = $self->_extract_field_declarations($code); 2469: 2470: # If this method came from a class, use those field declarations 2471: if ($method->{fields} && keys %{$method->{fields}}) { 2472: $fields = $method->{fields}; 2473: } 2474: ●2475 → 2503 → 2533 2475: my $schema = { 2476: function => $method->{name}, 2477: _confidence => { 2478: 'input' => {}, 2479: 'output' => {} 2480: }, 2481: input => {}, 2482: output => {}, 2483: setup => undef, 2484: transforms => {}, 2485: }; 2486: 2487: # Analyze different sources 2488: my $pod_params = $self->_analyze_pod($pod, $method->{name}); 2489: my $code_params = $self->_analyze_code($code, $method); 2490: 2491: # A POD INPUT section that documents $class describes a class method, so 2492: # the harness has to pass the class as the invocant rather than as an 2493: # ordinary first argument. 2494: $schema->{invocant} = 'class' if $self->_pod_documents_class_invocant($pod); 2495: 2496: # Neither analysis may hand a reference string to the schema as a parameter. 2497: $self->_sanitize_parameter_names($pod_params, 'POD analysis'); 2498: $self->_sanitize_parameter_names($code_params, 'code analysis'); 2499: 2500: # Validate POD/code agreement if strict mode is enabled. 2501: # Skip when there is no POD at all â strict_pod checks accuracy of 2502: # existing documentation, not whether every method is documented. 2503: if ($self->{strict_pod} && $pod) { 2504: my @validation_errors = $self->_validate_pod_code_agreement( 2505: $pod_params, 2506: $code_params, 2507: $method->{name}, 2508: { 2509: ignore_self => 1, 2510: allow_renames => 1, 2511: } 2512: ); 2513:
Mutants (Total: 2, Killed: 2, Survived: 0)
2514: if (@validation_errors) { 2515: my $error_msg = "POD/Code disagreement in method '$method->{name}':\n " . 2516: join("\n ", @validation_errors); 2517: 2518: # Add to schema for reference even if we croak 2519: $schema->{_pod_validation_errors} = \@validation_errors; 2520: 2521: # Either croak immediately or log based on configuration 2522: if($self->{strict_pod} == $STRICT_POD_FATAL) { 2523: croak("[POD STRICT] $error_msg"); 2524: } else { # 1 = warnings 2525: carp("[POD STRICT] $error_msg"); 2526: # Continue with analysis, but mark as problematic 2527: $schema->{_pod_disagreement} = 1; 2528: } 2529: } 2530: $schema->{_strict_pod_level} = $self->{strict_pod}; 2531: } 2532: ●2533 → 2535 → 2594 2533: my $validator_params = $self->_extract_validator_schema($code); 2534: 2535: if ($validator_params) { 2536: $schema->{input} = $validator_params->{input}; 2537: $schema->{input_style} = 'hash'; 2538: $schema->{_confidence}{input} = { 'factors' => [ 'Determined from validator' ], 'level' => 'high' }; 2539: $schema->{_analysis}{confidence_factors}{input} = [ 2540: 'Input schema extracted from validator' 2541: ]; 2542: # =head4 Input spec overrides take highest priority â apply them on top of 2543: # the validator schema so authors can tune test constraints (optional, 2544: # memberof, matches) without altering the runtime validation call. 2545: for my $name (keys %$pod_params) { 2546: next unless ($pod_params->{$name}{_source} // '') eq SOURCE_INPUT_SPEC; 2547: my $pod_p = $pod_params->{$name};
Mutants (Total: 1, Killed: 1, Survived: 0)
2548: $schema->{input}{$name} //= {}; 2549: $schema->{input}{$name}{optional} = $pod_p->{optional} if defined $pod_p->{optional}; 2550: $schema->{input}{$name}{memberof} = $pod_p->{memberof} if defined $pod_p->{memberof}; 2551: $schema->{input}{$name}{matches} = $pod_p->{matches} if defined $pod_p->{matches}; 2552: $schema->{input}{$name}{type} = $pod_p->{type} if defined $pod_p->{type}; 2553: $schema->{input}{$name}{min} = $pod_p->{min} if defined $pod_p->{min}; 2554: $schema->{input}{$name}{max} = $pod_p->{max} if defined $pod_p->{max}; 2555: # A documented element or value shape is structural, not a
2556: # constraint the validator states.Mutants (Total: 3, Killed: 0, Survived: 3)
- NUM_BOUNDARY_2555_23_>: Numeric boundary flip < to >
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_2555_23_<=: Numeric boundary flip < to <=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_2555_23_>=: Numeric boundary flip < to >=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );2557: $schema->{input}{$name}{schema} = $pod_p->{schema} if ref($pod_p->{schema}) eq 'HASH'; 2558: 2559: # These constraints are documented, even though the field's 2560: # _source stays the type-checking marker (SOURCE_VALIDATOR). 2561: for my $key (qw(min max memberof matches nomatch notmemberof)) { 2562: next unless defined $pod_p->{$key}; 2563: $schema->{input}{$name}{_constraint_source}{$key} = SOURCE_INPUT_SPEC; 2564: } 2565: } 2566: 2567: # Not every validator extractor fills in per-parameter provenance, so 2568: # stamp the one source value here too. The harness treats a 2569: # 'validator' source as proof that the routine checks types; POD and 2570: # code-derived sources describe intent only. 2571: $schema->{input}{$_}{_source} //= SOURCE_VALIDATOR for keys %{$schema->{input}}; 2572: } else { 2573: # Merge field declarations into code_params before merging analyses 2574: if (keys %$fields) { 2575: $self->_merge_field_declarations($code_params, $fields); 2576: } 2577: 2578: # A lone documented input parameter may be the whole argument list 2579: # under another name; the helper decides from the body and folds the 2580: # code's facts about that argument onto the documented name. 2581: $self->_positional_pod_input($pod_params, $code_params, $code); 2582:Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_2556_5: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes2583: # Merge analyses 2584: $schema->{input} = $self->_merge_parameter_analyses( 2585: $pod_params, 2586: $code_params, 2587: ); 2588: } 2589: 2590: # ---------------------------------------- 2591: # Legacy Output Analysis (unchanged) 2592: # ---------------------------------------- 2593: ●2594 → 2607 → 2613 2594: $schema->{output} = $self->_analyze_output( 2595: $method->{pod}, 2596: $method->{body}, 2597: $method->{name} 2598: ); 2599: 2600: 2601: # Detect accessor methods 2602: $self->_detect_accessor_methods($method, $schema); 2603: 2604: # Detect if this is an instance method that needs object instantiation 2605: # Constructors never require object instantiation 2606: my $needs_object = $self->_needs_object_instantiation($method->{name}, $method->{body}, $method); 2607: if($method->{name} ne 'new' && $needs_object) { 2608: $schema->{new} = $needs_object; 2609: $self->_log(" NEW: Method requires object instantiation: $needs_object"); 2610: } 2611: 2612: # Calculate confidences ●2613 → 2614 → 2617 2613: my $input_confidence = $schema->{_confidence}{'input'}; 2614: if(!ref($input_confidence)) { 2615: $input_confidence = $schema->{_confidence}{'input'} = $self->_calculate_input_confidence($schema->{input}); 2616: } ●2617 → 2630 → 2635 2617: my $output_confidence = $schema->{_confidence}{'output'} = $self->_calculate_output_confidence($schema->{output}); 2618: 2619: # Add metadata 2620: $schema->{_notes} = $self->_generate_notes($schema->{input}); 2621: 2622: # Add analytics 2623: $schema->{_analysis} ||= {}; 2624: $schema->{_analysis}{input_confidence} = $input_confidence->{level}; 2625: $schema->{_analysis}{output_confidence} = $output_confidence->{level}; 2626: $schema->{_analysis}{confidence_factors} ||= {}; 2627: $schema->{_analysis}{confidence_factors}{input} ||= $input_confidence->{factors}; 2628: $schema->{_analysis}{confidence_factors}{output} ||= $output_confidence->{factors}; 2629: 2630: foreach my $mode('input', 'output') { 2631: $self->_set_defaults($schema, $mode); 2632: } 2633: 2634: # Optionally store detailed per-parameter analysis ●2635 → 2635 → 2640 2635: if ($input_confidence->{per_parameter}) {Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_2582_5: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 2, Killed: 2, Survived: 0)
2636: $schema->{_analysis}{per_parameter_scores} = $input_confidence->{per_parameter}; 2637: } 2638:
Mutants (Total: 2, Killed: 2, Survived: 0)
2639: # Calculate overall confidence (for backward compatibility) ●2640 → 2660 → 2666 2640: my $input_level = $input_confidence->{level}; 2641: my $output_level = $output_confidence->{level}; 2642: 2643: my %level_rank = ( 2644: none => 0, 2645: very_low => 1, 2646: low => 2, 2647: medium => 3, 2648: high => 4 2649: ); 2650: 2651: # Overall is the lower of input and output 2652: $input_level //= 'none'; 2653: $output_level //= 'none'; 2654: my $overall = $level_rank{$input_level} < $level_rank{$output_level} ? $input_level : $output_level; 2655: 2656: $schema->{_analysis}{overall_confidence} = $overall; 2657: 2658: # Analyze parameter relationships 2659: my $relationships = $self->_analyze_relationships($method); 2660: if ($relationships && @{$relationships}) { 2661: $schema->{relationships} = $relationships; 2662: $self->_log(" Found " . scalar(@$relationships) . " parameter relationships"); 2663: } 2664: 2665: # Store modern feature info in schema ●2666 → 2671 → 2675 2666: $schema->{_attributes} = $attributes if keys %$attributes; 2667: $schema->{_modern_features}{postfix_dereferencing} = $postfix_derefs if keys %$postfix_derefs; 2668: $schema->{_fields} = $fields if keys %$fields; 2669: 2670: # Store class info if this is a class method 2671: if ($method->{class}) { 2672: $schema->{_class} = $method->{class}; 2673: } 2674:
Mutants (Total: 1, Killed: 1, Survived: 0)
●2675 → 2678 → 2689 2675: my $hints = $self->_extract_test_hints($method, $schema); 2676: $self->_extract_pod_examples($pod, $hints); 2677:
Mutants (Total: 1, Killed: 1, Survived: 0)
2678: for my $k (qw(boundary_values invalid_inputs valid_inputs equivalence_classes)) { 2679: my %seen; 2680: $hints->{$k} = [ 2681: grep { !$seen{ defined $_ ? $_ : '__undef__' }++ } 2682: @{ $hints->{$k} } 2683: ]; 2684: }
Mutants (Total: 1, Killed: 1, Survived: 0)
2685: 2686: # -------------------------------------------------- 2687: # YAML test hints: numeric boundaries 2688: # -------------------------------------------------- ●2689 → 2689 → 2706 2689: if ($self->_method_has_numeric_intent($schema)) { 2690: $schema->{_yamltest_hints} ||= {}; 2691: 2692: # Do not override existing hints 2693: $schema->{_yamltest_hints}{boundary_values} ||= []; 2694: 2695: my %seen = map { (defined $_ ? $_ : '__undef__') => 1 } 2696: @{ $schema->{_yamltest_hints}{boundary_values} }; 2697: 2698: foreach my $v (@{ $self->_numeric_boundary_values }) { 2699: my $key = defined $v ? $v : '__undef__'; 2700: push @{ $schema->{_yamltest_hints}{boundary_values} }, $v unless $seen{$key}++;
2701: } 2702: 2703: $self->_log(' HINTS: Added numeric boundary values'); 2704: } 2705: ●2706 → 2706 → 2714 2706: if (keys %$hints) { 2707: $schema->{_yamltest_hints} ||= {}; 2708: foreach my $k (keys %$hints) { 2709: $schema->{_yamltest_hints}{$k} = $hints->{$k} 2710: unless exists $schema->{_yamltest_hints}{$k}; 2711: } 2712: } 2713: ●2714 → 2714 → 2723 2714: if(($level_rank{$overall} < $level_rank{$LEVEL_MEDIUM}) && 2715: ($level_rank{$overall} < ($self->{confidence_threshold} * 4))) { 2716: $schema->{_low_confidence} = 1 2717: } 2718: 2719: # ---------------------------------------- 2720: # Non-invasive reasoning layer 2721: # ---------------------------------------- 2722: ●2723 → 2732 → 2736 2723: my $method_model = App::Test::Generator::Model::Method->new( 2724: name => $method->{name}, 2725: source => $method->{body}, 2726: ); 2727: 2728: my $return_analyzer = App::Test::Generator::Analyzer::Return->new(); 2729: $return_analyzer->analyze($method_model); 2730: 2731: # Let model learn from finalized schema 2732: if ($schema->{output}) { 2733: $method_model->absorb_legacy_output($schema->{output}); 2734: } 2735: ●2736 → 2771 → 2779 2736: $method_model->resolve_return_type(); 2737: $method_model->resolve_classification(); 2738: $method_model->resolve_confidence();Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_2700_3: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes🧪 Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_2700_3: Replace return expression with undef
LOW: Mutation survived, but impact may be minor🧪 Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );Mutants (Total: 1, Killed: 1, Survived: 0)
2739: 2740: # Attach only metadata 2741: $schema->{_model} = { 2742: classification => $method_model->classification,
Mutants (Total: 1, Killed: 1, Survived: 0)
2743: confidence => $method_model->confidence, 2744: }; 2745: 2746: # ---------------------------------------- 2747: # Return Meta Analysis (Non-invasive) 2748: # ---------------------------------------- 2749:
Mutants (Total: 1, Killed: 1, Survived: 0)
2750: my $meta = App::Test::Generator::Analyzer::ReturnMeta->new(); 2751: my $analysis = $meta->analyze($schema); 2752:
Mutants (Total: 1, Killed: 1, Survived: 0)
2753: $schema->{_analysis}{stability_score} = $analysis->{stability_score};
Mutants (Total: 1, Killed: 1, Survived: 0)
2754: $schema->{_analysis}{consistency_score} = $analysis->{consistency_score}; 2755: $schema->{_analysis}{risk_flags} = $analysis->{risk_flags}; 2756: 2757: # ---------------------------------------- 2758: # Side Effect Analysis (Non-invasive) 2759: # ---------------------------------------- 2760: 2761: my $se = App::Test::Generator::Analyzer::SideEffect->new(); 2762: 2763: my $effects = $se->analyze($method); 2764: 2765: $schema->{_analysis}{side_effects} = $effects; 2766: 2767: # A routine whose documented side effects include creating or writing a 2768: # file is doing its job when it leaves that file behind, so the harness's 2769: # leftover-file check must not report it. Record the contract here for 2770: # _write_schema to emit as check_files: 0. 2771: if($self->_pod_documents_file_write($pod)) { 2772: $schema->{_analysis}{side_effects}{writes_file} = 1; 2773: } 2774: 2775: # ---------------------------------------- 2776: # Complexity Analysis (Non-invasive) 2777: # ----------------------------------------
2778: 2779: my $cx = App::Test::Generator::Analyzer::Complexity->new(); 2780: my $complexity = $cx->analyze($method); 2781: 2782: $schema->{_analysis}{complexity} = $complexity; 2783: 2784: return $schema; 2785: } 2786: 2787: # -------------------------------------------------- 2788: # _method_has_numeric_intent 2789: # 2790: # Purpose: Determine whether a method schema 2791: # has numeric intent â either a numeric 2792: # output type or at least one required 2793: # numeric input parameter â to decide 2794: # whether to add standard numeric 2795: # boundary hint values. 2796: # 2797: # Entry: $schema - schema hashref as built by 2798: # _analyze_method. 2799: # 2800: # Exit: Returns 1 if numeric intent is 2801: # detected, 0 otherwise. 2802: # 2803: # Side effects: None. 2804: # -------------------------------------------------- 2805: sub _method_has_numeric_intent { ●2806 → 2812 → 2817 2806: my ($self, $schema) = @_; 2807: 2808: # Numeric output 2809: return 1 if ($schema->{output} && $schema->{output}{type} && $schema->{output}{type} =~ /^(number|integer)$/); 2810: 2811: # Numeric inputs 2812: foreach my $p (values %{ $schema->{input} || {} }) { 2813: next if $p->{optional}; 2814: return 1 if ($p->{type} && $p->{type} =~ /^(number|integer)$/); 2815: } 2816: 2817: return 0; 2818: }Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_2777_3: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes🧪 Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_2777_3: Replace return expression with undef
LOW: Mutation survived, but impact may be minor🧪 Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );Mutants (Total: 1, Killed: 1, Survived: 0)
2819: 2820: # -------------------------------------------------- 2821: # _numeric_boundary_values 2822: # 2823: # Purpose: Return the standard set of numeric 2824: # boundary values used as test hints 2825: # for methods with numeric intent. 2826: #
Mutants (Total: 1, Killed: 1, Survived: 0)
2827: # Entry: None. 2828: # 2829: # Exit: Returns an arrayref of boundary 2830: # values: [-1, 0, 1, 2, 100]. 2831: # 2832: # Side effects: None. 2833: # -------------------------------------------------- 2834: sub _numeric_boundary_values { 2835: return [ -1, 0, 1, 2, 100 ]; 2836: } 2837: 2838: # -------------------------------------------------- 2839: # _detect_accessor_methods 2840: # 2841: # Purpose: Detect whether a method is a getter, 2842: # setter, or combined getter/setter 2843: # accessor by analysing assignment and 2844: # return patterns involving $self->{...}. 2845: # 2846: # Entry: $method - method hashref containing 2847: # at minimum 'body' and 2848: # optionally 'pod'. 2849: # $schema - schema hashref (modified 2850: # in place). 2851: # 2852: # Exit: Returns nothing. Modifies $schema in 2853: # place, setting accessor, input, 2854: # input_style, output, and _confidence 2855: # keys as appropriate. 2856: # 2857: # Side effects: Croaks if a getter/setter has more 2858: # than one argument, or if a setter 2859: # returns non-self data. 2860: # Logs detections to stdout when 2861: # verbose is set. 2862: # 2863: # Notes: Four accessor patterns are detected 2864: # in order: (1) combined getter/setter 2865: # with shift, (2) combined getter/setter 2866: # with validated input, (3) getter only, 2867: # (4) setter that returns $self. Methods 2868: # accessing multiple $self fields are 2869: # skipped immediately. 2870: # -------------------------------------------------- 2871: sub _detect_accessor_methods { ●2872 → 2891 → 2894 2872: my ($self, $method, $schema) = @_; 2873: 2874: # A constructor is not an accessor, even when it stores one field: the 2875: # harness may call new() with no arguments and let the defaults apply, 2876: # and its argument types come from the validator, not from the one 2877: # assignment the body happens to make. Geocode::new stores only 2878: # _geocoder on the conditional path, and the accessor reading typed its 2879: # whole parameter list as a single string, so instance methods were 2880: # built with new(geocoder => 'test') and the constructor rightly refused.
Mutants (Total: 1, Killed: 1, Survived: 0)
2881: return if(($method->{name} // '') eq 'new'); 2882: 2883: my $body = $method->{body}; 2884:
Mutants (Total: 1, Killed: 1, Survived: 0)
2885: # Normalize whitespace for regex sanity 2886: my $code = $body; 2887: $code =~ s/\s+/ /g; 2888: 2889: # If a method touches more than one $self->{...}, itâs not an accessor. 2890: my %fields_seen; 2891: while ($code =~ /\$self\s*->\s*\{\s*['"]?([^}'"]+)['"]?\s*\}/g) { 2892: $fields_seen{$1}++;
Mutants (Total: 1, Killed: 1, Survived: 0)
2893: } ●2894 → 2894 → 2909 2894: if (keys(%fields_seen) > 1) { 2895: $self->_log(" Skipping accessor detection: multiple fields accessed");
Mutants (Total: 1, Killed: 1, Survived: 0)
2896: return; 2897: } 2898:
Mutants (Total: 1, Killed: 1, Survived: 0)
2899: # A store guarded by the presence of an argument is the same get/set 2900: # idiom as `if (@_)`, just written against a named lexical: 2901: # 2902: # my $status = shift; 2903: # return $self->{status} = $status if(defined($status)); 2904: # ...
Mutants (Total: 1, Killed: 1, Survived: 0)
2905: # return $self->{status} || 200; 2906: # 2907: # CGI::Info::status is this shape, and it was being typed as a plain 2908: # function because every branch below only looked for `if (@_)`. ●2909 → 2910 → 2927 2909: my $conditional_arg = 0; 2910: while($code =~ /\bmy\s+\$(\w+)\s*=\s*shift\b/g) { 2911: my $arg = $1;
2912: # The invocant is shifted too, but a test on $self says nothingMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_2911_7: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
2913: # about whether an argument was supplied. 2914: next if($arg eq 'self'); 2915: if($code =~ /(?:if|unless)\s*\(?\s*(?:defined\s*\(?\s*)?\$\Q$arg\E\b/) { 2916: $conditional_arg = 1; 2917: last; 2918: } 2919: } 2920: # `if (@_)` stays the strongest signal; a named-argument guard is 2921: # weaker evidence and must not turn a heuristic miss into a croak. 2922: # The guard must test the argument itself: CGI::Info::protocol reads 2923: # if($ENV{'SCRIPT_URI'}) and stores a value it computed, which says 2924: # nothing about how the method is called. Reading any `if($x)` as an 2925: # argument guard typed it as a getset accessor, and the harness then 2926: # set a value the routine never looks at. ●2927 → 2932 → 3176 2927: my $arg_guard = ($code =~ /\bif\s*\(\s*(?:\@_|scalar\s*\(\s*\@_\s*\))/) ? 1 : 0; 2928: 2929: # ------------------------------- 2930: # Getter/Setter combo 2931: # ------------------------------- 2932: if ( 2933: # Require get/set of the same property 2934: $code =~ /\$self\s*->\s*\{\s*['"]?([^}'"]+)['"]?\s*\}\s*=\s*shift\s*;/ && 2935: $code =~ /return\s+\$self\s*->\s*\{\s*['"]?\Q$1\E['"]?\s*\}\s*;/ && 2936: $code =~ /if\s*\(\s*\@_/
2937: ) { 2938: my $property = $1; 2939: 2940: if(!defined($property)) { 2941: if($code =~ /\$self\s*->\s*\{\s*['"]?([^}'"]+)['"]?\s*\}\s*=\s*shift\s*;/) { 2942: $property = $1; 2943: } 2944: } 2945: 2946: $schema->{accessor} = { 2947: type => 'getset', 2948: property => $property, 2949: }; 2950: 2951: $self->_log(" Detected getter/setter accessor for property: $property"); 2952: 2953: $schema->{input} ||= { value => { type => 'string', optional => 1 } }; 2954: 2955: $schema->{input_style} = 'hash'; 2956: 2957: $schema->{_confidence}{input} = { 2958: level => 'high', 2959: factors => ['Detected combined getter/setter accessor'], 2960: }; 2961: if (my $pod = $method->{pod}) { 2962: if ($pod =~ /\b(LWP::UserAgent(?:::\w+)*)\b/) { 2963: my $class = $1; 2964: $schema->{output} = { 2965: type => 'object', 2966: isa => $class, 2967: }; 2968: $schema->{input}{$property} = { 2969: type => 'object', 2970: isa => $class, 2971: optional => 1,Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_2936_3: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes🧪 Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_2936_3: Replace return expression with undef
LOW: Mutation survived, but impact may be minor🧪 Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );2972: }; 2973: 2974: $schema->{_confidence}{output} = { 2975: level => 'high', 2976: factors => ['POD specifies UserAgent object'], 2977: }; 2978: } 2979: } 2980: } elsif(($arg_guard || $conditional_arg) && 2981: $code =~ /\$self\s*->\s*\{\s*['"]?([^}'"]+)['"]?\s*\}\s*=\s*(?:shift|\@_|\$_\[\d+\]|\$\w+)\b/x && 2982: $code =~ /return\b/ 2983: ) { 2984: # ------------------------------- 2985: # Getter/Setter (validated input) 2986: # ------------------------------- 2987: my $property = $1; 2988: 2989: # A named-argument guard is weaker evidence than `if (@_)`, so when 2990: # the method declares more than one parameter assume this is not an 2991: # accessor rather than croaking further down on an ambiguous match. 2992: if($conditional_arg && !$arg_guard && 2993: (ref($schema->{input}) eq 'HASH') && (scalar(keys %{$schema->{input}}) > 1)) { 2994: $self->_log(" Skipping conditional accessor: more than one argument"); 2995: return; 2996: } 2997: 2998: if(!defined($property)) { 2999: if($code =~ /\$self\s*->\s*\{\s*['"]?([^}'"]+)['"]?\s*\}\s*=/) { 3000: $property = $1; 3001: } 3002: } 3003: if ($code =~ /validate_strict/) { 3004: push @{ $schema->{_confidence}{input}{factors} }, 'Setter uses Params::Validate::Strict'; 3005: } else { 3006: # --------------------------------------- 3007: # Detect object input via blessed($arg) 3008: # --------------------------------------- 3009: if ($code =~ /blessed\s*\(\s*\$(\w+)\s*\)/) { 3010: my $param = $1; 3011: 3012: $self->_log(" Detected object input via blessed(\$$param)"); 3013: 3014: $schema->{input} = { 3015: $param => { 3016: type => 'object', 3017: optional => 1, 3018: } 3019: }; 3020: 3021: $schema->{_confidence}{input} = { 3022: level => 'high', 3023: factors => ['Input validated by Scalar::Util::blessed'], 3024: }; 3025: } else { 3026: # fallback ONLY if nothing known 3027: $schema->{input} ||= { 3028: value => { type => 'string', optional => 1 }, 3029: }; 3030: } 3031: }; 3032: $schema->{accessor} = { 3033: type => 'getset', 3034: property => $property, 3035: }; 3036: 3037: $self->_log(" Detected getter/setter accessor for property: $property"); 3038: if (my $pod = $method->{pod}) { 3039: if ($pod =~ /\b(LWP::UserAgent(?:::\w+)*)\b/) { 3040: my $class = $1; 3041: $schema->{output} = { 3042: type => 'object', 3043: isa => $class, 3044: }; 3045: $schema->{input}{$property} = { 3046: type => 'object', 3047: isa => $class, 3048: optional => 1, 3049: }; 3050:Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_2971_2: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes🧪 Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_2971_2: Replace return expression with undef
LOW: Mutation survived, but impact may be minor🧪 Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );Mutants (Total: 2, Killed: 2, Survived: 0)
3051: $schema->{_confidence}{output} = { 3052: level => 'high', 3053: factors => ['POD specifies UserAgent object'], 3054: }; 3055: } 3056: } 3057: # Set position 0 on whichever single input parameter already exists. 3058: # The parameter may be named differently from the stored property 3059: # (e.g. $dir for the logdir property), so find the existing key 3060: # rather than creating a new entry keyed by $property â doing the 3061: # latter produces a duplicate-position collision between the real 3062: # param and the spurious $property key. 3063: if(ref($schema->{input}) eq 'HASH') { 3064: my @input_keys = keys %{$schema->{input}}; 3065: if(scalar @input_keys > 1) { 3066: croak(__PACKAGE__, ': A getset accessor function can have at most one argument'); 3067: } elsif(@input_keys == 1) { 3068: $schema->{input}{$input_keys[0]}{position} = 0; 3069: } else { 3070: $schema->{input}{$property}{position} = 0;
Mutants (Total: 2, Killed: 2, Survived: 0)
3071: } 3072: } 3073: } elsif ($code =~ /return\s+\$self\s*->\s*\{\s*['"]?([^}'"]+)['"]?\s*\}\s*;/) { 3074: # ------------------------------- 3075: # Getter 3076: # ------------------------------- 3077: my $property = $1; 3078: 3079: # Don't flag mutators like 3080: # sub foo { 3081: # my $self = shift; 3082: # $self->{bar} = shift; 3083: # return $self->{bar}; 3084: # } 3085: # Only exclude if the property is being set FROM EXTERNAL INPUT 3086: if($code !~ /\$self\s*->\s*\{\s*['"]?\Q$property\E['"]?\s*\}\s*=\s*(?:shift|\$\w+\s*=\s*shift|\@_|\$_\[\d+\])/) { 3087: my @returns = $code =~ /return\b/g; 3088: my @self_returns = $code =~ /return\s+\$self\s*->\s*\{\s*['"]?\Q$property\E['"]?\s*\}/g; 3089: # it's a getter 3090: if (scalar(@returns) == scalar(@self_returns)) { 3091: # all returns are returning $self->{$property}, so it's a getter 3092: $schema->{accessor} = { 3093: type => 'getter', 3094: property => $property, 3095: }; 3096: 3097: $self->_log(" Detected getter accessor for property: $property"); 3098: 3099: # A memoised property's initializer is the only evidence of 3100: # what the getter returns:
Mutants (Total: 1, Killed: 1, Survived: 0)
3101: # $self->{proposals} //= [ map { ... } @{ $self->survivors } ];
3102: # Without it the expression looks like a scalar, and the 3103: # harness validates the returned arrayref as a string. 3104: $schema->{output} ||= {}; 3105: if($code =~ /\$self\s*->\s*\{\s*['"]?\Q$property\E['"]?\s*\}\s*\/\/=\s*\[/) { 3106: $schema->{output}{type} = 'arrayref'; 3107: } elsif($code =~ /\$self\s*->\s*\{\s*['"]?\Q$property\E['"]?\s*\}\s*\/\/=\s*\{/) { 3108: $schema->{output}{type} = 'hashref'; 3109: } 3110: 3111: $schema->{_confidence}{output} = { 3112: level => 'high', 3113: factors => ['Detected getter method'], 3114: }; 3115: delete $schema->{input}; 3116: } 3117: } 3118: } elsif ( 3119: $code =~ /return\s+\$self\b/ && 3120: $code =~ /\$self\s*->\s*\{\s*['"]?([^}'"]+)['"]?\s*\}\s*=\s*\$(\w+)\s*;/ 3121: ) { 3122: # ------------------------------- 3123: # Setter 3124: # ------------------------------- 3125: my ($property, $param) = ($1, $2); 3126: 3127: $schema->{accessor} = { 3128: type => 'setter', 3129: property => $property, 3130: param => $param,Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_3101_4: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes🧪 Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_3101_4: Replace return expression with undef
LOW: Mutation survived, but impact may be minor🧪 Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );Mutants (Total: 1, Killed: 1, Survived: 0)
3131: };
Mutants (Total: 2, Killed: 2, Survived: 0)
3132: 3133: $self->_log(" Detected setter accessor for property: $property"); 3134: 3135: # A setter that hands the argument to something else before storing 3136: # it, such as CGI::Info::set_logger's 3137: # 3138: # $self->{'logger'} = Log::Abstraction->new($logger); 3139: # 3140: # does not constrain what the argument may be, so the 'string' default 3141: # would invent cases like "a hash ref must die" that the routine 3142: # rightly accepts. Claim 'string' only when every assignment stores the 3143: # argument itself. 3144: my $param_type = 'string'; 3145: while($code =~ /\$self\s*->\s*\{\s*['"]?\Q$property\E['"]?\s*\}\s*=\s*([^;]+);/g) { 3146: if($1 =~ /(?:->|::)\w+\s*\([^)]*\$\Q$param\E\b/) { 3147: $param_type = 'any'; 3148: last; 3149: } 3150: } 3151: 3152: $schema->{input} = { 3153: $param => { type => $param_type }, # safe default 3154: }; 3155: $schema->{input_style} = 'hash'; 3156: 3157: $schema->{_confidence}{input} = { 3158: level => 'high', 3159: factors => ['Detected setter/accessor method'], 3160: }; 3161: if($schema->{output}{_returns_self}) { 3162: if($schema->{output}{type} ne 'object') { 3163: croak 'Setter can not return data other than $self'; 3164: } 3165: if($schema->{output}{isa} ne $self->{_package_name}) { 3166: croak 'Setter can not return data other than $self'; 3167: } 3168: } elsif(scalar(keys %{$schema->{output}}) != 0) { 3169: $self->_analysis_error( 3170: method => $method->{name}, 3171: message => "Setter cannot return data", 3172: ); 3173: } 3174: } 3175: ●3176 → 3176 → 0 3176: if(exists($schema->{accessor})) { 3177: if($schema->{accessor}{type} && $schema->{accessor}{type} =~ /setter|getset/ && $schema->{input}) { 3178: for my $param (keys %{ $schema->{input} }) { 3179: my $in = $schema->{input}{$param}; 3180: 3181: if ($in->{type} && ($in->{type} eq 'object')) { 3182: $schema->{output} = { 3183: type => 'object', 3184: ($in->{isa} ? (isa => $in->{isa}) : ()), 3185: }; 3186: 3187: $schema->{_confidence}{output} = { 3188: level => 'high', 3189: factors => ['Output type propagated from setter input'], 3190: }; 3191: } 3192: } 3193: } 3194: 3195: if($schema->{accessor}{type} && $schema->{accessor}{property} && ($schema->{accessor}{type} =~ /getter|getset/) && 3196: ((!defined($schema->{output}{type})) || ($schema->{output}{type} eq 'string'))) { 3197: if (my $pod = $method->{pod}) {
Mutants (Total: 1, Killed: 1, Survived: 0)
3198: # POD says "UserAgent object" 3199: if ($pod =~ /\bUser[- ]?Agent\b.*\bobject\b/i) { 3200: $schema->{output}{type} = 'object'; 3201: $schema->{output}{isa} = 'LWP::UserAgent'; 3202: 3203: push @{ $schema->{_confidence}{output}{factors} }, 'POD indicates UserAgent object'; 3204: 3205: $schema->{_confidence}{output}{level} = 'high'; 3206: } 3207: } 3208: } 3209: } 3210: } 3211: 3212: # -------------------------------------------------- 3213: # _analysis_error 3214: #
3215: # Purpose: Report a fatal analysis error with 3216: # module, method, and file context, 3217: # then croak. 3218: #Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_3214_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes3219: # Entry: Named args: 3220: # method - method name string. 3221: # message - error description string. 3222: # 3223: # Exit: Does not return â always croaks. 3224: # 3225: # Side effects: None beyond the croak. 3226: # -------------------------------------------------- 3227: sub _analysis_error { 3228: my ($self, %args) = @_; 3229: 3230: my $method = $args{method} // 'UNKNOWN'; 3231: my $msg = $args{message} // 'Analysis error'; 3232: 3233: my $module = $self->{_package_name} // 'UNKNOWN'; 3234: my $file = $self->{input_file} // 'UNKNOWN'; 3235: 3236: croak join "\n", 3237: $msg, 3238: " Module: $module", 3239: " Method: $method", 3240: " File: $file", 3241: ''; 3242: } 3243: 3244: # -------------------------------------------------- 3245: # _extract_validator_schema 3246: # 3247: # Purpose: Try each supported validator extractor 3248: # in priority order and return the first 3249: # schema that yields a non-empty input 3250: # spec. Used to detect explicit 3251: # parameter validation declarations 3252: # before falling back to heuristic 3253: # code analysis. 3254: # 3255: # Entry: $code - method body source string. 3256: # 3257: # Exit: Returns a schema hashref on success, 3258: # or undef if no supported validator 3259: # call is detected. 3260: # 3261: # Side effects: None. 3262: # 3263: # Notes: Extractors tried in order: 3264: # Params::Validate::Strict, 3265: # Params::Validate, 3266: # MooseX::Params::Validate, 3267: # Type::Params. 3268: # -------------------------------------------------- 3269: sub _extract_validator_schema { ●3270 → 3272 → 3277 3270: my ($self, $code) = @_; 3271: 3272: for my $extractor ('_extract_pvs_schema', '_extract_pv_schema', '_extract_moosex_params_schema', '_extract_type_params_schema') { 3273: my $res = $self->$extractor($code); 3274: return $res if ($res && ref($res) eq 'HASH' && keys %{ $res->{input} || {} }); 3275: } 3276: 3277: return; 3278: } 3279: 3280: # -------------------------------------------------- 3281: # _parse_schema_hash 3282: # 3283: # Purpose: Parse a PPI block node representing 3284: # a validator schema hash literal and 3285: # return a normalised schema structure 3286: # suitable for use as input spec. 3287: # 3288: # Entry: $hash - a PPI node with a children() 3289: # method, typically a 3290: # PPI::Structure::Block from 3291: # a validate_strict call. 3292: # 3293: # Exit: Returns a hashref with keys: 3294: # input - hashref of param specs 3295: # input_style - 'hash' 3296: # _confidence - confidence hashref 3297: # or undef if parsing fails. 3298: # 3299: # Side effects: None. 3300: # -------------------------------------------------- 3301: sub _parse_schema_hash { ●3302 → 3306 → 3361 3302: my ($self, $hash) = @_; 3303: 3304: my %result; 3305: 3306: for my $child ($hash->children) { 3307: # skip whitespace and operators 3308: if ($child->isa('PPI::Statement') || $child->isa('PPI::Statement::Expression')) { 3309: my ($key, $val); 3310: 3311: my @tokens = grep { 3312: !$_->isa('PPI::Token::Whitespace') && 3313: !$_->isa('PPI::Token::Operator') 3314: } $child->children; 3315: 3316: for (my $i = 0; $i < @tokens - 1; $i++) { 3317: if(($tokens[$i]->isa('PPI::Token::Word') || $tokens[$i]->isa('PPI::Token::Quote')) && 3318: $tokens[$i+1]->isa('PPI::Structure::Constructor')) { 3319: $key = $tokens[$i]->content;Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_3218_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes3320: $key =~ s/^['"]|['"]$//g; 3321: $val = $tokens[$i+1]; 3322: last; 3323: } 3324: }Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_3319_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes3325: 3326: next unless $key && $val; 3327: 3328: my %param; 3329: for my $inner ($val->children) { 3330: next unless $inner->isa('PPI::Statement') || $inner->isa('PPI::Statement::Expression'); 3331: 3332: my ($k, undef, $v) = grep { 3333: !$_->isa('PPI::Token::Whitespace') && 3334: !$_->isa('PPI::Token::Operator') 3335: } $inner->children; 3336: 3337: next unless $k && $v; 3338: 3339: my $keyname = $k->content; 3340: my $value = $v->can('content') ? $v->content : undef; 3341: $value =~ s/^['"]|['"]$//g if defined $value; 3342: 3343: if ($keyname eq 'type') { 3344: $param{type} = lc($value); 3345: } elsif ($keyname eq 'optional') { 3346: $param{optional} = $value ? 1 : 0; 3347: } elsif ($keyname =~ /^(min|max)$/ && looks_like_number($value)) { 3348: $param{$keyname} = 0 + $value; 3349: } elsif ($keyname eq 'matches') { 3350: $param{matches} = qr/$value/; 3351: } 3352: } 3353: 3354: $param{type} //= 'string'; 3355: $param{optional} //= 0; 3356: 3357: $result{$key} = \%param; 3358: } 3359: } 3360: 3361: return { 3362: input => \%result, 3363: input_style => 'hash', 3364: _confidence => { 3365: input => { 3366: level => 'high', 3367: factors => ['Input schema extracted from validator'], 3368: }, 3369: }, 3370: }; 3371: } 3372:Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_3324_2: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes🧪 Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_3324_2: Replace return expression with undef
LOW: Mutation survived, but impact may be minor🧪 Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );3373: # -------------------------------------------------- 3374: # _ppi 3375: # 3376: # Purpose: Return a PPI::Document for a code 3377: # string, using a per-instance cache 3378: # to avoid re-parsing the same string 3379: # multiple times during a single 3380: # analysis pass. 3381: # 3382: # Entry: $code - either a string of Perl source 3383: # code, or an object that 3384: # already has a find() method 3385: # (returned as-is). 3386: # 3387: # Exit: Returns a PPI::Document, or the 3388: # original object if it alreadyMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_3372_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
3389: # supports find(). 3390: # 3391: # Side effects: Populates $self->{_ppi_cache}.
3392: # -------------------------------------------------- 3393: sub _ppi { 3394: my ($self, $code) = @_; 3395: 3396: return $code if ref($code) && $code->can('find'); 3397: 3398: $self->{_ppi_cache} ||= {}; 3399: return $self->{_ppi_cache}{$code} //= PPI::Document->new(\$code); 3400: } 3401: 3402: # -------------------------------------------------- 3403: # _extract_pvs_schema 3404: # 3405: # Purpose: Detect and extract a parameter schema 3406: # from a Params::Validate::Strict 3407: # validate_strict() call in the method 3408: # body. 3409: # 3410: # Entry: $code - method body source string. 3411: # 3412: # Exit: Returns a schema hashref with input, 3413: # style, and source keys on success, 3414: # or undef if no validate_strict call 3415: # is found or parsing fails. 3416: # 3417: # Side effects: None. 3418: # -------------------------------------------------- 3419: sub _extract_pvs_schema { ●3420 → 3430 → 3465 3420: my ($self, $code) = @_; 3421: 3422: return unless $code =~ /\bvalidate_strict\s*\(/; 3423: 3424: my $doc = $self->_ppi($code) or return; 3425: 3426: my $calls = $doc->find(sub { 3427: $_[1]->isa('PPI::Token::Word') && ($_[1]->content eq 'validate_strict' || $_[1]->content eq 'Params::Validate::Strict::validate_strict') 3428: }) or return; 3429: 3430: for my $call (@$calls) { 3431: my $list = $call->parent(); 3432: while ($list && !$list->isa('PPI::Structure::List')) { 3433: $list = $list->parent(); 3434: } 3435: if(!defined($list)) { 3436: my $next = $call->next_sibling(); 3437: next unless defined $next; 3438: if($next->content() =~ /schema\s*=>\s*(\{(?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*\})/s) { 3439: my $schema_text = $1; 3440: next if $schema_text =~ $UNSAFE_KEYWORD_RE; 3441: my $compartment = Safe->new(); 3442: $compartment->permit_only(qw(:base_core :base_mem :base_orig)); 3443: 3444: my $schema_str = "my \$schema = $schema_text"; 3445: my $schema = $compartment->reval($schema_str); 3446: if($self->_usable_validator_schema($schema)) { 3447: return { 3448: input => $schema, 3449: style => 'hash', 3450: source => SOURCE_VALIDATOR 3451: } 3452: } 3453: } 3454: } 3455: next unless $list;Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_3391_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
3456: 3457: my ($schema_block) = grep { $_->isa('PPI::Structure::Block') } $list->children; 3458: 3459: next unless $schema_block; 3460: 3461: my $schema = $self->_extract_schema_hash_from_block($schema_block); 3462: return $self->_normalize_validator_schema($schema) if $schema; 3463: } 3464: 3465: return; 3466: } 3467: 3468: # -------------------------------------------------- 3469: # _extract_pv_schema 3470: # 3471: # Purpose: Detect and extract a parameter schema 3472: # from a Params::Validate validate() 3473: # call in the method body. 3474: # 3475: # Entry: $code - method body source string. 3476: #
Mutants (Total: 1, Killed: 1, Survived: 0)
3477: # Exit: Returns a schema hashref with input, 3478: # style, and source keys on success, 3479: # or undef if no validate() call is 3480: # found or parsing fails. 3481: #
Mutants (Total: 1, Killed: 1, Survived: 0)
3482: # Side effects: None. 3483: # -------------------------------------------------- 3484: sub _extract_pv_schema { ●3485 → 3495 → 3542 3485: my ($self, $code) = @_; 3486: 3487: return unless $code =~ /\bvalidate\s*\(/;
Mutants (Total: 1, Killed: 1, Survived: 0)
3488: 3489: my $doc = $self->_ppi($code) or return; 3490: 3491: my $calls = $doc->find(sub { 3492: $_[1]->isa('PPI::Token::Word') && ($_[1]->content eq 'validate' || $_[1]->content eq 'Params::Validate::validate') 3493: }) or return; 3494: 3495: for my $call (@$calls) {
Mutants (Total: 1, Killed: 1, Survived: 0)
3496: my $list = $call->parent; 3497: while ($list && !$list->isa('PPI::Structure::List')) { 3498: $list = $list->parent; 3499: } 3500: if(!defined($list)) { 3501: my $next = $call->next_sibling(); 3502: my ($arglist, $schema_text) = $self->_parse_pv_call($next); 3503: 3504: if($schema_text && $schema_text !~ $UNSAFE_KEYWORD_RE) { 3505: my $compartment = Safe->new(); 3506: $compartment->permit_only(qw(:base_core :base_mem :base_orig)); 3507: 3508: my $schema_str = "my \$schema = $schema_text";
3509: my $schema = $compartment->reval($schema_str); 3510: 3511: if($self->_usable_validator_schema($schema)) { 3512: foreach my $arg(keys %{$schema}) { 3513: my $field = $schema->{$arg}; 3514: if(my $type = $field->{'type'}) { 3515: if($type eq 'ARRAYREF') { 3516: $field->{'type'} = 'arrayref'; 3517: } elsif($type eq 'SCALAR') { 3518: $field->{'type'} = 'string'; 3519: } 3520: } 3521: delete $field->{'callbacks'}; 3522: } 3523:Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_3508_5: Invert condition unless to if
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
3524: return { 3525: input => $schema, 3526: style => 'hash', 3527: source => SOURCE_VALIDATOR 3528: } 3529: } 3530: }
Mutants (Total: 1, Killed: 1, Survived: 0)
3531: } 3532: next unless $list; 3533: 3534: my ($schema_block) = grep { $_->isa('PPI::Structure::Block') } $list->children; 3535: 3536: next unless $schema_block; 3537: 3538: my $schema = $self->_extract_schema_hash_from_block($schema_block); 3539: return $self->_normalize_validator_schema($schema) if $schema;
Mutants (Total: 1, Killed: 1, Survived: 0)
3540: } 3541: 3542: return; 3543: } 3544: 3545: # -------------------------------------------------- 3546: # _parse_pv_call
Mutants (Total: 1, Killed: 1, Survived: 0)
3547: # 3548: # Purpose: Split a Params::Validate call argument 3549: # string into its two components: the 3550: # first argument (typically \@_) and 3551: # the schema hash string. 3552: # 3553: # Entry: $string - the raw argument string 3554: # from the validate() call, 3555: # including outer parentheses. 3556: # 3557: # Exit: Returns a two-element list: 3558: # ($first_arg, $hash_str) 3559: # or an empty list if no comma is found 3560: # at brace depth zero (malformed call). 3561: # 3562: # Side effects: None. 3563: # -------------------------------------------------- 3564: sub _parse_pv_call { ●3565 → 3579 → 3596 3565: my ($self, $string) = @_; 3566: 3567: # Remove outer parentheses and whitespace 3568: $string =~ s/^\s*\(\s*//; 3569: $string =~ s/\s*\)\s*$//; 3570: 3571: # Find the first comma at brace-depth 0, jumping over each balanced 3572: # {...} block in one step via extract_bracketed rather than 3573: # counting depth character by character 3574: require Text::Balanced; 3575: my $rest = $string; 3576: my $comma_pos = 0; 3577: my $found_comma = 0; 3578: 3579: while (length $rest) { 3580: if (substr($rest, 0, 1) eq '{') { 3581: # extract_bracketed advances $rest past the extracted block 3582: # in place, so $rest must not be re-truncated afterwards
3583: my $extracted = Text::Balanced::extract_bracketed($rest, '{}'); 3584: return unless defined $extracted; # Broken source code 3585: $comma_pos += length $extracted; 3586: next; 3587: } 3588: if (substr($rest, 0, 1) eq ',') {Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_3582_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes3589: $found_comma = 1;Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_3588_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes3590: last; 3591: } 3592: $comma_pos++; 3593: $rest = substr($rest, 1); 3594: } 3595: 3596: return unless $found_comma;Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_3589_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes3597: 3598: my $first_arg = substr($string, 0, $comma_pos); 3599: my $hash_str = substr($string, $comma_pos + 1); 3600: 3601: # Trim whitespace 3602: $first_arg =~ s/^\s+|\s+$//g; 3603: $hash_str =~ s/^\s+|\s+$//g; 3604: 3605: return ($first_arg, $hash_str); 3606: } 3607: 3608: # -------------------------------------------------- 3609: # _extract_moosex_params_schema 3610: # 3611: # Purpose: Detect and extract a parameter schema 3612: # from a MooseX::Params::Validate 3613: # validated_hash() call in the method 3614: # body. 3615: # 3616: # Entry: $code - method body source string. 3617: # 3618: # Exit: Returns a schema hashref with input, 3619: # style, and source keys on success, 3620: # or undef if no validated_hash() call 3621: # is found or parsing fails. 3622: #Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_3596_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
3623: # Side effects: None. 3624: # -------------------------------------------------- 3625: sub _extract_moosex_params_schema 3626: { ●3627 → 3637 → 3701 3627: my ($self, $code) = @_; 3628: 3629: return unless $code =~ /\bvalidated_hash\s*\(/; 3630: 3631: my $doc = $self->_ppi($code) or return; 3632: 3633: my $calls = $doc->find(sub { 3634: $_[1]->isa('PPI::Token::Word') && ($_[1]->content eq 'validated_hash') 3635: }) or return;
3636: 3637: for my $call (@$calls) { 3638: my $list = $call->parent(); 3639: while ($list && !$list->isa('PPI::Structure::List')) { 3640: $list = $list->parent; 3641: } 3642: if(!defined($list)) {Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_3635_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes3643: my $next = $call->next_sibling(); 3644: my ($arglist, $schema_text) = $self->_parse_pv_call($next); 3645: 3646: if($schema_text && $schema_text !~ $UNSAFE_KEYWORD_RE) { 3647: my $compartment = Safe->new(); 3648: $compartment->permit_only(qw(:base_core :base_mem :base_orig)); 3649: 3650: my $schema_str = "my \$schema = { $schema_text }"; 3651: $schema_str =~ s/ArrayRef\[(.+?)\]/arrayref, element_type => $1/g; 3652: my $schema = $compartment->reval($schema_str); 3653: 3654: if($self->_usable_validator_schema($schema)) { 3655: foreach my $arg(keys %{$schema}) {Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_3642_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes3656: my $field = $schema->{$arg}; 3657: if(my $isa = delete $field->{'isa'}) { 3658: $field->{'type'} = $isa; 3659: } 3660: if(exists($field->{'required'})) { 3661: my $required = delete $field->{'required'}; 3662: $field->{'optional'} = $required ? 0 : 1;Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_3655_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes3663: } else { 3664: $field->{'optional'} = 1; 3665: } 3666: if(ref($field->{'default'}) eq 'CODE') { 3667: delete $field->{'default'}; # TODO 3668: } 3669: } 3670: 3671: foreach my $arg(keys %{$schema}) { 3672: my $field = $schema->{$arg};Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_3662_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes3673: if(my $type = $field->{'type'}) { 3674: if($type eq 'ARRAYREF') { 3675: $field->{'type'} = 'arrayref'; 3676: } elsif($type eq 'SCALAR') { 3677: $field->{'type'} = 'string'; 3678: } 3679: } 3680: delete $field->{'callbacks'}; 3681: } 3682: 3683: return { 3684: input => $schema, 3685: style => 'hash', 3686: source => SOURCE_VALIDATOR 3687: } 3688: } 3689: } 3690: } 3691: next unless $list; 3692: 3693: my ($schema_block) = grep { $_->isa('PPI::Structure::Block') } $list->children; 3694: 3695: next unless $schema_block; 3696: 3697: my $schema = $self->_extract_schema_hash_from_block($schema_block); 3698: return $self->_normalize_validator_schema($schema) if $schema;Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_3672_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
3699: } 3700: 3701: return; 3702: }
Mutants (Total: 1, Killed: 1, Survived: 0)
3703: 3704: # -------------------------------------------------- 3705: # _extract_schema_hash_from_block 3706: # 3707: # Purpose: Extract a parameter schema hashref from
Mutants (Total: 1, Killed: 1, Survived: 0)
3708: # a PPI::Structure::Block node representing 3709: # the schema argument to a validator call
Mutants (Total: 1, Killed: 1, Survived: 0)
3710: # such as validate_strict({ ... }). 3711: #
Mutants (Total: 1, Killed: 1, Survived: 0)
3712: # Entry: $block - a PPI::Structure::Block node. 3713: # 3714: # Exit: Returns a hashref of parameter name to 3715: # spec hashref, or undef if parsing fails.
3716: # 3717: # Side effects: None. 3718: # 3719: # Notes: Delegates to _parse_schema_hash which 3720: # expects a PPI node with a children() 3721: # method. This method exists to provide 3722: # a clear semantic name at the call site. 3723: # -------------------------------------------------- 3724: sub _extract_schema_hash_from_block { 3725: my ($self, $block) = @_; 3726: 3727: return unless $block && $block->can('children'); 3728:Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_3715_6: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
3729: my $result = $self->_parse_schema_hash($block); 3730: 3731: return unless $result && ref($result) eq 'HASH' && $result->{input}; 3732:
Mutants (Total: 1, Killed: 1, Survived: 0)
3733: return $result->{input}; 3734: } 3735:
3736: # -------------------------------------------------- 3737: # _usable_validator_schema 3738: # 3739: # Purpose: Decide whether a schema hash evaluated 3740: # from source code is a real parameter 3741: # schema, or the remains of a runtime 3742: # expression that was never meant to be 3743: # evaluated at all.Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_3735_5: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes3744: # 3745: # Entry: $schema - value returned by 3746: # Safe->reval() on the schemaMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_3743_5: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes3747: # text found in the call. 3748: # 3749: # Exit: Returns true when the schema is aMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_3746_5: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes3750: # non-empty hash of named parameters to 3751: # spec hashes, false otherwise. 3752: # 3753: # Side effects: None. 3754: # 3755: # Notes: CGI::Info::params validates each 3756: # parameter inside a loop with 3757: # 3758: # validate_strict({ 3759: # schema => { $key => $schema }, 3760: # args => { $key => $value },Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_3749_5: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 2, Killed: 2, Survived: 0)
3761: # }); 3762: # 3763: # Evaluating { $key => $schema } with 3764: # both lexicals undefined yields 3765: # { '' => undef }. Accepting that as the 3766: # method's input gave the schema an empty 3767: # parameter name, which the harness 3768: # generator rightly refuses to turn into 3769: # a Perl variable, so no harness could be 3770: # generated for the routine at all. 3771: # -------------------------------------------------- 3772: sub _usable_validator_schema { ●3773 → 3780 → 3785 3773: my ($self, $schema) = @_; 3774: 3775: return 0 unless ref($schema) eq 'HASH'; 3776: 3777: my @names = keys %$schema; 3778: return 0 unless @names; 3779: 3780: for my $name (@names) { 3781: return 0 unless length($name); 3782: return 0 unless ref($schema->{$name}) eq 'HASH'; 3783: } 3784:
Mutants (Total: 2, Killed: 2, Survived: 0)
3785: return 1; 3786: } 3787: 3788: # -------------------------------------------------- 3789: # _normalize_validator_schema 3790: # 3791: # Purpose: Normalise a raw validator schema 3792: # hashref (as extracted from PPI) into 3793: # the standard input spec format used 3794: # throughout the extractor. 3795: # 3796: # Entry: $schema - hashref of parameter name 3797: # to raw spec hashref, as 3798: # produced by 3799: # _extract_schema_hash_from_block. 3800: # 3801: # Exit: Returns a hashref with keys: 3802: # input_style - 'hash' 3803: # input - normalised param specs 3804: # Each param spec gains an explicit 3805: # optional key and _source / _type_confidence 3806: # metadata. 3807: # 3808: # Side effects: None. 3809: # -------------------------------------------------- 3810: sub _normalize_validator_schema { ●3811 → 3815 → 3826 3811: my ($self, $schema) = @_;
Mutants (Total: 2, Killed: 2, Survived: 0)
3812: 3813: my %input;
Mutants (Total: 2, Killed: 2, Survived: 0)
3814: 3815: for my $name (keys %$schema) { 3816: my $spec = $schema->{$name}; 3817: 3818: $input{$name} = { 3819: %$spec, 3820: optional => exists $spec->{optional} ? $spec->{optional} : 0, 3821: _source => SOURCE_VALIDATOR, 3822: _type_confidence => 'high', 3823: }; 3824: } 3825: 3826: return { 3827: input_style => 'hash', 3828: input => \%input, 3829: }; 3830: } 3831: 3832: # -------------------------------------------------- 3833: # _extract_type_params_schema 3834: # 3835: # Purpose: Detect and extract a parameter schema 3836: # from a Type::Params signature_for() 3837: # declaration for the current method, 3838: # located in the module-level document. 3839: # 3840: # Entry: $code - method body source string 3841: # (used to extract the function 3842: # name for lookup). 3843: # 3844: # Exit: Returns a schema hashref on success, 3845: # or undef if no signature_for 3846: # declaration is found or compilation 3847: # fails. 3848: # 3849: # Side effects: May fork a child process to compile 3850: # the signature in isolation. 3851: # -------------------------------------------------- 3852: sub _extract_type_params_schema { 3853: my ($self, $code) = @_; 3854: 3855: my $function = $self->_extract_function_name($code) or return; 3856: 3857: my $doc = $self->{_document} or return; 3858: my $stmt = $self->_find_signature_statement($doc, $function) or return;
Mutants (Total: 2, Killed: 2, Survived: 0)
3859: 3860: my $signature_expr = $self->_extract_signature_expression($stmt, $function) or return; 3861: 3862: my $meta = $self->_compile_signature_isolated($function, $signature_expr) or return; 3863: 3864: return $self->_build_schema_from_meta($meta); 3865: } 3866: 3867: # -------------------------------------------------- 3868: # _extract_function_name 3869: # 3870: # Purpose: Extract the subroutine name from the 3871: # start of a method body string, used 3872: # to look up its Type::Params signature. 3873: # 3874: # Entry: $code - method body source string. 3875: # 3876: # Exit: Returns the subroutine name string, 3877: # or undef if no 'sub name' declaration 3878: # is found. 3879: # 3880: # Side effects: None. 3881: # -------------------------------------------------- 3882: sub _extract_function_name { 3883: my ($self, $code) = @_; 3884: return $1 if $code =~ /^\s*sub\s+([a-zA-Z0-9_]+)/; 3885: return; 3886: } 3887: 3888: # -------------------------------------------------- 3889: # _find_signature_statement
Mutants (Total: 1, Killed: 1, Survived: 0)
3890: # 3891: # Purpose: Search a PPI document for a 3892: # signature_for statement that 3893: # corresponds to a named function. 3894: # 3895: # Entry: $doc - PPI::Document to search.
Mutants (Total: 1, Killed: 1, Survived: 0)
3896: # $function - function name string. 3897: # 3898: # Exit: Returns the matching PPI::Statement
Mutants (Total: 1, Killed: 1, Survived: 0)
3899: # node, or undef if none is found. 3900: # 3901: # Side effects: None. 3902: # --------------------------------------------------
3903: sub _find_signature_statement { ●3904 → 3912 → 3919 3904: my ($self, $doc, $function) = @_; 3905: 3906: my $statements = $doc->find( 3907: sub {Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_3902_5: Invert condition unless to if
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
3908: $_[1]->isa('PPI::Statement') && $_[1]->content =~ /^\s*signature_for\b/ 3909: } 3910: ) or return; 3911:
Mutants (Total: 1, Killed: 1, Survived: 0)
3912: foreach my $stmt (@$statements) { 3913: my $content = $stmt->content; 3914: if ($content =~ /^\s*signature_for\s+\Q$function\E\b/) { 3915: return $stmt; 3916: } 3917: } 3918: 3919: return; 3920: } 3921: 3922: # -------------------------------------------------- 3923: # _extract_signature_expression 3924: # 3925: # Purpose: Extract the Type::Params signature 3926: # expression (everything after =>) from 3927: # a signature_for statement node.
Mutants (Total: 1, Killed: 1, Survived: 0)
3928: # 3929: # Entry: $stmt - PPI::Statement node. 3930: # $function - function name string, 3931: # used in the match pattern. 3932: # 3933: # Exit: Returns the signature expression 3934: # string, or undef if the pattern
Mutants (Total: 1, Killed: 1, Survived: 0)
3935: # does not match. 3936: # 3937: # Side effects: None. 3938: # -------------------------------------------------- 3939: sub _extract_signature_expression { ●3940 → 3944 → 3948 3940: my ($self, $stmt, $function) = @_; 3941: 3942: my $content = $stmt->content; 3943: 3944: if ($content =~ /^\s*signature_for\s+\Q$function\E\s*=>\s*(.+?);?\s*$/s) { 3945: return $1; 3946: } 3947: 3948: return; 3949: } 3950: 3951: # -------------------------------------------------- 3952: # _compile_signature_isolated 3953: #
Mutants (Total: 1, Killed: 1, Survived: 0)
3954: # Purpose: Compile and evaluate a Type::Params 3955: # signature expression in an isolated
3956: # process to extract parameter metadata 3957: # without polluting the current process. 3958: # 3959: # Only runs when the caller passed 3960: # allow_signature_exec => 1 to new(). 3961: # Extracting parameter types from a 3962: # Type::Params signature_for() declaration 3963: # requires actually building the type 3964: # objects at runtime -- there is no purely 3965: # static way to do it -- so this is real 3966: # execution of an excerpt of the target 3967: # module's own source. Every other codeMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_3955_5: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes3968: # path in this module is static (PPI-only) 3969: # analysis that never runs the target's 3970: # code, so this one feature must be optedMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_3967_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes3971: # into explicitly rather than triggered 3972: # implicitly by extract_all(). 3973: # 3974: # A Safe compartment was previously tried 3975: # first as a "fast path" before falling 3976: # back to this subprocess unconditionally.Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_3970_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
3977: # It was removed: Type::Params and 3978: # Types::Common pull in XS modules (e.g. 3979: # B.pm via Type::Params), and Safe cannot 3980: # host XS/dynamic loading at all, so the 3981: # compartment never succeeded for any real 3982: # signature_for() declaration -- it was 3983: # dead code that gave a false impression of 3984: # sandboxing while every real call fell 3985: # through to the unconditional subprocess 3986: # below.
Mutants (Total: 1, Killed: 1, Survived: 0)
3987: #
3988: # Entry: $function - function name string. 3989: # $signature_expr - Type::ParamsMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_3987_5: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes3990: # signature expression 3991: # string. 3992: # 3993: # Exit: Returns a decoded JSON hashref 3994: # containing parameters and returns 3995: # metadata on success. 3996: # Returns undef without running anything if 3997: # allow_signature_exec was not enabled. 3998: # Croaks on unsafe expressions, timeout, 3999: # or compile errors. 4000: # 4001: # Side effects: May fork a child process with a 4002: # memory limit applied via 4003: # BSD::Resource if available.Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_3989_6: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes4004: # Memory limiting is best-effort and 4005: # silently skipped on platforms where 4006: # BSD::Resource is unavailable. 4007: # -------------------------------------------------- 4008: sub _compile_signature_isolated { ●4009 → 4011 → 4020 4009: my ($self, $function, $signature_expr) = @_; 4010: 4011: unless ($self->{allow_signature_exec}) { 4012: carp "Skipping Type::Params signature_for($function) extraction: ", 4013: 'allow_signature_exec => 1 was not passed to new() ', 4014: '(this would execute code from the target module)' 4015: if $self->{verbose}; 4016: return; 4017: } 4018: 4019: # Remove comments ●4020 → 4029 → 4033 4020: $signature_expr =~ s/#.*$//mg; 4021: 4022: # Reject obviously dangerous constructs. This is defense in depth 4023: # only, not a real security boundary -- it is a denylist of literal 4024: # tokens and cannot catch e.g. a symbolic-ref call built by string 4025: # concatenation. The actual control here is the allow_signature_exec 4026: # opt-in above: this code must never run against a module the caller 4027: # has not already decided to trust enough to execute. 4028: # Both checks unified into one croak so the message and class are consistent 4029: if ($signature_expr =~ $UNSAFE_KEYWORD_RE || $signature_expr =~ $UNSAFE_CHAR_RE) { 4030: croak 'Unsafe signature expression -- rejected to prevent code execution'; 4031: } 4032: ●4033 → 4137 → 4145 4033: my $payload = <<'PERL'; 4034: use strict; 4035: use warnings; 4036: use Type::Params -sigs; 4037: use Types::Common -types; 4038: use JSON::MaybeXS; 4039: 4040: # Apply address-space limit passed from parent via env. Done here (in the 4041: # child) rather than in the parent so the parent's memory is never capped. 4042: if (my $limit = $ENV{_ATG_RLIMIT_AS}) { 4043: eval { 4044: require BSD::Resource; 4045: BSD::Resource::setrlimit(BSD::Resource::RLIMIT_AS(), $limit, $limit); 4046: }; 4047: } 4048: 4049: # Stub sub so Perl can parse it 4050: sub FUNCTION_NAME {} 4051: 4052: # Create the Type::Params signature object 4053: my $sig = signature_for FUNCTION_NAME => SIGNATURE_EXPR; 4054: 4055: # Extract parameters â guard against older Type::Params (< 2.x) where 4056: # signature_for() installs the constraint but returns undef rather thanMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_4003_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
4057: # the signature object, so ->parameters() would die. 4058: my @sig_params = (defined $sig && ref $sig && $sig->can('parameters'))
Mutants (Total: 1, Killed: 1, Survived: 0)
4059: ? @{ $sig->parameters || [] } 4060: : (); 4061: my $pos = 0; 4062: my @params; 4063: 4064: # if ($sig->method) { 4065: # The $self value 4066: # push @params, { 4067: # name => 'arg0', 4068: # optional => 0, 4069: # position => $pos++, 4070: # }; 4071: # } 4072: 4073: for my $p (@sig_params) { 4074: my $name = ($p->can('name') && defined($p->name) && length($p->name)) 4075: ? $p->name 4076: : "arg$pos"; 4077: push @params, { 4078: name => $name,
Mutants (Total: 1, Killed: 1, Survived: 0)
4079: optional => $p->optional ? 1 : 0, 4080: position => $pos, 4081: type => $p->type->name 4082: }; 4083: $pos++; 4084: } 4085: 4086: # Extract return type 4087: my $returns; 4088: if (my $r = $sig->returns_scalar) { 4089: $returns = { 4090: context => 'scalar',
Mutants (Total: 2, Killed: 2, Survived: 0)
4091: type => $r ? $r->name : 'unknown', 4092: }; 4093: } elsif ($r = $sig->returns_list) { 4094: $returns = { 4095: context => 'list', 4096: type => $r ? $r->name : 'unknown', 4097: }; 4098: } 4099: 4100: print encode_json({ 4101: parameters => \@params, 4102: returns => $returns, 4103: }); 4104: PERL 4105: 4106: # Substitute function name and signature expression 4107: $payload =~ s/FUNCTION_NAME/$function/g; 4108: $payload =~ s/SIGNATURE_EXPR/$signature_expr/; 4109: 4110: # Run in an isolated Perl process 4111: my ($wtr, $rdr, $err) = (undef, undef, gensym); 4112: local %ENV; 4113: 4114: # Pass the memory limit to the child via env so the child can apply 4115: # setrlimit on itself after exec. Must NOT call setrlimit here in the 4116: # parent: setrlimit(RLIMIT_AS) constrains the parent's own address
Mutants (Total: 1, Killed: 1, Survived: 0)
4117: # space, and when the parent later tries to allocate memory for test 4118: # framework teardown it would OOM and crash inside the Test::Builder 4119: # subtest context, producing a "context destroyed" error.
Mutants (Total: 1, Killed: 1, Survived: 0)
4120: $ENV{_ATG_RLIMIT_AS} = $MEMORY_LIMIT_BYTES; 4121: 4122: my $pid = open3($wtr, $rdr, $err, $^X, '-T'); 4123: 4124: print $wtr $payload; 4125: close $wtr; 4126: 4127: local $SIG{ALRM} = sub { croak 'Signature compile timeout' }; 4128: eval { alarm($SIGNATURE_TIMEOUT_SECS) }; # no-op on Windows 4129: 4130: my $stdout = do { local $/; <$rdr> };
Mutants (Total: 4, Killed: 4, Survived: 0)
4131: my $stderr = do { local $/; <$err> };
Mutants (Total: 1, Killed: 1, Survived: 0)
4132: 4133: eval { alarm 0 }; 4134: 4135: waitpid($pid, 0); 4136: 4137: if ($stderr && length $stderr) { 4138: carp "Error compiling signature:\n$stderr" if $self->{verbose}; 4139: return; 4140: }
Mutants (Total: 1, Killed: 1, Survived: 0)
4141: 4142: # Child may be killed by the kernel OOM killer (SIGKILL) before it can 4143: # write anything to stdout or stderr. Guard both cases so we degrade
4144: # gracefully rather than croaking with "malformed JSON". ●4145 → 4145 → 4150 4145: if (!defined($stdout) || !length($stdout)) {Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_4143_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes4146: carp 'Signature subprocess produced no output' if $self->{verbose}; 4147: return; 4148: } 4149: ●4150 → 4151 → 4155 4150: my $result = eval { decode_json($stdout) }; 4151: if ($@) { 4152: carp "Error decoding signature output: $@" if $self->{verbose}; 4153: return; 4154: } 4155: return $result;Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_4145_5: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes4156: } 4157: 4158: # -------------------------------------------------- 4159: # _build_schema_from_meta 4160: # 4161: # Purpose: Convert the parameter and return type 4162: # metadata produced by 4163: # _compile_signature_isolated into a 4164: # standard schema hashref. 4165: # 4166: # Entry: $meta - hashref with 'parameters' 4167: # arrayref and optional 4168: # 'returns' hashref, as decoded 4169: # from the isolated compileMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_4155_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes4170: # JSON output. 4171: # 4172: # Exit: Returns a schema hashref with input, 4173: # output, style, source, _notes, and 4174: # _confidence keys. 4175: # 4176: # Side effects: None. 4177: #Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_4169_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes4178: # Notes: Unknown Type::Params type names are 4179: # mapped to 'string' with a note added 4180: # and confidence downgraded to 'medium'. 4181: # -------------------------------------------------- 4182: sub _build_schema_from_meta { ●4183 → 4200 → 4217 4183: my ($self, $meta) = @_;Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_4177_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes4184: 4185: my %type_map = ( 4186: Num => 'number', 4187: Int => 'integer', 4188: Str => 'string', 4189: Bool => 'boolean', 4190: Object => 'object', 4191: ArrayRef => 'array', 4192: HashRef => 'object', 4193: ); 4194: 4195: my $input; 4196: my $position = 0; 4197: my $confidence = 'high';Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_4183_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
4198: my @notes = ('Type::Params detected'); 4199: 4200: foreach my $p (@{ $meta->{parameters} || [] }) { 4201: my $type = $type_map{ $p->{type} } // 'string'; 4202: 4203: if (!exists $type_map{$p->{type}}) {
Mutants (Total: 1, Killed: 1, Survived: 0)
4204: push @notes, "Unknown type $p->{type}, defaulting to string"; 4205: $confidence = 'medium'; 4206: } 4207: 4208: $input->{"arg$position"} = { 4209: type => $type, 4210: position => $position, 4211: optional => $p->{optional} ? 1 : 0,
Mutants (Total: 1, Killed: 1, Survived: 0)
4212: }; 4213: 4214: $position++; 4215: } 4216: ●4217 → 4219 → 4233 4217: my $output; 4218: 4219: if (my $ret = $meta->{returns}) { 4220: my $type = $type_map{ $ret->{type} } // 'string'; 4221: 4222: if (!exists $type_map{$ret->{type}}) { 4223: push @notes, "Unknown return type $ret->{type}, defaulting to string"; 4224: $confidence = 'medium'; 4225: } 4226: 4227: $output = { 4228: type => $type, 4229: "_$ret->{context}_context" => { type => $type }, 4230: }; 4231: } 4232: 4233: return { 4234: input => $input, 4235: output => $output, 4236: style => 'hash', 4237: source => SOURCE_VALIDATOR, 4238: _notes => \@notes, 4239: _confidence => { 4240: input => $confidence, 4241: }, 4242: }; 4243: } 4244: 4245: # -------------------------------------------------- 4246: # _analyze_pod 4247: # 4248: # Purpose: Parse POD documentation for a method 4249: # and extract parameter names, types, 4250: # constraints, and optionality from 4251: # multiple POD patterns. 4252: # 4253: # Entry: $pod - string of POD content as 4254: # returned by _extract_pod_before. 4255: # May be undef or empty. 4256: #
4257: # Exit: Returns a hashref of parameter name 4258: # to parameter spec hashref. Returns an 4259: # empty hashref if no POD is provided 4260: # or no parameters are found. 4261: # 4262: # Side effects: Carps when a semantic type is 4263: # detected, advising the caller to 4264: # set config->properties. 4265: # Logs progress to stdout whenMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_4256_6: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
4266: # verbose is set. 4267: # 4268: # Notes: Three pattern strategies are tried 4269: # in order: (1) named Parameters section, 4270: # (2) inline $name - type format, 4271: # (3) =over/=item list. Parameters found 4272: # earlier take precedence over later 4273: # discoveries. Default values from POD 4274: # are merged in last. 4275: # -------------------------------------------------- 4276: sub _analyze_pod { ●4277 → 4286 → 4302 4277: my ($self, $pod, $routine) = @_; 4278: 4279: return {} unless $pod; 4280: 4281: my %params; 4282: my $position_counter = 0;
Mutants (Total: 1, Killed: 1, Survived: 0)
4283: 4284: # Check for positional arguments in method signature 4285: # Pattern: =head2 method_name($arg1, $arg2, $arg3)
Mutants (Total: 1, Killed: 1, Survived: 0)
4286: if ($pod =~ /=head2\s+\w+\s*\(([^)]+)\)/s) {
4287: my $sig = $1; 4288: # Extract parameter names in order 4289: my @sig_params = $sig =~ /\$(\w+)/g; 4290:Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_4286_6: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes4291: # Skip $self or $class 4292: shift @sig_params if @sig_params && $sig_params[0] =~ /^(self|class|pkg|proto|klass)$/i; 4293: 4294: # Assign positions 4295: foreach my $param (@sig_params) {Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_4290_7: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
4296: $params{$param}{position} //= $position_counter; 4297: $self->_log(" POD: $param has position $params{$param}{position}"); 4298: $position_counter++; 4299: }
4300: } 4301:Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_4299_6: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes●4302 → 4307 → 4312 4302: $self->_log(" POD: Found $position_counter unnamed parameters to add to the position list"); 4303: 4304: # Pattern 1: Parse line-by-line in Parameters section 4305: # First, extract the Parameters section 4306: my $param_section; 4307: if($pod =~ /(?:Parameters?|Arguments?|Inputs?):?\s*\n((?:\s*\$.*\n)+)/si) { 4308: $param_section = $1; 4309: } elsif ($pod =~ /^=head\d+\s+(?:Parameters?|Arguments?|Inputs?)\b.*?\n(.*?)(?=^=head|\Z)/msi) { 4310: $param_section = $1; 4311: }Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_4301_7: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes●4312 → 4312 → 4396 4312: if($param_section) { 4313: my $param_order = 0; 4314: 4315: $self->_log(" POD: Scan for named parameters in '$param_section'"); 4316: # Now parse each line that starts with $varname 4317: foreach my $line (split /\n/, $param_section) { 4318: if ($line =~ /C<\$(\w+)>\s*\((Required|Mandatory)\)/i) { 4319: $params{$1}{optional} = 0; 4320: $self->_log(" POD: $1 marked required from item header"); 4321: } 4322: 4323: # Match: $name - type (constraints), description 4324: # or: $name - type, description 4325: # or: $name - type 4326: if(($line =~ /^\s*\$(\w+)\s*-\s*(\w+)(?:\s*\(([^)]+)\))?\s*,?\s*(.*)$/i) || 4327: ($line =~ /^\s*C<\$(\w+)>\s*-\s*(\w+)(?:\s*\(([^)]+)\))?\s*,?\s*(.*)$/i)) { 4328: my ($name, $type, $constraint, $desc) = ($1, lc($2), $3, $4); 4329: 4330: # Clean up 4331: $desc =~ s/^\s+|\s+$//g if $desc; 4332: 4333: # Skip common non-parameters 4334: next if $name =~ /^(self|class|pkg|proto|klass|return|returns?)$/i; 4335: 4336: $params{$name} ||= { _source => SOURCE_POD }; 4337: 4338: # If we haven't already assigned a position from the signature, use order in Parameters section 4339: unless (exists $params{$name}{position}) { 4340: $params{$name}{position} = $param_order++; 4341: $self->_log(" POD: $name has position $params{$name}{position} (from Parameters order)"); 4342: } 4343: 4344: # Normalize type names 4345: $type = 'integer' if $type eq 'int'; 4346: $type = 'number' if $type eq 'num' || $type eq 'float'; 4347: $type = 'boolean' if $type eq 'bool'; 4348: $type = 'arrayref' if $type eq 'array'; 4349: $type = 'hashref' if $type eq 'hash'; 4350: 4351: $params{$name}{type} = $type; 4352: 4353: # Parse constraints 4354: if($constraint) { 4355: $self->_parse_constraints($params{$name}, $constraint); 4356: } 4357: 4358: # Check for optional/required in description OR constraint.Mutants (Total: 2, Killed: 1, Survived: 1)
- NUM_BOUNDARY_4311_27_!=: Numeric boundary flip == to !=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );4359: # Use word boundaries to avoid matching "optionally" as "optional". 4360: my $full_text = ($constraint || '') . ' ' . ($desc || '');Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_4358_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes4361: if ($full_text =~ /\boptional\b/i) { 4362: $params{$name}{optional} = 1; 4363: $self->_log(" POD: $name marked as optional"); 4364: } elsif ($full_text =~ /required|mandatory/i) { 4365: $params{$name}{optional} = 0; 4366: $self->_log(" POD: $name marked as required");Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_4360_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes4367: } 4368:Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_4366_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes4369: # Detect semantic types: 4370: if ($desc =~ /\b(email|url|uri|path|filename)\b/i) { 4371: # TODO: ensure properties is set to 1 in $config 4372: carp('Manually set config->properties to 1 in ', $self->{'input_file'}); 4373: $params{$name}{semantic} = lc($1); 4374: } 4375: 4376: # Look for regex patternsMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_4368_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
4377: if ($desc && $desc =~ m{matches?\s+(/[^/]+/|qr/.+?/)}i) { 4378: $params{$name}{matches} = $1; 4379: $params{$name}{_source} = SOURCE_POD; # documentation, not a check 4380: } 4381:
4382: if(my $values = $self->_prose_memberof($desc)) { 4383: $params{$name}{memberof} = $values; 4384: $params{$name}{_source} = SOURCE_POD; # documentation, not a checkMutants (Total: 4, Killed: 0, Survived: 4)
- NUM_BOUNDARY_4381_38_>: Numeric boundary flip >= to >
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_4381_38_<: Numeric boundary flip >= to <
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_4381_38_<=: Numeric boundary flip >= to <=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- COND_INV_4381_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
4385: $self->_log(" POD: $name memberof from prose: " . join(', ', @{$values})); 4386: } 4387: 4388: $self->_log(" POD: Found parameter '$name' in parameters section, type=$type" . 4389: ($constraint ? " ($constraint)" : '') . 4390: ($desc ? " - $desc" : ''));
4391: } 4392: } 4393: } 4394: 4395: # Pattern 2: Also try the inline format in case Parameters: section wasn't found ●4396 → 4396 → 4457 4396: while ($pod =~ /\$(\w+)\s*-\s*(string|integer|int|number|num|float|boolean|bool|arrayref|array|hashref|hash|object|any)(?:\s*\(([^)]+)\))?\s*,?\s*(.*)$/gim) {Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_4390_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes4397: my ($name, $type, $constraint, $desc) = ($1, lc($2), $3, $4); 4398: 4399: # Only process if we haven't already found this param in the Parameters section 4400: next if exists $params{$name}; 4401: 4402: # Clean up description - remove leading/trailing whitespace 4403: $desc =~ s/^\s+|\s+$//g if $desc; 4404:Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_4396_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
4405: # Skip common words that aren't parameters
Mutants (Total: 1, Killed: 1, Survived: 0)
4406: next if $name =~ /^(self|class|pkg|proto|klass|return|returns?)$/i; 4407: 4408: $params{$name} ||= { _source => SOURCE_POD }; 4409:
4410: # Normalize type names 4411: $type = 'integer' if $type eq 'int'; 4412: $type = 'number' if $type eq 'num' || $type eq 'float'; 4413: $type = 'boolean' if $type eq 'bool'; 4414: $type = 'arrayref' if $type eq 'array'; 4415: $type = 'hashref' if $type eq 'hash'; 4416: 4417: $params{$name}{type} = $type;Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_4409_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes4418:Mutants (Total: 4, Killed: 1, Survived: 3)
- NUM_BOUNDARY_4417_20_>: Numeric boundary flip >= to >
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_4417_20_<: Numeric boundary flip >= to <
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_4417_20_<=: Numeric boundary flip >= to <=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );Mutants (Total: 1, Killed: 1, Survived: 0)
4419: # Parse constraints 4420: if ($constraint) { 4421: $self->_parse_constraints($params{$name}, $constraint); 4422: } 4423: 4424: # Check for optional/required in description. 4425: # Use word boundaries to avoid matching "optionally" as "optional". 4426: if ($desc) { 4427: if ($desc =~ /\boptional\b/i) { 4428: $params{$name}{optional} = 1; 4429: } elsif ($desc =~ /required|mandatory/i) { 4430: $params{$name}{optional} = 0; 4431: } 4432: 4433: # Look for regex patterns in description 4434: if ($desc =~ m{matches?\s+(/[^/]+/|qr/.+?/)}i) { 4435: $params{$name}{matches} = $1; 4436: } 4437: } 4438: 4439: if(my $values = $self->_prose_memberof($desc)) { 4440: $params{$name}{memberof} = $values; 4441: $params{$name}{_source} = SOURCE_POD; # documentation, not a check 4442: $self->_log(" POD: $name memberof from prose: " . join(', ', @{$values})); 4443: } 4444: 4445: $self->_log(" POD: Found parameter '$name' in the inline documentation, type=$type" . 4446: ($constraint ? " ($constraint)" : '')); 4447: } 4448: 4449: # Pattern 3: Parse =over /=item list of arguments, e.g. `=item * C<$name>`. 4450: # The sigil is required here: `=item * C<field>` without one usually 4451: # documents a returned key or an internal field, not an argument.
Mutants (Total: 1, Killed: 1, Survived: 0)
4452: # 4453: # Inside an Arguments section the sigil is optional: some modules write 4454: # `=item * C<mutation_results>` for a real argument. Add the sigil for 4455: # those items only, so a Returns list elsewhere still cannot name an 4456: # argument.
●4457 → 4470 → 4550 4457: my $item_pod = $pod; 4458: $item_pod =~ s{ 4459: (?:^=head[2-6]\s+arguments?\b) 4460: (.*?)Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_4456_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
4461: (?=^=head[1-6]\b|\z) 4462: }{ 4463: my $section = $&; 4464: $section =~ s{^=item(\s+\*\s*)C<\s*([A-Za-z_]\w*)\s*>}{ 4465: '=item' . $1 . 'C<$' . $2 . '>' 4466: }gme; 4467: $section; 4468: }msgeix; 4469: 4470: while ($item_pod =~ /=item\s+(?:\*\s*)?(?:C<)?\$(\w+)\b(?:>)?\s*(?:-.*)?\n?(.*?)(?==item|\=back|\=head)/sig) { 4471: my $name = $1; 4472: my $desc = $2; 4473: 4474: # Never allow empty or undefined parameter names 4475: next unless defined $name && length $name; 4476: 4477: $desc =~ s/^\s+|\s+$//g; 4478: 4479: # Skip common non-parameters 4480: next if $name =~ /^(self|class|pkg|proto|klass|return|returns?)$/i; 4481: 4482: $params{$name} ||= { _source => SOURCE_POD }; 4483: 4484: # Explicit typed form only: 4485: # $param - type (constraints) 4486: if ($desc =~ /^\s*(string|integer|int|number|num|float|boolean|bool|array|arrayref|hash|hashref|any)\b(?:\s*\(([^)]+)\))?/i) { 4487: my $type = lc($1); 4488: my $constraint = $2; 4489:
Mutants (Total: 1, Killed: 1, Survived: 0)
4490: # Normalize type names 4491: $type = 'integer' if $type eq 'int'; 4492: $type = 'number' if $type eq 'num' || $type eq 'float'; 4493: $type = 'boolean' if $type eq 'bool'; 4494: $type = 'arrayref' if $type eq 'array'; 4495: $type = 'hashref' if $type eq 'hash'; 4496: 4497: $params{$name}{type} = $type; 4498:
Mutants (Total: 1, Killed: 1, Survived: 0)
4499: if ($constraint) { 4500: $self->_parse_constraints($params{$name}, $constraint); 4501: } 4502: 4503: $self->_log(" POD: Explicit type '$type' for $name"); 4504: } else { 4505: # Heuristic inference from description text 4506: if ($desc =~ /\bstring\b/i) { 4507: $params{$name}{type} = 'string';
Mutants (Total: 4, Killed: 4, Survived: 0)
4508: } elsif ($desc =~ /\b(int|integer)\b/i) { 4509: $params{$name}{type} = 'integer';
Mutants (Total: 1, Killed: 1, Survived: 0)
4510: } elsif ($desc =~ /\b(num|number|float)\b/i) { 4511: $params{$name}{type} = 'number'; 4512: } elsif ($desc =~ /\b(bool|boolean)\b/i) { 4513: $params{$name}{type} = 'boolean'; 4514: } elsif ($desc =~ /\bhashref\b/i) { 4515: # "either a path or an already decoded hashref": the harness 4516: # can build a hashref, so prefer it over the default string. 4517: $params{$name}{type} = 'hashref'; 4518: } 4519: } 4520: 4521: # Check for optional/required in description. 4522: # Use word boundaries to avoid matching "optionally" as "optional". 4523: # Ignore code spans: a description that mentions the parameter name 4524: # C<optional> (CoverageGuidedFuzzer's schema) is not saying the 4525: # parameter itself is optional, and can still say "Required." 4526: my $optionality_text = $desc; 4527: $optionality_text =~ s/\b[CBIL]<[^>]*>//g; 4528: if ($optionality_text =~ /\boptional\b/i) { 4529: $params{$name}{optional} = 1; 4530: } elsif ($optionality_text =~ /\b(?:required|mandatory)\b/i) { 4531: $params{$name}{optional} = 0; 4532: } 4533: 4534: # Look for regex patterns 4535: if ($desc =~ m{matches?\s+(/[^/]+/|qr/.+?/)}i) { 4536: $params{$name}{matches} = $1; 4537: $params{$name}{_source} = SOURCE_POD; # documentation, not a check 4538: } 4539: 4540: if(my $values = $self->_prose_memberof($desc)) { 4541: $params{$name}{memberof} = $values; 4542: $params{$name}{_source} = SOURCE_POD; # documentation, not a check 4543: $self->_log(" POD: $name memberof from prose: " . join(', ', @{$values})); 4544: } 4545: 4546: $self->_log(" POD: Found parameter '$name' from =item list"); 4547: } 4548: 4549: # Extract default values from POD ●4550 → 4551 → 4563 4550: my $pod_defaults = $self->_extract_defaults_from_pod($pod); 4551: foreach my $param (keys %$pod_defaults) { 4552: if (exists $params{$param}) { 4553: $params{$param}{_default} = $pod_defaults->{$param}; 4554: $params{$param}{optional} = 1 unless defined $params{$param}{optional}; 4555: $self->_log(sprintf(" POD: %s has default value: %s", 4556: $param,
4557: defined($pod_defaults->{$param}) ? $pod_defaults->{$param} : 'undef' 4558: )); 4559: } 4560: } 4561: 4562: # Default undocumented optionality: documented params are REQUIRED unless stated otherwise ●4563 → 4563 → 4578 4563: for my $name (keys %params) { 4564: next if $name =~ /^(self|class|pkg|proto|klass)$/i; 4565: 4566: # TODO: if optionality was never explicitly set, assume required. 4567: # Currently disabled as it breaks some schemas â revisit in a future pass. 4568: # if (!exists $params{$name}{optional}) { 4569: # $params{$name}{optional} = 0; 4570: # $self->_log(" POD: $name assumed required (no optional/default specified)"); 4571: # } 4572: } 4573: 4574: # Pattern 0: =head3|4 Input formal spec â highest-priority type source. 4575: # Runs last so positional matching can use positions set by earlier patterns. 4576: # Accepts positional array format: [ {type=>'...'}, ... ] 4577: # and named hash format: { name => {type=>'...'}, ... } ●4578 → 4578 → 4695 4578: if ($pod =~ /=head[34]\s+Input\b(.*?)(?==head|\z)/si) { 4579: my $block = $1; 4580: $block =~ s/\A\s+//;Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_4556_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
4581: # The spec may follow introductory prose and comment lines: start at 4582: # the first line that opens the structure. 4583: $block =~ s/\A.*?^[ \t]+(?=[\[\{])//ms unless($block =~ /\A[\[\{]/); 4584: 4585: if ($block =~ /\A\[/) { 4586: # Positional format: each {â¦} maps to the param at that array index. 4587: my $idx = 0; 4588: while ($block =~ /\{([^}]*)\}/g) { 4589: my $spec = $1; 4590: my ($name) = grep { ($params{$_}{position} // -1) == $idx } 4591: keys %params; 4592: if (defined $name) { 4593: $params{$name}{_source} = SOURCE_INPUT_SPEC;
Mutants (Total: 5, Killed: 5, Survived: 0)
4594: if (my $t = $self->_map_formal_input_type($spec)) { 4595: $params{$name}{type} = $t; 4596: $self->_log(" POD: $name type '$t' from =head Input (positional $idx)"); 4597: }
Mutants (Total: 7, Killed: 7, Survived: 0)
4598: if(defined(my $opt = _spec_optionality($spec))) { 4599: $params{$name}{optional} = $opt; 4600: } 4601: }
Mutants (Total: 1, Killed: 1, Survived: 0)
4602: $idx++; 4603: } 4604: } elsif ($block =~ /\A\{/) { 4605: # Named format: each 'name => {â¦}' entry maps directly by name. 4606: while ($block =~ /\b(\w+)\s*=>\s*\{([^}]*)\}/g) { 4607: my ($name, $spec) = ($1, $2); 4608: next if $name =~ /^(self|class|pkg|proto|klass)$/i; 4609: $params{$name} //= { _source => SOURCE_INPUT_SPEC }; 4610: $params{$name}{_source} = SOURCE_INPUT_SPEC; 4611: if (my $t = $self->_map_formal_input_type($spec)) { 4612: $params{$name}{type} = $t; 4613: $self->_log(" POD: $name type '$t' from =head Input (named)"); 4614: } 4615: if(defined(my $opt = _spec_optionality($spec))) { 4616: $params{$name}{optional} = $opt; 4617: } 4618: if ($spec =~ /\bmemberof\s*=>\s*\[([^\]]*)\]/i) { 4619: my $list_str = $1; 4620: my @vals; 4621: while ($list_str =~ /['"]([^'"]*)['"]/g) { 4622: push @vals, $1; 4623: } 4624: if(@vals) { 4625: $params{$name}{memberof} = \@vals; 4626: # The list is documentation: the code may accept more. 4627: $params{$name}{_source} = SOURCE_INPUT_SPEC; 4628: } 4629: } 4630: if ($spec =~ /\bmin\s*=>\s*(\d+)/i) { 4631: $params{$name}{min} = $1 + 0; 4632: } 4633: if ($spec =~ /\bmax\s*=>\s*(\d+)/i) { 4634: $params{$name}{max} = $1 + 0; 4635: } 4636: # A documented size is a claim about valid input, not a check 4637: # the routine has been seen to make: NameCase's spec says 4638: # min => 1 while its code accepts []. The harness still uses 4639: # the bound to build valid data, but generates no outside case. 4640: if(exists($params{$name}{min}) || exists($params{$name}{max})) { 4641: $params{$name}{_source} = SOURCE_INPUT_SPEC; 4642: } 4643: if ($spec =~ /\bisa\s*=>\s*['"]([^'"]+)['"]/i) { 4644: $params{$name}{isa} = $1; 4645: }
Mutants (Total: 4, Killed: 4, Survived: 0)
4646: } 4647: # Two or more documented names signal a hash/named API, and 4648: # positional info from signature analysis is then not meaningful:
4649: # it causes "param X missing position" errors when params are 4650: # mixed. A lone name may instead label the first positional 4651: # argument, which _positional_pod_input decides once the body is 4652: # known. 4653: delete $params{$_}{position} for keys %params;Mutants (Total: 4, Killed: 1, Survived: 3)
- NUM_BOUNDARY_4648_14_>: Numeric boundary flip >= to >
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_4648_14_<: Numeric boundary flip >= to <
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_4648_14_<=: Numeric boundary flip >= to <=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );Mutants (Total: 1, Killed: 1, Survived: 0)
4654: } 4655: 4656: # A human-readable table names each parameter once, as 4657: # `lat : number -90 .. 90` or `$path SCALAR a readable .json file`. 4658: # It is a formal specification like the structures above, so the type 4659: # it gives is documented rather than a check the code was seen to make. 4660: $self->_apply_pod_input_table($block, \%params, $routine); 4661: 4662: # Some input specs are a bare list of `name => { ... }` entries with no 4663: # outer braces, as Database::Join's new() has. Parsing the whole bare 4664: # list would read unrelated examples in the block, so only the 4665: # unambiguous required flag is taken from it; the parameter itself is 4666: # described by the validator, signature or prose. A structured spec 4667: # was read above, and only top-level entries count: a nested 4668: # properties entry's required flag belongs to that property. 4669: unless($block =~ /\A[\[\{]/) { 4670: for my $entry (_top_level_hash_entries($block)) { 4671: my ($bare_name, $bare_spec) = @{$entry}; 4672: next if $bare_name =~ /^(self|class|pkg|proto|klass)$/i; 4673: my $own = _own_spec_text($bare_spec); 4674: next unless $own =~ /\brequired\s*=>\s*(0|1)/i; 4675: next if $own =~ /\boptional\s*=>\s*(?:0|1)/i; 4676: $params{$bare_name} //= { _source => SOURCE_INPUT_SPEC }; 4677: $params{$bare_name}{optional} = 1 - ($1 + 0); 4678: 4679: # The comment lines under the entry describe its shape. 4680: my ($desc) = $block =~ /(?:^|\n)[ \t]*\Q$bare_name\E\s*=>[^\n]*(?:\n[ \t]+[^\n#][^\n]*)*\n((?:[ \t]*#[^\n]*(?:\n|\z))+)/; 4681: my ($bare_type) = $own =~ /\btype\s*=>\s*'?(\w+)/; 4682: if(my $shape = _pod_nested_input_shape($bare_type // '', $desc)) { 4683: $params{$bare_name}{schema} = $shape; 4684: } 4685: } 4686: } 4687: } 4688: 4689: # Documented value lists in =item prose, e.g. 4690: # =item * C<$colour> - one of red, green or blue 4691: # Run after the formal =head Input spec, which can be the only place a 4692: # parameter is named (strict_pod is such a parameter): the prose list 4693: # then still reaches it. Only parameters already found are updated: 4694: # a Returns section also uses =item, and its entries are outputs. ●4695 → 4695 → 4707 4695: while ($pod =~ /=item\s+(?:\*\s*)?(?:C<\$?(\w+)>|\$(\w+))\s*-?\s*((?:[^\n]*\n)*?)(?==item|\=back|\=head)/gi) { 4696: my ($name, $text) = ($1 // $2, $3); 4697: next unless $params{$name}; 4698: next if defined($params{$name}{memberof}); 4699: 4700: if(my $values = $self->_prose_memberof($text)) { 4701: $params{$name}{memberof} = $values; 4702: $params{$name}{_source} = SOURCE_POD; # documentation, not a check 4703: $self->_log(" POD: $name memberof from prose: " . join(', ', @{$values})); 4704: } 4705: } 4706: 4707: $self->_sanitize_parameter_names(\%params, 'POD analysis'); 4708: return \%params;
Mutants (Total: 1, Killed: 1, Survived: 0)
4709: } 4710: 4711: # -------------------------------------------------- 4712: # _map_formal_input_type 4713: # 4714: # Purpose: Extract and normalise the type string 4715: # from a parameter spec fragment such as 4716: # "type => 'scalar | scalarref'". 4717: # Handles union types by returning the 4718: # canonical ATG type for the first
4719: # recognised alternative. 4720: # 4721: # Entry: $spec - text content of a { } block 4722: # from a =head3|4 Input spec. 4723: # 4724: # Exit: Canonical type string, or undef when 4725: # no 'type' key is present or the valueMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_4718_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 4, Killed: 4, Survived: 0)
4726: # is not a recognised type name. 4727: # -------------------------------------------------- 4728: sub _map_formal_input_type { ●4729 → 4758 → 4761 4729: my ($self, $spec) = @_; 4730: # Accept both quoted type => 'scalar' and unquoted Params::Validate 4731: # constants type => OBJECT (no quotes around the constant name).
Mutants (Total: 1, Killed: 1, Survived: 0)
4732: return undef unless $spec =~ /\btype\s*=>\s*(?:['"]([^'"]+)['"]|([A-Z_]+))/i; 4733: my $raw = lc(defined($1) ? $1 : $2);
Mutants (Total: 1, Killed: 1, Survived: 0)
4734: $raw =~ s/\s+//g; 4735: 4736: my %map = ( 4737: scalar => 'string', 4738: scalarref => 'string', 4739: str => 'string', 4740: string => 'string', 4741: int => 'integer', 4742: integer => 'integer', 4743: num => 'number', 4744: number => 'number',
Mutants (Total: 4, Killed: 4, Survived: 0)
4745: float => 'number', 4746: bool => 'boolean', 4747: boolean => 'boolean', 4748: array => 'arrayref', 4749: arrayref => 'arrayref', 4750: hash => 'hashref',
Mutants (Total: 1, Killed: 1, Survived: 0)
4751: hashref => 'hashref', 4752: object => 'object', 4753: any => 'any', 4754: undef => 'undef',
Mutants (Total: 1, Killed: 1, Survived: 0)
4755: coderef => 'coderef', 4756: ); 4757: 4758: for my $t (split /\|/, $raw) { 4759: return $map{$t} if exists $map{$t}; 4760: } 4761: return undef; 4762: } 4763: 4764: # -------------------------------------------------- 4765: # _apply_pod_input_table 4766: # 4767: # Purpose: Read a =head3|4 Input section written as a table, one 4768: # `name : type ...` (or `$name SCALAR ...`) line per parameter,
4769: # and record the type each one documents. 4770: # 4771: # Entry: $block - text of the Input section. 4772: # $params - parameters found so far; updated in place. 4773: # 4774: # Exit: Returns the number of parameters the table describes. 4775: # 4776: # Notes: The table is a formal input specification, so its type is 4777: # documented: the harness builds valid data from it instead of 4778: # expecting a wrong-typed value to die. A range in the entry, 4779: # such as `-90 .. 90`, is a documented bound, and "optional" or 4780: # "default" makes the parameter optional. 4781: # -------------------------------------------------- 4782: # -------------------------------------------------- 4783: # _pod_documents_class_invocant 4784: # 4785: # Purpose: Say whether a method's POD INPUT section documents a $class 4786: # invocant, which makes the routine a class method. 4787: # 4788: # Entry: $pod - the method's POD text. 4789: # 4790: # Exit: Returns 1 when the INPUT section names $class, 0 otherwise. 4791: # -------------------------------------------------- 4792: sub _pod_documents_class_invocant { 4793: my ($self, $pod) = @_; 4794: 4795: return 0 unless defined($pod) && length($pod); 4796: return 0 unless $pod =~ /=head[34]\s+Input\b(.*?)(?==head|\z)/si; 4797: 4798: # `$class SCALAR the class (called as a class method)` and 4799: # `class : SCALAR` are both written this way. 4800: return (($1 =~ /^\s*\$?class\b/mi) ? 1 : 0); 4801: } 4802: 4803: # -------------------------------------------------- 4804: # _strip_literals 4805: #Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_4768_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
4806: # Purpose: Remove quoted strings and regex literals from a code fragment 4807: # before looking for arithmetic operators in it. A '-' in 4808: # 'Period-over-period', a '%' in sprintf '%04d', or a '/' in 4809: # /[0-9%]/ is text, not arithmetic, and reading it as an operator 4810: # typed string arguments and string-returning routines as numbers.
Mutants (Total: 1, Killed: 1, Survived: 0)
4811: # 4812: # Entry: $code - source fragment (a parameter body or a return value). 4813: # 4814: # Exit: The fragment with each quoted string and regex literal body 4815: # emptied. Undef is treated as an empty fragment. 4816: # -------------------------------------------------- 4817: sub _strip_literals { 4818: my ($code) = @_; 4819:
Mutants (Total: 4, Killed: 4, Survived: 0)
4820: return '' unless defined($code); 4821: 4822: $code =~ s/'(?:\\.|[^'\\])*'/''/g; 4823: $code =~ s/"(?:\\.|[^"\\])*"/""/g; 4824: 4825: # m{...}, qr{...} and s{...}{...}, which a '/' pattern would miss.
Mutants (Total: 1, Killed: 1, Survived: 0)
4826: $code =~ s{\b(?:qr|m|s|tr|y)\s*\{(?:\\.|[^{}\\]|\{[^{}]*\})*\} 4827: (?:\s*[a-z]*\s*\{(?:\\.|[^{}\\]|\{[^{}]*\})*\})?}{''}gx; 4828: $code =~ s{\b(?:qr|m|s|tr|y)\s*/(?:\\.|[^/\\])*/}{''}g; 4829: $code =~ s{([=!]~\s*)/(?:\\.|[^/\\])*/}{"$1"}g; 4830:
Mutants (Total: 1, Killed: 1, Survived: 0)
4831: return $code; 4832: } 4833: 4834: # -------------------------------------------------- 4835: # _strip_comments
Mutants (Total: 1, Killed: 1, Survived: 0)
4836: # 4837: # Purpose: Remove Perl comments from a code fragment before it is scanned 4838: # for parameters. A comment may quote an example signature; 4839: # reading it as code invents parameters the routine does not take 4840: # (an example in extract_all() once added $password to its schema).
Mutants (Total: 1, Killed: 1, Survived: 0)
4841: # 4842: # Entry: $code - source fragment (a method body). 4843: # $node - optional PPI node for the same code. When given, its 4844: # token stream is used, so a '#' inside a quoted string 4845: # is kept.
Mutants (Total: 1, Killed: 1, Survived: 0)
4846: # 4847: # Exit: The fragment with each comment removed. Undef is treated as an 4848: # empty fragment. 4849: # -------------------------------------------------- 4850: sub _strip_comments {
Mutants (Total: 1, Killed: 1, Survived: 0)
●4851 → 4855 → 4862 4851: my ($code, $node) = @_; 4852: 4853: return '' unless defined($code); 4854: 4855: if($node && $node->can('tokens')) { 4856: return join '', map {
Mutants (Total: 1, Killed: 1, Survived: 0)
4857: $_->isa('PPI::Token::Comment') ? '' : $_->content 4858: } $node->tokens; 4859: } 4860: 4861: # No PPI node (a synthesized class method): fall back to line comments.
Mutants (Total: 1, Killed: 1, Survived: 0)
4862: $code =~ s/[ \t]*\#[^\n]*//g; 4863: return $code; 4864: } 4865:
Mutants (Total: 1, Killed: 1, Survived: 0)
4866: # -------------------------------------------------- 4867: # _pod_input_prose_type 4868: # 4869: # Purpose: Name the type a one-line description of an input value gives, 4870: # for the `$value # string` form of an Input table.
Mutants (Total: 1, Killed: 1, Survived: 0)
4871: # 4872: # Entry: $text - the description after the '#'. 4873: # 4874: # Exit: Canonical type string, or undef when it names none.
Mutants (Total: 1, Killed: 1, Survived: 0)
4875: # -------------------------------------------------- 4876: sub _pod_input_prose_type { 4877: my ($text) = @_; 4878: 4879: return undef unless defined($text); 4880: return 'arrayref' if $text =~ /\barrayref\b|\barray\s+of\b|\blist\s+of\b/i; 4881: return 'hashref' if $text =~ /\bhashref\b|\bhash\s+of\b/i; 4882: return 'boolean' if $text =~ /\bboolean\b|\bbool\b/i; 4883: return 'integer' if $text =~ /\binteger\b|\bint\b/i; 4884: return 'number' if $text =~ /\bnumber\b|\bfloat\b/i; 4885: return 'string' if $text =~ /\bstring\b|\btext\b/i; 4886: return undef; 4887: } 4888: 4889: # -------------------------------------------------- 4890: # _pod_input_hash_dump 4891: # 4892: # Purpose: Read an Input section written as the Perl 4893: # hash it documents, one outer key per 4894: # parameter: 4895: # 4896: # { 4897: # name => { type => 'string', optional => 1 }, 4898: # strategy => { type => HASHREF, optional => 0 }, 4899: # } 4900: # 4901: # Only the outer keys are parameters; an inner 4902: # key describes its parameter. Lines outside 4903: # those hashes ("Valid and invalid input, by 4904: # partition:") are prose. 4905: #
Mutants (Total: 1, Killed: 1, Survived: 0)
4906: # Entry: $block - the Input section's text. 4907: # 4908: # Exit: A list of [ $name, \%fields ] in document 4909: # order, or an empty list when the section is 4910: # not a hash dump. 4911: # -------------------------------------------------- 4912: sub _pod_input_hash_dump { ●4913 → 4918 → 4938 4913: my ($block) = @_; 4914: 4915: my @rows; 4916: my ($name, $body, $depth) = (undef, '', 0); 4917: 4918: for my $line (split(/\n/, $block)) { 4919: my $added; 4920: if(!defined($name)) { 4921: next unless $line =~ /^\s*(\w+)\s*=>\s*\{(.*)$/; 4922: ($name, $body, $depth) = ($1, '', 1); 4923: $added = $2; 4924: } else { 4925: $added = $line; 4926: } 4927: 4928: $body .= ' ' . $added; 4929: $depth += ($added =~ tr/{//) - ($added =~ tr/}//); 4930: next if $depth > 0; 4931: 4932: push @rows, [ $name, _pod_input_hash_fields($body) ] if $depth == 0; 4933: undef $name; 4934: $body = ''; 4935: $depth = 0; 4936: } 4937:
4938: return @rows; 4939: } 4940:Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_4937_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes4941: sub _pod_input_hash_fields { ●4942 → 4947 → 4952 4942: my ($body) = @_; 4943: 4944: my %fields;Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_4940_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
4945: # Keys are often quoted ('type' => 'boolean'), so the quote before =>
Mutants (Total: 1, Killed: 1, Survived: 0)
4946: # belongs to the key. 4947: while($body =~ /'?(\w+)'?\s*=>\s*'?([A-Za-z0-9_:.]+)'?/g) { 4948: $fields{$1} = $2; 4949: } 4950: # An enum names the documented values; the bare-word scan above cannot 4951: # read the list, so record it separately. ●4952 → 4952 → 4957 4952: if($body =~ /\benum\s*=>\s*\[([^\]]*)\]/) { 4953: my @values = $1 =~ /['"]([^'"]+)['"]/g; 4954: $fields{enum} = \@values if(@values); 4955: } 4956: 4957: return \%fields; 4958: } 4959: 4960: # The shape of a documented nested argument, read from the comment lines 4961: # under its Input entry: "Arrayref of {col, op, val} predicate hashrefs" is 4962: # an array of hashes with those keys, and "index => criteria hashref" is a 4963: # hash whose values are hashes. A type-less element spec maps key names to 4964: # their specs, which is how the harness builds a fixed-key hash. 4965: sub _pod_nested_input_shape { ●4966 → 4971 → 4987 4966: my ($type, $desc) = @_; 4967: 4968: return undef unless(defined($type) && length($type)); 4969: return undef unless(defined($desc) && !ref($desc) && length($desc)); 4970: 4971: if(($type eq 'arrayref') && $desc =~ /\bof\s+\{([^}]+)\}/i) { 4972: my %element; 4973: for my $key ($1 =~ /(\w+)/g) { 4974: my %spec = (type => 'string'); 4975: # "op -- one of: eq, ne, ..." is the documented domain. 4976: if($desc =~ /\b\Q$key\E\s*--\s*one\s+of:\s*([^\n]+)/i) { 4977: my @values = map { s/\A\s+|\s+\z//gr } split /,/, $1;
Mutants (Total: 1, Killed: 1, Survived: 0)
4978: $spec{memberof} = \@values if(@values); 4979: } 4980: $element{$key} = \%spec; 4981: } 4982: return { %element } if(%element); 4983: } 4984: 4985: # "Arrayref of insight hashrefs" (Database::BI::Summary's insights) holds 4986: # hashes, not the strings a bare arrayref would otherwise be given. ●4987 → 4987 → 4991 4987: if(($type eq 'arrayref') && $desc =~ /\bhashrefs?\b/i) { 4988: return { type => 'hashref' }; 4989: } 4990: 4991: return { type => 'hashref' } 4992: if(($type eq 'hashref') && $desc =~ /=>\s*\w+\s+hashref\b/i); 4993: 4994: return undef; 4995: } 4996: 4997: # `10_000` is the number 10000 written for a reader, not a string with 4998: # underscores in it. 4999: sub _undigitised { 5000: my ($number) = @_; 5001: 5002: return undef unless defined($number); 5003: $number =~ s/_//g; 5004: return $number + 0;
5005: }Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_5004_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes5006: 5007: sub _apply_pod_input_table { ●5008 → 5041 → 5090 5008: my ($self, $block, $params, $routine) = @_; 5009: 5010: my %types = ( 5011: scalar => 'string', 5012: str => 'string', 5013: string => 'string', 5014: int => 'integer', 5015: integer => 'integer', 5016: num => 'number', 5017: number => 'number',Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_5005_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes5018: float => 'number', 5019: bool => 'boolean', 5020: boolean => 'boolean',Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_5017_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes5021: array => 'arrayref', 5022: arrayref => 'arrayref', 5023: hash => 'hashref', 5024: hashref => 'hashref', 5025: object => 'object', 5026: coderef => 'coderef', 5027: code => 'coderef', 5028: any => 'any', 5029: ); 5030: 5031: # The section may document the interface as the Perl hash it is: 5032: # 5033: # { 5034: # name => { type => 'string', optional => 1 }, 5035: # strategy => { type => HASHREF, optional => 0 }, 5036: # } 5037: # 5038: # Its outer keys are the parameters, in order, and their type and 5039: # optionality are stated rather than inferred. Prose elsewhere in the 5040: # section is not a row. 5041: if(my @dump = _pod_input_hash_dump($block)) { 5042: my $count = 0; 5043: for my $row (@dump) { 5044: my ($name, $fields) = @{$row}; 5045: next if $name =~ /^(?:self|class|pkg|proto|klass|returns?)$/i; 5046: 5047: # A hash documents named arguments, not call order: whether the 5048: # routine takes them positionally is the code's business, so the 5049: # call positions (if any) come from its signature. 5050: my $p = $params->{$name} //= {}; 5051: 5052: if(defined($fields->{type})) { 5053: my $type = $types{lc($fields->{type})}; 5054: $p->{type} = $type if defined($type); 5055: } 5056: # A parameter the hash documents is required unless it says 5057: # otherwise, as the table parser treats a bare row. 5058: $p->{optional} = ($fields->{optional} ? 1 : 0); 5059: $p->{isa} = $fields->{isa} 5060: if defined($fields->{isa}) && $fields->{isa} !~ /\Aundef\z/i; 5061: # The documented values are the domain: a generated string outside 5062: # them is an error the routine promises to reject. 5063: $p->{memberof} = $fields->{enum} 5064: if ref($fields->{enum}) eq 'ARRAY' && @{$fields->{enum}}; 5065: $p->{min} = $fields->{min} + 0 5066: if defined($fields->{min}) && $fields->{min} =~ /\A-?\d/; 5067: $p->{max} = $fields->{max} + 0 5068: if defined($fields->{max}) && $fields->{max} =~ /\A-?\d/;Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_5020_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes5069: $p->{_source} = SOURCE_INPUT_SPEC; 5070: 5071: # The comment lines under the row describe the documented shape. 5072: # "Arrayref of {col, op, val} predicate hashrefs" fixes the element 5073: # keys (Database::Join::new's mandatory_filters), and a hashref 5074: # documented as "index => criteria hashref" holds hashrefs rather 5075: # than the strings a bare hashref would otherwise be given. 5076: my ($desc) = $block =~ /(?:^|\n)[ \t]*\Q$name\E\s*=>[^\n]*\n((?:[ \t]*#[^\n]*(?:\n|\z))+)/; 5077: if(my $shape = _pod_nested_input_shape($p->{type}, $desc)) { 5078: $p->{schema} = $shape; 5079: } 5080: 5081: $self->_log(' POD: ' . $name . ' type ' 5082: . (defined($p->{type}) ? "'$p->{type}'" : '(none)')Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_5068_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes5083: . ' from the Input hash'); 5084: $count++;Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_5082_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
5085: } 5086: 5087: return $count if $count; 5088: } 5089: ●5090 → 5101 → 5110 5090: my @found; 5091: my %row_text; 5092: 5093: # The table lists the arguments in call order, so it gives their positions. 5094: my $position = 0;
Mutants (Total: 1, Killed: 1, Survived: 0)
5095: my $row_routine; 5096: 5097: # A row can name several parameters at once: `$spec, $mtime, $size # as 5098: # for path`. Each is an argument of the routine, in this order, described 5099: # by the rest of the row, so the row is read once per name. 5100: my @lines; 5101: for my $line (split(/\n/, $block)) { 5102: if($line =~ /^(\s{0,8})(\\?[\$\@%]\w+\s*,\s*(?:\\?[\$\@%]\w+\s*,\s*)*\\?[\$\@%]\w+)\s*(.*)$/) { 5103: my ($indent, $names, $rest) = ($1, $2, $3); 5104: push @lines, map { $indent . $_ . " $rest" } ($names =~ /\\?([\$\@%]\w+)/g); 5105: } else { 5106: push @lines, $line; 5107: } 5108: } 5109: ●5110 → 5110 → 5267 5110: for my $line (@lines) {
Mutants (Total: 4, Killed: 4, Survived: 0)
5111: my ($name, $spec, $prose); 5112: 5113: # One block can document several helpers, each row prefixed with the 5114: # routine it belongs to: `compile_pattern: $pattern # string`. 5115: if($line =~ /^\s{0,8}(\w+)\s*:\s*\\?[\$\@%](\w+)\s+#\s*(\S.*)$/) { 5116: ($row_routine, $name, $spec, $prose) = ($1, $2, $3, 1); 5117: # The section's own indentation is stripped from its first line, so no 5118: # leading space is required. `$name : type`, `$name => type`, and the 5119: # sigil forms `\@rows arrayref ...` / `\%models => hashref ...` all 5120: # name a parameter and give its type; the sigil rows were previously 5121: # skipped, leaving those parameters to the inferred code types. 5122: } elsif($line =~ /^\s{0,8}\\?[\$\@%]?(\w+)\s*(?::|=>)\s*(\S.*)$/) { 5123: ($name, $spec) = ($1, $2);
Mutants (Total: 1, Killed: 1, Survived: 0)
5124: # A prose line can look like a row ("Effect: on the array 5125: # backend ..."); only a value that begins with a documented type 5126: # declares an argument. A type can be written quoted 5127: # ("'string',") or with a sigil first. 5128: (my $first = $spec) =~ s/\A['"]//; 5129: ($first) = $first =~ /\A([A-Za-z]+)/;
Mutants (Total: 1, Killed: 1, Survived: 0)
5130: next unless(defined($first) && exists($types{lc($first)})); 5131: } elsif($line =~ /^\s{0,8}\\?[\$\@%](\w+)\s+(SCALAR|ARRAYREF|HASHREF|CODEREF|CODE|OBJECT|GLOB)\b\s*,?\s*(.*)$/i) { 5132: ($name, $spec) = ($1, "$2 $3"); 5133: } elsif($line =~ /^\s*\\?[\$\@%](\w+)\s+#\s*(\S.*)$/) { 5134: # `\t$value # string`, or a wider indent under a routine's 5135: # first row: the comment describes the value. 5136: ($name, $spec, $prose) = ($1, $2, 1); 5137: } elsif($line =~ /^\s{0,8}\\?[\$\@%](\w+)\s+(\S.*)$/) { 5138: # `\@rows arrayref of hashrefs # required; ...`: the type 5139: # follows the parameter, in lower case. 5140: ($name, $spec, $prose) = ($1, $2, 1); 5141: } else { 5142: next; 5143: } 5144: 5145: # Another routine's rows are not this routine's arguments. 5146: next if defined($routine) && defined($row_routine) && $row_routine ne $routine; 5147: 5148: next if $name =~ /^(?:self|class|pkg|proto|klass|returns?)$/i; 5149:
Mutants (Total: 1, Killed: 1, Survived: 0)
5150: # A quoted type ('arrayref',) is written the same way as a bare one: 5151: # the quote belongs to the value, not to the type's name.
5152: (my $typed_spec = $spec) =~ s/\A['"]//; 5153: my ($type_word) = $typed_spec =~ /\A([A-Za-z]+)/; 5154: my $type; 5155: if($prose) { 5156: # In a comment the first word is prose, not a type: `$spec # any 5157: # spec string, or undef` documents a string, though its first word 5158: # is "any". The type is the one the description names.Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_5151_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
5159: $type = _pod_input_prose_type($spec); 5160: $type = $types{lc($type_word)} if(!defined($type) && defined($type_word)); 5161: } else { 5162: $type = defined($type_word) ? $types{lc($type_word)} : undef; 5163: $type = _pod_input_prose_type($spec) if(!defined($type) && $prose); 5164: }
Mutants (Total: 1, Killed: 1, Survived: 0)
5165: 5166: # The row documents the argument, so it exists and has this call 5167: # position even when the description names no type the extractor 5168: # recognises; the code's type then stands rather than the row 5169: # claiming a constraint it does not state. 5170: my $p = $params->{$name} //= {};
Mutants (Total: 1, Killed: 1, Survived: 0)
5171: $p->{position} = $position++ unless defined $p->{position}; 5172: $p->{type} = $type if defined($type); 5173: $p->{_source} = SOURCE_INPUT_SPEC; 5174: $row_text{$name} = $spec; 5175: 5176: # The row's own comment describes the documented shape: an arrayref 5177: # of "insight hashrefs" holds hashes rather than strings. 5178: if(my $shape = _pod_nested_input_shape($type, $spec)) {
Mutants (Total: 2, Killed: 2, Survived: 0)
5179: $p->{schema} = $shape; 5180: } 5181: 5182: if($spec =~ /\boptional\b/i || $spec =~ /\bdefault\b/i) { 5183: $p->{optional} = 1; 5184: } elsif($spec =~ /\b(?:required|mandatory)\b/i) { 5185: $p->{optional} = 0; 5186: } 5187: 5188: # `one or more` and `at least one` state the same size floor: an 5189: # empty list is the documented error, so say so rather than letting 5190: # the harness treat [] as a legal value. A list that must hold at 5191: # least one element cannot be left out either, so it is required 5192: # unless the row itself says optional. 5193: if(defined($type) && $type eq 'arrayref' && $spec =~ /\b(?:one\s+or\s+more|at\s+least\s+one|non-empty)\b/i) { 5194: $p->{min} = 1; 5195: $p->{optional} = 0 unless defined $p->{optional}; 5196: } 5197: 5198: # "a readable .json file" is a precondition on the path: the harness 5199: # has to supply an existing file, not a generated string. 5200: if(defined($type) && $type eq 'string' && $spec =~ /\b(?:readable|existing)\b[^;:]*\bfile\b/i) { 5201: $p->{semantic} = 'existing_file'; 5202: } 5203: 5204: # "an existing directory" is the same kind of precondition, for the 5205: # cache factories that stat the directory they are given. The 5206: # harness makes a temporary directory rather than guessing at a path. 5207: if(defined($type) && $type eq 'string' && $spec =~ /\bdir(?:ectory)?\b/i
Mutants (Total: 1, Killed: 1, Survived: 0)
5208: && $spec =~ /\b(?:existing|readable|writable)\b/i) { 5209: $p->{semantic} = 'directory'; 5210: } 5211: 5212: # "the SQLite file's contents" is a byte string: a wide character is 5213: # not something a byte-oriented write accepts, so the harness passes 5214: # bytes rather than text (and no BOM probe, which is text). 5215: if($name =~ /\A(?:bytes|blob)\z/i 5216: || $spec =~ /\braw\s+bytes\b|file'?s\s+contents|\bbinary\s+(?:data|contents)\b/i) { 5217: $p->{semantic} = 'bytes'; 5218: $p->{type} //= 'string'; 5219: } 5220: 5221: # A documented range, e.g. `lat : number -90 .. 90` 5222: if($spec =~ /(-?\d+(?:\.\d+)?)\s*\.\.\s*(-?\d+(?:\.\d+)?)/) { 5223: $p->{min} = $1 + 0; 5224: $p->{max} = $2 + 0; 5225: # Or with words, as Database::BI::Password documents `rounds`: 5226: # `10_000 to 100_000_000 (default 200_000)`. An underscore is a
5227: # digit separator, not part of the value.Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_5226_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
5228: } elsif($spec =~ /(-?\d[\d_]*)\s+to\s+(-?\d[\d_]*)/) { 5229: $p->{min} = _undigitised($1); 5230: $p->{max} = _undigitised($2); 5231: } 5232: 5233: # The documented default is the value the routine is meant to run 5234: # with, so a maximum far above it is a work factor: a PBKDF2 round 5235: # count near the documented maximum can take minutes per call, which
5236: # no fuzz run can afford. Only then does the default cap the valid 5237: # data; an ordinary bounded option (a port, 1 to 65535 with defaultMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_5235_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
5238: # 8080) must still be generated across its whole range, so the cap 5239: # needs the maximum to be at least ten times the default (and a 5240: # positive default, so a flag whose default is 0 is not pinned at 0). 5241: # max stays the documented bound either way, so a value above it is 5242: # still probed. 5243: if(defined($type) && ($type =~ /\A(?:integer|number)\z/) 5244: && $spec =~ /\bdefault\b\s*\(?\s*(-?\d[\d_]*)/i) { 5245: my $default = _undigitised($1); 5246: $p->{default} = $default; 5247: $p->{sample_max} = $default 5248: if defined($p->{max}) && ($default > 0) 5249: && ($p->{max} >= 10 * $default)
Mutants (Total: 1, Killed: 1, Survived: 0)
5250: && (!defined($p->{min}) || ($default >= $p->{min})); 5251: } 5252: 5253: if(my $values = $self->_prose_memberof($spec)) { 5254: $p->{memberof} = $values; 5255: } 5256:
Mutants (Total: 1, Killed: 1, Survived: 0)
5257: $self->_log(' POD: ' . $name . ' type ' . (defined($type) ? "'$type'" : '(none)') 5258: . ' from the Input table'); 5259: push @found, $name; 5260: } 5261: 5262: # A nested "Measure hashref keys:" block documents the shape of the 5263: # hashrefs an arrayref argument holds. Without it the harness invents a 5264: # string element, which the routine rightly rejects; with it the 5265: # documented keys, their allowed values and their patterns are what the 5266: # harness builds. ●5267 → 5267 → 5316 5267: if($block =~ /^(\w+)\s+hashref\s+keys\s*:\s*\n(.*?)(?=\n\s*\n|\z)/msi) { 5268: my ($kind, $rows) = ($1, $2); 5269: my (%element, %alternation); 5270: for my $line (split /\n/, $rows) { 5271: next unless($line =~ /^\s{0,8}(\w+)\s*=>\s*(\S.*)$/); 5272: my ($key, $text) = ($1, $2); 5273: # A key another key's description makes conditional on the 5274: # function ("required for all functions except bare count") is 5275: # left out: the element is built for the function that needs no 5276: # further column. 5277: next if($text =~ /\brequired\b[^;]*\bexcept\b/i); 5278: my %spec = (type => 'string'); 5279: if($text =~ /\(([^)]*\|[^)]*)\)/) { 5280: my @values = map { s/\A\s+|\s+\z//gr } split /\|/, $1; 5281: $spec{memberof} = \@values if(@values); 5282: $alternation{$key} = \@values; 5283: } 5284: if($text =~ /match(?:es)?\s+C?<\s*\/(.*?)\/\s*>/) { 5285: $spec{matches} = $1; 5286: } 5287: $element{$key} = \%spec; 5288: } 5289: 5290: # The description says which listed function needs no further key; 5291: # build the element for that one. 5292: if(my ($except) = $rows =~ /\bexcept\s+(?:bare\s+)?(\w+)/i) { 5293: for my $key (keys %alternation) { 5294: next unless(grep { $_ eq $except } @{$alternation{$key}}); 5295: $element{$key}{memberof} = [ $except ]; 5296: } 5297: } 5298: 5299: if(%element) { 5300: for my $name (keys %{$params}) { 5301: my $p = $params->{$name}; 5302: next unless(($p->{_source} // '') eq SOURCE_INPUT_SPEC); 5303: next unless((($p->{type} // '') =~ /^array/)); 5304: next unless(defined($row_text{$name}) 5305: && $row_text{$name} =~ /arrayref\s+of\s+\Q$kind\E\s+hashrefs/i); 5306: $p->{schema} = { %element }; 5307: } 5308: } 5309: } 5310: 5311: # A section documenting "Reserved keys extracted before the rest is treated 5312: # as WHERE criteria" describes a variadic named API (Database::Join's 5313: # aggregate): only the key it marks required is required, and an optional 5314: # reference it gives no element shape for cannot be built validly, so it 5315: # is left out rather than fuzzed with invented contents. ●5316 → 5316 → 5332 5316: if($block =~ /\bReserved keys\b/i) { 5317: for my $name (keys %{$params}) { 5318: my $p = $params->{$name}; 5319: next unless(($p->{_source} // '') eq SOURCE_INPUT_SPEC); 5320: 5321: $p->{optional} = 1 unless(defined($p->{optional}) && !$p->{optional}); 5322: 5323: my $type = $p->{type} // ''; 5324: next unless(($type eq 'arrayref') || ($type eq 'array') || ($type eq 'hashref')); 5325: next if(ref($p->{schema}) eq 'HASH'); 5326: next if(ref($p->{memberof}) eq 'ARRAY' && @{$p->{memberof}}); 5327: 5328: delete $params->{$name} if($p->{optional}); 5329: } 5330: } 5331: 5332: return scalar @found; 5333: } 5334: 5335: # -------------------------------------------------- 5336: # _analyze_output 5337: # 5338: # Purpose: Orchestrate analysis of a method's 5339: # return value by combining POD return 5340: # section parsing, code return statement 5341: # analysis, boolean detection, context 5342: # detection, void detection, chaining 5343: # detection, and error convention 5344: # detection. 5345: # 5346: # Entry: $pod - POD string for the method. 5347: # $code - method body source string. 5348: # $method_name - name of the method being 5349: # analysed, used for 5350: # boolean heuristics. 5351: # 5352: # Exit: Returns a hashref describing the 5353: # output type and behaviour, or an empty 5354: # hashref if nothing could be determined. 5355: # Keys include: type, value, isa, and 5356: # various _* metadata keys. 5357: # 5358: # Side effects: Logs progress to stdout when
Mutants (Total: 1, Killed: 1, Survived: 0)
5359: # verbose is set. 5360: # -------------------------------------------------- 5361: sub _analyze_output { 5362: my ($self, $pod, $code, $method_name) = @_; 5363: 5364: my %output; 5365: 5366: $self->_analyze_output_from_pod(\%output, $pod); 5367: $self->_analyze_output_from_code(\%output, $code, $method_name);
Mutants (Total: 1, Killed: 1, Survived: 0)
5368: $self->_enhance_boolean_detection(\%output, $pod, $code, $method_name); 5369: $self->_detect_list_context(\%output, $code); 5370: $self->_detect_void_context(\%output, $code, $method_name); 5371: $self->_detect_chaining_pattern(\%output, $code); 5372: $self->_detect_error_conventions(\%output, $code); 5373: 5374: $self->_validate_output(\%output) if keys %output; 5375: 5376: # Don't return empty output
Mutants (Total: 1, Killed: 1, Survived: 0)
5377: return (keys %output) ? \%output : {}; 5378: } 5379: 5380: # -------------------------------------------------- 5381: # _analyze_output_from_pod 5382: # 5383: # Purpose: Parse the POD documentation for a 5384: # method's return value and populate 5385: # an output hashref with type, value, 5386: # and behaviour information.
Mutants (Total: 1, Killed: 1, Survived: 0)
5387: # 5388: # Entry: $output - hashref to populate 5389: # (modified in place). 5390: # $pod - POD string for the method. 5391: # 5392: # Exit: Returns nothing. Modifies $output 5393: # in place. 5394: # 5395: # Side effects: Logs detections to stdout when
Mutants (Total: 1, Killed: 1, Survived: 0)
5396: # verbose is set. 5397: # 5398: # Notes: Two patterns are tried: (1) a 5399: # 'Returns:' section of up to 3 lines, 5400: # and (2) an inline 'returns X' phrase. 5401: # The section pattern takes precedence. 5402: # -------------------------------------------------- 5403: sub _analyze_output_from_pod { ●5404 → 5408 → 0 5404: my ($self, $output, $pod) = @_;
Mutants (Total: 1, Killed: 1, Survived: 0)
5405: my %VALID_OUTPUT_TYPES = map { $_ => 1 } 5406: qw(string integer number float boolean arrayref hashref object coderef void undef); 5407: 5408: if ($pod) { 5409: # Pattern 0: =head4 Output formal spec (highest priority â explicit over heuristic) 5410: # The outer container shape determines the return type: 5411: # (...) â list/array of items 5412: # [...] â arrayref (bare [] = empty/void, skip) 5413: # {...} â hashref spec; look for type => inside, or isa => for object 5414: if($pod =~ /=head4\s+Output\b(.*?)(?==head|\z)/si) { 5415: my $block = $1;
Mutants (Total: 1, Killed: 1, Survived: 0)
5416: $block =~ s/^\s+//; 5417: if($block =~ /^\(/) { 5418: $output->{type} = 'array'; 5419: $self->_log(" OUTPUT: type 'array' from =head4 Output list notation"); 5420: } elsif($block =~ /^\[/) { 5421: unless($block =~ /^\[\s*\]/) { 5422: $output->{type} = 'arrayref'; 5423: $self->_log(" OUTPUT: type 'arrayref' from =head4 Output arrayref notation"); 5424: } 5425: } elsif($block =~ /^\{/) { 5426: if($block =~ /type\s*=>\s*['"]?(\w[\w:]*?)['"]?\s*[,}]/i) { 5427: my $type = lc($1); 5428: $type = 'string' if $type eq 'scalar' || $type eq 'scalarref' || $type eq 'str'; 5429: $type = 'integer' if $type eq 'int'; 5430: $type = 'number' if $type eq 'float' || $type eq 'num'; 5431: $type = 'boolean' if $type eq 'bool'; 5432: $type = 'hashref' if $type eq 'hash'; 5433: $type = 'arrayref' if $type eq 'array'; 5434: if($VALID_OUTPUT_TYPES{$type}) { 5435: $output->{type} = $type; 5436: $self->_log(" OUTPUT: type '$type' from =head4 Output formal spec"); 5437: } elsif($block =~ /\bisa\s*=>/) { 5438: $output->{type} = 'object'; 5439: $self->_log(" OUTPUT: type 'object' from =head4 Output isa spec"); 5440: } 5441: } elsif($block =~ /\bisa\s*=>/) { 5442: $output->{type} = 'object'; 5443: $self->_log(" OUTPUT: type 'object' from =head4 Output isa spec"); 5444: } elsif($block =~ /^\{[^}]*\}/ && $block =~ /=>/) { 5445: # A record such as 5446: # `{ n => 'integer', unit => 'string' } | undef` 5447: # documents a hashref return. 5448: $output->{type} = 'hashref'; 5449: $self->_log(" OUTPUT: type 'hashref' from =head4 Output record notation"); 5450: } 5451: } elsif($block =~ /\A(?:(?:Always|Usually)\s+)?(?:An?\s+)?(Hashref|Hash|Arrayref|Array|List)(?=\s*(?:of\b|:|\(|\[|\.|;|,|\z))/i) {
Mutants (Total: 1, Killed: 1, Survived: 0)
5452: # A documented shape such as "Hashref: column_name => {...}", 5453: # "Arrayref of hashrefs" or "Always an arrayref of hashrefs" 5454: # names the container first. "The hash string." names a 5455: # string, so an article alone does not make it a container. 5456: my $word = lc($1); 5457: $output->{type} = ($word =~ /^array|^list/) ? 'arrayref' : 'hashref'; 5458: $self->_log(" OUTPUT: type '$output->{type}' from =head4 Output shape"); 5459: } 5460: }
Mutants (Total: 1, Killed: 1, Survived: 0)
5461: 5462: # Pattern 1: Returns: section 5463: # Up to 3 lines 5464: if ($pod =~ /Returns?:\s+([^\n]+(?:\n[^\n]+){0,2})/si) { 5465: my $returns_desc = $1; 5466: $returns_desc =~ s/^\s+|\s+$//g; 5467: 5468: $self->_log(" OUTPUT: Found Returns section: $returns_desc"); 5469:
Mutants (Total: 1, Killed: 1, Survived: 0)
5470: # Try to infer type from description (skip if Pattern 0 already set type) 5471: if (!$output->{type} && $returns_desc =~ /\b(string|text)\b/i) { 5472: $output->{type} = 'string'; 5473: } elsif (!$output->{type} && $returns_desc =~ /\b(integer|int|count)\b/i) { 5474: $output->{type} = 'integer'; 5475: } elsif (!$output->{type} && $returns_desc =~ /\b(float|decimal|number)\b/i) { 5476: $output->{type} = 'number'; 5477: } elsif (!$output->{type} && $returns_desc =~ /\b(boolean|true|false)\b/i) {
Mutants (Total: 1, Killed: 1, Survived: 0)
5478: $output->{type} = 'boolean'; 5479: } elsif (!$output->{type} && $returns_desc =~ /\b(array|list)\b/i) { 5480: $output->{type} = 'arrayref'; 5481: } elsif (!$output->{type} && $returns_desc =~ /\b(hash|hashref|dictionary)\b/i) { 5482: $output->{type} = 'hashref'; 5483: } elsif (!$output->{type} && $returns_desc =~ /\b(object|instance)\b/i) { 5484: $output->{type} = 'object'; 5485: } elsif (!$output->{type} && $returns_desc =~ /\bundef\b/i) { 5486: $output->{type} = 'undef'; 5487: }
Mutants (Total: 1, Killed: 1, Survived: 0)
5488: 5489: # Look for specific values 5490: if ($returns_desc =~ /\b1\s+(?:on\s+success|if\s+successful)\b/i) { 5491: $output->{value} = 1; 5492: if(defined($output->{'type'}) && ($output->{type} eq 'scalar')) { 5493: $output->{type} = 'boolean'; 5494: } else { 5495: $output->{type} ||= 'boolean';
Mutants (Total: 1, Killed: 1, Survived: 0)
5496: } 5497: $self->_log(" OUTPUT: Returns 1 on success"); 5498: } elsif ($returns_desc =~ /\b0\s+(?:on\s+failure|if\s+fail)\b/i) { 5499: $output->{alt_value} = 0; 5500: } elsif ($returns_desc =~ /dies\s+on\s+(?:error|failure)/i) { 5501: $output->{_STATUS} = 'LIVES'; 5502: $self->_log(' OUTPUT: Should not die on success'); 5503: } 5504: if ($returns_desc =~ /\b(true|false)\b/i) { 5505: $output->{type} ||= 'boolean'; 5506: } 5507: if ($returns_desc =~ /\bundef\b/i) { 5508: $output->{optional} = 1; 5509: } 5510: } 5511: 5512: # Pattern 2: Inline "returns X" 5513: if((!$output->{type}) && ($pod =~ /returns?\s+(?:an?\s+)?(\w+)/i)) { 5514: my $type = lc($1); 5515: 5516: $type = 'boolean' if $type =~ /^(true|false|bool)$/; 5517: # Skip if it's just a number (like "returns 1") 5518: $type = 'integer' if $type eq 'int'; 5519: $type = 'number' if $type =~ /^(num|float)$/; 5520: $type = 'arrayref' if $type eq 'array'; 5521: $type = 'hashref' if $type eq 'hash'; 5522: 5523: if($type =~ /^\d+$/) { 5524: if($type eq '1' || $type eq '0') { 5525: # Try hard to guess if the result is a boolean 5526: if($pod =~ /1 on success.+0 (on|if) /i) { 5527: $type = 'boolean'; 5528: } elsif($pod =~ /return 0 .+ 1 on success/) { 5529: $type = 'boolean'; 5530: } else { 5531: $type = 'integer';
Mutants (Total: 1, Killed: 1, Survived: 0)
5532: } 5533: } else { 5534: $type = 'integer'; 5535: } 5536: } 5537: 5538: $type = 'arrayref' if !$type && $pod =~ /returns?\s+.+\slist\b/i; 5539: # $output->{type} = $type if $type && $type !~ /^\d+$/;
Mutants (Total: 1, Killed: 1, Survived: 0)
5540: if ($VALID_OUTPUT_TYPES{$type}) { 5541: $output->{type} = $type; 5542: $self->_log(" OUTPUT: Inferred type from POD: $type"); 5543: } else { 5544: $self->_log(" OUTPUT: POD return type '$type' is not a valid type, ignoring"); 5545: } 5546: } 5547: } 5548: } 5549:
Mutants (Total: 1, Killed: 1, Survived: 0)
5550: # -------------------------------------------------- 5551: # _extract_defaults_from_pod 5552: # 5553: # Purpose: Extract default values for parameters 5554: # from POD documentation using multiple 5555: # pattern strategies. 5556: # 5557: # Entry: $pod - POD string for the method.
Mutants (Total: 1, Killed: 1, Survived: 0)
5558: # May be undef or empty. 5559: # 5560: # Exit: Returns a hashref of parameter name 5561: # to cleaned default value. Returns an 5562: # empty hashref if no POD is provided 5563: # or no defaults are found. 5564: # 5565: # Side effects: None. 5566: # 5567: # Notes: Three strategies are tried: (1) lines 5568: # containing 'Default:' or 'Defaults to:', 5569: # (2) lines containing 'Optional, default', 5570: # (3) inline $name - type, default value 5571: # format. Parameter names are inferred 5572: # by scanning backwards from the default 5573: # phrase to the nearest $variable. 5574: # -------------------------------------------------- 5575: sub _extract_defaults_from_pod { ●5576 → 5583 → 5607 5576: my ($self, $pod) = @_; 5577: 5578: return {} unless $pod; 5579: 5580: my %defaults; 5581: 5582: # Pattern 1: Default: 'value' or Defaults to: 'value' 5583: while ($pod =~ /(?:Default(?:s? to)?|default(?:s? to)?)[:]\s*([^\n\r]+)/gi) { 5584: my $default_text = $1; 5585: my $match_pos = pos($pod); 5586: $default_text =~ s/^\s+|\s+$//g; 5587: 5588: # Look backwards in the POD to find the parameter name 5589: my $context = substr($pod, 0, $match_pos); 5590: my @param_matches = ($context =~ /\$(\w+)/g); 5591: my $param = $param_matches[-1] if @param_matches; # Last parameter before default 5592: 5593: if ($param) { 5594: # Always clean the default value - let _clean_default_value handle everything 5595: if ($default_text =~ /(\w+)\s*=\s*(.+)$/) { 5596: # Has explicit param = value format in the default text 5597: my ($p, $value) = ($1, $2); 5598: $defaults{$p} = $self->_clean_default_value($value); 5599: } else { 5600: # Just a value, associate with the found param
Mutants (Total: 1, Killed: 1, Survived: 0)
5601: $defaults{$param} = $self->_clean_default_value($default_text, 0); # NOT from code 5602: } 5603: } 5604: } 5605: 5606: # Pattern 2: Optional, default 'value' ●5607 → 5607 → 5622 5607: while ($pod =~ /Optional(?:,)?\s+(?:default|value)\s*[:=]?\s*([^\n\r,;]+)/gi) { 5608: my $default_text = $1; 5609: my $match_pos = pos($pod); 5610: $default_text =~ s/^\s+|\s+$//g; 5611: 5612: # Look backwards for parameter name 5613: my $context = substr($pod, 0, $match_pos);
Mutants (Total: 1, Killed: 1, Survived: 0)
5614: my @param_matches = ($context =~ /\$(\w+)/g); 5615: if (@param_matches) { 5616: my $param = $param_matches[-1]; # Last parameter before the default
Mutants (Total: 1, Killed: 1, Survived: 0)
5617: $defaults{$param} = $self->_clean_default_value($default_text, 0); 5618: } 5619: } 5620: 5621: # Pattern 3: In parameter descriptions: $param - type, default 'value' ●5622 → 5622 → 5627 5622: while ($pod =~ /\$(\w+)\s*-\s*\w+(?:\([^)]*\))?[,\s]+default\s+['"]?([^'",\n]+)['"]?/gi) { 5623: my ($param, $value) = ($1, $2); 5624: $defaults{$param} = $self->_clean_default_value($value, 0); 5625: } 5626: 5627: return \%defaults; 5628: }
Mutants (Total: 1, Killed: 1, Survived: 0)
5629: 5630: # -------------------------------------------------- 5631: # _analyze_output_from_code 5632: # 5633: # Purpose: Analyse return statements in a method 5634: # body to infer the output type by 5635: # counting and classifying each return 5636: # expression. 5637: # 5638: # Entry: $output - hashref to populate 5639: # (modified in place).
Mutants (Total: 1, Killed: 1, Survived: 0)
5640: # $code - method body source string. 5641: # $method_name - method name string. 5642: # 5643: # Exit: Returns nothing. Modifies $output 5644: # in place.
Mutants (Total: 4, Killed: 4, Survived: 0)
5645: # 5646: # Side effects: Logs detections to stdout when 5647: # verbose is set. 5648: # -------------------------------------------------- 5649: sub _analyze_output_from_code 5650: { ●5651 → 5653 → 0 5651: my ($self, $output, $code, $method_name) = @_; 5652: 5653: if ($code) { 5654: # Early boolean detection - check for consistent 1/0 returns 5655: my @all_returns = $code =~ /return\s+([^;]+);/g; 5656: if (@all_returns) { 5657: my $boolean_count = 0; 5658: my $total_count = scalar(@all_returns); 5659: 5660: foreach my $ret (@all_returns) { 5661: $ret =~ s/^\s+|\s+$//g; 5662: # Match 0 or 1, even with conditions
5663: $boolean_count++ if ($ret =~ /^(?:0|1)(?:\s|$)/); 5664: } 5665: 5666: # If most returns are 0 or 1, strongly suggest boolean 5667: if ($boolean_count >= 2 && $boolean_count >= $total_count * 0.8) { 5668: unless ($output->{type}) { 5669: $output->{type} = 'boolean'; 5670: $self->_log(" OUTPUT: Early detection - $boolean_count/$total_count returns are 0/1, setting boolean"); 5671: } 5672: }Mutants (Total: 4, Killed: 1, Survived: 3)
- NUM_BOUNDARY_5662_17_>: Numeric boundary flip >= to >
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_5662_17_<: Numeric boundary flip >= to <
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_5662_17_<=: Numeric boundary flip >= to <=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );Mutants (Total: 1, Killed: 1, Survived: 0)
5673: } 5674: 5675: my @return_statements; 5676:
5677: if ($code =~ /return\s+bless\s*\{[^}]*\}\s*,\s*['"]?(\w+)['"]?/s) { 5678: # Detect blessed refs 5679: $output->{type} = 'object'; 5680: if($method_name eq 'new') { 5681: # If we found the new() method, the object we're returning should be a sensible oneMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_5676_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes5682: if($self->{_document} && (my $package_stmt = $self->{_document}->find_first('PPI::Statement::Package'))) { 5683: $output->{isa} = $package_stmt->namespace(); 5684: $self->{_package_name} //= $output->{isa}; 5685: } 5686: } else { 5687: $output->{isa} = $1; 5688: } 5689: $self->_log(" OUTPUT: Bless found, inferring type from code is $output->{isa}"); 5690: } elsif ($code =~ /return\s+bless/s) { 5691: $output->{type} = 'object'; 5692: if($method_name eq 'new') { 5693: $output->{isa} = $self->_extract_package_name(); 5694: $self->_log(" OUTPUT: Bless found, inferring type from code is $output->{isa}"); 5695: } else { 5696: $self->_log(' OUTPUT: Bless found, inferring type from code is object'); 5697: } 5698: } elsif ($code =~ /return\s*\(\s*[^)]+\s*,\s*[^)]+\s*\)\s*;/) { 5699: # Detect array context returns - must end with semicolon to be actual return 5700: $output->{type} = 'array'; # Not arrayref - actual array 5701: $self->_log(' OUTPUT: Found array contect return'); 5702: } elsif ($code =~ /return\s+bless[^,]+,\s*__PACKAGE__/) { 5703: # Detect: bless {}, __PACKAGE__ 5704: $output->{type} = 'object'; 5705: # Get package name from the extractor's stored document 5706: if ($self->{_document}) { 5707: my $pkg = $self->{_document}->find_first('PPI::Statement::Package'); 5708: $output->{isa} = $pkg ? $pkg->namespace : 'UNKNOWN'; 5709: $self->_log(' OUTPUT: Object blessed into __PACKAGE__: ' . ($output->{isa} || 'UNKNOWN')); 5710: $self->{_package_name} //= $output->{isa}; 5711: } 5712: } elsif ($code =~ /return\s*\(([^)]+)\)/) { 5713: my $content = $1; 5714: if ($content =~ /,/) { # Has comma = multiple values 5715: $output->{type} = 'array'; 5716: } 5717: } elsif ($code =~ /return\s+\$self\s*;/ && $code =~ /\$self\s*->\s*\{[^}]+\}\s*=/) { 5718: # Returns $self for chaining 5719: $output->{type} = 'object'; 5720: if ($self->{_document}) { 5721: my $pkg = $self->{_document}->find_first('PPI::Statement::Package'); 5722: $output->{isa} = $pkg ? $pkg->namespace : 'UNKNOWN'; 5723: $self->_log(' OUTPUT: Object chained into __PACKAGE__: ' . ($output->{isa} || 'UNKNOWN')); 5724: $self->{_package_name} //= $output->{isa}; 5725: } 5726: } 5727: 5728: # Find all return statements 5729: while ($code =~ /return\s+([^;]+);/g) { 5730: my $return_expr = $1; 5731: push @return_statements, $return_expr; 5732: } 5733: 5734: if (@return_statements) { 5735: $self->_log(' OUTPUT: Found ' . scalar(@return_statements) . ' return statement(s)'); 5736: 5737: # Analyze return patterns 5738: my %return_types; 5739: 5740: if($output->{'type'}) { 5741: $return_types{$output->{'type'}} += 3; # Add weighting to what's already been found 5742: } 5743: my $min; 5744: my $time_list; 5745: foreach my $ret (@return_statements) { 5746: $ret =~ s/^\s+|\s+$//g; 5747: 5748: # Arithmetic operators inside a regex literal or a quoted 5749: # string are not arithmetic. SafeUA::numeric_host returns a 5750: # dotted quad and sprintf('%04d-...') returns a date: neither 5751: # is a number, though /:/ has a '/' and '%04d' a '%'. 5752: my $ops_ret = _strip_literals($ret);Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_5681_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes5753: 5754: # Literal values 5755: if ($ret eq '1' || $ret eq '0') { 5756: $return_types{boolean}++; 5757: } elsif ($ret =~ /^['"]/) { 5758: $return_types{string}++; 5759: } elsif ($ret =~ /^-?\d+$/) { 5760: $return_types{integer}++; 5761: } elsif ($ret =~ /^-?\d+\.\d+$/) { 5762: $return_types{number}++; 5763: } elsif ($ret =~ /\A(?:sprintf|join|lc|uc|lcfirst|ucfirst|quotemeta)\b/) { 5764: # A formatting or case call returns text, whatever arithmetic 5765: # its arguments contain: sprintf '%02d:%02d', $h, $m is a 5766: # timestamp string, not a number. 5767: $return_types{string} += 2; 5768: } elsif ($ret =~ /\Aundef\b/) { 5769: # `return undef unless $id` is an undef return with a guard, 5770: # the same error return as a bare `return undef`. 5771: $return_types{undef}++; 5772: } elsif ($self->_returns_time_list($ret)) { 5773: # localtime and gmtime give the nine-element time list inMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_5752_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
5774: # list context; the arithmetic in their argument does not 5775: # make the return a number. 5776: $return_types{array} += 2; 5777: $time_list = 1; 5778: } elsif ($ret =~ /^\[/) { 5779: # Data structures
Mutants (Total: 1, Killed: 1, Survived: 0)
5780: $return_types{arrayref}++; 5781: } elsif ($ret =~ /^\{/) { 5782: $return_types{hashref}++; 5783: } elsif ($ret =~ /^\\\%/) { 5784: # `return \%checked`: a reference to a lexical hash has no 5785: # $ sigil, so before this it fell through every branch and 5786: # the routine was left with no output type at all. 5787: $return_types{hashref}++; 5788: } elsif ($ret =~ /^\\\@/) { 5789: $return_types{arrayref}++; 5790: } elsif ($ops_ret =~ m{ 5791: # Numeric expressions (heuristic, medium confidence). 5792: # `->` is a method call, `//` a defined-or, and `-e` a file 5793: # test, not operators. 5794: (?: 5795: \+ | -(?!>|[A-Za-z]\b) | \* | (?<!\/)\/(?!\/) | (?<!\\)% 5796: | \+\+ | -- 5797: ) 5798: }x) { 5799: $return_types{number} += 2; 5800: } elsif ($ret =~ /\|\|\s*\d+\b/) { 5801: # Logical-or fallback with numeric literal (e.g. $x || 200) 5802: $return_types{integer} += 2; 5803: $self->_log(" OUTPUT: Numeric fallback expression detected"); 5804: } elsif($ret =~ /^length[\s\(]/) { 5805: $return_types{integer}++; 5806: $min = 0; 5807: } elsif($ret =~ /^pos[\s\(]/) { 5808: $return_types{integer}++; 5809: $min = 0; 5810: } elsif($ret =~ /^index[\s\(]/) { 5811: $return_types{integer}++; 5812: $min = -1; 5813: } elsif($ret =~ /^rindex[\s\(]/) { 5814: $return_types{integer}++; 5815: $min = -1; 5816: } elsif($ret =~ /^ord[\s\(]/) { 5817: $return_types{integer}++; 5818: } elsif ($ops_ret =~ /=/ && $ops_ret =~ /\$\w+/) { 5819: # Assignment returning a value (e.g. $self->{status} = $status) 5820: # If assignment involves a numeric literal or variable, assume numeric intent. 5821: # $1, $2 and friends are regex captures - strings, not numeric 5822: # literals - so drop them before looking for digits. CGI::Info::script_dir 5823: # returns "$self->{script_path} =~ $dir_regex ? $1 : ..." and the 5824: # "1" in $1 was being read as a numeric literal. 5825: (my $numeric_ret = $ops_ret) =~ s/\$\d+//g; 5826: if ($numeric_ret =~ /\b\d+\b/) { 5827: $return_types{integer} += 2; 5828: $self->_log(" OUTPUT: Assignment with numeric value detected"); 5829: } else { 5830: $return_types{scalar}++; 5831: } 5832: } 5833: # Variables/expressions
Mutants (Total: 1, Killed: 1, Survived: 0)
5834: elsif ($ret =~ /\$\w+/) { 5835: # \@_ is this routine's own argument list being passed 5836: # along, not an arrayref being returned. CGI::Info::get_cookie 5837: # returns $self->cookie(\@_) and was typed as returning an
Mutants (Total: 1, Killed: 1, Survived: 0)
5838: # arrayref because of it. 5839: (my $ref_ret = $ret) =~ s/\\\@_\b//g; 5840: if ($ref_ret =~ /\\\@/) { 5841: $return_types{arrayref}++; 5842: } elsif ($ref_ret =~ /\\\%/) { 5843: $return_types{hashref}++; 5844: } elsif ($ret =~ /bless/) { 5845: $return_types{object} += 2; # Heigher weight 5846: } elsif ($ret =~ /^\{[^}]*\}$/) { 5847: $return_types{hashref}++;
Mutants (Total: 1, Killed: 1, Survived: 0)
5848: } elsif ($ret =~ /^\[[^\]]*\]$/) { 5849: $return_types{arrayref}++; 5850: } else { 5851: $return_types{scalar}++; 5852: } 5853: } 5854: } 5855: 5856: # Determine most common return type 5857: if (keys %return_types) { 5858: # The undef paths are the documented error return 5859: # (_error_return), not the type of a successful value: a
Mutants (Total: 1, Killed: 1, Survived: 0)
5860: # routine returning a record or undef returns a record when 5861: # it succeeds, however many guards send it back undef. 5862: my %value_types = %return_types; 5863: delete $value_types{undef} if(keys(%value_types) > 1); 5864: # A tie is broken by name so the same code always yields the 5865: # same schema: hash order is randomised per process, and 5866: # Geo::Coder::Free::geocode_many alternated between string and 5867: # hashref in successive runs. 5868: my ($most_common) = sort { $value_types{$b} <=> $value_types{$a} || $a cmp $b } keys %value_types; 5869: # Prefer integer over scalar if numeric returns dominate 5870: if ($return_types{integer} && (!$return_types{string})) { 5871: if (!$output->{type} || $output->{type} eq 'scalar') { 5872: $output->{type} = 'integer'; 5873: $self->_log(" OUTPUT: Numeric returns dominate, forcing integer"); 5874: $output->{_type_confidence} ||= 'low'; 5875: if(defined($min)) { 5876: $output->{min} = $min; 5877: } 5878: } 5879: } 5880: unless ($output->{type}) { 5881: $output->{type} = $most_common; 5882: 5883: # Assign confidence for inferred numeric expressions 5884: if ($most_common eq 'number') { 5885: $output->{_type_confidence} ||= 'medium'; 5886: if(defined($min)) { 5887: $output->{min} = $min; 5888: } 5889: } 5890: 5891: $self->_log(" OUTPUT: Inferred type from code: $most_common"); 5892: } 5893:
5894: if($time_list && ($output->{type} // '') eq 'array') { 5895: # 'number': a time field can be negative (a fixed offset 5896: # before the epoch), and Params::Validate::Strict reads 5897: # the '-' of an integer element as a non-digit. 5898: $output->{element_type} = 'number'; 5899: } 5900: } 5901: 5902: # Check for consistent single value returns 5903: if (@return_statements == 1 && $return_statements[0] eq '1') { 5904: $output->{value} = 1; 5905: $output->{type} = 'boolean' if !$output->{type} || $output->{type} eq 'scalar'; 5906: $self->_log(" OUTPUT: Type already set to '$output->{type}', overriding with boolean") if($output->{'type'});Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_5893_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes5907: } 5908: } else { 5909: # No explicit return - might return nothing or implicit undef 5910: $self->_log(" OUTPUT: No explicit return statement found"); 5911: } 5912: } 5913: } 5914: 5915: # -------------------------------------------------- 5916: # _enhance_boolean_detection 5917: # 5918: # Purpose: Apply additional boolean-specific 5919: # detection heuristics using a weighted 5920: # scoring system, to override weak 5921: # type assignments when there is strong 5922: # evidence of a boolean return. 5923: # 5924: # Entry: $output - output hashref 5925: # (modified in place). 5926: # $pod - POD string. 5927: # $code - method body source string. 5928: # $method_name - method name string. 5929: # 5930: # Exit: Returns nothing. Modifies $output 5931: # in place, setting type to 'boolean' 5932: # if the score reaches 5933: # $BOOLEAN_SCORE_THRESHOLD. 5934: # 5935: # Side effects: Logs scoring details to stdout when 5936: # verbose is set. 5937: # 5938: # Notes: Only fires when output type is 5939: # not yet set or is 'unknown'. Does not 5940: # override explicitly set types. 5941: # -------------------------------------------------- 5942: sub _enhance_boolean_detection { ●5943 → 5950 → 5968 5943: my ($self, $output, $pod, $code, $method_name) = @_; 5944:Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_5906_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
5945: my $boolean_score = 0; # Track evidence for boolean return 5946: 5947: return unless !$output->{type} || $output->{type} eq 'unknown'; 5948: 5949: # Look for stronger boolean indicators 5950: if ($pod && !$output->{type}) { 5951: # Common boolean return patterns in POD 5952: if ($pod =~ /returns?\s+(?:true|false|1|0)\s+(?:on|for|upon)\s+(?:success|failure|error|valid|invalid)/i) {
Mutants (Total: 1, Killed: 1, Survived: 0)
5953: $boolean_score += 30; 5954: $self->_log(' OUTPUT: Strong boolean indicator in POD (+30)'); 5955: } 5956: 5957: # Check for method names that suggest boolean returns 5958: if ($pod =~ /(?:method|sub)\s+(\w+)/) { 5959: my $inferred_method_name = $1; 5960: if ($inferred_method_name =~ /^(is_|has_|can_|should_|contains_|exists_)/) { 5961: $boolean_score += 20; 5962: $self->_log(" OUTPUT: Inferred method name '$inferred_method_name' suggests boolean return (+20)"); 5963: } 5964: } 5965: } 5966: 5967: # Analyze code for boolean patterns ●5968 → 5968 → 5996 5968: if ($code) { 5969: # Count boolean return idioms 5970: my $true_returns = () = $code =~ /return\s+1\s*;/g; 5971: my $false_returns = () = $code =~ /return\s+0\s*;/g; 5972: 5973: if ($true_returns + $false_returns >= 2) { 5974: $boolean_score += 40;
Mutants (Total: 1, Killed: 1, Survived: 0)
5975: $self->_log(' OUTPUT: Multiple 1/0 returns suggest boolean (+40)'); 5976: } elsif ($true_returns + $false_returns == 1) { 5977: $boolean_score += 10; 5978: $self->_log(' OUTPUT: Single 1/0 return (+10)');
Mutants (Total: 1, Killed: 1, Survived: 0)
5979: } 5980: 5981: # Ternary operators that return booleans 5982: if ($code =~ /return\s+(?:\w+\s*[!=]=\s*\w+|\w+\s*>\s*\w+|\w+\s*<\s*\w+)\s*\?\s*(?:1|0)\s*:\s*(?:1|0)/) { 5983: $boolean_score += 25; 5984: $self->_log(' OUTPUT: Ternary with 1/0 suggests boolean (+25)'); 5985: } 5986: 5987: # Check for common boolean method patterns 5988: if ($code =~ /return\s+[!\$\@\%]/) { 5989: # Returns negation or existence check 5990: $boolean_score += 15; 5991: $self->_log(' OUTPUT: Returns negation/existence check (+15)'); 5992: } 5993: } 5994: 5995: # Check method name for boolean indicators ●5996 → 5996 → 6009 5996: if ($method_name) { 5997: if ($method_name =~ /^(?:is_|has_|can_|should_|contains_|exists_|check_|verify_|validate_)/) { 5998: $boolean_score += 25; 5999: $self->_log(" OUTPUT: Method name '$method_name' suggests boolean return (+25)"); 6000: } 6001: if ($method_name =~ /_ok$/) { 6002: $boolean_score += 30; 6003: $self->_log(" OUTPUT: Method name '$method_name' ends with '_ok' (+30)"); 6004: } 6005: } 6006: 6007: # Apply boolean type if we have strong evidence 6008: # Override weak type assignments (like 'array' from false positive) ●6009 → 6009 → 0 6009: if($boolean_score >= $BOOLEAN_SCORE_THRESHOLD) { 6010: if (!$output->{type} || $output->{type} eq 'scalar' || $output->{type} eq 'array' || $output->{type} eq 'undef') { 6011: my $old_type = $output->{type} || 'none'; 6012: $output->{type} = 'boolean'; 6013: $self->_log(" OUTPUT: Boolean score $boolean_score >= $BOOLEAN_SCORE_THRESHOLD, setting type to boolean (was: $old_type)"); 6014: } 6015: } 6016: } 6017: 6018: # -------------------------------------------------- 6019: # _detect_list_context 6020: # 6021: # Purpose: Detect methods that return different 6022: # values depending on calling context 6023: # via wantarray, and methods that 6024: # return explicit lists. 6025: # 6026: # Entry: $output - output hashref (modified 6027: # in place). 6028: # $code - method body source string. 6029: # 6030: # Exit: Returns nothing. Modifies $output
Mutants (Total: 1, Killed: 1, Survived: 0)
6031: # in place, setting _context_aware, 6032: # _list_context, _scalar_context, 6033: # _list_return, and/or type keys. 6034: # 6035: # Side effects: Logs detections to stdout when 6036: # verbose is set. 6037: # -------------------------------------------------- 6038: sub _detect_list_context { ●6039 → 6043 → 6081 6039: my ($self, $output, $code) = @_;
Mutants (Total: 1, Killed: 1, Survived: 0)
6040: return unless $code; 6041: 6042: # Check for wantarray usage 6043: if ($code =~ /wantarray/) { 6044: $output->{_context_aware} = 1; 6045: $self->_log(' OUTPUT: Method uses wantarray - context sensitive'); 6046: 6047: # Debug: show what we're matching against 6048: if ($code =~ /(wantarray[^;]+;)/s) { 6049: $self->_log(" DEBUG wantarray line: $1"); 6050: } 6051: 6052: if ($code =~ /wantarray\s*\?\s*\(([^)]+)\)\s*:\s*([^;]+)/s) { 6053: # Pattern 1: wantarray ? (list, items) : scalar_value (with parens) 6054: my ($list_return, $scalar_return) = ($1, $2); 6055: $self->_log(" DEBUG list (with parens): [$list_return], scalar: [$scalar_return]"); 6056:
Mutants (Total: 2, Killed: 2, Survived: 0)
6057: $output->{_list_context} = $self->_infer_type_from_expression($list_return); 6058: $output->{_scalar_context} = $self->_infer_type_from_expression($scalar_return); 6059: $self->_log(' OUTPUT: Detected context-dependent returns (parenthesized)'); 6060: } elsif ($code =~ /wantarray\s*\?\s*([^:]+?)\s*:\s*([^;]+)/s) { 6061: # Pattern 2: wantarray ? @array : scalar (no parens around list) 6062: my ($list_return, $scalar_return) = ($1, $2); 6063: # Clean up 6064: $list_return =~ s/^\s+|\s+$//g;
Mutants (Total: 1, Killed: 1, Survived: 0)
6065: $scalar_return =~ s/^\s+|\s+$//g; 6066: 6067: $self->_log(" DEBUG list (no parens): [$list_return], scalar: [$scalar_return]"); 6068: 6069: $output->{_list_context} = $self->_infer_type_from_expression($list_return); 6070: $output->{_scalar_context} = $self->_infer_type_from_expression($scalar_return); 6071: $self->_log(' OUTPUT: Detected context-dependent returns (non-parenthesized)'); 6072: } elsif ($code =~ /return[^;]*unless\s+wantarray.*?return\s*\(([^)]+)\)/s) { 6073: # Pattern 3: return unless wantarray; return (list); 6074: $output->{_list_context} = { type => 'array' }; 6075: $self->_log(' OUTPUT: Detected list context return after wantarray check'); 6076: } 6077: } 6078: 6079: # Detect explicit list returns (multiple values in parentheses) 6080: # Avoid false positives from function calls ●6081 → 6081 → 0 6081: if ($code =~ /return\s*\(\s*([^)]+)\s*\)\s*;/) {
Mutants (Total: 2, Killed: 2, Survived: 0)
6082: my $content = $1; 6083: 6084: # Count commas outside of nested structures, jumping over each 6085: # balanced bracketed block in one step via extract_bracketed 6086: require Text::Balanced; 6087: my $comma_count = 0; 6088: my $rest = $content; 6089: while (length $rest) { 6090: if (substr($rest, 0, 1) =~ /[(\[{]/) { 6091: my $extracted = Text::Balanced::extract_bracketed($rest, '(){}[]'); 6092: last unless defined $extracted; # Unbalanced brackets
Mutants (Total: 2, Killed: 2, Survived: 0)
6093: next; 6094: } 6095: $comma_count++ if substr($rest, 0, 1) eq ','; 6096: $rest = substr($rest, 1); 6097: } 6098: 6099: if ($comma_count > 0 && $content !~ /\b(?:bless|new)\b/) {
Mutants (Total: 2, Killed: 2, Survived: 0)
6100: # Multiple values returned 6101: unless ($output->{type} && $output->{type} eq 'boolean') { 6102: $output->{type} = 'array'; 6103: $output->{_list_return} = $comma_count + 1; 6104: $self->_log(' OUTPUT: Returns list of ' . ($comma_count + 1) . ' values'); 6105: } 6106: } 6107: } 6108: }
Mutants (Total: 2, Killed: 2, Survived: 0)
6109: 6110: # -------------------------------------------------- 6111: # _returns_time_list 6112: # 6113: # Purpose: Decide whether a return expression 6114: # gives the nine-element list built by 6115: # localtime or gmtime, rather than a 6116: # scalar derived from one. 6117: #
Mutants (Total: 2, Killed: 2, Survived: 0)
6118: # Entry: $ret - a return expression. 6119: # 6120: # Exit: Returns true when the whole
Mutants (Total: 2, Killed: 2, Survived: 0)
6121: # expression, or the arm of a ternary 6122: # that ends it, is a localtime/gmtime 6123: # call. 6124: # -------------------------------------------------- 6125: sub _returns_time_list { 6126: my ($self, $ret) = @_; 6127: 6128: return 0 unless defined($ret); 6129: return 0 unless $ret =~ /(?:\A|[?:])\s*\(*\s*(?:localtime|gmtime)\s*\(/; 6130: 6131: return $ret =~ /(?:localtime|gmtime)\s*\([^()]*\)\s*\)*\s*\z/ ? 1 : 0; 6132: } 6133: 6134: # -------------------------------------------------- 6135: # _detect_void_context 6136: # 6137: # Purpose: Detect methods that return nothing 6138: # meaningful (void context), methods 6139: # that always return 1 as a success 6140: # indicator, and methods whose name 6141: # suggests void context (setters, 6142: # mutators, loggers). 6143: # 6144: # Entry: $output - output hashref
Mutants (Total: 2, Killed: 2, Survived: 0)
6145: # (modified in place). 6146: # $code - method body source string.
Mutants (Total: 1, Killed: 1, Survived: 0)
6147: # $method_name - method name string.
Mutants (Total: 2, Killed: 2, Survived: 0)
6148: # 6149: # Exit: Returns nothing. Modifies $output
Mutants (Total: 2, Killed: 2, Survived: 0)
6150: # in place, setting _void_context, 6151: # _success_indicator, and/or type.
Mutants (Total: 2, Killed: 2, Survived: 0)
6152: # 6153: # Side effects: Logs detections to stdout when
Mutants (Total: 2, Killed: 2, Survived: 0)
6154: # verbose is set. 6155: # --------------------------------------------------
6156: sub _detect_void_context { ●6157 → 6171 → 6180 6157: my ($self, $output, $code, $method_name) = @_;Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_6155_3: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes🧪 Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_6155_3: Replace return expression with undef
LOW: Mutation survived, but impact may be minor🧪 Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );Mutants (Total: 2, Killed: 2, Survived: 0)
6158: return unless $code; 6159: 6160: $self->_log(" DEBUG _detect_void_context called for $method_name"); 6161: 6162: # Methods that typically don't return meaningful values 6163: my $void_patterns = { 6164: 'setter' => qr/^set_\w+$/, 6165: 'mutator' => qr/^(?:add|remove|delete|clear|reset|update)_/, 6166: 'logger' => qr/^(?:log|debug|warn|error|info)$/, 6167: 'printer' => qr/^(?:print|say|dump)_/, 6168: }; 6169: 6170: # Check if method name suggests void context 6171: foreach my $type (keys %$void_patterns) { 6172: if ($method_name =~ $void_patterns->{$type}) { 6173: $output->{_void_context_hint} = $type; 6174: $self->_log(" OUTPUT: Method name suggests $type (typically void context)"); 6175: last; 6176: } 6177: } 6178: 6179: # Analyze return statements ●6180 → 6189 → 6204 6180: my @returns = $code =~ /return\s*([^;]*);/g; 6181: 6182: $self->_log(' DEBUG Found ' . scalar(@returns) . ' return statements'); 6183: 6184: # Count different return patterns 6185: my $no_value_returns = 0; 6186: my $true_returns = 0; 6187: my $self_returns = 0; 6188: 6189: foreach my $ret (@returns) { 6190: $ret =~ s/^\s+|\s+$//g; 6191: $self->_log(" DEBUG return value: [$ret]"); 6192: $no_value_returns++ if $ret eq ''; 6193: $no_value_returns++ if($ret =~ /^(if|unless)\s/);
Mutants (Total: 1, Killed: 1, Survived: 0)
6194: $true_returns++ if $ret eq '1'; 6195: $self_returns++ if $ret eq '$self'; 6196: if ($ret =~ /\?\s*1\s*:\s*0\b/) { 6197: # Strong boolean signal: ternary returning 1/0 6198: $true_returns++;
Mutants (Total: 1, Killed: 1, Survived: 0)
6199: # $self->_log(" OUTPUT: Ternary 1:0 return detected, treating as boolean (+40)"); 6200: $self->_log(' OUTPUT: Ternary 1:0 return detected, treating as boolean'); 6201: } 6202: }
Mutants (Total: 1, Killed: 1, Survived: 0)
6203: ●6204 → 6209 → 0 6204: my $total_returns = scalar(@returns); 6205: 6206: $self->_log(" DEBUG no_value=$no_value_returns, true=$true_returns, self=$self_returns, total=$total_returns"); 6207: 6208: # Void context indicators 6209: if ($no_value_returns > 0 && $no_value_returns == $total_returns) { 6210: $output->{_void_context} = 1; 6211: $output->{type} = 'void'; # This should override any previous type 6212: $self->_log(' OUTPUT: All returns are empty - void context method'); 6213: } elsif ($true_returns > 0 && $true_returns == $total_returns && $total_returns >= 1) {
Mutants (Total: 1, Killed: 1, Survived: 0)
6214: # Methods that always return true (success indicator) 6215: $output->{_success_indicator} = 1;
6216: # Don't override type if already set to boolean 6217: unless ($output->{type} && $output->{type} eq 'boolean') { 6218: $output->{type} = 'boolean'; 6219: } 6220: $self->_log(' OUTPUT: Always returns 1 - success indicator pattern');Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_6215_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes6221: } 6222: } 6223: 6224: # --------------------------------------------------Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_6220_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes6225: # _detect_chaining_pattern 6226: # 6227: # Purpose: Detect methods that return $self for 6228: # fluent interface chaining, by countingMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_6224_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 2, Killed: 2, Survived: 0)
6229: # the proportion of return statements 6230: # that return $self. 6231: # 6232: # Entry: $output - output hashref (modified 6233: # in place). 6234: # $code - method body source string. 6235: # 6236: # Exit: Returns nothing. Modifies $output 6237: # in place, setting type to 'object', 6238: # _returns_self to 1, and isa to the 6239: # current package name when the 6240: # proportion of $self returns is >= 0.8. 6241: # 6242: # Side effects: Logs detection to stdout when 6243: # verbose is set. 6244: # -------------------------------------------------- 6245: sub _detect_chaining_pattern { ●6246 → 6253 → 6261 6246: my ($self, $output, $code) = @_; 6247: return unless $code; 6248: 6249: # Count returns of $self 6250: my $self_returns = 0; 6251: my $total_returns = 0; 6252: 6253: while ($code =~ /return\s+([^;]+);/g) { 6254: my $ret = $1; 6255: $ret =~ s/^\s+|\s+$//g; 6256: $total_returns++; 6257: $self_returns++ if $ret eq '$self'; 6258: }
Mutants (Total: 1, Killed: 1, Survived: 0)
6259: 6260: # If most/all returns are $self, it's a chaining method ●6261 → 6261 → 0 6261: if ($self_returns > 0 && $total_returns > 0) { 6262: my $ratio = $self_returns / $total_returns; 6263: 6264: if ($ratio >= 0.8) {
Mutants (Total: 1, Killed: 1, Survived: 0)
6265: $output->{type} = 'object'; 6266: $output->{_returns_self} = 1; 6267: 6268: # Get the class name 6269: if ($self->{_document}) { 6270: my $pkg = $self->{_document}->find_first('PPI::Statement::Package');
Mutants (Total: 1, Killed: 1, Survived: 0)
6271: $output->{isa} = $pkg ? $pkg->namespace : 'UNKNOWN'; 6272: $self->{_package_name} //= $output->{isa}; 6273: } 6274: 6275: $self->_log(" OUTPUT: Chainable method - returns \$self ($self_returns/$total_returns returns)"); 6276: }
Mutants (Total: 1, Killed: 1, Survived: 0)
6277: } 6278: } 6279: 6280: # -------------------------------------------------- 6281: # _detect_error_conventions 6282: #
Mutants (Total: 1, Killed: 1, Survived: 0)
6283: # Purpose: Analyse how a method signals errors 6284: # by detecting patterns such as 6285: # 'return undef if', implicit bare 6286: # returns, empty list returns, 0/1 6287: # boolean error patterns, and eval 6288: # exception handling.
Mutants (Total: 1, Killed: 1, Survived: 0)
6289: # 6290: # Entry: $output - output hashref (modified 6291: # in place). 6292: # $code - method body source string. 6293: #
Mutants (Total: 2, Killed: 2, Survived: 0)
6294: # Exit: Returns nothing. Modifies $output 6295: # in place, setting _error_handling, 6296: # _error_return, and 6297: # _success_failure_pattern keys. 6298: # 6299: # Side effects: Logs detections to stdout when 6300: # verbose is set. 6301: # -------------------------------------------------- 6302: sub _detect_error_conventions { ●6303 → 6312 → 6318 6303: my ($self, $output, $code) = @_; 6304: 6305: return unless $code; 6306: 6307: $self->_log(' DEBUG _detect_error_conventions called'); 6308: 6309: my %error_patterns; 6310: 6311: # Pattern 1: return undef if/unless condition 6312: while ($code =~ /return\s+undef\s+(?:if|unless)\s+([^;]+);/g) { 6313: push @{$error_patterns{undef_on_error}}, $1; 6314: $self->_log(" DEBUG Found 'return undef' pattern"); 6315: } 6316: 6317: # Pattern 2: return if/unless (implicit undef) ●6318 → 6318 → 6324 6318: while ($code =~ /return\s+(?:if|unless)\s+([^;]+);/g) { 6319: push @{$error_patterns{implicit_undef}}, $1; 6320: $self->_log(" DEBUG Found implicit undef pattern"); 6321: } 6322: 6323: # Pattern 3: return () - matches with or without conditions ●6324 → 6324 → 6330 6324: if ($code =~ /return\s*\(\s*\)\s*(?:if|unless|;)/) { 6325: $error_patterns{empty_list} = 1; 6326: $self->_log(" DEBUG Found empty list return"); 6327: } 6328: 6329: # Pattern 4: return 0/1 pattern (indicates boolean with error handling) ●6330 → 6333 → 6341 6330: my $zero_returns = 0; 6331: my $one_returns = 0; 6332: # Match "return 0" or "return 1" followed by anything (condition or semicolon) 6333: while ($code =~ /return\s+(0|1)\s*(?:;|if|unless)/g) { 6334: if ($1 eq '0') { 6335: $zero_returns++; 6336: } else { 6337: $one_returns++;
Mutants (Total: 1, Killed: 1, Survived: 0)
6338: } 6339: } 6340:
Mutants (Total: 1, Killed: 1, Survived: 0)
●6341 → 6341 → 6347 6341: if ($zero_returns > 0 && $one_returns > 0) { 6342: $error_patterns{zero_on_error} = 1; 6343: $self->_log(" DEBUG Found 0/1 return pattern ($zero_returns zeros, $one_returns ones)"); 6344: } 6345: 6346: # Pattern 5: Exception handling with eval ●6347 → 6347 → 6356 6347: if ($code =~ /eval\s*\{/) { 6348: # Check if there's error handling after eval 6349: if ($code =~ /eval\s*\{.*?\}[^}]*(?:if\s*\(\s*\$\@|catch|return\s+undef)/s) { 6350: $error_patterns{exception_handling} = 1; 6351: $self->_log(' DEBUG Found exception handling with eval'); 6352: }
Mutants (Total: 1, Killed: 1, Survived: 0)
6353: } 6354: 6355: # Detect success/failure return pattern ●6356 → 6360 → 6366 6356: my @all_returns = $code =~ /return\s+([^;]+);/g; 6357: my $has_undef = grep { /^\s*undef\s*(?:if|unless|$)/ } @all_returns; 6358: my $has_value = grep { !/^\s*undef\s*$/ && !/^\s*$/ } @all_returns; 6359: 6360: if ($has_undef && $has_value && scalar(@all_returns) >= 2) { 6361: $output->{_success_failure_pattern} = 1;
Mutants (Total: 1, Killed: 1, Survived: 0)
6362: $self->_log(" OUTPUT: Uses success/failure return pattern"); 6363: } 6364: 6365: # Store error conventions in output ●6366 → 6366 → 0 6366: if(scalar(keys %error_patterns)) { 6367: $output->{_error_handling} = \%error_patterns; 6368: 6369: # Determine primary error convention 6370: if ($error_patterns{undef_on_error}) {
Mutants (Total: 2, Killed: 2, Survived: 0)
6371: $output->{_error_return} = 'undef'; 6372: $self->_log(" OUTPUT: Returns undef on error"); 6373: } elsif ($error_patterns{implicit_undef}) { 6374: $output->{_error_return} = 'undef'; 6375: $self->_log(" OUTPUT: Returns implicit undef on error"); 6376: } elsif ($error_patterns{empty_list}) { 6377: $output->{_error_return} = 'empty_list'; 6378: $self->_log(" OUTPUT: Returns empty list on error"); 6379: } elsif ($error_patterns{zero_on_error}) { 6380: $output->{_error_return} = 'false'; 6381: $self->_log(" OUTPUT: Returns 0/false on error"); 6382: } 6383: 6384: if ($error_patterns{exception_handling}) { 6385: $self->_log(" OUTPUT: Has exception handling"); 6386: } 6387: } else { 6388: delete $output->{_error_handling}; 6389: } 6390: } 6391: 6392: # -------------------------------------------------- 6393: # _infer_type_from_expression 6394: # 6395: # Purpose: Infer the data type of a return 6396: # expression string by matching it 6397: # against common Perl literal and 6398: # variable patterns. 6399: # 6400: # Entry: $expr - return expression string, 6401: # trimmed of leading and 6402: # trailing whitespace. 6403: # May be undef. 6404: # 6405: # Exit: Returns a type hashref of the form 6406: # { type => '...' } and optionally 6407: # { min => N }. Defaults to 6408: # { type => 'scalar' } when no 6409: # pattern matches. 6410: # 6411: # Side effects: None. 6412: # -------------------------------------------------- 6413: sub _infer_type_from_expression { ●6414 → 6421 → 6441 6414: my ($self, $expr) = @_; 6415: 6416: return { type => 'scalar' } unless defined $expr; 6417: 6418: $expr =~ s/^\s+|\s+$//g; 6419: 6420: # Check for multiple comma-separated values (indicates array/list)
Mutants (Total: 1, Killed: 1, Survived: 0)
6421: if ($expr =~ /,/) { 6422: require Text::Balanced; 6423: my $comma_count = 0; 6424: my $rest = $expr; 6425: while (length $rest) {
Mutants (Total: 1, Killed: 1, Survived: 0)
6426: if (substr($rest, 0, 1) =~ /[(\[{]/) { 6427: my $extracted = Text::Balanced::extract_bracketed($rest, '(){}[]'); 6428: last unless defined $extracted; # Unbalanced brackets 6429: next; 6430: } 6431: $comma_count++ if substr($rest, 0, 1) eq ','; 6432: $rest = substr($rest, 1); 6433: } 6434: 6435: if ($comma_count > 0) { 6436: return { type => 'array' }; 6437: } 6438: } 6439: 6440: # Check for @ prefix (array) ●6441 → 6441 → 6446 6441: if ($expr =~ /^\@\w+/ || $expr =~ /^qw\(/ || $expr =~ /^\@\{/) { 6442: return { type => 'array' }; 6443: } 6444: 6445: # Check for scalar() function - returns count ●6446 → 6446 → 6451 6446: if ($expr =~ /scalar\s*\(/) { 6447: return { type => 'integer', min => 0 }; 6448: } 6449: 6450: # Check for array reference ●6451 → 6451 → 6456 6451: if ($expr =~ /^\[/ || $expr =~ /^\\\@/) { 6452: return { type => 'arrayref' }; 6453: } 6454: 6455: # Check for hash reference ●6456 → 6456 → 6461 6456: if ($expr =~ /^\{/ || $expr =~ /^\\\%/) { 6457: return { type => 'hashref' }; 6458: } 6459: 6460: # Check for hash ●6461 → 6461 → 6466 6461: if ($expr =~ /^\%\w+/ || $expr =~ /^\%\{/) { 6462: return { type => 'hash' }; 6463: } 6464: 6465: # Check for strings ●6466 → 6466 → 6472 6466: if ($expr =~ /^['"]/ || $expr =~ /['"]$/) { 6467: return { type => 'string' }; 6468: } 6469: 6470: # Check for booleans first â must come before the integer check 6471: # since /^-?\d+$/ would otherwise match 0 and 1 as integers ●6472 → 6472 → 6477 6472: if($expr =~ /^[01]$/) { 6473: return { type => 'boolean' }; 6474: } 6475: 6476: # Check for integers ●6477 → 6477 → 6481 6477: if($expr =~ /^-?\d+$/) { 6478: return { type => 'integer' }; 6479: } 6480: ●6481 → 6481 → 6486 6481: if ($expr =~ /^-?\d+\.\d+$/) { 6482: return { type => 'number' }; 6483: } 6484: 6485: # Check for objects ●6486 → 6486 → 6490 6486: if ($expr =~ /bless/) { 6487: return { type => 'object' }; 6488: } 6489: ●6490 → 6490 → 6495 6490: if($expr =~ /\blength\s*\(/) { 6491: return { type => 'integer', min => 0 }; 6492: } 6493: 6494: # Default to scalar 6495: return { type => 'scalar' }; 6496: } 6497: 6498: # -------------------------------------------------- 6499: # _detect_chaining_from_pod 6500: # 6501: # Purpose: Check POD documentation for explicit 6502: # indications that a method is chainable 6503: # or part of a fluent interface. 6504: # 6505: # Entry: $output - output hashref (modified 6506: # in place). 6507: # $pod - POD string for the method. 6508: # 6509: # Exit: Returns nothing. Sets _returns_self 6510: # in $output if chaining keywords are 6511: # found. 6512: # 6513: # Side effects: Logs detection to stdout when 6514: # verbose is set. 6515: # -------------------------------------------------- 6516: sub _detect_chaining_from_pod { ●6517 → 6521 → 0 6517: my ($self, $output, $pod) = @_; 6518: return unless $pod; 6519: 6520: # Look for explicit chaining documentation 6521: if ($pod =~ /returns?\s+(?:\$)?self\b/i || 6522: $pod =~ /chainable/i || 6523: $pod =~ /fluent\s+interface/i || 6524: $pod =~ /method\s+chaining/i) { 6525: 6526: $output->{_returns_self} = 1; 6527: $self->_log(" OUTPUT: POD indicates chainable/fluent interface"); 6528: } 6529: } 6530: 6531: # -------------------------------------------------- 6532: # _validate_output 6533: # 6534: # Purpose: Apply basic sanity checks to the 6535: # assembled output hashref and warn 6536: # about suspicious type combinations, 6537: # normalising clearly invalid types to 6538: # 'string'. 6539: # 6540: # Entry: $output - output hashref (modified 6541: # in place). 6542: # 6543: # Exit: Returns nothing. May modify type key 6544: # in $output. Logs warnings to stdout 6545: # when verbose is set. 6546: # 6547: # Side effects: None. 6548: # -------------------------------------------------- 6549: sub _validate_output { ●6550 → 6553 → 6556 6550: my ($self, $output) = @_; 6551: 6552: # Warn about suspicious combinations 6553: if (defined $output->{type} && $output->{type} eq 'boolean' && !defined($output->{value})) { 6554: $self->_log(' WARNING Boolean type without value - may want to set value: 1'); 6555: } ●6556 → 6556 → 6559 6556: if ($output->{value} && defined $output->{type} && $output->{type} ne 'boolean') { 6557: $self->_log(" WARNING Value set but type is not boolean: $output->{type}"); 6558: } ●6559 → 6560 → 0 6559: my %valid_types = map { $_ => 1 } qw(string integer number boolean array arrayref hashref object void); 6560: if(exists $output->{type}) { 6561: if(!$valid_types{$output->{type}}) { 6562: $self->_log(" WARNING Output value type is unknown: '$output->{type}', setting to string"); 6563: $output->{type} = 'string'; 6564: } 6565: } 6566: } 6567: 6568: # -------------------------------------------------- 6569: # _prose_memberof 6570: #
Mutants (Total: 1, Killed: 1, Survived: 0)
6571: # Purpose: Recognise a documented list of allowed values written as 6572: # prose, such as "one of red, green or blue", "must be one 6573: # of C<low>, C<moderate> or C<high>", "valid values are 1, 6574: # 5 and 111" or "either C<host> or C<port>". 6575: # The list is documentation, not a check the routine was 6576: # seen to make, so callers mark the parameter 6577: # _source => 'pod': the harness uses the values as valid
6578: # data and generates no must-die case outside the set. 6579: # Entry: $text - a parameter description or constraint, possibly 6580: # containing POD formatting codes.Mutants (Total: 2, Killed: 0, Survived: 2)
- NUM_BOUNDARY_6577_40_!=: Numeric boundary flip == to !=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- COND_INV_6577_5: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes6581: # Exit: Arrayref of the documented values, or undef when the text 6582: # holds no recognisable list. Every value must be a single 6583: # token, so prose like "one of the four recognised keys set 6584: # to a true value also adds ..." is not mistaken for a list. 6585: # -------------------------------------------------- 6586: sub _prose_memberof { ●6587 → 6598 → 6609 6587: my ($self, $text) = @_; 6588: 6589: return undef unless defined($text) && length($text); 6590: 6591: my $plain = $text; 6592: $plain =~ s/\b[CLIB]<([^<>]*)>/$1/g; # drop POD formatting 6593: $plain =~ s/\bE<([^<>]*)>/$1/g;Mutants (Total: 1, Killed: 0, Survived: 1)
- NUM_BOUNDARY_6580_44_!=: Numeric boundary flip == to !=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );Mutants (Total: 2, Killed: 2, Survived: 0)
6594: $plain =~ s/\A\s+//; 6595: $plain =~ s/\s+\z//; 6596:
6597: my $list; 6598: if($plain =~ /\b(?:one\s+of|valid\s+values?\s*(?:are|is)?\s*:?|allowed\s+values?\s*(?:are|is)?\s*:?|accepted\s+values?\s*(?:are|is)?\s*:?|permitted\s+values?\s*(?:are|is)?\s*:?)\s*(.+)$/i) { 6599: $list = $1; 6600: } elsif($plain =~ /\b(?:must\s+be\s+)?either\s+(.+)$/i) { 6601: $list = $1; 6602: } elsif($plain =~ /\b(?:also\s+)?accepts\s+the\s+strings?\s+(.+)$/i) { 6603: # "Also accepts the strings off, warn, and fatal." 6604: $list = $1; 6605: } else { 6606: return undef; 6607: } 6608:Mutants (Total: 1, Killed: 0, Survived: 1)
- NUM_BOUNDARY_6596_43_!=: Numeric boundary flip == to !=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );●6609 → 6616 → 6622 6609: $list =~ s/\.(?:\s|\z).*\z//s; # stop at the end of the sentence 6610: $list =~ s/\s*\.\s*\z//; 6611: $list =~ s/\s+\z//; 6612: 6613: my @values = grep { length } split(/\s*,\s*(?:(?:and|or)\s+)?|\s+(?:and|or)\s+/i, $list); 6614: return undef if(@values < 2 || @values > 20); 6615: 6616: for my $value (@values) { 6617: $value =~ s/\A\s+|\s+\z//g; 6618: $value =~ s/\A['"]|['"]\z//g; 6619: return undef unless $value =~ /\A[A-Za-z0-9_:.+-]+\z/; 6620: } 6621: 6622: return \@values; 6623: } 6624: 6625: # -------------------------------------------------- 6626: # _parse_constraints 6627: # 6628: # Purpose: Parse a constraint string extracted 6629: # from POD documentation and populate 6630: # min, max, or other constraint fields 6631: # in a parameter hashref. 6632: # 6633: # Entry: $param - hashref for the parameter 6634: # being annotated (modified 6635: # in place). 6636: # $constraint - the constraint string,Mutants (Total: 4, Killed: 0, Survived: 4)
- NUM_BOUNDARY_6608_39_<: Numeric boundary flip > to <
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_6608_39_>=: Numeric boundary flip > to >=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_6608_39_<=: Numeric boundary flip > to <=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- COND_INV_6608_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 2, Killed: 2, Survived: 0)
6637: # e.g. '3-50', 'positive',
Mutants (Total: 2, Killed: 2, Survived: 0)
6638: # '>= 0', 'min 3'.
Mutants (Total: 2, Killed: 2, Survived: 0)
6639: # 6640: # Exit: Returns nothing. Modifies $param in 6641: # place by setting min and/or max keys. 6642: # 6643: # Side effects: Logs min/max values to stdout when 6644: # verbose is set, and marks the constraints as 6645: # documented (documentation only). 6646: # -------------------------------------------------- 6647: sub _parse_constraints { ●6648 → 6651 → 6656 6648: my ($self, $param, $constraint) = @_; 6649: 6650: # A documented list of values, e.g. "(one of red, green)" 6651: if(my $values = $self->_prose_memberof($constraint)) { 6652: $param->{memberof} = $values; 6653: } 6654: 6655: # Range: "3-50" or "1-100 chars" ●6656 → 6656 → 6696 6656: if ($constraint =~ /(\d+)\s*-\s*(\d+)/) { 6657: $param->{min} = $1; 6658: $param->{max} = $2; 6659: } 6660: elsif ($constraint =~ /(\d+)\s*\.\.\s*(\d+)/) { 6661: # Range: 0..19 6662: $param->{min} = $1;
Mutants (Total: 2, Killed: 2, Survived: 0)
6663: $param->{max} = $2; 6664: } 6665: # Minimum: "min 3" or "at least 5" 6666: elsif ($constraint =~ /(?:min|minimum|at least)\s*(\d+)/i) {
Mutants (Total: 1, Killed: 1, Survived: 0)
6667: $param->{min} = $1; 6668: }
6669: # Maximum: "max 50" or "up to 100" 6670: elsif ($constraint =~ /(?:max|maximum|up to)\s*(\d+)/i) { 6671: $param->{max} = $1; 6672: } 6673: # Positive 6674: elsif ($constraint =~ /positive/i) { 6675: $param->{min} = 1 if $param->{type} && $param->{type} eq 'integer'; 6676: $param->{min} = 0.01 if $param->{type} && $param->{type} eq 'number'; 6677: } 6678: # Non-negative 6679: elsif ($constraint =~ /non-negative/i) { 6680: $param->{min} = 0; 6681: } elsif($constraint =~ /^(\S+)\s+(.+)$/) { 6682: my ($op, $val) = ($1, $2); 6683: if(looks_like_number($val)) { 6684: if ($op eq '<') {Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_6668_3: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes🧪 Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_6668_3: Replace return expression with undef
LOW: Mutation survived, but impact may be minor🧪 Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );Mutants (Total: 2, Killed: 2, Survived: 0)
6685: $param->{max} = $val - 1; 6686: } elsif ($op eq '<=') { 6687: $param->{max} = $val; 6688: } elsif ($op eq '>') { 6689: $param->{min} = $val + 1; 6690: } elsif ($op eq '>=') { 6691: $param->{min} = $val; 6692: } 6693: } 6694: } 6695: ●6696 → 6696 → 6699 6696: if(defined($param->{max})) { 6697: $self->_log(" Set max to $param->{max}"); 6698: } ●6699 → 6699 → 6706 6699: if(defined($param->{min})) { 6700: $self->_log(" Set min to $param->{min}"); 6701: } 6702: 6703: # These constraints come from prose ("3-50 chars", "at least 5"): they 6704: # describe valid input rather than a check the code was seen to make, so 6705: # the harness uses them as data hints and expects no croak outside them. ●6706 → 6706 → 0 6706: if(defined($param->{min}) || defined($param->{max}) || $param->{memberof}) { 6707: $param->{_source} = SOURCE_POD; 6708: } 6709: } 6710: 6711: # -------------------------------------------------- 6712: # _analyze_code 6713: # 6714: # Purpose: Analyse a method's source code using 6715: # pattern matching to infer parameter 6716: # names, types, constraints, defaults, 6717: # and optionality. Orchestrates all 6718: # per-parameter code analysis helpers. 6719: #
Mutants (Total: 1, Killed: 1, Survived: 0)
6720: # Entry: $code - method body source string. 6721: # $method - method hashref (used for 6722: # constructor-specific logic 6723: # when extracting parameters 6724: # from @_ patterns).
Mutants (Total: 1, Killed: 1, Survived: 0)
6725: # 6726: # Exit: Returns a hashref of parameter name 6727: # to parameter spec hashref, with as
Mutants (Total: 1, Killed: 1, Survived: 0)
6728: # much type and constraint information 6729: # as could be inferred from the code. 6730: # 6731: # Side effects: Logs progress and warnings to stdout 6732: # when verbose is set. 6733: # 6734: # Notes: Analysis is capped at max_parameters 6735: # to prevent runaway processing on 6736: # pathological methods. Falls back to 6737: # classic @_ extraction if signature 6738: # extraction found no parameters. 6739: # -------------------------------------------------- 6740: sub _analyze_code { ●6741 → 6758 → 6768 6741: my ($self, $code, $method) = @_; 6742: 6743: # A comment is prose, not code. A signature shown in an example comment 6744: # (extract_all's # my ($password, %opts) = @_) must not become a parameter. 6745: $code = _strip_comments($code, $method->{node});
Mutants (Total: 1, Killed: 1, Survived: 0)
6746: 6747: my %params; 6748: 6749: # Safety check - limit parameter analysis to prevent runaway processing 6750: my $param_count = 0; 6751: 6752: # Extract parameter names from various signature styles 6753: $self->_extract_parameters_from_signature(\%params, $code); 6754: 6755: # Params::Get: get_params('key', \@_) passes the param name as a string, 6756: # not as a $var in the signature, so run this unconditionally as a second 6757: # pass after the early-returning signature parsers have finished. 6758: if($code =~ /Params::Get/) {
Mutants (Total: 1, Killed: 1, Survived: 0)
6759: my $pos = scalar keys %params; 6760: while($code =~ /get_params\s*\(\s*['"](\w+)['"]/g) { 6761: my $name = $1; 6762: next if $name =~ /^(self|class|pkg|proto|klass)$/i; 6763: $params{$name} //= { _source => SOURCE_CODE, position => $pos++ }; 6764: $self->_log(" CODE: Found Params::Get parameter '$name'"); 6765: }
Mutants (Total: 1, Killed: 1, Survived: 0)
6766: } 6767: ●6768 → 6771 → 6784 6768: $self->_extract_defaults_from_code(\%params, $code, $method);
6769: 6770: # Infer types from defaults 6771: foreach my $param (keys %params) {Mutants (Total: 3, Killed: 0, Survived: 3)
- NUM_BOUNDARY_6768_52_>: Numeric boundary flip < to >
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_6768_52_<=: Numeric boundary flip < to <=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_6768_52_>=: Numeric boundary flip < to >=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );6772: if ($params{$param}{_default} && !$params{$param}{type}) { 6773: my $default = $params{$param}{_default}; 6774: if (ref($default) eq 'HASH') { 6775: $params{$param}{type} = 'hashref'; 6776: $self->_log(" CODE: $param type inferred as hashref from default");Mutants (Total: 3, Killed: 0, Survived: 3)
- NUM_BOUNDARY_6771_52_<: Numeric boundary flip > to <
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_6771_52_>=: Numeric boundary flip > to >=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_6771_52_<=: Numeric boundary flip > to <=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );Mutants (Total: 1, Killed: 1, Survived: 0)
6777: } elsif (ref($default) eq 'ARRAY') { 6778: $params{$param}{type} = 'arrayref'; 6779: $self->_log(" CODE: $param type inferred as arrayref from default"); 6780: } 6781: }
6782: } 6783: ●6784 → 6784 → 6799 6784: if($code =~ /(?:croak|die)\(.*\)\s+if\s*\(\s*scalar\(\@_\)\s*<\s*(\d+)\s*\)/s) { 6785: my $required_count = $1; 6786: my @param_names = sort { $params{$a}{position} <=> $params{$b}{position} } keys %params; 6787: for my $i (0 .. $required_count-1) { 6788: $params{$param_names[$i]}{optional} = 0; 6789: $self->_log(" CODE: $param_names[$i] marked required due to croak scalar check"); 6790: } 6791: } elsif ($code =~ /(?:croak|die)\(.*\)\s+if\s*\(\s*scalar\(\@_\)\s*==\s*0\s*\)/s) { 6792: foreach my $param (keys %params) { 6793: $params{$param}{optional} = 0; 6794: $self->_log(" CODE: $param: all parameters are required due to 'scalar(@_) == 0' check"); 6795: } 6796: } 6797: 6798: # Analyze each parameter (with safety limit) ●6799 → 6799 → 6868 6799: foreach my $param (keys %params) { 6800: if ($param_count++ > $self->{max_parameters}) { 6801: $self->_log(" WARNING: Max parameters ($self->{max_parameters}) exceeded, skipping remaining"); 6802: last; 6803: } 6804: 6805: my $p = \$params{$param}; 6806: 6807: $self->_analyze_parameter_type($p, $param, $code); 6808: $self->_analyze_parameter_constraints($p, $param, $code); 6809: $self->_analyze_parameter_validation($p, $param, $code); 6810: $self->_analyze_advanced_types($p, $param, $code); 6811: 6812: # Defined checks 6813: if ($code =~ /defined\s*\(\s*\$$param\s*\)/) { 6814: $$p->{optional} = 0; 6815: $self->_log(" CODE: $param is required (defined check)"); 6816: } 6817: 6818: # Determine optional/required and numeric type from code 6819: if ($code =~ /\s*\$$param\s*(?:\/\/|\|\|)=/) { 6820: # e.g. $var //= 5; or $var ||= 5; 6821: $$p->{optional} = 1; 6822: $self->_log(" CODE: $param is optional (default value assigned in code)");Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_6781_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
6823: } elsif ($code =~ /\s*\$$param\s*(?!->)(?:[\+\-\*\%]|\/(?!\/)|(?:\+\+)|(?:--)|(?:[\+\-\*\%]=|\/(?!\/)=)|\+\$|\$[+-])/ ) { 6824: # Covers arithmetic usage: 6825: # $x + $param, $param++, $param--, $x += $param, $x -= $param, etc. 6826: $$p->{optional} = 0; 6827: $$p->{type} //= 'number'; 6828: $self->_log(" CODE: $param is required (used in arithmetic context)");
Mutants (Total: 1, Killed: 1, Survived: 0)
6829: } elsif ($code =~ /\$\b$param\b\s*(?:\+0|\*1)/) { 6830: # Forces numeric context, e.g., "$param + 0" or "$param * 1" 6831: $$p->{optional} = 0; 6832: $$p->{type} //= 'number'; 6833: $self->_log(" CODE: $param is required (numeric context)");
6834: }Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_6833_3: Invert condition unless to if
MEDIUM: Add tests asserting both true and false outcomes6835: 6836: # Required parameter checks (undef causes error) 6837: 6838: # Style 1: block form 6839: if ($code =~ /if\s*\(\s*!\s*defined\s*\(\s*\$$param\s*\)\s*\)\s*\{([^}]+)\}/s) { 6840: my $block = $1; 6841: if ($block =~ /\b(croak|die|confess)\b/) { 6842: $$p->{optional} = 0; 6843: $self->_log(" CODE: $param is required (undef causes error)"); 6844: } 6845: } 6846: 6847: # Style 2: postfix unless 6848: if ($code =~ /\b(croak|die|confess)\b[^;]*\bunless\s+defined\s*\(\s*\$$param\s*\)/) { 6849: $$p->{optional} = 0; 6850: $self->_log(" CODE: $param is required (postfix undef check)"); 6851: } 6852:Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_6834_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
6853: # Exists checks for hash keys 6854: if ($code =~ /exists\s*\(\s*\$$param\s*\)/) { 6855: $$p->{type} = 'hashkey';
6856: $self->_log(" CODE: $param is a hash key"); 6857: } 6858: 6859: # Scalar context for arraysMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_6855_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes6860: if ($code =~ /scalar\s*\(\s*\@?\$$param\s*\)/) { 6861: $$p->{type} = 'array'; 6862: $self->_log(" CODE: $param used in scalar context (array)"); 6863: } 6864: 6865: $self->_extract_error_constraints($p, $param, $code); 6866: } 6867: 6868: $self->_sanitize_parameter_names(\%params, 'code analysis');Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_6859_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
6869: return \%params; 6870: } 6871: 6872: # -------------------------------------------------- 6873: # _analyze_parameter_type 6874: # 6875: # Purpose: Infer the type of a single parameter 6876: # from ref() checks, isa() calls, 6877: # bless patterns, array/hash operations, 6878: # and numeric operator usage in the 6879: # method body. 6880: # 6881: # Entry: $p_ref - reference to the parameter 6882: # hashref (modified in place 6883: # via the referenced hash). 6884: # $param - parameter name string. 6885: # $code - method body source string. 6886: # 6887: # Exit: Returns nothing. Modifies the 6888: # referenced parameter hashref. 6889: # 6890: # Side effects: Logs detections to stdout when 6891: # verbose is set. 6892: # -------------------------------------------------- 6893: sub _analyze_parameter_type { ●6894 → 6898 → 6917 6894: my ($self, $p_ref, $param, $code) = @_; 6895: my $p = $$p_ref; 6896: 6897: # Type inference from ref() checks 6898: if ($code =~ /ref\s*\(\s*\$$param\s*\)\s*eq\s*['"](ARRAY|HASH|SCALAR)['"]/gi) { 6899: my $reftype = lc($1); 6900: $p->{type} = $reftype eq 'array' ? 'arrayref' : 6901: $reftype eq 'hash' ? 'hashref' : 6902: 'scalar'; 6903: $self->_log(" CODE: $param is $p->{type} (ref check)"); 6904: } 6905: # ISA checks for objects 6906: elsif ($code =~ /\$$param\s*->\s*isa\s*\(\s*['"]([^'"]+)['"]\s*\)/i) { 6907: $p->{type} = 'object'; 6908: $p->{isa} = $1; 6909: $self->_log(" CODE: $param is object of class $1"); 6910: } 6911: # Blessed references 6912: elsif ($code =~ /bless\s+.*\$$param/) { 6913: $p->{type} = 'object'; 6914: $self->_log(" CODE: $param is blessed object"); 6915: } 6916: # Array/hash operations ●6917 → 6917 → 6930 6917: if (!$p->{type}) { 6918: if ($code =~ /\@\{\s*\$$param\s*\}/ || $code =~ /push\s*\(\s*\@?\$$param/) { 6919: $p->{type} = 'arrayref'; 6920: } elsif ($code =~ /\%\{\s*\$$param\s*\}/ || $code =~ /\$$param\s*->\s*\{/) { 6921: $p->{type} = 'hashref'; 6922: } 6923: } 6924: 6925: # An argument used only as `$param->method` is an object the caller 6926: # supplies (a controller, a cache, a database handle). The harness 6927: # cannot build one, so it is an object rather than a guessed scalar.
Mutants (Total: 1, Killed: 1, Survived: 0)
6928: # `$param->{...}` and `$param->[...]` are hash and array access, which 6929: # the check above has already typed. ●6930 → 6930 → 6940 6930: if (!$p->{type} && $code =~ /\$$param\s*->\s*[A-Za-z_]\w*/) { 6931: $p->{type} = 'object'; 6932: # A method call on undef is an error, so the argument cannot be 6933: # omitted unless the body guards the call (a truthiness test in 6934: # _analyze_parameter_validation makes it optional again). 6935: $p->{optional} = 0;
Mutants (Total: 1, Killed: 1, Survived: 0)
6936: $self->_log(" CODE: $param is an object (called as a method holder)"); 6937: } 6938: 6939: # Infer type from the default value if type is unknown ●6940 → 6940 → 6954 6940: if (!$p->{type} && exists $p->{_default}) {
Mutants (Total: 1, Killed: 1, Survived: 0)
6941: my $default = $p->{_default}; 6942: if (ref($default) eq 'HASH') { 6943: $p->{type} = 'hashref'; 6944: $self->_log(" CODE: $param type inferred as hashref from default"); 6945: } elsif (ref($default) eq 'ARRAY') { 6946: $p->{type} = 'arrayref'; 6947: $self->_log(" CODE: $param type inferred as arrayref from default"); 6948: } 6949: } 6950: 6951: # ------------------------------------------------------------
Mutants (Total: 1, Killed: 1, Survived: 0)
6952: # Heuristic numeric inference (low confidence) 6953: # ------------------------------------------------------------ ●6954 → 6954 → 0 6954: if (!$p->{type}) { 6955: # A '-' or '%' in 'Period-over-period' or "%04d" is text, not 6956: # arithmetic, so the operators are looked for outside the literals. 6957: my $ops_code = _strip_literals($code); 6958: # An explicit looks_like_number($param) check is a direct 6959: # numeric-type assertion by the author, stronger evidence than 6960: # incidental arithmetic adjacency (e.g. $param is only ever
6961: # used inside a defined-or default before the arithmetic, so 6962: # the arithmetic-operator check below never sees $param itself 6963: # next to an operator). 6964: if ($code =~ /\blooks_like_number\s*\(\s*\$$param\s*\)/) { 6965: $p->{type} = 'number'; 6966: $p->{_type_confidence} = 'heuristic'; 6967: $self->_log(" CODE: $param inferred as number (looks_like_number check)"); 6968: } 6969: # Numeric operators: + - * / % ** 6970: # Use \/(?!\/) to exclude // (defined-or) from matching as division. 6971: # `$c->req` is a method call, not $c minus something, so '-' before 6972: # '>' does not count as an operator. 6973: elsif ( 6974: $ops_code =~ /\$$param\s*(?:[\+\*\%]|-(?!>|[A-Za-z]\b)|(?<!\/)\/(?!\/))/ || 6975: $ops_code =~ /(?:[\+\*\%]|-(?!>|[A-Za-z]\b)|(?<!\/)\/(?!\/))\s*\$$param/ || 6976: $ops_code =~ /\bint\s*\(\s*\$$param\s*\)/ ||Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_6960_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes6977: $ops_code =~ /\babs\s*\(\s*\$$param\s*\)/ 6978: ) { 6979: $p->{type} = 'number'; 6980: $p->{_type_confidence} = 'heuristic'; 6981: $self->_log(" CODE: $param inferred as number (numeric operator)"); 6982: } 6983: # Numeric comparison 6984: elsif ( 6985: $ops_code =~ /\$$param\s*(?:==|!=|<=|>=|<|>)/ || 6986: $ops_code =~ /(?:==|!=|<=|>=|<|>)\s*\$$param/Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_6976_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 2, Killed: 2, Survived: 0)
6987: ) { 6988: $p->{type} = 'number'; 6989: $p->{_type_confidence} = 'heuristic'; 6990: $self->_log(" CODE: $param inferred as number (numeric comparison)"); 6991: } 6992: } 6993: } 6994: 6995: # -------------------------------------------------- 6996: # _analyze_advanced_types 6997: # 6998: # Purpose: Apply enhanced type detection to a 6999: # single parameter, checking for 7000: # DateTime objects, file handles, 7001: # coderefs, and enum-like constraints 7002: # beyond what basic type inference 7003: # can determine. 7004: # 7005: # Entry: $p_ref - reference to the parameter 7006: # hashref (modified in place 7007: # via the referenced hash). 7008: # $param - the parameter name string. 7009: # $code - method body source string. 7010: # 7011: # Exit: Returns nothing. Modifies the 7012: # referenced parameter hashref in place. 7013: # 7014: # Side effects: Logs detections to stdout when 7015: # verbose is set. 7016: # 7017: # Notes: Delegates to four specialised
Mutants (Total: 1, Killed: 1, Survived: 0)
7018: # detectors: _detect_datetime_type, 7019: # _detect_filehandle_type, 7020: # _detect_coderef_type, and 7021: # _detect_enum_type. Each detector 7022: # returns early on first match so 7023: # detectors are implicitly prioritised 7024: # in that order. 7025: # --------------------------------------------------
Mutants (Total: 3, Killed: 3, Survived: 0)
7026: sub _analyze_advanced_types { 7027: my ($self, $p_ref, $param, $code) = @_; 7028: 7029: # Dereference once to get the hash reference 7030: my $p = $$p_ref; 7031: 7032: # Now pass the dereferenced hash to the detection methods 7033: $self->_detect_datetime_type($p, $param, $code); 7034: $self->_detect_filehandle_type($p, $param, $code); 7035: $self->_detect_coderef_type($p, $param, $code); 7036: $self->_detect_enum_type($p, $param, $code); 7037: } 7038: 7039: # -------------------------------------------------- 7040: # _detect_datetime_type 7041: # 7042: # Purpose: Detect DateTime objects, Time::Piece 7043: # objects, date strings, ISO 8601 7044: # strings, and UNIX timestamps by 7045: # analysing code patterns involving 7046: # the parameter. 7047: # 7048: # Entry: $p - parameter hashref (modified 7049: # in place). 7050: # $param - parameter name string. 7051: # $code - method body source string. 7052: # 7053: # Exit: Returns nothing. Modifies $p in place, 7054: # setting type, isa, semantic, min, 7055: # matches, and/or format keys. 7056: # Returns immediately on first match. 7057: # 7058: # Side effects: Logs detections to stdout when 7059: # verbose is set. 7060: # -------------------------------------------------- 7061: sub _detect_datetime_type { ●7062 → 7068 → 7077 7062: my ($self, $p, $param, $code) = @_; 7063: 7064: # Validate param is just a simple word 7065: return unless defined $param && $param =~ /^\w+$/; 7066: 7067: # DateTime object detection via isa/UNIVERSAL checks 7068: if ($code =~ /\$$param\s*->\s*isa\s*\(\s*['"]DateTime['"]\s*\)/i) { 7069: $p->{type} = 'object'; 7070: $p->{isa} = 'DateTime'; 7071: $p->{semantic} = 'datetime_object'; 7072: $self->_log(" ADVANCED: $param is DateTime object"); 7073: return; 7074: } 7075: 7076: # Check for DateTime method calls ●7077 → 7077 → 7086 7077: if ($code =~ /\$$param\s*->\s*(ymd|dmy|mdy|hms|iso8601|epoch|strftime)/) { 7078: $p->{type} = 'object'; 7079: $p->{isa} = 'DateTime';
Mutants (Total: 1, Killed: 1, Survived: 0)
7080: $p->{semantic} = 'datetime_object';
Mutants (Total: 1, Killed: 1, Survived: 0)
7081: $self->_log(" ADVANCED: $param uses DateTime methods"); 7082: return; 7083: } 7084: 7085: # Time::Piece detection ●7086 → 7086 → 7097 7086: if ($code =~ /\$$param\s*->\s*isa\s*\(\s*['"]Time::Piece['"]\s*\)/i || 7087: $code =~ /\$$param\s*->\s*(strftime|epoch|year|mon|mday)/) { 7088: $p->{type} = 'object'; 7089: $p->{isa} = 'Time::Piece'; 7090: $p->{semantic} = 'timepiece_object'; 7091: $self->_log(" ADVANCED: $param is Time::Piece object"); 7092: return; 7093: } 7094: 7095: # ISO 8601 date pattern. Checked before the looser date-string match
Mutants (Total: 1, Killed: 1, Survived: 0)
7096: # below, which would otherwise claim a full datetime first. ●7097 → 7097 → 7109 7097: if ($code =~ /\$$param\s*=~\s*\/([^\/]+)\//) { 7098: my $regex = $1; 7099: if ($self->_looks_like_iso8601_regex($regex)) {
Mutants (Total: 1, Killed: 1, Survived: 0)
7100: $p->{type} = 'string'; 7101: $p->{semantic} = 'iso8601_string'; 7102: $p->{matches} = '/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z?$/'; 7103: $self->_log(" ADVANCED: $param validated as ISO 8601 datetime");
Mutants (Total: 1, Killed: 1, Survived: 0)
7104: return; 7105: } 7106: } 7107:
Mutants (Total: 1, Killed: 1, Survived: 0)
7108: # String date/time patterns via regex matching ●7109 → 7109 → 7118 7109: if ($code =~ /\$$param\s*=~\s*\/.*?\\d\{4\}.*?\\d\{2\}.*?\\d\{2\}/) { 7110: $p->{type} = 'string'; 7111: $p->{semantic} = 'date_string';
Mutants (Total: 1, Killed: 1, Survived: 0)
7112: $p->{format} = 'YYYY-MM-DD or similar'; 7113: $self->_log(" ADVANCED: $param validated as date string pattern"); 7114: return; 7115: } 7116: 7117: # UNIX timestamp detection (numeric with specific range)
Mutants (Total: 1, Killed: 1, Survived: 0)
●7118 → 7118 → 7129 7118: if ($code =~ /\$$param\s*>\s*\d{9,}/ || # UNIX timestamps are 10+ digits 7119: $code =~ /time\(\s*\)\s*-\s*\$$param/ || 7120: $code =~ /\$$param\s*-\s*time\(\s*\)/) { 7121: $p->{type} = 'integer'; 7122: $p->{semantic} = 'unix_timestamp'; 7123: $p->{min} = 0;
Mutants (Total: 1, Killed: 1, Survived: 0)
7124: $self->_log(" ADVANCED: $param appears to be UNIX timestamp"); 7125: return; 7126: } 7127: 7128: # Date parsing with strptime or similar ●7129 → 7129 → 0 7129: if ($code =~ /strptime\s*\(\s*\$$param/ ||
Mutants (Total: 1, Killed: 1, Survived: 0)
7130: $code =~ /DateTime::Format::\w+\s*->\s*parse_datetime\s*\(\s*\$$param/) { 7131: $p->{type} = 'string'; 7132: $p->{semantic} = 'datetime_parseable'; 7133: $self->_log(" ADVANCED: $param is parsed as datetime"); 7134: return; 7135: } 7136: } 7137: 7138: # -------------------------------------------------- 7139: # _looks_like_iso8601_regex 7140: # 7141: # Purpose: Decide whether a regex body names an 7142: # ISO 8601 datetime rather than merely 7143: # containing the letters t and z, which 7144: # a timezone alternation such as 7145: # /\A(?:utc|gmt|z)\z/i also does. 7146: #
Mutants (Total: 1, Killed: 1, Survived: 0)
7147: # Entry: $regex - regex body without its 7148: # delimiters. 7149: # 7150: # Exit: Returns true when the body spells out 7151: # a year, month and day before the time 7152: # separator.
Mutants (Total: 1, Killed: 1, Survived: 0)
7153: # -------------------------------------------------- 7154: sub _looks_like_iso8601_regex { 7155: my ($self, $regex) = @_; 7156: 7157: return 0 unless defined $regex && $regex =~ /[Tt]/ && $regex =~ /[Zz]/;
Mutants (Total: 4, Killed: 4, Survived: 0)
7158: 7159: my $digit = qr/(?:\\d|\[0-9\])/; 7160: my $year = qr/(?:$digit\s*\{\s*4\s*\}|$digit$digit$digit$digit)/; 7161: my $short = qr/(?:$digit\s*\{\s*[12]\s*\}|$digit$digit)/; 7162: 7163: return $regex =~ /$year[^A-Za-z]{0,3}$short[^A-Za-z]{0,3}$short/ ? 1 : 0; 7164: } 7165: 7166: # --------------------------------------------------
7167: # _detect_filehandle_type 7168: # 7169: # Purpose: Detect file handle parameters andMutants (Total: 4, Killed: 1, Survived: 3)
- NUM_BOUNDARY_7166_11_>: Numeric boundary flip >= to >
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_7166_11_<: Numeric boundary flip >= to <
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_7166_11_<=: Numeric boundary flip >= to <=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );7170: # file path string parameters by 7171: # analysing I/O operations, file test 7172: # operators, and path manipulationMutants (Total: 3, Killed: 0, Survived: 3)
- NUM_BOUNDARY_7169_16_>: Numeric boundary flip >= to >
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_7169_16_<: Numeric boundary flip >= to <
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_7169_16_<=: Numeric boundary flip >= to <=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );7173: # patterns involving the parameter. 7174: # 7175: # Entry: $p - parameter hashref (modified 7176: # in place). 7177: # $param - parameter name string. 7178: # $code - method body source string. 7179: # 7180: # Exit: Returns nothing. Modifies $p in place, 7181: # setting type, isa, and semantic keys. 7182: # Returns immediately on first match. 7183: # 7184: # Side effects: Logs detections to stdout when 7185: # verbose is set. 7186: # -------------------------------------------------- 7187: sub _detect_filehandle_type { ●7188 → 7195 → 7204 7188: my ($self, $p, $param, $code) = @_; 7189: 7190: return unless defined $param && $param =~ /^\w+$/; 7191: 7192: # File handle operations. The builtin has to be a name of its own: an 7193: # underscore before it means a call such as _json_read($path), whose 7194: # argument is a path, not a handle. 7195: if ($code =~ /(?<![\w:])(?:open|close|read|print|say|sysread|syswrite)\s*\(?\s*\$$param/) { 7196: $p->{type} = 'object'; 7197: $p->{isa} = 'IO::Handle'; 7198: $p->{semantic} = 'filehandle'; 7199: $self->_log(" ADVANCED: $param is a file handle"); 7200: return; 7201: } 7202: 7203: # Filehandle-specific operations ●7204 → 7204 → 7215 7204: if ($code =~ /\$$param\s*->\s*(readline|getline|print|say|close|flush|autoflush)/) { 7205: $p->{type} = 'object'; 7206: $p->{isa} = 'IO::Handle'; 7207: $p->{semantic} = 'filehandle'; 7208: $self->_log(" ADVANCED: $param uses filehandle methods"); 7209: return; 7210: } 7211: 7212: # File test operators. A -d test is a directory requirement: the value 7213: # has to name an existing directory, which no spelling pattern can 7214: # capture, so it gets its own semantic rather than a filepath pattern. ●7215 → 7215 → 7228 7215: if ($code =~ /(?:-[frwxoOeszlpSbctugkTBMAC])\s+\$$param/) { 7216: $p->{type} = 'string'; 7217: if ($code =~ /-d\s+\$$param/) { 7218: $p->{semantic} = 'directory'; 7219: $self->_log(" ADVANCED: $param is tested as a directory"); 7220: } else {Mutants (Total: 3, Killed: 0, Survived: 3)
- NUM_BOUNDARY_7172_16_>: Numeric boundary flip >= to >
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_7172_16_<: Numeric boundary flip >= to <
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_7172_16_<=: Numeric boundary flip >= to <=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );Mutants (Total: 1, Killed: 1, Survived: 0)
7221: $p->{semantic} = 'filepath'; 7222: $self->_log(" ADVANCED: $param is tested as file path"); 7223: } 7224: return; 7225: } 7226: 7227: # File::Spec operations or path manipulation ●7228 → 7228 → 7238 7228: if ($code =~ /File::(?:Spec|Basename)::\w+\s*\(\s*\$$param/ ||
Mutants (Total: 1, Killed: 1, Survived: 0)
7229: $code =~ /(?:basename|dirname|fileparse)\s*\(\s*\$$param/) { 7230: $p->{type} = 'string'; 7231: $p->{semantic} = 'filepath'; 7232: $self->_log(" ADVANCED: $param manipulated as file path"); 7233: return; 7234: }
Mutants (Total: 1, Killed: 1, Survived: 0)
7235: 7236: # Path validation patterns 7237: # Only match a literal path assigned or defaulted to this variable ●7238 → 7238 → 7246 7238: if(defined $p->{_default} && $p->{_default} =~ m{^([A-Za-z]:\\|/|\./|\.\./)}) { 7239: $p->{type} = 'string'; 7240: $p->{semantic} = 'filepath';
Mutants (Total: 1, Killed: 1, Survived: 0)
7241: $self->_log(" ADVANCED: $param default looks like a path"); 7242: return; 7243: } 7244:
7245: # IO::File detection ●7246 → 7246 → 0 7246: if ($code =~ /\$$param\s*->\s*isa\s*\(\s*['"]IO::File['"]\s*\)/ || 7247: $code =~ /IO::File\s*->\s*new\s*\(\s*\$$param/) {Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_7244_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes7248: $p->{type} = 'object'; 7249: $p->{isa} = 'IO::File'; 7250: $p->{semantic} = 'filehandle'; 7251: $self->_log(" ADVANCED: $param is IO::File object"); 7252: return; 7253: }Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_7247_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
7254: } 7255: 7256: # -------------------------------------------------- 7257: # _detect_coderef_type 7258: # 7259: # Purpose: Detect coderef and callback parameters
Mutants (Total: 1, Killed: 1, Survived: 0)
7260: # by analysing ref() checks, invocation 7261: # patterns, and parameter naming 7262: # conventions. 7263: # 7264: # Entry: $p - parameter hashref (modified 7265: # in place).
Mutants (Total: 1, Killed: 1, Survived: 0)
7266: # $param - parameter name string. 7267: # $code - method body source string. 7268: # 7269: # Exit: Returns nothing. Modifies $p in place, 7270: # setting type and semantic keys. 7271: # Returns immediately on first match.
Mutants (Total: 1, Killed: 1, Survived: 0)
7272: # 7273: # Side effects: Logs detections to stdout when 7274: # verbose is set. 7275: # -------------------------------------------------- 7276: sub _detect_coderef_type { ●7277 → 7282 → 7291 7277: my ($self, $p, $param, $code) = @_;
Mutants (Total: 1, Killed: 1, Survived: 0)
7278: 7279: return unless defined $param && $param =~ /^\w+$/; 7280: 7281: # ref() check for CODE, for a plain variable or a named argument 7282: if ($code =~ /ref\s*\(\s*\$$param\s*\)\s*eq\s*['"]CODE['"]/i 7283: || $code =~ /ref\s*\(\s*\$args\{\s*['"]?$param['"]?\s*\}\s*\)\s*eq\s*['"]CODE['"]/i) { 7284: $p->{type} = 'coderef'; 7285: $p->{semantic} = 'callback'; 7286: $self->_log(" ADVANCED: $param is coderef (ref check)");
Mutants (Total: 4, Killed: 4, Survived: 0)
7287: return; 7288: } 7289:
7290: # Invocation as coderef - note the escaped @ in \@_ ●7291 → 7291 → 7301 7291: if ($code =~ /\$$param\s*->\s*\(/ || 7292: $code =~ /\$$param\s*->\s*\(\s*\@_\s*\)/ ||Mutants (Total: 3, Killed: 0, Survived: 3)
- NUM_BOUNDARY_7289_18_>: Numeric boundary flip >= to >
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_7289_18_<: Numeric boundary flip >= to <
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );- NUM_BOUNDARY_7289_18_<=: Numeric boundary flip >= to <=
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );Mutants (Total: 3, Killed: 3, Survived: 0)
7293: $code =~ /&\s*\{\s*\$$param\s*\}/) { 7294: $p->{type} = 'coderef'; 7295: $p->{semantic} = 'callback'; 7296: $self->_log(" ADVANCED: $param invoked as coderef"); 7297: return; 7298: } 7299: 7300: # Parameter name suggests callback ●7301 → 7301 → 7309 7301: if ($param =~ /^(?:callback|cb|handler|sub|code|fn|func|on_\w+)$/i) { 7302: $p->{type} = 'coderef'; 7303: $p->{semantic} = 'callback'; 7304: $self->_log(" ADVANCED: $param name suggests coderef"); 7305: return; 7306: } 7307: 7308: # Blessed coderef (unusual but valid) ●7309 → 7309 → 0 7309: if ($code =~ /blessed\s*\(\s*\$$param\s*\)/ && 7310: $code =~ /ref\s*\(\s*\$$param\s*\)\s*eq\s*['"]CODE['"]/i) { 7311: $p->{type} = 'object'; 7312: $p->{isa} = 'blessed_coderef'; 7313: $p->{semantic} = 'callback'; 7314: $self->_log(" ADVANCED: $param is blessed coderef"); 7315: return; 7316: } 7317: } 7318: 7319: # -------------------------------------------------- 7320: # _detect_enum_type 7321: # 7322: # Purpose: Detect enum-like parameters whose 7323: # valid values are a fixed set, by 7324: # analysing validation patterns 7325: # including regex alternations, hash 7326: # lookups, grep checks, given/when, 7327: # if/elsif chains, and smart match. 7328: # 7329: # Entry: $p - parameter hashref (modified 7330: # in place). 7331: # $param - parameter name string. 7332: # $code - method body source string. 7333: # 7334: # Exit: Returns nothing. Modifies $p in place, 7335: # setting type, enum, and semantic keys. 7336: # Returns immediately on first match. 7337: # 7338: # Side effects: Logs detections to stdout when 7339: # verbose is set. 7340: #
Mutants (Total: 1, Killed: 1, Survived: 0)
7341: # Notes: Requires at least 3 if/elsif branches 7342: # for pattern 5 to avoid false positives 7343: # from ordinary conditional code. 7344: # -------------------------------------------------- 7345: sub _detect_enum_type { ●7346 → 7352 → 7365 7346: my ($self, $p, $param, $code) = @_; 7347: 7348: return unless defined $param && $param =~ /^\w+$/; 7349: 7350: # Pattern 1: die/croak unless value is in list 7351: # die 'Invalid status' unless $status =~ /^(active|inactive|pending)$/;
Mutants (Total: 1, Killed: 1, Survived: 0)
7352: if ($code =~ /unless\s+\$$param\s*=~\s*\/\^?\(([^)]+)\)/) { 7353: my $values = $1; 7354: my @enum_values = split(/\|/, $values); 7355: $p->{type} = 'string' unless $p->{type}; 7356: $p->{enum} = \@enum_values; 7357: $p->{semantic} = 'enum'; 7358: $self->_log(" ADVANCED: $param is enum with values: " . join(', ', @enum_values)); 7359: return; 7360: }
7361: 7362: # Pattern 2: Hash lookup for validation 7363: # my %valid = map { $_ => 1 } qw(red green blue); 7364: # die unless $valid{$param}; ●7365 → 7365 → 7380 7365: if ($code =~ /\%(\w+)\s*=.*?qw\s*[\(\[<{]([^)\]>}]+)[\)\]>}]/) { 7366: my $hash_name = $1; 7367: my $values_str = $2; 7368: if (defined $values_str && $code =~ /\$$hash_name\s*\{\s*\$$param\s*\}/) { 7369: my @enum_values = split(/\s+/, $values_str); 7370: $p->{type} = 'string' unless $p->{type}; 7371: $p->{enum} = \@enum_values; 7372: $p->{semantic} = 'enum';Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_7360_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 2, Killed: 2, Survived: 0)
7373: $self->_log(" ADVANCED: $param validated via hash lookup: " . join(', ', @enum_values)); 7374: return; 7375: } 7376: } 7377: 7378: # Pattern 3: Array grep validation 7379: # die unless grep { $_ eq $param } qw(foo bar baz); ●7380 → 7380 → 7391 7380: if ($code =~ /grep\s*\{[^}]*\$$param[^}]*\}\s*qw\s*[\(\[<{]([^)\]>}]+)[\)\]>}]/) { 7381: my $values_str = $1; 7382: my @enum_values = split(/\s+/, $values_str); 7383: $p->{type} = 'string' unless $p->{type}; 7384: $p->{enum} = \@enum_values; 7385: $p->{semantic} = 'enum'; 7386: $self->_log(" ADVANCED: $param validated via grep: " . join(', ', @enum_values)); 7387: return; 7388: } 7389: 7390: # Pattern 4: Given/when (Perl 5.10+) ●7391 → 7391 → 7407 7391: if ($code =~ /given\s*\(\s*\$$param\s*\)/) { 7392: my @enum_values; 7393: while ($code =~ /when\s*\(\s*['"]([^'"]+)['"]\s*\)/g) { 7394: push @enum_values, $1; 7395: } 7396: if (@enum_values >= 2) { 7397: $p->{type} = 'string' unless $p->{type}; 7398: $p->{enum} = \@enum_values; 7399: $p->{semantic} = 'enum'; 7400: $self->_log(" ADVANCED: $param has enum values from given/when: " . 7401: join(', ', @enum_values));
Mutants (Total: 1, Killed: 1, Survived: 0)
7402: return; 7403: } 7404: } 7405:
7406: # Pattern 5: Multiple if/elsif checking specific values ●7407 → 7408 → 7411 7407: my @if_values; 7408: while ($code =~ /if\s*\(\s*\$$param\s*eq\s*['"]([^'"]+)['"]\s*\)/g) { 7409: push @if_values, $1; 7410: } ●7411 → 7411 → 7414 7411: while ($code =~ /elsif\s*\(\s*\$$param\s*eq\s*['"]([^'"]+)['"]\s*\)/g) {Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_7405_3: Invert condition unless to if
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 2, Killed: 2, Survived: 0)
7412: push @if_values, $1; 7413: } ●7414 → 7414 → 7424 7414: if (@if_values >= 3) { 7415: $p->{type} = 'string' unless $p->{type}; 7416: $p->{enum} = \@if_values; 7417: $p->{semantic} = 'enum'; 7418: $self->_log(" ADVANCED: $param appears to be enum from if/elsif: " . 7419: join(', ', @if_values)); 7420: return; 7421: } 7422: 7423: # Pattern 6: Smart match (~~) with array ●7424 → 7424 → 0 7424: if ($code =~ /\$$param\s*~~\s*\[([^\]]+)\]/ || 7425: $code =~ /\$$param\s*~~\s*qw\s*[\(\[<{]([^)\]>}]+)[\)\]>}]/) { 7426: my $values_str = $1; 7427: my @enum_values; 7428: if ($values_str =~ /['"]/) { 7429: @enum_values = $values_str =~ /['"](.*?)['"]/g; 7430: } else { 7431: @enum_values = split(/\s+/, $values_str); 7432: } 7433: if (@enum_values) { 7434: $p->{type} = 'string' unless $p->{type}; 7435: $p->{enum} = \@enum_values; 7436: $p->{semantic} = 'enum'; 7437: $self->_log(" ADVANCED: $param validated with smart match: " . 7438: join(', ', @enum_values)); 7439: return; 7440: } 7441: } 7442: } 7443: 7444: # -------------------------------------------------- 7445: # _extract_error_constraints 7446: # 7447: # Purpose: Extract invalid-value constraints and 7448: # error messages from die/croak patterns
Mutants (Total: 1, Killed: 1, Survived: 0)
7449: # referencing a specific parameter, and 7450: # infer numeric bounds from comparisons 7451: # with literals. 7452: # 7453: # Entry: $p_ref - reference to the parameter 7454: # hashref (modified in place). 7455: # $param - parameter name string. 7456: # $code - method body source string. 7457: # 7458: # Exit: Returns nothing. May add _invalid, 7459: # _errors, min, and/or max to the 7460: # referenced parameter hashref. 7461: # 7462: # Side effects: Logs detections to stdout when 7463: # verbose is set. 7464: # -------------------------------------------------- 7465: sub _extract_error_constraints { ●7466 → 7469 → 7525 7466: my ($self, $p, $param, $code) = @_; 7467: 7468: # Look for die/croak/confess with a condition involving this param 7469: while ($code =~ / 7470: (?:die|croak|confess) # error call 7471: \s* 7472: (?: 7473: ["']([^"']+)["'] # captured error message 7474: | 7475: q[qw]?\s*[\(\[]([^)\]]+)[\)\]] # q(), qq(), qw() 7476: )? 7477: \s* 7478: if\s+ 7479: (.+?) # condition 7480: \s*; 7481: /gsx) { 7482: 7483: my $message = $1 || $2; 7484: my $condition = $3; 7485: 7486: # Only keep conditions that reference this parameter 7487: next unless $condition =~ /\$$param\b/; 7488: 7489: # Initialize storage 7490: $$p->{_invalid} ||= []; 7491: $$p->{_errors} ||= []; 7492: 7493: # Normalize condition (strip surrounding parens) 7494: $condition =~ s/^\(|\)$//g; 7495: $condition =~ s/\s+/ /g; 7496: 7497: # Try to extract a meaningful invalid constraint 7498: my $constraint; 7499: 7500: # Examples: 7501: # $age <= 0 7502: # $x eq '' 7503: # length($s) < 3 7504: if ($condition =~ /\$$param\s*([!<>=]=?|eq|ne|lt|gt|le|ge)\s*(.+)/) { 7505: $constraint = "$1 $2"; 7506: } 7507: elsif ($condition =~ /length\s*\(\s*\$$param\s*\)\s*([<>=!]+)\s*(\d+)/) { 7508: $constraint = "length $1 $2"; 7509: } 7510: elsif ($condition =~ /\$$param\s*==\s*0/) { 7511: $constraint = '== 0'; 7512: } 7513: 7514: # Store results 7515: push @{ $$p->{_invalid} }, $constraint if $constraint; 7516: push @{ $$p->{_errors} }, $message if defined $message; 7517: 7518: $self->_log( 7519: " ERROR: $param invalid when [$condition]" .
Mutants (Total: 2, Killed: 2, Survived: 0)
7520: (defined $message ? " => '$message'" : '') 7521: ); 7522: } 7523: 7524: # Numeric comparison with literal ●7525 → 7525 → 0 7525: if ($code =~ /\b\Q$param\E\s*(<=|<|>=|>)\s*(-?\d+)/) { 7526: my ($op, $num) = ($1, $2); 7527: 7528: # Mark required 7529: $$p->{optional} = 0; 7530: 7531: if ($op eq '<=') { 7532: $$p->{min} = $num + 1; 7533: } elsif ($op eq '<') { 7534: $$p->{min} = $num; 7535: } elsif ($op eq '>=') { 7536: $$p->{max} = $num - 1; 7537: } elsif ($op eq '>') { 7538: $$p->{max} = $num; 7539: } 7540: 7541: $self->_log(" ERROR: $param normalized constraint from '$op $num'"); 7542: } 7543: } 7544: 7545: # -------------------------------------------------- 7546: # _extract_parameters_from_signature 7547: #
Mutants (Total: 1, Killed: 1, Survived: 0)
7548: # Purpose: Extract parameter names and positions 7549: # from a method's signature, trying 7550: # modern Perl subroutine signatures 7551: # first and falling back to traditional 7552: # @_ extraction styles. 7553: # 7554: # Entry: $params - hashref to populate with 7555: # parameter specs (modified 7556: # in place). 7557: # $code - method body source string. 7558: # 7559: # Exit: Returns nothing. Populates $params. 7560: # 7561: # Side effects: Logs detections to stdout when 7562: # verbose is set. 7563: #
Mutants (Total: 1, Killed: 1, Survived: 0)
7564: # Notes: Three traditional styles are 7565: # supported: (1) my ($self, ...) = @_, 7566: # (2) my $self = shift; my $x = shift, 7567: # (3) my $x = $_[N]. $self and $class 7568: # are always excluded from the returned
Mutants (Total: 2, Killed: 2, Survived: 0)
7569: # parameters. 7570: # -------------------------------------------------- 7571: sub _extract_parameters_from_signature { ●7572 → 7585 → 7599 7572: my ($self, $params, $code) = @_; 7573: 7574: # Modern Style: Subroutine signatures with attributes 7575: # Handle multi-line signatures 7576: # sub foo :attr1 :attr2(val) ( 7577: # $self, 7578: # $x :Type, 7579: # $y = default 7580: # ) { } 7581: 7582: # Try to match signature after attributes 7583: # Look for the parameter list - it's the last (...) before the opening brace 7584: # that contains sigils ($, %, @) 7585: if ($code =~ /sub\s+\w+\s*(?::\w+(?:\([^)]*\))?\s*)*\(((?:[^()]|\([^)]*\))*)\)\s*\{/s) { 7586: my $potential_sig = $1; 7587: 7588: # Check if this looks like parameters (has sigils) 7589: if ($potential_sig =~ /[\$\%\@]/) { 7590: $self->_log(" SIG: Found modern signature: ($potential_sig)"); 7591: $self->_parse_modern_signature($params, $potential_sig); 7592: return; 7593: } 7594: } 7595: 7596: # Direct-index style: my $self = $_[0]; my $arg = $_[1]; ... 7597: # Must be checked before Style 1 to avoid matching @_ inside closures 7598: # defined in the body of a method that uses this style. ●7599 → 7599 → 7611 7599: if($code =~ /my\s+\$(?:self|class)\s*=\s*\$_\[0\]/) { 7600: my $pos = 0; 7601: while($code =~ /my\s+\$(\w+)\s*=\s*\$_\[(\d+)\]/g) { 7602: my $name = $1;
Mutants (Total: 1, Killed: 1, Survived: 0)
7603: next if $name =~ /^(self|class|pkg|proto|klass)$/i; 7604: $params->{$name} //= { _source => SOURCE_CODE, optional => 1, position => $pos++ }; 7605: $self->_log(" CODE: Found direct-index parameter '\$$name' at \$_[$2]"); 7606: } 7607: return; 7608: }
Mutants (Total: 1, Killed: 1, Survived: 0)
7609: 7610: # Traditional Style 1: my ($self, $arg1, $arg2) = @_; ●7611 → 7611 → 7645 7611: if ($code =~ /my\s*\(\s*([^)]+)\)\s*=\s*\@_/s) { 7612: my $sig = $1; 7613: my $pos = 0; 7614: 7615: while ($sig =~ /\$(\w+)/g) { 7616: my $name = $1; 7617: 7618: next if $name =~ /^(self|class|pkg|proto|klass)$/i; 7619: 7620: $params->{$name} //= { 7621: _source => SOURCE_CODE, 7622: optional => 1, 7623: }; 7624: 7625: $params->{$name}{position} = $pos unless exists $params->{$name}{position}; 7626: 7627: $pos++;
Mutants (Total: 1, Killed: 1, Survived: 0)
7628: } 7629: return; 7630: } elsif ($code =~ /my\s+\$self\s*=\s*shift/) { 7631: # Traditional Style 2: my $self = shift; my $arg1 = shift; 7632: my @shifts;
7633: while ($code =~ /my\s+\$(\w+)\s*=\s*shift/g) { 7634: push @shifts, $1; 7635: } 7636: shift @shifts if @shifts && $shifts[0] =~ /^(self|class|pkg|proto|klass)$/i; 7637: my $pos = 0; 7638: foreach my $param (@shifts) { 7639: $params->{$param} ||= { _source => SOURCE_CODE, optional => 1, position => $pos++ }; 7640: } 7641: return; 7642: } 7643: 7644: # Traditional Style 3: Function parameters (no $self) ●7645 → 7645 → 7656 7645: if ($code =~ /my\s*\(\s*([^)]+)\)\s*=\s*\@_/s) { 7646: my $sig = $1; 7647: my @param_names = $sig =~ /\$(\w+)/g; 7648: my $pos = 0; 7649: foreach my $param (@param_names) { 7650: next if $param =~ /^(self|class|pkg|proto|klass)$/i; 7651: $params->{$param} ||= { _source => SOURCE_CODE, optional => 1, position => $pos++ }; 7652: }Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_7632_6: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 2, Killed: 2, Survived: 0)
7653: } 7654: 7655: # De-duplicate ●7656 → 7657 → 0 7656: my %seen; 7657: foreach my $param (keys %$params) { 7658: if ($seen{$param}++) { 7659: $self->_log(" WARNING: Duplicate parameter '$param' found"); 7660: } 7661: } 7662: } 7663: 7664: # -------------------------------------------------- 7665: # _parse_modern_signature 7666: # 7667: # Purpose: Parse a Perl 5.20+ subroutine 7668: # signature string into individual 7669: # parameter specs, respecting nested 7670: # structures when splitting on commas. 7671: # 7672: # Entry: $params - hashref to populate 7673: # (modified in place). 7674: # $sig - signature string with outer 7675: # parentheses already removed. 7676: # 7677: # Exit: Returns nothing. Populates $params 7678: # via _parse_signature_parameter. 7679: # 7680: # Side effects: Logs parsing details to stdout when 7681: # verbose is set. 7682: # -------------------------------------------------- 7683: sub _parse_modern_signature { ●7684 → 7695 → 7713 7684: my ($self, $params, $sig) = @_; 7685:
Mutants (Total: 1, Killed: 1, Survived: 0)
7686: $self->_log(" DEBUG: Parsing signature: [$sig]"); 7687: 7688: # Split signature by commas, but respect nested structures (e.g. a 7689: # default value containing a hashref/arrayref literal) 7690: require Text::Balanced; 7691: my @parts;
Mutants (Total: 1, Killed: 1, Survived: 0)
7692: my $current = ''; 7693: my $rest = $sig; 7694: 7695: while (length $rest) { 7696: if (substr($rest, 0, 1) =~ /[(\[{]/) { 7697: # extract_bracketed advances $rest past the extracted block 7698: # in place, so $rest must not be re-truncated afterwards 7699: my $extracted = Text::Balanced::extract_bracketed($rest, '(){}[]'); 7700: last unless defined $extracted; # Unbalanced brackets 7701: $current .= $extracted; 7702: next; 7703: } 7704: if (substr($rest, 0, 1) eq ',') { 7705: push @parts, $current; 7706: $current = ''; 7707: $rest = substr($rest, 1); 7708: next; 7709: } 7710: $current .= substr($rest, 0, 1); 7711: $rest = substr($rest, 1);
Mutants (Total: 1, Killed: 1, Survived: 0)
7712: } ●7713 → 7717 → 0 7713: push @parts, $current if $current =~ /\S/; 7714: 7715: my $position = 0; 7716:
7717: foreach my $part (@parts) { 7718: $part =~ s/^\s+|\s+$//g; 7719: 7720: # Skip empty parts 7721: next unless $part; 7722: 7723: # Parse different parameter types 7724: my $param_info = $self->_parse_signature_parameter($part, $position); 7725: 7726: if ($param_info) { 7727: my $name = $param_info->{name}; 7728: 7729: # Skip self/class 7730: if ($name =~ /^(self|class|pkg|proto|klass)$/i) { 7731: next; 7732: } 7733: 7734: $params->{$name} = $param_info; 7735: $self->_log(" SIG: $name has position $position" . 7736: ($param_info->{optional} ? ' (optional)' : '') . 7737: ($param_info->{_default} ? ", default: $param_info->{_default}" : ''));Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_7716_6: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 2, Killed: 2, Survived: 0)
7738: $position++; 7739: } 7740: } 7741: } 7742: 7743: # -------------------------------------------------- 7744: # _parse_signature_parameter 7745: # 7746: # Purpose: Parse a single parameter declaration 7747: # from a modern Perl signature, handling 7748: # type constraints, default values, 7749: # plain scalars, and slurpy array/hash 7750: # parameters. 7751: # 7752: # Entry: $part - a single parameter string 7753: # (one comma-separated 7754: # element from the signature). 7755: # $position - zero-based position index 7756: # of this parameter. 7757: # 7758: # Exit: Returns a parameter info hashref on 7759: # success, or undef if the string does 7760: # not match any known pattern. 7761: # 7762: # Side effects: None. 7763: # 7764: # Notes: Six patterns are tried in order: 7765: # (1) :Type with default, 7766: # (2) :Type without default, 7767: # (3) default without type, 7768: # (4) plain $name, 7769: # (5) slurpy @name, 7770: # (6) slurpy %name. 7771: # --------------------------------------------------
Mutants (Total: 1, Killed: 1, Survived: 0)
7772: sub _parse_signature_parameter { ●7773 → 7782 → 7872 7773: my ($self, $part, $position) = @_; 7774: 7775: my %info = ( 7776: _source => SOURCE_SIGNATURE, 7777: position => $position, 7778: optional => 0, 7779: ); 7780: 7781: # Pattern 1: Type constraint WITH default: $name :Type = default 7782: if ($part =~ /^\$(\w+)\s*:\s*(\w+)\s*=\s*(.+)$/s) { 7783: my ($name, $constraint, $default) = ($1, $2, $3);
Mutants (Total: 1, Killed: 1, Survived: 0)
7784: $default =~ s/^\s+|\s+$//g; 7785: 7786: $info{name} = $name; 7787: $info{optional} = 1; 7788: $info{_default} = $self->_clean_default_value($default, 1); 7789: 7790: # Apply type constraint 7791: if ($constraint =~ /^(Int|Integer)$/i) { 7792: $info{type} = 'integer'; 7793: } elsif ($constraint =~ /^(Num|Number)$/i) { 7794: $info{type} = 'number'; 7795: } elsif ($constraint =~ /^(Str|String)$/i) {
Mutants (Total: 1, Killed: 1, Survived: 0)
7796: $info{type} = 'string'; 7797: } elsif ($constraint =~ /^(Bool|Boolean)$/i) { 7798: $info{type} = 'boolean'; 7799: } elsif ($constraint =~ /^(Array|ArrayRef)$/i) { 7800: $info{type} = 'arrayref'; 7801: } elsif ($constraint =~ /^(Hash|HashRef)$/i) { 7802: $info{type} = 'hashref'; 7803: } else { 7804: $info{type} = 'object'; 7805: $info{isa} = $constraint; 7806: } 7807: 7808: return \%info;
Mutants (Total: 2, Killed: 2, Survived: 0)
7809: } elsif ($part =~ /^\$(\w+)\s*:\s*(\w+)\s*$/s) { 7810: # Pattern 2: Type constraint WITHOUT default: $name :Type 7811: my ($name, $constraint) = ($1, $2); 7812: $info{name} = $name; 7813: $info{optional} = 0; 7814: 7815: # Apply type constraint (same as above) 7816: if ($constraint =~ /^(Int|Integer)$/i) { 7817: $info{type} = 'integer'; 7818: } elsif ($constraint =~ /^(Num|Number)$/i) { 7819: $info{type} = 'number'; 7820: } elsif ($constraint =~ /^(Str|String)$/i) { 7821: $info{type} = 'string'; 7822: } elsif ($constraint =~ /^(Bool|Boolean)$/i) { 7823: $info{type} = 'boolean'; 7824: } elsif ($constraint =~ /^(Array|ArrayRef)$/i) { 7825: $info{type} = 'arrayref'; 7826: } elsif ($constraint =~ /^(Hash|HashRef)$/i) { 7827: $info{type} = 'hashref'; 7828: } else { 7829: $info{type} = 'object'; 7830: $info{isa} = $constraint; 7831: } 7832: 7833: return \%info; 7834: } elsif ($part =~ /^\$(\w+)\s*=\s*(.+)$/s) { 7835: # Pattern 3: Default WITHOUT type: $name = default 7836: my ($name, $default) = ($1, $2); 7837: $default =~ s/^\s+|\s+$//g; 7838: 7839: $info{name} = $name; 7840: $info{optional} = 1; 7841: $info{_default} = $self->_clean_default_value($default, 1); 7842: $info{type} = $self->_infer_type_from_default($info{_default}) if $self->can('_infer_type_from_default');
Mutants (Total: 1, Killed: 1, Survived: 0)
7843: 7844: return \%info; 7845: } 7846: 7847: # Pattern 4: Plain parameter: $name 7848: elsif ($part =~ /^\$(\w+)$/s) { 7849: $info{name} = $1; 7850: $info{optional} = 0; 7851: return \%info; 7852: } 7853: 7854: # Pattern 5: Array parameter: @name 7855: elsif ($part =~ /^\@(\w+)$/s) { 7856: $info{name} = $1; 7857: $info{type} = 'array';
Mutants (Total: 2, Killed: 2, Survived: 0)
7858: $info{slurpy} = 1; 7859: $info{optional} = 1; 7860: return \%info; 7861: } 7862: 7863: # Pattern 6: Hash parameter: %name 7864: elsif ($part =~ /^\%(\w+)$/s) { 7865: $info{name} = $1; 7866: $info{type} = 'hash'; 7867: $info{slurpy} = 1; 7868: $info{optional} = 1; 7869: return \%info; 7870: } 7871: 7872: return undef; 7873: } 7874: 7875: # -------------------------------------------------- 7876: # _infer_type_from_default 7877: # 7878: # Purpose: Infer a parameter type from its 7879: # default value when no explicit type 7880: # annotation is available. 7881: # 7882: # Entry: $default - the cleaned default value 7883: # scalar, hashref, or 7884: # arrayref. May be undef. 7885: # 7886: # Exit: Returns a type string ('hashref', 7887: # 'arrayref', 'integer', 'number', 7888: # 'boolean', 'string'), or undef if 7889: # $default is undef. 7890: #
Mutants (Total: 1, Killed: 1, Survived: 0)
7891: # Side effects: None. 7892: # -------------------------------------------------- 7893: sub _infer_type_from_default { ●7894 → 7898 → 0 7894: my ($self, $default) = @_; 7895: 7896: return undef unless defined $default; 7897: 7898: if (ref($default) eq 'HASH') { 7899: return 'hashref'; 7900: } elsif (ref($default) eq 'ARRAY') { 7901: return 'arrayref'; 7902: } elsif ($default =~ /^-?\d+$/) { 7903: return 'integer'; 7904: } elsif ($default =~ /^-?\d+\.\d+$/) { 7905: return 'number';
7906: } elsif ($default eq '1' || $default eq '0') { 7907: return 'boolean'; 7908: } else { 7909: return 'string'; 7910: } 7911: } 7912: 7913: # -------------------------------------------------- 7914: # _extract_subroutine_attributes 7915: # 7916: # Purpose: Extract Perl subroutine attributes 7917: # (e.g. :lvalue, :method, :Returns(Int)) 7918: # from a method's source string. 7919: # 7920: # Entry: $code - method body source string.Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_7905_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
7921: # 7922: # Exit: Returns a hashref of attribute name 7923: # to value (1 for flag-only attributes, 7924: # the attribute argument string for 7925: # attributes with values). 7926: # Returns an empty hashref if no 7927: # attributes are found. 7928: # 7929: # Side effects: Logs detections to stdout when 7930: # verbose is set. 7931: # -------------------------------------------------- 7932: sub _extract_subroutine_attributes { ●7933 → 7945 → 7950 7933: my ($self, $code) = @_; 7934: 7935: my %attributes;
Mutants (Total: 2, Killed: 2, Survived: 0)
7936: 7937: # Extract all attributes from the sub declaration 7938: # Attributes are :name or :name(value) between sub name and either ( or { 7939: # Pattern: sub name ATTRIBUTES ( params ) { } 7940: # or: sub name ATTRIBUTES { } 7941: 7942: # First, find the attributes section (everything between sub name and ( or { ) 7943: my $attr_section = ''; 7944: 7945: if($code =~ /sub\s+\w+\s+((?::\w+(?:\([^)]*\))?\s*)+)/s) { 7946: $attr_section = $1; 7947: } 7948: 7949: # Parse individual attributes from the section ●7950 → 7950 → 7965 7950: if($attr_section) { 7951: while($attr_section =~ /:(\w+)(?:\(([^)]*)\))?/g) { 7952: my ($name, $value) = ($1, $2); 7953: 7954: if (defined $value && $value ne '') { 7955: $attributes{$name} = $value; 7956: $self->_log(" ATTR: Found attribute :$name($value)"); 7957: } else { 7958: $attributes{$name} = 1; 7959: $self->_log(" ATTR: Found attribute :$name"); 7960: } 7961: }
Mutants (Total: 1, Killed: 1, Survived: 0)
7962: } 7963: 7964: # Process common attributes ●7965 → 7965 → 7972 7965: if ($attributes{Returns}) { 7966: my $return_type = $attributes{Returns}; 7967: if ($return_type ne '1') { # Only log if it's an actual type, not just the flag 7968: $self->_log(" ATTR: Method declares return type: $return_type"); 7969: } 7970: } 7971: ●7972 → 7972 → 7976 7972: if ($attributes{lvalue}) { 7973: $self->_log(" ATTR: Method is lvalue (can be assigned to)"); 7974: } 7975: ●7976 → 7976 → 7980 7976: if ($attributes{method}) { 7977: $self->_log(' ATTR: Method explicitly marked as :method'); 7978: } 7979: 7980: return \%attributes; 7981: } 7982: 7983: # --------------------------------------------------
Mutants (Total: 1, Killed: 1, Survived: 0)
7984: # _analyze_postfix_dereferencing
Mutants (Total: 1, Killed: 1, Survived: 0)
7985: # 7986: # Purpose: Detect usage of Perl 5.20+ postfix 7987: # dereferencing syntax in a method body 7988: # and record which dereference forms 7989: # are used.
Mutants (Total: 1, Killed: 1, Survived: 0)
7990: # 7991: # Entry: $code - method body source string.
Mutants (Total: 1, Killed: 1, Survived: 0)
7992: # 7993: # Exit: Returns a hashref whose keys are 7994: # dereference form names (array_deref, 7995: # hash_deref, scalar_deref, code_deref, 7996: # array_slice, hash_slice) with value 1 7997: # when detected. 7998: # Returns an empty hashref if no 7999: # postfix dereferencing is found. 8000: # 8001: # Side effects: Logs detections to stdout when 8002: # verbose is set. 8003: # -------------------------------------------------- 8004: sub _analyze_postfix_dereferencing { ●8005 → 8010 → 8016 8005: my ($self, $code) = @_; 8006: 8007: my %derefs;
8008: 8009: # Array dereference: $ref->@* 8010: if ($code =~ /\$\w+\s*->\s*\@\*/) { 8011: $derefs{array_deref} = 1; 8012: $self->_log(" MODERN: Uses postfix array dereferencing (->@*)"); 8013: } 8014: 8015: # Hash dereference: $ref->%* ●8016 → 8016 → 8022 8016: if ($code =~ /\$\w+\s*->\s*\%\*/) {Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_8007_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes8017: $derefs{hash_deref} = 1;Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_8016_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 2, Killed: 2, Survived: 0)
8018: $self->_log(" MODERN: Uses postfix hash dereferencing (->%*)"); 8019: } 8020: 8021: # Scalar dereference: $ref->$* ●8022 → 8022 → 8028 8022: if ($code =~ /\$\w+\s*->\s*\$\*/) { 8023: $derefs{scalar_deref} = 1;
Mutants (Total: 1, Killed: 1, Survived: 0)
8024: $self->_log(' MODERN: Uses postfix scalar dereferencing (->$*)'); 8025: } 8026: 8027: # Code dereference: $ref->&* ●8028 → 8028 → 8034 8028: if ($code =~ /\$\w+\s*->\s*\&\*/) { 8029: $derefs{code_deref} = 1;
Mutants (Total: 1, Killed: 1, Survived: 0)
8030: $self->_log(" MODERN: Uses postfix code dereferencing (->&*)"); 8031: }
Mutants (Total: 1, Killed: 1, Survived: 0)
8032: 8033: # Array element: $ref->@[0,2,4] ●8034 → 8034 → 8040 8034: if ($code =~ /\$\w+\s*->\s*\@\[/) { 8035: $derefs{array_slice} = 1; 8036: $self->_log(" MODERN: Uses postfix array slice (->@[...])"); 8037: } 8038: 8039: # Hash element: $ref->%{key1,key2} ●8040 → 8040 → 8045 8040: if ($code =~ /\$\w+\s*->\s*\%\{/) {
Mutants (Total: 1, Killed: 1, Survived: 0)
8041: $derefs{hash_slice} = 1; 8042: $self->_log(" MODERN: Uses postfix hash slice (->%{...})"); 8043: }
8044: 8045: return \%derefs; 8046: } 8047: 8048: # --------------------------------------------------Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_8043_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
8049: # _extract_field_declarations 8050: # 8051: # Purpose: Extract Perl 5.38 field declarations 8052: # from a class body or method source
Mutants (Total: 1, Killed: 1, Survived: 0)
8053: # string, capturing field names, 8054: # :param attributes, default values, 8055: # and :isa type constraints. 8056: # 8057: # Entry: $code - source string potentially 8058: # containing 'field $name ...' 8059: # declarations. 8060: # 8061: # Exit: Returns a hashref of field name to 8062: # field_info hashref. Returns an empty 8063: # hashref if no field declarations 8064: # are found. 8065: # 8066: # Side effects: Logs detections to stdout when 8067: # verbose is set. 8068: # -------------------------------------------------- 8069: sub _extract_field_declarations { ●8070 → 8078 → 8122 8070: my ($self, $code) = @_; 8071: 8072: my %fields; 8073: 8074: # Pattern: field $name :param; 8075: # Pattern: field $name :param(name); 8076: # Pattern: field $name = default; 8077: # More lenient pattern to catch various formats 8078: while ($code =~ /^\s*field\s+\$(\w+)\s*([^;]*);/gm) { 8079: my ($name, $modifiers) = ($1, $2); 8080: 8081: $self->_log(" FIELD: Found field \$$name with modifiers: [$modifiers]"); 8082: 8083: my %field_info = ( 8084: name => $name, 8085: _source => SOURCE_FIELD 8086: ); 8087: 8088: # Check for :param attribute 8089: if ($modifiers =~ /:param(?:\(([^)]+)\))?/) { 8090: $field_info{is_param} = 1; 8091: 8092: if (defined $1) { 8093: # Explicit parameter name 8094: $field_info{param_name} = $1; 8095: } else { 8096: # Implicit - field name is param name 8097: $field_info{param_name} = $name; 8098: } 8099: 8100: $self->_log(" FIELD: $name maps to parameter: $field_info{param_name}"); 8101: } 8102: 8103: # Check for default value - must come before type constraint check
Mutants (Total: 1, Killed: 1, Survived: 0)
8104: if ($modifiers =~ /=\s*([^:;]+)(?::|;|$)/) { 8105: my $default = $1; 8106: $default =~ s/\s+$//; 8107: $field_info{_default} = $self->_clean_default_value($default, 1); 8108: $field_info{optional} = 1;
8109: $self->_log(" FIELD: $name has default: " . (defined $field_info{_default} ? $field_info{_default} : 'undef')); 8110: } 8111: 8112: # Check for type constraintsMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_8108_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
8113: if ($modifiers =~ /:isa\(([^)]+)\)/) { 8114: $field_info{isa} = $1; 8115: $field_info{type} = 'object'; 8116: $self->_log(" FIELD: $name has type constraint: $1");
8117: } 8118: 8119: $fields{$name} = \%field_info; 8120: } 8121:Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_8116_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
8122: return \%fields; 8123: } 8124: 8125: # -------------------------------------------------- 8126: # _merge_field_declarations 8127: # 8128: # Purpose: Integrate Perl 5.38 field declarations 8129: # that carry the :param attribute into 8130: # the code parameter hashref, so they 8131: # appear as constructor parameters in
Mutants (Total: 1, Killed: 1, Survived: 0)
8132: # the generated schema. 8133: # 8134: # Entry: $params - hashref of parameters 8135: # extracted from code analysis 8136: # (modified in place). 8137: # $fields - hashref of field declarations 8138: # as returned by 8139: # _extract_field_declarations. 8140: # 8141: # Exit: Returns nothing. Modifies $params 8142: # in place. 8143: #
Mutants (Total: 1, Killed: 1, Survived: 0)
8144: # Side effects: Logs merges to stdout when verbose 8145: # is set. 8146: # 8147: # Notes: Only fields with is_param => 1 are 8148: # merged. The param_name key in the 8149: # field (which may differ from the 8150: # field name if :param(name) was used) 8151: # determines the parameter key.
8152: # -------------------------------------------------- 8153: sub _merge_field_declarations { ●8154 → 8156 → 0 8154: my ($self, $params, $fields) = @_; 8155: 8156: foreach my $field_name (keys %$fields) { 8157: my $field = $fields->{$field_name}; 8158: 8159: # Only process fields that are parameters 8160: next unless $field->{is_param}; 8161: 8162: my $param_name = $field->{param_name}; 8163: 8164: # Create or update parameter info 8165: $params->{$param_name} ||= {}; 8166: my $p = $params->{$param_name}; 8167: 8168: # Merge field information into parameter 8169: $p->{_source} = SOURCE_FIELD unless $p->{_source}; 8170: $p->{field_name} = $field_name if $field_name ne $param_name; 8171:Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_8151_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
8172: if ($field->{_default}) { 8173: $p->{_default} = $field->{_default}; 8174: $p->{optional} = 1; 8175: }
Mutants (Total: 1, Killed: 1, Survived: 0)
8176: 8177: if ($field->{isa}) { 8178: $p->{isa} = $field->{isa}; 8179: $p->{type} = 'object';
8180: } 8181: 8182: $self->_log(" MERGED: Field $field_name -> parameter $param_name"); 8183: }Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_8179_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes8184: } 8185: 8186: # -------------------------------------------------- 8187: # _extract_defaults_from_code 8188: # 8189: # Purpose: Scan a method body for default valueMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_8183_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
8190: # assignment patterns and populate the 8191: # optional and _default fields of 8192: # known parameters. 8193: # 8194: # Entry: $params - hashref of parameters 8195: # (modified in place). 8196: # $code - method body source string. 8197: # $method - method hashref, used for 8198: # constructor-specific 8199: # exclusions of $class and
Mutants (Total: 2, Killed: 2, Survived: 0)
8200: # $self. 8201: # 8202: # Exit: Returns nothing. Modifies $params 8203: # in place. 8204: # 8205: # Side effects: Logs detections to stdout when 8206: # verbose is set. 8207: # 8208: # Notes: Eight default patterns are tried. 8209: # Only parameters already present in 8210: # $params are updated â this method 8211: # does not add new parameters. 8212: # Falls back to extracting all @_ 8213: # assignments if $params is empty 8214: # after the main pass. 8215: # -------------------------------------------------- 8216: sub _extract_defaults_from_code { ●8217 → 8220 → 8231 8217: my ($self, $params, $code, $method) = @_; 8218: 8219: # Pattern 1: my $param = value; 8220: while ($code =~ /my\s+\$(\w+)\s*=\s*([^;]+);/g) { 8221: my ($param, $value) = ($1, $2); 8222: next unless exists $params->{$param}; 8223: next if $value =~ /->/; # deref/method call, not a default value 8224: 8225: $params->{$param}{_default} = $self->_clean_default_value($value, 1); 8226: $params->{$param}{optional} = 1; 8227: $self->_log(" CODE: $param has default: " . $self->_format_default($params->{$param}{_default})); 8228: } 8229: 8230: # Pattern 2: $param = value unless defined $param; ●8231 → 8231 → 8241 8231: while ($code =~ /\$(\w+)\s*=\s*([^;]+?)\s+unless\s+(?:defined\s+)?\$\1/g) { 8232: my ($param, $value) = ($1, $2); 8233: next unless exists $params->{$param}; 8234: 8235: $params->{$param}{_default} = $self->_clean_default_value($value, 1); 8236: $params->{$param}{optional} = 1; 8237: $self->_log(" CODE: $param has default (unless): " . $self->_format_default($params->{$param}{_default})); 8238: } 8239: 8240: # Pattern 3: $param = value unless $param;
Mutants (Total: 1, Killed: 1, Survived: 0)
●8241 → 8241 → 8251 8241: while ($code =~ /\$(\w+)\s*=\s*([^;]+?)\s+unless\s+\$\1/g) {
Mutants (Total: 1, Killed: 1, Survived: 0)
8242: my ($param, $value) = ($1, $2); 8243: next unless exists $params->{$param}; 8244: 8245: $params->{$param}{_default} = $self->_clean_default_value($value, 1); 8246: $params->{$param}{optional} = 1; 8247: $self->_log(" CODE: $param has default (unless): " . $self->_format_default($params->{$param}{_default})); 8248: } 8249: 8250: # Pattern 4: $param = $param || 'default'; ●8251 → 8251 → 8261 8251: while ($code =~ /\$(\w+)\s*=\s*\$\1\s*\|\|\s*([^;]+);/g) { 8252: my ($param, $value) = ($1, $2); 8253: next unless exists $params->{$param}; 8254: 8255: $params->{$param}{_default} = $self->_clean_default_value($value, 1); 8256: $params->{$param}{optional} = 1; 8257: $self->_log(" CODE: $param has default (||): " . $self->_format_default($params->{$param}{_default})); 8258: } 8259: 8260: # Pattern 5: $param ||= 'default'; ●8261 → 8261 → 8271 8261: while ($code =~ /\$(\w+)\s*\|\|=\s*([^;]+);/g) { 8262: my ($param, $value) = ($1, $2); 8263: next unless exists $params->{$param}; 8264: 8265: $params->{$param}{_default} = $self->_clean_default_value($value, 1); 8266: $params->{$param}{optional} = 1; 8267: $self->_log(" CODE: $param has default (||=): " . $self->_format_default($params->{$param}{_default})); 8268: } 8269: 8270: # Pattern 6: $param //= 'default'; ●8271 → 8271 → 8282 8271: while ($code =~ /\$(\w+)\s*\/\/=\s*([^;]+);/g) { 8272: my ($param, $value) = ($1, $2); 8273: next unless exists $params->{$param}; # Using -> because $params is a reference 8274: 8275: $params->{$param}{_default} = $self->_clean_default_value($value, 1); 8276: 8277: $params->{$param}{optional} = 1; 8278: $self->_log(" CODE: $param has default (//=): " . $self->_format_default($params->{$param}{_default})); 8279: } 8280: 8281: # Pattern 7: $param = defined $param ? $param : 'default'; ●8282 → 8282 → 8296 8282: while ($code =~ /\$(\w+)\s*=\s*defined\s+\$\1\s*\?\s*\$\1\s*:\s*([^;]+);/g) { 8283: my ($param, $value) = ($1, $2); 8284:
Mutants (Total: 1, Killed: 1, Survived: 0)
8285: # Create param entry if it doesn't exist 8286: $params->{$param} ||= {}; 8287: 8288: my $cleaned = $self->_clean_default_value($value, 1); 8289: 8290: $params->{$param}{_default} = $cleaned; 8291: $params->{$param}{optional} = 1; 8292: $self->_log(" CODE: $param has default (ternary): " . $self->_format_default($params->{$param}{_default})); 8293: } 8294:
Mutants (Total: 1, Killed: 1, Survived: 0)
8295: # Pattern 8: $param = $args{param} || 'default'; ●8296 → 8296 → 8306 8296: while ($code =~ /\$(\w+)\s*=\s*\$args\{['"]?\w+['"]?\}\s*\|\|\s*([^;]+);/g) { 8297: my ($param, $value) = ($1, $2);
Mutants (Total: 1, Killed: 1, Survived: 0)
8298: next unless exists $params->{$param}; 8299: 8300: $params->{$param}{_default} = $self->_clean_default_value($value, 1); 8301: $params->{$param}{optional} = 1; 8302: $self->_log(" CODE: $param has default (from args): " . $self->_format_default($params->{$param}{_default}));
Mutants (Total: 1, Killed: 1, Survived: 0)
8303: } 8304: 8305: # Pattern for non-empty hashref ●8306 → 8306 → 8322 8306: while ($code =~ /\$(\w+)\s*\|\|=\s*\{[^}]+\}/gs) { 8307: my $param = $1;
8308: next unless exists $params->{$param}; 8309: 8310: # Return empty hashref as placeholder (can't evaluate complex hashrefs) 8311: $params->{$param}{_default} = {}; 8312: $params->{$param}{optional} = 1; 8313: $self->_log(" CODE: $param has hashref default (||=)"); 8314: } 8315: 8316: # Fallback: extract parameters from classic Perl body stylesMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_8307_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 2, Killed: 2, Survived: 0)
8317: # Only run if signature extraction found nothing AND the code does not use 8318: # the direct-index ($_[0]) style â that style is used for no-param methods 8319: # whose empty %params would otherwise trigger this fallback and pick up 8320: # my (...) = @_ from inner closures as if they were method params. 8321: # TODO: On constructors, use $class to help to determine the output type ●8322 → 8322 → 0 8322: if (!keys %{$params} && $code !~ /my\s+\$(?:self|class|pkg|proto|klass)\s*=\s*\$_\[0\]/) { 8323: my $position = 0; 8324: 8325: # Style 1: my ($a, $b) = @_; 8326: while ($code =~ /my\s*\(\s*([^)]+)\s*\)\s*=\s*\@_/g) { 8327: my @vars = $1 =~ /\$(\w+)/g; 8328: foreach my $var (@vars) { 8329: if(($position == 0) && ($var =~ /^(self|class|pkg|proto|klass)$/i)) { 8330: # Invocant â skip it 8331: delete $params->{$var}; 8332: } else { 8333: $params->{$var} ||= { position => $position++ }; 8334: $self->_log(" CODE: $var extracted from \@_ list assignment"); 8335: } 8336: } 8337: } 8338: 8339: # Style 2: my $x = shift;
Mutants (Total: 1, Killed: 1, Survived: 0)
8340: while ($code =~ /my\s+\$(\w+)\s*=\s*shift\b/g) {
Mutants (Total: 2, Killed: 2, Survived: 0)
8341: my $var = $1; 8342: if(($position == 0) && ($var =~ /^(self|class|pkg|proto|klass)$/i)) {
Mutants (Total: 2, Killed: 2, Survived: 0)
8343: # Invocant â skip it 8344: delete $params->{$var};
Mutants (Total: 2, Killed: 2, Survived: 0)
8345: } else { 8346: $params->{$var} ||= { position => $position++ };
Mutants (Total: 2, Killed: 2, Survived: 0)
8347: $self->_log(" CODE: $var is extracted from shift"); 8348: }
Mutants (Total: 2, Killed: 2, Survived: 0)
8349: } 8350:
Mutants (Total: 2, Killed: 2, Survived: 0)
8351: # Style 3: my $x = $_[0]; 8352: while ($code =~ /my\s+\$(\w+)\s*=\s*\$_\[(\d+)\]/g) {
Mutants (Total: 2, Killed: 2, Survived: 0)
8353: my ($var, $index) = ($1, $2); 8354: if(($index > 0) || ($var !~ /^(self|class|pkg|proto|klass)$/i)) { 8355: $params->{$var} ||= { position => $index }; 8356: $self->_log(" CODE: $var is extracted from \$_\[$index\]"); 8357: } 8358: } 8359: } 8360: } 8361: 8362: # -------------------------------------------------- 8363: # _format_default 8364: # 8365: # Purpose: Format a default value for display 8366: # in verbose log output. 8367: # 8368: # Entry: $default - the default value to 8369: # format. May be undef, 8370: # a scalar, a hashref, or 8371: # an arrayref. 8372: # 8373: # Exit: Returns a display string: 'undef' 8374: # for undef, 'HASH ref' / 'ARRAY ref' 8375: # for references, or the value itself 8376: # for scalars. 8377: # 8378: # Side effects: None. 8379: # -------------------------------------------------- 8380: sub _format_default { 8381: my ($self, $default) = @_; 8382: return 'undef' unless defined $default; 8383: return ref($default) . ' ref' if ref($default); 8384: return $default; 8385: } 8386: 8387: # Resolve the right-hand side of a length comparison: a literal or a 8388: # Readonly/use-constant name. 8389: sub _length_constraint_value { 8390: my ($self, $rhs) = @_; 8391: 8392: return $rhs + 0 if $rhs =~ /^\d+$/;
8393: return undef unless $rhs =~ /^\$(\w+)$/; 8394: return $self->_module_constants()->{$1}; 8395: } 8396: 8397: # Record the accepted length range. When the comparison is an error 8398: # condition (an `if` guard), the accepted range is its negation. 8399: sub _record_length_constraint { ●8400 → 8402 → 8407 8400: my ($self, $p, $op, $val, $invert) = @_; 8401: 8402: if($invert) { 8403: my %negated = ('<' => '>=', '<=' => '>', '>' => '<=', '>=' => '<'); 8404: $op = $negated{$op}; 8405: } 8406: ●8407 → 8407 → 0 8407: if($op eq '<') { 8408: my $max = $val - 1; 8409: $p->{max} = $max if !defined($p->{max}) || $max < $p->{max}; 8410: } elsif($op eq '<=') { 8411: $p->{max} = $val if !defined($p->{max}) || $val < $p->{max}; 8412: } elsif($op eq '>') {Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_8392_2: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes🧪 Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_8392_2: Replace return expression with undef
LOW: Mutation survived, but impact may be minor🧪 Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );Mutants (Total: 1, Killed: 1, Survived: 0)
8413: my $min = $val + 1; 8414: $p->{min} = $min if !defined($p->{min}) || $min > $p->{min};
8415: } elsif($op eq '>=') { 8416: $p->{min} = $val if !defined($p->{min}) || $val > $p->{min};Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_8414_3: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes🧪 Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_8414_3: Replace return expression with undef
LOW: Mutation survived, but impact may be minor🧪 Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );8417: } 8418: } 8419: 8420: # Return ($op, $value) when a guard condition is exactly one length 8421: # comparison, or an empty list when the comparison is only one operand of a 8422: # compound condition. A compound condition enforces no bound of its own: 8423: # `croak ... if length($t) < 5 || $other` still croaks for long text when 8424: # $other is true, and `... if length($t) < 5 && $other` accepts short text 8425: # when $other is false. Only a condition that is nothing but the comparison 8426: # makes the negation of that comparison a real constraint. 8427: sub _whole_condition_length_guard {Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_8416_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes●8428 → 8434 → 8455 8428: my ($self, $param, $condition) = @_; 8429: 8430: $condition =~ s/^\s+//; 8431: $condition =~ s/\s+$//; 8432: 8433: # Drop balanced outer parentheses, as in `if (length($t) < 5)`. 8434: while($condition =~ /^\((.*)\)$/s) { 8435: my $inner = $1; 8436: my $depth = 0; 8437: my $balanced = 1; 8438: foreach my $char (split(//, $inner)) { 8439: if($char eq '(') {Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_8427_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
8440: $depth++; 8441: } elsif($char eq ')') { 8442: $depth--; 8443: if($depth < 0) { 8444: $balanced = 0; 8445: last; 8446: } 8447: }
8448: } 8449: last unless $balanced && ($depth == 0); 8450: $condition = $inner; 8451: $condition =~ s/^\s+//; 8452: $condition =~ s/\s+$//; 8453: } 8454: 8455: return unless $condition =~ /^length\s*\(\s*\$\Q$param\E\s*\)\s*([<>]=?)\s*(\d+|\$\w+)$/; 8456: 8457: my ($op, $rhs) = ($1, $2); 8458: my $val = $self->_length_constraint_value($rhs); 8459: return unless defined $val; 8460: 8461: return ($op, $val);Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_8447_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
8462: } 8463: 8464: # -------------------------------------------------- 8465: # _module_constants 8466: # 8467: # Purpose: Build and cache a hash of numeric 8468: # constant values declared in the target 8469: # module source, covering both Readonly 8470: # lexicals and 'use constant' barewords. 8471: # Used by _analyze_parameter_constraints 8472: # to resolve right-hand sides like 8473: # $MIN_NAME_LEN that are not literals.
8474: # 8475: # Entry: None (uses $self->{_document}). 8476: # 8477: # Exit: Returns a hashref { NAME => value }. 8478: # Returns {} if the PPI document is not 8479: # yet loaded. 8480: # 8481: # Side effects: Caches result in $self->{_constants}. 8482: # --------------------------------------------------Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_8473_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 2, Killed: 2, Survived: 0)
8483: sub _module_constants { ●8484 → 8489 → 8494 8484: my ($self) = @_; 8485: return $self->{_constants} if exists $self->{_constants}; 8486: 8487: my %c;
Mutants (Total: 1, Killed: 1, Survived: 0)
8488: my $doc = $self->{_document}; 8489: unless ($doc) { 8490: $self->{_constants} = \%c; 8491: return \%c; 8492: } 8493: ●8494 → 8497 → 8502 8494: my $src = $doc->serialize(); 8495: 8496: # Readonly my $CONST => numeric_value; 8497: while ($src =~ /Readonly\s+(?:my|our)\s+\$(\w+)\s*=>\s*([+-]?\d+(?:\.\d+)?)/g) {
8498: $c{$1} = $2; 8499: } 8500: 8501: # use constant CONST => numeric_value;Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_8497_3: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes🧪 Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_8497_3: Replace return expression with undef
LOW: Mutation survived, but impact may be minor🧪 Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );●8502 → 8502 → 8506 8502: while ($src =~ /use\s+constant\s+(\w+)\s*=>\s*([+-]?\d+(?:\.\d+)?)/g) { 8503: $c{$1} = $2; 8504: } 8505: 8506: $self->{_constants} = \%c; 8507: return \%c; 8508: } 8509: 8510: # --------------------------------------------------Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_8501_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 2, Killed: 2, Survived: 0)
8511: # _analyze_parameter_constraints 8512: # 8513: # Purpose: Infer min, max, and regex match 8514: # constraints for a single parameter 8515: # from length checks, numeric 8516: # comparisons, and regex match 8517: # patterns in the method body. 8518: # 8519: # Entry: $p_ref - reference to the parameter 8520: # hashref (modified in place). 8521: # $param - parameter name string. 8522: # $code - method body source string. 8523: # 8524: # Exit: Returns nothing. Modifies the 8525: # referenced parameter hashref. 8526: # 8527: # Side effects: Logs detections to stdout when 8528: # verbose is set. 8529: # 8530: # Notes: Numeric comparisons that appear 8531: # inside die/croak guard conditions 8532: # are excluded to avoid inferring 8533: # invalid-input ranges as valid 8534: # constraints. 8535: # -------------------------------------------------- 8536: sub _analyze_parameter_constraints { ●8537 → 8542 → 8551 8537: my ($self, $p_ref, $param, $code) = @_; 8538: my $p = $$p_ref; 8539: 8540: # Do not treat comparisons inside die/croak/confess as valid constraints 8541: my $guarded = 0; 8542: if ($code =~ /(die|croak|confess)\b[^{;]*\bif\b[^{;]*\$$param\b/s) { 8543: $guarded = 1;
Mutants (Total: 1, Killed: 1, Survived: 0)
8544: } 8545: 8546: # Length checks for strings. A comparison only describes the accepted 8547: # range when it guards an error: `croak ... unless length >= 5` accepts 8548: # >= 5, while `croak ... if length < 5` also accepts >= 5. Reading the
Mutants (Total: 1, Killed: 1, Survived: 0)
8549: # second condition literally would invent a max of 4 and can contradict 8550: # a min inferred from the first form.
Mutants (Total: 1, Killed: 1, Survived: 0)
●8551 → 8554 → 8562 8551: $p->{type} ||= 'string' if $code =~ /length\s*\(\s*\$$param\s*\)/; 8552: 8553: my $postfix_guards = $code; 8554: while ($postfix_guards =~ /\b(?:croak|die|confess)\b[^;{}]*?\b(if|unless)\b\s*([^;{}]+)/g) { 8555: my ($guard, $condition) = ($1, $2);
Mutants (Total: 1, Killed: 1, Survived: 0)
8556: my ($op, $val) = $self->_whole_condition_length_guard($param, $condition); 8557: next unless defined $op; 8558: $self->_record_length_constraint($p, $op, $val, ($guard eq 'if')); 8559: $self->_log(" CODE: $param length constraint from $guard guard: $op $val"); 8560: } 8561: ●8562 → 8563 → 8573 8562: my $block_guards = $code; 8563: while ($block_guards =~ /\b(if|unless)\s*\(\s*length\s*\(\s*\$$param\s*\)\s*([<>]=?)\s*(\d+|\$\w+)\s*\)\s*\{([^{}]*)\}/g) { 8564: my ($guard, $op, $rhs, $block) = ($1, $2, $3, $4); 8565: next unless $block =~ /\b(?:croak|die|confess)\b/;
Mutants (Total: 2, Killed: 2, Survived: 0)
8566: my $val = $self->_length_constraint_value($rhs); 8567: next unless defined $val; 8568: $self->_record_length_constraint($p, $op, $val, ($guard eq 'if')); 8569: $self->_log(" CODE: $param length constraint from $guard block: $op $rhs");
Mutants (Total: 1, Killed: 1, Survived: 0)
8570: } 8571: 8572: # Numeric range checks (only if NOT part of error guard) ●8573 → 8573 → 8591 8573: if ( 8574: !$guarded
8575: && $code =~ /\$$param\s*([<>]=?)\s*([+-]?(?:\d+\.?\d*|\.\d+))/ 8576: ) { 8577: my ($op, $val) = ($1, $2); 8578: $p->{type} ||= looks_like_number($val) ? 'number' : 'integer'; 8579: 8580: if ($op eq '<' || $op eq '<=') { 8581: # Only set max if it tightens the range 8582: my $max = ($op eq '<') ? $val - 1 : $val; 8583: $p->{max} = $max if !defined($p->{max}) || $max < $p->{max}; 8584: } elsif ($op eq '>' || $op eq '>=') { 8585: my $min = ($op eq '>') ? $val + 1 : $val; 8586: $p->{min} = $min if !defined($p->{min}) || $min > $p->{min};Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_8574_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 2, Killed: 2, Survived: 0)
8587: } 8588: } 8589: 8590: # Regex pattern matching with better capture
Mutants (Total: 1, Killed: 1, Survived: 0)
●8591 → 8591 → 0 8591: if($code =~ /\$$param\s*=~\s*(?:qr?\/([^\/]+)\/|(\$[\w:]+|\$\{\w+\}))/ ) { 8592: my ($body, $variable) = ($1, $2); 8593: $p->{type} ||= 'string'; 8594:
8595: if(defined($variable)) { 8596: # The pattern lives in a variable whose value is not in the 8597: # schema, and the harness would emit that name as a regex. 8598: $self->_log(" CODE: $param matches $variable, a pattern held in a variable; not recorded"); 8599: } elsif(!_pattern_is_self_contained($body)) {Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_8594_4: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes🧪 Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_8594_4: Replace return expression with undef
LOW: Mutation survived, but impact may be minor🧪 Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );8600: $self->_log(" CODE: $param matches '$body', which depends on run-time variables; not recorded"); 8601: } else {Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_8599_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes8602: $p->{matches} = "/$body/"; 8603: $self->_log(" CODE: $param matches pattern: $p->{matches}"); 8604: }Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_8601_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes8605: } 8606: } 8607: 8608: # --------------------------------------------------Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_8604_4: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes🧪 Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_8604_4: Replace return expression with undef
LOW: Mutation survived, but impact may be minor🧪 Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );Mutants (Total: 2, Killed: 2, Survived: 0)
8609: # _pattern_is_self_contained 8610: # 8611: # Purpose: Decide whether a regex taken from the 8612: # source text still means the same thing 8613: # once the harness compiles it from a 8614: # string. 8615: # 8616: # Entry: $pattern - regex body as written in the 8617: # source. 8618: # 8619: # Exit: Returns true when the pattern stands 8620: # alone. \Q and \E are handled by the 8621: # regex lexer, so they quote nothing when 8622: # the pattern arrives as an interpolated 8623: # string; a pattern interpolating a 8624: # variable depends on a value no schema 8625: # carries (q_wrap's delimiter loop uses 8626: # /\Q$l\E|\Q$r\E/). 8627: # -------------------------------------------------- 8628: sub _pattern_is_self_contained { 8629: my ($pattern) = @_; 8630: 8631: return 0 unless defined($pattern) && length($pattern); 8632: return 0 if $pattern =~ /\\[QE]/; 8633: return 0 if $pattern =~ /(?<!\\)[\$\@]\w/; 8634: 8635: return 1; 8636: } 8637: 8638: # -------------------------------------------------- 8639: # _analyze_parameter_validation 8640: # 8641: # Purpose: Determine optionality and extract
Mutants (Total: 2, Killed: 2, Survived: 0)
8642: # default values for a single parameter 8643: # by analysing explicit required checks 8644: # (die/croak unless defined) and default 8645: # assignment patterns in the method body. 8646: # 8647: # Entry: $p_ref - reference to the parameter 8648: # hashref (modified in place).
Mutants (Total: 1, Killed: 1, Survived: 0)
8649: # $param - parameter name string. 8650: # $code - method body source string.
Mutants (Total: 1, Killed: 1, Survived: 0)
8651: # 8652: # Exit: Returns nothing. Modifies the 8653: # referenced parameter hashref. 8654: # 8655: # Side effects: Logs detections to stdout when 8656: # verbose is set. 8657: #
8658: # Notes: Explicit required checks take highest 8659: # priority and override any default 8660: # value detected earlier. 8661: # -------------------------------------------------- 8662: sub _analyze_parameter_validation { ●8663 → 8670 → 8677 8663: my ($self, $p_ref, $param, $code) = @_; 8664: my $p = $$p_ref;Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_8657_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
8665: 8666: # Required/optional checks 8667: my $is_required = 0; 8668: 8669: # Die/croak if not defined 8670: if ($code =~ /(?:die|croak|confess)\s+[^;]*unless\s+(?:defined\s+)?\$$param/s) { 8671: $is_required = 1;
8672: } 8673: 8674: # A routine that refuses an empty value ("croak ... unless defined $x && 8675: # length $x") does not accept one, so the harness's empty-string case is 8676: # an error rather than a survival case. ●8677 → 8677 → 8684 8677: if($code =~ /(?:croak|die|confess)\b[^;]*\bunless\b[^;]*?(?:length\s*\(?\s*\$$param\b|defined\s+\$$param\b[^;]*?\blength\b)/s) {Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_8671_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 5, Killed: 5, Survived: 0)
8678: $is_required = 1; 8679: $p->{_not_empty} = 1;
8680: $self->_log(" CODE: $param must not be empty (the code rejects it)"); 8681: } 8682: 8683: # Extract default values with the new method ●8684 → 8685 → 8709 8684: my $default_value = $self->_extract_default_value($param, $code); 8685: if (defined $default_value && !exists $p->{_default}) { 8686: $p->{optional} = 1; 8687: $p->{_default} = $default_value; 8688: 8689: # Try to infer type from default value if not already set 8690: unless ($p->{type}) { 8691: if (looks_like_number($default_value)) { 8692: $p->{type} = $default_value =~ /\./ ? 'number' : 'integer'; 8693: } elsif (ref($default_value) eq 'ARRAY') { 8694: $p->{type} = 'arrayref'; 8695: } elsif (ref($default_value) eq 'HASH') { 8696: $p->{type} = 'hashref'; 8697: } elsif ($default_value eq 'undef') { 8698: $p->{type} = 'scalar'; # undef can be any scalar 8699: } elsif (defined $default_value && !ref($default_value)) { 8700: $p->{type} = 'string'; 8701: } 8702: } 8703: 8704: $self->_log(" CODE: $param has default value: " . (ref($default_value) ? ref($default_value) . ' ref' : $default_value)); 8705: } 8706: 8707: # Also check for simple default assignment without condition 8708: # Pattern: $param = 'value'; ●8709 → 8709 → 8727 8709: if (!$default_value && !exists $p->{_default} && $code =~ /\$$param\s*=\s*([^;{}]+?)(?:\s*[;}])/s) { 8710: my $assignment = $1; 8711: # Make sure it's not part of a larger expression 8712: if ($assignment !~ /\$$param/ && $assignment !~ /^shift/) {Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_8679_2: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes🧪 Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_8679_2: Replace return expression with undef
LOW: Mutation survived, but impact may be minor🧪 Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );Mutants (Total: 1, Killed: 1, Survived: 0)
8713: my $possible_default = $assignment; 8714: $possible_default =~ s/\s*;\s*$//; 8715: $possible_default = $self->_clean_default_value($possible_default); 8716: if (defined $possible_default) { 8717: $p->{_default} = $possible_default; 8718: $p->{optional} = 1; 8719: $self->_log(" CODE: $param has unconditional default: $possible_default"); 8720: } 8721: } 8722: } 8723: 8724: # A bare truthiness test ("if($dir) {...}") is a presence test: the 8725: # routine does something different when nothing was passed, so the 8726: # argument can be omitted. An explicit required check wins over this. ●8727 → 8727 → 8733 8727: if (!$is_required && ($code =~ /\b(?:if|unless)\s*\(\s*\$$param\s*\)/)) { 8728: $p->{optional} = 1; 8729: $self->_log(" CODE: $param is optional (only used when truthy)"); 8730: } 8731: 8732: # Explicit required check overrides default detection ●8733 → 8733 → 0 8733: if ($is_required) { 8734: $p->{optional} = 0; 8735: delete $p->{_default} if exists $p->{_default}; 8736: $self->_log(" CODE: $param is required (validation check)"); 8737: }
Mutants (Total: 1, Killed: 1, Survived: 0)
8738: } 8739: 8740: # -------------------------------------------------- 8741: # _positional_pod_input 8742: # 8743: # Purpose: Recognise a lone documented input parameter that is really the
8744: # first positional argument under another name. 8745: # 8746: # Entry: $pod - parameters from _analyze_pod; mutated. 8747: # $code_params - parameters from code analysis; mutated. 8748: # $code - the subroutine body as source text. 8749: # 8750: # Exit: Returns the documented name when it is treated as position 0, 8751: # otherwise undef. 8752: #Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_8743_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes8753: # Notes: Two or more documented names describe a hash of arguments, and 8754: # a body that reads an argument hash (my %args = @_, $args->{...}, 8755: # $_[0]{...}) keeps the named style even with one name. A body 8756: # that shows no positional use at all -- a wrapper forwarding @_, 8757: # say -- proves nothing either way, so it stays named rather than 8758: # guessing.Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_8752_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 2, Killed: 2, Survived: 0)
8759: #
Mutants (Total: 2, Killed: 2, Survived: 0)
8760: # Side effects: On success sets position 0, drops stray documented names and 8761: # replaces the code analysis with the one argument, renamed. 8762: # -------------------------------------------------- 8763: sub _positional_pod_input { 8764: my ($self, $pod, $code_params, $code) = @_; 8765: 8766: my @documented = grep { ($pod->{$_}{_source} // '') eq SOURCE_INPUT_SPEC } keys %$pod; 8767: return undef unless @documented == 1; 8768: return undef unless $self->_argument_style($code) eq 'positional'; 8769: 8770: my ($name) = @documented; 8771: $pod->{$name}{position} = 0; 8772: 8773: # The body names the same argument however it likes, so carry its facts 8774: # (a directory tested with -d, say) to the documented name. 8775: my @code_names = keys %$code_params; 8776: my $source = $code_params->{$name} ? $name 8777: : (@code_names == 1 ? $code_names[0] : undef); 8778: 8779: # Empty list, not {}: a hashref here would become a one-element list and 8780: # land in the hash as a "HASH(0x...)" key. 8781: %$code_params = $source ? ($name => $code_params->{$source}) : (); 8782: %$pod = ($name => $pod->{$name}); 8783: $self->_log(" POD: single Input spec '$name' describes a positional argument"); 8784: 8785: return $name; 8786: } 8787: 8788: # -------------------------------------------------- 8789: # _argument_style 8790: # 8791: # Purpose: Classify how a subroutine reads its arguments.
Mutants (Total: 2, Killed: 2, Survived: 0)
8792: # 8793: # Entry: $code - the subroutine body as source text. 8794: # 8795: # Exit: 'named' when the body reads an argument hash, 'positional' 8796: # when it reads an argument by position, '' when neither shows. 8797: # 8798: # Notes: $self->{...} is object state, not an argument, so it is removed 8799: # before looking for hash dereferences. '' is not 'positional': 8800: # a wrapper that only forwards @_ proves nothing, so it keeps the 8801: # named style these heuristics started from. An invocant shift 8802: # is not an argument.
Mutants (Total: 1, Killed: 1, Survived: 0)
8803: # 8804: # Side effects: None. 8805: # -------------------------------------------------- 8806: sub _argument_style { 8807: my ($self, $code) = @_;
Mutants (Total: 1, Killed: 1, Survived: 0)
8808: 8809: return '' unless defined $code; 8810: 8811: my $body = $code; 8812: $body =~ s/\$self\s*->\s*\{[^}]*\}//g; 8813: 8814: return 'named' if($body =~ /\bmy\s+%\w+\s*=[^;]*\@_/s); 8815: return 'named' if($body =~ /\bmy\s*\(\s*[^)]*%\w+\s*\)\s*=\s*\@_/s); 8816: return 'named' if($body =~ /\$_\s*\[\s*\d+\s*\]\s*(?:->\s*)?\{/); 8817: return 'named' if($body =~ /\$\w+\s*->\s*\{/); 8818: 8819: return 'positional' if($body =~ /\$_\s*\[\s*\d+\s*\]/); 8820: return 'positional' if($body =~ /\bmy\s+\$(?!self\b|class\b)\w+\s*=\s*shift\b/);
Mutants (Total: 1, Killed: 1, Survived: 0)
8821: return 'positional' if($body =~ /\bmy\s*\((?!\s*\$(?:self|class)\s*\))[^)]*\)\s*=\s*\@_/s); 8822: 8823: return ''; 8824: } 8825: 8826: # -------------------------------------------------- 8827: # _merge_parameter_analyses 8828: # 8829: # Purpose: Merge parameter information from POD, 8830: # code, and signature analysis into a 8831: # single authoritative parameter hashref 8832: # for each parameter.
Mutants (Total: 1, Killed: 1, Survived: 0)
8833: # 8834: # Entry: $pod - hashref of parameters from POD 8835: # analysis. 8836: # $code - hashref of parameters from 8837: # code analysis. 8838: # $sig - hashref of parameters from 8839: # signature analysis (optional, 8840: # defaults to empty hashref). 8841: #
Mutants (Total: 1, Killed: 1, Survived: 0)
8842: # Exit: Returns a merged hashref of parameter 8843: # name to spec hashref. Each spec has
8844: # all available information combined, 8845: # with POD taking highest priority, 8846: # code second, and signature filling 8847: # remaining gaps. 8848: # 8849: # Side effects: Logs merged parameter details to 8850: # stdout when verbose is set. 8851: # 8852: # Notes: Position is determined by majority 8853: # vote across all sources, with the 8854: # lowest position winning ties. OptionalMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_8843_3: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
8855: # status is determined by 8856: # _determine_optional_status. The single 8857: # _source provenance marker is retained on 8858: # each merged parameter. 8859: # -------------------------------------------------- 8860: # -------------------------------------------------- 8861: # _sanitize_parameter_names 8862: #
Mutants (Total: 2, Killed: 2, Survived: 0)
8863: # Purpose: Drop keys that cannot be parameter names, and report them.
Mutants (Total: 2, Killed: 2, Survived: 0)
8864: # 8865: # Entry: $params - hashref keyed by parameter name; modified in place. 8866: # $where - the analysis stage, for the warning text. 8867: # 8868: # Exit: Number of keys dropped. 8869: # 8870: # Notes: A hashref used where a list of key/value pairs was meant 8871: # stringifies to "HASH(0x...)" and silently becomes a parameter. 8872: # Such a key is never a variable the routine can read, so the 8873: # schema would test an argument that does not exist. Perl hash 8874: # keys are always strings, so the string form is what we see. 8875: # 8876: # Side effects: Emits a carp warning for each dropped key. 8877: # -------------------------------------------------- 8878: sub _sanitize_parameter_names { ●8879 → 8882 → 8893 8879: my ($self, $params, $where) = @_; 8880: 8881: my $dropped = 0; 8882: for my $name (keys %$params) { 8883: my $invalid = ref($name) 8884: || $name =~ /\A(?:HASH|ARRAY|SCALAR|CODE|GLOB|REF|REGEXP|Regexp|LVALUE|VSTRING|FORMAT|IO)\(0x[0-9a-fA-F]+\)\z/ 8885: || $name =~ /\s/; 8886: next unless $invalid; 8887: 8888: carp(__PACKAGE__ . ": ignoring parameter key '$name' from $where: not a parameter name"); 8889: delete $params->{$name}; 8890: $dropped++; 8891: } 8892: 8893: return $dropped; 8894: } 8895: 8896: sub _merge_parameter_analyses {
●8897 → 8909 → 8925 8897: my ($self, $pod, $code, $sig) = @_; 8898: 8899: # Belt and braces: every analysis should already be clean, but a merge is 8900: # the last point before these keys become schema parameters.Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_8896_2: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes🧪 Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_8896_2: Replace return expression with undef
LOW: Mutation survived, but impact may be minor🧪 Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );Mutants (Total: 1, Killed: 1, Survived: 0)
8901: $self->_sanitize_parameter_names($_, 'parameter merge') 8902: for grep { ref($_) eq 'HASH' } ($pod, $code, $sig); 8903: 8904: # A routine's POD may name a positional argument differently from the 8905: # variable the body assigns it to (`$value` documented, `$val` in code). 8906: # Calls are positional and the POD is the specification, so the code 8907: # analysis of that slot belongs to the documented parameter instead of 8908: # inventing a second argument. 8909: if(ref($pod) eq 'HASH' && ref($code) eq 'HASH') { 8910: for my $code_name (keys %$code) { 8911: next if exists $pod->{$code_name}; 8912: my $pos = $code->{$code_name}{position}; 8913: next unless defined($pos); 8914: my ($pod_name) = grep {
Mutants (Total: 2, Killed: 2, Survived: 0)
8915: !exists($code->{$_}) 8916: && defined($pod->{$_}{position}) 8917: && ($pod->{$_}{position} == $pos) 8918: } sort keys %$pod; 8919: next unless defined($pod_name); 8920: $code->{$pod_name} = delete $code->{$code_name}; 8921: $self->_log(" MERGE: code parameter \$$code_name is the documented \$$pod_name"); 8922: }
Mutants (Total: 1, Killed: 1, Survived: 0)
8923: } 8924: ●8925 → 8933 → 9010 8925: my %merged; 8926:
Mutants (Total: 1, Killed: 1, Survived: 0)
8927: my @constraint_keys = qw(min max memberof matches nomatch notmemberof); 8928: my %is_constraint = map { $_ => 1 } @constraint_keys; 8929: 8930: # Start with all parameters from all sources 8931: my %all_params = map { $_ => 1 } (keys %$pod, keys %$code, keys %$sig); 8932: 8933: foreach my $param (keys %all_params) { 8934: my $p = $merged{$param} = {}; 8935: 8936: # Collect position from all sources 8937: my @positions; 8938: push @positions, $pod->{$param}{position} if $pod->{$param} && defined $pod->{$param}{position}; 8939: push @positions, $sig->{$param}{position} if $sig->{$param} && defined $sig->{$param}{position}; 8940: push @positions, $code->{$param}{position} if $code->{$param} && defined $code->{$param}{position};
Mutants (Total: 1, Killed: 1, Survived: 0)
8941: 8942: # Use the most common position, or lowest if tie 8943: if (@positions) { 8944: my %pos_count; 8945: $pos_count{$_}++ for @positions; 8946: my ($best_pos) = sort { $pos_count{$b} <=> $pos_count{$a} || $a <=> $b } keys %pos_count; 8947: $p->{position} = $best_pos unless(exists($p->{position})); 8948: }
Mutants (Total: 1, Killed: 1, Survived: 0)
8949: 8950: # POD has highest priority for type info and explicit declarations 8951: if ($pod->{$param}) {
Mutants (Total: 1, Killed: 1, Survived: 0)
8952: %$p = (%$p, %{$pod->{$param}}); 8953: $p->{_source} //= SOURCE_POD; 8954: 8955: # Record which source each constraint came from, so a documented
Mutants (Total: 1, Killed: 1, Survived: 0)
8956: # minimum does not make a maximum enforced by the code tolerant. 8957: my $source = $pod->{$param}{_source} // SOURCE_POD; 8958: for my $key (@constraint_keys) { 8959: next unless exists($pod->{$param}{$key}) && defined($pod->{$param}{$key}); 8960: $p->{_constraint_source}{$key} //= $source; 8961: } 8962: } 8963: 8964: # Code analysis adds concrete evidence (but doesn't override POD explicit types) 8965: if ($code->{$param}) {
Mutants (Total: 1, Killed: 1, Survived: 0)
8966: foreach my $key (keys %{$code->{$param}}) { 8967: next if $key eq '_source'; 8968: next if $key eq 'position';
Mutants (Total: 1, Killed: 1, Survived: 0)
8969: # A formal input-spec row that names no type says the argument 8970: # exists and in which position, not that it has none: the 8971: # code's evidence still supplies the type. 8972: 8973: # Only override if POD didn't provide this info or it's a stronger signal 8974: my $from_pod = exists $pod->{$param}; 8975: # A documented type is the specification; only a type the code
Mutants (Total: 1, Killed: 1, Survived: 0)
8976: # shows outright replaces it, not one a pattern in the body 8977: # was guessed to imply (qr/$pattern/ is not division). 8978: my $heuristic_type = (($code->{$param}{_type_confidence} // '') eq 'heuristic'); 8979: if (!exists $p->{$key} || 8980: ($key eq 'type' && $from_pod && $p->{type} eq 'string' &&
Mutants (Total: 2, Killed: 2, Survived: 0)
8981: $code->{$param}{$key} ne 'string' && !$heuristic_type)) {
8982: $p->{$key} = $code->{$param}{$key}; 8983: $p->{_constraint_source}{$key} = SOURCE_CODE if $is_constraint{$key}; 8984: } 8985: } 8986: $p->{_source} //= $code->{$param}{_source}; 8987: } 8988: 8989: # Signature fills in remaining gaps 8990: if ($sig->{$param}) { 8991: foreach my $key (keys %{$sig->{$param}}) { 8992: next if $key eq '_source'; 8993: next if $key eq 'position'; 8994: next if defined($p->{$key}); 8995: $p->{$key} = $sig->{$param}{$key}; 8996: $p->{_constraint_source}{$key} = SOURCE_SIGNATURE if $is_constraint{$key}; 8997: } 8998: $p->{_source} //= $sig->{$param}{_source}; 8999: } 9000: 9001: # The source is the single provenance decision: validator-backed 9002: # parameters are type-checked, POD/input-spec parameters are 9003: # documentation, and code/signature/field parameters are inferred. 9004: 9005: # Handle optional field with better logic 9006: $self->_determine_optional_status($p, $pod->{$param}, $code->{$param}); 9007: } 9008: 9009: # Debug logging ●9010 → 9010 → 9020 9010: if ($self->{verbose}) { 9011: foreach my $param (sort { ($merged{$a}{position} || 999) <=> ($merged{$b}{position} || 999) } keys %merged) {Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_8981_2: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes🧪 Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_8981_2: Replace return expression with undef
LOW: Mutation survived, but impact may be minor🧪 Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );Mutants (Total: 2, Killed: 2, Survived: 0)
9012: my $p = $merged{$param}; 9013: $self->_log(" MERGED $param: " . 9014: 'pos=' . (defined($p->{position}) ? $p->{position} : 'none') . 9015: ", type=" . ($p->{type} || 'none') . 9016: ", optional=" . (defined($p->{optional}) ? $p->{optional} : 'undef')); 9017: } 9018: } 9019: 9020: return \%merged; 9021: } 9022: 9023: # -------------------------------------------------- 9024: # _determine_optional_status
Mutants (Total: 1, Killed: 1, Survived: 0)
9025: # 9026: # Purpose: Set the optional field on a merged 9027: # parameter spec based on evidence from 9028: # POD and code analysis, with POD taking 9029: # highest priority. 9030: # 9031: # Entry: $merged_param - the merged parameter 9032: # hashref (modified in
Mutants (Total: 1, Killed: 1, Survived: 0)
9033: # place). 9034: # $pod_param - parameter spec from 9035: # POD analysis, or undef. 9036: # $code_param - parameter spec from 9037: # code analysis, or undef. 9038: # 9039: # Exit: Returns nothing. Sets or leaves 9040: # $merged_param->{optional}. 9041: # 9042: # Side effects: None. 9043: # -------------------------------------------------- 9044: sub _determine_optional_status { ●9045 → 9051 → 0 9045: my ($self, $merged_param, $pod_param, $code_param) = @_; 9046:
9047: my $pod_optional = $pod_param ? $pod_param->{optional} : undef; 9048: my $code_optional = $code_param ? $code_param->{optional} : undef; 9049: 9050: # Explicit POD declaration wins 9051: if (defined $pod_optional) { 9052: $merged_param->{optional} = $pod_optional; 9053: }Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_9046_4: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
9054: # Code validation evidence 9055: elsif (defined $code_optional) { 9056: $merged_param->{optional} = $code_optional; 9057: } 9058: # Default: if we have any info about the param, assume required 9059: elsif (keys %$merged_param > 0) { 9060: $merged_param->{optional} = 0; 9061: } 9062: # Otherwise leave undef (unknown)
Mutants (Total: 2, Killed: 2, Survived: 0)
9063: }
Mutants (Total: 2, Killed: 2, Survived: 0)
9064: 9065: 9066: # -------------------------------------------------- 9067: # _calculate_input_confidence 9068: # 9069: # Purpose: Calculate a confidence score and level 9070: # for the input parameter analysis, 9071: # based on how much type, constraint, 9072: # and semantic information was inferred 9073: # for each parameter. 9074: # 9075: # Entry: $params - hashref of merged parameter 9076: # specs as produced by 9077: # _merge_parameter_analyses. 9078: # 9079: # Exit: Returns a hashref with keys: 9080: # level - one of: none, 9081: # very_low, low, 9082: # medium, high 9083: # score - numeric average 9084: # across all params 9085: # factors - arrayref of 9086: # human-readable 9087: # factor strings 9088: # per_parameter - hashref of per- 9089: # parameter score 9090: # and factor detail 9091: # Returns { level => 'none', ... } if 9092: # no parameters were found. 9093: # 9094: # Side effects: None.
9095: # -------------------------------------------------- 9096: sub _calculate_input_confidence {Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_9094_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes●9097 → 9107 → 9177 9097: my ($self, $params) = @_; 9098: 9099: my @factors; # Track all confidence factors 9100: 9101: return { level => 'none', factors => ['No parameters found'] } unless keys %$params; 9102: 9103: my $total_score = 0; 9104: my $count = 0;Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_9096_3: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes🧪 Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_9096_3: Replace return expression with undef
LOW: Mutation survived, but impact may be minor🧪 Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );9105: my %param_details; # Store per-parameter analysisMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_9104_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomes9106: 9107: foreach my $param (keys %$params) { 9108: my $p = $params->{$param}; 9109: my $score = 0; 9110: my @param_factors; 9111: 9112: # Type information 9113: if ($p->{type}) { 9114: if ($p->{type} eq 'string' && ($p->{min} || $p->{max} || $p->{matches})) { 9115: $score += 25; 9116: push @param_factors, "Type: constrained string (+25)"; 9117: } elsif ($p->{type} eq 'string') { 9118: $score += 10; 9119: push @param_factors, "Type: plain string (+10)"; 9120: } else { 9121: $score += 30; 9122: push @param_factors, "Type: $p->{type} (+30)"; 9123: } 9124: } else { 9125: push @param_factors, "No type information (-0)"; 9126: } 9127: 9128: # Constraints 9129: if (defined $p->{min}) { 9130: $score += 15; 9131: push @param_factors, 'Has min constraint (+15)'; 9132: } 9133: if (defined $p->{max}) { 9134: $score += 15; 9135: push @param_factors, "Has max constraint (+15)"; 9136: } 9137: if (defined $p->{optional}) { 9138: $score += 20;Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_9105_3: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes🧪 Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_9105_3: Replace return expression with undef
LOW: Mutation survived, but impact may be minor🧪 Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );Mutants (Total: 2, Killed: 2, Survived: 0)
9139: push @param_factors, "Optional/required explicitly defined (+20)"; 9140: } 9141: if ($p->{matches}) { 9142: $score += 20; 9143: push @param_factors, 'Has regex pattern constraint (+20)'; 9144: } 9145: if ($p->{isa}) { 9146: $score += 25; 9147: push @param_factors, "Specific class constraint: $p->{isa} (+25)";
9148: }Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_9147_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 2, Killed: 2, Survived: 0)
9149: 9150: # Position information 9151: if (defined $p->{position}) { 9152: $score += 10; 9153: push @param_factors, "Position defined: $p->{position} (+10)";
9154: } 9155: 9156: # Default valueMutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_9153_2: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes🧪 Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_9153_2: Replace return expression with undef
LOW: Mutation survived, but impact may be minor🧪 Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );9157: if (exists $p->{_default}) { 9158: $score += 10; 9159: push @param_factors, "Has default value (+10)"; 9160: } 9161: 9162: # Semantic information 9163: if ($p->{semantic}) { 9164: $score += 15; 9165: push @param_factors, "Semantic type: $p->{semantic} (+15)"; 9166: } 9167: 9168: $param_details{$param} = { 9169: score => $score, 9170: factors => \@param_factors 9171: }; 9172: 9173: $total_score += $score; 9174: $count++; 9175: } 9176: ●9177 → 9186 → 9199 9177: my $avg = $count ? ($total_score / $count) : 0; 9178: 9179: # Build summary factors 9180: push @factors, sprintf("Analyzed %d parameter%s", $count, $count == 1 ? '' : 's'); 9181: push @factors, sprintf("Average confidence score: %.1f", $avg); 9182: 9183: # Add top contributing factors 9184: my @sorted_params = sort { $param_details{$b}{score} <=> $param_details{$a}{score} } keys %param_details; 9185: 9186: if (@sorted_params) { 9187: my $highest = $sorted_params[0]; 9188: my $highest_score = $param_details{$highest}{score}; 9189: push @factors, sprintf("Highest scoring parameter: \$$highest (score: %d)", $highest_score);Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_9156_2: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes🧪 Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_9156_2: Replace return expression with undef
LOW: Mutation survived, but impact may be minor🧪 Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );Mutants (Total: 2, Killed: 2, Survived: 0)
9190: 9191: if (@sorted_params > 1) { 9192: my $lowest = $sorted_params[-1]; 9193: my $lowest_score = $param_details{$lowest}{score}; 9194: push @factors, sprintf("Lowest scoring parameter: \$$lowest (score: %d)", $lowest_score); 9195: } 9196: } 9197: 9198: # Determine confidence level ●9199 → 9200 → 9214 9199: my $level;
Mutants (Total: 1, Killed: 1, Survived: 0)
9200: if ($avg >= $CONFIDENCE_HIGH_THRESHOLD) { 9201: $level = $LEVEL_HIGH; 9202: push @factors, "High confidence: comprehensive type and constraint information"; 9203: } elsif ($avg >= $CONFIDENCE_MEDIUM_THRESHOLD) {
Mutants (Total: 2, Killed: 2, Survived: 0)
9204: $level = $LEVEL_MEDIUM; 9205: push @factors, "Medium confidence: some type or constraint information present"; 9206: } elsif ($avg >= $CONFIDENCE_LOW_THRESHOLD) { 9207: $level = $LEVEL_LOW;
Mutants (Total: 1, Killed: 1, Survived: 0)
9208: push @factors, "Low confidence: minimal type information"; 9209: } else { 9210: $level = $LEVEL_VERY_LOW; 9211: push @factors, "Very low confidence: little to no type information";
Mutants (Total: 2, Killed: 2, Survived: 0)
9212: } 9213: 9214: return { 9215: level => $level, 9216: score => $avg,
Mutants (Total: 1, Killed: 1, Survived: 0)
9217: factors => \@factors, 9218: per_parameter => \%param_details 9219: }; 9220: }
Mutants (Total: 2, Killed: 2, Survived: 0)
9221: 9222: # -------------------------------------------------- 9223: # _calculate_output_confidence 9224: #
Mutants (Total: 1, Killed: 1, Survived: 0)
9225: # Purpose: Calculate a confidence score and level 9226: # for the output analysis based on how 9227: # much return type, value, class,
Mutants (Total: 2, Killed: 2, Survived: 0)
9228: # context, and error convention 9229: # information was determined. 9230: # 9231: # Entry: $output - the output hashref as built
Mutants (Total: 1, Killed: 1, Survived: 0)
9232: # by _analyze_output. 9233: # 9234: # Exit: Returns a hashref with keys: 9235: # level - one of: none, very_low,
Mutants (Total: 2, Killed: 2, Survived: 0)
9236: # low, medium, high 9237: # score - numeric confidence score 9238: # factors - arrayref of factor strings 9239: # Returns { level => 'none', ... } if
Mutants (Total: 1, Killed: 1, Survived: 0)
9240: # output is empty. 9241: # 9242: # Side effects: None. 9243: # --------------------------------------------------
9244: sub _calculate_output_confidence { ●9245 → 9254 → 9262 9245: my ($self, $output) = @_; 9246: 9247: my @factors;Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_9243_3: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes🧪 Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_9243_3: Replace return expression with undef
LOW: Mutation survived, but impact may be minor🧪 Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );Mutants (Total: 1, Killed: 1, Survived: 0)
9248: 9249: return { level => 'none', factors => ['No return information found'] } unless keys %$output; 9250: 9251: my $score = 0;
Mutants (Total: 2, Killed: 2, Survived: 0)
9252: 9253: # Type information 9254: if ($output->{type}) { 9255: $score += 30;
Mutants (Total: 1, Killed: 1, Survived: 0)
9256: push @factors, "Return type defined: $output->{type} (+30)"; 9257: } else { 9258: push @factors, 'No return type information (-0)'; 9259: }
Mutants (Total: 2, Killed: 2, Survived: 0)
9260: 9261: # Specific value known ●9262 → 9262 → 9268 9262: if (defined $output->{value}) {
Mutants (Total: 2, Killed: 2, Survived: 0)
9263: $score += 30; 9264: push @factors, "Specific return value: $output->{value} (+30)"; 9265: } 9266: 9267: # Class information for objects ●9268 → 9268 → 9274 9268: if ($output->{isa}) { 9269: $score += 30; 9270: push @factors, "Returns specific class: $output->{isa} (+30)"; 9271: } 9272: 9273: # Context-aware returns ●9274 → 9274 → 9287 9274: if ($output->{_context_aware}) { 9275: $score += 20; 9276: push @factors, "Context-aware return (wantarray) (+20)"; 9277: 9278: if ($output->{_list_context}) { 9279: push @factors, " List context: $output->{_list_context}{type}"; 9280: } 9281: if ($output->{_scalar_context}) { 9282: push @factors, " Scalar context: $output->{_scalar_context}{type}"; 9283: } 9284: } 9285: 9286: # Error handling information ●9287 → 9287 → 9293 9287: if ($output->{_error_return}) { 9288: $score += 15; 9289: push @factors, "Error return convention documented: $output->{_error_return} (+15)"; 9290: } 9291: 9292: # Success/failure pattern ●9293 → 9293 → 9299 9293: if ($output->{_success_failure_pattern}) { 9294: $score += 10; 9295: push @factors, 'Success/failure pattern detected (+10)'; 9296: } 9297: 9298: # Chainable methods ●9299 → 9299 → 9305 9299: if ($output->{_returns_self}) { 9300: $score += 15; 9301: push @factors, "Chainable method (fluent interface) (+15)"; 9302: } 9303: 9304: # Void context ●9305 → 9305 → 9311 9305: if ($output->{_void_context}) { 9306: $score += 20;
Mutants (Total: 2, Killed: 2, Survived: 0)
9307: push @factors, "Void context method (no meaningful return) (+20)"; 9308: } 9309: 9310: # Exception handling ●9311 → 9311 → 9316 9311: if ($output->{_error_handling} && $output->{_error_handling}{exception_handling}) { 9312: $score += 10; 9313: push @factors, 'Exception handling present (+10)'; 9314: } 9315: ●9316 → 9320 → 9334 9316: push @factors, sprintf("Total output confidence score: %d", $score); 9317: 9318: # Determine confidence level 9319: my $level; 9320: if ($score >= $CONFIDENCE_HIGH_THRESHOLD) { 9321: $level = $LEVEL_HIGH; 9322: push @factors, "High confidence: detailed return type and behavior"; 9323: } elsif ($score >= $CONFIDENCE_MEDIUM_THRESHOLD) { 9324: $level = $LEVEL_MEDIUM; 9325: push @factors, "Medium confidence: return type defined"; 9326: } elsif ($score >= $CONFIDENCE_LOW_THRESHOLD) { 9327: $level = $LEVEL_LOW; 9328: push @factors, "Low confidence: minimal return information"; 9329: } else { 9330: $level = $LEVEL_VERY_LOW;
Mutants (Total: 1, Killed: 1, Survived: 0)
9331: push @factors, 'Very low confidence: little return information'; 9332: } 9333: 9334: return { 9335: level => $level,
Mutants (Total: 1, Killed: 1, Survived: 0)
9336: score => $score, 9337: factors => \@factors 9338: }; 9339: } 9340:
Mutants (Total: 1, Killed: 1, Survived: 0)
9341: # -------------------------------------------------- 9342: # _generate_confidence_report 9343: # 9344: # Purpose: Generate a human-readable text report 9345: # of all confidence factors for a 9346: # schema, for debugging and review 9347: # purposes. 9348: # 9349: # Entry: $schema - schema hashref containing 9350: # a populated _analysis key. 9351: # 9352: # Exit: Returns a multi-line string report, 9353: # or nothing if $schema->{_analysis} 9354: # is absent. 9355: # 9356: # Side effects: None. 9357: # -------------------------------------------------- 9358: sub _generate_confidence_report 9359: { ●9360 → 9374 → 9385 9360: my ($self, $schema) = @_; 9361: 9362: return unless $schema->{_analysis}; 9363: 9364: my $analysis = $schema->{_analysis}; 9365: my @report; 9366: 9367: push @report, "Confidence Analysis for " . ($schema->{method_name} || 'method'); 9368: push @report, '=' x 60;
Mutants (Total: 1, Killed: 1, Survived: 0)
9369: push @report, ''; 9370: 9371: push @report, "Overall Confidence: " . uc($analysis->{overall_confidence}); 9372: push @report, ''; 9373: 9374: if ($analysis->{confidence_factors}{input}) { 9375: push @report, ( 9376: "Input Parameters:", 9377: " Confidence Level: " . uc($analysis->{input_confidence}) 9378: ); 9379: foreach my $factor (@{$analysis->{confidence_factors}{input}}) { 9380: push @report, " - $factor"; 9381: } 9382: push @report, ''; 9383: } 9384: ●9385 → 9385 → 9394 9385: if ($analysis->{confidence_factors}{output}) { 9386: push @report, 'Return Value:', 9387: " Confidence Level: " . uc($analysis->{output_confidence}); 9388: foreach my $factor (@{$analysis->{confidence_factors}{output}}) { 9389: push @report, " - $factor"; 9390: } 9391: push @report, ''; 9392: } 9393: ●9394 → 9394 → 9406 9394: if ($analysis->{per_parameter_scores}) { 9395: push @report, 'Per-Parameter Analysis:'; 9396: foreach my $param (sort keys %{$analysis->{per_parameter_scores}}) { 9397: my $details = $analysis->{per_parameter_scores}{$param}; 9398: push @report, " \$$param (score: $details->{score}):"; 9399: foreach my $factor (@{$details->{factors}}) { 9400: push @report, " - $factor"; 9401: } 9402: } 9403: push @report, ''; 9404: } 9405: 9406: return join("\n", @report); 9407: } 9408:
9409: # -------------------------------------------------- 9410: # _generate_notes 9411: # 9412: # Purpose: Generate human-readable advisory notes 9413: # about parameters whose type or 9414: # optionality could not be determined,Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_9408_2: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes🧪 Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_9408_2: Replace return expression with undef
LOW: Mutation survived, but impact may be minor🧪 Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );Mutants (Total: 1, Killed: 1, Survived: 0)
9415: # to guide manual schema review. 9416: # 9417: # Entry: $params - hashref of merged parameter 9418: # specs. 9419: # 9420: # Exit: Returns an arrayref of note strings. 9421: # Returns an empty arrayref if all 9422: # parameters have known types and 9423: # optionality. 9424: # 9425: # Side effects: None.
Mutants (Total: 2, Killed: 2, Survived: 0)
9426: # -------------------------------------------------- 9427: sub _generate_notes { ●9428 → 9432 → 9445 9428: my ($self, $params) = @_; 9429: 9430: my @notes; 9431: 9432: foreach my $param (sort keys %$params) { 9433: my $p = $params->{$param}; 9434: 9435: unless ($p->{type}) { 9436: push @notes, "$param: type unknown - please review - will set to 'string' as a default"; 9437: } 9438: 9439: unless (defined $p->{optional}) { 9440: push @notes, "$param: optional status unknown"; 9441: # Don't automatically set - let it be undef if we don't know 9442: } 9443: } 9444: 9445: return \@notes; 9446: }
Mutants (Total: 1, Killed: 1, Survived: 0)
9447: 9448: # -------------------------------------------------- 9449: # _set_defaults 9450: # 9451: # Purpose: Apply default type values to any 9452: # parameters in a schema mode (input 9453: # or output) whose type was not set 9454: # during analysis, setting them to 9455: # 'string' as a conservative fallback. 9456: # 9457: # Entry: $schema - the schema hashref being 9458: # built by _analyze_method. 9459: # $mode - either 'input' or 'output'. 9460: # 9461: # Exit: Returns nothing. Modifies $schema in 9462: # place by setting type => 'string' on 9463: # any parameter that lacks a type, and 9464: # downgrading input confidence to 'low'. 9465: # 9466: # Side effects: Logs type defaulting to stdout when
Mutants (Total: 1, Killed: 1, Survived: 0)
9467: # verbose is set. 9468: # 9469: # Notes: Called after all analysis is complete 9470: # so that genuine type unknowns can be 9471: # distinguished from analysis gaps. 9472: # -------------------------------------------------- 9473: sub _set_defaults { ●9474 → 9478 → 0 9474: my ($self, $schema, $mode) = @_; 9475: 9476: my $params = $schema->{$mode}; 9477:
Mutants (Total: 2, Killed: 2, Survived: 0)
9478: foreach my $param (keys %$params) { 9479: my $p = $params->{$param}; 9480: 9481: next unless(ref($p) eq 'HASH'); 9482: unless ($p->{type}) { 9483: $self->_log(" DEBUG {$mode}{$param}: Setting to 'string' as a default"); 9484: $p->{'type'} = 'string'; 9485: $schema->{_confidence}{$mode}->{level} = 'low'; # Setting a default means it's a guess 9486: } 9487: } 9488: } 9489: 9490: # -------------------------------------------------- 9491: # _analyze_relationships 9492: # 9493: # Purpose: Detect inter-parameter relationships 9494: # in a method's source code, including 9495: # mutually exclusive parameters, required 9496: # groups, conditional requirements, 9497: # dependencies, and value-based 9498: # constraints. 9499: # 9500: # Entry: $method - method hashref containing 9501: # at minimum a 'body' key 9502: # with the source string. 9503: # 9504: # Exit: Returns an arrayref of relationship 9505: # hashrefs. Returns an empty arrayref 9506: # if no parameters or no relationships 9507: # are found. 9508: # 9509: # Side effects: Logs detections to stdout when 9510: # verbose is set. 9511: # 9512: # Notes: Parameter names are extracted via 9513: # _extract_parameters_from_signature, so 9514: # every style it supports -- my (...) = 9515: # @_, shift-style (my $x = shift), direct- 9516: # index ($_[N]), and modern signatures -- 9517: # is analysed for relationships, not just 9518: # the my (...) = @_ list-assignment form. 9519: # -------------------------------------------------- 9520: sub _analyze_relationships { 9521: my ($self, $method) = @_;
Mutants (Total: 1, Killed: 1, Survived: 0)
9522: 9523: my $code = $method->{body}; 9524: my @relationships; 9525: 9526: # Extract all parameter names from the method, using the same 9527: # multi-style detection used for schema population so shift-style 9528: # and modern-signature methods get relationship analysis too 9529: my %params; 9530: $self->_extract_parameters_from_signature(\%params, $code); 9531: my @param_names = sort { $params{$a}{position} <=> $params{$b}{position} } keys %params;
Mutants (Total: 1, Killed: 1, Survived: 0)
9532: 9533: return [] unless @param_names; 9534: 9535: # Detect mutually exclusive parameters 9536: push @relationships, @{$self->_detect_mutually_exclusive($code, \@param_names)}; 9537: 9538: # Detect required groups (OR logic) 9539: push @relationships, @{$self->_detect_required_groups($code, \@param_names)}; 9540:
Mutants (Total: 1, Killed: 1, Survived: 0)
9541: # Detect conditional requirements (IF-THEN) 9542: push @relationships, @{$self->_detect_conditional_requirements($code, \@param_names)}; 9543:
Mutants (Total: 1, Killed: 1, Survived: 0)
9544: # Detect dependencies 9545: push @relationships, @{$self->_detect_dependencies($code, \@param_names)}; 9546: 9547: # Detect value-based constraints 9548: push @relationships, @{$self->_detect_value_constraints($code, \@param_names)}; 9549: 9550: # Deduplicate relationships 9551: my @unique = $self->_deduplicate_relationships(\@relationships); 9552: 9553: return \@unique; 9554: }
Mutants (Total: 1, Killed: 1, Survived: 0)
9555: 9556: # -------------------------------------------------- 9557: # _deduplicate_relationships 9558: # 9559: # Purpose: Remove duplicate relationship entries 9560: # from the relationships list by 9561: # computing a canonical signature for 9562: # each relationship type. 9563: #
9564: # Entry: $relationships - arrayref of 9565: # relationship hashrefs. 9566: # 9567: # Exit: Returns a deduplicated list of 9568: # relationship hashrefs.Mutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_9563_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 1, Killed: 1, Survived: 0)
9569: # 9570: # Side effects: None. 9571: # -------------------------------------------------- 9572: sub _deduplicate_relationships { ●9573 → 9578 → 9602 9573: my ($self, $relationships) = @_;
Mutants (Total: 1, Killed: 1, Survived: 0)
9574: 9575: my @unique; 9576: my %seen; 9577: 9578: foreach my $rel (@$relationships) {
Mutants (Total: 1, Killed: 1, Survived: 0)
9579: # Create a signature for this relationship
Mutants (Total: 1, Killed: 1, Survived: 0)
9580: my $sig;
Mutants (Total: 2, Killed: 2, Survived: 0)
9581: if ($rel->{type} eq 'mutually_exclusive') { 9582: $sig = join(':', 'mutex', sort @{$rel->{params}});
Mutants (Total: 2, Killed: 2, Survived: 0)
9583: } elsif ($rel->{type} eq 'required_group') { 9584: $sig = join(':', 'reqgroup', sort @{$rel->{params}}); 9585: } elsif ($rel->{type} eq 'conditional_requirement') { 9586: $sig = join(':', 'condreq', $rel->{if}, $rel->{then_required}); 9587: } elsif ($rel->{type} eq 'dependency') {
Mutants (Total: 1, Killed: 1, Survived: 0)
9588: $sig = join(':', 'dep', $rel->{param}, $rel->{requires});
Mutants (Total: 2, Killed: 2, Survived: 0)
9589: } elsif ($rel->{type} eq 'value_constraint') { 9590: $sig = join(':', 'valcon', $rel->{if}, $rel->{then}, $rel->{operator}, $rel->{value}); 9591: } elsif ($rel->{type} eq 'value_conditional') { 9592: $sig = join(':', 'valcond', $rel->{if}, $rel->{equals}, $rel->{then_required});
Mutants (Total: 1, Killed: 1, Survived: 0)
9593: } else {
9594: $sig = join(':', $rel->{type}, %$rel); 9595: }Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_9593_3: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes🧪 Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_9593_3: Replace return expression with undef
LOW: Mutation survived, but impact may be minor🧪 Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );9596: 9597: unless ($seen{$sig}++) { 9598: push @unique, $rel; 9599: }Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_9595_3: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes🧪 Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_9595_3: Replace return expression with undef
LOW: Mutation survived, but impact may be minor🧪 Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );Mutants (Total: 1, Killed: 1, Survived: 0)
9600: }
Mutants (Total: 2, Killed: 2, Survived: 0)
9601: 9602: return @unique; 9603: } 9604:
Mutants (Total: 1, Killed: 1, Survived: 0)
9605: # --------------------------------------------------
Mutants (Total: 2, Killed: 2, Survived: 0)
9606: # _detect_mutually_exclusive 9607: # 9608: # Purpose: Detect pairs of parameters that cannot 9609: # be specified together, by searching 9610: # for die/croak/confess patterns 9611: # that fire when both are truthy. 9612: #
9613: # Entry: $code - method body source string. 9614: # $param_names - arrayref of parameter 9615: # name strings. 9616: # 9617: # Exit: Returns an arrayref of relationshipMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_9612_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 2, Killed: 2, Survived: 0)
9618: # hashrefs of type 'mutually_exclusive'. 9619: # Returns an empty arrayref if none found. 9620: # 9621: # Side effects: Logs detections to stdout when 9622: # verbose is set. 9623: # -------------------------------------------------- 9624: sub _detect_mutually_exclusive { ●9625 → 9631 → 9686 9625: my ($self, $code, $param_names) = @_; 9626: 9627: my @relationships; 9628: 9629: # Pattern 1: die/croak if $x && $y 9630: # Look for: die/croak ... if $param1 && $param2 9631: foreach my $param1 (@$param_names) { 9632: foreach my $param2 (@$param_names) { 9633: next if $param1 eq $param2; 9634: 9635: # Check various patterns 9636: if ($code =~ /(?:die|croak|confess)[^;]*if\s+\$$param1\s+&&\s+\$$param2/ || 9637: $code =~ /(?:die|croak|confess)[^;]*if\s+\$$param2\s+&&\s+\$$param1/) { 9638: 9639: # Avoid duplicates (param1,param2 vs param2,param1) 9640: my $found_reverse = 0; 9641: foreach my $rel (@relationships) { 9642: if ($rel->{type} eq 'mutually_exclusive' && 9643: (($rel->{params}[0] eq $param2 && $rel->{params}[1] eq $param1))) { 9644: $found_reverse = 1; 9645: last; 9646: } 9647: } 9648: 9649: next if $found_reverse; 9650: 9651: push @relationships, { 9652: type => 'mutually_exclusive', 9653: params => [$param1, $param2], 9654: description => "Cannot specify both $param1 and $param2" 9655: }; 9656: 9657: $self->_log(" RELATIONSHIP: $param1 and $param2 are mutually exclusive"); 9658: } 9659: 9660: # Pattern 2: die "Cannot specify both X and Y" 9661: if ($code =~ /(?:die|croak|confess)\s+['"](Cannot|Can't)[^'"]*both[^'"]*$param1[^'"]*$param2/i || 9662: $code =~ /(?:die|croak|confess)\s+['"](Cannot|Can't)[^'"]*both[^'"]*$param2[^'"]*$param1/i) { 9663: 9664: my $found_reverse = 0; 9665: foreach my $rel (@relationships) { 9666: if ($rel->{type} eq 'mutually_exclusive' && 9667: (($rel->{params}[0] eq $param2 && $rel->{params}[1] eq $param1))) { 9668: $found_reverse = 1;
Mutants (Total: 1, Killed: 1, Survived: 0)
9669: last; 9670: } 9671: } 9672: 9673: next if $found_reverse;
Mutants (Total: 1, Killed: 1, Survived: 0)
9674:
Mutants (Total: 1, Killed: 1, Survived: 0)
9675: push @relationships, { 9676: type => 'mutually_exclusive', 9677: params => [$param1, $param2], 9678: description => "Cannot specify both $param1 and $param2"
Mutants (Total: 1, Killed: 1, Survived: 0)
9679: }; 9680: 9681: $self->_log(" RELATIONSHIP: $param1 and $param2 are mutually exclusive (from error message)"); 9682: } 9683: } 9684: } 9685: 9686: return \@relationships; 9687: }
Mutants (Total: 1, Killed: 1, Survived: 0)
9688:
Mutants (Total: 1, Killed: 1, Survived: 0)
9689: # -------------------------------------------------- 9690: # _detect_required_groups 9691: # 9692: # Purpose: Detect parameter groups where at least 9693: # one parameter must be specified (OR 9694: # logic), by searching for die/croak 9695: # patterns that fire unless any of the 9696: # group is truthy.
Mutants (Total: 1, Killed: 1, Survived: 0)
9697: #
Mutants (Total: 1, Killed: 1, Survived: 0)
9698: # Entry: $code - method body source string. 9699: # $param_names - arrayref of parameter 9700: # name strings. 9701: # 9702: # Exit: Returns an arrayref of relationship 9703: # hashrefs of type 'required_group'. 9704: # Returns an empty arrayref if none found.
9705: # 9706: # Side effects: Logs detections to stdout when 9707: # verbose is set. 9708: # --------------------------------------------------Mutants (Total: 2, Killed: 1, Survived: 1)
- NUM_BOUNDARY_9704_66_==: Numeric boundary flip != to ==
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );9709: sub _detect_required_groups { ●9710 → 9715 → 9771 9710: my ($self, $code, $param_names) = @_; 9711: 9712: my @relationships; 9713:Mutants (Total: 2, Killed: 1, Survived: 1)
- NUM_BOUNDARY_9708_66_==: Numeric boundary flip != to ==
HIGH: Likely missing edge-case test (boundary value)🧪 Suggested Test# Boundary test suggestion is( func(VALUE_AT_BOUNDARY), EXPECTED, 'Test boundary behaviour' );Mutants (Total: 1, Killed: 1, Survived: 0)
9714: # Pattern 1: die/croak unless $x || $y 9715: foreach my $param1 (@$param_names) { 9716: foreach my $param2 (@$param_names) { 9717: next if $param1 eq $param2; 9718: 9719: if ($code =~ /(?:die|croak|confess)[^;]*unless\s+\$$param1\s+\|\|\s+\$$param2/ ||
Mutants (Total: 2, Killed: 2, Survived: 0)
9720: $code =~ /(?:die|croak|confess)[^;]*unless\s+\$$param2\s+\|\|\s+\$$param1/) { 9721: 9722: # Avoid duplicates 9723: my $found_reverse = 0; 9724: foreach my $rel (@relationships) { 9725: if ($rel->{type} eq 'required_group' && 9726: (($rel->{params}[0] eq $param2 && $rel->{params}[1] eq $param1))) { 9727: $found_reverse = 1; 9728: last; 9729: } 9730: } 9731: 9732: next if $found_reverse; 9733: 9734: push @relationships, { 9735: type => 'required_group', 9736: params => [$param1, $param2], 9737: logic => 'or', 9738: description => "Must specify either $param1 or $param2" 9739: }; 9740: 9741: $self->_log(" RELATIONSHIP: Must specify either $param1 or $param2"); 9742: }
Mutants (Total: 2, Killed: 2, Survived: 0)
9743: 9744: # Pattern 2: die "Must specify either X or Y" 9745: if ($code =~ /(?:die|croak|confess)\s+['"]Must\s+specify\s+either[^'"]*$param1[^'"]*or[^'"]*$param2/i ||
Mutants (Total: 2, Killed: 2, Survived: 0)
9746: $code =~ /(?:die|croak|confess)\s+['"]Must\s+specify\s+either[^'"]*$param2[^'"]*or[^'"]*$param1/i) {
Mutants (Total: 2, Killed: 2, Survived: 0)
9747:
Mutants (Total: 2, Killed: 2, Survived: 0)
9748: my $found_reverse = 0; 9749: foreach my $rel (@relationships) { 9750: if ($rel->{type} eq 'required_group' && 9751: (($rel->{params}[0] eq $param2 && $rel->{params}[1] eq $param1))) { 9752: $found_reverse = 1; 9753: last; 9754: } 9755: } 9756: 9757: next if $found_reverse; 9758: 9759: push @relationships, { 9760: type => 'required_group', 9761: params => [$param1, $param2], 9762: logic => 'or', 9763: description => "Must specify either $param1 or $param2" 9764: }; 9765: 9766: $self->_log(" RELATIONSHIP: Must specify either $param1 or $param2 (from error message)"); 9767: } 9768: } 9769: } 9770: 9771: return \@relationships; 9772: } 9773:
Mutants (Total: 2, Killed: 2, Survived: 0)
9774: # -------------------------------------------------- 9775: # _detect_conditional_requirements 9776: # 9777: # Purpose: Detect IF-THEN parameter relationships 9778: # where one parameter being present 9779: # makes another required, by searching 9780: # for die/croak patterns of the form 9781: # 'die if $x && !$y'. 9782: # 9783: # Entry: $code - method body source string. 9784: # $param_names - arrayref of parameter 9785: # name strings. 9786: #
Mutants (Total: 1, Killed: 1, Survived: 0)
9787: # Exit: Returns an arrayref of relationship
Mutants (Total: 2, Killed: 2, Survived: 0)
9788: # hashrefs of type 9789: # 'conditional_requirement'. 9790: # Returns an empty arrayref if none found. 9791: #
9792: # Side effects: Logs detections to stdout whenMutants (Total: 1, Killed: 0, Survived: 1)
- COND_INV_9791_2: Invert condition if to unless
MEDIUM: Add tests asserting both true and false outcomesMutants (Total: 2, Killed: 2, Survived: 0)
9793: # verbose is set. 9794: # -------------------------------------------------- 9795: sub _detect_conditional_requirements {
●9796 → 9800 → 9842 9796: my ($self, $code, $param_names) = @_; 9797: 9798: my @relationships; 9799: 9800: foreach my $param1 (@$param_names) { 9801: foreach my $param2 (@$param_names) { 9802: next if $param1 eq $param2; 9803: 9804: # Pattern 1: die if $x && !$y (if x then y required) 9805: if ($code =~ /(?:die|croak|confess)[^;]*if\s+\$$param1\s+&&\s+!\$$param2/) { 9806: push @relationships, { 9807: type => 'conditional_requirement', 9808: if => $param1, 9809: then_required => $param2, 9810: description => "When $param1 is specified, $param2 is required" 9811: }; 9812: 9813: $self->_log(" RELATIONSHIP: $param1 requires $param2"); 9814: } 9815: 9816: # Pattern 2: die if $x && !defined($y) 9817: if ($code =~ /(?:die|croak|confess)[^;]*if\s+\$$param1\s+&&\s+!defined\s*\(\s*\$$param2\s*\)/) { 9818: push @relationships, { 9819: type => 'conditional_requirement', 9820: if => $param1, 9821: then_required => $param2, 9822: description => "When $param1 is specified, $param2 is required" 9823: }; 9824: 9825: $self->_log(" RELATIONSHIP: $param1 requires $param2 (defined check)"); 9826: } 9827: 9828: # Pattern 3: Error message "X requires Y" 9829: if ($code =~ /(?:die|croak|confess)\s+['"]\w*$param1[^'"]*requires[^'"]*$param2/i) { 9830: push @relationships, { 9831: type => 'conditional_requirement', 9832: if => $param1, 9833: then_required => $param2, 9834: description => "When $param1 is specified, $param2 is required" 9835: }; 9836: 9837: $self->_log(" RELATIONSHIP: $param1 requires $param2 (from error message)"); 9838: } 9839: } 9840: } 9841: 9842: return \@relationships; 9843: } 9844: 9845: # -------------------------------------------------- 9846: # _detect_dependencies 9847: # 9848: # Purpose: Detect simple parameter dependencies 9849: # where one parameter requires another 9850: # to also be present, by combining 9851: # error message pattern matching with 9852: # code condition matching. 9853: # 9854: # Entry: $code - method body source string. 9855: # $param_names - arrayref of parameter 9856: # name strings.Mutants (Total: 2, Killed: 0, Survived: 2)
- BOOL_NEGATE_9795_2: Negate boolean return expression
MEDIUM: Add tests asserting both true and false outcomes🧪 Suggested Test# Boolean branch test suggestion ok( !func(INPUT), 'Verify boolean branch behaviour' );- RETURN_UNDEF_9795_2: Replace return expression with undef
LOW: Mutation survived, but impact may be minor🧪 Suggested Test# Return value assertion is( func(INPUT), EXPECTED, 'Verify correct return value' );Mutants (Total: 1, Killed: 1, Survived: 0)
9857: # 9858: # Exit: Returns an arrayref of relationship 9859: # hashrefs of type 'dependency'. 9860: # Returns an empty arrayref if none found. 9861: # 9862: # Side effects: Logs detections to stdout when 9863: # verbose is set. 9864: # -------------------------------------------------- 9865: sub _detect_dependencies {
Mutants (Total: 1, Killed: 1, Survived: 0)
●9866 → 9870 → 9891 9866: my ($self, $code, $param_names) = @_;
Mutants (Total: 2, Killed: 2, Survived: 0)
9867: 9868: my @relationships;
Mutants (Total: 2, Killed: 2, Survived: 0)
9869: 9870: foreach my $param1 (@$param_names) { 9871: foreach my $param2 (@$param_names) { 9872: next if $param1 eq $param2; 9873: 9874: # Pattern 1: Error message mentions "X requires Y" AND code checks $x && !$y 9875: # Split into two checks to be more flexible 9876: if (($code =~ /(?:die|croak|confess)\s+['"]\w*$param1[^'"]*requires[^'"]*$param2/i) && 9877: ($code =~ /if\s+\$$param1\s+&&\s+!\$$param2/)) { 9878: 9879: push @relationships, { 9880: type => 'dependency', 9881: param => $param1, 9882: requires => $param2, 9883: description => "$param1 requires $param2 to be specified" 9884: }; 9885: 9886: $self->_log(" RELATIONSHIP: $param1 depends on $param2"); 9887: } 9888: } 9889: } 9890: 9891: return \@relationships; 9892: } 9893: 9894: # -------------------------------------------------- 9895: # _detect_value_constraints 9896: # 9897: # Purpose: Detect value-based constraints between 9898: # parameters, such as 'if $ssl then 9899: # $port must equal 443' or 'if $mode 9900: # eq secure then $key is required'. 9901: # 9902: # Entry: $code - method body source string. 9903: # $param_names - arrayref of parameter 9904: # name strings. 9905: # 9906: # Exit: Returns an arrayref of relationship 9907: # hashrefs of type 'value_constraint' 9908: # or 'value_conditional'. 9909: # Returns an empty arrayref if none found. 9910: # 9911: # Side effects: Logs detections to stdout when 9912: # verbose is set. 9913: # -------------------------------------------------- 9914: sub _detect_value_constraints { ●9915 → 9919 → 9969 9915: my ($self, $code, $param_names) = @_; 9916: 9917: my @relationships; 9918: 9919: foreach my $param1 (@$param_names) { 9920: foreach my $param2 (@$param_names) { 9921: next if $param1 eq $param2; 9922: 9923: # Pattern 1: die if $x && $y != value 9924: if ($code =~ /(?:die|croak|confess)[^;]*if\s+\$$param1\s+&&\s+\$$param2\s*!=\s*(\d+)/) { 9925: my $value = $1; 9926: push @relationships, { 9927: type => 'value_constraint', 9928: if => $param1, 9929: then => $param2, 9930: operator => '==', 9931: value => $value, 9932: description => "When $param1 is specified, $param2 must equal $value" 9933: }; 9934: 9935: $self->_log(" RELATIONSHIP: $param1 requires $param2 == $value"); 9936: } 9937: 9938: # Pattern 2: die if $x && $y < value 9939: if ($code =~ /(?:die|croak|confess)[^;]*if\s+\$$param1\s+&&\s+\$$param2\s*<\s*(\d+)/) { 9940: my $value = $1; 9941: push @relationships, { 9942: type => 'value_constraint', 9943: if => $param1, 9944: then => $param2, 9945: operator => '>=', 9946: value => $value, 9947: description => "When $param1 is specified, $param2 must be >= $value" 9948: }; 9949: 9950: $self->_log(" RELATIONSHIP: $param1 requires $param2 >= $value"); 9951: } 9952: 9953: # Pattern 3: die if $x eq 'value' && !$y 9954: if ($code =~ /(?:die|croak|confess)[^;]*if\s+\$$param1\s+eq\s+['"]([^'"]+)['"]\s+&&\s+!\$$param2/) { 9955: my $value = $1; 9956: push @relationships, { 9957: type => 'value_conditional', 9958: if => $param1, 9959: equals => $value, 9960: then_required => $param2, 9961: description => "When $param1 equals '$value', $param2 is required" 9962: }; 9963: 9964: $self->_log(" RELATIONSHIP: $param1='$value' requires $param2"); 9965: } 9966: } 9967: } 9968: 9969: return \@relationships; 9970: } 9971: 9972: # Write a single method schema to a YAML file in output_dir. 9973: # 9974: # Entry: $method_name is a non-empty string; $schema is a hashref. 9975: # Exit: YAML file written to output_dir/$method_name.yml. 9976: # Side effects: Creates output_dir if it does not exist. 9977: # Notes: Croaks if output_dir was not set in new(). 9978: 9979: sub _write_schema { ●9980 → 9994 → 10001 9980: my ($self, $method_name, $schema) = @_; 9981: 9982: # output_dir is required here â croak early with a clear message 9983: # rather than letting make_path fail with a cryptic error 9984: croak(__PACKAGE__, ': output_dir must be provided to new() when writing schema files') unless defined $self->{output_dir}; 9985: 9986: make_path($self->{output_dir}) unless -d $self->{output_dir}; 9987: 9988: my $filename = "$self->{output_dir}/${method_name}.yml"; 9989: 9990: local $YAML::XS::QuoteNumericStrings = 0; 9991: 9992: # Extract package name for module field 9993: my $package_name = ''; 9994: if ($self->{_document}) { 9995: my $package_stmt = $self->{_document}->find_first('PPI::Statement::Package'); 9996: $package_name = $package_stmt ? $package_stmt->namespace : ''; 9997: $self->{_package_name} //= $package_name; 9998: } 9999: 10000: # Clean up schema for output - use the format expected by App::Test::Generator::Template ●10001 → 10017 → 1002210001: my $output = { 10002: function => $method_name, 10003: module => $package_name, 10004: config => { 10005: close_stdin => 1, 10006: dedup => 1, 10007: test_nuls => 0, 10008: test_undef => 0, 10009: test_empty => 1, 10010: test_non_ascii => 0, 10011: test_security => 0 10012: } 10013: }; 10014: 10015: # A file the POD documents the routine creating or writing is the 10016: # requested result, not a leftover, so turn that destructive check off. 10017: if($schema->{_analysis}{side_effects}{writes_file}) { 10018: $output->{config}{check_files} = 0; 10019: } 10020: # A routine that returns a database handle keeps a descriptor open by 10021: # design; the harness is told not to call that a leak. ●10022 → 10022 → 1002810022: if($schema->{_analysis}{side_effects}{keeps_fd}) { 10023: $output->{config}{check_fds} = 0; 10024: } 10025: 10026: # The routine has a precondition no generated value can meet, so there is 10027: # nothing meaningful to fuzz; the harness and all-fuzz report it skipped. ●10028 → 10034 → 1006910028: $output->{skip} = $schema->{skip} if($schema->{skip}); 10029: 10030: # A class method is called as Module->routine(...), not Module::routine(...). 10031: $output->{invocant} = $schema->{invocant} if($schema->{invocant}); 10032: 10033: # Process input parameters with advanced type handling 10034: if($schema->{'input'}) { 10035: if(scalar(keys %{$schema->{'input'}})) { 10036: $output->{'input'} = {}; 10037: 10038: foreach my $param_name (sort keys %{$schema->{'input'}}) { 10039: my $param = $schema->{'input'}{$param_name}; 10040: if($param->{name}) { 10041: my $name = delete $param->{name}; 10042: if($name ne $param_name) { 10043: # Sanity check 10044: croak("BUG: Parameter name - expected $param_name, got $name"); 10045: } 10046: } 10047: my $cleaned_param = $self->_serialize_parameter_for_yaml($param); 10048: $output->{'input'}{$param_name} = $cleaned_param; 10049: } 10050: 10051: # If some params have positions and others neither a position nor 10052: # named: 1, treat the whole input as a named (hash) API and strip 10053: # all positions. Such mixed state arises when a named-API method 10054: # also happens to have a Params::Get positional-key call alongside 10055: # =head4 Input named-block params that carry no position. A param 10056: # marked named: 1 is deliberate: it is an option after the 10057: # positional arguments, and the two kinds are fuzzed together. 10058: my @with_pos = grep { defined $output->{input}{$_}{position} } sort keys %{$output->{input}}; 10059: my @without_pos = grep { !defined $output->{input}{$_}{position} } sort keys %{$output->{input}}; 10060: if (@with_pos && grep { !$output->{input}{$_}{named} } @without_pos) { 10061: delete $output->{input}{$_}{position} for @with_pos; 10062: } 10063: } else { 10064: delete $output->{input}; 10065: } 10066: } 10067: 10068: # Process output ●10069 → 10069 → 1007910069: if($schema->{'output'} && (scalar(keys %{$schema->{'output'}}))) { 10070: if((ref($schema->{output}{_error_handling}) eq 'HASH') && (scalar(keys %{$schema->{output}{_error_handling}}) == 0)) { 10071: delete $schema->{output}{_error_handling}; 10072: } 10073: # value/alt_value are inference metadata; Return::Set does not recognise them as validation rules 10074: my %out_spec = %{$schema->{'output'}}; 10075: delete @out_spec{qw(value alt_value)}; 10076: $output->{'output'} = \%out_spec; 10077: } 10078: ●10079 → 10079 → 1008510079: if($schema->{'output'}{'type'} && ($schema->{'output'}{'type'} eq 'scalar')) { 10080: $schema->{'output'}{'type'} = 'string'; 10081: $schema->{_confidence}{output}->{level} = 'low'; # A guess 10082: } 10083: 10084: # Add 'new' field if object instantiation is needed ●10085 → 10085 → 1009610085: if ($schema->{new}) { 10086: # TODO: consider allowing parent class packages up the ISA chain 10087: if(ref($schema->{new}) || ($schema->{new} eq $package_name)) { 10088: $output->{new} = $schema->{new} eq $package_name ? undef : $schema->{'new'}; 10089: } else { 10090: $self->_log(" NEW: Don't use $schema->{new} for object insantiation"); 10091: delete $schema->{new}; 10092: delete $output->{new}; 10093: } 10094: } 10095: ●10096 → 10096 → 1009910096: if(!defined($schema->{_confidence}{input}->{level})) { 10097: $schema->{_confidence}{input} = $self->_calculate_input_confidence($schema->{input}); 10098: } ●10099 → 10099 → 1010410099: if(!defined($schema->{_confidence}{output}->{level})) { 10100: $schema->{_confidence}{output} = $self->_calculate_output_confidence($schema->{output}); 10101: } 10102: 10103: # Add relationships if detected ●10104 → 10104 → 1010810104: if ($schema->{relationships} && @{$schema->{relationships}}) { 10105: $output->{relationships} = $schema->{relationships}; 10106: } 10107: ●10108 → 10108 → 1011210108: if($schema->{accessor} && scalar(keys %{$schema->{accessor}})) { 10109: $output->{accessor} = $schema->{accessor}; 10110: } 10111: 10112: open my $fh, '>', $filename; 10113: print $fh YAML::XS::Dump($output); 10114: print $fh $self->_generate_schema_comments($schema, $method_name); 10115: close $fh; 10116: 10117: my $rel_info = $schema->{relationships} ? 10118: ' [' . scalar(@{$schema->{relationships}}) . ' relationships]' : ''; 10119: $self->_log(" Wrote: $filename (input confidence: $schema->{_confidence}{input}->{level})" . 10120: ($schema->{new} ? " [requires: $schema->{new}]" : '') . $rel_info); 10121: } 10122: 10123: # -------------------------------------------------- 10124: # _generate_schema_comments 10125: # 10126: # Purpose: Generate the YAML comment block 10127: # appended to the end of each written 10128: # schema file, containing provenance, 10129: # confidence levels, parameter type 10130: # notes, relationship summaries, and 10131: # warnings about types requiring 10132: # special test setup. 10133: # 10134: # Entry: $schema - the schema hashref as 10135: # built by _analyze_method. 10136: # $method_name - the method name string, 10137: # used in the fuzz 10138: # command hint. 10139: # 10140: # Exit: Returns a string of YAML comment lines 10141: # beginning with a blank line and ending 10142: # with a trailing newline. 10143: # 10144: # Side effects: None. 10145: # -------------------------------------------------- 10146: sub _generate_schema_comments { ●10147 → 10159 → 1018810147: my ($self, $schema, $method_name) = @_; 10148: 10149: my @comments; 10150: 10151: push @comments, ''; 10152: push @comments, '# Generated by ' . ref($self); 10153: push @comments, "# Run: fuzz-harness-generator -r $self->{output_dir}/${method_name}.yml"; 10154: push @comments, '#'; 10155: push @comments, "# Input confidence: $schema->{_confidence}{input}->{level}"; 10156: push @comments, "# Output confidence: $schema->{_confidence}{output}->{level}"; 10157: 10158: # Add notes about parameters 10159: if ($schema->{input}) { 10160: my @param_notes; 10161: foreach my $param_name (sort keys %{$schema->{input}}) { 10162: my $p = $schema->{input}{$param_name}; 10163: 10164: if ($p->{semantic}) { 10165: push @param_notes, "$param_name: $p->{semantic}"; 10166: } 10167: 10168: if ($p->{enum}) { 10169: push @param_notes, "$param_name: enum with " . scalar(@{$p->{enum}}) . " values"; 10170: } 10171: 10172: if ($p->{isa}) { 10173: push @param_notes, "$param_name: requires $p->{isa} object"; 10174: } 10175: } 10176: 10177: if (@param_notes) { 10178: push @comments, '#'; 10179: push @comments, '# Parameter types detected:'; 10180: foreach my $note (sort @param_notes) { 10181: push @comments, "# - $note"; 10182: } 10183: } 10184: } 10185: 10186: # Add relationship notes, sorted so their order does not depend on 10187: # detection order. ●10188 → 10188 → 1020210188: if ($schema->{relationships} && @{$schema->{relationships}}) { 10189: push @comments, ( 10190: '#', 10191: '# Parameter relationships detected:' 10192: ); 10193: my @relationship_notes = map { 10194: $_->{description} || _format_relationship($_) 10195: } @{$schema->{relationships}}; 10196: foreach my $desc (sort @relationship_notes) { 10197: push @comments, "# - $desc"; 10198: } 10199: } 10200: 10201: # Add general notes ●10202 → 10202 → 1021010202: if ($schema->{_notes} && scalar(@{$schema->{_notes}})) { 10203: push @comments, '#'; 10204: push @comments, '# Notes:'; 10205: foreach my $note (sort @{$schema->{_notes}}) { 10206: push @comments, "# - $note"; 10207: } 10208: } 10209: ●10210 → 10210 → 1022910210: if($schema->{_analysis}) { 10211: push @comments, ( 10212: '#', 10213: '# Analysis:', 10214: '# TODO:', 10215: ); 10216: # confidence_factors: 10217: # input: 10218: # - No parameters found 10219: # output: 10220: # - 'Return type defined: object (+30)' 10221: # - 'Total output confidence score: 30' 10222: # - 'Medium confidence: return type defined' 10223: # input_confidence: none 10224: # output_confidence: medium 10225: # overall_confidence: none 10226: } 10227: 10228: # Add warnings for complex types ●10229 → 10230 → 1024810229: my @warnings; 10230: if ($schema->{input}) { 10231: foreach my $param_name (sort keys %{$schema->{input}}) { 10232: my $p = $schema->{input}{$param_name}; 10233: 10234: if ($p->{type} && $p->{type} eq 'coderef') { 10235: push @warnings, "Parameter '$param_name' is a coderef - you'll need to provide a sub {} in tests"; 10236: } 10237: 10238: if ($p->{semantic} && $p->{semantic} eq 'filehandle') { 10239: push @warnings, "Parameter '$param_name' is a filehandle - consider using IO::String or mock"; 10240: } 10241: 10242: if ($p->{isa} && $p->{isa} =~ /DateTime/) { 10243: push @warnings, "Parameter '$param_name' requires DateTime - ensure DateTime is loaded"; 10244: } 10245: } 10246: } 10247: ●10248 → 10248 → 1025610248: if (@warnings) { 10249: push @comments, '#'; 10250: push @comments, '# WARNINGS - Manual test setup may be required:'; 10251: foreach my $warning (sort @warnings) { 10252: push @comments, "# ! $warning"; 10253: } 10254: } 10255: 10256: push @comments, ''; 10257: 10258: return join("\n", @comments); 10259: } 10260: 10261: # -------------------------------------------------- 10262: # _serialize_parameter_for_yaml 10263: # 10264: # Purpose: Convert a parameter spec hashref into 10265: # a cleaned, YAML-serialisable form 10266: # suitable for App::Test::Generator 10267: # consumption, handling semantic type 10268: # mappings, enum values, and object 10269: # class annotations. 10270: # 10271: # Entry: $param - parameter spec hashref as 10272: # produced by the merge and 10273: # analysis pipeline. 10274: # 10275: # Exit: Returns a new hashref containing only 10276: # the fields App::Test::Generator 10277: # understands, with internal _ keys 10278: # and semantic keys removed or converted. 10279: # 10280: # Side effects: None. 10281: # 10282: # Notes: Semantic types are mapped to 10283: # appropriate base types with additional 10284: # constraint and note fields. 10285: # The original $param hashref is not 10286: # modified. 10287: # -------------------------------------------------- 10288: sub _serialize_parameter_for_yaml { ●10289 → 10294 → 1029910289: my ($self, $param) = @_; 10290: 10291: my %cleaned; 10292: 10293: # Copy basic fields that App::Test::Generator expects 10294: foreach my $field (qw(type position named optional min max sample_max matches default _not_empty)) { 10295: $cleaned{$field} = $param->{$field} if defined $param->{$field}; 10296: } 10297: 10298: # Provenance drives the harness's tolerance and type-check decisions. ●10299 → 10303 → 1031310299: $cleaned{_source} = $param->{_source} if defined($param->{_source}) && length($param->{_source}); 10300: 10301: # Per-constraint provenance: a documented minimum and a code-enforced 10302: # maximum on the same field are separate decisions. 10303: if(ref($param->{_constraint_source}) eq 'HASH') { 10304: my %provenance; 10305: foreach my $key (qw(min max memberof matches nomatch notmemberof)) { 10306: my $source = $param->{_constraint_source}{$key}; 10307: $provenance{$key} = $source if defined($source) && length($source); 10308: } 10309: $cleaned{_constraint_source} = \%provenance if keys %provenance; 10310: } 10311: 10312: # Handle advanced type mappings ●10313 → 10313 → 1039510313: if(my $semantic = $param->{semantic}) { 10314: if ($semantic eq 'datetime_object') { 10315: # DateTime objects: test generator needs to know how to create them 10316: $cleaned{type} = 'object'; 10317: $cleaned{isa} = $param->{isa} || 'DateTime'; 10318: $cleaned{_note} = 'Requires DateTime object'; 10319: } elsif ($semantic eq 'timepiece_object') { 10320: $cleaned{type} = 'object'; 10321: $cleaned{isa} = $param->{isa} || 'Time::Piece'; 10322: $cleaned{_note} = 'Requires Time::Piece object'; 10323: } elsif ($semantic eq 'date_string') { 10324: # Date strings: provide regex pattern 10325: $cleaned{type} = 'string'; 10326: $cleaned{matches} ||= '/^\d{4}-\d{2}-\d{2}$/'; 10327: $cleaned{_example} = '2024-12-12'; 10328: } elsif ($semantic eq 'bytes') { 10329: # A byte string is not text: the harness passes bytes and makes no 10330: # wide-character (BOM) probe, which a byte-oriented write rejects. 10331: $cleaned{semantic} = 'bytes'; 10332: $cleaned{type} //= 'string'; 10333: } elsif ($semantic eq 'iso8601_string') { 10334: $cleaned{type} = 'string'; 10335: $cleaned{matches} ||= '/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z?$/'; 10336: $cleaned{_example} = '2024-12-12T10:30:00Z'; 10337: } elsif ($semantic eq 'unix_timestamp') { 10338: $cleaned{type} = 'integer'; 10339: $cleaned{min} ||= 0; 10340: $cleaned{max} ||= $INT32_MAX; # 32-bit max 10341: $cleaned{_note} = 'UNIX timestamp'; 10342: } elsif ($semantic eq 'datetime_parseable') { 10343: $cleaned{type} = 'string'; 10344: $cleaned{_note} = 'Must be parseable as datetime'; 10345: } elsif ($semantic eq 'filehandle') { 10346: # File handles: special handling needed 10347: $cleaned{type} = 'object'; 10348: $cleaned{isa} = $param->{isa} || 'IO::Handle'; 10349: $cleaned{_note} = 'File handle - may need mock in tests'; 10350: } elsif ($semantic eq 'filepath') { 10351: # File paths: string with path pattern 10352: $cleaned{type} = 'string'; 10353: $cleaned{matches} ||= '/^[\\w\\/.\\-_]+$/'; 10354: $cleaned{_note} = 'File path'; 10355: } elsif ($semantic eq 'existing_file') { 10356: # The routine only tests that the file exists. Any existing 10357: # file satisfies that, so keep the semantic for the harness to 10358: # supply a temporary file instead of guessing at a path. 10359: $cleaned{type} = 'string'; 10360: $cleaned{semantic} = 'existing_file'; 10361: $cleaned{_note} = 'Existing file'; 10362: } elsif ($semantic eq 'directory') { 10363: # The value must name an existing directory. No pattern can 10364: # express that and any generated path would fail the -d test, 10365: # so keep the semantic for the harness to act on instead of 10366: # guessing at the spelling. 10367: $cleaned{type} = 'string'; 10368: $cleaned{semantic} = 'directory'; 10369: $cleaned{_note} = 'Existing directory'; 10370: } elsif ($semantic eq 'callback') { 10371: # Coderefs: mark as special type 10372: $cleaned{type} = 'coderef'; 10373: $cleaned{_note} = 'CODE reference - provide sub { } in tests'; 10374: } elsif ($semantic eq 'enum') { 10375: # Enum: keep as string but add valid values. 10376: # If the formal input spec explicitly declared a different type, honour 10377: # it â the enum values from code analysis are regex-internal alternates 10378: # (e.g. numeric format variants) that are meaningless as string choices. 10379: if (($param->{_source} // '') eq SOURCE_INPUT_SPEC && defined $param->{type} && $param->{type} ne 'string') { 10380: # Formal spec wins; suppress spurious regex-derived enum. 10381: delete $cleaned{enum}; 10382: } else { 10383: $cleaned{type} = 'string'; 10384: if ($param->{enum} && ref($param->{enum}) eq 'ARRAY') { 10385: $cleaned{enum} = $param->{enum}; 10386: $cleaned{_note} = 'Must be one of: ' . join(', ', @{$param->{enum}}); 10387: } 10388: } 10389: } 10390: } 10391: 10392: # The harness injected this value itself (a stub's advertised column), so 10393: # it is a fixture rather than a documented domain: no outside value is 10394: # expected to be an error. ●10395 → 10399 → 1040810395: $cleaned{_fixture} = 1 if($param->{_fixture}); 10396: 10397: # The element shape of an arrayref of hashrefs, read from the POD's nested 10398: # key block: a YAML scalar cannot describe it. 10399: if(ref($param->{schema}) eq 'HASH') { 10400: $cleaned{schema} = $param->{schema}; 10401: } 10402: 10403: # Handle memberof even if not marked with semantic. 10404: # enum and memberof are mutually exclusive â only set memberof when enum 10405: # is not already being output (avoids the "has both" validation error). 10406: # Also suppress when the formal input spec declared a non-string type â 10407: # the enum values are regex-internal alternates, not valid string members. ●10408 → 10409 → 1041210408: my $formal_non_string = (($param->{_source} // '') eq SOURCE_INPUT_SPEC) && defined $param->{type} && $param->{type} ne 'string'; 10409: if($param->{enum} && ref($param->{enum}) eq 'ARRAY' && !$cleaned{enum} && !$formal_non_string) { 10410: $cleaned{memberof} = $param->{enum}; 10411: } ●10412 → 10412 → 1041710412: if($param->{memberof} && ref($param->{memberof}) eq 'ARRAY') { 10413: $cleaned{memberof} = $param->{memberof}; 10414: } 10415: 10416: # Handle object class ●10417 → 10417 → 1042210417: if ($param->{isa} && !$cleaned{isa}) { 10418: $cleaned{isa} = $param->{isa}; 10419: } 10420: 10421: # Add format hints where available ●10422 → 10422 → 1043210422: if ($param->{format}) { 10423: $cleaned{_format} = $param->{format}; 10424: } 10425: 10426: # Patterns harvested from source or POD arrive as slash-delimited 10427: # literals ('/^abc$/'). Consumers compile what they are given with 10428: # qr//, which would take the delimiters to be part of the pattern, so 10429: # store the pattern body. It stays a plain string: a compiled Regexp 10430: # is written to YAML as a !!perl/regexp object that a YAML consumer 10431: # cannot read back, and the schema is a data file. ●10432 → 10432 → 1045110432: if(defined(my $pattern = $cleaned{matches})) { 10433: if((reftype($pattern) // '') eq 'REGEXP') { 10434: # Some extraction paths hand over a compiled pattern, possibly a 10435: # blessed subclass (e.g. a regexp from a Safe compartment). 10436: my ($body) = re::regexp_pattern($pattern); 10437: $cleaned{matches} = $body if defined($body); 10438: } elsif(!ref($pattern)) { 10439: (my $body = $pattern) =~ s{^/(.+)/$}{$1}s; 10440: my $compiled = eval { qr/$body/ }; 10441: if($@) { 10442: $self->_log(" invalid matches pattern '$pattern': $@"); 10443: } else { 10444: $cleaned{matches} = $body; 10445: } 10446: } 10447: } 10448: 10449: # A stand-in for an arrayref of live objects: the harness has to build 10450: # one, and a YAML scalar cannot describe it. ●10451 → 10451 → 1045710451: if(ref($param->{_stub_elements}) eq 'HASH') { 10452: $cleaned{_stub_elements} = $param->{_stub_elements}; 10453: } 10454: 10455: # Remove internal fields. The directory and existing-file semantics are 10456: # kept: the harness needs them to supply a path that exists. 10457: delete $cleaned{semantic} 10458: unless(($cleaned{semantic} // '') =~ /^(?:directory|existing_file|bytes)$/); 10459: 10460: return \%cleaned; 10461: } 10462: 10463: # -------------------------------------------------- 10464: # _format_relationship 10465: # 10466: # Purpose: Format a relationship hashref as a 10467: # short human-readable description 10468: # string for use in YAML comments. 10469: # 10470: # Entry: $rel - relationship hashref as 10471: # produced by the relationship 10472: # detection methods. 10473: # 10474: # Exit: Returns a description string. 10475: # Returns 'Unknown relationship' for 10476: # unrecognised types. 10477: # 10478: # Side effects: None. 10479: # -------------------------------------------------- 10480: sub _format_relationship { ●10481 → 10483 → 1049610481: my $rel = $_[0]; 10482: 10483: if ($rel->{type} eq 'mutually_exclusive') { 10484: return 'Mutually exclusive: ' . join(', ', @{$rel->{params}}); 10485: } elsif ($rel->{type} eq 'required_group') { 10486: return "Required group (OR): " . join(', ', @{$rel->{params}}); 10487: } elsif ($rel->{type} eq 'conditional_requirement') { 10488: return "If $rel->{if} then $rel->{then_required} required"; 10489: } elsif ($rel->{type} eq 'dependency') { 10490: return "$rel->{param} depends on $rel->{requires}"; 10491: } elsif ($rel->{type} eq 'value_constraint') { 10492: return "If $rel->{if} then $rel->{then} $rel->{operator} $rel->{value}"; 10493: } elsif ($rel->{type} eq 'value_conditional') { 10494: return "If $rel->{if}='$rel->{equals}' then $rel->{then_required} required"; 10495: } 10496: return 'Unknown relationship'; 10497: } 10498: 10499: # -------------------------------------------------- 10500: # _needs_object_instantiation 10501: # 10502: # Purpose: Determine whether a method requires 10503: # -------------------------------------------------- 10504: # _ctor_representative_args 10505: # 10506: # Purpose: Given a new() method schema, return a 10507: # hashref of representative values for its 10508: # required parameters, suitable for use as 10509: # the new: key in an instance-method schema. 10510: # Returns {} for a no-arg constructor. 10511: # Returns undef when any required param is 10512: # of a type that cannot be represented as a 10513: # plain YAML scalar (e.g. coderef, object). 10514: # 10515: # Entry: $ctor_schema - schema hashref for new(). 10516: # 10517: # Exit: Hashref of {param => value} or undef. 10518: # -------------------------------------------------- 10519: 10520: # A parameter whose value the routine reads from disk is a precondition, not an 10521: # argument the harness can make up. Two cases are distinguishable: 10522: # 10523: # * the routine only tests that the file exists (`-e`/`-f`) and keeps the 10524: # path, as a constructor validating its argument does. Any existing file 10525: # will do, so the parameter is marked semantic => 'existing_file' and the 10526: # harness supplies a real temporary file. 10527: # * the routine parses or slurps the file's contents. No synthesized or 10528: # empty fixture can satisfy that, so the routine is reported as skipped 10529: # rather than failed on a call it could never make correctly. 10530: sub _requires_input_file 10531: { ●10532 → 10537 → 1056510532: my ($body, $input) = @_; 10533: 10534: return undef unless(ref($input) eq 'HASH'); 10535: return undef unless(defined($body) && length($body)); 10536: 10537: foreach my $param (sort keys %{$input}) { 10538: my $p = quotemeta($param); 10539: 10540: # The value is often copied out of %args under another name first. 10541: my @names = ($p); 10542: while($body =~ /\bmy\s+\$(\w+)\s*=\s*\$args\{\s*['"]?$p['"]?\s*\}\s*;/g) { 10543: push @names, quotemeta($1) if($1 ne $param); 10544: } 10545: my $v = '(?:' . join('|', @names) . ')'; 10546: 10547: # A file whose contents are read, not merely tested for existence. 10548: return 'needs an existing input file whose contents it parses' 10549: if($body =~ /\b(?:PPI::Document->new|_load_schema|_slurp|read_file|slurp_file)\s*\(\s*\$$v\b/ 10550: || $body =~ /\bopen\b\s*\(?[^;]*['"]<[^;]*\$$v\b/); 10551: 10552: my $tests_existence = ($body =~ /-[ef]\s+\$args\{\s*['"]?$p['"]?\s*\}/) 10553: || ($body =~ /-[ef]\s+\$$v\b/) 10554: || ($body =~ /-[ef]\s+\$self->\{\s*['"]?$p['"]?\s*\}/); 10555: # Object::Configure reads the file its caller's config_file names and 10556: # croaks when it is missing; that test is not in this body to be seen. 10557: $tests_existence ||= ($param eq 'config_file') 10558: && ($body =~ /\bObject::Configure::configure\s*\(/); 10559: next unless($tests_existence); 10560: 10561: my $spec = $input->{$param}; 10562: $spec->{semantic} = 'existing_file' if(ref($spec) eq 'HASH'); 10563: } 10564: 10565: return undef; 10566: } 10567: 10568: # The part of a formal-spec entry that describes the entry itself, without 10569: # any nested { ... } such as a properties map. The named and positional 10570: # parsers capture up to the first closing brace, so an unbalanced trailing 10571: # nested opening is dropped as well. 10572: sub _own_spec_text 10573: { 10574: my $spec = $_[0] // ''; 10575: 10576: 1 while($spec =~ s/\{[^{}]*\}//g); 10577: $spec =~ s/\{.*\z//s; 10578: 10579: return $spec; 10580: } 10581: 10582: # The optional flag a formal-spec entry gives its own parameter: 0 or 1, or 10583: # undef when it says nothing. An explicit optional wins over required. 10584: sub _spec_optionality 10585: { 10586: my $own = _own_spec_text($_[0]); 10587: 10588: return $1 + 0 if($own =~ /\boptional\s*=>\s*(0|1)/i); 10589: return 1 - $1 if($own =~ /\brequired\s*=>\s*(0|1)/i); 10590: return undef; 10591: } 10592: 10593: # The name => { ... } entries at brace depth 0 of a bare-list spec, as 10594: # [ name, body ] pairs with the body's nested braces intact. 10595: sub _top_level_hash_entries 10596: { ●10597 → 10601 → 1062210597: my $text = $_[0]; 10598: 10599: my (@entries, $pending, $name, $start); 10600: my $depth = 0; 10601: while($text =~ /\b(\w+)\s*=>\s*(?=\{)|([{}])/g) { 10602: if(defined($1)) { 10603: $pending = $1 if($depth == 0); 10604: next; 10605: } 10606: if($2 eq '{') { 10607: if(($depth == 0) && defined($pending)) { 10608: ($name, $start) = ($pending, pos($text)); 10609: } 10610: undef $pending; 10611: $depth++; 10612: next; 10613: } 10614: next unless($depth > 0); 10615: $depth--; 10616: if(($depth == 0) && defined($name)) { 10617: push @entries, [ $name, substr($text, $start, pos($text) - 1 - $start) ]; 10618: undef $name; 10619: } 10620: } 10621: 10622: return @entries; 10623: } 10624: 10625: # True when a required arrayref constructor parameter is not a list of 10626: # values but a list of live objects: the constructor rejects an empty list, 10627: # calls methods on the elements, or checks that they are blessed. A YAML 10628: # fixture cannot contain such objects, so both new() and the instance methods 10629: # that need its result must be reported as skipped. 10630: # 10631: # Database::Join->new is the motivating case: its databases parameter must 10632: # hold one or more Database::Abstraction instances, and the constructor calls 10633: # columns() on each one to build its routing table. 10634: # True when a constructor takes an object it will call methods on and the 10635: # schema gives no can/isa for standing one in, or an existing directory whose 10636: # files it reads. A YAML fixture can hold neither, so new() is reported as 10637: # skipped and the instance methods that need its result are not fuzzed. 10638: sub _constructor_needs_live_dependencies 10639: { ●10640 → 10645 → 1065810640: my ($ctor_schema) = @_; 10641: 10642: my $input = $ctor_schema->{input}; 10643: return undef unless(ref($input) eq 'HASH'); 10644: 10645: for my $param (sort keys %$input) { 10646: my $spec = $input->{$param}; 10647: next unless(ref($spec) eq 'HASH'); 10648: 10649: my $type = $spec->{type} // ''; 10650: if(($type =~ /\bobject\b/) && !defined($spec->{can}) && !defined($spec->{isa})) { 10651: return "constructor needs a live '$param' object, which a fixture cannot provide"; 10652: } 10653: if(($spec->{semantic} // '') eq 'directory') { 10654: return "constructor needs an existing '$param' directory, which a fixture cannot provide"; 10655: } 10656: } 10657: 10658: return undef; 10659: } 10660: 10661: # The required arrayref constructor parameters whose elements are live 10662: # objects, with the reason each one is: the constructor rejects an empty 10663: # list, calls a method on an element, or checks that an element is blessed. 10664: # The names matter as well as the reasons, because a stand-in can be supplied 10665: # for every such parameter when the POD says what the elements are. 10666: sub _constructor_live_object_param_reasons 10667: { ●10668 → 10677 → 1070310668: my ($body, $ctor_schema) = @_; 10669: 10670: my $content = ref($body) ? eval { $body->content } : $body; 10671: return () unless(defined($content) && length($content)); 10672: 10673: my $input = $ctor_schema->{input}; 10674: return () unless(ref($input) eq 'HASH'); 10675: 10676: my %reasons; 10677: for my $param (sort keys %$input) { 10678: my $spec = $input->{$param}; 10679: next unless(ref($spec) eq 'HASH'); 10680: next if($spec->{optional}); 10681: 10682: my $type = $spec->{type} // ''; 10683: next unless(($type eq 'arrayref') || ($type eq 'array')); 10684: 10685: my $p = quotemeta($param); 10686: my $field = qr/\$\w+(?:->)?\{\s*['"]?$p['"]?\s*\}/; 10687: 10688: # `croak ... unless @{ $p->{databases} }`. 10689: my $empty_guard = ($content =~ /\bcroak\b[^;]*?\bunless\b[^;]*?\@\{\s*$field\s*\}/s); 10690: 10691: # An element is blessed or has a method called on it. 10692: my $elements_are_objects = 10693: ($content =~ /$field\s*(?:->\s*)?\[\s*[^\]]+\s*\]\s*->\s*\w+/) 10694: || ($content =~ /\bblessed\s*\(\s*$field\s*(?:->\s*)?\[\s*[^\]]+\s*\]\s*\)/); 10695: 10696: next unless($empty_guard || $elements_are_objects); 10697: 10698: $reasons{$param} = $empty_guard 10699: ? "needs a non-empty arrayref of live objects in '$param'" 10700: : "needs live objects in '$param'"; 10701: } 10702: 10703: return %reasons; 10704: } 10705: 10706: sub _constructor_requires_live_objects 10707: { 10708: my ($body, $ctor_schema) = @_; 10709: 10710: my %reasons = _constructor_live_object_param_reasons($body, $ctor_schema); 10711: return undef unless(%reasons); 10712: 10713: my ($param) = sort keys %reasons; 10714: return $reasons{$param}; 10715: } 10716: 10717: # The class the POD says a constructor's object elements must be, e.g. 10718: # "Each element of C<databases> must be an already-instantiated subclass of 10719: # C<Database::Abstraction>". Reading it from the documentation keeps the 10720: # stand-in the harness builds tied to what the constructor promises rather 10721: # than to a class name guessed from the code. 10722: sub _pod_constructor_element_class 10723: { 10724: my ($pod) = @_; 10725: 10726: return undef unless(defined($pod) && length($pod)); 10727: 10728: return $1 if($pod =~ /\bsubclass(?:es)?\s+of\s+(?:C<)?([A-Z]\w*(?:::\w+)+)/); 10729: return $1 if($pod =~ /\bisa\s*\(\s*['\"]?([A-Z]\w*(?:::\w+)+)/); 10730: return $1 if($pod =~ /\binstances?\s+of\s+(?:C<)?([A-Z]\w*(?:::\w+)+)/); 10731: 10732: return undef; 10733: } 10734: 10735: # Teach the harness to stand an object in for a constructor argument that 10736: # YAML cannot hold. Database::Join->new requires a non-empty list of live 10737: # Database::Abstraction objects: nothing a generated file can name gives it 10738: # one, so every instance method used to be skipped. The POD names the base 10739: # class, and the documented join_column default names the column the 10740: # constructor checks for, so a stub that answers the DA methods the 10741: # constructor calls can be built: it is blessed into a package inheriting 10742: # from the documented class and answers columns(), schema() and 10743: # selectall_arrayref(). 10744: # 10745: # Only the Database::Abstraction interface is stubbed: those are the methods 10746: # the canned answers describe. Anything else keeps the skip. 10747: sub _constructor_object_stubs 10748: { ●10749 → 10763 → 1078410749: my ($ctor_schema, $pod, $body) = @_; 10750: 10751: my %reasons = _constructor_live_object_param_reasons($body, $ctor_schema); 10752: return {} unless(%reasons); 10753: 10754: my $base = _pod_constructor_element_class($pod); 10755: return {} unless(defined($base) && ($base eq 'Database::Abstraction')); 10756: 10757: my $input = $ctor_schema->{input} // {}; 10758: my $join_column = (ref($input->{join_column}) eq 'HASH') 10759: ? $input->{join_column}{default} : undef; 10760: return {} unless(defined($join_column) && !ref($join_column) && length($join_column)); 10761: 10762: my %stubs; 10763: for my $param (sort keys %reasons) { 10764: # The constructor's own `croak ... unless @{ $p->{$param} }` documents 10765: # that the list must not be empty. 10766: $input->{$param}{min} = 1; 10767: my $stub = { 10768: isa => $base, 10769: methods => { 10770: columns => [ $join_column ], 10771: schema => {}, 10772: selectall_arrayref => [], 10773: }, 10774: }; 10775: $input->{$param}{_stub_elements} = $stub; 10776: $stubs{$param} = $stub; 10777: } 10778: 10779: # The stand-in advertises only the join column, so that is the only value 10780: # its columns() reports and the only one the constructor's check accepts. 10781: # The list is a harness fixture, not a documented domain: every other 10782: # string is absent from every stub database and rightly croaks, so only 10783: # the fixture value is exercised. ●10784 → 10784 → 1079310784: if(ref($input->{join_column}) eq 'HASH') { 10785: $input->{join_column}{memberof} = [ $join_column ]; 10786: $input->{join_column}{_constraint_source}{memberof} = 'fixture'; 10787: $input->{join_column}{_fixture} = 1; 10788: } 10789: 10790: # A documented predicate's column must exist in the merged view too, and 10791: # the only column the stand-in publishes is the join column 10792: # (Database::Join::new's mandatory_filters). ●10793 → 10793 → 1080210793: for my $param (keys %$input) { 10794: my $element = $input->{$param}{schema}; 10795: next unless(ref($element) eq 'HASH' && ref($element->{col}) eq 'HASH'); 10796: next if(ref($element->{col}{memberof}) eq 'ARRAY' && @{$element->{col}{memberof}}); 10797: $element->{col}{memberof} = [ $join_column ]; 10798: $element->{col}{_constraint_source}{memberof} = 'fixture'; 10799: $element->{col}{_fixture} = 1; 10800: } 10801: 10802: return \%stubs; 10803: } 10804: 10805: # -------------------------------------------------- 10806: # _keeps_database_handle 10807: # 10808: # Purpose: Decide whether a call keeps a database handle open on purpose, 10809: # so the harness's "no file descriptors leaked" check can be off. 10810: # 10811: # Entry: $body - the subroutine source text. 10812: # $pod - the routine's POD text ('' when it has none). 10813: # 10814: # Exit: Returns 1 when the call holds a descriptor rather than leaking 10815: # one, 0 otherwise. 10816: # 10817: # Notes: Three documented shapes, each narrow. A handle returned to the 10818: # caller needs the POD to document C<dbh> (Database::Join's 10819: # dbi_source). A routine that queries the documented SQLite 10820: # cache goes through the cache path, whose first call builds the 10821: # cache and keeps the handle on the object (count and aggregate 10822: # document "the cached join tables" / "the existing SQLite 10823: # cache"). Storing the handle on the object is retention in 10824: # itself, so it needs no inference (the cache builder). 10825: # Invalidation is not retention: Database::Join::add_database 10826: # deletes and disconnects the cache and documents no cache, so 10827: # its calls stay checked. 10828: # 10829: # Side effects: None. 10830: # -------------------------------------------------- 10831: sub _keeps_database_handle 10832: { 10833: my ($body, $pod) = @_; 10834: 10835: return 0 unless defined($body); 10836: 10837: # A handle handed to the caller, as the POD's output documents it. 10838: return 1 if(($body =~ /\breturn\s*\{[^}]*\bdbh\s*=>/s) && ($pod =~ /\bdbh\b/)); 10839: 10840: # The cache builder stores the handle on the object for the next call. 10841: return 1 if(($body =~ /\$self\s*->\s*\{_sqlite_cache\}\s*=\s*\{/s) 10842: && ($body =~ /\bdbh\s*=>/)); 10843: 10844: # A routine that queries the documented SQLite cache reaches it through 10845: # the cache path, whose first call builds it and keeps the handle. 10846: return 1 if(($pod =~ /\b(?:SQLite\s+)?cache/i) 10847: && ($body =~ /\$self\s*->\s*(?:_build_sqlite_cache|_sqlite_join|_sqlite_aggregate)\s*\(/)); 10848: 10849: return 0; 10850: } 10851: 10852: # True when the routine's whole body is a croak, with nothing but simple 10853: # assignments before it: such a method exists only to report that the 10854: # operation is unsupported, and every call is expected to die. 10855: sub _always_croaks 10856: { 10857: my ($body) = @_; 10858: 10859: my $code = $body // ''; 10860: $code =~ s/#[^\n]*//g; 10861: $code =~ s/\A\s*sub\s+\w+\s*\{//; 10862: $code =~ s/\}\s*\z//; 10863: 10864: return ($code =~ /\A\s*(?:my\s+[^;]+;\s*)*croak\b[^;]*;\s*\z/s) ? 1 : 0; 10865: } 10866: 10867: # True when the constructor refuses to build the package itself. Two idioms 10868: # are recognised: an explicit abstract-class check (Class::Abstract and 10869: # friends), and a croak over a constructor argument that the schema does not 10870: # describe, which the harness therefore cannot pass. 10871: sub _constructor_refuses_direct_instantiation 10872: { ●10873 → 10883 → 1088710873: my ($body, $ctor_schema) = @_; 10874: 10875: # _find_methods() keeps the body as source text, but accept a PPI node too. 10876: my $content = ref($body) ? eval { $body->content } : $body; 10877: return 0 unless(defined($content) && length($content)); 10878: 10879: return 1 if($content =~ /\bcheck_abstract\s*\(/); 10880: return 1 if(($content =~ /\bcroak\b/) && ($content =~ /\beq\s+__PACKAGE__\b/)); 10881: 10882: my %declared = (ref($ctor_schema->{input}) eq 'HASH') ? %{$ctor_schema->{input}} : (); 10883: while($content =~ /\$args\{\s*(['"]?)([\w:]+)\1\s*\}\s*or\s+croak\b/sg) { 10884: return 1 unless(exists($declared{$2})); 10885: } 10886: 10887: return 0; 10888: } 10889: 10890: sub _ctor_representative_args { ●10891 → 10905 → 1093310891: my ($self, $ctor_schema) = @_; 10892: 10893: my %REP = ( 10894: string => 'test', 10895: integer => 42, 10896: float => 3.14, 10897: boolean => 1, 10898: hashref => {}, 10899: arrayref => [], 10900: any => 'test', 10901: ); 10902: 10903: my $input = $ctor_schema->{input} // {}; 10904: my %args; 10905: for my $param_name (keys %$input) { 10906: my $spec = $input->{$param_name} // {}; 10907: next if $spec->{optional}; 10908: # A constructor that reads a *file* argument is often not buildable 10909: # from an arbitrary one: the file has to be a module, live under the 10910: # class's lib_dir, or be parseable (Mutator, SchemaExtractor). Leave 10911: # it unbuilt, as before, rather than failing every method of the 10912: # class. A directory is a fixture the harness can make without 10913: # knowing what is in it. 10914: if ($param_name =~ /(?:file|filename)/i) { 10915: return undef; 10916: } 10917: if ($param_name =~ /(?:dir|path)/i) { 10918: $args{$param_name} = { '_path' => 'directory' }; 10919: next; 10920: } 10921: # A list of live objects the POD describes: the harness builds a 10922: # stand-in for each element instead of an empty arrayref. 10923: if (ref($spec->{_stub_elements}) eq 'HASH') { 10924: $args{$param_name} = [ { '_stub' => $spec->{_stub_elements} } ]; 10925: next; 10926: } 10927: my $type = $spec->{type} // 'string'; 10928: unless (exists $REP{$type}) { 10929: return undef; 10930: } 10931: $args{$param_name} = $REP{$type}; 10932: } 10933: return \%args; 10934: } 10935: 10936: # an object to be instantiated before 10937: # it can be called, and if so return 10938: # the package name to instantiate. 10939: # 10940: # Entry: $method_name - name of the method. 10941: # $method_body - method source string. 10942: # $method_info - method hashref from 10943: # _find_methods (optional, 10944: # for backward compat). 10945: # 10946: # Exit: Returns the package name string if 10947: # object instantiation is required. 10948: # Returns undef if the method is a 10949: # constructor, factory, singleton, or 10950: # pure class method. 10951: # 10952: # Side effects: Logs analysis decisions to stdout 10953: # when verbose is set. 10954: # 10955: # Notes: Orchestrates five detection sub-steps: 10956: # factory detection, singleton detection, 10957: # instance method detection, inheritance 10958: # check, and constructor requirements. 10959: # Instance method detection overrides 10960: # factory detection when both fire. 10961: # -------------------------------------------------- 10962: sub _needs_object_instantiation { ●10963 → 10989 → 1099310963: my ($self, $method_name, $method_body, $method_info) = @_; 10964: 10965: # Allow method_info to be optional for backward compatibility 10966: $method_info ||= {}; 10967: 10968: my $doc = $self->{_document}; 10969: return undef unless $doc; 10970: 10971: # Get the current package name 10972: my $package_stmt = $doc->find_first('PPI::Statement::Package'); 10973: my $current_package = $package_stmt ? $package_stmt->namespace : 'UNKNOWN'; 10974: $self->{_package_name} //= $current_package; 10975: 10976: # Initialize result structure 10977: my $result = { 10978: package => $current_package, 10979: needs_object => 0, 10980: type => 'unknown', 10981: details => {}, 10982: constructor_params => undef, 10983: }; 10984: 10985: # Track whether we should explicitly skip object instantiation 10986: my $skip_object = 0; 10987: 10988: # Skip constructors and destructors 10989: if ($method_name eq 'new') { 10990: $self->_log(" OBJECT: Constructor '$method_name' detected; skipping instantiation analysis"); 10991: return undef; 10992: } ●10993 → 10993 → 1099810993: if($method_name =~ /^(create|build|construct|init|DESTROY)$/i) { 10994: $skip_object = 1; 10995: } 10996: 10997: # 1. Check for factory methods that return instances ●10998 → 11004 → 1101510998: my $is_factory = $self->_detect_factory_method( 10999: $method_name, $method_body, $current_package, $method_info 11000: ); 11001: 11002: # 2. Check for singleton patterns 11003: my $is_singleton = $self->_detect_singleton_pattern($method_name, $method_body); 11004: if ($is_singleton) { 11005: $result->{needs_object} = 0; # Singleton methods return the singleton instance 11006: $result->{type} = 'singleton_accessor'; 11007: $result->{details} = $is_singleton; 11008: $self->_log(" OBJECT: Detected singleton accessor '$method_name'"); 11009: # Singleton accessors typically don't need object creation in tests 11010: # as they're called on the class, not instance 11011: $skip_object = 1; 11012: } 11013: 11014: # 3. Check if this is an instance method that needs an object ●11015 → 11016 → 1106311015: my $is_instance_method = $self->_detect_instance_method($method_name, $method_body); 11016: if ($is_instance_method && 11017: ($is_instance_method->{explicit_self} || 11018: $is_instance_method->{shift_self} || 11019: $is_instance_method->{accesses_object_data} || 11020: ($is_instance_method->{calls_instance_methods} && 11021: scalar @{$is_instance_method->{calls_instance_methods}}))) { 11022: 11023: # Instance-only methods override factory detection 11024: if ($is_factory) { 11025: $self->_log( 11026: " OBJECT: Instance-only method '$method_name' overrides factory detection" 11027: ); 11028: } 11029: 11030: $result->{needs_object} = 1; 11031: $result->{type} = 'instance_method'; 11032: $result->{details} = $is_instance_method; 11033: 11034: # 4. Check for inheritance - if parent class constructor should be used 11035: my $inheritance_info = $self->_check_inheritance_for_constructor( 11036: $current_package, $method_body 11037: ); 11038: if ($inheritance_info && $inheritance_info->{use_parent_constructor}) { 11039: $result->{package} = $inheritance_info->{parent_class}; 11040: $result->{details}{inheritance} = $inheritance_info; 11041: $self->_log( 11042: " OBJECT: Method '$method_name' uses parent class constructor: $inheritance_info->{parent_class}" 11043: ); 11044: } 11045: 11046: # 5. Check if constructor needs specific parameters 11047: my $constructor_needs = $self->_detect_constructor_requirements( 11048: $current_package, $result->{package} 11049: ); 11050: if ($constructor_needs) { 11051: $result->{constructor_params} = $constructor_needs; 11052: $result->{details}{constructor_requirements} = $constructor_needs; 11053: $self->_log( 11054: " OBJECT: Constructor for $result->{package} requires parameters" 11055: ); 11056: } 11057: 11058: # Return the package name (or parent package) that needs instantiation 11059: return $result->{package}; 11060: } 11061: 11062: # 6. Check for class methods that might need objects from other classes ●11063 → 11064 → 1107811063: my $needs_other_object = $self->_detect_external_object_dependency($method_body); 11064: if ($needs_other_object) { 11065: $result->{needs_object} = 1; 11066: $result->{type} = 'external_dependency'; 11067: $result->{package} = $needs_other_object->{package} 11068: if $needs_other_object->{package}; 11069: $result->{details} = $needs_other_object; 11070: 11071: $self->_log( 11072: " OBJECT: Method '$method_name' depends on external object: $needs_other_object->{package}" 11073: ); 11074: return $result->{package} if $result->{package}; 11075: } 11076: 11077: # Factory method only if NOT instance-based ●11078 → 11078 → 1108711078: if ($is_factory && !$skip_object) { 11079: $result->{needs_object} = 0; 11080: $result->{type} = 'factory'; 11081: $result->{details} = $is_factory; 11082: $self->_log( 11083: " OBJECT: Detected factory method '$method_name' returns $is_factory->{returns_class} objects" 11084: ) if $is_factory->{returns_class}; 11085: } 11086: 11087: return undef; 11088: } 11089: 11090: # -------------------------------------------------- 11091: # _detect_factory_method 11092: # 11093: # Purpose: Detect whether a method is a factory 11094: # that creates and returns object 11095: # instances rather than operating on 11096: # an existing instance. 11097: # 11098: # Entry: $method_name - method name string. 11099: # $method_body - method source string. 11100: # $current_package - current package name. 11101: # $method_info - method hashref 11102: # (optional). 11103: # 11104: # Exit: Returns a factory_info hashref on 11105: # detection, or undef if the method 11106: # is not a factory. 11107: # The hashref includes: returns_class, 11108: # confidence, and one of: 11109: # returns_blessed, returns_new, 11110: # returns_factory_result, pod_hint. 11111: # 11112: # Side effects: None. 11113: # -------------------------------------------------- 11114: sub _detect_factory_method { ●11115 → 11120 → 1112511115: my ($self, $method_name, $method_body, $current_package, $method_info) = @_; 11116: 11117: my %factory_info; 11118: 11119: # Check method name patterns 11120: if ($method_name =~ /^(create_|make_|build_|get_)/i) { 11121: $factory_info{name_pattern} = 1; 11122: } 11123: 11124: # Look for object creation patterns in the method body ●11125 → 11125 → 1117611125: if ($method_body) { 11126: # Pattern 1: Returns a blessed reference 11127: if ($method_body =~ /return\s+bless\s*\{[^}]*\},\s*['"]?(\w+(?:::\w+)*|\$\w+)['"]?/s || 11128: $method_body =~ /bless\s*\{[^}]*\},\s*['"]?(\w+(?:::\w+)*|\$\w+)['"]?.*return/s) { 11129: my $class_name = $1; 11130: 11131: # Handle variable class names 11132: if ($class_name =~ /^\$(class|self|package)$/) { 11133: $factory_info{returns_class} = $current_package; 11134: } elsif ($class_name =~ /^\$/) { 11135: $factory_info{returns_class} = 'VARIABLE'; # Unknown variable 11136: } else { 11137: $factory_info{returns_class} = $class_name; 11138: } 11139: 11140: $factory_info{returns_blessed} = 1; 11141: $factory_info{confidence} = 'high'; 11142: return \%factory_info; 11143: } 11144: 11145: # Pattern 2: Returns ->new() call on class or $self 11146: if ($method_body =~ /return\s+([\$\w:]+)->new\(/s || 11147: $method_body =~ /([\$\w:]+)->new\(.*return/s) { 11148: my $target = $1; 11149: 11150: # Determine what class is being instantiated 11151: if ($target eq '$self' || $target eq 'shift' || $target =~ /^\$/) { 11152: $factory_info{returns_class} = $current_package; 11153: $factory_info{self_new} = 1; 11154: } elsif ($target =~ /::/) { 11155: $factory_info{returns_class} = $target; 11156: $factory_info{external_class} = 1; 11157: } else { 11158: $factory_info{returns_class} = $target; 11159: } 11160: 11161: $factory_info{returns_new} = 1; 11162: $factory_info{confidence} = 'medium'; 11163: return \%factory_info; 11164: } 11165: 11166: # Pattern 3: Returns an object from another factory method 11167: if ($method_body =~ /return\s+([\$\w:]+)->(create_|make_|build_|get_)/i || 11168: $method_body =~ /([\$\w:]+)->(create_|make_|build_|get_).*return/si) { 11169: $factory_info{returns_factory_result} = 1; 11170: $factory_info{confidence} = 'low'; 11171: return \%factory_info; 11172: } 11173: } 11174: 11175: # Check for return type hints in POD if available ●11176 → 11176 → 1118511176: if ($method_info && ref($method_info) eq 'HASH' && $method_info->{pod}) { 11177: my $pod = $method_info->{pod}; 11178: if ($pod =~ /returns?\s+(?:an?\s+)?(object|instance|new\s+\w+)/i) { 11179: $factory_info{pod_hint} = 1; 11180: $factory_info{confidence} = 'low'; 11181: return \%factory_info; 11182: } 11183: } 11184: 11185: return undef; 11186: } 11187: 11188: # -------------------------------------------------- 11189: # _detect_singleton_pattern 11190: # 11191: # Purpose: Detect singleton accessor methods 11192: # that return a shared instance rather 11193: # than creating a new object, by 11194: # checking the method name and body 11195: # for singleton patterns. 11196: # 11197: # Entry: $method_name - method name string. 11198: # $method_body - method source string. 11199: # 11200: # Exit: Returns a singleton_info hashref on 11201: # detection (always contains at least 11202: # name_pattern => 1), or undef if the 11203: # method name does not match the 11204: # singleton accessor pattern. 11205: # 11206: # Side effects: None. 11207: # 11208: # Notes: Only fires for methods named 11209: # instance, get_instance, singleton, 11210: # or shared_instance. Methods not 11211: # matching these names always return 11212: # undef regardless of body content. 11213: # -------------------------------------------------- 11214: sub _detect_singleton_pattern { ●11215 → 11225 → 1125411215: my ($self, $method_name, $method_body) = @_; 11216: 11217: # Check method name patterns 11218: return undef unless $method_name =~ /^(instance|get_instance|singleton|shared_instance)$/i; 11219: 11220: my %singleton_info = ( 11221: name_pattern => 1, 11222: ); 11223: 11224: # Look for singleton patterns in code 11225: if ($method_body) { 11226: # Pattern 1: Static/state variable holding instance 11227: if ($method_body =~ /(?:my\s+)?(?:our\s+)?\$(?:instance|_instance|singleton)\b/s || 11228: $method_body =~ /state\s+\$(?:instance|_instance|singleton)\b/s) { 11229: $singleton_info{static_variable} = 1; 11230: $singleton_info{confidence} = 'high'; 11231: } 11232: 11233: # Pattern 2: Returns $instance if defined (with better regex) 11234: if ($method_body =~ /return\s+\$instance\s+if\s+(?:defined\s+)?\$instance/ || 11235: $method_body =~ /unless\s+\$instance.*?=\s*.*?new/) { 11236: $singleton_info{returns_instance} = 1; 11237: $singleton_info{confidence} = 'high'; 11238: } 11239: 11240: # Pattern 3: ||= new() pattern (with better regex) 11241: if ($method_body =~ /\$instance\s*\|\|=\s*.*?new/ || 11242: $method_body =~ /\$instance\s*=\s*.*?new\s+unless\s+(?:defined\s+)?\$instance/) { 11243: $singleton_info{lazy_initialization} = 1; 11244: $singleton_info{confidence} = 'medium'; 11245: } 11246: 11247: # Pattern 4: Direct return of $instance variable 11248: if ($method_body =~ /return\s+\$instance;/) { 11249: $singleton_info{returns_instance} = 1; 11250: $singleton_info{confidence} = 'high' unless $singleton_info{confidence}; 11251: } 11252: } 11253: 11254: return \%singleton_info if keys %singleton_info > 0; # Need at least name pattern 11255: 11256: return undef; 11257: } 11258: 11259: # -------------------------------------------------- 11260: # _detect_instance_method 11261: # 11262: # Purpose: Detect whether a method is an 11263: # instance method that requires a 11264: # blessed object ($self) to be called, 11265: # through multiple detection patterns 11266: # of varying confidence. 11267: # 11268: # Entry: $method_name - method name string. 11269: # $method_body - method source string. 11270: # 11271: # Exit: Returns an instance_info hashref if 11272: # any instance method signal is found. 11273: # Returns undef if no signals are 11274: # detected. 11275: # The hashref may contain: explicit_self, 11276: # shift_self, uses_self, 11277: # accesses_object_data, 11278: # calls_instance_methods, 11279: # private_method, and confidence. 11280: # 11281: # Side effects: None. 11282: # -------------------------------------------------- 11283: sub _detect_instance_method { ●11284 → 11289 → 1131411284: my ($self, $method_name, $method_body) = @_; 11285: 11286: my %instance_info; 11287: 11288: # Pattern 1: my ($self, ...) = @_; 11289: if ($method_body =~ /my\s*\(\s*\$self\s*[,)]/) { 11290: $instance_info{explicit_self} = 1; 11291: $instance_info{confidence} = 'high'; 11292: } 11293: 11294: # Pattern 1b: my $self = $_[0]; (direct-index style) 11295: elsif ($method_body =~ /my\s+\$self\s*=\s*\$_\[0\]/) { 11296: $instance_info{explicit_self} = 1; 11297: $instance_info{confidence} = 'high'; 11298: } 11299: 11300: # Pattern 2: my $self = shift; 11301: elsif ($method_body =~ /my\s+\$self\s*=\s*shift/) { 11302: $instance_info{shift_self} = 1; 11303: $instance_info{confidence} = 'high'; 11304: } 11305: 11306: # Pattern 3: Uses $self->something (including hash/array access) 11307: # This catches $self->{value} and $self->[0] as well as $self->method() 11308: elsif ($method_body =~ /\$self\s*->\s*(\w+|[\{\[])/) { 11309: $instance_info{uses_self} = 1; 11310: $instance_info{confidence} = 'medium'; 11311: } 11312: 11313: # Pattern 4: Accesses object data: $self->{...}, $self->[...] ●11314 → 11314 → 1132011314: if ($method_body =~ /\$self\s*->\s*[\{\[]/) { 11315: $instance_info{accesses_object_data} = 1; 11316: $instance_info{confidence} = 'high' unless $instance_info{confidence} eq 'high'; 11317: } 11318: 11319: # Pattern 5: Calls other instance methods on $self ●11320 → 11320 → 1132911320: if ($method_body =~ /\$self\s*->\s*(\w+)\s*\(/s) { 11321: $instance_info{calls_instance_methods} = []; 11322: while ($method_body =~ /\$self\s*->\s*(\w+)\s*\(/g) { 11323: push @{$instance_info{calls_instance_methods}}, $1; 11324: } 11325: $instance_info{confidence} = 'high' if @{$instance_info{calls_instance_methods}}; 11326: } 11327: 11328: # Pattern 6: Method name suggests instance method (not perfect but helpful) ●11329 → 11329 → 1133511329: if ($method_name =~ /^_/ && $method_name !~ /^_new/) { 11330: # Private methods are usually instance methods 11331: $instance_info{private_method} = 1; 11332: $instance_info{confidence} = 'low' unless exists $instance_info{confidence}; 11333: } 11334: 11335: return \%instance_info if keys %instance_info; 11336: return undef; 11337: } 11338: 11339: # -------------------------------------------------- 11340: # _check_inheritance_for_constructor 11341: # 11342: # Purpose: Determine whether the current package 11343: # uses an inherited constructor from a 11344: # parent class, by examining use parent, 11345: # use base, and @ISA declarations. 11346: # 11347: # Entry: $current_package - current package 11348: # name string. 11349: # $method_body - method source string 11350: # (checked for SUPER:: 11351: # calls). 11352: # 11353: # Exit: Returns an inheritance_info hashref 11354: # if any inheritance information is 11355: # found, or undef otherwise. 11356: # The hashref may contain: 11357: # parent_statements, isa_array, 11358: # uses_super, calls_super_new, 11359: # has_own_constructor, 11360: # use_parent_constructor, parent_class. 11361: # 11362: # Side effects: None. 11363: # -------------------------------------------------- 11364: sub _check_inheritance_for_constructor { ●11365 → 11377 → 1139311365: my ($self, $current_package, $method_body) = @_; 11366: 11367: my $doc = $self->{_document}; 11368: return undef unless $doc; 11369: 11370: my %inheritance_info; 11371: 11372: # 1. Look for parent/base statements 11373: my @parent_classes; 11374: 11375: # Find all 'use parent' or 'use base' statements 11376: my $includes = $doc->find('PPI::Statement::Include') || []; 11377: foreach my $inc (@$includes) { 11378: my $content = $inc->content; 11379: if ($content =~ /use\s+(parent|base)\s+['"]?([\w:]+)['"]?/) { 11380: push @parent_classes, $2; 11381: $inheritance_info{parent_statements} = \@parent_classes; 11382: } 11383: # Also check for multiple parents: use parent qw(Class1 Class2) 11384: if ($content =~ /use\s+(parent|base)\s+qw?[\(\[]?(.+?)[\)\]]?;/) { 11385: my $parents = $2; 11386: my @multi_parents = split /\s+/, $parents; 11387: push @parent_classes, @multi_parents; 11388: $inheritance_info{parent_statements} = \@parent_classes; 11389: } 11390: } 11391: 11392: # 2. Look for @ISA assignments (with or without 'our') ●11393 → 11394 → 1140611393: my $isas = $doc->find('PPI::Statement::Variable') || []; 11394: foreach my $isa (@$isas) { 11395: my $content = $isa->content(); 11396: # Match both "our @ISA = qw(...)" and "@ISA = qw(...)" 11397: if ($content =~ /(?:our\s+)?\@ISA\s*=\s*qw?[\(\[]?(.+?)[\)\]]?/) { 11398: my $parents = $1; 11399: my @isa_parents = split(/\s+/, $parents); 11400: push @parent_classes, @isa_parents; 11401: $inheritance_info{isa_array} = \@isa_parents; 11402: } 11403: } 11404: 11405: # Also look for @ISA in regular statements ●11406 → 11407 → 1141811406: my $statements = $doc->find('PPI::Statement') || []; 11407: foreach my $stmt (@$statements) { 11408: my $content = $stmt->content; 11409: if ($content =~ /\@ISA\s*=\s*qw?[\(\[]?(.+?)[\)\]]?/) { 11410: my $parents = $1; 11411: my @isa_parents = split(/\s+/, $parents); 11412: push @parent_classes, @isa_parents; 11413: $inheritance_info{isa_array} = \@isa_parents; 11414: } 11415: } 11416: 11417: # 3. Check if method uses SUPER:: calls ●11418 → 11418 → 1142611418: if ($method_body && $method_body =~ /SUPER::/) { 11419: $inheritance_info{uses_super} = 1; 11420: if ($method_body =~ /SUPER::new/) { 11421: $inheritance_info{calls_super_new} = 1; 11422: } 11423: } 11424: 11425: # 4. Check if current package has its own new method ●11426 → 11431 → 1143911426: my $has_own_new = $doc->find(sub { 11427: $_[1]->isa('PPI::Statement::Sub') && 11428: $_[1]->name eq 'new' 11429: }); 11430: 11431: if ($has_own_new) { 11432: $inheritance_info{has_own_constructor} = 1; 11433: } elsif (@parent_classes) { 11434: # No own constructor, but has parents - might need parent constructor 11435: $inheritance_info{use_parent_constructor} = 1; 11436: $inheritance_info{parent_class} = $parent_classes[0]; # Use first parent 11437: } 11438: 11439: return \%inheritance_info if keys %inheritance_info; 11440: return undef; 11441: } 11442: 11443: # -------------------------------------------------- 11444: # _detect_constructor_requirements 11445: # 11446: # Purpose: Analyse the new() method of the 11447: # current or target package to determine 11448: # what parameters the constructor 11449: # requires, including required and 11450: # optional parameters and their defaults. 11451: # 11452: # Entry: $current_package - the package being 11453: # analysed. 11454: # $target_package - the package whose 11455: # constructor will 11456: # be called (may 11457: # differ from current 11458: # for inherited 11459: # constructors). 11460: # 11461: # Exit: Returns a requirements hashref on 11462: # success, or undef if no new() method 11463: # is found. For external classes, 11464: # returns a minimal hashref with 11465: # external_class => 1. 11466: # 11467: # Side effects: None. 11468: # -------------------------------------------------- 11469: sub _detect_constructor_requirements { ●11470 → 11477 → 1148611470: my ($self, $current_package, $target_package) = @_; 11471: 11472: my $doc = $self->{_document}; 11473: return undef unless $doc; 11474: 11475: # If target is different from current, we can't analyze it 11476: # (external class, parent class in different file) 11477: if ($target_package ne $current_package) { 11478: return { 11479: external_class => 1, 11480: package => $target_package, 11481: note => "Constructor for external class $target_package - parameters unknown" 11482: }; 11483: } 11484: 11485: # Find the new method in current package ●11486 → 11499 → 1151011486: my $new_method = $doc->find_first(sub { 11487: $_[1]->isa('PPI::Statement::Sub') && 11488: $_[1]->name eq 'new' 11489: }); 11490: 11491: return undef unless $new_method; 11492: 11493: my %requirements; 11494: 11495: # Get method body 11496: my $body = $new_method->content; 11497: 11498: # Look for parameter extraction patterns - handle both $self and $class 11499: if ($body =~ /my\s*\(\s*\$(self|class)\s*,\s*(.+?)\)\s*=\s*\@_/s) { 11500: my $params = $2; 11501: my @param_names = $params =~ /\$(\w+)/g; 11502: 11503: if (@param_names) { 11504: $requirements{parameters} = \@param_names; 11505: $requirements{parameter_count} = scalar @param_names; 11506: } 11507: } 11508: 11509: # Look for shift patterns ●11510 → 11511 → 1151511510: my @shift_params; 11511: while ($body =~ /my\s+\$(\w+)\s*=\s*shift/g) { 11512: push @shift_params, $1; 11513: } 11514: # Remove $self or $class if present ●11515 → 11517 → 1152411515: @shift_params = grep { $_ !~ /^(self|class|pkg|proto|klass)$/i } @shift_params; 11516: 11517: if (@shift_params) { 11518: $requirements{parameters} = \@shift_params; 11519: $requirements{parameter_count} = scalar @shift_params; 11520: $requirements{shift_pattern} = 1; 11521: } 11522: 11523: # Look for validation of parameters (more flexible pattern) ●11524 → 11525 → 1152811524: my @required_params; 11525: if ($body =~ /croak.*unless.*(?:defined\s+)?\$(\w+)/g) { 11526: push @required_params, $1; 11527: } ●11528 → 11528 → 1153211528: if ($body =~ /die.*unless.*(?:defined\s+)?\$(\w+)/g) { 11529: push @required_params, $1; 11530: } 11531: ●11532 → 11532 → 1153711532: if (@required_params) { 11533: $requirements{required_parameters} = \@required_params; 11534: } 11535: 11536: # Look for default values (optional parameters) ●11537 → 11542 → 1155211537: my @optional_params; 11538: my %default_values; 11539: 11540: # Use the new _extract_default_value method 11541: # Check for each parameter in the constructor body 11542: if ($requirements{parameters}) { 11543: foreach my $param (@{$requirements{parameters}}) { 11544: my $default = $self->_extract_default_value($param, $body); 11545: if (defined $default) { 11546: push @optional_params, $param; 11547: $default_values{$param} = $default; 11548: } 11549: } 11550: } 11551: ●11552 → 11552 → 1155711552: if (@optional_params) { 11553: $requirements{optional_parameters} = \@optional_params; 11554: $requirements{default_values} = \%default_values; 11555: } 11556: 11557: return \%requirements if keys %requirements; 11558: return undef; 11559: } 11560: 11561: 11562: # -------------------------------------------------- 11563: # _detect_external_object_dependency 11564: # 11565: # Purpose: Detect whether a method creates or 11566: # depends on objects from classes other 11567: # than the current package, by scanning 11568: # for ->new() calls on named classes 11569: # and method calls on typed variables. 11570: # 11571: # Entry: $method_body - method source string. 11572: # May be undef. 11573: # 11574: # Exit: Returns a dependency_info hashref if 11575: # external object usage is found, or 11576: # undef otherwise. 11577: # The hashref may contain: 11578: # creates_objects (arrayref of class 11579: # names), uses_objects (arrayref of 11580: # class names), and package (the primary 11581: # dependency class). 11582: # 11583: # Side effects: None. 11584: # -------------------------------------------------- 11585: sub _detect_external_object_dependency { ●11586 → 11595 → 1160111586: my ($self, $method_body) = @_; 11587: 11588: return undef unless $method_body; 11589: 11590: my %dependency_info; 11591: 11592: # Pattern 1: Creates objects of other classes with ->new() or ->create() 11593: # Reset pos for global match 11594: pos($method_body) = 0; 11595: while ($method_body =~ /(\w+(?:::\w+)*)->(?:new|create)\(/g) { 11596: my $class = $1; 11597: next if $class eq 'main' || $class eq '__PACKAGE__' || $class =~ /^\$/; 11598: push @{$dependency_info{creates_objects}}, $class; 11599: } 11600: ●11601 → 11601 → 1160911601: if ($dependency_info{creates_objects}) { 11602: # Remove duplicates 11603: my %seen; 11604: $dependency_info{creates_objects} = [grep { !$seen{$_}++ } @{$dependency_info{creates_objects}}]; 11605: $dependency_info{package} = $dependency_info{creates_objects}[0]; 11606: } 11607: 11608: # Pattern 2: Calls methods on objects from other classes ●11609 → 11609 → 1163911609: if ($method_body =~ /\$(\w+)->\w+\(/) { 11610: my %object_vars; 11611: # Reset pos for global match â the if check above used a 11612: # non-/g match so it cannot have advanced pos, but the while 11613: # loop's own /g matches still need to start from the beginning. 11614: pos($method_body) = 0; 11615: while ($method_body =~ /\$(\w+)->\w+\(/g) { 11616: $object_vars{$1}++; 11617: } 11618: 11619: # Try to determine type of object variables 11620: my @object_classes; 11621: foreach my $var (keys %object_vars) { 11622: # Look for type declarations or assignments 11623: if ($method_body =~ /my\s+\$$var\s*=\s*(\w+(?:::\w+)+)->(?:new|create)/) { 11624: push @object_classes, $1; 11625: } elsif ($method_body =~ /my\s+\$$var\s*=\s*(\w+(?:::\w+)+)->/) { 11626: push @object_classes, $1; 11627: } 11628: } 11629: 11630: if (@object_classes) { 11631: $dependency_info{uses_objects} = \@object_classes; 11632: $dependency_info{package} = $object_classes[0] unless $dependency_info{package}; 11633: } 11634: } 11635: 11636: # Pattern 3: Receives objects as parameters (type hints in comments/POD) 11637: # This would need integration with parameter analysis 11638: 11639: return \%dependency_info if keys %dependency_info; 11640: return undef; 11641: } 11642: 11643: # -------------------------------------------------- 11644: # _get_parent_class 11645: # 11646: # Purpose: Find the first parent class of the 11647: # current package by searching the 11648: # PPI document for use parent, use base, 11649: # or our @ISA declarations. 11650: # 11651: # Entry: None (operates on $self->{_document}). 11652: # 11653: # Exit: Returns the parent class name string, 11654: # or undef if no parent is found. 11655: # 11656: # Side effects: None. 11657: # -------------------------------------------------- 11658: sub _get_parent_class { ●11659 → 11671 → 1167711659: my $self = $_[0]; 11660: 11661: my $doc = $self->{_document}; 11662: return unless $doc; 11663: 11664: # Look for use parent statements 11665: my $parent_stmt = $doc->find_first(sub { 11666: $_[1]->isa('PPI::Statement::Include') && 11667: $_[1]->type eq 'use' && 11668: $_[1]->module =~ /^(parent|base)$/ && 11669: $_[1]->arguments =~ /['"](\w+(?:::\w+)*)['"]/ 11670: }); 11671: if ($parent_stmt) { 11672: my $parent = $1; 11673: return $parent; 11674: } 11675: 11676: # Look for @ISA assignment ●11677 → 11681 → 1168511677: my $isa_stmt = $doc->find_first(sub { 11678: $_[1]->isa('PPI::Statement') && 11679: $_[1]->content =~ /our\s+\@ISA\s*=\s*\(\s*['"](\w+(?:::\w+)*)['"]\s*\)/ 11680: }); 11681: if ($isa_stmt && $isa_stmt->content =~ /['"](\w+(?:::\w+)*)['"]/) { 11682: return $1; 11683: } 11684: 11685: return; 11686: } 11687: 11688: # -------------------------------------------------- 11689: # _get_class_for_instance_method 11690: # 11691: # Purpose: Determine which class should be used 11692: # for object instantiation when testing 11693: # an instance method, preferring the 11694: # current package if it has a new() 11695: # method, falling back to the parent 11696: # class otherwise. 11697: # 11698: # Entry: None (operates on $self->{_document}). 11699: # 11700: # Exit: Returns the package name string to 11701: # use for instantiation. Returns 11702: # 'UNKNOWN_PACKAGE' if no package 11703: # statement is found. 11704: # 11705: # Side effects: Stores the package name in 11706: # $self->{_package_name} if not 11707: # already set. 11708: # -------------------------------------------------- 11709: sub _get_class_for_instance_method { ●11710 → 11724 → 1172911710: my $self = $_[0]; 11711: 11712: # Get the current package 11713: my $doc = $self->{_document}; 11714: my $package_stmt = $doc->find_first('PPI::Statement::Package'); 11715: return 'UNKNOWN_PACKAGE' unless $package_stmt; 11716: my $package_name = $package_stmt->namespace; 11717: $self->{_package_name} //= $package_name; 11718: 11719: # Check if the current package has a 'new' method 11720: my $has_new = $doc->find(sub { 11721: $_[1]->isa('PPI::Statement::Sub') && $_[1]->name eq 'new' 11722: }); 11723: 11724: if ($has_new) { 11725: return $package_name; 11726: } 11727: 11728: # Otherwise, try to get the parent class 11729: my $parent = $self->_get_parent_class(); 11730: return $parent if $parent; 11731: 11732: # Fallback to current package 11733: return $package_name; 11734: } 11735: 11736: # -------------------------------------------------- 11737: # _extract_default_value 11738: # 11739: # Purpose: Extract a default value for a named 11740: # parameter from a method body by 11741: # matching multiple common Perl default 11742: # assignment idioms. 11743: # 11744: # Entry: $param - parameter name string. 11745: # $code - method body source string. 11746: # 11747: # Exit: Returns the cleaned default value 11748: # scalar on success, or undef if no 11749: # default assignment pattern is found. 11750: # 11751: # Side effects: None. 11752: # 11753: # Notes: Eight patterns are tried in order: 11754: # ||, //=, defined ternary, unless 11755: # defined, ||=, //, multi-line if 11756: # !defined, unless defined block. 11757: # Comment lines are stripped from the 11758: # code before matching to avoid false 11759: # positives. Delegates to 11760: # _clean_default_value for value 11761: # normalisation. 11762: # -------------------------------------------------- 11763: sub _extract_default_value { ●11764 → 11776 → 1178411764: my ($self, $param, $code) = @_; 11765: 11766: return undef unless $param && $code; 11767: 11768: # Clean up the code for easier pattern matching 11769: # Remove comments to avoid false positives 11770: my $clean_code = $code; 11771: $clean_code =~ s/#.*$//gm; 11772: $clean_code =~ s/^\s+|\s+$//g; 11773: 11774: # Pattern 1: $param = $param || 'default_value' 11775: # Also handles: $param = $arg || 'default' 11776: if ($clean_code =~ /\$$param\s*=\s*(?:\$$param|\$[a-zA-Z_]\w*)\s*\|\|\s*([^;]+)/) { 11777: my $default = $1; 11778: $default =~ s/\s*;\s*$//; 11779: $default = $self->_clean_default_value($default); 11780: return $default if defined $default; 11781: } 11782: 11783: # Pattern 2: $param //= 'default_value' ●11784 → 11784 → 1179311784: if ($clean_code =~ /\$$param\s*\/\/=\s*([^;]+)/) { 11785: my $default = $1; 11786: $default =~ s/\s*;\s*$//; 11787: $default = $self->_clean_default_value($default); 11788: return $default if defined $default; 11789: } 11790: 11791: # Pattern 3: $param = defined $param ? $param : 'default' 11792: # Also handles: $param = defined $arg ? $arg : 'default' ●11793 → 11793 → 1180111793: if ($clean_code =~ /\$$param\s*=\s*defined\s+(?:\$$param|\$[a-zA-Z_]\w*)\s*\?\s*(?:\$$param|\$[a-zA-Z_]\w*)\s*:\s*([^;]+)/) { 11794: my $default = $1; 11795: $default =~ s/\s*;\s*$//; 11796: $default = $self->_clean_default_value($default); 11797: return $default if defined $default; 11798: } 11799: 11800: # Pattern 4: $param = 'default' unless defined $param; ●11801 → 11801 → 1180811801: if ($clean_code =~ /\$$param\s*=\s*([^;]+?)\s+unless\s+defined\s+(?:\$$param|\$[a-zA-Z_]\w*)/) { 11802: my $default = $1; 11803: $default = $self->_clean_default_value($default); 11804: return $default if defined $default; 11805: } 11806: 11807: # Pattern 5: $param ||= 'default' ●11808 → 11808 → 1181611808: if ($clean_code =~ /\$$param\s*\|\|=\s*([^;]+)/) { 11809: my $default = $1; 11810: $default =~ s/\s*;\s*$//; 11811: $default = $self->_clean_default_value($default); 11812: return $default if defined $default; 11813: } 11814: 11815: # Pattern 6: $param = $arg // 'default' ●11816 → 11816 → 1182411816: if ($clean_code =~ /\$$param\s*=\s*(?:\$$param|\$[a-zA-Z_]\w*)\s*\/\/\s*([^;]+)/) { 11817: my $default = $1; 11818: $default =~ s/\s*;\s*$//; 11819: $default = $self->_clean_default_value($default); 11820: return $default if defined $default; 11821: } 11822: 11823: # Pattern 7: Multi-line: if (!defined $param) { $param = 'default'; } ●11824 → 11824 → 1183211824: if ($clean_code =~ /if\s*\(\s*!defined\s+\$$param\s*\)\s*\{[^}]*\$$param\s*=\s*([^;]+)/s) { 11825: my $default = $1; 11826: $default =~ s/\s*;\s*$//; 11827: $default = $self->_clean_default_value($default); 11828: return $default if defined $default; 11829: } 11830: 11831: # Pattern 8: unless (defined $param) { $param = 'default'; } ●11832 → 11832 → 1183911832: if ($clean_code =~ /unless\s*\(\s*defined\s+\$$param\s*\)\s*\{[^}]*\$$param\s*=\s*([^;]+)/s) { 11833: my $default = $1; 11834: $default =~ s/\s*;\s*$//; 11835: $default = $self->_clean_default_value($default); 11836: return $default if defined $default; 11837: } 11838: 11839: return undef; 11840: } 11841: 11842: # -------------------------------------------------- 11843: # _extract_test_hints 11844: # 11845: # Purpose: Extract structured test hints from 11846: # a method's code and schema, including 11847: # boundary values, invalid inputs, and 11848: # valid input examples from POD. 11849: # 11850: # Entry: $method - method hashref. 11851: # $schema - schema hashref as built so 11852: # far by _analyze_method. 11853: # 11854: # Exit: Returns a hints hashref with keys: 11855: # boundary_values, invalid_inputs, 11856: # equivalence_classes, valid_inputs. 11857: # Keys with empty arrays are deleted 11858: # before returning. 11859: # 11860: # Side effects: None. 11861: # -------------------------------------------------- 11862: sub _extract_test_hints { ●11863 → 11879 → 1188311863: my ($self, $method, $schema) = @_; 11864: 11865: my %hints = ( 11866: boundary_values => [], 11867: invalid_inputs => [], 11868: equivalence_classes => [], 11869: valid_inputs => [], 11870: ); 11871: 11872: my $code = $method->{body}; 11873: return {} unless $code; 11874: 11875: $self->_extract_invalid_input_hints($code, \%hints); 11876: $self->_extract_boundary_value_hints($code, \%hints); 11877: 11878: # prune empties 11879: for my $k (keys %hints) { 11880: delete $hints{$k} unless @{$hints{$k}}; 11881: } 11882: 11883: return \%hints; 11884: } 11885: 11886: # -------------------------------------------------- 11887: # _extract_invalid_input_hints 11888: # 11889: # Purpose: Detect likely invalid input values 11890: # from a method body by looking for 11891: # defined checks, empty string checks, 11892: # and negative number checks. 11893: # 11894: # Entry: $code - method body source string. 11895: # $hints - hints hashref (modified in 11896: # place via invalid_inputs key). 11897: # 11898: # Exit: Returns nothing. Appends to 11899: # $hints->{invalid_inputs}. 11900: # 11901: # Side effects: None. 11902: # -------------------------------------------------- 11903: sub _extract_invalid_input_hints { ●11904 → 11907 → 1191211904: my ($self, $code, $hints) = @_; 11905: 11906: # undef invalid 11907: if ($code =~ /defined\s*\(\s*\$/) { 11908: push @{ $hints->{invalid_inputs} }, 'undef'; 11909: } 11910: 11911: # empty string invalid ●11912 → 11912 → 1191711912: if ($code =~ /\beq\s*''/ || $code =~ /\blength\s*\(/) { 11913: push @{ $hints->{invalid_inputs} }, ''; 11914: } 11915: 11916: # negative number invalid ●11917 → 11917 → 011917: if ($code =~ /\$\w+\s*<\s*0/) { 11918: push @{ $hints->{invalid_inputs} }, -1; 11919: } 11920: } 11921: 11922: # -------------------------------------------------- 11923: # _extract_boundary_value_hints 11924: # 11925: # Purpose: Extract numeric boundary values from 11926: # comparison operators in a method body, 11927: # adding both the boundary value and 11928: # the value one step either side. 11929: # 11930: # Entry: $code - method body source string. 11931: # $hints - hints hashref (modified in 11932: # place via boundary_values key). 11933: # 11934: # Exit: Returns nothing. Appends to and 11935: # deduplicates $hints->{boundary_values}. 11936: # 11937: # Side effects: None. 11938: # -------------------------------------------------- 11939: sub _extract_boundary_value_hints { ●11940 → 11942 → 1195711940: my ($self, $code, $hints) = @_; 11941: 11942: while ($code =~ /\$\w+\s*(<=|<|>=|>)\s*(\d+)/g) { 11943: my ($op, $n) = ($1, $2); 11944: 11945: if ($op eq '<') { 11946: push @{ $hints->{boundary_values} }, $n, $n+1; 11947: } elsif ($op eq '<=') { 11948: push @{ $hints->{boundary_values} }, $n, $n+1; 11949: } elsif ($op eq '>') { 11950: push @{ $hints->{boundary_values} }, $n, $n-1; 11951: } elsif ($op eq '>=') { 11952: push @{ $hints->{boundary_values} }, $n, $n-1; 11953: } 11954: } 11955: 11956: # Remove duplicates 11957: my %seen; 11958: $hints->{boundary_values} = [ grep { !$seen{$_}++ } @{ $hints->{boundary_values} } ]; 11959: } 11960: 11961: # -------------------------------------------------- 11962: # _extract_pod_examples 11963: # 11964: # Purpose: Extract example method call patterns from a method's 11965: # SYNOPSIS section (=head1 or =head2) and from any 11966: # =for example begin/end blocks, and add them as 11967: # valid_inputs hints for fuzzing. 11968: # 11969: # Entry: $pod - POD string for the method. May be undef. 11970: # $hints - hints hashref (modified in place via the 11971: # valid_inputs key). 11972: # 11973: # Exit: Returns $hints. Appends to $hints->{valid_inputs}. 11974: # 11975: # Side effects: Logs the number of examples found to stdout when 11976: # verbose is set. 11977: # 11978: # Notes: For standalone runnable round-trip tests (not just 11979: # fuzzing hints) use App::Test::Generator::PodExampleExtractor 11980: # and bin/pod-example-tester instead. 11981: # -------------------------------------------------- 11982: sub _extract_pod_examples { ●11983 → 11991 → 1199611983: my ($self, $pod, $hints) = @_; 11984: 11985: return $hints unless $pod; 11986: 11987: my @examples; 11988: 11989: # Accept both =head1 SYNOPSIS (module-level) and =head2 SYNOPSIS (method-level) 11990: my $synopsis = ''; 11991: if($pod =~ /=head[12]\s+SYNOPSIS\s*(.+?)(?=\n=head|\z)/s) { 11992: $synopsis = $1; 11993: } 11994: 11995: # Also collect =for example begin ... =for example end blocks ●11996 → 11997 → 1200011996: my @for_blocks; 11997: while($pod =~ /=for\s+example\s+begin(.+?)=for\s+example\s+end/sg) { 11998: push @for_blocks, $1; 11999: } ●12000 → 12005 → 1202312000: $synopsis .= join('', @for_blocks); 12001: 12002: return $hints unless length($synopsis); 12003: 12004: # Constructor examples: ->wilma(foo => 'bar', count => 5) 12005: while ($synopsis =~ /->([a-z_0-9A-Z]+)\s*\(\s*(.*?)\s*\)/sg) { 12006: my ($method, $args) = ($1, $2); 12007: my %kv; 12008: 12009: while ($args =~ /(\w+)\s*=>\s*(?:'([^']*)'|"([^"]*)"|(\d+))/g) { 12010: my $key = $1; 12011: my $val = defined $2 ? $2 : defined $3 ? $3 : $4; 12012: $kv{$key} = $val; 12013: } 12014: 12015: push @examples, { 12016: style => 'named', 12017: source => 'pod', 12018: args => \%kv, 12019: function => $method, # TODO: add a sanity check this is what we expect 12020: } if %kv; 12021: } 12022: ●12023 → 12023 → 1204312023: unless(scalar(@examples)) { 12024: # Positional calls: func($a, $b) 12025: while ($synopsis =~ /\b(\w+)\s*\(\s*(.*?)\s*\)/sg) { 12026: my ($func, $argstr) = ($1, $2); 12027: 12028: # next if $func eq 'new'; # already handled 12029: 12030: my @args = map { s/^\s+|\s+$//gr } split /\s*,\s*/, $argstr; 12031: 12032: next unless @args; 12033: 12034: push @examples, { 12035: style => 'positional', 12036: source => 'pod', 12037: function => $func, 12038: args => \@args, 12039: }; 12040: } 12041: } 12042: ●12043 → 12043 → 1205012043: if (scalar(@examples)) { 12044: $hints->{valid_inputs} ||= []; 12045: push @{ $hints->{valid_inputs} }, @examples; 12046: 12047: $self->_log(" POD: extracted " . scalar(@examples) . " example call(s)"); 12048: } 12049: ●12050 → 12050 → 1205412050: for my $k (qw(boundary_values invalid_inputs valid_inputs equivalence_classes)) { 12051: $hints->{$k} //= []; 12052: } 12053: 12054: return $hints; 12055: } 12056: 12057: # -------------------------------------------------- 12058: # _clean_default_value 12059: # 12060: # Purpose: Normalise a raw default value string 12061: # extracted from code or POD into a 12062: # clean Perl scalar, handling quoted 12063: # strings, numeric literals, boolean 12064: # keywords, empty containers, and 12065: # undef. 12066: # 12067: # Entry: $value - raw value string. 12068: # May be undef. 12069: # $from_code - true if the value was 12070: # extracted from source 12071: # code (affects escape 12072: # sequence handling). 12073: # 12074: # Exit: Returns the cleaned value: 12075: # undef for undef or unparseable 12076: # {} for empty hashrefs 12077: # [] for empty arrayrefs 12078: # integer for whole numbers 12079: # float for decimal numbers 12080: # 1 or 0 for boolean keywords 12081: # string for everything else 12082: # 12083: # Side effects: None. 12084: # -------------------------------------------------- 12085: sub _clean_default_value { ●12086 → 12098 → 1210512086: my ($self, $value, $from_code) = @_; 12087: 12088: return unless defined $value; 12089: 12090: # Remove leading/trailing whitespace 12091: $value =~ s/^\s+|\s+$//g; 12092: 12093: # Remove parenthetical notes like "(no password)" only if there's content before them 12094: $value =~ s/(\S+)\s*\([^)]+\)\s*$/$1/; 12095: $value =~ s/^\s+|\s+$//g; 12096: 12097: # Handle chained || or // operators - extract the rightmost value 12098: if ($value =~ /\|\||\/{2}/) { 12099: my @parts = split(/\s*(?:\|\||\/{2})\s*/, $value); 12100: $value = $parts[-1]; 12101: $value =~ s/^\s+|\s+$//g; 12102: } 12103: 12104: # Remove trailing semicolon if present ●12105 → 12108 → 1211712105: $value =~ s/;\s*$//; 12106: 12107: # Handle q{}, qq{}, qw{} quotes 12108: if ($value =~ /^qq?\{(.*?)\}$/s) { 12109: $value = $1; 12110: } elsif ($value =~ /^qw\{(.*?)\}$/s) { 12111: $value = $1; 12112: } elsif ($value =~ /^q[qwx]?\s*([^a-zA-Z0-9\{\[])(.*?)\1$/s) { 12113: $value = $2; 12114: } 12115: 12116: # Handle quoted strings ●12117 → 12117 → 1214012117: if ($value =~ /^(['"])(.*)\1$/s) { 12118: $value = $2; 12119: 12120: if ($from_code) { 12121: # In regex captures from source code, escape sequences are doubled 12122: # \\n in capture needs to become \n for the test 12123: $value =~ s/\\\\/\\/g; 12124: } 12125: 12126: # Only unescape the quote characters themselves 12127: $value =~ s/\\"/"/g; 12128: $value =~ s/\\'/'/g; 12129: 12130: # If NOT from code (i.e., from POD), interpret escape sequences 12131: unless ($from_code) { 12132: $value =~ s/\\n/\n/g; 12133: $value =~ s/\\r/\r/g; 12134: $value =~ s/\\t/\t/g; 12135: $value =~ s/\\\\/\\/g; 12136: } 12137: } 12138: 12139: # Sometimes trailing ) is left on ●12140 → 12140 → 1214512140: if($value !~ /^\(/) { 12141: $value =~ s/\)$//; 12142: } 12143: 12144: # Handle Perl empty hash (must be before numeric/boolean checks) ●12145 → 12145 → 1215012145: if ($value =~ /^\{\s*\}$/) { 12146: return {}; 12147: } 12148: 12149: # Handle Perl empty list/array ●12150 → 12150 → 1215512150: if ($value =~ /^\[\s*\]$/) { 12151: return []; 12152: } 12153: 12154: # Handle numeric values ●12155 → 12155 → 1216412155: if ($value =~ /^-?\d+(?:\.\d+)?$/) { 12156: if ($value =~ /\./) { 12157: return $value + 0; 12158: } else { 12159: return int($value); 12160: } 12161: } 12162: 12163: # Handle boolean keywords ●12164 → 12164 → 1216912164: if ($value =~ /^(true|false)$/i) { 12165: return lc($1) eq 'true' ? 1 : 0; 12166: } 12167: 12168: # Handle Perl boolean constants ●12169 → 12169 → 1217612169: if ($value eq '1') { 12170: return 1; 12171: } elsif ($value eq '0') { 12172: return 0; 12173: } 12174: 12175: # Handle undef ●12176 → 12176 → 1218112176: if ($value eq 'undef') { 12177: return undef; 12178: } 12179: 12180: # Handle __PACKAGE__ and similar constants ●12181 → 12181 → 1218612181: if ($value eq '__PACKAGE__') { 12182: return '__PACKAGE__'; 12183: } 12184: 12185: # Remove surrounding parentheses ●12186 → 12189 → 1219412186: $value =~ s/^\((.+)\)$/$1/; 12187: 12188: # Handle expressions we can't evaluate 12189: if ($value =~ /^\$[a-zA-Z_]/ || $value =~ /\(.*\)/) { 12190: return if($value =~ /^\$|\@|\%/); # The default is a value, so who knows its type? 12191: # return $value; 12192: } 12193: 12194: return $value; 12195: } 12196: 12197: # -------------------------------------------------- 12198: # _validate_pod_code_agreement 12199: # 12200: # Purpose: Compare POD parameter documentation 12201: # against code-inferred parameters and 12202: # return a list of disagreements when 12203: # strict_pod mode is enabled. 12204: # 12205: # Entry: $pod_params - hashref of parameters 12206: # from POD analysis. 12207: # $code_params - hashref of parameters 12208: # from code analysis. 12209: # $method_name - method name string, 12210: # used for context in 12211: # error messages. 12212: # 12213: # Exit: Returns a list of disagreement 12214: # strings. Returns an empty list if 12215: # all parameters agree. 12216: # 12217: # Side effects: None. 12218: # 12219: # Notes: Type mismatches are classified as 12220: # either 'compatible' (e.g. integer vs 12221: # number) or 'incompatible' via 12222: # _types_are_compatible. $self and 12223: # $class are excluded from undocumented 12224: # parameter warnings in appropriate 12225: # context. 12226: # -------------------------------------------------- 12227: sub _validate_pod_code_agreement { ●12228 → 12235 → 1230612228: my ($self, $pod_params, $code_params, $method_name) = @_; 12229: 12230: my @errors; 12231: 12232: # Get all parameter names from both sources 12233: my %all_params = map { $_ => 1 } (keys %$pod_params, keys %$code_params); 12234: 12235: foreach my $param (sort keys %all_params) { 12236: my $pod = $pod_params->{$param} || {}; 12237: my $code = $code_params->{$param} || {}; 12238: 12239: # A =head3|4 Input formal spec is authoritative for the parameter's 12240: # existence, type, optionality and pattern: heuristic code analysis may 12241: # legitimately disagree. Its bounds are still checked below, because a 12242: # formal minimum and a code maximum that do not overlap leave the merged 12243: # schema with no valid value. 12244: unless(($pod->{_source} // '') eq SOURCE_INPUT_SPEC) { 12245: # Check if parameter exists in both 12246: if (exists $pod_params->{$param} && !exists $code_params->{$param}) { 12247: push @errors, "Parameter '\$$param' documented in POD but not found in code signature"; 12248: next; 12249: } 12250: 12251: if(!exists $pod_params->{$param} && exists $code_params->{$param}) { 12252: if($param =~ /^(class|pkg|proto|klass)$/i) { 12253: # class invocant, not a user-facing parameter 12254: next; 12255: } 12256: if($param eq 'self') { 12257: # instance invocant, not a user-facing parameter 12258: next; 12259: } 12260: push @errors, "Parameter '\$$param' found in code but not documented in POD"; 12261: next; 12262: } 12263: 12264: # Compare types if both exist 12265: if ($pod->{type} && $code->{type} && $pod->{type} ne $code->{type}) { 12266: if (!$self->_types_are_compatible($pod->{type}, $code->{type})) { 12267: push @errors, "Type mismatch for '\$$param': POD says '$pod->{type}', code suggests '$code->{type}' (incompatible)"; 12268: } else { 12269: push @errors, "Type difference for '\$$param': POD says '$pod->{type}', code suggests '$code->{type}' (compatible)"; 12270: } 12271: } 12272: 12273: # Compare optional status if both exist 12274: if (exists $pod->{optional} && exists $code->{optional} && 12275: $pod->{optional} != $code->{optional}) { 12276: my $pod_status = $pod->{optional} ? 'optional' : 'required'; 12277: my $code_status = $code->{optional} ? 'optional' : 'required'; 12278: push @errors, "Optional status mismatch for '\$$param': POD says '$pod_status', code suggests '$code_status'"; 12279: } 12280: 12281: # Check regex patterns 12282: if ($pod->{matches} && $code->{matches} && $pod->{matches} ne $code->{matches}) { 12283: push @errors, "Pattern mismatch for '\$$param': POD says '$pod->{matches}', code suggests '$code->{matches}'"; 12284: } 12285: } 12286: 12287: # Check constraints (min/max), including a formal spec's bounds. 12288: if (defined $pod->{min} && defined $code->{min} && $pod->{min} != $code->{min}) { 12289: push @errors, "Min constraint mismatch for '\$$param': POD says '$pod->{min}', code suggests '$code->{min}'"; 12290: } 12291: 12292: if (defined $pod->{max} && defined $code->{max} && $pod->{max} != $code->{max}) { 12293: push @errors, "Max constraint mismatch for '\$$param': POD says '$pod->{max}', code suggests '$code->{max}'"; 12294: } 12295: 12296: if (defined $pod->{min} && defined $code->{max} && $pod->{min} > $code->{max}) { 12297: push @errors, "Constraint contradiction for '\$$param': POD says min '$pod->{min}', code suggests max '$code->{max}' (no valid value)"; 12298: } 12299: 12300: if (defined $code->{min} && defined $pod->{max} && $code->{min} > $pod->{max}) { 12301: push @errors, "Constraint contradiction for '\$$param': code suggests min '$code->{min}', POD says max '$pod->{max}' (no valid value)"; 12302: } 12303: } 12304: 12305: # Return errors (empty array if no errors) 12306: return @errors; 12307: } 12308: 12309: # -------------------------------------------------- 12310: # _validate_strictness_level 12311: # 12312: # Purpose: Validate and normalise the strict_pod 12313: # option value accepted by new() into 12314: # an integer level: 0 (off), 1 (warn), 12315: # or 2 (fatal). 12316: # 12317: # Entry: $val - the raw value passed to 12318: # strict_pod in new(). May be 12319: # undef, a number, or a string. 12320: # 12321: # Exit: Returns 0, 1, or 2. 12322: # Croaks if the value is not recognised. 12323: # 12324: # Side effects: None. 12325: # -------------------------------------------------- 12326: sub _validate_strictness_level { 12327: my $val = $_[0]; 12328: 12329: return 0 unless defined $val; 12330: 12331: # Numeric 12332: return 0 if $val =~ /^(0|off|none)$/i; 12333: return 1 if $val =~ /^(1|warn|warning)$/i; 12334: return 2 if $val =~ /^(2|fatal|die|error)$/i; 12335: 12336: croak("Invalid value for --strict-pod: '$val' (use off|warn|fatal)"); 12337: } 12338: 12339: # -------------------------------------------------- 12340: # _types_are_compatible 12341: # 12342: # Purpose: Determine whether two type strings 12343: # are compatible for POD/code agreement 12344: # checking, allowing semantically 12345: # equivalent types (e.g. 'integer' and 12346: # 'number') to coexist without 12347: # triggering a strict POD warning. 12348: # 12349: # Entry: $pod_type - type string from POD. 12350: # $code_type - type string from code. 12351: # 12352: # Exit: Returns 1 if compatible, 0 otherwise. 12353: # 12354: # Side effects: None. 12355: # -------------------------------------------------- 12356: sub _types_are_compatible { ●12357 → 12373 → 1237812357: my ($self, $pod_type, $code_type) = @_; 12358: 12359: # Exact match is always compatible 12360: return 1 if $pod_type eq $code_type; 12361: 12362: # Define compatibility matrix 12363: my %compatible_types = ( 12364: 'integer' => ['number', 'scalar'], 12365: 'number' => ['scalar'], 12366: 'string' => ['scalar'], 12367: 'scalar' => ['string', 'integer', 'number'], 12368: 'arrayref' => ['array'], 12369: 'hashref' => ['hash'], 12370: ); 12371: 12372: # Check if code_type is compatible with pod_type 12373: if (my $allowed = $compatible_types{$pod_type}) { 12374: return grep { $_ eq $code_type } @$allowed; 12375: } 12376: 12377: # Check if pod_type is compatible with code_type ●12378 → 12378 → 1238212378: if (my $allowed = $compatible_types{$code_type}) { 12379: return grep { $_ eq $pod_type } @$allowed; 12380: } 12381: 12382: return 0; # Not compatible 12383: } 12384: 12385: =head2 generate_pod_validation_report 12386: 12387: Generate a human-readable report of all POD/code disagreements found 12388: across a set of extracted schemas. 12389: 12390: my $schemas = $extractor->extract_all(no_write => 1); 12391: my $report = $extractor->generate_pod_validation_report($schemas); 12392: print $report; 12393: 12394: =head3 Arguments 12395: 12396: =over 4 12397: 12398: =item * C<$schemas> 12399: 12400: A hashref of method name to schema hashref as returned by 12401: C<extract_all>. Required. 12402: 12403: =back 12404: 12405: =head3 Returns 12406: 12407: A string containing the full validation report, or a single line 12408: confirming all methods passed if no disagreements were found. 12409: 12410: =head3 Side effects 12411: 12412: None. 12413: 12414: =head3 Notes 12415: 12416: Only methods whose schemas contain a C<_pod_validation_errors> key 12417: (populated when C<strict_pod> is 1 or 2) appear in the report. If 12418: C<strict_pod> was 0 when C<extract_all> was called, this method will 12419: always return the all-passed message. 12420: 12421: =head3 API specification 12422: 12423: =head4 input 12424: 12425: { 12426: self => { type => OBJECT, isa => 'App::Test::Generator::SchemaExtractor' }, 12427: schemas => { type => HASHREF }, 12428: } 12429: 12430: =head4 output 12431: 12432: { type => SCALAR } 12433: 12434: =cut 12435: 12436: sub generate_pod_validation_report { ●12437 → 12440 → 1245212437: my ($self, $schemas) = @_; 12438: 12439: my @reports; 12440: foreach my $method_name (sort keys %$schemas) { 12441: my $schema = $schemas->{$method_name}; 12442: 12443: if (my $errors = $schema->{_pod_validation_errors}) { 12444: push @reports, "Method: $method_name"; 12445: push @reports, " Severity: " . ($schema->{_pod_disagreement} ? 'warning' : 'fatal'); 12446: push @reports, " Errors:"; 12447: push @reports, map { " - $_" } @$errors; 12448: push @reports, ''; 12449: } 12450: } 12451: ●12452 → 12452 → 012452: if (@reports) { 12453: return join("\n", "POD/Code Validation Report:", '=' x 40, '', @reports); 12454: } else { 12455: return 'POD/Code Validation: All methods passed consistency checks.'; 12456: } 12457: } 12458: 12459: =head2 _log 12460: 12461: Log a message if verbose mode is on. 12462: 12463: =cut 12464: 12465: sub _log { 12466: my($self, $msg) = @_; 12467: 12468: print "$msg\n" if $self->{verbose}; 12469: } 12470: 12471: =head1 NOTES 12472: 12473: C<SchemaExtractor> uses heuristic analysis of Perl source and POD to infer 12474: parameter types and constraints. Inference accuracy improves with 12475: well-documented modules; C<=head3 Input> / C<=head4 Input> formal specs are 12476: parsed at highest priority and override all heuristics. 12477: 12478: A lone name in a C<=head4 input> block is treated as the first positional 12479: argument when the body reads a positional argument (C<< $_[0] >>, a list 12480: assignment from C<@_>, or a C<shift>) and does not read an argument hash 12481: (C<my %args = @_>, a hashref dereference, or C<< $_[0]{...} >>); the 12482: documented name is then a label for that argument, as C<name> is for 12483: C<$_[0]> in L<Lingua::EN::NameCase/nc>. Two or more names, and a body that 12484: only forwards C<@_>, remain named arguments. 12485: 12486: The output is always a best-effort schema suitable as a starting template; 12487: review and augment the generated YAML before using it as a definitive 12488: specification. Pass it to L<App::Test::Generator> to generate fuzz harnesses. 12489: 12490: =head1 TODO 12491: 12492: Extend C<=head4 Input> parsing to cover the C<enum>/C<memberof> constraint 12493: synonym (union types, e.g. C<scalar | scalarref>, are already handled by 12494: C<_map_formal_input_type>). 12495: 12496: =head1 SEE ALSO 12497: 12498: =over 4 12499: 12500: =item * L<App::Test::Generator> - Generate fuzz and corpus-driven test harnesses 12501: 12502: Output from this module serves as input to that module. 12503: So with well-documented code, you can automatically create your tests. 12504: 12505: =item * L<App::Test::Generator::Template> - Template of the file of tests created by C<App::Test::Generator> 12506: 12507: =back 12508: 12509: =head1 AUTHOR 12510: 12511: Nigel Horne, C<< <njh at nigelhorne.com> >> 12512: 12513: =head1 LICENCE AND COPYRIGHT 12514: 12515: Copyright 2025-2026 Nigel Horne. 12516: 12517: Usage is subject to GPL2 licence terms. 12518: If you use it, 12519: please let me know. 12520: 12521: =cut 12522: 12523: 1;