Commit | Line | Data |
7a63380c |
1 | package Function::Parameters; |
2 | |
7dd35535 |
3 | use v5.14.0; |
7a63380c |
4 | use warnings; |
5 | |
63915d26 |
6 | use Carp qw(confess); |
7 | |
db81d362 |
8 | use XSLoader; |
9 | BEGIN { |
c1240985 |
10 | our $VERSION = '1.0301'; |
db81d362 |
11 | XSLoader::load; |
7a63380c |
12 | } |
13 | |
2d5cf47a |
14 | sub _assert_valid_identifier { |
15 | my ($name, $with_dollar) = @_; |
16 | my $bonus = $with_dollar ? '\$' : ''; |
17 | $name =~ /^${bonus}[^\W\d]\w*\z/ |
18 | or confess qq{"$name" doesn't look like a valid identifier}; |
19 | } |
20 | |
b72eb6ee |
21 | sub _assert_valid_attributes { |
22 | my ($attrs) = @_; |
4b76be72 |
23 | $attrs =~ m{ |
24 | ^ \s*+ |
25 | : \s*+ |
26 | (?&ident) (?! [^\s:(] ) (?¶m)?+ \s*+ |
27 | (?: |
28 | (?: : \s*+ )? |
29 | (?&ident) (?! [^\s:(] ) (?¶m)?+ \s*+ |
30 | )*+ |
31 | \z |
32 | |
33 | (?(DEFINE) |
34 | (?<ident> |
35 | [^\W\d] |
36 | \w*+ |
37 | ) |
38 | (?<param> |
39 | \( |
40 | [^()\\]*+ |
41 | (?: |
42 | (?: |
43 | \\ . |
44 | | |
45 | (?¶m) |
46 | ) |
47 | [^()\\]*+ |
48 | )*+ |
49 | \) |
50 | ) |
51 | ) |
52 | }sx or confess qq{"$attrs" doesn't look like valid attributes}; |
b72eb6ee |
53 | } |
54 | |
7193dffb |
55 | sub _reify_type_default { |
56 | require Moose::Util::TypeConstraints; |
57 | Moose::Util::TypeConstraints::find_or_create_isa_type_constraint($_[0]) |
58 | } |
59 | |
11305599 |
60 | sub _delete_default { |
61 | my ($href, $key, $default) = @_; |
62 | exists $href->{$key} ? delete $href->{$key} : $default |
63 | } |
64 | |
125c067e |
65 | my @bare_arms = qw(function method); |
2d5cf47a |
66 | my %type_map = ( |
f7651a6e |
67 | function => {}, # all default settings |
68 | function_strict => { |
69 | defaults => 'function', |
70 | strict => 1, |
63915d26 |
71 | }, |
f7651a6e |
72 | method => { |
73 | defaults => 'function', |
74 | attributes => ':method', |
75 | shift => '$self', |
76 | invocant => 1, |
7947f7ce |
77 | }, |
f7651a6e |
78 | method_strict => { |
79 | defaults => 'method', |
80 | strict => 1, |
81 | }, |
82 | classmethod => { |
83 | defaults => 'method', |
84 | shift => '$class', |
85 | }, |
86 | classmethod_strict => { |
87 | defaults => 'classmethod', |
88 | strict => 1, |
a23979e1 |
89 | }, |
2d5cf47a |
90 | ); |
c9a39f6b |
91 | |
7193dffb |
92 | our @type_reifiers = \&_reify_type_default; |
93 | |
db81d362 |
94 | sub import { |
95 | my $class = shift; |
7a63380c |
96 | |
fcaf7811 |
97 | if (!@_) { |
98 | @_ = { |
99 | fun => 'function', |
100 | method => 'method', |
101 | }; |
102 | } |
103 | if (@_ == 1 && $_[0] eq ':strict') { |
104 | @_ = { |
105 | fun => 'function_strict', |
106 | method => 'method_strict', |
107 | }; |
108 | } |
125c067e |
109 | if (@_ == 1 && ref($_[0]) eq 'HASH') { |
fcaf7811 |
110 | @_ = map [$_, $_[0]{$_}], keys %{$_[0]}; |
125c067e |
111 | } |
7a63380c |
112 | |
125c067e |
113 | my %spec; |
114 | |
115 | my $bare = 0; |
116 | for my $proto (@_) { |
117 | my $item = ref $proto |
118 | ? $proto |
119 | : [$proto, $bare_arms[$bare++] || confess(qq{Don't know what to do with "$proto"})] |
120 | ; |
ae6e00b5 |
121 | my ($name, $proto_type) = @$item; |
2d5cf47a |
122 | _assert_valid_identifier $name; |
123 | |
f7651a6e |
124 | $proto_type = {defaults => $proto_type} unless ref $proto_type; |
b72eb6ee |
125 | |
ae6e00b5 |
126 | my %type = %$proto_type; |
f7651a6e |
127 | while (my $defaults = delete $type{defaults}) { |
128 | my $base = $type_map{$defaults} |
129 | or confess qq["$defaults" doesn't look like a valid type (one of ${\join ', ', sort keys %type_map})]; |
130 | %type = (%$base, %type); |
131 | } |
132 | |
ae6e00b5 |
133 | my %clean; |
10acc8b1 |
134 | |
f7651a6e |
135 | $clean{name} = delete $type{name} // 'optional'; |
ae6e00b5 |
136 | $clean{name} =~ /^(?:optional|required|prohibited)\z/ |
137 | or confess qq["$clean{name}" doesn't look like a valid name attribute (one of optional, required, prohibited)]; |
10acc8b1 |
138 | |
f7651a6e |
139 | $clean{shift} = delete $type{shift} // ''; |
10acc8b1 |
140 | _assert_valid_identifier $clean{shift}, 1 if $clean{shift}; |
141 | |
f7651a6e |
142 | $clean{attrs} = join ' ', map delete $type{$_} // (), qw(attributes attrs); |
10acc8b1 |
143 | _assert_valid_attributes $clean{attrs} if $clean{attrs}; |
125c067e |
144 | |
11305599 |
145 | $clean{default_arguments} = _delete_default \%type, 'default_arguments', 1; |
146 | $clean{named_parameters} = _delete_default \%type, 'named_parameters', 1; |
147 | $clean{types} = _delete_default \%type, 'types', 1; |
7193dffb |
148 | |
11305599 |
149 | $clean{invocant} = _delete_default \%type, 'invocant', 0; |
42e595b0 |
150 | $clean{runtime} = _delete_default \%type, 'runtime', 0; |
f7651a6e |
151 | $clean{check_argument_count} = _delete_default \%type, 'check_argument_count', 0; |
e21fed2b |
152 | $clean{check_argument_types} = _delete_default \%type, 'check_argument_types', 1; |
f7651a6e |
153 | $clean{check_argument_count} = $clean{check_argument_types} = 1 if delete $type{strict}; |
63915d26 |
154 | |
7193dffb |
155 | if (my $rt = delete $type{reify_type}) { |
156 | ref $rt eq 'CODE' or confess qq{"$rt" doesn't look like a type reifier}; |
157 | |
158 | my $index; |
159 | for my $i (0 .. $#type_reifiers) { |
160 | if ($type_reifiers[$i] == $rt) { |
161 | $index = $i; |
162 | last; |
163 | } |
164 | } |
165 | unless (defined $index) { |
166 | $index = @type_reifiers; |
167 | push @type_reifiers, $rt; |
168 | } |
169 | |
170 | $clean{reify_type} = $index; |
171 | } |
172 | |
ae6e00b5 |
173 | %type and confess "Invalid keyword property: @{[keys %type]}"; |
174 | |
175 | $spec{$name} = \%clean; |
125c067e |
176 | } |
177 | |
db81d362 |
178 | for my $kw (keys %spec) { |
179 | my $type = $spec{$kw}; |
180 | |
63915d26 |
181 | my $flags = |
11c807bc |
182 | $type->{name} eq 'prohibited' ? FLAG_ANON_OK : |
183 | $type->{name} eq 'required' ? FLAG_NAME_OK : |
184 | FLAG_ANON_OK | FLAG_NAME_OK |
63915d26 |
185 | ; |
f7651a6e |
186 | $flags |= FLAG_DEFAULT_ARGS if $type->{default_arguments}; |
187 | $flags |= FLAG_CHECK_NARGS if $type->{check_argument_count}; |
188 | $flags |= FLAG_CHECK_TARGS if $type->{check_argument_types}; |
189 | $flags |= FLAG_INVOCANT if $type->{invocant}; |
190 | $flags |= FLAG_NAMED_PARAMS if $type->{named_parameters}; |
191 | $flags |= FLAG_TYPES_OK if $type->{types}; |
42e595b0 |
192 | $flags |= FLAG_RUNTIME if $type->{runtime}; |
63915d26 |
193 | $^H{HINTK_FLAGS_ . $kw} = $flags; |
ae6e00b5 |
194 | $^H{HINTK_SHIFT_ . $kw} = $type->{shift}; |
10acc8b1 |
195 | $^H{HINTK_ATTRS_ . $kw} = $type->{attrs}; |
7193dffb |
196 | $^H{HINTK_REIFY_ . $kw} = $type->{reify_type} // 0; |
db81d362 |
197 | $^H{+HINTK_KEYWORDS} .= "$kw "; |
125c067e |
198 | } |
eeb7df5f |
199 | } |
200 | |
db81d362 |
201 | sub unimport { |
eeb7df5f |
202 | my $class = shift; |
125c067e |
203 | |
db81d362 |
204 | if (!@_) { |
205 | delete $^H{+HINTK_KEYWORDS}; |
125c067e |
206 | return; |
207 | } |
208 | |
db81d362 |
209 | for my $kw (@_) { |
210 | $^H{+HINTK_KEYWORDS} =~ s/(?<![^ ])\Q$kw\E //g; |
125c067e |
211 | } |
212 | } |
213 | |
db81d362 |
214 | |
53c979f0 |
215 | our %metadata; |
216 | |
217 | sub _register_info { |
218 | my ( |
219 | $key, |
220 | $declarator, |
221 | $invocant, |
51a483f8 |
222 | $invocant_type, |
53c979f0 |
223 | $positional_required, |
224 | $positional_optional, |
225 | $named_required, |
226 | $named_optional, |
227 | $slurpy, |
51a483f8 |
228 | $slurpy_type, |
53c979f0 |
229 | ) = @_; |
230 | |
51a483f8 |
231 | my $info = { |
232 | declarator => $declarator, |
233 | invocant => defined $invocant ? [$invocant, $invocant_type] : undef, |
234 | slurpy => defined $slurpy ? [$slurpy , $slurpy_type ] : undef, |
235 | positional_required => $positional_required, |
236 | positional_optional => $positional_optional, |
237 | named_required => $named_required, |
238 | named_optional => $named_optional, |
239 | }; |
240 | |
241 | $metadata{$key} = $info; |
242 | } |
243 | |
244 | sub _mkparam1 { |
245 | my ($pair) = @_; |
246 | my ($v, $t) = @{$pair || []} or return undef; |
247 | Function::Parameters::Param->new( |
248 | name => $v, |
249 | type => $t, |
250 | ) |
251 | } |
252 | |
253 | sub _mkparams { |
254 | my @r; |
255 | while (my ($v, $t) = splice @_, 0, 2) { |
256 | push @r, Function::Parameters::Param->new( |
257 | name => $v, |
258 | type => $t, |
259 | ); |
260 | } |
261 | \@r |
53c979f0 |
262 | } |
263 | |
264 | sub info { |
265 | my ($func) = @_; |
266 | my $key = _cv_root $func or return undef; |
51a483f8 |
267 | my $info = $metadata{$key} or return undef; |
53c979f0 |
268 | require Function::Parameters::Info; |
269 | Function::Parameters::Info->new( |
42e595b0 |
270 | keyword => $info->{declarator}, |
51a483f8 |
271 | invocant => _mkparam1($info->{invocant}), |
42e595b0 |
272 | slurpy => _mkparam1($info->{slurpy}), |
51a483f8 |
273 | (map +("_$_" => _mkparams @{$info->{$_}}), glob '{positional,named}_{required,optional}') |
53c979f0 |
274 | ) |
275 | } |
276 | |
125c067e |
277 | 'ok' |
7a63380c |
278 | |
279 | __END__ |
280 | |
f2541b7d |
281 | =encoding UTF-8 |
282 | |
7a63380c |
283 | =head1 NAME |
284 | |
285 | Function::Parameters - subroutine definitions with parameter lists |
286 | |
287 | =head1 SYNOPSIS |
288 | |
81203272 |
289 | use Function::Parameters qw(:strict); |
7a63380c |
290 | |
698e861c |
291 | # simple function |
7a63380c |
292 | fun foo($bar, $baz) { |
293 | return $bar + $baz; |
294 | } |
295 | |
698e861c |
296 | # function with prototype |
d71d548b |
297 | fun mymap($fun, @args) |
298 | :(&@) |
299 | { |
7a63380c |
300 | my @res; |
301 | for (@args) { |
302 | push @res, $fun->($_); |
303 | } |
304 | @res |
305 | } |
306 | |
307 | print "$_\n" for mymap { $_ * 2 } 1 .. 4; |
125c067e |
308 | |
698e861c |
309 | # method with implicit $self |
125c067e |
310 | method set_name($name) { |
311 | $self->{name} = $name; |
312 | } |
d8e5d540 |
313 | |
314 | # method with explicit invocant |
315 | method new($class: %init) { |
316 | return bless { %init }, $class; |
317 | } |
318 | |
81203272 |
319 | # function with optional parameters |
698e861c |
320 | fun search($haystack, $needle = qr/^(?!)/, $offset = 0) { |
321 | ... |
322 | } |
d8e5d540 |
323 | |
81203272 |
324 | # method with named parameters |
325 | method resize(:$width, :$height) { |
326 | $self->{width} = $width; |
327 | $self->{height} = $height; |
698e861c |
328 | } |
8dbfd12d |
329 | |
81203272 |
330 | $obj->resize(height => 4, width => 5); |
8dbfd12d |
331 | |
81203272 |
332 | # function with named optional parameters |
333 | fun search($haystack, :$needle = qr/^(?!)/, :$offset = 0) { |
334 | ... |
335 | } |
8dbfd12d |
336 | |
81203272 |
337 | my $results = search $text, offset => 200; |
8dbfd12d |
338 | |
81203272 |
339 | =head1 DESCRIPTION |
8dbfd12d |
340 | |
81203272 |
341 | This module extends Perl with keywords that let you define functions with |
342 | parameter lists. It uses Perl's L<keyword plugin|perlapi/PL_keyword_plugin> |
343 | API, so it works reliably and doesn't require a source filter. |
344 | |
345 | =head2 Basics |
346 | |
347 | The anatomy of a function (as recognized by this module): |
348 | |
349 | =over |
8dbfd12d |
350 | |
81203272 |
351 | =item 1. |
352 | |
353 | The keyword introducing the function. |
354 | |
355 | =item 2. |
356 | |
357 | The function name (optional). |
358 | |
359 | =item 3. |
360 | |
361 | The parameter list (optional). |
362 | |
363 | =item 4. |
364 | |
365 | The prototype (optional). |
366 | |
367 | =item 5. |
368 | |
369 | The attribute list (optional). |
370 | |
371 | =item 6. |
372 | |
373 | The function body. |
374 | |
375 | =back |
376 | |
377 | Example: |
378 | |
379 | # (1) (2) (3) (4) (5) (6) |
380 | fun foo ($x, $y) :($$) :lvalue { ... } |
c9a39f6b |
381 | |
81203272 |
382 | # (1) (6) |
383 | my $f = fun { ... }; |
125c067e |
384 | |
81203272 |
385 | In the following section I'm going to describe all parts in order from simplest to most complex. |
7a63380c |
386 | |
81203272 |
387 | =head3 Body |
7a63380c |
388 | |
81203272 |
389 | This is just a normal block of statements, as with L<C<sub>|perlsub>. No surprises here. |
7a63380c |
390 | |
81203272 |
391 | =head3 Name |
7a63380c |
392 | |
81203272 |
393 | If present, it specifies the name of the function being defined. As with |
42e595b0 |
394 | L<C<sub>|perlsub>, if a name is present, by default the whole declaration is |
395 | syntactically a statement and its effects are performed at compile time (i.e. |
396 | at runtime you can call functions whose definitions only occur later in the |
397 | file - but see the C<runtime> flag below). If no name is present, the |
398 | declaration is an expression that evaluates to a reference to the function in |
399 | question. |
7a63380c |
400 | |
81203272 |
401 | =head3 Attributes |
7a63380c |
402 | |
81203272 |
403 | Attributes are relatively unusual in Perl code, but if you want them, they work |
404 | exactly the same as with L<C<sub>|perlsub/Subroutine-Attributes>. |
c9a39f6b |
405 | |
81203272 |
406 | =head3 Prototype |
698e861c |
407 | |
81203272 |
408 | As with L<C<sub>|perlsub/Prototypes>, a prototype, if present, contains hints as to how |
409 | the compiler should parse calls to this function. This means prototypes have no |
410 | effect if the function call is compiled before the function declaration has |
411 | been seen by the compiler or if the function to call is only determined at |
412 | runtime (e.g. because it's called as a method or through a reference). |
698e861c |
413 | |
81203272 |
414 | With L<C<sub>|perlsub>, a prototype comes directly after the function name (if |
415 | any). C<Function::Parameters> reserves this spot for the |
416 | L<parameter list|/"Parameter list">. To specify a prototype, put it as the |
417 | first attribute (e.g. C<fun foo :(&$$)>). This is syntactically unambiguous |
418 | because normal L<attributes|/Attributes> need a name after the colon. |
7a63380c |
419 | |
81203272 |
420 | =head3 Parameter list |
125c067e |
421 | |
81203272 |
422 | The parameter list is a list of variables enclosed in parentheses, except it's |
423 | actually a bit more complicated than that. A parameter list can include the |
424 | following 6 parts, all of which are optional: |
125c067e |
425 | |
81203272 |
426 | =over |
125c067e |
427 | |
81203272 |
428 | =item 1. Invocant |
125c067e |
429 | |
81203272 |
430 | This is a scalar variable followed by a colon (C<:>) and no comma. If an |
431 | invocant is present in the parameter list, the first element of |
432 | L<C<@_>|perlvar/@ARG> is automatically L<C<shift>ed|perlfunc/shift> off and |
433 | placed in this variable. This is intended for methods: |
125c067e |
434 | |
81203272 |
435 | method new($class: %init) { |
436 | return bless { %init }, $class; |
437 | } |
438 | |
439 | method throw($self:) { |
440 | die $self; |
441 | } |
125c067e |
442 | |
81203272 |
443 | =item 2. Required positional parameters |
fcaf7811 |
444 | |
81203272 |
445 | The most common kind of parameter. This is simply a comma-separated list of |
446 | scalars, which are filled from left to right with the arguments that the caller |
447 | passed in: |
fcaf7811 |
448 | |
81203272 |
449 | fun add($x, $y) { |
450 | return $x + $y; |
451 | } |
452 | |
453 | say add(2, 3); # "5" |
454 | |
455 | =item 3. Optional positional parameters |
456 | |
457 | Parameters can be marked as optional by putting an equals sign (C<=>) and an |
458 | expression (the "default argument") after them. If no corresponding argument is |
459 | passed in by the caller, the default argument will be used to initialize the |
460 | parameter: |
461 | |
462 | fun scale($base, $factor = 2) { |
463 | return $base * $factor; |
464 | } |
465 | |
466 | say scale(3, 5); # "15" |
467 | say scale(3); # "6" |
468 | |
469 | The default argument is I<not> cached. Every time a function is called with |
470 | some optional arguments missing, the corresponding default arguments are |
471 | evaluated from left to right. This makes no difference for a value like C<2> |
472 | but it is important for expressions with side effects, such as reference |
473 | constructors (C<[]>, C<{}>) or function calls. |
474 | |
475 | Default arguments see not only the surrounding lexical scope of their function |
476 | but also any preceding parameters. This allows the creation of dynamic defaults |
477 | based on previous arguments: |
478 | |
479 | method set_name($self: $nick = $self->default_nick, $real_name = $nick) { |
480 | $self->{nick} = $nick; |
481 | $self->{real_name} = $real_name; |
482 | } |
483 | |
484 | $obj->set_name("simplicio"); # same as: $obj->set_name("simplicio", "simplicio"); |
63a24d7c |
485 | |
81203272 |
486 | Because default arguments are actually evaluated as part of the function body, |
487 | you can also do silly things like this: |
488 | |
489 | fun foo($n = return "nope") { |
490 | "you gave me $n" |
491 | } |
492 | |
493 | say foo(2 + 2); # "you gave me 4" |
494 | say foo(); # "nope" |
495 | |
496 | =item 4. Required named parameters |
497 | |
498 | By putting a colon (C<:>) in front of a parameter you can make it named |
499 | instead of positional: |
500 | |
501 | fun rectangle(:$width, :$height) { |
502 | ... |
503 | } |
504 | |
505 | rectangle(width => 2, height => 5); |
506 | rectangle(height => 5, width => 2); # same thing! |
507 | |
508 | That is, the caller must specify a key name in addition to the value, but in |
509 | exchange the order of the arguments doesn't matter anymore. As with hash |
510 | initialization, you can specify the same key multiple times and the last |
511 | occurrence wins: |
512 | |
849229d4 |
513 | rectangle(height => 1, width => 2, height => 2, height => 5); |
81203272 |
514 | # same as: rectangle(width => 2, height => 5); |
515 | |
516 | You can combine positional and named parameters as long as the positional |
517 | parameters come first: |
518 | |
519 | fun named_rectangle($name, :$width, :$height) { |
520 | ... |
521 | } |
522 | |
523 | named_rectangle("Avocado", width => 0.5, height => 1.2); |
524 | |
525 | =item 5. Optional named parameters |
526 | |
527 | As with positional parameters, you can make named parameters optional by |
528 | specifying a default argument after an equals sign (C<=>): |
529 | |
530 | fun rectangle(:$width, :$height, :$color = "chartreuse") { |
531 | ... |
532 | } |
533 | |
534 | rectangle(height => 10, width => 5); |
535 | # same as: rectangle(height => 10, width => 5, color => "chartreuse"); |
125c067e |
536 | |
537 | =cut |
538 | |
539 | =pod |
81203272 |
540 | |
541 | fun get($url, :$cookie_jar = HTTP::Cookies->new(), :$referrer = $url) { |
542 | ... |
543 | } |
125c067e |
544 | |
81203272 |
545 | my $data = get "http://www.example.com/", referrer => undef; # overrides $referrer = $url |
125c067e |
546 | |
81203272 |
547 | The above example shows that passing any value (even C<undef>) will override |
548 | the default argument. |
63a24d7c |
549 | |
81203272 |
550 | =item 6. Slurpy parameter |
ce052c57 |
551 | |
81203272 |
552 | Finally you can put an array or hash in the parameter list, which will gobble |
553 | up the remaining arguments (if any): |
ce052c57 |
554 | |
81203272 |
555 | fun foo($x, $y, @rest) { ... } |
556 | |
557 | foo "a", "b"; # $x = "a", $y = "b", @rest = () |
558 | foo "a", "b", "c"; # $x = "a", $y = "b", @rest = ("c") |
559 | foo "a", "b", "c", "d"; # $x = "a", $y = "b", @rest = ("c", "d") |
ce052c57 |
560 | |
81203272 |
561 | If you combine this with named parameters, the slurpy parameter will end up |
562 | containing all unrecognized keys: |
ce052c57 |
563 | |
81203272 |
564 | fun bar(:$size, @whatev) { ... } |
565 | |
566 | bar weight => 20, size => 2, location => [0, -3]; |
567 | # $size = 2, @whatev = ('weight', 20, 'location', [0, -3]) |
ce052c57 |
568 | |
81203272 |
569 | =back |
ce052c57 |
570 | |
81203272 |
571 | Apart from the L<C<shift>|perlfunc/shift> performed by the L<invocant|/"1. |
572 | Invocant">, all of the above leave L<C<@_>|perlvar/@ARG> unchanged; and if you |
573 | don't specify a parameter list at all, L<C<@_>|perlvar/@ARG> is all you get. |
d8e5d540 |
574 | |
81203272 |
575 | =head3 Keyword |
d8e5d540 |
576 | |
81203272 |
577 | The keywords provided by C<Function::Parameters> are customizable. Since |
578 | C<Function::Parameters> is actually a L<pragma|perlpragma>, the provided |
579 | keywords have lexical scope. The following import variants can be used: |
d8e5d540 |
580 | |
81203272 |
581 | =over |
273c6544 |
582 | |
81203272 |
583 | =item C<use Function::Parameters ':strict'> |
273c6544 |
584 | |
81203272 |
585 | Provides the keywords C<fun> and C<method> (described below) and enables |
586 | argument checks so that calling a function and omitting a required argument (or |
587 | passing too many arguments) will throw an error. |
273c6544 |
588 | |
81203272 |
589 | =item C<use Function::Parameters> |
273c6544 |
590 | |
81203272 |
591 | Provides the keywords C<fun> and C<method> (described below) and enables |
592 | "lax" mode: Omitting a required argument sets it to C<undef> while excess |
593 | arguments are silently ignored. |
273c6544 |
594 | |
81203272 |
595 | =item C<< use Function::Parameters { KEYWORD1 => TYPE1, KEYWORD2 => TYPE2, ... } >> |
698e861c |
596 | |
81203272 |
597 | Provides completely custom keywords as described by their types. A "type" is |
598 | either a string (one of the predefined types C<function>, C<method>, |
599 | C<classmethod>, C<function_strict>, C<method_strict>, C<classmethod_strict>) or |
600 | a reference to a hash with the following keys: |
698e861c |
601 | |
81203272 |
602 | =over |
698e861c |
603 | |
f7651a6e |
604 | =item C<defaults> |
605 | |
606 | Valid values: One of the predefined types C<function>, C<method>, |
607 | C<classmethod>, C<function_strict>, C<method_strict>, C<classmethod_strict>. |
608 | This will set the defaults for all other keys from the specified type, which is |
609 | useful if you only want to override some properties: |
610 | |
611 | use Function::Parameters { defmethod => { defaults => 'method', shift => '$this' } }; |
612 | |
613 | This example defines a keyword called C<defmethod> that works like the standard |
614 | C<method> keyword, but the implicit object variable is called C<$this> instead |
615 | of C<$self>. |
616 | |
617 | Using the string types directly is equivalent to C<defaults> with no further |
618 | customization: |
619 | |
620 | use Function::Parameters { |
621 | foo => 'function', # like: foo => { defaults => 'function' }, |
622 | bar => 'function_strict', # like: bar => { defaults => 'function_strict' }, |
623 | baz => 'method_strict', # like: baz => { defaults => 'method_strict' }, |
624 | }; |
625 | |
81203272 |
626 | =item C<name> |
698e861c |
627 | |
81203272 |
628 | Valid values: C<optional> (default), C<required> (all functions defined with |
629 | this keyword must have a name), and C<prohibited> (functions defined with this |
630 | keyword must be anonymous). |
698e861c |
631 | |
42e595b0 |
632 | =item C<runtime> |
633 | |
634 | Valid values: booleans. If enabled, this keyword takes effect at runtime, not |
635 | compile time: |
636 | |
637 | use Function::Parameters { fun => { defaults => 'function_strict', runtime => 1 } }; |
638 | say defined &foo ? "defined" : "not defined"; # not defined |
639 | fun foo() {} |
640 | say defined &foo ? "defined" : "not defined"; # defined |
641 | |
642 | C<&foo> is only defined after C<fun foo() {}> has been reached at runtime. |
643 | |
644 | B<CAVEAT:> A future version of this module may enable C<< runtime => 1 >> by |
645 | default for methods. |
646 | |
81203272 |
647 | =item C<shift> |
698e861c |
648 | |
81203272 |
649 | Valid values: strings that look like scalar variables. This lets you specify a |
650 | default L<invocant|/"1. Invocant">, i.e. a function defined with this keyword |
651 | that doesn't have an explicit invocant in its parameter list will automatically |
652 | L<C<shift>|perlfunc/shift> its first argument into the variable specified here. |
698e861c |
653 | |
81203272 |
654 | =item C<invocant> |
698e861c |
655 | |
81203272 |
656 | Valid values: booleans. If you set this to a true value, the keyword will |
657 | accept L<invocants|/"1. Invocant"> in parameter lists; otherwise specifying |
658 | an invocant in a function defined with this keyword is a syntax error. |
698e861c |
659 | |
81203272 |
660 | =item C<attributes> |
698e861c |
661 | |
81203272 |
662 | Valid values: strings containing (source code for) attributes. This causes any |
663 | function defined with this keyword to have the specified |
664 | L<attributes|attributes> (in addition to any attributes specified in the |
665 | function definition itself). |
698e861c |
666 | |
81203272 |
667 | =item C<default_arguments> |
698e861c |
668 | |
81203272 |
669 | Valid values: booleans. This property is on by default; use |
670 | C<< default_arguments => 0 >> to turn it off. This controls whether optional |
671 | parameters are allowed. If it is turned off, using C<=> in parameter lists is |
672 | a syntax error. |
698e861c |
673 | |
81203272 |
674 | =item C<check_argument_count> |
698e861c |
675 | |
81203272 |
676 | Valid values: booleans. If turned on, functions defined with this keyword will |
677 | automatically check that they have been passed all required arguments and no |
678 | excess arguments. If this check fails, an exception will by thrown via |
679 | L<C<Carp::croak>|Carp>. |
698e861c |
680 | |
f7651a6e |
681 | =item C<check_argument_types> |
682 | |
e21fed2b |
683 | Valid values: booleans. This property is on by default; use |
684 | C<< check_argument_types => 0 >> to turn it off. This controls whether |
685 | functions defined with this keyword automatically check that the arguments they |
686 | are passed pass the declared type constraints (if any). See |
687 | L</Experimental feature: Types> below. |
f7651a6e |
688 | |
689 | =item C<strict> |
690 | |
691 | Valid values: booleans. This turns on both C<check_argument_count> and |
692 | C<check_argument_types>. |
7193dffb |
693 | |
694 | =item C<reify_type> |
695 | |
696 | Valid values: code references. The function specified here will be called to |
697 | turn type annotations into constraint objects (see |
e7c6de2c |
698 | L</Experimental feature: Types> below). It will receive two arguments: a string |
699 | containing the type description, and the name of the current package. |
7193dffb |
700 | |
701 | The default type reifier is equivalent to: |
702 | |
703 | sub { |
704 | require Moose::Util::TypeConstraints; |
705 | Moose::Util::TypeConstraints::find_or_create_isa_type_constraint($_[0]) |
706 | } |
707 | |
ce052c57 |
708 | =back |
709 | |
81203272 |
710 | The predefined type C<function> is equivalent to: |
698e861c |
711 | |
712 | { |
f7651a6e |
713 | name => 'optional', |
714 | default_arguments => 1, |
715 | strict => 0, |
716 | invocant => 0, |
42e595b0 |
717 | runtime => 0, |
698e861c |
718 | } |
719 | |
81203272 |
720 | These are all default values, so C<function> is also equivalent to C<{}>. |
698e861c |
721 | |
81203272 |
722 | C<method> is equivalent to: |
698e861c |
723 | |
724 | { |
f7651a6e |
725 | defaults => 'function', |
726 | attributes => ':method', |
727 | shift => '$self', |
728 | invocant => 1, |
42e595b0 |
729 | # runtime => 1, ## possibly in a future version of this module |
698e861c |
730 | } |
731 | |
7817d698 |
732 | |
81203272 |
733 | C<classmethod> is equivalent to: |
698e861c |
734 | |
735 | { |
f7651a6e |
736 | defaults => 'method', |
737 | shift => '$class', |
698e861c |
738 | } |
ce052c57 |
739 | |
81203272 |
740 | C<function_strict>, C<method_strict>, and |
741 | C<classmethod_strict> are like C<function>, C<method>, and |
f7651a6e |
742 | C<classmethod>, respectively, but with C<< strict => 1 >>. |
63a24d7c |
743 | |
81203272 |
744 | =back |
63a24d7c |
745 | |
81203272 |
746 | Plain C<use Function::Parameters> is equivalent to |
747 | C<< use Function::Parameters { fun => 'function', method => 'method' } >>. |
63a24d7c |
748 | |
81203272 |
749 | C<use Function::Parameters qw(:strict)> is equivalent to |
750 | C<< use Function::Parameters { fun => 'function_strict', method => 'method_strict' } >>. |
63a24d7c |
751 | |
ebdc721b |
752 | =head2 Introspection |
753 | |
754 | You can ask a function at runtime what parameters it has. This functionality is |
755 | available through the function C<Function::Parameters::info> (which is not |
756 | exported, so you have to call it by its full name). It takes a reference to a |
757 | function, and returns either C<undef> (if it knows nothing about the function) |
758 | or a L<Function::Parameters::Info> object describing the parameter list. |
759 | |
af04c6f1 |
760 | Note: This feature is implemented using L<Moo>, so you'll need to have L<Moo> |
b70db867 |
761 | installed if you want to call C<Function::Parameters::info> (alternatively, if |
762 | L<Moose> is already loaded by the time C<Function::Parameters::info> is first |
763 | called, it will use that instead). |
af04c6f1 |
764 | |
ebdc721b |
765 | See L<Function::Parameters::Info> for examples. |
766 | |
81203272 |
767 | =head2 Wrapping C<Function::Parameters> |
125c067e |
768 | |
81203272 |
769 | If you want to write a wrapper around C<Function::Parameters>, you only have to |
770 | call its C<import> method. Due to its L<pragma|perlpragma> nature it always |
771 | affects the file that is currently being compiled. |
63a24d7c |
772 | |
773 | package Some::Wrapper; |
774 | use Function::Parameters (); |
775 | sub import { |
776 | Function::Parameters->import; |
698e861c |
777 | # or Function::Parameters->import(@custom_import_args); |
63a24d7c |
778 | } |
eeb7df5f |
779 | |
0175ff9a |
780 | =head2 Experimental feature: Types |
781 | |
782 | An experimental feature is now available: You can annotate parameters with |
7193dffb |
783 | types. That is, before each parameter you can put a type specification |
784 | consisting of identifiers (C<Foo>), unions (C<... | ...>), and parametric types |
785 | (C<...[...]>). Example: |
0175ff9a |
786 | |
6865b43c |
787 | fun foo(Int $n, ArrayRef[Str | CodeRef] $cb) { ... } |
0175ff9a |
788 | |
7193dffb |
789 | If you do this, the type reification function corresponding to the keyword will |
790 | be called to turn the type (a string) into a constraint object. The default |
791 | type reifier simply loads L<Moose> and forwards to |
792 | L<C<Moose::Util::TypeConstraints::find_or_parse_type_constraint>|Moose::Util::TypeConstraints/find_or_parse_type_constraint>, |
793 | which creates L<Moose types|Moose::Manual::Types>. |
0175ff9a |
794 | |
795 | If you are in "lax" mode, nothing further happens and the types are ignored. If |
796 | you are in "strict" mode, C<Function::Parameters> generates code to make sure |
797 | any values passed in conform to the type (via |
d54d249f |
798 | L<< C<< $constraint->check($value) >>|Moose::Meta::TypeConstraint/$constraint->check($value) >>). |
0175ff9a |
799 | |
800 | In addition, these type constraints are inspectable through the |
801 | L<Function::Parameters::Info> object returned by |
802 | L<C<Function::Parameters::info>|/Introspection>. |
803 | |
804 | =head2 Experimental experimental feature: Type expressions |
805 | |
806 | An even more experimental feature is the ability to specify arbitrary |
807 | expressions as types. The syntax for this is like the literal types described |
808 | above, but with an expression wrapped in parentheses (C<( EXPR )>). Example: |
809 | |
810 | fun foo(('Int') $n, ($othertype) $x) { ... } |
811 | |
812 | Every type expression must return either a string (which is resolved as for |
813 | literal types), or a L<type constraint object|Moose::Meta::TypeConstraint> |
814 | (providing C<check> and C<get_message> methods). |
815 | |
816 | Note that these expressions are evaluated (once) at parse time (similar to |
817 | C<BEGIN> blocks), so make sure that any variables you use are set and any |
818 | functions you call are defined at parse time. |
819 | |
81203272 |
820 | =head2 How it works |
821 | |
822 | The module is actually written in L<C|perlxs> and uses |
823 | L<C<PL_keyword_plugin>|perlapi/PL_keyword_plugin> to generate opcodes directly. |
824 | However, you can run L<C<perl -MO=Deparse ...>|B::Deparse> on your code to see |
825 | what happens under the hood. In the simplest case (no argument checks, possibly |
826 | an L<invocant|/"1. Invocant">, required positional/slurpy parameters only), the |
827 | generated code corresponds to: |
828 | |
829 | fun foo($x, $y, @z) { ... } |
830 | # ... turns into ... |
831 | sub foo { my ($x, $y, @z) = @_; sub foo; ... } |
832 | |
833 | method bar($x, $y, @z) { ... } |
834 | # ... turns into ... |
835 | sub bar :method { my $self = shift; my ($x, $y, @z) = @_; sub bar; ... } |
836 | |
42e595b0 |
837 | =head1 BUGS AND INCOMPATIBILITIES |
838 | |
839 | A future version of this module may enable C<< runtime => 1 >> by default for |
840 | methods. If this would break your code, please send me a note or file a bug on |
841 | RT. |
842 | |
0175ff9a |
843 | =head1 SUPPORT AND DOCUMENTATION |
844 | |
845 | After installing, you can find documentation for this module with the |
846 | perldoc command. |
847 | |
848 | perldoc Function::Parameters |
849 | |
850 | You can also look for information at: |
851 | |
852 | =over |
853 | |
854 | =item MetaCPAN |
855 | |
856 | L<https://metacpan.org/module/Function%3A%3AParameters> |
857 | |
858 | =item RT, CPAN's request tracker |
859 | |
860 | L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Function-Parameters> |
861 | |
862 | =item AnnoCPAN, Annotated CPAN documentation |
863 | |
864 | L<http://annocpan.org/dist/Function-Parameters> |
865 | |
866 | =item CPAN Ratings |
867 | |
868 | L<http://cpanratings.perl.org/d/Function-Parameters> |
869 | |
870 | =item Search CPAN |
871 | |
872 | L<http://search.cpan.org/dist/Function-Parameters/> |
873 | |
874 | =back |
875 | |
ebdc721b |
876 | =head1 SEE ALSO |
877 | |
878 | L<Function::Parameters::Info> |
879 | |
7a63380c |
880 | =head1 AUTHOR |
881 | |
882 | Lukas Mai, C<< <l.mai at web.de> >> |
883 | |
884 | =head1 COPYRIGHT & LICENSE |
885 | |
b70db867 |
886 | Copyright 2010-2013 Lukas Mai. |
7a63380c |
887 | |
888 | This program is free software; you can redistribute it and/or modify it |
889 | under the terms of either: the GNU General Public License as published |
890 | by the Free Software Foundation; or the Artistic License. |
891 | |
892 | See http://dev.perl.org/licenses/ for more information. |
893 | |
894 | =cut |