version 1.0201
[p5sagit/Function-Parameters.git] / lib / Function / Parameters.pm
CommitLineData
7a63380c 1package Function::Parameters;
2
7dd35535 3use v5.14.0;
7a63380c 4use warnings;
5
63915d26 6use Carp qw(confess);
7
db81d362 8use XSLoader;
9BEGIN {
3746f917 10 our $VERSION = '1.0201';
db81d362 11 XSLoader::load;
7a63380c 12}
13
2d5cf47a 14sub _assert_valid_identifier {
15 my ($name, $with_dollar) = @_;
16 my $bonus = $with_dollar ? '\$' : '';
17 $name =~ /^${bonus}[^\W\d]\w*\z/
18 or confess qq{"$name" doesn't look like a valid identifier};
19}
20
b72eb6ee 21sub _assert_valid_attributes {
22 my ($attrs) = @_;
4b76be72 23 $attrs =~ m{
24 ^ \s*+
25 : \s*+
26 (?&ident) (?! [^\s:(] ) (?&param)?+ \s*+
27 (?:
28 (?: : \s*+ )?
29 (?&ident) (?! [^\s:(] ) (?&param)?+ \s*+
30 )*+
31 \z
32
33 (?(DEFINE)
34 (?<ident>
35 [^\W\d]
36 \w*+
37 )
38 (?<param>
39 \(
40 [^()\\]*+
41 (?:
42 (?:
43 \\ .
44 |
45 (?&param)
46 )
47 [^()\\]*+
48 )*+
49 \)
50 )
51 )
52 }sx or confess qq{"$attrs" doesn't look like valid attributes};
b72eb6ee 53}
54
7193dffb 55sub _reify_type_default {
56 require Moose::Util::TypeConstraints;
57 Moose::Util::TypeConstraints::find_or_create_isa_type_constraint($_[0])
58}
59
11305599 60sub _delete_default {
61 my ($href, $key, $default) = @_;
62 exists $href->{$key} ? delete $href->{$key} : $default
63}
64
125c067e 65my @bare_arms = qw(function method);
2d5cf47a 66my %type_map = (
11c807bc 67 function => {
68 name => 'optional',
69 default_arguments => 1,
63915d26 70 check_argument_count => 0,
11c807bc 71 named_parameters => 1,
72 types => 1,
7193dffb 73 reify_type => \&_reify_type_default,
63915d26 74 },
11c807bc 75 method => {
76 name => 'optional',
77 default_arguments => 1,
63915d26 78 check_argument_count => 0,
11c807bc 79 named_parameters => 1,
80 types => 1,
7193dffb 81 reify_type => \&_reify_type_default,
11c807bc 82 attrs => ':method',
83 shift => '$self',
84 invocant => 1,
7947f7ce 85 },
11c807bc 86 classmethod => {
87 name => 'optional',
88 default_arguments => 1,
63915d26 89 check_argument_count => 0,
11c807bc 90 named_parameters => 1,
91 types => 1,
7193dffb 92 reify_type => \&_reify_type_default,
11c807bc 93 attributes => ':method',
94 shift => '$class',
95 invocant => 1,
a23979e1 96 },
2d5cf47a 97);
7817d698 98for my $k (keys %type_map) {
99 $type_map{$k . '_strict'} = {
100 %{$type_map{$k}},
101 check_argument_count => 1,
102 };
103}
c9a39f6b 104
7193dffb 105our @type_reifiers = \&_reify_type_default;
106
db81d362 107sub import {
108 my $class = shift;
7a63380c 109
fcaf7811 110 if (!@_) {
111 @_ = {
112 fun => 'function',
113 method => 'method',
114 };
115 }
116 if (@_ == 1 && $_[0] eq ':strict') {
117 @_ = {
118 fun => 'function_strict',
119 method => 'method_strict',
120 };
121 }
125c067e 122 if (@_ == 1 && ref($_[0]) eq 'HASH') {
fcaf7811 123 @_ = map [$_, $_[0]{$_}], keys %{$_[0]};
125c067e 124 }
7a63380c 125
125c067e 126 my %spec;
127
128 my $bare = 0;
129 for my $proto (@_) {
130 my $item = ref $proto
131 ? $proto
132 : [$proto, $bare_arms[$bare++] || confess(qq{Don't know what to do with "$proto"})]
133 ;
ae6e00b5 134 my ($name, $proto_type) = @$item;
2d5cf47a 135 _assert_valid_identifier $name;
136
ae6e00b5 137 unless (ref $proto_type) {
138 # use '||' instead of 'or' to preserve $proto_type in the error message
139 $proto_type = $type_map{$proto_type}
140 || confess qq["$proto_type" doesn't look like a valid type (one of ${\join ', ', sort keys %type_map})];
2d5cf47a 141 }
b72eb6ee 142
ae6e00b5 143 my %type = %$proto_type;
144 my %clean;
10acc8b1 145
ae6e00b5 146 $clean{name} = delete $type{name} || 'optional';
147 $clean{name} =~ /^(?:optional|required|prohibited)\z/
148 or confess qq["$clean{name}" doesn't look like a valid name attribute (one of optional, required, prohibited)];
10acc8b1 149
ae6e00b5 150 $clean{shift} = delete $type{shift} || '';
10acc8b1 151 _assert_valid_identifier $clean{shift}, 1 if $clean{shift};
152
698e861c 153 $clean{attrs} = join ' ', map delete $type{$_} || (), qw(attributes attrs);
10acc8b1 154 _assert_valid_attributes $clean{attrs} if $clean{attrs};
125c067e 155
11305599 156 $clean{default_arguments} = _delete_default \%type, 'default_arguments', 1;
157 $clean{named_parameters} = _delete_default \%type, 'named_parameters', 1;
158 $clean{types} = _delete_default \%type, 'types', 1;
7193dffb 159
11305599 160 $clean{check_argument_count} = _delete_default \%type, 'check_argument_count', 0;
161 $clean{invocant} = _delete_default \%type, 'invocant', 0;
63915d26 162
7193dffb 163 if (my $rt = delete $type{reify_type}) {
164 ref $rt eq 'CODE' or confess qq{"$rt" doesn't look like a type reifier};
165
166 my $index;
167 for my $i (0 .. $#type_reifiers) {
168 if ($type_reifiers[$i] == $rt) {
169 $index = $i;
170 last;
171 }
172 }
173 unless (defined $index) {
174 $index = @type_reifiers;
175 push @type_reifiers, $rt;
176 }
177
178 $clean{reify_type} = $index;
179 }
180
ae6e00b5 181 %type and confess "Invalid keyword property: @{[keys %type]}";
182
183 $spec{$name} = \%clean;
125c067e 184 }
185
db81d362 186 for my $kw (keys %spec) {
187 my $type = $spec{$kw};
188
63915d26 189 my $flags =
11c807bc 190 $type->{name} eq 'prohibited' ? FLAG_ANON_OK :
191 $type->{name} eq 'required' ? FLAG_NAME_OK :
192 FLAG_ANON_OK | FLAG_NAME_OK
63915d26 193 ;
11c807bc 194 $flags |= FLAG_DEFAULT_ARGS if $type->{default_arguments};
51a483f8 195 $flags |= FLAG_CHECK_NARGS | FLAG_CHECK_TARGS if $type->{check_argument_count};
11c807bc 196 $flags |= FLAG_INVOCANT if $type->{invocant};
197 $flags |= FLAG_NAMED_PARAMS if $type->{named_parameters};
198 $flags |= FLAG_TYPES_OK if $type->{types};
63915d26 199 $^H{HINTK_FLAGS_ . $kw} = $flags;
ae6e00b5 200 $^H{HINTK_SHIFT_ . $kw} = $type->{shift};
10acc8b1 201 $^H{HINTK_ATTRS_ . $kw} = $type->{attrs};
7193dffb 202 $^H{HINTK_REIFY_ . $kw} = $type->{reify_type} // 0;
db81d362 203 $^H{+HINTK_KEYWORDS} .= "$kw ";
125c067e 204 }
eeb7df5f 205}
206
db81d362 207sub unimport {
eeb7df5f 208 my $class = shift;
125c067e 209
db81d362 210 if (!@_) {
211 delete $^H{+HINTK_KEYWORDS};
125c067e 212 return;
213 }
214
db81d362 215 for my $kw (@_) {
216 $^H{+HINTK_KEYWORDS} =~ s/(?<![^ ])\Q$kw\E //g;
125c067e 217 }
218}
219
db81d362 220
53c979f0 221our %metadata;
222
223sub _register_info {
224 my (
225 $key,
226 $declarator,
227 $invocant,
51a483f8 228 $invocant_type,
53c979f0 229 $positional_required,
230 $positional_optional,
231 $named_required,
232 $named_optional,
233 $slurpy,
51a483f8 234 $slurpy_type,
53c979f0 235 ) = @_;
236
51a483f8 237 my $info = {
238 declarator => $declarator,
239 invocant => defined $invocant ? [$invocant, $invocant_type] : undef,
240 slurpy => defined $slurpy ? [$slurpy , $slurpy_type ] : undef,
241 positional_required => $positional_required,
242 positional_optional => $positional_optional,
243 named_required => $named_required,
244 named_optional => $named_optional,
245 };
246
247 $metadata{$key} = $info;
248}
249
250sub _mkparam1 {
251 my ($pair) = @_;
252 my ($v, $t) = @{$pair || []} or return undef;
253 Function::Parameters::Param->new(
254 name => $v,
255 type => $t,
256 )
257}
258
259sub _mkparams {
260 my @r;
261 while (my ($v, $t) = splice @_, 0, 2) {
262 push @r, Function::Parameters::Param->new(
263 name => $v,
264 type => $t,
265 );
266 }
267 \@r
53c979f0 268}
269
270sub info {
271 my ($func) = @_;
272 my $key = _cv_root $func or return undef;
51a483f8 273 my $info = $metadata{$key} or return undef;
53c979f0 274 require Function::Parameters::Info;
275 Function::Parameters::Info->new(
51a483f8 276 keyword => $info->{declarator},
277 invocant => _mkparam1($info->{invocant}),
278 slurpy => _mkparam1($info->{slurpy}),
279 (map +("_$_" => _mkparams @{$info->{$_}}), glob '{positional,named}_{required,optional}')
53c979f0 280 )
281}
282
125c067e 283'ok'
7a63380c 284
285__END__
286
f2541b7d 287=encoding UTF-8
288
7a63380c 289=head1 NAME
290
291Function::Parameters - subroutine definitions with parameter lists
292
293=head1 SYNOPSIS
294
81203272 295 use Function::Parameters qw(:strict);
7a63380c 296
698e861c 297 # simple function
7a63380c 298 fun foo($bar, $baz) {
299 return $bar + $baz;
300 }
301
698e861c 302 # function with prototype
d71d548b 303 fun mymap($fun, @args)
304 :(&@)
305 {
7a63380c 306 my @res;
307 for (@args) {
308 push @res, $fun->($_);
309 }
310 @res
311 }
312
313 print "$_\n" for mymap { $_ * 2 } 1 .. 4;
125c067e 314
698e861c 315 # method with implicit $self
125c067e 316 method set_name($name) {
317 $self->{name} = $name;
318 }
d8e5d540 319
320 # method with explicit invocant
321 method new($class: %init) {
322 return bless { %init }, $class;
323 }
324
81203272 325 # function with optional parameters
698e861c 326 fun search($haystack, $needle = qr/^(?!)/, $offset = 0) {
327 ...
328 }
d8e5d540 329
81203272 330 # method with named parameters
331 method resize(:$width, :$height) {
332 $self->{width} = $width;
333 $self->{height} = $height;
698e861c 334 }
8dbfd12d 335
81203272 336 $obj->resize(height => 4, width => 5);
8dbfd12d 337
81203272 338 # function with named optional parameters
339 fun search($haystack, :$needle = qr/^(?!)/, :$offset = 0) {
340 ...
341 }
8dbfd12d 342
81203272 343 my $results = search $text, offset => 200;
8dbfd12d 344
81203272 345=head1 DESCRIPTION
8dbfd12d 346
81203272 347This module extends Perl with keywords that let you define functions with
348parameter lists. It uses Perl's L<keyword plugin|perlapi/PL_keyword_plugin>
349API, so it works reliably and doesn't require a source filter.
350
351=head2 Basics
352
353The anatomy of a function (as recognized by this module):
354
355=over
8dbfd12d 356
81203272 357=item 1.
358
359The keyword introducing the function.
360
361=item 2.
362
363The function name (optional).
364
365=item 3.
366
367The parameter list (optional).
368
369=item 4.
370
371The prototype (optional).
372
373=item 5.
374
375The attribute list (optional).
376
377=item 6.
378
379The function body.
380
381=back
382
383Example:
384
385 # (1) (2) (3) (4) (5) (6)
386 fun foo ($x, $y) :($$) :lvalue { ... }
c9a39f6b 387
81203272 388 # (1) (6)
389 my $f = fun { ... };
125c067e 390
81203272 391In the following section I'm going to describe all parts in order from simplest to most complex.
7a63380c 392
81203272 393=head3 Body
7a63380c 394
81203272 395This is just a normal block of statements, as with L<C<sub>|perlsub>. No surprises here.
7a63380c 396
81203272 397=head3 Name
7a63380c 398
81203272 399If present, it specifies the name of the function being defined. As with
400L<C<sub>|perlsub>, if a name is present, the whole declaration is syntactically
401a statement and its effects are performed at compile time (i.e. at runtime you
402can call functions whose definitions only occur later in the file). If no name
403is present, the declaration is an expression that evaluates to a reference to
404the function in question. No surprises here either.
7a63380c 405
81203272 406=head3 Attributes
7a63380c 407
81203272 408Attributes are relatively unusual in Perl code, but if you want them, they work
409exactly the same as with L<C<sub>|perlsub/Subroutine-Attributes>.
c9a39f6b 410
81203272 411=head3 Prototype
698e861c 412
81203272 413As with L<C<sub>|perlsub/Prototypes>, a prototype, if present, contains hints as to how
414the compiler should parse calls to this function. This means prototypes have no
415effect if the function call is compiled before the function declaration has
416been seen by the compiler or if the function to call is only determined at
417runtime (e.g. because it's called as a method or through a reference).
698e861c 418
81203272 419With L<C<sub>|perlsub>, a prototype comes directly after the function name (if
420any). C<Function::Parameters> reserves this spot for the
421L<parameter list|/"Parameter list">. To specify a prototype, put it as the
422first attribute (e.g. C<fun foo :(&$$)>). This is syntactically unambiguous
423because normal L<attributes|/Attributes> need a name after the colon.
7a63380c 424
81203272 425=head3 Parameter list
125c067e 426
81203272 427The parameter list is a list of variables enclosed in parentheses, except it's
428actually a bit more complicated than that. A parameter list can include the
429following 6 parts, all of which are optional:
125c067e 430
81203272 431=over
125c067e 432
81203272 433=item 1. Invocant
125c067e 434
81203272 435This is a scalar variable followed by a colon (C<:>) and no comma. If an
436invocant is present in the parameter list, the first element of
437L<C<@_>|perlvar/@ARG> is automatically L<C<shift>ed|perlfunc/shift> off and
438placed in this variable. This is intended for methods:
125c067e 439
81203272 440 method new($class: %init) {
441 return bless { %init }, $class;
442 }
443
444 method throw($self:) {
445 die $self;
446 }
125c067e 447
81203272 448=item 2. Required positional parameters
fcaf7811 449
81203272 450The most common kind of parameter. This is simply a comma-separated list of
451scalars, which are filled from left to right with the arguments that the caller
452passed in:
fcaf7811 453
81203272 454 fun add($x, $y) {
455 return $x + $y;
456 }
457
458 say add(2, 3); # "5"
459
460=item 3. Optional positional parameters
461
462Parameters can be marked as optional by putting an equals sign (C<=>) and an
463expression (the "default argument") after them. If no corresponding argument is
464passed in by the caller, the default argument will be used to initialize the
465parameter:
466
467 fun scale($base, $factor = 2) {
468 return $base * $factor;
469 }
470
471 say scale(3, 5); # "15"
472 say scale(3); # "6"
473
474The default argument is I<not> cached. Every time a function is called with
475some optional arguments missing, the corresponding default arguments are
476evaluated from left to right. This makes no difference for a value like C<2>
477but it is important for expressions with side effects, such as reference
478constructors (C<[]>, C<{}>) or function calls.
479
480Default arguments see not only the surrounding lexical scope of their function
481but also any preceding parameters. This allows the creation of dynamic defaults
482based on previous arguments:
483
484 method set_name($self: $nick = $self->default_nick, $real_name = $nick) {
485 $self->{nick} = $nick;
486 $self->{real_name} = $real_name;
487 }
488
489 $obj->set_name("simplicio"); # same as: $obj->set_name("simplicio", "simplicio");
63a24d7c 490
81203272 491Because default arguments are actually evaluated as part of the function body,
492you can also do silly things like this:
493
494 fun foo($n = return "nope") {
495 "you gave me $n"
496 }
497
498 say foo(2 + 2); # "you gave me 4"
499 say foo(); # "nope"
500
501=item 4. Required named parameters
502
503By putting a colon (C<:>) in front of a parameter you can make it named
504instead of positional:
505
506 fun rectangle(:$width, :$height) {
507 ...
508 }
509
510 rectangle(width => 2, height => 5);
511 rectangle(height => 5, width => 2); # same thing!
512
513That is, the caller must specify a key name in addition to the value, but in
514exchange the order of the arguments doesn't matter anymore. As with hash
515initialization, you can specify the same key multiple times and the last
516occurrence wins:
517
849229d4 518 rectangle(height => 1, width => 2, height => 2, height => 5);
81203272 519 # same as: rectangle(width => 2, height => 5);
520
521You can combine positional and named parameters as long as the positional
522parameters come first:
523
524 fun named_rectangle($name, :$width, :$height) {
525 ...
526 }
527
528 named_rectangle("Avocado", width => 0.5, height => 1.2);
529
530=item 5. Optional named parameters
531
532As with positional parameters, you can make named parameters optional by
533specifying a default argument after an equals sign (C<=>):
534
535 fun rectangle(:$width, :$height, :$color = "chartreuse") {
536 ...
537 }
538
539 rectangle(height => 10, width => 5);
540 # same as: rectangle(height => 10, width => 5, color => "chartreuse");
125c067e 541
542=cut
543
544=pod
81203272 545
546 fun get($url, :$cookie_jar = HTTP::Cookies->new(), :$referrer = $url) {
547 ...
548 }
125c067e 549
81203272 550 my $data = get "http://www.example.com/", referrer => undef; # overrides $referrer = $url
125c067e 551
81203272 552The above example shows that passing any value (even C<undef>) will override
553the default argument.
63a24d7c 554
81203272 555=item 6. Slurpy parameter
ce052c57 556
81203272 557Finally you can put an array or hash in the parameter list, which will gobble
558up the remaining arguments (if any):
ce052c57 559
81203272 560 fun foo($x, $y, @rest) { ... }
561
562 foo "a", "b"; # $x = "a", $y = "b", @rest = ()
563 foo "a", "b", "c"; # $x = "a", $y = "b", @rest = ("c")
564 foo "a", "b", "c", "d"; # $x = "a", $y = "b", @rest = ("c", "d")
ce052c57 565
81203272 566If you combine this with named parameters, the slurpy parameter will end up
567containing all unrecognized keys:
ce052c57 568
81203272 569 fun bar(:$size, @whatev) { ... }
570
571 bar weight => 20, size => 2, location => [0, -3];
572 # $size = 2, @whatev = ('weight', 20, 'location', [0, -3])
ce052c57 573
81203272 574=back
ce052c57 575
81203272 576Apart from the L<C<shift>|perlfunc/shift> performed by the L<invocant|/"1.
577Invocant">, all of the above leave L<C<@_>|perlvar/@ARG> unchanged; and if you
578don't specify a parameter list at all, L<C<@_>|perlvar/@ARG> is all you get.
d8e5d540 579
81203272 580=head3 Keyword
d8e5d540 581
81203272 582The keywords provided by C<Function::Parameters> are customizable. Since
583C<Function::Parameters> is actually a L<pragma|perlpragma>, the provided
584keywords have lexical scope. The following import variants can be used:
d8e5d540 585
81203272 586=over
273c6544 587
81203272 588=item C<use Function::Parameters ':strict'>
273c6544 589
81203272 590Provides the keywords C<fun> and C<method> (described below) and enables
591argument checks so that calling a function and omitting a required argument (or
592passing too many arguments) will throw an error.
273c6544 593
81203272 594=item C<use Function::Parameters>
273c6544 595
81203272 596Provides the keywords C<fun> and C<method> (described below) and enables
597"lax" mode: Omitting a required argument sets it to C<undef> while excess
598arguments are silently ignored.
273c6544 599
81203272 600=item C<< use Function::Parameters { KEYWORD1 => TYPE1, KEYWORD2 => TYPE2, ... } >>
698e861c 601
81203272 602Provides completely custom keywords as described by their types. A "type" is
603either a string (one of the predefined types C<function>, C<method>,
604C<classmethod>, C<function_strict>, C<method_strict>, C<classmethod_strict>) or
605a reference to a hash with the following keys:
698e861c 606
81203272 607=over
698e861c 608
81203272 609=item C<name>
698e861c 610
81203272 611Valid values: C<optional> (default), C<required> (all functions defined with
612this keyword must have a name), and C<prohibited> (functions defined with this
613keyword must be anonymous).
698e861c 614
81203272 615=item C<shift>
698e861c 616
81203272 617Valid values: strings that look like scalar variables. This lets you specify a
618default L<invocant|/"1. Invocant">, i.e. a function defined with this keyword
619that doesn't have an explicit invocant in its parameter list will automatically
620L<C<shift>|perlfunc/shift> its first argument into the variable specified here.
698e861c 621
81203272 622=item C<invocant>
698e861c 623
81203272 624Valid values: booleans. If you set this to a true value, the keyword will
625accept L<invocants|/"1. Invocant"> in parameter lists; otherwise specifying
626an invocant in a function defined with this keyword is a syntax error.
698e861c 627
81203272 628=item C<attributes>
698e861c 629
81203272 630Valid values: strings containing (source code for) attributes. This causes any
631function defined with this keyword to have the specified
632L<attributes|attributes> (in addition to any attributes specified in the
633function definition itself).
698e861c 634
81203272 635=item C<default_arguments>
698e861c 636
81203272 637Valid values: booleans. This property is on by default; use
638C<< default_arguments => 0 >> to turn it off. This controls whether optional
639parameters are allowed. If it is turned off, using C<=> in parameter lists is
640a syntax error.
698e861c 641
81203272 642=item C<check_argument_count>
698e861c 643
81203272 644Valid values: booleans. If turned on, functions defined with this keyword will
645automatically check that they have been passed all required arguments and no
646excess arguments. If this check fails, an exception will by thrown via
647L<C<Carp::croak>|Carp>.
698e861c 648
7193dffb 649Currently this flag is overloaded to also enable type checks (see
650L</Experimental feature: Types> below).
651
652=item C<reify_type>
653
654Valid values: code references. The function specified here will be called to
655turn type annotations into constraint objects (see
e7c6de2c 656L</Experimental feature: Types> below). It will receive two arguments: a string
657containing the type description, and the name of the current package.
7193dffb 658
659The default type reifier is equivalent to:
660
661 sub {
662 require Moose::Util::TypeConstraints;
663 Moose::Util::TypeConstraints::find_or_create_isa_type_constraint($_[0])
664 }
665
ce052c57 666=back
667
81203272 668The predefined type C<function> is equivalent to:
698e861c 669
670 {
11c807bc 671 name => 'optional',
672 invocant => 0,
673 default_arguments => 1,
698e861c 674 check_argument_count => 0,
675 }
676
81203272 677These are all default values, so C<function> is also equivalent to C<{}>.
698e861c 678
81203272 679C<method> is equivalent to:
698e861c 680
681 {
11c807bc 682 name => 'optional',
683 shift => '$self',
684 invocant => 1,
685 attributes => ':method',
686 default_arguments => 1,
81203272 687 check_argument_count => 0,
698e861c 688 }
689
7817d698 690
81203272 691C<classmethod> is equivalent to:
698e861c 692
693 {
11c807bc 694 name => 'optional',
695 shift => '$class',
696 invocant => 1,
697 attributes => ':method',
698 default_arguments => 1,
81203272 699 check_argument_count => 0,
698e861c 700 }
ce052c57 701
81203272 702C<function_strict>, C<method_strict>, and
703C<classmethod_strict> are like C<function>, C<method>, and
704C<classmethod>, respectively, but with C<< check_argument_count => 1 >>.
63a24d7c 705
81203272 706=back
63a24d7c 707
81203272 708Plain C<use Function::Parameters> is equivalent to
709C<< use Function::Parameters { fun => 'function', method => 'method' } >>.
63a24d7c 710
81203272 711C<use Function::Parameters qw(:strict)> is equivalent to
712C<< use Function::Parameters { fun => 'function_strict', method => 'method_strict' } >>.
63a24d7c 713
ebdc721b 714=head2 Introspection
715
716You can ask a function at runtime what parameters it has. This functionality is
717available through the function C<Function::Parameters::info> (which is not
718exported, so you have to call it by its full name). It takes a reference to a
719function, and returns either C<undef> (if it knows nothing about the function)
720or a L<Function::Parameters::Info> object describing the parameter list.
721
af04c6f1 722Note: This feature is implemented using L<Moo>, so you'll need to have L<Moo>
b70db867 723installed if you want to call C<Function::Parameters::info> (alternatively, if
724L<Moose> is already loaded by the time C<Function::Parameters::info> is first
725called, it will use that instead).
af04c6f1 726
ebdc721b 727See L<Function::Parameters::Info> for examples.
728
81203272 729=head2 Wrapping C<Function::Parameters>
125c067e 730
81203272 731If you want to write a wrapper around C<Function::Parameters>, you only have to
732call its C<import> method. Due to its L<pragma|perlpragma> nature it always
733affects the file that is currently being compiled.
63a24d7c 734
735 package Some::Wrapper;
736 use Function::Parameters ();
737 sub import {
738 Function::Parameters->import;
698e861c 739 # or Function::Parameters->import(@custom_import_args);
63a24d7c 740 }
eeb7df5f 741
0175ff9a 742=head2 Experimental feature: Types
743
744An experimental feature is now available: You can annotate parameters with
7193dffb 745types. That is, before each parameter you can put a type specification
746consisting of identifiers (C<Foo>), unions (C<... | ...>), and parametric types
747(C<...[...]>). Example:
0175ff9a 748
749 fun foo(Int $n, ArrayRef[String | CodeRef] $cb) { ... }
750
7193dffb 751If you do this, the type reification function corresponding to the keyword will
752be called to turn the type (a string) into a constraint object. The default
753type reifier simply loads L<Moose> and forwards to
754L<C<Moose::Util::TypeConstraints::find_or_parse_type_constraint>|Moose::Util::TypeConstraints/find_or_parse_type_constraint>,
755which creates L<Moose types|Moose::Manual::Types>.
0175ff9a 756
757If you are in "lax" mode, nothing further happens and the types are ignored. If
758you are in "strict" mode, C<Function::Parameters> generates code to make sure
759any values passed in conform to the type (via
d54d249f 760L<< C<< $constraint->check($value) >>|Moose::Meta::TypeConstraint/$constraint->check($value) >>).
0175ff9a 761
762In addition, these type constraints are inspectable through the
763L<Function::Parameters::Info> object returned by
764L<C<Function::Parameters::info>|/Introspection>.
765
766=head2 Experimental experimental feature: Type expressions
767
768An even more experimental feature is the ability to specify arbitrary
769expressions as types. The syntax for this is like the literal types described
770above, but with an expression wrapped in parentheses (C<( EXPR )>). Example:
771
772 fun foo(('Int') $n, ($othertype) $x) { ... }
773
774Every type expression must return either a string (which is resolved as for
775literal types), or a L<type constraint object|Moose::Meta::TypeConstraint>
776(providing C<check> and C<get_message> methods).
777
778Note that these expressions are evaluated (once) at parse time (similar to
779C<BEGIN> blocks), so make sure that any variables you use are set and any
780functions you call are defined at parse time.
781
81203272 782=head2 How it works
783
784The module is actually written in L<C|perlxs> and uses
785L<C<PL_keyword_plugin>|perlapi/PL_keyword_plugin> to generate opcodes directly.
786However, you can run L<C<perl -MO=Deparse ...>|B::Deparse> on your code to see
787what happens under the hood. In the simplest case (no argument checks, possibly
788an L<invocant|/"1. Invocant">, required positional/slurpy parameters only), the
789generated code corresponds to:
790
791 fun foo($x, $y, @z) { ... }
792 # ... turns into ...
793 sub foo { my ($x, $y, @z) = @_; sub foo; ... }
794
795 method bar($x, $y, @z) { ... }
796 # ... turns into ...
797 sub bar :method { my $self = shift; my ($x, $y, @z) = @_; sub bar; ... }
798
0175ff9a 799=head1 SUPPORT AND DOCUMENTATION
800
801After installing, you can find documentation for this module with the
802perldoc command.
803
804 perldoc Function::Parameters
805
806You can also look for information at:
807
808=over
809
810=item MetaCPAN
811
812L<https://metacpan.org/module/Function%3A%3AParameters>
813
814=item RT, CPAN's request tracker
815
816L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Function-Parameters>
817
818=item AnnoCPAN, Annotated CPAN documentation
819
820L<http://annocpan.org/dist/Function-Parameters>
821
822=item CPAN Ratings
823
824L<http://cpanratings.perl.org/d/Function-Parameters>
825
826=item Search CPAN
827
828L<http://search.cpan.org/dist/Function-Parameters/>
829
830=back
831
ebdc721b 832=head1 SEE ALSO
833
834L<Function::Parameters::Info>
835
7a63380c 836=head1 AUTHOR
837
838Lukas Mai, C<< <l.mai at web.de> >>
839
840=head1 COPYRIGHT & LICENSE
841
b70db867 842Copyright 2010-2013 Lukas Mai.
7a63380c 843
844This program is free software; you can redistribute it and/or modify it
845under the terms of either: the GNU General Public License as published
846by the Free Software Foundation; or the Artistic License.
847
848See http://dev.perl.org/licenses/ for more information.
849
850=cut