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