1 package Function::Parameters;
10 our $VERSION = '1.0301';
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])
61 my ($href, $key, $default) = @_;
62 exists $href->{$key} ? delete $href->{$key} : $default
65 my @bare_arms = qw(function method);
67 function => {}, # all default settings
69 defaults => 'function',
73 defaults => 'function',
74 attributes => ':method',
86 classmethod_strict => {
87 defaults => 'classmethod',
92 our @type_reifiers = \&_reify_type_default;
103 if (@_ == 1 && $_[0] eq ':strict') {
105 fun => 'function_strict',
106 method => 'method_strict',
109 if (@_ == 1 && ref($_[0]) eq 'HASH') {
110 @_ = map [$_, $_[0]{$_}], keys %{$_[0]};
117 my $item = ref $proto
119 : [$proto, $bare_arms[$bare++] || confess(qq{Don't know what to do with "$proto"})]
121 my ($name, $proto_type) = @$item;
122 _assert_valid_identifier $name;
124 $proto_type = {defaults => $proto_type} unless ref $proto_type;
126 my %type = %$proto_type;
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);
135 $clean{name} = delete $type{name} // 'optional';
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)];
139 $clean{shift} = delete $type{shift} // '';
140 _assert_valid_identifier $clean{shift}, 1 if $clean{shift};
142 $clean{attrs} = join ' ', map delete $type{$_} // (), qw(attributes attrs);
143 _assert_valid_attributes $clean{attrs} if $clean{attrs};
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;
149 $clean{invocant} = _delete_default \%type, 'invocant', 0;
150 $clean{runtime} = _delete_default \%type, 'runtime', 0;
151 $clean{check_argument_count} = _delete_default \%type, 'check_argument_count', 0;
152 $clean{check_argument_types} = _delete_default \%type, 'check_argument_types', 0;
153 $clean{check_argument_count} = $clean{check_argument_types} = 1 if delete $type{strict};
155 if (my $rt = delete $type{reify_type}) {
156 ref $rt eq 'CODE' or confess qq{"$rt" doesn't look like a type reifier};
159 for my $i (0 .. $#type_reifiers) {
160 if ($type_reifiers[$i] == $rt) {
165 unless (defined $index) {
166 $index = @type_reifiers;
167 push @type_reifiers, $rt;
170 $clean{reify_type} = $index;
173 %type and confess "Invalid keyword property: @{[keys %type]}";
175 $spec{$name} = \%clean;
178 for my $kw (keys %spec) {
179 my $type = $spec{$kw};
182 $type->{name} eq 'prohibited' ? FLAG_ANON_OK :
183 $type->{name} eq 'required' ? FLAG_NAME_OK :
184 FLAG_ANON_OK | FLAG_NAME_OK
186 $flags |= FLAG_DEFAULT_ARGS if $type->{default_arguments};
187 $flags |= FLAG_CHECK_NARGS if $type->{check_argument_count};
188 $flags |= FLAG_CHECK_TARGS if $type->{check_argument_types};
189 $flags |= FLAG_INVOCANT if $type->{invocant};
190 $flags |= FLAG_NAMED_PARAMS if $type->{named_parameters};
191 $flags |= FLAG_TYPES_OK if $type->{types};
192 $flags |= FLAG_RUNTIME if $type->{runtime};
193 $^H{HINTK_FLAGS_ . $kw} = $flags;
194 $^H{HINTK_SHIFT_ . $kw} = $type->{shift};
195 $^H{HINTK_ATTRS_ . $kw} = $type->{attrs};
196 $^H{HINTK_REIFY_ . $kw} = $type->{reify_type} // 0;
197 $^H{+HINTK_KEYWORDS} .= "$kw ";
205 delete $^H{+HINTK_KEYWORDS};
210 $^H{+HINTK_KEYWORDS} =~ s/(?<![^ ])\Q$kw\E //g;
223 $positional_required,
224 $positional_optional,
232 declarator => $declarator,
233 invocant => defined $invocant ? [$invocant, $invocant_type] : undef,
234 slurpy => defined $slurpy ? [$slurpy , $slurpy_type ] : undef,
235 positional_required => $positional_required,
236 positional_optional => $positional_optional,
237 named_required => $named_required,
238 named_optional => $named_optional,
241 $metadata{$key} = $info;
246 my ($v, $t) = @{$pair || []} or return undef;
247 Function::Parameters::Param->new(
255 while (my ($v, $t) = splice @_, 0, 2) {
256 push @r, Function::Parameters::Param->new(
266 my $key = _cv_root $func or return undef;
267 my $info = $metadata{$key} or return undef;
268 require Function::Parameters::Info;
269 Function::Parameters::Info->new(
270 keyword => $info->{declarator},
271 invocant => _mkparam1($info->{invocant}),
272 slurpy => _mkparam1($info->{slurpy}),
273 (map +("_$_" => _mkparams @{$info->{$_}}), glob '{positional,named}_{required,optional}')
285 Function::Parameters - subroutine definitions with parameter lists
289 use Function::Parameters qw(:strict);
292 fun foo($bar, $baz) {
296 # function with prototype
297 fun mymap($fun, @args)
302 push @res, $fun->($_);
307 print "$_\n" for mymap { $_ * 2 } 1 .. 4;
309 # method with implicit $self
310 method set_name($name) {
311 $self->{name} = $name;
314 # method with explicit invocant
315 method new($class: %init) {
316 return bless { %init }, $class;
319 # function with optional parameters
320 fun search($haystack, $needle = qr/^(?!)/, $offset = 0) {
324 # method with named parameters
325 method resize(:$width, :$height) {
326 $self->{width} = $width;
327 $self->{height} = $height;
330 $obj->resize(height => 4, width => 5);
332 # function with named optional parameters
333 fun search($haystack, :$needle = qr/^(?!)/, :$offset = 0) {
337 my $results = search $text, offset => 200;
341 This module extends Perl with keywords that let you define functions with
342 parameter lists. It uses Perl's L<keyword plugin|perlapi/PL_keyword_plugin>
343 API, so it works reliably and doesn't require a source filter.
347 The anatomy of a function (as recognized by this module):
353 The keyword introducing the function.
357 The function name (optional).
361 The parameter list (optional).
365 The prototype (optional).
369 The attribute list (optional).
379 # (1) (2) (3) (4) (5) (6)
380 fun foo ($x, $y) :($$) :lvalue { ... }
385 In the following section I'm going to describe all parts in order from simplest to most complex.
389 This is just a normal block of statements, as with L<C<sub>|perlsub>. No surprises here.
393 If present, it specifies the name of the function being defined. As with
394 L<C<sub>|perlsub>, if a name is present, by default the whole declaration is
395 syntactically a statement and its effects are performed at compile time (i.e.
396 at runtime you can call functions whose definitions only occur later in the
397 file - but see the C<runtime> flag below). If no name is present, the
398 declaration is an expression that evaluates to a reference to the function in
403 Attributes are relatively unusual in Perl code, but if you want them, they work
404 exactly the same as with L<C<sub>|perlsub/Subroutine-Attributes>.
408 As with L<C<sub>|perlsub/Prototypes>, a prototype, if present, contains hints as to how
409 the compiler should parse calls to this function. This means prototypes have no
410 effect if the function call is compiled before the function declaration has
411 been seen by the compiler or if the function to call is only determined at
412 runtime (e.g. because it's called as a method or through a reference).
414 With L<C<sub>|perlsub>, a prototype comes directly after the function name (if
415 any). C<Function::Parameters> reserves this spot for the
416 L<parameter list|/"Parameter list">. To specify a prototype, put it as the
417 first attribute (e.g. C<fun foo :(&$$)>). This is syntactically unambiguous
418 because normal L<attributes|/Attributes> need a name after the colon.
420 =head3 Parameter list
422 The parameter list is a list of variables enclosed in parentheses, except it's
423 actually a bit more complicated than that. A parameter list can include the
424 following 6 parts, all of which are optional:
430 This is a scalar variable followed by a colon (C<:>) and no comma. If an
431 invocant is present in the parameter list, the first element of
432 L<C<@_>|perlvar/@ARG> is automatically L<C<shift>ed|perlfunc/shift> off and
433 placed in this variable. This is intended for methods:
435 method new($class: %init) {
436 return bless { %init }, $class;
439 method throw($self:) {
443 =item 2. Required positional parameters
445 The most common kind of parameter. This is simply a comma-separated list of
446 scalars, which are filled from left to right with the arguments that the caller
455 =item 3. Optional positional parameters
457 Parameters can be marked as optional by putting an equals sign (C<=>) and an
458 expression (the "default argument") after them. If no corresponding argument is
459 passed in by the caller, the default argument will be used to initialize the
462 fun scale($base, $factor = 2) {
463 return $base * $factor;
466 say scale(3, 5); # "15"
469 The default argument is I<not> cached. Every time a function is called with
470 some optional arguments missing, the corresponding default arguments are
471 evaluated from left to right. This makes no difference for a value like C<2>
472 but it is important for expressions with side effects, such as reference
473 constructors (C<[]>, C<{}>) or function calls.
475 Default arguments see not only the surrounding lexical scope of their function
476 but also any preceding parameters. This allows the creation of dynamic defaults
477 based on previous arguments:
479 method set_name($self: $nick = $self->default_nick, $real_name = $nick) {
480 $self->{nick} = $nick;
481 $self->{real_name} = $real_name;
484 $obj->set_name("simplicio"); # same as: $obj->set_name("simplicio", "simplicio");
486 Because default arguments are actually evaluated as part of the function body,
487 you can also do silly things like this:
489 fun foo($n = return "nope") {
493 say foo(2 + 2); # "you gave me 4"
496 =item 4. Required named parameters
498 By putting a colon (C<:>) in front of a parameter you can make it named
499 instead of positional:
501 fun rectangle(:$width, :$height) {
505 rectangle(width => 2, height => 5);
506 rectangle(height => 5, width => 2); # same thing!
508 That is, the caller must specify a key name in addition to the value, but in
509 exchange the order of the arguments doesn't matter anymore. As with hash
510 initialization, you can specify the same key multiple times and the last
513 rectangle(height => 1, width => 2, height => 2, height => 5);
514 # same as: rectangle(width => 2, height => 5);
516 You can combine positional and named parameters as long as the positional
517 parameters come first:
519 fun named_rectangle($name, :$width, :$height) {
523 named_rectangle("Avocado", width => 0.5, height => 1.2);
525 =item 5. Optional named parameters
527 As with positional parameters, you can make named parameters optional by
528 specifying a default argument after an equals sign (C<=>):
530 fun rectangle(:$width, :$height, :$color = "chartreuse") {
534 rectangle(height => 10, width => 5);
535 # same as: rectangle(height => 10, width => 5, color => "chartreuse");
541 fun get($url, :$cookie_jar = HTTP::Cookies->new(), :$referrer = $url) {
545 my $data = get "http://www.example.com/", referrer => undef; # overrides $referrer = $url
547 The above example shows that passing any value (even C<undef>) will override
548 the default argument.
550 =item 6. Slurpy parameter
552 Finally you can put an array or hash in the parameter list, which will gobble
553 up the remaining arguments (if any):
555 fun foo($x, $y, @rest) { ... }
557 foo "a", "b"; # $x = "a", $y = "b", @rest = ()
558 foo "a", "b", "c"; # $x = "a", $y = "b", @rest = ("c")
559 foo "a", "b", "c", "d"; # $x = "a", $y = "b", @rest = ("c", "d")
561 If you combine this with named parameters, the slurpy parameter will end up
562 containing all unrecognized keys:
564 fun bar(:$size, @whatev) { ... }
566 bar weight => 20, size => 2, location => [0, -3];
567 # $size = 2, @whatev = ('weight', 20, 'location', [0, -3])
571 Apart from the L<C<shift>|perlfunc/shift> performed by the L<invocant|/"1.
572 Invocant">, all of the above leave L<C<@_>|perlvar/@ARG> unchanged; and if you
573 don't specify a parameter list at all, L<C<@_>|perlvar/@ARG> is all you get.
577 The keywords provided by C<Function::Parameters> are customizable. Since
578 C<Function::Parameters> is actually a L<pragma|perlpragma>, the provided
579 keywords have lexical scope. The following import variants can be used:
583 =item C<use Function::Parameters ':strict'>
585 Provides the keywords C<fun> and C<method> (described below) and enables
586 argument checks so that calling a function and omitting a required argument (or
587 passing too many arguments) will throw an error.
589 =item C<use Function::Parameters>
591 Provides the keywords C<fun> and C<method> (described below) and enables
592 "lax" mode: Omitting a required argument sets it to C<undef> while excess
593 arguments are silently ignored.
595 =item C<< use Function::Parameters { KEYWORD1 => TYPE1, KEYWORD2 => TYPE2, ... } >>
597 Provides completely custom keywords as described by their types. A "type" is
598 either a string (one of the predefined types C<function>, C<method>,
599 C<classmethod>, C<function_strict>, C<method_strict>, C<classmethod_strict>) or
600 a reference to a hash with the following keys:
606 Valid values: One of the predefined types C<function>, C<method>,
607 C<classmethod>, C<function_strict>, C<method_strict>, C<classmethod_strict>.
608 This will set the defaults for all other keys from the specified type, which is
609 useful if you only want to override some properties:
611 use Function::Parameters { defmethod => { defaults => 'method', shift => '$this' } };
613 This example defines a keyword called C<defmethod> that works like the standard
614 C<method> keyword, but the implicit object variable is called C<$this> instead
617 Using the string types directly is equivalent to C<defaults> with no further
620 use Function::Parameters {
621 foo => 'function', # like: foo => { defaults => 'function' },
622 bar => 'function_strict', # like: bar => { defaults => 'function_strict' },
623 baz => 'method_strict', # like: baz => { defaults => 'method_strict' },
628 Valid values: C<optional> (default), C<required> (all functions defined with
629 this keyword must have a name), and C<prohibited> (functions defined with this
630 keyword must be anonymous).
634 Valid values: booleans. If enabled, this keyword takes effect at runtime, not
637 use Function::Parameters { fun => { defaults => 'function_strict', runtime => 1 } };
638 say defined &foo ? "defined" : "not defined"; # not defined
640 say defined &foo ? "defined" : "not defined"; # defined
642 C<&foo> is only defined after C<fun foo() {}> has been reached at runtime.
644 B<CAVEAT:> A future version of this module may enable C<< runtime => 1 >> by
649 Valid values: strings that look like scalar variables. This lets you specify a
650 default L<invocant|/"1. Invocant">, i.e. a function defined with this keyword
651 that doesn't have an explicit invocant in its parameter list will automatically
652 L<C<shift>|perlfunc/shift> its first argument into the variable specified here.
656 Valid values: booleans. If you set this to a true value, the keyword will
657 accept L<invocants|/"1. Invocant"> in parameter lists; otherwise specifying
658 an invocant in a function defined with this keyword is a syntax error.
662 Valid values: strings containing (source code for) attributes. This causes any
663 function defined with this keyword to have the specified
664 L<attributes|attributes> (in addition to any attributes specified in the
665 function definition itself).
667 =item C<default_arguments>
669 Valid values: booleans. This property is on by default; use
670 C<< default_arguments => 0 >> to turn it off. This controls whether optional
671 parameters are allowed. If it is turned off, using C<=> in parameter lists is
674 =item C<check_argument_count>
676 Valid values: booleans. If turned on, functions defined with this keyword will
677 automatically check that they have been passed all required arguments and no
678 excess arguments. If this check fails, an exception will by thrown via
679 L<C<Carp::croak>|Carp>.
681 =item C<check_argument_types>
683 Valid values: booleans. If turned on, functions defined with this keyword will
684 automatically check that the arguments they are passed pass the declared type
685 constraints (if any). See L</Experimental feature: Types> below.
689 Valid values: booleans. This turns on both C<check_argument_count> and
690 C<check_argument_types>.
694 Valid values: code references. The function specified here will be called to
695 turn type annotations into constraint objects (see
696 L</Experimental feature: Types> below). It will receive two arguments: a string
697 containing the type description, and the name of the current package.
699 The default type reifier is equivalent to:
702 require Moose::Util::TypeConstraints;
703 Moose::Util::TypeConstraints::find_or_create_isa_type_constraint($_[0])
708 The predefined type C<function> is equivalent to:
712 default_arguments => 1,
718 These are all default values, so C<function> is also equivalent to C<{}>.
720 C<method> is equivalent to:
723 defaults => 'function',
724 attributes => ':method',
727 # runtime => 1, ## possibly in a future version of this module
731 C<classmethod> is equivalent to:
734 defaults => 'method',
738 C<function_strict>, C<method_strict>, and
739 C<classmethod_strict> are like C<function>, C<method>, and
740 C<classmethod>, respectively, but with C<< strict => 1 >>.
744 Plain C<use Function::Parameters> is equivalent to
745 C<< use Function::Parameters { fun => 'function', method => 'method' } >>.
747 C<use Function::Parameters qw(:strict)> is equivalent to
748 C<< use Function::Parameters { fun => 'function_strict', method => 'method_strict' } >>.
752 You can ask a function at runtime what parameters it has. This functionality is
753 available through the function C<Function::Parameters::info> (which is not
754 exported, so you have to call it by its full name). It takes a reference to a
755 function, and returns either C<undef> (if it knows nothing about the function)
756 or a L<Function::Parameters::Info> object describing the parameter list.
758 Note: This feature is implemented using L<Moo>, so you'll need to have L<Moo>
759 installed if you want to call C<Function::Parameters::info> (alternatively, if
760 L<Moose> is already loaded by the time C<Function::Parameters::info> is first
761 called, it will use that instead).
763 See L<Function::Parameters::Info> for examples.
765 =head2 Wrapping C<Function::Parameters>
767 If you want to write a wrapper around C<Function::Parameters>, you only have to
768 call its C<import> method. Due to its L<pragma|perlpragma> nature it always
769 affects the file that is currently being compiled.
771 package Some::Wrapper;
772 use Function::Parameters ();
774 Function::Parameters->import;
775 # or Function::Parameters->import(@custom_import_args);
778 =head2 Experimental feature: Types
780 An experimental feature is now available: You can annotate parameters with
781 types. That is, before each parameter you can put a type specification
782 consisting of identifiers (C<Foo>), unions (C<... | ...>), and parametric types
783 (C<...[...]>). Example:
785 fun foo(Int $n, ArrayRef[Str | CodeRef] $cb) { ... }
787 If you do this, the type reification function corresponding to the keyword will
788 be called to turn the type (a string) into a constraint object. The default
789 type reifier simply loads L<Moose> and forwards to
790 L<C<Moose::Util::TypeConstraints::find_or_parse_type_constraint>|Moose::Util::TypeConstraints/find_or_parse_type_constraint>,
791 which creates L<Moose types|Moose::Manual::Types>.
793 If you are in "lax" mode, nothing further happens and the types are ignored. If
794 you are in "strict" mode, C<Function::Parameters> generates code to make sure
795 any values passed in conform to the type (via
796 L<< C<< $constraint->check($value) >>|Moose::Meta::TypeConstraint/$constraint->check($value) >>).
798 In addition, these type constraints are inspectable through the
799 L<Function::Parameters::Info> object returned by
800 L<C<Function::Parameters::info>|/Introspection>.
802 =head2 Experimental experimental feature: Type expressions
804 An even more experimental feature is the ability to specify arbitrary
805 expressions as types. The syntax for this is like the literal types described
806 above, but with an expression wrapped in parentheses (C<( EXPR )>). Example:
808 fun foo(('Int') $n, ($othertype) $x) { ... }
810 Every type expression must return either a string (which is resolved as for
811 literal types), or a L<type constraint object|Moose::Meta::TypeConstraint>
812 (providing C<check> and C<get_message> methods).
814 Note that these expressions are evaluated (once) at parse time (similar to
815 C<BEGIN> blocks), so make sure that any variables you use are set and any
816 functions you call are defined at parse time.
820 The module is actually written in L<C|perlxs> and uses
821 L<C<PL_keyword_plugin>|perlapi/PL_keyword_plugin> to generate opcodes directly.
822 However, you can run L<C<perl -MO=Deparse ...>|B::Deparse> on your code to see
823 what happens under the hood. In the simplest case (no argument checks, possibly
824 an L<invocant|/"1. Invocant">, required positional/slurpy parameters only), the
825 generated code corresponds to:
827 fun foo($x, $y, @z) { ... }
829 sub foo { my ($x, $y, @z) = @_; sub foo; ... }
831 method bar($x, $y, @z) { ... }
833 sub bar :method { my $self = shift; my ($x, $y, @z) = @_; sub bar; ... }
835 =head1 BUGS AND INCOMPATIBILITIES
837 A future version of this module may enable C<< runtime => 1 >> by default for
838 methods. If this would break your code, please send me a note or file a bug on
841 =head1 SUPPORT AND DOCUMENTATION
843 After installing, you can find documentation for this module with the
846 perldoc Function::Parameters
848 You can also look for information at:
854 L<https://metacpan.org/module/Function%3A%3AParameters>
856 =item RT, CPAN's request tracker
858 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Function-Parameters>
860 =item AnnoCPAN, Annotated CPAN documentation
862 L<http://annocpan.org/dist/Function-Parameters>
866 L<http://cpanratings.perl.org/d/Function-Parameters>
870 L<http://search.cpan.org/dist/Function-Parameters/>
876 L<Function::Parameters::Info>
880 Lukas Mai, C<< <l.mai at web.de> >>
882 =head1 COPYRIGHT & LICENSE
884 Copyright 2010-2013 Lukas Mai.
886 This program is free software; you can redistribute it and/or modify it
887 under the terms of either: the GNU General Public License as published
888 by the Free Software Foundation; or the Artistic License.
890 See http://dev.perl.org/licenses/ for more information.