| File: | blib/lib/App/Test/Generator/SchemaExtractor.pm |
| Coverage: | 80.5% |
| line | stmt | bran | cond | sub | time | code |
|---|---|---|---|---|---|---|
| 1 | package App::Test::Generator::SchemaExtractor; | |||||
| 2 | ||||||
| 3 | 91 91 91 | 1118579 49 974 | use strict; | |||
| 4 | 91 91 91 | 106 44 1472 | use warnings; | |||
| 5 | 91 91 91 | 12364 451321 149 | use autodie qw(:all); | |||
| 6 | ||||||
| 7 | 91 91 91 | 591394 88 1024 | use App::Test::Generator::Model::Method; | |||
| 8 | 91 91 91 | 10725 78 983 | use App::Test::Generator::Analyzer::Complexity; | |||
| 9 | 91 91 91 | 9887 85 880 | use App::Test::Generator::Analyzer::Return; | |||
| 10 | 91 91 91 | 9074 75 848 | use App::Test::Generator::Analyzer::ReturnMeta; | |||
| 11 | 91 91 91 | 9641 82 1126 | use App::Test::Generator::Analyzer::SideEffect; | |||
| 12 | 91 | 1974 | use App::Test::Generator::Provenance qw( | |||
| 13 | SOURCE_VALIDATOR SOURCE_INPUT_SPEC SOURCE_POD | |||||
| 14 | SOURCE_CODE SOURCE_SIGNATURE SOURCE_FIELD | |||||
| 15 | 91 91 | 8592 80 | ); | |||
| 16 | ||||||
| 17 | 91 91 91 | 113 80 1017 | use Carp qw(carp croak); | |||
| 18 | 91 91 91 | 14771 4297463 1109 | use PPI; | |||
| 19 | 91 91 91 | 12745 415681 970 | use Pod::Simple::Text; | |||
| 20 | 91 91 91 | 180 82 2358 | use File::Basename; | |||
| 21 | 91 91 91 | 126 65 1203 | use File::Path qw(make_path); | |||
| 22 | 91 91 91 | 13828 200410 1364 | use Params::Get; | |||
| 23 | 91 91 91 | 15878 297613 910 | use Safe; | |||
| 24 | 91 91 91 | 161 63 1527 | use Scalar::Util qw(looks_like_number refaddr reftype); | |||
| 25 | 91 91 91 | 9551 74293 1692 | use YAML::XS; | |||
| 26 | 91 91 91 | 13509 76033 1622 | use IPC::Open3; | |||
| 27 | 91 91 91 | 163 68 1787 | use JSON::MaybeXS qw(encode_json decode_json); | |||
| 28 | 91 91 91 | 115 60 902 | use Readonly; | |||
| 29 | 91 91 91 | 101 69 2084214 | 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 - 89 | =head1 NAME App::Test::Generator::SchemaExtractor - Extract test schemas from Perl modules =head1 VERSION Version 0.52 =cut | |||||
| 90 | ||||||
| 91 | our $VERSION = '0.52'; | |||||
| 92 | ||||||
| 93 - 1375 | =head1 SYNOPSIS
use App::Test::Generator::SchemaExtractor;
my $extractor = App::Test::Generator::SchemaExtractor->new(
input_file => 'lib/MyModule.pm',
output_dir => 'schemas/',
verbose => 1,
);
my $schemas = $extractor->extract_all();
=head1 DESCRIPTION
App::Test::Generator::SchemaExtractor analyzes Perl modules and generates
structured YAML schema files suitable for automated test generation by L<App::Test::Generator>.
This module employs
static analysis techniques to infer parameter types, constraints, and
method behaviors directly from your source code.
=head2 Analysis Methods
The extractor combines multiple analysis approaches for a comprehensive schema generation:
=over 4
=item * B<POD Documentation Analysis>
Parses embedded documentation to extract:
- Parameter names, types, and descriptions from =head2 sections
- Method signatures with positional parameters
- Return value specifications from "Returns:" sections
- Constraints (ranges, patterns, required/optional status)
(in a formal C<=head4 Input> spec, C<required =E<gt> 1> means
C<optional: 0> and an explicit C<optional> flag wins; a bare list of
C<name =E<gt> { ... }> entries with no outer braces contributes only
its top-level C<required> flags)
- Semantic type detection (email, URL, filename)
=item * B<Code Pattern Detection>
Analyzes source code using PPI to identify:
- Method signatures and parameter extraction patterns
- Type validation (ref(), isa(), blessed())
- Constraint patterns (length checks, numeric comparisons, regex matches)
- Return statement analysis and value type inference
- Object instantiation requirements and accessor methods
=item * B<Signature Analysis>
Examines method declarations for:
- Parameter names and positional information
- Instance vs. class method detection
- Method modifiers (Moose-style before/after/around)
- Various parameter declaration styles (shift, @_ assignment)
=item * B<Heuristic Inference>
Applies Perl-specific domain knowledge:
- Boolean return detection from method names (is_*, has_*, can_*)
- Common Perl idioms and coding patterns
- Context awareness (scalar vs list, wantarray usage)
- Object-oriented patterns (constructors, accessors, chaining)
=back
=head2 Generated Schema Structure
The extracted schemas follow this YAML structure:
function: method_name
module: Package::Name
input:
param1:
type: string
min: 3
max: 50
optional: 0
position: 0
param2:
type: integer
min: 0
max: 100
optional: 1
position: 1
output:
type: boolean
value: 1
new: Package::Name # if object instantiation required
config:
test_empty: 1
test_nuls: 0
test_undef: 0
test_non_ascii: 0
=head2 Advanced Detection Capabilities
=over 4
=item * B<Accessor Method Detection>
Automatically identifies getter, setter, and combined accessor methods
by analyzing common patterns like C<return $self-E<gt>{property}> and
C<$self-E<gt>{property} = $value>.
=item * B<Params::Get Integration>
Recognises parameters extracted via C<Params::Get::get_params('key', \@_)>,
treating the quoted key as a named parameter equivalent to a traditional
C<my ($self, $key) = @_> signature. This prevents false positives from
C<--strict-pod> when the method body never declares an explicit C<$key>
variable.
=item * B<Direct-Index Self Style>
Recognises C<my $self = $_[0]> as a valid method-invocant pattern. Parameters
at C<$_[1]>, C<$_[2]>, etc. are extracted as positional parameters. Without
this, the signature fallback would incorrectly pick up C<my (...) = @_> from
inner closures defined in the method body and treat those variables as the
outer method's parameters.
=item * B<Boolean Return Inference>
Detects boolean-returning methods through multiple signals:
- Method name patterns (is_*, has_*, can_*)
- Return patterns (consistent 1/0 returns)
- POD descriptions ("returns true on success")
- Ternary operators with boolean results
=item * B<Context Awareness>
Identifies methods that use C<wantarray> and can return different
values in scalar vs list context.
=item * B<Object Lifecycle Management>
Detects instance methods requiring object instantiation and
automatically adds the C<new> field to schemas.
=item * B<Enhanced Object Detection>
The extractor includes sophisticated object detection capabilities that go beyond simple instance method identification:
=over 4
=item * B<Factory Method Recognition>
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.
=item * B<Singleton Pattern Detection>
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.
=item * B<Constructor Parameter Analysis>
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.
A constructor that rejects an empty arrayref, or calls methods on (or
checks C<blessed> on) the elements of a required arrayref parameter, needs
live objects that a YAML fixture cannot hold. Its C<new> schema gets a
C<skip> reason such as C<needs a non-empty arrayref of live objects in
'databases'>, and its instance methods are emitted with C<new: ~> so
harnesses skip them.
=item * B<Inheritance Relationship Handling>
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.
=item * B<External Object Dependency Detection>
Identifies when methods create or depend on objects from other classes, enabling proper test setup with mock objects or real dependencies.
=back
These enhancements ensure that generated test schemas accurately reflect the object-oriented structure of the code, leading to more meaningful and effective test generation.
=back
=head2 Confidence Scoring
Each generated schema includes detailed confidence assessments:
=over 4
=item * B<High Confidence>
Multiple independent analysis sources converge on consistent,
well-constrained parameters with explicit validation logic and
comprehensive documentation.
=item * B<Medium Confidence>
Reasonable evidence from code patterns or partial documentation,
but may lack comprehensive constraints or have some ambiguities.
=item * B<Low Confidence>
Minimal evidence - primarily based on naming conventions,
default assumptions, or single-source analysis.
=item * B<Very Low Confidence>
Barely any detectable signals - schema should be thoroughly
reviewed before use in test generation.
=back
=head2 Use Cases
=over 4
=item * B<Automated Test Generation>
Generate comprehensive test suites with L<App::Test::Generator> using
extracted schemas as input. The schemas provide the necessary structure
for generating both positive and negative test cases.
=item * B<API Documentation Generation>
Supplement existing documentation with automatically inferred interface
specifications, parameter requirements, and return types.
=item * B<Code Quality Assessment>
Identify methods with poor documentation, inconsistent parameter handling,
or unclear interfaces that may benefit from refactoring.
=item * B<Refactoring Assistance>
Detect method dependencies, object instantiation requirements, and
parameter usage patterns to inform refactoring decisions.
=item * B<Legacy Code Analysis>
Quickly understand the interface contracts of legacy Perl codebases
without extensive manual code reading.
=back
=head2 Integration with Testing Ecosystem
The generated schemas are specifically designed to work with the
L<App::Test::Generator> ecosystem:
# Extract schemas from your module
my $extractor = App::Test::Generator::SchemaExtractor->new(...);
my $schemas = $extractor->extract_all();
# Use with test generator (typically as separate steps)
# fuzz-harness-generator -r schemas/method_name.yml
=head2 Limitations and Considerations
=over 4
=item * B<Dynamic Code Patterns>
Highly dynamic code (string evals, AUTOLOAD, symbolic references)
may not be fully detected by static analysis.
=item * B<Complex Validation Logic>
Sophisticated validation involving multiple parameters or external
dependencies may require manual schema refinement.
=item * B<Confidence Heuristics>
Confidence scores are based on heuristics and should be reviewed
by developers familiar with the codebase.
=item * B<Perl Idiom Recognition>
Some Perl-specific idioms may require custom pattern recognition
beyond the built-in detectors.
=item * B<Documentation Dependency>
Analysis quality improves significantly with comprehensive POD
documentation following consistent patterns.
=item * B<Multi-Package Files>
Only the first package in a file is analysed. A file that declares
additional packages, such as a small error class, is still extracted, but
its schemas carry a C<skip> reason so generated harnesses are not run
against it. Perl 5.38 C<class> blocks are not detected in such a file:
the C<class>/C<method> scan reads the whole source, so it runs only when
the file declares at most one C<package>.
=back
=head2 Best Practices for Optimal Results
=over 4
=item * B<Comprehensive POD Documentation>
Write detailed POD with explicit parameter documentation using
consistent patterns like C<$param - type (constraints), description>.
=item * B<Consistent Coding Patterns>
Use consistent parameter validation patterns and method signatures
throughout your codebase.
=item * B<Schema Review Process>
Review and refine automatically generated schemas, particularly
those with low confidence scores.
=item * B<Descriptive Naming>
Use descriptive method and parameter names that clearly indicate
purpose and expected types.
=item * B<Progressive Enhancement>
Start with automatically generated schemas and progressively
refine them based on test results and code understanding.
=back
The module is particularly valuable for large codebases where manual schema
creation would be prohibitively time-consuming, and for maintaining test
coverage as code evolves through continuous integration pipelines.
=head2 Advanced Type Detection
The schema extractor includes enhanced type detection capabilities that identify specialized Perl types beyond basic strings and integers.
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.
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.
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.
=head3 Example Advanced Type Schema
For a method like:
sub process_event {
my ($self, $timestamp, $status, $callback) = @_;
croak unless $timestamp > 1000000000;
croak unless $status =~ /^(active|pending|complete)$/;
croak unless ref($callback) eq 'CODE';
$callback->($timestamp, $status);
}
The extractor generates:
---
function: process_event
module: MyModule
input:
timestamp:
type: integer
# min: 0
# max: 2147483647
position: 0
_note: Unix timestamp
semantic: unix_timestamp
status:
type: string
enum:
- active
- pending
- complete
position: 1
_note: 'Must be one of: active, pending, complete'
callback:
type: coderef
position: 2
_note: 'CODE reference - provide sub { } in tests'
=head1 RELATIONSHIP DETECTION
The schema extractor detects relationships and dependencies between parameters,
enabling more sophisticated validation and test generation.
=head2 Relationship Types
=over 4
=item * B<mutually_exclusive>
Parameters that cannot be used together.
die if $file && $content; # Can't specify both
Generated schema:
relationships:
- type: mutually_exclusive
params: [file, content]
description: Cannot specify both file and content
=item * B<required_group>
At least one parameter from the group must be specified (OR logic).
die unless $id || $name; # Must provide one
Generated schema:
relationships:
- type: required_group
params: [id, name]
logic: or
description: Must specify either id or name
=item * B<conditional_requirement>
If one parameter is specified, another becomes required (IF-THEN logic).
die if $async && !$callback; # async requires callback
Generated schema:
relationships:
- type: conditional_requirement
if: async
then_required: callback
description: When async is specified, callback is required
=item * B<dependency>
One parameter depends on another being present.
die "Port requires host" if $port && !$host;
Generated schema:
relationships:
- type: dependency
param: port
requires: host
description: port requires host to be specified
=item * B<value_constraint>
Specific value requirements between parameters.
die if $ssl && $port != 443; # ssl requires port 443
Generated schema:
relationships:
- type: value_constraint
if: ssl
then: port
operator: ==
value: 443
description: When ssl is specified, port must equal 443
=item * B<value_conditional>
Parameter required when another has a specific value.
die if $mode eq 'secure' && !$key;
Generated schema:
relationships:
- type: value_conditional
if: mode
equals: secure
then_required: key
description: When mode equals 'secure', key is required
=back
=head2 Default Value Extraction
The extractor comprehensively extracts default values from both code and POD documentation:
=head3 Code Pattern Recognition
Extracts defaults from multiple Perl idioms:
=over 4
=item * Logical OR operator: C<$param = $param || 'default'>
=item * Defined-or operator: C<$param //= 'default'>
=item * Ternary operator: C<$param = defined $param ? $param : 'default'>
=item * Unless conditional: C<$param = 'default' unless defined $param>
=item * Chained defaults: C<$param = $param || $self->{_default} || 'fallback'>
=item * Multi-line patterns: C<$param = {} unless $param>
=back
=head3 POD Pattern Recognition
Extracts defaults from documentation:
=over 4
=item * Standard format: C<Default: 'value'>
=item * Alternative format: C<Defaults to: 'value'>
=item * Inline format: C<Optional, default: 'value'>
=item * Parameter lists: C<$param - type, default 'value'>
=back
=head3 Value Processing
Properly handles:
=over 4
=item * String literals with quotes and escape sequences
=item * Numeric values (integers and floats)
=item * Boolean values (true/false converted to 1/0)
=item * Empty data structures ([] and {})
=item * Special values (undef, __PACKAGE__)
=item * Complex expressions (preserved as-is when unevaluatable)
=item * Quote operators (q{}, qq{}, qw{})
=back
=head3 Type Inference
When a parameter has a default value but no explicit type annotation,
the type is automatically inferred from the default:
$options = {} # inferred as hashref
$items = [] # inferred as arrayref
$count = 42 # inferred as integer
$ratio = 3.14 # inferred as number
$enabled = 1 # inferred as boolean
=head2 Context-Aware Return Analysis
The extractor provides comprehensive analysis of method return behavior,
including context sensitivity, error handling conventions, and method chaining patterns.
When a method's POD contains a C<=head4 Output> block in
L<Params::Validate::Strict> schema format, the C<type> declared there is
used as the authoritative output type and takes precedence over all
heuristic code analysis:
=head4 Output
{
type => 'hashref',
}
This is the recommended way to document methods whose return type would
otherwise be misidentified (e.g. a method that returns C<$self-E<gt>{cache}>
where the cache happens to hold a hashref).
Using parentheses as the outer container emits C<type: array>, indicating a
list-returning method. L<App::Test::Generator> 0.39+ (with L<Test::Returns>
0.03+) captures these results in list context automatically:
=head4 Output
(
{
type => 'hashref',
},
...
)
=head3 List vs Scalar Context Detection
Automatically detects methods that return different values based on calling context:
sub get_items {
my $self = $_[0];
return wantarray ? @items : scalar(@items);
}
Detection captures:
=over 4
=item * C<_context_aware> flag - Method uses wantarray
=item * C<_list_context> - Type returned in list context (e.g., 'array')
=item * C<_scalar_context> - Type returned in scalar context (e.g., 'integer')
=back
Recognizes both ternary operator patterns and conditional return patterns.
=head3 Void Context Methods
Identifies methods that don't return meaningful values:
=over 4
=item * Setters (C<set_*> methods)
=item * Mutators (C<add_*, remove_*, delete_*, clear_*, reset_*, update_*>)
=item * Loggers (C<log, debug, warn, error, info>)
=item * Methods with only empty returns
=back
Example:
sub set_name {
my ($self, $name) = @_;
$self->{name} = $name;
return; # Void context
}
Sets C<_void_context> flag and C<type =E<gt> 'void'>.
=head3 Method Chaining Detection
Identifies chainable methods that return C<$self> for fluent interfaces:
sub set_width {
my ($self, $width) = @_;
$self->{width} = $width;
return $self; # Chainable
}
Detection provides:
=over 4
=item * C<_returns_self> - Returns invocant for chaining
=item * C<class> - The class name being returned
=back
Also detects chaining documentation in POD (keywords: "chainable", "fluent interface",
"returns self", "method chaining").
=head3 Error Return Conventions
Analyzes how methods signal errors:
B<Pattern Detection:>
=over 4
=item * C<undef_on_error> - Explicit C<return undef if/unless condition>
=item * C<implicit_undef> - Bare C<return if/unless condition>
=item * C<empty_list> - C<return ()> for list context errors
=item * C<zero_on_error> - Returns 0/false for boolean error indication
=item * C<exception_handling> - Uses eval blocks with error checking
=back
B<Example Analysis:>
sub fetch_user {
my ($self, $id) = @_;
return undef unless $id; # undef_on_error
return undef if $id < 0; # undef_on_error
return $self->{users}{$id};
}
Results in:
_error_return: 'undef'
_success_failure_pattern: 1
_error_handling: {
undef_on_error: ['$id', '$id < 0']
}
B<Success/Failure Pattern:>
Methods that return different types for success vs. failure are flagged with
C<_success_failure_pattern>. Common patterns:
=over 4
=item * Returns value on success, undef on failure
=item * Returns true on success, false on failure
=item * Returns data on success, empty list on failure
=back
=head3 Success Indicator Detection
Methods that always return true (typically for side effects):
sub update_status {
my ($self, $status) = @_;
$self->{status} = $status;
return 1; # Success indicator
}
Sets C<_success_indicator> flag when method consistently returns 1.
=head3 Schema Output
Enhanced return analysis adds these fields to method schemas:
output:
type: boolean # Inferred return type
_context_aware: 1 # Uses wantarray
_list_context:
type: array
_scalar_context:
type: integer
_returns_self: 1 # Returns $self
_void_context: 1 # No meaningful return
_success_indicator: 1 # Always returns true
_error_return: undef # How errors are signaled
_success_failure_pattern: 1 # Mixed return types
_error_handling: # Detailed error patterns
undef_on_error: [...]
exception_handling: 1
This comprehensive analysis enables:
=over 4
=item * Better test generation (testing both contexts, error paths)
=item * Documentation generation (clear error conventions)
=item * API design validation (consistent error handling)
=item * Contract specification (precise return behavior)
=back
=head2 Example
For a method like:
sub connect {
my ($self, $host, $port, $ssl, $file, $content) = @_;
die if $file && $content; # mutually exclusive
die unless $host || $file; # required group
die "Port requires host" if $port && !$host; # dependency
die if $ssl && $port != 443; # value constraint
# ... connection logic
}
The extractor generates:
relationships:
- type: mutually_exclusive
params: [file, content]
description: Cannot specify both file and content
- type: required_group
params: [host, file]
logic: or
description: Must specify either host or file
- type: dependency
param: port
requires: host
description: port requires host to be specified
- type: value_constraint
if: ssl
then: port
operator: ==
value: 443
description: When ssl is specified, port must equal 443
=head1 MODERN PERL FEATURES
This module adds support for:
=head2 Subroutine Signatures (Perl 5.20+)
sub connect($host, $port = 3306, %options) {
...
}
Extracts: required params, optional params with defaults, slurpy params
=head2 Type Constraints (Perl 5.36+)
sub calculate($x :Int, $y :Num) {
...
}
Recognizes: Int, Num, Str, Bool, ArrayRef, HashRef, custom classes
=head3 Subroutine Attributes
sub get_value :lvalue :Returns(Int) {
...
}
Detects: :lvalue, :method, :Returns(Type), custom attributes
=head2 Postfix Dereferencing (Perl 5.20+)
my @array = $arrayref->@*;
my %hash = $hashref->%*;
my @slice = $arrayref->@[1,3,5];
Tracks usage of modern dereferencing syntax
=head2 Field Declarations (Perl 5.38+)
field $host :param = 'localhost';
field $port :param(port_number) = 3306;
field $logger :param :isa(Log::Any);
Extracts fields and maps them to parameters
=head2 Modern Perl Features Support
The schema extractor supports modern Perl syntax introduced in versions 5.20, 5.36, and 5.38+.
=head3 Subroutine Signatures (Perl 5.20+)
Automatically extracts parameters from native Perl signatures:
use feature 'signatures';
sub connect($host, $port = 3306, $database = undef) {
...
}
Extracted schema includes:
=over 4
=item * Parameter positions
=item * Optional vs required parameters
=item * Default values from signature
=item * Slurpy parameters (@array, %hash)
=back
B<Example:>
# Signature with defaults
sub process($file, %options) { ... }
# Extracts:
# $file: position 0, required
# %options: named: 1, optional, slurpy hash
=head3 Type Constraints in Signatures (Perl 5.36+)
Recognizes type constraints in signature parameters:
sub calculate($x :Int, $y :Num, $name :Str = "result") {
return $x + $y;
}
Supported constraint types:
=over 4
=item * C<:Int, :Integer> -> integer
=item * C<:Num, :Number> -> number
=item * C<:Str, :String> -> string
=item * C<:Bool, :Boolean> -> boolean
=item * C<:ArrayRef, :Array> -> arrayref
=item * C<:HashRef, :Hash> -> hashref
=item * C<:ClassName> -> object with isa constraint
=back
Type constraints are combined with defaults when both are present.
=head3 Subroutine Attributes
Extracts and documents subroutine attributes:
sub get_value :lvalue {
my $self = shift;
return $self->{value};
}
sub calculate :Returns(Int) :method {
my ($self, $x, $y) = @_;
return $x + $y;
}
Recognized attributes stored in C<_attributes> field:
=over 4
=item * C<:lvalue> - Method can be assigned to
=item * C<:method> - Explicitly marked as method
=item * C<:Returns(Type)> - Declares return type
=item * Custom attributes with values: C<:MyAttr(value)>
=back
=head3 Postfix Dereferencing (Perl 5.20+)
Detects usage of postfix dereferencing syntax:
use feature 'postderef';
sub process_array {
my ($self, $arrayref) = @_;
my @array = $arrayref->@*; # Array dereference
my @slice = $arrayref->@[1,3,5]; # Array slice
return @array;
}
sub process_hash {
my ($self, $hashref) = @_;
my %hash = $hashref->%*; # Hash dereference
return keys %hash;
}
Tracked features stored in C<_modern_features>:
=over 4
=item * C<array_deref> - Uses C<-E<gt>@*>
=item * C<hash_deref> - Uses C<-E<gt>%*>
=item * C<scalar_deref> - Uses C<-E<gt>$*>
=item * C<code_deref> - Uses C<-E<gt>&*>
=item * C<array_slice> - Uses C<-E<gt>@[...]>
=item * C<hash_slice> - Uses C<-E<gt>%{...}>
=back
=head3 Field Declarations (Perl 5.38+)
Extracts field declarations from class syntax and maps them to method parameters:
use feature 'class';
class DatabaseConnection {
field $host :param = 'localhost';
field $port :param = 3306;
field $username :param(user);
field $password :param;
field $logger :param :isa(Log::Any);
method connect() {
# Fields available as instance variables
}
}
Field attributes:
=over 4
=item * C<:param> - Field is a constructor parameter (uses field name)
=item * C<:param(name)> - Field maps to parameter with different name
=item * C<:isa(Class)> - Type constraint for the field
=item * Default values in field declarations
=back
Extracted schema includes both field information in C<_fields> and merged parameter
information in C<input>, allowing proper validation of class constructors.
=head3 Mixed Modern and Traditional Syntax
The extractor handles code that mixes modern and traditional syntax:
sub modern($x, $y = 5) {
# Modern signature with default
}
sub traditional {
my ($self, $x, $y) = @_;
$y //= 5; # Traditional default in code
# Both extract same parameter information
}
Priority order for parameter information:
=over 4
=item 1. Signature declarations (highest priority)
=item 2. Field declarations (for class methods)
=item 3. POD documentation
=item 4. Code analysis (lowest priority)
=back
This ensures that explicit declarations in signatures take precedence over
inferred information from code analysis.
=head3 Backwards Compatibility
All modern Perl feature detection is optional and automatic:
=over 4
=item * Traditional C<sub> declarations continue to work
=item * Code without modern features extracts parameters as before
=item * Modern features are additive - they enhance rather than replace existing extraction
=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
=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
=back
=head2 _yamltest_hints
Each method schema returned by L</extract_all> now optionally includes a
C<_yamltest_hints> key, which provides guidance for automated test generation
based on the code analysis.
This is intended to help L<App::Test::Generator> create meaningful tests,
including boundary and invalid input cases, without manually specifying them.
The structure is a hashref with the following keys:
=over 4
=item * boundary_values
An arrayref of numeric values that represent boundaries detected from
comparisons in the code. These are derived from literals in statements
like C<$x < 0> or C<$y >= 255>. The generator can use these to create
boundary tests.
Example:
_yamltest_hints:
boundary_values: [0, 1, 100, 255]
=item * invalid_inputs
An arrayref of values that are likely to be rejected by the method,
based on checks like C<defined>, empty strings, or numeric validations.
Example:
_yamltest_hints:
invalid_inputs: [undef, '', -1]
=item * equivalence_classes
An arrayref intended to capture detected equivalence classes or patterns
among inputs. Currently this is empty by default, but future enhancements
may populate it based on detected input groupings.
Example:
_yamltest_hints:
equivalence_classes: []
=back
=head3 Usage
When calling C<extract_all>, each method schema will include
C<_yamltest_hints> if any hints were detected:
my $schemas = $extractor->extract_all;
my $hints = $schemas->{example_method}->{_yamltest_hints};
You can then feed these hints into automated test generators to produce
negative tests, boundary tests, and parameter-specific test cases.
=head3 Notes
=over 4
=item * Hints are inferred heuristically from code and validation statements.
=item * Not all inputs are guaranteed to be detected; the feature is additive
and will never remove information from the schema.
=item * Currently, equivalence classes are not populated, but the field exists
for future extension.
=item * Boundary and invalid input hints are deduplicated to avoid repeated
test values.
=back
=head3 Examples
Given a method like:
sub example {
my ($x) = @_;
die "negative" if $x < 0;
return unless defined($x);
return $x * 2;
}
After running:
my $extractor = App::Test::Generator::SchemaExtractor->new(
input_file => 'TestHints.pm',
output_dir => '/tmp',
quiet => 1,
);
my $schemas = $extractor->extract_all;
The schema for the method "example" will include:
$schemas->{example} = {
function => 'example',
_confidence => {
input => 'unknown',
output => 'unknown',
},
input => {
x => {
type => 'scalar',
optional => 0,
}
},
output => {
type => 'scalar',
},
_yamltest_hints => {
boundary_values => [0, 1],
invalid_inputs => [undef, -1],
equivalence_classes => [],
},
_notes => '...',
_analysis => {
input_confidence => 'low',
output_confidence => 'unknown',
confidence_factors => {
input => {...},
output => {...},
},
overall_confidence => 'low',
},
_fields => {},
_modern_features => {},
_attributes => {},
};
=head1 METHODS
=head2 new
Construct a new SchemaExtractor for a given Perl source file.
my $extractor = App::Test::Generator::SchemaExtractor->new(
input_file => 'lib/MyModule.pm', # Required
output_dir => 'schemas/', # Optional - only needed if writing schemas
verbose => 1, # Default: 0
include_private => 1, # Default: 0
max_parameters => 50, # Default: 20
confidence_threshold => 0.7, # Default: 0.5
strict_pod => 0|1|2, # Default: 0 (off)
allow_signature_exec => 1, # Default: 0 (off)
);
=head3 Arguments
=over 4
=item * C<$input_file>
Path to the Perl source file to analyse. Required. Must exist on disk.
=item * C<output_dir>
Directory to write generated schema YAML files. Optional - only
required if C<_write_schema> will be called. Callers passing
C<no_write =E<gt> 1> to C<extract_all> do not need to supply it.
=item * C<verbose>
Print progress messages to stdout during analysis. Optional, default 0.
=item * C<include_private>
Include methods whose names begin with C<_> in the analysis. Optional,
default 0. Methods whose name begins with C<_new>, C<_init>, or
C<_build> are always included regardless of this setting (a prefix
match, so e.g. C<_build_attribute> and C<_init_logger> qualify too,
matching common Moose builder/initializer naming conventions).
=item * C<max_parameters>
Safety limit on the number of parameters analysed per method to prevent
runaway processing on pathological code. Optional, default 20.
=item * C<confidence_threshold>
Minimum confidence score (0.0-1.0) below which a schema is marked with
C<_low_confidence =E<gt> 1>. Optional, default 0.5.
=item * C<strict_pod>
Controls POD/code agreement validation. C<0> disables validation,
C<1> emits warnings, C<2> croaks on first disagreement. Also accepts
the strings C<off>, C<warn>, and C<fatal>. Optional, default 0.
=item * C<allow_signature_exec>
Opt-in flag allowing extraction of parameter types from a
L<Type::Params> C<signature_for()> declaration. This requires actually
running the C<signature_for> expression (sliced from the target
module's own source) in a forked C<perl -T> process, since
L<Type::Params> types are runtime objects that cannot be introspected
statically. Every other extraction path in this module is static
(L<PPI>-only) analysis that never executes any of the target module's
code; this is the one exception. Optional, default 0 (the
C<signature_for> path is silently skipped, with a warning under
C<verbose>, when off). Only enable this for modules whose code you
already trust enough to execute.
=back
=head3 Returns
A blessed hashref. Croaks if C<input_file> is missing or does not
exist on disk.
=head3 Side effects
Reads and parses the input file using L<PPI> at construction time.
=head3 API specification
=head4 input
{
input_file => { type => SCALAR },
output_dir => { type => SCALAR, optional => 1 },
verbose => { type => SCALAR, optional => 1 },
include_private => { type => SCALAR, optional => 1 },
max_parameters => { type => SCALAR, optional => 1 },
confidence_threshold => { type => SCALAR, optional => 1 },
strict_pod => { type => SCALAR, optional => 1 },
allow_signature_exec => { type => SCALAR, optional => 1 },
}
=head4 output
{
type => OBJECT,
isa => 'App::Test::Generator::SchemaExtractor',
}
=cut | |||||
| 1376 | ||||||
| 1377 | sub new { | |||||
| 1378 | 592 | 2564668 | my $class = shift; | |||
| 1379 | ||||||
| 1380 | # Handle hash or hashref arguments | |||||
| 1381 | 592 | 970 | my $params = Params::Get::get_params('input_file', @_) || {}; | |||
| 1382 | ||||||
| 1383 | 589 | 6909 | 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 | 589 | 2471 | 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 | 589 | 3293 | unless (-f $self->{input_file}) { | |||
| 1400 | 3 | 69 | croak(__PACKAGE__, ": Input file '$self->{input_file}' does not exist"); | |||
| 1401 | } | |||||
| 1402 | ||||||
| 1403 | 586 | 1004 | return bless $self, $class; | |||
| 1404 | } | |||||
| 1405 | ||||||
| 1406 - 1479 | =head2 extract_all
Extract schemas for all qualifying methods in the module and return
them as a hashref.
my $schemas = $extractor->extract_all();
# Suppress writing .yml files to disk
my $schemas = $extractor->extract_all(no_write => 1);
=head3 Arguments
=over 4
=item * C<no_write>
When true, schema files are not written to C<output_dir>. The returned
hashref is still fully populated. Useful when the caller wants to
inspect or augment schemas before deciding whether to write them.
Optional, default 0.
=back
=head3 Returns
A hashref mapping method name strings to schema hashrefs. Each schema
contains at minimum the keys C<function>, C<module>, C<input>,
C<output>, and C<_analysis>. See L</Generated Schema Structure> for
the full structure.
=head3 Side effects
Parses the input file with L<PPI>. Writes one YAML file per method to
C<output_dir> unless C<no_write> is set. Creates C<output_dir> if it
does not exist and writing is enabled.
=head3 Notes
Private methods (names beginning with C<_>) are excluded unless
C<include_private =E<gt> 1> was passed to C<new>. Duplicate method
names are deduplicated with a warning logged to stdout in verbose mode.
POD/code agreement validation is applied if C<strict_pod> was set in
C<new>. At level 2 (fatal), the first disagreement causes an immediate
croak.
=head3 API specification
=head4 input
{
self => { type => OBJECT, isa => 'App::Test::Generator::SchemaExtractor' },
no_write => { type => SCALAR, optional => 1 },
}
=head4 output
{
type => HASHREF,
keys => {
'*' => {
type => HASHREF,
keys => {
function => { type => SCALAR },
module => { type => SCALAR },
input => { type => HASHREF },
output => { type => HASHREF },
_analysis => { type => HASHREF },
},
},
},
}
=cut | |||||
| 1480 | ||||||
| 1481 | sub extract_all { | |||||
| 1482 | 212 | 2839 | my $self = shift; | |||
| 1483 | 212 | 284 | my $params = Params::Get::get_params(undef, @_) || {}; | |||
| 1484 | ||||||
| 1485 | 212 | 2095 | $self->_log("Parsing $self->{input_file}..."); | |||
| 1486 | 212 | 409 | $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 | 212 | 758 | or croak "Failed to parse $self->{input_file}"; | |||
| 1491 | ||||||
| 1492 | # Store document for later use | |||||
| 1493 | 212 | 1336057 | $self->{_document} = $document; | |||
| 1494 | ||||||
| 1495 | 212 | 442 | my $package_name = $self->_extract_package_name($document); | |||
| 1496 | 212 | 1590 | $self->{_package_name} //= $package_name; | |||
| 1497 | 212 | 398 | $self->_log("Package: $package_name"); | |||
| 1498 | ||||||
| 1499 | 212 | 363 | my $methods = $self->_find_methods($document); | |||
| 1500 | 212 | 430 | $self->_log('Found ' . scalar(@$methods) . ' methods (pre-dedup)'); | |||
| 1501 | ||||||
| 1502 | 212 | 300 | my %schemas; | |||
| 1503 | my %delegates; | |||||
| 1504 | 212 | 0 | my $ctor_body; | |||
| 1505 | 212 212 | 189 228 | foreach my $method (@{$methods}) { | |||
| 1506 | 474 | 714 | $self->_log("\nAnalyzing method: $method->{name}"); | |||
| 1507 | ||||||
| 1508 | 474 | 602 | my $schema = $self->_analyze_method($method); | |||
| 1509 | 473 | 641 | $schemas{$method->{name}} = $schema; | |||
| 1510 | 473 | 617 | $schema->{'module'} = $package_name; | |||
| 1511 | 473 | 527 | $ctor_body = $method->{body} if($method->{name} eq 'new'); | |||
| 1512 | ||||||
| 1513 | 473 | 680 | my $target = $self->_delegated_method($method->{body}); | |||
| 1514 | 473 | 528 | $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 | 211 | 208 | my $object_stubs = {}; | |||
| 1526 | 211 | 258 | if (exists $schemas{new}) { | |||
| 1527 | 36 104 36 | 25 99 35 | 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 | 36 | 119 | $ctor_body, | |||
| 1532 | ); | |||||
| 1533 | 36 1 36 | 32 3 42 | $self->_log(' STUB: stood in for ' . join(', ', sort keys %{$object_stubs})) if %{$object_stubs}; | |||
| 1534 | ||||||
| 1535 | 36 | 75 | my $ctor_args = $self->_ctor_representative_args($schemas{new}); | |||
| 1536 | 36 | 40 | if (defined $ctor_args) { | |||
| 1537 | 34 | 43 | for my $method_name (keys %schemas) { | |||
| 1538 | 102 | 91 | next if $method_name eq 'new'; | |||
| 1539 | 68 | 42 | my $schema = $schemas{$method_name}; | |||
| 1540 | 68 | 116 | next unless exists $schema->{new} && defined $schema->{new}; | |||
| 1541 | 57 | 37 | $schema->{new} = $ctor_args; | |||
| 1542 | 57 | 62 | $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 | 211 | 364 | if($ctor_body && $schemas{new} | |||
| 1554 | && (my $reason = _constructor_requires_live_objects($ctor_body, $schemas{new}))) { | |||||
| 1555 | 2 2 | 2 3 | $schemas{new}{skip} = $reason unless %{$object_stubs}; | |||
| 1556 | 2 2 | 2 3 | $self->_log(" UNBUILDABLE: new: $reason") unless %{$object_stubs}; | |||
| 1557 | } | |||||
| 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 | 211 | 301 | 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 | 5 5 | 5 15 | $schemas{new}{skip} //= $reason unless %{$object_stubs}; | |||
| 1574 | 5 5 | 5 7 | $self->_log(" UNBUILDABLE: new: $reason") unless %{$object_stubs}; | |||
| 1575 | } | |||||
| 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 | 211 | 283 | 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 | 2 | 3 | $schemas{new}{output} = { _STATUS => 'DIES' }; | |||
| 1587 | 2 | 3 | for my $method_name (keys %schemas) { | |||
| 1588 | 4 | 4 | next if($method_name eq 'new'); | |||
| 1589 | 2 | 3 | my $schema = $schemas{$method_name}; | |||
| 1590 | 2 | 4 | next unless(exists($schema->{new}) && defined($schema->{new})); | |||
| 1591 | 2 | 2 | $schema->{new} = $package_name; | |||
| 1592 | 2 | 2 | $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 | 211 211 | 165 264 | foreach my $method (@{$methods}) { | |||
| 1604 | 473 | 517 | my $schema = $schemas{$method->{name}}; | |||
| 1605 | 473 | 934 | 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 | 473 | 527 | 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. | |||||
| 1620 | 473 | 2560 | if($body =~ /\bmy\s*(?:\(([^)]*)\)|(%\w+))\s*=\s*\@_/s) { | |||
| 1621 | 247 | 215 | my $declared = $1; | |||
| 1622 | 247 | 440 | if(!defined($declared) || ($declared =~ /[\@%]\w+/)) { | |||
| 1623 | 49 | 25 | my @prefix; | |||
| 1624 | 49 | 122 | for my $decl (split(/\s*,\s*/, $declared // '')) { | |||
| 1625 | 92 | 116 | last if($decl =~ /^\s*[\@%]/); | |||
| 1626 | 45 | 143 | push @prefix, $1 if($decl =~ /^\s*\$(?!self\b|class\b)(\w+)/); | |||
| 1627 | } | |||||
| 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 | 49 2 | 73 3 | my %keep = map { $prefix[$_] => $_ } 0 .. $#prefix; | |||
| 1633 | 49 49 | 41 72 | for my $param (keys %{ $schema->{input} // {} }) { | |||
| 1634 | 54 | 34 | my $spec = $schema->{input}{$param}; | |||
| 1635 | 54 | 49 | my $pos = exists($keep{$param}) ? delete($keep{$param}) : $spec->{position}; | |||
| 1636 | 54 | 60 | if(defined($pos) && ($pos < @prefix)) { | |||
| 1637 | 2 | 3 | $spec->{position} = $pos; | |||
| 1638 | 2 | 2 | delete $spec->{named}; | |||
| 1639 | } else { | |||||
| 1640 | 52 | 22 | delete $spec->{position}; | |||
| 1641 | 52 | 53 | $spec->{named} = 1 if @prefix; | |||
| 1642 | } | |||||
| 1643 | } | |||||
| 1644 | } | |||||
| 1645 | } | |||||
| 1646 | ||||||
| 1647 | 473 | 1746 | if($body =~ /\bcroak\b[^;\n]*must be implemented by subclass/) { | |||
| 1648 | 1 | 1 | $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 | 1 | 2 | $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 | 4 | 6 | $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 | 0 | 0 | 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 | 473 | 511 | if(_always_croaks($body)) { | |||
| 1669 | 2 | 3 | $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 | 473 | 726 | if(_keeps_database_handle($body, $method->{pod} // '')) { | |||
| 1677 | 2 | 2 | $schema->{_analysis}{side_effects}{keeps_fd} = 1; | |||
| 1678 | } | |||||
| 1679 | ||||||
| 1680 | 473 | 576 | if(my $skip = _requires_input_file($body, $schema->{input})) { | |||
| 1681 | 3 | 5 | $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 | |||||
| 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 | 473 | 3208 | if((my $pod = $method->{pod} // '') =~ /(?:HASHREF|hashref)\s+of\s*\{|(?:HASHREF|hashref)[^\n]*\bmodel store\b/i) { | |||
| 1693 | 2 | 4 | $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 | 473 | 656 | if((my $pod = $method->{pod} // '') =~ /HASHREF[^\n]*\{[^}]*\bdatabase\b[^}]*\b(?:username|password)\b/i) { | |||
| 1701 | 1 | 2 | $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 | 473 55 | 503 64 | if(ref($schema->{new}) eq 'HASH' && %{$schema->{new}}) { | |||
| 1707 | 9 9 | 7 11 | foreach my $param (keys %{$schema->{new}}) { | |||
| 1708 | 9 | 6 | my $p = quotemeta($param); | |||
| 1709 | # Read directly, or through a local copy of the hashref. | |||||
| 1710 | 9 | 250 | my $reads_keys = ($body =~ /\$self->\{\s*['"]?$p['"]?\s*\}->\{/) | |||
| 1711 | || ($body =~ /my\s+\$(\w+)\s*=\s*\$self->\{\s*['"]?$p['"]?\s*\}/ && $body =~ /\$$1->\{/); | |||||
| 1712 | 9 | 17 | next unless($reads_keys && ($body =~ /\bcroak\b/)); | |||
| 1713 | 2 | 3 | $schema->{new} = $self->{_package_name} if($self->{_package_name}); | |||
| 1714 | 2 | 3 | last; | |||
| 1715 | } | |||||
| 1716 | } | |||||
| 1717 | ||||||
| 1718 | 473 473 | 293 546 | _next_parameter: foreach my $param_name (keys %{$schema->{input} // {}}) { | |||
| 1719 | 403 | 320 | my $spec = $schema->{input}{$param_name}; | |||
| 1720 | 403 | 381 | next unless(ref($spec) eq 'HASH'); | |||
| 1721 | 403 | 308 | my $p = quotemeta($param_name); | |||
| 1722 | ||||||
| 1723 | 403 | 15862 | if($body =~ /ref\(\s*\$args\{\s*['"]?$p['"]?\s*\}\s*\)\s*(?:ne|eq)\s*['"]CODE['"]/ | |||
| 1724 | || $body =~ /\$args\{\s*['"]?$p['"]?\s*\}\s*->\s*\(/) { | |||||
| 1725 | 1 | 1 | $spec->{type} = 'coderef'; | |||
| 1726 | 1 | 2 | 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 | 402 | 9575 | if($body =~ /my\s+\$(\w+)\s*=\s*\$args\{\s*['"]?$p['"]?\s*\}/) { | |||
| 1732 | 4 | 4 | my $var = $1; | |||
| 1733 | 4 | 69 | if($body =~ /[\$%](\w+)\s*\{\s*\$$var\s*\}/) { | |||
| 1734 | 1 | 1 | my $const = $1; | |||
| 1735 | 1 | 4 | my $source = $self->{_document} ? $self->{_document}->serialize : ''; | |||
| 1736 | 1 | 428 | if($source =~ /%$const\s*(?:=|=>)\s*.*?qw\s*[\(\{\[]([^\)\}\]]+)[\)\}\]]/s) { | |||
| 1737 | 1 | 2 | my @values = split(' ', $1); | |||
| 1738 | 1 | 2 | $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 | 402 | 401 | my @accepted; | |||
| 1749 | 402 | 5037 | my @subjects = ( | |||
| 1750 | qr/\$$p\b/, | |||||
| 1751 | qr/\$args\{\s*['"]?$p['"]?\s*\}/, | |||||
| 1752 | ); | |||||
| 1753 | 402 | 413 | foreach my $subject (@subjects) { | |||
| 1754 | 804 | 12316 | while($body =~ /$subject\s*=~\s*\/([^\/\n]+)\//g) { | |||
| 1755 | 16 | 15 | my $pattern = $1; | |||
| 1756 | 16 | 22 | my $at = $-[0]; | |||
| 1757 | 16 | 24 | my $from = rindex($body, ';', $at); | |||
| 1758 | 16 | 14 | $from = 0 if($from < 0); | |||
| 1759 | 16 | 19 | 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 | 16 | 55 | my $accepts = $prefix =~ /\breturn\b[^;]*\bunless\b/ | |||
| 1767 | ? 0 | |||||
| 1768 | : ($prefix =~ /\breturn\b/ || $prefix =~ /\b(?:croak|die|confess)\b[^;]*\bunless\b/); | |||||
| 1769 | 16 | 20 | 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 | 0 | 0 | my $brace = index($body, '{', $+[0]); | |||
| 1773 | 0 | 0 | if($brace >= 0) { | |||
| 1774 | 0 | 0 | my $close = index($body, "\n\t}", $brace); | |||
| 1775 | 0 | 0 | my $block = substr($body, $brace, | |||
| 1776 | (($close >= 0) ? $close - $brace : 400)); | |||||
| 1777 | 0 | 0 | $accepts = ($block =~ /\breturn\b/) ? 1 : 0; | |||
| 1778 | } | |||||
| 1779 | } | |||||
| 1780 | 16 | 17 | next unless($accepts); | |||
| 1781 | # A pattern in a croak's own condition names a rejected | |||||
| 1782 | # value, not an accepted one. | |||||
| 1783 | 14 | 19 | next if($prefix =~ /\b(?:croak|die|confess)\b[^;]*\bif\b/); | |||
| 1784 | 14 | 18 | if(!_pattern_is_self_contained($pattern)) { | |||
| 1785 | 0 | 0 | $self->_log(" CODE: $param_name matches '$pattern', which depends on run-time variables; not recorded"); | |||
| 1786 | 0 | 0 | next; | |||
| 1787 | } | |||||
| 1788 | 14 | 27 | push @accepted, $pattern; | |||
| 1789 | } | |||||
| 1790 | } | |||||
| 1791 | ||||||
| 1792 | 402 | 233 | my $croaks_about_param = 0; | |||
| 1793 | 402 | 282 | foreach my $subject (@subjects) { | |||
| 1794 | 685 | 8227 | next unless($body =~ /\b(?:croak|die|confess)\b[^;]*$subject/s); | |||
| 1795 | 125 | 94 | $croaks_about_param = 1; | |||
| 1796 | 125 | 94 | last; | |||
| 1797 | } | |||||
| 1798 | ||||||
| 1799 | 402 | 235 | my $pattern; | |||
| 1800 | 402 | 10497 | if($body =~ /\$args\{\s*['"]?$p['"]?\s*\}\s*=~\s*\/([^\/\n]+)\//) { | |||
| 1801 | 1 | 1 | $pattern = $1; | |||
| 1802 | } elsif($body =~ /\$$p\b\s*=~\s*\/([^\/\n]+)\//) { | |||||
| 1803 | 13 | 13 | $pattern = $1; | |||
| 1804 | } | |||||
| 1805 | 402 | 1410 | if(@accepted && $croaks_about_param) { | |||
| 1806 | 10 | 8 | my %seen; | |||
| 1807 | 10 12 | 8 24 | @accepted = grep { !$seen{$_}++ } @accepted; | |||
| 1808 | $spec->{matches} = (@accepted == 1) | |||||
| 1809 | ? $accepted[0] | |||||
| 1810 | 10 3 | 20 3 | : join('|', map { "(?:$_)" } @accepted); | |||
| 1811 | 10 | 30 | $spec->{_source} = SOURCE_VALIDATOR; | |||
| 1812 | } elsif(defined($pattern) && _pattern_is_self_contained($pattern) | |||||
| 1813 | && ($body =~ /\bcroak\b[^;\n]*(?:not a valid|invalid)/i)) { | |||||
| 1814 | 0 | 0 | $spec->{matches} = $pattern; | |||
| 1815 | 0 | 0 | $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 | 211 | 365 | if($schemas{new} && $schemas{new}{skip}) { | |||
| 1824 | 7 | 11 | for my $method_name (keys %schemas) { | |||
| 1825 | 15 | 13 | next if($method_name eq 'new'); | |||
| 1826 | 8 | 4 | my $schema = $schemas{$method_name}; | |||
| 1827 | 8 | 11 | next unless(exists($schema->{new}) && defined($schema->{new})); | |||
| 1828 | 3 | 3 | $schema->{new} = $package_name; | |||
| 1829 | 3 | 5 | $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 | 211 | 266 | for my $method_name (sort keys %delegates) { | |||
| 1838 | 3 | 3 | my $target = $delegates{$method_name}; | |||
| 1839 | 3 | 4 | next if $method_name eq $target; | |||
| 1840 | 3 | 3 | my $target_schema = $schemas{$target}; | |||
| 1841 | 3 | 4 | next unless $target_schema; | |||
| 1842 | ||||||
| 1843 | 2 | 2 | my $schema = $schemas{$method_name}; | |||
| 1844 | 2 | 2 | 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 | |||||
| 1849 | # takes arguments. | |||||
| 1850 | 2 2 | 4 3 | if(ref($target_schema->{output}) eq 'HASH' && %{$target_schema->{output}}) { | |||
| 1851 | 2 2 | 2 5 | $schema->{output} = { %{$target_schema->{output}} }; | |||
| 1852 | } | |||||
| 1853 | ||||||
| 1854 | next unless ref($target_schema->{input}) eq 'HASH' | |||||
| 1855 | 2 2 | 6 3 | && scalar(keys %{$target_schema->{input}}); | |||
| 1856 | 1 1 | 2 1 | next if ref($schema->{input}) eq 'HASH' && scalar(keys %{$schema->{input}}); | |||
| 1857 | ||||||
| 1858 | $schema->{input} = { | |||||
| 1859 | 1 1 1 1 | 1 1 2 1 | map { $_ => { %{$target_schema->{input}{$_}} } } sort keys %{$target_schema->{input}} | |||
| 1860 | }; | |||||
| 1861 | $schema->{_confidence}{input} = { | |||||
| 1862 | 1 | 3 | 'level' => 'medium', | |||
| 1863 | 'factors' => [ "Forwarded to $target()" ] | |||||
| 1864 | }; | |||||
| 1865 | 1 1 | 1 1 | push @{$schema->{_notes}}, "input inherited from $target(), which this routine forwards \@_ to"; | |||
| 1866 | 1 | 1 | $self->_log(" DELEGATE: $method_name input inherited from $target"); | |||
| 1867 | } | |||||
| 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 | 211 | 226 | if($self->{_multiple_packages}) { | |||
| 1874 | 1 | 2 | for my $method_name (keys %schemas) { | |||
| 1875 | $schemas{$method_name}{skip} //= | |||||
| 1876 | 1 | 2 | "multi-package file; only the primary package $package_name is extracted"; | |||
| 1877 | } | |||||
| 1878 | } | |||||
| 1879 | ||||||
| 1880 | 211 | 241 | unless ($params->{no_write}) { | |||
| 1881 | 105 | 156 | for my $method_name (keys %schemas) { | |||
| 1882 | 193 | 297 | $self->_write_schema($method_name, $schemas{$method_name}); | |||
| 1883 | } | |||||
| 1884 | } | |||||
| 1885 | ||||||
| 1886 | 211 | 774 | 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 | # | |||||
| 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 | 473 | 456 | my ($self, $code) = @_; | |||
| 1913 | ||||||
| 1914 | 473 | 477 | return unless defined($code); | |||
| 1915 | ||||||
| 1916 | 473 | 1004 | (my $body = $code) =~ s/\A\s*sub\s+\w+\s*//; | |||
| 1917 | 473 | 1811 | $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 | 473 | 702 | 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 | |||||
| 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 | 247 | 2749 | my ($self, $document) = @_; | |||
| 1950 | ||||||
| 1951 | 247 | 733 | if(!defined($document)) { | |||
| 1952 | 33 | 26 | $document = $self->{_document}; | |||
| 1953 | } | |||||
| 1954 | 247 | 586 | my $pkgs = $document->find('PPI::Statement::Package') || []; | |||
| 1955 | 247 | 380836 | if(@$pkgs == 0) { | |||
| 1956 | 9 | 19 | my $package_stmt = $document->find_first('PPI::Statement::Package'); | |||
| 1957 | 9 | 8875 | return $package_stmt ? $package_stmt->namespace() : ''; | |||
| 1958 | } | |||||
| 1959 | 238 | 800 | $self->{_package_name} //= $pkgs->[0]->namespace(); | |||
| 1960 | 238 | 2305 | if(@$pkgs > 1) { | |||
| 1961 | 1 | 2 | $self->{_multiple_packages} = 1; | |||
| 1962 | 1 | 1 | $self->_log(" Multiple packages; analyzing " . $pkgs->[0]->namespace() . " only"); | |||
| 1963 | } | |||||
| 1964 | 238 | 376 | 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 | 509 | 449 | my ($self, $node, $pkgs) = @_; | |||
| 1972 | ||||||
| 1973 | 509 | 973 | return 1 unless($pkgs && @$pkgs > 1); | |||
| 1974 | ||||||
| 1975 | 3 3 | 1 7 | my $loc = eval { $node->location }; | |||
| 1976 | 3 | 1138 | return 1 unless(ref($loc) eq 'ARRAY'); | |||
| 1977 | ||||||
| 1978 | 3 | 1 | my $owner = $pkgs->[0]; | |||
| 1979 | 3 | 2 | for my $pkg (@$pkgs) { | |||
| 1980 | 6 6 | 3 6 | my $pkg_loc = eval { $pkg->location }; | |||
| 1981 | 6 | 29 | next unless(ref($pkg_loc) eq 'ARRAY'); | |||
| 1982 | 6 | 6 | last if($pkg_loc->[0] > $loc->[0]); | |||
| 1983 | 5 | 3 | $owner = $pkg; | |||
| 1984 | } | |||||
| 1985 | ||||||
| 1986 | 3 | 4 | my $primary = $self->{_package_name} // $pkgs->[0]->namespace(); | |||
| 1987 | 3 | 2 | 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 silently | |||||
| 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 | 218 | 25490 | my ($self, $document) = @_; | |||
| 2021 | ||||||
| 2022 | 218 | 253 | my $subs = $document->find('PPI::Statement::Sub') || []; | |||
| 2023 | 218 | 287526 | 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 | 35776 | 187173 | $_[1]->isa('PPI::Statement') | |||
| 2029 | && $_[1]->content =~ /^\s*(?:before|after|around)\b/ | |||||
| 2030 | 218 | 286442 | }) || []; | |||
| 2031 | ||||||
| 2032 | 218 | 1156 | my @methods; | |||
| 2033 | 218 | 236 | foreach my $sub (@$subs) { | |||
| 2034 | 509 | 18476 | my $name = $sub->name(); | |||
| 2035 | ||||||
| 2036 | 509 | 9950 | 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 | 509 | 625 | next unless $self->_in_primary_package($sub, $pkgs); | |||
| 2040 | 507 | 666 | next if $name =~ /^(BEGIN|END|DESTROY|AUTOLOAD|CHECK|INIT|UNITCHECK)$/; | |||
| 2041 | 505 | 479 | next if $name =~ /::/; # cross-package sub (e.g. sub DB::DB { }) | |||
| 2042 | ||||||
| 2043 | # Skip private methods unless explicitly included, or they're special | |||||
| 2044 | 505 | 643 | if ($name =~ /^_/ && $name !~ /^_(new|init|build)/) { | |||
| 2045 | 21 | 29 | next unless $self->{include_private}; | |||
| 2046 | } | |||||
| 2047 | ||||||
| 2048 | # Get the POD before this sub | |||||
| 2049 | 487 | 645 | my $pod = $self->_extract_pod_before($sub); | |||
| 2050 | ||||||
| 2051 | 487 | 589 | push @methods, { | |||
| 2052 | name => $name, | |||||
| 2053 | node => $sub, | |||||
| 2054 | body => $sub->content(), | |||||
| 2055 | pod => $pod, | |||||
| 2056 | type => 'sub', | |||||
| 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 | 218 | 13319 | my $content = $document->content(); | |||
| 2063 | 218 | 37650 | if (@$pkgs <= 1 && $content =~ /\bclass\b/) { | |||
| 2064 | 46 | 80 | $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 | 46 | 718 | (my $code_only = $content) =~ s/^=\w[^\n]*.*?^=cut[^\n]*\n//gms; | |||
| 2070 | 46 | 328 | $code_only =~ s/\s*#[^\n]*//g; | |||
| 2071 | 46 | 94 | $self->_extract_class_methods($code_only, \@methods); | |||
| 2072 | } | |||||
| 2073 | ||||||
| 2074 | # Process method modifiers (Moose) | |||||
| 2075 | 218 | 262 | foreach my $decl (@$sub_decls) { | |||
| 2076 | 0 | 0 | next unless $self->_in_primary_package($decl, $pkgs); | |||
| 2077 | 0 | 0 | my $content = $decl->content; | |||
| 2078 | 0 | 0 | if ($content =~ /^\s*(before|after|around)\s+['"]?(\w+)['"]?\b/) { | |||
| 2079 | 0 | 0 | my ($modifier, $method_name) = ($1, $2); | |||
| 2080 | 0 | 0 | my $full_name = "${modifier}_$method_name"; | |||
| 2081 | ||||||
| 2082 | # Look for the actual sub definition that follows | |||||
| 2083 | 0 | 0 | my $next_sib = $decl->next_sibling; | |||
| 2084 | 0 | 0 | while ($next_sib && !$next_sib->isa('PPI::Statement::Sub')) { | |||
| 2085 | 0 | 0 | $next_sib = $next_sib->next_sibling; | |||
| 2086 | } | |||||
| 2087 | ||||||
| 2088 | 0 | 0 | if ($next_sib && $next_sib->isa('PPI::Statement::Sub')) { | |||
| 2089 | 0 | 0 | my $pod = $self->_extract_pod_before($decl); # POD might be before modifier | |||
| 2090 | 0 | 0 | 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 | 0 | 0 | $self->_log(" Found method modifier: $full_name"); | |||
| 2100 | } | |||||
| 2101 | } | |||||
| 2102 | } | |||||
| 2103 | ||||||
| 2104 | # Prevent silent duplicate method overwrites | |||||
| 2105 | 218 | 171 | my %seen; | |||
| 2106 | @methods = grep { | |||||
| 2107 | 218 488 | 237 329 | my $n = $_->{name}; | |||
| 2108 | 488 | 541 | if ($seen{$n}++) { | |||
| 2109 | 1 | 26 | $self->_log(" WARNING: duplicate method '$n' ignored"); | |||
| 2110 | 1 | 2 | 0; | |||
| 2111 | } else { | |||||
| 2112 | 487 | 440 | 1; | |||
| 2113 | } | |||||
| 2114 | } @methods; | |||||
| 2115 | ||||||
| 2116 | 218 | 352 | 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. | |||||
| 2126 | # | |||||
| 2127 | # Entry: $content - full document source string. | |||||
| 2128 | # $methods - arrayref to push discovered | |||||
| 2129 | # method hashrefs onto | |||||
| 2130 | # (modified in place). | |||||
| 2131 | # | |||||
| 2132 | # Exit: Returns nothing. Appends to $methods. | |||||
| 2133 | # | |||||
| 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 | 47 | 60 | 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 | 47 | 168 | while ($content =~ /class\s+(\w+)\s*\{/g) { | |||
| 2153 | 2 | 2 | my $class_name = $1; | |||
| 2154 | 2 | 3 | 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 | 2 | 5 | require Text::Balanced; | |||
| 2160 | 2 | 6 | my $extracted = Text::Balanced::extract_bracketed(substr($content, $start_pos - 1), '{}'); | |||
| 2161 | ||||||
| 2162 | 2 | 505 | next unless defined $extracted; # unbalanced braces, skip class | |||
| 2163 | ||||||
| 2164 | 2 | 4 | my $class_body = substr($extracted, 1, length($extracted) - 2); | |||
| 2165 | ||||||
| 2166 | 2 | 3 | $self->_log(" Found class $class_name"); | |||
| 2167 | ||||||
| 2168 | # Extract field declarations from class | |||||
| 2169 | 2 | 4 | my $fields = $self->_extract_field_declarations($class_body); | |||
| 2170 | ||||||
| 2171 | # Find methods in the class body | |||||
| 2172 | 2 | 7 | while ($class_body =~ /method\s+(\w+)\s*(\([^)]*\))?\s*\{/g) { | |||
| 2173 | 2 | 4 | my ($method_name, $sig_with_parens) = ($1, $2 || '()'); | |||
| 2174 | ||||||
| 2175 | # Skip private unless configured | |||||
| 2176 | 2 | 5 | if ($method_name =~ /^_/ && $method_name !~ /^_(new|init|build)/) { | |||
| 2177 | 0 | 0 | next unless $self->{include_private}; | |||
| 2178 | } | |||||
| 2179 | ||||||
| 2180 | # Reconstruct as sub for analysis | |||||
| 2181 | 2 | 2 | my $signature = $sig_with_parens; | |||
| 2182 | 2 | 4 | $signature =~ s/^\(//; | |||
| 2183 | 2 | 3 | $signature =~ s/\)$//; | |||
| 2184 | ||||||
| 2185 | # Build a fake sub declaration | |||||
| 2186 | 2 | 3 | my $fake_sub = "sub $method_name($signature) { }"; | |||
| 2187 | ||||||
| 2188 | 2 | 8 | 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 | 2 | 3 | $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, by | |||||
| 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 empty | |||||
| 2219 | # 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 | 489 | 2804 | my ($self, $sub) = @_; | |||
| 2232 | ||||||
| 2233 | 489 489 | 324 895 | my $name = eval { $sub->can('name') ? $sub->name : undef }; | |||
| 2234 | 489 | 6760 | my $pod = ''; | |||
| 2235 | 489 | 686 | my $current = $sub->previous_sibling(); | |||
| 2236 | 489 | 6239 | my $skipped_declaration = 0; | |||
| 2237 | 489 | 304 | my $steps = 0; | |||
| 2238 | ||||||
| 2239 | # Walk backwards collecting POD. | |||||
| 2240 | # 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 | 489 | 1125 | while($current && $steps++ < $POD_WALK_LIMIT) { | |||
| 2243 | 1249 | 9887 | if ($current->isa('PPI::Token::Pod')) { | |||
| 2244 | 240 | 211 | 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 | 240 | 503 | if(!$skipped_declaration | |||
| 2249 | || (defined($name) && $content =~ /^=head[1-6]\s+\Q$name\E\b/m)) { | |||||
| 2250 | 240 | 233 | $pod = $content . $pod; | |||
| 2251 | } | |||||
| 2252 | 240 | 177 | last; # Only take the immediately adjacent pod block | |||
| 2253 | } elsif ($current->isa('PPI::Token::Comment')) { | |||||
| 2254 | # Include comments that might contain parameter info | |||||
| 2255 | 40 | 36 | my $comment = $current->content(); | |||
| 2256 | 40 | 67 | if ($comment =~ /#\s*(?:param|arg|input)\s+\$(\w+)\s*:\s*(.+)/i) { | |||
| 2257 | 0 | 0 | $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/) { | |||||
| 2267 | # A simple file-scoped declaration: the POD is still this | |||||
| 2268 | # routine's documentation. | |||||
| 2269 | 1 | 22 | $skipped_declaration = 1; | |||
| 2270 | } else { | |||||
| 2271 | # Hit non-POD, non-whitespace - stop | |||||
| 2272 | 244 | 193 | last; | |||
| 2273 | } | |||||
| 2274 | 765 | 686 | $current = $current->previous_sibling(); | |||
| 2275 | } | |||||
| 2276 | ||||||
| 2277 | # A POD token can span several routines (and the module-level sections | |||||
| 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 | 489 | 4024 | if($pod && defined($name) && $pod =~ /^=head([1-6])\s+\Q$name\E\b/m) { | |||
| 2282 | 239 | 402 | my ($level, $start) = ($1, $-[0]); | |||
| 2283 | 239 | 608 | my $section = substr($pod, $start); | |||
| 2284 | ||||||
| 2285 | 239 | 322 | my $method_names = {}; | |||
| 2286 | 239 239 | 201 374 | if(my $doc = eval { $sub->document }) { | |||
| 2287 | 239 | 1895 | $method_names = $self->{_pod_method_names}{refaddr($doc)} ||= do { | |||
| 2288 | 138 | 114 | my %names; | |||
| 2289 | 138 | 191 | my $subs = $doc->find('PPI::Statement::Sub'); | |||
| 2290 | 138 138 | 203226 251 | for my $method (@{ $subs || [] }) { | |||
| 2291 | 272 272 | 168 242 | my $method_name = eval { $method->name }; | |||
| 2292 | 272 | 4375 | $names{$method_name} = 1 if defined($method_name); | |||
| 2293 | } | |||||
| 2294 | 138 | 235 | \%names; | |||
| 2295 | }; | |||||
| 2296 | } | |||||
| 2297 | ||||||
| 2298 | 239 | 159 | my $cut; | |||
| 2299 | 239 | 594 | while($section =~ /^=head([1-6])\s+(.+?)\s*$/mg) { | |||
| 2300 | 536 | 491 | my ($heading_level, $title) = ($1, $2); | |||
| 2301 | 536 | 751 | next if($-[0] == 0); # the routine's own heading | |||
| 2302 | 297 | 628 | if($heading_level < $level | |||
| 2303 | || ($heading_level == $level && $method_names->{$title})) { | |||||
| 2304 | 0 | 0 | $cut = $-[0]; | |||
| 2305 | 0 | 0 | last; | |||
| 2306 | } | |||||
| 2307 | } | |||||
| 2308 | 239 | 303 | if(defined($cut)) { | |||
| 2309 | 0 | 0 | $section = substr($section, 0, $cut); | |||
| 2310 | 0 | 0 | $section =~ s/\s+\z//; | |||
| 2311 | } | |||||
| 2312 | 239 | 226 | $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 | 489 | 6423 | if(defined($name) && $pod !~ /^=head[1-6]\s+\Q$name\E\b/m) { | |||
| 2319 | 250 | 313 | my $named = $self->_pod_section_naming_routine($sub, $name); | |||
| 2320 | 250 | 1395881 | $pod = $named if defined($named) && length($named); | |||
| 2321 | } | |||||
| 2322 | ||||||
| 2323 | 489 | 648 | 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. | |||||
| 2332 | # | |||||
| 2333 | # Entry: $sub - the PPI statement for the routine. | |||||
| 2334 | # $name - the routine's name. | |||||
| 2335 | # | |||||
| 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 | 250 | 231 | my ($self, $sub, $name) = @_; | |||
| 2349 | ||||||
| 2350 | 250 250 | 167 318 | my $doc = eval { $sub->document } or return undef; | |||
| 2351 | 250 | 1606 | my $tokens = $doc->find('PPI::Token::Pod') or return undef; | |||
| 2352 | ||||||
| 2353 | 31 78 | 149211 126 | my $text = join('', map { $_->content . "\n" } @$tokens); | |||
| 2354 | ||||||
| 2355 | # Every heading with its offset, so a section runs to the next heading | |||||
| 2356 | # at the same or a higher level. | |||||
| 2357 | 31 | 130 | my @heads; | |||
| 2358 | 31 | 96 | while($text =~ /^=head([1-6])\s+(.+?)\s*$/mg) { | |||
| 2359 | 175 | 341 | push @heads, [ $-[0], $1 + 0, $2 ]; | |||
| 2360 | } | |||||
| 2361 | ||||||
| 2362 | 31 | 43 | for my $i (0 .. $#heads) { | |||
| 2363 | 167 167 | 79 119 | my ($start, $level) = @{ $heads[$i] }; | |||
| 2364 | 167 | 79 | my $end = length($text); | |||
| 2365 | 167 | 124 | for my $j ($i + 1 .. $#heads) { | |||
| 2366 | 240 | 149 | next unless $heads[$j][1] <= $level; | |||
| 2367 | 120 | 74 | $end = $heads[$j][0]; | |||
| 2368 | 120 | 49 | last; | |||
| 2369 | } | |||||
| 2370 | 167 | 122 | 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 | 167 | 1537 | my ($synopsis) = $section =~ /\A(.*?)(?=^=head[3-6]\b|\z)/ms; | |||
| 2380 | 167 | 863 | next unless (($heads[$i][2] // '') =~ /\A\Q$name\E\b/) | |||
| 2381 | || (defined($synopsis) && $synopsis =~ /^\s*\Q$name\E\s*\(/m); | |||||
| 2382 | ||||||
| 2383 | 5 | 23 | $section =~ s/\s+\z//; | |||
| 2384 | 5 | 11 | return $section; | |||
| 2385 | } | |||||
| 2386 | ||||||
| 2387 | 26 | 53 | 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 | |||||
| 2401 | # says a file is created, written, | |||||
| 2402 | # overwritten or updated; 0 otherwise. | |||||
| 2403 | # Side effects: None. | |||||
| 2404 | # Notes: Only the SIDE EFFECTS section is examined. | |||||
| 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 | 476 | 3248 | my ($self, $pod) = @_; | |||
| 2411 | ||||||
| 2412 | 476 | 753 | return 0 unless defined($pod) && length($pod); | |||
| 2413 | ||||||
| 2414 | 242 | 618 | my ($section) = $pod =~ /^=head[1-4]\s+SIDE\s+EFFECTS\b(.*?)(?=^=head[1-4]\b|\z)/mis; | |||
| 2415 | 242 | 396 | return 0 unless defined($section) && length($section); | |||
| 2416 | ||||||
| 2417 | 2 | 7 | return 1 if $section =~ /\b(?:creates?|writes?|rewrites?|overwrites?|updates?)\b[^.\n]*\bfiles?\b/i; | |||
| 2418 | 1 | 2 | return 1 if $section =~ /\bfiles?\b[^.\n]*\b(?:is|are)\s+(?:created|written|rewritten|overwritten|updated)\b/i; | |||
| 2419 | ||||||
| 2420 | 1 | 1 | return 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 | # | |||||
| 2435 | # Entry: $method - a method hashref as produced | |||||
| 2436 | # by _find_methods, containing | |||||
| 2437 | # at minimum: name, body, pod. | |||||
| 2438 | # | |||||
| 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 | 474 | 373 | my ($self, $method) = @_; | |||
| 2462 | 474 | 433 | my $code = $method->{body}; | |||
| 2463 | 474 | 363 | my $pod = $method->{pod}; | |||
| 2464 | ||||||
| 2465 | # Extract modern features | |||||
| 2466 | 474 | 698 | my $attributes = $self->_extract_subroutine_attributes($code); | |||
| 2467 | 474 | 621 | my $postfix_derefs = $self->_analyze_postfix_dereferencing($code); | |||
| 2468 | 474 | 592 | my $fields = $self->_extract_field_declarations($code); | |||
| 2469 | ||||||
| 2470 | # If this method came from a class, use those field declarations | |||||
| 2471 | 474 1 | 548 2 | if ($method->{fields} && keys %{$method->{fields}}) { | |||
| 2472 | 1 | 1 | $fields = $method->{fields}; | |||
| 2473 | } | |||||
| 2474 | ||||||
| 2475 | my $schema = { | |||||
| 2476 | function => $method->{name}, | |||||
| 2477 | 474 | 1293 | _confidence => { | |||
| 2478 | 'input' => {}, | |||||
| 2479 | 'output' => {} | |||||
| 2480 | }, | |||||
| 2481 | input => {}, | |||||
| 2482 | output => {}, | |||||
| 2483 | setup => undef, | |||||
| 2484 | transforms => {}, | |||||
| 2485 | }; | |||||
| 2486 | ||||||
| 2487 | # Analyze different sources | |||||
| 2488 | 474 | 837 | my $pod_params = $self->_analyze_pod($pod, $method->{name}); | |||
| 2489 | 474 | 1050 | 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 | 474 | 612 | $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 | 474 | 571 | $self->_sanitize_parameter_names($pod_params, 'POD analysis'); | |||
| 2498 | 474 | 501 | $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 | 474 | 639 | 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 | 63 | 205 | ignore_self => 1, | |||
| 2510 | allow_renames => 1, | |||||
| 2511 | } | |||||
| 2512 | ); | |||||
| 2513 | ||||||
| 2514 | 63 | 103 | if (@validation_errors) { | |||
| 2515 | 16 | 35 | 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 | 16 | 25 | $schema->{_pod_validation_errors} = \@validation_errors; | |||
| 2520 | ||||||
| 2521 | # Either croak immediately or log based on configuration | |||||
| 2522 | 16 | 35 | if($self->{strict_pod} == $STRICT_POD_FATAL) { | |||
| 2523 | 1 | 14 | croak("[POD STRICT] $error_msg"); | |||
| 2524 | } else { # 1 = warnings | |||||
| 2525 | 15 | 1221 | carp("[POD STRICT] $error_msg"); | |||
| 2526 | # Continue with analysis, but mark as problematic | |||||
| 2527 | 15 | 594 | $schema->{_pod_disagreement} = 1; | |||
| 2528 | } | |||||
| 2529 | } | |||||
| 2530 | 62 | 84 | $schema->{_strict_pod_level} = $self->{strict_pod}; | |||
| 2531 | } | |||||
| 2532 | ||||||
| 2533 | 473 | 675 | my $validator_params = $self->_extract_validator_schema($code); | |||
| 2534 | ||||||
| 2535 | 473 | 466 | if ($validator_params) { | |||
| 2536 | 8 | 11 | $schema->{input} = $validator_params->{input}; | |||
| 2537 | 8 | 11 | $schema->{input_style} = 'hash'; | |||
| 2538 | 8 | 19 | $schema->{_confidence}{input} = { 'factors' => [ 'Determined from validator' ], 'level' => 'high' }; | |||
| 2539 | $schema->{_analysis}{confidence_factors}{input} = [ | |||||
| 2540 | 8 | 17 | '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 | 8 | 13 | for my $name (keys %$pod_params) { | |||
| 2546 | 4 | 5 | next unless ($pod_params->{$name}{_source} // '') eq SOURCE_INPUT_SPEC; | |||
| 2547 | 4 | 2 | my $pod_p = $pod_params->{$name}; | |||
| 2548 | 4 | 4 | $schema->{input}{$name} //= {}; | |||
| 2549 | 4 | 6 | $schema->{input}{$name}{optional} = $pod_p->{optional} if defined $pod_p->{optional}; | |||
| 2550 | 4 | 2 | $schema->{input}{$name}{memberof} = $pod_p->{memberof} if defined $pod_p->{memberof}; | |||
| 2551 | 4 | 4 | $schema->{input}{$name}{matches} = $pod_p->{matches} if defined $pod_p->{matches}; | |||
| 2552 | 4 | 4 | $schema->{input}{$name}{type} = $pod_p->{type} if defined $pod_p->{type}; | |||
| 2553 | 4 | 4 | $schema->{input}{$name}{min} = $pod_p->{min} if defined $pod_p->{min}; | |||
| 2554 | 4 | 4 | $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. | |||||
| 2557 | 4 | 3 | $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 | 4 | 4 | for my $key (qw(min max memberof matches nomatch notmemberof)) { | |||
| 2562 | 24 | 15 | next unless defined $pod_p->{$key}; | |||
| 2563 | 0 | 0 | $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 | 8 8 | 9 29 | $schema->{input}{$_}{_source} //= SOURCE_VALIDATOR for keys %{$schema->{input}}; | |||
| 2572 | } else { | |||||
| 2573 | # Merge field declarations into code_params before merging analyses | |||||
| 2574 | 465 | 520 | if (keys %$fields) { | |||
| 2575 | 1 | 1 | $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 | 465 | 821 | $self->_positional_pod_input($pod_params, $code_params, $code); | |||
| 2582 | ||||||
| 2583 | # Merge analyses | |||||
| 2584 | 465 | 597 | $schema->{input} = $self->_merge_parameter_analyses( | |||
| 2585 | $pod_params, | |||||
| 2586 | $code_params, | |||||
| 2587 | ); | |||||
| 2588 | } | |||||
| 2589 | ||||||
| 2590 | # ---------------------------------------- | |||||
| 2591 | # Legacy Output Analysis (unchanged) | |||||
| 2592 | # ---------------------------------------- | |||||
| 2593 | ||||||
| 2594 | $schema->{output} = $self->_analyze_output( | |||||
| 2595 | $method->{pod}, | |||||
| 2596 | $method->{body}, | |||||
| 2597 | $method->{name} | |||||
| 2598 | 473 | 861 | ); | |||
| 2599 | ||||||
| 2600 | ||||||
| 2601 | # Detect accessor methods | |||||
| 2602 | 473 | 684 | $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 | 473 | 757 | my $needs_object = $self->_needs_object_instantiation($method->{name}, $method->{body}, $method); | |||
| 2607 | 473 | 881 | if($method->{name} ne 'new' && $needs_object) { | |||
| 2608 | 202 | 254 | $schema->{new} = $needs_object; | |||
| 2609 | 202 | 313 | $self->_log(" NEW: Method requires object instantiation: $needs_object"); | |||
| 2610 | } | |||||
| 2611 | ||||||
| 2612 | # Calculate confidences | |||||
| 2613 | 473 | 452 | my $input_confidence = $schema->{_confidence}{'input'}; | |||
| 2614 | 473 | 486 | if(!ref($input_confidence)) { | |||
| 2615 | 0 | 0 | $input_confidence = $schema->{_confidence}{'input'} = $self->_calculate_input_confidence($schema->{input}); | |||
| 2616 | } | |||||
| 2617 | 473 | 771 | my $output_confidence = $schema->{_confidence}{'output'} = $self->_calculate_output_confidence($schema->{output}); | |||
| 2618 | ||||||
| 2619 | # Add metadata | |||||
| 2620 | 473 | 708 | $schema->{_notes} = $self->_generate_notes($schema->{input}); | |||
| 2621 | ||||||
| 2622 | # Add analytics | |||||
| 2623 | 473 | 910 | $schema->{_analysis} ||= {}; | |||
| 2624 | 473 | 512 | $schema->{_analysis}{input_confidence} = $input_confidence->{level}; | |||
| 2625 | 473 | 418 | $schema->{_analysis}{output_confidence} = $output_confidence->{level}; | |||
| 2626 | 473 | 757 | $schema->{_analysis}{confidence_factors} ||= {}; | |||
| 2627 | 473 | 880 | $schema->{_analysis}{confidence_factors}{input} ||= $input_confidence->{factors}; | |||
| 2628 | 473 | 790 | $schema->{_analysis}{confidence_factors}{output} ||= $output_confidence->{factors}; | |||
| 2629 | ||||||
| 2630 | 473 | 383 | foreach my $mode('input', 'output') { | |||
| 2631 | 946 | 868 | $self->_set_defaults($schema, $mode); | |||
| 2632 | } | |||||
| 2633 | ||||||
| 2634 | # Optionally store detailed per-parameter analysis | |||||
| 2635 | 473 | 446 | if ($input_confidence->{per_parameter}) { | |||
| 2636 | 0 | 0 | $schema->{_analysis}{per_parameter_scores} = $input_confidence->{per_parameter}; | |||
| 2637 | } | |||||
| 2638 | ||||||
| 2639 | # Calculate overall confidence (for backward compatibility) | |||||
| 2640 | 473 | 335 | my $input_level = $input_confidence->{level}; | |||
| 2641 | 473 | 310 | my $output_level = $output_confidence->{level}; | |||
| 2642 | ||||||
| 2643 | 473 | 873 | 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 | 473 | 704 | $input_level //= 'none'; | |||
| 2653 | 473 | 385 | $output_level //= 'none'; | |||
| 2654 | 473 | 551 | my $overall = $level_rank{$input_level} < $level_rank{$output_level} ? $input_level : $output_level; | |||
| 2655 | ||||||
| 2656 | 473 | 416 | $schema->{_analysis}{overall_confidence} = $overall; | |||
| 2657 | ||||||
| 2658 | # Analyze parameter relationships | |||||
| 2659 | 473 | 606 | my $relationships = $self->_analyze_relationships($method); | |||
| 2660 | 473 473 | 567 494 | if ($relationships && @{$relationships}) { | |||
| 2661 | 7 | 4 | $schema->{relationships} = $relationships; | |||
| 2662 | 7 | 13 | $self->_log(" Found " . scalar(@$relationships) . " parameter relationships"); | |||
| 2663 | } | |||||
| 2664 | ||||||
| 2665 | # Store modern feature info in schema | |||||
| 2666 | 473 | 492 | $schema->{_attributes} = $attributes if keys %$attributes; | |||
| 2667 | 473 | 464 | $schema->{_modern_features}{postfix_dereferencing} = $postfix_derefs if keys %$postfix_derefs; | |||
| 2668 | 473 | 408 | $schema->{_fields} = $fields if keys %$fields; | |||
| 2669 | ||||||
| 2670 | # Store class info if this is a class method | |||||
| 2671 | 473 | 469 | if ($method->{class}) { | |||
| 2672 | 1 | 1 | $schema->{_class} = $method->{class}; | |||
| 2673 | } | |||||
| 2674 | ||||||
| 2675 | 473 | 685 | my $hints = $self->_extract_test_hints($method, $schema); | |||
| 2676 | 473 | 659 | $self->_extract_pod_examples($pod, $hints); | |||
| 2677 | ||||||
| 2678 | 473 | 438 | for my $k (qw(boundary_values invalid_inputs valid_inputs equivalence_classes)) { | |||
| 2679 | 1892 | 932 | my %seen; | |||
| 2680 | $hints->{$k} = [ | |||||
| 2681 | 122 | 207 | grep { !$seen{ defined $_ ? $_ : '__undef__' }++ } | |||
| 2682 | 1892 1892 | 887 1668 | @{ $hints->{$k} } | |||
| 2683 | ]; | |||||
| 2684 | } | |||||
| 2685 | ||||||
| 2686 | # -------------------------------------------------- | |||||
| 2687 | # YAML test hints: numeric boundaries | |||||
| 2688 | # -------------------------------------------------- | |||||
| 2689 | 473 | 580 | if ($self->_method_has_numeric_intent($schema)) { | |||
| 2690 | 170 | 296 | $schema->{_yamltest_hints} ||= {}; | |||
| 2691 | ||||||
| 2692 | # Do not override existing hints | |||||
| 2693 | 170 | 421 | $schema->{_yamltest_hints}{boundary_values} ||= []; | |||
| 2694 | ||||||
| 2695 | 0 | 0 | my %seen = map { (defined $_ ? $_ : '__undef__') => 1 } | |||
| 2696 | 170 170 | 118 188 | @{ $schema->{_yamltest_hints}{boundary_values} }; | |||
| 2697 | ||||||
| 2698 | 170 170 | 116 181 | foreach my $v (@{ $self->_numeric_boundary_values }) { | |||
| 2699 | 849 | 486 | my $key = defined $v ? $v : '__undef__'; | |||
| 2700 | 849 849 | 730 561 | push @{ $schema->{_yamltest_hints}{boundary_values} }, $v unless $seen{$key}++; | |||
| 2701 | } | |||||
| 2702 | ||||||
| 2703 | 170 | 203 | $self->_log(' HINTS: Added numeric boundary values'); | |||
| 2704 | } | |||||
| 2705 | ||||||
| 2706 | 473 | 461 | if (keys %$hints) { | |||
| 2707 | 473 | 694 | $schema->{_yamltest_hints} ||= {}; | |||
| 2708 | 473 | 462 | foreach my $k (keys %$hints) { | |||
| 2709 | $schema->{_yamltest_hints}{$k} = $hints->{$k} | |||||
| 2710 | 1892 | 1630 | unless exists $schema->{_yamltest_hints}{$k}; | |||
| 2711 | } | |||||
| 2712 | } | |||||
| 2713 | ||||||
| 2714 | 473 | 669 | if(($level_rank{$overall} < $level_rank{$LEVEL_MEDIUM}) && | |||
| 2715 | ($level_rank{$overall} < ($self->{confidence_threshold} * 4))) { | |||||
| 2716 | 392 | 1437 | $schema->{_low_confidence} = 1 | |||
| 2717 | } | |||||
| 2718 | ||||||
| 2719 | # ---------------------------------------- | |||||
| 2720 | # Non-invasive reasoning layer | |||||
| 2721 | # ---------------------------------------- | |||||
| 2722 | ||||||
| 2723 | my $method_model = App::Test::Generator::Model::Method->new( | |||||
| 2724 | name => $method->{name}, | |||||
| 2725 | source => $method->{body}, | |||||
| 2726 | 473 | 1735 | ); | |||
| 2727 | ||||||
| 2728 | 473 | 1092 | my $return_analyzer = App::Test::Generator::Analyzer::Return->new(); | |||
| 2729 | 473 | 673 | $return_analyzer->analyze($method_model); | |||
| 2730 | ||||||
| 2731 | # Let model learn from finalized schema | |||||
| 2732 | 473 | 463 | if ($schema->{output}) { | |||
| 2733 | 473 | 683 | $method_model->absorb_legacy_output($schema->{output}); | |||
| 2734 | } | |||||
| 2735 | ||||||
| 2736 | 473 | 648 | $method_model->resolve_return_type(); | |||
| 2737 | 473 | 629 | $method_model->resolve_classification(); | |||
| 2738 | 473 | 568 | $method_model->resolve_confidence(); | |||
| 2739 | ||||||
| 2740 | # Attach only metadata | |||||
| 2741 | $schema->{_model} = { | |||||
| 2742 | 473 | 574 | classification => $method_model->classification, | |||
| 2743 | confidence => $method_model->confidence, | |||||
| 2744 | }; | |||||
| 2745 | ||||||
| 2746 | # ---------------------------------------- | |||||
| 2747 | # Return Meta Analysis (Non-invasive) | |||||
| 2748 | # ---------------------------------------- | |||||
| 2749 | ||||||
| 2750 | 473 | 1015 | my $meta = App::Test::Generator::Analyzer::ReturnMeta->new(); | |||
| 2751 | 473 | 562 | my $analysis = $meta->analyze($schema); | |||
| 2752 | ||||||
| 2753 | 473 | 431 | $schema->{_analysis}{stability_score} = $analysis->{stability_score}; | |||
| 2754 | 473 | 433 | $schema->{_analysis}{consistency_score} = $analysis->{consistency_score}; | |||
| 2755 | 473 | 386 | $schema->{_analysis}{risk_flags} = $analysis->{risk_flags}; | |||
| 2756 | ||||||
| 2757 | # ---------------------------------------- | |||||
| 2758 | # Side Effect Analysis (Non-invasive) | |||||
| 2759 | # ---------------------------------------- | |||||
| 2760 | ||||||
| 2761 | 473 | 960 | my $se = App::Test::Generator::Analyzer::SideEffect->new(); | |||
| 2762 | ||||||
| 2763 | 473 | 568 | my $effects = $se->analyze($method); | |||
| 2764 | ||||||
| 2765 | 473 | 435 | $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 | 473 | 602 | if($self->_pod_documents_file_write($pod)) { | |||
| 2772 | 0 | 0 | $schema->{_analysis}{side_effects}{writes_file} = 1; | |||
| 2773 | } | |||||
| 2774 | ||||||
| 2775 | # ---------------------------------------- | |||||
| 2776 | # Complexity Analysis (Non-invasive) | |||||
| 2777 | # ---------------------------------------- | |||||
| 2778 | ||||||
| 2779 | 473 | 890 | my $cx = App::Test::Generator::Analyzer::Complexity->new(); | |||
| 2780 | 473 | 535 | my $complexity = $cx->analyze($method); | |||
| 2781 | ||||||
| 2782 | 473 | 448 | $schema->{_analysis}{complexity} = $complexity; | |||
| 2783 | ||||||
| 2784 | 473 | 2560 | 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 | 477 | 397 | my ($self, $schema) = @_; | |||
| 2807 | ||||||
| 2808 | # Numeric output | |||||
| 2809 | 477 | 1551 | return 1 if ($schema->{output} && $schema->{output}{type} && $schema->{output}{type} =~ /^(number|integer)$/); | |||
| 2810 | ||||||
| 2811 | # Numeric inputs | |||||
| 2812 | 323 323 | 205 455 | foreach my $p (values %{ $schema->{input} || {} }) { | |||
| 2813 | 328 | 295 | next if $p->{optional}; | |||
| 2814 | 139 | 389 | return 1 if ($p->{type} && $p->{type} =~ /^(number|integer)$/); | |||
| 2815 | } | |||||
| 2816 | ||||||
| 2817 | 304 | 328 | return 0; | |||
| 2818 | } | |||||
| 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 | # | |||||
| 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 | 170 | 215 | 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 | 478 | 445 | 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. | |||||
| 2881 | 478 | 671 | return if(($method->{name} // '') eq 'new'); | |||
| 2882 | ||||||
| 2883 | 442 | 358 | my $body = $method->{body}; | |||
| 2884 | ||||||
| 2885 | # Normalize whitespace for regex sanity | |||||
| 2886 | 442 | 295 | my $code = $body; | |||
| 2887 | 442 | 1765 | $code =~ s/\s+/ /g; | |||
| 2888 | ||||||
| 2889 | # If a method touches more than one $self->{...}, itâs not an accessor. | |||||
| 2890 | 442 | 314 | my %fields_seen; | |||
| 2891 | 442 | 625 | while ($code =~ /\$self\s*->\s*\{\s*['"]?([^}'"]+)['"]?\s*\}/g) { | |||
| 2892 | 118 | 162 | $fields_seen{$1}++; | |||
| 2893 | } | |||||
| 2894 | 442 | 455 | if (keys(%fields_seen) > 1) { | |||
| 2895 | 5 | 8 | $self->_log(" Skipping accessor detection: multiple fields accessed"); | |||
| 2896 | 5 | 6 | return; | |||
| 2897 | } | |||||
| 2898 | ||||||
| 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 | # ... | |||||
| 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 | 437 | 299 | my $conditional_arg = 0; | |||
| 2910 | 437 | 650 | while($code =~ /\bmy\s+\$(\w+)\s*=\s*shift\b/g) { | |||
| 2911 | 86 | 79 | my $arg = $1; | |||
| 2912 | # The invocant is shifted too, but a test on $self says nothing | |||||
| 2913 | # about whether an argument was supplied. | |||||
| 2914 | 86 | 142 | next if($arg eq 'self'); | |||
| 2915 | 53 | 1625 | if($code =~ /(?:if|unless)\s*\(?\s*(?:defined\s*\(?\s*)?\$\Q$arg\E\b/) { | |||
| 2916 | 24 | 15 | $conditional_arg = 1; | |||
| 2917 | 24 | 25 | 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 | 437 | 543 | my $arg_guard = ($code =~ /\bif\s*\(\s*(?:\@_|scalar\s*\(\s*\@_\s*\))/) ? 1 : 0; | |||
| 2928 | ||||||
| 2929 | # ------------------------------- | |||||
| 2930 | # Getter/Setter combo | |||||
| 2931 | # ------------------------------- | |||||
| 2932 | 437 | 2327 | 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 | 0 | 0 | my $property = $1; | |||
| 2939 | ||||||
| 2940 | 0 | 0 | if(!defined($property)) { | |||
| 2941 | 0 | 0 | if($code =~ /\$self\s*->\s*\{\s*['"]?([^}'"]+)['"]?\s*\}\s*=\s*shift\s*;/) { | |||
| 2942 | 0 | 0 | $property = $1; | |||
| 2943 | } | |||||
| 2944 | } | |||||
| 2945 | ||||||
| 2946 | $schema->{accessor} = { | |||||
| 2947 | 0 | 0 | type => 'getset', | |||
| 2948 | property => $property, | |||||
| 2949 | }; | |||||
| 2950 | ||||||
| 2951 | 0 | 0 | $self->_log(" Detected getter/setter accessor for property: $property"); | |||
| 2952 | ||||||
| 2953 | 0 | 0 | $schema->{input} ||= { value => { type => 'string', optional => 1 } }; | |||
| 2954 | ||||||
| 2955 | 0 | 0 | $schema->{input_style} = 'hash'; | |||
| 2956 | ||||||
| 2957 | $schema->{_confidence}{input} = { | |||||
| 2958 | 0 | 0 | level => 'high', | |||
| 2959 | factors => ['Detected combined getter/setter accessor'], | |||||
| 2960 | }; | |||||
| 2961 | 0 | 0 | if (my $pod = $method->{pod}) { | |||
| 2962 | 0 | 0 | if ($pod =~ /\b(LWP::UserAgent(?:::\w+)*)\b/) { | |||
| 2963 | 0 | 0 | my $class = $1; | |||
| 2964 | $schema->{output} = { | |||||
| 2965 | 0 | 0 | type => 'object', | |||
| 2966 | isa => $class, | |||||
| 2967 | }; | |||||
| 2968 | 0 | 0 | $schema->{input}{$property} = { | |||
| 2969 | type => 'object', | |||||
| 2970 | isa => $class, | |||||
| 2971 | optional => 1, | |||||
| 2972 | }; | |||||
| 2973 | ||||||
| 2974 | $schema->{_confidence}{output} = { | |||||
| 2975 | 0 | 0 | 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 | 9 | 9 | 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 | 9 | 28 | if($conditional_arg && !$arg_guard && | |||
| 2993 | 5 | 9 | (ref($schema->{input}) eq 'HASH') && (scalar(keys %{$schema->{input}}) > 1)) { | |||
| 2994 | 0 | 0 | $self->_log(" Skipping conditional accessor: more than one argument"); | |||
| 2995 | 0 | 0 | return; | |||
| 2996 | } | |||||
| 2997 | ||||||
| 2998 | 9 | 10 | if(!defined($property)) { | |||
| 2999 | 9 | 21 | if($code =~ /\$self\s*->\s*\{\s*['"]?([^}'"]+)['"]?\s*\}\s*=/) { | |||
| 3000 | 9 | 8 | $property = $1; | |||
| 3001 | } | |||||
| 3002 | } | |||||
| 3003 | 9 | 13 | if ($code =~ /validate_strict/) { | |||
| 3004 | 2 2 | 2 2 | push @{ $schema->{_confidence}{input}{factors} }, 'Setter uses Params::Validate::Strict'; | |||
| 3005 | } else { | |||||
| 3006 | # --------------------------------------- | |||||
| 3007 | # Detect object input via blessed($arg) | |||||
| 3008 | # --------------------------------------- | |||||
| 3009 | 7 | 11 | if ($code =~ /blessed\s*\(\s*\$(\w+)\s*\)/) { | |||
| 3010 | 0 | 0 | my $param = $1; | |||
| 3011 | ||||||
| 3012 | 0 | 0 | $self->_log(" Detected object input via blessed(\$$param)"); | |||
| 3013 | ||||||
| 3014 | $schema->{input} = { | |||||
| 3015 | 0 | 0 | $param => { | |||
| 3016 | type => 'object', | |||||
| 3017 | optional => 1, | |||||
| 3018 | } | |||||
| 3019 | }; | |||||
| 3020 | ||||||
| 3021 | $schema->{_confidence}{input} = { | |||||
| 3022 | 0 | 0 | level => 'high', | |||
| 3023 | factors => ['Input validated by Scalar::Util::blessed'], | |||||
| 3024 | }; | |||||
| 3025 | } else { | |||||
| 3026 | # fallback ONLY if nothing known | |||||
| 3027 | $schema->{input} ||= { | |||||
| 3028 | 7 | 10 | value => { type => 'string', optional => 1 }, | |||
| 3029 | }; | |||||
| 3030 | } | |||||
| 3031 | }; | |||||
| 3032 | $schema->{accessor} = { | |||||
| 3033 | 9 | 20 | type => 'getset', | |||
| 3034 | property => $property, | |||||
| 3035 | }; | |||||
| 3036 | ||||||
| 3037 | 9 | 15 | $self->_log(" Detected getter/setter accessor for property: $property"); | |||
| 3038 | 9 | 10 | if (my $pod = $method->{pod}) { | |||
| 3039 | 3 | 6 | if ($pod =~ /\b(LWP::UserAgent(?:::\w+)*)\b/) { | |||
| 3040 | 0 | 0 | my $class = $1; | |||
| 3041 | $schema->{output} = { | |||||
| 3042 | 0 | 0 | type => 'object', | |||
| 3043 | isa => $class, | |||||
| 3044 | }; | |||||
| 3045 | 0 | 0 | $schema->{input}{$property} = { | |||
| 3046 | type => 'object', | |||||
| 3047 | isa => $class, | |||||
| 3048 | optional => 1, | |||||
| 3049 | }; | |||||
| 3050 | ||||||
| 3051 | $schema->{_confidence}{output} = { | |||||
| 3052 | 0 | 0 | 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 | 9 | 12 | if(ref($schema->{input}) eq 'HASH') { | |||
| 3064 | 9 9 | 7 11 | my @input_keys = keys %{$schema->{input}}; | |||
| 3065 | 9 | 15 | if(scalar @input_keys > 1) { | |||
| 3066 | 0 | 0 | croak(__PACKAGE__, ': A getset accessor function can have at most one argument'); | |||
| 3067 | } elsif(@input_keys == 1) { | |||||
| 3068 | 9 | 16 | $schema->{input}{$input_keys[0]}{position} = 0; | |||
| 3069 | } else { | |||||
| 3070 | 0 | 0 | $schema->{input}{$property}{position} = 0; | |||
| 3071 | } | |||||
| 3072 | } | |||||
| 3073 | } elsif ($code =~ /return\s+\$self\s*->\s*\{\s*['"]?([^}'"]+)['"]?\s*\}\s*;/) { | |||||
| 3074 | # ------------------------------- | |||||
| 3075 | # Getter | |||||
| 3076 | # ------------------------------- | |||||
| 3077 | 26 | 31 | 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 | 26 | 917 | if($code !~ /\$self\s*->\s*\{\s*['"]?\Q$property\E['"]?\s*\}\s*=\s*(?:shift|\$\w+\s*=\s*shift|\@_|\$_\[\d+\])/) { | |||
| 3087 | 25 | 61 | my @returns = $code =~ /return\b/g; | |||
| 3088 | 25 | 307 | my @self_returns = $code =~ /return\s+\$self\s*->\s*\{\s*['"]?\Q$property\E['"]?\s*\}/g; | |||
| 3089 | # it's a getter | |||||
| 3090 | 25 | 38 | if (scalar(@returns) == scalar(@self_returns)) { | |||
| 3091 | # all returns are returning $self->{$property}, so it's a getter | |||||
| 3092 | $schema->{accessor} = { | |||||
| 3093 | 23 | 59 | type => 'getter', | |||
| 3094 | property => $property, | |||||
| 3095 | }; | |||||
| 3096 | ||||||
| 3097 | 23 | 43 | $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: | |||||
| 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 | 23 | 29 | $schema->{output} ||= {}; | |||
| 3105 | 23 | 585 | if($code =~ /\$self\s*->\s*\{\s*['"]?\Q$property\E['"]?\s*\}\s*\/\/=\s*\[/) { | |||
| 3106 | 0 | 0 | $schema->{output}{type} = 'arrayref'; | |||
| 3107 | } elsif($code =~ /\$self\s*->\s*\{\s*['"]?\Q$property\E['"]?\s*\}\s*\/\/=\s*\{/) { | |||||
| 3108 | 0 | 0 | $schema->{output}{type} = 'hashref'; | |||
| 3109 | } | |||||
| 3110 | ||||||
| 3111 | $schema->{_confidence}{output} = { | |||||
| 3112 | 23 | 62 | level => 'high', | |||
| 3113 | factors => ['Detected getter method'], | |||||
| 3114 | }; | |||||
| 3115 | 23 | 42 | 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 | 7 | 11 | my ($property, $param) = ($1, $2); | |||
| 3126 | ||||||
| 3127 | $schema->{accessor} = { | |||||
| 3128 | 7 | 20 | type => 'setter', | |||
| 3129 | property => $property, | |||||
| 3130 | param => $param, | |||||
| 3131 | }; | |||||
| 3132 | ||||||
| 3133 | 7 | 13 | $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 | 7 | 5 | my $param_type = 'string'; | |||
| 3145 | 7 | 243 | while($code =~ /\$self\s*->\s*\{\s*['"]?\Q$property\E['"]?\s*\}\s*=\s*([^;]+);/g) { | |||
| 3146 | 8 | 221 | if($1 =~ /(?:->|::)\w+\s*\([^)]*\$\Q$param\E\b/) { | |||
| 3147 | 1 | 1 | $param_type = 'any'; | |||
| 3148 | 1 | 1 | last; | |||
| 3149 | } | |||||
| 3150 | } | |||||
| 3151 | ||||||
| 3152 | $schema->{input} = { | |||||
| 3153 | 7 | 15 | $param => { type => $param_type }, # safe default | |||
| 3154 | }; | |||||
| 3155 | 7 | 11 | $schema->{input_style} = 'hash'; | |||
| 3156 | ||||||
| 3157 | $schema->{_confidence}{input} = { | |||||
| 3158 | 7 | 13 | level => 'high', | |||
| 3159 | factors => ['Detected setter/accessor method'], | |||||
| 3160 | }; | |||||
| 3161 | 7 | 11 | if($schema->{output}{_returns_self}) { | |||
| 3162 | 6 | 10 | if($schema->{output}{type} ne 'object') { | |||
| 3163 | 0 | 0 | croak 'Setter can not return data other than $self'; | |||
| 3164 | } | |||||
| 3165 | 6 | 9 | if($schema->{output}{isa} ne $self->{_package_name}) { | |||
| 3166 | 0 | 0 | croak 'Setter can not return data other than $self'; | |||
| 3167 | } | |||||
| 3168 | 1 | 3 | } elsif(scalar(keys %{$schema->{output}}) != 0) { | |||
| 3169 | $self->_analysis_error( | |||||
| 3170 | method => $method->{name}, | |||||
| 3171 | 0 | 0 | message => "Setter cannot return data", | |||
| 3172 | ); | |||||
| 3173 | } | |||||
| 3174 | } | |||||
| 3175 | ||||||
| 3176 | 437 | 570 | if(exists($schema->{accessor})) { | |||
| 3177 | 39 | 177 | if($schema->{accessor}{type} && $schema->{accessor}{type} =~ /setter|getset/ && $schema->{input}) { | |||
| 3178 | 16 16 | 12 23 | for my $param (keys %{ $schema->{input} }) { | |||
| 3179 | 16 | 16 | my $in = $schema->{input}{$param}; | |||
| 3180 | ||||||
| 3181 | 16 | 34 | if ($in->{type} && ($in->{type} eq 'object')) { | |||
| 3182 | $schema->{output} = { | |||||
| 3183 | type => 'object', | |||||
| 3184 | 2 | 4 | ($in->{isa} ? (isa => $in->{isa}) : ()), | |||
| 3185 | }; | |||||
| 3186 | ||||||
| 3187 | $schema->{_confidence}{output} = { | |||||
| 3188 | 2 | 4 | level => 'high', | |||
| 3189 | factors => ['Output type propagated from setter input'], | |||||
| 3190 | }; | |||||
| 3191 | } | |||||
| 3192 | } | |||||
| 3193 | } | |||||
| 3194 | ||||||
| 3195 | 39 | 242 | if($schema->{accessor}{type} && $schema->{accessor}{property} && ($schema->{accessor}{type} =~ /getter|getset/) && | |||
| 3196 | ((!defined($schema->{output}{type})) || ($schema->{output}{type} eq 'string'))) { | |||||
| 3197 | 28 | 47 | if (my $pod = $method->{pod}) { | |||
| 3198 | # POD says "UserAgent object" | |||||
| 3199 | 12 | 30 | if ($pod =~ /\bUser[- ]?Agent\b.*\bobject\b/i) { | |||
| 3200 | 1 | 1 | $schema->{output}{type} = 'object'; | |||
| 3201 | 1 | 2 | $schema->{output}{isa} = 'LWP::UserAgent'; | |||
| 3202 | ||||||
| 3203 | 1 1 | 1 1 | push @{ $schema->{_confidence}{output}{factors} }, 'POD indicates UserAgent object'; | |||
| 3204 | ||||||
| 3205 | 1 | 2 | $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 | # | |||||
| 3219 | # 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 | 2 | 2560 | my ($self, %args) = @_; | |||
| 3229 | ||||||
| 3230 | 2 | 8 | my $method = $args{method} // 'UNKNOWN'; | |||
| 3231 | 2 | 8 | my $msg = $args{message} // 'Analysis error'; | |||
| 3232 | ||||||
| 3233 | 2 | 5 | my $module = $self->{_package_name} // 'UNKNOWN'; | |||
| 3234 | 2 | 6 | my $file = $self->{input_file} // 'UNKNOWN'; | |||
| 3235 | ||||||
| 3236 | 2 | 31 | 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 | 478 | 407 | my ($self, $code) = @_; | |||
| 3271 | ||||||
| 3272 | 478 | 434 | for my $extractor ('_extract_pvs_schema', '_extract_pv_schema', '_extract_moosex_params_schema', '_extract_type_params_schema') { | |||
| 3273 | 1888 | 2358 | my $res = $self->$extractor($code); | |||
| 3274 | 1888 10 | 4811 24 | return $res if ($res && ref($res) eq 'HASH' && keys %{ $res->{input} || {} }); | |||
| 3275 | } | |||||
| 3276 | ||||||
| 3277 | 468 | 374 | 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 | 1 | 730 | my ($self, $hash) = @_; | |||
| 3303 | ||||||
| 3304 | 1 | 2 | my %result; | |||
| 3305 | ||||||
| 3306 | 1 | 4 | for my $child ($hash->children) { | |||
| 3307 | # skip whitespace and operators | |||||
| 3308 | 1 | 8 | if ($child->isa('PPI::Statement') || $child->isa('PPI::Statement::Expression')) { | |||
| 3309 | 0 | 0 | my ($key, $val); | |||
| 3310 | ||||||
| 3311 | my @tokens = grep { | |||||
| 3312 | 0 0 | 0 0 | !$_->isa('PPI::Token::Whitespace') && | |||
| 3313 | !$_->isa('PPI::Token::Operator') | |||||
| 3314 | } $child->children; | |||||
| 3315 | ||||||
| 3316 | 0 | 0 | for (my $i = 0; $i < @tokens - 1; $i++) { | |||
| 3317 | 0 | 0 | if(($tokens[$i]->isa('PPI::Token::Word') || $tokens[$i]->isa('PPI::Token::Quote')) && | |||
| 3318 | $tokens[$i+1]->isa('PPI::Structure::Constructor')) { | |||||
| 3319 | 0 | 0 | $key = $tokens[$i]->content; | |||
| 3320 | 0 | 0 | $key =~ s/^['"]|['"]$//g; | |||
| 3321 | 0 | 0 | $val = $tokens[$i+1]; | |||
| 3322 | 0 | 0 | last; | |||
| 3323 | } | |||||
| 3324 | } | |||||
| 3325 | ||||||
| 3326 | 0 | 0 | next unless $key && $val; | |||
| 3327 | ||||||
| 3328 | 0 | 0 | my %param; | |||
| 3329 | 0 | 0 | for my $inner ($val->children) { | |||
| 3330 | 0 | 0 | next unless $inner->isa('PPI::Statement') || $inner->isa('PPI::Statement::Expression'); | |||
| 3331 | ||||||
| 3332 | my ($k, undef, $v) = grep { | |||||
| 3333 | 0 0 | 0 0 | !$_->isa('PPI::Token::Whitespace') && | |||
| 3334 | !$_->isa('PPI::Token::Operator') | |||||
| 3335 | } $inner->children; | |||||
| 3336 | ||||||
| 3337 | 0 | 0 | next unless $k && $v; | |||
| 3338 | ||||||
| 3339 | 0 | 0 | my $keyname = $k->content; | |||
| 3340 | 0 | 0 | my $value = $v->can('content') ? $v->content : undef; | |||
| 3341 | 0 | 0 | $value =~ s/^['"]|['"]$//g if defined $value; | |||
| 3342 | ||||||
| 3343 | 0 | 0 | if ($keyname eq 'type') { | |||
| 3344 | 0 | 0 | $param{type} = lc($value); | |||
| 3345 | } elsif ($keyname eq 'optional') { | |||||
| 3346 | 0 | 0 | $param{optional} = $value ? 1 : 0; | |||
| 3347 | } elsif ($keyname =~ /^(min|max)$/ && looks_like_number($value)) { | |||||
| 3348 | 0 | 0 | $param{$keyname} = 0 + $value; | |||
| 3349 | } elsif ($keyname eq 'matches') { | |||||
| 3350 | 0 | 0 | $param{matches} = qr/$value/; | |||
| 3351 | } | |||||
| 3352 | } | |||||
| 3353 | ||||||
| 3354 | 0 | 0 | $param{type} //= 'string'; | |||
| 3355 | 0 | 0 | $param{optional} //= 0; | |||
| 3356 | ||||||
| 3357 | 0 | 0 | $result{$key} = \%param; | |||
| 3358 | } | |||||
| 3359 | } | |||||
| 3360 | ||||||
| 3361 | return { | |||||
| 3362 | 1 | 5 | 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 | ||||||
| 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 already | |||||
| 3389 | # supports find(). | |||||
| 3390 | # | |||||
| 3391 | # Side effects: Populates $self->{_ppi_cache}. | |||||
| 3392 | # -------------------------------------------------- | |||||
| 3393 | sub _ppi { | |||||
| 3394 | 33 | 4679 | my ($self, $code) = @_; | |||
| 3395 | ||||||
| 3396 | 33 | 163 | return $code if ref($code) && $code->can('find'); | |||
| 3397 | ||||||
| 3398 | 32 | 68 | $self->{_ppi_cache} ||= {}; | |||
| 3399 | 32 | 129 | 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 | 486 | 410 | my ($self, $code) = @_; | |||
| 3421 | ||||||
| 3422 | 486 | 1099 | return unless $code =~ /\bvalidate_strict\s*\(/; | |||
| 3423 | ||||||
| 3424 | 13 | 20 | my $doc = $self->_ppi($code) or return; | |||
| 3425 | ||||||
| 3426 | my $calls = $doc->find(sub { | |||||
| 3427 | 1728 | 5994 | $_[1]->isa('PPI::Token::Word') && ($_[1]->content eq 'validate_strict' || $_[1]->content eq 'Params::Validate::Strict::validate_strict') | |||
| 3428 | 13 | 57891 | }) or return; | |||
| 3429 | ||||||
| 3430 | 13 | 83 | for my $call (@$calls) { | |||
| 3431 | 13 | 33 | my $list = $call->parent(); | |||
| 3432 | 13 | 200 | while ($list && !$list->isa('PPI::Structure::List')) { | |||
| 3433 | 60 | 248 | $list = $list->parent(); | |||
| 3434 | } | |||||
| 3435 | 13 | 31 | if(!defined($list)) { | |||
| 3436 | 13 | 26 | my $next = $call->next_sibling(); | |||
| 3437 | 13 | 246 | next unless defined $next; | |||
| 3438 | 13 | 14 | if($next->content() =~ /schema\s*=>\s*(\{(?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*\})/s) { | |||
| 3439 | 11 | 1216 | my $schema_text = $1; | |||
| 3440 | 11 | 27 | next if $schema_text =~ $UNSAFE_KEYWORD_RE; | |||
| 3441 | 11 | 87 | my $compartment = Safe->new(); | |||
| 3442 | 11 | 3818 | $compartment->permit_only(qw(:base_core :base_mem :base_orig)); | |||
| 3443 | ||||||
| 3444 | 11 | 42 | my $schema_str = "my \$schema = $schema_text"; | |||
| 3445 | 11 | 25 | my $schema = $compartment->reval($schema_str); | |||
| 3446 | 11 | 2586 | if($self->_usable_validator_schema($schema)) { | |||
| 3447 | return { | |||||
| 3448 | 10 | 34 | input => $schema, | |||
| 3449 | style => 'hash', | |||||
| 3450 | source => SOURCE_VALIDATOR | |||||
| 3451 | } | |||||
| 3452 | } | |||||
| 3453 | } | |||||
| 3454 | } | |||||
| 3455 | 3 | 110 | next unless $list; | |||
| 3456 | ||||||
| 3457 | 0 0 | 0 0 | my ($schema_block) = grep { $_->isa('PPI::Structure::Block') } $list->children; | |||
| 3458 | ||||||
| 3459 | 0 | 0 | next unless $schema_block; | |||
| 3460 | ||||||
| 3461 | 0 | 0 | my $schema = $self->_extract_schema_hash_from_block($schema_block); | |||
| 3462 | 0 | 0 | return $self->_normalize_validator_schema($schema) if $schema; | |||
| 3463 | } | |||||
| 3464 | ||||||
| 3465 | 3 | 4 | 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 | # | |||||
| 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 | # | |||||
| 3482 | # Side effects: None. | |||||
| 3483 | # -------------------------------------------------- | |||||
| 3484 | sub _extract_pv_schema { | |||||
| 3485 | 481 | 443 | my ($self, $code) = @_; | |||
| 3486 | ||||||
| 3487 | 481 | 633 | return unless $code =~ /\bvalidate\s*\(/; | |||
| 3488 | ||||||
| 3489 | 8 | 12 | my $doc = $self->_ppi($code) or return; | |||
| 3490 | ||||||
| 3491 | my $calls = $doc->find(sub { | |||||
| 3492 | 689 | 2443 | $_[1]->isa('PPI::Token::Word') && ($_[1]->content eq 'validate' || $_[1]->content eq 'Params::Validate::validate') | |||
| 3493 | 8 | 23988 | }) or return; | |||
| 3494 | ||||||
| 3495 | 8 | 45 | for my $call (@$calls) { | |||
| 3496 | 8 | 11 | my $list = $call->parent; | |||
| 3497 | 8 | 112 | while ($list && !$list->isa('PPI::Structure::List')) { | |||
| 3498 | 30 | 116 | $list = $list->parent; | |||
| 3499 | } | |||||
| 3500 | 8 | 15 | if(!defined($list)) { | |||
| 3501 | 8 | 107 | my $next = $call->next_sibling(); | |||
| 3502 | 8 | 151 | my ($arglist, $schema_text) = $self->_parse_pv_call($next); | |||
| 3503 | ||||||
| 3504 | 8 | 21 | if($schema_text && $schema_text !~ $UNSAFE_KEYWORD_RE) { | |||
| 3505 | 8 | 48 | my $compartment = Safe->new(); | |||
| 3506 | 8 | 2507 | $compartment->permit_only(qw(:base_core :base_mem :base_orig)); | |||
| 3507 | ||||||
| 3508 | 8 | 25 | my $schema_str = "my \$schema = $schema_text"; | |||
| 3509 | 8 | 12 | my $schema = $compartment->reval($schema_str); | |||
| 3510 | ||||||
| 3511 | 8 | 1722 | if($self->_usable_validator_schema($schema)) { | |||
| 3512 | 7 7 | 5 6 | foreach my $arg(keys %{$schema}) { | |||
| 3513 | 12 | 9 | my $field = $schema->{$arg}; | |||
| 3514 | 12 | 10 | if(my $type = $field->{'type'}) { | |||
| 3515 | 12 | 15 | if($type eq 'ARRAYREF') { | |||
| 3516 | 1 | 1 | $field->{'type'} = 'arrayref'; | |||
| 3517 | } elsif($type eq 'SCALAR') { | |||||
| 3518 | 11 | 6 | $field->{'type'} = 'string'; | |||
| 3519 | } | |||||
| 3520 | } | |||||
| 3521 | 12 | 19 | delete $field->{'callbacks'}; | |||
| 3522 | } | |||||
| 3523 | ||||||
| 3524 | return { | |||||
| 3525 | 7 | 18 | input => $schema, | |||
| 3526 | style => 'hash', | |||||
| 3527 | source => SOURCE_VALIDATOR | |||||
| 3528 | } | |||||
| 3529 | } | |||||
| 3530 | } | |||||
| 3531 | } | |||||
| 3532 | 1 | 43 | next unless $list; | |||
| 3533 | ||||||
| 3534 | 0 0 | 0 0 | my ($schema_block) = grep { $_->isa('PPI::Structure::Block') } $list->children; | |||
| 3535 | ||||||
| 3536 | 0 | 0 | next unless $schema_block; | |||
| 3537 | ||||||
| 3538 | 0 | 0 | my $schema = $self->_extract_schema_hash_from_block($schema_block); | |||
| 3539 | 0 | 0 | return $self->_normalize_validator_schema($schema) if $schema; | |||
| 3540 | } | |||||
| 3541 | ||||||
| 3542 | 1 | 1 | return; | |||
| 3543 | } | |||||
| 3544 | ||||||
| 3545 | # -------------------------------------------------- | |||||
| 3546 | # _parse_pv_call | |||||
| 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 | 21 | 20 | my ($self, $string) = @_; | |||
| 3566 | ||||||
| 3567 | # Remove outer parentheses and whitespace | |||||
| 3568 | 21 | 29 | $string =~ s/^\s*\(\s*//; | |||
| 3569 | 21 | 2008 | $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 | 21 | 708 | require Text::Balanced; | |||
| 3575 | 21 | 6173 | my $rest = $string; | |||
| 3576 | 21 | 13 | my $comma_pos = 0; | |||
| 3577 | 21 | 16 | my $found_comma = 0; | |||
| 3578 | ||||||
| 3579 | 21 | 23 | while (length $rest) { | |||
| 3580 | 93 | 68 | 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 | 1 | 3 | my $extracted = Text::Balanced::extract_bracketed($rest, '{}'); | |||
| 3584 | 1 | 120 | return unless defined $extracted; # Broken source code | |||
| 3585 | 1 | 1 | $comma_pos += length $extracted; | |||
| 3586 | 1 | 1 | next; | |||
| 3587 | } | |||||
| 3588 | 92 | 65 | if (substr($rest, 0, 1) eq ',') { | |||
| 3589 | 20 | 10 | $found_comma = 1; | |||
| 3590 | 20 | 15 | last; | |||
| 3591 | } | |||||
| 3592 | 72 | 32 | $comma_pos++; | |||
| 3593 | 72 | 49 | $rest = substr($rest, 1); | |||
| 3594 | } | |||||
| 3595 | ||||||
| 3596 | 21 | 22 | return unless $found_comma; | |||
| 3597 | ||||||
| 3598 | 20 | 12 | my $first_arg = substr($string, 0, $comma_pos); | |||
| 3599 | 20 | 19 | my $hash_str = substr($string, $comma_pos + 1); | |||
| 3600 | ||||||
| 3601 | # Trim whitespace | |||||
| 3602 | 20 | 31 | $first_arg =~ s/^\s+|\s+$//g; | |||
| 3603 | 20 | 118 | $hash_str =~ s/^\s+|\s+$//g; | |||
| 3604 | ||||||
| 3605 | 20 | 26 | 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 | # | |||||
| 3623 | # Side effects: None. | |||||
| 3624 | # -------------------------------------------------- | |||||
| 3625 | sub _extract_moosex_params_schema | |||||
| 3626 | { | |||||
| 3627 | 480 | 434 | my ($self, $code) = @_; | |||
| 3628 | ||||||
| 3629 | 480 | 641 | return unless $code =~ /\bvalidated_hash\s*\(/; | |||
| 3630 | ||||||
| 3631 | 9 | 11 | my $doc = $self->_ppi($code) or return; | |||
| 3632 | ||||||
| 3633 | my $calls = $doc->find(sub { | |||||
| 3634 | 742 | 2499 | $_[1]->isa('PPI::Token::Word') && ($_[1]->content eq 'validated_hash') | |||
| 3635 | 9 | 24948 | }) or return; | |||
| 3636 | ||||||
| 3637 | 9 | 46 | for my $call (@$calls) { | |||
| 3638 | 9 | 15 | my $list = $call->parent(); | |||
| 3639 | 9 | 171 | while ($list && !$list->isa('PPI::Structure::List')) { | |||
| 3640 | 36 | 181 | $list = $list->parent; | |||
| 3641 | } | |||||
| 3642 | 9 | 26 | if(!defined($list)) { | |||
| 3643 | 9 | 14 | my $next = $call->next_sibling(); | |||
| 3644 | 9 | 207 | my ($arglist, $schema_text) = $self->_parse_pv_call($next); | |||
| 3645 | ||||||
| 3646 | 9 | 23 | if($schema_text && $schema_text !~ $UNSAFE_KEYWORD_RE) { | |||
| 3647 | 9 | 53 | my $compartment = Safe->new(); | |||
| 3648 | 9 | 2780 | $compartment->permit_only(qw(:base_core :base_mem :base_orig)); | |||
| 3649 | ||||||
| 3650 | 9 | 25 | my $schema_str = "my \$schema = { $schema_text }"; | |||
| 3651 | 9 | 22 | $schema_str =~ s/ArrayRef\[(.+?)\]/arrayref, element_type => $1/g; | |||
| 3652 | 9 | 11 | my $schema = $compartment->reval($schema_str); | |||
| 3653 | ||||||
| 3654 | 9 | 1945 | if($self->_usable_validator_schema($schema)) { | |||
| 3655 | 9 9 | 8 6 | foreach my $arg(keys %{$schema}) { | |||
| 3656 | 14 | 11 | my $field = $schema->{$arg}; | |||
| 3657 | 14 | 13 | if(my $isa = delete $field->{'isa'}) { | |||
| 3658 | 14 | 13 | $field->{'type'} = $isa; | |||
| 3659 | } | |||||
| 3660 | 14 | 13 | if(exists($field->{'required'})) { | |||
| 3661 | 11 | 6 | my $required = delete $field->{'required'}; | |||
| 3662 | 11 | 16 | $field->{'optional'} = $required ? 0 : 1; | |||
| 3663 | } else { | |||||
| 3664 | 3 | 2 | $field->{'optional'} = 1; | |||
| 3665 | } | |||||
| 3666 | 14 | 14 | if(ref($field->{'default'}) eq 'CODE') { | |||
| 3667 | 2 | 21 | delete $field->{'default'}; # TODO | |||
| 3668 | } | |||||
| 3669 | } | |||||
| 3670 | ||||||
| 3671 | 9 9 | 8 7 | foreach my $arg(keys %{$schema}) { | |||
| 3672 | 14 | 11 | my $field = $schema->{$arg}; | |||
| 3673 | 14 | 8 | if(my $type = $field->{'type'}) { | |||
| 3674 | 14 | 17 | if($type eq 'ARRAYREF') { | |||
| 3675 | 0 | 0 | $field->{'type'} = 'arrayref'; | |||
| 3676 | } elsif($type eq 'SCALAR') { | |||||
| 3677 | 0 | 0 | $field->{'type'} = 'string'; | |||
| 3678 | } | |||||
| 3679 | } | |||||
| 3680 | 14 | 10 | delete $field->{'callbacks'}; | |||
| 3681 | } | |||||
| 3682 | ||||||
| 3683 | return { | |||||
| 3684 | 9 | 21 | input => $schema, | |||
| 3685 | style => 'hash', | |||||
| 3686 | source => SOURCE_VALIDATOR | |||||
| 3687 | } | |||||
| 3688 | } | |||||
| 3689 | } | |||||
| 3690 | } | |||||
| 3691 | 0 | 0 | next unless $list; | |||
| 3692 | ||||||
| 3693 | 0 0 | 0 0 | my ($schema_block) = grep { $_->isa('PPI::Structure::Block') } $list->children; | |||
| 3694 | ||||||
| 3695 | 0 | 0 | next unless $schema_block; | |||
| 3696 | ||||||
| 3697 | 0 | 0 | my $schema = $self->_extract_schema_hash_from_block($schema_block); | |||
| 3698 | 0 | 0 | return $self->_normalize_validator_schema($schema) if $schema; | |||
| 3699 | } | |||||
| 3700 | ||||||
| 3701 | 0 | 0 | return; | |||
| 3702 | } | |||||
| 3703 | ||||||
| 3704 | # -------------------------------------------------- | |||||
| 3705 | # _extract_schema_hash_from_block | |||||
| 3706 | # | |||||
| 3707 | # Purpose: Extract a parameter schema hashref from | |||||
| 3708 | # a PPI::Structure::Block node representing | |||||
| 3709 | # the schema argument to a validator call | |||||
| 3710 | # such as validate_strict({ ... }). | |||||
| 3711 | # | |||||
| 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 | 2 | 5 | my ($self, $block) = @_; | |||
| 3726 | ||||||
| 3727 | 2 | 8 | return unless $block && $block->can('children'); | |||
| 3728 | ||||||
| 3729 | 0 | 0 | my $result = $self->_parse_schema_hash($block); | |||
| 3730 | ||||||
| 3731 | 0 | 0 | return unless $result && ref($result) eq 'HASH' && $result->{input}; | |||
| 3732 | ||||||
| 3733 | 0 | 0 | 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. | |||||
| 3744 | # | |||||
| 3745 | # Entry: $schema - value returned by | |||||
| 3746 | # Safe->reval() on the schema | |||||
| 3747 | # text found in the call. | |||||
| 3748 | # | |||||
| 3749 | # Exit: Returns true when the schema is a | |||||
| 3750 | # 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 }, | |||||
| 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 | 28 | 26 | my ($self, $schema) = @_; | |||
| 3774 | ||||||
| 3775 | 28 | 39 | return 0 unless ref($schema) eq 'HASH'; | |||
| 3776 | ||||||
| 3777 | 27 | 31 | my @names = keys %$schema; | |||
| 3778 | 27 | 29 | return 0 unless @names; | |||
| 3779 | ||||||
| 3780 | 27 | 23 | for my $name (@names) { | |||
| 3781 | 45 | 37 | return 0 unless length($name); | |||
| 3782 | 44 | 48 | return 0 unless ref($schema->{$name}) eq 'HASH'; | |||
| 3783 | } | |||||
| 3784 | ||||||
| 3785 | 26 | 35 | 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 | 5 | 15 | my ($self, $schema) = @_; | |||
| 3812 | ||||||
| 3813 | 5 | 3 | my %input; | |||
| 3814 | ||||||
| 3815 | 5 | 5 | for my $name (keys %$schema) { | |||
| 3816 | 8 | 6 | my $spec = $schema->{$name}; | |||
| 3817 | ||||||
| 3818 | $input{$name} = { | |||||
| 3819 | %$spec, | |||||
| 3820 | 8 | 15 | optional => exists $spec->{optional} ? $spec->{optional} : 0, | |||
| 3821 | _source => SOURCE_VALIDATOR, | |||||
| 3822 | _type_confidence => 'high', | |||||
| 3823 | }; | |||||
| 3824 | } | |||||
| 3825 | ||||||
| 3826 | return { | |||||
| 3827 | 5 | 7 | 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 | 471 | 3816 | my ($self, $code) = @_; | |||
| 3854 | ||||||
| 3855 | 471 | 567 | my $function = $self->_extract_function_name($code) or return; | |||
| 3856 | ||||||
| 3857 | 470 | 838 | my $doc = $self->{_document} or return; | |||
| 3858 | 467 | 584 | my $stmt = $self->_find_signature_statement($doc, $function) or return; | |||
| 3859 | ||||||
| 3860 | 2 | 9 | my $signature_expr = $self->_extract_signature_expression($stmt, $function) or return; | |||
| 3861 | ||||||
| 3862 | 2 | 8 | my $meta = $self->_compile_signature_isolated($function, $signature_expr) or return; | |||
| 3863 | ||||||
| 3864 | 1 | 4 | 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 | 472 | 1344 | my ($self, $code) = @_; | |||
| 3884 | 472 | 1257 | return $1 if $code =~ /^\s*sub\s+([a-zA-Z0-9_]+)/; | |||
| 3885 | 3 | 6 | return; | |||
| 3886 | } | |||||
| 3887 | ||||||
| 3888 | # -------------------------------------------------- | |||||
| 3889 | # _find_signature_statement | |||||
| 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. | |||||
| 3896 | # $function - function name string. | |||||
| 3897 | # | |||||
| 3898 | # Exit: Returns the matching PPI::Statement | |||||
| 3899 | # node, or undef if none is found. | |||||
| 3900 | # | |||||
| 3901 | # Side effects: None. | |||||
| 3902 | # -------------------------------------------------- | |||||
| 3903 | sub _find_signature_statement { | |||||
| 3904 | 467 | 3476 | my ($self, $doc, $function) = @_; | |||
| 3905 | ||||||
| 3906 | my $statements = $doc->find( | |||||
| 3907 | sub { | |||||
| 3908 | 278230 | 1346053 | $_[1]->isa('PPI::Statement') && $_[1]->content =~ /^\s*signature_for\b/ | |||
| 3909 | } | |||||
| 3910 | 467 | 1407 | ) or return; | |||
| 3911 | ||||||
| 3912 | 2 | 13 | foreach my $stmt (@$statements) { | |||
| 3913 | 2 | 3 | my $content = $stmt->content; | |||
| 3914 | 2 | 104 | if ($content =~ /^\s*signature_for\s+\Q$function\E\b/) { | |||
| 3915 | 2 | 4 | return $stmt; | |||
| 3916 | } | |||||
| 3917 | } | |||||
| 3918 | ||||||
| 3919 | 0 | 0 | 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. | |||||
| 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 | |||||
| 3935 | # does not match. | |||||
| 3936 | # | |||||
| 3937 | # Side effects: None. | |||||
| 3938 | # -------------------------------------------------- | |||||
| 3939 | sub _extract_signature_expression { | |||||
| 3940 | 3 | 1793 | my ($self, $stmt, $function) = @_; | |||
| 3941 | ||||||
| 3942 | 3 | 4 | my $content = $stmt->content; | |||
| 3943 | ||||||
| 3944 | 3 | 135 | if ($content =~ /^\s*signature_for\s+\Q$function\E\s*=>\s*(.+?);?\s*$/s) { | |||
| 3945 | 2 | 4 | return $1; | |||
| 3946 | } | |||||
| 3947 | ||||||
| 3948 | 1 | 1 | return; | |||
| 3949 | } | |||||
| 3950 | ||||||
| 3951 | # -------------------------------------------------- | |||||
| 3952 | # _compile_signature_isolated | |||||
| 3953 | # | |||||
| 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 code | |||||
| 3968 | # path in this module is static (PPI-only) | |||||
| 3969 | # analysis that never runs the target's | |||||
| 3970 | # code, so this one feature must be opted | |||||
| 3971 | # 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. | |||||
| 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. | |||||
| 3987 | # | |||||
| 3988 | # Entry: $function - function name string. | |||||
| 3989 | # $signature_expr - Type::Params | |||||
| 3990 | # 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. | |||||
| 4004 | # Memory limiting is best-effort and | |||||
| 4005 | # silently skipped on platforms where | |||||
| 4006 | # BSD::Resource is unavailable. | |||||
| 4007 | # -------------------------------------------------- | |||||
| 4008 | sub _compile_signature_isolated { | |||||
| 4009 | 10 | 9460 | my ($self, $function, $signature_expr) = @_; | |||
| 4010 | ||||||
| 4011 | 10 | 34 | 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 | 2 | 3 | if $self->{verbose}; | |||
| 4016 | 2 | 3 | return; | |||
| 4017 | } | |||||
| 4018 | ||||||
| 4019 | # Remove comments | |||||
| 4020 | 8 | 25 | $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 | 8 | 21 | if ($signature_expr =~ $UNSAFE_KEYWORD_RE || $signature_expr =~ $UNSAFE_CHAR_RE) { | |||
| 4030 | 0 | 0 | croak 'Unsafe signature expression -- rejected to prevent code execution'; | |||
| 4031 | } | |||||
| 4032 | ||||||
| 4033 | 8 | 110 | 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 than | |||||
| 4057 | # the signature object, so ->parameters() would die. | |||||
| 4058 | my @sig_params = (defined $sig && ref $sig && $sig->can('parameters')) | |||||
| 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, | |||||
| 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', | |||||
| 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 | 8 | 32 | $payload =~ s/FUNCTION_NAME/$function/g; | |||
| 4108 | 8 | 27 | $payload =~ s/SIGNATURE_EXPR/$signature_expr/; | |||
| 4109 | ||||||
| 4110 | # Run in an isolated Perl process | |||||
| 4111 | 8 | 194 | my ($wtr, $rdr, $err) = (undef, undef, gensym); | |||
| 4112 | 8 | 110 | 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 | |||||
| 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. | |||||
| 4120 | 8 | 28 | $ENV{_ATG_RLIMIT_AS} = $MEMORY_LIMIT_BYTES; | |||
| 4121 | ||||||
| 4122 | 8 | 45 | my $pid = open3($wtr, $rdr, $err, $^X, '-T'); | |||
| 4123 | ||||||
| 4124 | 8 | 31970 | print $wtr $payload; | |||
| 4125 | 8 | 67 | close $wtr; | |||
| 4126 | ||||||
| 4127 | 8 0 | 1374 0 | local $SIG{ALRM} = sub { croak 'Signature compile timeout' }; | |||
| 4128 | 8 8 | 32 93 | eval { alarm($SIGNATURE_TIMEOUT_SECS) }; # no-op on Windows | |||
| 4129 | ||||||
| 4130 | 8 8 8 | 65 60 56 | my $stdout = do { local $/; <$rdr> }; | |||
| 4131 | 8 8 8 | 19 24 36 | my $stderr = do { local $/; <$err> }; | |||
| 4132 | ||||||
| 4133 | 8 8 | 22 27 | eval { alarm 0 }; | |||
| 4134 | ||||||
| 4135 | 8 | 5485 | waitpid($pid, 0); | |||
| 4136 | ||||||
| 4137 | 8 | 78 | if ($stderr && length $stderr) { | |||
| 4138 | 1 | 8 | carp "Error compiling signature:\n$stderr" if $self->{verbose}; | |||
| 4139 | 1 | 104 | return; | |||
| 4140 | } | |||||
| 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 | 7 | 88 | if (!defined($stdout) || !length($stdout)) { | |||
| 4146 | 4 | 54 | carp 'Signature subprocess produced no output' if $self->{verbose}; | |||
| 4147 | 4 | 458 | return; | |||
| 4148 | } | |||||
| 4149 | ||||||
| 4150 | 3 3 | 16 54 | my $result = eval { decode_json($stdout) }; | |||
| 4151 | 3 | 24 | if ($@) { | |||
| 4152 | 3 | 14 | carp "Error decoding signature output: $@" if $self->{verbose}; | |||
| 4153 | 3 | 307 | return; | |||
| 4154 | } | |||||
| 4155 | 0 | 0 | return $result; | |||
| 4156 | } | |||||
| 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 compile | |||||
| 4170 | # 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 | # | |||||
| 4178 | # 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 | 8 | 32 | my ($self, $meta) = @_; | |||
| 4184 | ||||||
| 4185 | 8 | 19 | 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 | 8 | 3 | my $input; | |||
| 4196 | 8 | 6 | my $position = 0; | |||
| 4197 | 8 | 5 | my $confidence = 'high'; | |||
| 4198 | 8 | 8 | my @notes = ('Type::Params detected'); | |||
| 4199 | ||||||
| 4200 | 8 8 | 4 10 | foreach my $p (@{ $meta->{parameters} || [] }) { | |||
| 4201 | 8 | 11 | my $type = $type_map{ $p->{type} } // 'string'; | |||
| 4202 | ||||||
| 4203 | 8 | 8 | if (!exists $type_map{$p->{type}}) { | |||
| 4204 | 1 | 2 | push @notes, "Unknown type $p->{type}, defaulting to string"; | |||
| 4205 | 1 | 1 | $confidence = 'medium'; | |||
| 4206 | } | |||||
| 4207 | ||||||
| 4208 | $input->{"arg$position"} = { | |||||
| 4209 | type => $type, | |||||
| 4210 | position => $position, | |||||
| 4211 | 8 | 12 | optional => $p->{optional} ? 1 : 0, | |||
| 4212 | }; | |||||
| 4213 | ||||||
| 4214 | 8 | 8 | $position++; | |||
| 4215 | } | |||||
| 4216 | ||||||
| 4217 | 8 | 7 | my $output; | |||
| 4218 | ||||||
| 4219 | 8 | 6 | if (my $ret = $meta->{returns}) { | |||
| 4220 | 2 | 3 | my $type = $type_map{ $ret->{type} } // 'string'; | |||
| 4221 | ||||||
| 4222 | 2 | 3 | if (!exists $type_map{$ret->{type}}) { | |||
| 4223 | 0 | 0 | push @notes, "Unknown return type $ret->{type}, defaulting to string"; | |||
| 4224 | 0 | 0 | $confidence = 'medium'; | |||
| 4225 | } | |||||
| 4226 | ||||||
| 4227 | $output = { | |||||
| 4228 | 2 | 4 | type => $type, | |||
| 4229 | "_$ret->{context}_context" => { type => $type }, | |||||
| 4230 | }; | |||||
| 4231 | } | |||||
| 4232 | ||||||
| 4233 | return { | |||||
| 4234 | 8 | 20 | 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 when | |||||
| 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 | 485 | 481 | my ($self, $pod, $routine) = @_; | |||
| 4278 | ||||||
| 4279 | 485 | 468 | return {} unless $pod; | |||
| 4280 | ||||||
| 4281 | 250 | 157 | my %params; | |||
| 4282 | 250 | 176 | my $position_counter = 0; | |||
| 4283 | ||||||
| 4284 | # Check for positional arguments in method signature | |||||
| 4285 | # Pattern: =head2 method_name($arg1, $arg2, $arg3) | |||||
| 4286 | 250 | 482 | if ($pod =~ /=head2\s+\w+\s*\(([^)]+)\)/s) { | |||
| 4287 | 42 | 45 | my $sig = $1; | |||
| 4288 | # Extract parameter names in order | |||||
| 4289 | 42 | 83 | my @sig_params = $sig =~ /\$(\w+)/g; | |||
| 4290 | ||||||
| 4291 | # Skip $self or $class | |||||
| 4292 | 42 | 114 | shift @sig_params if @sig_params && $sig_params[0] =~ /^(self|class|pkg|proto|klass)$/i; | |||
| 4293 | ||||||
| 4294 | # Assign positions | |||||
| 4295 | 42 | 43 | foreach my $param (@sig_params) { | |||
| 4296 | 54 | 126 | $params{$param}{position} //= $position_counter; | |||
| 4297 | 54 | 90 | $self->_log(" POD: $param has position $params{$param}{position}"); | |||
| 4298 | 54 | 48 | $position_counter++; | |||
| 4299 | } | |||||
| 4300 | } | |||||
| 4301 | ||||||
| 4302 | 250 | 383 | $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 | 250 | 173 | my $param_section; | |||
| 4307 | 250 | 2563 | if($pod =~ /(?:Parameters?|Arguments?|Inputs?):?\s*\n((?:\s*\$.*\n)+)/si) { | |||
| 4308 | 39 | 41 | $param_section = $1; | |||
| 4309 | } elsif ($pod =~ /^=head\d+\s+(?:Parameters?|Arguments?|Inputs?)\b.*?\n(.*?)(?=^=head|\Z)/msi) { | |||||
| 4310 | 123 | 131 | $param_section = $1; | |||
| 4311 | } | |||||
| 4312 | 250 | 283 | if($param_section) { | |||
| 4313 | 162 | 151 | my $param_order = 0; | |||
| 4314 | ||||||
| 4315 | 162 | 258 | $self->_log(" POD: Scan for named parameters in '$param_section'"); | |||
| 4316 | # Now parse each line that starts with $varname | |||||
| 4317 | 162 | 319 | foreach my $line (split /\n/, $param_section) { | |||
| 4318 | 892 | 694 | if ($line =~ /C<\$(\w+)>\s*\((Required|Mandatory)\)/i) { | |||
| 4319 | 0 | 0 | $params{$1}{optional} = 0; | |||
| 4320 | 0 | 0 | $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 | 892 | 1166 | if(($line =~ /^\s*\$(\w+)\s*-\s*(\w+)(?:\s*\(([^)]+)\))?\s*,?\s*(.*)$/i) || | |||
| 4327 | ($line =~ /^\s*C<\$(\w+)>\s*-\s*(\w+)(?:\s*\(([^)]+)\))?\s*,?\s*(.*)$/i)) { | |||||
| 4328 | 54 | 145 | my ($name, $type, $constraint, $desc) = ($1, lc($2), $3, $4); | |||
| 4329 | ||||||
| 4330 | # Clean up | |||||
| 4331 | 54 | 116 | $desc =~ s/^\s+|\s+$//g if $desc; | |||
| 4332 | ||||||
| 4333 | # Skip common non-parameters | |||||
| 4334 | 54 | 91 | next if $name =~ /^(self|class|pkg|proto|klass|return|returns?)$/i; | |||
| 4335 | ||||||
| 4336 | 53 | 103 | $params{$name} ||= { _source => SOURCE_POD }; | |||
| 4337 | ||||||
| 4338 | # If we haven't already assigned a position from the signature, use order in Parameters section | |||||
| 4339 | 53 | 108 | unless (exists $params{$name}{position}) { | |||
| 4340 | 24 | 21 | $params{$name}{position} = $param_order++; | |||
| 4341 | 24 | 35 | $self->_log(" POD: $name has position $params{$name}{position} (from Parameters order)"); | |||
| 4342 | } | |||||
| 4343 | ||||||
| 4344 | # Normalize type names | |||||
| 4345 | 53 | 61 | $type = 'integer' if $type eq 'int'; | |||
| 4346 | 53 | 107 | $type = 'number' if $type eq 'num' || $type eq 'float'; | |||
| 4347 | 53 | 51 | $type = 'boolean' if $type eq 'bool'; | |||
| 4348 | 53 | 49 | $type = 'arrayref' if $type eq 'array'; | |||
| 4349 | 53 | 50 | $type = 'hashref' if $type eq 'hash'; | |||
| 4350 | ||||||
| 4351 | 53 | 51 | $params{$name}{type} = $type; | |||
| 4352 | ||||||
| 4353 | # Parse constraints | |||||
| 4354 | 53 | 47 | if($constraint) { | |||
| 4355 | 11 | 21 | $self->_parse_constraints($params{$name}, $constraint); | |||
| 4356 | } | |||||
| 4357 | ||||||
| 4358 | # Check for optional/required in description OR constraint. | |||||
| 4359 | # Use word boundaries to avoid matching "optionally" as "optional". | |||||
| 4360 | 53 | 103 | my $full_text = ($constraint || '') . ' ' . ($desc || ''); | |||
| 4361 | 53 | 146 | if ($full_text =~ /\boptional\b/i) { | |||
| 4362 | 6 | 5 | $params{$name}{optional} = 1; | |||
| 4363 | 6 | 7 | $self->_log(" POD: $name marked as optional"); | |||
| 4364 | } elsif ($full_text =~ /required|mandatory/i) { | |||||
| 4365 | 2 | 2 | $params{$name}{optional} = 0; | |||
| 4366 | 2 | 3 | $self->_log(" POD: $name marked as required"); | |||
| 4367 | } | |||||
| 4368 | ||||||
| 4369 | # Detect semantic types: | |||||
| 4370 | 53 | 94 | if ($desc =~ /\b(email|url|uri|path|filename)\b/i) { | |||
| 4371 | # TODO: ensure properties is set to 1 in $config | |||||
| 4372 | 2 | 31 | carp('Manually set config->properties to 1 in ', $self->{'input_file'}); | |||
| 4373 | 2 | 299 | $params{$name}{semantic} = lc($1); | |||
| 4374 | } | |||||
| 4375 | ||||||
| 4376 | # Look for regex patterns | |||||
| 4377 | 53 | 108 | if ($desc && $desc =~ m{matches?\s+(/[^/]+/|qr/.+?/)}i) { | |||
| 4378 | 6 | 9 | $params{$name}{matches} = $1; | |||
| 4379 | 6 | 8 | $params{$name}{_source} = SOURCE_POD; # documentation, not a check | |||
| 4380 | } | |||||
| 4381 | ||||||
| 4382 | 53 | 87 | if(my $values = $self->_prose_memberof($desc)) { | |||
| 4383 | 0 | 0 | $params{$name}{memberof} = $values; | |||
| 4384 | 0 | 0 | $params{$name}{_source} = SOURCE_POD; # documentation, not a check | |||
| 4385 | 0 0 | 0 0 | $self->_log(" POD: $name memberof from prose: " . join(', ', @{$values})); | |||
| 4386 | } | |||||
| 4387 | ||||||
| 4388 | 53 | 125 | $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 | 250 | 545 | while ($pod =~ /\$(\w+)\s*-\s*(string|integer|int|number|num|float|boolean|bool|arrayref|array|hashref|hash|object|any)(?:\s*\(([^)]+)\))?\s*,?\s*(.*)$/gim) { | |||
| 4397 | 32 | 68 | 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 | 32 | 55 | next if exists $params{$name}; | |||
| 4401 | ||||||
| 4402 | # Clean up description - remove leading/trailing whitespace | |||||
| 4403 | 2 | 6 | $desc =~ s/^\s+|\s+$//g if $desc; | |||
| 4404 | ||||||
| 4405 | # Skip common words that aren't parameters | |||||
| 4406 | 2 | 3 | next if $name =~ /^(self|class|pkg|proto|klass|return|returns?)$/i; | |||
| 4407 | ||||||
| 4408 | 1 | 4 | $params{$name} ||= { _source => SOURCE_POD }; | |||
| 4409 | ||||||
| 4410 | # Normalize type names | |||||
| 4411 | 1 | 1 | $type = 'integer' if $type eq 'int'; | |||
| 4412 | 1 | 2 | $type = 'number' if $type eq 'num' || $type eq 'float'; | |||
| 4413 | 1 | 2 | $type = 'boolean' if $type eq 'bool'; | |||
| 4414 | 1 | 1 | $type = 'arrayref' if $type eq 'array'; | |||
| 4415 | 1 | 2 | $type = 'hashref' if $type eq 'hash'; | |||
| 4416 | ||||||
| 4417 | 1 | 2 | $params{$name}{type} = $type; | |||
| 4418 | ||||||
| 4419 | # Parse constraints | |||||
| 4420 | 1 | 1 | if ($constraint) { | |||
| 4421 | 0 | 0 | $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 | 1 | 1 | if ($desc) { | |||
| 4427 | 1 | 4 | if ($desc =~ /\boptional\b/i) { | |||
| 4428 | 0 | 0 | $params{$name}{optional} = 1; | |||
| 4429 | } elsif ($desc =~ /required|mandatory/i) { | |||||
| 4430 | 0 | 0 | $params{$name}{optional} = 0; | |||
| 4431 | } | |||||
| 4432 | ||||||
| 4433 | # Look for regex patterns in description | |||||
| 4434 | 1 | 1 | if ($desc =~ m{matches?\s+(/[^/]+/|qr/.+?/)}i) { | |||
| 4435 | 0 | 0 | $params{$name}{matches} = $1; | |||
| 4436 | } | |||||
| 4437 | } | |||||
| 4438 | ||||||
| 4439 | 1 | 2 | if(my $values = $self->_prose_memberof($desc)) { | |||
| 4440 | 0 | 0 | $params{$name}{memberof} = $values; | |||
| 4441 | 0 | 0 | $params{$name}{_source} = SOURCE_POD; # documentation, not a check | |||
| 4442 | 0 0 | 0 0 | $self->_log(" POD: $name memberof from prose: " . join(', ', @{$values})); | |||
| 4443 | } | |||||
| 4444 | ||||||
| 4445 | 1 | 3 | $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. | |||||
| 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 | 250 | 195 | my $item_pod = $pod; | |||
| 4458 | 250 | 678 | $item_pod =~ s{ | |||
| 4459 | (?:^=head[2-6]\s+arguments?\b) | |||||
| 4460 | (.*?) | |||||
| 4461 | (?=^=head[1-6]\b|\z) | |||||
| 4462 | }{ | |||||
| 4463 | 43 | 62 | my $section = $&; | |||
| 4464 | 43 | 84 | $section =~ s{^=item(\s+\*\s*)C<\s*([A-Za-z_]\w*)\s*>}{ | |||
| 4465 | 14 | 31 | '=item' . $1 . 'C<$' . $2 . '>' | |||
| 4466 | }gme; | |||||
| 4467 | 43 | 90 | $section; | |||
| 4468 | }msgeix; | |||||
| 4469 | ||||||
| 4470 | 250 | 1051 | while ($item_pod =~ /=item\s+(?:\*\s*)?(?:C<)?\$(\w+)\b(?:>)?\s*(?:-.*)?\n?(.*?)(?==item|\=back|\=head)/sig) { | |||
| 4471 | 51 | 51 | my $name = $1; | |||
| 4472 | 51 | 45 | my $desc = $2; | |||
| 4473 | ||||||
| 4474 | # Never allow empty or undefined parameter names | |||||
| 4475 | 51 | 82 | next unless defined $name && length $name; | |||
| 4476 | ||||||
| 4477 | 51 | 133 | $desc =~ s/^\s+|\s+$//g; | |||
| 4478 | ||||||
| 4479 | # Skip common non-parameters | |||||
| 4480 | 51 | 77 | next if $name =~ /^(self|class|pkg|proto|klass|return|returns?)$/i; | |||
| 4481 | ||||||
| 4482 | 51 | 141 | $params{$name} ||= { _source => SOURCE_POD }; | |||
| 4483 | ||||||
| 4484 | # Explicit typed form only: | |||||
| 4485 | # $param - type (constraints) | |||||
| 4486 | 51 | 73 | if ($desc =~ /^\s*(string|integer|int|number|num|float|boolean|bool|array|arrayref|hash|hashref|any)\b(?:\s*\(([^)]+)\))?/i) { | |||
| 4487 | 14 | 17 | my $type = lc($1); | |||
| 4488 | 14 | 9 | my $constraint = $2; | |||
| 4489 | ||||||
| 4490 | # Normalize type names | |||||
| 4491 | 14 | 15 | $type = 'integer' if $type eq 'int'; | |||
| 4492 | 14 | 22 | $type = 'number' if $type eq 'num' || $type eq 'float'; | |||
| 4493 | 14 | 10 | $type = 'boolean' if $type eq 'bool'; | |||
| 4494 | 14 | 15 | $type = 'arrayref' if $type eq 'array'; | |||
| 4495 | 14 | 8 | $type = 'hashref' if $type eq 'hash'; | |||
| 4496 | ||||||
| 4497 | 14 | 16 | $params{$name}{type} = $type; | |||
| 4498 | ||||||
| 4499 | 14 | 9 | if ($constraint) { | |||
| 4500 | 3 | 6 | $self->_parse_constraints($params{$name}, $constraint); | |||
| 4501 | } | |||||
| 4502 | ||||||
| 4503 | 14 | 18 | $self->_log(" POD: Explicit type '$type' for $name"); | |||
| 4504 | } else { | |||||
| 4505 | # Heuristic inference from description text | |||||
| 4506 | 37 | 181 | if ($desc =~ /\bstring\b/i) { | |||
| 4507 | 0 | 0 | $params{$name}{type} = 'string'; | |||
| 4508 | } elsif ($desc =~ /\b(int|integer)\b/i) { | |||||
| 4509 | 1 | 2 | $params{$name}{type} = 'integer'; | |||
| 4510 | } elsif ($desc =~ /\b(num|number|float)\b/i) { | |||||
| 4511 | 0 | 0 | $params{$name}{type} = 'number'; | |||
| 4512 | } elsif ($desc =~ /\b(bool|boolean)\b/i) { | |||||
| 4513 | 0 | 0 | $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 | 3 | 5 | $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 | 51 | 41 | my $optionality_text = $desc; | |||
| 4527 | 51 | 53 | $optionality_text =~ s/\b[CBIL]<[^>]*>//g; | |||
| 4528 | 51 | 119 | if ($optionality_text =~ /\boptional\b/i) { | |||
| 4529 | 4 | 5 | $params{$name}{optional} = 1; | |||
| 4530 | } elsif ($optionality_text =~ /\b(?:required|mandatory)\b/i) { | |||||
| 4531 | 11 | 13 | $params{$name}{optional} = 0; | |||
| 4532 | } | |||||
| 4533 | ||||||
| 4534 | # Look for regex patterns | |||||
| 4535 | 51 | 56 | if ($desc =~ m{matches?\s+(/[^/]+/|qr/.+?/)}i) { | |||
| 4536 | 0 | 0 | $params{$name}{matches} = $1; | |||
| 4537 | 0 | 0 | $params{$name}{_source} = SOURCE_POD; # documentation, not a check | |||
| 4538 | } | |||||
| 4539 | ||||||
| 4540 | 51 | 67 | if(my $values = $self->_prose_memberof($desc)) { | |||
| 4541 | 5 | 4 | $params{$name}{memberof} = $values; | |||
| 4542 | 5 | 4 | $params{$name}{_source} = SOURCE_POD; # documentation, not a check | |||
| 4543 | 5 5 | 5 6 | $self->_log(" POD: $name memberof from prose: " . join(', ', @{$values})); | |||
| 4544 | } | |||||
| 4545 | ||||||
| 4546 | 51 | 62 | $self->_log(" POD: Found parameter '$name' from =item list"); | |||
| 4547 | } | |||||
| 4548 | ||||||
| 4549 | # Extract default values from POD | |||||
| 4550 | 250 | 428 | my $pod_defaults = $self->_extract_defaults_from_pod($pod); | |||
| 4551 | 250 | 334 | foreach my $param (keys %$pod_defaults) { | |||
| 4552 | 11 | 13 | if (exists $params{$param}) { | |||
| 4553 | 11 | 8 | $params{$param}{_default} = $pod_defaults->{$param}; | |||
| 4554 | 11 | 8 | $params{$param}{optional} = 1 unless defined $params{$param}{optional}; | |||
| 4555 | $self->_log(sprintf(" POD: %s has default value: %s", | |||||
| 4556 | $param, | |||||
| 4557 | 11 | 21 | defined($pod_defaults->{$param}) ? $pod_defaults->{$param} : 'undef' | |||
| 4558 | )); | |||||
| 4559 | } | |||||
| 4560 | } | |||||
| 4561 | ||||||
| 4562 | # Default undocumented optionality: documented params are REQUIRED unless stated otherwise | |||||
| 4563 | 250 | 290 | for my $name (keys %params) { | |||
| 4564 | 127 | 193 | 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 | 250 | 937 | if ($pod =~ /=head[34]\s+Input\b(.*?)(?==head|\z)/si) { | |||
| 4579 | 101 | 102 | my $block = $1; | |||
| 4580 | 101 | 193 | $block =~ s/\A\s+//; | |||
| 4581 | # The spec may follow introductory prose and comment lines: start at | |||||
| 4582 | # the first line that opens the structure. | |||||
| 4583 | 101 | 231 | $block =~ s/\A.*?^[ \t]+(?=[\[\{])//ms unless($block =~ /\A[\[\{]/); | |||
| 4584 | ||||||
| 4585 | 101 | 301 | if ($block =~ /\A\[/) { | |||
| 4586 | # Positional format: each {â¦} maps to the param at that array index. | |||||
| 4587 | 7 | 5 | my $idx = 0; | |||
| 4588 | 7 | 14 | while ($block =~ /\{([^}]*)\}/g) { | |||
| 4589 | 9 | 10 | my $spec = $1; | |||
| 4590 | 9 3 | 16 6 | my ($name) = grep { ($params{$_}{position} // -1) == $idx } | |||
| 4591 | keys %params; | |||||
| 4592 | 9 | 10 | if (defined $name) { | |||
| 4593 | 3 | 3 | $params{$name}{_source} = SOURCE_INPUT_SPEC; | |||
| 4594 | 3 | 4 | if (my $t = $self->_map_formal_input_type($spec)) { | |||
| 4595 | 3 | 2 | $params{$name}{type} = $t; | |||
| 4596 | 3 | 4 | $self->_log(" POD: $name type '$t' from =head Input (positional $idx)"); | |||
| 4597 | } | |||||
| 4598 | 3 | 4 | if(defined(my $opt = _spec_optionality($spec))) { | |||
| 4599 | 0 | 0 | $params{$name}{optional} = $opt; | |||
| 4600 | } | |||||
| 4601 | } | |||||
| 4602 | 9 | 11 | $idx++; | |||
| 4603 | } | |||||
| 4604 | } elsif ($block =~ /\A\{/) { | |||||
| 4605 | # Named format: each 'name => {â¦}' entry maps directly by name. | |||||
| 4606 | 68 | 201 | while ($block =~ /\b(\w+)\s*=>\s*\{([^}]*)\}/g) { | |||
| 4607 | 88 | 131 | my ($name, $spec) = ($1, $2); | |||
| 4608 | 88 | 181 | next if $name =~ /^(self|class|pkg|proto|klass)$/i; | |||
| 4609 | 78 | 243 | $params{$name} //= { _source => SOURCE_INPUT_SPEC }; | |||
| 4610 | 78 | 72 | $params{$name}{_source} = SOURCE_INPUT_SPEC; | |||
| 4611 | 78 | 146 | if (my $t = $self->_map_formal_input_type($spec)) { | |||
| 4612 | 78 | 79 | $params{$name}{type} = $t; | |||
| 4613 | 78 | 118 | $self->_log(" POD: $name type '$t' from =head Input (named)"); | |||
| 4614 | } | |||||
| 4615 | 78 | 142 | if(defined(my $opt = _spec_optionality($spec))) { | |||
| 4616 | 60 | 68 | $params{$name}{optional} = $opt; | |||
| 4617 | } | |||||
| 4618 | 78 | 145 | if ($spec =~ /\bmemberof\s*=>\s*\[([^\]]*)\]/i) { | |||
| 4619 | 4 | 4 | my $list_str = $1; | |||
| 4620 | 4 | 3 | my @vals; | |||
| 4621 | 4 | 12 | while ($list_str =~ /['"]([^'"]*)['"]/g) { | |||
| 4622 | 8 | 11 | push @vals, $1; | |||
| 4623 | } | |||||
| 4624 | 4 | 4 | if(@vals) { | |||
| 4625 | 4 | 4 | $params{$name}{memberof} = \@vals; | |||
| 4626 | # The list is documentation: the code may accept more. | |||||
| 4627 | 4 | 4 | $params{$name}{_source} = SOURCE_INPUT_SPEC; | |||
| 4628 | } | |||||
| 4629 | } | |||||
| 4630 | 78 | 166 | if ($spec =~ /\bmin\s*=>\s*(\d+)/i) { | |||
| 4631 | 30 | 53 | $params{$name}{min} = $1 + 0; | |||
| 4632 | } | |||||
| 4633 | 78 | 158 | if ($spec =~ /\bmax\s*=>\s*(\d+)/i) { | |||
| 4634 | 17 | 27 | $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 | 78 | 164 | if(exists($params{$name}{min}) || exists($params{$name}{max})) { | |||
| 4641 | 40 | 50 | $params{$name}{_source} = SOURCE_INPUT_SPEC; | |||
| 4642 | } | |||||
| 4643 | 78 | 188 | if ($spec =~ /\bisa\s*=>\s*['"]([^'"]+)['"]/i) { | |||
| 4644 | 0 | 0 | $params{$name}{isa} = $1; | |||
| 4645 | } | |||||
| 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 | 68 | 143 | delete $params{$_}{position} for keys %params; | |||
| 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 | 101 | 244 | $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 | 101 | 216 | unless($block =~ /\A[\[\{]/) { | |||
| 4670 | 26 | 52 | for my $entry (_top_level_hash_entries($block)) { | |||
| 4671 | 6 6 | 4 4 | my ($bare_name, $bare_spec) = @{$entry}; | |||
| 4672 | 6 | 7 | next if $bare_name =~ /^(self|class|pkg|proto|klass)$/i; | |||
| 4673 | 6 | 7 | my $own = _own_spec_text($bare_spec); | |||
| 4674 | 6 | 13 | next unless $own =~ /\brequired\s*=>\s*(0|1)/i; | |||
| 4675 | 2 | 4 | next if $own =~ /\boptional\s*=>\s*(?:0|1)/i; | |||
| 4676 | 2 | 3 | $params{$bare_name} //= { _source => SOURCE_INPUT_SPEC }; | |||
| 4677 | 2 | 4 | $params{$bare_name}{optional} = 1 - ($1 + 0); | |||
| 4678 | ||||||
| 4679 | # The comment lines under the entry describe its shape. | |||||
| 4680 | 2 | 93 | my ($desc) = $block =~ /(?:^|\n)[ \t]*\Q$bare_name\E\s*=>[^\n]*(?:\n[ \t]+[^\n#][^\n]*)*\n((?:[ \t]*#[^\n]*(?:\n|\z))+)/; | |||
| 4681 | 2 | 5 | my ($bare_type) = $own =~ /\btype\s*=>\s*'?(\w+)/; | |||
| 4682 | 2 | 5 | if(my $shape = _pod_nested_input_shape($bare_type // '', $desc)) { | |||
| 4683 | 0 | 0 | $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 | 250 | 538 | while ($pod =~ /=item\s+(?:\*\s*)?(?:C<\$?(\w+)>|\$(\w+))\s*-?\s*((?:[^\n]*\n)*?)(?==item|\=back|\=head)/gi) { | |||
| 4696 | 62 | 108 | my ($name, $text) = ($1 // $2, $3); | |||
| 4697 | 62 | 68 | next unless $params{$name}; | |||
| 4698 | 52 | 57 | next if defined($params{$name}{memberof}); | |||
| 4699 | ||||||
| 4700 | 47 | 45 | if(my $values = $self->_prose_memberof($text)) { | |||
| 4701 | 0 | 0 | $params{$name}{memberof} = $values; | |||
| 4702 | 0 | 0 | $params{$name}{_source} = SOURCE_POD; # documentation, not a check | |||
| 4703 | 0 0 | 0 0 | $self->_log(" POD: $name memberof from prose: " . join(', ', @{$values})); | |||
| 4704 | } | |||||
| 4705 | } | |||||
| 4706 | ||||||
| 4707 | 250 | 905 | $self->_sanitize_parameter_names(\%params, 'POD analysis'); | |||
| 4708 | 250 | 280 | return \%params; | |||
| 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 value | |||||
| 4726 | # is not a recognised type name. | |||||
| 4727 | # -------------------------------------------------- | |||||
| 4728 | sub _map_formal_input_type { | |||||
| 4729 | 86 | 1226 | my ($self, $spec) = @_; | |||
| 4730 | # Accept both quoted type => 'scalar' and unquoted Params::Validate | |||||
| 4731 | # constants type => OBJECT (no quotes around the constant name). | |||||
| 4732 | 86 | 205 | return undef unless $spec =~ /\btype\s*=>\s*(?:['"]([^'"]+)['"]|([A-Z_]+))/i; | |||
| 4733 | 85 | 171 | my $raw = lc(defined($1) ? $1 : $2); | |||
| 4734 | 85 | 87 | $raw =~ s/\s+//g; | |||
| 4735 | ||||||
| 4736 | 85 | 638 | 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', | |||||
| 4745 | float => 'number', | |||||
| 4746 | bool => 'boolean', | |||||
| 4747 | boolean => 'boolean', | |||||
| 4748 | array => 'arrayref', | |||||
| 4749 | arrayref => 'arrayref', | |||||
| 4750 | hash => 'hashref', | |||||
| 4751 | hashref => 'hashref', | |||||
| 4752 | object => 'object', | |||||
| 4753 | any => 'any', | |||||
| 4754 | undef => 'undef', | |||||
| 4755 | coderef => 'coderef', | |||||
| 4756 | ); | |||||
| 4757 | ||||||
| 4758 | 85 | 113 | for my $t (split /\|/, $raw) { | |||
| 4759 | 85 | 255 | return $map{$t} if exists $map{$t}; | |||
| 4760 | } | |||||
| 4761 | 1 | 3 | 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 | 474 | 411 | my ($self, $pod) = @_; | |||
| 4794 | ||||||
| 4795 | 474 | 1460 | return 0 unless defined($pod) && length($pod); | |||
| 4796 | 241 | 1396 | 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 | 97 | 460 | return (($1 =~ /^\s*\$?class\b/mi) ? 1 : 0); | |||
| 4801 | } | |||||
| 4802 | ||||||
| 4803 | # -------------------------------------------------- | |||||
| 4804 | # _strip_literals | |||||
| 4805 | # | |||||
| 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. | |||||
| 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 | 818 | 647 | my ($code) = @_; | |||
| 4819 | ||||||
| 4820 | 818 | 670 | return '' unless defined($code); | |||
| 4821 | ||||||
| 4822 | 818 | 1142 | $code =~ s/'(?:\\.|[^'\\])*'/''/g; | |||
| 4823 | 818 | 880 | $code =~ s/"(?:\\.|[^"\\])*"/""/g; | |||
| 4824 | ||||||
| 4825 | # m{...}, qr{...} and s{...}{...}, which a '/' pattern would miss. | |||||
| 4826 | 818 | 1379 | $code =~ s{\b(?:qr|m|s|tr|y)\s*\{(?:\\.|[^{}\\]|\{[^{}]*\})*\} | |||
| 4827 | (?:\s*[a-z]*\s*\{(?:\\.|[^{}\\]|\{[^{}]*\})*\})?}{''}gx; | |||||
| 4828 | 818 | 670 | $code =~ s{\b(?:qr|m|s|tr|y)\s*/(?:\\.|[^/\\])*/}{''}g; | |||
| 4829 | 818 | 631 | $code =~ s{([=!]~\s*)/(?:\\.|[^/\\])*/}{"$1"}g; | |||
| 4830 | ||||||
| 4831 | 818 | 670 | return $code; | |||
| 4832 | } | |||||
| 4833 | ||||||
| 4834 | # -------------------------------------------------- | |||||
| 4835 | # _strip_comments | |||||
| 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). | |||||
| 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. | |||||
| 4846 | # | |||||
| 4847 | # Exit: The fragment with each comment removed. Undef is treated as an | |||||
| 4848 | # empty fragment. | |||||
| 4849 | # -------------------------------------------------- | |||||
| 4850 | sub _strip_comments { | |||||
| 4851 | 949 | 1110 | my ($code, $node) = @_; | |||
| 4852 | ||||||
| 4853 | 949 | 1128 | return '' unless defined($code); | |||
| 4854 | ||||||
| 4855 | 949 | 3560 | if($node && $node->can('tokens')) { | |||
| 4856 | return join '', map { | |||||
| 4857 | 945 44052 | 1420 112929 | $_->isa('PPI::Token::Comment') ? '' : $_->content | |||
| 4858 | } $node->tokens; | |||||
| 4859 | } | |||||
| 4860 | ||||||
| 4861 | # No PPI node (a synthesized class method): fall back to line comments. | |||||
| 4862 | 4 | 11 | $code =~ s/[ \t]*\#[^\n]*//g; | |||
| 4863 | 4 | 4 | return $code; | |||
| 4864 | } | |||||
| 4865 | ||||||
| 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. | |||||
| 4871 | # | |||||
| 4872 | # Entry: $text - the description after the '#'. | |||||
| 4873 | # | |||||
| 4874 | # Exit: Canonical type string, or undef when it names none. | |||||
| 4875 | # -------------------------------------------------- | |||||
| 4876 | sub _pod_input_prose_type { | |||||
| 4877 | 8 | 7 | my ($text) = @_; | |||
| 4878 | ||||||
| 4879 | 8 | 9 | return undef unless defined($text); | |||
| 4880 | 8 | 18 | return 'arrayref' if $text =~ /\barrayref\b|\barray\s+of\b|\blist\s+of\b/i; | |||
| 4881 | 8 | 14 | return 'hashref' if $text =~ /\bhashref\b|\bhash\s+of\b/i; | |||
| 4882 | 8 | 16 | return 'boolean' if $text =~ /\bboolean\b|\bbool\b/i; | |||
| 4883 | 8 | 16 | return 'integer' if $text =~ /\binteger\b|\bint\b/i; | |||
| 4884 | 8 | 16 | return 'number' if $text =~ /\bnumber\b|\bfloat\b/i; | |||
| 4885 | 8 | 14 | return 'string' if $text =~ /\bstring\b|\btext\b/i; | |||
| 4886 | 5 | 5 | 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 | # | |||||
| 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 | 101 | 118 | my ($block) = @_; | |||
| 4914 | ||||||
| 4915 | 101 | 66 | my @rows; | |||
| 4916 | 101 | 112 | my ($name, $body, $depth) = (undef, '', 0); | |||
| 4917 | ||||||
| 4918 | 101 | 180 | for my $line (split(/\n/, $block)) { | |||
| 4919 | 367 | 191 | my $added; | |||
| 4920 | 367 | 261 | if(!defined($name)) { | |||
| 4921 | 361 | 797 | next unless $line =~ /^\s*(\w+)\s*=>\s*\{(.*)$/; | |||
| 4922 | 88 | 100 | ($name, $body, $depth) = ($1, '', 1); | |||
| 4923 | 88 | 73 | $added = $2; | |||
| 4924 | } else { | |||||
| 4925 | 6 | 3 | $added = $line; | |||
| 4926 | } | |||||
| 4927 | ||||||
| 4928 | 94 | 96 | $body .= ' ' . $added; | |||
| 4929 | 94 | 966 | $depth += ($added =~ tr/{//) - ($added =~ tr/}//); | |||
| 4930 | 94 | 95 | next if $depth > 0; | |||
| 4931 | ||||||
| 4932 | 88 | 152 | push @rows, [ $name, _pod_input_hash_fields($body) ] if $depth == 0; | |||
| 4933 | 88 | 65 | undef $name; | |||
| 4934 | 88 | 66 | $body = ''; | |||
| 4935 | 88 | 61 | $depth = 0; | |||
| 4936 | } | |||||
| 4937 | ||||||
| 4938 | 101 | 563 | return @rows; | |||
| 4939 | } | |||||
| 4940 | ||||||
| 4941 | sub _pod_input_hash_fields { | |||||
| 4942 | 88 | 91 | my ($body) = @_; | |||
| 4943 | ||||||
| 4944 | 88 | 59 | my %fields; | |||
| 4945 | # Keys are often quoted ('type' => 'boolean'), so the quote before => | |||||
| 4946 | # belongs to the key. | |||||
| 4947 | 88 | 280 | while($body =~ /'?(\w+)'?\s*=>\s*'?([A-Za-z0-9_:.]+)'?/g) { | |||
| 4948 | 208 | 760 | $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 | 88 | 125 | if($body =~ /\benum\s*=>\s*\[([^\]]*)\]/) { | |||
| 4953 | 0 | 0 | my @values = $1 =~ /['"]([^'"]+)['"]/g; | |||
| 4954 | 0 | 0 | $fields{enum} = \@values if(@values); | |||
| 4955 | } | |||||
| 4956 | ||||||
| 4957 | 88 | 116 | 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 | 118 | 114 | my ($type, $desc) = @_; | |||
| 4967 | ||||||
| 4968 | 118 | 1006 | return undef unless(defined($type) && length($type)); | |||
| 4969 | 113 | 1826 | return undef unless(defined($desc) && !ref($desc) && length($desc)); | |||
| 4970 | ||||||
| 4971 | 37 | 41 | if(($type eq 'arrayref') && $desc =~ /\bof\s+\{([^}]+)\}/i) { | |||
| 4972 | 1 | 1 | my %element; | |||
| 4973 | 1 | 3 | for my $key ($1 =~ /(\w+)/g) { | |||
| 4974 | 3 | 2 | my %spec = (type => 'string'); | |||
| 4975 | # "op -- one of: eq, ne, ..." is the documented domain. | |||||
| 4976 | 3 | 51 | if($desc =~ /\b\Q$key\E\s*--\s*one\s+of:\s*([^\n]+)/i) { | |||
| 4977 | 1 8 | 3 9 | my @values = map { s/\A\s+|\s+\z//gr } split /,/, $1; | |||
| 4978 | 1 | 3 | $spec{memberof} = \@values if(@values); | |||
| 4979 | } | |||||
| 4980 | 3 | 5 | $element{$key} = \%spec; | |||
| 4981 | } | |||||
| 4982 | 1 | 4 | 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 | 36 | 50 | if(($type eq 'arrayref') && $desc =~ /\bhashrefs?\b/i) { | |||
| 4988 | 2 | 4 | return { type => 'hashref' }; | |||
| 4989 | } | |||||
| 4990 | ||||||
| 4991 | 34 | 39 | return { type => 'hashref' } | |||
| 4992 | if(($type eq 'hashref') && $desc =~ /=>\s*\w+\s+hashref\b/i); | |||||
| 4993 | ||||||
| 4994 | 33 | 34 | 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 | 9 | 3 | my ($number) = @_; | |||
| 5001 | ||||||
| 5002 | 9 | 10 | return undef unless defined($number); | |||
| 5003 | 9 | 7 | $number =~ s/_//g; | |||
| 5004 | 9 | 8 | return $number + 0; | |||
| 5005 | } | |||||
| 5006 | ||||||
| 5007 | sub _apply_pod_input_table { | |||||
| 5008 | 101 | 139 | my ($self, $block, $params, $routine) = @_; | |||
| 5009 | ||||||
| 5010 | 101 | 593 | my %types = ( | |||
| 5011 | scalar => 'string', | |||||
| 5012 | str => 'string', | |||||
| 5013 | string => 'string', | |||||
| 5014 | int => 'integer', | |||||
| 5015 | integer => 'integer', | |||||
| 5016 | num => 'number', | |||||
| 5017 | number => 'number', | |||||
| 5018 | float => 'number', | |||||
| 5019 | bool => 'boolean', | |||||
| 5020 | boolean => 'boolean', | |||||
| 5021 | 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 | 101 | 572 | if(my @dump = _pod_input_hash_dump($block)) { | |||
| 5042 | 63 | 66 | my $count = 0; | |||
| 5043 | 63 | 64 | for my $row (@dump) { | |||
| 5044 | 88 88 | 56 86 | my ($name, $fields) = @{$row}; | |||
| 5045 | 88 | 548 | 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 | 79 | 494 | my $p = $params->{$name} //= {}; | |||
| 5051 | ||||||
| 5052 | 79 | 527 | if(defined($fields->{type})) { | |||
| 5053 | 79 | 101 | my $type = $types{lc($fields->{type})}; | |||
| 5054 | 79 | 113 | $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 | 79 | 512 | $p->{optional} = ($fields->{optional} ? 1 : 0); | |||
| 5059 | $p->{isa} = $fields->{isa} | |||||
| 5060 | 79 | 150 | 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 | 79 0 | 166 0 | if ref($fields->{enum}) eq 'ARRAY' && @{$fields->{enum}}; | |||
| 5065 | $p->{min} = $fields->{min} + 0 | |||||
| 5066 | 79 | 1357 | if defined($fields->{min}) && $fields->{min} =~ /\A-?\d/; | |||
| 5067 | $p->{max} = $fields->{max} + 0 | |||||
| 5068 | 79 | 975 | if defined($fields->{max}) && $fields->{max} =~ /\A-?\d/; | |||
| 5069 | 79 | 497 | $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 | 79 | 1770 | my ($desc) = $block =~ /(?:^|\n)[ \t]*\Q$name\E\s*=>[^\n]*\n((?:[ \t]*#[^\n]*(?:\n|\z))+)/; | |||
| 5077 | 79 | 155 | if(my $shape = _pod_nested_input_shape($p->{type}, $desc)) { | |||
| 5078 | 2 | 1 | $p->{schema} = $shape; | |||
| 5079 | } | |||||
| 5080 | ||||||
| 5081 | $self->_log(' POD: ' . $name . ' type ' | |||||
| 5082 | 79 | 2186 | . (defined($p->{type}) ? "'$p->{type}'" : '(none)') | |||
| 5083 | . ' from the Input hash'); | |||||
| 5084 | 79 | 79 | $count++; | |||
| 5085 | } | |||||
| 5086 | ||||||
| 5087 | 63 | 126 | return $count if $count; | |||
| 5088 | } | |||||
| 5089 | ||||||
| 5090 | 38 | 37 | my @found; | |||
| 5091 | my %row_text; | |||||
| 5092 | ||||||
| 5093 | # The table lists the arguments in call order, so it gives their positions. | |||||
| 5094 | 38 | 24 | my $position = 0; | |||
| 5095 | 38 | 41 | 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 | 38 | 54 | for my $line (split(/\n/, $block)) { | |||
| 5102 | 112 | 109 | if($line =~ /^(\s{0,8})(\\?[\$\@%]\w+\s*,\s*(?:\\?[\$\@%]\w+\s*,\s*)*\\?[\$\@%]\w+)\s*(.*)$/) { | |||
| 5103 | 1 | 3 | my ($indent, $names, $rest) = ($1, $2, $3); | |||
| 5104 | 1 3 | 2 5 | push @lines, map { $indent . $_ . " $rest" } ($names =~ /\\?([\$\@%]\w+)/g); | |||
| 5105 | } else { | |||||
| 5106 | 111 | 86 | push @lines, $line; | |||
| 5107 | } | |||||
| 5108 | } | |||||
| 5109 | ||||||
| 5110 | 38 | 47 | for my $line (@lines) { | |||
| 5111 | 114 | 455 | 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 | 114 | 373 | if($line =~ /^\s{0,8}(\w+)\s*:\s*\\?[\$\@%](\w+)\s+#\s*(\S.*)$/) { | |||
| 5116 | 2 | 3 | ($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 | 25 | 26 | ($name, $spec) = ($1, $2); | |||
| 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 | 25 | 23 | (my $first = $spec) =~ s/\A['"]//; | |||
| 5129 | 25 | 26 | ($first) = $first =~ /\A([A-Za-z]+)/; | |||
| 5130 | 25 | 45 | 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 | 5 | 11 | ($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 | 6 | 7 | ($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 | 1 | 2 | ($name, $spec, $prose) = ($1, $2, 1); | |||
| 5141 | } else { | |||||
| 5142 | 75 | 60 | next; | |||
| 5143 | } | |||||
| 5144 | ||||||
| 5145 | # Another routine's rows are not this routine's arguments. | |||||
| 5146 | 39 | 68 | next if defined($routine) && defined($row_routine) && $row_routine ne $routine; | |||
| 5147 | ||||||
| 5148 | 38 | 50 | next if $name =~ /^(?:self|class|pkg|proto|klass|returns?)$/i; | |||
| 5149 | ||||||
| 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 | 37 | 33 | (my $typed_spec = $spec) =~ s/\A['"]//; | |||
| 5153 | 37 | 36 | my ($type_word) = $typed_spec =~ /\A([A-Za-z]+)/; | |||
| 5154 | 37 | 22 | my $type; | |||
| 5155 | 37 | 28 | 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. | |||||
| 5159 | 8 | 7 | $type = _pod_input_prose_type($spec); | |||
| 5160 | 8 | 11 | $type = $types{lc($type_word)} if(!defined($type) && defined($type_word)); | |||
| 5161 | } else { | |||||
| 5162 | 29 | 28 | $type = defined($type_word) ? $types{lc($type_word)} : undef; | |||
| 5163 | 29 | 29 | $type = _pod_input_prose_type($spec) if(!defined($type) && $prose); | |||
| 5164 | } | |||||
| 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 | 37 | 55 | my $p = $params->{$name} //= {}; | |||
| 5171 | 37 | 47 | $p->{position} = $position++ unless defined $p->{position}; | |||
| 5172 | 37 | 37 | $p->{type} = $type if defined($type); | |||
| 5173 | 37 | 36 | $p->{_source} = SOURCE_INPUT_SPEC; | |||
| 5174 | 37 | 26 | $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 | 37 | 32 | if(my $shape = _pod_nested_input_shape($type, $spec)) { | |||
| 5179 | 2 | 2 | $p->{schema} = $shape; | |||
| 5180 | } | |||||
| 5181 | ||||||
| 5182 | 37 | 106 | if($spec =~ /\boptional\b/i || $spec =~ /\bdefault\b/i) { | |||
| 5183 | 14 | 9 | $p->{optional} = 1; | |||
| 5184 | } elsif($spec =~ /\b(?:required|mandatory)\b/i) { | |||||
| 5185 | 7 | 7 | $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 | 37 | 69 | if(defined($type) && $type eq 'arrayref' && $spec =~ /\b(?:one\s+or\s+more|at\s+least\s+one|non-empty)\b/i) { | |||
| 5194 | 6 | 4 | $p->{min} = 1; | |||
| 5195 | 6 | 7 | $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 | 37 | 76 | if(defined($type) && $type eq 'string' && $spec =~ /\b(?:readable|existing)\b[^;:]*\bfile\b/i) { | |||
| 5201 | 1 | 2 | $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 | 37 | 73 | if(defined($type) && $type eq 'string' && $spec =~ /\bdir(?:ectory)?\b/i | |||
| 5208 | && $spec =~ /\b(?:existing|readable|writable)\b/i) { | |||||
| 5209 | 1 | 1 | $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 | 37 | 123 | if($name =~ /\A(?:bytes|blob)\z/i | |||
| 5216 | || $spec =~ /\braw\s+bytes\b|file'?s\s+contents|\bbinary\s+(?:data|contents)\b/i) { | |||||
| 5217 | 1 | 1 | $p->{semantic} = 'bytes'; | |||
| 5218 | 1 | 2 | $p->{type} //= 'string'; | |||
| 5219 | } | |||||
| 5220 | ||||||
| 5221 | # A documented range, e.g. `lat : number -90 .. 90` | |||||
| 5222 | 37 | 60 | if($spec =~ /(-?\d+(?:\.\d+)?)\s*\.\.\s*(-?\d+(?:\.\d+)?)/) { | |||
| 5223 | 2 | 3 | $p->{min} = $1 + 0; | |||
| 5224 | 2 | 2 | $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. | |||||
| 5228 | } elsif($spec =~ /(-?\d[\d_]*)\s+to\s+(-?\d[\d_]*)/) { | |||||
| 5229 | 3 | 5 | $p->{min} = _undigitised($1); | |||
| 5230 | 3 | 4 | $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 default | |||||
| 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 | 37 | 70 | if(defined($type) && ($type =~ /\A(?:integer|number)\z/) | |||
| 5244 | && $spec =~ /\bdefault\b\s*\(?\s*(-?\d[\d_]*)/i) { | |||||
| 5245 | 3 | 3 | my $default = _undigitised($1); | |||
| 5246 | 3 | 4 | $p->{default} = $default; | |||
| 5247 | $p->{sample_max} = $default | |||||
| 5248 | if defined($p->{max}) && ($default > 0) | |||||
| 5249 | && ($p->{max} >= 10 * $default) | |||||
| 5250 | 3 | 9 | && (!defined($p->{min}) || ($default >= $p->{min})); | |||
| 5251 | } | |||||
| 5252 | ||||||
| 5253 | 37 | 39 | if(my $values = $self->_prose_memberof($spec)) { | |||
| 5254 | 0 | 0 | $p->{memberof} = $values; | |||
| 5255 | } | |||||
| 5256 | ||||||
| 5257 | 37 | 59 | $self->_log(' POD: ' . $name . ' type ' . (defined($type) ? "'$type'" : '(none)') | |||
| 5258 | . ' from the Input table'); | |||||
| 5259 | 37 | 38 | 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 | 38 | 61 | if($block =~ /^(\w+)\s+hashref\s+keys\s*:\s*\n(.*?)(?=\n\s*\n|\z)/msi) { | |||
| 5268 | 0 | 0 | my ($kind, $rows) = ($1, $2); | |||
| 5269 | 0 | 0 | my (%element, %alternation); | |||
| 5270 | 0 | 0 | for my $line (split /\n/, $rows) { | |||
| 5271 | 0 | 0 | next unless($line =~ /^\s{0,8}(\w+)\s*=>\s*(\S.*)$/); | |||
| 5272 | 0 | 0 | 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 | 0 | 0 | next if($text =~ /\brequired\b[^;]*\bexcept\b/i); | |||
| 5278 | 0 | 0 | my %spec = (type => 'string'); | |||
| 5279 | 0 | 0 | if($text =~ /\(([^)]*\|[^)]*)\)/) { | |||
| 5280 | 0 0 | 0 0 | my @values = map { s/\A\s+|\s+\z//gr } split /\|/, $1; | |||
| 5281 | 0 | 0 | $spec{memberof} = \@values if(@values); | |||
| 5282 | 0 | 0 | $alternation{$key} = \@values; | |||
| 5283 | } | |||||
| 5284 | 0 | 0 | if($text =~ /match(?:es)?\s+C?<\s*\/(.*?)\/\s*>/) { | |||
| 5285 | 0 | 0 | $spec{matches} = $1; | |||
| 5286 | } | |||||
| 5287 | 0 | 0 | $element{$key} = \%spec; | |||
| 5288 | } | |||||
| 5289 | ||||||
| 5290 | # The description says which listed function needs no further key; | |||||
| 5291 | # build the element for that one. | |||||
| 5292 | 0 | 0 | if(my ($except) = $rows =~ /\bexcept\s+(?:bare\s+)?(\w+)/i) { | |||
| 5293 | 0 | 0 | for my $key (keys %alternation) { | |||
| 5294 | 0 0 0 | 0 0 0 | next unless(grep { $_ eq $except } @{$alternation{$key}}); | |||
| 5295 | 0 | 0 | $element{$key}{memberof} = [ $except ]; | |||
| 5296 | } | |||||
| 5297 | } | |||||
| 5298 | ||||||
| 5299 | 0 | 0 | if(%element) { | |||
| 5300 | 0 0 | 0 0 | for my $name (keys %{$params}) { | |||
| 5301 | 0 | 0 | my $p = $params->{$name}; | |||
| 5302 | 0 | 0 | next unless(($p->{_source} // '') eq SOURCE_INPUT_SPEC); | |||
| 5303 | 0 | 0 | next unless((($p->{type} // '') =~ /^array/)); | |||
| 5304 | next unless(defined($row_text{$name}) | |||||
| 5305 | 0 | 0 | && $row_text{$name} =~ /arrayref\s+of\s+\Q$kind\E\s+hashrefs/i); | |||
| 5306 | 0 | 0 | $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 | 38 | 81 | if($block =~ /\bReserved keys\b/i) { | |||
| 5317 | 0 0 | 0 0 | for my $name (keys %{$params}) { | |||
| 5318 | 0 | 0 | my $p = $params->{$name}; | |||
| 5319 | 0 | 0 | next unless(($p->{_source} // '') eq SOURCE_INPUT_SPEC); | |||
| 5320 | ||||||
| 5321 | 0 | 0 | $p->{optional} = 1 unless(defined($p->{optional}) && !$p->{optional}); | |||
| 5322 | ||||||
| 5323 | 0 | 0 | my $type = $p->{type} // ''; | |||
| 5324 | 0 | 0 | next unless(($type eq 'arrayref') || ($type eq 'array') || ($type eq 'hashref')); | |||
| 5325 | 0 | 0 | next if(ref($p->{schema}) eq 'HASH'); | |||
| 5326 | 0 0 | 0 0 | next if(ref($p->{memberof}) eq 'ARRAY' && @{$p->{memberof}}); | |||
| 5327 | ||||||
| 5328 | 0 | 0 | delete $params->{$name} if($p->{optional}); | |||
| 5329 | } | |||||
| 5330 | } | |||||
| 5331 | ||||||
| 5332 | 38 | 80 | 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 | |||||
| 5359 | # verbose is set. | |||||
| 5360 | # -------------------------------------------------- | |||||
| 5361 | sub _analyze_output { | |||||
| 5362 | 475 | 2388 | my ($self, $pod, $code, $method_name) = @_; | |||
| 5363 | ||||||
| 5364 | 475 | 297 | my %output; | |||
| 5365 | ||||||
| 5366 | 475 | 701 | $self->_analyze_output_from_pod(\%output, $pod); | |||
| 5367 | 475 | 776 | $self->_analyze_output_from_code(\%output, $code, $method_name); | |||
| 5368 | 475 | 697 | $self->_enhance_boolean_detection(\%output, $pod, $code, $method_name); | |||
| 5369 | 475 | 739 | $self->_detect_list_context(\%output, $code); | |||
| 5370 | 475 | 742 | $self->_detect_void_context(\%output, $code, $method_name); | |||
| 5371 | 475 | 702 | $self->_detect_chaining_pattern(\%output, $code); | |||
| 5372 | 475 | 648 | $self->_detect_error_conventions(\%output, $code); | |||
| 5373 | ||||||
| 5374 | 475 | 852 | $self->_validate_output(\%output) if keys %output; | |||
| 5375 | ||||||
| 5376 | # Don't return empty output | |||||
| 5377 | 475 | 657 | 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. | |||||
| 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 | |||||
| 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 | 478 | 426 | my ($self, $output, $pod) = @_; | |||
| 5405 | 478 5258 | 492 4004 | my %VALID_OUTPUT_TYPES = map { $_ => 1 } | |||
| 5406 | qw(string integer number float boolean arrayref hashref object coderef void undef); | |||||
| 5407 | ||||||
| 5408 | 478 | 671 | 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 | 245 | 715 | if($pod =~ /=head4\s+Output\b(.*?)(?==head|\z)/si) { | |||
| 5415 | 81 | 90 | my $block = $1; | |||
| 5416 | 81 | 133 | $block =~ s/^\s+//; | |||
| 5417 | 81 | 273 | if($block =~ /^\(/) { | |||
| 5418 | 2 | 3 | $output->{type} = 'array'; | |||
| 5419 | 2 | 2 | $self->_log(" OUTPUT: type 'array' from =head4 Output list notation"); | |||
| 5420 | } elsif($block =~ /^\[/) { | |||||
| 5421 | 0 | 0 | unless($block =~ /^\[\s*\]/) { | |||
| 5422 | 0 | 0 | $output->{type} = 'arrayref'; | |||
| 5423 | 0 | 0 | $self->_log(" OUTPUT: type 'arrayref' from =head4 Output arrayref notation"); | |||
| 5424 | } | |||||
| 5425 | } elsif($block =~ /^\{/) { | |||||
| 5426 | 74 | 241 | if($block =~ /type\s*=>\s*['"]?(\w[\w:]*?)['"]?\s*[,}]/i) { | |||
| 5427 | 73 | 89 | my $type = lc($1); | |||
| 5428 | 73 | 218 | $type = 'string' if $type eq 'scalar' || $type eq 'scalarref' || $type eq 'str'; | |||
| 5429 | 73 | 114 | $type = 'integer' if $type eq 'int'; | |||
| 5430 | 73 | 235 | $type = 'number' if $type eq 'float' || $type eq 'num'; | |||
| 5431 | 73 | 132 | $type = 'boolean' if $type eq 'bool'; | |||
| 5432 | 73 | 97 | $type = 'hashref' if $type eq 'hash'; | |||
| 5433 | 73 | 112 | $type = 'arrayref' if $type eq 'array'; | |||
| 5434 | 73 | 110 | if($VALID_OUTPUT_TYPES{$type}) { | |||
| 5435 | 73 | 79 | $output->{type} = $type; | |||
| 5436 | 73 | 117 | $self->_log(" OUTPUT: type '$type' from =head4 Output formal spec"); | |||
| 5437 | } elsif($block =~ /\bisa\s*=>/) { | |||||
| 5438 | 0 | 0 | $output->{type} = 'object'; | |||
| 5439 | 0 | 0 | $self->_log(" OUTPUT: type 'object' from =head4 Output isa spec"); | |||
| 5440 | } | |||||
| 5441 | } elsif($block =~ /\bisa\s*=>/) { | |||||
| 5442 | 0 | 0 | $output->{type} = 'object'; | |||
| 5443 | 0 | 0 | $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 | 1 | 1 | $output->{type} = 'hashref'; | |||
| 5449 | 1 | 2 | $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) { | |||||
| 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 | 3 | 3 | my $word = lc($1); | |||
| 5457 | 3 | 8 | $output->{type} = ($word =~ /^array|^list/) ? 'arrayref' : 'hashref'; | |||
| 5458 | 3 | 5 | $self->_log(" OUTPUT: type '$output->{type}' from =head4 Output shape"); | |||
| 5459 | } | |||||
| 5460 | } | |||||
| 5461 | ||||||
| 5462 | # Pattern 1: Returns: section | |||||
| 5463 | # Up to 3 lines | |||||
| 5464 | 245 | 370 | if ($pod =~ /Returns?:\s+([^\n]+(?:\n[^\n]+){0,2})/si) { | |||
| 5465 | 8 | 8 | my $returns_desc = $1; | |||
| 5466 | 8 | 21 | $returns_desc =~ s/^\s+|\s+$//g; | |||
| 5467 | ||||||
| 5468 | 8 | 14 | $self->_log(" OUTPUT: Found Returns section: $returns_desc"); | |||
| 5469 | ||||||
| 5470 | # Try to infer type from description (skip if Pattern 0 already set type) | |||||
| 5471 | 8 | 111 | if (!$output->{type} && $returns_desc =~ /\b(string|text)\b/i) { | |||
| 5472 | 1 | 1 | $output->{type} = 'string'; | |||
| 5473 | } elsif (!$output->{type} && $returns_desc =~ /\b(integer|int|count)\b/i) { | |||||
| 5474 | 1 | 2 | $output->{type} = 'integer'; | |||
| 5475 | } elsif (!$output->{type} && $returns_desc =~ /\b(float|decimal|number)\b/i) { | |||||
| 5476 | 0 | 0 | $output->{type} = 'number'; | |||
| 5477 | } elsif (!$output->{type} && $returns_desc =~ /\b(boolean|true|false)\b/i) { | |||||
| 5478 | 1 | 2 | $output->{type} = 'boolean'; | |||
| 5479 | } elsif (!$output->{type} && $returns_desc =~ /\b(array|list)\b/i) { | |||||
| 5480 | 0 | 0 | $output->{type} = 'arrayref'; | |||
| 5481 | } elsif (!$output->{type} && $returns_desc =~ /\b(hash|hashref|dictionary)\b/i) { | |||||
| 5482 | 0 | 0 | $output->{type} = 'hashref'; | |||
| 5483 | } elsif (!$output->{type} && $returns_desc =~ /\b(object|instance)\b/i) { | |||||
| 5484 | 2 | 2 | $output->{type} = 'object'; | |||
| 5485 | } elsif (!$output->{type} && $returns_desc =~ /\bundef\b/i) { | |||||
| 5486 | 0 | 0 | $output->{type} = 'undef'; | |||
| 5487 | } | |||||
| 5488 | ||||||
| 5489 | # Look for specific values | |||||
| 5490 | 8 | 20 | if ($returns_desc =~ /\b1\s+(?:on\s+success|if\s+successful)\b/i) { | |||
| 5491 | 1 | 1 | $output->{value} = 1; | |||
| 5492 | 1 | 3 | if(defined($output->{'type'}) && ($output->{type} eq 'scalar')) { | |||
| 5493 | 0 | 0 | $output->{type} = 'boolean'; | |||
| 5494 | } else { | |||||
| 5495 | 1 | 2 | $output->{type} ||= 'boolean'; | |||
| 5496 | } | |||||
| 5497 | 1 | 2 | $self->_log(" OUTPUT: Returns 1 on success"); | |||
| 5498 | } elsif ($returns_desc =~ /\b0\s+(?:on\s+failure|if\s+fail)\b/i) { | |||||
| 5499 | 0 | 0 | $output->{alt_value} = 0; | |||
| 5500 | } elsif ($returns_desc =~ /dies\s+on\s+(?:error|failure)/i) { | |||||
| 5501 | 0 | 0 | $output->{_STATUS} = 'LIVES'; | |||
| 5502 | 0 | 0 | $self->_log(' OUTPUT: Should not die on success'); | |||
| 5503 | } | |||||
| 5504 | 8 | 17 | if ($returns_desc =~ /\b(true|false)\b/i) { | |||
| 5505 | 1 | 2 | $output->{type} ||= 'boolean'; | |||
| 5506 | } | |||||
| 5507 | 8 | 30 | if ($returns_desc =~ /\bundef\b/i) { | |||
| 5508 | 0 | 0 | $output->{optional} = 1; | |||
| 5509 | } | |||||
| 5510 | } | |||||
| 5511 | ||||||
| 5512 | # Pattern 2: Inline "returns X" | |||||
| 5513 | 245 | 737 | if((!$output->{type}) && ($pod =~ /returns?\s+(?:an?\s+)?(\w+)/i)) { | |||
| 5514 | 44 | 67 | my $type = lc($1); | |||
| 5515 | ||||||
| 5516 | 44 | 74 | $type = 'boolean' if $type =~ /^(true|false|bool)$/; | |||
| 5517 | # Skip if it's just a number (like "returns 1") | |||||
| 5518 | 44 | 50 | $type = 'integer' if $type eq 'int'; | |||
| 5519 | 44 | 67 | $type = 'number' if $type =~ /^(num|float)$/; | |||
| 5520 | 44 | 37 | $type = 'arrayref' if $type eq 'array'; | |||
| 5521 | 44 | 42 | $type = 'hashref' if $type eq 'hash'; | |||
| 5522 | ||||||
| 5523 | 44 | 57 | if($type =~ /^\d+$/) { | |||
| 5524 | 0 | 0 | if($type eq '1' || $type eq '0') { | |||
| 5525 | # Try hard to guess if the result is a boolean | |||||
| 5526 | 0 | 0 | if($pod =~ /1 on success.+0 (on|if) /i) { | |||
| 5527 | 0 | 0 | $type = 'boolean'; | |||
| 5528 | } elsif($pod =~ /return 0 .+ 1 on success/) { | |||||
| 5529 | 0 | 0 | $type = 'boolean'; | |||
| 5530 | } else { | |||||
| 5531 | 0 | 0 | $type = 'integer'; | |||
| 5532 | } | |||||
| 5533 | } else { | |||||
| 5534 | 0 | 0 | $type = 'integer'; | |||
| 5535 | } | |||||
| 5536 | } | |||||
| 5537 | ||||||
| 5538 | 44 | 50 | $type = 'arrayref' if !$type && $pod =~ /returns?\s+.+\slist\b/i; | |||
| 5539 | # $output->{type} = $type if $type && $type !~ /^\d+$/; | |||||
| 5540 | 44 | 39 | if ($VALID_OUTPUT_TYPES{$type}) { | |||
| 5541 | 14 | 21 | $output->{type} = $type; | |||
| 5542 | 14 | 19 | $self->_log(" OUTPUT: Inferred type from POD: $type"); | |||
| 5543 | } else { | |||||
| 5544 | 30 | 40 | $self->_log(" OUTPUT: POD return type '$type' is not a valid type, ignoring"); | |||
| 5545 | } | |||||
| 5546 | } | |||||
| 5547 | } | |||||
| 5548 | } | |||||
| 5549 | ||||||
| 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. | |||||
| 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 | 256 | 2179 | my ($self, $pod) = @_; | |||
| 5577 | ||||||
| 5578 | 256 | 242 | return {} unless $pod; | |||
| 5579 | ||||||
| 5580 | 255 | 172 | my %defaults; | |||
| 5581 | ||||||
| 5582 | # Pattern 1: Default: 'value' or Defaults to: 'value' | |||||
| 5583 | 255 | 517 | while ($pod =~ /(?:Default(?:s? to)?|default(?:s? to)?)[:]\s*([^\n\r]+)/gi) { | |||
| 5584 | 19 | 16 | my $default_text = $1; | |||
| 5585 | 19 | 12 | my $match_pos = pos($pod); | |||
| 5586 | 19 | 25 | $default_text =~ s/^\s+|\s+$//g; | |||
| 5587 | ||||||
| 5588 | # Look backwards in the POD to find the parameter name | |||||
| 5589 | 19 | 16 | my $context = substr($pod, 0, $match_pos); | |||
| 5590 | 19 | 33 | my @param_matches = ($context =~ /\$(\w+)/g); | |||
| 5591 | 19 | 15 | my $param = $param_matches[-1] if @param_matches; # Last parameter before default | |||
| 5592 | ||||||
| 5593 | 19 | 15 | if ($param) { | |||
| 5594 | # Always clean the default value - let _clean_default_value handle everything | |||||
| 5595 | 19 | 14 | if ($default_text =~ /(\w+)\s*=\s*(.+)$/) { | |||
| 5596 | # Has explicit param = value format in the default text | |||||
| 5597 | 0 | 0 | my ($p, $value) = ($1, $2); | |||
| 5598 | 0 | 0 | $defaults{$p} = $self->_clean_default_value($value); | |||
| 5599 | } else { | |||||
| 5600 | # Just a value, associate with the found param | |||||
| 5601 | 19 | 26 | $defaults{$param} = $self->_clean_default_value($default_text, 0); # NOT from code | |||
| 5602 | } | |||||
| 5603 | } | |||||
| 5604 | } | |||||
| 5605 | ||||||
| 5606 | # Pattern 2: Optional, default 'value' | |||||
| 5607 | 255 | 482 | while ($pod =~ /Optional(?:,)?\s+(?:default|value)\s*[:=]?\s*([^\n\r,;]+)/gi) { | |||
| 5608 | 8 | 9 | my $default_text = $1; | |||
| 5609 | 8 | 8 | my $match_pos = pos($pod); | |||
| 5610 | 8 | 10 | $default_text =~ s/^\s+|\s+$//g; | |||
| 5611 | ||||||
| 5612 | # Look backwards for parameter name | |||||
| 5613 | 8 | 11 | my $context = substr($pod, 0, $match_pos); | |||
| 5614 | 8 | 13 | my @param_matches = ($context =~ /\$(\w+)/g); | |||
| 5615 | 8 | 12 | if (@param_matches) { | |||
| 5616 | 7 | 6 | my $param = $param_matches[-1]; # Last parameter before the default | |||
| 5617 | 7 | 8 | $defaults{$param} = $self->_clean_default_value($default_text, 0); | |||
| 5618 | } | |||||
| 5619 | } | |||||
| 5620 | ||||||
| 5621 | # Pattern 3: In parameter descriptions: $param - type, default 'value' | |||||
| 5622 | 255 | 528 | while ($pod =~ /\$(\w+)\s*-\s*\w+(?:\([^)]*\))?[,\s]+default\s+['"]?([^'",\n]+)['"]?/gi) { | |||
| 5623 | 1 | 3 | my ($param, $value) = ($1, $2); | |||
| 5624 | 1 | 2 | $defaults{$param} = $self->_clean_default_value($value, 0); | |||
| 5625 | } | |||||
| 5626 | ||||||
| 5627 | 255 | 234 | return \%defaults; | |||
| 5628 | } | |||||
| 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). | |||||
| 5640 | # $code - method body source string. | |||||
| 5641 | # $method_name - method name string. | |||||
| 5642 | # | |||||
| 5643 | # Exit: Returns nothing. Modifies $output | |||||
| 5644 | # in place. | |||||
| 5645 | # | |||||
| 5646 | # Side effects: Logs detections to stdout when | |||||
| 5647 | # verbose is set. | |||||
| 5648 | # -------------------------------------------------- | |||||
| 5649 | sub _analyze_output_from_code | |||||
| 5650 | { | |||||
| 5651 | 477 | 459 | my ($self, $output, $code, $method_name) = @_; | |||
| 5652 | ||||||
| 5653 | 477 | 439 | if ($code) { | |||
| 5654 | # Early boolean detection - check for consistent 1/0 returns | |||||
| 5655 | 477 | 1072 | my @all_returns = $code =~ /return\s+([^;]+);/g; | |||
| 5656 | 477 | 451 | if (@all_returns) { | |||
| 5657 | 455 | 307 | my $boolean_count = 0; | |||
| 5658 | 455 | 789 | my $total_count = scalar(@all_returns); | |||
| 5659 | ||||||
| 5660 | 455 | 454 | foreach my $ret (@all_returns) { | |||
| 5661 | 511 | 950 | $ret =~ s/^\s+|\s+$//g; | |||
| 5662 | # Match 0 or 1, even with conditions | |||||
| 5663 | 511 | 695 | $boolean_count++ if ($ret =~ /^(?:0|1)(?:\s|$)/); | |||
| 5664 | } | |||||
| 5665 | ||||||
| 5666 | # If most returns are 0 or 1, strongly suggest boolean | |||||
| 5667 | 455 | 999 | if ($boolean_count >= 2 && $boolean_count >= $total_count * 0.8) { | |||
| 5668 | 6 | 9 | unless ($output->{type}) { | |||
| 5669 | 6 | 7 | $output->{type} = 'boolean'; | |||
| 5670 | 6 | 12 | $self->_log(" OUTPUT: Early detection - $boolean_count/$total_count returns are 0/1, setting boolean"); | |||
| 5671 | } | |||||
| 5672 | } | |||||
| 5673 | } | |||||
| 5674 | ||||||
| 5675 | 477 | 291 | my @return_statements; | |||
| 5676 | ||||||
| 5677 | 477 | 2465 | if ($code =~ /return\s+bless\s*\{[^}]*\}\s*,\s*['"]?(\w+)['"]?/s) { | |||
| 5678 | # Detect blessed refs | |||||
| 5679 | 4 | 5 | $output->{type} = 'object'; | |||
| 5680 | 4 | 4 | if($method_name eq 'new') { | |||
| 5681 | # If we found the new() method, the object we're returning should be a sensible one | |||||
| 5682 | 2 | 5 | if($self->{_document} && (my $package_stmt = $self->{_document}->find_first('PPI::Statement::Package'))) { | |||
| 5683 | 2 | 122 | $output->{isa} = $package_stmt->namespace(); | |||
| 5684 | 2 | 21 | $self->{_package_name} //= $output->{isa}; | |||
| 5685 | } | |||||
| 5686 | } else { | |||||
| 5687 | 2 | 4 | $output->{isa} = $1; | |||
| 5688 | } | |||||
| 5689 | 4 | 10 | $self->_log(" OUTPUT: Bless found, inferring type from code is $output->{isa}"); | |||
| 5690 | } elsif ($code =~ /return\s+bless/s) { | |||||
| 5691 | 35 | 50 | $output->{type} = 'object'; | |||
| 5692 | 35 | 45 | if($method_name eq 'new') { | |||
| 5693 | 33 | 149 | $output->{isa} = $self->_extract_package_name(); | |||
| 5694 | 33 | 395 | $self->_log(" OUTPUT: Bless found, inferring type from code is $output->{isa}"); | |||
| 5695 | } else { | |||||
| 5696 | 2 | 3 | $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 | 1 | 1 | $output->{type} = 'array'; # Not arrayref - actual array | |||
| 5701 | 1 | 1 | $self->_log(' OUTPUT: Found array contect return'); | |||
| 5702 | } elsif ($code =~ /return\s+bless[^,]+,\s*__PACKAGE__/) { | |||||
| 5703 | # Detect: bless {}, __PACKAGE__ | |||||
| 5704 | 0 | 0 | $output->{type} = 'object'; | |||
| 5705 | # Get package name from the extractor's stored document | |||||
| 5706 | 0 | 0 | if ($self->{_document}) { | |||
| 5707 | 0 | 0 | my $pkg = $self->{_document}->find_first('PPI::Statement::Package'); | |||
| 5708 | 0 | 0 | $output->{isa} = $pkg ? $pkg->namespace : 'UNKNOWN'; | |||
| 5709 | 0 | 0 | $self->_log(' OUTPUT: Object blessed into __PACKAGE__: ' . ($output->{isa} || 'UNKNOWN')); | |||
| 5710 | 0 | 0 | $self->{_package_name} //= $output->{isa}; | |||
| 5711 | } | |||||
| 5712 | } elsif ($code =~ /return\s*\(([^)]+)\)/) { | |||||
| 5713 | 3 | 4 | my $content = $1; | |||
| 5714 | 3 | 8 | if ($content =~ /,/) { # Has comma = multiple values | |||
| 5715 | 0 | 0 | $output->{type} = 'array'; | |||
| 5716 | } | |||||
| 5717 | } elsif ($code =~ /return\s+\$self\s*;/ && $code =~ /\$self\s*->\s*\{[^}]+\}\s*=/) { | |||||
| 5718 | # Returns $self for chaining | |||||
| 5719 | 10 | 10 | $output->{type} = 'object'; | |||
| 5720 | 10 | 45 | if ($self->{_document}) { | |||
| 5721 | 10 | 16 | my $pkg = $self->{_document}->find_first('PPI::Statement::Package'); | |||
| 5722 | 10 | 751 | $output->{isa} = $pkg ? $pkg->namespace : 'UNKNOWN'; | |||
| 5723 | 10 | 135 | $self->_log(' OUTPUT: Object chained into __PACKAGE__: ' . ($output->{isa} || 'UNKNOWN')); | |||
| 5724 | 10 | 14 | $self->{_package_name} //= $output->{isa}; | |||
| 5725 | } | |||||
| 5726 | } | |||||
| 5727 | ||||||
| 5728 | # Find all return statements | |||||
| 5729 | 477 | 989 | while ($code =~ /return\s+([^;]+);/g) { | |||
| 5730 | 511 | 482 | my $return_expr = $1; | |||
| 5731 | 511 | 555 | push @return_statements, $return_expr; | |||
| 5732 | } | |||||
| 5733 | ||||||
| 5734 | 477 | 392 | if (@return_statements) { | |||
| 5735 | 455 | 726 | $self->_log(' OUTPUT: Found ' . scalar(@return_statements) . ' return statement(s)'); | |||
| 5736 | ||||||
| 5737 | # Analyze return patterns | |||||
| 5738 | 455 | 304 | my %return_types; | |||
| 5739 | ||||||
| 5740 | 455 | 496 | if($output->{'type'}) { | |||
| 5741 | 145 | 200 | $return_types{$output->{'type'}} += 3; # Add weighting to what's already been found | |||
| 5742 | } | |||||
| 5743 | 455 | 359 | my $min; | |||
| 5744 | my $time_list; | |||||
| 5745 | 455 | 349 | foreach my $ret (@return_statements) { | |||
| 5746 | 511 | 886 | $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 | 511 | 507 | my $ops_ret = _strip_literals($ret); | |||
| 5753 | ||||||
| 5754 | # Literal values | |||||
| 5755 | 511 | 2516 | if ($ret eq '1' || $ret eq '0') { | |||
| 5756 | 39 | 43 | $return_types{boolean}++; | |||
| 5757 | } elsif ($ret =~ /^['"]/) { | |||||
| 5758 | 33 | 36 | $return_types{string}++; | |||
| 5759 | } elsif ($ret =~ /^-?\d+$/) { | |||||
| 5760 | 107 | 111 | $return_types{integer}++; | |||
| 5761 | } elsif ($ret =~ /^-?\d+\.\d+$/) { | |||||
| 5762 | 0 | 0 | $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 | 38 | 50 | $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 | 10 | 11 | $return_types{undef}++; | |||
| 5772 | } elsif ($self->_returns_time_list($ret)) { | |||||
| 5773 | # localtime and gmtime give the nine-element time list in | |||||
| 5774 | # list context; the arithmetic in their argument does not | |||||
| 5775 | # make the return a number. | |||||
| 5776 | 1 | 2 | $return_types{array} += 2; | |||
| 5777 | 1 | 1 | $time_list = 1; | |||
| 5778 | } elsif ($ret =~ /^\[/) { | |||||
| 5779 | # Data structures | |||||
| 5780 | 10 | 11 | $return_types{arrayref}++; | |||
| 5781 | } elsif ($ret =~ /^\{/) { | |||||
| 5782 | 6 | 7 | $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 | 4 | 6 | $return_types{hashref}++; | |||
| 5788 | } elsif ($ret =~ /^\\\@/) { | |||||
| 5789 | 0 | 0 | $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 | 52 | 74 | $return_types{number} += 2; | |||
| 5800 | } elsif ($ret =~ /\|\|\s*\d+\b/) { | |||||
| 5801 | # Logical-or fallback with numeric literal (e.g. $x || 200) | |||||
| 5802 | 1 | 2 | $return_types{integer} += 2; | |||
| 5803 | 1 | 1 | $self->_log(" OUTPUT: Numeric fallback expression detected"); | |||
| 5804 | } elsif($ret =~ /^length[\s\(]/) { | |||||
| 5805 | 2 | 3 | $return_types{integer}++; | |||
| 5806 | 2 | 2 | $min = 0; | |||
| 5807 | } elsif($ret =~ /^pos[\s\(]/) { | |||||
| 5808 | 0 | 0 | $return_types{integer}++; | |||
| 5809 | 0 | 0 | $min = 0; | |||
| 5810 | } elsif($ret =~ /^index[\s\(]/) { | |||||
| 5811 | 0 | 0 | $return_types{integer}++; | |||
| 5812 | 0 | 0 | $min = -1; | |||
| 5813 | } elsif($ret =~ /^rindex[\s\(]/) { | |||||
| 5814 | 0 | 0 | $return_types{integer}++; | |||
| 5815 | 0 | 0 | $min = -1; | |||
| 5816 | } elsif($ret =~ /^ord[\s\(]/) { | |||||
| 5817 | 0 | 0 | $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 | 37 | 53 | (my $numeric_ret = $ops_ret) =~ s/\$\d+//g; | |||
| 5826 | 37 | 74 | if ($numeric_ret =~ /\b\d+\b/) { | |||
| 5827 | 14 | 17 | $return_types{integer} += 2; | |||
| 5828 | 14 | 20 | $self->_log(" OUTPUT: Assignment with numeric value detected"); | |||
| 5829 | } else { | |||||
| 5830 | 23 | 37 | $return_types{scalar}++; | |||
| 5831 | } | |||||
| 5832 | } | |||||
| 5833 | # Variables/expressions | |||||
| 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 | |||||
| 5838 | # arrayref because of it. | |||||
| 5839 | 160 | 185 | (my $ref_ret = $ret) =~ s/\\\@_\b//g; | |||
| 5840 | 160 | 491 | if ($ref_ret =~ /\\\@/) { | |||
| 5841 | 0 | 0 | $return_types{arrayref}++; | |||
| 5842 | } elsif ($ref_ret =~ /\\\%/) { | |||||
| 5843 | 3 | 4 | $return_types{hashref}++; | |||
| 5844 | } elsif ($ret =~ /bless/) { | |||||
| 5845 | 4 | 6 | $return_types{object} += 2; # Heigher weight | |||
| 5846 | } elsif ($ret =~ /^\{[^}]*\}$/) { | |||||
| 5847 | 0 | 0 | $return_types{hashref}++; | |||
| 5848 | } elsif ($ret =~ /^\[[^\]]*\]$/) { | |||||
| 5849 | 0 | 0 | $return_types{arrayref}++; | |||
| 5850 | } else { | |||||
| 5851 | 153 | 206 | $return_types{scalar}++; | |||
| 5852 | } | |||||
| 5853 | } | |||||
| 5854 | } | |||||
| 5855 | ||||||
| 5856 | # Determine most common return type | |||||
| 5857 | 455 | 437 | if (keys %return_types) { | |||
| 5858 | # The undef paths are the documented error return | |||||
| 5859 | # (_error_return), not the type of a successful value: a | |||||
| 5860 | # routine returning a record or undef returns a record when | |||||
| 5861 | # it succeeds, however many guards send it back undef. | |||||
| 5862 | 451 | 522 | my %value_types = %return_types; | |||
| 5863 | 451 | 520 | 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 | 451 97 | 583 199 | 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 | 451 | 638 | if ($return_types{integer} && (!$return_types{string})) { | |||
| 5871 | 124 | 171 | if (!$output->{type} || $output->{type} eq 'scalar') { | |||
| 5872 | 106 | 82 | $output->{type} = 'integer'; | |||
| 5873 | 106 | 106 | $self->_log(" OUTPUT: Numeric returns dominate, forcing integer"); | |||
| 5874 | 106 | 170 | $output->{_type_confidence} ||= 'low'; | |||
| 5875 | 106 | 83 | if(defined($min)) { | |||
| 5876 | 2 | 2 | $output->{min} = $min; | |||
| 5877 | } | |||||
| 5878 | } | |||||
| 5879 | } | |||||
| 5880 | 451 | 489 | unless ($output->{type}) { | |||
| 5881 | 200 | 207 | $output->{type} = $most_common; | |||
| 5882 | ||||||
| 5883 | # Assign confidence for inferred numeric expressions | |||||
| 5884 | 200 | 217 | if ($most_common eq 'number') { | |||
| 5885 | 35 | 90 | $output->{_type_confidence} ||= 'medium'; | |||
| 5886 | 35 | 38 | if(defined($min)) { | |||
| 5887 | 0 | 0 | $output->{min} = $min; | |||
| 5888 | } | |||||
| 5889 | } | |||||
| 5890 | ||||||
| 5891 | 200 | 230 | $self->_log(" OUTPUT: Inferred type from code: $most_common"); | |||
| 5892 | } | |||||
| 5893 | ||||||
| 5894 | 451 | 588 | 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 | 1 | 1 | $output->{element_type} = 'number'; | |||
| 5899 | } | |||||
| 5900 | } | |||||
| 5901 | ||||||
| 5902 | # Check for consistent single value returns | |||||
| 5903 | 455 | 1066 | if (@return_statements == 1 && $return_statements[0] eq '1') { | |||
| 5904 | 28 | 32 | $output->{value} = 1; | |||
| 5905 | 28 | 67 | $output->{type} = 'boolean' if !$output->{type} || $output->{type} eq 'scalar'; | |||
| 5906 | 28 | 55 | $self->_log(" OUTPUT: Type already set to '$output->{type}', overriding with boolean") if($output->{'type'}); | |||
| 5907 | } | |||||
| 5908 | } else { | |||||
| 5909 | # No explicit return - might return nothing or implicit undef | |||||
| 5910 | 22 | 21 | $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 | 476 | 546 | my ($self, $output, $pod, $code, $method_name) = @_; | |||
| 5944 | ||||||
| 5945 | 476 | 330 | my $boolean_score = 0; # Track evidence for boolean return | |||
| 5946 | ||||||
| 5947 | 476 | 888 | return unless !$output->{type} || $output->{type} eq 'unknown'; | |||
| 5948 | ||||||
| 5949 | # Look for stronger boolean indicators | |||||
| 5950 | 28 | 77 | if ($pod && !$output->{type}) { | |||
| 5951 | # Common boolean return patterns in POD | |||||
| 5952 | 6 | 11 | if ($pod =~ /returns?\s+(?:true|false|1|0)\s+(?:on|for|upon)\s+(?:success|failure|error|valid|invalid)/i) { | |||
| 5953 | 0 | 0 | $boolean_score += 30; | |||
| 5954 | 0 | 0 | $self->_log(' OUTPUT: Strong boolean indicator in POD (+30)'); | |||
| 5955 | } | |||||
| 5956 | ||||||
| 5957 | # Check for method names that suggest boolean returns | |||||
| 5958 | 6 | 20 | if ($pod =~ /(?:method|sub)\s+(\w+)/) { | |||
| 5959 | 0 | 0 | my $inferred_method_name = $1; | |||
| 5960 | 0 | 0 | if ($inferred_method_name =~ /^(is_|has_|can_|should_|contains_|exists_)/) { | |||
| 5961 | 0 | 0 | $boolean_score += 20; | |||
| 5962 | 0 | 0 | $self->_log(" OUTPUT: Inferred method name '$inferred_method_name' suggests boolean return (+20)"); | |||
| 5963 | } | |||||
| 5964 | } | |||||
| 5965 | } | |||||
| 5966 | ||||||
| 5967 | # Analyze code for boolean patterns | |||||
| 5968 | 28 | 23 | if ($code) { | |||
| 5969 | # Count boolean return idioms | |||||
| 5970 | 28 | 48 | my $true_returns = () = $code =~ /return\s+1\s*;/g; | |||
| 5971 | 28 | 35 | my $false_returns = () = $code =~ /return\s+0\s*;/g; | |||
| 5972 | ||||||
| 5973 | 28 | 50 | if ($true_returns + $false_returns >= 2) { | |||
| 5974 | 0 | 0 | $boolean_score += 40; | |||
| 5975 | 0 | 0 | $self->_log(' OUTPUT: Multiple 1/0 returns suggest boolean (+40)'); | |||
| 5976 | } elsif ($true_returns + $false_returns == 1) { | |||||
| 5977 | 2 | 2 | $boolean_score += 10; | |||
| 5978 | 2 | 3 | $self->_log(' OUTPUT: Single 1/0 return (+10)'); | |||
| 5979 | } | |||||
| 5980 | ||||||
| 5981 | # Ternary operators that return booleans | |||||
| 5982 | 28 | 39 | 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 | 0 | 0 | $boolean_score += 25; | |||
| 5984 | 0 | 0 | $self->_log(' OUTPUT: Ternary with 1/0 suggests boolean (+25)'); | |||
| 5985 | } | |||||
| 5986 | ||||||
| 5987 | # Check for common boolean method patterns | |||||
| 5988 | 28 | 49 | if ($code =~ /return\s+[!\$\@\%]/) { | |||
| 5989 | # Returns negation or existence check | |||||
| 5990 | 0 | 0 | $boolean_score += 15; | |||
| 5991 | 0 | 0 | $self->_log(' OUTPUT: Returns negation/existence check (+15)'); | |||
| 5992 | } | |||||
| 5993 | } | |||||
| 5994 | ||||||
| 5995 | # Check method name for boolean indicators | |||||
| 5996 | 28 | 36 | if ($method_name) { | |||
| 5997 | 28 | 43 | if ($method_name =~ /^(?:is_|has_|can_|should_|contains_|exists_|check_|verify_|validate_)/) { | |||
| 5998 | 2 | 1 | $boolean_score += 25; | |||
| 5999 | 2 | 3 | $self->_log(" OUTPUT: Method name '$method_name' suggests boolean return (+25)"); | |||
| 6000 | } | |||||
| 6001 | 28 | 64 | if ($method_name =~ /_ok$/) { | |||
| 6002 | 0 | 0 | $boolean_score += 30; | |||
| 6003 | 0 | 0 | $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 | 28 | 46 | if($boolean_score >= $BOOLEAN_SCORE_THRESHOLD) { | |||
| 6010 | 2 | 6 | if (!$output->{type} || $output->{type} eq 'scalar' || $output->{type} eq 'array' || $output->{type} eq 'undef') { | |||
| 6011 | 2 | 3 | my $old_type = $output->{type} || 'none'; | |||
| 6012 | 2 | 2 | $output->{type} = 'boolean'; | |||
| 6013 | 2 | 4 | $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 | |||||
| 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 | 476 | 426 | my ($self, $output, $code) = @_; | |||
| 6040 | 476 | 420 | return unless $code; | |||
| 6041 | ||||||
| 6042 | # Check for wantarray usage | |||||
| 6043 | 476 | 572 | if ($code =~ /wantarray/) { | |||
| 6044 | 5 | 6 | $output->{_context_aware} = 1; | |||
| 6045 | 5 | 6 | $self->_log(' OUTPUT: Method uses wantarray - context sensitive'); | |||
| 6046 | ||||||
| 6047 | # Debug: show what we're matching against | |||||
| 6048 | 5 | 9 | if ($code =~ /(wantarray[^;]+;)/s) { | |||
| 6049 | 4 | 11 | $self->_log(" DEBUG wantarray line: $1"); | |||
| 6050 | } | |||||
| 6051 | ||||||
| 6052 | 5 | 21 | if ($code =~ /wantarray\s*\?\s*\(([^)]+)\)\s*:\s*([^;]+)/s) { | |||
| 6053 | # Pattern 1: wantarray ? (list, items) : scalar_value (with parens) | |||||
| 6054 | 1 | 1 | my ($list_return, $scalar_return) = ($1, $2); | |||
| 6055 | 1 | 2 | $self->_log(" DEBUG list (with parens): [$list_return], scalar: [$scalar_return]"); | |||
| 6056 | ||||||
| 6057 | 1 | 2 | $output->{_list_context} = $self->_infer_type_from_expression($list_return); | |||
| 6058 | 1 | 1 | $output->{_scalar_context} = $self->_infer_type_from_expression($scalar_return); | |||
| 6059 | 1 | 1 | $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 | 3 | 6 | my ($list_return, $scalar_return) = ($1, $2); | |||
| 6063 | # Clean up | |||||
| 6064 | 3 | 4 | $list_return =~ s/^\s+|\s+$//g; | |||
| 6065 | 3 | 6 | $scalar_return =~ s/^\s+|\s+$//g; | |||
| 6066 | ||||||
| 6067 | 3 | 8 | $self->_log(" DEBUG list (no parens): [$list_return], scalar: [$scalar_return]"); | |||
| 6068 | ||||||
| 6069 | 3 | 6 | $output->{_list_context} = $self->_infer_type_from_expression($list_return); | |||
| 6070 | 3 | 4 | $output->{_scalar_context} = $self->_infer_type_from_expression($scalar_return); | |||
| 6071 | 3 | 4 | $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 | 1 | 0 | $output->{_list_context} = { type => 'array' }; | |||
| 6075 | 1 | 2 | $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 | 476 | 739 | if ($code =~ /return\s*\(\s*([^)]+)\s*\)\s*;/) { | |||
| 6082 | 4 | 4 | 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 | 4 | 319 | require Text::Balanced; | |||
| 6087 | 4 | 3034 | my $comma_count = 0; | |||
| 6088 | 4 | 2 | my $rest = $content; | |||
| 6089 | 4 | 6 | while (length $rest) { | |||
| 6090 | 44 | 31 | if (substr($rest, 0, 1) =~ /[(\[{]/) { | |||
| 6091 | 5 | 7 | my $extracted = Text::Balanced::extract_bracketed($rest, '(){}[]'); | |||
| 6092 | 5 | 311 | last unless defined $extracted; # Unbalanced brackets | |||
| 6093 | 5 | 5 | next; | |||
| 6094 | } | |||||
| 6095 | 39 | 26 | $comma_count++ if substr($rest, 0, 1) eq ','; | |||
| 6096 | 39 | 43 | $rest = substr($rest, 1); | |||
| 6097 | } | |||||
| 6098 | ||||||
| 6099 | 4 | 11 | if ($comma_count > 0 && $content !~ /\b(?:bless|new)\b/) { | |||
| 6100 | # Multiple values returned | |||||
| 6101 | 3 | 6 | unless ($output->{type} && $output->{type} eq 'boolean') { | |||
| 6102 | 3 | 2 | $output->{type} = 'array'; | |||
| 6103 | 3 | 3 | $output->{_list_return} = $comma_count + 1; | |||
| 6104 | 3 | 4 | $self->_log(' OUTPUT: Returns list of ' . ($comma_count + 1) . ' values'); | |||
| 6105 | } | |||||
| 6106 | } | |||||
| 6107 | } | |||||
| 6108 | } | |||||
| 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 | # | |||||
| 6118 | # Entry: $ret - a return expression. | |||||
| 6119 | # | |||||
| 6120 | # Exit: Returns true when the whole | |||||
| 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 | 284 | 273 | my ($self, $ret) = @_; | |||
| 6127 | ||||||
| 6128 | 284 | 269 | return 0 unless defined($ret); | |||
| 6129 | 284 | 2587 | return 0 unless $ret =~ /(?:\A|[?:])\s*\(*\s*(?:localtime|gmtime)\s*\(/; | |||
| 6130 | ||||||
| 6131 | 1 | 4 | 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 | |||||
| 6145 | # (modified in place). | |||||
| 6146 | # $code - method body source string. | |||||
| 6147 | # $method_name - method name string. | |||||
| 6148 | # | |||||
| 6149 | # Exit: Returns nothing. Modifies $output | |||||
| 6150 | # in place, setting _void_context, | |||||
| 6151 | # _success_indicator, and/or type. | |||||
| 6152 | # | |||||
| 6153 | # Side effects: Logs detections to stdout when | |||||
| 6154 | # verbose is set. | |||||
| 6155 | # -------------------------------------------------- | |||||
| 6156 | sub _detect_void_context { | |||||
| 6157 | 476 | 439 | my ($self, $output, $code, $method_name) = @_; | |||
| 6158 | 476 | 413 | return unless $code; | |||
| 6159 | ||||||
| 6160 | 476 | 568 | $self->_log(" DEBUG _detect_void_context called for $method_name"); | |||
| 6161 | ||||||
| 6162 | # Methods that typically don't return meaningful values | |||||
| 6163 | 476 | 1550 | 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 | 476 | 555 | foreach my $type (keys %$void_patterns) { | |||
| 6172 | 1872 | 2379 | if ($method_name =~ $void_patterns->{$type}) { | |||
| 6173 | 16 | 14 | $output->{_void_context_hint} = $type; | |||
| 6174 | 16 | 24 | $self->_log(" OUTPUT: Method name suggests $type (typically void context)"); | |||
| 6175 | 16 | 11 | last; | |||
| 6176 | } | |||||
| 6177 | } | |||||
| 6178 | ||||||
| 6179 | # Analyze return statements | |||||
| 6180 | 476 | 840 | my @returns = $code =~ /return\s*([^;]*);/g; | |||
| 6181 | ||||||
| 6182 | 476 | 648 | $self->_log(' DEBUG Found ' . scalar(@returns) . ' return statements'); | |||
| 6183 | ||||||
| 6184 | # Count different return patterns | |||||
| 6185 | 476 | 366 | my $no_value_returns = 0; | |||
| 6186 | 476 | 317 | my $true_returns = 0; | |||
| 6187 | 476 | 295 | my $self_returns = 0; | |||
| 6188 | ||||||
| 6189 | 476 | 393 | foreach my $ret (@returns) { | |||
| 6190 | 515 | 812 | $ret =~ s/^\s+|\s+$//g; | |||
| 6191 | 515 | 587 | $self->_log(" DEBUG return value: [$ret]"); | |||
| 6192 | 515 | 431 | $no_value_returns++ if $ret eq ''; | |||
| 6193 | 515 | 535 | $no_value_returns++ if($ret =~ /^(if|unless)\s/); | |||
| 6194 | 515 | 415 | $true_returns++ if $ret eq '1'; | |||
| 6195 | 515 | 410 | $self_returns++ if $ret eq '$self'; | |||
| 6196 | 515 | 564 | if ($ret =~ /\?\s*1\s*:\s*0\b/) { | |||
| 6197 | # Strong boolean signal: ternary returning 1/0 | |||||
| 6198 | 12 | 12 | $true_returns++; | |||
| 6199 | # $self->_log(" OUTPUT: Ternary 1:0 return detected, treating as boolean (+40)"); | |||||
| 6200 | 12 | 12 | $self->_log(' OUTPUT: Ternary 1:0 return detected, treating as boolean'); | |||
| 6201 | } | |||||
| 6202 | } | |||||
| 6203 | ||||||
| 6204 | 476 | 324 | my $total_returns = scalar(@returns); | |||
| 6205 | ||||||
| 6206 | 476 | 700 | $self->_log(" DEBUG no_value=$no_value_returns, true=$true_returns, self=$self_returns, total=$total_returns"); | |||
| 6207 | ||||||
| 6208 | # Void context indicators | |||||
| 6209 | 476 | 1404 | if ($no_value_returns > 0 && $no_value_returns == $total_returns) { | |||
| 6210 | 7 | 6 | $output->{_void_context} = 1; | |||
| 6211 | 7 | 6 | $output->{type} = 'void'; # This should override any previous type | |||
| 6212 | 7 | 6 | $self->_log(' OUTPUT: All returns are empty - void context method'); | |||
| 6213 | } elsif ($true_returns > 0 && $true_returns == $total_returns && $total_returns >= 1) { | |||||
| 6214 | # Methods that always return true (success indicator) | |||||
| 6215 | 41 | 91 | $output->{_success_indicator} = 1; | |||
| 6216 | # Don't override type if already set to boolean | |||||
| 6217 | 41 | 91 | unless ($output->{type} && $output->{type} eq 'boolean') { | |||
| 6218 | 5 | 6 | $output->{type} = 'boolean'; | |||
| 6219 | } | |||||
| 6220 | 41 | 38 | $self->_log(' OUTPUT: Always returns 1 - success indicator pattern'); | |||
| 6221 | } | |||||
| 6222 | } | |||||
| 6223 | ||||||
| 6224 | # -------------------------------------------------- | |||||
| 6225 | # _detect_chaining_pattern | |||||
| 6226 | # | |||||
| 6227 | # Purpose: Detect methods that return $self for | |||||
| 6228 | # fluent interface chaining, by counting | |||||
| 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 | 475 | 394 | my ($self, $output, $code) = @_; | |||
| 6247 | 475 | 369 | return unless $code; | |||
| 6248 | ||||||
| 6249 | # Count returns of $self | |||||
| 6250 | 475 | 297 | my $self_returns = 0; | |||
| 6251 | 475 | 279 | my $total_returns = 0; | |||
| 6252 | ||||||
| 6253 | 475 | 816 | while ($code =~ /return\s+([^;]+);/g) { | |||
| 6254 | 508 | 392 | my $ret = $1; | |||
| 6255 | 508 | 761 | $ret =~ s/^\s+|\s+$//g; | |||
| 6256 | 508 | 280 | $total_returns++; | |||
| 6257 | 508 | 556 | $self_returns++ if $ret eq '$self'; | |||
| 6258 | } | |||||
| 6259 | ||||||
| 6260 | # If most/all returns are $self, it's a chaining method | |||||
| 6261 | 475 | 566 | if ($self_returns > 0 && $total_returns > 0) { | |||
| 6262 | 12 | 11 | my $ratio = $self_returns / $total_returns; | |||
| 6263 | ||||||
| 6264 | 12 | 13 | if ($ratio >= 0.8) { | |||
| 6265 | 10 | 12 | $output->{type} = 'object'; | |||
| 6266 | 10 | 13 | $output->{_returns_self} = 1; | |||
| 6267 | ||||||
| 6268 | # Get the class name | |||||
| 6269 | 10 | 14 | if ($self->{_document}) { | |||
| 6270 | 9 | 13 | my $pkg = $self->{_document}->find_first('PPI::Statement::Package'); | |||
| 6271 | 9 | 429 | $output->{isa} = $pkg ? $pkg->namespace : 'UNKNOWN'; | |||
| 6272 | 9 | 78 | $self->{_package_name} //= $output->{isa}; | |||
| 6273 | } | |||||
| 6274 | ||||||
| 6275 | 10 | 16 | $self->_log(" OUTPUT: Chainable method - returns \$self ($self_returns/$total_returns returns)"); | |||
| 6276 | } | |||||
| 6277 | } | |||||
| 6278 | } | |||||
| 6279 | ||||||
| 6280 | # -------------------------------------------------- | |||||
| 6281 | # _detect_error_conventions | |||||
| 6282 | # | |||||
| 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. | |||||
| 6289 | # | |||||
| 6290 | # Entry: $output - output hashref (modified | |||||
| 6291 | # in place). | |||||
| 6292 | # $code - method body source string. | |||||
| 6293 | # | |||||
| 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 | 476 | 407 | my ($self, $output, $code) = @_; | |||
| 6304 | ||||||
| 6305 | 476 | 398 | return unless $code; | |||
| 6306 | ||||||
| 6307 | 476 | 471 | $self->_log(' DEBUG _detect_error_conventions called'); | |||
| 6308 | ||||||
| 6309 | 476 | 256 | my %error_patterns; | |||
| 6310 | ||||||
| 6311 | # Pattern 1: return undef if/unless condition | |||||
| 6312 | 476 | 683 | while ($code =~ /return\s+undef\s+(?:if|unless)\s+([^;]+);/g) { | |||
| 6313 | 12 12 | 8 16 | push @{$error_patterns{undef_on_error}}, $1; | |||
| 6314 | 12 | 10 | $self->_log(" DEBUG Found 'return undef' pattern"); | |||
| 6315 | } | |||||
| 6316 | ||||||
| 6317 | # Pattern 2: return if/unless (implicit undef) | |||||
| 6318 | 476 | 778 | while ($code =~ /return\s+(?:if|unless)\s+([^;]+);/g) { | |||
| 6319 | 7 7 | 6 9 | push @{$error_patterns{implicit_undef}}, $1; | |||
| 6320 | 7 | 6 | $self->_log(" DEBUG Found implicit undef pattern"); | |||
| 6321 | } | |||||
| 6322 | ||||||
| 6323 | # Pattern 3: return () - matches with or without conditions | |||||
| 6324 | 476 | 655 | if ($code =~ /return\s*\(\s*\)\s*(?:if|unless|;)/) { | |||
| 6325 | 3 | 4 | $error_patterns{empty_list} = 1; | |||
| 6326 | 3 | 5 | $self->_log(" DEBUG Found empty list return"); | |||
| 6327 | } | |||||
| 6328 | ||||||
| 6329 | # Pattern 4: return 0/1 pattern (indicates boolean with error handling) | |||||
| 6330 | 476 | 303 | my $zero_returns = 0; | |||
| 6331 | 476 | 327 | my $one_returns = 0; | |||
| 6332 | # Match "return 0" or "return 1" followed by anything (condition or semicolon) | |||||
| 6333 | 476 | 765 | while ($code =~ /return\s+(0|1)\s*(?:;|if|unless)/g) { | |||
| 6334 | 49 | 61 | if ($1 eq '0') { | |||
| 6335 | 12 | 13 | $zero_returns++; | |||
| 6336 | } else { | |||||
| 6337 | 37 | 37 | $one_returns++; | |||
| 6338 | } | |||||
| 6339 | } | |||||
| 6340 | ||||||
| 6341 | 476 | 515 | if ($zero_returns > 0 && $one_returns > 0) { | |||
| 6342 | 6 | 7 | $error_patterns{zero_on_error} = 1; | |||
| 6343 | 6 | 9 | $self->_log(" DEBUG Found 0/1 return pattern ($zero_returns zeros, $one_returns ones)"); | |||
| 6344 | } | |||||
| 6345 | ||||||
| 6346 | # Pattern 5: Exception handling with eval | |||||
| 6347 | 476 | 572 | if ($code =~ /eval\s*\{/) { | |||
| 6348 | # Check if there's error handling after eval | |||||
| 6349 | 5 | 26 | if ($code =~ /eval\s*\{.*?\}[^}]*(?:if\s*\(\s*\$\@|catch|return\s+undef)/s) { | |||
| 6350 | 3 | 4 | $error_patterns{exception_handling} = 1; | |||
| 6351 | 3 | 4 | $self->_log(' DEBUG Found exception handling with eval'); | |||
| 6352 | } | |||||
| 6353 | } | |||||
| 6354 | ||||||
| 6355 | # Detect success/failure return pattern | |||||
| 6356 | 476 | 696 | my @all_returns = $code =~ /return\s+([^;]+);/g; | |||
| 6357 | 476 512 | 446 557 | my $has_undef = grep { /^\s*undef\s*(?:if|unless|$)/ } @all_returns; | |||
| 6358 | 476 512 | 347 956 | my $has_value = grep { !/^\s*undef\s*$/ && !/^\s*$/ } @all_returns; | |||
| 6359 | ||||||
| 6360 | 476 | 556 | if ($has_undef && $has_value && scalar(@all_returns) >= 2) { | |||
| 6361 | 9 | 8 | $output->{_success_failure_pattern} = 1; | |||
| 6362 | 9 | 9 | $self->_log(" OUTPUT: Uses success/failure return pattern"); | |||
| 6363 | } | |||||
| 6364 | ||||||
| 6365 | # Store error conventions in output | |||||
| 6366 | 476 | 417 | if(scalar(keys %error_patterns)) { | |||
| 6367 | 24 | 30 | $output->{_error_handling} = \%error_patterns; | |||
| 6368 | ||||||
| 6369 | # Determine primary error convention | |||||
| 6370 | 24 | 43 | if ($error_patterns{undef_on_error}) { | |||
| 6371 | 8 | 8 | $output->{_error_return} = 'undef'; | |||
| 6372 | 8 | 10 | $self->_log(" OUTPUT: Returns undef on error"); | |||
| 6373 | } elsif ($error_patterns{implicit_undef}) { | |||||
| 6374 | 6 | 4 | $output->{_error_return} = 'undef'; | |||
| 6375 | 6 | 7 | $self->_log(" OUTPUT: Returns implicit undef on error"); | |||
| 6376 | } elsif ($error_patterns{empty_list}) { | |||||
| 6377 | 3 | 5 | $output->{_error_return} = 'empty_list'; | |||
| 6378 | 3 | 2 | $self->_log(" OUTPUT: Returns empty list on error"); | |||
| 6379 | } elsif ($error_patterns{zero_on_error}) { | |||||
| 6380 | 6 | 6 | $output->{_error_return} = 'false'; | |||
| 6381 | 6 | 7 | $self->_log(" OUTPUT: Returns 0/false on error"); | |||
| 6382 | } | |||||
| 6383 | ||||||
| 6384 | 24 | 36 | if ($error_patterns{exception_handling}) { | |||
| 6385 | 3 | 2 | $self->_log(" OUTPUT: Has exception handling"); | |||
| 6386 | } | |||||
| 6387 | } else { | |||||
| 6388 | 452 | 455 | 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 | 37 | 391 | my ($self, $expr) = @_; | |||
| 6415 | ||||||
| 6416 | 37 | 35 | return { type => 'scalar' } unless defined $expr; | |||
| 6417 | ||||||
| 6418 | 35 | 56 | $expr =~ s/^\s+|\s+$//g; | |||
| 6419 | ||||||
| 6420 | # Check for multiple comma-separated values (indicates array/list) | |||||
| 6421 | 35 | 35 | if ($expr =~ /,/) { | |||
| 6422 | 5 | 603 | require Text::Balanced; | |||
| 6423 | 5 | 6203 | my $comma_count = 0; | |||
| 6424 | 5 | 5 | my $rest = $expr; | |||
| 6425 | 5 | 7 | while (length $rest) { | |||
| 6426 | 42 | 33 | if (substr($rest, 0, 1) =~ /[(\[{]/) { | |||
| 6427 | 5 | 7 | my $extracted = Text::Balanced::extract_bracketed($rest, '(){}[]'); | |||
| 6428 | 5 | 258 | last unless defined $extracted; # Unbalanced brackets | |||
| 6429 | 5 | 5 | next; | |||
| 6430 | } | |||||
| 6431 | 37 | 24 | $comma_count++ if substr($rest, 0, 1) eq ','; | |||
| 6432 | 37 | 24 | $rest = substr($rest, 1); | |||
| 6433 | } | |||||
| 6434 | ||||||
| 6435 | 5 | 7 | if ($comma_count > 0) { | |||
| 6436 | 3 | 8 | return { type => 'array' }; | |||
| 6437 | } | |||||
| 6438 | } | |||||
| 6439 | ||||||
| 6440 | # Check for @ prefix (array) | |||||
| 6441 | 32 | 71 | if ($expr =~ /^\@\w+/ || $expr =~ /^qw\(/ || $expr =~ /^\@\{/) { | |||
| 6442 | 6 | 13 | return { type => 'array' }; | |||
| 6443 | } | |||||
| 6444 | ||||||
| 6445 | # Check for scalar() function - returns count | |||||
| 6446 | 26 | 29 | if ($expr =~ /scalar\s*\(/) { | |||
| 6447 | 4 | 7 | return { type => 'integer', min => 0 }; | |||
| 6448 | } | |||||
| 6449 | ||||||
| 6450 | # Check for array reference | |||||
| 6451 | 22 | 29 | if ($expr =~ /^\[/ || $expr =~ /^\\\@/) { | |||
| 6452 | 4 | 24 | return { type => 'arrayref' }; | |||
| 6453 | } | |||||
| 6454 | ||||||
| 6455 | # Check for hash reference | |||||
| 6456 | 18 | 24 | if ($expr =~ /^\{/ || $expr =~ /^\\\%/) { | |||
| 6457 | 3 | 5 | return { type => 'hashref' }; | |||
| 6458 | } | |||||
| 6459 | ||||||
| 6460 | # Check for hash | |||||
| 6461 | 15 | 22 | if ($expr =~ /^\%\w+/ || $expr =~ /^\%\{/) { | |||
| 6462 | 0 | 0 | return { type => 'hash' }; | |||
| 6463 | } | |||||
| 6464 | ||||||
| 6465 | # Check for strings | |||||
| 6466 | 15 | 27 | if ($expr =~ /^['"]/ || $expr =~ /['"]$/) { | |||
| 6467 | 2 | 4 | 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 | 13 | 13 | if($expr =~ /^[01]$/) { | |||
| 6473 | 4 | 8 | return { type => 'boolean' }; | |||
| 6474 | } | |||||
| 6475 | ||||||
| 6476 | # Check for integers | |||||
| 6477 | 9 | 14 | if($expr =~ /^-?\d+$/) { | |||
| 6478 | 4 | 7 | return { type => 'integer' }; | |||
| 6479 | } | |||||
| 6480 | ||||||
| 6481 | 5 | 9 | if ($expr =~ /^-?\d+\.\d+$/) { | |||
| 6482 | 2 | 4 | return { type => 'number' }; | |||
| 6483 | } | |||||
| 6484 | ||||||
| 6485 | # Check for objects | |||||
| 6486 | 3 | 5 | if ($expr =~ /bless/) { | |||
| 6487 | 0 | 0 | return { type => 'object' }; | |||
| 6488 | } | |||||
| 6489 | ||||||
| 6490 | 3 | 8 | if($expr =~ /\blength\s*\(/) { | |||
| 6491 | 2 | 4 | return { type => 'integer', min => 0 }; | |||
| 6492 | } | |||||
| 6493 | ||||||
| 6494 | # Default to scalar | |||||
| 6495 | 1 | 2 | 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 | 5 | 15 | my ($self, $output, $pod) = @_; | |||
| 6518 | 5 | 6 | return unless $pod; | |||
| 6519 | ||||||
| 6520 | # Look for explicit chaining documentation | |||||
| 6521 | 4 | 17 | 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 | 3 | 4 | $output->{_returns_self} = 1; | |||
| 6527 | 3 | 4 | $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 | 465 | 1872 | my ($self, $output) = @_; | |||
| 6551 | ||||||
| 6552 | # Warn about suspicious combinations | |||||
| 6553 | 465 | 953 | if (defined $output->{type} && $output->{type} eq 'boolean' && !defined($output->{value})) { | |||
| 6554 | 20 | 27 | $self->_log(' WARNING Boolean type without value - may want to set value: 1'); | |||
| 6555 | } | |||||
| 6556 | 465 | 598 | if ($output->{value} && defined $output->{type} && $output->{type} ne 'boolean') { | |||
| 6557 | 0 | 0 | $self->_log(" WARNING Value set but type is not boolean: $output->{type}"); | |||
| 6558 | } | |||||
| 6559 | 465 4185 | 487 2843 | my %valid_types = map { $_ => 1 } qw(string integer number boolean array arrayref hashref object void); | |||
| 6560 | 465 | 576 | if(exists $output->{type}) { | |||
| 6561 | 460 | 619 | if(!$valid_types{$output->{type}}) { | |||
| 6562 | 97 | 125 | $self->_log(" WARNING Output value type is unknown: '$output->{type}', setting to string"); | |||
| 6563 | 97 | 127 | $output->{type} = 'string'; | |||
| 6564 | } | |||||
| 6565 | } | |||||
| 6566 | } | |||||
| 6567 | ||||||
| 6568 | # -------------------------------------------------- | |||||
| 6569 | # _prose_memberof | |||||
| 6570 | # | |||||
| 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. | |||||
| 6581 | # 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 | 218 | 174 | my ($self, $text) = @_; | |||
| 6588 | ||||||
| 6589 | 218 | 316 | return undef unless defined($text) && length($text); | |||
| 6590 | ||||||
| 6591 | 182 | 126 | my $plain = $text; | |||
| 6592 | 182 | 193 | $plain =~ s/\b[CLIB]<([^<>]*)>/$1/g; # drop POD formatting | |||
| 6593 | 182 | 125 | $plain =~ s/\bE<([^<>]*)>/$1/g; | |||
| 6594 | 182 | 188 | $plain =~ s/\A\s+//; | |||
| 6595 | 182 | 271 | $plain =~ s/\s+\z//; | |||
| 6596 | ||||||
| 6597 | 182 | 105 | my $list; | |||
| 6598 | 182 | 687 | 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 | 7 | 6 | $list = $1; | |||
| 6600 | } elsif($plain =~ /\b(?:must\s+be\s+)?either\s+(.+)$/i) { | |||||
| 6601 | 1 | 1 | $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 | 1 | 1 | $list = $1; | |||
| 6605 | } else { | |||||
| 6606 | 173 | 255 | return undef; | |||
| 6607 | } | |||||
| 6608 | ||||||
| 6609 | 9 | 9 | $list =~ s/\.(?:\s|\z).*\z//s; # stop at the end of the sentence | |||
| 6610 | 9 | 7 | $list =~ s/\s*\.\s*\z//; | |||
| 6611 | 9 | 69 | $list =~ s/\s+\z//; | |||
| 6612 | ||||||
| 6613 | 9 20 | 35 13 | my @values = grep { length } split(/\s*,\s*(?:(?:and|or)\s+)?|\s+(?:and|or)\s+/i, $list); | |||
| 6614 | 9 | 17 | return undef if(@values < 2 || @values > 20); | |||
| 6615 | ||||||
| 6616 | 6 | 6 | for my $value (@values) { | |||
| 6617 | 15 | 13 | $value =~ s/\A\s+|\s+\z//g; | |||
| 6618 | 15 | 12 | $value =~ s/\A['"]|['"]\z//g; | |||
| 6619 | 15 | 18 | return undef unless $value =~ /\A[A-Za-z0-9_:.+-]+\z/; | |||
| 6620 | } | |||||
| 6621 | ||||||
| 6622 | 5 | 5 | 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, | |||||
| 6637 | # e.g. '3-50', 'positive', | |||||
| 6638 | # '>= 0', 'min 3'. | |||||
| 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 | 29 | 1930 | my ($self, $param, $constraint) = @_; | |||
| 6649 | ||||||
| 6650 | # A documented list of values, e.g. "(one of red, green)" | |||||
| 6651 | 29 | 34 | if(my $values = $self->_prose_memberof($constraint)) { | |||
| 6652 | 0 | 0 | $param->{memberof} = $values; | |||
| 6653 | } | |||||
| 6654 | ||||||
| 6655 | # Range: "3-50" or "1-100 chars" | |||||
| 6656 | 29 | 136 | if ($constraint =~ /(\d+)\s*-\s*(\d+)/) { | |||
| 6657 | 9 | 10 | $param->{min} = $1; | |||
| 6658 | 9 | 11 | $param->{max} = $2; | |||
| 6659 | } | |||||
| 6660 | elsif ($constraint =~ /(\d+)\s*\.\.\s*(\d+)/) { | |||||
| 6661 | # Range: 0..19 | |||||
| 6662 | 2 | 2 | $param->{min} = $1; | |||
| 6663 | 2 | 2 | $param->{max} = $2; | |||
| 6664 | } | |||||
| 6665 | # Minimum: "min 3" or "at least 5" | |||||
| 6666 | elsif ($constraint =~ /(?:min|minimum|at least)\s*(\d+)/i) { | |||||
| 6667 | 6 | 7 | $param->{min} = $1; | |||
| 6668 | } | |||||
| 6669 | # Maximum: "max 50" or "up to 100" | |||||
| 6670 | elsif ($constraint =~ /(?:max|maximum|up to)\s*(\d+)/i) { | |||||
| 6671 | 4 | 6 | $param->{max} = $1; | |||
| 6672 | } | |||||
| 6673 | # Positive | |||||
| 6674 | elsif ($constraint =~ /positive/i) { | |||||
| 6675 | 2 | 4 | $param->{min} = 1 if $param->{type} && $param->{type} eq 'integer'; | |||
| 6676 | 2 | 5 | $param->{min} = 0.01 if $param->{type} && $param->{type} eq 'number'; | |||
| 6677 | } | |||||
| 6678 | # Non-negative | |||||
| 6679 | elsif ($constraint =~ /non-negative/i) { | |||||
| 6680 | 2 | 2 | $param->{min} = 0; | |||
| 6681 | } elsif($constraint =~ /^(\S+)\s+(.+)$/) { | |||||
| 6682 | 2 | 2 | my ($op, $val) = ($1, $2); | |||
| 6683 | 2 | 8 | if(looks_like_number($val)) { | |||
| 6684 | 0 | 0 | if ($op eq '<') { | |||
| 6685 | 0 | 0 | $param->{max} = $val - 1; | |||
| 6686 | } elsif ($op eq '<=') { | |||||
| 6687 | 0 | 0 | $param->{max} = $val; | |||
| 6688 | } elsif ($op eq '>') { | |||||
| 6689 | 0 | 0 | $param->{min} = $val + 1; | |||
| 6690 | } elsif ($op eq '>=') { | |||||
| 6691 | 0 | 0 | $param->{min} = $val; | |||
| 6692 | } | |||||
| 6693 | } | |||||
| 6694 | } | |||||
| 6695 | ||||||
| 6696 | 29 | 28 | if(defined($param->{max})) { | |||
| 6697 | 15 | 18 | $self->_log(" Set max to $param->{max}"); | |||
| 6698 | } | |||||
| 6699 | 29 | 30 | if(defined($param->{min})) { | |||
| 6700 | 21 | 23 | $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 | 29 | 60 | if(defined($param->{min}) || defined($param->{max}) || $param->{memberof}) { | |||
| 6707 | 25 | 25 | $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 | # | |||||
| 6720 | # Entry: $code - method body source string. | |||||
| 6721 | # $method - method hashref (used for | |||||
| 6722 | # constructor-specific logic | |||||
| 6723 | # when extracting parameters | |||||
| 6724 | # from @_ patterns). | |||||
| 6725 | # | |||||
| 6726 | # Exit: Returns a hashref of parameter name | |||||
| 6727 | # to parameter spec hashref, with as | |||||
| 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 | 476 | 1606 | 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 | 476 | 1585 | $code = _strip_comments($code, $method->{node}); | |||
| 6746 | ||||||
| 6747 | 476 | 2020 | my %params; | |||
| 6748 | ||||||
| 6749 | # Safety check - limit parameter analysis to prevent runaway processing | |||||
| 6750 | 476 | 364 | my $param_count = 0; | |||
| 6751 | ||||||
| 6752 | # Extract parameter names from various signature styles | |||||
| 6753 | 476 | 718 | $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 | 476 | 602 | if($code =~ /Params::Get/) { | |||
| 6759 | 7 | 7 | my $pos = scalar keys %params; | |||
| 6760 | 7 | 22 | while($code =~ /get_params\s*\(\s*['"](\w+)['"]/g) { | |||
| 6761 | 3 | 3 | my $name = $1; | |||
| 6762 | 3 | 5 | next if $name =~ /^(self|class|pkg|proto|klass)$/i; | |||
| 6763 | 3 | 11 | $params{$name} //= { _source => SOURCE_CODE, position => $pos++ }; | |||
| 6764 | 3 | 3 | $self->_log(" CODE: Found Params::Get parameter '$name'"); | |||
| 6765 | } | |||||
| 6766 | } | |||||
| 6767 | ||||||
| 6768 | 476 | 794 | $self->_extract_defaults_from_code(\%params, $code, $method); | |||
| 6769 | ||||||
| 6770 | # Infer types from defaults | |||||
| 6771 | 476 | 464 | foreach my $param (keys %params) { | |||
| 6772 | 349 | 490 | if ($params{$param}{_default} && !$params{$param}{type}) { | |||
| 6773 | 24 | 17 | my $default = $params{$param}{_default}; | |||
| 6774 | 24 | 41 | if (ref($default) eq 'HASH') { | |||
| 6775 | 2 | 2 | $params{$param}{type} = 'hashref'; | |||
| 6776 | 2 | 2 | $self->_log(" CODE: $param type inferred as hashref from default"); | |||
| 6777 | } elsif (ref($default) eq 'ARRAY') { | |||||
| 6778 | 1 | 1 | $params{$param}{type} = 'arrayref'; | |||
| 6779 | 1 | 2 | $self->_log(" CODE: $param type inferred as arrayref from default"); | |||
| 6780 | } | |||||
| 6781 | } | |||||
| 6782 | } | |||||
| 6783 | ||||||
| 6784 | 476 | 882 | if($code =~ /(?:croak|die)\(.*\)\s+if\s*\(\s*scalar\(\@_\)\s*<\s*(\d+)\s*\)/s) { | |||
| 6785 | 0 | 0 | my $required_count = $1; | |||
| 6786 | 0 0 | 0 0 | my @param_names = sort { $params{$a}{position} <=> $params{$b}{position} } keys %params; | |||
| 6787 | 0 | 0 | for my $i (0 .. $required_count-1) { | |||
| 6788 | 0 | 0 | $params{$param_names[$i]}{optional} = 0; | |||
| 6789 | 0 | 0 | $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 | 0 | 0 | foreach my $param (keys %params) { | |||
| 6793 | 0 | 0 | $params{$param}{optional} = 0; | |||
| 6794 | 0 | 0 | $self->_log(" CODE: $param: all parameters are required due to 'scalar(@_) == 0' check"); | |||
| 6795 | } | |||||
| 6796 | } | |||||
| 6797 | ||||||
| 6798 | # Analyze each parameter (with safety limit) | |||||
| 6799 | 476 | 464 | foreach my $param (keys %params) { | |||
| 6800 | 349 | 446 | if ($param_count++ > $self->{max_parameters}) { | |||
| 6801 | 0 | 0 | $self->_log(" WARNING: Max parameters ($self->{max_parameters}) exceeded, skipping remaining"); | |||
| 6802 | 0 | 0 | last; | |||
| 6803 | } | |||||
| 6804 | ||||||
| 6805 | 349 | 301 | my $p = \$params{$param}; | |||
| 6806 | ||||||
| 6807 | 349 | 565 | $self->_analyze_parameter_type($p, $param, $code); | |||
| 6808 | 349 | 780 | $self->_analyze_parameter_constraints($p, $param, $code); | |||
| 6809 | 349 | 593 | $self->_analyze_parameter_validation($p, $param, $code); | |||
| 6810 | 349 | 511 | $self->_analyze_advanced_types($p, $param, $code); | |||
| 6811 | ||||||
| 6812 | # Defined checks | |||||
| 6813 | 349 | 3311 | if ($code =~ /defined\s*\(\s*\$$param\s*\)/) { | |||
| 6814 | 25 | 56 | $$p->{optional} = 0; | |||
| 6815 | 25 | 40 | $self->_log(" CODE: $param is required (defined check)"); | |||
| 6816 | } | |||||
| 6817 | ||||||
| 6818 | # Determine optional/required and numeric type from code | |||||
| 6819 | 349 | 14790 | if ($code =~ /\s*\$$param\s*(?:\/\/|\|\|)=/) { | |||
| 6820 | # e.g. $var //= 5; or $var ||= 5; | |||||
| 6821 | 8 | 9 | $$p->{optional} = 1; | |||
| 6822 | 8 | 11 | $self->_log(" CODE: $param is optional (default value assigned in code)"); | |||
| 6823 | } elsif ($code =~ /\s*\$$param\s*(?!->)(?:[\+\-\*\%]|\/(?!\/)|(?:\+\+)|(?:--)|(?:[\+\-\*\%]=|\/(?!\/)=)|\+\$|\$[+-])/ ) { | |||||
| 6824 | # Covers arithmetic usage: | |||||
| 6825 | # $x + $param, $param++, $param--, $x += $param, $x -= $param, etc. | |||||
| 6826 | 40 | 60 | $$p->{optional} = 0; | |||
| 6827 | 40 | 91 | $$p->{type} //= 'number'; | |||
| 6828 | 40 | 65 | $self->_log(" CODE: $param is required (used in arithmetic context)"); | |||
| 6829 | } elsif ($code =~ /\$\b$param\b\s*(?:\+0|\*1)/) { | |||||
| 6830 | # Forces numeric context, e.g., "$param + 0" or "$param * 1" | |||||
| 6831 | 0 | 0 | $$p->{optional} = 0; | |||
| 6832 | 0 | 0 | $$p->{type} //= 'number'; | |||
| 6833 | 0 | 0 | $self->_log(" CODE: $param is required (numeric context)"); | |||
| 6834 | } | |||||
| 6835 | ||||||
| 6836 | # Required parameter checks (undef causes error) | |||||
| 6837 | ||||||
| 6838 | # Style 1: block form | |||||
| 6839 | 349 | 7419 | if ($code =~ /if\s*\(\s*!\s*defined\s*\(\s*\$$param\s*\)\s*\)\s*\{([^}]+)\}/s) { | |||
| 6840 | 0 | 0 | my $block = $1; | |||
| 6841 | 0 | 0 | if ($block =~ /\b(croak|die|confess)\b/) { | |||
| 6842 | 0 | 0 | $$p->{optional} = 0; | |||
| 6843 | 0 | 0 | $self->_log(" CODE: $param is required (undef causes error)"); | |||
| 6844 | } | |||||
| 6845 | } | |||||
| 6846 | ||||||
| 6847 | # Style 2: postfix unless | |||||
| 6848 | 349 | 6216 | if ($code =~ /\b(croak|die|confess)\b[^;]*\bunless\s+defined\s*\(\s*\$$param\s*\)/) { | |||
| 6849 | 18 | 19 | $$p->{optional} = 0; | |||
| 6850 | 18 | 30 | $self->_log(" CODE: $param is required (postfix undef check)"); | |||
| 6851 | } | |||||
| 6852 | ||||||
| 6853 | # Exists checks for hash keys | |||||
| 6854 | 349 | 3242 | if ($code =~ /exists\s*\(\s*\$$param\s*\)/) { | |||
| 6855 | 0 | 0 | $$p->{type} = 'hashkey'; | |||
| 6856 | 0 | 0 | $self->_log(" CODE: $param is a hash key"); | |||
| 6857 | } | |||||
| 6858 | ||||||
| 6859 | # Scalar context for arrays | |||||
| 6860 | 349 | 3375 | if ($code =~ /scalar\s*\(\s*\@?\$$param\s*\)/) { | |||
| 6861 | 0 | 0 | $$p->{type} = 'array'; | |||
| 6862 | 0 | 0 | $self->_log(" CODE: $param used in scalar context (array)"); | |||
| 6863 | } | |||||
| 6864 | ||||||
| 6865 | 349 | 533 | $self->_extract_error_constraints($p, $param, $code); | |||
| 6866 | } | |||||
| 6867 | ||||||
| 6868 | 476 | 677 | $self->_sanitize_parameter_names(\%params, 'code analysis'); | |||
| 6869 | 476 | 422 | 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 | 353 | 343 | my ($self, $p_ref, $param, $code) = @_; | |||
| 6895 | 353 | 251 | my $p = $$p_ref; | |||
| 6896 | ||||||
| 6897 | # Type inference from ref() checks | |||||
| 6898 | 353 | 20260 | if ($code =~ /ref\s*\(\s*\$$param\s*\)\s*eq\s*['"](ARRAY|HASH|SCALAR)['"]/gi) { | |||
| 6899 | 7 | 9 | my $reftype = lc($1); | |||
| 6900 | 7 | 15 | $p->{type} = $reftype eq 'array' ? 'arrayref' : | |||
| 6901 | $reftype eq 'hash' ? 'hashref' : | |||||
| 6902 | 'scalar'; | |||||
| 6903 | 7 | 12 | $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 | 3 | 4 | $p->{type} = 'object'; | |||
| 6908 | 3 | 4 | $p->{isa} = $1; | |||
| 6909 | 3 | 9 | $self->_log(" CODE: $param is object of class $1"); | |||
| 6910 | } | |||||
| 6911 | # Blessed references | |||||
| 6912 | elsif ($code =~ /bless\s+.*\$$param/) { | |||||
| 6913 | 5 | 7 | $p->{type} = 'object'; | |||
| 6914 | 5 | 7 | $self->_log(" CODE: $param is blessed object"); | |||
| 6915 | } | |||||
| 6916 | # Array/hash operations | |||||
| 6917 | 353 | 637 | if (!$p->{type}) { | |||
| 6918 | 319 | 9430 | if ($code =~ /\@\{\s*\$$param\s*\}/ || $code =~ /push\s*\(\s*\@?\$$param/) { | |||
| 6919 | 5 | 8 | $p->{type} = 'arrayref'; | |||
| 6920 | } elsif ($code =~ /\%\{\s*\$$param\s*\}/ || $code =~ /\$$param\s*->\s*\{/) { | |||||
| 6921 | 5 | 9 | $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. | |||||
| 6928 | # `$param->{...}` and `$param->[...]` are hash and array access, which | |||||
| 6929 | # the check above has already typed. | |||||
| 6930 | 353 | 8303 | if (!$p->{type} && $code =~ /\$$param\s*->\s*[A-Za-z_]\w*/) { | |||
| 6931 | 2 | 3 | $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 | 2 | 2 | $p->{optional} = 0; | |||
| 6936 | 2 | 4 | $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 | 353 | 689 | if (!$p->{type} && exists $p->{_default}) { | |||
| 6941 | 26 | 19 | my $default = $p->{_default}; | |||
| 6942 | 26 | 41 | if (ref($default) eq 'HASH') { | |||
| 6943 | 0 | 0 | $p->{type} = 'hashref'; | |||
| 6944 | 0 | 0 | $self->_log(" CODE: $param type inferred as hashref from default"); | |||
| 6945 | } elsif (ref($default) eq 'ARRAY') { | |||||
| 6946 | 0 | 0 | $p->{type} = 'arrayref'; | |||
| 6947 | 0 | 0 | $self->_log(" CODE: $param type inferred as arrayref from default"); | |||
| 6948 | } | |||||
| 6949 | } | |||||
| 6950 | ||||||
| 6951 | # ------------------------------------------------------------ | |||||
| 6952 | # Heuristic numeric inference (low confidence) | |||||
| 6953 | # ------------------------------------------------------------ | |||||
| 6954 | 353 | 390 | 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 | 307 | 359 | 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 | 307 | 20271 | if ($code =~ /\blooks_like_number\s*\(\s*\$$param\s*\)/) { | |||
| 6965 | 11 | 12 | $p->{type} = 'number'; | |||
| 6966 | 11 | 12 | $p->{_type_confidence} = 'heuristic'; | |||
| 6967 | 11 | 19 | $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*\)/ || | |||||
| 6977 | $ops_code =~ /\babs\s*\(\s*\$$param\s*\)/ | |||||
| 6978 | ) { | |||||
| 6979 | 47 | 55 | $p->{type} = 'number'; | |||
| 6980 | 47 | 38 | $p->{_type_confidence} = 'heuristic'; | |||
| 6981 | 47 | 77 | $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/ | |||||
| 6987 | ) { | |||||
| 6988 | 20 | 28 | $p->{type} = 'number'; | |||
| 6989 | 20 | 17 | $p->{_type_confidence} = 'heuristic'; | |||
| 6990 | 20 | 29 | $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 | |||||
| 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 | # -------------------------------------------------- | |||||
| 7026 | sub _analyze_advanced_types { | |||||
| 7027 | 350 | 1682 | my ($self, $p_ref, $param, $code) = @_; | |||
| 7028 | ||||||
| 7029 | # Dereference once to get the hash reference | |||||
| 7030 | 350 | 269 | my $p = $$p_ref; | |||
| 7031 | ||||||
| 7032 | # Now pass the dereferenced hash to the detection methods | |||||
| 7033 | 350 | 514 | $self->_detect_datetime_type($p, $param, $code); | |||
| 7034 | 350 | 1013 | $self->_detect_filehandle_type($p, $param, $code); | |||
| 7035 | 350 | 650 | $self->_detect_coderef_type($p, $param, $code); | |||
| 7036 | 350 | 520 | $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 | 353 | 338 | my ($self, $p, $param, $code) = @_; | |||
| 7063 | ||||||
| 7064 | # Validate param is just a simple word | |||||
| 7065 | 353 | 830 | return unless defined $param && $param =~ /^\w+$/; | |||
| 7066 | ||||||
| 7067 | # DateTime object detection via isa/UNIVERSAL checks | |||||
| 7068 | 353 | 6573 | if ($code =~ /\$$param\s*->\s*isa\s*\(\s*['"]DateTime['"]\s*\)/i) { | |||
| 7069 | 2 | 3 | $p->{type} = 'object'; | |||
| 7070 | 2 | 3 | $p->{isa} = 'DateTime'; | |||
| 7071 | 2 | 2 | $p->{semantic} = 'datetime_object'; | |||
| 7072 | 2 | 4 | $self->_log(" ADVANCED: $param is DateTime object"); | |||
| 7073 | 2 | 3 | return; | |||
| 7074 | } | |||||
| 7075 | ||||||
| 7076 | # Check for DateTime method calls | |||||
| 7077 | 351 | 4319 | if ($code =~ /\$$param\s*->\s*(ymd|dmy|mdy|hms|iso8601|epoch|strftime)/) { | |||
| 7078 | 1 | 1 | $p->{type} = 'object'; | |||
| 7079 | 1 | 2 | $p->{isa} = 'DateTime'; | |||
| 7080 | 1 | 1 | $p->{semantic} = 'datetime_object'; | |||
| 7081 | 1 | 2 | $self->_log(" ADVANCED: $param uses DateTime methods"); | |||
| 7082 | 1 | 1 | return; | |||
| 7083 | } | |||||
| 7084 | ||||||
| 7085 | # Time::Piece detection | |||||
| 7086 | 350 | 9988 | if ($code =~ /\$$param\s*->\s*isa\s*\(\s*['"]Time::Piece['"]\s*\)/i || | |||
| 7087 | $code =~ /\$$param\s*->\s*(strftime|epoch|year|mon|mday)/) { | |||||
| 7088 | 0 | 0 | $p->{type} = 'object'; | |||
| 7089 | 0 | 0 | $p->{isa} = 'Time::Piece'; | |||
| 7090 | 0 | 0 | $p->{semantic} = 'timepiece_object'; | |||
| 7091 | 0 | 0 | $self->_log(" ADVANCED: $param is Time::Piece object"); | |||
| 7092 | 0 | 0 | return; | |||
| 7093 | } | |||||
| 7094 | ||||||
| 7095 | # ISO 8601 date pattern. Checked before the looser date-string match | |||||
| 7096 | # below, which would otherwise claim a full datetime first. | |||||
| 7097 | 350 | 2887 | if ($code =~ /\$$param\s*=~\s*\/([^\/]+)\//) { | |||
| 7098 | 15 | 16 | my $regex = $1; | |||
| 7099 | 15 | 31 | if ($self->_looks_like_iso8601_regex($regex)) { | |||
| 7100 | 2 | 3 | $p->{type} = 'string'; | |||
| 7101 | 2 | 2 | $p->{semantic} = 'iso8601_string'; | |||
| 7102 | 2 | 2 | $p->{matches} = '/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z?$/'; | |||
| 7103 | 2 | 4 | $self->_log(" ADVANCED: $param validated as ISO 8601 datetime"); | |||
| 7104 | 2 | 3 | return; | |||
| 7105 | } | |||||
| 7106 | } | |||||
| 7107 | ||||||
| 7108 | # String date/time patterns via regex matching | |||||
| 7109 | 348 | 2851 | if ($code =~ /\$$param\s*=~\s*\/.*?\\d\{4\}.*?\\d\{2\}.*?\\d\{2\}/) { | |||
| 7110 | 1 | 1 | $p->{type} = 'string'; | |||
| 7111 | 1 | 1 | $p->{semantic} = 'date_string'; | |||
| 7112 | 1 | 1 | $p->{format} = 'YYYY-MM-DD or similar'; | |||
| 7113 | 1 | 2 | $self->_log(" ADVANCED: $param validated as date string pattern"); | |||
| 7114 | 1 | 1 | return; | |||
| 7115 | } | |||||
| 7116 | ||||||
| 7117 | # UNIX timestamp detection (numeric with specific range) | |||||
| 7118 | 347 | 8994 | 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 | 2 | 2 | $p->{type} = 'integer'; | |||
| 7122 | 2 | 4 | $p->{semantic} = 'unix_timestamp'; | |||
| 7123 | 2 | 2 | $p->{min} = 0; | |||
| 7124 | 2 | 3 | $self->_log(" ADVANCED: $param appears to be UNIX timestamp"); | |||
| 7125 | 2 | 3 | return; | |||
| 7126 | } | |||||
| 7127 | ||||||
| 7128 | # Date parsing with strptime or similar | |||||
| 7129 | 345 | 8565 | if ($code =~ /strptime\s*\(\s*\$$param/ || | |||
| 7130 | $code =~ /DateTime::Format::\w+\s*->\s*parse_datetime\s*\(\s*\$$param/) { | |||||
| 7131 | 0 | 0 | $p->{type} = 'string'; | |||
| 7132 | 0 | 0 | $p->{semantic} = 'datetime_parseable'; | |||
| 7133 | 0 | 0 | $self->_log(" ADVANCED: $param is parsed as datetime"); | |||
| 7134 | 0 | 0 | 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 | # | |||||
| 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. | |||||
| 7153 | # -------------------------------------------------- | |||||
| 7154 | sub _looks_like_iso8601_regex { | |||||
| 7155 | 15 | 15 | my ($self, $regex) = @_; | |||
| 7156 | ||||||
| 7157 | 15 | 54 | return 0 unless defined $regex && $regex =~ /[Tt]/ && $regex =~ /[Zz]/; | |||
| 7158 | ||||||
| 7159 | 4 | 6 | my $digit = qr/(?:\\d|\[0-9\])/; | |||
| 7160 | 4 | 54 | my $year = qr/(?:$digit\s*\{\s*4\s*\}|$digit$digit$digit$digit)/; | |||
| 7161 | 4 | 42 | my $short = qr/(?:$digit\s*\{\s*[12]\s*\}|$digit$digit)/; | |||
| 7162 | ||||||
| 7163 | 4 | 128 | 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 and | |||||
| 7170 | # file path string parameters by | |||||
| 7171 | # analysing I/O operations, file test | |||||
| 7172 | # operators, and path manipulation | |||||
| 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 | 351 | 392 | my ($self, $p, $param, $code) = @_; | |||
| 7189 | ||||||
| 7190 | 351 | 725 | 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 | 351 | 11781 | if ($code =~ /(?<![\w:])(?:open|close|read|print|say|sysread|syswrite)\s*\(?\s*\$$param/) { | |||
| 7196 | 2 | 3 | $p->{type} = 'object'; | |||
| 7197 | 2 | 3 | $p->{isa} = 'IO::Handle'; | |||
| 7198 | 2 | 3 | $p->{semantic} = 'filehandle'; | |||
| 7199 | 2 | 4 | $self->_log(" ADVANCED: $param is a file handle"); | |||
| 7200 | 2 | 2 | return; | |||
| 7201 | } | |||||
| 7202 | ||||||
| 7203 | # Filehandle-specific operations | |||||
| 7204 | 349 | 4338 | if ($code =~ /\$$param\s*->\s*(readline|getline|print|say|close|flush|autoflush)/) { | |||
| 7205 | 1 | 2 | $p->{type} = 'object'; | |||
| 7206 | 1 | 2 | $p->{isa} = 'IO::Handle'; | |||
| 7207 | 1 | 1 | $p->{semantic} = 'filehandle'; | |||
| 7208 | 1 | 2 | $self->_log(" ADVANCED: $param uses filehandle methods"); | |||
| 7209 | 1 | 1 | 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 | 348 | 3351 | if ($code =~ /(?:-[frwxoOeszlpSbctugkTBMAC])\s+\$$param/) { | |||
| 7216 | 4 | 7 | $p->{type} = 'string'; | |||
| 7217 | 4 | 27 | if ($code =~ /-d\s+\$$param/) { | |||
| 7218 | 2 | 3 | $p->{semantic} = 'directory'; | |||
| 7219 | 2 | 3 | $self->_log(" ADVANCED: $param is tested as a directory"); | |||
| 7220 | } else { | |||||
| 7221 | 2 | 4 | $p->{semantic} = 'filepath'; | |||
| 7222 | 2 | 5 | $self->_log(" ADVANCED: $param is tested as file path"); | |||
| 7223 | } | |||||
| 7224 | 4 | 6 | return; | |||
| 7225 | } | |||||
| 7226 | ||||||
| 7227 | # File::Spec operations or path manipulation | |||||
| 7228 | 344 | 9185 | if ($code =~ /File::(?:Spec|Basename)::\w+\s*\(\s*\$$param/ || | |||
| 7229 | $code =~ /(?:basename|dirname|fileparse)\s*\(\s*\$$param/) { | |||||
| 7230 | 0 | 0 | $p->{type} = 'string'; | |||
| 7231 | 0 | 0 | $p->{semantic} = 'filepath'; | |||
| 7232 | 0 | 0 | $self->_log(" ADVANCED: $param manipulated as file path"); | |||
| 7233 | 0 | 0 | return; | |||
| 7234 | } | |||||
| 7235 | ||||||
| 7236 | # Path validation patterns | |||||
| 7237 | # Only match a literal path assigned or defaulted to this variable | |||||
| 7238 | 344 | 596 | if(defined $p->{_default} && $p->{_default} =~ m{^([A-Za-z]:\\|/|\./|\.\./)}) { | |||
| 7239 | 0 | 0 | $p->{type} = 'string'; | |||
| 7240 | 0 | 0 | $p->{semantic} = 'filepath'; | |||
| 7241 | 0 | 0 | $self->_log(" ADVANCED: $param default looks like a path"); | |||
| 7242 | 0 | 0 | return; | |||
| 7243 | } | |||||
| 7244 | ||||||
| 7245 | # IO::File detection | |||||
| 7246 | 344 | 9883 | if ($code =~ /\$$param\s*->\s*isa\s*\(\s*['"]IO::File['"]\s*\)/ || | |||
| 7247 | $code =~ /IO::File\s*->\s*new\s*\(\s*\$$param/) { | |||||
| 7248 | 0 | 0 | $p->{type} = 'object'; | |||
| 7249 | 0 | 0 | $p->{isa} = 'IO::File'; | |||
| 7250 | 0 | 0 | $p->{semantic} = 'filehandle'; | |||
| 7251 | 0 | 0 | $self->_log(" ADVANCED: $param is IO::File object"); | |||
| 7252 | 0 | 0 | return; | |||
| 7253 | } | |||||
| 7254 | } | |||||
| 7255 | ||||||
| 7256 | # -------------------------------------------------- | |||||
| 7257 | # _detect_coderef_type | |||||
| 7258 | # | |||||
| 7259 | # Purpose: Detect coderef and callback parameters | |||||
| 7260 | # by analysing ref() checks, invocation | |||||
| 7261 | # patterns, and parameter naming | |||||
| 7262 | # conventions. | |||||
| 7263 | # | |||||
| 7264 | # Entry: $p - parameter hashref (modified | |||||
| 7265 | # in place). | |||||
| 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. | |||||
| 7272 | # | |||||
| 7273 | # Side effects: Logs detections to stdout when | |||||
| 7274 | # verbose is set. | |||||
| 7275 | # -------------------------------------------------- | |||||
| 7276 | sub _detect_coderef_type { | |||||
| 7277 | 352 | 799 | my ($self, $p, $param, $code) = @_; | |||
| 7278 | ||||||
| 7279 | 352 | 634 | return unless defined $param && $param =~ /^\w+$/; | |||
| 7280 | ||||||
| 7281 | # ref() check for CODE, for a plain variable or a named argument | |||||
| 7282 | 352 | 15399 | 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 | 2 | 3 | $p->{type} = 'coderef'; | |||
| 7285 | 2 | 3 | $p->{semantic} = 'callback'; | |||
| 7286 | 2 | 4 | $self->_log(" ADVANCED: $param is coderef (ref check)"); | |||
| 7287 | 2 | 3 | return; | |||
| 7288 | } | |||||
| 7289 | ||||||
| 7290 | # Invocation as coderef - note the escaped @ in \@_ | |||||
| 7291 | 350 | 9341 | if ($code =~ /\$$param\s*->\s*\(/ || | |||
| 7292 | $code =~ /\$$param\s*->\s*\(\s*\@_\s*\)/ || | |||||
| 7293 | $code =~ /&\s*\{\s*\$$param\s*\}/) { | |||||
| 7294 | 2 | 3 | $p->{type} = 'coderef'; | |||
| 7295 | 2 | 2 | $p->{semantic} = 'callback'; | |||
| 7296 | 2 | 4 | $self->_log(" ADVANCED: $param invoked as coderef"); | |||
| 7297 | 2 | 3 | return; | |||
| 7298 | } | |||||
| 7299 | ||||||
| 7300 | # Parameter name suggests callback | |||||
| 7301 | 348 | 637 | if ($param =~ /^(?:callback|cb|handler|sub|code|fn|func|on_\w+)$/i) { | |||
| 7302 | 2 | 2 | $p->{type} = 'coderef'; | |||
| 7303 | 2 | 2 | $p->{semantic} = 'callback'; | |||
| 7304 | 2 | 3 | $self->_log(" ADVANCED: $param name suggests coderef"); | |||
| 7305 | 2 | 3 | return; | |||
| 7306 | } | |||||
| 7307 | ||||||
| 7308 | # Blessed coderef (unusual but valid) | |||||
| 7309 | 346 | 3348 | if ($code =~ /blessed\s*\(\s*\$$param\s*\)/ && | |||
| 7310 | $code =~ /ref\s*\(\s*\$$param\s*\)\s*eq\s*['"]CODE['"]/i) { | |||||
| 7311 | 0 | 0 | $p->{type} = 'object'; | |||
| 7312 | 0 | 0 | $p->{isa} = 'blessed_coderef'; | |||
| 7313 | 0 | 0 | $p->{semantic} = 'callback'; | |||
| 7314 | 0 | 0 | $self->_log(" ADVANCED: $param is blessed coderef"); | |||
| 7315 | 0 | 0 | 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 | # | |||||
| 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 | 352 | 345 | my ($self, $p, $param, $code) = @_; | |||
| 7347 | ||||||
| 7348 | 352 | 596 | 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)$/; | |||||
| 7352 | 352 | 3857 | if ($code =~ /unless\s+\$$param\s*=~\s*\/\^?\(([^)]+)\)/) { | |||
| 7353 | 4 | 5 | my $values = $1; | |||
| 7354 | 4 | 6 | my @enum_values = split(/\|/, $values); | |||
| 7355 | 4 | 9 | $p->{type} = 'string' unless $p->{type}; | |||
| 7356 | 4 | 7 | $p->{enum} = \@enum_values; | |||
| 7357 | 4 | 6 | $p->{semantic} = 'enum'; | |||
| 7358 | 4 | 11 | $self->_log(" ADVANCED: $param is enum with values: " . join(', ', @enum_values)); | |||
| 7359 | 4 | 4 | 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 | 348 | 478 | if ($code =~ /\%(\w+)\s*=.*?qw\s*[\(\[<{]([^)\]>}]+)[\)\]>}]/) { | |||
| 7366 | 3 | 4 | my $hash_name = $1; | |||
| 7367 | 3 | 3 | my $values_str = $2; | |||
| 7368 | 3 | 39 | if (defined $values_str && $code =~ /\$$hash_name\s*\{\s*\$$param\s*\}/) { | |||
| 7369 | 2 | 4 | my @enum_values = split(/\s+/, $values_str); | |||
| 7370 | 2 | 6 | $p->{type} = 'string' unless $p->{type}; | |||
| 7371 | 2 | 3 | $p->{enum} = \@enum_values; | |||
| 7372 | 2 | 3 | $p->{semantic} = 'enum'; | |||
| 7373 | 2 | 7 | $self->_log(" ADVANCED: $param validated via hash lookup: " . join(', ', @enum_values)); | |||
| 7374 | 2 | 3 | return; | |||
| 7375 | } | |||||
| 7376 | } | |||||
| 7377 | ||||||
| 7378 | # Pattern 3: Array grep validation | |||||
| 7379 | # die unless grep { $_ eq $param } qw(foo bar baz); | |||||
| 7380 | 346 | 6176 | if ($code =~ /grep\s*\{[^}]*\$$param[^}]*\}\s*qw\s*[\(\[<{]([^)\]>}]+)[\)\]>}]/) { | |||
| 7381 | 1 | 2 | my $values_str = $1; | |||
| 7382 | 1 | 2 | my @enum_values = split(/\s+/, $values_str); | |||
| 7383 | 1 | 3 | $p->{type} = 'string' unless $p->{type}; | |||
| 7384 | 1 | 1 | $p->{enum} = \@enum_values; | |||
| 7385 | 1 | 1 | $p->{semantic} = 'enum'; | |||
| 7386 | 1 | 3 | $self->_log(" ADVANCED: $param validated via grep: " . join(', ', @enum_values)); | |||
| 7387 | 1 | 2 | return; | |||
| 7388 | } | |||||
| 7389 | ||||||
| 7390 | # Pattern 4: Given/when (Perl 5.10+) | |||||
| 7391 | 345 | 3232 | if ($code =~ /given\s*\(\s*\$$param\s*\)/) { | |||
| 7392 | 1 | 1 | my @enum_values; | |||
| 7393 | 1 | 6 | while ($code =~ /when\s*\(\s*['"]([^'"]+)['"]\s*\)/g) { | |||
| 7394 | 2 | 3 | push @enum_values, $1; | |||
| 7395 | } | |||||
| 7396 | 1 | 1 | if (@enum_values >= 2) { | |||
| 7397 | 1 | 4 | $p->{type} = 'string' unless $p->{type}; | |||
| 7398 | 1 | 3 | $p->{enum} = \@enum_values; | |||
| 7399 | 1 | 1 | $p->{semantic} = 'enum'; | |||
| 7400 | 1 | 2 | $self->_log(" ADVANCED: $param has enum values from given/when: " . | |||
| 7401 | join(', ', @enum_values)); | |||||
| 7402 | 1 | 3 | return; | |||
| 7403 | } | |||||
| 7404 | } | |||||
| 7405 | ||||||
| 7406 | # Pattern 5: Multiple if/elsif checking specific values | |||||
| 7407 | 344 | 271 | my @if_values; | |||
| 7408 | 344 | 6838 | while ($code =~ /if\s*\(\s*\$$param\s*eq\s*['"]([^'"]+)['"]\s*\)/g) { | |||
| 7409 | 10 | 21 | push @if_values, $1; | |||
| 7410 | } | |||||
| 7411 | 344 | 6695 | while ($code =~ /elsif\s*\(\s*\$$param\s*eq\s*['"]([^'"]+)['"]\s*\)/g) { | |||
| 7412 | 7 | 13 | push @if_values, $1; | |||
| 7413 | } | |||||
| 7414 | 344 | 470 | if (@if_values >= 3) { | |||
| 7415 | 3 | 7 | $p->{type} = 'string' unless $p->{type}; | |||
| 7416 | 3 | 5 | $p->{enum} = \@if_values; | |||
| 7417 | 3 | 3 | $p->{semantic} = 'enum'; | |||
| 7418 | 3 | 10 | $self->_log(" ADVANCED: $param appears to be enum from if/elsif: " . | |||
| 7419 | join(', ', @if_values)); | |||||
| 7420 | 3 | 6 | return; | |||
| 7421 | } | |||||
| 7422 | ||||||
| 7423 | # Pattern 6: Smart match (~~) with array | |||||
| 7424 | 341 | 8025 | if ($code =~ /\$$param\s*~~\s*\[([^\]]+)\]/ || | |||
| 7425 | $code =~ /\$$param\s*~~\s*qw\s*[\(\[<{]([^)\]>}]+)[\)\]>}]/) { | |||||
| 7426 | 0 | 0 | my $values_str = $1; | |||
| 7427 | 0 | 0 | my @enum_values; | |||
| 7428 | 0 | 0 | if ($values_str =~ /['"]/) { | |||
| 7429 | 0 | 0 | @enum_values = $values_str =~ /['"](.*?)['"]/g; | |||
| 7430 | } else { | |||||
| 7431 | 0 | 0 | @enum_values = split(/\s+/, $values_str); | |||
| 7432 | } | |||||
| 7433 | 0 | 0 | if (@enum_values) { | |||
| 7434 | 0 | 0 | $p->{type} = 'string' unless $p->{type}; | |||
| 7435 | 0 | 0 | $p->{enum} = \@enum_values; | |||
| 7436 | 0 | 0 | $p->{semantic} = 'enum'; | |||
| 7437 | 0 | 0 | $self->_log(" ADVANCED: $param validated with smart match: " . | |||
| 7438 | join(', ', @enum_values)); | |||||
| 7439 | 0 | 0 | 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 | |||||
| 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 | 352 | 347 | my ($self, $p, $param, $code) = @_; | |||
| 7467 | ||||||
| 7468 | # Look for die/croak/confess with a condition involving this param | |||||
| 7469 | 352 | 736 | 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 | 39 | 54 | my $message = $1 || $2; | |||
| 7484 | 39 | 34 | my $condition = $3; | |||
| 7485 | ||||||
| 7486 | # Only keep conditions that reference this parameter | |||||
| 7487 | 39 | 123 | next unless $condition =~ /\$$param\b/; | |||
| 7488 | ||||||
| 7489 | # Initialize storage | |||||
| 7490 | 26 | 60 | $$p->{_invalid} ||= []; | |||
| 7491 | 26 | 48 | $$p->{_errors} ||= []; | |||
| 7492 | ||||||
| 7493 | # Normalize condition (strip surrounding parens) | |||||
| 7494 | 26 | 49 | $condition =~ s/^\(|\)$//g; | |||
| 7495 | 26 | 43 | $condition =~ s/\s+/ /g; | |||
| 7496 | ||||||
| 7497 | # Try to extract a meaningful invalid constraint | |||||
| 7498 | 26 | 14 | my $constraint; | |||
| 7499 | ||||||
| 7500 | # Examples: | |||||
| 7501 | # $age <= 0 | |||||
| 7502 | # $x eq '' | |||||
| 7503 | # length($s) < 3 | |||||
| 7504 | 26 | 774 | if ($condition =~ /\$$param\s*([!<>=]=?|eq|ne|lt|gt|le|ge)\s*(.+)/) { | |||
| 7505 | 8 | 15 | $constraint = "$1 $2"; | |||
| 7506 | } | |||||
| 7507 | elsif ($condition =~ /length\s*\(\s*\$$param\s*\)\s*([<>=!]+)\s*(\d+)/) { | |||||
| 7508 | 3 | 4 | $constraint = "length $1 $2"; | |||
| 7509 | } | |||||
| 7510 | elsif ($condition =~ /\$$param\s*==\s*0/) { | |||||
| 7511 | 0 | 0 | $constraint = '== 0'; | |||
| 7512 | } | |||||
| 7513 | ||||||
| 7514 | # Store results | |||||
| 7515 | 26 11 | 31 15 | push @{ $$p->{_invalid} }, $constraint if $constraint; | |||
| 7516 | 26 21 | 22 21 | push @{ $$p->{_errors} }, $message if defined $message; | |||
| 7517 | ||||||
| 7518 | 26 | 46 | $self->_log( | |||
| 7519 | " ERROR: $param invalid when [$condition]" . | |||||
| 7520 | (defined $message ? " => '$message'" : '') | |||||
| 7521 | ); | |||||
| 7522 | } | |||||
| 7523 | ||||||
| 7524 | # Numeric comparison with literal | |||||
| 7525 | 352 | 4520 | if ($code =~ /\b\Q$param\E\s*(<=|<|>=|>)\s*(-?\d+)/) { | |||
| 7526 | 22 | 32 | my ($op, $num) = ($1, $2); | |||
| 7527 | ||||||
| 7528 | # Mark required | |||||
| 7529 | 22 | 30 | $$p->{optional} = 0; | |||
| 7530 | ||||||
| 7531 | 22 | 65 | if ($op eq '<=') { | |||
| 7532 | 1 | 2 | $$p->{min} = $num + 1; | |||
| 7533 | } elsif ($op eq '<') { | |||||
| 7534 | 5 | 9 | $$p->{min} = $num; | |||
| 7535 | } elsif ($op eq '>=') { | |||||
| 7536 | 2 | 2 | $$p->{max} = $num - 1; | |||
| 7537 | } elsif ($op eq '>') { | |||||
| 7538 | 14 | 21 | $$p->{max} = $num; | |||
| 7539 | } | |||||
| 7540 | ||||||
| 7541 | 22 | 41 | $self->_log(" ERROR: $param normalized constraint from '$op $num'"); | |||
| 7542 | } | |||||
| 7543 | } | |||||
| 7544 | ||||||
| 7545 | # -------------------------------------------------- | |||||
| 7546 | # _extract_parameters_from_signature | |||||
| 7547 | # | |||||
| 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 | # | |||||
| 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 | |||||
| 7569 | # parameters. | |||||
| 7570 | # -------------------------------------------------- | |||||
| 7571 | sub _extract_parameters_from_signature { | |||||
| 7572 | 958 | 786 | 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 | 958 | 2621 | if ($code =~ /sub\s+\w+\s*(?::\w+(?:\([^)]*\))?\s*)*\(((?:[^()]|\([^)]*\))*)\)\s*\{/s) { | |||
| 7586 | 28 | 27 | my $potential_sig = $1; | |||
| 7587 | ||||||
| 7588 | # Check if this looks like parameters (has sigils) | |||||
| 7589 | 28 | 36 | if ($potential_sig =~ /[\$\%\@]/) { | |||
| 7590 | 24 | 29 | $self->_log(" SIG: Found modern signature: ($potential_sig)"); | |||
| 7591 | 24 | 33 | $self->_parse_modern_signature($params, $potential_sig); | |||
| 7592 | 24 | 14 | 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 | 934 | 989 | if($code =~ /my\s+\$(?:self|class)\s*=\s*\$_\[0\]/) { | |||
| 7600 | 22 | 13 | my $pos = 0; | |||
| 7601 | 22 | 58 | while($code =~ /my\s+\$(\w+)\s*=\s*\$_\[(\d+)\]/g) { | |||
| 7602 | 24 | 22 | my $name = $1; | |||
| 7603 | 24 | 48 | next if $name =~ /^(self|class|pkg|proto|klass)$/i; | |||
| 7604 | 2 | 8 | $params->{$name} //= { _source => SOURCE_CODE, optional => 1, position => $pos++ }; | |||
| 7605 | 2 | 4 | $self->_log(" CODE: Found direct-index parameter '\$$name' at \$_[$2]"); | |||
| 7606 | } | |||||
| 7607 | 22 | 19 | return; | |||
| 7608 | } | |||||
| 7609 | ||||||
| 7610 | # Traditional Style 1: my ($self, $arg1, $arg2) = @_; | |||||
| 7611 | 912 | 1601 | if ($code =~ /my\s*\(\s*([^)]+)\)\s*=\s*\@_/s) { | |||
| 7612 | 496 | 446 | my $sig = $1; | |||
| 7613 | 496 | 319 | my $pos = 0; | |||
| 7614 | ||||||
| 7615 | 496 | 745 | while ($sig =~ /\$(\w+)/g) { | |||
| 7616 | 957 | 650 | my $name = $1; | |||
| 7617 | ||||||
| 7618 | 957 | 1966 | next if $name =~ /^(self|class|pkg|proto|klass)$/i; | |||
| 7619 | ||||||
| 7620 | 544 | 1159 | $params->{$name} //= { | |||
| 7621 | _source => SOURCE_CODE, | |||||
| 7622 | optional => 1, | |||||
| 7623 | }; | |||||
| 7624 | ||||||
| 7625 | 544 | 645 | $params->{$name}{position} = $pos unless exists $params->{$name}{position}; | |||
| 7626 | ||||||
| 7627 | 544 | 459 | $pos++; | |||
| 7628 | } | |||||
| 7629 | 496 | 439 | return; | |||
| 7630 | } elsif ($code =~ /my\s+\$self\s*=\s*shift/) { | |||||
| 7631 | # Traditional Style 2: my $self = shift; my $arg1 = shift; | |||||
| 7632 | 63 | 48 | my @shifts; | |||
| 7633 | 63 | 126 | while ($code =~ /my\s+\$(\w+)\s*=\s*shift/g) { | |||
| 7634 | 78 | 124 | push @shifts, $1; | |||
| 7635 | } | |||||
| 7636 | 63 | 159 | shift @shifts if @shifts && $shifts[0] =~ /^(self|class|pkg|proto|klass)$/i; | |||
| 7637 | 63 | 36 | my $pos = 0; | |||
| 7638 | 63 | 64 | foreach my $param (@shifts) { | |||
| 7639 | 15 | 42 | $params->{$param} ||= { _source => SOURCE_CODE, optional => 1, position => $pos++ }; | |||
| 7640 | } | |||||
| 7641 | 63 | 60 | return; | |||
| 7642 | } | |||||
| 7643 | ||||||
| 7644 | # Traditional Style 3: Function parameters (no $self) | |||||
| 7645 | 353 | 310 | if ($code =~ /my\s*\(\s*([^)]+)\)\s*=\s*\@_/s) { | |||
| 7646 | 0 | 0 | my $sig = $1; | |||
| 7647 | 0 | 0 | my @param_names = $sig =~ /\$(\w+)/g; | |||
| 7648 | 0 | 0 | my $pos = 0; | |||
| 7649 | 0 | 0 | foreach my $param (@param_names) { | |||
| 7650 | 0 | 0 | next if $param =~ /^(self|class|pkg|proto|klass)$/i; | |||
| 7651 | 0 | 0 | $params->{$param} ||= { _source => SOURCE_CODE, optional => 1, position => $pos++ }; | |||
| 7652 | } | |||||
| 7653 | } | |||||
| 7654 | ||||||
| 7655 | # De-duplicate | |||||
| 7656 | 353 | 233 | my %seen; | |||
| 7657 | 353 | 336 | foreach my $param (keys %$params) { | |||
| 7658 | 0 | 0 | if ($seen{$param}++) { | |||
| 7659 | 0 | 0 | $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 | 26 | 2908 | my ($self, $params, $sig) = @_; | |||
| 7685 | ||||||
| 7686 | 26 | 34 | $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 | 26 | 1070 | require Text::Balanced; | |||
| 7691 | 26 | 9525 | my @parts; | |||
| 7692 | 26 | 18 | my $current = ''; | |||
| 7693 | 26 | 20 | my $rest = $sig; | |||
| 7694 | ||||||
| 7695 | 26 | 23 | while (length $rest) { | |||
| 7696 | 743 | 485 | 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 | 3 | 7 | my $extracted = Text::Balanced::extract_bracketed($rest, '(){}[]'); | |||
| 7700 | 3 | 269 | last unless defined $extracted; # Unbalanced brackets | |||
| 7701 | 3 | 3 | $current .= $extracted; | |||
| 7702 | 3 | 4 | next; | |||
| 7703 | } | |||||
| 7704 | 740 | 407 | if (substr($rest, 0, 1) eq ',') { | |||
| 7705 | 47 | 24 | push @parts, $current; | |||
| 7706 | 47 | 32 | $current = ''; | |||
| 7707 | 47 | 19 | $rest = substr($rest, 1); | |||
| 7708 | 47 | 39 | next; | |||
| 7709 | } | |||||
| 7710 | 693 | 354 | $current .= substr($rest, 0, 1); | |||
| 7711 | 693 | 370 | $rest = substr($rest, 1); | |||
| 7712 | } | |||||
| 7713 | 26 | 37 | push @parts, $current if $current =~ /\S/; | |||
| 7714 | ||||||
| 7715 | 26 | 19 | my $position = 0; | |||
| 7716 | ||||||
| 7717 | 26 | 20 | foreach my $part (@parts) { | |||
| 7718 | 73 | 119 | $part =~ s/^\s+|\s+$//g; | |||
| 7719 | ||||||
| 7720 | # Skip empty parts | |||||
| 7721 | 73 | 51 | next unless $part; | |||
| 7722 | ||||||
| 7723 | # Parse different parameter types | |||||
| 7724 | 73 | 66 | my $param_info = $self->_parse_signature_parameter($part, $position); | |||
| 7725 | ||||||
| 7726 | 73 | 52 | if ($param_info) { | |||
| 7727 | 73 | 44 | my $name = $param_info->{name}; | |||
| 7728 | ||||||
| 7729 | # Skip self/class | |||||
| 7730 | 73 | 75 | if ($name =~ /^(self|class|pkg|proto|klass)$/i) { | |||
| 7731 | 18 | 26 | next; | |||
| 7732 | } | |||||
| 7733 | ||||||
| 7734 | 55 | 43 | $params->{$name} = $param_info; | |||
| 7735 | $self->_log(" SIG: $name has position $position" . | |||||
| 7736 | ($param_info->{optional} ? ' (optional)' : '') . | |||||
| 7737 | 55 | 100 | ($param_info->{_default} ? ", default: $param_info->{_default}" : '')); | |||
| 7738 | 55 | 50 | $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 | # -------------------------------------------------- | |||||
| 7772 | sub _parse_signature_parameter { | |||||
| 7773 | 86 | 3449 | my ($self, $part, $position) = @_; | |||
| 7774 | ||||||
| 7775 | 86 | 92 | 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 | 86 | 212 | if ($part =~ /^\$(\w+)\s*:\s*(\w+)\s*=\s*(.+)$/s) { | |||
| 7783 | 7 | 11 | my ($name, $constraint, $default) = ($1, $2, $3); | |||
| 7784 | 7 | 8 | $default =~ s/^\s+|\s+$//g; | |||
| 7785 | ||||||
| 7786 | 7 | 5 | $info{name} = $name; | |||
| 7787 | 7 | 6 | $info{optional} = 1; | |||
| 7788 | 7 | 8 | $info{_default} = $self->_clean_default_value($default, 1); | |||
| 7789 | ||||||
| 7790 | # Apply type constraint | |||||
| 7791 | 7 | 17 | if ($constraint =~ /^(Int|Integer)$/i) { | |||
| 7792 | 2 | 3 | $info{type} = 'integer'; | |||
| 7793 | } elsif ($constraint =~ /^(Num|Number)$/i) { | |||||
| 7794 | 3 | 4 | $info{type} = 'number'; | |||
| 7795 | } elsif ($constraint =~ /^(Str|String)$/i) { | |||||
| 7796 | 2 | 2 | $info{type} = 'string'; | |||
| 7797 | } elsif ($constraint =~ /^(Bool|Boolean)$/i) { | |||||
| 7798 | 0 | 0 | $info{type} = 'boolean'; | |||
| 7799 | } elsif ($constraint =~ /^(Array|ArrayRef)$/i) { | |||||
| 7800 | 0 | 0 | $info{type} = 'arrayref'; | |||
| 7801 | } elsif ($constraint =~ /^(Hash|HashRef)$/i) { | |||||
| 7802 | 0 | 0 | $info{type} = 'hashref'; | |||
| 7803 | } else { | |||||
| 7804 | 0 | 0 | $info{type} = 'object'; | |||
| 7805 | 0 | 0 | $info{isa} = $constraint; | |||
| 7806 | } | |||||
| 7807 | ||||||
| 7808 | 7 | 6 | return \%info; | |||
| 7809 | } elsif ($part =~ /^\$(\w+)\s*:\s*(\w+)\s*$/s) { | |||||
| 7810 | # Pattern 2: Type constraint WITHOUT default: $name :Type | |||||
| 7811 | 14 | 14 | my ($name, $constraint) = ($1, $2); | |||
| 7812 | 14 | 15 | $info{name} = $name; | |||
| 7813 | 14 | 7 | $info{optional} = 0; | |||
| 7814 | ||||||
| 7815 | # Apply type constraint (same as above) | |||||
| 7816 | 14 | 35 | if ($constraint =~ /^(Int|Integer)$/i) { | |||
| 7817 | 4 | 4 | $info{type} = 'integer'; | |||
| 7818 | } elsif ($constraint =~ /^(Num|Number)$/i) { | |||||
| 7819 | 2 | 0 | $info{type} = 'number'; | |||
| 7820 | } elsif ($constraint =~ /^(Str|String)$/i) { | |||||
| 7821 | 2 | 3 | $info{type} = 'string'; | |||
| 7822 | } elsif ($constraint =~ /^(Bool|Boolean)$/i) { | |||||
| 7823 | 2 | 1 | $info{type} = 'boolean'; | |||
| 7824 | } elsif ($constraint =~ /^(Array|ArrayRef)$/i) { | |||||
| 7825 | 2 | 2 | $info{type} = 'arrayref'; | |||
| 7826 | } elsif ($constraint =~ /^(Hash|HashRef)$/i) { | |||||
| 7827 | 0 | 0 | $info{type} = 'hashref'; | |||
| 7828 | } else { | |||||
| 7829 | 2 | 2 | $info{type} = 'object'; | |||
| 7830 | 2 | 1 | $info{isa} = $constraint; | |||
| 7831 | } | |||||
| 7832 | ||||||
| 7833 | 14 | 13 | return \%info; | |||
| 7834 | } elsif ($part =~ /^\$(\w+)\s*=\s*(.+)$/s) { | |||||
| 7835 | # Pattern 3: Default WITHOUT type: $name = default | |||||
| 7836 | 16 | 21 | my ($name, $default) = ($1, $2); | |||
| 7837 | 16 | 21 | $default =~ s/^\s+|\s+$//g; | |||
| 7838 | ||||||
| 7839 | 16 | 14 | $info{name} = $name; | |||
| 7840 | 16 | 11 | $info{optional} = 1; | |||
| 7841 | 16 | 23 | $info{_default} = $self->_clean_default_value($default, 1); | |||
| 7842 | 16 | 42 | $info{type} = $self->_infer_type_from_default($info{_default}) if $self->can('_infer_type_from_default'); | |||
| 7843 | ||||||
| 7844 | 16 | 16 | return \%info; | |||
| 7845 | } | |||||
| 7846 | ||||||
| 7847 | # Pattern 4: Plain parameter: $name | |||||
| 7848 | elsif ($part =~ /^\$(\w+)$/s) { | |||||
| 7849 | 39 | 34 | $info{name} = $1; | |||
| 7850 | 39 | 26 | $info{optional} = 0; | |||
| 7851 | 39 | 29 | return \%info; | |||
| 7852 | } | |||||
| 7853 | ||||||
| 7854 | # Pattern 5: Array parameter: @name | |||||
| 7855 | elsif ($part =~ /^\@(\w+)$/s) { | |||||
| 7856 | 4 | 4 | $info{name} = $1; | |||
| 7857 | 4 | 4 | $info{type} = 'array'; | |||
| 7858 | 4 | 7 | $info{slurpy} = 1; | |||
| 7859 | 4 | 3 | $info{optional} = 1; | |||
| 7860 | 4 | 4 | return \%info; | |||
| 7861 | } | |||||
| 7862 | ||||||
| 7863 | # Pattern 6: Hash parameter: %name | |||||
| 7864 | elsif ($part =~ /^\%(\w+)$/s) { | |||||
| 7865 | 4 | 5 | $info{name} = $1; | |||
| 7866 | 4 | 3 | $info{type} = 'hash'; | |||
| 7867 | 4 | 5 | $info{slurpy} = 1; | |||
| 7868 | 4 | 3 | $info{optional} = 1; | |||
| 7869 | 4 | 4 | return \%info; | |||
| 7870 | } | |||||
| 7871 | ||||||
| 7872 | 2 | 2 | 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 | # | |||||
| 7891 | # Side effects: None. | |||||
| 7892 | # -------------------------------------------------- | |||||
| 7893 | sub _infer_type_from_default { | |||||
| 7894 | 33 | 39 | my ($self, $default) = @_; | |||
| 7895 | ||||||
| 7896 | 33 | 31 | return undef unless defined $default; | |||
| 7897 | ||||||
| 7898 | 29 | 80 | if (ref($default) eq 'HASH') { | |||
| 7899 | 2 | 3 | return 'hashref'; | |||
| 7900 | } elsif (ref($default) eq 'ARRAY') { | |||||
| 7901 | 2 | 3 | return 'arrayref'; | |||
| 7902 | } elsif ($default =~ /^-?\d+$/) { | |||||
| 7903 | 16 | 21 | return 'integer'; | |||
| 7904 | } elsif ($default =~ /^-?\d+\.\d+$/) { | |||||
| 7905 | 2 | 3 | return 'number'; | |||
| 7906 | } elsif ($default eq '1' || $default eq '0') { | |||||
| 7907 | 0 | 0 | return 'boolean'; | |||
| 7908 | } else { | |||||
| 7909 | 7 | 11 | 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. | |||||
| 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 | 481 | 1418 | my ($self, $code) = @_; | |||
| 7934 | ||||||
| 7935 | 481 | 334 | my %attributes; | |||
| 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 | 481 | 326 | my $attr_section = ''; | |||
| 7944 | ||||||
| 7945 | 481 | 806 | if($code =~ /sub\s+\w+\s+((?::\w+(?:\([^)]*\))?\s*)+)/s) { | |||
| 7946 | 9 | 6 | $attr_section = $1; | |||
| 7947 | } | |||||
| 7948 | ||||||
| 7949 | # Parse individual attributes from the section | |||||
| 7950 | 481 | 444 | if($attr_section) { | |||
| 7951 | 9 | 17 | while($attr_section =~ /:(\w+)(?:\(([^)]*)\))?/g) { | |||
| 7952 | 11 | 12 | my ($name, $value) = ($1, $2); | |||
| 7953 | ||||||
| 7954 | 11 | 17 | if (defined $value && $value ne '') { | |||
| 7955 | 5 | 4 | $attributes{$name} = $value; | |||
| 7956 | 5 | 9 | $self->_log(" ATTR: Found attribute :$name($value)"); | |||
| 7957 | } else { | |||||
| 7958 | 6 | 6 | $attributes{$name} = 1; | |||
| 7959 | 6 | 8 | $self->_log(" ATTR: Found attribute :$name"); | |||
| 7960 | } | |||||
| 7961 | } | |||||
| 7962 | } | |||||
| 7963 | ||||||
| 7964 | # Process common attributes | |||||
| 7965 | 481 | 516 | if ($attributes{Returns}) { | |||
| 7966 | 4 | 3 | my $return_type = $attributes{Returns}; | |||
| 7967 | 4 | 5 | if ($return_type ne '1') { # Only log if it's an actual type, not just the flag | |||
| 7968 | 4 | 5 | $self->_log(" ATTR: Method declares return type: $return_type"); | |||
| 7969 | } | |||||
| 7970 | } | |||||
| 7971 | ||||||
| 7972 | 481 | 523 | if ($attributes{lvalue}) { | |||
| 7973 | 4 | 5 | $self->_log(" ATTR: Method is lvalue (can be assigned to)"); | |||
| 7974 | } | |||||
| 7975 | ||||||
| 7976 | 481 | 516 | if ($attributes{method}) { | |||
| 7977 | 2 | 2 | $self->_log(' ATTR: Method explicitly marked as :method'); | |||
| 7978 | } | |||||
| 7979 | ||||||
| 7980 | 481 | 421 | return \%attributes; | |||
| 7981 | } | |||||
| 7982 | ||||||
| 7983 | # -------------------------------------------------- | |||||
| 7984 | # _analyze_postfix_dereferencing | |||||
| 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. | |||||
| 7990 | # | |||||
| 7991 | # Entry: $code - method body source string. | |||||
| 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 | 483 | 988 | my ($self, $code) = @_; | |||
| 8006 | ||||||
| 8007 | 483 | 287 | my %derefs; | |||
| 8008 | ||||||
| 8009 | # Array dereference: $ref->@* | |||||
| 8010 | 483 | 823 | if ($code =~ /\$\w+\s*->\s*\@\*/) { | |||
| 8011 | 4 | 3 | $derefs{array_deref} = 1; | |||
| 8012 | 4 | 6 | $self->_log(" MODERN: Uses postfix array dereferencing (->@*)"); | |||
| 8013 | } | |||||
| 8014 | ||||||
| 8015 | # Hash dereference: $ref->%* | |||||
| 8016 | 483 | 726 | if ($code =~ /\$\w+\s*->\s*\%\*/) { | |||
| 8017 | 3 | 3 | $derefs{hash_deref} = 1; | |||
| 8018 | 3 | 4 | $self->_log(" MODERN: Uses postfix hash dereferencing (->%*)"); | |||
| 8019 | } | |||||
| 8020 | ||||||
| 8021 | # Scalar dereference: $ref->$* | |||||
| 8022 | 483 | 673 | if ($code =~ /\$\w+\s*->\s*\$\*/) { | |||
| 8023 | 2 | 3 | $derefs{scalar_deref} = 1; | |||
| 8024 | 2 | 2 | $self->_log(' MODERN: Uses postfix scalar dereferencing (->$*)'); | |||
| 8025 | } | |||||
| 8026 | ||||||
| 8027 | # Code dereference: $ref->&* | |||||
| 8028 | 483 | 636 | if ($code =~ /\$\w+\s*->\s*\&\*/) { | |||
| 8029 | 1 | 1 | $derefs{code_deref} = 1; | |||
| 8030 | 1 | 1 | $self->_log(" MODERN: Uses postfix code dereferencing (->&*)"); | |||
| 8031 | } | |||||
| 8032 | ||||||
| 8033 | # Array element: $ref->@[0,2,4] | |||||
| 8034 | 483 | 655 | if ($code =~ /\$\w+\s*->\s*\@\[/) { | |||
| 8035 | 2 | 3 | $derefs{array_slice} = 1; | |||
| 8036 | 2 | 2 | $self->_log(" MODERN: Uses postfix array slice (->@[...])"); | |||
| 8037 | } | |||||
| 8038 | ||||||
| 8039 | # Hash element: $ref->%{key1,key2} | |||||
| 8040 | 483 | 661 | if ($code =~ /\$\w+\s*->\s*\%\{/) { | |||
| 8041 | 2 | 2 | $derefs{hash_slice} = 1; | |||
| 8042 | 2 | 2 | $self->_log(" MODERN: Uses postfix hash slice (->%{...})"); | |||
| 8043 | } | |||||
| 8044 | ||||||
| 8045 | 483 | 403 | return \%derefs; | |||
| 8046 | } | |||||
| 8047 | ||||||
| 8048 | # -------------------------------------------------- | |||||
| 8049 | # _extract_field_declarations | |||||
| 8050 | # | |||||
| 8051 | # Purpose: Extract Perl 5.38 field declarations | |||||
| 8052 | # from a class body or method source | |||||
| 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 | 484 | 1770 | my ($self, $code) = @_; | |||
| 8071 | ||||||
| 8072 | 484 | 315 | 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 | 484 | 639 | while ($code =~ /^\s*field\s+\$(\w+)\s*([^;]*);/gm) { | |||
| 8079 | 12 | 13 | my ($name, $modifiers) = ($1, $2); | |||
| 8080 | ||||||
| 8081 | 12 | 16 | $self->_log(" FIELD: Found field \$$name with modifiers: [$modifiers]"); | |||
| 8082 | ||||||
| 8083 | 12 | 15 | my %field_info = ( | |||
| 8084 | name => $name, | |||||
| 8085 | _source => SOURCE_FIELD | |||||
| 8086 | ); | |||||
| 8087 | ||||||
| 8088 | # Check for :param attribute | |||||
| 8089 | 12 | 21 | if ($modifiers =~ /:param(?:\(([^)]+)\))?/) { | |||
| 8090 | 11 | 10 | $field_info{is_param} = 1; | |||
| 8091 | ||||||
| 8092 | 11 | 10 | if (defined $1) { | |||
| 8093 | # Explicit parameter name | |||||
| 8094 | 2 | 2 | $field_info{param_name} = $1; | |||
| 8095 | } else { | |||||
| 8096 | # Implicit - field name is param name | |||||
| 8097 | 9 | 9 | $field_info{param_name} = $name; | |||
| 8098 | } | |||||
| 8099 | ||||||
| 8100 | 11 | 13 | $self->_log(" FIELD: $name maps to parameter: $field_info{param_name}"); | |||
| 8101 | } | |||||
| 8102 | ||||||
| 8103 | # Check for default value - must come before type constraint check | |||||
| 8104 | 12 | 14 | if ($modifiers =~ /=\s*([^:;]+)(?::|;|$)/) { | |||
| 8105 | 4 | 4 | my $default = $1; | |||
| 8106 | 4 | 5 | $default =~ s/\s+$//; | |||
| 8107 | 4 | 7 | $field_info{_default} = $self->_clean_default_value($default, 1); | |||
| 8108 | 4 | 6 | $field_info{optional} = 1; | |||
| 8109 | 4 | 9 | $self->_log(" FIELD: $name has default: " . (defined $field_info{_default} ? $field_info{_default} : 'undef')); | |||
| 8110 | } | |||||
| 8111 | ||||||
| 8112 | # Check for type constraints | |||||
| 8113 | 12 | 18 | if ($modifiers =~ /:isa\(([^)]+)\)/) { | |||
| 8114 | 3 | 4 | $field_info{isa} = $1; | |||
| 8115 | 3 | 3 | $field_info{type} = 'object'; | |||
| 8116 | 3 | 8 | $self->_log(" FIELD: $name has type constraint: $1"); | |||
| 8117 | } | |||||
| 8118 | ||||||
| 8119 | 12 | 16 | $fields{$name} = \%field_info; | |||
| 8120 | } | |||||
| 8121 | ||||||
| 8122 | 484 | 406 | 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 | |||||
| 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 | # | |||||
| 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 | 6 | 25 | my ($self, $params, $fields) = @_; | |||
| 8155 | ||||||
| 8156 | 6 | 8 | foreach my $field_name (keys %$fields) { | |||
| 8157 | 11 | 6 | my $field = $fields->{$field_name}; | |||
| 8158 | ||||||
| 8159 | # Only process fields that are parameters | |||||
| 8160 | 11 | 14 | next unless $field->{is_param}; | |||
| 8161 | ||||||
| 8162 | 9 | 4 | my $param_name = $field->{param_name}; | |||
| 8163 | ||||||
| 8164 | # Create or update parameter info | |||||
| 8165 | 9 | 18 | $params->{$param_name} ||= {}; | |||
| 8166 | 9 | 6 | my $p = $params->{$param_name}; | |||
| 8167 | ||||||
| 8168 | # Merge field information into parameter | |||||
| 8169 | 9 | 10 | $p->{_source} = SOURCE_FIELD unless $p->{_source}; | |||
| 8170 | 9 | 11 | $p->{field_name} = $field_name if $field_name ne $param_name; | |||
| 8171 | ||||||
| 8172 | 9 | 7 | if ($field->{_default}) { | |||
| 8173 | 3 | 2 | $p->{_default} = $field->{_default}; | |||
| 8174 | 3 | 3 | $p->{optional} = 1; | |||
| 8175 | } | |||||
| 8176 | ||||||
| 8177 | 9 | 8 | if ($field->{isa}) { | |||
| 8178 | 2 | 2 | $p->{isa} = $field->{isa}; | |||
| 8179 | 2 | 3 | $p->{type} = 'object'; | |||
| 8180 | } | |||||
| 8181 | ||||||
| 8182 | 9 | 10 | $self->_log(" MERGED: Field $field_name -> parameter $param_name"); | |||
| 8183 | } | |||||
| 8184 | } | |||||
| 8185 | ||||||
| 8186 | # -------------------------------------------------- | |||||
| 8187 | # _extract_defaults_from_code | |||||
| 8188 | # | |||||
| 8189 | # Purpose: Scan a method body for default value | |||||
| 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 | |||||
| 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 | 481 | 510 | my ($self, $params, $code, $method) = @_; | |||
| 8218 | ||||||
| 8219 | # Pattern 1: my $param = value; | |||||
| 8220 | 481 | 838 | while ($code =~ /my\s+\$(\w+)\s*=\s*([^;]+);/g) { | |||
| 8221 | 172 | 218 | my ($param, $value) = ($1, $2); | |||
| 8222 | 172 | 649 | next unless exists $params->{$param}; | |||
| 8223 | 7 | 10 | next if $value =~ /->/; # deref/method call, not a default value | |||
| 8224 | ||||||
| 8225 | 7 | 15 | $params->{$param}{_default} = $self->_clean_default_value($value, 1); | |||
| 8226 | 7 | 7 | $params->{$param}{optional} = 1; | |||
| 8227 | 7 | 19 | $self->_log(" CODE: $param has default: " . $self->_format_default($params->{$param}{_default})); | |||
| 8228 | } | |||||
| 8229 | ||||||
| 8230 | # Pattern 2: $param = value unless defined $param; | |||||
| 8231 | 481 | 1411 | while ($code =~ /\$(\w+)\s*=\s*([^;]+?)\s+unless\s+(?:defined\s+)?\$\1/g) { | |||
| 8232 | 4 | 5 | my ($param, $value) = ($1, $2); | |||
| 8233 | 4 | 4 | next unless exists $params->{$param}; | |||
| 8234 | ||||||
| 8235 | 4 | 6 | $params->{$param}{_default} = $self->_clean_default_value($value, 1); | |||
| 8236 | 4 | 4 | $params->{$param}{optional} = 1; | |||
| 8237 | 4 | 17 | $self->_log(" CODE: $param has default (unless): " . $self->_format_default($params->{$param}{_default})); | |||
| 8238 | } | |||||
| 8239 | ||||||
| 8240 | # Pattern 3: $param = value unless $param; | |||||
| 8241 | 481 | 990 | while ($code =~ /\$(\w+)\s*=\s*([^;]+?)\s+unless\s+\$\1/g) { | |||
| 8242 | 1 | 1 | my ($param, $value) = ($1, $2); | |||
| 8243 | 1 | 1 | next unless exists $params->{$param}; | |||
| 8244 | ||||||
| 8245 | 1 | 1 | $params->{$param}{_default} = $self->_clean_default_value($value, 1); | |||
| 8246 | 1 | 1 | $params->{$param}{optional} = 1; | |||
| 8247 | 1 | 2 | $self->_log(" CODE: $param has default (unless): " . $self->_format_default($params->{$param}{_default})); | |||
| 8248 | } | |||||
| 8249 | ||||||
| 8250 | # Pattern 4: $param = $param || 'default'; | |||||
| 8251 | 481 | 1028 | while ($code =~ /\$(\w+)\s*=\s*\$\1\s*\|\|\s*([^;]+);/g) { | |||
| 8252 | 8 | 11 | my ($param, $value) = ($1, $2); | |||
| 8253 | 8 | 8 | next unless exists $params->{$param}; | |||
| 8254 | ||||||
| 8255 | 8 | 8 | $params->{$param}{_default} = $self->_clean_default_value($value, 1); | |||
| 8256 | 8 | 7 | $params->{$param}{optional} = 1; | |||
| 8257 | 8 | 11 | $self->_log(" CODE: $param has default (||): " . $self->_format_default($params->{$param}{_default})); | |||
| 8258 | } | |||||
| 8259 | ||||||
| 8260 | # Pattern 5: $param ||= 'default'; | |||||
| 8261 | 481 | 1038 | while ($code =~ /\$(\w+)\s*\|\|=\s*([^;]+);/g) { | |||
| 8262 | 3 | 6 | my ($param, $value) = ($1, $2); | |||
| 8263 | 3 | 9 | next unless exists $params->{$param}; | |||
| 8264 | ||||||
| 8265 | 3 | 6 | $params->{$param}{_default} = $self->_clean_default_value($value, 1); | |||
| 8266 | 3 | 5 | $params->{$param}{optional} = 1; | |||
| 8267 | 3 | 7 | $self->_log(" CODE: $param has default (||=): " . $self->_format_default($params->{$param}{_default})); | |||
| 8268 | } | |||||
| 8269 | ||||||
| 8270 | # Pattern 6: $param //= 'default'; | |||||
| 8271 | 481 | 605 | while ($code =~ /\$(\w+)\s*\/\/=\s*([^;]+);/g) { | |||
| 8272 | 8 | 10 | my ($param, $value) = ($1, $2); | |||
| 8273 | 8 | 9 | next unless exists $params->{$param}; # Using -> because $params is a reference | |||
| 8274 | ||||||
| 8275 | 7 | 11 | $params->{$param}{_default} = $self->_clean_default_value($value, 1); | |||
| 8276 | ||||||
| 8277 | 7 | 6 | $params->{$param}{optional} = 1; | |||
| 8278 | 7 | 12 | $self->_log(" CODE: $param has default (//=): " . $self->_format_default($params->{$param}{_default})); | |||
| 8279 | } | |||||
| 8280 | ||||||
| 8281 | # Pattern 7: $param = defined $param ? $param : 'default'; | |||||
| 8282 | 481 | 762 | while ($code =~ /\$(\w+)\s*=\s*defined\s+\$\1\s*\?\s*\$\1\s*:\s*([^;]+);/g) { | |||
| 8283 | 4 | 4 | my ($param, $value) = ($1, $2); | |||
| 8284 | ||||||
| 8285 | # Create param entry if it doesn't exist | |||||
| 8286 | 4 | 4 | $params->{$param} ||= {}; | |||
| 8287 | ||||||
| 8288 | 4 | 4 | my $cleaned = $self->_clean_default_value($value, 1); | |||
| 8289 | ||||||
| 8290 | 4 | 3 | $params->{$param}{_default} = $cleaned; | |||
| 8291 | 4 | 4 | $params->{$param}{optional} = 1; | |||
| 8292 | 4 | 4 | $self->_log(" CODE: $param has default (ternary): " . $self->_format_default($params->{$param}{_default})); | |||
| 8293 | } | |||||
| 8294 | ||||||
| 8295 | # Pattern 8: $param = $args{param} || 'default'; | |||||
| 8296 | 481 | 633 | while ($code =~ /\$(\w+)\s*=\s*\$args\{['"]?\w+['"]?\}\s*\|\|\s*([^;]+);/g) { | |||
| 8297 | 0 | 0 | my ($param, $value) = ($1, $2); | |||
| 8298 | 0 | 0 | next unless exists $params->{$param}; | |||
| 8299 | ||||||
| 8300 | 0 | 0 | $params->{$param}{_default} = $self->_clean_default_value($value, 1); | |||
| 8301 | 0 | 0 | $params->{$param}{optional} = 1; | |||
| 8302 | 0 | 0 | $self->_log(" CODE: $param has default (from args): " . $self->_format_default($params->{$param}{_default})); | |||
| 8303 | } | |||||
| 8304 | ||||||
| 8305 | # Pattern for non-empty hashref | |||||
| 8306 | 481 | 585 | while ($code =~ /\$(\w+)\s*\|\|=\s*\{[^}]+\}/gs) { | |||
| 8307 | 1 | 1 | my $param = $1; | |||
| 8308 | 1 | 2 | next unless exists $params->{$param}; | |||
| 8309 | ||||||
| 8310 | # Return empty hashref as placeholder (can't evaluate complex hashrefs) | |||||
| 8311 | 1 | 1 | $params->{$param}{_default} = {}; | |||
| 8312 | 1 | 1 | $params->{$param}{optional} = 1; | |||
| 8313 | 1 | 1 | $self->_log(" CODE: $param has hashref default (||=)"); | |||
| 8314 | } | |||||
| 8315 | ||||||
| 8316 | # Fallback: extract parameters from classic Perl body styles | |||||
| 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 | 481 | 294 | if (!keys %{$params} && $code !~ /my\s+\$(?:self|class|pkg|proto|klass)\s*=\s*\$_\[0\]/) { | |||
| 8323 | 260 | 547 | my $position = 0; | |||
| 8324 | ||||||
| 8325 | # Style 1: my ($a, $b) = @_; | |||||
| 8326 | 260 | 370 | while ($code =~ /my\s*\(\s*([^)]+)\s*\)\s*=\s*\@_/g) { | |||
| 8327 | 62 | 103 | my @vars = $1 =~ /\$(\w+)/g; | |||
| 8328 | 62 | 73 | foreach my $var (@vars) { | |||
| 8329 | 60 | 136 | if(($position == 0) && ($var =~ /^(self|class|pkg|proto|klass)$/i)) { | |||
| 8330 | # Invocant â skip it | |||||
| 8331 | 60 | 89 | delete $params->{$var}; | |||
| 8332 | } else { | |||||
| 8333 | 0 | 0 | $params->{$var} ||= { position => $position++ }; | |||
| 8334 | 0 | 0 | $self->_log(" CODE: $var extracted from \@_ list assignment"); | |||
| 8335 | } | |||||
| 8336 | } | |||||
| 8337 | } | |||||
| 8338 | ||||||
| 8339 | # Style 2: my $x = shift; | |||||
| 8340 | 260 | 372 | while ($code =~ /my\s+\$(\w+)\s*=\s*shift\b/g) { | |||
| 8341 | 71 | 67 | my $var = $1; | |||
| 8342 | 71 | 226 | if(($position == 0) && ($var =~ /^(self|class|pkg|proto|klass)$/i)) { | |||
| 8343 | # Invocant â skip it | |||||
| 8344 | 27 | 33 | delete $params->{$var}; | |||
| 8345 | } else { | |||||
| 8346 | 44 | 158 | $params->{$var} ||= { position => $position++ }; | |||
| 8347 | 44 | 71 | $self->_log(" CODE: $var is extracted from shift"); | |||
| 8348 | } | |||||
| 8349 | } | |||||
| 8350 | ||||||
| 8351 | # Style 3: my $x = $_[0]; | |||||
| 8352 | 260 | 377 | while ($code =~ /my\s+\$(\w+)\s*=\s*\$_\[(\d+)\]/g) { | |||
| 8353 | 0 | 0 | my ($var, $index) = ($1, $2); | |||
| 8354 | 0 | 0 | if(($index > 0) || ($var !~ /^(self|class|pkg|proto|klass)$/i)) { | |||
| 8355 | 0 | 0 | $params->{$var} ||= { position => $index }; | |||
| 8356 | 0 | 0 | $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 | 39 | 41 | my ($self, $default) = @_; | |||
| 8382 | 39 | 35 | return 'undef' unless defined $default; | |||
| 8383 | 36 | 42 | return ref($default) . ' ref' if ref($default); | |||
| 8384 | 31 | 41 | 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 | 28 | 28 | my ($self, $rhs) = @_; | |||
| 8391 | ||||||
| 8392 | 28 | 49 | return $rhs + 0 if $rhs =~ /^\d+$/; | |||
| 8393 | 6 | 21 | return undef unless $rhs =~ /^\$(\w+)$/; | |||
| 8394 | 6 | 6 | 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 | 28 | 35 | my ($self, $p, $op, $val, $invert) = @_; | |||
| 8401 | ||||||
| 8402 | 28 | 29 | if($invert) { | |||
| 8403 | 9 | 18 | my %negated = ('<' => '>=', '<=' => '>', '>' => '<=', '>=' => '<'); | |||
| 8404 | 9 | 12 | $op = $negated{$op}; | |||
| 8405 | } | |||||
| 8406 | ||||||
| 8407 | 28 | 64 | if($op eq '<') { | |||
| 8408 | 0 | 0 | my $max = $val - 1; | |||
| 8409 | 0 | 0 | $p->{max} = $max if !defined($p->{max}) || $max < $p->{max}; | |||
| 8410 | } elsif($op eq '<=') { | |||||
| 8411 | 8 | 21 | $p->{max} = $val if !defined($p->{max}) || $val < $p->{max}; | |||
| 8412 | } elsif($op eq '>') { | |||||
| 8413 | 0 | 0 | my $min = $val + 1; | |||
| 8414 | 0 | 0 | $p->{min} = $min if !defined($p->{min}) || $min > $p->{min}; | |||
| 8415 | } elsif($op eq '>=') { | |||||
| 8416 | 20 | 41 | $p->{min} = $val if !defined($p->{min}) || $val > $p->{min}; | |||
| 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 { | |||||
| 8428 | 173 | 178 | my ($self, $param, $condition) = @_; | |||
| 8429 | ||||||
| 8430 | 173 | 162 | $condition =~ s/^\s+//; | |||
| 8431 | 173 | 220 | $condition =~ s/\s+$//; | |||
| 8432 | ||||||
| 8433 | # Drop balanced outer parentheses, as in `if (length($t) < 5)`. | |||||
| 8434 | 173 | 221 | while($condition =~ /^\((.*)\)$/s) { | |||
| 8435 | 0 | 0 | my $inner = $1; | |||
| 8436 | 0 | 0 | my $depth = 0; | |||
| 8437 | 0 | 0 | my $balanced = 1; | |||
| 8438 | 0 | 0 | foreach my $char (split(//, $inner)) { | |||
| 8439 | 0 | 0 | if($char eq '(') { | |||
| 8440 | 0 | 0 | $depth++; | |||
| 8441 | } elsif($char eq ')') { | |||||
| 8442 | 0 | 0 | $depth--; | |||
| 8443 | 0 | 0 | if($depth < 0) { | |||
| 8444 | 0 | 0 | $balanced = 0; | |||
| 8445 | 0 | 0 | last; | |||
| 8446 | } | |||||
| 8447 | } | |||||
| 8448 | } | |||||
| 8449 | 0 | 0 | last unless $balanced && ($depth == 0); | |||
| 8450 | 0 | 0 | $condition = $inner; | |||
| 8451 | 0 | 0 | $condition =~ s/^\s+//; | |||
| 8452 | 0 | 0 | $condition =~ s/\s+$//; | |||
| 8453 | } | |||||
| 8454 | ||||||
| 8455 | 173 | 3367 | return unless $condition =~ /^length\s*\(\s*\$\Q$param\E\s*\)\s*([<>]=?)\s*(\d+|\$\w+)$/; | |||
| 8456 | ||||||
| 8457 | 26 | 39 | my ($op, $rhs) = ($1, $2); | |||
| 8458 | 26 | 41 | my $val = $self->_length_constraint_value($rhs); | |||
| 8459 | 26 | 30 | return unless defined $val; | |||
| 8460 | ||||||
| 8461 | 26 | 35 | return ($op, $val); | |||
| 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 | # -------------------------------------------------- | |||||
| 8483 | sub _module_constants { | |||||
| 8484 | 6 | 3 | my ($self) = @_; | |||
| 8485 | 6 | 11 | return $self->{_constants} if exists $self->{_constants}; | |||
| 8486 | ||||||
| 8487 | 2 | 2 | my %c; | |||
| 8488 | 2 | 2 | my $doc = $self->{_document}; | |||
| 8489 | 2 | 4 | unless ($doc) { | |||
| 8490 | 0 | 0 | $self->{_constants} = \%c; | |||
| 8491 | 0 | 0 | return \%c; | |||
| 8492 | } | |||||
| 8493 | ||||||
| 8494 | 2 | 5 | my $src = $doc->serialize(); | |||
| 8495 | ||||||
| 8496 | # Readonly my $CONST => numeric_value; | |||||
| 8497 | 2 | 3865 | while ($src =~ /Readonly\s+(?:my|our)\s+\$(\w+)\s*=>\s*([+-]?\d+(?:\.\d+)?)/g) { | |||
| 8498 | 10 | 27 | $c{$1} = $2; | |||
| 8499 | } | |||||
| 8500 | ||||||
| 8501 | # use constant CONST => numeric_value; | |||||
| 8502 | 2 | 12 | while ($src =~ /use\s+constant\s+(\w+)\s*=>\s*([+-]?\d+(?:\.\d+)?)/g) { | |||
| 8503 | 0 | 0 | $c{$1} = $2; | |||
| 8504 | } | |||||
| 8505 | ||||||
| 8506 | 2 | 5 | $self->{_constants} = \%c; | |||
| 8507 | 2 | 4 | return \%c; | |||
| 8508 | } | |||||
| 8509 | ||||||
| 8510 | # -------------------------------------------------- | |||||
| 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 | 356 | 604 | my ($self, $p_ref, $param, $code) = @_; | |||
| 8538 | 356 | 232 | my $p = $$p_ref; | |||
| 8539 | ||||||
| 8540 | # Do not treat comparisons inside die/croak/confess as valid constraints | |||||
| 8541 | 356 | 235 | my $guarded = 0; | |||
| 8542 | 356 | 4997 | if ($code =~ /(die|croak|confess)\b[^{;]*\bif\b[^{;]*\$$param\b/s) { | |||
| 8543 | 39 | 36 | $guarded = 1; | |||
| 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 | |||||
| 8549 | # second condition literally would invent a max of 4 and can contradict | |||||
| 8550 | # a min inferred from the first form. | |||||
| 8551 | 356 | 3521 | $p->{type} ||= 'string' if $code =~ /length\s*\(\s*\$$param\s*\)/; | |||
| 8552 | ||||||
| 8553 | 356 | 288 | my $postfix_guards = $code; | |||
| 8554 | 356 | 1197 | while ($postfix_guards =~ /\b(?:croak|die|confess)\b[^;{}]*?\b(if|unless)\b\s*([^;{}]+)/g) { | |||
| 8555 | 173 | 213 | my ($guard, $condition) = ($1, $2); | |||
| 8556 | 173 | 237 | my ($op, $val) = $self->_whole_condition_length_guard($param, $condition); | |||
| 8557 | 173 | 293 | next unless defined $op; | |||
| 8558 | 26 | 44 | $self->_record_length_constraint($p, $op, $val, ($guard eq 'if')); | |||
| 8559 | 26 | 45 | $self->_log(" CODE: $param length constraint from $guard guard: $op $val"); | |||
| 8560 | } | |||||
| 8561 | ||||||
| 8562 | 356 | 263 | my $block_guards = $code; | |||
| 8563 | 356 | 13334 | while ($block_guards =~ /\b(if|unless)\s*\(\s*length\s*\(\s*\$$param\s*\)\s*([<>]=?)\s*(\d+|\$\w+)\s*\)\s*\{([^{}]*)\}/g) { | |||
| 8564 | 2 | 4 | my ($guard, $op, $rhs, $block) = ($1, $2, $3, $4); | |||
| 8565 | 2 | 4 | next unless $block =~ /\b(?:croak|die|confess)\b/; | |||
| 8566 | 2 | 1 | my $val = $self->_length_constraint_value($rhs); | |||
| 8567 | 2 | 2 | next unless defined $val; | |||
| 8568 | 2 | 2 | $self->_record_length_constraint($p, $op, $val, ($guard eq 'if')); | |||
| 8569 | 2 | 2 | $self->_log(" CODE: $param length constraint from $guard block: $op $rhs"); | |||
| 8570 | } | |||||
| 8571 | ||||||
| 8572 | # Numeric range checks (only if NOT part of error guard) | |||||
| 8573 | 356 | 4927 | if ( | |||
| 8574 | !$guarded | |||||
| 8575 | && $code =~ /\$$param\s*([<>]=?)\s*([+-]?(?:\d+\.?\d*|\.\d+))/ | |||||
| 8576 | ) { | |||||
| 8577 | 15 | 21 | my ($op, $val) = ($1, $2); | |||
| 8578 | 15 | 22 | $p->{type} ||= looks_like_number($val) ? 'number' : 'integer'; | |||
| 8579 | ||||||
| 8580 | 15 | 50 | if ($op eq '<' || $op eq '<=') { | |||
| 8581 | # Only set max if it tightens the range | |||||
| 8582 | 2 | 4 | my $max = ($op eq '<') ? $val - 1 : $val; | |||
| 8583 | 2 | 6 | $p->{max} = $max if !defined($p->{max}) || $max < $p->{max}; | |||
| 8584 | } elsif ($op eq '>' || $op eq '>=') { | |||||
| 8585 | 13 | 16 | my $min = ($op eq '>') ? $val + 1 : $val; | |||
| 8586 | 13 | 28 | $p->{min} = $min if !defined($p->{min}) || $min > $p->{min}; | |||
| 8587 | } | |||||
| 8588 | } | |||||
| 8589 | ||||||
| 8590 | # Regex pattern matching with better capture | |||||
| 8591 | 356 | 11925 | if($code =~ /\$$param\s*=~\s*(?:qr?\/([^\/]+)\/|(\$[\w:]+|\$\{\w+\}))/ ) { | |||
| 8592 | 2 | 4 | my ($body, $variable) = ($1, $2); | |||
| 8593 | 2 | 6 | $p->{type} ||= 'string'; | |||
| 8594 | ||||||
| 8595 | 2 | 4 | 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 | 1 | 2 | $self->_log(" CODE: $param matches $variable, a pattern held in a variable; not recorded"); | |||
| 8599 | } elsif(!_pattern_is_self_contained($body)) { | |||||
| 8600 | 0 | 0 | $self->_log(" CODE: $param matches '$body', which depends on run-time variables; not recorded"); | |||
| 8601 | } else { | |||||
| 8602 | 1 | 2 | $p->{matches} = "/$body/"; | |||
| 8603 | 1 | 2 | $self->_log(" CODE: $param matches pattern: $p->{matches}"); | |||
| 8604 | } | |||||
| 8605 | } | |||||
| 8606 | } | |||||
| 8607 | ||||||
| 8608 | # -------------------------------------------------- | |||||
| 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 | 19 | 18 | my ($pattern) = @_; | |||
| 8630 | ||||||
| 8631 | 19 | 30 | return 0 unless defined($pattern) && length($pattern); | |||
| 8632 | 19 | 32 | return 0 if $pattern =~ /\\[QE]/; | |||
| 8633 | 18 | 24 | return 0 if $pattern =~ /(?<!\\)[\$\@]\w/; | |||
| 8634 | ||||||
| 8635 | 18 | 31 | return 1; | |||
| 8636 | } | |||||
| 8637 | ||||||
| 8638 | # -------------------------------------------------- | |||||
| 8639 | # _analyze_parameter_validation | |||||
| 8640 | # | |||||
| 8641 | # Purpose: Determine optionality and extract | |||||
| 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). | |||||
| 8649 | # $param - parameter name string. | |||||
| 8650 | # $code - method body source string. | |||||
| 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 | 353 | 361 | my ($self, $p_ref, $param, $code) = @_; | |||
| 8664 | 353 | 246 | my $p = $$p_ref; | |||
| 8665 | ||||||
| 8666 | # Required/optional checks | |||||
| 8667 | 353 | 223 | my $is_required = 0; | |||
| 8668 | ||||||
| 8669 | # Die/croak if not defined | |||||
| 8670 | 353 | 6194 | if ($code =~ /(?:die|croak|confess)\s+[^;]*unless\s+(?:defined\s+)?\$$param/s) { | |||
| 8671 | 36 | 27 | $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 | 353 | 8374 | if($code =~ /(?:croak|die|confess)\b[^;]*\bunless\b[^;]*?(?:length\s*\(?\s*\$$param\b|defined\s+\$$param\b[^;]*?\blength\b)/s) { | |||
| 8678 | 16 | 28 | $is_required = 1; | |||
| 8679 | 16 | 32 | $p->{_not_empty} = 1; | |||
| 8680 | 16 | 49 | $self->_log(" CODE: $param must not be empty (the code rejects it)"); | |||
| 8681 | } | |||||
| 8682 | ||||||
| 8683 | # Extract default values with the new method | |||||
| 8684 | 353 | 668 | my $default_value = $self->_extract_default_value($param, $code); | |||
| 8685 | 353 | 449 | if (defined $default_value && !exists $p->{_default}) { | |||
| 8686 | 3 | 3 | $p->{optional} = 1; | |||
| 8687 | 3 | 3 | $p->{_default} = $default_value; | |||
| 8688 | ||||||
| 8689 | # Try to infer type from default value if not already set | |||||
| 8690 | 3 | 5 | unless ($p->{type}) { | |||
| 8691 | 3 | 5 | if (looks_like_number($default_value)) { | |||
| 8692 | 3 | 5 | $p->{type} = $default_value =~ /\./ ? 'number' : 'integer'; | |||
| 8693 | } elsif (ref($default_value) eq 'ARRAY') { | |||||
| 8694 | 0 | 0 | $p->{type} = 'arrayref'; | |||
| 8695 | } elsif (ref($default_value) eq 'HASH') { | |||||
| 8696 | 0 | 0 | $p->{type} = 'hashref'; | |||
| 8697 | } elsif ($default_value eq 'undef') { | |||||
| 8698 | 0 | 0 | $p->{type} = 'scalar'; # undef can be any scalar | |||
| 8699 | } elsif (defined $default_value && !ref($default_value)) { | |||||
| 8700 | 0 | 0 | $p->{type} = 'string'; | |||
| 8701 | } | |||||
| 8702 | } | |||||
| 8703 | ||||||
| 8704 | 3 | 8 | $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 | 353 | 5497 | if (!$default_value && !exists $p->{_default} && $code =~ /\$$param\s*=\s*([^;{}]+?)(?:\s*[;}])/s) { | |||
| 8710 | 57 | 65 | my $assignment = $1; | |||
| 8711 | # Make sure it's not part of a larger expression | |||||
| 8712 | 57 | 291 | if ($assignment !~ /\$$param/ && $assignment !~ /^shift/) { | |||
| 8713 | 12 | 11 | my $possible_default = $assignment; | |||
| 8714 | 12 | 13 | $possible_default =~ s/\s*;\s*$//; | |||
| 8715 | 12 | 27 | $possible_default = $self->_clean_default_value($possible_default); | |||
| 8716 | 12 | 17 | if (defined $possible_default) { | |||
| 8717 | 12 | 15 | $p->{_default} = $possible_default; | |||
| 8718 | 12 | 14 | $p->{optional} = 1; | |||
| 8719 | 12 | 21 | $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 | 353 | 4193 | if (!$is_required && ($code =~ /\b(?:if|unless)\s*\(\s*\$$param\s*\)/)) { | |||
| 8728 | 2 | 3 | $p->{optional} = 1; | |||
| 8729 | 2 | 4 | $self->_log(" CODE: $param is optional (only used when truthy)"); | |||
| 8730 | } | |||||
| 8731 | ||||||
| 8732 | # Explicit required check overrides default detection | |||||
| 8733 | 353 | 591 | if ($is_required) { | |||
| 8734 | 46 | 62 | $p->{optional} = 0; | |||
| 8735 | 46 | 62 | delete $p->{_default} if exists $p->{_default}; | |||
| 8736 | 46 | 66 | $self->_log(" CODE: $param is required (validation check)"); | |||
| 8737 | } | |||||
| 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 | # | |||||
| 8753 | # 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. | |||||
| 8759 | # | |||||
| 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 | 465 | 462 | my ($self, $pod, $code_params, $code) = @_; | |||
| 8765 | ||||||
| 8766 | 465 220 | 506 383 | my @documented = grep { ($pod->{$_}{_source} // '') eq SOURCE_INPUT_SPEC } keys %$pod; | |||
| 8767 | 465 | 571 | return undef unless @documented == 1; | |||
| 8768 | 58 | 96 | return undef unless $self->_argument_style($code) eq 'positional'; | |||
| 8769 | ||||||
| 8770 | 52 | 55 | my ($name) = @documented; | |||
| 8771 | 52 | 86 | $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 | 52 | 71 | my @code_names = keys %$code_params; | |||
| 8776 | 52 | 82 | 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 | 52 | 102 | %$code_params = $source ? ($name => $code_params->{$source}) : (); | |||
| 8782 | 52 | 75 | %$pod = ($name => $pod->{$name}); | |||
| 8783 | 52 | 102 | $self->_log(" POD: single Input spec '$name' describes a positional argument"); | |||
| 8784 | ||||||
| 8785 | 52 | 47 | return $name; | |||
| 8786 | } | |||||
| 8787 | ||||||
| 8788 | # -------------------------------------------------- | |||||
| 8789 | # _argument_style | |||||
| 8790 | # | |||||
| 8791 | # Purpose: Classify how a subroutine reads its arguments. | |||||
| 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. | |||||
| 8803 | # | |||||
| 8804 | # Side effects: None. | |||||
| 8805 | # -------------------------------------------------- | |||||
| 8806 | sub _argument_style { | |||||
| 8807 | 58 | 76 | my ($self, $code) = @_; | |||
| 8808 | ||||||
| 8809 | 58 | 67 | return '' unless defined $code; | |||
| 8810 | ||||||
| 8811 | 58 | 55 | my $body = $code; | |||
| 8812 | 58 | 78 | $body =~ s/\$self\s*->\s*\{[^}]*\}//g; | |||
| 8813 | ||||||
| 8814 | 58 | 104 | return 'named' if($body =~ /\bmy\s+%\w+\s*=[^;]*\@_/s); | |||
| 8815 | 58 | 114 | return 'named' if($body =~ /\bmy\s*\(\s*[^)]*%\w+\s*\)\s*=\s*\@_/s); | |||
| 8816 | 55 | 94 | return 'named' if($body =~ /\$_\s*\[\s*\d+\s*\]\s*(?:->\s*)?\{/); | |||
| 8817 | 55 | 93 | return 'named' if($body =~ /\$\w+\s*->\s*\{/); | |||
| 8818 | ||||||
| 8819 | 52 | 75 | return 'positional' if($body =~ /\$_\s*\[\s*\d+\s*\]/); | |||
| 8820 | 51 | 176 | return 'positional' if($body =~ /\bmy\s+\$(?!self\b|class\b)\w+\s*=\s*shift\b/); | |||
| 8821 | 18 | 64 | return 'positional' if($body =~ /\bmy\s*\((?!\s*\$(?:self|class)\s*\))[^)]*\)\s*=\s*\@_/s); | |||
| 8822 | ||||||
| 8823 | 0 | 0 | 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. | |||||
| 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 | # | |||||
| 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. Optional | |||||
| 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 | # | |||||
| 8863 | # Purpose: Drop keys that cannot be parameter names, and report them. | |||||
| 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 | 2617 | 79902 | my ($self, $params, $where) = @_; | |||
| 8880 | ||||||
| 8881 | 2617 | 1331 | my $dropped = 0; | |||
| 8882 | 2617 | 1765 | for my $name (keys %$params) { | |||
| 8883 | 1730 | 2521 | 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 | 1730 | 1700 | next unless $invalid; | |||
| 8887 | ||||||
| 8888 | 2 | 11 | carp(__PACKAGE__ . ": ignoring parameter key '$name' from $where: not a parameter name"); | |||
| 8889 | 2 | 165 | delete $params->{$name}; | |||
| 8890 | 2 | 2 | $dropped++; | |||
| 8891 | } | |||||
| 8892 | ||||||
| 8893 | 2617 | 1706 | return $dropped; | |||
| 8894 | } | |||||
| 8895 | ||||||
| 8896 | sub _merge_parameter_analyses { | |||||
| 8897 | 471 | 469 | 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. | |||||
| 8901 | $self->_sanitize_parameter_names($_, 'parameter merge') | |||||
| 8902 | 471 1413 | 362 1420 | 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 | 471 | 804 | if(ref($pod) eq 'HASH' && ref($code) eq 'HASH') { | |||
| 8910 | 471 | 395 | for my $code_name (keys %$code) { | |||
| 8911 | 348 | 354 | next if exists $pod->{$code_name}; | |||
| 8912 | 178 | 131 | my $pos = $code->{$code_name}{position}; | |||
| 8913 | 178 | 176 | next unless defined($pos); | |||
| 8914 | my ($pod_name) = grep { | |||||
| 8915 | 173 | 182 | !exists($code->{$_}) | |||
| 8916 | && defined($pod->{$_}{position}) | |||||
| 8917 | 15 | 37 | && ($pod->{$_}{position} == $pos) | |||
| 8918 | } sort keys %$pod; | |||||
| 8919 | 173 | 163 | next unless defined($pod_name); | |||
| 8920 | 1 | 1 | $code->{$pod_name} = delete $code->{$code_name}; | |||
| 8921 | 1 | 2 | $self->_log(" MERGE: code parameter \$$code_name is the documented \$$pod_name"); | |||
| 8922 | } | |||||
| 8923 | } | |||||
| 8924 | ||||||
| 8925 | 471 | 300 | my %merged; | |||
| 8926 | ||||||
| 8927 | 471 | 579 | my @constraint_keys = qw(min max memberof matches nomatch notmemberof); | |||
| 8928 | 471 2826 | 386 2205 | my %is_constraint = map { $_ => 1 } @constraint_keys; | |||
| 8929 | ||||||
| 8930 | # Start with all parameters from all sources | |||||
| 8931 | 471 573 | 661 500 | my %all_params = map { $_ => 1 } (keys %$pod, keys %$code, keys %$sig); | |||
| 8932 | ||||||
| 8933 | 471 | 484 | foreach my $param (keys %all_params) { | |||
| 8934 | 402 | 485 | my $p = $merged{$param} = {}; | |||
| 8935 | ||||||
| 8936 | # Collect position from all sources | |||||
| 8937 | 402 | 268 | my @positions; | |||
| 8938 | 402 | 674 | push @positions, $pod->{$param}{position} if $pod->{$param} && defined $pod->{$param}{position}; | |||
| 8939 | 402 | 428 | push @positions, $sig->{$param}{position} if $sig->{$param} && defined $sig->{$param}{position}; | |||
| 8940 | 402 | 720 | push @positions, $code->{$param}{position} if $code->{$param} && defined $code->{$param}{position}; | |||
| 8941 | ||||||
| 8942 | # Use the most common position, or lowest if tie | |||||
| 8943 | 402 | 362 | if (@positions) { | |||
| 8944 | 361 | 219 | my %pos_count; | |||
| 8945 | 361 | 604 | $pos_count{$_}++ for @positions; | |||
| 8946 | 361 1 | 399 3 | my ($best_pos) = sort { $pos_count{$b} <=> $pos_count{$a} || $a <=> $b } keys %pos_count; | |||
| 8947 | 361 | 602 | $p->{position} = $best_pos unless(exists($p->{position})); | |||
| 8948 | } | |||||
| 8949 | ||||||
| 8950 | # POD has highest priority for type info and explicit declarations | |||||
| 8951 | 402 | 364 | if ($pod->{$param}) { | |||
| 8952 | 225 225 | 215 371 | %$p = (%$p, %{$pod->{$param}}); | |||
| 8953 | 225 | 297 | $p->{_source} //= SOURCE_POD; | |||
| 8954 | ||||||
| 8955 | # Record which source each constraint came from, so a documented | |||||
| 8956 | # minimum does not make a maximum enforced by the code tolerant. | |||||
| 8957 | 225 | 265 | my $source = $pod->{$param}{_source} // SOURCE_POD; | |||
| 8958 | 225 | 188 | for my $key (@constraint_keys) { | |||
| 8959 | 1350 | 1094 | next unless exists($pod->{$param}{$key}) && defined($pod->{$param}{$key}); | |||
| 8960 | 91 | 167 | $p->{_constraint_source}{$key} //= $source; | |||
| 8961 | } | |||||
| 8962 | } | |||||
| 8963 | ||||||
| 8964 | # Code analysis adds concrete evidence (but doesn't override POD explicit types) | |||||
| 8965 | 402 | 385 | if ($code->{$param}) { | |||
| 8966 | 348 348 | 218 391 | foreach my $key (keys %{$code->{$param}}) { | |||
| 8967 | 1440 | 951 | next if $key eq '_source'; | |||
| 8968 | 1140 | 689 | next if $key eq 'position'; | |||
| 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 | 797 | 484 | my $from_pod = exists $pod->{$param}; | |||
| 8975 | # A documented type is the specification; only a type the code | |||||
| 8976 | # shows outright replaces it, not one a pattern in the body | |||||
| 8977 | # was guessed to imply (qr/$pattern/ is not division). | |||||
| 8978 | 797 | 779 | my $heuristic_type = (($code->{$param}{_type_confidence} // '') eq 'heuristic'); | |||
| 8979 | 797 | 980 | if (!exists $p->{$key} || | |||
| 8980 | ($key eq 'type' && $from_pod && $p->{type} eq 'string' && | |||||
| 8981 | $code->{$param}{$key} ne 'string' && !$heuristic_type)) { | |||||
| 8982 | 640 | 439 | $p->{$key} = $code->{$param}{$key}; | |||
| 8983 | 640 | 556 | $p->{_constraint_source}{$key} = SOURCE_CODE if $is_constraint{$key}; | |||
| 8984 | } | |||||
| 8985 | } | |||||
| 8986 | 348 | 501 | $p->{_source} //= $code->{$param}{_source}; | |||
| 8987 | } | |||||
| 8988 | ||||||
| 8989 | # Signature fills in remaining gaps | |||||
| 8990 | 402 | 385 | if ($sig->{$param}) { | |||
| 8991 | 0 0 | 0 0 | foreach my $key (keys %{$sig->{$param}}) { | |||
| 8992 | 0 | 0 | next if $key eq '_source'; | |||
| 8993 | 0 | 0 | next if $key eq 'position'; | |||
| 8994 | 0 | 0 | next if defined($p->{$key}); | |||
| 8995 | 0 | 0 | $p->{$key} = $sig->{$param}{$key}; | |||
| 8996 | 0 | 0 | $p->{_constraint_source}{$key} = SOURCE_SIGNATURE if $is_constraint{$key}; | |||
| 8997 | } | |||||
| 8998 | 0 | 0 | $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 | 402 | 546 | $self->_determine_optional_status($p, $pod->{$param}, $code->{$param}); | |||
| 9007 | } | |||||
| 9008 | ||||||
| 9009 | # Debug logging | |||||
| 9010 | 471 | 499 | if ($self->{verbose}) { | |||
| 9011 | 2 1 | 4 3 | foreach my $param (sort { ($merged{$a}{position} || 999) <=> ($merged{$b}{position} || 999) } keys %merged) { | |||
| 9012 | 2 | 1 | my $p = $merged{$param}; | |||
| 9013 | $self->_log(" MERGED $param: " . | |||||
| 9014 | 'pos=' . (defined($p->{position}) ? $p->{position} : 'none') . | |||||
| 9015 | ", type=" . ($p->{type} || 'none') . | |||||
| 9016 | 2 | 5 | ", optional=" . (defined($p->{optional}) ? $p->{optional} : 'undef')); | |||
| 9017 | } | |||||
| 9018 | } | |||||
| 9019 | ||||||
| 9020 | 471 | 930 | return \%merged; | |||
| 9021 | } | |||||
| 9022 | ||||||
| 9023 | # -------------------------------------------------- | |||||
| 9024 | # _determine_optional_status | |||||
| 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 | |||||
| 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 | 408 | 1084 | my ($self, $merged_param, $pod_param, $code_param) = @_; | |||
| 9046 | ||||||
| 9047 | 408 | 390 | my $pod_optional = $pod_param ? $pod_param->{optional} : undef; | |||
| 9048 | 408 | 426 | my $code_optional = $code_param ? $code_param->{optional} : undef; | |||
| 9049 | ||||||
| 9050 | # Explicit POD declaration wins | |||||
| 9051 | 408 | 430 | if (defined $pod_optional) { | |||
| 9052 | 122 | 142 | $merged_param->{optional} = $pod_optional; | |||
| 9053 | } | |||||
| 9054 | # Code validation evidence | |||||
| 9055 | elsif (defined $code_optional) { | |||||
| 9056 | 256 | 323 | $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 | 30 | 40 | $merged_param->{optional} = 0; | |||
| 9061 | } | |||||
| 9062 | # Otherwise leave undef (unknown) | |||||
| 9063 | } | |||||
| 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 { | |||||
| 9097 | 165 | 3097 | my ($self, $params) = @_; | |||
| 9098 | ||||||
| 9099 | 165 | 122 | my @factors; # Track all confidence factors | |||
| 9100 | ||||||
| 9101 | 165 | 278 | return { level => 'none', factors => ['No parameters found'] } unless keys %$params; | |||
| 9102 | ||||||
| 9103 | 128 | 98 | my $total_score = 0; | |||
| 9104 | 128 | 82 | my $count = 0; | |||
| 9105 | 128 | 93 | my %param_details; # Store per-parameter analysis | |||
| 9106 | ||||||
| 9107 | 128 | 155 | foreach my $param (keys %$params) { | |||
| 9108 | 163 | 119 | my $p = $params->{$param}; | |||
| 9109 | 163 | 88 | my $score = 0; | |||
| 9110 | 163 | 105 | my @param_factors; | |||
| 9111 | ||||||
| 9112 | # Type information | |||||
| 9113 | 163 | 207 | if ($p->{type}) { | |||
| 9114 | 162 | 639 | if ($p->{type} eq 'string' && ($p->{min} || $p->{max} || $p->{matches})) { | |||
| 9115 | 44 | 31 | $score += 25; | |||
| 9116 | 44 | 52 | push @param_factors, "Type: constrained string (+25)"; | |||
| 9117 | } elsif ($p->{type} eq 'string') { | |||||
| 9118 | 31 | 26 | $score += 10; | |||
| 9119 | 31 | 27 | push @param_factors, "Type: plain string (+10)"; | |||
| 9120 | } else { | |||||
| 9121 | 87 | 76 | $score += 30; | |||
| 9122 | 87 | 100 | push @param_factors, "Type: $p->{type} (+30)"; | |||
| 9123 | } | |||||
| 9124 | } else { | |||||
| 9125 | 1 | 1 | push @param_factors, "No type information (-0)"; | |||
| 9126 | } | |||||
| 9127 | ||||||
| 9128 | # Constraints | |||||
| 9129 | 163 | 185 | if (defined $p->{min}) { | |||
| 9130 | 50 | 32 | $score += 15; | |||
| 9131 | 50 | 49 | push @param_factors, 'Has min constraint (+15)'; | |||
| 9132 | } | |||||
| 9133 | 163 | 207 | if (defined $p->{max}) { | |||
| 9134 | 30 | 23 | $score += 15; | |||
| 9135 | 30 | 28 | push @param_factors, "Has max constraint (+15)"; | |||
| 9136 | } | |||||
| 9137 | 163 | 179 | if (defined $p->{optional}) { | |||
| 9138 | 157 | 122 | $score += 20; | |||
| 9139 | 157 | 124 | push @param_factors, "Optional/required explicitly defined (+20)"; | |||
| 9140 | } | |||||
| 9141 | 163 | 182 | if ($p->{matches}) { | |||
| 9142 | 13 | 10 | $score += 20; | |||
| 9143 | 13 | 7 | push @param_factors, 'Has regex pattern constraint (+20)'; | |||
| 9144 | } | |||||
| 9145 | 163 | 217 | if ($p->{isa}) { | |||
| 9146 | 5 | 4 | $score += 25; | |||
| 9147 | 5 | 4 | push @param_factors, "Specific class constraint: $p->{isa} (+25)"; | |||
| 9148 | } | |||||
| 9149 | ||||||
| 9150 | # Position information | |||||
| 9151 | 163 | 203 | if (defined $p->{position}) { | |||
| 9152 | 150 | 100 | $score += 10; | |||
| 9153 | 150 | 169 | push @param_factors, "Position defined: $p->{position} (+10)"; | |||
| 9154 | } | |||||
| 9155 | ||||||
| 9156 | # Default value | |||||
| 9157 | 163 | 212 | if (exists $p->{_default}) { | |||
| 9158 | 26 | 13 | $score += 10; | |||
| 9159 | 26 | 16 | push @param_factors, "Has default value (+10)"; | |||
| 9160 | } | |||||
| 9161 | ||||||
| 9162 | # Semantic information | |||||
| 9163 | 163 | 241 | if ($p->{semantic}) { | |||
| 9164 | 17 | 6 | $score += 15; | |||
| 9165 | 17 | 15 | push @param_factors, "Semantic type: $p->{semantic} (+15)"; | |||
| 9166 | } | |||||
| 9167 | ||||||
| 9168 | 163 | 269 | $param_details{$param} = { | |||
| 9169 | score => $score, | |||||
| 9170 | factors => \@param_factors | |||||
| 9171 | }; | |||||
| 9172 | ||||||
| 9173 | 163 | 107 | $total_score += $score; | |||
| 9174 | 163 | 121 | $count++; | |||
| 9175 | } | |||||
| 9176 | ||||||
| 9177 | 128 | 217 | my $avg = $count ? ($total_score / $count) : 0; | |||
| 9178 | ||||||
| 9179 | # Build summary factors | |||||
| 9180 | 128 | 273 | push @factors, sprintf("Analyzed %d parameter%s", $count, $count == 1 ? '' : 's'); | |||
| 9181 | 128 | 671 | push @factors, sprintf("Average confidence score: %.1f", $avg); | |||
| 9182 | ||||||
| 9183 | # Add top contributing factors | |||||
| 9184 | 128 45 | 198 49 | my @sorted_params = sort { $param_details{$b}{score} <=> $param_details{$a}{score} } keys %param_details; | |||
| 9185 | ||||||
| 9186 | 128 | 186 | if (@sorted_params) { | |||
| 9187 | 128 | 106 | my $highest = $sorted_params[0]; | |||
| 9188 | 128 | 118 | my $highest_score = $param_details{$highest}{score}; | |||
| 9189 | 128 | 177 | push @factors, sprintf("Highest scoring parameter: \$$highest (score: %d)", $highest_score); | |||
| 9190 | ||||||
| 9191 | 128 | 251 | if (@sorted_params > 1) { | |||
| 9192 | 25 | 18 | my $lowest = $sorted_params[-1]; | |||
| 9193 | 25 | 63 | my $lowest_score = $param_details{$lowest}{score}; | |||
| 9194 | 25 | 41 | push @factors, sprintf("Lowest scoring parameter: \$$lowest (score: %d)", $lowest_score); | |||
| 9195 | } | |||||
| 9196 | } | |||||
| 9197 | ||||||
| 9198 | # Determine confidence level | |||||
| 9199 | 128 | 89 | my $level; | |||
| 9200 | 128 | 185 | if ($avg >= $CONFIDENCE_HIGH_THRESHOLD) { | |||
| 9201 | 99 | 393 | $level = $LEVEL_HIGH; | |||
| 9202 | 99 | 217 | push @factors, "High confidence: comprehensive type and constraint information"; | |||
| 9203 | } elsif ($avg >= $CONFIDENCE_MEDIUM_THRESHOLD) { | |||||
| 9204 | 23 | 96 | $level = $LEVEL_MEDIUM; | |||
| 9205 | 23 | 43 | push @factors, "Medium confidence: some type or constraint information present"; | |||
| 9206 | } elsif ($avg >= $CONFIDENCE_LOW_THRESHOLD) { | |||||
| 9207 | 3 | 24 | $level = $LEVEL_LOW; | |||
| 9208 | 3 | 10 | push @factors, "Low confidence: minimal type information"; | |||
| 9209 | } else { | |||||
| 9210 | 3 | 18 | $level = $LEVEL_VERY_LOW; | |||
| 9211 | 3 | 6 | push @factors, "Very low confidence: little to no type information"; | |||
| 9212 | } | |||||
| 9213 | ||||||
| 9214 | return { | |||||
| 9215 | 128 | 344 | level => $level, | |||
| 9216 | score => $avg, | |||||
| 9217 | factors => \@factors, | |||||
| 9218 | per_parameter => \%param_details | |||||
| 9219 | }; | |||||
| 9220 | } | |||||
| 9221 | ||||||
| 9222 | # -------------------------------------------------- | |||||
| 9223 | # _calculate_output_confidence | |||||
| 9224 | # | |||||
| 9225 | # Purpose: Calculate a confidence score and level | |||||
| 9226 | # for the output analysis based on how | |||||
| 9227 | # much return type, value, class, | |||||
| 9228 | # context, and error convention | |||||
| 9229 | # information was determined. | |||||
| 9230 | # | |||||
| 9231 | # Entry: $output - the output hashref as built | |||||
| 9232 | # by _analyze_output. | |||||
| 9233 | # | |||||
| 9234 | # Exit: Returns a hashref with keys: | |||||
| 9235 | # level - one of: none, very_low, | |||||
| 9236 | # low, medium, high | |||||
| 9237 | # score - numeric confidence score | |||||
| 9238 | # factors - arrayref of factor strings | |||||
| 9239 | # Returns { level => 'none', ... } if | |||||
| 9240 | # output is empty. | |||||
| 9241 | # | |||||
| 9242 | # Side effects: None. | |||||
| 9243 | # -------------------------------------------------- | |||||
| 9244 | sub _calculate_output_confidence { | |||||
| 9245 | 490 | 2485 | my ($self, $output) = @_; | |||
| 9246 | ||||||
| 9247 | 490 | 308 | my @factors; | |||
| 9248 | ||||||
| 9249 | 490 | 551 | return { level => 'none', factors => ['No return information found'] } unless keys %$output; | |||
| 9250 | ||||||
| 9251 | 470 | 318 | my $score = 0; | |||
| 9252 | ||||||
| 9253 | # Type information | |||||
| 9254 | 470 | 465 | if ($output->{type}) { | |||
| 9255 | 462 | 346 | $score += 30; | |||
| 9256 | 462 | 578 | push @factors, "Return type defined: $output->{type} (+30)"; | |||
| 9257 | } else { | |||||
| 9258 | 8 | 7 | push @factors, 'No return type information (-0)'; | |||
| 9259 | } | |||||
| 9260 | ||||||
| 9261 | # Specific value known | |||||
| 9262 | 470 | 503 | if (defined $output->{value}) { | |||
| 9263 | 32 | 24 | $score += 30; | |||
| 9264 | 32 | 43 | push @factors, "Specific return value: $output->{value} (+30)"; | |||
| 9265 | } | |||||
| 9266 | ||||||
| 9267 | # Class information for objects | |||||
| 9268 | 470 | 475 | if ($output->{isa}) { | |||
| 9269 | 49 | 37 | $score += 30; | |||
| 9270 | 49 | 66 | push @factors, "Returns specific class: $output->{isa} (+30)"; | |||
| 9271 | } | |||||
| 9272 | ||||||
| 9273 | # Context-aware returns | |||||
| 9274 | 470 | 494 | if ($output->{_context_aware}) { | |||
| 9275 | 4 | 1 | $score += 20; | |||
| 9276 | 4 | 4 | push @factors, "Context-aware return (wantarray) (+20)"; | |||
| 9277 | ||||||
| 9278 | 4 | 5 | if ($output->{_list_context}) { | |||
| 9279 | 4 | 5 | push @factors, " List context: $output->{_list_context}{type}"; | |||
| 9280 | } | |||||
| 9281 | 4 | 4 | if ($output->{_scalar_context}) { | |||
| 9282 | 3 | 4 | push @factors, " Scalar context: $output->{_scalar_context}{type}"; | |||
| 9283 | } | |||||
| 9284 | } | |||||
| 9285 | ||||||
| 9286 | # Error handling information | |||||
| 9287 | 470 | 438 | if ($output->{_error_return}) { | |||
| 9288 | 21 | 16 | $score += 15; | |||
| 9289 | 21 | 26 | push @factors, "Error return convention documented: $output->{_error_return} (+15)"; | |||
| 9290 | } | |||||
| 9291 | ||||||
| 9292 | # Success/failure pattern | |||||
| 9293 | 470 | 462 | if ($output->{_success_failure_pattern}) { | |||
| 9294 | 8 | 5 | $score += 10; | |||
| 9295 | 8 | 119 | push @factors, 'Success/failure pattern detected (+10)'; | |||
| 9296 | } | |||||
| 9297 | ||||||
| 9298 | # Chainable methods | |||||
| 9299 | 470 | 479 | if ($output->{_returns_self}) { | |||
| 9300 | 10 | 58 | $score += 15; | |||
| 9301 | 10 | 11 | push @factors, "Chainable method (fluent interface) (+15)"; | |||
| 9302 | } | |||||
| 9303 | ||||||
| 9304 | # Void context | |||||
| 9305 | 470 | 426 | if ($output->{_void_context}) { | |||
| 9306 | 6 | 5 | $score += 20; | |||
| 9307 | 6 | 5 | push @factors, "Void context method (no meaningful return) (+20)"; | |||
| 9308 | } | |||||
| 9309 | ||||||
| 9310 | # Exception handling | |||||
| 9311 | 470 | 563 | if ($output->{_error_handling} && $output->{_error_handling}{exception_handling}) { | |||
| 9312 | 2 | 2 | $score += 10; | |||
| 9313 | 2 | 2 | push @factors, 'Exception handling present (+10)'; | |||
| 9314 | } | |||||
| 9315 | ||||||
| 9316 | 470 | 767 | push @factors, sprintf("Total output confidence score: %d", $score); | |||
| 9317 | ||||||
| 9318 | # Determine confidence level | |||||
| 9319 | 470 | 285 | my $level; | |||
| 9320 | 470 | 946 | if ($score >= $CONFIDENCE_HIGH_THRESHOLD) { | |||
| 9321 | 83 | 227 | $level = $LEVEL_HIGH; | |||
| 9322 | 83 | 180 | push @factors, "High confidence: detailed return type and behavior"; | |||
| 9323 | } elsif ($score >= $CONFIDENCE_MEDIUM_THRESHOLD) { | |||||
| 9324 | 24 | 92 | $level = $LEVEL_MEDIUM; | |||
| 9325 | 24 | 46 | push @factors, "Medium confidence: return type defined"; | |||
| 9326 | } elsif ($score >= $CONFIDENCE_LOW_THRESHOLD) { | |||||
| 9327 | 360 | 1998 | $level = $LEVEL_LOW; | |||
| 9328 | 360 | 697 | push @factors, "Low confidence: minimal return information"; | |||
| 9329 | } else { | |||||
| 9330 | 3 | 15 | $level = $LEVEL_VERY_LOW; | |||
| 9331 | 3 | 6 | push @factors, 'Very low confidence: little return information'; | |||
| 9332 | } | |||||
| 9333 | ||||||
| 9334 | return { | |||||
| 9335 | 470 | 1111 | level => $level, | |||
| 9336 | score => $score, | |||||
| 9337 | factors => \@factors | |||||
| 9338 | }; | |||||
| 9339 | } | |||||
| 9340 | ||||||
| 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 | 3 | 11 | my ($self, $schema) = @_; | |||
| 9361 | ||||||
| 9362 | 3 | 4 | return unless $schema->{_analysis}; | |||
| 9363 | ||||||
| 9364 | 2 | 3 | my $analysis = $schema->{_analysis}; | |||
| 9365 | 2 | 1 | my @report; | |||
| 9366 | ||||||
| 9367 | 2 | 4 | push @report, "Confidence Analysis for " . ($schema->{method_name} || 'method'); | |||
| 9368 | 2 | 2 | push @report, '=' x 60; | |||
| 9369 | 2 | 2 | push @report, ''; | |||
| 9370 | ||||||
| 9371 | 2 | 2 | push @report, "Overall Confidence: " . uc($analysis->{overall_confidence}); | |||
| 9372 | 2 | 2 | push @report, ''; | |||
| 9373 | ||||||
| 9374 | 2 | 3 | if ($analysis->{confidence_factors}{input}) { | |||
| 9375 | push @report, ( | |||||
| 9376 | "Input Parameters:", | |||||
| 9377 | " Confidence Level: " . uc($analysis->{input_confidence}) | |||||
| 9378 | 2 | 3 | ); | |||
| 9379 | 2 2 | 1 3 | foreach my $factor (@{$analysis->{confidence_factors}{input}}) { | |||
| 9380 | 2 | 3 | push @report, " - $factor"; | |||
| 9381 | } | |||||
| 9382 | 2 | 1 | push @report, ''; | |||
| 9383 | } | |||||
| 9384 | ||||||
| 9385 | 2 | 2 | if ($analysis->{confidence_factors}{output}) { | |||
| 9386 | push @report, 'Return Value:', | |||||
| 9387 | 2 | 2 | " Confidence Level: " . uc($analysis->{output_confidence}); | |||
| 9388 | 2 2 | 2 2 | foreach my $factor (@{$analysis->{confidence_factors}{output}}) { | |||
| 9389 | 2 | 3 | push @report, " - $factor"; | |||
| 9390 | } | |||||
| 9391 | 2 | 0 | push @report, ''; | |||
| 9392 | } | |||||
| 9393 | ||||||
| 9394 | 2 | 3 | if ($analysis->{per_parameter_scores}) { | |||
| 9395 | 0 | 0 | push @report, 'Per-Parameter Analysis:'; | |||
| 9396 | 0 0 | 0 0 | foreach my $param (sort keys %{$analysis->{per_parameter_scores}}) { | |||
| 9397 | 0 | 0 | my $details = $analysis->{per_parameter_scores}{$param}; | |||
| 9398 | 0 | 0 | push @report, " \$$param (score: $details->{score}):"; | |||
| 9399 | 0 0 | 0 0 | foreach my $factor (@{$details->{factors}}) { | |||
| 9400 | 0 | 0 | push @report, " - $factor"; | |||
| 9401 | } | |||||
| 9402 | } | |||||
| 9403 | 0 | 0 | push @report, ''; | |||
| 9404 | } | |||||
| 9405 | ||||||
| 9406 | 2 | 5 | 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, | |||||
| 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. | |||||
| 9426 | # -------------------------------------------------- | |||||
| 9427 | sub _generate_notes { | |||||
| 9428 | 478 | 1164 | my ($self, $params) = @_; | |||
| 9429 | ||||||
| 9430 | 478 | 318 | my @notes; | |||
| 9431 | ||||||
| 9432 | 478 | 770 | foreach my $param (sort keys %$params) { | |||
| 9433 | 407 | 278 | my $p = $params->{$param}; | |||
| 9434 | ||||||
| 9435 | 407 | 405 | unless ($p->{type}) { | |||
| 9436 | 109 | 154 | push @notes, "$param: type unknown - please review - will set to 'string' as a default"; | |||
| 9437 | } | |||||
| 9438 | ||||||
| 9439 | 407 | 421 | unless (defined $p->{optional}) { | |||
| 9440 | 12 | 18 | push @notes, "$param: optional status unknown"; | |||
| 9441 | # Don't automatically set - let it be undef if we don't know | |||||
| 9442 | } | |||||
| 9443 | } | |||||
| 9444 | ||||||
| 9445 | 478 | 580 | return \@notes; | |||
| 9446 | } | |||||
| 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 | |||||
| 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 | 948 | 729 | my ($self, $schema, $mode) = @_; | |||
| 9475 | ||||||
| 9476 | 948 | 602 | my $params = $schema->{$mode}; | |||
| 9477 | ||||||
| 9478 | 948 | 757 | foreach my $param (keys %$params) { | |||
| 9479 | 1202 | 739 | my $p = $params->{$param}; | |||
| 9480 | ||||||
| 9481 | 1202 | 1123 | next unless(ref($p) eq 'HASH'); | |||
| 9482 | 433 | 485 | unless ($p->{type}) { | |||
| 9483 | 130 | 148 | $self->_log(" DEBUG {$mode}{$param}: Setting to 'string' as a default"); | |||
| 9484 | 130 | 101 | $p->{'type'} = 'string'; | |||
| 9485 | 130 | 139 | $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 | 479 | 388 | my ($self, $method) = @_; | |||
| 9522 | ||||||
| 9523 | 479 | 331 | my $code = $method->{body}; | |||
| 9524 | 479 | 346 | 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 | 479 | 660 | $self->_extract_parameters_from_signature(\%params, $code); | |||
| 9531 | 479 138 | 529 152 | my @param_names = sort { $params{$a}{position} <=> $params{$b}{position} } keys %params; | |||
| 9532 | ||||||
| 9533 | 479 | 539 | return [] unless @param_names; | |||
| 9534 | ||||||
| 9535 | # Detect mutually exclusive parameters | |||||
| 9536 | 206 206 | 161 325 | push @relationships, @{$self->_detect_mutually_exclusive($code, \@param_names)}; | |||
| 9537 | ||||||
| 9538 | # Detect required groups (OR logic) | |||||
| 9539 | 206 206 | 162 305 | push @relationships, @{$self->_detect_required_groups($code, \@param_names)}; | |||
| 9540 | ||||||
| 9541 | # Detect conditional requirements (IF-THEN) | |||||
| 9542 | 206 206 | 153 296 | push @relationships, @{$self->_detect_conditional_requirements($code, \@param_names)}; | |||
| 9543 | ||||||
| 9544 | # Detect dependencies | |||||
| 9545 | 206 206 | 139 276 | push @relationships, @{$self->_detect_dependencies($code, \@param_names)}; | |||
| 9546 | ||||||
| 9547 | # Detect value-based constraints | |||||
| 9548 | 206 206 | 154 273 | push @relationships, @{$self->_detect_value_constraints($code, \@param_names)}; | |||
| 9549 | ||||||
| 9550 | # Deduplicate relationships | |||||
| 9551 | 206 | 276 | my @unique = $self->_deduplicate_relationships(\@relationships); | |||
| 9552 | ||||||
| 9553 | 206 | 339 | return \@unique; | |||
| 9554 | } | |||||
| 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. | |||||
| 9569 | # | |||||
| 9570 | # Side effects: None. | |||||
| 9571 | # -------------------------------------------------- | |||||
| 9572 | sub _deduplicate_relationships { | |||||
| 9573 | 210 | 819 | my ($self, $relationships) = @_; | |||
| 9574 | ||||||
| 9575 | 210 | 161 | my @unique; | |||
| 9576 | my %seen; | |||||
| 9577 | ||||||
| 9578 | 210 | 183 | foreach my $rel (@$relationships) { | |||
| 9579 | # Create a signature for this relationship | |||||
| 9580 | 31 | 16 | my $sig; | |||
| 9581 | 31 | 39 | if ($rel->{type} eq 'mutually_exclusive') { | |||
| 9582 | 13 13 | 12 19 | $sig = join(':', 'mutex', sort @{$rel->{params}}); | |||
| 9583 | } elsif ($rel->{type} eq 'required_group') { | |||||
| 9584 | 5 5 | 4 7 | $sig = join(':', 'reqgroup', sort @{$rel->{params}}); | |||
| 9585 | } elsif ($rel->{type} eq 'conditional_requirement') { | |||||
| 9586 | 7 | 7 | $sig = join(':', 'condreq', $rel->{if}, $rel->{then_required}); | |||
| 9587 | } elsif ($rel->{type} eq 'dependency') { | |||||
| 9588 | 3 | 3 | $sig = join(':', 'dep', $rel->{param}, $rel->{requires}); | |||
| 9589 | } elsif ($rel->{type} eq 'value_constraint') { | |||||
| 9590 | 2 | 18 | $sig = join(':', 'valcon', $rel->{if}, $rel->{then}, $rel->{operator}, $rel->{value}); | |||
| 9591 | } elsif ($rel->{type} eq 'value_conditional') { | |||||
| 9592 | 1 | 3 | $sig = join(':', 'valcond', $rel->{if}, $rel->{equals}, $rel->{then_required}); | |||
| 9593 | } else { | |||||
| 9594 | 0 | 0 | $sig = join(':', $rel->{type}, %$rel); | |||
| 9595 | } | |||||
| 9596 | ||||||
| 9597 | 31 | 35 | unless ($seen{$sig}++) { | |||
| 9598 | 25 | 46 | push @unique, $rel; | |||
| 9599 | } | |||||
| 9600 | } | |||||
| 9601 | ||||||
| 9602 | 210 | 237 | return @unique; | |||
| 9603 | } | |||||
| 9604 | ||||||
| 9605 | # -------------------------------------------------- | |||||
| 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 relationship | |||||
| 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 | 211 | 1104 | my ($self, $code, $param_names) = @_; | |||
| 9626 | ||||||
| 9627 | 211 | 144 | my @relationships; | |||
| 9628 | ||||||
| 9629 | # Pattern 1: die/croak if $x && $y | |||||
| 9630 | # Look for: die/croak ... if $param1 && $param2 | |||||
| 9631 | 211 | 192 | foreach my $param1 (@$param_names) { | |||
| 9632 | 316 | 240 | foreach my $param2 (@$param_names) { | |||
| 9633 | 696 | 554 | next if $param1 eq $param2; | |||
| 9634 | ||||||
| 9635 | # Check various patterns | |||||
| 9636 | 380 | 12071 | 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 | 22 | 16 | my $found_reverse = 0; | |||
| 9641 | 22 | 15 | foreach my $rel (@relationships) { | |||
| 9642 | 13 | 33 | if ($rel->{type} eq 'mutually_exclusive' && | |||
| 9643 | (($rel->{params}[0] eq $param2 && $rel->{params}[1] eq $param1))) { | |||||
| 9644 | 11 | 9 | $found_reverse = 1; | |||
| 9645 | 11 | 7 | last; | |||
| 9646 | } | |||||
| 9647 | } | |||||
| 9648 | ||||||
| 9649 | 22 | 28 | next if $found_reverse; | |||
| 9650 | ||||||
| 9651 | 11 | 26 | push @relationships, { | |||
| 9652 | type => 'mutually_exclusive', | |||||
| 9653 | params => [$param1, $param2], | |||||
| 9654 | description => "Cannot specify both $param1 and $param2" | |||||
| 9655 | }; | |||||
| 9656 | ||||||
| 9657 | 11 | 17 | $self->_log(" RELATIONSHIP: $param1 and $param2 are mutually exclusive"); | |||
| 9658 | } | |||||
| 9659 | ||||||
| 9660 | # Pattern 2: die "Cannot specify both X and Y" | |||||
| 9661 | 369 | 25519 | 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 | 1 | 2 | my $found_reverse = 0; | |||
| 9665 | 1 | 1 | foreach my $rel (@relationships) { | |||
| 9666 | 1 | 4 | if ($rel->{type} eq 'mutually_exclusive' && | |||
| 9667 | (($rel->{params}[0] eq $param2 && $rel->{params}[1] eq $param1))) { | |||||
| 9668 | 0 | 0 | $found_reverse = 1; | |||
| 9669 | 0 | 0 | last; | |||
| 9670 | } | |||||
| 9671 | } | |||||
| 9672 | ||||||
| 9673 | 1 | 1 | next if $found_reverse; | |||
| 9674 | ||||||
| 9675 | 1 | 3 | push @relationships, { | |||
| 9676 | type => 'mutually_exclusive', | |||||
| 9677 | params => [$param1, $param2], | |||||
| 9678 | description => "Cannot specify both $param1 and $param2" | |||||
| 9679 | }; | |||||
| 9680 | ||||||
| 9681 | 1 | 2 | $self->_log(" RELATIONSHIP: $param1 and $param2 are mutually exclusive (from error message)"); | |||
| 9682 | } | |||||
| 9683 | } | |||||
| 9684 | } | |||||
| 9685 | ||||||
| 9686 | 211 | 252 | return \@relationships; | |||
| 9687 | } | |||||
| 9688 | ||||||
| 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. | |||||
| 9697 | # | |||||
| 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 | # -------------------------------------------------- | |||||
| 9709 | sub _detect_required_groups { | |||||
| 9710 | 209 | 892 | my ($self, $code, $param_names) = @_; | |||
| 9711 | ||||||
| 9712 | 209 | 126 | my @relationships; | |||
| 9713 | ||||||
| 9714 | # Pattern 1: die/croak unless $x || $y | |||||
| 9715 | 209 | 177 | foreach my $param1 (@$param_names) { | |||
| 9716 | 312 | 204 | foreach my $param2 (@$param_names) { | |||
| 9717 | 688 | 513 | next if $param1 eq $param2; | |||
| 9718 | ||||||
| 9719 | 376 | 10378 | if ($code =~ /(?:die|croak|confess)[^;]*unless\s+\$$param1\s+\|\|\s+\$$param2/ || | |||
| 9720 | $code =~ /(?:die|croak|confess)[^;]*unless\s+\$$param2\s+\|\|\s+\$$param1/) { | |||||
| 9721 | ||||||
| 9722 | # Avoid duplicates | |||||
| 9723 | 10 | 6 | my $found_reverse = 0; | |||
| 9724 | 10 | 11 | foreach my $rel (@relationships) { | |||
| 9725 | 5 | 17 | if ($rel->{type} eq 'required_group' && | |||
| 9726 | (($rel->{params}[0] eq $param2 && $rel->{params}[1] eq $param1))) { | |||||
| 9727 | 5 | 3 | $found_reverse = 1; | |||
| 9728 | 5 | 5 | last; | |||
| 9729 | } | |||||
| 9730 | } | |||||
| 9731 | ||||||
| 9732 | 10 | 11 | next if $found_reverse; | |||
| 9733 | ||||||
| 9734 | 5 | 16 | push @relationships, { | |||
| 9735 | type => 'required_group', | |||||
| 9736 | params => [$param1, $param2], | |||||
| 9737 | logic => 'or', | |||||
| 9738 | description => "Must specify either $param1 or $param2" | |||||
| 9739 | }; | |||||
| 9740 | ||||||
| 9741 | 5 | 9 | $self->_log(" RELATIONSHIP: Must specify either $param1 or $param2"); | |||
| 9742 | } | |||||
| 9743 | ||||||
| 9744 | # Pattern 2: die "Must specify either X or Y" | |||||
| 9745 | 371 | 25356 | if ($code =~ /(?:die|croak|confess)\s+['"]Must\s+specify\s+either[^'"]*$param1[^'"]*or[^'"]*$param2/i || | |||
| 9746 | $code =~ /(?:die|croak|confess)\s+['"]Must\s+specify\s+either[^'"]*$param2[^'"]*or[^'"]*$param1/i) { | |||||
| 9747 | ||||||
| 9748 | 1 | 1 | my $found_reverse = 0; | |||
| 9749 | 1 | 1 | foreach my $rel (@relationships) { | |||
| 9750 | 1 | 4 | if ($rel->{type} eq 'required_group' && | |||
| 9751 | (($rel->{params}[0] eq $param2 && $rel->{params}[1] eq $param1))) { | |||||
| 9752 | 0 | 0 | $found_reverse = 1; | |||
| 9753 | 0 | 0 | last; | |||
| 9754 | } | |||||
| 9755 | } | |||||
| 9756 | ||||||
| 9757 | 1 | 2 | next if $found_reverse; | |||
| 9758 | ||||||
| 9759 | 1 | 1 | push @relationships, { | |||
| 9760 | type => 'required_group', | |||||
| 9761 | params => [$param1, $param2], | |||||
| 9762 | logic => 'or', | |||||
| 9763 | description => "Must specify either $param1 or $param2" | |||||
| 9764 | }; | |||||
| 9765 | ||||||
| 9766 | 1 | 1 | $self->_log(" RELATIONSHIP: Must specify either $param1 or $param2 (from error message)"); | |||
| 9767 | } | |||||
| 9768 | } | |||||
| 9769 | } | |||||
| 9770 | ||||||
| 9771 | 209 | 191 | return \@relationships; | |||
| 9772 | } | |||||
| 9773 | ||||||
| 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 | # | |||||
| 9787 | # Exit: Returns an arrayref of relationship | |||||
| 9788 | # hashrefs of type | |||||
| 9789 | # 'conditional_requirement'. | |||||
| 9790 | # Returns an empty arrayref if none found. | |||||
| 9791 | # | |||||
| 9792 | # Side effects: Logs detections to stdout when | |||||
| 9793 | # verbose is set. | |||||
| 9794 | # -------------------------------------------------- | |||||
| 9795 | sub _detect_conditional_requirements { | |||||
| 9796 | 209 | 1051 | my ($self, $code, $param_names) = @_; | |||
| 9797 | ||||||
| 9798 | 209 | 125 | my @relationships; | |||
| 9799 | ||||||
| 9800 | 209 | 167 | foreach my $param1 (@$param_names) { | |||
| 9801 | 312 | 227 | foreach my $param2 (@$param_names) { | |||
| 9802 | 688 | 473 | next if $param1 eq $param2; | |||
| 9803 | ||||||
| 9804 | # Pattern 1: die if $x && !$y (if x then y required) | |||||
| 9805 | 376 | 5292 | if ($code =~ /(?:die|croak|confess)[^;]*if\s+\$$param1\s+&&\s+!\$$param2/) { | |||
| 9806 | 5 | 16 | 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 | 5 | 10 | $self->_log(" RELATIONSHIP: $param1 requires $param2"); | |||
| 9814 | } | |||||
| 9815 | ||||||
| 9816 | # Pattern 2: die if $x && !defined($y) | |||||
| 9817 | 376 | 7725 | if ($code =~ /(?:die|croak|confess)[^;]*if\s+\$$param1\s+&&\s+!defined\s*\(\s*\$$param2\s*\)/) { | |||
| 9818 | 0 | 0 | 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 | 0 | 0 | $self->_log(" RELATIONSHIP: $param1 requires $param2 (defined check)"); | |||
| 9826 | } | |||||
| 9827 | ||||||
| 9828 | # Pattern 3: Error message "X requires Y" | |||||
| 9829 | 376 | 12414 | if ($code =~ /(?:die|croak|confess)\s+['"]\w*$param1[^'"]*requires[^'"]*$param2/i) { | |||
| 9830 | 4 | 9 | 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 | 4 | 4 | $self->_log(" RELATIONSHIP: $param1 requires $param2 (from error message)"); | |||
| 9838 | } | |||||
| 9839 | } | |||||
| 9840 | } | |||||
| 9841 | ||||||
| 9842 | 209 | 199 | 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. | |||||
| 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 { | |||||
| 9866 | 210 | 19632 | my ($self, $code, $param_names) = @_; | |||
| 9867 | ||||||
| 9868 | 210 | 157 | my @relationships; | |||
| 9869 | ||||||
| 9870 | 210 | 163 | foreach my $param1 (@$param_names) { | |||
| 9871 | 314 | 229 | foreach my $param2 (@$param_names) { | |||
| 9872 | 692 | 483 | 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 | 378 | 11615 | if (($code =~ /(?:die|croak|confess)\s+['"]\w*$param1[^'"]*requires[^'"]*$param2/i) && | |||
| 9877 | ($code =~ /if\s+\$$param1\s+&&\s+!\$$param2/)) { | |||||
| 9878 | ||||||
| 9879 | 6 | 18 | push @relationships, { | |||
| 9880 | type => 'dependency', | |||||
| 9881 | param => $param1, | |||||
| 9882 | requires => $param2, | |||||
| 9883 | description => "$param1 requires $param2 to be specified" | |||||
| 9884 | }; | |||||
| 9885 | ||||||
| 9886 | 6 | 12 | $self->_log(" RELATIONSHIP: $param1 depends on $param2"); | |||
| 9887 | } | |||||
| 9888 | } | |||||
| 9889 | } | |||||
| 9890 | ||||||
| 9891 | 210 | 185 | 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 | 207 | 183 | my ($self, $code, $param_names) = @_; | |||
| 9916 | ||||||
| 9917 | 207 | 174 | my @relationships; | |||
| 9918 | ||||||
| 9919 | 207 | 166 | foreach my $param1 (@$param_names) { | |||
| 9920 | 308 | 209 | foreach my $param2 (@$param_names) { | |||
| 9921 | 680 | 451 | next if $param1 eq $param2; | |||
| 9922 | ||||||
| 9923 | # Pattern 1: die if $x && $y != value | |||||
| 9924 | 372 | 7117 | if ($code =~ /(?:die|croak|confess)[^;]*if\s+\$$param1\s+&&\s+\$$param2\s*!=\s*(\d+)/) { | |||
| 9925 | 3 | 4 | my $value = $1; | |||
| 9926 | 3 | 10 | 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 | 3 | 6 | $self->_log(" RELATIONSHIP: $param1 requires $param2 == $value"); | |||
| 9936 | } | |||||
| 9937 | ||||||
| 9938 | # Pattern 2: die if $x && $y < value | |||||
| 9939 | 372 | 7075 | if ($code =~ /(?:die|croak|confess)[^;]*if\s+\$$param1\s+&&\s+\$$param2\s*<\s*(\d+)/) { | |||
| 9940 | 0 | 0 | my $value = $1; | |||
| 9941 | 0 | 0 | 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 | 0 | 0 | $self->_log(" RELATIONSHIP: $param1 requires $param2 >= $value"); | |||
| 9951 | } | |||||
| 9952 | ||||||
| 9953 | # Pattern 3: die if $x eq 'value' && !$y | |||||
| 9954 | 372 | 9351 | if ($code =~ /(?:die|croak|confess)[^;]*if\s+\$$param1\s+eq\s+['"]([^'"]+)['"]\s+&&\s+!\$$param2/) { | |||
| 9955 | 1 | 2 | my $value = $1; | |||
| 9956 | 1 | 4 | 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 | 1 | 3 | $self->_log(" RELATIONSHIP: $param1='$value' requires $param2"); | |||
| 9965 | } | |||||
| 9966 | } | |||||
| 9967 | } | |||||
| 9968 | ||||||
| 9969 | 207 | 180 | 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 | 196 | 4049 | 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 | 196 | 240 | croak(__PACKAGE__, ': output_dir must be provided to new() when writing schema files') unless defined $self->{output_dir}; | |||
| 9985 | ||||||
| 9986 | 195 | 2235 | make_path($self->{output_dir}) unless -d $self->{output_dir}; | |||
| 9987 | ||||||
| 9988 | 195 | 272 | my $filename = "$self->{output_dir}/${method_name}.yml"; | |||
| 9989 | ||||||
| 9990 | 195 | 222 | local $YAML::XS::QuoteNumericStrings = 0; | |||
| 9991 | ||||||
| 9992 | # Extract package name for module field | |||||
| 9993 | 195 | 178 | my $package_name = ''; | |||
| 9994 | 195 | 341 | if ($self->{_document}) { | |||
| 9995 | 193 | 267 | my $package_stmt = $self->{_document}->find_first('PPI::Statement::Package'); | |||
| 9996 | 193 | 20070 | $package_name = $package_stmt ? $package_stmt->namespace : ''; | |||
| 9997 | 193 | 1976 | $self->{_package_name} //= $package_name; | |||
| 9998 | } | |||||
| 9999 | ||||||
| 10000 | # Clean up schema for output - use the format expected by App::Test::Generator::Template | |||||
| 10001 | 195 | 635 | 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 | 195 | 280 | if($schema->{_analysis}{side_effects}{writes_file}) { | |||
| 10018 | 1 | 2 | $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 | 195 | 238 | if($schema->{_analysis}{side_effects}{keeps_fd}) { | |||
| 10023 | 2 | 3 | $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 | 195 | 218 | $output->{skip} = $schema->{skip} if($schema->{skip}); | |||
| 10029 | ||||||
| 10030 | # A class method is called as Module->routine(...), not Module::routine(...). | |||||
| 10031 | 195 | 199 | $output->{invocant} = $schema->{invocant} if($schema->{invocant}); | |||
| 10032 | ||||||
| 10033 | # Process input parameters with advanced type handling | |||||
| 10034 | 195 | 200 | if($schema->{'input'}) { | |||
| 10035 | 192 192 | 137 220 | if(scalar(keys %{$schema->{'input'}})) { | |||
| 10036 | 159 | 174 | $output->{'input'} = {}; | |||
| 10037 | ||||||
| 10038 | 159 159 | 115 228 | foreach my $param_name (sort keys %{$schema->{'input'}}) { | |||
| 10039 | 241 | 195 | my $param = $schema->{'input'}{$param_name}; | |||
| 10040 | 241 | 222 | if($param->{name}) { | |||
| 10041 | 24 | 13 | my $name = delete $param->{name}; | |||
| 10042 | 24 | 20 | if($name ne $param_name) { | |||
| 10043 | # Sanity check | |||||
| 10044 | 0 | 0 | croak("BUG: Parameter name - expected $param_name, got $name"); | |||
| 10045 | } | |||||
| 10046 | } | |||||
| 10047 | 241 | 316 | my $cleaned_param = $self->_serialize_parameter_for_yaml($param); | |||
| 10048 | 241 | 227 | $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 | 159 241 159 | 164 263 193 | my @with_pos = grep { defined $output->{input}{$_}{position} } sort keys %{$output->{input}}; | |||
| 10059 | 159 241 159 | 131 256 163 | my @without_pos = grep { !defined $output->{input}{$_}{position} } sort keys %{$output->{input}}; | |||
| 10060 | 159 1 | 348 1 | if (@with_pos && grep { !$output->{input}{$_}{named} } @without_pos) { | |||
| 10061 | 1 | 2 | delete $output->{input}{$_}{position} for @with_pos; | |||
| 10062 | } | |||||
| 10063 | } else { | |||||
| 10064 | 33 | 28 | delete $output->{input}; | |||
| 10065 | } | |||||
| 10066 | } | |||||
| 10067 | ||||||
| 10068 | # Process output | |||||
| 10069 | 195 195 | 257 277 | if($schema->{'output'} && (scalar(keys %{$schema->{'output'}}))) { | |||
| 10070 | 195 190 | 299 338 | if((ref($schema->{output}{_error_handling}) eq 'HASH') && (scalar(keys %{$schema->{output}{_error_handling}}) == 0)) { | |||
| 10071 | 177 | 160 | delete $schema->{output}{_error_handling}; | |||
| 10072 | } | |||||
| 10073 | # value/alt_value are inference metadata; Return::Set does not recognise them as validation rules | |||||
| 10074 | 195 195 | 172 278 | my %out_spec = %{$schema->{'output'}}; | |||
| 10075 | 195 | 213 | delete @out_spec{qw(value alt_value)}; | |||
| 10076 | 195 | 165 | $output->{'output'} = \%out_spec; | |||
| 10077 | } | |||||
| 10078 | ||||||
| 10079 | 195 | 391 | if($schema->{'output'}{'type'} && ($schema->{'output'}{'type'} eq 'scalar')) { | |||
| 10080 | 0 | 0 | $schema->{'output'}{'type'} = 'string'; | |||
| 10081 | 0 | 0 | $schema->{_confidence}{output}->{level} = 'low'; # A guess | |||
| 10082 | } | |||||
| 10083 | ||||||
| 10084 | # Add 'new' field if object instantiation is needed | |||||
| 10085 | 195 | 212 | if ($schema->{new}) { | |||
| 10086 | # TODO: consider allowing parent class packages up the ISA chain | |||||
| 10087 | 100 | 151 | if(ref($schema->{new}) || ($schema->{new} eq $package_name)) { | |||
| 10088 | 98 | 127 | $output->{new} = $schema->{new} eq $package_name ? undef : $schema->{'new'}; | |||
| 10089 | } else { | |||||
| 10090 | 2 | 4 | $self->_log(" NEW: Don't use $schema->{new} for object insantiation"); | |||
| 10091 | 2 | 2 | delete $schema->{new}; | |||
| 10092 | 2 | 2 | delete $output->{new}; | |||
| 10093 | } | |||||
| 10094 | } | |||||
| 10095 | ||||||
| 10096 | 195 | 291 | if(!defined($schema->{_confidence}{input}->{level})) { | |||
| 10097 | 153 | 234 | $schema->{_confidence}{input} = $self->_calculate_input_confidence($schema->{input}); | |||
| 10098 | } | |||||
| 10099 | 195 | 291 | if(!defined($schema->{_confidence}{output}->{level})) { | |||
| 10100 | 1 | 4 | $schema->{_confidence}{output} = $self->_calculate_output_confidence($schema->{output}); | |||
| 10101 | } | |||||
| 10102 | ||||||
| 10103 | # Add relationships if detected | |||||
| 10104 | 195 7 | 464 8 | if ($schema->{relationships} && @{$schema->{relationships}}) { | |||
| 10105 | 7 | 2 | $output->{relationships} = $schema->{relationships}; | |||
| 10106 | } | |||||
| 10107 | ||||||
| 10108 | 195 7 | 274 11 | if($schema->{accessor} && scalar(keys %{$schema->{accessor}})) { | |||
| 10109 | 7 | 7 | $output->{accessor} = $schema->{accessor}; | |||
| 10110 | } | |||||
| 10111 | ||||||
| 10112 | 195 | 391 | open my $fh, '>', $filename; | |||
| 10113 | 195 | 67310 | print $fh YAML::XS::Dump($output); | |||
| 10114 | 195 | 773 | print $fh $self->_generate_schema_comments($schema, $method_name); | |||
| 10115 | 195 | 301 | close $fh; | |||
| 10116 | ||||||
| 10117 | my $rel_info = $schema->{relationships} ? | |||||
| 10118 | 195 7 | 27477 5 | ' [' . scalar(@{$schema->{relationships}}) . ' relationships]' : ''; | |||
| 10119 | $self->_log(" Wrote: $filename (input confidence: $schema->{_confidence}{input}->{level})" . | |||||
| 10120 | 195 | 496 | ($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 | 200 | 244 | my ($self, $schema, $method_name) = @_; | |||
| 10148 | ||||||
| 10149 | 200 | 134 | my @comments; | |||
| 10150 | ||||||
| 10151 | 200 | 211 | push @comments, ''; | |||
| 10152 | 200 | 217 | push @comments, '# Generated by ' . ref($self); | |||
| 10153 | 200 | 372 | push @comments, "# Run: fuzz-harness-generator -r $self->{output_dir}/${method_name}.yml"; | |||
| 10154 | 200 | 153 | push @comments, '#'; | |||
| 10155 | 200 | 242 | push @comments, "# Input confidence: $schema->{_confidence}{input}->{level}"; | |||
| 10156 | 200 | 218 | push @comments, "# Output confidence: $schema->{_confidence}{output}->{level}"; | |||
| 10157 | ||||||
| 10158 | # Add notes about parameters | |||||
| 10159 | 200 | 235 | if ($schema->{input}) { | |||
| 10160 | 192 | 119 | my @param_notes; | |||
| 10161 | 192 192 | 141 275 | foreach my $param_name (sort keys %{$schema->{input}}) { | |||
| 10162 | 241 | 186 | my $p = $schema->{input}{$param_name}; | |||
| 10163 | ||||||
| 10164 | 241 | 286 | if ($p->{semantic}) { | |||
| 10165 | 18 | 16 | push @param_notes, "$param_name: $p->{semantic}"; | |||
| 10166 | } | |||||
| 10167 | ||||||
| 10168 | 241 | 275 | if ($p->{enum}) { | |||
| 10169 | 5 5 | 4 5 | push @param_notes, "$param_name: enum with " . scalar(@{$p->{enum}}) . " values"; | |||
| 10170 | } | |||||
| 10171 | ||||||
| 10172 | 241 | 388 | if ($p->{isa}) { | |||
| 10173 | 6 | 7 | push @param_notes, "$param_name: requires $p->{isa} object"; | |||
| 10174 | } | |||||
| 10175 | } | |||||
| 10176 | ||||||
| 10177 | 192 | 277 | if (@param_notes) { | |||
| 10178 | 20 | 14 | push @comments, '#'; | |||
| 10179 | 20 | 12 | push @comments, '# Parameter types detected:'; | |||
| 10180 | 20 | 16 | foreach my $note (sort @param_notes) { | |||
| 10181 | 29 | 26 | push @comments, "# - $note"; | |||
| 10182 | } | |||||
| 10183 | } | |||||
| 10184 | } | |||||
| 10185 | ||||||
| 10186 | # Add relationship notes, sorted so their order does not depend on | |||||
| 10187 | # detection order. | |||||
| 10188 | 200 8 | 312 9 | if ($schema->{relationships} && @{$schema->{relationships}}) { | |||
| 10189 | 8 | 8 | push @comments, ( | |||
| 10190 | '#', | |||||
| 10191 | '# Parameter relationships detected:' | |||||
| 10192 | ); | |||||
| 10193 | my @relationship_notes = map { | |||||
| 10194 | 17 | 16 | $_->{description} || _format_relationship($_) | |||
| 10195 | 8 8 | 4 8 | } @{$schema->{relationships}}; | |||
| 10196 | 8 | 8 | foreach my $desc (sort @relationship_notes) { | |||
| 10197 | 17 | 11 | push @comments, "# - $desc"; | |||
| 10198 | } | |||||
| 10199 | } | |||||
| 10200 | ||||||
| 10201 | # Add general notes | |||||
| 10202 | 200 198 | 317 296 | if ($schema->{_notes} && scalar(@{$schema->{_notes}})) { | |||
| 10203 | 40 | 31 | push @comments, '#'; | |||
| 10204 | 40 | 31 | push @comments, '# Notes:'; | |||
| 10205 | 40 40 | 27 43 | foreach my $note (sort @{$schema->{_notes}}) { | |||
| 10206 | 74 | 62 | push @comments, "# - $note"; | |||
| 10207 | } | |||||
| 10208 | } | |||||
| 10209 | ||||||
| 10210 | 200 | 237 | if($schema->{_analysis}) { | |||
| 10211 | 195 | 205 | 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 | 200 | 116 | my @warnings; | |||
| 10230 | 200 | 192 | if ($schema->{input}) { | |||
| 10231 | 192 192 | 140 200 | foreach my $param_name (sort keys %{$schema->{input}}) { | |||
| 10232 | 241 | 152 | my $p = $schema->{input}{$param_name}; | |||
| 10233 | ||||||
| 10234 | 241 | 470 | if ($p->{type} && $p->{type} eq 'coderef') { | |||
| 10235 | 3 | 4 | push @warnings, "Parameter '$param_name' is a coderef - you'll need to provide a sub {} in tests"; | |||
| 10236 | } | |||||
| 10237 | ||||||
| 10238 | 241 | 240 | if ($p->{semantic} && $p->{semantic} eq 'filehandle') { | |||
| 10239 | 2 | 3 | push @warnings, "Parameter '$param_name' is a filehandle - consider using IO::String or mock"; | |||
| 10240 | } | |||||
| 10241 | ||||||
| 10242 | 241 | 289 | if ($p->{isa} && $p->{isa} =~ /DateTime/) { | |||
| 10243 | 2 | 2 | push @warnings, "Parameter '$param_name' requires DateTime - ensure DateTime is loaded"; | |||
| 10244 | } | |||||
| 10245 | } | |||||
| 10246 | } | |||||
| 10247 | ||||||
| 10248 | 200 | 222 | if (@warnings) { | |||
| 10249 | 7 | 4 | push @comments, '#'; | |||
| 10250 | 7 | 5 | push @comments, '# WARNINGS - Manual test setup may be required:'; | |||
| 10251 | 7 | 5 | foreach my $warning (sort @warnings) { | |||
| 10252 | 7 | 6 | push @comments, "# ! $warning"; | |||
| 10253 | } | |||||
| 10254 | } | |||||
| 10255 | ||||||
| 10256 | 200 | 156 | push @comments, ''; | |||
| 10257 | ||||||
| 10258 | 200 | 495 | 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 | 258 | 4580 | my ($self, $param) = @_; | |||
| 10290 | ||||||
| 10291 | 258 | 158 | my %cleaned; | |||
| 10292 | ||||||
| 10293 | # Copy basic fields that App::Test::Generator expects | |||||
| 10294 | 258 | 264 | foreach my $field (qw(type position named optional min max sample_max matches default _not_empty)) { | |||
| 10295 | 2580 | 1976 | $cleaned{$field} = $param->{$field} if defined $param->{$field}; | |||
| 10296 | } | |||||
| 10297 | ||||||
| 10298 | # Provenance drives the harness's tolerance and type-check decisions. | |||||
| 10299 | 258 | 535 | $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 | 258 | 296 | if(ref($param->{_constraint_source}) eq 'HASH') { | |||
| 10304 | 65 | 45 | my %provenance; | |||
| 10305 | 65 | 60 | foreach my $key (qw(min max memberof matches nomatch notmemberof)) { | |||
| 10306 | 390 | 231 | my $source = $param->{_constraint_source}{$key}; | |||
| 10307 | 390 | 356 | $provenance{$key} = $source if defined($source) && length($source); | |||
| 10308 | } | |||||
| 10309 | 65 | 172 | $cleaned{_constraint_source} = \%provenance if keys %provenance; | |||
| 10310 | } | |||||
| 10311 | ||||||
| 10312 | # Handle advanced type mappings | |||||
| 10313 | 258 | 288 | if(my $semantic = $param->{semantic}) { | |||
| 10314 | 26 | 103 | if ($semantic eq 'datetime_object') { | |||
| 10315 | # DateTime objects: test generator needs to know how to create them | |||||
| 10316 | 2 | 1 | $cleaned{type} = 'object'; | |||
| 10317 | 2 | 2 | $cleaned{isa} = $param->{isa} || 'DateTime'; | |||
| 10318 | 2 | 3 | $cleaned{_note} = 'Requires DateTime object'; | |||
| 10319 | } elsif ($semantic eq 'timepiece_object') { | |||||
| 10320 | 0 | 0 | $cleaned{type} = 'object'; | |||
| 10321 | 0 | 0 | $cleaned{isa} = $param->{isa} || 'Time::Piece'; | |||
| 10322 | 0 | 0 | $cleaned{_note} = 'Requires Time::Piece object'; | |||
| 10323 | } elsif ($semantic eq 'date_string') { | |||||
| 10324 | # Date strings: provide regex pattern | |||||
| 10325 | 1 | 1 | $cleaned{type} = 'string'; | |||
| 10326 | 1 | 2 | $cleaned{matches} ||= '/^\d{4}-\d{2}-\d{2}$/'; | |||
| 10327 | 1 | 1 | $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 | 0 | 0 | $cleaned{semantic} = 'bytes'; | |||
| 10332 | 0 | 0 | $cleaned{type} //= 'string'; | |||
| 10333 | } elsif ($semantic eq 'iso8601_string') { | |||||
| 10334 | 1 | 1 | $cleaned{type} = 'string'; | |||
| 10335 | 1 | 1 | $cleaned{matches} ||= '/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z?$/'; | |||
| 10336 | 1 | 1 | $cleaned{_example} = '2024-12-12T10:30:00Z'; | |||
| 10337 | } elsif ($semantic eq 'unix_timestamp') { | |||||
| 10338 | 3 | 3 | $cleaned{type} = 'integer'; | |||
| 10339 | 3 | 10 | $cleaned{min} ||= 0; | |||
| 10340 | 3 | 10 | $cleaned{max} ||= $INT32_MAX; # 32-bit max | |||
| 10341 | 3 | 7 | $cleaned{_note} = 'UNIX timestamp'; | |||
| 10342 | } elsif ($semantic eq 'datetime_parseable') { | |||||
| 10343 | 0 | 0 | $cleaned{type} = 'string'; | |||
| 10344 | 0 | 0 | $cleaned{_note} = 'Must be parseable as datetime'; | |||
| 10345 | } elsif ($semantic eq 'filehandle') { | |||||
| 10346 | # File handles: special handling needed | |||||
| 10347 | 2 | 3 | $cleaned{type} = 'object'; | |||
| 10348 | 2 | 3 | $cleaned{isa} = $param->{isa} || 'IO::Handle'; | |||
| 10349 | 2 | 3 | $cleaned{_note} = 'File handle - may need mock in tests'; | |||
| 10350 | } elsif ($semantic eq 'filepath') { | |||||
| 10351 | # File paths: string with path pattern | |||||
| 10352 | 2 | 3 | $cleaned{type} = 'string'; | |||
| 10353 | 2 | 22 | $cleaned{matches} ||= '/^[\\w\\/.\\-_]+$/'; | |||
| 10354 | 2 | 3 | $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 | 1 | 1 | $cleaned{type} = 'string'; | |||
| 10360 | 1 | 1 | $cleaned{semantic} = 'existing_file'; | |||
| 10361 | 1 | 2 | $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 | 2 | 2 | $cleaned{type} = 'string'; | |||
| 10368 | 2 | 2 | $cleaned{semantic} = 'directory'; | |||
| 10369 | 2 | 18 | $cleaned{_note} = 'Existing directory'; | |||
| 10370 | } elsif ($semantic eq 'callback') { | |||||
| 10371 | # Coderefs: mark as special type | |||||
| 10372 | 5 | 6 | $cleaned{type} = 'coderef'; | |||
| 10373 | 5 | 8 | $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 | 5 | 10 | if (($param->{_source} // '') eq SOURCE_INPUT_SPEC && defined $param->{type} && $param->{type} ne 'string') { | |||
| 10380 | # Formal spec wins; suppress spurious regex-derived enum. | |||||
| 10381 | 0 | 0 | delete $cleaned{enum}; | |||
| 10382 | } else { | |||||
| 10383 | 5 | 5 | $cleaned{type} = 'string'; | |||
| 10384 | 5 | 10 | if ($param->{enum} && ref($param->{enum}) eq 'ARRAY') { | |||
| 10385 | 5 | 5 | $cleaned{enum} = $param->{enum}; | |||
| 10386 | 5 5 | 3 11 | $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 | 258 | 263 | $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 | 258 | 224 | if(ref($param->{schema}) eq 'HASH') { | |||
| 10400 | 0 | 0 | $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 | 258 | 475 | my $formal_non_string = (($param->{_source} // '') eq SOURCE_INPUT_SPEC) && defined $param->{type} && $param->{type} ne 'string'; | |||
| 10409 | 258 | 301 | if($param->{enum} && ref($param->{enum}) eq 'ARRAY' && !$cleaned{enum} && !$formal_non_string) { | |||
| 10410 | 2 | 3 | $cleaned{memberof} = $param->{enum}; | |||
| 10411 | } | |||||
| 10412 | 258 | 249 | if($param->{memberof} && ref($param->{memberof}) eq 'ARRAY') { | |||
| 10413 | 4 | 4 | $cleaned{memberof} = $param->{memberof}; | |||
| 10414 | } | |||||
| 10415 | ||||||
| 10416 | # Handle object class | |||||
| 10417 | 258 | 262 | if ($param->{isa} && !$cleaned{isa}) { | |||
| 10418 | 4 | 4 | $cleaned{isa} = $param->{isa}; | |||
| 10419 | } | |||||
| 10420 | ||||||
| 10421 | # Add format hints where available | |||||
| 10422 | 258 | 232 | if ($param->{format}) { | |||
| 10423 | 1 | 1 | $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 | 258 | 248 | if(defined(my $pattern = $cleaned{matches})) { | |||
| 10433 | 17 | 54 | 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 | 0 | 0 | my ($body) = re::regexp_pattern($pattern); | |||
| 10437 | 0 | 0 | $cleaned{matches} = $body if defined($body); | |||
| 10438 | } elsif(!ref($pattern)) { | |||||
| 10439 | 17 | 33 | (my $body = $pattern) =~ s{^/(.+)/$}{$1}s; | |||
| 10440 | 17 17 | 9 289 | my $compiled = eval { qr/$body/ }; | |||
| 10441 | 17 | 19 | if($@) { | |||
| 10442 | 0 | 0 | $self->_log(" invalid matches pattern '$pattern': $@"); | |||
| 10443 | } else { | |||||
| 10444 | 17 | 25 | $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 | 258 | 239 | if(ref($param->{_stub_elements}) eq 'HASH') { | |||
| 10452 | 0 | 0 | $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 | 258 | 469 | unless(($cleaned{semantic} // '') =~ /^(?:directory|existing_file|bytes)$/); | |||
| 10459 | ||||||
| 10460 | 258 | 228 | 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 | 14 | 4711 | my $rel = $_[0]; | |||
| 10482 | ||||||
| 10483 | 14 | 24 | if ($rel->{type} eq 'mutually_exclusive') { | |||
| 10484 | 3 3 | 3 9 | return 'Mutually exclusive: ' . join(', ', @{$rel->{params}}); | |||
| 10485 | } elsif ($rel->{type} eq 'required_group') { | |||||
| 10486 | 2 2 | 2 5 | return "Required group (OR): " . join(', ', @{$rel->{params}}); | |||
| 10487 | } elsif ($rel->{type} eq 'conditional_requirement') { | |||||
| 10488 | 2 | 4 | return "If $rel->{if} then $rel->{then_required} required"; | |||
| 10489 | } elsif ($rel->{type} eq 'dependency') { | |||||
| 10490 | 3 | 6 | return "$rel->{param} depends on $rel->{requires}"; | |||
| 10491 | } elsif ($rel->{type} eq 'value_constraint') { | |||||
| 10492 | 2 | 5 | return "If $rel->{if} then $rel->{then} $rel->{operator} $rel->{value}"; | |||
| 10493 | } elsif ($rel->{type} eq 'value_conditional') { | |||||
| 10494 | 1 | 2 | return "If $rel->{if}='$rel->{equals}' then $rel->{then_required} required"; | |||
| 10495 | } | |||||
| 10496 | 1 | 2 | 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 | 473 | 374 | my ($body, $input) = @_; | |||
| 10533 | ||||||
| 10534 | 473 | 610 | return undef unless(ref($input) eq 'HASH'); | |||
| 10535 | 451 | 602 | return undef unless(defined($body) && length($body)); | |||
| 10536 | ||||||
| 10537 | 451 451 | 420 503 | foreach my $param (sort keys %{$input}) { | |||
| 10538 | 403 | 364 | my $p = quotemeta($param); | |||
| 10539 | ||||||
| 10540 | # The value is often copied out of %args under another name first. | |||||
| 10541 | 403 | 356 | my @names = ($p); | |||
| 10542 | 403 | 13565 | while($body =~ /\bmy\s+\$(\w+)\s*=\s*\$args\{\s*['"]?$p['"]?\s*\}\s*;/g) { | |||
| 10543 | 4 | 11 | push @names, quotemeta($1) if($1 ne $param); | |||
| 10544 | } | |||||
| 10545 | 403 | 583 | my $v = '(?:' . join('|', @names) . ')'; | |||
| 10546 | ||||||
| 10547 | # A file whose contents are read, not merely tested for existence. | |||||
| 10548 | 403 | 10737 | 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 | 400 | 14137 | 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 | 400 | 870 | $tests_existence ||= ($param eq 'config_file') | |||
| 10558 | && ($body =~ /\bObject::Configure::configure\s*\(/); | |||||
| 10559 | 400 | 553 | next unless($tests_existence); | |||
| 10560 | ||||||
| 10561 | 3 | 4 | my $spec = $input->{$param}; | |||
| 10562 | 3 | 5 | $spec->{semantic} = 'existing_file' if(ref($spec) eq 'HASH'); | |||
| 10563 | } | |||||
| 10564 | ||||||
| 10565 | 448 | 508 | 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 | 90 | 119 | my $spec = $_[0] // ''; | |||
| 10575 | ||||||
| 10576 | 90 | 146 | 1 while($spec =~ s/\{[^{}]*\}//g); | |||
| 10577 | 90 | 92 | $spec =~ s/\{.*\z//s; | |||
| 10578 | ||||||
| 10579 | 90 | 79 | 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 | 84 | 358 | my $own = _own_spec_text($_[0]); | |||
| 10587 | ||||||
| 10588 | 84 | 261 | return $1 + 0 if($own =~ /\boptional\s*=>\s*(0|1)/i); | |||
| 10589 | 24 | 35 | return 1 - $1 if($own =~ /\brequired\s*=>\s*(0|1)/i); | |||
| 10590 | 22 | 27 | 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 | 27 | 1325 | my $text = $_[0]; | |||
| 10598 | ||||||
| 10599 | 27 | 27 | my (@entries, $pending, $name, $start); | |||
| 10600 | 27 | 423 | my $depth = 0; | |||
| 10601 | 27 | 220 | while($text =~ /\b(\w+)\s*=>\s*(?=\{)|([{}])/g) { | |||
| 10602 | 34 | 29 | if(defined($1)) { | |||
| 10603 | 10 | 9 | $pending = $1 if($depth == 0); | |||
| 10604 | 10 | 8 | next; | |||
| 10605 | } | |||||
| 10606 | 24 | 20 | if($2 eq '{') { | |||
| 10607 | 12 | 17 | if(($depth == 0) && defined($pending)) { | |||
| 10608 | 8 | 5 | ($name, $start) = ($pending, pos($text)); | |||
| 10609 | } | |||||
| 10610 | 12 | 8 | undef $pending; | |||
| 10611 | 12 | 5 | $depth++; | |||
| 10612 | 12 | 35 | next; | |||
| 10613 | } | |||||
| 10614 | 12 | 7 | next unless($depth > 0); | |||
| 10615 | 12 | 8 | $depth--; | |||
| 10616 | 12 | 47 | if(($depth == 0) && defined($name)) { | |||
| 10617 | 8 | 9 | push @entries, [ $name, substr($text, $start, pos($text) - 1 - $start) ]; | |||
| 10618 | 8 | 27 | undef $name; | |||
| 10619 | } | |||||
| 10620 | } | |||||
| 10621 | ||||||
| 10622 | 27 | 40 | 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 | 36 | 36 | my ($ctor_schema) = @_; | |||
| 10641 | ||||||
| 10642 | 36 | 30 | my $input = $ctor_schema->{input}; | |||
| 10643 | 36 | 45 | return undef unless(ref($input) eq 'HASH'); | |||
| 10644 | ||||||
| 10645 | 36 | 44 | for my $param (sort keys %$input) { | |||
| 10646 | 24 | 15 | my $spec = $input->{$param}; | |||
| 10647 | 24 | 28 | next unless(ref($spec) eq 'HASH'); | |||
| 10648 | ||||||
| 10649 | 24 | 27 | my $type = $spec->{type} // ''; | |||
| 10650 | 24 | 46 | if(($type =~ /\bobject\b/) && !defined($spec->{can}) && !defined($spec->{isa})) { | |||
| 10651 | 5 | 11 | return "constructor needs a live '$param' object, which a fixture cannot provide"; | |||
| 10652 | } | |||||
| 10653 | 19 | 35 | if(($spec->{semantic} // '') eq 'directory') { | |||
| 10654 | 0 | 0 | return "constructor needs an existing '$param' directory, which a fixture cannot provide"; | |||
| 10655 | } | |||||
| 10656 | } | |||||
| 10657 | ||||||
| 10658 | 31 | 46 | 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 | 74 | 65 | my ($body, $ctor_schema) = @_; | |||
| 10669 | ||||||
| 10670 | 74 0 | 70 0 | my $content = ref($body) ? eval { $body->content } : $body; | |||
| 10671 | 74 | 137 | return () unless(defined($content) && length($content)); | |||
| 10672 | ||||||
| 10673 | 74 | 61 | my $input = $ctor_schema->{input}; | |||
| 10674 | 74 | 77 | return () unless(ref($input) eq 'HASH'); | |||
| 10675 | ||||||
| 10676 | 74 | 41 | my %reasons; | |||
| 10677 | 74 | 96 | for my $param (sort keys %$input) { | |||
| 10678 | 54 | 37 | my $spec = $input->{$param}; | |||
| 10679 | 54 | 42 | next unless(ref($spec) eq 'HASH'); | |||
| 10680 | 54 | 50 | next if($spec->{optional}); | |||
| 10681 | ||||||
| 10682 | 26 | 19 | my $type = $spec->{type} // ''; | |||
| 10683 | 26 | 41 | next unless(($type eq 'arrayref') || ($type eq 'array')); | |||
| 10684 | ||||||
| 10685 | 8 | 8 | my $p = quotemeta($param); | |||
| 10686 | 8 | 62 | my $field = qr/\$\w+(?:->)?\{\s*['"]?$p['"]?\s*\}/; | |||
| 10687 | ||||||
| 10688 | # `croak ... unless @{ $p->{databases} }`. | |||||
| 10689 | 8 | 55 | 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 | 8 | 129 | 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 | 8 | 12 | next unless($empty_guard || $elements_are_objects); | |||
| 10697 | ||||||
| 10698 | 5 | 11 | $reasons{$param} = $empty_guard | |||
| 10699 | ? "needs a non-empty arrayref of live objects in '$param'" | |||||
| 10700 | : "needs live objects in '$param'"; | |||||
| 10701 | } | |||||
| 10702 | ||||||
| 10703 | 74 | 80 | return %reasons; | |||
| 10704 | } | |||||
| 10705 | ||||||
| 10706 | sub _constructor_requires_live_objects | |||||
| 10707 | { | |||||
| 10708 | 38 | 895 | my ($body, $ctor_schema) = @_; | |||
| 10709 | ||||||
| 10710 | 38 | 52 | my %reasons = _constructor_live_object_param_reasons($body, $ctor_schema); | |||
| 10711 | 38 | 81 | return undef unless(%reasons); | |||
| 10712 | ||||||
| 10713 | 3 | 4 | my ($param) = sort keys %reasons; | |||
| 10714 | 3 | 6 | 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 | 2 | 2 | my ($pod) = @_; | |||
| 10725 | ||||||
| 10726 | 2 | 4 | return undef unless(defined($pod) && length($pod)); | |||
| 10727 | ||||||
| 10728 | 2 | 6 | return $1 if($pod =~ /\bsubclass(?:es)?\s+of\s+(?:C<)?([A-Z]\w*(?:::\w+)+)/); | |||
| 10729 | 1 | 2 | return $1 if($pod =~ /\bisa\s*\(\s*['\"]?([A-Z]\w*(?:::\w+)+)/); | |||
| 10730 | 1 | 2 | return $1 if($pod =~ /\binstances?\s+of\s+(?:C<)?([A-Z]\w*(?:::\w+)+)/); | |||
| 10731 | ||||||
| 10732 | 1 | 0 | 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 | 36 | 46 | my ($ctor_schema, $pod, $body) = @_; | |||
| 10750 | ||||||
| 10751 | 36 | 69 | my %reasons = _constructor_live_object_param_reasons($body, $ctor_schema); | |||
| 10752 | 36 | 52 | return {} unless(%reasons); | |||
| 10753 | ||||||
| 10754 | 2 | 4 | my $base = _pod_constructor_element_class($pod); | |||
| 10755 | 2 | 6 | return {} unless(defined($base) && ($base eq 'Database::Abstraction')); | |||
| 10756 | ||||||
| 10757 | 1 | 2 | my $input = $ctor_schema->{input} // {}; | |||
| 10758 | my $join_column = (ref($input->{join_column}) eq 'HASH') | |||||
| 10759 | 1 | 3 | ? $input->{join_column}{default} : undef; | |||
| 10760 | 1 | 3 | return {} unless(defined($join_column) && !ref($join_column) && length($join_column)); | |||
| 10761 | ||||||
| 10762 | 1 | 1 | my %stubs; | |||
| 10763 | 1 | 2 | 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 | 1 | 1 | $input->{$param}{min} = 1; | |||
| 10767 | 1 | 3 | my $stub = { | |||
| 10768 | isa => $base, | |||||
| 10769 | methods => { | |||||
| 10770 | columns => [ $join_column ], | |||||
| 10771 | schema => {}, | |||||
| 10772 | selectall_arrayref => [], | |||||
| 10773 | }, | |||||
| 10774 | }; | |||||
| 10775 | 1 | 2 | $input->{$param}{_stub_elements} = $stub; | |||
| 10776 | 1 | 1 | $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 | 1 | 2 | if(ref($input->{join_column}) eq 'HASH') { | |||
| 10785 | 1 | 1 | $input->{join_column}{memberof} = [ $join_column ]; | |||
| 10786 | 1 | 2 | $input->{join_column}{_constraint_source}{memberof} = 'fixture'; | |||
| 10787 | 1 | 2 | $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 | 1 | 2 | for my $param (keys %$input) { | |||
| 10794 | 4 | 4 | my $element = $input->{$param}{schema}; | |||
| 10795 | 4 | 6 | next unless(ref($element) eq 'HASH' && ref($element->{col}) eq 'HASH'); | |||
| 10796 | 1 0 | 2 0 | next if(ref($element->{col}{memberof}) eq 'ARRAY' && @{$element->{col}{memberof}}); | |||
| 10797 | 1 | 1 | $element->{col}{memberof} = [ $join_column ]; | |||
| 10798 | 1 | 2 | $element->{col}{_constraint_source}{memberof} = 'fixture'; | |||
| 10799 | 1 | 1 | $element->{col}{_fixture} = 1; | |||
| 10800 | } | |||||
| 10801 | ||||||
| 10802 | 1 | 1 | 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 | 473 | 382 | my ($body, $pod) = @_; | |||
| 10834 | ||||||
| 10835 | 473 | 387 | return 0 unless defined($body); | |||
| 10836 | ||||||
| 10837 | # A handle handed to the caller, as the POD's output documents it. | |||||
| 10838 | 473 | 646 | 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 | 472 | 559 | 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 | 472 | 1381 | return 1 if(($pod =~ /\b(?:SQLite\s+)?cache/i) | |||
| 10847 | && ($body =~ /\$self\s*->\s*(?:_build_sqlite_cache|_sqlite_join|_sqlite_aggregate)\s*\(/)); | |||||
| 10848 | ||||||
| 10849 | 471 | 423 | 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 | 473 | 367 | my ($body) = @_; | |||
| 10858 | ||||||
| 10859 | 473 | 405 | my $code = $body // ''; | |||
| 10860 | 473 | 358 | $code =~ s/#[^\n]*//g; | |||
| 10861 | 473 | 678 | $code =~ s/\A\s*sub\s+\w+\s*\{//; | |||
| 10862 | 473 | 644 | $code =~ s/\}\s*\z//; | |||
| 10863 | ||||||
| 10864 | 473 | 727 | 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 | 36 | 36 | my ($body, $ctor_schema) = @_; | |||
| 10874 | ||||||
| 10875 | # _find_methods() keeps the body as source text, but accept a PPI node too. | |||||
| 10876 | 36 0 | 46 0 | my $content = ref($body) ? eval { $body->content } : $body; | |||
| 10877 | 36 | 69 | return 0 unless(defined($content) && length($content)); | |||
| 10878 | ||||||
| 10879 | 36 | 57 | return 1 if($content =~ /\bcheck_abstract\s*\(/); | |||
| 10880 | 36 | 83 | return 1 if(($content =~ /\bcroak\b/) && ($content =~ /\beq\s+__PACKAGE__\b/)); | |||
| 10881 | ||||||
| 10882 | 35 35 | 53 42 | my %declared = (ref($ctor_schema->{input}) eq 'HASH') ? %{$ctor_schema->{input}} : (); | |||
| 10883 | 35 | 76 | while($content =~ /\$args\{\s*(['"]?)([\w:]+)\1\s*\}\s*or\s+croak\b/sg) { | |||
| 10884 | 1 | 2 | return 1 unless(exists($declared{$2})); | |||
| 10885 | } | |||||
| 10886 | ||||||
| 10887 | 34 | 54 | return 0; | |||
| 10888 | } | |||||
| 10889 | ||||||
| 10890 | sub _ctor_representative_args { | |||||
| 10891 | 36 | 35 | my ($self, $ctor_schema) = @_; | |||
| 10892 | ||||||
| 10893 | 36 | 117 | 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 | 36 | 47 | my $input = $ctor_schema->{input} // {}; | |||
| 10904 | 36 | 73 | my %args; | |||
| 10905 | 36 | 41 | for my $param_name (keys %$input) { | |||
| 10906 | 26 | 24 | my $spec = $input->{$param_name} // {}; | |||
| 10907 | 26 | 24 | 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 | 12 | 32 | if ($param_name =~ /(?:file|filename)/i) { | |||
| 10915 | 1 | 1 | return undef; | |||
| 10916 | } | |||||
| 10917 | 11 | 24 | if ($param_name =~ /(?:dir|path)/i) { | |||
| 10918 | 2 | 3 | $args{$param_name} = { '_path' => 'directory' }; | |||
| 10919 | 2 | 2 | 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 | 9 | 16 | if (ref($spec->{_stub_elements}) eq 'HASH') { | |||
| 10924 | 1 | 3 | $args{$param_name} = [ { '_stub' => $spec->{_stub_elements} } ]; | |||
| 10925 | 1 | 1 | next; | |||
| 10926 | } | |||||
| 10927 | 8 | 5 | my $type = $spec->{type} // 'string'; | |||
| 10928 | 8 | 9 | unless (exists $REP{$type}) { | |||
| 10929 | 1 | 2 | return undef; | |||
| 10930 | } | |||||
| 10931 | 7 | 10 | $args{$param_name} = $REP{$type}; | |||
| 10932 | } | |||||
| 10933 | 34 | 57 | 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 | 478 | 1391 | my ($self, $method_name, $method_body, $method_info) = @_; | |||
| 10964 | ||||||
| 10965 | # Allow method_info to be optional for backward compatibility | |||||
| 10966 | 478 | 435 | $method_info ||= {}; | |||
| 10967 | ||||||
| 10968 | 478 | 369 | my $doc = $self->{_document}; | |||
| 10969 | 478 | 772 | return undef unless $doc; | |||
| 10970 | ||||||
| 10971 | # Get the current package name | |||||
| 10972 | 478 | 715 | my $package_stmt = $doc->find_first('PPI::Statement::Package'); | |||
| 10973 | 478 | 40885 | my $current_package = $package_stmt ? $package_stmt->namespace : 'UNKNOWN'; | |||
| 10974 | 478 | 4943 | $self->{_package_name} //= $current_package; | |||
| 10975 | ||||||
| 10976 | # Initialize result structure | |||||
| 10977 | 478 | 1016 | 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 | 478 | 324 | my $skip_object = 0; | |||
| 10987 | ||||||
| 10988 | # Skip constructors and destructors | |||||
| 10989 | 478 | 485 | if ($method_name eq 'new') { | |||
| 10990 | 36 | 51 | $self->_log(" OBJECT: Constructor '$method_name' detected; skipping instantiation analysis"); | |||
| 10991 | 36 | 55 | return undef; | |||
| 10992 | } | |||||
| 10993 | 442 | 707 | if($method_name =~ /^(create|build|construct|init|DESTROY)$/i) { | |||
| 10994 | 3 | 3 | $skip_object = 1; | |||
| 10995 | } | |||||
| 10996 | ||||||
| 10997 | # 1. Check for factory methods that return instances | |||||
| 10998 | 442 | 644 | 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 | 442 | 572 | my $is_singleton = $self->_detect_singleton_pattern($method_name, $method_body); | |||
| 11004 | 442 | 380 | if ($is_singleton) { | |||
| 11005 | 1 | 1 | $result->{needs_object} = 0; # Singleton methods return the singleton instance | |||
| 11006 | 1 | 1 | $result->{type} = 'singleton_accessor'; | |||
| 11007 | 1 | 0 | $result->{details} = $is_singleton; | |||
| 11008 | 1 | 2 | $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 | 1 | 0 | $skip_object = 1; | |||
| 11012 | } | |||||
| 11013 | ||||||
| 11014 | # 3. Check if this is an instance method that needs an object | |||||
| 11015 | 442 | 546 | my $is_instance_method = $self->_detect_instance_method($method_name, $method_body); | |||
| 11016 | 442 | 601 | 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 | 205 | 166 | if ($is_factory) { | |||
| 11025 | 5 | 10 | $self->_log( | |||
| 11026 | " OBJECT: Instance-only method '$method_name' overrides factory detection" | |||||
| 11027 | ); | |||||
| 11028 | } | |||||
| 11029 | ||||||
| 11030 | 205 | 149 | $result->{needs_object} = 1; | |||
| 11031 | 205 | 183 | $result->{type} = 'instance_method'; | |||
| 11032 | 205 | 156 | $result->{details} = $is_instance_method; | |||
| 11033 | ||||||
| 11034 | # 4. Check for inheritance - if parent class constructor should be used | |||||
| 11035 | 205 | 245 | my $inheritance_info = $self->_check_inheritance_for_constructor( | |||
| 11036 | $current_package, $method_body | |||||
| 11037 | ); | |||||
| 11038 | 205 | 278 | if ($inheritance_info && $inheritance_info->{use_parent_constructor}) { | |||
| 11039 | 0 | 0 | $result->{package} = $inheritance_info->{parent_class}; | |||
| 11040 | 0 | 0 | $result->{details}{inheritance} = $inheritance_info; | |||
| 11041 | 0 | 0 | $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 | 205 | 360 | ); | |||
| 11050 | 205 | 192 | if ($constructor_needs) { | |||
| 11051 | 8 | 7 | $result->{constructor_params} = $constructor_needs; | |||
| 11052 | 8 | 11 | $result->{details}{constructor_requirements} = $constructor_needs; | |||
| 11053 | 8 | 16 | $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 | 205 | 549 | return $result->{package}; | |||
| 11060 | } | |||||
| 11061 | ||||||
| 11062 | # 6. Check for class methods that might need objects from other classes | |||||
| 11063 | 237 | 313 | my $needs_other_object = $self->_detect_external_object_dependency($method_body); | |||
| 11064 | 237 | 207 | if ($needs_other_object) { | |||
| 11065 | 0 | 0 | $result->{needs_object} = 1; | |||
| 11066 | 0 | 0 | $result->{type} = 'external_dependency'; | |||
| 11067 | $result->{package} = $needs_other_object->{package} | |||||
| 11068 | 0 | 0 | if $needs_other_object->{package}; | |||
| 11069 | 0 | 0 | $result->{details} = $needs_other_object; | |||
| 11070 | ||||||
| 11071 | 0 | 0 | $self->_log( | |||
| 11072 | " OBJECT: Method '$method_name' depends on external object: $needs_other_object->{package}" | |||||
| 11073 | ); | |||||
| 11074 | 0 | 0 | return $result->{package} if $result->{package}; | |||
| 11075 | } | |||||
| 11076 | ||||||
| 11077 | # Factory method only if NOT instance-based | |||||
| 11078 | 237 | 305 | if ($is_factory && !$skip_object) { | |||
| 11079 | 1 | 1 | $result->{needs_object} = 0; | |||
| 11080 | 1 | 1 | $result->{type} = 'factory'; | |||
| 11081 | 1 | 1 | $result->{details} = $is_factory; | |||
| 11082 | $self->_log( | |||||
| 11083 | " OBJECT: Detected factory method '$method_name' returns $is_factory->{returns_class} objects" | |||||
| 11084 | 1 | 3 | ) if $is_factory->{returns_class}; | |||
| 11085 | } | |||||
| 11086 | ||||||
| 11087 | 237 | 320 | 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 | 448 | 9104 | my ($self, $method_name, $method_body, $current_package, $method_info) = @_; | |||
| 11116 | ||||||
| 11117 | 448 | 269 | my %factory_info; | |||
| 11118 | ||||||
| 11119 | # Check method name patterns | |||||
| 11120 | 448 | 645 | if ($method_name =~ /^(create_|make_|build_|get_)/i) { | |||
| 11121 | 13 | 15 | $factory_info{name_pattern} = 1; | |||
| 11122 | } | |||||
| 11123 | ||||||
| 11124 | # Look for object creation patterns in the method body | |||||
| 11125 | 448 | 420 | if ($method_body) { | |||
| 11126 | # Pattern 1: Returns a blessed reference | |||||
| 11127 | 448 | 1172 | if ($method_body =~ /return\s+bless\s*\{[^}]*\},\s*['"]?(\w+(?:::\w+)*|\$\w+)['"]?/s || | |||
| 11128 | $method_body =~ /bless\s*\{[^}]*\},\s*['"]?(\w+(?:::\w+)*|\$\w+)['"]?.*return/s) { | |||||
| 11129 | 6 | 8 | my $class_name = $1; | |||
| 11130 | ||||||
| 11131 | # Handle variable class names | |||||
| 11132 | 6 | 16 | if ($class_name =~ /^\$(class|self|package)$/) { | |||
| 11133 | 2 | 2 | $factory_info{returns_class} = $current_package; | |||
| 11134 | } elsif ($class_name =~ /^\$/) { | |||||
| 11135 | 1 | 1 | $factory_info{returns_class} = 'VARIABLE'; # Unknown variable | |||
| 11136 | } else { | |||||
| 11137 | 3 | 5 | $factory_info{returns_class} = $class_name; | |||
| 11138 | } | |||||
| 11139 | ||||||
| 11140 | 6 | 6 | $factory_info{returns_blessed} = 1; | |||
| 11141 | 6 | 7 | $factory_info{confidence} = 'high'; | |||
| 11142 | 6 | 7 | return \%factory_info; | |||
| 11143 | } | |||||
| 11144 | ||||||
| 11145 | # Pattern 2: Returns ->new() call on class or $self | |||||
| 11146 | 442 | 996 | if ($method_body =~ /return\s+([\$\w:]+)->new\(/s || | |||
| 11147 | $method_body =~ /([\$\w:]+)->new\(.*return/s) { | |||||
| 11148 | 7 | 9 | my $target = $1; | |||
| 11149 | ||||||
| 11150 | # Determine what class is being instantiated | |||||
| 11151 | 7 | 32 | if ($target eq '$self' || $target eq 'shift' || $target =~ /^\$/) { | |||
| 11152 | 0 | 0 | $factory_info{returns_class} = $current_package; | |||
| 11153 | 0 | 0 | $factory_info{self_new} = 1; | |||
| 11154 | } elsif ($target =~ /::/) { | |||||
| 11155 | 1 | 2 | $factory_info{returns_class} = $target; | |||
| 11156 | 1 | 2 | $factory_info{external_class} = 1; | |||
| 11157 | } else { | |||||
| 11158 | 6 | 6 | $factory_info{returns_class} = $target; | |||
| 11159 | } | |||||
| 11160 | ||||||
| 11161 | 7 | 8 | $factory_info{returns_new} = 1; | |||
| 11162 | 7 | 7 | $factory_info{confidence} = 'medium'; | |||
| 11163 | 7 | 10 | return \%factory_info; | |||
| 11164 | } | |||||
| 11165 | ||||||
| 11166 | # Pattern 3: Returns an object from another factory method | |||||
| 11167 | 435 | 1369 | if ($method_body =~ /return\s+([\$\w:]+)->(create_|make_|build_|get_)/i || | |||
| 11168 | $method_body =~ /([\$\w:]+)->(create_|make_|build_|get_).*return/si) { | |||||
| 11169 | 0 | 0 | $factory_info{returns_factory_result} = 1; | |||
| 11170 | 0 | 0 | $factory_info{confidence} = 'low'; | |||
| 11171 | 0 | 0 | return \%factory_info; | |||
| 11172 | } | |||||
| 11173 | } | |||||
| 11174 | ||||||
| 11175 | # Check for return type hints in POD if available | |||||
| 11176 | 435 | 1094 | if ($method_info && ref($method_info) eq 'HASH' && $method_info->{pod}) { | |||
| 11177 | 212 | 191 | my $pod = $method_info->{pod}; | |||
| 11178 | 212 | 425 | if ($pod =~ /returns?\s+(?:an?\s+)?(object|instance|new\s+\w+)/i) { | |||
| 11179 | 0 | 0 | $factory_info{pod_hint} = 1; | |||
| 11180 | 0 | 0 | $factory_info{confidence} = 'low'; | |||
| 11181 | 0 | 0 | return \%factory_info; | |||
| 11182 | } | |||||
| 11183 | } | |||||
| 11184 | ||||||
| 11185 | 435 | 433 | 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 | 451 | 889 | my ($self, $method_name, $method_body) = @_; | |||
| 11216 | ||||||
| 11217 | # Check method name patterns | |||||
| 11218 | 451 | 695 | return undef unless $method_name =~ /^(instance|get_instance|singleton|shared_instance)$/i; | |||
| 11219 | ||||||
| 11220 | 7 | 7 | my %singleton_info = ( | |||
| 11221 | name_pattern => 1, | |||||
| 11222 | ); | |||||
| 11223 | ||||||
| 11224 | # Look for singleton patterns in code | |||||
| 11225 | 7 | 9 | if ($method_body) { | |||
| 11226 | # Pattern 1: Static/state variable holding instance | |||||
| 11227 | 7 | 21 | if ($method_body =~ /(?:my\s+)?(?:our\s+)?\$(?:instance|_instance|singleton)\b/s || | |||
| 11228 | $method_body =~ /state\s+\$(?:instance|_instance|singleton)\b/s) { | |||||
| 11229 | 5 | 4 | $singleton_info{static_variable} = 1; | |||
| 11230 | 5 | 7 | $singleton_info{confidence} = 'high'; | |||
| 11231 | } | |||||
| 11232 | ||||||
| 11233 | # Pattern 2: Returns $instance if defined (with better regex) | |||||
| 11234 | 7 | 26 | if ($method_body =~ /return\s+\$instance\s+if\s+(?:defined\s+)?\$instance/ || | |||
| 11235 | $method_body =~ /unless\s+\$instance.*?=\s*.*?new/) { | |||||
| 11236 | 1 | 1 | $singleton_info{returns_instance} = 1; | |||
| 11237 | 1 | 1 | $singleton_info{confidence} = 'high'; | |||
| 11238 | } | |||||
| 11239 | ||||||
| 11240 | # Pattern 3: ||= new() pattern (with better regex) | |||||
| 11241 | 7 | 21 | if ($method_body =~ /\$instance\s*\|\|=\s*.*?new/ || | |||
| 11242 | $method_body =~ /\$instance\s*=\s*.*?new\s+unless\s+(?:defined\s+)?\$instance/) { | |||||
| 11243 | 3 | 3 | $singleton_info{lazy_initialization} = 1; | |||
| 11244 | 3 | 4 | $singleton_info{confidence} = 'medium'; | |||
| 11245 | } | |||||
| 11246 | ||||||
| 11247 | # Pattern 4: Direct return of $instance variable | |||||
| 11248 | 7 | 11 | if ($method_body =~ /return\s+\$instance;/) { | |||
| 11249 | 4 | 6 | $singleton_info{returns_instance} = 1; | |||
| 11250 | 4 | 5 | $singleton_info{confidence} = 'high' unless $singleton_info{confidence}; | |||
| 11251 | } | |||||
| 11252 | } | |||||
| 11253 | ||||||
| 11254 | 7 | 11 | return \%singleton_info if keys %singleton_info > 0; # Need at least name pattern | |||
| 11255 | ||||||
| 11256 | 0 | 0 | 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 | 450 | 1792 | my ($self, $method_name, $method_body) = @_; | |||
| 11285 | ||||||
| 11286 | 450 | 278 | my %instance_info; | |||
| 11287 | ||||||
| 11288 | # Pattern 1: my ($self, ...) = @_; | |||||
| 11289 | 450 | 1233 | if ($method_body =~ /my\s*\(\s*\$self\s*[,)]/) { | |||
| 11290 | 166 | 175 | $instance_info{explicit_self} = 1; | |||
| 11291 | 166 | 161 | $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 | 9 | 11 | $instance_info{explicit_self} = 1; | |||
| 11297 | 9 | 10 | $instance_info{confidence} = 'high'; | |||
| 11298 | } | |||||
| 11299 | ||||||
| 11300 | # Pattern 2: my $self = shift; | |||||
| 11301 | elsif ($method_body =~ /my\s+\$self\s*=\s*shift/) { | |||||
| 11302 | 34 | 41 | $instance_info{shift_self} = 1; | |||
| 11303 | 34 | 38 | $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 | 2 | 2 | $instance_info{uses_self} = 1; | |||
| 11310 | 2 | 2 | $instance_info{confidence} = 'medium'; | |||
| 11311 | } | |||||
| 11312 | ||||||
| 11313 | # Pattern 4: Accesses object data: $self->{...}, $self->[...] | |||||
| 11314 | 450 | 634 | if ($method_body =~ /\$self\s*->\s*[\{\[]/) { | |||
| 11315 | 79 | 73 | $instance_info{accesses_object_data} = 1; | |||
| 11316 | 79 | 108 | $instance_info{confidence} = 'high' unless $instance_info{confidence} eq 'high'; | |||
| 11317 | } | |||||
| 11318 | ||||||
| 11319 | # Pattern 5: Calls other instance methods on $self | |||||
| 11320 | 450 | 592 | if ($method_body =~ /\$self\s*->\s*(\w+)\s*\(/s) { | |||
| 11321 | 10 | 12 | $instance_info{calls_instance_methods} = []; | |||
| 11322 | 10 | 22 | while ($method_body =~ /\$self\s*->\s*(\w+)\s*\(/g) { | |||
| 11323 | 10 10 | 6 15 | push @{$instance_info{calls_instance_methods}}, $1; | |||
| 11324 | } | |||||
| 11325 | 10 10 | 9 14 | $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 | 450 | 546 | if ($method_name =~ /^_/ && $method_name !~ /^_new/) { | |||
| 11330 | # Private methods are usually instance methods | |||||
| 11331 | 5 | 5 | $instance_info{private_method} = 1; | |||
| 11332 | 5 | 9 | $instance_info{confidence} = 'low' unless exists $instance_info{confidence}; | |||
| 11333 | } | |||||
| 11334 | ||||||
| 11335 | 450 | 478 | return \%instance_info if keys %instance_info; | |||
| 11336 | 234 | 214 | 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 | 208 | 10358 | my ($self, $current_package, $method_body) = @_; | |||
| 11366 | ||||||
| 11367 | 208 | 167 | my $doc = $self->{_document}; | |||
| 11368 | 208 | 242 | return undef unless $doc; | |||
| 11369 | ||||||
| 11370 | 207 | 153 | 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 | 207 | 219 | my $includes = $doc->find('PPI::Statement::Include') || []; | |||
| 11377 | 207 | 686530 | foreach my $inc (@$includes) { | |||
| 11378 | 364 | 292 | my $content = $inc->content; | |||
| 11379 | 364 | 2757 | if ($content =~ /use\s+(parent|base)\s+['"]?([\w:]+)['"]?/) { | |||
| 11380 | 4 | 5 | push @parent_classes, $2; | |||
| 11381 | 4 | 6 | $inheritance_info{parent_statements} = \@parent_classes; | |||
| 11382 | } | |||||
| 11383 | # Also check for multiple parents: use parent qw(Class1 Class2) | |||||
| 11384 | 364 | 401 | if ($content =~ /use\s+(parent|base)\s+qw?[\(\[]?(.+?)[\)\]]?;/) { | |||
| 11385 | 0 | 0 | my $parents = $2; | |||
| 11386 | 0 | 0 | my @multi_parents = split /\s+/, $parents; | |||
| 11387 | 0 | 0 | push @parent_classes, @multi_parents; | |||
| 11388 | 0 | 0 | $inheritance_info{parent_statements} = \@parent_classes; | |||
| 11389 | } | |||||
| 11390 | } | |||||
| 11391 | ||||||
| 11392 | # 2. Look for @ISA assignments (with or without 'our') | |||||
| 11393 | 207 | 211 | my $isas = $doc->find('PPI::Statement::Variable') || []; | |||
| 11394 | 207 | 685131 | foreach my $isa (@$isas) { | |||
| 11395 | 1403 | 947 | my $content = $isa->content(); | |||
| 11396 | # Match both "our @ISA = qw(...)" and "@ISA = qw(...)" | |||||
| 11397 | 1403 | 27042 | if ($content =~ /(?:our\s+)?\@ISA\s*=\s*qw?[\(\[]?(.+?)[\)\]]?/) { | |||
| 11398 | 0 | 0 | my $parents = $1; | |||
| 11399 | 0 | 0 | my @isa_parents = split(/\s+/, $parents); | |||
| 11400 | 0 | 0 | push @parent_classes, @isa_parents; | |||
| 11401 | 0 | 0 | $inheritance_info{isa_array} = \@isa_parents; | |||
| 11402 | } | |||||
| 11403 | } | |||||
| 11404 | ||||||
| 11405 | # Also look for @ISA in regular statements | |||||
| 11406 | 207 | 215 | my $statements = $doc->find('PPI::Statement') || []; | |||
| 11407 | 207 | 685032 | foreach my $stmt (@$statements) { | |||
| 11408 | 8970 | 5334 | my $content = $stmt->content; | |||
| 11409 | 8970 | 175873 | if ($content =~ /\@ISA\s*=\s*qw?[\(\[]?(.+?)[\)\]]?/) { | |||
| 11410 | 1 | 2 | my $parents = $1; | |||
| 11411 | 1 | 1 | my @isa_parents = split(/\s+/, $parents); | |||
| 11412 | 1 | 1 | push @parent_classes, @isa_parents; | |||
| 11413 | 1 | 1 | $inheritance_info{isa_array} = \@isa_parents; | |||
| 11414 | } | |||||
| 11415 | } | |||||
| 11416 | ||||||
| 11417 | # 3. Check if method uses SUPER:: calls | |||||
| 11418 | 207 | 496 | if ($method_body && $method_body =~ /SUPER::/) { | |||
| 11419 | 2 | 3 | $inheritance_info{uses_super} = 1; | |||
| 11420 | 2 | 5 | if ($method_body =~ /SUPER::new/) { | |||
| 11421 | 0 | 0 | $inheritance_info{calls_super_new} = 1; | |||
| 11422 | } | |||||
| 11423 | } | |||||
| 11424 | ||||||
| 11425 | # 4. Check if current package has its own new method | |||||
| 11426 | my $has_own_new = $doc->find(sub { | |||||
| 11427 | 87108 | 296006 | $_[1]->isa('PPI::Statement::Sub') && | |||
| 11428 | $_[1]->name eq 'new' | |||||
| 11429 | 207 | 422 | }); | |||
| 11430 | ||||||
| 11431 | 207 | 1081 | if ($has_own_new) { | |||
| 11432 | 59 | 77 | $inheritance_info{has_own_constructor} = 1; | |||
| 11433 | } elsif (@parent_classes) { | |||||
| 11434 | # No own constructor, but has parents - might need parent constructor | |||||
| 11435 | 1 | 2 | $inheritance_info{use_parent_constructor} = 1; | |||
| 11436 | 1 | 2 | $inheritance_info{parent_class} = $parent_classes[0]; # Use first parent | |||
| 11437 | } | |||||
| 11438 | ||||||
| 11439 | 207 | 324 | return \%inheritance_info if keys %inheritance_info; | |||
| 11440 | 147 | 297 | 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 | 209 | 12923 | my ($self, $current_package, $target_package) = @_; | |||
| 11471 | ||||||
| 11472 | 209 | 184 | my $doc = $self->{_document}; | |||
| 11473 | 209 | 245 | 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 | 209 | 226 | if ($target_package ne $current_package) { | |||
| 11478 | return { | |||||
| 11479 | 1 | 9 | 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 | my $new_method = $doc->find_first(sub { | |||||
| 11487 | 64064 | 214701 | $_[1]->isa('PPI::Statement::Sub') && | |||
| 11488 | $_[1]->name eq 'new' | |||||
| 11489 | 208 | 351 | }); | |||
| 11490 | ||||||
| 11491 | 208 | 1918 | return undef unless $new_method; | |||
| 11492 | ||||||
| 11493 | 60 | 48 | my %requirements; | |||
| 11494 | ||||||
| 11495 | # Get method body | |||||
| 11496 | 60 | 62 | my $body = $new_method->content; | |||
| 11497 | ||||||
| 11498 | # Look for parameter extraction patterns - handle both $self and $class | |||||
| 11499 | 60 | 5298 | if ($body =~ /my\s*\(\s*\$(self|class)\s*,\s*(.+?)\)\s*=\s*\@_/s) { | |||
| 11500 | 49 | 59 | my $params = $2; | |||
| 11501 | 49 | 60 | my @param_names = $params =~ /\$(\w+)/g; | |||
| 11502 | ||||||
| 11503 | 49 | 56 | if (@param_names) { | |||
| 11504 | 3 | 5 | $requirements{parameters} = \@param_names; | |||
| 11505 | 3 | 5 | $requirements{parameter_count} = scalar @param_names; | |||
| 11506 | } | |||||
| 11507 | } | |||||
| 11508 | ||||||
| 11509 | # Look for shift patterns | |||||
| 11510 | 60 | 46 | my @shift_params; | |||
| 11511 | 60 | 97 | while ($body =~ /my\s+\$(\w+)\s*=\s*shift/g) { | |||
| 11512 | 1 | 2 | push @shift_params, $1; | |||
| 11513 | } | |||||
| 11514 | # Remove $self or $class if present | |||||
| 11515 | 60 1 | 62 3 | @shift_params = grep { $_ !~ /^(self|class|pkg|proto|klass)$/i } @shift_params; | |||
| 11516 | ||||||
| 11517 | 60 | 63 | if (@shift_params) { | |||
| 11518 | 0 | 0 | $requirements{parameters} = \@shift_params; | |||
| 11519 | 0 | 0 | $requirements{parameter_count} = scalar @shift_params; | |||
| 11520 | 0 | 0 | $requirements{shift_pattern} = 1; | |||
| 11521 | } | |||||
| 11522 | ||||||
| 11523 | # Look for validation of parameters (more flexible pattern) | |||||
| 11524 | 60 | 46 | my @required_params; | |||
| 11525 | 60 | 119 | if ($body =~ /croak.*unless.*(?:defined\s+)?\$(\w+)/g) { | |||
| 11526 | 9 | 11 | push @required_params, $1; | |||
| 11527 | } | |||||
| 11528 | 60 | 126 | if ($body =~ /die.*unless.*(?:defined\s+)?\$(\w+)/g) { | |||
| 11529 | 1 | 1 | push @required_params, $1; | |||
| 11530 | } | |||||
| 11531 | ||||||
| 11532 | 60 | 56 | if (@required_params) { | |||
| 11533 | 10 | 16 | $requirements{required_parameters} = \@required_params; | |||
| 11534 | } | |||||
| 11535 | ||||||
| 11536 | # Look for default values (optional parameters) | |||||
| 11537 | 60 | 53 | 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 | 60 | 79 | if ($requirements{parameters}) { | |||
| 11543 | 3 3 | 1 3 | foreach my $param (@{$requirements{parameters}}) { | |||
| 11544 | 5 | 8 | my $default = $self->_extract_default_value($param, $body); | |||
| 11545 | 5 | 5 | if (defined $default) { | |||
| 11546 | 2 | 2 | push @optional_params, $param; | |||
| 11547 | 2 | 3 | $default_values{$param} = $default; | |||
| 11548 | } | |||||
| 11549 | } | |||||
| 11550 | } | |||||
| 11551 | ||||||
| 11552 | 60 | 51 | if (@optional_params) { | |||
| 11553 | 2 | 3 | $requirements{optional_parameters} = \@optional_params; | |||
| 11554 | 2 | 2 | $requirements{default_values} = \%default_values; | |||
| 11555 | } | |||||
| 11556 | ||||||
| 11557 | 60 | 75 | return \%requirements if keys %requirements; | |||
| 11558 | 50 | 66 | 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 | 243 | 4012 | my ($self, $method_body) = @_; | |||
| 11587 | ||||||
| 11588 | 243 | 225 | return undef unless $method_body; | |||
| 11589 | ||||||
| 11590 | 242 | 173 | my %dependency_info; | |||
| 11591 | ||||||
| 11592 | # Pattern 1: Creates objects of other classes with ->new() or ->create() | |||||
| 11593 | # Reset pos for global match | |||||
| 11594 | 242 | 253 | pos($method_body) = 0; | |||
| 11595 | 242 | 535 | while ($method_body =~ /(\w+(?:::\w+)*)->(?:new|create)\(/g) { | |||
| 11596 | 5 | 6 | my $class = $1; | |||
| 11597 | 5 | 15 | next if $class eq 'main' || $class eq '__PACKAGE__' || $class =~ /^\$/; | |||
| 11598 | 4 4 | 3 14 | push @{$dependency_info{creates_objects}}, $class; | |||
| 11599 | } | |||||
| 11600 | ||||||
| 11601 | 242 | 252 | if ($dependency_info{creates_objects}) { | |||
| 11602 | # Remove duplicates | |||||
| 11603 | 3 | 3 | my %seen; | |||
| 11604 | 3 4 3 | 2 8 3 | $dependency_info{creates_objects} = [grep { !$seen{$_}++ } @{$dependency_info{creates_objects}}]; | |||
| 11605 | 3 | 5 | $dependency_info{package} = $dependency_info{creates_objects}[0]; | |||
| 11606 | } | |||||
| 11607 | ||||||
| 11608 | # Pattern 2: Calls methods on objects from other classes | |||||
| 11609 | 242 | 298 | if ($method_body =~ /\$(\w+)->\w+\(/) { | |||
| 11610 | 4 | 3 | 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 | 4 | 5 | pos($method_body) = 0; | |||
| 11615 | 4 | 13 | while ($method_body =~ /\$(\w+)->\w+\(/g) { | |||
| 11616 | 5 | 7 | $object_vars{$1}++; | |||
| 11617 | } | |||||
| 11618 | ||||||
| 11619 | # Try to determine type of object variables | |||||
| 11620 | 4 | 3 | my @object_classes; | |||
| 11621 | 4 | 5 | foreach my $var (keys %object_vars) { | |||
| 11622 | # Look for type declarations or assignments | |||||
| 11623 | 5 | 187 | if ($method_body =~ /my\s+\$$var\s*=\s*(\w+(?:::\w+)+)->(?:new|create)/) { | |||
| 11624 | 3 | 6 | push @object_classes, $1; | |||
| 11625 | } elsif ($method_body =~ /my\s+\$$var\s*=\s*(\w+(?:::\w+)+)->/) { | |||||
| 11626 | 0 | 0 | push @object_classes, $1; | |||
| 11627 | } | |||||
| 11628 | } | |||||
| 11629 | ||||||
| 11630 | 4 | 6 | if (@object_classes) { | |||
| 11631 | 3 | 4 | $dependency_info{uses_objects} = \@object_classes; | |||
| 11632 | 3 | 4 | $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 | 242 | 249 | return \%dependency_info if keys %dependency_info; | |||
| 11640 | 238 | 204 | 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 | 2 | 2587 | my $self = $_[0]; | |||
| 11660 | ||||||
| 11661 | 2 | 3 | my $doc = $self->{_document}; | |||
| 11662 | 2 | 3 | return unless $doc; | |||
| 11663 | ||||||
| 11664 | # Look for use parent statements | |||||
| 11665 | my $parent_stmt = $doc->find_first(sub { | |||||
| 11666 | 68 | 285 | $_[1]->isa('PPI::Statement::Include') && | |||
| 11667 | $_[1]->type eq 'use' && | |||||
| 11668 | $_[1]->module =~ /^(parent|base)$/ && | |||||
| 11669 | $_[1]->arguments =~ /['"](\w+(?:::\w+)*)['"]/ | |||||
| 11670 | 2 | 4 | }); | |||
| 11671 | 2 | 11 | if ($parent_stmt) { | |||
| 11672 | 0 | 0 | my $parent = $1; | |||
| 11673 | 0 | 0 | return $parent; | |||
| 11674 | } | |||||
| 11675 | ||||||
| 11676 | # Look for @ISA assignment | |||||
| 11677 | my $isa_stmt = $doc->find_first(sub { | |||||
| 11678 | 68 | 315 | $_[1]->isa('PPI::Statement') && | |||
| 11679 | $_[1]->content =~ /our\s+\@ISA\s*=\s*\(\s*['"](\w+(?:::\w+)*)['"]\s*\)/ | |||||
| 11680 | 2 | 5 | }); | |||
| 11681 | 2 | 9 | if ($isa_stmt && $isa_stmt->content =~ /['"](\w+(?:::\w+)*)['"]/) { | |||
| 11682 | 0 | 0 | return $1; | |||
| 11683 | } | |||||
| 11684 | ||||||
| 11685 | 2 | 2 | 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 | 2 | 2393 | my $self = $_[0]; | |||
| 11711 | ||||||
| 11712 | # Get the current package | |||||
| 11713 | 2 | 2 | my $doc = $self->{_document}; | |||
| 11714 | 2 | 3 | my $package_stmt = $doc->find_first('PPI::Statement::Package'); | |||
| 11715 | 2 | 295 | return 'UNKNOWN_PACKAGE' unless $package_stmt; | |||
| 11716 | 1 | 2 | my $package_name = $package_stmt->namespace; | |||
| 11717 | 1 | 10 | $self->{_package_name} //= $package_name; | |||
| 11718 | ||||||
| 11719 | # Check if the current package has a 'new' method | |||||
| 11720 | my $has_new = $doc->find(sub { | |||||
| 11721 | 46 | 193 | $_[1]->isa('PPI::Statement::Sub') && $_[1]->name eq 'new' | |||
| 11722 | 1 | 3 | }); | |||
| 11723 | ||||||
| 11724 | 1 | 6 | if ($has_new) { | |||
| 11725 | 1 | 1 | return $package_name; | |||
| 11726 | } | |||||
| 11727 | ||||||
| 11728 | # Otherwise, try to get the parent class | |||||
| 11729 | 0 | 0 | my $parent = $self->_get_parent_class(); | |||
| 11730 | 0 | 0 | return $parent if $parent; | |||
| 11731 | ||||||
| 11732 | # Fallback to current package | |||||
| 11733 | 0 | 0 | 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 | 376 | 8856 | my ($self, $param, $code) = @_; | |||
| 11765 | ||||||
| 11766 | 376 | 580 | return undef unless $param && $code; | |||
| 11767 | ||||||
| 11768 | # Clean up the code for easier pattern matching | |||||
| 11769 | # Remove comments to avoid false positives | |||||
| 11770 | 373 | 284 | my $clean_code = $code; | |||
| 11771 | 373 | 333 | $clean_code =~ s/#.*$//gm; | |||
| 11772 | 373 | 3441 | $clean_code =~ s/^\s+|\s+$//g; | |||
| 11773 | ||||||
| 11774 | # Pattern 1: $param = $param || 'default_value' | |||||
| 11775 | # Also handles: $param = $arg || 'default' | |||||
| 11776 | 373 | 8613 | if ($clean_code =~ /\$$param\s*=\s*(?:\$$param|\$[a-zA-Z_]\w*)\s*\|\|\s*([^;]+)/) { | |||
| 11777 | 12 | 13 | my $default = $1; | |||
| 11778 | 12 | 11 | $default =~ s/\s*;\s*$//; | |||
| 11779 | 12 | 14 | $default = $self->_clean_default_value($default); | |||
| 11780 | 12 | 23 | return $default if defined $default; | |||
| 11781 | } | |||||
| 11782 | ||||||
| 11783 | # Pattern 2: $param //= 'default_value' | |||||
| 11784 | 361 | 3261 | if ($clean_code =~ /\$$param\s*\/\/=\s*([^;]+)/) { | |||
| 11785 | 10 | 12 | my $default = $1; | |||
| 11786 | 10 | 9 | $default =~ s/\s*;\s*$//; | |||
| 11787 | 10 | 15 | $default = $self->_clean_default_value($default); | |||
| 11788 | 10 | 20 | return $default if defined $default; | |||
| 11789 | } | |||||
| 11790 | ||||||
| 11791 | # Pattern 3: $param = defined $param ? $param : 'default' | |||||
| 11792 | # Also handles: $param = defined $arg ? $arg : 'default' | |||||
| 11793 | 352 | 11958 | if ($clean_code =~ /\$$param\s*=\s*defined\s+(?:\$$param|\$[a-zA-Z_]\w*)\s*\?\s*(?:\$$param|\$[a-zA-Z_]\w*)\s*:\s*([^;]+)/) { | |||
| 11794 | 6 | 6 | my $default = $1; | |||
| 11795 | 6 | 5 | $default =~ s/\s*;\s*$//; | |||
| 11796 | 6 | 7 | $default = $self->_clean_default_value($default); | |||
| 11797 | 6 | 13 | return $default if defined $default; | |||
| 11798 | } | |||||
| 11799 | ||||||
| 11800 | # Pattern 4: $param = 'default' unless defined $param; | |||||
| 11801 | 346 | 7990 | if ($clean_code =~ /\$$param\s*=\s*([^;]+?)\s+unless\s+defined\s+(?:\$$param|\$[a-zA-Z_]\w*)/) { | |||
| 11802 | 3 | 4 | my $default = $1; | |||
| 11803 | 3 | 3 | $default = $self->_clean_default_value($default); | |||
| 11804 | 3 | 7 | return $default if defined $default; | |||
| 11805 | } | |||||
| 11806 | ||||||
| 11807 | # Pattern 5: $param ||= 'default' | |||||
| 11808 | 343 | 3041 | if ($clean_code =~ /\$$param\s*\|\|=\s*([^;]+)/) { | |||
| 11809 | 5 | 5 | my $default = $1; | |||
| 11810 | 5 | 9 | $default =~ s/\s*;\s*$//; | |||
| 11811 | 5 | 9 | $default = $self->_clean_default_value($default); | |||
| 11812 | 5 | 14 | return $default if defined $default; | |||
| 11813 | } | |||||
| 11814 | ||||||
| 11815 | # Pattern 6: $param = $arg // 'default' | |||||
| 11816 | 338 | 6790 | if ($clean_code =~ /\$$param\s*=\s*(?:\$$param|\$[a-zA-Z_]\w*)\s*\/\/\s*([^;]+)/) { | |||
| 11817 | 2 | 3 | my $default = $1; | |||
| 11818 | 2 | 3 | $default =~ s/\s*;\s*$//; | |||
| 11819 | 2 | 2 | $default = $self->_clean_default_value($default); | |||
| 11820 | 2 | 3 | return $default if defined $default; | |||
| 11821 | } | |||||
| 11822 | ||||||
| 11823 | # Pattern 7: Multi-line: if (!defined $param) { $param = 'default'; } | |||||
| 11824 | 337 | 6827 | if ($clean_code =~ /if\s*\(\s*!defined\s+\$$param\s*\)\s*\{[^}]*\$$param\s*=\s*([^;]+)/s) { | |||
| 11825 | 1 | 1 | my $default = $1; | |||
| 11826 | 1 | 1 | $default =~ s/\s*;\s*$//; | |||
| 11827 | 1 | 1 | $default = $self->_clean_default_value($default); | |||
| 11828 | 1 | 4 | return $default if defined $default; | |||
| 11829 | } | |||||
| 11830 | ||||||
| 11831 | # Pattern 8: unless (defined $param) { $param = 'default'; } | |||||
| 11832 | 336 | 6684 | if ($clean_code =~ /unless\s*\(\s*defined\s+\$$param\s*\)\s*\{[^}]*\$$param\s*=\s*([^;]+)/s) { | |||
| 11833 | 1 | 1 | my $default = $1; | |||
| 11834 | 1 | 2 | $default =~ s/\s*;\s*$//; | |||
| 11835 | 1 | 1 | $default = $self->_clean_default_value($default); | |||
| 11836 | 1 | 3 | return $default if defined $default; | |||
| 11837 | } | |||||
| 11838 | ||||||
| 11839 | 335 | 664 | 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 | 476 | 412 | my ($self, $method, $schema) = @_; | |||
| 11864 | ||||||
| 11865 | 476 | 878 | my %hints = ( | |||
| 11866 | boundary_values => [], | |||||
| 11867 | invalid_inputs => [], | |||||
| 11868 | equivalence_classes => [], | |||||
| 11869 | valid_inputs => [], | |||||
| 11870 | ); | |||||
| 11871 | ||||||
| 11872 | 476 | 387 | my $code = $method->{body}; | |||
| 11873 | 476 | 417 | return {} unless $code; | |||
| 11874 | ||||||
| 11875 | 475 | 714 | $self->_extract_invalid_input_hints($code, \%hints); | |||
| 11876 | 475 | 622 | $self->_extract_boundary_value_hints($code, \%hints); | |||
| 11877 | ||||||
| 11878 | # prune empties | |||||
| 11879 | 475 | 569 | for my $k (keys %hints) { | |||
| 11880 | 1900 1900 | 843 1609 | delete $hints{$k} unless @{$hints{$k}}; | |||
| 11881 | } | |||||
| 11882 | ||||||
| 11883 | 475 | 459 | 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 | 482 | 874 | my ($self, $code, $hints) = @_; | |||
| 11905 | ||||||
| 11906 | # undef invalid | |||||
| 11907 | 482 | 638 | if ($code =~ /defined\s*\(\s*\$/) { | |||
| 11908 | 31 31 | 26 41 | push @{ $hints->{invalid_inputs} }, 'undef'; | |||
| 11909 | } | |||||
| 11910 | ||||||
| 11911 | # empty string invalid | |||||
| 11912 | 482 | 958 | if ($code =~ /\beq\s*''/ || $code =~ /\blength\s*\(/) { | |||
| 11913 | 28 28 | 74 31 | push @{ $hints->{invalid_inputs} }, ''; | |||
| 11914 | } | |||||
| 11915 | ||||||
| 11916 | # negative number invalid | |||||
| 11917 | 482 | 624 | if ($code =~ /\$\w+\s*<\s*0/) { | |||
| 11918 | 8 8 | 7 11 | 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 | 480 | 849 | my ($self, $code, $hints) = @_; | |||
| 11941 | ||||||
| 11942 | 480 | 1090 | while ($code =~ /\$\w+\s*(<=|<|>=|>)\s*(\d+)/g) { | |||
| 11943 | 38 | 56 | my ($op, $n) = ($1, $2); | |||
| 11944 | ||||||
| 11945 | 38 | 77 | if ($op eq '<') { | |||
| 11946 | 13 13 | 22 30 | push @{ $hints->{boundary_values} }, $n, $n+1; | |||
| 11947 | } elsif ($op eq '<=') { | |||||
| 11948 | 5 5 | 5 10 | push @{ $hints->{boundary_values} }, $n, $n+1; | |||
| 11949 | } elsif ($op eq '>') { | |||||
| 11950 | 15 15 | 13 34 | push @{ $hints->{boundary_values} }, $n, $n-1; | |||
| 11951 | } elsif ($op eq '>=') { | |||||
| 11952 | 5 5 | 7 12 | push @{ $hints->{boundary_values} }, $n, $n-1; | |||
| 11953 | } | |||||
| 11954 | } | |||||
| 11955 | ||||||
| 11956 | # Remove duplicates | |||||
| 11957 | 480 | 309 | my %seen; | |||
| 11958 | 480 76 480 | 311 117 656 | $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 | 479 | 414 | my ($self, $pod, $hints) = @_; | |||
| 11984 | ||||||
| 11985 | 479 | 398 | return $hints unless $pod; | |||
| 11986 | ||||||
| 11987 | 244 | 157 | my @examples; | |||
| 11988 | ||||||
| 11989 | # Accept both =head1 SYNOPSIS (module-level) and =head2 SYNOPSIS (method-level) | |||||
| 11990 | 244 | 189 | my $synopsis = ''; | |||
| 11991 | 244 | 338 | if($pod =~ /=head[12]\s+SYNOPSIS\s*(.+?)(?=\n=head|\z)/s) { | |||
| 11992 | 5 | 6 | $synopsis = $1; | |||
| 11993 | } | |||||
| 11994 | ||||||
| 11995 | # Also collect =for example begin ... =for example end blocks | |||||
| 11996 | 244 | 137 | my @for_blocks; | |||
| 11997 | 244 | 353 | while($pod =~ /=for\s+example\s+begin(.+?)=for\s+example\s+end/sg) { | |||
| 11998 | 1 | 2 | push @for_blocks, $1; | |||
| 11999 | } | |||||
| 12000 | 244 | 280 | $synopsis .= join('', @for_blocks); | |||
| 12001 | ||||||
| 12002 | 244 | 307 | return $hints unless length($synopsis); | |||
| 12003 | ||||||
| 12004 | # Constructor examples: ->wilma(foo => 'bar', count => 5) | |||||
| 12005 | 6 | 21 | while ($synopsis =~ /->([a-z_0-9A-Z]+)\s*\(\s*(.*?)\s*\)/sg) { | |||
| 12006 | 6 | 8 | my ($method, $args) = ($1, $2); | |||
| 12007 | 6 | 4 | my %kv; | |||
| 12008 | ||||||
| 12009 | 6 | 14 | while ($args =~ /(\w+)\s*=>\s*(?:'([^']*)'|"([^"]*)"|(\d+))/g) { | |||
| 12010 | 10 | 7 | my $key = $1; | |||
| 12011 | 10 | 21 | my $val = defined $2 ? $2 : defined $3 ? $3 : $4; | |||
| 12012 | 10 | 15 | $kv{$key} = $val; | |||
| 12013 | } | |||||
| 12014 | ||||||
| 12015 | 6 | 14 | 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 | 6 | 4 | unless(scalar(@examples)) { | |||
| 12024 | # Positional calls: func($a, $b) | |||||
| 12025 | 1 | 4 | while ($synopsis =~ /\b(\w+)\s*\(\s*(.*?)\s*\)/sg) { | |||
| 12026 | 1 | 2 | my ($func, $argstr) = ($1, $2); | |||
| 12027 | ||||||
| 12028 | # next if $func eq 'new'; # already handled | |||||
| 12029 | ||||||
| 12030 | 1 2 | 3 4 | my @args = map { s/^\s+|\s+$//gr } split /\s*,\s*/, $argstr; | |||
| 12031 | ||||||
| 12032 | 1 | 1 | next unless @args; | |||
| 12033 | ||||||
| 12034 | 1 | 3 | push @examples, { | |||
| 12035 | style => 'positional', | |||||
| 12036 | source => 'pod', | |||||
| 12037 | function => $func, | |||||
| 12038 | args => \@args, | |||||
| 12039 | }; | |||||
| 12040 | } | |||||
| 12041 | } | |||||
| 12042 | ||||||
| 12043 | 6 | 6 | if (scalar(@examples)) { | |||
| 12044 | 6 | 9 | $hints->{valid_inputs} ||= []; | |||
| 12045 | 6 6 | 4 4 | push @{ $hints->{valid_inputs} }, @examples; | |||
| 12046 | ||||||
| 12047 | 6 | 10 | $self->_log(" POD: extracted " . scalar(@examples) . " example call(s)"); | |||
| 12048 | } | |||||
| 12049 | ||||||
| 12050 | 6 | 7 | for my $k (qw(boundary_values invalid_inputs valid_inputs equivalence_classes)) { | |||
| 12051 | 24 | 21 | $hints->{$k} //= []; | |||
| 12052 | } | |||||
| 12053 | ||||||
| 12054 | 6 | 7 | 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 | 185 | 165 | my ($self, $value, $from_code) = @_; | |||
| 12087 | ||||||
| 12088 | 185 | 163 | return unless defined $value; | |||
| 12089 | ||||||
| 12090 | # Remove leading/trailing whitespace | |||||
| 12091 | 183 | 270 | $value =~ s/^\s+|\s+$//g; | |||
| 12092 | ||||||
| 12093 | # Remove parenthetical notes like "(no password)" only if there's content before them | |||||
| 12094 | 183 | 132 | $value =~ s/(\S+)\s*\([^)]+\)\s*$/$1/; | |||
| 12095 | 183 | 207 | $value =~ s/^\s+|\s+$//g; | |||
| 12096 | ||||||
| 12097 | # Handle chained || or // operators - extract the rightmost value | |||||
| 12098 | 183 | 288 | if ($value =~ /\|\||\/{2}/) { | |||
| 12099 | 7 | 22 | my @parts = split(/\s*(?:\|\||\/{2})\s*/, $value); | |||
| 12100 | 7 | 6 | $value = $parts[-1]; | |||
| 12101 | 7 | 8 | $value =~ s/^\s+|\s+$//g; | |||
| 12102 | } | |||||
| 12103 | ||||||
| 12104 | # Remove trailing semicolon if present | |||||
| 12105 | 183 | 143 | $value =~ s/;\s*$//; | |||
| 12106 | ||||||
| 12107 | # Handle q{}, qq{}, qw{} quotes | |||||
| 12108 | 183 | 277 | if ($value =~ /^qq?\{(.*?)\}$/s) { | |||
| 12109 | 3 | 2 | $value = $1; | |||
| 12110 | } elsif ($value =~ /^qw\{(.*?)\}$/s) { | |||||
| 12111 | 0 | 0 | $value = $1; | |||
| 12112 | } elsif ($value =~ /^q[qwx]?\s*([^a-zA-Z0-9\{\[])(.*?)\1$/s) { | |||||
| 12113 | 0 | 0 | $value = $2; | |||
| 12114 | } | |||||
| 12115 | ||||||
| 12116 | # Handle quoted strings | |||||
| 12117 | 183 | 220 | if ($value =~ /^(['"])(.*)\1$/s) { | |||
| 12118 | 50 | 42 | $value = $2; | |||
| 12119 | ||||||
| 12120 | 50 | 39 | 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 | 18 | 14 | $value =~ s/\\\\/\\/g; | |||
| 12124 | } | |||||
| 12125 | ||||||
| 12126 | # Only unescape the quote characters themselves | |||||
| 12127 | 50 | 43 | $value =~ s/\\"/"/g; | |||
| 12128 | 50 | 27 | $value =~ s/\\'/'/g; | |||
| 12129 | ||||||
| 12130 | # If NOT from code (i.e., from POD), interpret escape sequences | |||||
| 12131 | 50 | 41 | unless ($from_code) { | |||
| 12132 | 32 | 23 | $value =~ s/\\n/\n/g; | |||
| 12133 | 32 | 20 | $value =~ s/\\r/\r/g; | |||
| 12134 | 32 | 32 | $value =~ s/\\t/\t/g; | |||
| 12135 | 32 | 21 | $value =~ s/\\\\/\\/g; | |||
| 12136 | } | |||||
| 12137 | } | |||||
| 12138 | ||||||
| 12139 | # Sometimes trailing ) is left on | |||||
| 12140 | 183 | 163 | if($value !~ /^\(/) { | |||
| 12141 | 181 | 125 | $value =~ s/\)$//; | |||
| 12142 | } | |||||
| 12143 | ||||||
| 12144 | # Handle Perl empty hash (must be before numeric/boolean checks) | |||||
| 12145 | 183 | 148 | if ($value =~ /^\{\s*\}$/) { | |||
| 12146 | 6 | 7 | return {}; | |||
| 12147 | } | |||||
| 12148 | ||||||
| 12149 | # Handle Perl empty list/array | |||||
| 12150 | 177 | 153 | if ($value =~ /^\[\s*\]$/) { | |||
| 12151 | 6 | 7 | return []; | |||
| 12152 | } | |||||
| 12153 | ||||||
| 12154 | # Handle numeric values | |||||
| 12155 | 171 | 218 | if ($value =~ /^-?\d+(?:\.\d+)?$/) { | |||
| 12156 | 68 | 67 | if ($value =~ /\./) { | |||
| 12157 | 11 | 26 | return $value + 0; | |||
| 12158 | } else { | |||||
| 12159 | 57 | 88 | return int($value); | |||
| 12160 | } | |||||
| 12161 | } | |||||
| 12162 | ||||||
| 12163 | # Handle boolean keywords | |||||
| 12164 | 103 | 134 | if ($value =~ /^(true|false)$/i) { | |||
| 12165 | 9 | 21 | return lc($1) eq 'true' ? 1 : 0; | |||
| 12166 | } | |||||
| 12167 | ||||||
| 12168 | # Handle Perl boolean constants | |||||
| 12169 | 94 | 113 | if ($value eq '1') { | |||
| 12170 | 0 | 0 | return 1; | |||
| 12171 | } elsif ($value eq '0') { | |||||
| 12172 | 0 | 0 | return 0; | |||
| 12173 | } | |||||
| 12174 | ||||||
| 12175 | # Handle undef | |||||
| 12176 | 94 | 91 | if ($value eq 'undef') { | |||
| 12177 | 12 | 15 | return undef; | |||
| 12178 | } | |||||
| 12179 | ||||||
| 12180 | # Handle __PACKAGE__ and similar constants | |||||
| 12181 | 82 | 67 | if ($value eq '__PACKAGE__') { | |||
| 12182 | 1 | 1 | return '__PACKAGE__'; | |||
| 12183 | } | |||||
| 12184 | ||||||
| 12185 | # Remove surrounding parentheses | |||||
| 12186 | 81 | 69 | $value =~ s/^\((.+)\)$/$1/; | |||
| 12187 | ||||||
| 12188 | # Handle expressions we can't evaluate | |||||
| 12189 | 81 | 155 | if ($value =~ /^\$[a-zA-Z_]/ || $value =~ /\(.*\)/) { | |||
| 12190 | 5 | 16 | return if($value =~ /^\$|\@|\%/); # The default is a value, so who knows its type? | |||
| 12191 | # return $value; | |||||
| 12192 | } | |||||
| 12193 | ||||||
| 12194 | 80 | 116 | 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 | 75 | 1035 | my ($self, $pod_params, $code_params, $method_name) = @_; | |||
| 12229 | ||||||
| 12230 | 75 | 55 | my @errors; | |||
| 12231 | ||||||
| 12232 | # Get all parameter names from both sources | |||||
| 12233 | 75 141 | 117 171 | my %all_params = map { $_ => 1 } (keys %$pod_params, keys %$code_params); | |||
| 12234 | ||||||
| 12235 | 75 | 135 | foreach my $param (sort keys %all_params) { | |||
| 12236 | 84 | 120 | my $pod = $pod_params->{$param} || {}; | |||
| 12237 | 84 | 115 | 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 | 84 | 178 | unless(($pod->{_source} // '') eq SOURCE_INPUT_SPEC) { | |||
| 12245 | # Check if parameter exists in both | |||||
| 12246 | 39 | 67 | if (exists $pod_params->{$param} && !exists $code_params->{$param}) { | |||
| 12247 | 3 | 4 | push @errors, "Parameter '\$$param' documented in POD but not found in code signature"; | |||
| 12248 | 3 | 3 | next; | |||
| 12249 | } | |||||
| 12250 | ||||||
| 12251 | 36 | 56 | if(!exists $pod_params->{$param} && exists $code_params->{$param}) { | |||
| 12252 | 20 | 28 | if($param =~ /^(class|pkg|proto|klass)$/i) { | |||
| 12253 | # class invocant, not a user-facing parameter | |||||
| 12254 | 1 | 1 | next; | |||
| 12255 | } | |||||
| 12256 | 19 | 23 | if($param eq 'self') { | |||
| 12257 | # instance invocant, not a user-facing parameter | |||||
| 12258 | 1 | 1 | next; | |||
| 12259 | } | |||||
| 12260 | 18 | 19 | push @errors, "Parameter '\$$param' found in code but not documented in POD"; | |||
| 12261 | 18 | 19 | next; | |||
| 12262 | } | |||||
| 12263 | ||||||
| 12264 | # Compare types if both exist | |||||
| 12265 | 16 | 50 | if ($pod->{type} && $code->{type} && $pod->{type} ne $code->{type}) { | |||
| 12266 | 3 | 6 | if (!$self->_types_are_compatible($pod->{type}, $code->{type})) { | |||
| 12267 | 1 | 3 | push @errors, "Type mismatch for '\$$param': POD says '$pod->{type}', code suggests '$code->{type}' (incompatible)"; | |||
| 12268 | } else { | |||||
| 12269 | 2 | 4 | 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 | 16 | 30 | if (exists $pod->{optional} && exists $code->{optional} && | |||
| 12275 | $pod->{optional} != $code->{optional}) { | |||||
| 12276 | 2 | 3 | my $pod_status = $pod->{optional} ? 'optional' : 'required'; | |||
| 12277 | 2 | 3 | my $code_status = $code->{optional} ? 'optional' : 'required'; | |||
| 12278 | 2 | 3 | push @errors, "Optional status mismatch for '\$$param': POD says '$pod_status', code suggests '$code_status'"; | |||
| 12279 | } | |||||
| 12280 | ||||||
| 12281 | # Check regex patterns | |||||
| 12282 | 16 | 28 | if ($pod->{matches} && $code->{matches} && $pod->{matches} ne $code->{matches}) { | |||
| 12283 | 0 | 0 | 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 | 61 | 161 | if (defined $pod->{min} && defined $code->{min} && $pod->{min} != $code->{min}) { | |||
| 12289 | 2 | 4 | push @errors, "Min constraint mismatch for '\$$param': POD says '$pod->{min}', code suggests '$code->{min}'"; | |||
| 12290 | } | |||||
| 12291 | ||||||
| 12292 | 61 | 120 | if (defined $pod->{max} && defined $code->{max} && $pod->{max} != $code->{max}) { | |||
| 12293 | 1 | 3 | push @errors, "Max constraint mismatch for '\$$param': POD says '$pod->{max}', code suggests '$code->{max}'"; | |||
| 12294 | } | |||||
| 12295 | ||||||
| 12296 | 61 | 128 | if (defined $pod->{min} && defined $code->{max} && $pod->{min} > $code->{max}) { | |||
| 12297 | 2 | 3 | push @errors, "Constraint contradiction for '\$$param': POD says min '$pod->{min}', code suggests max '$code->{max}' (no valid value)"; | |||
| 12298 | } | |||||
| 12299 | ||||||
| 12300 | 61 | 120 | if (defined $code->{min} && defined $pod->{max} && $code->{min} > $pod->{max}) { | |||
| 12301 | 0 | 0 | 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 | 75 | 137 | 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 | 607 | 9516 | my $val = $_[0]; | |||
| 12328 | ||||||
| 12329 | 607 | 1359 | return 0 unless defined $val; | |||
| 12330 | ||||||
| 12331 | # Numeric | |||||
| 12332 | 95 | 243 | return 0 if $val =~ /^(0|off|none)$/i; | |||
| 12333 | 86 | 330 | return 1 if $val =~ /^(1|warn|warning)$/i; | |||
| 12334 | 13 | 32 | return 2 if $val =~ /^(2|fatal|die|error)$/i; | |||
| 12335 | ||||||
| 12336 | 2 | 10 | 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 | 21 | 28 | my ($self, $pod_type, $code_type) = @_; | |||
| 12358 | ||||||
| 12359 | # Exact match is always compatible | |||||
| 12360 | 21 | 22 | return 1 if $pod_type eq $code_type; | |||
| 12361 | ||||||
| 12362 | # Define compatibility matrix | |||||
| 12363 | 16 | 32 | 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 | 16 | 17 | if (my $allowed = $compatible_types{$pod_type}) { | |||
| 12374 | 14 19 | 9 30 | return grep { $_ eq $code_type } @$allowed; | |||
| 12375 | } | |||||
| 12376 | ||||||
| 12377 | # Check if pod_type is compatible with code_type | |||||
| 12378 | 2 | 16 | if (my $allowed = $compatible_types{$code_type}) { | |||
| 12379 | 2 2 | 3 6 | return grep { $_ eq $pod_type } @$allowed; | |||
| 12380 | } | |||||
| 12381 | ||||||
| 12382 | 0 | 0 | return 0; # Not compatible | |||
| 12383 | } | |||||
| 12384 | ||||||
| 12385 - 12434 | =head2 generate_pod_validation_report
Generate a human-readable report of all POD/code disagreements found
across a set of extracted schemas.
my $schemas = $extractor->extract_all(no_write => 1);
my $report = $extractor->generate_pod_validation_report($schemas);
print $report;
=head3 Arguments
=over 4
=item * C<$schemas>
A hashref of method name to schema hashref as returned by
C<extract_all>. Required.
=back
=head3 Returns
A string containing the full validation report, or a single line
confirming all methods passed if no disagreements were found.
=head3 Side effects
None.
=head3 Notes
Only methods whose schemas contain a C<_pod_validation_errors> key
(populated when C<strict_pod> is 1 or 2) appear in the report. If
C<strict_pod> was 0 when C<extract_all> was called, this method will
always return the all-passed message.
=head3 API specification
=head4 input
{
self => { type => OBJECT, isa => 'App::Test::Generator::SchemaExtractor' },
schemas => { type => HASHREF },
}
=head4 output
{ type => SCALAR }
=cut | |||||
| 12435 | ||||||
| 12436 | sub generate_pod_validation_report { | |||||
| 12437 | 17 | 1301 | my ($self, $schemas) = @_; | |||
| 12438 | ||||||
| 12439 | 17 | 14 | my @reports; | |||
| 12440 | 17 | 26 | foreach my $method_name (sort keys %$schemas) { | |||
| 12441 | 26 | 16 | my $schema = $schemas->{$method_name}; | |||
| 12442 | ||||||
| 12443 | 26 | 30 | if (my $errors = $schema->{_pod_validation_errors}) { | |||
| 12444 | 16 | 19 | push @reports, "Method: $method_name"; | |||
| 12445 | 16 | 25 | push @reports, " Severity: " . ($schema->{_pod_disagreement} ? 'warning' : 'fatal'); | |||
| 12446 | 16 | 13 | push @reports, " Errors:"; | |||
| 12447 | 16 16 | 15 20 | push @reports, map { " - $_" } @$errors; | |||
| 12448 | 16 | 13 | push @reports, ''; | |||
| 12449 | } | |||||
| 12450 | } | |||||
| 12451 | ||||||
| 12452 | 17 | 130 | if (@reports) { | |||
| 12453 | 11 | 21 | return join("\n", "POD/Code Validation Report:", '=' x 40, '', @reports); | |||
| 12454 | } else { | |||||
| 12455 | 6 | 6 | return 'POD/Code Validation: All methods passed consistency checks.'; | |||
| 12456 | } | |||||
| 12457 | } | |||||
| 12458 | ||||||
| 12459 - 12463 | =head2 _log Log a message if verbose mode is on. =cut | |||||
| 12464 | ||||||
| 12465 | sub _log { | |||||
| 12466 | 7584 | 8085 | my($self, $msg) = @_; | |||
| 12467 | ||||||
| 12468 | 7584 | 7406 | print "$msg\n" if $self->{verbose}; | |||
| 12469 | } | |||||
| 12470 | ||||||
| 12471 - 12521 | =head1 NOTES
C<SchemaExtractor> uses heuristic analysis of Perl source and POD to infer
parameter types and constraints. Inference accuracy improves with
well-documented modules; C<=head3 Input> / C<=head4 Input> formal specs are
parsed at highest priority and override all heuristics.
A lone name in a C<=head4 input> block is treated as the first positional
argument when the body reads a positional argument (C<< $_[0] >>, a list
assignment from C<@_>, or a C<shift>) and does not read an argument hash
(C<my %args = @_>, a hashref dereference, or C<< $_[0]{...} >>); the
documented name is then a label for that argument, as C<name> is for
C<$_[0]> in L<Lingua::EN::NameCase/nc>. Two or more names, and a body that
only forwards C<@_>, remain named arguments.
The output is always a best-effort schema suitable as a starting template;
review and augment the generated YAML before using it as a definitive
specification. Pass it to L<App::Test::Generator> to generate fuzz harnesses.
=head1 TODO
Extend C<=head4 Input> parsing to cover the C<enum>/C<memberof> constraint
synonym (union types, e.g. C<scalar | scalarref>, are already handled by
C<_map_formal_input_type>).
=head1 SEE ALSO
=over 4
=item * L<App::Test::Generator> - Generate fuzz and corpus-driven test harnesses
Output from this module serves as input to that module.
So with well-documented code, you can automatically create your tests.
=item * L<App::Test::Generator::Template> - Template of the file of tests created by C<App::Test::Generator>
=back
=head1 AUTHOR
Nigel Horne, C<< <njh at nigelhorne.com> >>
=head1 LICENCE AND COPYRIGHT
Copyright 2025-2026 Nigel Horne.
Usage is subject to GPL2 licence terms.
If you use it,
please let me know.
=cut | |||||
| 12522 | ||||||
| 12523 | 1; | |||||