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