2 package Moose::Util::TypeConstraints;
5 use List::MoreUtils qw( all any );
6 use Scalar::Util qw( blessed reftype );
9 ## --------------------------------------------------------
10 # Prototyped subs must be predeclared because we have a
11 # circular dependency with Moose::Meta::Attribute et. al.
12 # so in case of us being use'd first the predeclaration
13 # ensures the prototypes are in scope when consumers are
23 ## --------------------------------------------------------
25 use Moose::Deprecated;
26 use Moose::Meta::TypeConstraint;
27 use Moose::Meta::TypeConstraint::Union;
28 use Moose::Meta::TypeConstraint::Intersection;
29 use Moose::Meta::TypeConstraint::Parameterized;
30 use Moose::Meta::TypeConstraint::Parameterizable;
31 use Moose::Meta::TypeConstraint::Class;
32 use Moose::Meta::TypeConstraint::Role;
33 use Moose::Meta::TypeConstraint::Enum;
34 use Moose::Meta::TypeConstraint::DuckType;
35 use Moose::Meta::TypeCoercion;
36 use Moose::Meta::TypeCoercion::Union;
37 use Moose::Meta::TypeCoercion::Intersection;
38 use Moose::Meta::TypeConstraint::Registry;
40 Moose::Exporter->setup_import_methods(
43 type subtype class_type role_type maybe_type duck_type
44 as where message optimize_as inline_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 _create_type_constraint_union(\@_);
77 sub create_named_type_constraint_union {
79 _create_type_constraint_union($name, \@_);
82 sub _create_type_constraint_union {
84 $name = shift if @_ > 1;
85 my @tcs = @{ shift() };
87 my @type_constraint_names;
89 if ( scalar @tcs == 1 && _detect_type_constraint_union( $tcs[0] ) ) {
90 @type_constraint_names = _parse_type_constraint_union( $tcs[0] );
93 @type_constraint_names = @tcs;
96 ( scalar @type_constraint_names >= 2 )
97 || __PACKAGE__->_throw_error(
98 "You must pass in at least 2 type names to make a union");
100 my @type_constraints = map {
101 find_or_parse_type_constraint($_)
102 || __PACKAGE__->_throw_error(
103 "Could not locate type constraint ($_) for the union");
104 } @type_constraint_names;
107 type_constraints => \@type_constraints
109 $options{name} = $name if defined $name;
111 return Moose::Meta::TypeConstraint::Union->new(%options);
114 sub create_type_constraint_intersection {
115 my @type_constraint_names;
117 if (scalar @_ == 1 && _detect_type_constraint_intersection($_[0])) {
118 @type_constraint_names = _parse_type_constraint_intersection($_[0]);
121 @type_constraint_names = @_;
124 (scalar @type_constraint_names >= 2)
125 || __PACKAGE__->_throw_error("You must pass in at least 2 type names to make an intersection");
127 my @type_constraints = map {
128 find_or_parse_type_constraint($_) ||
129 __PACKAGE__->_throw_error("Could not locate type constraint ($_) for the intersection");
130 } @type_constraint_names;
132 return Moose::Meta::TypeConstraint::Intersection->new(
133 type_constraints => \@type_constraints
137 sub create_parameterized_type_constraint {
138 my $type_constraint_name = shift;
139 my ( $base_type, $type_parameter )
140 = _parse_parameterized_type_constraint($type_constraint_name);
142 ( defined $base_type && defined $type_parameter )
143 || __PACKAGE__->_throw_error(
144 "Could not parse type name ($type_constraint_name) correctly");
146 if ( $REGISTRY->has_type_constraint($base_type) ) {
147 my $base_type_tc = $REGISTRY->get_type_constraint($base_type);
148 return _create_parameterized_type_constraint(
154 __PACKAGE__->_throw_error(
155 "Could not locate the base type ($base_type)");
159 sub _create_parameterized_type_constraint {
160 my ( $base_type_tc, $type_parameter ) = @_;
161 if ( $base_type_tc->can('parameterize') ) {
162 return $base_type_tc->parameterize($type_parameter);
165 return Moose::Meta::TypeConstraint::Parameterized->new(
166 name => $base_type_tc->name . '[' . $type_parameter . ']',
167 parent => $base_type_tc,
169 find_or_create_isa_type_constraint($type_parameter),
174 #should we also support optimized checks?
175 sub create_class_type_constraint {
176 my ( $class, $options ) = @_;
178 # too early for this check
179 #find_type_constraint("ClassName")->check($class)
180 # || __PACKAGE__->_throw_error("Can't create a class type constraint because '$class' is not a class name");
188 $options{name} ||= "__ANON__";
190 Moose::Meta::TypeConstraint::Class->new(%options);
193 sub create_role_type_constraint {
194 my ( $role, $options ) = @_;
196 # too early for this check
197 #find_type_constraint("ClassName")->check($class)
198 # || __PACKAGE__->_throw_error("Can't create a class type constraint because '$class' is not a class name");
206 $options{name} ||= "__ANON__";
208 Moose::Meta::TypeConstraint::Role->new(%options);
211 sub find_or_create_type_constraint {
212 my ( $type_constraint_name, $options_for_anon_type ) = @_;
215 = find_or_parse_type_constraint($type_constraint_name) ) {
218 elsif ( defined $options_for_anon_type ) {
221 # if there is no $options_for_anon_type
222 # specified, then we assume they don't
223 # want to create one, and return nothing.
225 # otherwise assume that we should create
226 # an ANON type with the $options_for_anon_type
227 # options which can be passed in. It should
228 # be noted that these don't get registered
229 # so we need to return it.
231 return Moose::Meta::TypeConstraint->new(
233 %{$options_for_anon_type}
240 sub find_or_create_isa_type_constraint {
241 my $type_constraint_name = shift;
242 find_or_parse_type_constraint($type_constraint_name)
243 || create_class_type_constraint($type_constraint_name);
246 sub find_or_create_does_type_constraint {
247 my $type_constraint_name = shift;
248 find_or_parse_type_constraint($type_constraint_name)
249 || create_role_type_constraint($type_constraint_name);
252 sub find_or_parse_type_constraint {
253 my $type_constraint_name = normalize_type_constraint_name(shift);
256 if ( $constraint = find_type_constraint($type_constraint_name) ) {
259 elsif (_detect_type_constraint_intersection($type_constraint_name)) {
260 $constraint = create_type_constraint_intersection($type_constraint_name);
262 elsif (_detect_type_constraint_union($type_constraint_name)) {
263 $constraint = create_type_constraint_union($type_constraint_name);
265 elsif ( _detect_parameterized_type_constraint($type_constraint_name) ) {
267 = create_parameterized_type_constraint($type_constraint_name);
273 $REGISTRY->add_type_constraint($constraint);
277 sub normalize_type_constraint_name {
278 my $type_constraint_name = shift;
279 $type_constraint_name =~ s/\s//g;
280 return $type_constraint_name;
286 local $Carp::CarpLevel = $Carp::CarpLevel + 1;
287 Carp::confess($error);
290 ## --------------------------------------------------------
291 ## exported functions ...
292 ## --------------------------------------------------------
294 sub find_type_constraint {
297 if ( blessed $type and $type->isa("Moose::Meta::TypeConstraint") ) {
301 return unless $REGISTRY->has_type_constraint($type);
302 return $REGISTRY->get_type_constraint($type);
306 sub register_type_constraint {
307 my $constraint = shift;
308 __PACKAGE__->_throw_error("can't register an unnamed type constraint")
309 unless defined $constraint->name;
310 $REGISTRY->add_type_constraint($constraint);
319 my %p = map { %{$_} } @_;
321 return _create_type_constraint(
322 $name, undef, $p{where}, $p{message},
323 $p{optimize_as}, $p{inline_as},
328 if ( @_ == 1 && !ref $_[0] ) {
329 __PACKAGE__->_throw_error(
330 'A subtype cannot consist solely of a name, it must have a parent'
334 # The blessed check is mostly to accommodate MooseX::Types, which
335 # uses an object which overloads stringification as a type name.
336 my $name = ref $_[0] && !blessed $_[0] ? undef : shift;
338 my %p = map { %{$_} } @_;
340 # subtype Str => where { ... };
341 if ( !exists $p{as} ) {
346 return _create_type_constraint(
347 $name, $p{as}, $p{where}, $p{message},
348 $p{optimize_as}, $p{inline_as},
353 register_type_constraint(
354 create_class_type_constraint(
356 ( defined( $_[1] ) ? $_[1] : () ),
361 sub role_type ($;$) {
362 register_type_constraint(
363 create_role_type_constraint(
365 ( defined( $_[1] ) ? $_[1] : () ),
371 my ($type_parameter) = @_;
373 register_type_constraint(
374 $REGISTRY->get_type_constraint('Maybe')->parameterize($type_parameter)
379 my ( $type_name, @methods ) = @_;
380 if ( ref $type_name eq 'ARRAY' && !@methods ) {
381 @methods = @$type_name;
384 if ( @methods == 1 && ref $methods[0] eq 'ARRAY' ) {
385 @methods = @{ $methods[0] };
388 register_type_constraint(
389 create_duck_type_constraint(
397 my ( $type_name, @coercion_map ) = @_;
398 _install_type_coercions( $type_name, \@coercion_map );
401 # The trick of returning @_ lets us avoid having to specify a
402 # prototype. Perl will parse this:
410 # subtype( 'Foo', as( 'Str', where { ... } ) );
412 # If as() returns all its extra arguments, this just works, and
413 # preserves backwards compatibility.
414 sub as { { as => shift }, @_ }
415 sub where (&) { { where => $_[0] } }
416 sub message (&) { { message => $_[0] } }
417 sub optimize_as (&) { { optimize_as => $_[0] } }
418 sub inline_as (&) { { inline_as => $_[0] } }
421 sub via (&) { $_[0] }
424 my ( $type_name, @values ) = @_;
427 # if only an array-ref is passed then
428 # you get an anon-enum
430 if ( ref $type_name eq 'ARRAY' ) {
432 || __PACKAGE__->_throw_error("enum called with an array reference and additional arguments. Did you mean to parenthesize the enum call's parameters?");
434 @values = @$type_name;
437 if ( @values == 1 && ref $values[0] eq 'ARRAY' ) {
438 @values = @{ $values[0] };
441 register_type_constraint(
442 create_enum_type_constraint(
450 my ( $type_name, @constraints ) = @_;
451 if ( ref $type_name eq 'ARRAY' ) {
453 || __PACKAGE__->_throw_error("union called with an array reference and additional arguments.");
454 @constraints = @$type_name;
457 if ( @constraints == 1 && ref $constraints[0] eq 'ARRAY' ) {
458 @constraints = @{ $constraints[0] };
460 if ( defined $type_name ) {
461 return register_type_constraint(
462 create_named_type_constraint_union( $type_name, @constraints )
465 return create_type_constraint_union( @constraints );
468 sub create_enum_type_constraint {
469 my ( $type_name, $values ) = @_;
471 Moose::Meta::TypeConstraint::Enum->new(
472 name => $type_name || '__ANON__',
477 sub create_duck_type_constraint {
478 my ( $type_name, $methods ) = @_;
480 Moose::Meta::TypeConstraint::DuckType->new(
481 name => $type_name || '__ANON__',
487 my ($to_match, @cases) = @_;
489 if (@cases % 2 != 0) {
490 $default = pop @cases;
491 (ref $default eq 'CODE')
492 || __PACKAGE__->_throw_error("Default case must be a CODE ref, not $default");
495 my ($type, $action) = splice @cases, 0, 2;
497 unless (blessed $type && $type->isa('Moose::Meta::TypeConstraint')) {
498 $type = find_or_parse_type_constraint($type)
499 || __PACKAGE__->_throw_error("Cannot find or parse the type '$type'")
502 (ref $action eq 'CODE')
503 || __PACKAGE__->_throw_error("Match action must be a CODE ref, not $action");
505 if ($type->check($to_match)) {
506 local $_ = $to_match;
507 return $action->($to_match);
511 || __PACKAGE__->_throw_error("No cases matched for $to_match");
513 local $_ = $to_match;
514 return $default->($to_match);
519 ## --------------------------------------------------------
520 ## desugaring functions ...
521 ## --------------------------------------------------------
523 sub _create_type_constraint ($$$;$$) {
528 my $optimized = shift;
531 my $pkg_defined_in = scalar( caller(1) );
533 if ( defined $name ) {
534 my $type = $REGISTRY->get_type_constraint($name);
536 ( $type->_package_defined_in eq $pkg_defined_in )
538 "The type constraint '$name' has already been created in "
539 . $type->_package_defined_in
540 . " and cannot be created again in "
544 $name =~ /^[\w:\.]+$/
545 or die qq{$name contains invalid characters for a type name.}
546 . qq{ Names can contain alphanumeric character, ":", and "."\n};
551 package_defined_in => $pkg_defined_in,
553 ( $check ? ( constraint => $check ) : () ),
554 ( $message ? ( message => $message ) : () ),
555 ( $optimized ? ( optimized => $optimized ) : () ),
556 ( $inlined ? ( inlined => $inlined ) : () ),
565 : find_or_create_isa_type_constraint($parent)
567 $constraint = $parent->create_child_type(%opts);
570 $constraint = Moose::Meta::TypeConstraint->new(%opts);
573 $REGISTRY->add_type_constraint($constraint)
579 sub _install_type_coercions ($$) {
580 my ( $type_name, $coercion_map ) = @_;
581 my $type = find_type_constraint($type_name);
583 || __PACKAGE__->_throw_error(
584 "Cannot find type '$type_name', perhaps you forgot to load it");
585 if ( $type->has_coercion ) {
586 $type->coercion->add_type_coercions(@$coercion_map);
589 my $type_coercion = Moose::Meta::TypeCoercion->new(
590 type_coercion_map => $coercion_map,
591 type_constraint => $type
593 $type->coercion($type_coercion);
597 ## --------------------------------------------------------
598 ## type notation parsing ...
599 ## --------------------------------------------------------
603 # All I have to say is mugwump++ cause I know
604 # do not even have enough regexp-fu to be able
605 # to have written this (I can only barely
606 # understand it as it is)
611 my $valid_chars = qr{[\w:\.]};
612 my $type_atom = qr{ (?>$valid_chars+) }x;
613 my $ws = qr{ (?>\s*) }x;
614 my $op_union = qr{ $ws \| $ws }x;
615 my $op_intersection = qr{ $ws & $ws }x;
617 my ($type, $type_capture_parts, $type_with_parameter, $union, $any, $intersection);
618 if (Class::MOP::IS_RUNNING_ON_5_10) {
620 = q{ (?&type_atom) (?: \[ (?&ws) (?&any) (?&ws) \] )? };
621 my $type_capture_parts_pattern
622 = q{ ((?&type_atom)) (?: \[ (?&ws) ((?&any)) (?&ws) \] )? };
623 my $type_with_parameter_pattern
624 = q{ (?&type_atom) \[ (?&ws) (?&any) (?&ws) \] };
626 = q{ (?&type) (?> (?: (?&op_union) (?&type) )+ ) };
627 my $intersection_pattern
628 = q{ (?&type) (?> (?: (?&op_intersection) (?&type) )+ ) };
630 = q{ (?&type) | (?&union) | (?&intersection) };
632 my $defines = qr{(?(DEFINE)
633 (?<valid_chars> $valid_chars)
634 (?<type_atom> $type_atom)
636 (?<op_union> $op_union)
637 (?<op_intersection> $op_intersection)
638 (?<type> $type_pattern)
639 (?<type_capture_parts> $type_capture_parts_pattern)
640 (?<type_with_parameter> $type_with_parameter_pattern)
641 (?<union> $union_pattern)
642 (?<intersection> $intersection_pattern)
643 (?<any> $any_pattern)
646 $type = qr{ $type_pattern $defines }x;
647 $type_capture_parts = qr{ $type_capture_parts_pattern $defines }x;
648 $type_with_parameter = qr{ $type_with_parameter_pattern $defines }x;
649 $union = qr{ $union_pattern $defines }x;
650 $intersection = qr{ $intersection_pattern $defines }x;
651 $any = qr{ $any_pattern $defines }x;
655 = qr{ $type_atom (?: \[ $ws (??{$any}) $ws \] )? }x;
657 = qr{ ($type_atom) (?: \[ $ws ((??{$any})) $ws \] )? }x;
659 = qr{ $type_atom \[ $ws (??{$any}) $ws \] }x;
661 = qr{ $type (?> (?: $op_union $type )+ ) }x;
663 = qr{ $type (?> (?: $op_intersection $type )+ ) }x;
665 = qr{ $type | $union | $intersection }x;
669 sub _parse_parameterized_type_constraint {
670 { no warnings 'void'; $any; } # force capture of interpolated lexical
671 $_[0] =~ m{ $type_capture_parts }x;
675 sub _detect_parameterized_type_constraint {
676 { no warnings 'void'; $any; } # force capture of interpolated lexical
677 $_[0] =~ m{ ^ $type_with_parameter $ }x;
680 sub _parse_type_constraint_union {
681 { no warnings 'void'; $any; } # force capture of interpolated lexical
684 while ( $given =~ m{ \G (?: $op_union )? ($type) }gcx ) {
687 ( pos($given) eq length($given) )
688 || __PACKAGE__->_throw_error( "'$given' didn't parse (parse-pos="
696 sub _parse_type_constraint_intersection {
697 { no warnings 'void'; $any; } # force capture of interpolated lexical
700 while ( $given =~ m{ \G (?: $op_intersection )? ($type) }gcx ) {
703 (pos($given) eq length($given))
704 || __PACKAGE__->_throw_error("'$given' didn't parse (parse-pos="
712 sub _detect_type_constraint_union {
713 { no warnings 'void'; $any; } # force capture of interpolated lexical
714 $_[0] =~ m{^ $type $op_union $type ( $op_union .* )? $}x;
717 sub _detect_type_constraint_intersection {
718 { no warnings 'void'; $any; } # force capture of interpolated lexical
719 $_[0] =~ m{^ $type $op_intersection $type ( $op_intersection .* )? $}x;
723 ## --------------------------------------------------------
724 # define some basic built-in types
725 ## --------------------------------------------------------
727 # By making these classes immutable before creating all the types in
728 # Moose::Util::TypeConstraints::Builtin , we avoid repeatedly calling the slow
729 # MOP-based accessors.
731 inline_constructor => 1,
732 constructor_name => "_new",
734 # these are Class::MOP accessors, so they need inlining
735 inline_accessors => 1
736 ) for grep { $_->is_mutable }
737 map { Class::MOP::class_of($_) }
739 Moose::Meta::TypeConstraint
740 Moose::Meta::TypeConstraint::Union
741 Moose::Meta::TypeConstraint::Intersection
742 Moose::Meta::TypeConstraint::Parameterized
743 Moose::Meta::TypeConstraint::Parameterizable
744 Moose::Meta::TypeConstraint::Class
745 Moose::Meta::TypeConstraint::Role
746 Moose::Meta::TypeConstraint::Enum
747 Moose::Meta::TypeConstraint::DuckType
748 Moose::Meta::TypeConstraint::Registry
751 require Moose::Util::TypeConstraints::Builtins;
752 Moose::Util::TypeConstraints::Builtins::define_builtins($REGISTRY);
754 my @PARAMETERIZABLE_TYPES
755 = map { $REGISTRY->get_type_constraint($_) } qw[ScalarRef ArrayRef HashRef Maybe];
757 sub get_all_parameterizable_types {@PARAMETERIZABLE_TYPES}
759 sub add_parameterizable_type {
762 && $type->isa('Moose::Meta::TypeConstraint::Parameterizable') )
763 || __PACKAGE__->_throw_error(
764 "Type must be a Moose::Meta::TypeConstraint::Parameterizable not $type"
766 push @PARAMETERIZABLE_TYPES => $type;
769 ## --------------------------------------------------------
770 # end of built-in types ...
771 ## --------------------------------------------------------
774 my @BUILTINS = list_all_type_constraints();
775 sub list_all_builtin_type_constraints {@BUILTINS}
782 goto &Moose::throw_error;
787 # ABSTRACT: Type constraint system for Moose
795 use Moose::Util::TypeConstraints;
801 subtype 'NaturalLessThanTen',
804 message { "This number ($_) is not less than ten!" };
810 enum 'RGBColors', [qw(red green blue)];
812 union 'StringOrArray', [qw( String Array )];
814 no Moose::Util::TypeConstraints;
818 This module provides Moose with the ability to create custom type
819 constraints to be used in attribute definition.
821 =head2 Important Caveat
823 This is B<NOT> a type system for Perl 5. These are type constraints,
824 and they are not used by Moose unless you tell it to. No type
825 inference is performed, expressions are not typed, etc. etc. etc.
827 A type constraint is at heart a small "check if a value is valid"
828 function. A constraint can be associated with an attribute. This
829 simplifies parameter validation, and makes your code clearer to read,
830 because you can refer to constraints by name.
832 =head2 Slightly Less Important Caveat
834 It is B<always> a good idea to quote your type names.
836 This prevents Perl from trying to execute the call as an indirect
837 object call. This can be an issue when you have a subtype with the
838 same name as a valid class.
842 subtype DateTime => as Object => where { $_->isa('DateTime') };
844 will I<just work>, while this:
847 subtype DateTime => as Object => where { $_->isa('DateTime') };
849 will fail silently and cause many headaches. The simple way to solve
850 this, as well as future proof your subtypes from classes which have
851 yet to have been created, is to quote the type name:
854 subtype 'DateTime', as 'Object', where { $_->isa('DateTime') };
856 =head2 Default Type Constraints
858 This module also provides a simple hierarchy for Perl 5 types, here is
859 that hierarchy represented visually.
883 B<NOTE:> Any type followed by a type parameter C<[`a]> can be
884 parameterized, this means you can say:
886 ArrayRef[Int] # an array of integers
887 HashRef[CodeRef] # a hash of str to CODE ref mappings
888 ScalarRef[Int] # a reference to an integer
889 Maybe[Str] # value may be a string, may be undefined
891 If Moose finds a name in brackets that it does not recognize as an
892 existing type, it assumes that this is a class name, for example
893 C<ArrayRef[DateTime]>.
895 B<NOTE:> Unless you parameterize a type, then it is invalid to include
896 the square brackets. I.e. C<ArrayRef[]> will be treated as a new type
897 name, I<not> as a parameterization of C<ArrayRef>.
899 B<NOTE:> The C<Undef> type constraint for the most part works
900 correctly now, but edge cases may still exist, please use it
903 B<NOTE:> The C<ClassName> type constraint does a complex package
904 existence check. This means that your class B<must> be loaded for this
905 type constraint to pass.
907 B<NOTE:> The C<RoleName> constraint checks a string is a I<package
908 name> which is a role, like C<'MyApp::Role::Comparable'>.
910 =head2 Type Constraint Naming
912 Type name declared via this module can only contain alphanumeric
913 characters, colons (:), and periods (.).
915 Since the types created by this module are global, it is suggested
916 that you namespace your types just as you would namespace your
917 modules. So instead of creating a I<Color> type for your
918 B<My::Graphics> module, you would call the type
919 I<My::Graphics::Types::Color> instead.
921 =head2 Use with Other Constraint Modules
923 This module can play nicely with other constraint modules with some
924 slight tweaking. The C<where> clause in types is expected to be a
925 C<CODE> reference which checks its first argument and returns a
926 boolean. Since most constraint modules work in a similar way, it
927 should be simple to adapt them to work with Moose.
929 For instance, this is how you could use it with
930 L<Declare::Constraints::Simple> to declare a completely new type.
932 type 'HashOfArrayOfObjects',
936 -values => IsArrayRef(IsObject)
940 For more examples see the F<t/examples/example_w_DCS.t> test
943 Here is an example of using L<Test::Deep> and its non-test
944 related C<eq_deeply> function.
946 type 'ArrayOfHashOfBarsAndRandomNumbers',
949 array_each(subhashof({
951 random_number => ignore()
955 For a complete example see the
956 F<t/examples/example_w_TestDeep.t> test file.
958 =head2 Error messages
960 Type constraints can also specify custom error messages, for when they fail to
961 validate. This is provided as just another coderef, which receives the invalid
962 value in C<$_>, as in:
964 subtype 'PositiveInt',
967 message { "$_ is not a positive integer!" };
969 If no message is specified, a default message will be used, which indicates
970 which type constraint was being used and what value failed. If
971 L<Devel::PartialDump> (version 0.14 or higher) is installed, it will be used to
972 display the invalid value, otherwise it will just be printed as is.
976 =head2 Type Constraint Constructors
978 The following functions are used to create type constraints. They
979 will also register the type constraints your create in a global
980 registry that is used to look types up by name.
982 See the L</SYNOPSIS> for an example of how to use these.
986 =item B<< subtype 'Name', as 'Parent', where { } ... >>
988 This creates a named subtype.
990 If you provide a parent that Moose does not recognize, it will
991 automatically create a new class type constraint for this name.
993 When creating a named type, the C<subtype> function should either be
994 called with the sugar helpers (C<where>, C<message>, etc), or with a
995 name and a hashref of parameters:
997 subtype( 'Foo', { where => ..., message => ... } );
999 The valid hashref keys are C<as> (the parent), C<where>, C<message>,
1002 =item B<< subtype as 'Parent', where { } ... >>
1004 This creates an unnamed subtype and will return the type
1005 constraint meta-object, which will be an instance of
1006 L<Moose::Meta::TypeConstraint>.
1008 When creating an anonymous type, the C<subtype> function should either
1009 be called with the sugar helpers (C<where>, C<message>, etc), or with
1010 just a hashref of parameters:
1012 subtype( { where => ..., message => ... } );
1014 =item B<class_type ($class, ?$options)>
1016 Creates a new subtype of C<Object> with the name C<$class> and the
1017 metaclass L<Moose::Meta::TypeConstraint::Class>.
1019 =item B<role_type ($role, ?$options)>
1021 Creates a C<Role> type constraint with the name C<$role> and the
1022 metaclass L<Moose::Meta::TypeConstraint::Role>.
1024 =item B<maybe_type ($type)>
1026 Creates a type constraint for either C<undef> or something of the
1029 =item B<duck_type ($name, \@methods)>
1031 This will create a subtype of Object and test to make sure the value
1032 C<can()> do the methods in C<\@methods>.
1034 This is intended as an easy way to accept non-Moose objects that
1035 provide a certain interface. If you're using Moose classes, we
1036 recommend that you use a C<requires>-only Role instead.
1038 =item B<duck_type (\@methods)>
1040 If passed an ARRAY reference as the only parameter instead of the
1041 C<$name>, C<\@methods> pair, this will create an unnamed duck type.
1042 This can be used in an attribute definition like so:
1046 isa => duck_type( [qw( get_set )] ),
1049 =item B<enum ($name, \@values)>
1051 This will create a basic subtype for a given set of strings.
1052 The resulting constraint will be a subtype of C<Str> and
1053 will match any of the items in C<\@values>. It is case sensitive.
1054 See the L</SYNOPSIS> for a simple example.
1056 B<NOTE:> This is not a true proper enum type, it is simply
1057 a convenient constraint builder.
1059 =item B<enum (\@values)>
1061 If passed an ARRAY reference as the only parameter instead of the
1062 C<$name>, C<\@values> pair, this will create an unnamed enum. This
1063 can then be used in an attribute definition like so:
1065 has 'sort_order' => (
1067 isa => enum([qw[ ascending descending ]]),
1070 =item B<union ($name, \@constraints)>
1072 This will create a basic subtype where any of the provided constraints
1073 may match in order to satisfy this constraint.
1075 =item B<union (\@constraints)>
1077 If passed an ARRAY reference as the only parameter instead of the
1078 C<$name>, C<\@constraints> pair, this will create an unnamed union.
1079 This can then be used in an attribute definition like so:
1083 isa => union([qw[ Str ArrayRef ]]),
1086 This is similar to the existing string union:
1088 isa => 'Str|ArrayRef'
1090 except that it supports anonymous elements as child constraints:
1094 isa => union([ 'Int', enum([qw[ red green blue ]]) ]),
1097 =item B<as 'Parent'>
1099 This is just sugar for the type constraint construction syntax.
1101 It takes a single argument, which is the name of a parent type.
1103 =item B<where { ... }>
1105 This is just sugar for the type constraint construction syntax.
1107 It takes a subroutine reference as an argument. When the type
1108 constraint is tested, the reference is run with the value to be tested
1109 in C<$_>. This reference should return true or false to indicate
1110 whether or not the constraint check passed.
1112 =item B<message { ... }>
1114 This is just sugar for the type constraint construction syntax.
1116 It takes a subroutine reference as an argument. When the type
1117 constraint fails, then the code block is run with the value provided
1118 in C<$_>. This reference should return a string, which will be used in
1119 the text of the exception thrown.
1121 =item B<inline_as { ... }>
1123 This can be used to define a "hand optimized" inlinable version of your type
1126 You provide a subroutine which will be called I<as a method> on a
1127 L<Moose::Meta::TypeConstraint> object. It will receive a single parameter, the
1128 name of the variable to check, typically something like C<"$_"> or C<"$_[0]">.
1130 The subroutine should return a code string suitable for inlining. You can
1131 assume that the check will be wrapped in parentheses when it is inlined.
1133 The inlined code should include any checks that your type's parent types
1134 do. For example, the C<Value> type's inlining sub looks like this:
1137 'defined(' . $_[1] . ')'
1138 . ' && !ref(' . $_[1] . ')'
1141 Note that it checks if the variable is defined, since it is a subtype of
1142 the C<Defined> type. However, to avoid repeating code, this can be optimized as:
1145 $_[0]->parent()->_inline_check($_[1])
1146 . ' && !ref(' . $_[1] . ')'
1149 =item B<optimize_as { ... }>
1151 B<This feature is deprecated, use C<inline_as> instead.>
1153 This can be used to define a "hand optimized" version of your
1154 type constraint which can be used to avoid traversing a subtype
1155 constraint hierarchy.
1157 B<NOTE:> You should only use this if you know what you are doing.
1158 All the built in types use this, so your subtypes (assuming they
1159 are shallow) will not likely need to use this.
1161 =item B<< type 'Name', where { } ... >>
1163 This creates a base type, which has no parent.
1165 The C<type> function should either be called with the sugar helpers
1166 (C<where>, C<message>, etc), or with a name and a hashref of
1169 type( 'Foo', { where => ..., message => ... } );
1171 The valid hashref keys are C<where>, C<message>, and C<inlined_as>.
1175 =head2 Type Constraint Utilities
1179 =item B<< match_on_type $value => ( $type => \&action, ... ?\&default ) >>
1181 This is a utility function for doing simple type based dispatching similar to
1182 match/case in OCaml and case/of in Haskell. It is not as featureful as those
1183 languages, nor does not it support any kind of automatic destructuring
1184 bind. Here is a simple Perl pretty printer dispatching over the core Moose
1189 match_on_type $x => (
1194 join ", " => map { $_ . ' => ' . ppprint( $hash->{$_} ) }
1200 '[ ' . ( join ", " => map { ppprint($_) } @$array ) . ' ]';
1202 CodeRef => sub {'sub { ... }'},
1203 RegexpRef => sub { 'qr/' . $_ . '/' },
1204 GlobRef => sub { '*' . B::svref_2object($_)->NAME },
1205 Object => sub { $_->can('to_string') ? $_->to_string : $_ },
1206 ScalarRef => sub { '\\' . ppprint( ${$_} ) },
1208 Str => sub { '"' . $_ . '"' },
1209 Undef => sub {'undef'},
1210 => sub { die "I don't know what $_ is" }
1214 Or a simple JSON serializer:
1218 match_on_type $x => (
1224 map { '"' . $_ . '" : ' . to_json( $hash->{$_} ) }
1230 '[ ' . ( join ", " => map { to_json($_) } @$array ) . ' ]';
1233 Str => sub { '"' . $_ . '"' },
1234 Undef => sub {'null'},
1235 => sub { die "$_ is not acceptable json type" }
1239 The matcher is done by mapping a C<$type> to an C<\&action>. The C<$type> can
1240 be either a string type or a L<Moose::Meta::TypeConstraint> object, and
1241 C<\&action> is a subroutine reference. This function will dispatch on the
1242 first match for C<$value>. It is possible to have a catch-all by providing an
1243 additional subroutine reference as the final argument to C<match_on_type>.
1247 =head2 Type Coercion Constructors
1249 You can define coercions for type constraints, which allow you to
1250 automatically transform values to something valid for the type
1251 constraint. If you ask your accessor to coerce, then Moose will run
1252 the type-coercion code first, followed by the type constraint
1253 check. This feature should be used carefully as it is very powerful
1254 and could easily take off a limb if you are not careful.
1256 See the L</SYNOPSIS> for an example of how to use these.
1260 =item B<< coerce 'Name', from 'OtherName', via { ... } >>
1262 This defines a coercion from one type to another. The C<Name> argument
1263 is the type you are coercing I<to>.
1265 To define multiple coercions, supply more sets of from/via pairs:
1268 from 'OtherName', via { ... },
1269 from 'ThirdName', via { ... };
1271 =item B<from 'OtherName'>
1273 This is just sugar for the type coercion construction syntax.
1275 It takes a single type name (or type object), which is the type being
1278 =item B<via { ... }>
1280 This is just sugar for the type coercion construction syntax.
1282 It takes a subroutine reference. This reference will be called with
1283 the value to be coerced in C<$_>. It is expected to return a new value
1284 of the proper type for the coercion.
1288 =head2 Creating and Finding Type Constraints
1290 These are additional functions for creating and finding type
1291 constraints. Most of these functions are not available for
1292 importing. The ones that are importable as specified.
1296 =item B<find_type_constraint($type_name)>
1298 This function can be used to locate the L<Moose::Meta::TypeConstraint>
1299 object for a named type.
1301 This function is importable.
1303 =item B<register_type_constraint($type_object)>
1305 This function will register a L<Moose::Meta::TypeConstraint> with the
1306 global type registry.
1308 This function is importable.
1310 =item B<normalize_type_constraint_name($type_constraint_name)>
1312 This method takes a type constraint name and returns the normalized
1313 form. This removes any whitespace in the string.
1315 =item B<create_type_constraint_union($pipe_separated_types | @type_constraint_names)>
1317 =item B<create_named_type_constraint_union($name, $pipe_separated_types | @type_constraint_names)>
1319 This can take a union type specification like C<'Int|ArrayRef[Int]'>,
1320 or a list of names. It returns a new
1321 L<Moose::Meta::TypeConstraint::Union> object.
1323 =item B<create_type_constraint_intersection ($pipe_separated_types | @type_constraint_names)>
1325 Given string with C<$pipe_separated_types> or a list of C<@type_constraint_names>,
1326 this will return a L<Moose::Meta::TypeConstraint::Intersection> instance.
1328 =item B<create_parameterized_type_constraint($type_name)>
1330 Given a C<$type_name> in the form of C<'BaseType[ContainerType]'>,
1331 this will create a new L<Moose::Meta::TypeConstraint::Parameterized>
1332 object. The C<BaseType> must exist already exist as a parameterizable
1335 =item B<create_class_type_constraint($class, $options)>
1337 Given a class name this function will create a new
1338 L<Moose::Meta::TypeConstraint::Class> object for that class name.
1340 The C<$options> is a hash reference that will be passed to the
1341 L<Moose::Meta::TypeConstraint::Class> constructor (as a hash).
1343 =item B<create_role_type_constraint($role, $options)>
1345 Given a role name this function will create a new
1346 L<Moose::Meta::TypeConstraint::Role> object for that role name.
1348 The C<$options> is a hash reference that will be passed to the
1349 L<Moose::Meta::TypeConstraint::Role> constructor (as a hash).
1351 =item B<create_enum_type_constraint($name, $values)>
1353 Given a enum name this function will create a new
1354 L<Moose::Meta::TypeConstraint::Enum> object for that enum name.
1356 =item B<create_duck_type_constraint($name, $methods)>
1358 Given a duck type name this function will create a new
1359 L<Moose::Meta::TypeConstraint::DuckType> object for that enum name.
1361 =item B<find_or_parse_type_constraint($type_name)>
1363 Given a type name, this first attempts to find a matching constraint
1364 in the global registry.
1366 If the type name is a union or parameterized type, it will create a
1367 new object of the appropriate, but if given a "regular" type that does
1368 not yet exist, it simply returns false.
1370 When given a union or parameterized type, the member or base type must
1373 If it creates a new union or parameterized type, it will add it to the
1376 =item B<find_or_create_isa_type_constraint($type_name)>
1378 =item B<find_or_create_does_type_constraint($type_name)>
1380 These functions will first call C<find_or_parse_type_constraint>. If
1381 that function does not return a type, a new type object will
1384 The C<isa> variant will use C<create_class_type_constraint> and the
1385 C<does> variant will use C<create_role_type_constraint>.
1387 =item B<get_type_constraint_registry>
1389 Returns the L<Moose::Meta::TypeConstraint::Registry> object which
1390 keeps track of all type constraints.
1392 =item B<list_all_type_constraints>
1394 This will return a list of type constraint names in the global
1395 registry. You can then fetch the actual type object using
1396 C<find_type_constraint($type_name)>.
1398 =item B<list_all_builtin_type_constraints>
1400 This will return a list of builtin type constraints, meaning those
1401 which are defined in this module. See the L<Default Type Constraints>
1402 section for a complete list.
1404 =item B<export_type_constraints_as_functions>
1406 This will export all the current type constraints as functions into
1407 the caller's namespace (C<Int()>, C<Str()>, etc). Right now, this is
1408 mostly used for testing, but it might prove useful to others.
1410 =item B<get_all_parameterizable_types>
1412 This returns all the parameterizable types that have been registered,
1413 as a list of type objects.
1415 =item B<add_parameterizable_type($type)>
1417 Adds C<$type> to the list of parameterizable types
1423 See L<Moose/BUGS> for details on reporting bugs.