• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

tobyink / p5-type-tiny / 347913b2b

07 Mar 2025 02:04PM UTC coverage: 99.681% (-0.05%) from 99.734%
347913b2b

push

github

3752 of 3764 relevant lines covered (99.68%)

29274.62 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

97.16
/lib/Type/Params.pm
1
package Type::Params;
2

3
use 5.008001;
528✔
4
use strict;
528✔
5
use warnings;
528✔
6

7
BEGIN {
8
        $Type::Params::AUTHORITY = 'cpan:TOBYINK';
544✔
9
        $Type::Params::VERSION   = '2.008002';
544✔
10
}
11

12
$Type::Params::VERSION =~ tr/_//d;
13

14
use B qw();
544✔
15
use Eval::TypeTiny qw( eval_closure set_subname );
544✔
16
use Scalar::Util qw( refaddr );
544✔
17
use Error::TypeTiny;
544✔
18
use Error::TypeTiny::Assertion;
544✔
19
use Error::TypeTiny::WrongNumberOfParameters;
544✔
20
use Types::Standard ();
544✔
21
use Types::TypeTiny ();
544✔
22

23
require Exporter::Tiny;
24
our @ISA = 'Exporter::Tiny';
25

26
our @EXPORT = qw(
27
        compile compile_named
28
);
29

30
our @EXPORT_OK = qw(
31
        compile_named_oo
32
        validate validate_named
33
        multisig
34
        Invocant ArgsObject
35
        wrap_subs wrap_methods
36
        signature signature_for signature_for_func signature_for_method
37
);
38

39
our %EXPORT_TAGS = (
40
        compile  => [ qw( compile compile_named compile_named_oo ) ],
41
        wrap     => [ qw( wrap_subs wrap_methods ) ],
42
        sigs     => [ qw( signature signature_for ) ],
43
        validate => [ qw( validate validate_named ) ],
44
        sigplus  => [ qw( signature signature_for signature_for_func signature_for_method ) ],
45
        
46
        v1       => [ qw( compile compile_named ) ],      # Old default
47
        v2       => [ qw( signature signature_for ) ],    # New recommendation
48
);
49

50
{
51
        my $Invocant;
52
        
53
        sub Invocant () {
54
                $Invocant ||= do {
8✔
55
                        require Type::Tiny::Union;
8✔
56
                        'Type::Tiny::Union'->new(
8✔
57
                                name             => 'Invocant',
58
                                type_constraints => [
59
                                        Types::Standard::Object(),
60
                                        Types::Standard::ClassName(),
61
                                ],
62
                        );
63
                };
64
        } #/ sub Invocant
65
        
66
        my $ArgsObject;
67
        
68
        sub ArgsObject (;@) {
69
                $ArgsObject ||= do {
40✔
70
                        'Type::Tiny'->new(
71
                                name                 => 'ArgsObject',
72
                                parent               => Types::Standard::Object(),
73
                                constraint           => q{ ref($_) =~ qr/^Type::Params::OO::/ },
74
                                constraint_generator => sub {
75
                                        Type::Tiny::check_parameter_count_for_parameterized_type( 'Type::Params', 'ArgsObject', \@_, 1, 1 );
24✔
76
                                        my $param = Types::Standard::assert_Str( shift );
24✔
77
                                        sub { defined( $_->{'~~caller'} ) and $_->{'~~caller'} eq $param };
78
                                },
79
                                inline_generator => sub {
24✔
80
                                        my $param  = shift;
24✔
81
                                        my $quoted = B::perlstring( $param );
82
                                        sub {
24✔
83
                                                my $var = pop;
84
                                                return (
24✔
85
                                                        Types::Standard::Object()->inline_check( $var ),
86
                                                        sprintf( q{ ref(%s) =~ qr/^Type::Params::OO::/ }, $var ),
87
                                                        sprintf(
88
                                                                q{ do { use Scalar::Util (); Scalar::Util::reftype(%s) eq 'HASH' } }, $var
89
                                                        ),
90
                                                        sprintf(
91
                                                                q{ defined((%s)->{'~~caller'}) && ((%s)->{'~~caller'} eq %s) }, $var, $var,
92
                                                                $quoted
93
                                                        ),
94
                                                );
24✔
95
                                        };
96
                                },
16✔
97
                        );
98
                };
99
                
40✔
100
                @_ ? $ArgsObject->parameterize( @{ $_[0] } ) : $ArgsObject;
101
        } #/ sub ArgsObject (;@)
102
        
103
        &Scalar::Util::set_prototype( \&ArgsObject, ';$' )
104
                if Eval::TypeTiny::NICE_PROTOTYPES;
105
}
106

107
sub signature {
2,072✔
108
        if ( @_ % 2 ) {
8✔
109
                require Error::TypeTiny;
8✔
110
                Error::TypeTiny::croak( "Expected even-sized list of arguments" );
111
        }
2,064✔
112
        my ( %opts ) = @_;
2,064✔
113
        $opts{next} ||= delete $opts{goto_next} if exists $opts{goto_next};
114

2,064✔
115
        my $for = [ caller( 1 + ( $opts{caller_level} || 0 ) ) ]->[3] || ( ( $opts{package} || '__ANON__' ) . '::__ANON__' );
2,064✔
116
        my ( $pkg, $sub ) = ( $for =~ /^(.+)::(\w+)$/ );
2,064✔
117
        $opts{package} ||= $pkg;
2,064✔
118
        $opts{subname} ||= $sub;
119

2,064✔
120
        require Type::Params::Signature;
2,064✔
121
        'Type::Params::Signature'->new_from_v2api( \%opts )->return_wanted;
122
}
123

124
sub signature_for {
240✔
125
        if ( not @_ % 2 ) {
8✔
126
                require Error::TypeTiny;
8✔
127
                Error::TypeTiny::croak( "Expected odd-sized list of arguments; did you forget the function name?" );
128
        }
232✔
129
        my ( $function, %opts ) = @_;
232✔
130
        my $package = $opts{package} || caller( $opts{caller_level} || 0 );
232✔
131
        $opts{next} ||= delete $opts{goto_next} if exists $opts{goto_next};
132

232✔
133
        if ( ref($function) eq 'ARRAY' ) {
16✔
134
                $opts{package} = $package;
16✔
135
                return map { signature_for( $_, %opts ) } @$function;
136
        }
137
        
216✔
138
        $opts{_is_signature_for} = 1;
139

216✔
140
        my $fullname = ( $function =~ /::/ ) ? $function : "$package\::$function";
216✔
141
        $opts{package}   ||= $package;
216✔
142
        $opts{subname}   ||= ( $function =~ /::(\w+)$/ ) ? $1 : $function;
544✔
143
        $opts{next}      ||= do { no strict 'refs'; exists(&$fullname) ? \&$fullname : undef; };
216✔
144
        if ( $opts{method} ) {
64✔
145
                $opts{next} ||= eval { $package->can( $opts{subname} ) };
146
        }
216✔
147
        if ( $opts{fallback} and not $opts{next} ) {
8✔
148
                $opts{next} = ref( $opts{fallback} ) ? $opts{fallback} : sub {};
149
        }
216✔
150
        if ( not $opts{next} ) {
8✔
151
                require Error::TypeTiny;
8✔
152
                return Error::TypeTiny::croak( "Function '$function' not found to wrap!" );
153
        }
154

208✔
155
        require Type::Params::Signature;
208✔
156
        my $sig = 'Type::Params::Signature'->new_from_v2api( \%opts );
157
        # Delay compilation
192✔
158
        my $compiled;
159
        my $coderef = sub {
192✔
160
                $compiled ||= $sig->coderef->compile;
161
                
544✔
162
                no strict 'refs';
544✔
163
                no warnings 'redefine';
192✔
164
                *$fullname = set_subname( $fullname, $compiled );
165
                
192✔
166
                goto( $compiled );
192✔
167
        };
168

544✔
169
        no strict 'refs';
544✔
170
        no warnings 'redefine';
192✔
171
        *$fullname = set_subname( $fullname, $coderef );
172

192✔
173
        return $sig;
174
}
175

176
sub signature_for_func {
8✔
177
        if ( not @_ % 2 ) {
×
178
                require Error::TypeTiny;
×
179
                Error::TypeTiny::croak( "Expected odd-sized list of arguments; did you forget the function name?" );
180
        }
8✔
181
        my ( $function, %opts ) = @_;
8✔
182
        my $N = !!$opts{named};
8✔
183
        @_ = ( $function, method => 0, allow_dash => $N, list_to_named => $N, %opts );
8✔
184
        goto \&signature_for;
185
}
186

187
sub signature_for_method {
8✔
188
        if ( not @_ % 2 ) {
×
189
                require Error::TypeTiny;
×
190
                Error::TypeTiny::croak( "Expected odd-sized list of arguments; did you forget the function name?" );
191
        }
8✔
192
        my ( $function, %opts ) = @_;
8✔
193
        my $N = !!$opts{named};
8✔
194
        @_ = ( $function, method => 1, allow_dash => $N, list_to_named => $N, %opts );
8✔
195
        goto \&signature_for;
196
}
197

