2 package Moose::Util::TypeConstraints;
5 use List::MoreUtils qw( all any );
6 use Scalar::Util qw( blessed reftype );
10 $VERSION = eval $VERSION;
11 our $AUTHORITY = 'cpan:STEVAN';
13 ## --------------------------------------------------------
14 # Prototyped subs must be predeclared because we have a
15 # circular dependency with Moose::Meta::Attribute et. al.
16 # so in case of us being use'd first the predeclaration
17 # ensures the prototypes are in scope when consumers are
26 ## --------------------------------------------------------
28 use Moose::Meta::TypeConstraint;
29 use Moose::Meta::TypeConstraint::Union;
30 use Moose::Meta::TypeConstraint::Parameterized;
31 use Moose::Meta::TypeConstraint::Parameterizable;
32 use Moose::Meta::TypeConstraint::Class;
33 use Moose::Meta::TypeConstraint::Role;
34 use Moose::Meta::TypeConstraint::Enum;
35 use Moose::Meta::TypeCoercion;
36 use Moose::Meta::TypeCoercion::Union;
37 use Moose::Meta::TypeConstraint::Registry;
38 use Moose::Util::TypeConstraints::OptimizedConstraints;
40 Moose::Exporter->setup_import_methods(
43 type subtype class_type role_type maybe_type duck_type
44 as where message optimize_as
48 register_type_constraint )
53 ## --------------------------------------------------------
54 ## type registry and some useful functions for it
55 ## --------------------------------------------------------
57 my $REGISTRY = Moose::Meta::TypeConstraint::Registry->new;
59 sub get_type_constraint_registry {$REGISTRY}
60 sub list_all_type_constraints { keys %{ $REGISTRY->type_constraints } }
62 sub export_type_constraints_as_functions {
65 foreach my $constraint ( keys %{ $REGISTRY->type_constraints } ) {
66 my $tc = $REGISTRY->get_type_constraint($constraint)
67 ->_compiled_type_constraint;
68 *{"${pkg}::${constraint}"}
69 = sub { $tc->( $_[0] ) ? 1 : undef }; # the undef is for compat
73 sub create_type_constraint_union {
74 my @type_constraint_names;
76 if ( scalar @_ == 1 && _detect_type_constraint_union( $_[0] ) ) {
77 @type_constraint_names = _parse_type_constraint_union( $_[0] );
80 @type_constraint_names = @_;
83 ( scalar @type_constraint_names >= 2 )
84 || __PACKAGE__->_throw_error(
85 "You must pass in at least 2 type names to make a union");
87 my @type_constraints = map {
88 find_or_parse_type_constraint($_)
89 || __PACKAGE__->_throw_error(
90 "Could not locate type constraint ($_) for the union");
91 } @type_constraint_names;
93 return Moose::Meta::TypeConstraint::Union->new(
94 type_constraints => \@type_constraints );
97 sub create_parameterized_type_constraint {
98 my $type_constraint_name = shift;
99 my ( $base_type, $type_parameter )
100 = _parse_parameterized_type_constraint($type_constraint_name);
102 ( defined $base_type && defined $type_parameter )
103 || __PACKAGE__->_throw_error(
104 "Could not parse type name ($type_constraint_name) correctly");
106 if ( $REGISTRY->has_type_constraint($base_type) ) {
107 my $base_type_tc = $REGISTRY->get_type_constraint($base_type);
108 return _create_parameterized_type_constraint(
114 __PACKAGE__->_throw_error(
115 "Could not locate the base type ($base_type)");
119 sub _create_parameterized_type_constraint {
120 my ( $base_type_tc, $type_parameter ) = @_;
121 if ( $base_type_tc->can('parameterize') ) {
122 return $base_type_tc->parameterize($type_parameter);
125 return Moose::Meta::TypeConstraint::Parameterized->new(
126 name => $base_type_tc->name . '[' . $type_parameter . ']',
127 parent => $base_type_tc,
129 find_or_create_isa_type_constraint($type_parameter),
134 #should we also support optimized checks?
135 sub create_class_type_constraint {
136 my ( $class, $options ) = @_;
138 # too early for this check
139 #find_type_constraint("ClassName")->check($class)
140 # || __PACKAGE__->_throw_error("Can't create a class type constraint because '$class' is not a class name");
148 $options{name} ||= "__ANON__";
150 Moose::Meta::TypeConstraint::Class->new(%options);
153 sub create_role_type_constraint {
154 my ( $role, $options ) = @_;
156 # too early for this check
157 #find_type_constraint("ClassName")->check($class)
158 # || __PACKAGE__->_throw_error("Can't create a class type constraint because '$class' is not a class name");
166 $options{name} ||= "__ANON__";
168 Moose::Meta::TypeConstraint::Role->new(%options);
171 sub find_or_create_type_constraint {
172 my ( $type_constraint_name, $options_for_anon_type ) = @_;
175 = find_or_parse_type_constraint($type_constraint_name) ) {
178 elsif ( defined $options_for_anon_type ) {
181 # if there is no $options_for_anon_type
182 # specified, then we assume they don't
183 # want to create one, and return nothing.
185 # otherwise assume that we should create
186 # an ANON type with the $options_for_anon_type
187 # options which can be passed in. It should
188 # be noted that these don't get registered
189 # so we need to return it.
191 return Moose::Meta::TypeConstraint->new(
193 %{$options_for_anon_type}
200 sub find_or_create_isa_type_constraint {
201 my $type_constraint_name = shift;
202 find_or_parse_type_constraint($type_constraint_name)
203 || create_class_type_constraint($type_constraint_name);
206 sub find_or_create_does_type_constraint {
207 my $type_constraint_name = shift;
208 find_or_parse_type_constraint($type_constraint_name)
209 || create_role_type_constraint($type_constraint_name);
212 sub find_or_parse_type_constraint {
213 my $type_constraint_name = normalize_type_constraint_name(shift);
216 if ( $constraint = find_type_constraint($type_constraint_name) ) {
219 elsif ( _detect_type_constraint_union($type_constraint_name) ) {
220 $constraint = create_type_constraint_union($type_constraint_name);
222 elsif ( _detect_parameterized_type_constraint($type_constraint_name) ) {
224 = create_parameterized_type_constraint($type_constraint_name);
230 $REGISTRY->add_type_constraint($constraint);
234 sub normalize_type_constraint_name {
235 my $type_constraint_name = shift;
236 $type_constraint_name =~ s/\s//g;
237 return $type_constraint_name;
243 local $Carp::CarpLevel = $Carp::CarpLevel + 1;
244 Carp::confess($error);
247 ## --------------------------------------------------------
248 ## exported functions ...
249 ## --------------------------------------------------------
251 sub find_type_constraint {
254 if ( blessed $type and $type->isa("Moose::Meta::TypeConstraint") ) {
258 return unless $REGISTRY->has_type_constraint($type);
259 return $REGISTRY->get_type_constraint($type);
263 sub register_type_constraint {
264 my $constraint = shift;
265 __PACKAGE__->_throw_error("can't register an unnamed type constraint")
266 unless defined $constraint->name;
267 $REGISTRY->add_type_constraint($constraint);
275 # back-compat version, called without sugar
276 if ( !any { ( reftype($_) || '' ) eq 'HASH' } @_ ) {
277 return _create_type_constraint( $_[0], undef, $_[1] );
282 my %p = map { %{$_} } @_;
284 return _create_type_constraint(
285 $name, undef, $p{where}, $p{message},
292 # crazy back-compat code for being called without sugar ...
294 # subtype 'Parent', sub { where };
295 if ( scalar @_ == 2 && ( reftype( $_[1] ) || '' ) eq 'CODE' ) {
296 return _create_type_constraint( undef, @_ );
299 # subtype 'Parent', sub { where }, sub { message };
300 # subtype 'Parent', sub { where }, sub { message }, sub { optimized };
301 if ( scalar @_ >= 3 && all { ( reftype($_) || '' ) eq 'CODE' }
303 return _create_type_constraint( undef, @_ );
306 # subtype 'Name', 'Parent', ...
307 if ( scalar @_ >= 2 && all { !ref } @_[ 0, 1 ] ) {
308 return _create_type_constraint(@_);
311 if ( @_ == 1 && !ref $_[0] ) {
312 __PACKAGE__->_throw_error(
313 'A subtype cannot consist solely of a name, it must have a parent'
317 # The blessed check is mostly to accommodate MooseX::Types, which
318 # uses an object which overloads stringification as a type name.
319 my $name = ref $_[0] && !blessed $_[0] ? undef : shift;
321 my %p = map { %{$_} } @_;
323 # subtype Str => where { ... };
324 if ( !exists $p{as} ) {
329 return _create_type_constraint(
330 $name, $p{as}, $p{where}, $p{message},
336 register_type_constraint(
337 create_class_type_constraint(
339 ( defined( $_[1] ) ? $_[1] : () ),
344 sub role_type ($;$) {
345 register_type_constraint(
346 create_role_type_constraint(
348 ( defined( $_[1] ) ? $_[1] : () ),
354 my ($type_parameter) = @_;
356 register_type_constraint(
357 $REGISTRY->get_type_constraint('Maybe')->parameterize($type_parameter)
362 my ( $type_name, @methods ) = @_;
363 if ( ref $type_name eq 'ARRAY' && !@methods ) {
364 @methods = @$type_name;
368 register_type_constraint(
369 _create_type_constraint(
374 return 0 unless all { $obj->can($_) } @methods;
379 my $class = blessed($obj);
380 my @missing_methods = grep { !$obj->can($_) } @methods;
382 "$class is missing methods '@missing_methods'";
389 my ( $type_name, @coercion_map ) = @_;
390 _install_type_coercions( $type_name, \@coercion_map );
393 # The trick of returning @_ lets us avoid having to specify a
394 # prototype. Perl will parse this:
402 # subtype( 'Foo', as( 'Str', where { ... } ) );
404 # If as() returns all it's extra arguments, this just works, and
405 # preserves backwards compatibility.
406 sub as { { as => shift }, @_ }
407 sub where (&) { { where => $_[0] } }
408 sub message (&) { { message => $_[0] } }
409 sub optimize_as (&) { { optimize_as => $_[0] } }
412 sub via (&) { $_[0] }
415 my ( $type_name, @values ) = @_;
418 # if only an array-ref is passed then
419 # you get an anon-enum
421 if ( ref $type_name eq 'ARRAY' && !@values ) {
422 @values = @$type_name;
425 ( scalar @values >= 2 )
426 || __PACKAGE__->_throw_error(
427 "You must have at least two values to enumerate through");
428 my %valid = map { $_ => 1 } @values;
430 register_type_constraint(
431 create_enum_type_constraint(
438 sub create_enum_type_constraint {
439 my ( $type_name, $values ) = @_;
441 Moose::Meta::TypeConstraint::Enum->new(
442 name => $type_name || '__ANON__',
447 ## --------------------------------------------------------
448 ## desugaring functions ...
449 ## --------------------------------------------------------
451 sub _create_type_constraint ($$$;$$) {
456 my $optimized = shift;
458 my $pkg_defined_in = scalar( caller(1) );
460 if ( defined $name ) {
461 my $type = $REGISTRY->get_type_constraint($name);
463 ( $type->_package_defined_in eq $pkg_defined_in )
465 "The type constraint '$name' has already been created in "
466 . $type->_package_defined_in
467 . " and cannot be created again in "
471 $name =~ /^[\w:\.]+$/
472 or die qq{$name contains invalid characters for a type name.}
473 . qq{ Names can contain alphanumeric character, ":", and "."\n};
478 package_defined_in => $pkg_defined_in,
480 ( $check ? ( constraint => $check ) : () ),
481 ( $message ? ( message => $message ) : () ),
482 ( $optimized ? ( optimized => $optimized ) : () ),
491 : find_or_create_isa_type_constraint($parent)
493 $constraint = $parent->create_child_type(%opts);
496 $constraint = Moose::Meta::TypeConstraint->new(%opts);
499 $REGISTRY->add_type_constraint($constraint)
505 sub _install_type_coercions ($$) {
506 my ( $type_name, $coercion_map ) = @_;
507 my $type = find_type_constraint($type_name);
509 || __PACKAGE__->_throw_error(
510 "Cannot find type '$type_name', perhaps you forgot to load it");
511 if ( $type->has_coercion ) {
512 $type->coercion->add_type_coercions(@$coercion_map);
515 my $type_coercion = Moose::Meta::TypeCoercion->new(
516 type_coercion_map => $coercion_map,
517 type_constraint => $type
519 $type->coercion($type_coercion);
523 ## --------------------------------------------------------
524 ## type notation parsing ...
525 ## --------------------------------------------------------
529 # All I have to say is mugwump++ cause I know
530 # do not even have enough regexp-fu to be able
531 # to have written this (I can only barely
532 # understand it as it is)
537 my $valid_chars = qr{[\w:\.]};
538 my $type_atom = qr{ $valid_chars+ };
542 my $type = qr{ $valid_chars+ (?: \[ \s* (??{$any}) \s* \] )? }x;
543 my $type_capture_parts
544 = qr{ ($valid_chars+) (?: \[ \s* ((??{$any})) \s* \] )? }x;
545 my $type_with_parameter
546 = qr{ $valid_chars+ \[ \s* (??{$any}) \s* \] }x;
548 my $op_union = qr{ \s* \| \s* }x;
549 my $union = qr{ $type (?: $op_union $type )+ }x;
551 $any = qr{ $type | $union }x;
553 sub _parse_parameterized_type_constraint {
554 { no warnings 'void'; $any; } # force capture of interpolated lexical
555 $_[0] =~ m{ $type_capture_parts }x;
559 sub _detect_parameterized_type_constraint {
560 { no warnings 'void'; $any; } # force capture of interpolated lexical
561 $_[0] =~ m{ ^ $type_with_parameter $ }x;
564 sub _parse_type_constraint_union {
565 { no warnings 'void'; $any; } # force capture of interpolated lexical
568 while ( $given =~ m{ \G (?: $op_union )? ($type) }gcx ) {
571 ( pos($given) eq length($given) )
572 || __PACKAGE__->_throw_error( "'$given' didn't parse (parse-pos="
580 sub _detect_type_constraint_union {
581 { no warnings 'void'; $any; } # force capture of interpolated lexical
582 $_[0] =~ m{^ $type $op_union $type ( $op_union .* )? $}x;
586 ## --------------------------------------------------------
587 # define some basic built-in types
588 ## --------------------------------------------------------
590 # By making these classes immutable before creating all the types we
591 # below, we avoid repeatedly calling the slow MOP-based accessors.
593 inline_constructor => 1,
594 constructor_name => "_new",
596 # these are Class::MOP accessors, so they need inlining
597 inline_accessors => 1
598 ) for grep { $_->is_mutable }
599 map { Class::MOP::class_of($_) }
601 Moose::Meta::TypeConstraint
602 Moose::Meta::TypeConstraint::Union
603 Moose::Meta::TypeConstraint::Parameterized
604 Moose::Meta::TypeConstraint::Parameterizable
605 Moose::Meta::TypeConstraint::Class
606 Moose::Meta::TypeConstraint::Role
607 Moose::Meta::TypeConstraint::Enum
608 Moose::Meta::TypeConstraint::Registry
611 type 'Any' => where {1}; # meta-type including all
612 subtype 'Item' => as 'Any'; # base-type
614 subtype 'Undef' => as 'Item' => where { !defined($_) };
615 subtype 'Defined' => as 'Item' => where { defined($_) };
617 subtype 'Bool' => as 'Item' =>
618 where { !defined($_) || $_ eq "" || "$_" eq '1' || "$_" eq '0' };
620 subtype 'Value' => as 'Defined' => where { !ref($_) } =>
621 optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Value;
623 subtype 'Ref' => as 'Defined' => where { ref($_) } =>
624 optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Ref;
626 subtype 'Str' => as 'Value' => where {1} =>
627 optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Str;
629 subtype 'Num' => as 'Str' =>
630 where { Scalar::Util::looks_like_number($_) } =>
631 optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Num;
633 subtype 'Int' => as 'Num' => where { "$_" =~ /^-?[0-9]+$/ } =>
634 optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Int;
636 subtype 'ScalarRef' => as 'Ref' => where { ref($_) eq 'SCALAR' } =>
638 \&Moose::Util::TypeConstraints::OptimizedConstraints::ScalarRef;
639 subtype 'CodeRef' => as 'Ref' => where { ref($_) eq 'CODE' } =>
640 optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::CodeRef;
641 subtype 'RegexpRef' => as 'Ref' => where { ref($_) eq 'Regexp' } =>
643 \&Moose::Util::TypeConstraints::OptimizedConstraints::RegexpRef;
644 subtype 'GlobRef' => as 'Ref' => where { ref($_) eq 'GLOB' } =>
645 optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::GlobRef;
648 # scalar filehandles are GLOB refs,
649 # but a GLOB ref is not always a filehandle
650 subtype 'FileHandle' => as 'GlobRef' => where {
651 Scalar::Util::openhandle($_) || ( blessed($_) && $_->isa("IO::Handle") );
653 \&Moose::Util::TypeConstraints::OptimizedConstraints::FileHandle;
656 # blessed(qr/.../) returns true,.. how odd
657 subtype 'Object' => as 'Ref' =>
658 where { blessed($_) && blessed($_) ne 'Regexp' } =>
659 optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Object;
661 subtype 'Role' => as 'Object' => where { $_->can('does') } =>
662 optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Role;
664 my $_class_name_checker = sub { };
666 subtype 'ClassName' => as 'Str' =>
667 where { Class::MOP::is_class_loaded($_) } => optimize_as
668 \&Moose::Util::TypeConstraints::OptimizedConstraints::ClassName;
670 subtype 'RoleName' => as 'ClassName' => where {
671 (Class::MOP::class_of($_) || return)->isa('Moose::Meta::Role');
673 \&Moose::Util::TypeConstraints::OptimizedConstraints::RoleName;
675 ## --------------------------------------------------------
676 # parameterizable types ...
678 $REGISTRY->add_type_constraint(
679 Moose::Meta::TypeConstraint::Parameterizable->new(
681 package_defined_in => __PACKAGE__,
682 parent => find_type_constraint('Ref'),
683 constraint => sub { ref($_) eq 'ARRAY' },
685 \&Moose::Util::TypeConstraints::OptimizedConstraints::ArrayRef,
686 constraint_generator => sub {
687 my $type_parameter = shift;
688 my $check = $type_parameter->_compiled_type_constraint;
690 foreach my $x (@$_) {
691 ( $check->($x) ) || return;
699 $REGISTRY->add_type_constraint(
700 Moose::Meta::TypeConstraint::Parameterizable->new(
702 package_defined_in => __PACKAGE__,
703 parent => find_type_constraint('Ref'),
704 constraint => sub { ref($_) eq 'HASH' },
706 \&Moose::Util::TypeConstraints::OptimizedConstraints::HashRef,
707 constraint_generator => sub {
708 my $type_parameter = shift;
709 my $check = $type_parameter->_compiled_type_constraint;
711 foreach my $x ( values %$_ ) {
712 ( $check->($x) ) || return;
720 $REGISTRY->add_type_constraint(
721 Moose::Meta::TypeConstraint::Parameterizable->new(
723 package_defined_in => __PACKAGE__,
724 parent => find_type_constraint('Item'),
725 constraint => sub {1},
726 constraint_generator => sub {
727 my $type_parameter = shift;
728 my $check = $type_parameter->_compiled_type_constraint;
730 return 1 if not( defined($_) ) || $check->($_);
737 my @PARAMETERIZABLE_TYPES
738 = map { $REGISTRY->get_type_constraint($_) } qw[ArrayRef HashRef Maybe];
740 sub get_all_parameterizable_types {@PARAMETERIZABLE_TYPES}
742 sub add_parameterizable_type {
745 && $type->isa('Moose::Meta::TypeConstraint::Parameterizable') )
746 || __PACKAGE__->_throw_error(
747 "Type must be a Moose::Meta::TypeConstraint::Parameterizable not $type"
749 push @PARAMETERIZABLE_TYPES => $type;
752 ## --------------------------------------------------------
753 # end of built-in types ...
754 ## --------------------------------------------------------
757 my @BUILTINS = list_all_type_constraints();
758 sub list_all_builtin_type_constraints {@BUILTINS}
765 goto &Moose::throw_error;
776 Moose::Util::TypeConstraints - Type constraint system for Moose
780 use Moose::Util::TypeConstraints;
786 subtype 'NaturalLessThanTen'
789 => message { "This number ($_) is not less than ten!" };
795 enum 'RGBColors' => qw(red green blue);
797 no Moose::Util::TypeConstraints;
801 This module provides Moose with the ability to create custom type
802 constraints to be used in attribute definition.
804 =head2 Important Caveat
806 This is B<NOT> a type system for Perl 5. These are type constraints,
807 and they are not used by Moose unless you tell it to. No type
808 inference is performed, expressions are not typed, etc. etc. etc.
810 A type constraint is at heart a small "check if a value is valid"
811 function. A constraint can be associated with an attribute. This
812 simplifies parameter validation, and makes your code clearer to read,
813 because you can refer to constraints by name.
815 =head2 Slightly Less Important Caveat
817 It is B<always> a good idea to quote your type names.
819 This prevents Perl from trying to execute the call as an indirect
820 object call. This can be an issue when you have a subtype with the
821 same name as a valid class.
825 subtype DateTime => as Object => where { $_->isa('DateTime') };
827 will I<just work>, while this:
830 subtype DateTime => as Object => where { $_->isa('DateTime') };
832 will fail silently and cause many headaches. The simple way to solve
833 this, as well as future proof your subtypes from classes which have
834 yet to have been created, is to quote the type name:
837 subtype 'DateTime' => as 'Object' => where { $_->isa('DateTime') };
839 =head2 Default Type Constraints
841 This module also provides a simple hierarchy for Perl 5 types, here is
842 that hierarchy represented visually.
867 B<NOTE:> Any type followed by a type parameter C<[`a]> can be
868 parameterized, this means you can say:
870 ArrayRef[Int] # an array of integers
871 HashRef[CodeRef] # a hash of str to CODE ref mappings
872 Maybe[Str] # value may be a string, may be undefined
874 If Moose finds a name in brackets that it does not recognize as an
875 existing type, it assumes that this is a class name, for example
876 C<ArrayRef[DateTime]>.
878 B<NOTE:> Unless you parameterize a type, then it is invalid to include
879 the square brackets. I.e. C<ArrayRef[]> will be treated as a new type
880 name, I<not> as a parameterization of C<ArrayRef>.
882 B<NOTE:> The C<Undef> type constraint for the most part works
883 correctly now, but edge cases may still exist, please use it
886 B<NOTE:> The C<ClassName> type constraint does a complex package
887 existence check. This means that your class B<must> be loaded for this
888 type constraint to pass.
890 B<NOTE:> The C<RoleName> constraint checks a string is a I<package
891 name> which is a role, like C<'MyApp::Role::Comparable'>. The C<Role>
892 constraint checks that an I<object does> the named role.
894 =head2 Type Constraint Naming
896 Type name declared via this module can only contain alphanumeric
897 characters, colons (:), and periods (.).
899 Since the types created by this module are global, it is suggested
900 that you namespace your types just as you would namespace your
901 modules. So instead of creating a I<Color> type for your
902 B<My::Graphics> module, you would call the type
903 I<My::Graphics::Types::Color> instead.
905 =head2 Use with Other Constraint Modules
907 This module can play nicely with other constraint modules with some
908 slight tweaking. The C<where> clause in types is expected to be a
909 C<CODE> reference which checks it's first argument and returns a
910 boolean. Since most constraint modules work in a similar way, it
911 should be simple to adapt them to work with Moose.
913 For instance, this is how you could use it with
914 L<Declare::Constraints::Simple> to declare a completely new type.
916 type 'HashOfArrayOfObjects',
920 -values => IsArrayRef(IsObject)
924 For more examples see the F<t/200_examples/004_example_w_DCS.t> test
927 Here is an example of using L<Test::Deep> and it's non-test
928 related C<eq_deeply> function.
930 type 'ArrayOfHashOfBarsAndRandomNumbers'
933 array_each(subhashof({
935 random_number => ignore()
939 For a complete example see the
940 F<t/200_examples/005_example_w_TestDeep.t> test file.
944 =head2 Type Constraint Constructors
946 The following functions are used to create type constraints. They
947 will also register the type constraints your create in a global
948 registry that is used to look types up by name.
950 See the L<SYNOPSIS> for an example of how to use these.
954 =item B<< subtype 'Name' => as 'Parent' => where { } ... >>
956 This creates a named subtype.
958 If you provide a parent that Moose does not recognize, it will
959 automatically create a new class type constraint for this name.
961 When creating a named type, the C<subtype> function should either be
962 called with the sugar helpers (C<where>, C<message>, etc), or with a
963 name and a hashref of parameters:
965 subtype( 'Foo', { where => ..., message => ... } );
967 The valid hashref keys are C<as> (the parent), C<where>, C<message>,
970 =item B<< subtype as 'Parent' => where { } ... >>
972 This creates an unnamed subtype and will return the type
973 constraint meta-object, which will be an instance of
974 L<Moose::Meta::TypeConstraint>.
976 When creating an anonymous type, the C<subtype> function should either
977 be called with the sugar helpers (C<where>, C<message>, etc), or with
978 just a hashref of parameters:
980 subtype( { where => ..., message => ... } );
982 =item B<class_type ($class, ?$options)>
984 Creates a new subtype of C<Object> with the name C<$class> and the
985 metaclass L<Moose::Meta::TypeConstraint::Class>.
987 =item B<role_type ($role, ?$options)>
989 Creates a C<Role> type constraint with the name C<$role> and the
990 metaclass L<Moose::Meta::TypeConstraint::Role>.
992 =item B<maybe_type ($type)>
994 Creates a type constraint for either C<undef> or something of the
997 =item B<duck_type ($name, @methods)>
999 This will create a subtype of Object and test to make sure the value
1000 C<can()> do the methods in C<@methods>.
1002 This is intended as an easy way to accept non-Moose objects that
1003 provide a certain interface. If you're using Moose classes, we
1004 recommend that you use a C<requires>-only Role instead.
1006 =item B<duck_type (\@methods)>
1008 If passed an ARRAY reference instead of the C<$name>, C<@methods>
1009 pair, this will create an unnamed duck type. This can be used in an
1010 attribute definition like so:
1014 isa => duck_type( [qw( get_set )] ),
1017 =item B<enum ($name, @values)>
1019 This will create a basic subtype for a given set of strings.
1020 The resulting constraint will be a subtype of C<Str> and
1021 will match any of the items in C<@values>. It is case sensitive.
1022 See the L<SYNOPSIS> for a simple example.
1024 B<NOTE:> This is not a true proper enum type, it is simply
1025 a convenient constraint builder.
1027 =item B<enum (\@values)>
1029 If passed an ARRAY reference instead of the C<$name>, C<@values> pair,
1030 this will create an unnamed enum. This can then be used in an attribute
1033 has 'sort_order' => (
1035 isa => enum([qw[ ascending descending ]]),
1038 =item B<as 'Parent'>
1040 This is just sugar for the type constraint construction syntax.
1042 It takes a single argument, which is the name of a parent type.
1044 =item B<where { ... }>
1046 This is just sugar for the type constraint construction syntax.
1048 It takes a subroutine reference as an argument. When the type
1049 constraint is tested, the reference is run with the value to be tested
1050 in C<$_>. This reference should return true or false to indicate
1051 whether or not the constraint check passed.
1053 =item B<message { ... }>
1055 This is just sugar for the type constraint construction syntax.
1057 It takes a subroutine reference as an argument. When the type
1058 constraint fails, then the code block is run with the value provided
1059 in C<$_>. This reference should return a string, which will be used in
1060 the text of the exception thrown.
1062 =item B<optimize_as { ... }>
1064 This can be used to define a "hand optimized" version of your
1065 type constraint which can be used to avoid traversing a subtype
1066 constraint hierarchy.
1068 B<NOTE:> You should only use this if you know what you are doing,
1069 all the built in types use this, so your subtypes (assuming they
1070 are shallow) will not likely need to use this.
1072 =item B<type 'Name' => where { } ... >
1074 This creates a base type, which has no parent.
1076 The C<type> function should either be called with the sugar helpers
1077 (C<where>, C<message>, etc), or with a name and a hashref of
1080 type( 'Foo', { where => ..., message => ... } );
1082 The valid hashref keys are C<where>, C<message>, and C<optimize_as>.
1086 =head2 Type Coercion Constructors
1088 You can define coercions for type constraints, which allow you to
1089 automatically transform values to something valid for the type
1090 constraint. If you ask your accessor to coerce, then Moose will run
1091 the type-coercion code first, followed by the type constraint
1092 check. This feature should be used carefully as it is very powerful
1093 and could easily take off a limb if you are not careful.
1095 See the L<SYNOPSIS> for an example of how to use these.
1099 =item B<< coerce 'Name' => from 'OtherName' => via { ... } >>
1101 This defines a coercion from one type to another. The C<Name> argument
1102 is the type you are coercing I<to>.
1104 =item B<from 'OtherName'>
1106 This is just sugar for the type coercion construction syntax.
1108 It takes a single type name (or type object), which is the type being
1111 =item B<via { ... }>
1113 This is just sugar for the type coercion construction syntax.
1115 It takes a subroutine reference. This reference will be called with
1116 the value to be coerced in C<$_>. It is expected to return a new value
1117 of the proper type for the coercion.
1121 =head2 Creating and Finding Type Constraints
1123 These are additional functions for creating and finding type
1124 constraints. Most of these functions are not available for
1125 importing. The ones that are importable as specified.
1129 =item B<find_type_constraint($type_name)>
1131 This function can be used to locate the L<Moose::Meta::TypeConstraint>
1132 object for a named type.
1134 This function is importable.
1136 =item B<register_type_constraint($type_object)>
1138 This function will register a L<Moose::Meta::TypeConstraint> with the
1139 global type registry.
1141 This function is importable.
1143 =item B<normalize_type_constraint_name($type_constraint_name)>
1145 This method takes a type constraint name and returns the normalized
1146 form. This removes any whitespace in the string.
1148 =item B<create_type_constraint_union($pipe_separated_types | @type_constraint_names)>
1150 This can take a union type specification like C<'Int|ArrayRef[Int]'>,
1151 or a list of names. It returns a new
1152 L<Moose::Meta::TypeConstraint::Union> object.
1154 =item B<create_parameterized_type_constraint($type_name)>
1156 Given a C<$type_name> in the form of C<'BaseType[ContainerType]'>,
1157 this will create a new L<Moose::Meta::TypeConstraint::Parameterized>
1158 object. The C<BaseType> must exist already exist as a parameterizable
1161 =item B<create_class_type_constraint($class, $options)>
1163 Given a class name this function will create a new
1164 L<Moose::Meta::TypeConstraint::Class> object for that class name.
1166 The C<$options> is a hash reference that will be passed to the
1167 L<Moose::Meta::TypeConstraint::Class> constructor (as a hash).
1169 =item B<create_role_type_constraint($role, $options)>
1171 Given a role name this function will create a new
1172 L<Moose::Meta::TypeConstraint::Role> object for that role name.
1174 The C<$options> is a hash reference that will be passed to the
1175 L<Moose::Meta::TypeConstraint::Role> constructor (as a hash).
1177 =item B<create_enum_type_constraint($name, $values)>
1179 Given a enum name this function will create a new
1180 L<Moose::Meta::TypeConstraint::Enum> object for that enum name.
1182 =item B<find_or_parse_type_constraint($type_name)>
1184 Given a type name, this first attempts to find a matching constraint
1185 in the global registry.
1187 If the type name is a union or parameterized type, it will create a
1188 new object of the appropriate, but if given a "regular" type that does
1189 not yet exist, it simply returns false.
1191 When given a union or parameterized type, the member or base type must
1194 If it creates a new union or parameterized type, it will add it to the
1197 =item B<find_or_create_isa_type_constraint($type_name)>
1199 =item B<find_or_create_does_type_constraint($type_name)>
1201 These functions will first call C<find_or_parse_type_constraint>. If
1202 that function does not return a type, a new anonymous type object will
1205 The C<isa> variant will use C<create_class_type_constraint> and the
1206 C<does> variant will use C<create_role_type_constraint>.
1208 =item B<get_type_constraint_registry>
1210 Returns the L<Moose::Meta::TypeConstraint::Registry> object which
1211 keeps track of all type constraints.
1213 =item B<list_all_type_constraints>
1215 This will return a list of type constraint names in the global
1216 registry. You can then fetch the actual type object using
1217 C<find_type_constraint($type_name)>.
1219 =item B<list_all_builtin_type_constraints>
1221 This will return a list of builtin type constraints, meaning those
1222 which are defined in this module. See the L<Default Type Constraints>
1223 section for a complete list.
1225 =item B<export_type_constraints_as_functions>
1227 This will export all the current type constraints as functions into
1228 the caller's namespace (C<Int()>, C<Str()>, etc). Right now, this is
1229 mostly used for testing, but it might prove useful to others.
1231 =item B<get_all_parameterizable_types>
1233 This returns all the parameterizable types that have been registered,
1234 as a list of type objects.
1236 =item B<add_parameterizable_type($type)>
1238 Adds C<$type> to the list of parameterizable types
1244 All complex software has bugs lurking in it, and this module is no
1245 exception. If you find a bug please either email me, or add the bug
1250 Stevan Little E<lt>stevan@iinteractive.comE<gt>
1252 =head1 COPYRIGHT AND LICENSE
1254 Copyright 2006-2009 by Infinity Interactive, Inc.
1256 L<http://www.iinteractive.com>
1258 This library is free software; you can redistribute it and/or modify
1259 it under the same terms as Perl itself.