4dd9b569e3679a37f18934c9be3057a8180ff0b6
[gitmo/MooseX-Types.git] / lib / MooseX / Types.pm
1 package MooseX::Types;
2 use Moose;
3
4 =head1 NAME
5
6 MooseX::Types - Organise your Moose types in libraries
7
8 =cut
9
10 use Moose::Util::TypeConstraints;
11 use MooseX::Types::TypeDecorator;
12 use MooseX::Types::Base             ();
13 use MooseX::Types::Util             qw( filter_tags );
14 use MooseX::Types::UndefinedType;
15 use Carp::Clan                      qw( ^MooseX::Types );
16
17 use namespace::clean -except => [qw( meta )];
18
19 use 5.008;
20 our $VERSION = '0.10';
21 my $UndefMsg = q{Action for type '%s' not yet defined in library '%s'};
22
23 =head1 SYNOPSIS
24
25 =head2 Library Definition
26
27   package MyLibrary;
28
29   # predeclare our own types
30   use MooseX::Types 
31     -declare => [qw(
32         PositiveInt NegativeInt
33         ArrayRefOfPositiveInt ArrayRefOfAtLeastThreeNegativeInts
34         LotsOfInnerConstraints StrOrArrayRef
35     )];
36
37   # import builtin types
38   use MooseX::Types::Moose 'Int';
39
40   # type definition.
41   subtype PositiveInt, 
42       as Int, 
43       where { $_ > 0 },
44       message { "Int is not larger than 0" };
45   
46   subtype NegativeInt,
47       as Int,
48       where { $_ < 0 },
49       message { "Int is not smaller than 0" };
50
51   # type coercion
52   coerce PositiveInt,
53       from Int,
54           via { 1 };
55
56   # with parameterized constraints.
57   
58   subtype ArrayRefOfPositiveInt,
59     as ArrayRef[PositiveInt];
60     
61   subtype ArrayRefOfAtLeastThreeNegativeInts,
62     as ArrayRef[NegativeInt],
63     where { scalar(@$_) > 2 };
64
65   subtype LotsOfInnerConstraints,
66     as ArrayRef[ArrayRef[HashRef[Int]]];
67     
68   # with TypeConstraint Unions
69   
70   subtype StrOrArrayRef,
71     as Str|ArrayRef;
72
73   1;
74
75 =head2 Usage
76
77   package Foo;
78   use Moose;
79   use MyLibrary qw( PositiveInt NegativeInt );
80
81   # use the exported constants as type names
82   has 'bar',
83       isa    => PositiveInt,
84       is     => 'rw';
85   has 'baz',
86       isa    => NegativeInt,
87       is     => 'rw';
88
89   sub quux {
90       my ($self, $value);
91
92       # test the value
93       print "positive\n" if is_PositiveInt($value);
94       print "negative\n" if is_NegativeInt($value);
95
96       # coerce the value, NegativeInt doesn't have a coercion
97       # helper, since it didn't define any coercions.
98       $value = to_PositiveInt($value) or die "Cannot coerce";
99   }
100
101   1;
102
103 =head1 DESCRIPTION
104
105 The types provided with L<Moose> are by design global. This package helps
106 you to organise and selectively import your own and the built-in types in
107 libraries. As a nice side effect, it catches typos at compile-time too.
108
109 However, the main reason for this module is to provide an easy way to not
110 have conflicts with your type names, since the internal fully qualified
111 names of the types will be prefixed with the library's name.
112
113 This module will also provide you with some helper functions to make it 
114 easier to use Moose types in your code.
115
116 =head1 TYPE HANDLER FUNCTIONS
117
118 =head2 $type
119
120 A constant with the name of your type. It contains the type's fully
121 qualified name. Takes no value, as all constants.
122
123 =head2 is_$type
124
125 This handler takes a value and tests if it is a valid value for this
126 C<$type>. It will return true or false.
127
128 =head2 to_$type
129
130 A handler that will take a value and coerce it into the C<$type>. It will
131 return a false value if the type could not be coerced.
132
133 B<Important Note>: This handler will only be exported for types that can
134 do type coercion. This has the advantage that a coercion to a type that
135 cannot hasn't defined any coercions will lead to a compile-time error.
136
137 =head1 LIBRARY DEFINITION
138
139 A MooseX::Types is just a normal Perl module. Unlike Moose 
140 itself, it does not install C<use strict> and C<use warnings> in your
141 class by default, so this is up to you.
142
143 The only thing a library is required to do is
144
145   use MooseX::Types -declare => \@types;
146
147 with C<@types> being a list of types you wish to define in this library.
148 This line will install a proper base class in your package as well as the
149 full set of L<handlers|/"TYPE HANDLER FUNCTIONS"> for your declared 
150 types. It will then hand control over to L<Moose::Util::TypeConstraints>'
151 C<import> method to export the functions you will need to declare your
152 types.
153
154 If you want to use Moose' built-in types (e.g. for subtyping) you will 
155 want to 
156
157   use MooseX::Types::Moose @types;
158
159 to import the helpers from the shipped L<MooseX::Types::Moose>
160 library which can export all types that come with Moose.
161
162 You will have to define coercions for your types or your library won't
163 export a L</to_$type> coercion helper for it.
164
165 Note that you currently cannot define types containing C<::>, since 
166 exporting would be a problem.
167
168 You also don't need to use C<warnings> and C<strict>, since the
169 definition of a library automatically exports those.
170
171 =head1 LIBRARY USAGE
172
173 You can import the L<"type helpers"|/"TYPE HANDLER FUNCTIONS"> of a
174 library by C<use>ing it with a list of types to import as arguments. If
175 you want all of them, use the C<:all> tag. For example:
176
177   use MyLibrary      ':all';
178   use MyOtherLibrary qw( TypeA TypeB );
179
180 MooseX::Types comes with a library of Moose' built-in types called
181 L<MooseX::Types::Moose>.
182
183 The exporting mechanism is, since version 0.5, implemented via a wrapper
184 around L<Sub::Exporter>. This means you can do something like this:
185
186   use MyLibrary TypeA => { -as => 'MyTypeA' },
187                 TypeB => { -as => 'MyTypeB' };
188
189 =head1 WRAPPING A LIBRARY
190
191 You can define your own wrapper subclasses to manipulate the behaviour
192 of a set of library exports. Here is an example:
193
194   package MyWrapper;
195   use strict;
196   use Class::C3;
197   use base 'MooseX::Types::Wrapper';
198
199   sub coercion_export_generator {
200       my $class = shift;
201       my $code = $class->next::method(@_);
202       return sub {
203           my $value = $code->(@_);
204           warn "Coercion returned undef!"
205               unless defined $value;
206           return $value;
207       };
208   }
209
210   1;
211
212 This class wraps the coercion generator (e.g., C<to_Int()>) and warns
213 if a coercion returned an undefined value. You can wrap any library
214 with this:
215
216   package Foo;
217   use strict;
218   use MyWrapper MyLibrary => [qw( Foo Bar )],
219                 Moose     => [qw( Str Int )];
220
221   ...
222   1;
223
224 The C<Moose> library name is a special shortcut for 
225 L<MooseX::Types::Moose>.
226
227 =head2 Generator methods you can overload
228
229 =over 4
230
231 =item type_export_generator( $short, $full )
232
233 Creates a closure returning the type's L<Moose::Meta::TypeConstraint> 
234 object. 
235
236 =item check_export_generator( $short, $full, $undef_message )
237
238 This creates the closure used to test if a value is valid for this type.
239
240 =item coercion_export_generator( $short, $full, $undef_message )
241
242 This is the closure that's doing coercions.
243
244 =back
245
246 =head2 Provided Parameters
247
248 =over 4
249
250 =item $short
251
252 The short, exported name of the type.
253
254 =item $full
255
256 The fully qualified name of this type as L<Moose> knows it.
257
258 =item $undef_message
259
260 A message that will be thrown when type functionality is used but the
261 type does not yet exist.
262
263 =back
264
265 =head1 RECURSIVE SUBTYPES
266
267 As of version 0.08, L<Moose::Types> has experimental support for Recursive
268 subtypes.  This will allow:
269
270     subtype Tree() => as HashRef[Str|Tree];
271
272 Which validates things like:
273
274     {key=>'value'};
275     {key=>{subkey1=>'value', subkey2=>'value'}}
276     
277 And so on.  This feature is new and there may be lurking bugs so don't be afraid
278 to hunt me down with patches and test cases if you have trouble.
279
280 =head1 NOTES REGARDING TYPE UNIONS
281
282 L<MooseX::Types> uses L<MooseX::Types::TypeDecorator> to do some overloading
283 which generally allows you to easily create union types:
284
285   subtype StrOrArrayRef,
286     as Str|ArrayRef;    
287
288 As with parameterized constrains, this overloading extends to modules using the
289 types you define in a type library.
290
291     use Moose;
292     use MooseX::Types::Moose qw(HashRef Int);
293     
294     has 'attr' => (isa=>HashRef|Int);
295
296 And everything should just work as you'd think.
297
298 =head1 METHODS
299
300 =head2 import
301
302 Installs the L<MooseX::Types::Base> class into the caller and 
303 exports types according to the specification described in 
304 L</"LIBRARY DEFINITION">. This will continue to 
305 L<Moose::Util::TypeConstraints>' C<import> method to export helper
306 functions you will need to declare your types.
307
308 =cut
309
310 sub import {
311     my ($class, %args) = @_;
312     my  $callee = caller;
313
314     # everyone should want this
315     strict->import;
316     warnings->import;
317
318     # inject base class into new library
319     {   no strict 'refs';
320         unshift @{ $callee . '::ISA' }, 'MooseX::Types::Base';
321     }
322
323     # generate predeclared type helpers
324     if (my @orig_declare = @{ $args{ -declare } || [] }) {
325         my ($tags, $declare) = filter_tags @orig_declare;
326         my @to_export;
327
328         for my $type (@$declare) {
329
330             croak "Cannot create a type containing '::' ($type) at the moment"
331                 if $type =~ /::/;
332
333             # add type to library and remember to export
334             $callee->add_type($type);
335             push @to_export, $type;
336         }
337
338         $callee->import({ -full => 1, -into => $callee }, @to_export);
339     }
340
341     # run type constraints import
342     return Moose::Util::TypeConstraints->import({ into => $callee });
343 }
344
345 =head2 type_export_generator
346
347 Generate a type export, e.g. C<Int()>. This will return either a
348 L<Moose::Meta::TypeConstraint> object, or alternatively a
349 L<MooseX::Types::UndefinedType> object if the type was not
350 yet defined.
351
352 =cut
353
354 sub type_export_generator {
355     my ($class, $type, $name) = @_;
356     
357     ## Return an anonymous subroutine that will generate the proxied type
358     ## constraint for you.
359     
360     return sub {
361         my $type_constraint;
362         if(defined(my $params = shift @_)) {
363             ## We currently only allow a TC to accept a single, ArrayRef
364             ## parameter, as in HashRef[Int], where [Int] is what's inside the
365             ## ArrayRef passed.
366             if(ref $params eq 'ARRAY') {
367                 $type_constraint = $class->create_arged_type_constraint($name, @$params);
368             } else {
369                 croak 'Arguments must be an ArrayRef, not '. ref $params;
370             }
371         } else {
372             $type_constraint = $class->create_base_type_constraint($name);
373         }
374
375         $type_constraint = defined($type_constraint) ? $type_constraint
376          : MooseX::Types::UndefinedType->new($name);
377          
378         my $type_decorator = $class->create_type_decorator($type_constraint);
379         
380         ## If there are additional args, that means it's probably stuff that
381         ## needs to be returned to the subtype.  Not an ideal solution here but
382         ## doesn't seem to cause trouble.
383         
384         if(@_) {
385             return ($type_decorator, @_);
386         } else {
387             return $type_decorator;
388         }
389     };
390 }
391
392 =head2 create_arged_type_constraint ($name, @args)
393
394 Given a String $name with @args find the matching typeconstraint and parameterize
395 it with @args.
396
397 =cut
398
399 sub create_arged_type_constraint {
400     my ($class, $name, @args) = @_;  
401     my $type_constraint = Moose::Util::TypeConstraints::find_or_create_type_constraint("$name");
402         return $type_constraint->parameterize(@args);
403 }
404
405 =head2 create_base_type_constraint ($name)
406
407 Given a String $name, find the matching typeconstraint.
408
409 =cut
410
411 sub create_base_type_constraint {
412     my ($class, $name) = @_;
413     return find_type_constraint($name);
414 }
415
416 =head2 create_type_decorator ($type_constraint)
417
418 Given a $type_constraint, return a lightweight L<MooseX::Types::TypeDecorator>
419 instance.
420
421 =cut
422
423 sub create_type_decorator {
424     my ($class, $type_constraint) = @_;
425     return MooseX::Types::TypeDecorator->new($type_constraint);
426 }
427
428 =head2 coercion_export_generator
429
430 This generates a coercion handler function, e.g. C<to_Int($value)>. 
431
432 =cut
433
434 sub coercion_export_generator {
435     my ($class, $type, $full, $undef_msg) = @_;
436     return sub {
437         my ($value) = @_;
438
439         # we need a type object
440         my $tobj = find_type_constraint($full) or croak $undef_msg;
441         my $return = $tobj->coerce($value);
442
443         # non-successful coercion returns false
444         return unless $tobj->check($return);
445
446         return $return;
447     }
448 }
449
450 =head2 check_export_generator
451
452 Generates a constraint check closure, e.g. C<is_Int($value)>.
453
454 =cut
455
456 sub check_export_generator {
457     my ($class, $type, $full, $undef_msg) = @_;
458     return sub {
459         my ($value) = @_;
460
461         # we need a type object
462         my $tobj = find_type_constraint($full) or croak $undef_msg;
463
464         return $tobj->check($value);
465     }
466 }
467
468 =head1 CAVEATS
469
470 The following are lists of gotcha's and their workarounds for developers coming
471 from the standard string based type constraint names
472
473 =head2 Uniqueness
474
475 A library makes the types quasi-unique by prefixing their names with (by
476 default) the library package name. If you're only using the type handler
477 functions provided by MooseX::Types, you shouldn't ever have to use
478 a type's actual full name.
479
480 =head2 Argument separation ('=>' versus ',')
481
482 The Perlop manpage has this to say about the '=>' operator: "The => operator is
483 a synonym for the comma, but forces any word (consisting entirely of word
484 characters) to its left to be interpreted as a string (as of 5.001). This
485 includes words that might otherwise be considered a constant or function call."
486
487 Due to this stringification, the following will NOT work as you might think:
488
489   subtype StrOrArrayRef => as Str|ArrayRef;
490   
491 The 'StrOrArrayRef' will have it's stringification activated this causes the
492 subtype to not be created.  Since the bareword type constraints are not strings
493 you really should not try to treat them that way.  You will have to use the ','
494 operator instead.  The author's of this package realize that all the L<Moose>
495 documention and examples nearly uniformly use the '=>' version of the comma
496 operator and this could be an issue if you are converting code.
497
498 Patches welcome for discussion.
499
500 =head2 Compatibility with Sub::Exporter
501
502 If you want to use L<Sub::Exporter> with a Type Library, you need to make sure
503 you export all the type constraints declared AS WELL AS any additional export
504 targets. For example if you do:
505
506     package TypeAndSubExporter; {
507         
508         use MooseX::Types::Moose qw(Str);
509         use MooseX::Types -declare => [qw(MyStr)];
510         use Sub::Exporter -setup => { exports => [ qw(something) ] };
511         
512         subtype MyStr,
513          as Str;
514          
515         sub something {
516             return 1;
517         }    
518         
519     } 1;
520     
521     package Foo; {
522         use TypeAndSubExporter qw(MyStr);
523     } 1;
524
525 You'll get a '"MyStr" is not exported by the TypeAndSubExporter module' error.
526 Upi can workaround by:
527
528         - use Sub::Exporter -setup => { exports => [ qw(something) ] };
529         + use Sub::Exporter -setup => { exports => [ qw(something MyStr) ] };
530
531 This is a workaround and I am exploring how to make these modules work better
532 together.  I realize this workaround will lead a lot of duplication in your
533 export declarations and will be onerous for large type libraries.  Patches and
534 detailed test cases welcome. See the tests directory for a start on this.
535     
536 =head1 SEE ALSO
537
538 L<Moose>, 
539 L<Moose::Util::TypeConstraints>, 
540 L<MooseX::Types::Moose>,
541 L<Sub::Exporter>
542
543 =head1 AUTHOR AND COPYRIGHT
544
545 Robert 'phaylon' Sedlacek C<E<lt>rs@474.atE<gt>>, with many thanks to
546 the C<#moose> cabal on C<irc.perl.org>.
547
548 Additional features by John Napiorkowski (jnapiorkowski) <jjnapiork@cpan.org>.
549
550 =head1 LICENSE
551
552 This program is free software; you can redistribute it and/or modify
553 it under the same terms as perl itself.
554
555 =cut
556
557 1;