198
sub compile {
664✔
199
        my @args = @_;
664✔
200
        @_ = ( positional => \@args );
664✔
201
        goto \&signature;
202
}
203

204
sub compile_named {
680✔
205
        my @args = @_;
680✔
206
        @_ = ( bless => 0, named => \@args );
680✔
207
        goto \&signature;
208
}
209

210
sub compile_named_oo {
160✔
211
        my @args = @_;
160✔
212
        @_ = ( bless => 1, named => \@args );
160✔
213
        goto \&signature;
214
}
215

216
# Would be faster to inline this into validate and validate_named, but
217
# that would complicate them. :/
218
sub _mk_key {
7,472✔
219
        local $_;
220
        join ':', map {
7,472✔
221
                Types::Standard::is_HashRef( $_ ) ? do {
3,904✔
222
                        my %h = %$_;
3,904✔
223
                        sprintf( '{%s}', _mk_key( map { ; $_ => $h{$_} } sort keys %h ) );
224
                } :
36,992✔
225
                Types::TypeTiny::is_TypeTiny( $_ ) ? sprintf( 'TYPE=%s', $_->{uniq} ) :
226
                Types::Standard::is_Ref( $_ )      ? sprintf( 'REF=%s', refaddr( $_ ) ) :
227
                Types::Standard::is_Undef( $_ )    ? sprintf( 'UNDEF' ) :
228
                B::perlstring( $_ )
229
        } @_;
230
} #/ sub _mk_key
231

232
{
233
        my %compiled;
234
        sub validate {
128✔
235
                my $arg = shift;
236
                my $sub = (
237
                        $compiled{ _mk_key( @_ ) } ||= signature(
238
                                caller_level => 1,
128✔
239
                                %{ ref( $_[0] ) eq 'HASH' ? shift( @_ ) : +{} },
240
                                positional => [ @_ ],
241
                        )
242
                );
128✔
243
                @_ = @$arg;
128✔
244
                goto $sub;
245
        } #/ sub validate
246
}
247

248
{
249
        my %compiled;
250
        sub validate_named {
3,440✔
251
                my $arg = shift;
252
                my $sub = (
253
                        $compiled{ _mk_key( @_ ) } ||= signature(
254
                                caller_level => 1,
255
                                bless => 0,
3,440✔
256
                                %{ ref( $_[0] ) eq 'HASH' ? shift( @_ ) : +{} },
257
                                named => [ @_ ],
258
                        )
259
                );
3,440✔
260
                @_ = @$arg;
3,440✔
261
                goto $sub;
262
        } #/ sub validate_named
263
}
264

265
sub multisig {
56✔
266
        my %options = ( ref( $_[0] ) eq "HASH" ) ? %{ +shift } : ();
56✔
267
        signature(
268
                %options,
269
                multi => \@_,
270
        );
271
} #/ sub multisig
272

273
sub wrap_methods {
16✔
274
        my $opts = ref( $_[0] ) eq 'HASH' ? shift : {};
16✔
275
        $opts->{caller} ||= caller;
16✔
276
        $opts->{skip_invocant} = 1;
16✔
277
        $opts->{use_can}       = 1;
16✔
278
        unshift @_, $opts;
16✔
279
        goto \&_wrap_subs;
280
}
281

282
sub wrap_subs {
8✔
283
        my $opts = ref( $_[0] ) eq 'HASH' ? shift : {};
8✔
284
        $opts->{caller} ||= caller;
8✔
285
        $opts->{skip_invocant} = 0;
8✔
286
        $opts->{use_can}       = 0;
8✔
287
        unshift @_, $opts;
8✔
288
        goto \&_wrap_subs;
289
}
290

291
sub _wrap_subs {
24✔
292
        my $opts = shift;
24✔
293
        while ( @_ ) {
64✔
294
                my ( $name, $proto ) = splice @_, 0, 2;
64✔
295
                my $fullname = ( $name =~ /::/ ) ? $name : sprintf( '%s::%s', $opts->{caller}, $name );
64✔
296
                my $orig = do {
544✔
297
                        no strict 'refs';
298
                        exists &$fullname     ? \&$fullname
299
                                : $opts->{use_can} ? ( $opts->{caller}->can( $name ) || sub { } )
300
                                : sub { }
64✔
301
                };
64✔
302
                my $new;
64✔
303
                if ( ref $proto eq 'CODE' ) {
304
                        $new = $opts->{skip_invocant}
305
                                ? sub {
32✔
306
                                        my $s = shift;
32✔
307
                                        @_ = ( $s, &$proto );
16✔
308
                                        goto $orig;
309
                                }
310
                                : sub {
16✔
311
                                        @_ = &$proto;
8✔
312
                                        goto $orig;
16✔
313
                                };
314
                }
315
                else {
316
                        $new = compile(
317
                                {
318
                                        'package'   => $opts->{caller},
319
                                        'subname'   => $name,
320
                                        'next'      => $orig,
48✔
321
                                        'head'      => $opts->{skip_invocant} ? 1 : 0,
322
                                },
323
                                @$proto,
324
                        );
325
                }
544✔
326
                no strict 'refs';
544✔
327
                no warnings 'redefine';
64✔
328
                *$fullname = set_subname( $fullname, $new );
329
        } #/ while ( @_ )
24✔
330
        1;
331
} #/ sub _wrap_subs
332

333
1;
334

335
__END__
336

337
=pod
338

339
=encoding utf-8
340

341
=for stopwords evals invocant
342

343
=head1 NAME
344

345
Type::Params - sub signature validation using Type::Tiny type constraints and coercions
346

347
=head1 SYNOPSIS
348

349
 use v5.36;
350
 use builtin qw( true false );
351
 
352
 package Horse {
353
   use Moo;
354
   use Types::Standard qw( Object );
355
   use Type::Params -sigs;
356
   use namespace::autoclean;
357
   
358
   ...;   # define attributes, etc
359
   
360
   signature_for add_child => (
361
     method     => true,
362
     positional => [ Object ],
363
   );
364
   
365
   sub add_child ( $self, $child ) {
366
     push $self->children->@*, $child;
367
     return $self;
368
   }
369
 }
370
 
371
 package main;
372
 
373
 my $boldruler = Horse->new;
374
 
375
 $boldruler->add_child( Horse->new );
376
 
377
 $boldruler->add_child( 123 );   # dies (123 is not an Object!)
378

379
=head1 STATUS
380

381
This module is covered by the
382
L<Type-Tiny stability policy|Type::Tiny::Manual::Policies/"STABILITY">.
383

384
=head1 DESCRIPTION
385

386
This documents the details of the L<Type::Params> package.
387
L<Type::Tiny::Manual> is a better starting place if you're new.
388

389
Type::Params uses L<Type::Tiny> constraints to validate the parameters to a
390
sub. It takes the slightly unorthodox approach of separating validation
391
into two stages:
392

393
=over
394

395
=item 1.
396

397
Compiling the parameter specification into a coderef; then
398

399
=item 2.
400

401
Using the coderef to validate parameters.
402

403
=back
404

405
The first stage is slow (it might take a couple of milliseconds), but
406
only needs to be done the first time the sub is called. The second stage
407
is fast; according to my benchmarks faster even than the XS version of
408
L<Params::Validate>.
409

410
With the modern API, you rarely need to worry about the two stages being
411
internally separate.
412

413
Note that most of the examples in this documentation use modern Perl
414
features such as subroutine signatures, postfix dereferencing, and
415
the C<true> and C<false> keywords from L<builtin>. On Perl version 5.36+,
416
you can enable all of these features using:
417

418
 use v5.36;
419
 use experimental 'builtin';
420
 use builtin 'true', 'false';
421

422
Type::Params does support older versions of Perl (as old as 5.8), but you
423
may need to adjust the syntax for some examples.
424

425
=head1 MODERN API
426

427
The modern API can be exported using:
428

429
 use Type::Params -sigs;
430

431
Or:
432

433
 use Type::Params -v2;
434

435
Or by requesting functions by name:
436

437
 use Type::Params qw( signature signature_for );
438

439
Two optional shortcuts can be exported:
440

441
 use Type::Params qw( signature_for_func signature_for_method );
442

443
Or:
444

445
 use Type::Params -sigplus;
446

447
=head2 C<< signature_for $function_name => ( %spec ) >>
448

449
Wraps an existing function in additional code that implements all aspects
450
of the subroutine's signature, including unpacking arguments from C<< @_ >>,
451
applying default values, coercing, and validating values.
452

453
C<< signature_for( \@functions, %opts ) >> is a useful shortcut if you have
454
multiple functions with the same signature.
455

456
 signature_for [ 'add_nums', 'subtract_nums' ] => (
457
   positional => [ Num, Num ],
458
 );
459

460
Although normally used in void context, C<signature_for> does return a value.
461

462
 my $meta = signature_for add_nums => (
463
   positional => [ Num, Num ],
464
 );
