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])
61 my ($href, $key, $default) = @_;
62 exists $href->{$key} ? delete $href->{$key} : $default
65 my @bare_arms = qw(function method);
69 default_arguments => 1,
70 check_argument_count => 0,
71 named_parameters => 1,
73 reify_type => \&_reify_type_default,
77 default_arguments => 1,
78 check_argument_count => 0,
79 named_parameters => 1,
81 reify_type => \&_reify_type_default,
88 default_arguments => 1,
89 check_argument_count => 0,
90 named_parameters => 1,
92 reify_type => \&_reify_type_default,
93 attributes => ':method',
98 for my $k (keys %type_map) {
99 $type_map{$k . '_strict'} = {
101 check_argument_count => 1,
105 our @type_reifiers = \&_reify_type_default;
116 if (@_ == 1 && $_[0] eq ':strict') {
118 fun => 'function_strict',
119 method => 'method_strict',
122 if (@_ == 1 && ref($_[0]) eq 'HASH') {
123 @_ = map [$_, $_[0]{$_}], keys %{$_[0]};
130 my $item = ref $proto
132 : [$proto, $bare_arms[$bare++] || confess(qq{Don't know what to do with "$proto"})]
134 my ($name, $proto_type) = @$item;
135 _assert_valid_identifier $name;
137 unless (ref $proto_type) {
138 # use '||' instead of 'or' to preserve $proto_type in the error message
139 $proto_type = $type_map{$proto_type}
140 || confess qq["$proto_type" doesn't look like a valid type (one of ${\join ', ', sort keys %type_map})];
143 my %type = %$proto_type;
146 $clean{name} = delete $type{name} || 'optional';
147 $clean{name} =~ /^(?:optional|required|prohibited)\z/
148 or confess qq["$clean{name}" doesn't look like a valid name attribute (one of optional, required, prohibited)];
150 $clean{shift} = delete $type{shift} || '';
151 _assert_valid_identifier $clean{shift}, 1 if $clean{shift};
153 $clean{attrs} = join ' ', map delete $type{$_} || (), qw(attributes attrs);
154 _assert_valid_attributes $clean{attrs} if $clean{attrs};
156 $clean{default_arguments} = _delete_default \%type, 'default_arguments', 1;
157 $clean{named_parameters} = _delete_default \%type, 'named_parameters', 1;
158 $clean{types} = _delete_default \%type, 'types', 1;
160 $clean{check_argument_count} = _delete_default \%type, 'check_argument_count', 0;
161 $clean{invocant} = _delete_default \%type, 'invocant', 0;
163 if (my $rt = delete $type{reify_type}) {
164 ref $rt eq 'CODE' or confess qq{"$rt" doesn't look like a type reifier};
167 for my $i (0 .. $#type_reifiers) {
168 if ($type_reifiers[$i] == $rt) {
173 unless (defined $index) {
174 $index = @type_reifiers;
175 push @type_reifiers, $rt;
178 $clean{reify_type} = $index;
181 %type and confess "Invalid keyword property: @{[keys %type]}";
183 $spec{$name} = \%clean;
186 for my $kw (keys %spec) {
187 my $type = $spec{$kw};
190 $type->{name} eq 'prohibited' ? FLAG_ANON_OK :
191 $type->{name} eq 'required' ? FLAG_NAME_OK :
192 FLAG_ANON_OK | FLAG_NAME_OK
194 $flags |= FLAG_DEFAULT_ARGS if $type->{default_arguments};
195 $flags |= FLAG_CHECK_NARGS | FLAG_CHECK_TARGS if $type->{check_argument_count};
196 $flags |= FLAG_INVOCANT if $type->{invocant};
197 $flags |= FLAG_NAMED_PARAMS if $type->{named_parameters};
198 $flags |= FLAG_TYPES_OK if $type->{types};
199 $^H{HINTK_FLAGS_ . $kw} = $flags;
200 $^H{HINTK_SHIFT_ . $kw} = $type->{shift};
201 $^H{HINTK_ATTRS_ . $kw} = $type->{attrs};
202 $^H{HINTK_REIFY_ . $kw} = $type->{reify_type} // 0;
203 $^H{+HINTK_KEYWORDS} .= "$kw ";
211 delete $^H{+HINTK_KEYWORDS};
216 $^H{+HINTK_KEYWORDS} =~ s/(?<![^ ])\Q$kw\E //g;
229 $positional_required,
230 $positional_optional,
238 declarator => $declarator,
239 invocant => defined $invocant ? [$invocant, $invocant_type] : undef,
240 slurpy => defined $slurpy ? [$slurpy , $slurpy_type ] : undef,
241 positional_required => $positional_required,
242 positional_optional => $positional_optional,
243 named_required => $named_required,
244 named_optional => $named_optional,
247 $metadata{$key} = $info;
252 my ($v, $t) = @{$pair || []} or return undef;
253 Function::Parameters::Param->new(
261 while (my ($v, $t) = splice @_, 0, 2) {
262 push @r, Function::Parameters::Param->new(
272 my $key = _cv_root $func or return undef;
273 my $info = $metadata{$key} or return undef;
274 require Function::Parameters::Info;
275 Function::Parameters::Info->new(
276 keyword => $info->{declarator},
277 invocant => _mkparam1($info->{invocant}),
278 slurpy => _mkparam1($info->{slurpy}),
279 (map +("_$_" => _mkparams @{$info->{$_}}), glob '{positional,named}_{required,optional}')
291 Function::Parameters - subroutine definitions with parameter lists
295 use Function::Parameters qw(:strict);
298 fun foo($bar, $baz) {
302 # function with prototype
303 fun mymap($fun, @args)
308 push @res, $fun->($_);
313 print "$_\n" for mymap { $_ * 2 } 1 .. 4;
315 # method with implicit $self
316 method set_name($name) {
317 $self->{name} = $name;
320 # method with explicit invocant
321 method new($class: %init) {
322 return bless { %init }, $class;
325 # function with optional parameters
326 fun search($haystack, $needle = qr/^(?!)/, $offset = 0) {
330 # method with named parameters
331 method resize(:$width, :$height) {
332 $self->{width} = $width;
333 $self->{height} = $height;
336 $obj->resize(height => 4, width => 5);
338 # function with named optional parameters
339 fun search($haystack, :$needle = qr/^(?!)/, :$offset = 0) {
343 my $results = search $text, offset => 200;
347 This module extends Perl with keywords that let you define functions with
348 parameter lists. It uses Perl's L<keyword plugin|perlapi/PL_keyword_plugin>
349 API, so it works reliably and doesn't require a source filter.
353 The anatomy of a function (as recognized by this module):
359 The keyword introducing the function.
363 The function name (optional).
367 The parameter list (optional).
371 The prototype (optional).
375 The attribute list (optional).
385 # (1) (2) (3) (4) (5) (6)
386 fun foo ($x, $y) :($$) :lvalue { ... }
391 In the following section I'm going to describe all parts in order from simplest to most complex.
395 This is just a normal block of statements, as with L<C<sub>|perlsub>. No surprises here.
399 If present, it specifies the name of the function being defined. As with
400 L<C<sub>|perlsub>, if a name is present, the whole declaration is syntactically
401 a statement and its effects are performed at compile time (i.e. at runtime you
402 can call functions whose definitions only occur later in the file). If no name
403 is present, the declaration is an expression that evaluates to a reference to
404 the function in question. No surprises here either.
408 Attributes are relatively unusual in Perl code, but if you want them, they work
409 exactly the same as with L<C<sub>|perlsub/Subroutine-Attributes>.
413 As with L<C<sub>|perlsub/Prototypes>, a prototype, if present, contains hints as to how
414 the compiler should parse calls to this function. This means prototypes have no
415 effect if the function call is compiled before the function declaration has
416 been seen by the compiler or if the function to call is only determined at
417 runtime (e.g. because it's called as a method or through a reference).
419 With L<C<sub>|perlsub>, a prototype comes directly after the function name (if
420 any). C<Function::Parameters> reserves this spot for the
421 L<parameter list|/"Parameter list">. To specify a prototype, put it as the
422 first attribute (e.g. C<fun foo :(&$$)>). This is syntactically unambiguous
423 because normal L<attributes|/Attributes> need a name after the colon.
425 =head3 Parameter list
427 The parameter list is a list of variables enclosed in parentheses, except it's
428 actually a bit more complicated than that. A parameter list can include the
429 following 6 parts, all of which are optional:
435 This is a scalar variable followed by a colon (C<:>) and no comma. If an
436 invocant is present in the parameter list, the first element of
437 L<C<@_>|perlvar/@ARG> is automatically L<C<shift>ed|perlfunc/shift> off and
438 placed in this variable. This is intended for methods:
440 method new($class: %init) {
441 return bless { %init }, $class;
444 method throw($self:) {
448 =item 2. Required positional parameters
450 The most common kind of parameter. This is simply a comma-separated list of
451 scalars, which are filled from left to right with the arguments that the caller
460 =item 3. Optional positional parameters
462 Parameters can be marked as optional by putting an equals sign (C<=>) and an
463 expression (the "default argument") after them. If no corresponding argument is
464 passed in by the caller, the default argument will be used to initialize the
467 fun scale($base, $factor = 2) {
468 return $base * $factor;
471 say scale(3, 5); # "15"
474 The default argument is I<not> cached. Every time a function is called with
475 some optional arguments missing, the corresponding default arguments are
476 evaluated from left to right. This makes no difference for a value like C<2>
477 but it is important for expressions with side effects, such as reference
478 constructors (C<[]>, C<{}>) or function calls.
480 Default arguments see not only the surrounding lexical scope of their function
481 but also any preceding parameters. This allows the creation of dynamic defaults
482 based on previous arguments:
484 method set_name($self: $nick = $self->default_nick, $real_name = $nick) {
485 $self->{nick} = $nick;
486 $self->{real_name} = $real_name;
489 $obj->set_name("simplicio"); # same as: $obj->set_name("simplicio", "simplicio");
491 Because default arguments are actually evaluated as part of the function body,
492 you can also do silly things like this:
494 fun foo($n = return "nope") {
498 say foo(2 + 2); # "you gave me 4"
501 =item 4. Required named parameters
503 By putting a colon (C<:>) in front of a parameter you can make it named
504 instead of positional:
506 fun rectangle(:$width, :$height) {
510 rectangle(width => 2, height => 5);
511 rectangle(height => 5, width => 2); # same thing!
513 That is, the caller must specify a key name in addition to the value, but in
514 exchange the order of the arguments doesn't matter anymore. As with hash
515 initialization, you can specify the same key multiple times and the last
518 rectangle(height => 1, width => 2, height => 2, height => 5;
519 # same as: rectangle(width => 2, height => 5);
521 You can combine positional and named parameters as long as the positional
522 parameters come first:
524 fun named_rectangle($name, :$width, :$height) {
528 named_rectangle("Avocado", width => 0.5, height => 1.2);
530 =item 5. Optional named parameters
532 As with positional parameters, you can make named parameters optional by
533 specifying a default argument after an equals sign (C<=>):
535 fun rectangle(:$width, :$height, :$color = "chartreuse") {
539 rectangle(height => 10, width => 5);
540 # same as: rectangle(height => 10, width => 5, color => "chartreuse");
546 fun get($url, :$cookie_jar = HTTP::Cookies->new(), :$referrer = $url) {
550 my $data = get "http://www.example.com/", referrer => undef; # overrides $referrer = $url
552 The above example shows that passing any value (even C<undef>) will override
553 the default argument.
555 =item 6. Slurpy parameter
557 Finally you can put an array or hash in the parameter list, which will gobble
558 up the remaining arguments (if any):
560 fun foo($x, $y, @rest) { ... }
562 foo "a", "b"; # $x = "a", $y = "b", @rest = ()
563 foo "a", "b", "c"; # $x = "a", $y = "b", @rest = ("c")
564 foo "a", "b", "c", "d"; # $x = "a", $y = "b", @rest = ("c", "d")
566 If you combine this with named parameters, the slurpy parameter will end up
567 containing all unrecognized keys:
569 fun bar(:$size, @whatev) { ... }
571 bar weight => 20, size => 2, location => [0, -3];
572 # $size = 2, @whatev = ('weight', 20, 'location', [0, -3])
576 Apart from the L<C<shift>|perlfunc/shift> performed by the L<invocant|/"1.
577 Invocant">, all of the above leave L<C<@_>|perlvar/@ARG> unchanged; and if you
578 don't specify a parameter list at all, L<C<@_>|perlvar/@ARG> is all you get.
582 The keywords provided by C<Function::Parameters> are customizable. Since
583 C<Function::Parameters> is actually a L<pragma|perlpragma>, the provided
584 keywords have lexical scope. The following import variants can be used:
588 =item C<use Function::Parameters ':strict'>
590 Provides the keywords C<fun> and C<method> (described below) and enables
591 argument checks so that calling a function and omitting a required argument (or
592 passing too many arguments) will throw an error.
594 =item C<use Function::Parameters>
596 Provides the keywords C<fun> and C<method> (described below) and enables
597 "lax" mode: Omitting a required argument sets it to C<undef> while excess
598 arguments are silently ignored.
600 =item C<< use Function::Parameters { KEYWORD1 => TYPE1, KEYWORD2 => TYPE2, ... } >>
602 Provides completely custom keywords as described by their types. A "type" is
603 either a string (one of the predefined types C<function>, C<method>,
604 C<classmethod>, C<function_strict>, C<method_strict>, C<classmethod_strict>) or
605 a reference to a hash with the following keys:
611 Valid values: C<optional> (default), C<required> (all functions defined with
612 this keyword must have a name), and C<prohibited> (functions defined with this
613 keyword must be anonymous).
617 Valid values: strings that look like scalar variables. This lets you specify a
618 default L<invocant|/"1. Invocant">, i.e. a function defined with this keyword
619 that doesn't have an explicit invocant in its parameter list will automatically
620 L<C<shift>|perlfunc/shift> its first argument into the variable specified here.
624 Valid values: booleans. If you set this to a true value, the keyword will
625 accept L<invocants|/"1. Invocant"> in parameter lists; otherwise specifying
626 an invocant in a function defined with this keyword is a syntax error.
630 Valid values: strings containing (source code for) attributes. This causes any
631 function defined with this keyword to have the specified
632 L<attributes|attributes> (in addition to any attributes specified in the
633 function definition itself).
635 =item C<default_arguments>
637 Valid values: booleans. This property is on by default; use
638 C<< default_arguments => 0 >> to turn it off. This controls whether optional
639 parameters are allowed. If it is turned off, using C<=> in parameter lists is
642 =item C<check_argument_count>
644 Valid values: booleans. If turned on, functions defined with this keyword will
645 automatically check that they have been passed all required arguments and no
646 excess arguments. If this check fails, an exception will by thrown via
647 L<C<Carp::croak>|Carp>.
649 Currently this flag is overloaded to also enable type checks (see
650 L</Experimental feature: Types> below).
654 Valid values: code references. The function specified here will be called to
655 turn type annotations into constraint objects (see
656 L</Experimental feature: Types> below).
658 The default type reifier is equivalent to:
661 require Moose::Util::TypeConstraints;
662 Moose::Util::TypeConstraints::find_or_create_isa_type_constraint($_[0])
667 The predefined type C<function> is equivalent to:
672 default_arguments => 1,
673 check_argument_count => 0,
676 These are all default values, so C<function> is also equivalent to C<{}>.
678 C<method> is equivalent to:
684 attributes => ':method',
685 default_arguments => 1,
686 check_argument_count => 0,
690 C<classmethod> is equivalent to:
696 attributes => ':method',
697 default_arguments => 1,
698 check_argument_count => 0,
701 C<function_strict>, C<method_strict>, and
702 C<classmethod_strict> are like C<function>, C<method>, and
703 C<classmethod>, respectively, but with C<< check_argument_count => 1 >>.
707 Plain C<use Function::Parameters> is equivalent to
708 C<< use Function::Parameters { fun => 'function', method => 'method' } >>.
710 C<use Function::Parameters qw(:strict)> is equivalent to
711 C<< use Function::Parameters { fun => 'function_strict', method => 'method_strict' } >>.
715 You can ask a function at runtime what parameters it has. This functionality is
716 available through the function C<Function::Parameters::info> (which is not
717 exported, so you have to call it by its full name). It takes a reference to a
718 function, and returns either C<undef> (if it knows nothing about the function)
719 or a L<Function::Parameters::Info> object describing the parameter list.
721 Note: This feature is implemented using L<Moo>, so you'll need to have L<Moo>
722 installed if you want to call C<Function::Parameters::info> (alternatively, if
723 L<Moose> is already loaded by the time C<Function::Parameters::info> is first
724 called, it will use that instead).
726 See L<Function::Parameters::Info> for examples.
728 =head2 Wrapping C<Function::Parameters>
730 If you want to write a wrapper around C<Function::Parameters>, you only have to
731 call its C<import> method. Due to its L<pragma|perlpragma> nature it always
732 affects the file that is currently being compiled.
734 package Some::Wrapper;
735 use Function::Parameters ();
737 Function::Parameters->import;
738 # or Function::Parameters->import(@custom_import_args);
741 =head2 Experimental feature: Types
743 An experimental feature is now available: You can annotate parameters with
744 types. That is, before each parameter you can put a type specification
745 consisting of identifiers (C<Foo>), unions (C<... | ...>), and parametric types
746 (C<...[...]>). Example:
748 fun foo(Int $n, ArrayRef[String | CodeRef] $cb) { ... }
750 If you do this, the type reification function corresponding to the keyword will
751 be called to turn the type (a string) into a constraint object. The default
752 type reifier simply loads L<Moose> and forwards to
753 L<C<Moose::Util::TypeConstraints::find_or_parse_type_constraint>|Moose::Util::TypeConstraints/find_or_parse_type_constraint>,
754 which creates L<Moose types|Moose::Manual::Types>.
756 If you are in "lax" mode, nothing further happens and the types are ignored. If
757 you are in "strict" mode, C<Function::Parameters> generates code to make sure
758 any values passed in conform to the type (via
759 L<< C<< $constraint->check($value) >>|Moose::Meta::TypeConstraint/$constraint->check($value) >>).
761 In addition, these type constraints are inspectable through the
762 L<Function::Parameters::Info> object returned by
763 L<C<Function::Parameters::info>|/Introspection>.
765 =head2 Experimental experimental feature: Type expressions
767 An even more experimental feature is the ability to specify arbitrary
768 expressions as types. The syntax for this is like the literal types described
769 above, but with an expression wrapped in parentheses (C<( EXPR )>). Example:
771 fun foo(('Int') $n, ($othertype) $x) { ... }
773 Every type expression must return either a string (which is resolved as for
774 literal types), or a L<type constraint object|Moose::Meta::TypeConstraint>
775 (providing C<check> and C<get_message> methods).
777 Note that these expressions are evaluated (once) at parse time (similar to
778 C<BEGIN> blocks), so make sure that any variables you use are set and any
779 functions you call are defined at parse time.
783 The module is actually written in L<C|perlxs> and uses
784 L<C<PL_keyword_plugin>|perlapi/PL_keyword_plugin> to generate opcodes directly.
785 However, you can run L<C<perl -MO=Deparse ...>|B::Deparse> on your code to see
786 what happens under the hood. In the simplest case (no argument checks, possibly
787 an L<invocant|/"1. Invocant">, required positional/slurpy parameters only), the
788 generated code corresponds to:
790 fun foo($x, $y, @z) { ... }
792 sub foo { my ($x, $y, @z) = @_; sub foo; ... }
794 method bar($x, $y, @z) { ... }
796 sub bar :method { my $self = shift; my ($x, $y, @z) = @_; sub bar; ... }
798 =head1 SUPPORT AND DOCUMENTATION
800 After installing, you can find documentation for this module with the
803 perldoc Function::Parameters
805 You can also look for information at:
811 L<https://metacpan.org/module/Function%3A%3AParameters>
813 =item RT, CPAN's request tracker
815 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Function-Parameters>
817 =item AnnoCPAN, Annotated CPAN documentation
819 L<http://annocpan.org/dist/Function-Parameters>
823 L<http://cpanratings.perl.org/d/Function-Parameters>
827 L<http://search.cpan.org/dist/Function-Parameters/>
833 L<Function::Parameters::Info>
837 Lukas Mai, C<< <l.mai at web.de> >>
839 =head1 COPYRIGHT & LICENSE
841 Copyright 2010-2013 Lukas Mai.
843 This program is free software; you can redistribute it and/or modify it
844 under the terms of either: the GNU General Public License as published
845 by the Free Software Foundation; or the Artistic License.
847 See http://dev.perl.org/licenses/ for more information.