4 # ABSTRACT: Organise your Moose types in libraries
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 );
14 use Scalar::Util 'reftype';
16 use namespace::clean -except => [qw( meta )];
19 my $UndefMsg = q{Action for type '%s' not yet defined in library '%s'};
23 =head2 Library Definition
27 # predeclare our own types
30 PositiveInt NegativeInt
31 ArrayRefOfPositiveInt ArrayRefOfAtLeastThreeNegativeInts
32 LotsOfInnerConstraints StrOrArrayRef
36 # import builtin types
37 use MooseX::Types::Moose qw/Int HashRef/;
43 message { "Int is not larger than 0" };
48 message { "Int is not smaller than 0" };
55 # with parameterized constraints.
57 subtype ArrayRefOfPositiveInt,
58 as ArrayRef[PositiveInt];
60 subtype ArrayRefOfAtLeastThreeNegativeInts,
61 as ArrayRef[NegativeInt],
62 where { scalar(@$_) > 2 };
64 subtype LotsOfInnerConstraints,
65 as ArrayRef[ArrayRef[HashRef[Int]]];
67 # with TypeConstraint Unions
69 subtype StrOrArrayRef,
74 class_type 'DateTime';
78 class_type MyDateTime, { class => 'DateTime' };
82 via { DateTime->new(%$_) };
90 use MyLibrary qw( PositiveInt NegativeInt );
92 # use the exported constants as type names
104 print "positive\n" if is_PositiveInt($value);
105 print "negative\n" if is_NegativeInt($value);
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";
116 The types provided with L<Moose> are by design global. This package helps
117 you to organise and selectively import your own and the built-in types in
118 libraries. As a nice side effect, it catches typos at compile-time too.
120 However, the main reason for this module is to provide an easy way to not
121 have conflicts with your type names, since the internal fully qualified
122 names of the types will be prefixed with the library's name.
124 This module will also provide you with some helper functions to make it
125 easier to use Moose types in your code.
127 String type names will produce a warning, unless it's for a C<class_type> or
128 C<role_type> declared within the library, or a fully qualified name like
129 C<'MyTypeLibrary::Foo'>.
131 =head1 TYPE HANDLER FUNCTIONS
135 A constant with the name of your type. It contains the type's fully
136 qualified name. Takes no value, as all constants.
140 This handler takes a value and tests if it is a valid value for this
141 C<$type>. It will return true or false.
145 A handler that will take a value and coerce it into the C<$type>. It will
146 return a false value if the type could not be coerced.
148 B<Important Note>: This handler will only be exported for types that can
149 do type coercion. This has the advantage that a coercion to a type that
150 has not defined any coercions will lead to a compile-time error.
152 =head1 LIBRARY DEFINITION
154 A MooseX::Types is just a normal Perl module. Unlike Moose
155 itself, it does not install C<use strict> and C<use warnings> in your
156 class by default, so this is up to you.
158 The only thing a library is required to do is
160 use MooseX::Types -declare => \@types;
162 with C<@types> being a list of types you wish to define in this library.
163 This line will install a proper base class in your package as well as the
164 full set of L<handlers|/"TYPE HANDLER FUNCTIONS"> for your declared
165 types. It will then hand control over to L<Moose::Util::TypeConstraints>'
166 C<import> method to export the functions you will need to declare your
169 If you want to use Moose' built-in types (e.g. for subtyping) you will
172 use MooseX::Types::Moose @types;
174 to import the helpers from the shipped L<MooseX::Types::Moose>
175 library which can export all types that come with Moose.
177 You will have to define coercions for your types or your library won't
178 export a L</to_$type> coercion helper for it.
180 Note that you currently cannot define types containing C<::>, since
181 exporting would be a problem.
183 You also don't need to use C<warnings> and C<strict>, since the
184 definition of a library automatically exports those.
188 You can import the L<"type helpers"|/"TYPE HANDLER FUNCTIONS"> of a
189 library by C<use>ing it with a list of types to import as arguments. If
190 you want all of them, use the C<:all> tag. For example:
192 use MyLibrary ':all';
193 use MyOtherLibrary qw( TypeA TypeB );
195 MooseX::Types comes with a library of Moose' built-in types called
196 L<MooseX::Types::Moose>.
198 The exporting mechanism is, since version 0.5, implemented via a wrapper
199 around L<Sub::Exporter>. This means you can do something like this:
201 use MyLibrary TypeA => { -as => 'MyTypeA' },
202 TypeB => { -as => 'MyTypeB' };
204 =head1 WRAPPING A LIBRARY
206 You can define your own wrapper subclasses to manipulate the behaviour
207 of a set of library exports. Here is an example:
212 use base 'MooseX::Types::Wrapper';
214 sub coercion_export_generator {
216 my $code = $class->next::method(@_);
218 my $value = $code->(@_);
219 warn "Coercion returned undef!"
220 unless defined $value;
227 This class wraps the coercion generator (e.g., C<to_Int()>) and warns
228 if a coercion returned an undefined value. You can wrap any library
233 use MyWrapper MyLibrary => [qw( Foo Bar )],
234 Moose => [qw( Str Int )];
239 The C<Moose> library name is a special shortcut for
240 L<MooseX::Types::Moose>.
242 =head2 Generator methods you can overload
246 =item type_export_generator( $short, $full )
248 Creates a closure returning the type's L<Moose::Meta::TypeConstraint>
251 =item check_export_generator( $short, $full, $undef_message )
253 This creates the closure used to test if a value is valid for this type.
255 =item coercion_export_generator( $short, $full, $undef_message )
257 This is the closure that's doing coercions.
261 =head2 Provided Parameters
267 The short, exported name of the type.
271 The fully qualified name of this type as L<Moose> knows it.
275 A message that will be thrown when type functionality is used but the
276 type does not yet exist.
280 =head1 RECURSIVE SUBTYPES
282 As of version 0.08, L<Moose::Types> has experimental support for Recursive
283 subtypes. This will allow:
285 subtype Tree() => as HashRef[Str|Tree];
287 Which validates things like:
290 {key=>{subkey1=>'value', subkey2=>'value'}}
292 And so on. This feature is new and there may be lurking bugs so don't be afraid
293 to hunt me down with patches and test cases if you have trouble.
295 =head1 NOTES REGARDING TYPE UNIONS
297 L<MooseX::Types> uses L<MooseX::Types::TypeDecorator> to do some overloading
298 which generally allows you to easily create union types:
300 subtype StrOrArrayRef,
303 As with parameterized constrains, this overloading extends to modules using the
304 types you define in a type library.
307 use MooseX::Types::Moose qw(HashRef Int);
309 has 'attr' => (isa=>HashRef|Int);
311 And everything should just work as you'd think.
317 Installs the L<MooseX::Types::Base> class into the caller and
318 exports types according to the specification described in
319 L</"LIBRARY DEFINITION">. This will continue to
320 L<Moose::Util::TypeConstraints>' C<import> method to export helper
321 functions you will need to declare your types.
326 my ($class, %args) = @_;
329 # everyone should want this
333 # inject base class into new library
335 unshift @{ $callee . '::ISA' }, 'MooseX::Types::Base';
338 # generate predeclared type helpers
339 if (my @orig_declare = @{ $args{ -declare } || [] }) {
340 my ($tags, $declare) = filter_tags @orig_declare;
343 for my $type (@$declare) {
345 croak "Cannot create a type containing '::' ($type) at the moment"
348 # add type to library and remember to export
349 $callee->add_type($type);
350 push @to_export, $type;
353 $callee->import({ -full => 1, -into => $callee }, @to_export);
356 # run type constraints import
357 Moose::Util::TypeConstraints->import({ into => $callee });
359 # override some with versions that check for syntax errors
360 MooseX::Types::CheckedUtilExports->import({ into => $callee });
365 =head2 type_export_generator
367 Generate a type export, e.g. C<Int()>. This will return either a
368 L<Moose::Meta::TypeConstraint> object, or alternatively a
369 L<MooseX::Types::UndefinedType> object if the type was not
374 sub type_export_generator {
375 my ($class, $type, $name) = @_;
377 ## Return an anonymous subroutine that will generate the proxied type
378 ## constraint for you.
380 return subname "__TYPE__::$name" => sub {
381 my $type_constraint = $class->create_base_type_constraint($name);
383 if(defined(my $params = shift @_)) {
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
387 if(reftype $params eq 'ARRAY') {
388 $type_constraint = $class->create_arged_type_constraint($name, @$params);
389 } elsif(!defined $type_constraint) {
390 croak "Syntax error in type definition (did you forget a comma"
393 croak "Argument must be an ArrayRef to create a parameterized "
394 . "type, Eg.: ${type}[Int]. Got: ".ref($params)."."
398 $type_constraint = defined($type_constraint) ? $type_constraint
399 : MooseX::Types::UndefinedType->new($name);
401 my $type_decorator = $class->create_type_decorator($type_constraint);
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.
408 return ($type_decorator, @_);
410 return $type_decorator;
415 =head2 create_arged_type_constraint ($name, @args)
417 Given a String $name with @args find the matching typeconstraint and parameterize
422 sub create_arged_type_constraint {
423 my ($class, $name, @args) = @_;
424 my $type_constraint = Moose::Util::TypeConstraints::find_or_create_type_constraint("$name");
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.
429 # This breaks MXMS, unfortunately, which relies on things like Tuple[...]
430 # creating new type objects each time.
432 # Moose::Util::TypeConstraints::find_type_constraint($parameterized->name)) {
435 # Moose::Util::TypeConstraints::register_type_constraint($parameterized);
436 return $parameterized;
439 =head2 create_base_type_constraint ($name)
441 Given a String $name, find the matching typeconstraint.
445 sub create_base_type_constraint {
446 my ($class, $name) = @_;
447 return find_type_constraint($name);
450 =head2 create_type_decorator ($type_constraint)
452 Given a $type_constraint, return a lightweight L<MooseX::Types::TypeDecorator>
457 sub create_type_decorator {
458 my ($class, $type_constraint) = @_;
459 return MooseX::Types::TypeDecorator->new($type_constraint);
462 =head2 coercion_export_generator
464 This generates a coercion handler function, e.g. C<to_Int($value)>.
468 sub coercion_export_generator {
469 my ($class, $type, $full, $undef_msg) = @_;
473 # we need a type object
474 my $tobj = find_type_constraint($full) or croak $undef_msg;
475 my $return = $tobj->coerce($value);
477 # non-successful coercion returns false
478 return unless $tobj->check($return);
484 =head2 check_export_generator
486 Generates a constraint check closure, e.g. C<is_Int($value)>.
490 sub check_export_generator {
491 my ($class, $type, $full, $undef_msg) = @_;
495 # we need a type object
496 my $tobj = find_type_constraint($full) or croak $undef_msg;
498 return $tobj->check($value);
504 The following are lists of gotcha's and their workarounds for developers coming
505 from the standard string based type constraint names
509 A library makes the types quasi-unique by prefixing their names with (by
510 default) the library package name. If you're only using the type handler
511 functions provided by MooseX::Types, you shouldn't ever have to use
512 a type's actual full name.
514 =head2 Argument separation ('=>' versus ',')
516 The Perlop manpage has this to say about the '=>' operator: "The => operator is
517 a synonym for the comma, but forces any word (consisting entirely of word
518 characters) to its left to be interpreted as a string (as of 5.001). This
519 includes words that might otherwise be considered a constant or function call."
521 Due to this stringification, the following will NOT work as you might think:
523 subtype StrOrArrayRef => as Str|ArrayRef;
525 The 'StrOrArrayRef' will have its stringification activated this causes the
526 subtype to not be created. Since the bareword type constraints are not strings
527 you really should not try to treat them that way. You will have to use the ','
528 operator instead. The author's of this package realize that all the L<Moose>
529 documention and examples nearly uniformly use the '=>' version of the comma
530 operator and this could be an issue if you are converting code.
532 Patches welcome for discussion.
534 =head2 Compatibility with Sub::Exporter
536 If you want to use L<Sub::Exporter> with a Type Library, you need to make sure
537 you export all the type constraints declared AS WELL AS any additional export
538 targets. For example if you do:
540 package TypeAndSubExporter; {
542 use MooseX::Types::Moose qw(Str);
543 use MooseX::Types -declare => [qw(MyStr)];
544 use Sub::Exporter -setup => { exports => [ qw(something) ] };
556 use TypeAndSubExporter qw(MyStr);
559 You'll get a '"MyStr" is not exported by the TypeAndSubExporter module' error.
560 Upi can workaround by:
562 - use Sub::Exporter -setup => { exports => [ qw(something) ] };
563 + use Sub::Exporter -setup => { exports => [ qw(something MyStr) ] };
565 This is a workaround and I am exploring how to make these modules work better
566 together. I realize this workaround will lead a lot of duplication in your
567 export declarations and will be onerous for large type libraries. Patches and
568 detailed test cases welcome. See the tests directory for a start on this.
570 =head1 COMBINING TYPE LIBRARIES
572 You may want to combine a set of types for your application with other type
573 libraries, like L<MooseX::Types::Moose> or L<MooseX::Types::Common::String>.
575 The L<MooseX::Types::Combine> module provides a simple API for combining a set
576 of type libraries together.
581 L<Moose::Util::TypeConstraints>,
582 L<MooseX::Types::Moose>,
585 =head1 ACKNOWLEDGEMENTS
587 Many thanks to the C<#moose> cabal on C<irc.perl.org>.
591 jnapiorkowski: John Napiorkowski <jjnapiork@cpan.org>
593 caelum: Rafael Kitover <rkitover@cpan.org>
595 rafl: Florian Ragwitz <rafl@debian.org>
597 hdp: Hans Dieter Pearcey <hdp@cpan.org>
599 autarch: Dave Rolsky <autarch@urth.org>