465
 
466
 sub add_nums ( $x, $y ) {
467
   return $x + $y;
468
 }
469

470
Or when used with multiple functions:
471

472
 my @metas = signature_for [ 'add_nums', 'subtract_nums' ] => (...);
473

474
This is a blessed L<Type::Params::Signature> object which provides some
475
introspection possibilities. Inspecting C<< $meta->coderef->code >> can
476
be useful to see what the signature is doing internally.
477

478
=head3 Signature Specification Options
479

480
The signature specification is a hash which must contain either a
481
C<positional>, C<named>, or C<multiple> key indicating whether your
482
function takes positional parameters, named parameters, or supports
483
multiple calling conventions, but may also include other options.
484

485
=head4 C<< positional >> B<ArrayRef>
486

487
This is conceptually a list of type constraints, one for each positional
488
parameter. For example, a signature for a function which accepts two
489
integers:
490

491
 signature_for myfunc => ( positional => [ Int, Int ] );
492

493
However, each type constraint is optionally followed by a hashref of
494
options which affect that parameter. For example:
495

496
 signature_for myfunc => ( positional => [
497
   Int, { default => 40 },
498
   Int, { default =>  2 },
499
 ] );
500

501
Type constraints can instead be given as strings, which will be looked
502
up using C<dwim_type> from L<Type::Utils>.
503

504
 signature_for myfunc => ( positional => [
505
   'Int', { default => 40 },
506
   'Int', { default =>  2 },
507
 ] );
508

509
See the section below for more information on parameter options.
510

511
Optional parameters must follow required parameters, and can be specified
512
using either the B<Optional> parameterizable type constraint, the
513
C<optional> parameter option, or by providing a default.
514

515
 # All three parameters are effectively optional.
516
 signature_for myfunc => ( positional => [
517
   Optional[Int],
518
   Int, { optional => true },
519
   Int, { default  => 42 },
520
 ] );
521

522
A single slurpy parameter may be provided at the end, using the B<Slurpy>
523
parameterizable type constraint, or the C<slurpy> parameter option:
524

525
 signature_for myfunc => ( positional => [
526
   Int,
527
   Slurpy[ ArrayRef[Int] ],
528
 ] );
529

530
 signature_for myfunc => ( positional => [
531
   Int,
532
   ArrayRef[Int], { slurpy => true },
533
 ] );
534

535
The C<positional> option can also be abbreviated to C<pos>.
536

537
So C<< signature_for myfunc => ( pos => [...] ) >> can be used instead of
538
the longer C<< signature_for myfunc => ( positional => [...] ) >>.
539

540
 signature_for add_numbers => ( pos => [ Num, Num ] );
541
 
542
 sub add_numbers ( $num1, $num2 ) {
543
   return $num1 + $num2;
544
 }
545
 
546
 say add_numbers( 2, 3 );   # says 5
547

548
=head4 C<< named >> B<ArrayRef>
549

550
This is conceptually a list of pairs of names and type constraints, one
551
name+type pair for each named parameter. For example, a signature for
552
a function which accepts two integers:
553

554
 signature_for myfunc => ( named => [ foo => Int, bar => Int ] )
555

556
However, each type constraint is optionally followed by a hashref of
557
options which affect that parameter. For example:
558

559
 signature_for myfunc => ( named => [
560
   foo => Int, { default => 40 },
561
   bar => Int, { default =>  2 },
562
 ] );
563

564
Type constraints can instead be given as strings, which will be looked
565
up using C<dwim_type> from L<Type::Utils>.
566

567
 signature_for myfunc => ( named => [
568
   foo => 'Int', { default => 40 },
569
   bar => 'Int', { default =>  2 },
570
 ] );
571

572
Optional and slurpy parameters are allowed, but unlike positional parameters,
573
they do not need to be at the end.
574

575
See the section below for more information on parameter options.
576

577
If a signature uses named parameters, the values are supplied to the
578
function as a single parameter object:
579

580
 signature_for add_numbers => ( named => [ num1 => Num, num2 => Num ] );
581
 
582
 sub add_numbers ( $arg ) {
583
   return $arg->num1 + $arg->num2;
584
 }
585
 
586
 say add_numbers(   num1 => 2, num2 => 3   );   # says 5
587
 say add_numbers( { num1 => 2, num2 => 3 } );   # also says 5
588

589
=head4 C<< named_to_list >> B<< ArrayRef|Bool >>
590

591
The C<named_to_list> option is ignored for signatures using positional
592
parameters, but for signatures using named parameters, allows them to
593
be supplied to the function as a list of values instead of as a single
594
object:
595

596
 signature_for add_numbers => (
597
   named         => [ num1 => Num, num2 => Num ],
598
   named_to_list => true,
599
 );
600
 
601
 sub add_numbers ( $num1, $num2 ) {
602
   return $num1 + $num2;
603
 }
604
 
605
 say add_numbers(   num1 => 2, num2 => 3   );   # says 5
606
 say add_numbers( { num1 => 2, num2 => 3 } );   # also says 5
607

608
You can think of C<add_numbers> above as a function which takes named
609
parameters from the outside, but receives positional parameters on the
610
inside.
611

612
You can use an arrayref to control the order in which the parameters will
613
be supplied. (By default they are returned in the order in which they were
614
defined.)
615

616
 signature_for add_numbers => (
617
   named         => [ num1 => Num, num2 => Num ],
618
   named_to_list => [ qw( num2 num1 ) ],
619
 );
620
 
621
 sub add_numbers ( $num2, $num1 ) {
622
   return $num1 + $num2;
623
 }
624
 
625
 say add_numbers(   num1 => 2, num2 => 3   );   # says 5
626
 say add_numbers( { num1 => 2, num2 => 3 } );   # also says 5
627

628
=head4 C<< list_to_named >> B<< Bool >>
629

630
For a function that accepts named parameters, allows them to alternatively
631
be supplied as a list in a hopefully do-what-you-mean manner.
632

633
 signature_for add_numbers => (
634
   named         => [ num1 => Num, num2 => Num ],
635
   list_to_named => true,
636
 );
637
 
638
 sub add_numbers ( $arg ) {
639
   return $arg->num1 + $arg->num2;
640
 }
641
 
642
 say add_numbers( num1 => 5, num2 => 10 );      # says 15
643
 say add_numbers( { num1 => 5, num2 => 10 } );  # also says 15
644
 say add_numbers( 5, num2 => 10 );              # says 15 yet again
645
 say add_numbers( 5, { num2 => 10 } );          # guess what? says 15
646
 say add_numbers( 10, num1 => 5 );              # 14. just kidding! 15
647
 say add_numbers( 10, { num1 => 5 } );          # another 15
648
 say add_numbers( 5, 10 );                      # surprise, it says 15
649
 
650
 # BAD: list_to_named argument cannot be at the end.
651
 say add_numbers( { num1 => 5 }, 10 );
652
 
653
 # BAD: list_to_named argument duplicated.
654
 say add_numbers( 5, 10, { num1 => 5 } );
655

656
Where a hash or hashref of named parameters are expected, any parameter
657
which doesn't look like it fits that pattern will be treated as a "sneaky"
658
positional parameter, and will be tried the first time a named parameter
659
seems to be missing.
660

661
This feature is normally only applied to required parameters. It can be
662
manually controlled on a per-parameter basis using the C<in_list> option.
663

664
Type::Params attempts to be intelligent at figuring out what order
665
the sneaky positional parameters were given in.
666

667
 signature_for add_to_ref => (
668
   named         => [ ref => ScalarRef[Num], add => Num ],
669
   list_to_named => true,
670
 );
671
 
672
 sub add_to_ref ( $arg ) {
673
   $arg->ref->$* += $arg->num;
674
 }
675
 
676
 my $sum = 0;
677
 add_to_ref( ref => \$sum, add => 1 );
678
 add_to_ref( \$sum, add => 2 );
679
 add_to_ref( \$sum, 3 );
680
 add_to_ref( 4, \$sum );
681
 add_to_ref( 5, sum => \$sum );
682
 add_to_ref( add => 5, sum => \$sum );
683
 say $sum; # 21
684

685
This approach is somewhat slower, but has the potential for very
686
do-what-I-mean functions.
687

688
Note that C<list_to_named> and C<named_to_list> can both be used in
689
the same signature as their meanings are not contradictory.
690

691
 signature_for add_to_ref => (
692
   named         => [ ref => ScalarRef[Num], add => Num ],
693
   list_to_named => true,
694
   named_to_list => true,
695
 );
696
 
697
 sub add_to_ref ( $ref, $num ) {
698
   $ref->$* += $num;
699
 }
700

701
=head4 C<< head >> B<< Int|ArrayRef >>
702

703
C<head> provides an additional list of non-optional, positional parameters
704
at the start of C<< @_ >>. This is often used for method calls. For example,
705
if you wish to define a signature for:
706

707
 $object->my_method( foo => 123, bar => 456 );
708

709
You could write it as this:
710

