1 package Function::Parameters;
10 our $VERSION = '1.0104';
14 sub _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};
21 sub _assert_valid_attributes {
26 (?&ident) (?! [^\s:(] ) (?¶m)?+ \s*+
29 (?&ident) (?! [^\s:(] ) (?¶m)?+ \s*+
52 }sx or confess qq{"$attrs" doesn't look like valid attributes};
55 sub _reify_type_default {
56 require Moose::Util::TypeConstraints;
57 Moose::Util::TypeConstraints::find_or_create_isa_type_constraint($_[0])
60 my @bare_arms = qw(function method);
64 default_arguments => 1,
65 check_argument_count => 0,
66 named_parameters => 1,
68 reify_type => \&_reify_type_default,
72 default_arguments => 1,
73 check_argument_count => 0,
74 named_parameters => 1,
76 reify_type => \&_reify_type_default,
83 default_arguments => 1,
84 check_argument_count => 0,
85 named_parameters => 1,
87 reify_type => \&_reify_type_default,
88 attributes => ':method',
93 for my $k (keys %type_map) {
94 $type_map{$k . '_strict'} = {
96 check_argument_count => 1,
100 our @type_reifiers = \&_reify_type_default;
111 if (@_ == 1 && $_[0] eq ':strict') {
113 fun => 'function_strict',
114 method => 'method_strict',
117 if (@_ == 1 && ref($_[0]) eq 'HASH') {
118 @_ = map [$_, $_[0]{$_}], keys %{$_[0]};
125 my $item = ref $proto
127 : [$proto, $bare_arms[$bare++] || confess(qq{Don't know what to do with "$proto"})]
129 my ($name, $proto_type) = @$item;
130 _assert_valid_identifier $name;
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})];
138 my %type = %$proto_type;
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)];
145 $clean{shift} = delete $type{shift} || '';
146 _assert_valid_identifier $clean{shift}, 1 if $clean{shift};
148 $clean{attrs} = join ' ', map delete $type{$_} || (), qw(attributes attrs);
149 _assert_valid_attributes $clean{attrs} if $clean{attrs};
151 $clean{default_arguments} =
152 exists $type{default_arguments}
153 ? !!delete $type{default_arguments}
157 $clean{check_argument_count} = !!delete $type{check_argument_count};
158 $clean{invocant} = !!delete $type{invocant};
159 $clean{named_parameters} = !!delete $type{named_parameters};
160 $clean{types} = !!delete $type{types};
162 if (my $rt = delete $type{reify_type}) {
163 ref $rt eq 'CODE' or confess qq{"$rt" doesn't look like a type reifier};
166 for my $i (0 .. $#type_reifiers) {
167 if ($type_reifiers[$i] == $rt) {
172 unless (defined $index) {
173 $index = @type_reifiers;
174 push @type_reifiers, $rt;
177 $clean{reify_type} = $index;
180 %type and confess "Invalid keyword property: @{[keys %type]}";
182 $spec{$name} = \%clean;
185 for my $kw (keys %spec) {
186 my $type = $spec{$kw};
189 $type->{name} eq 'prohibited' ? FLAG_ANON_OK :
190 $type->{name} eq 'required' ? FLAG_NAME_OK :
191 FLAG_ANON_OK | FLAG_NAME_OK
193 $flags |= FLAG_DEFAULT_ARGS if $type->{default_arguments};
194 $flags |= FLAG_CHECK_NARGS | FLAG_CHECK_TARGS if $type->{check_argument_count};
195 $flags |= FLAG_INVOCANT if $type->{invocant};
196 $flags |= FLAG_NAMED_PARAMS if $type->{named_parameters};
197 $flags |= FLAG_TYPES_OK if $type->{types};
198 $^H{HINTK_FLAGS_ . $kw} = $flags;
199 $^H{HINTK_SHIFT_ . $kw} = $type->{shift};
200 $^H{HINTK_ATTRS_ . $kw} = $type->{attrs};
201 $^H{HINTK_REIFY_ . $kw} = $type->{reify_type} // 0;
202 $^H{+HINTK_KEYWORDS} .= "$kw ";
210 delete $^H{+HINTK_KEYWORDS};
215 $^H{+HINTK_KEYWORDS} =~ s/(?<![^ ])\Q$kw\E //g;
228 $positional_required,
229 $positional_optional,
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,
246 $metadata{$key} = $info;
251 my ($v, $t) = @{$pair || []} or return undef;
252 Function::Parameters::Param->new(
260 while (my ($v, $t) = splice @_, 0, 2) {
261 push @r, Function::Parameters::Param->new(
271 my $key = _cv_root $func or return undef;
272 my $info = $metadata{$key} or return undef;
273 require Function::Parameters::Info;
274 Function::Parameters::Info->new(
275 keyword => $info->{declarator},
276 invocant => _mkparam1($info->{invocant}),
277 slurpy => _mkparam1($info->{slurpy}),
278 (map +("_$_" => _mkparams @{$info->{$_}}), glob '{positional,named}_{required,optional}')
290 Function::Parameters - subroutine definitions with parameter lists
294 use Function::Parameters qw(:strict);
297 fun foo($bar, $baz) {
301 # function with prototype
302 fun mymap($fun, @args)
307 push @res, $fun->($_);
312 print "$_\n" for mymap { $_ * 2 } 1 .. 4;
314 # method with implicit $self
315 method set_name($name) {
316 $self->{name} = $name;
319 # method with explicit invocant
320 method new($class: %init) {
321 return bless { %init }, $class;
324 # function with optional parameters
325 fun search($haystack, $needle = qr/^(?!)/, $offset = 0) {
329 # method with named parameters
330 method resize(:$width, :$height) {
331 $self->{width} = $width;
332 $self->{height} = $height;
335 $obj->resize(height => 4, width => 5);
337 # function with named optional parameters
338 fun search($haystack, :$needle = qr/^(?!)/, :$offset = 0) {
342 my $results = search $text, offset => 200;
346 This module extends Perl with keywords that let you define functions with
347 parameter lists. It uses Perl's L<keyword plugin|perlapi/PL_keyword_plugin>
348 API, so it works reliably and doesn't require a source filter.
352 The anatomy of a function (as recognized by this module):
358 The keyword introducing the function.
362 The function name (optional).
366 The parameter list (optional).
370 The prototype (optional).
374 The attribute list (optional).
384 # (1) (2) (3) (4) (5) (6)
385 fun foo ($x, $y) :($$) :lvalue { ... }
390 In the following section I'm going to describe all parts in order from simplest to most complex.
394 This is just a normal block of statements, as with L<C<sub>|perlsub>. No surprises here.
398 If present, it specifies the name of the function being defined. As with
399 L<C<sub>|perlsub>, if a name is present, the whole declaration is syntactically
400 a statement and its effects are performed at compile time (i.e. at runtime you
401 can call functions whose definitions only occur later in the file). If no name
402 is present, the declaration is an expression that evaluates to a reference to
403 the function in question. No surprises here either.
407 Attributes are relatively unusual in Perl code, but if you want them, they work
408 exactly the same as with L<C<sub>|perlsub/Subroutine-Attributes>.
412 As with L<C<sub>|perlsub/Prototypes>, a prototype, if present, contains hints as to how
413 the compiler should parse calls to this function. This means prototypes have no
414 effect if the function call is compiled before the function declaration has
415 been seen by the compiler or if the function to call is only determined at
416 runtime (e.g. because it's called as a method or through a reference).
418 With L<C<sub>|perlsub>, a prototype comes directly after the function name (if
419 any). C<Function::Parameters> reserves this spot for the
420 L<parameter list|/"Parameter list">. To specify a prototype, put it as the
421 first attribute (e.g. C<fun foo :(&$$)>). This is syntactically unambiguous
422 because normal L<attributes|/Attributes> need a name after the colon.
424 =head3 Parameter list
426 The parameter list is a list of variables enclosed in parentheses, except it's
427 actually a bit more complicated than that. A parameter list can include the
428 following 6 parts, all of which are optional:
434 This is a scalar variable followed by a colon (C<:>) and no comma. If an
435 invocant is present in the parameter list, the first element of
436 L<C<@_>|perlvar/@ARG> is automatically L<C<shift>ed|perlfunc/shift> off and
437 placed in this variable. This is intended for methods:
439 method new($class: %init) {
440 return bless { %init }, $class;
443 method throw($self:) {
447 =item 2. Required positional parameters
449 The most common kind of parameter. This is simply a comma-separated list of
450 scalars, which are filled from left to right with the arguments that the caller
459 =item 3. Optional positional parameters
461 Parameters can be marked as optional by putting an equals sign (C<=>) and an
462 expression (the "default argument") after them. If no corresponding argument is
463 passed in by the caller, the default argument will be used to initialize the
466 fun scale($base, $factor = 2) {
467 return $base * $factor;
470 say scale(3, 5); # "15"
473 The default argument is I<not> cached. Every time a function is called with
474 some optional arguments missing, the corresponding default arguments are
475 evaluated from left to right. This makes no difference for a value like C<2>
476 but it is important for expressions with side effects, such as reference
477 constructors (C<[]>, C<{}>) or function calls.
479 Default arguments see not only the surrounding lexical scope of their function
480 but also any preceding parameters. This allows the creation of dynamic defaults
481 based on previous arguments:
483 method set_name($self: $nick = $self->default_nick, $real_name = $nick) {
484 $self->{nick} = $nick;
485 $self->{real_name} = $real_name;
488 $obj->set_name("simplicio"); # same as: $obj->set_name("simplicio", "simplicio");
490 Because default arguments are actually evaluated as part of the function body,
491 you can also do silly things like this:
493 fun foo($n = return "nope") {
497 say foo(2 + 2); # "you gave me 4"
500 =item 4. Required named parameters
502 By putting a colon (C<:>) in front of a parameter you can make it named
503 instead of positional:
505 fun rectangle(:$width, :$height) {
509 rectangle(width => 2, height => 5);
510 rectangle(height => 5, width => 2); # same thing!
512 That is, the caller must specify a key name in addition to the value, but in
513 exchange the order of the arguments doesn't matter anymore. As with hash
514 initialization, you can specify the same key multiple times and the last
517 rectangle(height => 1, width => 2, height => 2, height => 5;
518 # same as: rectangle(width => 2, height => 5);
520 You can combine positional and named parameters as long as the positional
521 parameters come first:
523 fun named_rectangle($name, :$width, :$height) {
527 named_rectangle("Avocado", width => 0.5, height => 1.2);
529 =item 5. Optional named parameters
531 As with positional parameters, you can make named parameters optional by
532 specifying a default argument after an equals sign (C<=>):
534 fun rectangle(:$width, :$height, :$color = "chartreuse") {
538 rectangle(height => 10, width => 5);
539 # same as: rectangle(height => 10, width => 5, color => "chartreuse");
545 fun get($url, :$cookie_jar = HTTP::Cookies->new(), :$referrer = $url) {
549 my $data = get "http://www.example.com/", referrer => undef; # overrides $referrer = $url
551 The above example shows that passing any value (even C<undef>) will override
552 the default argument.
554 =item 6. Slurpy parameter
556 Finally you can put an array or hash in the parameter list, which will gobble
557 up the remaining arguments (if any):
559 fun foo($x, $y, @rest) { ... }
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")
565 If you combine this with named parameters, the slurpy parameter will end up
566 containing all unrecognized keys:
568 fun bar(:$size, @whatev) { ... }
570 bar weight => 20, size => 2, location => [0, -3];
571 # $size = 2, @whatev = ('weight', 20, 'location', [0, -3])
575 Apart from the L<C<shift>|perlfunc/shift> performed by the L<invocant|/"1.
576 Invocant">, all of the above leave L<C<@_>|perlvar/@ARG> unchanged; and if you
577 don't specify a parameter list at all, L<C<@_>|perlvar/@ARG> is all you get.
581 The keywords provided by C<Function::Parameters> are customizable. Since
582 C<Function::Parameters> is actually a L<pragma|perlpragma>, the provided
583 keywords have lexical scope. The following import variants can be used:
587 =item C<use Function::Parameters ':strict'>
589 Provides the keywords C<fun> and C<method> (described below) and enables
590 argument checks so that calling a function and omitting a required argument (or
591 passing too many arguments) will throw an error.
593 =item C<use Function::Parameters>
595 Provides 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
597 arguments are silently ignored.
599 =item C<< use Function::Parameters { KEYWORD1 => TYPE1, KEYWORD2 => TYPE2, ... } >>
601 Provides completely custom keywords as described by their types. A "type" is
602 either a string (one of the predefined types C<function>, C<method>,
603 C<classmethod>, C<function_strict>, C<method_strict>, C<classmethod_strict>) or
604 a reference to a hash with the following keys:
610 Valid values: C<optional> (default), C<required> (all functions defined with
611 this keyword must have a name), and C<prohibited> (functions defined with this
612 keyword must be anonymous).
616 Valid values: strings that look like scalar variables. This lets you specify a
617 default L<invocant|/"1. Invocant">, i.e. a function defined with this keyword
618 that doesn't have an explicit invocant in its parameter list will automatically
619 L<C<shift>|perlfunc/shift> its first argument into the variable specified here.
623 Valid values: booleans. If you set this to a true value, the keyword will
624 accept L<invocants|/"1. Invocant"> in parameter lists; otherwise specifying
625 an invocant in a function defined with this keyword is a syntax error.
629 Valid values: strings containing (source code for) attributes. This causes any
630 function defined with this keyword to have the specified
631 L<attributes|attributes> (in addition to any attributes specified in the
632 function definition itself).
634 =item C<default_arguments>
636 Valid values: booleans. This property is on by default; use
637 C<< default_arguments => 0 >> to turn it off. This controls whether optional
638 parameters are allowed. If it is turned off, using C<=> in parameter lists is
641 =item C<check_argument_count>
643 Valid values: booleans. If turned on, functions defined with this keyword will
644 automatically check that they have been passed all required arguments and no
645 excess arguments. If this check fails, an exception will by thrown via
646 L<C<Carp::croak>|Carp>.
648 Currently this flag is overloaded to also enable type checks (see
649 L</Experimental feature: Types> below).
653 Valid values: code references. The function specified here will be called to
654 turn type annotations into constraint objects (see
655 L</Experimental feature: Types> below).
657 The default type reifier is equivalent to:
660 require Moose::Util::TypeConstraints;
661 Moose::Util::TypeConstraints::find_or_create_isa_type_constraint($_[0])
666 The predefined type C<function> is equivalent to:
671 default_arguments => 1,
672 check_argument_count => 0,
675 These are all default values, so C<function> is also equivalent to C<{}>.
677 C<method> is equivalent to:
683 attributes => ':method',
684 default_arguments => 1,
685 check_argument_count => 0,
689 C<classmethod> is equivalent to:
695 attributes => ':method',
696 default_arguments => 1,
697 check_argument_count => 0,
700 C<function_strict>, C<method_strict>, and
701 C<classmethod_strict> are like C<function>, C<method>, and
702 C<classmethod>, respectively, but with C<< check_argument_count => 1 >>.
706 Plain C<use Function::Parameters> is equivalent to
707 C<< use Function::Parameters { fun => 'function', method => 'method' } >>.
709 C<use Function::Parameters qw(:strict)> is equivalent to
710 C<< use Function::Parameters { fun => 'function_strict', method => 'method_strict' } >>.
714 You can ask a function at runtime what parameters it has. This functionality is
715 available through the function C<Function::Parameters::info> (which is not
716 exported, so you have to call it by its full name). It takes a reference to a
717 function, and returns either C<undef> (if it knows nothing about the function)
718 or a L<Function::Parameters::Info> object describing the parameter list.
720 Note: This feature is implemented using L<Moo>, so you'll need to have L<Moo>
721 installed if you want to call C<Function::Parameters::info> (alternatively, if
722 L<Moose> is already loaded by the time C<Function::Parameters::info> is first
723 called, it will use that instead).
725 See L<Function::Parameters::Info> for examples.
727 =head2 Wrapping C<Function::Parameters>
729 If you want to write a wrapper around C<Function::Parameters>, you only have to
730 call its C<import> method. Due to its L<pragma|perlpragma> nature it always
731 affects the file that is currently being compiled.
733 package Some::Wrapper;
734 use Function::Parameters ();
736 Function::Parameters->import;
737 # or Function::Parameters->import(@custom_import_args);
740 =head2 Experimental feature: Types
742 An experimental feature is now available: You can annotate parameters with
743 types. That is, before each parameter you can put a type specification
744 consisting of identifiers (C<Foo>), unions (C<... | ...>), and parametric types
745 (C<...[...]>). Example:
747 fun foo(Int $n, ArrayRef[String | CodeRef] $cb) { ... }
749 If you do this, the type reification function corresponding to the keyword will
750 be called to turn the type (a string) into a constraint object. The default
751 type reifier simply loads L<Moose> and forwards to
752 L<C<Moose::Util::TypeConstraints::find_or_parse_type_constraint>|Moose::Util::TypeConstraints/find_or_parse_type_constraint>,
753 which creates L<Moose types|Moose::Manual::Types>.
755 If you are in "lax" mode, nothing further happens and the types are ignored. If
756 you are in "strict" mode, C<Function::Parameters> generates code to make sure
757 any values passed in conform to the type (via
758 L<< C<< $constraint->check($value) >>|Moose::Meta::TypeConstraint/$constraint->check($value) >>).
760 In addition, these type constraints are inspectable through the
761 L<Function::Parameters::Info> object returned by
762 L<C<Function::Parameters::info>|/Introspection>.
764 =head2 Experimental experimental feature: Type expressions
766 An even more experimental feature is the ability to specify arbitrary
767 expressions as types. The syntax for this is like the literal types described
768 above, but with an expression wrapped in parentheses (C<( EXPR )>). Example:
770 fun foo(('Int') $n, ($othertype) $x) { ... }
772 Every type expression must return either a string (which is resolved as for
773 literal types), or a L<type constraint object|Moose::Meta::TypeConstraint>
774 (providing C<check> and C<get_message> methods).
776 Note that these expressions are evaluated (once) at parse time (similar to
777 C<BEGIN> blocks), so make sure that any variables you use are set and any
778 functions you call are defined at parse time.
782 The module is actually written in L<C|perlxs> and uses
783 L<C<PL_keyword_plugin>|perlapi/PL_keyword_plugin> to generate opcodes directly.
784 However, you can run L<C<perl -MO=Deparse ...>|B::Deparse> on your code to see
785 what happens under the hood. In the simplest case (no argument checks, possibly
786 an L<invocant|/"1. Invocant">, required positional/slurpy parameters only), the
787 generated code corresponds to:
789 fun foo($x, $y, @z) { ... }
791 sub foo { my ($x, $y, @z) = @_; sub foo; ... }
793 method bar($x, $y, @z) { ... }
795 sub bar :method { my $self = shift; my ($x, $y, @z) = @_; sub bar; ... }
797 =head1 SUPPORT AND DOCUMENTATION
799 After installing, you can find documentation for this module with the
802 perldoc Function::Parameters
804 You can also look for information at:
810 L<https://metacpan.org/module/Function%3A%3AParameters>
812 =item RT, CPAN's request tracker
814 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Function-Parameters>
816 =item AnnoCPAN, Annotated CPAN documentation
818 L<http://annocpan.org/dist/Function-Parameters>
822 L<http://cpanratings.perl.org/d/Function-Parameters>
826 L<http://search.cpan.org/dist/Function-Parameters/>
832 L<Function::Parameters::Info>
836 Lukas Mai, C<< <l.mai at web.de> >>
838 =head1 COPYRIGHT & LICENSE
840 Copyright 2010-2013 Lukas Mai.
842 This program is free software; you can redistribute it and/or modify it
843 under the terms of either: the GNU General Public License as published
844 by the Free Software Foundation; or the Artistic License.
846 See http://dev.perl.org/licenses/ for more information.