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