711
 signature_for my_method => (
712
   head    => [ Object ],
713
   named   => [ foo => Optional[Int], bar => Optional[Int] ],
714
 );
715
 
716
 sub my_method ( $self, $arg ) {
717
   ...;
718
 }
719

720
If C<head> is set as a number instead of an arrayref, it is the number of
721
additional arguments at the start:
722

723
 signature_for stash_foobar = (
724
   head    => 2,
725
   named   => [ foo => Optional[Int], bar => Optional[Int] ],
726
 );
727
 
728
 sub stash_foobar ( $self, $ctx, $arg ) {
729
   $ctx->stash->{foo} = $arg->foo if $arg->has_foo;
730
   $ctx->stash->{bar} = $arg->bar if $arg->has_bar;
731
   return $self;
732
 }
733
 
734
 ...;
735
 
736
 $app->stash_foobar( $context, foo => 123 );
737

738
In this case, no type checking is performed on those additional arguments;
739
it is just checked that they exist.
740

741
=head4 C<< tail >> B<< Int|ArrayRef >>
742

743
A C<tail> is like a C<head> except that it is for arguments at the I<end>
744
of C<< @_ >>.
745

746
 signature_for my_method => (
747
   head    => [ Object ],
748
   named   => [ foo => Optional[Int], bar => Optional[Int] ],
749
   tail    => [ CodeRef ],
750
 );
751
 
752
 sub my_method ( $self, $arg, $callback ) {
753
   ...;
754
 }
755
 
756
 $object->my_method( foo => 123, bar => 456, sub { ... } );
757

758
=head4 C<< method >> B<< Bool|TypeTiny >>
759

760
While C<head> can be used for method signatures, a more declarative way is
761
to set C<< method => true >>.
762

