version bump
[p5sagit/Function-Parameters.git] / lib / Function / Parameters.pm
CommitLineData
7a63380c 1package Function::Parameters;
2
7dd35535 3use v5.14.0;
4
7a63380c 5use warnings;
6
63915d26 7use Carp qw(confess);
8
db81d362 9use XSLoader;
10BEGIN {
15b2a1ed 11 our $VERSION = '1.0004';
db81d362 12 XSLoader::load;
7a63380c 13}
14
2d5cf47a 15sub _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};
20}
21
b72eb6ee 22sub _assert_valid_attributes {
23 my ($attrs) = @_;
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};
26}
27
125c067e 28my @bare_arms = qw(function method);
2d5cf47a 29my %type_map = (
63915d26 30 function => {
31 name => 'optional',
32 default_arguments => 1,
33 check_argument_count => 0,
e158cf8f 34 named_parameters => 1,
63915d26 35 },
7947f7ce 36 method => {
37 name => 'optional',
63915d26 38 default_arguments => 1,
39 check_argument_count => 0,
e158cf8f 40 named_parameters => 1,
7947f7ce 41 attrs => ':method',
63915d26 42 shift => '$self',
d8e5d540 43 invocant => 1,
7947f7ce 44 },
a23979e1 45 classmethod => {
46 name => 'optional',
63915d26 47 default_arguments => 1,
48 check_argument_count => 0,
e158cf8f 49 named_parameters => 1,
698e861c 50 attributes => ':method',
63915d26 51 shift => '$class',
d8e5d540 52 invocant => 1,
a23979e1 53 },
2d5cf47a 54);
7817d698 55for my $k (keys %type_map) {
56 $type_map{$k . '_strict'} = {
57 %{$type_map{$k}},
58 check_argument_count => 1,
59 };
60}
c9a39f6b 61
db81d362 62sub import {
63 my $class = shift;
7a63380c 64
fcaf7811 65 if (!@_) {
66 @_ = {
67 fun => 'function',
68 method => 'method',
69 };
70 }
71 if (@_ == 1 && $_[0] eq ':strict') {
72 @_ = {
73 fun => 'function_strict',
74 method => 'method_strict',
75 };
76 }
125c067e 77 if (@_ == 1 && ref($_[0]) eq 'HASH') {
fcaf7811 78 @_ = map [$_, $_[0]{$_}], keys %{$_[0]};
125c067e 79 }
7a63380c 80
125c067e 81 my %spec;
82
83 my $bare = 0;
84 for my $proto (@_) {
85 my $item = ref $proto
86 ? $proto
87 : [$proto, $bare_arms[$bare++] || confess(qq{Don't know what to do with "$proto"})]
88 ;
ae6e00b5 89 my ($name, $proto_type) = @$item;
2d5cf47a 90 _assert_valid_identifier $name;
91
ae6e00b5 92 unless (ref $proto_type) {
93 # use '||' instead of 'or' to preserve $proto_type in the error message
94 $proto_type = $type_map{$proto_type}
95 || confess qq["$proto_type" doesn't look like a valid type (one of ${\join ', ', sort keys %type_map})];
2d5cf47a 96 }
b72eb6ee 97
ae6e00b5 98 my %type = %$proto_type;
99 my %clean;
10acc8b1 100
ae6e00b5 101 $clean{name} = delete $type{name} || 'optional';
102 $clean{name} =~ /^(?:optional|required|prohibited)\z/
103 or confess qq["$clean{name}" doesn't look like a valid name attribute (one of optional, required, prohibited)];
10acc8b1 104
ae6e00b5 105 $clean{shift} = delete $type{shift} || '';
10acc8b1 106 _assert_valid_identifier $clean{shift}, 1 if $clean{shift};
107
698e861c 108 $clean{attrs} = join ' ', map delete $type{$_} || (), qw(attributes attrs);
10acc8b1 109 _assert_valid_attributes $clean{attrs} if $clean{attrs};
125c067e 110
59f51b8b 111 $clean{default_arguments} =
112 exists $type{default_arguments}
113 ? !!delete $type{default_arguments}
114 : 1
115 ;
63915d26 116 $clean{check_argument_count} = !!delete $type{check_argument_count};
d8e5d540 117 $clean{invocant} = !!delete $type{invocant};
e158cf8f 118 $clean{named_parameters} = !!delete $type{named_parameters};
63915d26 119
ae6e00b5 120 %type and confess "Invalid keyword property: @{[keys %type]}";
121
122 $spec{$name} = \%clean;
125c067e 123 }
124
db81d362 125 for my $kw (keys %spec) {
126 my $type = $spec{$kw};
127
63915d26 128 my $flags =
129 $type->{name} eq 'prohibited' ? FLAG_ANON_OK :
130 $type->{name} eq 'required' ? FLAG_NAME_OK :
131 FLAG_ANON_OK | FLAG_NAME_OK
132 ;
133 $flags |= FLAG_DEFAULT_ARGS if $type->{default_arguments};
134 $flags |= FLAG_CHECK_NARGS if $type->{check_argument_count};
d8e5d540 135 $flags |= FLAG_INVOCANT if $type->{invocant};
e158cf8f 136 $flags |= FLAG_NAMED_PARAMS if $type->{named_parameters};
63915d26 137 $^H{HINTK_FLAGS_ . $kw} = $flags;
ae6e00b5 138 $^H{HINTK_SHIFT_ . $kw} = $type->{shift};
10acc8b1 139 $^H{HINTK_ATTRS_ . $kw} = $type->{attrs};
db81d362 140 $^H{+HINTK_KEYWORDS} .= "$kw ";
125c067e 141 }
eeb7df5f 142}
143
db81d362 144sub unimport {
eeb7df5f 145 my $class = shift;
125c067e 146
db81d362 147 if (!@_) {
148 delete $^H{+HINTK_KEYWORDS};
125c067e 149 return;
150 }
151
db81d362 152 for my $kw (@_) {
153 $^H{+HINTK_KEYWORDS} =~ s/(?<![^ ])\Q$kw\E //g;
125c067e 154 }
155}
156
db81d362 157
125c067e 158'ok'
7a63380c 159
160__END__
161
f2541b7d 162=encoding UTF-8
163
7a63380c 164=head1 NAME
165
166Function::Parameters - subroutine definitions with parameter lists
167
168=head1 SYNOPSIS
169
81203272 170 use Function::Parameters qw(:strict);
7a63380c 171
698e861c 172 # simple function
7a63380c 173 fun foo($bar, $baz) {
174 return $bar + $baz;
175 }
176
698e861c 177 # function with prototype
d71d548b 178 fun mymap($fun, @args)
179 :(&@)
180 {
7a63380c 181 my @res;
182 for (@args) {
183 push @res, $fun->($_);
184 }
185 @res
186 }
187
188 print "$_\n" for mymap { $_ * 2 } 1 .. 4;
125c067e 189
698e861c 190 # method with implicit $self
125c067e 191 method set_name($name) {
192 $self->{name} = $name;
193 }
d8e5d540 194
195 # method with explicit invocant
196 method new($class: %init) {
197 return bless { %init }, $class;
198 }
199
81203272 200 # function with optional parameters
698e861c 201 fun search($haystack, $needle = qr/^(?!)/, $offset = 0) {
202 ...
203 }
d8e5d540 204
81203272 205 # method with named parameters
206 method resize(:$width, :$height) {
207 $self->{width} = $width;
208 $self->{height} = $height;
698e861c 209 }
8dbfd12d 210
81203272 211 $obj->resize(height => 4, width => 5);
8dbfd12d 212
81203272 213 # function with named optional parameters
214 fun search($haystack, :$needle = qr/^(?!)/, :$offset = 0) {
215 ...
216 }
8dbfd12d 217
81203272 218 my $results = search $text, offset => 200;
8dbfd12d 219
81203272 220=head1 DESCRIPTION
8dbfd12d 221
81203272 222This module extends Perl with keywords that let you define functions with
223parameter lists. It uses Perl's L<keyword plugin|perlapi/PL_keyword_plugin>
224API, so it works reliably and doesn't require a source filter.
225
226=head2 Basics
227
228The anatomy of a function (as recognized by this module):
229
230=over
8dbfd12d 231
81203272 232=item 1.
233
234The keyword introducing the function.
235
236=item 2.
237
238The function name (optional).
239
240=item 3.
241
242The parameter list (optional).
243
244=item 4.
245
246The prototype (optional).
247
248=item 5.
249
250The attribute list (optional).
251
252=item 6.
253
254The function body.
255
256=back
257
258Example:
259
260 # (1) (2) (3) (4) (5) (6)
261 fun foo ($x, $y) :($$) :lvalue { ... }
c9a39f6b 262
81203272 263 # (1) (6)
264 my $f = fun { ... };
125c067e 265
81203272 266In the following section I'm going to describe all parts in order from simplest to most complex.
7a63380c 267
81203272 268=head3 Body
7a63380c 269
81203272 270This is just a normal block of statements, as with L<C<sub>|perlsub>. No surprises here.
7a63380c 271
81203272 272=head3 Name
7a63380c 273
81203272 274If present, it specifies the name of the function being defined. As with
275L<C<sub>|perlsub>, if a name is present, the whole declaration is syntactically
276a statement and its effects are performed at compile time (i.e. at runtime you
277can call functions whose definitions only occur later in the file). If no name
278is present, the declaration is an expression that evaluates to a reference to
279the function in question. No surprises here either.
7a63380c 280
81203272 281=head3 Attributes
7a63380c 282
81203272 283Attributes are relatively unusual in Perl code, but if you want them, they work
284exactly the same as with L<C<sub>|perlsub/Subroutine-Attributes>.
c9a39f6b 285
81203272 286=head3 Prototype
698e861c 287
81203272 288As with L<C<sub>|perlsub/Prototypes>, a prototype, if present, contains hints as to how
289the compiler should parse calls to this function. This means prototypes have no
290effect if the function call is compiled before the function declaration has
291been seen by the compiler or if the function to call is only determined at
292runtime (e.g. because it's called as a method or through a reference).
698e861c 293
81203272 294With L<C<sub>|perlsub>, a prototype comes directly after the function name (if
295any). C<Function::Parameters> reserves this spot for the
296L<parameter list|/"Parameter list">. To specify a prototype, put it as the
297first attribute (e.g. C<fun foo :(&$$)>). This is syntactically unambiguous
298because normal L<attributes|/Attributes> need a name after the colon.
7a63380c 299
81203272 300=head3 Parameter list
125c067e 301
81203272 302The parameter list is a list of variables enclosed in parentheses, except it's
303actually a bit more complicated than that. A parameter list can include the
304following 6 parts, all of which are optional:
125c067e 305
81203272 306=over
125c067e 307
81203272 308=item 1. Invocant
125c067e 309
81203272 310This is a scalar variable followed by a colon (C<:>) and no comma. If an
311invocant is present in the parameter list, the first element of
312L<C<@_>|perlvar/@ARG> is automatically L<C<shift>ed|perlfunc/shift> off and
313placed in this variable. This is intended for methods:
125c067e 314
81203272 315 method new($class: %init) {
316 return bless { %init }, $class;
317 }
318
319 method throw($self:) {
320 die $self;
321 }
125c067e 322
81203272 323=item 2. Required positional parameters
fcaf7811 324
81203272 325The most common kind of parameter. This is simply a comma-separated list of
326scalars, which are filled from left to right with the arguments that the caller
327passed in:
fcaf7811 328
81203272 329 fun add($x, $y) {
330 return $x + $y;
331 }
332
333 say add(2, 3); # "5"
334
335=item 3. Optional positional parameters
336
337Parameters can be marked as optional by putting an equals sign (C<=>) and an
338expression (the "default argument") after them. If no corresponding argument is
339passed in by the caller, the default argument will be used to initialize the
340parameter:
341
342 fun scale($base, $factor = 2) {
343 return $base * $factor;
344 }
345
346 say scale(3, 5); # "15"
347 say scale(3); # "6"
348
349The default argument is I<not> cached. Every time a function is called with
350some optional arguments missing, the corresponding default arguments are
351evaluated from left to right. This makes no difference for a value like C<2>
352but it is important for expressions with side effects, such as reference
353constructors (C<[]>, C<{}>) or function calls.
354
355Default arguments see not only the surrounding lexical scope of their function
356but also any preceding parameters. This allows the creation of dynamic defaults
357based on previous arguments:
358
359 method set_name($self: $nick = $self->default_nick, $real_name = $nick) {
360 $self->{nick} = $nick;
361 $self->{real_name} = $real_name;
362 }
363
364 $obj->set_name("simplicio"); # same as: $obj->set_name("simplicio", "simplicio");
63a24d7c 365
81203272 366Because default arguments are actually evaluated as part of the function body,
367you can also do silly things like this:
368
369 fun foo($n = return "nope") {
370 "you gave me $n"
371 }
372
373 say foo(2 + 2); # "you gave me 4"
374 say foo(); # "nope"
375
376=item 4. Required named parameters
377
378By putting a colon (C<:>) in front of a parameter you can make it named
379instead of positional:
380
381 fun rectangle(:$width, :$height) {
382 ...
383 }
384
385 rectangle(width => 2, height => 5);
386 rectangle(height => 5, width => 2); # same thing!
387
388That is, the caller must specify a key name in addition to the value, but in
389exchange the order of the arguments doesn't matter anymore. As with hash
390initialization, you can specify the same key multiple times and the last
391occurrence wins:
392
393 rectangle(height => 1, width => 2, height => 2, height => 5;
394 # same as: rectangle(width => 2, height => 5);
395
396You can combine positional and named parameters as long as the positional
397parameters come first:
398
399 fun named_rectangle($name, :$width, :$height) {
400 ...
401 }
402
403 named_rectangle("Avocado", width => 0.5, height => 1.2);
404
405=item 5. Optional named parameters
406
407As with positional parameters, you can make named parameters optional by
408specifying a default argument after an equals sign (C<=>):
409
410 fun rectangle(:$width, :$height, :$color = "chartreuse") {
411 ...
412 }
413
414 rectangle(height => 10, width => 5);
415 # same as: rectangle(height => 10, width => 5, color => "chartreuse");
125c067e 416
417=cut
418
419=pod
81203272 420
421 fun get($url, :$cookie_jar = HTTP::Cookies->new(), :$referrer = $url) {
422 ...
423 }
125c067e 424
81203272 425 my $data = get "http://www.example.com/", referrer => undef; # overrides $referrer = $url
125c067e 426
81203272 427The above example shows that passing any value (even C<undef>) will override
428the default argument.
63a24d7c 429
81203272 430=item 6. Slurpy parameter
ce052c57 431
81203272 432Finally you can put an array or hash in the parameter list, which will gobble
433up the remaining arguments (if any):
ce052c57 434
81203272 435 fun foo($x, $y, @rest) { ... }
436
437 foo "a", "b"; # $x = "a", $y = "b", @rest = ()
438 foo "a", "b", "c"; # $x = "a", $y = "b", @rest = ("c")
439 foo "a", "b", "c", "d"; # $x = "a", $y = "b", @rest = ("c", "d")
ce052c57 440
81203272 441If you combine this with named parameters, the slurpy parameter will end up
442containing all unrecognized keys:
ce052c57 443
81203272 444 fun bar(:$size, @whatev) { ... }
445
446 bar weight => 20, size => 2, location => [0, -3];
447 # $size = 2, @whatev = ('weight', 20, 'location', [0, -3])
ce052c57 448
81203272 449=back
ce052c57 450
81203272 451Apart from the L<C<shift>|perlfunc/shift> performed by the L<invocant|/"1.
452Invocant">, all of the above leave L<C<@_>|perlvar/@ARG> unchanged; and if you
453don't specify a parameter list at all, L<C<@_>|perlvar/@ARG> is all you get.
d8e5d540 454
81203272 455=head3 Keyword
d8e5d540 456
81203272 457The keywords provided by C<Function::Parameters> are customizable. Since
458C<Function::Parameters> is actually a L<pragma|perlpragma>, the provided
459keywords have lexical scope. The following import variants can be used:
d8e5d540 460
81203272 461=over
273c6544 462
81203272 463=item C<use Function::Parameters ':strict'>
273c6544 464
81203272 465Provides the keywords C<fun> and C<method> (described below) and enables
466argument checks so that calling a function and omitting a required argument (or
467passing too many arguments) will throw an error.
273c6544 468
81203272 469=item C<use Function::Parameters>
273c6544 470
81203272 471Provides the keywords C<fun> and C<method> (described below) and enables
472"lax" mode: Omitting a required argument sets it to C<undef> while excess
473arguments are silently ignored.
273c6544 474
81203272 475=item C<< use Function::Parameters { KEYWORD1 => TYPE1, KEYWORD2 => TYPE2, ... } >>
698e861c 476
81203272 477Provides completely custom keywords as described by their types. A "type" is
478either a string (one of the predefined types C<function>, C<method>,
479C<classmethod>, C<function_strict>, C<method_strict>, C<classmethod_strict>) or
480a reference to a hash with the following keys:
698e861c 481
81203272 482=over
698e861c 483
81203272 484=item C<name>
698e861c 485
81203272 486Valid values: C<optional> (default), C<required> (all functions defined with
487this keyword must have a name), and C<prohibited> (functions defined with this
488keyword must be anonymous).
698e861c 489
81203272 490=item C<shift>
698e861c 491
81203272 492Valid values: strings that look like scalar variables. This lets you specify a
493default L<invocant|/"1. Invocant">, i.e. a function defined with this keyword
494that doesn't have an explicit invocant in its parameter list will automatically
495L<C<shift>|perlfunc/shift> its first argument into the variable specified here.
698e861c 496
81203272 497=item C<invocant>
698e861c 498
81203272 499Valid values: booleans. If you set this to a true value, the keyword will
500accept L<invocants|/"1. Invocant"> in parameter lists; otherwise specifying
501an invocant in a function defined with this keyword is a syntax error.
698e861c 502
81203272 503=item C<attributes>
698e861c 504
81203272 505Valid values: strings containing (source code for) attributes. This causes any
506function defined with this keyword to have the specified
507L<attributes|attributes> (in addition to any attributes specified in the
508function definition itself).
698e861c 509
81203272 510=item C<default_arguments>
698e861c 511
81203272 512Valid values: booleans. This property is on by default; use
513C<< default_arguments => 0 >> to turn it off. This controls whether optional
514parameters are allowed. If it is turned off, using C<=> in parameter lists is
515a syntax error.
698e861c 516
81203272 517=item C<check_argument_count>
698e861c 518
81203272 519Valid values: booleans. If turned on, functions defined with this keyword will
520automatically check that they have been passed all required arguments and no
521excess arguments. If this check fails, an exception will by thrown via
522L<C<Carp::croak>|Carp>.
698e861c 523
ce052c57 524=back
525
81203272 526The predefined type C<function> is equivalent to:
698e861c 527
528 {
529 name => 'optional',
81203272 530 invocant => 0,
698e861c 531 default_arguments => 1,
532 check_argument_count => 0,
533 }
534
81203272 535These are all default values, so C<function> is also equivalent to C<{}>.
698e861c 536
81203272 537C<method> is equivalent to:
698e861c 538
539 {
540 name => 'optional',
698e861c 541 shift => '$self',
d8e5d540 542 invocant => 1,
81203272 543 attributes => ':method',
544 default_arguments => 1,
545 check_argument_count => 0,
698e861c 546 }
547
7817d698 548
81203272 549C<classmethod> is equivalent to:
698e861c 550
551 {
552 name => 'optional',
698e861c 553 shift => '$class',
d8e5d540 554 invocant => 1,
81203272 555 attributes => ':method',
556 default_arguments => 1,
557 check_argument_count => 0,
698e861c 558 }
ce052c57 559
81203272 560C<function_strict>, C<method_strict>, and
561C<classmethod_strict> are like C<function>, C<method>, and
562C<classmethod>, respectively, but with C<< check_argument_count => 1 >>.
63a24d7c 563
81203272 564=back
63a24d7c 565
81203272 566Plain C<use Function::Parameters> is equivalent to
567C<< use Function::Parameters { fun => 'function', method => 'method' } >>.
63a24d7c 568
81203272 569C<use Function::Parameters qw(:strict)> is equivalent to
570C<< use Function::Parameters { fun => 'function_strict', method => 'method_strict' } >>.
63a24d7c 571
81203272 572=head2 Wrapping C<Function::Parameters>
125c067e 573
81203272 574If you want to write a wrapper around C<Function::Parameters>, you only have to
575call its C<import> method. Due to its L<pragma|perlpragma> nature it always
576affects the file that is currently being compiled.
63a24d7c 577
578 package Some::Wrapper;
579 use Function::Parameters ();
580 sub import {
581 Function::Parameters->import;
698e861c 582 # or Function::Parameters->import(@custom_import_args);
63a24d7c 583 }
eeb7df5f 584
81203272 585=head2 How it works
586
587The module is actually written in L<C|perlxs> and uses
588L<C<PL_keyword_plugin>|perlapi/PL_keyword_plugin> to generate opcodes directly.
589However, you can run L<C<perl -MO=Deparse ...>|B::Deparse> on your code to see
590what happens under the hood. In the simplest case (no argument checks, possibly
591an L<invocant|/"1. Invocant">, required positional/slurpy parameters only), the
592generated code corresponds to:
593
594 fun foo($x, $y, @z) { ... }
595 # ... turns into ...
596 sub foo { my ($x, $y, @z) = @_; sub foo; ... }
597
598 method bar($x, $y, @z) { ... }
599 # ... turns into ...
600 sub bar :method { my $self = shift; my ($x, $y, @z) = @_; sub bar; ... }
601
7a63380c 602=head1 AUTHOR
603
604Lukas Mai, C<< <l.mai at web.de> >>
605
606=head1 COPYRIGHT & LICENSE
607
db81d362 608Copyright 2010, 2011, 2012 Lukas Mai.
7a63380c 609
610This program is free software; you can redistribute it and/or modify it
611under the terms of either: the GNU General Public License as published
612by the Free Software Foundation; or the Artistic License.
613
614See http://dev.perl.org/licenses/ for more information.
615
616=cut