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