763
If you wish to be specific that this is an object method, intended to be
764
called on blessed objects only, then you may use C<< method => Object >>,
765
using the B<Object> type from L<Types::Standard>. If you wish to specify
766
that it's a class method, then use C<< method => Str >>, using the B<Str>
767
type from L<Types::Standard>. (C<< method => ClassName >> is perhaps
768
clearer, but it's a slower check.)
769

770
 signature_for my_method => (
771
   method  => true,
772
   named   => [ foo => Optional[Int], bar => Optional[Int] ],
773
 );
774
 
775
 sub my_method ( $self, $arg ) {
776
   ...;
777
 }
778

779
The C<method> option has some other subtle differences from C<head>. Any
780
parameter defaults which are coderefs will be called as methods on the
781
invocant instead of being called with no arguments. The C<package> option
782
will be interpreted slightly differently.
783

784
It is possible to use both C<method> and C<head> in the same signature.
785
The invocant is interpreted as being I<before> the C<head>.
786

787
A shortcut is provided for C<< method => true >>, though it also enables
788
a couple of other options.
789

790
 use Type::Params qw( signature_for_method );
791
 
792
 signature_for_method my_method => (
793
   named => [ foo => Optional[Int], bar => Optional[Int] ],
794
 );
795
 
796
 sub my_method ( $self, $arg ) {
797
   ...;
798
 }
799

800
=head4 C<< description >> B<Str>
801

802
This is the description of the coderef that will show up in stack traces.
803
It defaults to "parameter validation for X" where X is the sub name. Usually
804
the default will be fine.
805

806
=head4 C<< package >> B<Str>
807

808
This allows you to add signatures to functions in other packages:
809

810
 signature_for foo => ( package "Some::Package", ... );
811

812
If C<method> is true and Some::Package doesn't contain a sub called "foo",
813
then Type::Params will traverse the inheritance heirarchy, looking for "foo".
814

815
If any type constraints are specified as strings, Type::Params will look
816
for types imported by this package.
817

818
 # Expects the MyInt type to be known by Some::Package.
819
 signature_for foo => ( package "Some::Package", pos => [ 'MyInt' ] );
820

821
This is also supported:
822

823
 signature_for "Some::Package::foo" => ( ... );
824

825
=head4 C<< fallback >> B<CodeRef|Bool>
826

827
If the sub being wrapped cannot be found, then C<signature_for> will usually
828
throw an error. If you want it to "still work" in this situation, use the
829
C<fallback> option. C<< fallback => \&alternative_coderef_to_wrap >>
830
will instead wrap a different coderef if the original cannot be found.
831
C<< fallback => true >> is a shortcut for C<< fallback => sub {} >>.
832
An example where this might be useful is if you're adding signatures to
833
methods which are inherited from a parent class, but you are not 100%
834
confident will exist (perhaps dependent on the version of the parent class).
835

836
 signature_for add_nums => (
837
   positional => [ Num, Num ],
838
   fallback   => sub { $_[0] + $_[1] },
839
 );
840

841
=head4 C<< on_die >> B<< Maybe[CodeRef] >>
842

843
Usually when the signature check hits an error, it will throw an exception,
844
which is a blessed L<Error::TypeTiny> object.
845

846
If you provide an C<on_die> coderef, then instead the L<Error::TypeTiny>
847
object will be passed to it.
848

849
 signature_for add_numbers => (
850
   positional => [ Num, Num ],
851
   on_die     => sub {
852
     my $error = shift;
853
     print "Existential crisis: $error\n";
854
     exit( 1 );
855
   },
856
 );
857
 
858
 sub add_numbers ( $num1, $num2 ) {
859
   return $num1 + $num2;
860
 }
861
 
862
 say add_numbers();   # has an existential crisis
863

864
If your C<on_die> coderef doesn't exit or throw an exception, it can
865
instead return a list which will be used as parameters for your function.
866

867
 signature_for add_numbers => (
868
   positional => [ Num, Num ],
869
   on_die     => sub { return ( 40, 2 ) },
870
 );
871
 
872
 sub add_numbers ( $num1, $num2 ) {
873
   return $num1 + $num2;
874
 }
875
 
876
 say add_numbers();   # 42
877

878
This is probably not very useful.
879

880
=head4 C<< strictness >> B<< Bool|Str >>
881

882
If you set C<strictness> to false, then certain signature checks will simply
883
never be done. The initial check that there's the correct number of parameters,
884
plus type checks on parameters which don't coerce can be skipped.
885

886
If you set it to true or do not set it at all, then these checks will always
887
be done.
888

889
Alternatively, it may be set to the quoted fully-qualified name of a Perl
890
global variable or a constant, and that will be compiled into the coderef
891
as a condition to enable strict checks.
892

893
 signature_for my_func => (
894
   strictness => '$::CHECK_TYPES',
895
   positional => [ Int, ArrayRef ],
896
 );
897
 
898
 sub my_func ( $int, $aref ) {
899
   ...;
900
 }
901
 
902
 # Type checks are skipped
903
 {
904
   local $::CHECK_TYPES = false;
905
   my ( $number, $list ) = my_func( {}, {} );
906
 }
907
 
908
 # Type checks are performed
909
 {
910
   local $::CHECK_TYPES = true;
911
   my ( $number, $list ) = my_func( {}, {} );
912
 }
913

914
A recommended use of C<strictness> is with L<Devel::StrictMode>.
915

916
 use Devel::StrictMode qw( STRICT );
917
 
918
 state $signature = signature(
919
   strictness => STRICT,
920
   positional => [ Int, ArrayRef ],
921
 );
922

923
=head4 C<< multiple >> B<< ArrayRef|HashRef >>
924

925
This option allows your signature to support multiple calling conventions.
926
Each entry in the array is an alternative signature, as a hashref:
927

928
 signature_for my_func => (
929
   multiple => [
930
     {
931
       positional    => [ ArrayRef, Int ],
932
     },
933
     {
934
       named         => [ array => ArrayRef, index => Int ],
935
       named_to_list => true,
936
     },
937
   ],
938
 );
939
 
940
 sub my_func ( $aref, $int ) {
941
   ...;
942
 }
943

944
That signature will allow your function to be called as:
945

946
 your_function( $arr, $ix );
947
 your_function( array => $arr, index => $ix );
948
 your_function( { array => $arr, index => $ix } );
949

950
Sometimes the alternatives will return the parameters in different orders:
951

952
 signature_for my_func => (
953
   multiple => [
954
     { positional => [ ArrayRef, Int ] },
955
     { positional => [ Int, ArrayRef ] },
956
   ],
957
 );
958

959
So how does your sub know how it's been called? One option is to use the
960
C<< ${^_TYPE_PARAMS_MULTISIG} >> global variable which will be set to the
961
index of the signature which was used:
962

963
 sub my_func {
964
   my ( $arr, $ix ) = ${^_TYPE_PARAMS_MULTISIG} == 1 ? reverse( @_ ) : @_;
965
   ...;
966
 }
967

968
If you'd prefer to use identifying names instead of a numeric index, you
969
can specify these using C<ID>:
970

971
 signature_for my_func => (
972
   multiple => [
973
     { ID => 'one', positional => [ ArrayRef, Int ] },
974
     { ID => 'two', positional => [ Int, ArrayRef ] },
975
   ],
976
 );
977

978
Or by using a hashref:
979

980
 signature_for my_func => (
981
   multiple => {
982
     one => { positional => [ ArrayRef, Int ] },
983
     two => { positional => [ Int, ArrayRef ] },
984
   },
985
 );
986

987
A neater solution is to use a C<next> coderef to re-order alternative
988
signature results into your preferred order:
989

990
 signature_for my_func => (
991
   multiple => [
992
     { positional => [ ArrayRef, Int ] },
993
     { positional => [ Int, ArrayRef ], next => sub { reverse @_ } },
994
   ],
995
 );
996
 
997
 sub my_func ( $arr, $ix ) {
998
   ...;
999
 }
1000

1001
While conceptally C<multiple> is an arrayref of hashrefs, it is also possible
1002
to use arrayrefs in the arrayref.
1003

1004
 multiple => [
1005
   [ ArrayRef, Int ],
1006
   [ Int, ArrayRef ],
1007
 ]
1008

1009
When an arrayref is used like that, it is a shortcut for a positional
1010
signature.
1011

1012
Coderefs may additionally be used:
1013

1014
 signature_for my_func => (
1015
   multiple => [
1016
     [ ArrayRef, Int ],
1017
     { positional => [ Int, ArrayRef ], next => sub { reverse @_ } },
1018
     sub { ... },
1019
     sub { ... },
1020
   ],
1021
 );
1022

1023
The coderefs should be subs which return a list of parameters if they
1024
succeed and throw an exception if they fail.
1025

1026
The following signatures are equivalent:
1027

1028
 signature_for my_func => (
1029
   multiple => [
1030
     { method => true, positional => [ ArrayRef, Int ] },
1031
     { method => true, positional => [ Int, ArrayRef ] },
1032
   ],
1033
 );
1034
 
1035
 signature_for my_func => (
1036
   method   => true,
1037
   multiple => [
1038
     { positional => [ ArrayRef, Int ] },
1039
     { positional => [ Int, ArrayRef ] },
1040
   ],
1041
 );
1042

1043
The C<multiple> option can also be abbreviated to C<multi>.
1044
So C<< signature( multi => [...] ) >> can be used instead of the longer
1045
C<< signature( multiple => [...] ) >>. Three whole keystrokes saved!
1046

1047
(B<Note:> in older releases of Type::Params, C<< ${^_TYPE_PARAMS_MULTISIG} >>
1048
was called C<< ${^TYPE_PARAMS_MULTISIG} >>. The latter name is no longer
1049
supported.)
1050

1051
=head4 C<< message >> B<Str>
1052

1053
Only used by C<multiple> signatures. The error message to throw when no
1054
signatures match.
1055

1056
=head4 C<< bless >> B<Bool|ClassName>, C<< class >> B<< ClassName|ArrayRef >>, and C<< constructor >> B<Str>
1057

1058
Named parameters are usually returned as a blessed object:
1059

1060
 signature_for add_numbers => ( named => [ num1 => Num, num2 => Num ] );
1061
 
1062
 sub add_numbers ( $arg ) {
1063
   return $arg->num1 + $arg->num2;
1064
 }
1065

1066
The class they are blessed into is one built on-the-fly by Type::Params.
1067
However, these three signature options allow you more control over that
1068
process.
1069

1070
Firstly, if you set C<< bless => false >> and do not set C<class> or
1071
C<constructor>, then C<< $arg >> will just be an unblessed hashref.
1072

1073
 signature_for add_numbers => (
1074
   named        => [ num1 => Num, num2 => Num ],
1075
   bless        => false,
1076
 );
1077
 
1078
 sub add_numbers ( $arg ) {
1079
   return $arg->{num1} + $arg->{num2};
1080
 }
1081

1082
This is a good speed boost, but having proper methods for each named
1083
parameter is a helpful way to catch misspelled names.
1084

1085
If you wish to manually create a class instead of relying on Type::Params
1086
generating one on-the-fly, you can do this:
1087

1088
 package Params::For::AddNumbers {
1089
   sub num1 ( $self ) {
1090
     return $self->{num1};
1091
   }
1092
   sub num2 ( $self ) {
1093
     return $self->{num2};
1094
   }
1095
   sub sum ( $self ) {
1096
     return $self->num1 + $self->num2;
1097
   }
1098
 }
1099
 
1100
 signature_for add_numbers => (
1101
   named        => [ num1 => Num, num2 => Num ],
1102
   bless        => 'Params::For::AddNumbers',
1103
 );
1104
 
1105
 sub add_numbers ( $arg ) {
1106
   return $arg->sum;
1107
 }
1108

1109
Note that C<Params::For::AddNumbers> here doesn't include a C<new> method
1110
because Type::Params will directly do C<< bless( $arg, $opts{bless} ) >>.
1111

1112
If you want Type::Params to use a proper constructor, you should use the
1113
C<class> option instead:
1114

1115
 package Params::For::AddNumbers {
1116
   use Moo;
1117
   has [ 'num1', 'num2' ] => ( is => 'ro' );
1118
   sub sum {
1119
     my $self = shift;
1120
     return $self->num1 + $self->num2;
1121
   }
1122
 }
1123
 
1124
 signature_for add_numbers => (
1125
   named        => [ num1 => Num, num2 => Num ],
1126
   class        => 'Params::For::AddNumbers',
1127
 );
1128
 
1129
 sub add_numbers ( $arg ) {
1130
   return $arg->sum;
1131
 }
1132

1133
If you wish to use a constructor named something other than C<new>, then
1134
use:
1135

1136
 signature_for add_numbers => (
1137
   named        => [ num1 => Num, num2 => Num ],
1138
   class        => 'Params::For::AddNumbers',
1139
   constructor  => 'new_from_hashref',
1140
 );
1141

1142
Or as a shortcut:
1143

1144
 signature_for add_numbers => (
1145
   named        => [ num1 => Num, num2 => Num ],
1146
   class        => [ 'Params::For::AddNumbers' => 'new_from_hashref' ],
1147
 );
1148

1149
It is doubtful you want to use any of these options, except
1150
C<< bless => false >>.
1151

1152
=head4 C<< returns >> B<TypeTiny>, C<< returns_scalar >> B<TypeTiny>, and C<< returns_list >> B<TypeTiny>
1153

1154
These can be used to specify the type returned by your function.
1155

1156
 signature_for round_number => (
1157
   pos          => [ Num ],
1158
   returns      => Int,
1159
 );
1160
 
1161
 sub round_number ( $num ) {
1162
   return int( $num );
1163
 }
1164

1165
If your function returns different types in scalar and list context,
1166
you can use C<returns_scalar> and C<returns_list> to indicate separate
1167
return types in different contexts.
1168

1169
 signature_for my_func => (
1170
   pos             => [ Int, Int ],
1171
   returns_scalar  => Int,
1172
   returns_list    => Tuple[ Int, Int, Int ],
1173
 );
1174

1175
The C<returns_list> constraint is defined using an B<ArrayRef>-like or
1176
B<HashRef>-like type constraint even though it's returning a list, not
1177
a single reference.
1178

1179
If your function is called in void context, then its return value is
1180
unimportant and should not be type checked.
1181

1182
=head4 C<< allow_dash >> B<Bool>
1183

1184
For any "word-like" named parameters or aliases, automatically creates an
1185
alias with a leading hyphen.
1186

1187
 signature_for withdraw_funds => (
1188
   named      => [ amount => Num, account => Str ],
1189
   allow_dash => true,
1190
 );
1191
 
1192
 sub withdraw_funds ( $arg ) {
1193
   ...;
1194
 }
1195
 
1196
 withdraw_funds(  amount => 11.99,  account => 'ABC123' );
1197
 withdraw_funds( -amount => 11.99,  account => 'ABC123' );
1198
 withdraw_funds(  amount => 11.99, -account => 'ABC123' );
1199
 withdraw_funds( -amount => 11.99, -account => 'ABC123' );
1200

1201
Has no effect on names that are not word-like. Word-like names are those
1202
matching C<< /\A[^\W0-9]\w*\z/ >>; essentially anything Perl allows as a
1203
normal unqualified variable name.
1204

1205
=head3 Parameter Options
1206

1207
In the parameter lists for the C<positional> and C<named> signature
1208
options, each parameter may be followed by a hashref of options specific
1209
to that parameter:
1210

1211
 signature_for my_func => (
1212
   positional => [
1213
     Int, \%options_for_first_parameter,
1214
     Int, \%options_for_other_parameter,
1215
   ],
1216
   %more_options_for_signature,
1217
 );
1218

1219
 signature_for my_func => (
1220
   named => [
1221
     foo => Int, \%options_for_foo,
1222
     bar => Int, \%options_for_bar,
1223
   ],
1224
   %more_options_for_signature,
1225
 );
1226

1227
The following options are supported for parameters.
1228

1229
=head4 C<< optional >> B<Bool>
1230

1231
An option I<called> optional!
1232

1233
This makes a parameter optional:
1234

1235
 signature_for add_nums => (
1236
   positional => [
1237
     Int,
1238
     Int,
1239
     Bool, { optional => true },
1240
   ],
1241
 );
1242
 
1243
 sub add_nums ( $num1, $num2, $debug ) {
1244
   my $sum = $num1 + $num2;
1245
   warn "$sum = $num1 + $num2" if $debug;
1246
   return $sum;
1247
 }
1248
 
1249
 add_nums( 2, 3, 1 );   # prints warning
1250
 add_nums( 2, 3, 0 );   # no warning
1251
 add_nums( 2, 3    );   # no warning
1252

1253
L<Types::Standard> also provides a B<Optional> parameterizable type
1254
which may be a neater way to do this:
1255

1256
 signature_for add_nums => ( pos => [ Int, Int, Optional[Bool] ] );
1257

1258
In signatures with positional parameters, any optional parameters must be
1259
defined I<after> non-optional parameters. The C<tail> option provides a
1260
workaround for required parameters at the end of C<< @_ >>.
1261

1262
In signatures with named parameters, the order of optional and non-optional
1263
parameters is unimportant.
1264

1265
=head4 C<< slurpy >> B<Bool>
1266

1267
A signature may contain a single slurpy parameter, which mops up any other
1268
arguments the caller provides your function.
1269

1270
In signatures with positional parameters, slurpy params must always have
1271
some kind of B<ArrayRef> or B<HashRef> type constraint, must always appear
1272
at the I<end> of the list of positional parameters, and they work like this:
1273

1274
 signature_for add_nums => (
1275
   positional => [
1276
     Num,
1277
     ArrayRef[Num], { slurpy => true },
1278
   ],
1279
 );
1280
 
1281
 sub add_nums ( $first_num, $other_nums ) {
1282
   my $sum = $first_num;
1283
   for my $other ( $other_nums->@* ) {
1284
     $sum += $other;
1285
   }
1286
   return $sum;
1287
 }
1288
 
1289
 say add_nums( 1 );            # says 1
1290
 say add_nums( 1, 2 );         # says 3
1291
 say add_nums( 1, 2, 3 );      # says 6
1292
 say add_nums( 1, 2, 3, 4 );   # says 10
1293

1294
In signatures with named parameters, slurpy params must always have
1295
some kind of B<HashRef> type constraint, and they work like this:
1296

1297
 use builtin qw( true false );
1298
 
1299
 signature_for process_data => (
1300
   method => true,
1301
   named  => [
1302
     input   => FileHandle,
1303
     output  => FileHandle,
1304
     flags   => HashRef[Bool], { slurpy => true },
1305
   ],
1306
 );
1307
 
1308
 sub process_data ( $self, $arg ) {
1309
   warn "Beginning data processing" if $arg->flags->{debug};
1310
   ...;
1311
 }
1312
 
1313
 $widget->process_data(
1314
   input  => \*STDIN,
1315
   output => \*STDOUT,
1316
   debug  => true,
1317
 );
1318

1319
The B<Slurpy> type constraint from L<Types::Standard> may be used as
1320
a shortcut to specify slurpy parameters:
1321

1322
 signature_for add_nums => (
1323
   positional => [ Num, Slurpy[ ArrayRef[Num] ] ],
1324
 )
1325

1326
The type B<< Slurpy[Any] >> is handled specially and treated as a
1327
slurpy B<ArrayRef> in signatures with positional parameters, and a
1328
slurpy B<HashRef> in signatures with named parameters, but has some
1329
additional optimizations for speed.
1330

1331
=head4 C<< default >> B<< CodeRef|ScalarRef|Ref|Str|Undef >>
1332

1333
A default may be provided for a parameter.
1334

1335
 signature_for my_func => (
1336
   positional => [
1337
     Int,
1338
     Int, { default => "666" },
1339
     Int, { default => "999" },
1340
   ],
1341
 );
1342

1343
Supported defaults are any strings (including numerical ones), C<undef>,
1344
and empty hashrefs and arrayrefs. Non-empty hashrefs and arrayrefs are
1345
I<< not allowed as defaults >>.
1346

1347
Alternatively, you may provide a coderef to generate a default value:
1348

1349
 signature_for my_func => (
1350
   positional => [
1351
     Int,
1352
     Int, { default => sub { 6 * 111 } },
1353
     Int, { default => sub { 9 * 111 } },
1354
   ]
1355
 );
1356

1357
That coderef may generate any value, including non-empty arrayrefs and
1358
non-empty hashrefs. For undef, simple strings, numbers, and empty
1359
structures, avoiding using a coderef will make your parameter processing
1360
faster.
1361

1362
Instead of a coderef, you can use a reference to a string of Perl source
1363
code:
1364

1365
 signature_for my_func => (
1366
   positional => [
1367
     Int,
1368
     Int, { default => \ '6 * 111' },
1369
     Int, { default => \ '9 * 111' },
1370
   ],
1371
 );
1372

1373
Defaults I<will> be validated against the type constraint, and
1374
potentially coerced.
1375

1376
Any parameter with a default will automatically be optional, as it
1377
makes no sense to provide a default for required paramaters.
1378

1379
Note that having I<any> defaults in a signature (even if they never
1380
end up getting used) can slow it down, as Type::Params will need to
1381
build a new array instead of just returning C<< @_ >>.
1382

1383
=head4 C<< default_on_undef >> B<Bool>
1384

1385
Normally defaults are only applied when a parameter is I<missing> (think
1386
C<exists> for hashes or the array being too short). Setting
1387
C<default_on_undef> to true will also trigger the default if a parameter
1388
is provided but undefined.
1389

1390
If the caller might legitimately want to supply undef as a value, it is
1391
not recommended you uswe this.
1392

1393
=head4 C<< coerce >> B<Bool>
1394

1395
Speaking of coercion, the C<coerce> option allows you to indicate that a
1396
value should be coerced into the correct type:
1397

1398
 signature_for my_func => (
1399
   positional => [
1400
     Int,
1401
     Int,
1402
     Bool, { coerce => true },
1403
   ],
1404
 );
1405

1406
Setting C<coerce> to false will disable coercion.
1407

1408
If C<coerce> is not specified, so is neither true nor false, then
1409
coercion will be enabled if the type constraint has a coercion, and
1410
disabled otherwise.
1411

1412
Note that having I<any> coercions in a signature (even if they never
1413
end up getting used) can slow it down, as Type::Params will need to
1414
build a new array instead of just returning C<< @_ >>.
1415

1416
=head4 C<< clone >> B<Bool>
1417

1418
If this is set to true, it will deep clone incoming values via C<dclone>
1419
from L<Storable> (a core module since Perl 5.7.3).
1420

1421
In the below example, C<< $arr >> is a reference to a I<clone of>
1422
C<< @numbers >>, so pushing additional numbers to it leaves C<< @numbers >>
1423
unaffected.
1424

1425
 signature_for foo => (
1426
   positional => [ ArrayRef, { clone => true } ],
1427
 );
1428
 
1429
 sub foo ( $arr ) {
1430
   push @$arr, 4, 5, 6;
1431
 }
1432
 
1433
 my @numbers = ( 1, 2, 3 );
1434
 foo( \@numbers );
1435
 print "@numbers\n";  ## 1 2 3
1436

1437
Note that cloning will significantly slow down your signature.
1438

1439
=head4 C<< name >> B<Str>
1440

1441
This overrides the name of a named parameter. I don't know why you
1442
would want to do that.
1443

1444
The following signature has two parameters: C<foo> and C<bar>. The
1445
name C<fool> is completely ignored.
1446

1447
 signature_for my_func => (
1448
   named => [
1449
     fool   => Int, { name => 'foo' },
1450
     bar    => Int,
1451
   ],
1452
 );
1453

1454
You can, however, also name positional parameters, which don't usually
1455
have names.
1456

1457
 signature_for my_func => (
1458
   positional => [
1459
     Int, { name => 'foo' },
1460
     Int, { name => 'bar' },
1461
   ],
1462
 );
1463

1464
The names of positional parameters are not really I<used> for anything
1465
at the moment, but may be incorporated into error messages or
1466
similar in the future.
1467

1468
=head4 C<< getter >> B<Str>
1469

1470
For signatures with named parameters, specifies the method name used
1471
to retrieve this parameter's value from the C<< $arg >> object.
1472

1473
 signature_for process_data => (
1474
   method => true,
1475
   named  => [
1476
     input   => FileHandle,    { getter => 'in' },
1477
     output  => FileHandle,    { getter => 'out' },
1478
     flags   => HashRef[Bool], { slurpy => true },
1479
   ],
1480
 );
1481
 
1482
 sub process_data ( $self, $arg ) {
1483
   warn "Beginning data processing" if $arg->flags->{debug};
1484
   
1485
   my ( $in, $out ) = ( $arg->in, $arg->out );
1486
   ...;
1487
 }
1488
 
1489
 $widget->process_data(
1490
   input  => \*STDIN,
1491
   output => \*STDOUT,
1492
   debug  => true,
1493
 );
1494

1495
Ignored by signatures with positional parameters.
1496

1497
=head4 C<< predicate >> B<Str>
1498

1499
The C<< $arg >> object provided by signatures with named parameters
1500
will also include "has" methods for any optional arguments.
1501
For example:
1502

1503
 signature_for process_data => (
1504
   method => true,
1505
   named  => [
1506
     input   => Optional[ FileHandle ],
1507
     output  => Optional[ FileHandle ],
1508
     flags   => Slurpy[ HashRef[Bool] ],
1509
   ],
1510
 );
1511
 
1512
 sub process_data ( $self, $arg ) {
1513
   
1514
   if ( $self->has_input and $self->has_output ) {
1515
     ...;
1516
   }
1517
   
1518
   ...;
1519
 }
1520

1521
Setting a C<predicate> option allows you to choose a different name
1522
for this method instead of "has_*".
1523

1524
It is also possible to set a C<predicate> for non-optional parameters,
1525
which don't normally get a "has" method.
1526

1527
Ignored by signatures with positional parameters.
1528

1529
=head4 C<< alias >> B<< Str|ArrayRef[Str] >>
1530

1531
A list of alternative names for the parameter, or a single alternative
1532
name.
1533

1534
 signature_for add_numbers => (
1535
   named => [
1536
     first_number   => Int, { alias => [ 'x' ] },
1537
     second_number  => Int, { alias =>   'y'   },
1538
   ],
1539
 );
1540
 
1541
 sub add_numbers ( $arg ) {
1542
   return $arg->first_number + $arg->second_number;
1543
 }
1544
 
1545
 say add_numbers( first_number => 40, second_number => 2 );  # 42
1546
 say add_numbers( x            => 40, y             => 2 );  # 42
1547
 say add_numbers( first_number => 40, y             => 2 );  # 42
1548
 say add_numbers( first_number => 40, x => 1, y => 2 );      # dies!
1549

1550
Ignored by signatures with positional parameters.
1551

1552
=head4 C<< in_list >> B<Bool>
1553

1554
In conjunction with C<list_to_named>, determines if this parameter can
1555
be provided as part of the list of "sneaky" positional parameters.
1556
If C<list_to_named> isn't being used, C<in_list> is ignored.
1557

1558
Defaults to false if the parameter is optional or has a default.
1559
Defaults to true if the parameter is required.
1560

1561
=head4 C<< strictness >> B<Bool|Str>
1562

1563
Overrides the signature option C<strictness> on a per-parameter basis.
1564

1565
=head2 C<< signature_for_func $function_name => ( %spec ) >>
1566

1567
Like C<signature_for> and defaults to C<< method => false >>.
1568

1569
If the signature has named parameters, it will additionally default
1570
C<list_to_named> and C<allow_dash> to true.
1571

1572
 signature_for_func add_to_ref => (
1573
   named         => [ ref => ScalarRef[Num], add => Num ],
1574
   named_to_list => true,
1575
 );
1576
 
1577
 sub add_to_ref ( $ref, $add ) {
1578
   $ref->$* += $add;
1579
 }
1580
 
1581
 my $sum = 0;
1582
 add_to_ref( ref => \$sum, add => 1 );
1583
 add_to_ref( \$sum, 2 );
1584
 add_to_ref( 3, \$sum );
1585
 add_to_ref( 4, { -ref => \$sum } );
1586
 say $sum; # 10
1587

1588
The exact behaviour of C<signature_for_func> is unstable and may change
1589
in future versions of Type::Params.
1590

1591
=head2 C<< signature_for_method $function_name => ( %spec ) >>
1592

1593
Like C<signature_for> but will default C<< method => true >>.
1594

1595
If the signature has named parameters, it will additionally default
1596
C<list_to_named> and C<allow_dash> to true.
1597

1598
 package Calculator {
1599
   use Types::Standard qw( Num ScalarRef );
1600
   use Type::Params qw( signature_for_method );
1601
   
1602
   ...;
1603
   
1604
   signature_for_method add_to_ref => (
1605
     named         => [ ref => ScalarRef[Num], add => Num ],
1606
     named_to_list => true,
1607
   );
1608
   
1609
   sub add_to_ref ( $self, $ref, $add ) {
1610
     $ref->$* += $add;
1611
   }
1612
 }
1613
 
1614
 my $calc = Calculator->new;
1615
 my $sum = 0;
1616
 $calc->add_to_ref( ref => \$sum, add => 1 );
1617
 $calc->add_to_ref( \$sum, 2 );
1618
 $calc->add_to_ref( 3, \$sum );
1619
 $calc->add_to_ref( 4, { -ref => \$sum } );
1620
 say $sum; # 10
1621

1622
The exact behaviour of C<signature_for_method> is unstable and may change
1623
in future versions of Type::Params.
1624

1625
=head2 C<< signature( %spec ) >>
1626

1627
The C<signature> function allows more fine-grained control over signatures.
1628
Instead of automatically wrapping your function, it returns a coderef that
1629
you can pass C<< @_ >> to.
1630

1631
The following are roughly equivalent:
1632

1633
 signature_for add_nums => ( pos => [ Num, Num ] );
1634
 
1635
 sub add_nums ( $x, $y ) {
1636
   return $x + $y;
1637
 }
1638

1639
And:
1640

1641
 sub add_nums {
1642
   state $signature = signature( pos => [ Num, Num ] );
1643
   my ( $x, $y ) = $signature->( @_ );
1644
   
1645
   return $x + $y;
1646
 }
1647

1648
Perl allows a slightly archaic way of calling coderefs without using
1649
parentheses, which may be slightly faster at the cost of being more
1650
obscure:
1651

1652
 sub add_nums {
1653
   state $signature = signature( pos => [ Num, Num ] );
1654
   my ( $x, $y ) = &$signature; # important: no parentheses!
1655
   
1656
   return $x + $y;
1657
 }
1658

1659
If you need to support Perl 5.8, which didn't have the C<state> keyword:
1660

1661
 my $__add_nums_sig;
1662
 sub add_nums {
1663
   $__add_nums_sig ||= signature( pos => [ Num, Num ] );
1664
   my ( $x, $y ) = &$__add_nums_sig;
1665
   
1666
   ...;
1667
 }
1668

1669
This gives you more control over how and when the signature is built and
1670
used, and what is done with the values it unpacks.
1671

1672
In particular, note that if your function is never called, the signature
1673
never even gets built, meaning that for functions you rarely use, there's
1674
less cost to having the signature.
1675

1676
As of 2025, you probably want to be using C<signature_for> instead of
1677
C<signature> in most cases.
1678

1679
=head3 Additional Signature Specification Options
1680

1681
There are certain options which make no sense for C<signature_for>, and
1682
are only useful for C<signature>. Others may behave slightly differently.
1683
These are noted here.
1684

1685
=head4 C<< returns >> B<TypeTiny>, C<< returns_scalar >> B<TypeTiny>, and C<< returns_list >> B<TypeTiny>
1686

1687
Because C<signature> isn't capable of fully wrapping your function,
1688
the C<returns>, C<returns_scalar>, and C<returns_list> options cannot
1689
do anything. You should consider them to be documentation only.
1690

1691
=head4 C<< subname >> B<Str>
1692

1693
The name of the sub whose parameters we're supposed to be checking.
1694
This is useful in stack traces, etc. Defaults to the caller.
1695

1696
=head4 C<< package >> B<Str>
1697

1698
Works the same as in C<signature_for>, but it's worth mentioning it
1699
again as it ties in closely with C<subname>.
1700

1701
=head4 C<< caller_level >> B<Int>
1702

1703
If you're wrapping C<signature> so that you can check signatures on behalf
1704
of another package, then setting C<caller_level> to 1 (or more, depending on
1705
the level of wrapping!) may be an alternative to manually setting the
1706
C<package> and C<subname>.
1707

1708
=head4 C<< next >> B<< Bool|CodeLike >>
1709

1710
This can be used for chaining coderefs. If you understand C<on_die>, this
1711
acts like an "on_live".
1712

1713
 sub add_numbers {
1714
   state $sig = signature(
1715
     positional => [ Num, Num ],
1716
     next => sub {
1717
       my ( $num1, $num2 ) = @_;
1718
       
1719
       return $num1 + $num2;
1720
     },
1721
   );
1722
   
1723
   my $sum = $sig->( @_ );
1724
   return $sum;
1725
 }
1726
 
1727
 say add_numbers( 2, 3 );   # says 5
1728

1729
If set to true instead of a coderef, has a slightly different behaviour:
1730

1731
 sub add_numbers {
1732
   state $sig = signature(
1733
     positional => [ Num, Num ],
1734
     next       => true,
1735
   );
1736
   
1737
   my $sum = $sig->(
1738
     sub { return $_[0] + $_[1] },
1739
     @_,
1740
   );
1741
   return $sum;
1742
 }
1743
 
1744
 say add_numbers( 2, 3 );   # says 5
1745

1746
This looks strange. Why would this be useful? Well, it works nicely with
1747
Moose's C<around> keyword.
1748

1749
 sub add_numbers {
1750
   return $_[1] + $_[2];
1751
 }
1752
 
1753
 around add_numbers => signature(
1754
   method     => true,
1755
   positional => [ Num, Num ],
1756
   next       => true,
1757
   package    => __PACKAGE__,
1758
   subname    => 'add_numbers',
1759
 );
1760
 
1761
 say __PACKAGE__->add_numbers( 2, 3 );   # says 5
1762

1763
Note the way C<around> works in Moose is that it expects a wrapper coderef
1764
as its final argument. That wrapper coderef then expects to be given a
1765
reference to the original function as its first parameter.
1766

1767
This can allow, for example, a role to provide a signature wrapping
1768
a method defined in a class.
1769

1770
This is kind of complex, and you're unlikely to use it, but it's been proven
1771
useful for tools that integrate Type::Params with Moose-like method modifiers.
1772

1773
Note that C<next> is the mechanism that C<signature_for> internally
1774
uses to connect the signature with the wrapped sub, so using C<next>
1775
with C<signature_for> is a good recipe for headaches.
1776

1777
If using C<multiple> signatures, C<next> is useful for each "inner"
1778
signature to massage parameters into the correct order. This use of
1779
C<next> I<is> supported for C<signature_for>.
1780

1781
The option C<goto_next> is supported as a historical alias for C<next>.
1782

1783
=head4 C<< want_source >> B<Bool>
1784

1785
Instead of returning a coderef, return Perl source code string. Handy
1786
for debugging.
1787

1788
=head4 C<< want_details >> B<Bool>
1789

1790
Instead of returning a coderef, return a hashref of stuff including the
1791
coderef. This is mostly for people extending Type::Params and I won't go
1792
into too many details about what else this hashref contains.
1793

1794
=head4 C<< want_object >> B<Bool>
1795

1796
Instead of returning a coderef, return a Type::Params::Signature object.
1797
This is the more modern version of C<want_details>.
1798

1799
=head1 LEGACY API
1800

1801
The following functions were the API prior to Type::Params v2. They are
1802
still supported, but their use is now discouraged.
1803

1804
If you don't provide an import list at all, you will import C<compile>
1805
and C<compile_named>:
1806

1807
 use Type::Params;
1808

1809
This does the same:
1810

1811
  use Type::Params -v1;
1812

1813
The following exports C<compile>, C<compile_named>, and C<compile_named_oo>:
1814

1815
 use Type::Params -compile;
1816

1817
The following exports C<wrap_subs> and C<wrap_methods>:
1818

1819
 use Type::Params -wrap;
1820

1821
=head2 C<< compile( @pos_params ) >>
1822

1823
Equivalent to C<< signature( positional => \@pos_params ) >>.
1824

1825
C<< compile( \%spec, @pos_params ) >> is equivalent to
1826
C<< signature( %spec, positional => \@pos_params ) >>.
1827

1828
=head2 C<< compile_named( @named_params ) >>
1829

1830
Equivalent to C<< signature( bless => 0, named => \@named_params ) >>.
1831

1832
C<< compile_named( \%spec, @named_params ) >> is equivalent to
1833
C<< signature( bless => false, %spec, named => \@named_params ) >>.
1834

1835
=head2 C<< compile_named_oo( @named_params ) >>
1836

1837
Equivalent to C<< signature( bless => true, named => \@named_params ) >>.
1838

1839
C<< compile_named_oo( \%spec, @named_params ) >> is equivalent to
1840
C<< signature( bless => true, %spec, named => \@named_params ) >>.
1841

1842
=head2 C<< validate( \@args, @pos_params ) >>
1843

1844
Equivalent to C<< signature( positional => \@pos_params )->( @args ) >>.
1845

1846
The C<validate> function has I<never> been recommended, and is not
1847
exported unless requested by name.
1848

1849
=head2 C<< validate_named( \@args, @named_params ) >>
1850

1851
Equivalent to C<< signature( bless => false, named => \@named_params )->( @args ) >>.
1852

1853
The C<validate_named> function has I<never> been recommended, and is not
1854
exported unless requested by name.
1855

1856
=head2 C<< wrap_subs( func1 => \@params1, func2 => \@params2, ... ) >>
1857

1858
Equivalent to:
1859

1860
 signature_for func1 => ( positional => \@params1 );
1861
 signature_for func2 => ( positional => \@params2 );
1862

1863
One slight difference is that instead of arrayrefs, you can provide the
1864
output of one of the C<compile> functions:
1865

1866
 wrap_subs( func1 => compile_named( @params1 ) );
1867

1868
C<wrap_subs> is not exported unless requested by name.
1869

1870
=head2 C<< wrap_methods( func1 => \@params1, func2 => \@params2, ... ) >>
1871

1872
Equivalent to:
1873

1874
 signature_for func1 => ( method => 1, positional => \@params1 );
1875
 signature_for func2 => ( method => 1, positional => \@params2 );
1876

1877
One slight difference is that instead of arrayrefs, you can provide the
1878
output of one of the C<compile> functions:
1879

1880
 wrap_methods( func1 => compile_named( @params1 ) );
1881

1882
C<wrap_methods> is not exported unless requested by name.
1883

1884
=head2 C<< multisig( @alternatives ) >>
1885

1886
Equivalent to:
1887

1888
 signature( multiple => \@alternatives )
1889

1890
C<< multisig( \%spec, @alternatives ) >> is equivalent to
1891
C<< signature( %spec, multiple => \@alternatives ) >>.
1892

1893
=head1 TYPE CONSTRAINTS
1894

1895
Although Type::Params is not a real type library, it exports two type
1896
constraints. Their use is no longer recommended.
1897

1898
=head2 B<Invocant>
1899

1900
Type::Params exports a type B<Invocant> on request. This gives you a type
1901
constraint which accepts classnames I<and> blessed objects.
1902

1903
 use Type::Params qw( compile Invocant );
1904
 
1905
 signature_for my_method => (
1906
   method     => Invocant,
1907
   positional => [ ArrayRef, Int ],
1908
 );
1909
 
1910
 sub my_method ($self_or_class, $arr, $ix) {
1911
   return $arr->[ $ix ];
1912
 }
1913

1914
C<Invocant> is not exported unless requested by name.
1915

1916
Recommendation: use B<Defined> from L<Types::Standard> instead.
1917

1918
=head2 B<ArgsObject>
1919

1920
Type::Params exports a parameterizable type constraint B<ArgsObject>.
1921
It accepts the kinds of objects returned by signature checks for named
1922
parameters.
1923

1924
  use v5.36;
1925
  
1926
  package Foo {
1927
    use Moo;
1928
    use Type::Params 'ArgsObject';
1929
    
1930
    has args => (
1931
      is  => 'ro',
1932
      isa => ArgsObject['Bar::bar'],
1933
    );
1934
  }
1935
  
1936
  package Bar {
1937
    use Types::Standard -types;
1938
    use Type::Params 'signature_for';
1939
    
1940
    signature_for bar => ( named => [ xxx => Int, yyy => ArrayRef ] );
1941
    
1942
    sub bar ( $got ) {
1943
      return 'Foo'->new( args => $got );
1944
    }
1945
  }
1946
  
1947
  Bar::bar( xxx => 42, yyy => [] );
1948

1949
The parameter "Bar::bar" refers to the caller when the check is compiled,
1950
rather than when the parameters are checked.
1951

1952
C<ArgsObject> is not exported unless requested by name.
1953

1954
Recommendation: use B<Object> from L<Types::Standard> instead.
1955

1956
=head1 ENVIRONMENT
1957

1958
=over
1959

1960
=item C<PERL_TYPE_PARAMS_XS>
1961

1962
Affects the building of accessors for C<< $arg >> objects. If set to true,
1963
will use L<Class::XSAccessor>. If set to false, will use pure Perl. If this
1964
environment variable does not exist, will use Class::XSAccessor.
1965

1966
If Class::XSAccessor is not installed or is too old, pure Perl will always
1967
be used as a fallback.
1968

1969
=back
1970

1971
=head1 BUGS
1972

1973
Please report any bugs to
1974
L<https://github.com/tobyink/p5-type-tiny/issues>.
1975

1976
=head1 SEE ALSO
1977

1978
L<The Type::Tiny homepage|https://typetiny.toby.ink/>.
1979

1980
L<Type::Tiny>, L<Type::Coercion>, L<Types::Standard>.
1981

1982
=head1 AUTHOR
1983

1984
Toby Inkster E<lt>tobyink@cpan.orgE<gt>.
1985

1986
=head1 COPYRIGHT AND LICENCE
1987

1988
This software is copyright (c) 2013-2014, 2017-2025 by Toby Inkster.
1989

1990
This is free software; you can redistribute it and/or modify it under
1991
the same terms as the Perl 5 programming language system itself.
1992

1993
=head1 DISCLAIMER OF WARRANTIES
1994

1995
THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
1996
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
1997
MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc