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