File Coverage

blib/lib/Method/Signatures.pm
Criterion Covered Total %
statement 237 246 96.3
branch 101 114 88.6
condition 17 29 58.6
subroutine 33 35 94.2
pod 9 21 42.8
total 397 445 89.2


line stmt bran cond sub pod time code
1             package Method::Signatures;
2              
3 61     61   1164499 use strict;
  61         666  
  61         1474  
4 61     61   191 use warnings;
  61         73  
  61         1256  
5              
6 61     61   27898 use Lexical::SealRequireHints;
  61         32920  
  61         310  
7 61     61   1563 use base 'Devel::Declare::MethodInstaller::Simple';
  61         704  
  61         31484  
8 61     61   1004005 use Method::Signatures::Utils;
  61         467  
  61         2941  
9 61     61   21563 use Method::Signatures::Parameter;
  61         134  
  61         1988  
10 61     61   24898 use Method::Signatures::Signature;
  61         130  
  61         119278  
11              
12             our $VERSION = '20160516.2032_001';
13              
14             our $DEBUG = $ENV{METHOD_SIGNATURES_DEBUG} || 0;
15              
16             our $INF = ( 0 + "inf" ) == 0 ? 9e9999 : "inf";
17              
18             # copied from Devel::Pragma
19             sub my_hints() {
20 318     318 0 629 $^H |= 0x20000;
21 318         484 return \%^H;
22             }
23              
24              
25             =head1 NAME
26              
27             Method::Signatures - method and function declarations with signatures and no source filter
28              
29             =for readme plugin version
30              
31             =head1 SYNOPSIS
32              
33             package Foo;
34              
35             use Method::Signatures;
36              
37             method new (%args) {
38             return bless {%args}, $self;
39             }
40              
41             =for readme stop
42              
43             method get ($key) {
44             return $self->{$key};
45             }
46              
47             method set ($key, $val) {
48             return $self->{$key} = $val;
49             }
50              
51             =for readme start
52              
53             # Can also get type checking if you like:
54              
55             method set (Str $key, Int $val) {
56             return $self->{$key} = $val; # now you know $val is always an integer
57             }
58              
59             =for readme stop
60              
61             func hello($greeting, $place) {
62             print "$greeting, $place!\n";
63             }
64              
65             =for readme start
66              
67             =head1 DESCRIPTION
68              
69             Provides two new keywords, C<func> and C<method>, so that you can write
70             subroutines with signatures instead of having to spell out
71             C<my $self = shift; my($thing) = @_>
72              
73             C<func> is like C<sub> but takes a signature where the prototype would
74             normally go. This takes the place of C<my($foo, $bar) = @_> and does
75             a whole lot more.
76              
77             C<method> is like C<func> but specifically for making methods. It will
78             automatically provide the invocant as C<$self> (L<by default|/invocant>).
79             No more C<my $self = shift>.
80              
81             =begin :readme
82              
83             =head1 INSTALLATION
84              
85             This module sources are hosted on github
86             https://github.com/evalEmpire/method-signatures.git
87             and uses C<Module::Build> to generate the distribution. It can be
88             istalled:
89              
90             =over
91              
92             =item directly
93              
94             cpanm git://github.com/evalEmpire/method-signatures.git
95              
96             =item from CPAN
97              
98             cpan Method::Signatures
99             cpanm Method::Signatures
100              
101             =item maualy cloninig the repository:
102              
103             git clone https://github.com/evalEmpire/method-signatures.git
104             cd method-signatures
105             perl Build.PL
106             ./Build install
107              
108             =back
109            
110             =for readme plugin requires
111              
112             =end :readme
113              
114             =for readme stop
115              
116             Also allows signatures, very similar to Perl 6 signatures.
117              
118             Also does type checking, understanding all the types that Moose (or Mouse)
119             would understand.
120              
121             And it does all this with B<no source filters>.
122              
123              
124             =head2 Signature syntax
125              
126             func echo($message) {
127             print "$message\n";
128             }
129              
130             is equivalent to:
131              
132             sub echo {
133             my($message) = @_;
134             print "$message\n";
135             }
136              
137             except the original line numbering is preserved and the arguments are
138             checked to make sure they match the signature.
139              
140             Similarly
141              
142             method foo($bar, $baz) {
143             $self->wibble($bar, $baz);
144             }
145              
146             is equivalent to:
147              
148             sub foo {
149             my $self = shift;
150             my($bar, $baz) = @_;
151             $self->wibble($bar, $baz);
152             }
153              
154             again with checks to make sure the arguments passed in match the
155             signature.
156              
157             The full signature syntax for each parameter is:
158              
159             Int|Str \:$param! where $SM_EXPR is ro = $AS_EXPR when $SM_EXPR
160             \_____/ ^^\____/^ \____________/ \___/ \________/ \___________/
161             | || | | | | | |
162             Type_/ || | | | | | |
163             Aliased?___/ | | | | | | |
164             Named?______/ | | | | | |
165             Parameter var___/ | | | | |
166             Required?__________/ | | | |
167             Parameter constraint(s)_____/ | | |
168             Parameter trait(s)______________________/ | |
169             Default value____________________________________/ |
170             When default value should be applied_________________________/
171              
172             Every component except the parameter name (with sigil) is optional.
173              
174             C<$SM_EXPR> is any expression that is valid as the RHS of a smartmatch,
175             or else a raw block of code. See L<"Value constraints">.
176              
177             C<$AS_EXPR> is any expression that is valid as the RHS of an
178             assignment operator. See L<"Defaults">.
179              
180              
181             =head3 C<@_>
182              
183             Other than removing C<$self>, C<@_> is left intact. You are free to
184             use C<@_> alongside the arguments provided by Method::Signatures.
185              
186              
187             =head3 Named parameters
188              
189             Parameters can be passed in named, as a hash, using the C<:$arg> syntax.
190              
191             method foo(:$arg) {
192             ...
193             }
194              
195             $object->foo( arg => 42 );
196              
197             Named parameters are optional by default.
198              
199             Required positional parameters and named parameters can be mixed, but
200             the named params must come last.
201              
202             method foo( $a, $b, :$c ) # legal
203              
204             Named parameters are passed in as a hash after all positional arguments.
205              
206             method display( $text, :$justify = 'left', :$enchef = 0 ) {
207             ...
208             }
209              
210             # $text = "Some stuff", $justify = "right", $enchef = 0
211             $obj->display( "Some stuff", justify => "right" );
212              
213             You cannot mix optional positional params with named params, as that
214             leads to ambiguities.
215              
216             method foo( $a, $b?, :$c ) # illegal
217              
218             # Is this $a = 'c', $b = 42 or $c = 42?
219             $obj->foo( c => 42 );
220              
221              
222             =head3 Aliased references
223              
224             A signature of C<\@arg> will take an array reference but allow it to
225             be used as C<@arg> inside the method. C<@arg> is an alias to the
226             original reference. Any changes to C<@arg> will affect the original
227             reference.
228              
229             package Stuff;
230             method add_one(\@foo) {
231             $_++ for @foo;
232             }
233              
234             my @bar = (1,2,3);
235             Stuff->add_one(\@bar); # @bar is now (2,3,4)
236              
237             This feature requires L<Data::Alias> to be installed.
238              
239              
240              
241             =head3 Invocant parameter
242              
243             The method invocant (i.e. C<$self>) can be changed as the first
244             parameter on a per-method basis. Put a colon after it instead of a comma:
245              
246             method foo($class:) {
247             $class->bar;
248             }
249              
250             method stuff($class: $arg, $another) {
251             $class->things($arg, $another);
252             }
253              
254             C<method> has an implied default invocant of C<$self:>, though that is
255             configurable by setting the L<invocant parameter|/invocant> on the
256             C<use Method::Signatures> line.
257              
258             C<func> has no invocant, as it is intended for creating subs that will not
259             be invoked on an object.
260              
261              
262             =head3 Defaults
263              
264             Each parameter can be given a default with the C<$arg = EXPR> syntax.
265             For example,
266              
267             method add($this = 23, $that = 42) {
268             return $this + $that;
269             }
270              
271             Almost any expression can be used as a default.
272              
273             method silly(
274             $num = 42,
275             $string = q[Hello, world!],
276             $hash = { this => 42, that => 23 },
277             $code = sub { $num + 4 },
278             @nums = (1,2,3),
279             )
280             {
281             ...
282             }
283              
284             Normally, defaults will only be used if the argument is not passed in at all.
285             Passing in C<undef> will override the default. That means ...
286              
287             Class->add(); # $this = 23, $that = 42
288             Class->add(99); # $this = 99, $that = 42
289             Class->add(99, undef); # $this = 99, $that = undef
290              
291             However, you can specify additional conditions under which a default is
292             also to be used, using a trailing C<when>. For example:
293              
294             # Use default if no argument passed
295             method get_results($how_many = 1) {...}
296              
297             # Use default if no argument passed OR argument is undef
298             method get_results($how_many = 1 when undef) {...}
299              
300             # Use default if no argument passed OR argument is empty string
301             method get_results($how_many = 1 when "") {...}
302              
303             # Use default if no argument passed OR argument is zero
304             method get_results($how_many = 1 when 0) {...}
305              
306             # Use default if no argument passed OR argument is zero or less
307             method get_results($how_many = 1 when sub{ $_[0] <= 0 }) {...}
308              
309             # Use default if no argument passed OR argument is invalid
310             method get_results($how_many = 1 when sub{ !valid($_[0]) }) {...}
311              
312             In other words, if you include a C<when I<value>> after the default,
313             the default is still used if the argument is missing, but is also
314             used if the argument is provided but smart-matches the specified I<value>.
315              
316             Note that the final two examples above use anonymous subroutines to
317             conform their complex tests to the requirements of the smartmatch
318             operator. Because this is useful, but syntactically clumsy, there is
319             also a short-cut for this behaviour. If the test after C<when> consists
320             of a block, the block is executed as the defaulting test, with the
321             actual argument value aliased to C<$_> (just like in a C<grep> block).
322             So the final two examples above could also be written:
323              
324             # Use default if no argument passed OR argument is zero or less
325             method get_results($how_many = 1 when {$_ <= 0}) {...}
326              
327             # Use default if no argument passed OR argument is invalid
328             method get_results($how_many = 1 when {!valid($_)}) } {...}
329              
330             The most commonly used form of C<when> modifier is almost
331             certainly C<when undef>:
332              
333             # Use default if no argument passed OR argument is undef
334             method get_results($how_many = 1 when undef) {...}
335              
336             which covers the common case where an uninitialized variable is passed
337             as an argument, or where supplying an explicit undefined value is
338             intended to indicate: "use the default instead."
339              
340             This usage is sufficiently common that a short-cut is provided:
341             using the C<//=> operator (instead of the regular assignment operator)
342             to specify the default. Like so:
343              
344             # Use default if no argument passed OR argument is undef
345             method get_results($how_many //= 1) {...}
346              
347              
348             Earlier parameters may be used in later defaults.
349              
350             method copy_cat($this, $that = $this) {
351             return $that;
352             }
353              
354             Any variable that has a default is considered optional.
355              
356              
357             =head3 Type Constraints
358              
359             Parameters can also be given type constraints. If they are, the value
360             passed in will be validated against the type constraint provided.
361             Types are provided by L<Any::Moose> which will load L<Mouse> if
362             L<Moose> is not already loaded.
363              
364             Type constraints can be a type, a role or a class. Each will be
365             checked in turn until one of them passes.
366              
367             * First, is the $value of that type declared in Moose (or Mouse)?
368              
369             * Then, does the $value have that role?
370             $value->DOES($type);
371              
372             * Finally, is the $value an object of that class?
373             $value->isa($type);
374              
375             The set of default types that are understood can be found in
376             L<Mouse::Util::TypeConstraints> (or L<Moose::Util::TypeConstraints>;
377             they are generally the same, but there may be small differences).
378              
379             # avoid "argument isn't numeric" warnings
380             method add(Int $this = 23, Int $that = 42) {
381             return $this + $that;
382             }
383              
384             L<Mouse> and L<Moose> also understand some parameterized types; see
385             their documentation for more details.
386              
387             method add(Int $this = 23, Maybe[Int] $that) {
388             # $this will definitely be defined
389             # but $that might be undef
390             return defined $that ? $this + $that : $this;
391             }
392              
393             You may also use disjunctions, which means that you are willing to
394             accept a value of either type.
395              
396             method add(Int $this = 23, Int|ArrayRef[Int] $that) {
397             # $that could be a single number,
398             # or a reference to an array of numbers
399             use List::Util qw<sum>;
400             my @ints = ($this);
401             push @ints, ref $that ? @$that : $that;
402             return sum(@ints);
403             }
404              
405             If the value does not validate against the type, a run-time exception
406             is thrown.
407              
408             # Error will be:
409             # In call to Class::add : the 'this' parameter ("cow") is not of type Int
410             Class->add('cow', 'boy'); # make a cowboy!
411              
412             You cannot declare the type of the invocant.
413              
414             # this generates a compile-time error
415             method new(ClassName $class:) {
416             ...
417             }
418              
419              
420             =head3 Value Constraints
421              
422             In addition to a type, each parameter can also be specified with one or
423             more additional constraints, using the C<$arg where CONSTRAINT> syntax.
424              
425             method set_name($name where qr{\S+ \s+ \S+}x) {
426             ...
427             }
428              
429             method set_rank($rank where \%STD_RANKS) {
430             ...
431             }
432              
433             method set_age(Int $age where [17..75] ) {
434             ...
435             }
436              
437             method set_rating($rating where { $_ >= 0 } where { $_ <= 100 } ) {
438             ...
439             }
440              
441             method set_serial_num(Int $snum where {valid_checksum($snum)} ) {
442             ...
443             }
444              
445             The C<where> keyword must appear immediately after the parameter name
446             and before any L<trait|"Parameter traits"> or L<default|"Defaults">.
447              
448             Each C<where> constraint is smartmatched against the value of the
449             corresponding parameter, and an exception is thrown if the value does
450             not satisfy the constraint.
451              
452             Any of the normal smartmatch arguments (numbers, strings, regexes,
453             undefs, hashrefs, arrayrefs, coderefs) can be used as a constraint.
454              
455             In addition, the constraint can be specified as a raw block. This block
456             can then refer to the parameter variable directly by name (as in the
457             definition of C<set_serial_num()> above), or else as C<$_> (as in the
458             definition of C<set_rating()>.
459              
460             Unlike type constraints, value constraints are tested I<after> any
461             default values have been resolved, and in the same order as they were
462             specified within the signature.
463              
464              
465             =head3 Placeholder parameters
466              
467             A positional argument can be ignored by using a bare C<$> sigil as its name.
468              
469             method foo( $a, $, $c ) {
470             ...
471             }
472              
473             The argument's value doesn't get stored in a variable, but the caller must
474             still supply it. Value and type constraints can be applied to placeholders.
475              
476             method bar( Int $ where { $_ < 10 } ) {
477             ...
478             }
479              
480              
481             =head3 Parameter traits
482              
483             Each parameter can be assigned a trait with the C<$arg is TRAIT> syntax.
484              
485             method stuff($this is ro) {
486             ...
487             }
488              
489             Any unknown trait is ignored.
490              
491             Most parameters have a default traits of C<is rw is copy>.
492              
493             =over 4
494              
495             =item B<ro>
496              
497             Read-only. Assigning or modifying the parameter is an error. This trait
498             requires L<Const::Fast> to be installed.
499              
500             =item B<rw>
501              
502             Read-write. It's ok to read or write the parameter.
503              
504             This is a default trait.
505              
506             =item B<copy>
507              
508             The parameter will be a copy of the argument (just like C<< my $arg = shift >>).
509              
510             This is a default trait except for the C<\@foo> parameter (see L<Aliased references>).
511              
512             =item B<alias>
513              
514             The parameter will be an alias of the argument. Any changes to the
515             parameter will be reflected in the caller. This trait requires
516             L<Data::Alias> to be installed.
517              
518             This is a default trait for the C<\@foo> parameter (see L<Aliased references>).
519              
520             =back
521              
522             =head3 Mixing value constraints, traits, and defaults
523              
524             As explained in L<Signature syntax>, there is a defined order when including
525             multiple trailing aspects of a parameter:
526              
527             =over 4
528              
529             =item * Any value constraint must immediately follow the parameter name.
530              
531             =item * Any trait must follow that.
532              
533             =item * Any default must come last.
534              
535             =back
536              
537             For instance, to have a parameter which has all three aspects:
538              
539             method echo($message where { length <= 80 } is ro = "what?") {
540             return $message
541             }
542              
543             Think of C<$message where { length <= 80 }> as being the left-hand side of the
544             trait, and C<$message where { length <= 80 } is ro> as being the left-hand side
545             of the default assignment.
546              
547              
548             =head3 Slurpy parameters
549              
550             A "slurpy" parameter is a list or hash parameter that "slurps up" all
551             remaining arguments. Since any following parameters can't receive values,
552             there can be only one slurpy parameter.
553              
554             Slurpy parameters must come at the end of the signature and they must
555             be positional.
556              
557             Slurpy parameters are optional by default.
558              
559             =head3 The "yada yada" marker
560              
561             The restriction that slurpy parameters must be positional, and must
562             appear at the end of the signature, means that they cannot be used in
563             conjunction with named parameters.
564              
565             This is frustrating, because there are many situations (in particular:
566             during object initialization, or when creating a callback) where it
567             is extremely handy to be able to ignore extra named arguments that don't
568             correspond to any named parameter.
569              
570             While it would be theoretically possible to allow a slurpy parameter to
571             come after named parameters, the current implementation does not support
572             this (see L<"Slurpy parameter restrictions">).
573              
574             Instead, there is a special syntax (colloquially known as the "yada yada")
575             that tells a method or function to simply ignore any extra arguments
576             that are passed to it:
577              
578             # Expect name, age, gender, and simply ignore anything else
579             method BUILD (:$name, :$age, :$gender, ...) {
580             $self->{name} = uc $name;
581             $self->{age} = min($age, 18);
582             $self->{gender} = $gender // 'unspecified';
583             }
584              
585             # Traverse tree with node-printing callback
586             # (Callback only interested in nodes, ignores any other args passed to it)
587             $tree->traverse( func($node, ...) { $node->print } );
588              
589             The C<...> may appear as a separate "pseudo-parameter" anywhere in the
590             signature, but is normally placed at the very end. It has no other
591             effect except to disable the usual "die if extra arguments" test that
592             the module sets up within each method or function.
593              
594             This means that a "yada yada" can also be used to ignore positional
595             arguments (as the second example above indicates). So, instead of:
596              
597             method verify ($min, $max, @etc) {
598             return $min <= $self->{val} && $self->{val} <= $max;
599             }
600              
601             you can just write:
602              
603             method verify ($min, $max, ...) {
604             return $min <= $self->{val} && $self->{val} <= $max;
605             }
606              
607             This is also marginally more efficient, as it does not have to allocate,
608             initialize, or deallocate the unused slurpy parameter C<@etc>.
609              
610             The bare C<@> sigil is a synonym for C<...>. A bare C<%> sigil is also a
611             synonym for C<...>, but requires that there must be an even number of extra
612             arguments, such as would be assigned to a hash.
613              
614              
615             =head3 Required and optional parameters
616              
617             Parameters declared using C<$arg!> are explicitly I<required>.
618             Parameters declared using C<$arg?> are explicitly I<optional>. These
619             declarations override all other considerations.
620              
621             A parameter is implicitly I<optional> if it is a named parameter, has a
622             default, or is slurpy. All other parameters are implicitly
623             I<required>.
624              
625             # $greeting is optional because it is named
626             method hello(:$greeting) { ... }
627              
628             # $greeting is required because it is positional
629             method hello($greeting) { ... }
630              
631             # $greeting is optional because it has a default
632             method hello($greeting = "Gruezi") { ... }
633              
634             # $greeting is required because it is explicitly declared using !
635             method hello(:$greeting!) { ... }
636              
637             # $greeting is required, even with the default, because it is
638             # explicitly declared using !
639             method hello(:$greeting! = "Gruezi") { ... }
640              
641              
642             =head3 The C<@_> signature
643              
644             The @_ signature is a special case which only shifts C<$self>. It
645             leaves the rest of C<@_> alone. This way you can get $self but do the
646             rest of the argument handling manually.
647              
648             Note that a signature of C<(@_)> is exactly equivalent to a signature
649             of C<(...)>. See L<"The yada yada marker">.
650              
651              
652             =head3 The empty signature
653              
654             If a method is given the signature of C<< () >> or no signature at
655             all, it takes no arguments.
656              
657              
658             =head2 Anonymous Methods
659              
660             An anonymous method can be declared just like an anonymous sub.
661              
662             my $method = method ($arg) {
663             return $self->foo($arg);
664             };
665              
666             $obj->$method(42);
667              
668              
669             =head2 Options
670              
671             Method::Signatures takes some options at `use` time of the form
672              
673             use Method::Signatures { option => "value", ... };
674              
675             =head3 invocant
676              
677             In some cases it is desirable for the invocant to be named something other
678             than C<$self>, and specifying it in the signature of every method is tedious
679             and prone to human-error. When this option is set, methods that do not specify
680             the invocant variable in their signatures will use the given variable name.
681              
682             use Method::Signatures { invocant => '$app' };
683              
684             method main { $app->config; $app->run; $app->cleanup; }
685              
686             Note that the leading sigil I<must> be provided, and the value must be a single
687             token that would be valid as a perl variable. Currently only scalar invocant
688             variables are supported (eg, the sigil must be a C<$>).
689              
690             This option only affects the packages in which it is used. All others will
691             continue to use C<$self> as the default invocant variable.
692              
693             =head3 compile_at_BEGIN
694              
695             By default, named methods and funcs are evaluated at compile time, as
696             if they were in a BEGIN block, just like normal Perl named subs. That
697             means this will work:
698              
699             echo("something");
700              
701             # This function is compiled first
702             func echo($msg) { print $msg }
703              
704             You can turn this off lexically by setting compile_at_BEGIN to a false value.
705              
706             use Method::Signatures { compile_at_BEGIN => 0 };
707              
708             compile_at_BEGIN currently causes some issues when used with Perl 5.8.
709             See L<Earlier Perl versions>.
710              
711             =head3 debug
712              
713             When true, turns on debugging messages about compiling methods and
714             funcs. See L<DEBUGGING>. The flag is currently global, but this may
715             change.
716              
717             =head2 Differences from Perl 6
718              
719             Method::Signatures is mostly a straight subset of Perl 6 signatures.
720             The important differences...
721              
722             =head3 Restrictions on named parameters
723              
724             As noted above, there are more restrictions on named parameters than
725             in Perl 6.
726              
727             =head3 Named parameters are just hashes
728              
729             Perl 5 lacks all the fancy named parameter syntax for the caller.
730              
731             =head3 Parameters are copies.
732              
733             In Perl 6, parameters are aliases. This makes sense in Perl 6 because
734             Perl 6 is an "everything is an object" language. Perl 5 is not, so
735             parameters are much more naturally passed as copies.
736              
737             You can alias using the "alias" trait.
738              
739             =head3 Can't use positional params as named params
740              
741             Perl 6 allows you to use any parameter as a named parameter. Perl 5
742             lacks the named parameter disambiguating syntax so it is not allowed.
743              
744             =head3 Addition of the C<\@foo> reference alias prototype
745              
746             In Perl 6, arrays and hashes don't get flattened, and their
747             referencing syntax is much improved. Perl 5 has no such luxury, so
748             Method::Signatures added a way to alias references to normal variables
749             to make them easier to work with.
750              
751             =head3 Addition of the C<@_> prototype
752              
753             Method::Signatures lets you punt and use @_ like in regular Perl 5.
754              
755             =cut
756              
757             sub import {
758 119     119   49591 my $class = shift;
759 119         241 my $caller = caller;
760             # default values
761              
762             # default invocant var - end-user can change with 'invocant' option.
763 119         835 my $inv_var = '$self';
764              
765 119         196 my $hints = my_hints;
766 119         433 $hints->{METHOD_SIGNATURES_compile_at_BEGIN} = 1; # default to on
767              
768 119         131 my $arg = shift;
769 119 100       317 if (defined $arg) {
770 34 50       55 if (ref $arg) {
    0          
771 34 50       79 $DEBUG = $arg->{debug} if exists $arg->{debug};
772 34 100       50 $caller = $arg->{into} if exists $arg->{into};
773             $hints->{METHOD_SIGNATURES_compile_at_BEGIN} = $arg->{compile_at_BEGIN}
774 34 100       66 if exists $arg->{compile_at_BEGIN};
775 34 100       48 if (exists $arg->{invocant}) {
776 27         26 $inv_var = $arg->{invocant};
777             # ensure (for now) the specified value is a valid variable
778             # name (with '$' sigil) and nothing more.
779 27 100       58 if ($inv_var !~ m{ \A \$ [^\W\d]\w* \z }x) {
780 25         80 require Carp;
781 25         2534 Carp::croak("Invalid invocant name: '$inv_var'");
782             }
783             }
784             }
785             elsif ($arg eq ':DEBUG') {
786 0         0 $DEBUG = 1;
787             }
788             else {
789 0         0 require Carp;
790 0         0 Carp::croak("Invalid Module::Signatures argument $arg");
791             }
792             }
793              
794             $class->install_methodhandler(
795 94         698 into => $caller,
796             name => 'method',
797             invocant => $inv_var,
798             );
799              
800 94         19728 $class->install_methodhandler(
801             into => $caller,
802             name => 'func',
803             );
804              
805 94         12528 DEBUG("import for $caller done\n");
806 94         281 DEBUG("method invocant is '$inv_var'\n");
807             }
808              
809              
810             # Inject special code to make named functions compile at BEGIN time.
811             # Otherwise we leave injection to Devel::Declare.
812             sub inject_if_block
813             {
814 203     203 0 3448 my ($self, $inject, $before) = @_;
815              
816 203         281 my $name = $self->{function_name};
817 203   100     732 my $attrs = $self->{attributes} || '';
818              
819 203         581 DEBUG( "attributes: $attrs\n" );
820              
821             # Named function compiled at BEGIN time
822 203 100 100     631 if( defined $name && $self->_do_compile_at_BEGIN ) {
823             # Devel::Declare needs the code ref which has been generated.
824             # Fortunately, "sub foo {...}" happens at compile time, so we
825             # can use \&foo at runtime even if it comes before the sub
826             # declaration in the code!
827 186         420 $before = qq[\\&$name; sub $name $attrs ];
828             }
829              
830 203         560 DEBUG( "inject: $inject\n" );
831 203         470 DEBUG( "before: $before\n" );
832 203 50       347 DEBUG( "linestr before: ".$self->get_linestr."\n" ) if $DEBUG;
833 203         625 my $ret = $self->SUPER::inject_if_block($inject, $before);
834 203 50       5690 DEBUG( "linestr after: ". $self->get_linestr."\n" ) if $DEBUG;
835              
836 203         350 return $ret;
837             }
838              
839              
840             # Check if compile_at_BEGIN is set in this scope.
841             sub _do_compile_at_BEGIN {
842 199     199   321 my $hints = my_hints;
843              
844             # Default to on.
845 199 100       435 return 1 if !exists $hints->{METHOD_SIGNATURES_compile_at_BEGIN};
846              
847 198         617 return $hints->{METHOD_SIGNATURES_compile_at_BEGIN};
848             }
849              
850              
851             # Sometimes a compilation error will happen but not throw an error causing the
852             # code to continue compiling and producing an unrelated error down the road.
853             #
854             # A symptom of this is that eval STRING no longer works. So we detect if the
855             # parser is a dead man walking.
856             sub _parser_is_fucked {
857 229     229   248 local $@;
858 229 100       11659 return eval 42 ? 0 : 1;
859             }
860              
861              
862             # Capture the function name
863             sub strip_name {
864 222     222 0 85003 my $self = shift;
865              
866 222         732 my $name = $self->SUPER::strip_name(@_);
867 222         4831 $self->{function_name} = $name;
868              
869 222         420 return $name;
870             }
871              
872              
873             # Capture the attributes
874             sub strip_attrs {
875 222     222 0 6271 my $self = shift;
876              
877 222         670 my $attrs = $self->SUPER::strip_attrs(@_);
878 222         2651 $self->{attributes} = $attrs;
879              
880 222         387 return $attrs;
881             }
882              
883              
884             # Overriden method from D::D::MS
885             sub parse_proto {
886 229     229 0 4458 my $self = shift;
887 229         231 my $proto = shift;
888              
889             # Before we try to compile signatures, make sure there isn't a hidden compilation error.
890 229 100       345 die $@ if _parser_is_fucked;
891              
892             $self->{signature} = Method::Signatures::Signature->new(
893             signature_string => defined $proto ? $proto : "",
894             invocant => $self->{invocant},
895             pre_invocant => $self->{pre_invocant}
896 227 100       4178 );
897              
898             # Then turn it into Perl code
899 210         1396 my $inject = $self->inject_from_signature();
900              
901 210         697 return $inject;
902             }
903              
904              
905             # Turn the parsed signature into Perl code
906             sub inject_from_signature {
907 210     210 0 10107 my $self = shift;
908 210   33     506 my $class = ref $self || $self;
909 210         300 my $signature = $self->{signature};
910              
911 210         253 $self->{line_number} = 1;
912              
913 210         178 my @code;
914 210 50       581 push @code, "my @{[$signature->pre_invocant]} = shift;" if $signature->pre_invocant;
  0         0  
915 210 100       544 push @code, "my @{[$signature->invocant]} = shift;" if $signature->invocant;
  158         862  
916              
917 210         255 for my $sig (@{$signature->positional_parameters}) {
  210         509  
918 219         436 push @code, $self->inject_for_sig($sig);
919             }
920              
921 210 100       226 if( @{$signature->named_parameters} ) {
  210         566  
922 24         29 my $first_named_idx = @{$signature->positional_parameters};
  24         51  
923 24 100       31 if (grep { $_->is_ref_alias or $_->traits->{alias} } @{$signature->named_parameters})
  42 100       205  
  24         55  
924             {
925 4         27 require Data::Alias;
926 4         11 push @code, "Data::Alias::alias( my (\%args) = \@_[$first_named_idx..\$#_] );";
927             }
928             else
929             {
930 20         52 push @code, "my (\%args) = \@_[$first_named_idx..\$#_];";
931             }
932              
933 24         34 for my $sig (@{$signature->named_parameters}) {
  24         59  
934 42         86 push @code, $self->inject_for_sig($sig);
935             }
936              
937 24 100 66     71 push @code, $class . '->named_param_error(\%args) if keys %args;'
938             if $signature->num_named && !$signature->num_yadayada;
939             }
940              
941 210         404 my $max_argv = $signature->max_argv_size;
942 210         308 my $max_args = $signature->max_args;
943 210 100       918 push @code, qq[$class->too_many_args_error($max_args) if scalar(\@_) > $max_argv; ]
944             unless $max_argv == $INF;
945              
946             # Add any additional trailing newlines so the body is on the right line.
947 210         923 push @code, $self->inject_newlines( $signature->num_lines - $self->{line_number} );
948              
949             # All on one line.
950 210         766 return join ' ', @code;
951             }
952              
953              
954             sub too_many_args_error {
955 9     9 1 5725 my($class, $max_args) = @_;
956              
957 9         37 $class->signature_error("was given too many arguments; it expects $max_args");
958             }
959              
960              
961             sub odd_number_args_error {
962 1     1 0 1738 my($class) = @_;
963              
964 1         2 $class->signature_error('was given an odd number of arguments for a placeholder hash');
965             }
966              
967              
968             sub named_param_error {
969 3     3 1 17604 my ($class, $args) = @_;
970 3         7 my @keys = keys %$args;
971              
972 3         19 $class->signature_error("does not take @keys as named argument(s)");
973             }
974              
975             # Regex to determine if a where clause is a block.
976             my $when_block_re = qr{
977             ^
978             \s*
979             \{
980             (?:
981             .* ; .* | # statements separated by semicolons
982             (?:(?! => ). )+ # doesn't look like a hash with fat commas
983             )
984             \}
985             \s*
986             $
987             }xs;
988              
989             sub inject_for_sig {
990 261     261 0 237 my $self = shift;
991 261   33     548 my $class = ref $self || $self;
992 261         213 my $sig = shift;
993              
994 261 100       993 return if $sig->is_at_underscore;
995              
996 257         208 my @code;
997              
998             # Add any necessary leading newlines so line numbers are preserved.
999 257         753 push @code, $self->inject_newlines($sig->first_line_number - $self->{line_number});
1000              
1001 257 100       815 if( $sig->is_hash_yadayada ) {
1002 1         3 my $is_odd = $sig->position % 2;
1003 1         3 push @code, qq[$class->odd_number_args_error() if scalar(\@_) % 2 != $is_odd;];
1004 1         2 return @code;
1005             }
1006              
1007 256         442 my $sigil = $sig->sigil;
1008 256         385 my $name = $sig->variable_name;
1009 256         358 my $idx = $sig->position;
1010 256         324 my $var = $sig->variable;
1011              
1012             # These are the defaults.
1013 256         320 my $lhs = "my $var";
1014 256         198 my ($rhs, $deletion_target);
1015              
1016 256 100       509 if( $sig->is_named ) {
1017 42         114 $sig->passed_in("\$args{$name}");
1018 42         71 $rhs = $deletion_target = $sig->passed_in;
1019 42 100       110 $rhs = "${sigil}{$rhs}" if $sig->is_ref_alias;
1020             }
1021             else {
1022 214 100       1056 $rhs = $sig->is_ref_alias ? "${sigil}{\$_[$idx]}" :
    100          
1023             $sig->sigil =~ /^[@%]$/ ? "\@_[$idx..\$#_]" :
1024             "\$_[$idx]" ;
1025 214         502 $sig->passed_in($rhs);
1026             }
1027              
1028 256 100       644 my $check_exists = $sig->is_named ? "exists \$args{$name}" : "( scalar(\@_) > $idx)";
1029 256         516 $sig->check_exists($check_exists);
1030              
1031 256         373 my $default = $sig->default;
1032 256         351 my $when = $sig->default_when;
1033              
1034             # Handle a default value
1035 256 100       557 if( defined $when ) {
    100          
1036             # Handle default with 'when { block using $_ }'
1037 54 100       185 if ($when =~ $when_block_re) {
1038 6         13 $rhs = "!$check_exists ? ($default) : do{ no warnings; my \$arg = $rhs; (grep $when \$arg) ? ($default) : \$arg}";
1039             }
1040              
1041             # Handle default with 'when anything_else'
1042             else {
1043 48         118 $rhs = "!$check_exists ? ($default) : do{ no warnings; my \$arg = $rhs; \$arg ~~ ($when) ? ($default) : \$arg }";
1044             }
1045             }
1046             # Handle simple defaults
1047             elsif( defined $default ) {
1048 34         68 $rhs = "$check_exists ? ($rhs) : ($default)";
1049             }
1050              
1051 256 100       547 if( $sig->is_required ) {
1052 119 100       264 if( $sig->is_placeholder ) {
1053 3         10 push @code, qq[${class}->required_placeholder_arg('$idx') unless $check_exists; ];
1054             } else {
1055 116         334 push @code, qq[${class}->required_arg('$var') unless $check_exists; ];
1056             }
1057             }
1058              
1059             # Handle \@foo
1060 256 100 100     1384 if ( $sig->is_ref_alias or $sig->traits->{alias} ) {
    100          
1061 13         62 require Data::Alias;
1062 13         58 push @code, sprintf 'Data::Alias::alias(%s = %s);', $lhs, $rhs;
1063             }
1064             # Handle "is ro"
1065             elsif ( $sig->traits->{ro} ) {
1066 16         3350 require Const::Fast;
1067 16         5698 push @code, "Const::Fast::const( $lhs => $rhs );";
1068             } else {
1069 227         411 push @code, "$lhs = $rhs;";
1070             }
1071              
1072 256 100       562 if( $sig->type ) {
1073 54         116 push @code, $self->inject_for_type_check($sig);
1074             }
1075              
1076             # Named arg has been handled, so don't pass to error handler
1077 256 100       471 push @code, "delete( $deletion_target );" if $deletion_target;
1078              
1079             # Handle 'where' constraints (after defaults are resolved)
1080 256         202 for my $constraint ( @{$sig->where} ) {
  256         613  
1081             # Handle 'where { block using $_ }'
1082 8 100       33 my $constraint_impl =
1083             $constraint =~ m{^ \s* \{ (?: .* ; .* | (?:(?! => ). )* ) \} \s* $}xs
1084             ? "sub $constraint"
1085             : $constraint;
1086              
1087 8 100       18 my( $error_reporter, $var_name ) =
1088             $sig->is_placeholder
1089             ? ( 'placeholder_where_error', $sig->position )
1090             : ( 'where_error', $var );
1091 8         18 my $error = sprintf q{ %s->%s(%s, '%s', '%s') }, $class, $error_reporter, $var, $var_name, $constraint;
1092 8         22 push @code, "$error unless do { no if \$] >= 5.017011, warnings => 'experimental::smartmatch'; grep { \$_ ~~ $constraint_impl } $var }; ";
1093             }
1094              
1095 256 100       551 if( $sig->is_placeholder ) {
1096 4         5 unshift @code, 'do {';
1097 4         6 push @code, '};';
1098             }
1099              
1100             # Record the current line number for the next injection.
1101 256         409 $self->{line_number} = $sig->first_line_number;
1102              
1103 256         679 return @code;
1104             }
1105              
1106 0     0   0 sub __magic_newline() { die "newline() should never be called"; }
1107              
1108             # Devel::Declare cannot normally inject multiple lines.
1109             # This is a way to trick it, the parser will continue through
1110             # a function call with a newline in the argument list.
1111             sub inject_newlines {
1112 467     467 0 385 my $self = shift;
1113 467         335 my $num_newlines = shift;
1114              
1115 467 100       884 return if $num_newlines == 0;
1116              
1117 33         138 return sprintf q[ Method::Signatures::__magic_newline(%s) if 0; ],
1118             "\n" x $num_newlines;
1119             }
1120              
1121              
1122             # A hook for extension authors
1123             # (see also type_check below)
1124             sub inject_for_type_check
1125             {
1126 52     52 1 52 my $self = shift;
1127 52   33     123 my $class = ref $self || $self;
1128 52         59 my ($sig) = @_;
1129              
1130 52 100 100     110 my $check_exists = $sig->is_optional && !defined $sig->default
1131             ? $sig->check_exists : '';
1132              
1133             # This is an optimization to unroll typecheck which makes Mouse types about 40% faster.
1134             # It only happens when type_check() has not been overridden.
1135 52 100       490 if( $class->can("type_check") eq __PACKAGE__->can("type_check") ) {
1136 51         290 my $check = sprintf q[($%s::mutc{cache}{'%s'} ||= %s->_make_constraint('%s'))->check(%s)],
1137             __PACKAGE__, $sig->type, $class, $sig->type, $sig->variable;
1138              
1139 51 100       171 my( $error_reporter, $variable_name ) =
1140             $sig->is_placeholder
1141             ? ( 'placeholder_type_error', $sig->position )
1142             : ( 'type_error', $sig->variable_name );
1143 51         171 my $error = sprintf q[%s->%s('%s', %s, '%s') ],
1144             $class, $error_reporter, $sig->type, $sig->variable, $variable_name;
1145 51         71 my $code = "$error if ";
1146 51 100       118 $code .= "$check_exists && " if $check_exists;
1147 51         84 $code .= "!$check";
1148 51         140 return "$code;";
1149             }
1150             # If a subclass has overridden type_check(), we must use that.
1151             else {
1152 1         2 my $name = $sig->variable_name;
1153 1         2 my $code = "${class}->type_check('@{[$sig->type]}', @{[$sig->passed_in]}, '$name')";
  1         4  
  1         23  
1154 1 50       3 $code .= "if $check_exists" if $check_exists;
1155 1         4 return "$code;";
1156             }
1157             }
1158              
1159             # This class method just dies with the message generated by signature_error.
1160             # If necessary it can be overridden by a subclass to do something fancier.
1161             #
1162             sub signature_error_handler {
1163 67     67 1 167 my ($class, $msg) = @_;
1164 67         450 die $msg;
1165             }
1166              
1167             # This is a common function to throw errors so that they appear to be from the point of the calling
1168             # sub, not any of the Method::Signatures subs.
1169             sub signature_error {
1170 68     68 1 868 my ($proto, $msg) = @_;
1171 68   33     277 my $class = ref $proto || $proto;
1172              
1173 68         246 my ($file, $line, $method) = carp_location_for($class);
1174 68         301 $class->signature_error_handler("In call to $method(), $msg at $file line $line.\n");
1175             }
1176              
1177             sub required_arg {
1178 9     9 1 8120 my ($class, $var) = @_;
1179              
1180 9         37 $class->signature_error("missing required argument $var");
1181             }
1182              
1183              
1184             sub required_placeholder_arg {
1185 3     3 0 1674 my ($class, $idx) = @_;
1186              
1187 3         11 $class->signature_error("missing required placeholder argument at position $idx");
1188             }
1189              
1190              
1191             # STUFF FOR TYPE CHECKING
1192              
1193             # This variable will hold all the bits we need. MUTC could stand for Moose::Util::TypeConstraint,
1194             # or it could stand for Mouse::Util::TypeConstraint ... depends on which one you've got loaded (or
1195             # Mouse if you have neither loaded). Because we use Any::Moose to allow the user to choose
1196             # whichever they like, we'll need to figure out the exact method names to call. We'll also need a
1197             # type constraint cache, where we stick our constraints once we find or create them. This insures
1198             # that we only have to run down any given constraint once, the first time it's seen, and then after
1199             # that it's simple enough to pluck back out. This is very similar to how MooseX::Params::Validate
1200             # does it.
1201             our %mutc;
1202              
1203             # This is a helper function to initialize our %mutc variable.
1204             sub _init_mutc
1205             {
1206 13     13   6053 require Any::Moose;
1207 13         15169 Any::Moose->import('::Util::TypeConstraints');
1208              
1209 61     61   334 no strict 'refs';
  61         76  
  61         29343  
1210 13         5726 my $class = any_moose('::Util::TypeConstraints');
1211 13         505 $mutc{class} = $class;
1212              
1213 13         21 $mutc{findit} = \&{ $class . '::find_or_parse_type_constraint' };
  13         68  
1214 13         20 $mutc{pull} = \&{ $class . '::find_type_constraint' };
  13         47  
1215 13         17 $mutc{make_class} = \&{ $class . '::class_type' };
  13         44  
1216 13         62 $mutc{make_role} = \&{ $class . '::role_type' };
  13         42  
1217              
1218 13         56 $mutc{isa_class} = $mutc{pull}->("ClassName");
1219 13         290 $mutc{isa_role} = $mutc{pull}->("RoleName");
1220             }
1221              
1222             # This is a helper function to find (or create) the constraint we need for a given type. It would
1223             # be called when the type is not found in our cache.
1224             sub _make_constraint
1225             {
1226 31     31   343086 my ($class, $type) = @_;
1227              
1228 31 100       186 _init_mutc() unless $mutc{class};
1229              
1230             # Look for basic types (Int, Str, Bool, etc). This will also create a new constraint for any
1231             # parameterized types (e.g. ArrayRef[Int]) or any disjunctions (e.g. Int|ScalarRef[Int]).
1232 31         210 my $constr = eval { $mutc{findit}->($type) };
  31         96  
1233 31 100       5871 if ($@)
1234             {
1235 1         4 $class->signature_error("the type $type is unrecognized (looks like it doesn't parse correctly)");
1236             }
1237 30 100       466 return $constr if $constr;
1238              
1239             # Check for roles. Note that you *must* check for roles before you check for classes, because a
1240             # role ISA class.
1241 5 50       96 return $mutc{make_role}->($type) if $mutc{isa_role}->check($type);
1242              
1243             # Now check for classes.
1244 5 100       29 return $mutc{make_class}->($type) if $mutc{isa_class}->check($type);
1245              
1246 2         10 $class->signature_error("the type $type is unrecognized (perhaps you forgot to load it?)");
1247             }
1248              
1249             # This method does the actual type checking. It's what we inject into our user's method, to be
1250             # called directly by them.
1251             #
1252             # Note that you can override this instead of inject_for_type_check if you'd rather. If you do,
1253             # remember that this is a class method, not an object method. That's because it's called at
1254             # runtime, when there is no Method::Signatures object still around.
1255             sub type_check
1256             {
1257 0     0 1 0 my ($class, $type, $value, $name) = @_;
1258              
1259             # find it if isn't cached
1260 0   0     0 $mutc{cache}->{$type} ||= $class->_make_constraint($type);
1261              
1262             # throw an error if the type check fails
1263 0 0       0 unless ($mutc{cache}->{$type}->check($value))
1264             {
1265 0         0 $class->type_error($type, $value, $name);
1266             }
1267              
1268             # $mutc{cache} = {};
1269             }
1270              
1271             # If you just want to change what the type failure errors look like, just override this.
1272             # Note that you can call signature_error yourself to handle the croak-like aspects.
1273             sub type_error
1274             {
1275 19     19 1 9354 my ($class, $type, $value, $name) = @_;
1276 19 100       57 $value = defined $value ? qq{"$value"} : 'undef';
1277 19         63 $class->signature_error(qq{the '$name' parameter ($value) is not of type $type});
1278             }
1279              
1280             sub placeholder_type_error
1281             {
1282 1     1 0 340 my ($class, $type, $value, $idx) = @_;
1283 1 50       4 $value = defined $value ? qq{"$value"} : 'undef';
1284 1         4 $class->signature_error(qq{the placeholder parameter at position $idx ($value) is not of type $type});
1285             }
1286              
1287             # Errors from `where' constraints are handled here.
1288             sub where_error
1289             {
1290 15     15 1 25688 my ($class, $value, $name, $constraint) = @_;
1291 15 100       41 $value = defined $value ? qq{"$value"} : 'undef';
1292 15         39 $class->signature_error(qq{$name value ($value) does not satisfy constraint: $constraint});
1293             }
1294              
1295             sub placeholder_where_error
1296             {
1297 1     1 0 2 my ($class, $value, $idx, $constraint) = @_;
1298 1 50       4 $value = defined $value ? qq{"$value"} : 'undef';
1299 1         4 $class->signature_error(qq{the placeholder parameter at position $idx value ($value) does not satisfy constraint: $constraint});
1300             }
1301              
1302             =head1 PERFORMANCE
1303              
1304             There is no run-time performance penalty for using this module above
1305             what it normally costs to do argument handling.
1306              
1307             There is also no run-time penalty for type-checking if you do not
1308             declare types. The run-time penalty if you do declare types should be
1309             very similar to using L<Mouse::Util::TypeConstraints> (or
1310             L<Moose::Util::TypeConstraints>) directly, and should be faster than
1311             using a module such as L<MooseX::Params::Validate>. The magic of
1312             L<Any::Moose> is used to give you the lightweight L<Mouse> if you have
1313             not yet loaded L<Moose>, or the full-bodied L<Moose> if you have.
1314              
1315             Type-checking modules are not loaded until run-time, so this is fine:
1316              
1317             use Method::Signatures;
1318             use Moose;
1319             # you will still get Moose type checking
1320             # (assuming you declare one or more methods with types)
1321              
1322              
1323             =head1 DEBUGGING
1324              
1325             One of the best ways to figure out what Method::Signatures is doing is
1326             to run your code through B::Deparse (run the code with -MO=Deparse).
1327              
1328             Setting the C<METHOD_SIGNATURES_DEBUG> environment variable will cause
1329             Method::Signatures to display debugging information when it is
1330             compiling signatures.
1331              
1332             =head1 EXAMPLE
1333              
1334             Here's an example of a method which displays some text and takes some
1335             extra options.
1336              
1337             use Method::Signatures;
1338              
1339             method display($text is ro, :$justify = "left", :$fh = \*STDOUT) {
1340             ...
1341             }
1342              
1343             # $text = $stuff, $justify = "left" and $fh = \*STDOUT
1344             $obj->display($stuff);
1345              
1346             # $text = $stuff, $justify = "left" and $fh = \*STDERR
1347             $obj->display($stuff, fh => \*STDERR);
1348              
1349             # error, missing required $text argument
1350             $obj->display();
1351              
1352             The display() method is equivalent to all this code.
1353              
1354             sub display {
1355             my $self = shift;
1356              
1357             croak('display() missing required argument $text') unless @_ > 0;
1358             const my $text = $_[0];
1359              
1360             my(%args) = @_[1 .. $#_];
1361             my $justify = exists $args{justify} ? $args{justify} : 'left';
1362             my $fh = exists $args{fh} ? $args{'fh'} : \*STDOUT;
1363              
1364             ...
1365             }
1366              
1367              
1368             =head1 EXPERIMENTING
1369              
1370             If you want to experiment with the prototype syntax, start with
1371             C<Method::Signatures::parse_func>. It takes a method prototype
1372             and returns a string of Perl 5 code which will be placed at the
1373             beginning of that method.
1374              
1375             If you would like to try to provide your own type checking, subclass
1376             L<Method::Signatures> and either override C<type_check> or
1377             C<inject_for_type_check>. See L</EXTENDING>, below.
1378              
1379             This interface is experimental, unstable and will change between
1380             versions.
1381              
1382              
1383             =head1 EXTENDING
1384              
1385             If you wish to subclass Method::Signatures, the following methods are
1386             good places to start.
1387              
1388             =head2 too_many_args_error, named_param_error, required_arg, type_error, where_error
1389              
1390             These are class methods which report the various run-time errors
1391             (extra parameters, unknown named parameter, required parameter
1392             missing, parameter fails type check, and parameter fails where
1393             constraint respectively). Note that each one calls
1394             C<signature_error>, which your versions should do as well.
1395              
1396             =head2 signature_error
1397              
1398             This is a class method which calls C<signature_error_handler> (see
1399             below) and reports the error as being from the caller's perspective.
1400             Most likely you will not need to override this. If you'd like to have
1401             Method::Signatures errors give full stack traces (similar to
1402             C<$Carp::Verbose>), have a look at L<Carp::Always>.
1403              
1404             =head2 signature_error_handler
1405              
1406             By default, C<signature_error> generates an error message and
1407             C<die>s with that message. If you need to do something fancier with
1408             the generated error message, your subclass can define its own
1409             C<signature_error_handler>. For example:
1410              
1411             package My::Method::Signatures;
1412              
1413             use Moose;
1414             extends 'Method::Signatures';
1415              
1416             sub signature_error_handler {
1417             my ($class, $msg) = @_;
1418             die bless { message => $msg }, 'My::ExceptionClass';
1419             };
1420              
1421             =head2 type_check
1422              
1423             This is a class method which is called to verify that parameters have
1424             the proper type. If you want to change the way that
1425             Method::Signatures does its type checking, this is most likely what
1426             you want to override. It calls C<type_error> (see above).
1427              
1428             =head2 inject_for_type_check
1429              
1430             This is the object method that actually inserts the call to
1431             L</type_check> into your Perl code. Most likely you will not need to
1432             override this, but if you wanted different parameters passed into
1433             C<type_check>, this would be the place to do it.
1434              
1435              
1436             =head1 BUGS, CAVEATS and NOTES
1437              
1438             Please report bugs and leave feedback at
1439             E<lt>bug-Method-SignaturesE<gt> at E<lt>rt.cpan.orgE<gt>. Or use the
1440             web interface at L<http://rt.cpan.org>. Report early, report often.
1441              
1442             =head2 One liners
1443              
1444             If you want to write "use Method::Signatures" in a one-liner, do a
1445             C<-MMethod::Signatures> first. This is due to a bug/limitation in
1446             Devel::Declare.
1447              
1448             =head2 Close parends in quotes or comments
1449              
1450             Because of the way L<Devel::Declare> parses things, an unbalanced
1451             close parend inside a quote or comment could throw off the signature
1452             parsing. For instance:
1453              
1454             func foo (
1455             $foo, # $foo might contain )
1456             $bar
1457             )
1458              
1459             is going to produce a syntax error, because the parend inside the
1460             comment is perceived as the end of the signature. On the other hand,
1461             this:
1462              
1463             func foo (
1464             $foo, # (this is the $foo parend)
1465             $bar
1466             )
1467              
1468             is fine, because the parends in the comments are balanced.
1469              
1470             If you absolutely can't avoid an unbalanced close parend, such as in
1471             the following signature:
1472              
1473             func foo ( $foo, $bar = ")" ) # this won't parse correctly
1474              
1475             you can always use a backslash to tell the parser that that close
1476             parend doesn't indicate the end of the signature:
1477              
1478             func foo ( $foo, $bar = "\)" ) # this is fine
1479              
1480             This even works in single quotes:
1481              
1482             func foo ( $foo, $bar = '\)' ) # default is ')', *not* '\)'!
1483              
1484             although we don't recomment that form, as it may be surprising to
1485             readers of your code.
1486              
1487             =head2 No source filter
1488              
1489             While this module does rely on the black magic of L<Devel::Declare> to
1490             access Perl's own parser, it does not depend on a source filter. As
1491             such, it doesn't try to parse and rewrite your source code and there
1492             should be no weird side effects.
1493              
1494             Devel::Declare only affects compilation. After that, it's a normal
1495             subroutine. As such, for all that hairy magic, this module is
1496             surprisingly stable.
1497              
1498             =head2 Earlier Perl versions
1499              
1500             The most noticeable is if an error occurs at compile time, such as a
1501             strict error, perl might not notice until it tries to compile
1502             something else via an C<eval> or C<require> at which point perl will
1503             appear to fail where there is no reason to fail.
1504              
1505             We recommend you use the L<"compile_at_BEGIN"> flag to turn off
1506             compile-time parsing.
1507              
1508             You can't use any feature that requires a smartmatch expression (i.e.
1509             conditional L<"Defaults"> and L<"Value Constraints">) in Perl 5.8.
1510              
1511             Method::Signatures cannot be used with Perl versions prior to 5.8
1512             because L<Devel::Declare> does not work with those earlier versions.
1513              
1514             =head2 What about class methods?
1515              
1516             Right now there's nothing special about class methods. Just use
1517             C<$class> as your invocant like the normal Perl 5 convention.
1518              
1519             There may be special syntax to separate class from object methods in
1520             the future.
1521              
1522             =head2 What about the return value?
1523              
1524             Currently there is no support for declaring the type of the return
1525             value.
1526              
1527             =head2 How does this relate to Perl's built-in prototypes?
1528              
1529             It doesn't. Perl prototypes are a rather different beastie from
1530             subroutine signatures. They don't work on methods anyway.
1531              
1532             A syntax for function prototypes is being considered.
1533              
1534             func($foo, $bar?) is proto($;$)
1535              
1536             =head2 Error checking
1537              
1538             Here's some additional checks I would like to add, mostly to avoid
1539             ambiguous or non-sense situations.
1540              
1541             * If one positional param is optional, everything to the right must be optional
1542              
1543             method foo($a, $b?, $c?) # legal
1544              
1545             method bar($a, $b?, $c) # illegal, ambiguous
1546              
1547             Does C<< ->bar(1,2) >> mean $a = 1 and $b = 2 or $a = 1, $c = 3?
1548              
1549             * Positionals are resolved before named params. They have precedence.
1550              
1551              
1552             =head2 Slurpy parameter restrictions
1553              
1554             Slurpy parameters are currently more restricted than they need to be.
1555             It is possible to work out a slurpy parameter in the middle, or a
1556             named slurpy parameter. However, there's lots of edge cases and
1557             possible nonsense configurations. Until that's worked out, we've left
1558             it restricted.
1559              
1560             =head2 What about...
1561              
1562             Method traits are in the pondering stage.
1563              
1564             An API to query a method's signature is in the pondering stage.
1565              
1566             Now that we have method signatures, multi-methods are a distinct possibility.
1567              
1568             Applying traits to all parameters as a short-hand?
1569              
1570             # Equivalent?
1571             method foo($a is ro, $b is ro, $c is ro)
1572             method foo($a, $b, $c) is ro
1573              
1574             L<Role::Basic> roles are currently not recognized by the type system.
1575              
1576             A "go really fast" switch. Turn off all runtime checks that might
1577             bite into performance.
1578              
1579             Method traits.
1580              
1581             method add($left, $right) is predictable # declarative
1582             method add($left, $right) is cached # procedural
1583             # (and Perl 6 compatible)
1584              
1585              
1586             =head1 THANKS
1587              
1588             Most of this module is based on or copied from hard work done by many
1589             other people.
1590              
1591             All the really scary parts are copied from or rely on Matt Trout's,
1592             Florian Ragwitz's and Rhesa Rozendaal's L<Devel::Declare> work.
1593              
1594             The prototype syntax is a slight adaptation of all the
1595             excellent work the Perl 6 folks have already done.
1596              
1597             The type checking and method modifier work was supplied by Buddy
1598             Burden (barefootcoder). Thanks to this, you can now use
1599             Method::Signatures (or, more properly,
1600             L<Method::Signatures::Modifiers>) instead of
1601             L<MooseX::Method::Signatures>, which fixes many of the problems
1602             commonly attributed to L<MooseX::Declare>.
1603              
1604             Value constraints and default conditions (i.e. "where" and "when")
1605             were added by Damian Conway, who also rewrote some of the signature
1606             parsing to make it more robust and more extensible.
1607              
1608             Also thanks to Matthijs van Duin for his awesome L<Data::Alias> which
1609             makes the C<\@foo> signature work perfectly and L<Sub::Name> which
1610             makes the subroutine names come out right in caller().
1611              
1612             And thanks to Florian Ragwitz for his parallel
1613             L<MooseX::Method::Signatures> module from which I borrow ideas and
1614             code.
1615              
1616              
1617             =head1 LICENSE
1618              
1619             The original code was taken from Matt S. Trout's tests for L<Devel::Declare>.
1620              
1621             Copyright 2007-2012 by Michael G Schwern E<lt>schwern@pobox.comE<gt>.
1622              
1623             This program is free software; you can redistribute it and/or
1624             modify it under the same terms as Perl itself.
1625              
1626             See F<http://www.perl.com/perl/misc/Artistic.html>
1627              
1628              
1629             =head1 SEE ALSO
1630              
1631             L<MooseX::Method::Signatures> for an alternative implementation.
1632              
1633             L<Perl6::Signature> for a more complete implementation of Perl 6 signatures.
1634              
1635             L<Method::Signatures::Simple> for a more basic version of what Method::Signatures provides.
1636              
1637             L<Function::Parameters> for a subset of Method::Signature's features without using L<Devel::Declare>.
1638              
1639             L<signatures> for C<sub> with signatures.
1640              
1641             Perl 6 subroutine parameters and arguments - L<http://perlcabal.org/syn/S06.html#Parameters_and_arguments>
1642              
1643             L<Moose::Util::TypeConstraints> or L<Mouse::Util::TypeConstraints> for
1644             further details on how the type-checking works.
1645              
1646             =cut
1647              
1648              
1649             1;