1 package Function::Parameters;
11 our $VERSION = '1.0102';
15 sub _assert_valid_identifier {
16 my ($name, $with_dollar) = @_;
17 my $bonus = $with_dollar ? '\$' : '';
18 $name =~ /^${bonus}[^\W\d]\w*\z/
19 or confess qq{"$name" doesn't look like a valid identifier};
22 sub _assert_valid_attributes {
24 $attrs =~ /^\s*:\s*[^\W\d]\w*\s*(?:(?:\s|:\s*)[^\W\d]\w*\s*)*(?:\(|\z)/
25 or confess qq{"$attrs" doesn't look like valid attributes};
28 my @bare_arms = qw(function method);
32 default_arguments => 1,
33 check_argument_count => 0,
34 named_parameters => 1,
39 default_arguments => 1,
40 check_argument_count => 0,
41 named_parameters => 1,
49 default_arguments => 1,
50 check_argument_count => 0,
51 named_parameters => 1,
53 attributes => ':method',
58 for my $k (keys %type_map) {
59 $type_map{$k . '_strict'} = {
61 check_argument_count => 1,
74 if (@_ == 1 && $_[0] eq ':strict') {
76 fun => 'function_strict',
77 method => 'method_strict',
80 if (@_ == 1 && ref($_[0]) eq 'HASH') {
81 @_ = map [$_, $_[0]{$_}], keys %{$_[0]};
90 : [$proto, $bare_arms[$bare++] || confess(qq{Don't know what to do with "$proto"})]
92 my ($name, $proto_type) = @$item;
93 _assert_valid_identifier $name;
95 unless (ref $proto_type) {
96 # use '||' instead of 'or' to preserve $proto_type in the error message
97 $proto_type = $type_map{$proto_type}
98 || confess qq["$proto_type" doesn't look like a valid type (one of ${\join ', ', sort keys %type_map})];
101 my %type = %$proto_type;
104 $clean{name} = delete $type{name} || 'optional';
105 $clean{name} =~ /^(?:optional|required|prohibited)\z/
106 or confess qq["$clean{name}" doesn't look like a valid name attribute (one of optional, required, prohibited)];
108 $clean{shift} = delete $type{shift} || '';
109 _assert_valid_identifier $clean{shift}, 1 if $clean{shift};
111 $clean{attrs} = join ' ', map delete $type{$_} || (), qw(attributes attrs);
112 _assert_valid_attributes $clean{attrs} if $clean{attrs};
114 $clean{default_arguments} =
115 exists $type{default_arguments}
116 ? !!delete $type{default_arguments}
119 $clean{check_argument_count} = !!delete $type{check_argument_count};
120 $clean{invocant} = !!delete $type{invocant};
121 $clean{named_parameters} = !!delete $type{named_parameters};
122 $clean{types} = !!delete $type{types};
124 %type and confess "Invalid keyword property: @{[keys %type]}";
126 $spec{$name} = \%clean;
129 for my $kw (keys %spec) {
130 my $type = $spec{$kw};
133 $type->{name} eq 'prohibited' ? FLAG_ANON_OK :
134 $type->{name} eq 'required' ? FLAG_NAME_OK :
135 FLAG_ANON_OK | FLAG_NAME_OK
137 $flags |= FLAG_DEFAULT_ARGS if $type->{default_arguments};
138 $flags |= FLAG_CHECK_NARGS | FLAG_CHECK_TARGS if $type->{check_argument_count};
139 $flags |= FLAG_INVOCANT if $type->{invocant};
140 $flags |= FLAG_NAMED_PARAMS if $type->{named_parameters};
141 $flags |= FLAG_TYPES_OK if $type->{types};
142 $^H{HINTK_FLAGS_ . $kw} = $flags;
143 $^H{HINTK_SHIFT_ . $kw} = $type->{shift};
144 $^H{HINTK_ATTRS_ . $kw} = $type->{attrs};
145 $^H{+HINTK_KEYWORDS} .= "$kw ";
153 delete $^H{+HINTK_KEYWORDS};
158 $^H{+HINTK_KEYWORDS} =~ s/(?<![^ ])\Q$kw\E //g;
171 $positional_required,
172 $positional_optional,
180 declarator => $declarator,
181 invocant => defined $invocant ? [$invocant, $invocant_type] : undef,
182 slurpy => defined $slurpy ? [$slurpy , $slurpy_type ] : undef,
183 positional_required => $positional_required,
184 positional_optional => $positional_optional,
185 named_required => $named_required,
186 named_optional => $named_optional,
189 $metadata{$key} = $info;
194 my ($v, $t) = @{$pair || []} or return undef;
195 Function::Parameters::Param->new(
203 while (my ($v, $t) = splice @_, 0, 2) {
204 push @r, Function::Parameters::Param->new(
214 my $key = _cv_root $func or return undef;
215 my $info = $metadata{$key} or return undef;
216 require Function::Parameters::Info;
217 Function::Parameters::Info->new(
218 keyword => $info->{declarator},
219 invocant => _mkparam1($info->{invocant}),
220 slurpy => _mkparam1($info->{slurpy}),
221 (map +("_$_" => _mkparams @{$info->{$_}}), glob '{positional,named}_{required,optional}')
233 Function::Parameters - subroutine definitions with parameter lists
237 use Function::Parameters qw(:strict);
240 fun foo($bar, $baz) {
244 # function with prototype
245 fun mymap($fun, @args)
250 push @res, $fun->($_);
255 print "$_\n" for mymap { $_ * 2 } 1 .. 4;
257 # method with implicit $self
258 method set_name($name) {
259 $self->{name} = $name;
262 # method with explicit invocant
263 method new($class: %init) {
264 return bless { %init }, $class;
267 # function with optional parameters
268 fun search($haystack, $needle = qr/^(?!)/, $offset = 0) {
272 # method with named parameters
273 method resize(:$width, :$height) {
274 $self->{width} = $width;
275 $self->{height} = $height;
278 $obj->resize(height => 4, width => 5);
280 # function with named optional parameters
281 fun search($haystack, :$needle = qr/^(?!)/, :$offset = 0) {
285 my $results = search $text, offset => 200;
289 This module extends Perl with keywords that let you define functions with
290 parameter lists. It uses Perl's L<keyword plugin|perlapi/PL_keyword_plugin>
291 API, so it works reliably and doesn't require a source filter.
295 The anatomy of a function (as recognized by this module):
301 The keyword introducing the function.
305 The function name (optional).
309 The parameter list (optional).
313 The prototype (optional).
317 The attribute list (optional).
327 # (1) (2) (3) (4) (5) (6)
328 fun foo ($x, $y) :($$) :lvalue { ... }
333 In the following section I'm going to describe all parts in order from simplest to most complex.
337 This is just a normal block of statements, as with L<C<sub>|perlsub>. No surprises here.
341 If present, it specifies the name of the function being defined. As with
342 L<C<sub>|perlsub>, if a name is present, the whole declaration is syntactically
343 a statement and its effects are performed at compile time (i.e. at runtime you
344 can call functions whose definitions only occur later in the file). If no name
345 is present, the declaration is an expression that evaluates to a reference to
346 the function in question. No surprises here either.
350 Attributes are relatively unusual in Perl code, but if you want them, they work
351 exactly the same as with L<C<sub>|perlsub/Subroutine-Attributes>.
355 As with L<C<sub>|perlsub/Prototypes>, a prototype, if present, contains hints as to how
356 the compiler should parse calls to this function. This means prototypes have no
357 effect if the function call is compiled before the function declaration has
358 been seen by the compiler or if the function to call is only determined at
359 runtime (e.g. because it's called as a method or through a reference).
361 With L<C<sub>|perlsub>, a prototype comes directly after the function name (if
362 any). C<Function::Parameters> reserves this spot for the
363 L<parameter list|/"Parameter list">. To specify a prototype, put it as the
364 first attribute (e.g. C<fun foo :(&$$)>). This is syntactically unambiguous
365 because normal L<attributes|/Attributes> need a name after the colon.
367 =head3 Parameter list
369 The parameter list is a list of variables enclosed in parentheses, except it's
370 actually a bit more complicated than that. A parameter list can include the
371 following 6 parts, all of which are optional:
377 This is a scalar variable followed by a colon (C<:>) and no comma. If an
378 invocant is present in the parameter list, the first element of
379 L<C<@_>|perlvar/@ARG> is automatically L<C<shift>ed|perlfunc/shift> off and
380 placed in this variable. This is intended for methods:
382 method new($class: %init) {
383 return bless { %init }, $class;
386 method throw($self:) {
390 =item 2. Required positional parameters
392 The most common kind of parameter. This is simply a comma-separated list of
393 scalars, which are filled from left to right with the arguments that the caller
402 =item 3. Optional positional parameters
404 Parameters can be marked as optional by putting an equals sign (C<=>) and an
405 expression (the "default argument") after them. If no corresponding argument is
406 passed in by the caller, the default argument will be used to initialize the
409 fun scale($base, $factor = 2) {
410 return $base * $factor;
413 say scale(3, 5); # "15"
416 The default argument is I<not> cached. Every time a function is called with
417 some optional arguments missing, the corresponding default arguments are
418 evaluated from left to right. This makes no difference for a value like C<2>
419 but it is important for expressions with side effects, such as reference
420 constructors (C<[]>, C<{}>) or function calls.
422 Default arguments see not only the surrounding lexical scope of their function
423 but also any preceding parameters. This allows the creation of dynamic defaults
424 based on previous arguments:
426 method set_name($self: $nick = $self->default_nick, $real_name = $nick) {
427 $self->{nick} = $nick;
428 $self->{real_name} = $real_name;
431 $obj->set_name("simplicio"); # same as: $obj->set_name("simplicio", "simplicio");
433 Because default arguments are actually evaluated as part of the function body,
434 you can also do silly things like this:
436 fun foo($n = return "nope") {
440 say foo(2 + 2); # "you gave me 4"
443 =item 4. Required named parameters
445 By putting a colon (C<:>) in front of a parameter you can make it named
446 instead of positional:
448 fun rectangle(:$width, :$height) {
452 rectangle(width => 2, height => 5);
453 rectangle(height => 5, width => 2); # same thing!
455 That is, the caller must specify a key name in addition to the value, but in
456 exchange the order of the arguments doesn't matter anymore. As with hash
457 initialization, you can specify the same key multiple times and the last
460 rectangle(height => 1, width => 2, height => 2, height => 5;
461 # same as: rectangle(width => 2, height => 5);
463 You can combine positional and named parameters as long as the positional
464 parameters come first:
466 fun named_rectangle($name, :$width, :$height) {
470 named_rectangle("Avocado", width => 0.5, height => 1.2);
472 =item 5. Optional named parameters
474 As with positional parameters, you can make named parameters optional by
475 specifying a default argument after an equals sign (C<=>):
477 fun rectangle(:$width, :$height, :$color = "chartreuse") {
481 rectangle(height => 10, width => 5);
482 # same as: rectangle(height => 10, width => 5, color => "chartreuse");
488 fun get($url, :$cookie_jar = HTTP::Cookies->new(), :$referrer = $url) {
492 my $data = get "http://www.example.com/", referrer => undef; # overrides $referrer = $url
494 The above example shows that passing any value (even C<undef>) will override
495 the default argument.
497 =item 6. Slurpy parameter
499 Finally you can put an array or hash in the parameter list, which will gobble
500 up the remaining arguments (if any):
502 fun foo($x, $y, @rest) { ... }
504 foo "a", "b"; # $x = "a", $y = "b", @rest = ()
505 foo "a", "b", "c"; # $x = "a", $y = "b", @rest = ("c")
506 foo "a", "b", "c", "d"; # $x = "a", $y = "b", @rest = ("c", "d")
508 If you combine this with named parameters, the slurpy parameter will end up
509 containing all unrecognized keys:
511 fun bar(:$size, @whatev) { ... }
513 bar weight => 20, size => 2, location => [0, -3];
514 # $size = 2, @whatev = ('weight', 20, 'location', [0, -3])
518 Apart from the L<C<shift>|perlfunc/shift> performed by the L<invocant|/"1.
519 Invocant">, all of the above leave L<C<@_>|perlvar/@ARG> unchanged; and if you
520 don't specify a parameter list at all, L<C<@_>|perlvar/@ARG> is all you get.
524 The keywords provided by C<Function::Parameters> are customizable. Since
525 C<Function::Parameters> is actually a L<pragma|perlpragma>, the provided
526 keywords have lexical scope. The following import variants can be used:
530 =item C<use Function::Parameters ':strict'>
532 Provides the keywords C<fun> and C<method> (described below) and enables
533 argument checks so that calling a function and omitting a required argument (or
534 passing too many arguments) will throw an error.
536 =item C<use Function::Parameters>
538 Provides the keywords C<fun> and C<method> (described below) and enables
539 "lax" mode: Omitting a required argument sets it to C<undef> while excess
540 arguments are silently ignored.
542 =item C<< use Function::Parameters { KEYWORD1 => TYPE1, KEYWORD2 => TYPE2, ... } >>
544 Provides completely custom keywords as described by their types. A "type" is
545 either a string (one of the predefined types C<function>, C<method>,
546 C<classmethod>, C<function_strict>, C<method_strict>, C<classmethod_strict>) or
547 a reference to a hash with the following keys:
553 Valid values: C<optional> (default), C<required> (all functions defined with
554 this keyword must have a name), and C<prohibited> (functions defined with this
555 keyword must be anonymous).
559 Valid values: strings that look like scalar variables. This lets you specify a
560 default L<invocant|/"1. Invocant">, i.e. a function defined with this keyword
561 that doesn't have an explicit invocant in its parameter list will automatically
562 L<C<shift>|perlfunc/shift> its first argument into the variable specified here.
566 Valid values: booleans. If you set this to a true value, the keyword will
567 accept L<invocants|/"1. Invocant"> in parameter lists; otherwise specifying
568 an invocant in a function defined with this keyword is a syntax error.
572 Valid values: strings containing (source code for) attributes. This causes any
573 function defined with this keyword to have the specified
574 L<attributes|attributes> (in addition to any attributes specified in the
575 function definition itself).
577 =item C<default_arguments>
579 Valid values: booleans. This property is on by default; use
580 C<< default_arguments => 0 >> to turn it off. This controls whether optional
581 parameters are allowed. If it is turned off, using C<=> in parameter lists is
584 =item C<check_argument_count>
586 Valid values: booleans. If turned on, functions defined with this keyword will
587 automatically check that they have been passed all required arguments and no
588 excess arguments. If this check fails, an exception will by thrown via
589 L<C<Carp::croak>|Carp>.
593 The predefined type C<function> is equivalent to:
598 default_arguments => 1,
599 check_argument_count => 0,
602 These are all default values, so C<function> is also equivalent to C<{}>.
604 C<method> is equivalent to:
610 attributes => ':method',
611 default_arguments => 1,
612 check_argument_count => 0,
616 C<classmethod> is equivalent to:
622 attributes => ':method',
623 default_arguments => 1,
624 check_argument_count => 0,
627 C<function_strict>, C<method_strict>, and
628 C<classmethod_strict> are like C<function>, C<method>, and
629 C<classmethod>, respectively, but with C<< check_argument_count => 1 >>.
633 Plain C<use Function::Parameters> is equivalent to
634 C<< use Function::Parameters { fun => 'function', method => 'method' } >>.
636 C<use Function::Parameters qw(:strict)> is equivalent to
637 C<< use Function::Parameters { fun => 'function_strict', method => 'method_strict' } >>.
641 You can ask a function at runtime what parameters it has. This functionality is
642 available through the function C<Function::Parameters::info> (which is not
643 exported, so you have to call it by its full name). It takes a reference to a
644 function, and returns either C<undef> (if it knows nothing about the function)
645 or a L<Function::Parameters::Info> object describing the parameter list.
647 Note: This feature is implemented using L<Moo>, so you'll need to have L<Moo>
648 installed if you want to call C<Function::Parameters::info> (alternatively, if
649 L<Moose> is already loaded by the time C<Function::Parameters::info> is first
650 called, it will use that instead).
652 See L<Function::Parameters::Info> for examples.
654 =head2 Wrapping C<Function::Parameters>
656 If you want to write a wrapper around C<Function::Parameters>, you only have to
657 call its C<import> method. Due to its L<pragma|perlpragma> nature it always
658 affects the file that is currently being compiled.
660 package Some::Wrapper;
661 use Function::Parameters ();
663 Function::Parameters->import;
664 # or Function::Parameters->import(@custom_import_args);
667 =head2 Experimental feature: Types
669 An experimental feature is now available: You can annotate parameters with
670 L<Moose types|Moose::Manual::Types>. That is, before each parameter you can put
671 a type specification consisting of identifiers (C<Foo>), unions (C<... | ...>),
672 and parametric types (C<...[...]>). Example:
674 fun foo(Int $n, ArrayRef[String | CodeRef] $cb) { ... }
676 If you do this, L<Moose> will be loaded automatically (if that hasn't happened
677 yet). These specifications are parsed and validated using
678 L<C<Moose::Util::TypeConstraints::find_or_parse_type_constraint>|Moose::Util::TypeConstraints/find_or_parse_type_constraint>.
680 If you are in "lax" mode, nothing further happens and the types are ignored. If
681 you are in "strict" mode, C<Function::Parameters> generates code to make sure
682 any values passed in conform to the type (via
683 L<< C<< $constraint->check($value) >>|Moose::Meta::TypeConstraint/$constraint->check($value) >>).
685 In addition, these type constraints are inspectable through the
686 L<Function::Parameters::Info> object returned by
687 L<C<Function::Parameters::info>|/Introspection>.
689 =head2 Experimental experimental feature: Type expressions
691 An even more experimental feature is the ability to specify arbitrary
692 expressions as types. The syntax for this is like the literal types described
693 above, but with an expression wrapped in parentheses (C<( EXPR )>). Example:
695 fun foo(('Int') $n, ($othertype) $x) { ... }
697 Every type expression must return either a string (which is resolved as for
698 literal types), or a L<type constraint object|Moose::Meta::TypeConstraint>
699 (providing C<check> and C<get_message> methods).
701 Note that these expressions are evaluated (once) at parse time (similar to
702 C<BEGIN> blocks), so make sure that any variables you use are set and any
703 functions you call are defined at parse time.
707 The module is actually written in L<C|perlxs> and uses
708 L<C<PL_keyword_plugin>|perlapi/PL_keyword_plugin> to generate opcodes directly.
709 However, you can run L<C<perl -MO=Deparse ...>|B::Deparse> on your code to see
710 what happens under the hood. In the simplest case (no argument checks, possibly
711 an L<invocant|/"1. Invocant">, required positional/slurpy parameters only), the
712 generated code corresponds to:
714 fun foo($x, $y, @z) { ... }
716 sub foo { my ($x, $y, @z) = @_; sub foo; ... }
718 method bar($x, $y, @z) { ... }
720 sub bar :method { my $self = shift; my ($x, $y, @z) = @_; sub bar; ... }
722 =head1 SUPPORT AND DOCUMENTATION
724 After installing, you can find documentation for this module with the
727 perldoc Function::Parameters
729 You can also look for information at:
735 L<https://metacpan.org/module/Function%3A%3AParameters>
737 =item RT, CPAN's request tracker
739 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Function-Parameters>
741 =item AnnoCPAN, Annotated CPAN documentation
743 L<http://annocpan.org/dist/Function-Parameters>
747 L<http://cpanratings.perl.org/d/Function-Parameters>
751 L<http://search.cpan.org/dist/Function-Parameters/>
757 L<Function::Parameters::Info>
761 Lukas Mai, C<< <l.mai at web.de> >>
763 =head1 COPYRIGHT & LICENSE
765 Copyright 2010-2013 Lukas Mai.
767 This program is free software; you can redistribute it and/or modify it
768 under the terms of either: the GNU General Public License as published
769 by the Free Software Foundation; or the Artistic License.
771 See http://dev.perl.org/licenses/ for more information.