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::Parameterized;
29 use Moose::Meta::TypeConstraint::Parameterizable;
30 use Moose::Meta::TypeConstraint::Class;
31 use Moose::Meta::TypeConstraint::Role;
32 use Moose::Meta::TypeConstraint::Enum;
33 use Moose::Meta::TypeConstraint::DuckType;
34 use Moose::Meta::TypeCoercion;
35 use Moose::Meta::TypeCoercion::Union;
36 use Moose::Meta::TypeConstraint::Registry;
38 Moose::Exporter->setup_import_methods(
41 type subtype class_type role_type maybe_type duck_type
42 as where message optimize_as inline_as
46 register_type_constraint
51 ## --------------------------------------------------------
52 ## type registry and some useful functions for it
53 ## --------------------------------------------------------
55 my $REGISTRY = Moose::Meta::TypeConstraint::Registry->new;
57 sub get_type_constraint_registry {$REGISTRY}
58 sub list_all_type_constraints { keys %{ $REGISTRY->type_constraints } }
60 sub export_type_constraints_as_functions {
63 foreach my $constraint ( keys %{ $REGISTRY->type_constraints } ) {
64 my $tc = $REGISTRY->get_type_constraint($constraint)
65 ->_compiled_type_constraint;
66 *{"${pkg}::${constraint}"}
67 = sub { $tc->( $_[0] ) ? 1 : undef }; # the undef is for compat
71 sub create_type_constraint_union {
72 _create_type_constraint_union(\@_);
75 sub create_named_type_constraint_union {
77 _create_type_constraint_union($name, \@_);
80 sub _create_type_constraint_union {
82 $name = shift if @_ > 1;
83 my @tcs = @{ shift() };
85 my @type_constraint_names;
87 if ( scalar @tcs == 1 && _detect_type_constraint_union( $tcs[0] ) ) {
88 @type_constraint_names = _parse_type_constraint_union( $tcs[0] );
91 @type_constraint_names = @tcs;
94 ( scalar @type_constraint_names >= 2 )
95 || __PACKAGE__->_throw_error(
96 "You must pass in at least 2 type names to make a union");
98 my @type_constraints = map {
99 find_or_parse_type_constraint($_)
100 || __PACKAGE__->_throw_error(
101 "Could not locate type constraint ($_) for the union");
102 } @type_constraint_names;
105 type_constraints => \@type_constraints
107 $options{name} = $name if defined $name;
109 return Moose::Meta::TypeConstraint::Union->new(%options);
113 sub create_parameterized_type_constraint {
114 my $type_constraint_name = shift;
115 my ( $base_type, $type_parameter )
116 = _parse_parameterized_type_constraint($type_constraint_name);
118 ( defined $base_type && defined $type_parameter )
119 || __PACKAGE__->_throw_error(
120 "Could not parse type name ($type_constraint_name) correctly");
122 if ( $REGISTRY->has_type_constraint($base_type) ) {
123 my $base_type_tc = $REGISTRY->get_type_constraint($base_type);
124 return _create_parameterized_type_constraint(
130 __PACKAGE__->_throw_error(
131 "Could not locate the base type ($base_type)");
135 sub _create_parameterized_type_constraint {
136 my ( $base_type_tc, $type_parameter ) = @_;
137 if ( $base_type_tc->can('parameterize') ) {
138 return $base_type_tc->parameterize($type_parameter);
141 return Moose::Meta::TypeConstraint::Parameterized->new(
142 name => $base_type_tc->name . '[' . $type_parameter . ']',
143 parent => $base_type_tc,
145 find_or_create_isa_type_constraint($type_parameter),
150 #should we also support optimized checks?
151 sub create_class_type_constraint {
152 my ( $class, $options ) = @_;
154 # too early for this check
155 #find_type_constraint("ClassName")->check($class)
156 # || __PACKAGE__->_throw_error("Can't create a class type constraint because '$class' is not a class name");
158 my $pkg_defined_in = scalar( caller(1) );
160 if (my $type = $REGISTRY->get_type_constraint($class)) {
162 "The type constraint '$class' has already been created in "
163 . $type->_package_defined_in
164 . " and cannot be created again in "
171 package_defined_in => $pkg_defined_in,
175 $options{name} ||= "__ANON__";
177 my $tc = Moose::Meta::TypeConstraint::Class->new(%options);
178 $REGISTRY->add_type_constraint($tc);
182 sub create_role_type_constraint {
183 my ( $role, $options ) = @_;
185 # too early for this check
186 #find_type_constraint("ClassName")->check($class)
187 # || __PACKAGE__->_throw_error("Can't create a class type constraint because '$class' is not a class name");
189 my $pkg_defined_in = scalar( caller(1) );
191 if (my $type = $REGISTRY->get_type_constraint($role)) {
193 "The type constraint '$role' has already been created in "
194 . $type->_package_defined_in
195 . " and cannot be created again in "
202 package_defined_in => $pkg_defined_in,
206 $options{name} ||= "__ANON__";
208 my $tc = Moose::Meta::TypeConstraint::Role->new(%options);
209 $REGISTRY->add_type_constraint($tc);
213 sub find_or_create_type_constraint {
214 my ( $type_constraint_name, $options_for_anon_type ) = @_;
217 = find_or_parse_type_constraint($type_constraint_name) ) {
220 elsif ( defined $options_for_anon_type ) {
223 # if there is no $options_for_anon_type
224 # specified, then we assume they don't
225 # want to create one, and return nothing.
227 # otherwise assume that we should create
228 # an ANON type with the $options_for_anon_type
229 # options which can be passed in. It should
230 # be noted that these don't get registered
231 # so we need to return it.
233 return Moose::Meta::TypeConstraint->new(
235 %{$options_for_anon_type}
242 sub find_or_create_isa_type_constraint {
243 my $type_constraint_name = shift;
244 find_or_parse_type_constraint($type_constraint_name)
245 || create_class_type_constraint($type_constraint_name);
248 sub find_or_create_does_type_constraint {
249 my $type_constraint_name = shift;
250 find_or_parse_type_constraint($type_constraint_name)
251 || create_role_type_constraint($type_constraint_name);
254 sub find_or_parse_type_constraint {
255 my $type_constraint_name = normalize_type_constraint_name(shift);
258 if ( $constraint = find_type_constraint($type_constraint_name) ) {
261 elsif ( _detect_type_constraint_union($type_constraint_name) ) {
262 $constraint = create_type_constraint_union($type_constraint_name);
264 elsif ( _detect_parameterized_type_constraint($type_constraint_name) ) {
266 = create_parameterized_type_constraint($type_constraint_name);
272 $REGISTRY->add_type_constraint($constraint);
276 sub normalize_type_constraint_name {
277 my $type_constraint_name = shift;
278 $type_constraint_name =~ s/\s//g;
279 return $type_constraint_name;
285 local $Carp::CarpLevel = $Carp::CarpLevel + 1;
286 Carp::confess($error);
289 ## --------------------------------------------------------
290 ## exported functions ...
291 ## --------------------------------------------------------
293 sub find_type_constraint {
296 if ( blessed $type and $type->isa("Moose::Meta::TypeConstraint") ) {
300 return unless $REGISTRY->has_type_constraint($type);
301 return $REGISTRY->get_type_constraint($type);
305 sub register_type_constraint {
306 my $constraint = shift;
307 __PACKAGE__->_throw_error("can't register an unnamed type constraint")
308 unless defined $constraint->name;
309 $REGISTRY->add_type_constraint($constraint);
318 my %p = map { %{$_} } @_;
320 return _create_type_constraint(
321 $name, undef, $p{where}, $p{message},
322 $p{optimize_as}, $p{inline_as},
327 if ( @_ == 1 && !ref $_[0] ) {
328 __PACKAGE__->_throw_error(
329 'A subtype cannot consist solely of a name, it must have a parent'
333 # The blessed check is mostly to accommodate MooseX::Types, which
334 # uses an object which overloads stringification as a type name.
335 my $name = ref $_[0] && !blessed $_[0] ? undef : shift;
337 my %p = map { %{$_} } @_;
339 # subtype Str => where { ... };
340 if ( !exists $p{as} ) {
345 return _create_type_constraint(
346 $name, $p{as}, $p{where}, $p{message},
347 $p{optimize_as}, $p{inline_as},
352 create_class_type_constraint(@_);
355 sub role_type ($;$) {
356 create_role_type_constraint(@_);
360 my ($type_parameter) = @_;
362 register_type_constraint(
363 $REGISTRY->get_type_constraint('Maybe')->parameterize($type_parameter)
368 my ( $type_name, @methods ) = @_;
369 if ( ref $type_name eq 'ARRAY' && !@methods ) {
370 @methods = @$type_name;
373 if ( @methods == 1 && ref $methods[0] eq 'ARRAY' ) {
374 @methods = @{ $methods[0] };
377 register_type_constraint(
378 create_duck_type_constraint(
386 my ( $type_name, @coercion_map ) = @_;
387 _install_type_coercions( $type_name, \@coercion_map );
390 # The trick of returning @_ lets us avoid having to specify a
391 # prototype. Perl will parse this:
399 # subtype( 'Foo', as( 'Str', where { ... } ) );
401 # If as() returns all its extra arguments, this just works, and
402 # preserves backwards compatibility.
403 sub as { { as => shift }, @_ }
404 sub where (&) { { where => $_[0] } }
405 sub message (&) { { message => $_[0] } }
406 sub optimize_as (&) { { optimize_as => $_[0] } }
407 sub inline_as (&) { { inline_as => $_[0] } }
410 sub via (&) { $_[0] }
413 my ( $type_name, @values ) = @_;
416 # if only an array-ref is passed then
417 # you get an anon-enum
419 if ( ref $type_name eq 'ARRAY' ) {
421 || __PACKAGE__->_throw_error("enum called with an array reference and additional arguments. Did you mean to parenthesize the enum call's parameters?");
423 @values = @$type_name;
426 if ( @values == 1 && ref $values[0] eq 'ARRAY' ) {
427 @values = @{ $values[0] };
430 register_type_constraint(
431 create_enum_type_constraint(
439 my ( $type_name, @constraints ) = @_;
440 if ( ref $type_name eq 'ARRAY' ) {
442 || __PACKAGE__->_throw_error("union called with an array reference and additional arguments.");
443 @constraints = @$type_name;
446 if ( @constraints == 1 && ref $constraints[0] eq 'ARRAY' ) {
447 @constraints = @{ $constraints[0] };
449 if ( defined $type_name ) {
450 return register_type_constraint(
451 create_named_type_constraint_union( $type_name, @constraints )
454 return create_type_constraint_union( @constraints );
457 sub create_enum_type_constraint {
458 my ( $type_name, $values ) = @_;
460 Moose::Meta::TypeConstraint::Enum->new(
461 name => $type_name || '__ANON__',
466 sub create_duck_type_constraint {
467 my ( $type_name, $methods ) = @_;
469 Moose::Meta::TypeConstraint::DuckType->new(
470 name => $type_name || '__ANON__',
476 my ($to_match, @cases) = @_;
478 if (@cases % 2 != 0) {
479 $default = pop @cases;
480 (ref $default eq 'CODE')
481 || __PACKAGE__->_throw_error("Default case must be a CODE ref, not $default");
484 my ($type, $action) = splice @cases, 0, 2;
486 unless (blessed $type && $type->isa('Moose::Meta::TypeConstraint')) {
487 $type = find_or_parse_type_constraint($type)
488 || __PACKAGE__->_throw_error("Cannot find or parse the type '$type'")
491 (ref $action eq 'CODE')
492 || __PACKAGE__->_throw_error("Match action must be a CODE ref, not $action");
494 if ($type->check($to_match)) {
495 local $_ = $to_match;
496 return $action->($to_match);
500 || __PACKAGE__->_throw_error("No cases matched for $to_match");
502 local $_ = $to_match;
503 return $default->($to_match);
508 ## --------------------------------------------------------
509 ## desugaring functions ...
510 ## --------------------------------------------------------
512 sub _create_type_constraint ($$$;$$) {
517 my $optimized = shift;
520 my $pkg_defined_in = scalar( caller(1) );
522 if ( defined $name ) {
523 my $type = $REGISTRY->get_type_constraint($name);
525 ( $type->_package_defined_in eq $pkg_defined_in )
527 "The type constraint '$name' has already been created in "
528 . $type->_package_defined_in
529 . " and cannot be created again in "
533 $name =~ /^[\w:\.]+$/
534 or die qq{$name contains invalid characters for a type name.}
535 . qq{ Names can contain alphanumeric character, ":", and "."\n};
540 package_defined_in => $pkg_defined_in,
542 ( $check ? ( constraint => $check ) : () ),
543 ( $message ? ( message => $message ) : () ),
544 ( $optimized ? ( optimized => $optimized ) : () ),
545 ( $inlined ? ( inlined => $inlined ) : () ),
554 : find_or_create_isa_type_constraint($parent)
556 $constraint = $parent->create_child_type(%opts);
559 $constraint = Moose::Meta::TypeConstraint->new(%opts);
562 $REGISTRY->add_type_constraint($constraint)
568 sub _install_type_coercions ($$) {
569 my ( $type_name, $coercion_map ) = @_;
570 my $type = find_type_constraint($type_name);
572 || __PACKAGE__->_throw_error(
573 "Cannot find type '$type_name', perhaps you forgot to load it");
574 if ( $type->has_coercion ) {
575 $type->coercion->add_type_coercions(@$coercion_map);
578 my $type_coercion = Moose::Meta::TypeCoercion->new(
579 type_coercion_map => $coercion_map,
580 type_constraint => $type
582 $type->coercion($type_coercion);
586 ## --------------------------------------------------------
587 ## type notation parsing ...
588 ## --------------------------------------------------------
592 # All I have to say is mugwump++ cause I know
593 # do not even have enough regexp-fu to be able
594 # to have written this (I can only barely
595 # understand it as it is)
600 my $valid_chars = qr{[\w:\.]};
601 my $type_atom = qr{ (?>$valid_chars+) }x;
602 my $ws = qr{ (?>\s*) }x;
603 my $op_union = qr{ $ws \| $ws }x;
605 my ($type, $type_capture_parts, $type_with_parameter, $union, $any);
606 if (Class::MOP::IS_RUNNING_ON_5_10) {
608 = q{ (?&type_atom) (?: \[ (?&ws) (?&any) (?&ws) \] )? };
609 my $type_capture_parts_pattern
610 = q{ ((?&type_atom)) (?: \[ (?&ws) ((?&any)) (?&ws) \] )? };
611 my $type_with_parameter_pattern
612 = q{ (?&type_atom) \[ (?&ws) (?&any) (?&ws) \] };
614 = q{ (?&type) (?> (?: (?&op_union) (?&type) )+ ) };
616 = q{ (?&type) | (?&union) };
618 my $defines = qr{(?(DEFINE)
619 (?<valid_chars> $valid_chars)
620 (?<type_atom> $type_atom)
622 (?<op_union> $op_union)
623 (?<type> $type_pattern)
624 (?<type_capture_parts> $type_capture_parts_pattern)
625 (?<type_with_parameter> $type_with_parameter_pattern)
626 (?<union> $union_pattern)
627 (?<any> $any_pattern)
630 $type = qr{ $type_pattern $defines }x;
631 $type_capture_parts = qr{ $type_capture_parts_pattern $defines }x;
632 $type_with_parameter = qr{ $type_with_parameter_pattern $defines }x;
633 $union = qr{ $union_pattern $defines }x;
634 $any = qr{ $any_pattern $defines }x;
638 = qr{ $type_atom (?: \[ $ws (??{$any}) $ws \] )? }x;
640 = qr{ ($type_atom) (?: \[ $ws ((??{$any})) $ws \] )? }x;
642 = qr{ $type_atom \[ $ws (??{$any}) $ws \] }x;
644 = qr{ $type (?> (?: $op_union $type )+ ) }x;
646 = qr{ $type | $union }x;
650 sub _parse_parameterized_type_constraint {
651 { no warnings 'void'; $any; } # force capture of interpolated lexical
652 $_[0] =~ m{ $type_capture_parts }x;
656 sub _detect_parameterized_type_constraint {
657 { no warnings 'void'; $any; } # force capture of interpolated lexical
658 $_[0] =~ m{ ^ $type_with_parameter $ }x;
661 sub _parse_type_constraint_union {
662 { no warnings 'void'; $any; } # force capture of interpolated lexical
665 while ( $given =~ m{ \G (?: $op_union )? ($type) }gcx ) {
668 ( pos($given) eq length($given) )
669 || __PACKAGE__->_throw_error( "'$given' didn't parse (parse-pos="
677 sub _detect_type_constraint_union {
678 { no warnings 'void'; $any; } # force capture of interpolated lexical
679 $_[0] =~ m{^ $type $op_union $type ( $op_union .* )? $}x;
683 ## --------------------------------------------------------
684 # define some basic built-in types
685 ## --------------------------------------------------------
687 # By making these classes immutable before creating all the types in
688 # Moose::Util::TypeConstraints::Builtin , we avoid repeatedly calling the slow
689 # MOP-based accessors.
691 inline_constructor => 1,
692 constructor_name => "_new",
694 # these are Class::MOP accessors, so they need inlining
695 inline_accessors => 1
696 ) for grep { $_->is_mutable }
697 map { Class::MOP::class_of($_) }
699 Moose::Meta::TypeConstraint
700 Moose::Meta::TypeConstraint::Union
701 Moose::Meta::TypeConstraint::Parameterized
702 Moose::Meta::TypeConstraint::Parameterizable
703 Moose::Meta::TypeConstraint::Class
704 Moose::Meta::TypeConstraint::Role
705 Moose::Meta::TypeConstraint::Enum
706 Moose::Meta::TypeConstraint::DuckType
707 Moose::Meta::TypeConstraint::Registry
710 require Moose::Util::TypeConstraints::Builtins;
711 Moose::Util::TypeConstraints::Builtins::define_builtins($REGISTRY);
713 my @PARAMETERIZABLE_TYPES
714 = map { $REGISTRY->get_type_constraint($_) } qw[ScalarRef ArrayRef HashRef Maybe];
716 sub get_all_parameterizable_types {@PARAMETERIZABLE_TYPES}
718 sub add_parameterizable_type {
721 && $type->isa('Moose::Meta::TypeConstraint::Parameterizable') )
722 || __PACKAGE__->_throw_error(
723 "Type must be a Moose::Meta::TypeConstraint::Parameterizable not $type"
725 push @PARAMETERIZABLE_TYPES => $type;
728 ## --------------------------------------------------------
729 # end of built-in types ...
730 ## --------------------------------------------------------
733 my @BUILTINS = list_all_type_constraints();
734 sub list_all_builtin_type_constraints {@BUILTINS}
741 goto &Moose::throw_error;
746 # ABSTRACT: Type constraint system for Moose
754 use Moose::Util::TypeConstraints;
760 subtype 'NaturalLessThanTen',
763 message { "This number ($_) is not less than ten!" };
769 class_type 'DateTimeClass', { class => 'DateTime' };
771 role_type 'Barks', { role => 'Some::Library::Role::Barks' };
773 enum 'RGBColors', [qw(red green blue)];
775 union 'StringOrArray', [qw( String Array )];
777 no Moose::Util::TypeConstraints;
781 This module provides Moose with the ability to create custom type
782 constraints to be used in attribute definition.
784 =head2 Important Caveat
786 This is B<NOT> a type system for Perl 5. These are type constraints,
787 and they are not used by Moose unless you tell it to. No type
788 inference is performed, expressions are not typed, etc. etc. etc.
790 A type constraint is at heart a small "check if a value is valid"
791 function. A constraint can be associated with an attribute. This
792 simplifies parameter validation, and makes your code clearer to read,
793 because you can refer to constraints by name.
795 =head2 Slightly Less Important Caveat
797 It is B<always> a good idea to quote your type names.
799 This prevents Perl from trying to execute the call as an indirect
800 object call. This can be an issue when you have a subtype with the
801 same name as a valid class.
805 subtype DateTime => as Object => where { $_->isa('DateTime') };
807 will I<just work>, while this:
810 subtype DateTime => as Object => where { $_->isa('DateTime') };
812 will fail silently and cause many headaches. The simple way to solve
813 this, as well as future proof your subtypes from classes which have
814 yet to have been created, is to quote the type name:
817 subtype 'DateTime', as 'Object', where { $_->isa('DateTime') };
819 =head2 Default Type Constraints
821 This module also provides a simple hierarchy for Perl 5 types, here is
822 that hierarchy represented visually.
846 B<NOTE:> Any type followed by a type parameter C<[`a]> can be
847 parameterized, this means you can say:
849 ArrayRef[Int] # an array of integers
850 HashRef[CodeRef] # a hash of str to CODE ref mappings
851 ScalarRef[Int] # a reference to an integer
852 Maybe[Str] # value may be a string, may be undefined
854 If Moose finds a name in brackets that it does not recognize as an
855 existing type, it assumes that this is a class name, for example
856 C<ArrayRef[DateTime]>.
858 B<NOTE:> Unless you parameterize a type, then it is invalid to include
859 the square brackets. I.e. C<ArrayRef[]> will be treated as a new type
860 name, I<not> as a parameterization of C<ArrayRef>.
862 B<NOTE:> The C<Undef> type constraint for the most part works
863 correctly now, but edge cases may still exist, please use it
866 B<NOTE:> The C<ClassName> type constraint does a complex package
867 existence check. This means that your class B<must> be loaded for this
868 type constraint to pass.
870 B<NOTE:> The C<RoleName> constraint checks a string is a I<package
871 name> which is a role, like C<'MyApp::Role::Comparable'>.
873 =head2 Type Constraint Naming
875 Type name declared via this module can only contain alphanumeric
876 characters, colons (:), and periods (.).
878 Since the types created by this module are global, it is suggested
879 that you namespace your types just as you would namespace your
880 modules. So instead of creating a I<Color> type for your
881 B<My::Graphics> module, you would call the type
882 I<My::Graphics::Types::Color> instead.
884 =head2 Use with Other Constraint Modules
886 This module can play nicely with other constraint modules with some
887 slight tweaking. The C<where> clause in types is expected to be a
888 C<CODE> reference which checks its first argument and returns a
889 boolean. Since most constraint modules work in a similar way, it
890 should be simple to adapt them to work with Moose.
892 For instance, this is how you could use it with
893 L<Declare::Constraints::Simple> to declare a completely new type.
895 type 'HashOfArrayOfObjects',
899 -values => IsArrayRef(IsObject)
903 For more examples see the F<t/examples/example_w_DCS.t> test
906 Here is an example of using L<Test::Deep> and its non-test
907 related C<eq_deeply> function.
909 type 'ArrayOfHashOfBarsAndRandomNumbers',
912 array_each(subhashof({
914 random_number => ignore()
918 For a complete example see the
919 F<t/examples/example_w_TestDeep.t> test file.
921 =head2 Error messages
923 Type constraints can also specify custom error messages, for when they fail to
924 validate. This is provided as just another coderef, which receives the invalid
925 value in C<$_>, as in:
927 subtype 'PositiveInt',
930 message { "$_ is not a positive integer!" };
932 If no message is specified, a default message will be used, which indicates
933 which type constraint was being used and what value failed. If
934 L<Devel::PartialDump> (version 0.14 or higher) is installed, it will be used to
935 display the invalid value, otherwise it will just be printed as is.
939 =head2 Type Constraint Constructors
941 The following functions are used to create type constraints. They
942 will also register the type constraints your create in a global
943 registry that is used to look types up by name.
945 See the L</SYNOPSIS> for an example of how to use these.
949 =item B<< subtype 'Name', as 'Parent', where { } ... >>
951 This creates a named subtype.
953 If you provide a parent that Moose does not recognize, it will
954 automatically create a new class type constraint for this name.
956 When creating a named type, the C<subtype> function should either be
957 called with the sugar helpers (C<where>, C<message>, etc), or with a
958 name and a hashref of parameters:
960 subtype( 'Foo', { where => ..., message => ... } );
962 The valid hashref keys are C<as> (the parent), C<where>, C<message>,
965 =item B<< subtype as 'Parent', where { } ... >>
967 This creates an unnamed subtype and will return the type
968 constraint meta-object, which will be an instance of
969 L<Moose::Meta::TypeConstraint>.
971 When creating an anonymous type, the C<subtype> function should either
972 be called with the sugar helpers (C<where>, C<message>, etc), or with
973 just a hashref of parameters:
975 subtype( { where => ..., message => ... } );
977 =item B<class_type ($class, ?$options)>
979 Creates a new subtype of C<Object> with the name C<$class> and the
980 metaclass L<Moose::Meta::TypeConstraint::Class>.
982 # Create a type called 'Box' which tests for objects which ->isa('Box')
985 By default, the name of the type and the name of the class are the same, but
986 you can specify both separately.
988 # Create a type called 'Box' which tests for objects which ->isa('ObjectLibrary::Box');
989 class_type 'Box', { class => 'ObjectLibrary::Box' };
991 =item B<role_type ($role, ?$options)>
993 Creates a C<Role> type constraint with the name C<$role> and the
994 metaclass L<Moose::Meta::TypeConstraint::Role>.
996 # Create a type called 'Walks' which tests for objects which ->does('Walks')
999 By default, the name of the type and the name of the role are the same, but
1000 you can specify both separately.
1002 # Create a type called 'Walks' which tests for objects which ->does('MooseX::Role::Walks');
1003 role_type 'Walks', { role => 'MooseX::Role::Walks' };
1005 =item B<maybe_type ($type)>
1007 Creates a type constraint for either C<undef> or something of the
1010 =item B<duck_type ($name, \@methods)>
1012 This will create a subtype of Object and test to make sure the value
1013 C<can()> do the methods in C<\@methods>.
1015 This is intended as an easy way to accept non-Moose objects that
1016 provide a certain interface. If you're using Moose classes, we
1017 recommend that you use a C<requires>-only Role instead.
1019 =item B<duck_type (\@methods)>
1021 If passed an ARRAY reference as the only parameter instead of the
1022 C<$name>, C<\@methods> pair, this will create an unnamed duck type.
1023 This can be used in an attribute definition like so:
1027 isa => duck_type( [qw( get_set )] ),
1030 =item B<enum ($name, \@values)>
1032 This will create a basic subtype for a given set of strings.
1033 The resulting constraint will be a subtype of C<Str> and
1034 will match any of the items in C<\@values>. It is case sensitive.
1035 See the L</SYNOPSIS> for a simple example.
1037 B<NOTE:> This is not a true proper enum type, it is simply
1038 a convenient constraint builder.
1040 =item B<enum (\@values)>
1042 If passed an ARRAY reference as the only parameter instead of the
1043 C<$name>, C<\@values> pair, this will create an unnamed enum. This
1044 can then be used in an attribute definition like so:
1046 has 'sort_order' => (
1048 isa => enum([qw[ ascending descending ]]),
1051 =item B<union ($name, \@constraints)>
1053 This will create a basic subtype where any of the provided constraints
1054 may match in order to satisfy this constraint.
1056 =item B<union (\@constraints)>
1058 If passed an ARRAY reference as the only parameter instead of the
1059 C<$name>, C<\@constraints> pair, this will create an unnamed union.
1060 This can then be used in an attribute definition like so:
1064 isa => union([qw[ Str ArrayRef ]]),
1067 This is similar to the existing string union:
1069 isa => 'Str|ArrayRef'
1071 except that it supports anonymous elements as child constraints:
1075 isa => union([ 'Int', enum([qw[ red green blue ]]) ]),
1078 =item B<as 'Parent'>
1080 This is just sugar for the type constraint construction syntax.
1082 It takes a single argument, which is the name of a parent type.
1084 =item B<where { ... }>
1086 This is just sugar for the type constraint construction syntax.
1088 It takes a subroutine reference as an argument. When the type
1089 constraint is tested, the reference is run with the value to be tested
1090 in C<$_>. This reference should return true or false to indicate
1091 whether or not the constraint check passed.
1093 =item B<message { ... }>
1095 This is just sugar for the type constraint construction syntax.
1097 It takes a subroutine reference as an argument. When the type
1098 constraint fails, then the code block is run with the value provided
1099 in C<$_>. This reference should return a string, which will be used in
1100 the text of the exception thrown.
1102 =item B<inline_as { ... }>
1104 This can be used to define a "hand optimized" inlinable version of your type
1107 You provide a subroutine which will be called I<as a method> on a
1108 L<Moose::Meta::TypeConstraint> object. It will receive a single parameter, the
1109 name of the variable to check, typically something like C<"$_"> or C<"$_[0]">.
1111 The subroutine should return a code string suitable for inlining. You can
1112 assume that the check will be wrapped in parentheses when it is inlined.
1114 The inlined code should include any checks that your type's parent types
1115 do. For example, the C<Value> type's inlining sub looks like this:
1118 'defined(' . $_[1] . ')'
1119 . ' && !ref(' . $_[1] . ')'
1122 Note that it checks if the variable is defined, since it is a subtype of
1123 the C<Defined> type. However, to avoid repeating code, this can be optimized as:
1126 $_[0]->parent()->_inline_check($_[1])
1127 . ' && !ref(' . $_[1] . ')'
1130 =item B<optimize_as { ... }>
1132 B<This feature is deprecated, use C<inline_as> instead.>
1134 This can be used to define a "hand optimized" version of your
1135 type constraint which can be used to avoid traversing a subtype
1136 constraint hierarchy.
1138 B<NOTE:> You should only use this if you know what you are doing.
1139 All the built in types use this, so your subtypes (assuming they
1140 are shallow) will not likely need to use this.
1142 =item B<< type 'Name', where { } ... >>
1144 This creates a base type, which has no parent.
1146 The C<type> function should either be called with the sugar helpers
1147 (C<where>, C<message>, etc), or with a name and a hashref of
1150 type( 'Foo', { where => ..., message => ... } );
1152 The valid hashref keys are C<where>, C<message>, and C<inlined_as>.
1156 =head2 Type Constraint Utilities
1160 =item B<< match_on_type $value => ( $type => \&action, ... ?\&default ) >>
1162 This is a utility function for doing simple type based dispatching similar to
1163 match/case in OCaml and case/of in Haskell. It is not as featureful as those
1164 languages, nor does not it support any kind of automatic destructuring
1165 bind. Here is a simple Perl pretty printer dispatching over the core Moose
1170 match_on_type $x => (
1175 join ", " => map { $_ . ' => ' . ppprint( $hash->{$_} ) }
1181 '[ ' . ( join ", " => map { ppprint($_) } @$array ) . ' ]';
1183 CodeRef => sub {'sub { ... }'},
1184 RegexpRef => sub { 'qr/' . $_ . '/' },
1185 GlobRef => sub { '*' . B::svref_2object($_)->NAME },
1186 Object => sub { $_->can('to_string') ? $_->to_string : $_ },
1187 ScalarRef => sub { '\\' . ppprint( ${$_} ) },
1189 Str => sub { '"' . $_ . '"' },
1190 Undef => sub {'undef'},
1191 => sub { die "I don't know what $_ is" }
1195 Or a simple JSON serializer:
1199 match_on_type $x => (
1205 map { '"' . $_ . '" : ' . to_json( $hash->{$_} ) }
1211 '[ ' . ( join ", " => map { to_json($_) } @$array ) . ' ]';
1214 Str => sub { '"' . $_ . '"' },
1215 Undef => sub {'null'},
1216 => sub { die "$_ is not acceptable json type" }
1220 The matcher is done by mapping a C<$type> to an C<\&action>. The C<$type> can
1221 be either a string type or a L<Moose::Meta::TypeConstraint> object, and
1222 C<\&action> is a subroutine reference. This function will dispatch on the
1223 first match for C<$value>. It is possible to have a catch-all by providing an
1224 additional subroutine reference as the final argument to C<match_on_type>.
1228 =head2 Type Coercion Constructors
1230 You can define coercions for type constraints, which allow you to
1231 automatically transform values to something valid for the type
1232 constraint. If you ask your accessor to coerce, then Moose will run
1233 the type-coercion code first, followed by the type constraint
1234 check. This feature should be used carefully as it is very powerful
1235 and could easily take off a limb if you are not careful.
1237 See the L</SYNOPSIS> for an example of how to use these.
1241 =item B<< coerce 'Name', from 'OtherName', via { ... } >>
1243 This defines a coercion from one type to another. The C<Name> argument
1244 is the type you are coercing I<to>.
1246 To define multiple coercions, supply more sets of from/via pairs:
1249 from 'OtherName', via { ... },
1250 from 'ThirdName', via { ... };
1252 =item B<from 'OtherName'>
1254 This is just sugar for the type coercion construction syntax.
1256 It takes a single type name (or type object), which is the type being
1259 =item B<via { ... }>
1261 This is just sugar for the type coercion construction syntax.
1263 It takes a subroutine reference. This reference will be called with
1264 the value to be coerced in C<$_>. It is expected to return a new value
1265 of the proper type for the coercion.
1269 =head2 Creating and Finding Type Constraints
1271 These are additional functions for creating and finding type
1272 constraints. Most of these functions are not available for
1273 importing. The ones that are importable as specified.
1277 =item B<find_type_constraint($type_name)>
1279 This function can be used to locate the L<Moose::Meta::TypeConstraint>
1280 object for a named type.
1282 This function is importable.
1284 =item B<register_type_constraint($type_object)>
1286 This function will register a L<Moose::Meta::TypeConstraint> with the
1287 global type registry.
1289 This function is importable.
1291 =item B<normalize_type_constraint_name($type_constraint_name)>
1293 This method takes a type constraint name and returns the normalized
1294 form. This removes any whitespace in the string.
1296 =item B<create_type_constraint_union($pipe_separated_types | @type_constraint_names)>
1298 =item B<create_named_type_constraint_union($name, $pipe_separated_types | @type_constraint_names)>
1300 This can take a union type specification like C<'Int|ArrayRef[Int]'>,
1301 or a list of names. It returns a new
1302 L<Moose::Meta::TypeConstraint::Union> object.
1304 =item B<create_parameterized_type_constraint($type_name)>
1306 Given a C<$type_name> in the form of C<'BaseType[ContainerType]'>,
1307 this will create a new L<Moose::Meta::TypeConstraint::Parameterized>
1308 object. The C<BaseType> must exist already exist as a parameterizable
1311 =item B<create_class_type_constraint($class, $options)>
1313 Given a class name this function will create a new
1314 L<Moose::Meta::TypeConstraint::Class> object for that class name.
1316 The C<$options> is a hash reference that will be passed to the
1317 L<Moose::Meta::TypeConstraint::Class> constructor (as a hash).
1319 =item B<create_role_type_constraint($role, $options)>
1321 Given a role name this function will create a new
1322 L<Moose::Meta::TypeConstraint::Role> object for that role name.
1324 The C<$options> is a hash reference that will be passed to the
1325 L<Moose::Meta::TypeConstraint::Role> constructor (as a hash).
1327 =item B<create_enum_type_constraint($name, $values)>
1329 Given a enum name this function will create a new
1330 L<Moose::Meta::TypeConstraint::Enum> object for that enum name.
1332 =item B<create_duck_type_constraint($name, $methods)>
1334 Given a duck type name this function will create a new
1335 L<Moose::Meta::TypeConstraint::DuckType> object for that enum name.
1337 =item B<find_or_parse_type_constraint($type_name)>
1339 Given a type name, this first attempts to find a matching constraint
1340 in the global registry.
1342 If the type name is a union or parameterized type, it will create a
1343 new object of the appropriate, but if given a "regular" type that does
1344 not yet exist, it simply returns false.
1346 When given a union or parameterized type, the member or base type must
1349 If it creates a new union or parameterized type, it will add it to the
1352 =item B<find_or_create_isa_type_constraint($type_name)>
1354 =item B<find_or_create_does_type_constraint($type_name)>
1356 These functions will first call C<find_or_parse_type_constraint>. If
1357 that function does not return a type, a new type object will
1360 The C<isa> variant will use C<create_class_type_constraint> and the
1361 C<does> variant will use C<create_role_type_constraint>.
1363 =item B<get_type_constraint_registry>
1365 Returns the L<Moose::Meta::TypeConstraint::Registry> object which
1366 keeps track of all type constraints.
1368 =item B<list_all_type_constraints>
1370 This will return a list of type constraint names in the global
1371 registry. You can then fetch the actual type object using
1372 C<find_type_constraint($type_name)>.
1374 =item B<list_all_builtin_type_constraints>
1376 This will return a list of builtin type constraints, meaning those
1377 which are defined in this module. See the L<Default Type Constraints>
1378 section for a complete list.
1380 =item B<export_type_constraints_as_functions>
1382 This will export all the current type constraints as functions into
1383 the caller's namespace (C<Int()>, C<Str()>, etc). Right now, this is
1384 mostly used for testing, but it might prove useful to others.
1386 =item B<get_all_parameterizable_types>
1388 This returns all the parameterizable types that have been registered,
1389 as a list of type objects.
1391 =item B<add_parameterizable_type($type)>
1393 Adds C<$type> to the list of parameterizable types
1399 See L<Moose/BUGS> for details on reporting bugs.