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