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