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