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