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 my @type_constraint_names;
74 if ( scalar @_ == 1 && _detect_type_constraint_union( $_[0] ) ) {
75 @type_constraint_names = _parse_type_constraint_union( $_[0] );
78 @type_constraint_names = @_;
81 ( scalar @type_constraint_names >= 2 )
82 || __PACKAGE__->_throw_error(
83 "You must pass in at least 2 type names to make a union");
85 my @type_constraints = map {
86 find_or_parse_type_constraint($_)
87 || __PACKAGE__->_throw_error(
88 "Could not locate type constraint ($_) for the union");
89 } @type_constraint_names;
91 return Moose::Meta::TypeConstraint::Union->new(
92 type_constraints => \@type_constraints );
95 sub create_named_type_constraint_union {
97 my @type_constraint_names;
99 if ( scalar @_ == 1 && _detect_type_constraint_union( $_[0] ) ) {
100 @type_constraint_names = _parse_type_constraint_union( $_[0] );
103 @type_constraint_names = @_;
106 ( scalar @type_constraint_names >= 2 )
107 || __PACKAGE__->_throw_error(
108 "You must pass in at least 2 type names to make a union");
110 my @type_constraints = map {
111 find_or_parse_type_constraint($_)
112 || __PACKAGE__->_throw_error(
113 "Could not locate type constraint ($_) for the union");
114 } @type_constraint_names;
117 type_constraints => \@type_constraints
119 $options{name} = $name if defined $name;
121 return Moose::Meta::TypeConstraint::Union->new(%options);
125 sub create_parameterized_type_constraint {
126 my $type_constraint_name = shift;
127 my ( $base_type, $type_parameter )
128 = _parse_parameterized_type_constraint($type_constraint_name);
130 ( defined $base_type && defined $type_parameter )
131 || __PACKAGE__->_throw_error(
132 "Could not parse type name ($type_constraint_name) correctly");
134 if ( $REGISTRY->has_type_constraint($base_type) ) {
135 my $base_type_tc = $REGISTRY->get_type_constraint($base_type);
136 return _create_parameterized_type_constraint(
142 __PACKAGE__->_throw_error(
143 "Could not locate the base type ($base_type)");
147 sub _create_parameterized_type_constraint {
148 my ( $base_type_tc, $type_parameter ) = @_;
149 if ( $base_type_tc->can('parameterize') ) {
150 return $base_type_tc->parameterize($type_parameter);
153 return Moose::Meta::TypeConstraint::Parameterized->new(
154 name => $base_type_tc->name . '[' . $type_parameter . ']',
155 parent => $base_type_tc,
157 find_or_create_isa_type_constraint($type_parameter),
162 #should we also support optimized checks?
163 sub create_class_type_constraint {
164 my ( $class, $options ) = @_;
166 # too early for this check
167 #find_type_constraint("ClassName")->check($class)
168 # || __PACKAGE__->_throw_error("Can't create a class type constraint because '$class' is not a class name");
176 $options{name} ||= "__ANON__";
178 Moose::Meta::TypeConstraint::Class->new(%options);
181 sub create_role_type_constraint {
182 my ( $role, $options ) = @_;
184 # too early for this check
185 #find_type_constraint("ClassName")->check($class)
186 # || __PACKAGE__->_throw_error("Can't create a class type constraint because '$class' is not a class name");
194 $options{name} ||= "__ANON__";
196 Moose::Meta::TypeConstraint::Role->new(%options);
199 sub find_or_create_type_constraint {
200 my ( $type_constraint_name, $options_for_anon_type ) = @_;
203 = find_or_parse_type_constraint($type_constraint_name) ) {
206 elsif ( defined $options_for_anon_type ) {
209 # if there is no $options_for_anon_type
210 # specified, then we assume they don't
211 # want to create one, and return nothing.
213 # otherwise assume that we should create
214 # an ANON type with the $options_for_anon_type
215 # options which can be passed in. It should
216 # be noted that these don't get registered
217 # so we need to return it.
219 return Moose::Meta::TypeConstraint->new(
221 %{$options_for_anon_type}
228 sub find_or_create_isa_type_constraint {
229 my $type_constraint_name = shift;
230 find_or_parse_type_constraint($type_constraint_name)
231 || create_class_type_constraint($type_constraint_name);
234 sub find_or_create_does_type_constraint {
235 my $type_constraint_name = shift;
236 find_or_parse_type_constraint($type_constraint_name)
237 || create_role_type_constraint($type_constraint_name);
240 sub find_or_parse_type_constraint {
241 my $type_constraint_name = normalize_type_constraint_name(shift);
244 if ( $constraint = find_type_constraint($type_constraint_name) ) {
247 elsif ( _detect_type_constraint_union($type_constraint_name) ) {
248 $constraint = create_type_constraint_union($type_constraint_name);
250 elsif ( _detect_parameterized_type_constraint($type_constraint_name) ) {
252 = create_parameterized_type_constraint($type_constraint_name);
258 $REGISTRY->add_type_constraint($constraint);
262 sub normalize_type_constraint_name {
263 my $type_constraint_name = shift;
264 $type_constraint_name =~ s/\s//g;
265 return $type_constraint_name;
271 local $Carp::CarpLevel = $Carp::CarpLevel + 1;
272 Carp::confess($error);
275 ## --------------------------------------------------------
276 ## exported functions ...
277 ## --------------------------------------------------------
279 sub find_type_constraint {
282 if ( blessed $type and $type->isa("Moose::Meta::TypeConstraint") ) {
286 return unless $REGISTRY->has_type_constraint($type);
287 return $REGISTRY->get_type_constraint($type);
291 sub register_type_constraint {
292 my $constraint = shift;
293 __PACKAGE__->_throw_error("can't register an unnamed type constraint")
294 unless defined $constraint->name;
295 $REGISTRY->add_type_constraint($constraint);
304 my %p = map { %{$_} } @_;
306 return _create_type_constraint(
307 $name, undef, $p{where}, $p{message},
308 $p{optimize_as}, $p{inline_as},
313 if ( @_ == 1 && !ref $_[0] ) {
314 __PACKAGE__->_throw_error(
315 'A subtype cannot consist solely of a name, it must have a parent'
319 # The blessed check is mostly to accommodate MooseX::Types, which
320 # uses an object which overloads stringification as a type name.
321 my $name = ref $_[0] && !blessed $_[0] ? undef : shift;
323 my %p = map { %{$_} } @_;
325 # subtype Str => where { ... };
326 if ( !exists $p{as} ) {
331 return _create_type_constraint(
332 $name, $p{as}, $p{where}, $p{message},
333 $p{optimize_as}, $p{inline_as},
338 register_type_constraint(
339 create_class_type_constraint(
341 ( defined( $_[1] ) ? $_[1] : () ),
346 sub role_type ($;$) {
347 register_type_constraint(
348 create_role_type_constraint(
350 ( defined( $_[1] ) ? $_[1] : () ),
356 my ($type_parameter) = @_;
358 register_type_constraint(
359 $REGISTRY->get_type_constraint('Maybe')->parameterize($type_parameter)
364 my ( $type_name, @methods ) = @_;
365 if ( ref $type_name eq 'ARRAY' && !@methods ) {
366 @methods = @$type_name;
369 if ( @methods == 1 && ref $methods[0] eq 'ARRAY' ) {
370 @methods = @{ $methods[0] };
373 register_type_constraint(
374 create_duck_type_constraint(
382 my ( $type_name, @coercion_map ) = @_;
383 _install_type_coercions( $type_name, \@coercion_map );
386 # The trick of returning @_ lets us avoid having to specify a
387 # prototype. Perl will parse this:
395 # subtype( 'Foo', as( 'Str', where { ... } ) );
397 # If as() returns all its extra arguments, this just works, and
398 # preserves backwards compatibility.
399 sub as { { as => shift }, @_ }
400 sub where (&) { { where => $_[0] } }
401 sub message (&) { { message => $_[0] } }
402 sub optimize_as (&) { { optimize_as => $_[0] } }
403 sub inline_as (&) { { inline_as => $_[0] } }
406 sub via (&) { $_[0] }
409 my ( $type_name, @values ) = @_;
412 # if only an array-ref is passed then
413 # you get an anon-enum
415 if ( ref $type_name eq 'ARRAY' ) {
417 || __PACKAGE__->_throw_error("enum called with an array reference and additional arguments. Did you mean to parenthesize the enum call's parameters?");
419 @values = @$type_name;
422 if ( @values == 1 && ref $values[0] eq 'ARRAY' ) {
423 @values = @{ $values[0] };
426 register_type_constraint(
427 create_enum_type_constraint(
435 my ( $type_name, @constraints ) = @_;
436 if ( ref $type_name eq 'ARRAY' ) {
438 || __PACKAGE__->_throw_error("union called with an array reference and additional arguments.");
439 @constraints = @$type_name;
442 if ( @constraints == 1 && ref $constraints[0] eq 'ARRAY' ) {
443 @constraints = @{ $constraints[0] };
445 if ( defined $type_name ) {
446 return register_type_constraint(
447 create_named_type_constraint_union( $type_name, @constraints )
450 return create_type_constraint_union( @constraints );
453 sub create_enum_type_constraint {
454 my ( $type_name, $values ) = @_;
456 Moose::Meta::TypeConstraint::Enum->new(
457 name => $type_name || '__ANON__',
462 sub create_duck_type_constraint {
463 my ( $type_name, $methods ) = @_;
465 Moose::Meta::TypeConstraint::DuckType->new(
466 name => $type_name || '__ANON__',
472 my ($to_match, @cases) = @_;
474 if (@cases % 2 != 0) {
475 $default = pop @cases;
476 (ref $default eq 'CODE')
477 || __PACKAGE__->_throw_error("Default case must be a CODE ref, not $default");
480 my ($type, $action) = splice @cases, 0, 2;
482 unless (blessed $type && $type->isa('Moose::Meta::TypeConstraint')) {
483 $type = find_or_parse_type_constraint($type)
484 || __PACKAGE__->_throw_error("Cannot find or parse the type '$type'")
487 (ref $action eq 'CODE')
488 || __PACKAGE__->_throw_error("Match action must be a CODE ref, not $action");
490 if ($type->check($to_match)) {
491 local $_ = $to_match;
492 return $action->($to_match);
496 || __PACKAGE__->_throw_error("No cases matched for $to_match");
498 local $_ = $to_match;
499 return $default->($to_match);
504 ## --------------------------------------------------------
505 ## desugaring functions ...
506 ## --------------------------------------------------------
508 sub _create_type_constraint ($$$;$$) {
513 my $optimized = shift;
516 my $pkg_defined_in = scalar( caller(1) );
518 if ( defined $name ) {
519 my $type = $REGISTRY->get_type_constraint($name);
521 ( $type->_package_defined_in eq $pkg_defined_in )
523 "The type constraint '$name' has already been created in "
524 . $type->_package_defined_in
525 . " and cannot be created again in "
529 $name =~ /^[\w:\.]+$/
530 or die qq{$name contains invalid characters for a type name.}
531 . qq{ Names can contain alphanumeric character, ":", and "."\n};
536 package_defined_in => $pkg_defined_in,
538 ( $check ? ( constraint => $check ) : () ),
539 ( $message ? ( message => $message ) : () ),
540 ( $optimized ? ( optimized => $optimized ) : () ),
541 ( $inlined ? ( inlined => $inlined ) : () ),
550 : find_or_create_isa_type_constraint($parent)
552 $constraint = $parent->create_child_type(%opts);
555 $constraint = Moose::Meta::TypeConstraint->new(%opts);
558 $REGISTRY->add_type_constraint($constraint)
564 sub _install_type_coercions ($$) {
565 my ( $type_name, $coercion_map ) = @_;
566 my $type = find_type_constraint($type_name);
568 || __PACKAGE__->_throw_error(
569 "Cannot find type '$type_name', perhaps you forgot to load it");
570 if ( $type->has_coercion ) {
571 $type->coercion->add_type_coercions(@$coercion_map);
574 my $type_coercion = Moose::Meta::TypeCoercion->new(
575 type_coercion_map => $coercion_map,
576 type_constraint => $type
578 $type->coercion($type_coercion);
582 ## --------------------------------------------------------
583 ## type notation parsing ...
584 ## --------------------------------------------------------
588 # All I have to say is mugwump++ cause I know
589 # do not even have enough regexp-fu to be able
590 # to have written this (I can only barely
591 # understand it as it is)
596 my $valid_chars = qr{[\w:\.]};
597 my $type_atom = qr{ (?>$valid_chars+) }x;
598 my $ws = qr{ (?>\s*) }x;
599 my $op_union = qr{ $ws \| $ws }x;
601 my ($type, $type_capture_parts, $type_with_parameter, $union, $any);
602 if (Class::MOP::IS_RUNNING_ON_5_10) {
604 = q{ (?&type_atom) (?: \[ (?&ws) (?&any) (?&ws) \] )? };
605 my $type_capture_parts_pattern
606 = q{ ((?&type_atom)) (?: \[ (?&ws) ((?&any)) (?&ws) \] )? };
607 my $type_with_parameter_pattern
608 = q{ (?&type_atom) \[ (?&ws) (?&any) (?&ws) \] };
610 = q{ (?&type) (?> (?: (?&op_union) (?&type) )+ ) };
612 = q{ (?&type) | (?&union) };
614 my $defines = qr{(?(DEFINE)
615 (?<valid_chars> $valid_chars)
616 (?<type_atom> $type_atom)
618 (?<op_union> $op_union)
619 (?<type> $type_pattern)
620 (?<type_capture_parts> $type_capture_parts_pattern)
621 (?<type_with_parameter> $type_with_parameter_pattern)
622 (?<union> $union_pattern)
623 (?<any> $any_pattern)
626 $type = qr{ $type_pattern $defines }x;
627 $type_capture_parts = qr{ $type_capture_parts_pattern $defines }x;
628 $type_with_parameter = qr{ $type_with_parameter_pattern $defines }x;
629 $union = qr{ $union_pattern $defines }x;
630 $any = qr{ $any_pattern $defines }x;
634 = qr{ $type_atom (?: \[ $ws (??{$any}) $ws \] )? }x;
636 = qr{ ($type_atom) (?: \[ $ws ((??{$any})) $ws \] )? }x;
638 = qr{ $type_atom \[ $ws (??{$any}) $ws \] }x;
640 = qr{ $type (?> (?: $op_union $type )+ ) }x;
642 = qr{ $type | $union }x;
646 sub _parse_parameterized_type_constraint {
647 { no warnings 'void'; $any; } # force capture of interpolated lexical
648 $_[0] =~ m{ $type_capture_parts }x;
652 sub _detect_parameterized_type_constraint {
653 { no warnings 'void'; $any; } # force capture of interpolated lexical
654 $_[0] =~ m{ ^ $type_with_parameter $ }x;
657 sub _parse_type_constraint_union {
658 { no warnings 'void'; $any; } # force capture of interpolated lexical
661 while ( $given =~ m{ \G (?: $op_union )? ($type) }gcx ) {
664 ( pos($given) eq length($given) )
665 || __PACKAGE__->_throw_error( "'$given' didn't parse (parse-pos="
673 sub _detect_type_constraint_union {
674 { no warnings 'void'; $any; } # force capture of interpolated lexical
675 $_[0] =~ m{^ $type $op_union $type ( $op_union .* )? $}x;
679 ## --------------------------------------------------------
680 # define some basic built-in types
681 ## --------------------------------------------------------
683 # By making these classes immutable before creating all the types in
684 # Moose::Util::TypeConstraints::Builtin , we avoid repeatedly calling the slow
685 # MOP-based accessors.
687 inline_constructor => 1,
688 constructor_name => "_new",
690 # these are Class::MOP accessors, so they need inlining
691 inline_accessors => 1
692 ) for grep { $_->is_mutable }
693 map { Class::MOP::class_of($_) }
695 Moose::Meta::TypeConstraint
696 Moose::Meta::TypeConstraint::Union
697 Moose::Meta::TypeConstraint::Parameterized
698 Moose::Meta::TypeConstraint::Parameterizable
699 Moose::Meta::TypeConstraint::Class
700 Moose::Meta::TypeConstraint::Role
701 Moose::Meta::TypeConstraint::Enum
702 Moose::Meta::TypeConstraint::DuckType
703 Moose::Meta::TypeConstraint::Registry
706 require Moose::Util::TypeConstraints::Builtins;
707 Moose::Util::TypeConstraints::Builtins::define_builtins($REGISTRY);
709 my @PARAMETERIZABLE_TYPES
710 = map { $REGISTRY->get_type_constraint($_) } qw[ScalarRef ArrayRef HashRef Maybe];
712 sub get_all_parameterizable_types {@PARAMETERIZABLE_TYPES}
714 sub add_parameterizable_type {
717 && $type->isa('Moose::Meta::TypeConstraint::Parameterizable') )
718 || __PACKAGE__->_throw_error(
719 "Type must be a Moose::Meta::TypeConstraint::Parameterizable not $type"
721 push @PARAMETERIZABLE_TYPES => $type;
724 ## --------------------------------------------------------
725 # end of built-in types ...
726 ## --------------------------------------------------------
729 my @BUILTINS = list_all_type_constraints();
730 sub list_all_builtin_type_constraints {@BUILTINS}
737 goto &Moose::throw_error;
742 # ABSTRACT: Type constraint system for Moose
750 use Moose::Util::TypeConstraints;
756 subtype 'NaturalLessThanTen',
759 message { "This number ($_) is not less than ten!" };
765 enum 'RGBColors', [qw(red green blue)];
767 no Moose::Util::TypeConstraints;
771 This module provides Moose with the ability to create custom type
772 constraints to be used in attribute definition.
774 =head2 Important Caveat
776 This is B<NOT> a type system for Perl 5. These are type constraints,
777 and they are not used by Moose unless you tell it to. No type
778 inference is performed, expressions are not typed, etc. etc. etc.
780 A type constraint is at heart a small "check if a value is valid"
781 function. A constraint can be associated with an attribute. This
782 simplifies parameter validation, and makes your code clearer to read,
783 because you can refer to constraints by name.
785 =head2 Slightly Less Important Caveat
787 It is B<always> a good idea to quote your type names.
789 This prevents Perl from trying to execute the call as an indirect
790 object call. This can be an issue when you have a subtype with the
791 same name as a valid class.
795 subtype DateTime => as Object => where { $_->isa('DateTime') };
797 will I<just work>, while this:
800 subtype DateTime => as Object => where { $_->isa('DateTime') };
802 will fail silently and cause many headaches. The simple way to solve
803 this, as well as future proof your subtypes from classes which have
804 yet to have been created, is to quote the type name:
807 subtype 'DateTime', as 'Object', where { $_->isa('DateTime') };
809 =head2 Default Type Constraints
811 This module also provides a simple hierarchy for Perl 5 types, here is
812 that hierarchy represented visually.
836 B<NOTE:> Any type followed by a type parameter C<[`a]> can be
837 parameterized, this means you can say:
839 ArrayRef[Int] # an array of integers
840 HashRef[CodeRef] # a hash of str to CODE ref mappings
841 ScalarRef[Int] # a reference to an integer
842 Maybe[Str] # value may be a string, may be undefined
844 If Moose finds a name in brackets that it does not recognize as an
845 existing type, it assumes that this is a class name, for example
846 C<ArrayRef[DateTime]>.
848 B<NOTE:> Unless you parameterize a type, then it is invalid to include
849 the square brackets. I.e. C<ArrayRef[]> will be treated as a new type
850 name, I<not> as a parameterization of C<ArrayRef>.
852 B<NOTE:> The C<Undef> type constraint for the most part works
853 correctly now, but edge cases may still exist, please use it
856 B<NOTE:> The C<ClassName> type constraint does a complex package
857 existence check. This means that your class B<must> be loaded for this
858 type constraint to pass.
860 B<NOTE:> The C<RoleName> constraint checks a string is a I<package
861 name> which is a role, like C<'MyApp::Role::Comparable'>.
863 =head2 Type Constraint Naming
865 Type name declared via this module can only contain alphanumeric
866 characters, colons (:), and periods (.).
868 Since the types created by this module are global, it is suggested
869 that you namespace your types just as you would namespace your
870 modules. So instead of creating a I<Color> type for your
871 B<My::Graphics> module, you would call the type
872 I<My::Graphics::Types::Color> instead.
874 =head2 Use with Other Constraint Modules
876 This module can play nicely with other constraint modules with some
877 slight tweaking. The C<where> clause in types is expected to be a
878 C<CODE> reference which checks its first argument and returns a
879 boolean. Since most constraint modules work in a similar way, it
880 should be simple to adapt them to work with Moose.
882 For instance, this is how you could use it with
883 L<Declare::Constraints::Simple> to declare a completely new type.
885 type 'HashOfArrayOfObjects',
889 -values => IsArrayRef(IsObject)
893 For more examples see the F<t/examples/example_w_DCS.t> test
896 Here is an example of using L<Test::Deep> and its non-test
897 related C<eq_deeply> function.
899 type 'ArrayOfHashOfBarsAndRandomNumbers',
902 array_each(subhashof({
904 random_number => ignore()
908 For a complete example see the
909 F<t/examples/example_w_TestDeep.t> test file.
911 =head2 Error messages
913 Type constraints can also specify custom error messages, for when they fail to
914 validate. This is provided as just another coderef, which receives the invalid
915 value in C<$_>, as in:
917 subtype 'PositiveInt',
920 message { "$_ is not a positive integer!" };
922 If no message is specified, a default message will be used, which indicates
923 which type constraint was being used and what value failed. If
924 L<Devel::PartialDump> (version 0.14 or higher) is installed, it will be used to
925 display the invalid value, otherwise it will just be printed as is.
929 =head2 Type Constraint Constructors
931 The following functions are used to create type constraints. They
932 will also register the type constraints your create in a global
933 registry that is used to look types up by name.
935 See the L</SYNOPSIS> for an example of how to use these.
939 =item B<< subtype 'Name', as 'Parent', where { } ... >>
941 This creates a named subtype.
943 If you provide a parent that Moose does not recognize, it will
944 automatically create a new class type constraint for this name.
946 When creating a named type, the C<subtype> function should either be
947 called with the sugar helpers (C<where>, C<message>, etc), or with a
948 name and a hashref of parameters:
950 subtype( 'Foo', { where => ..., message => ... } );
952 The valid hashref keys are C<as> (the parent), C<where>, C<message>,
955 =item B<< subtype as 'Parent', where { } ... >>
957 This creates an unnamed subtype and will return the type
958 constraint meta-object, which will be an instance of
959 L<Moose::Meta::TypeConstraint>.
961 When creating an anonymous type, the C<subtype> function should either
962 be called with the sugar helpers (C<where>, C<message>, etc), or with
963 just a hashref of parameters:
965 subtype( { where => ..., message => ... } );
967 =item B<class_type ($class, ?$options)>
969 Creates a new subtype of C<Object> with the name C<$class> and the
970 metaclass L<Moose::Meta::TypeConstraint::Class>.
972 =item B<role_type ($role, ?$options)>
974 Creates a C<Role> type constraint with the name C<$role> and the
975 metaclass L<Moose::Meta::TypeConstraint::Role>.
977 =item B<maybe_type ($type)>
979 Creates a type constraint for either C<undef> or something of the
982 =item B<duck_type ($name, \@methods)>
984 This will create a subtype of Object and test to make sure the value
985 C<can()> do the methods in C<\@methods>.
987 This is intended as an easy way to accept non-Moose objects that
988 provide a certain interface. If you're using Moose classes, we
989 recommend that you use a C<requires>-only Role instead.
991 =item B<duck_type (\@methods)>
993 If passed an ARRAY reference as the only parameter instead of the
994 C<$name>, C<\@methods> pair, this will create an unnamed duck type.
995 This can be used in an attribute definition like so:
999 isa => duck_type( [qw( get_set )] ),
1002 =item B<enum ($name, \@values)>
1004 This will create a basic subtype for a given set of strings.
1005 The resulting constraint will be a subtype of C<Str> and
1006 will match any of the items in C<\@values>. It is case sensitive.
1007 See the L</SYNOPSIS> for a simple example.
1009 B<NOTE:> This is not a true proper enum type, it is simply
1010 a convenient constraint builder.
1012 =item B<enum (\@values)>
1014 If passed an ARRAY reference as the only parameter instead of the
1015 C<$name>, C<\@values> pair, this will create an unnamed enum. This
1016 can then be used in an attribute definition like so:
1018 has 'sort_order' => (
1020 isa => enum([qw[ ascending descending ]]),
1023 =item B<as 'Parent'>
1025 This is just sugar for the type constraint construction syntax.
1027 It takes a single argument, which is the name of a parent type.
1029 =item B<where { ... }>
1031 This is just sugar for the type constraint construction syntax.
1033 It takes a subroutine reference as an argument. When the type
1034 constraint is tested, the reference is run with the value to be tested
1035 in C<$_>. This reference should return true or false to indicate
1036 whether or not the constraint check passed.
1038 =item B<message { ... }>
1040 This is just sugar for the type constraint construction syntax.
1042 It takes a subroutine reference as an argument. When the type
1043 constraint fails, then the code block is run with the value provided
1044 in C<$_>. This reference should return a string, which will be used in
1045 the text of the exception thrown.
1047 =item B<inline_as { ... }>
1049 This can be used to define a "hand optimized" inlinable version of your type
1052 You provide a subroutine which will be called I<as a method> on a
1053 L<Moose::Meta::TypeConstraint> object. It will receive a single parameter, the
1054 name of the variable to check, typically something like C<"$_"> or C<"$_[0]">.
1056 The subroutine should return a code string suitable for inlining. You can
1057 assume that the check will be wrapped in parentheses when it is inlined.
1059 The inlined code should include any checks that your type's parent types
1060 do. For example, the C<Value> type's inlining sub looks like this:
1063 'defined(' . $_[1] . ')'
1064 . ' && !ref(' . $_[1] . ')'
1067 Note that it checks if the variable is defined, since it is a subtype of
1068 the C<Defined> type. However, to avoid repeating code, this can be optimized as:
1071 $_[0]->parent()->_inline_check($_[1])
1072 . ' && !ref(' . $_[1] . ')'
1075 =item B<optimize_as { ... }>
1077 B<This feature is deprecated, use C<inline_as> instead.>
1079 This can be used to define a "hand optimized" version of your
1080 type constraint which can be used to avoid traversing a subtype
1081 constraint hierarchy.
1083 B<NOTE:> You should only use this if you know what you are doing.
1084 All the built in types use this, so your subtypes (assuming they
1085 are shallow) will not likely need to use this.
1087 =item B<< type 'Name', where { } ... >>
1089 This creates a base type, which has no parent.
1091 The C<type> function should either be called with the sugar helpers
1092 (C<where>, C<message>, etc), or with a name and a hashref of
1095 type( 'Foo', { where => ..., message => ... } );
1097 The valid hashref keys are C<where>, C<message>, and C<inlined_as>.
1101 =head2 Type Constraint Utilities
1105 =item B<< match_on_type $value => ( $type => \&action, ... ?\&default ) >>
1107 This is a utility function for doing simple type based dispatching similar to
1108 match/case in OCaml and case/of in Haskell. It is not as featureful as those
1109 languages, nor does not it support any kind of automatic destructuring
1110 bind. Here is a simple Perl pretty printer dispatching over the core Moose
1115 match_on_type $x => (
1120 join ", " => map { $_ . ' => ' . ppprint( $hash->{$_} ) }
1126 '[ ' . ( join ", " => map { ppprint($_) } @$array ) . ' ]';
1128 CodeRef => sub {'sub { ... }'},
1129 RegexpRef => sub { 'qr/' . $_ . '/' },
1130 GlobRef => sub { '*' . B::svref_2object($_)->NAME },
1131 Object => sub { $_->can('to_string') ? $_->to_string : $_ },
1132 ScalarRef => sub { '\\' . ppprint( ${$_} ) },
1134 Str => sub { '"' . $_ . '"' },
1135 Undef => sub {'undef'},
1136 => sub { die "I don't know what $_ is" }
1140 Or a simple JSON serializer:
1144 match_on_type $x => (
1150 map { '"' . $_ . '" : ' . to_json( $hash->{$_} ) }
1156 '[ ' . ( join ", " => map { to_json($_) } @$array ) . ' ]';
1159 Str => sub { '"' . $_ . '"' },
1160 Undef => sub {'null'},
1161 => sub { die "$_ is not acceptable json type" }
1165 The matcher is done by mapping a C<$type> to an C<\&action>. The C<$type> can
1166 be either a string type or a L<Moose::Meta::TypeConstraint> object, and
1167 C<\&action> is a subroutine reference. This function will dispatch on the
1168 first match for C<$value>. It is possible to have a catch-all by providing an
1169 additional subroutine reference as the final argument to C<match_on_type>.
1173 =head2 Type Coercion Constructors
1175 You can define coercions for type constraints, which allow you to
1176 automatically transform values to something valid for the type
1177 constraint. If you ask your accessor to coerce, then Moose will run
1178 the type-coercion code first, followed by the type constraint
1179 check. This feature should be used carefully as it is very powerful
1180 and could easily take off a limb if you are not careful.
1182 See the L</SYNOPSIS> for an example of how to use these.
1186 =item B<< coerce 'Name', from 'OtherName', via { ... } >>
1188 This defines a coercion from one type to another. The C<Name> argument
1189 is the type you are coercing I<to>.
1191 To define multiple coercions, supply more sets of from/via pairs:
1194 from 'OtherName', via { ... },
1195 from 'ThirdName', via { ... };
1197 =item B<from 'OtherName'>
1199 This is just sugar for the type coercion construction syntax.
1201 It takes a single type name (or type object), which is the type being
1204 =item B<via { ... }>
1206 This is just sugar for the type coercion construction syntax.
1208 It takes a subroutine reference. This reference will be called with
1209 the value to be coerced in C<$_>. It is expected to return a new value
1210 of the proper type for the coercion.
1214 =head2 Creating and Finding Type Constraints
1216 These are additional functions for creating and finding type
1217 constraints. Most of these functions are not available for
1218 importing. The ones that are importable as specified.
1222 =item B<find_type_constraint($type_name)>
1224 This function can be used to locate the L<Moose::Meta::TypeConstraint>
1225 object for a named type.
1227 This function is importable.
1229 =item B<register_type_constraint($type_object)>
1231 This function will register a L<Moose::Meta::TypeConstraint> with the
1232 global type registry.
1234 This function is importable.
1236 =item B<normalize_type_constraint_name($type_constraint_name)>
1238 This method takes a type constraint name and returns the normalized
1239 form. This removes any whitespace in the string.
1241 =item B<create_type_constraint_union($pipe_separated_types | @type_constraint_names)>
1243 This can take a union type specification like C<'Int|ArrayRef[Int]'>,
1244 or a list of names. It returns a new
1245 L<Moose::Meta::TypeConstraint::Union> object.
1247 =item B<create_parameterized_type_constraint($type_name)>
1249 Given a C<$type_name> in the form of C<'BaseType[ContainerType]'>,
1250 this will create a new L<Moose::Meta::TypeConstraint::Parameterized>
1251 object. The C<BaseType> must exist already exist as a parameterizable
1254 =item B<create_class_type_constraint($class, $options)>
1256 Given a class name this function will create a new
1257 L<Moose::Meta::TypeConstraint::Class> object for that class name.
1259 The C<$options> is a hash reference that will be passed to the
1260 L<Moose::Meta::TypeConstraint::Class> constructor (as a hash).
1262 =item B<create_role_type_constraint($role, $options)>
1264 Given a role name this function will create a new
1265 L<Moose::Meta::TypeConstraint::Role> object for that role name.
1267 The C<$options> is a hash reference that will be passed to the
1268 L<Moose::Meta::TypeConstraint::Role> constructor (as a hash).
1270 =item B<create_enum_type_constraint($name, $values)>
1272 Given a enum name this function will create a new
1273 L<Moose::Meta::TypeConstraint::Enum> object for that enum name.
1275 =item B<create_duck_type_constraint($name, $methods)>
1277 Given a duck type name this function will create a new
1278 L<Moose::Meta::TypeConstraint::DuckType> object for that enum name.
1280 =item B<find_or_parse_type_constraint($type_name)>
1282 Given a type name, this first attempts to find a matching constraint
1283 in the global registry.
1285 If the type name is a union or parameterized type, it will create a
1286 new object of the appropriate, but if given a "regular" type that does
1287 not yet exist, it simply returns false.
1289 When given a union or parameterized type, the member or base type must
1292 If it creates a new union or parameterized type, it will add it to the
1295 =item B<find_or_create_isa_type_constraint($type_name)>
1297 =item B<find_or_create_does_type_constraint($type_name)>
1299 These functions will first call C<find_or_parse_type_constraint>. If
1300 that function does not return a type, a new type object will
1303 The C<isa> variant will use C<create_class_type_constraint> and the
1304 C<does> variant will use C<create_role_type_constraint>.
1306 =item B<get_type_constraint_registry>
1308 Returns the L<Moose::Meta::TypeConstraint::Registry> object which
1309 keeps track of all type constraints.
1311 =item B<list_all_type_constraints>
1313 This will return a list of type constraint names in the global
1314 registry. You can then fetch the actual type object using
1315 C<find_type_constraint($type_name)>.
1317 =item B<list_all_builtin_type_constraints>
1319 This will return a list of builtin type constraints, meaning those
1320 which are defined in this module. See the L<Default Type Constraints>
1321 section for a complete list.
1323 =item B<export_type_constraints_as_functions>
1325 This will export all the current type constraints as functions into
1326 the caller's namespace (C<Int()>, C<Str()>, etc). Right now, this is
1327 mostly used for testing, but it might prove useful to others.
1329 =item B<get_all_parameterizable_types>
1331 This returns all the parameterizable types that have been registered,
1332 as a list of type objects.
1334 =item B<add_parameterizable_type($type)>
1336 Adds C<$type> to the list of parameterizable types
1342 See L<Moose/BUGS> for details on reporting bugs.