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");
164 $options{name} ||= "__ANON__";
166 my $tc = Moose::Meta::TypeConstraint::Class->new(%options);
167 $REGISTRY->add_type_constraint($tc);
171 sub create_role_type_constraint {
172 my ( $role, $options ) = @_;
174 # too early for this check
175 #find_type_constraint("ClassName")->check($class)
176 # || __PACKAGE__->_throw_error("Can't create a class type constraint because '$class' is not a class name");
184 $options{name} ||= "__ANON__";
186 my $tc = Moose::Meta::TypeConstraint::Role->new(%options);
187 $REGISTRY->add_type_constraint($tc);
191 sub find_or_create_type_constraint {
192 my ( $type_constraint_name, $options_for_anon_type ) = @_;
195 = find_or_parse_type_constraint($type_constraint_name) ) {
198 elsif ( defined $options_for_anon_type ) {
201 # if there is no $options_for_anon_type
202 # specified, then we assume they don't
203 # want to create one, and return nothing.
205 # otherwise assume that we should create
206 # an ANON type with the $options_for_anon_type
207 # options which can be passed in. It should
208 # be noted that these don't get registered
209 # so we need to return it.
211 return Moose::Meta::TypeConstraint->new(
213 %{$options_for_anon_type}
220 sub find_or_create_isa_type_constraint {
221 my $type_constraint_name = shift;
222 find_or_parse_type_constraint($type_constraint_name)
223 || create_class_type_constraint($type_constraint_name);
226 sub find_or_create_does_type_constraint {
227 my $type_constraint_name = shift;
228 find_or_parse_type_constraint($type_constraint_name)
229 || create_role_type_constraint($type_constraint_name);
232 sub find_or_parse_type_constraint {
233 my $type_constraint_name = normalize_type_constraint_name(shift);
236 if ( $constraint = find_type_constraint($type_constraint_name) ) {
239 elsif ( _detect_type_constraint_union($type_constraint_name) ) {
240 $constraint = create_type_constraint_union($type_constraint_name);
242 elsif ( _detect_parameterized_type_constraint($type_constraint_name) ) {
244 = create_parameterized_type_constraint($type_constraint_name);
250 $REGISTRY->add_type_constraint($constraint);
254 sub normalize_type_constraint_name {
255 my $type_constraint_name = shift;
256 $type_constraint_name =~ s/\s//g;
257 return $type_constraint_name;
263 local $Carp::CarpLevel = $Carp::CarpLevel + 1;
264 Carp::confess($error);
267 ## --------------------------------------------------------
268 ## exported functions ...
269 ## --------------------------------------------------------
271 sub find_type_constraint {
274 if ( blessed $type and $type->isa("Moose::Meta::TypeConstraint") ) {
278 return unless $REGISTRY->has_type_constraint($type);
279 return $REGISTRY->get_type_constraint($type);
283 sub register_type_constraint {
284 my $constraint = shift;
285 __PACKAGE__->_throw_error("can't register an unnamed type constraint")
286 unless defined $constraint->name;
287 $REGISTRY->add_type_constraint($constraint);
296 my %p = map { %{$_} } @_;
298 return _create_type_constraint(
299 $name, undef, $p{where}, $p{message},
300 $p{optimize_as}, $p{inline_as},
305 if ( @_ == 1 && !ref $_[0] ) {
306 __PACKAGE__->_throw_error(
307 'A subtype cannot consist solely of a name, it must have a parent'
311 # The blessed check is mostly to accommodate MooseX::Types, which
312 # uses an object which overloads stringification as a type name.
313 my $name = ref $_[0] && !blessed $_[0] ? undef : shift;
315 my %p = map { %{$_} } @_;
317 # subtype Str => where { ... };
318 if ( !exists $p{as} ) {
323 return _create_type_constraint(
324 $name, $p{as}, $p{where}, $p{message},
325 $p{optimize_as}, $p{inline_as},
330 create_class_type_constraint(@_);
333 sub role_type ($;$) {
334 create_role_type_constraint(@_);
338 my ($type_parameter) = @_;
340 register_type_constraint(
341 $REGISTRY->get_type_constraint('Maybe')->parameterize($type_parameter)
346 my ( $type_name, @methods ) = @_;
347 if ( ref $type_name eq 'ARRAY' && !@methods ) {
348 @methods = @$type_name;
351 if ( @methods == 1 && ref $methods[0] eq 'ARRAY' ) {
352 @methods = @{ $methods[0] };
355 register_type_constraint(
356 create_duck_type_constraint(
364 my ( $type_name, @coercion_map ) = @_;
365 _install_type_coercions( $type_name, \@coercion_map );
368 # The trick of returning @_ lets us avoid having to specify a
369 # prototype. Perl will parse this:
377 # subtype( 'Foo', as( 'Str', where { ... } ) );
379 # If as() returns all its extra arguments, this just works, and
380 # preserves backwards compatibility.
381 sub as { { as => shift }, @_ }
382 sub where (&) { { where => $_[0] } }
383 sub message (&) { { message => $_[0] } }
384 sub optimize_as (&) { { optimize_as => $_[0] } }
385 sub inline_as (&) { { inline_as => $_[0] } }
388 sub via (&) { $_[0] }
391 my ( $type_name, @values ) = @_;
394 # if only an array-ref is passed then
395 # you get an anon-enum
397 if ( ref $type_name eq 'ARRAY' ) {
399 || __PACKAGE__->_throw_error("enum called with an array reference and additional arguments. Did you mean to parenthesize the enum call's parameters?");
401 @values = @$type_name;
404 if ( @values == 1 && ref $values[0] eq 'ARRAY' ) {
405 @values = @{ $values[0] };
408 register_type_constraint(
409 create_enum_type_constraint(
417 my ( $type_name, @constraints ) = @_;
418 if ( ref $type_name eq 'ARRAY' ) {
420 || __PACKAGE__->_throw_error("union called with an array reference and additional arguments.");
421 @constraints = @$type_name;
424 if ( @constraints == 1 && ref $constraints[0] eq 'ARRAY' ) {
425 @constraints = @{ $constraints[0] };
427 if ( defined $type_name ) {
428 return register_type_constraint(
429 create_named_type_constraint_union( $type_name, @constraints )
432 return create_type_constraint_union( @constraints );
435 sub create_enum_type_constraint {
436 my ( $type_name, $values ) = @_;
438 Moose::Meta::TypeConstraint::Enum->new(
439 name => $type_name || '__ANON__',
444 sub create_duck_type_constraint {
445 my ( $type_name, $methods ) = @_;
447 Moose::Meta::TypeConstraint::DuckType->new(
448 name => $type_name || '__ANON__',
454 my ($to_match, @cases) = @_;
456 if (@cases % 2 != 0) {
457 $default = pop @cases;
458 (ref $default eq 'CODE')
459 || __PACKAGE__->_throw_error("Default case must be a CODE ref, not $default");
462 my ($type, $action) = splice @cases, 0, 2;
464 unless (blessed $type && $type->isa('Moose::Meta::TypeConstraint')) {
465 $type = find_or_parse_type_constraint($type)
466 || __PACKAGE__->_throw_error("Cannot find or parse the type '$type'")
469 (ref $action eq 'CODE')
470 || __PACKAGE__->_throw_error("Match action must be a CODE ref, not $action");
472 if ($type->check($to_match)) {
473 local $_ = $to_match;
474 return $action->($to_match);
478 || __PACKAGE__->_throw_error("No cases matched for $to_match");
480 local $_ = $to_match;
481 return $default->($to_match);
486 ## --------------------------------------------------------
487 ## desugaring functions ...
488 ## --------------------------------------------------------
490 sub _create_type_constraint ($$$;$$) {
495 my $optimized = shift;
498 my $pkg_defined_in = scalar( caller(1) );
500 if ( defined $name ) {
501 my $type = $REGISTRY->get_type_constraint($name);
503 ( $type->_package_defined_in eq $pkg_defined_in )
505 "The type constraint '$name' has already been created in "
506 . $type->_package_defined_in
507 . " and cannot be created again in "
511 $name =~ /^[\w:\.]+$/
512 or die qq{$name contains invalid characters for a type name.}
513 . qq{ Names can contain alphanumeric character, ":", and "."\n};
518 package_defined_in => $pkg_defined_in,
520 ( $check ? ( constraint => $check ) : () ),
521 ( $message ? ( message => $message ) : () ),
522 ( $optimized ? ( optimized => $optimized ) : () ),
523 ( $inlined ? ( inlined => $inlined ) : () ),
532 : find_or_create_isa_type_constraint($parent)
534 $constraint = $parent->create_child_type(%opts);
537 $constraint = Moose::Meta::TypeConstraint->new(%opts);
540 $REGISTRY->add_type_constraint($constraint)
546 sub _install_type_coercions ($$) {
547 my ( $type_name, $coercion_map ) = @_;
548 my $type = find_type_constraint($type_name);
550 || __PACKAGE__->_throw_error(
551 "Cannot find type '$type_name', perhaps you forgot to load it");
552 if ( $type->has_coercion ) {
553 $type->coercion->add_type_coercions(@$coercion_map);
556 my $type_coercion = Moose::Meta::TypeCoercion->new(
557 type_coercion_map => $coercion_map,
558 type_constraint => $type
560 $type->coercion($type_coercion);
564 ## --------------------------------------------------------
565 ## type notation parsing ...
566 ## --------------------------------------------------------
570 # All I have to say is mugwump++ cause I know
571 # do not even have enough regexp-fu to be able
572 # to have written this (I can only barely
573 # understand it as it is)
578 my $valid_chars = qr{[\w:\.]};
579 my $type_atom = qr{ (?>$valid_chars+) }x;
580 my $ws = qr{ (?>\s*) }x;
581 my $op_union = qr{ $ws \| $ws }x;
583 my ($type, $type_capture_parts, $type_with_parameter, $union, $any);
584 if (Class::MOP::IS_RUNNING_ON_5_10) {
586 = q{ (?&type_atom) (?: \[ (?&ws) (?&any) (?&ws) \] )? };
587 my $type_capture_parts_pattern
588 = q{ ((?&type_atom)) (?: \[ (?&ws) ((?&any)) (?&ws) \] )? };
589 my $type_with_parameter_pattern
590 = q{ (?&type_atom) \[ (?&ws) (?&any) (?&ws) \] };
592 = q{ (?&type) (?> (?: (?&op_union) (?&type) )+ ) };
594 = q{ (?&type) | (?&union) };
596 my $defines = qr{(?(DEFINE)
597 (?<valid_chars> $valid_chars)
598 (?<type_atom> $type_atom)
600 (?<op_union> $op_union)
601 (?<type> $type_pattern)
602 (?<type_capture_parts> $type_capture_parts_pattern)
603 (?<type_with_parameter> $type_with_parameter_pattern)
604 (?<union> $union_pattern)
605 (?<any> $any_pattern)
608 $type = qr{ $type_pattern $defines }x;
609 $type_capture_parts = qr{ $type_capture_parts_pattern $defines }x;
610 $type_with_parameter = qr{ $type_with_parameter_pattern $defines }x;
611 $union = qr{ $union_pattern $defines }x;
612 $any = qr{ $any_pattern $defines }x;
616 = qr{ $type_atom (?: \[ $ws (??{$any}) $ws \] )? }x;
618 = qr{ ($type_atom) (?: \[ $ws ((??{$any})) $ws \] )? }x;
620 = qr{ $type_atom \[ $ws (??{$any}) $ws \] }x;
622 = qr{ $type (?> (?: $op_union $type )+ ) }x;
624 = qr{ $type | $union }x;
628 sub _parse_parameterized_type_constraint {
629 { no warnings 'void'; $any; } # force capture of interpolated lexical
630 $_[0] =~ m{ $type_capture_parts }x;
634 sub _detect_parameterized_type_constraint {
635 { no warnings 'void'; $any; } # force capture of interpolated lexical
636 $_[0] =~ m{ ^ $type_with_parameter $ }x;
639 sub _parse_type_constraint_union {
640 { no warnings 'void'; $any; } # force capture of interpolated lexical
643 while ( $given =~ m{ \G (?: $op_union )? ($type) }gcx ) {
646 ( pos($given) eq length($given) )
647 || __PACKAGE__->_throw_error( "'$given' didn't parse (parse-pos="
655 sub _detect_type_constraint_union {
656 { no warnings 'void'; $any; } # force capture of interpolated lexical
657 $_[0] =~ m{^ $type $op_union $type ( $op_union .* )? $}x;
661 ## --------------------------------------------------------
662 # define some basic built-in types
663 ## --------------------------------------------------------
665 # By making these classes immutable before creating all the types in
666 # Moose::Util::TypeConstraints::Builtin , we avoid repeatedly calling the slow
667 # MOP-based accessors.
669 inline_constructor => 1,
670 constructor_name => "_new",
672 # these are Class::MOP accessors, so they need inlining
673 inline_accessors => 1
674 ) for grep { $_->is_mutable }
675 map { Class::MOP::class_of($_) }
677 Moose::Meta::TypeConstraint
678 Moose::Meta::TypeConstraint::Union
679 Moose::Meta::TypeConstraint::Parameterized
680 Moose::Meta::TypeConstraint::Parameterizable
681 Moose::Meta::TypeConstraint::Class
682 Moose::Meta::TypeConstraint::Role
683 Moose::Meta::TypeConstraint::Enum
684 Moose::Meta::TypeConstraint::DuckType
685 Moose::Meta::TypeConstraint::Registry
688 require Moose::Util::TypeConstraints::Builtins;
689 Moose::Util::TypeConstraints::Builtins::define_builtins($REGISTRY);
691 my @PARAMETERIZABLE_TYPES
692 = map { $REGISTRY->get_type_constraint($_) } qw[ScalarRef ArrayRef HashRef Maybe];
694 sub get_all_parameterizable_types {@PARAMETERIZABLE_TYPES}
696 sub add_parameterizable_type {
699 && $type->isa('Moose::Meta::TypeConstraint::Parameterizable') )
700 || __PACKAGE__->_throw_error(
701 "Type must be a Moose::Meta::TypeConstraint::Parameterizable not $type"
703 push @PARAMETERIZABLE_TYPES => $type;
706 ## --------------------------------------------------------
707 # end of built-in types ...
708 ## --------------------------------------------------------
711 my @BUILTINS = list_all_type_constraints();
712 sub list_all_builtin_type_constraints {@BUILTINS}
719 goto &Moose::throw_error;
724 # ABSTRACT: Type constraint system for Moose
732 use Moose::Util::TypeConstraints;
738 subtype 'NaturalLessThanTen',
741 message { "This number ($_) is not less than ten!" };
747 class_type 'DateTimeClass', { class => 'DateTime' };
749 role_type 'Barks', { role => 'Some::Library::Role::Barks' };
751 enum 'RGBColors', [qw(red green blue)];
753 union 'StringOrArray', [qw( String Array )];
755 no Moose::Util::TypeConstraints;
759 This module provides Moose with the ability to create custom type
760 constraints to be used in attribute definition.
762 =head2 Important Caveat
764 This is B<NOT> a type system for Perl 5. These are type constraints,
765 and they are not used by Moose unless you tell it to. No type
766 inference is performed, expressions are not typed, etc. etc. etc.
768 A type constraint is at heart a small "check if a value is valid"
769 function. A constraint can be associated with an attribute. This
770 simplifies parameter validation, and makes your code clearer to read,
771 because you can refer to constraints by name.
773 =head2 Slightly Less Important Caveat
775 It is B<always> a good idea to quote your type names.
777 This prevents Perl from trying to execute the call as an indirect
778 object call. This can be an issue when you have a subtype with the
779 same name as a valid class.
783 subtype DateTime => as Object => where { $_->isa('DateTime') };
785 will I<just work>, while this:
788 subtype DateTime => as Object => where { $_->isa('DateTime') };
790 will fail silently and cause many headaches. The simple way to solve
791 this, as well as future proof your subtypes from classes which have
792 yet to have been created, is to quote the type name:
795 subtype 'DateTime', as 'Object', where { $_->isa('DateTime') };
797 =head2 Default Type Constraints
799 This module also provides a simple hierarchy for Perl 5 types, here is
800 that hierarchy represented visually.
824 B<NOTE:> Any type followed by a type parameter C<[`a]> can be
825 parameterized, this means you can say:
827 ArrayRef[Int] # an array of integers
828 HashRef[CodeRef] # a hash of str to CODE ref mappings
829 ScalarRef[Int] # a reference to an integer
830 Maybe[Str] # value may be a string, may be undefined
832 If Moose finds a name in brackets that it does not recognize as an
833 existing type, it assumes that this is a class name, for example
834 C<ArrayRef[DateTime]>.
836 B<NOTE:> Unless you parameterize a type, then it is invalid to include
837 the square brackets. I.e. C<ArrayRef[]> will be treated as a new type
838 name, I<not> as a parameterization of C<ArrayRef>.
840 B<NOTE:> The C<Undef> type constraint for the most part works
841 correctly now, but edge cases may still exist, please use it
844 B<NOTE:> The C<ClassName> type constraint does a complex package
845 existence check. This means that your class B<must> be loaded for this
846 type constraint to pass.
848 B<NOTE:> The C<RoleName> constraint checks a string is a I<package
849 name> which is a role, like C<'MyApp::Role::Comparable'>.
851 =head2 Type Constraint Naming
853 Type name declared via this module can only contain alphanumeric
854 characters, colons (:), and periods (.).
856 Since the types created by this module are global, it is suggested
857 that you namespace your types just as you would namespace your
858 modules. So instead of creating a I<Color> type for your
859 B<My::Graphics> module, you would call the type
860 I<My::Graphics::Types::Color> instead.
862 =head2 Use with Other Constraint Modules
864 This module can play nicely with other constraint modules with some
865 slight tweaking. The C<where> clause in types is expected to be a
866 C<CODE> reference which checks its first argument and returns a
867 boolean. Since most constraint modules work in a similar way, it
868 should be simple to adapt them to work with Moose.
870 For instance, this is how you could use it with
871 L<Declare::Constraints::Simple> to declare a completely new type.
873 type 'HashOfArrayOfObjects',
877 -values => IsArrayRef(IsObject)
881 For more examples see the F<t/examples/example_w_DCS.t> test
884 Here is an example of using L<Test::Deep> and its non-test
885 related C<eq_deeply> function.
887 type 'ArrayOfHashOfBarsAndRandomNumbers',
890 array_each(subhashof({
892 random_number => ignore()
896 For a complete example see the
897 F<t/examples/example_w_TestDeep.t> test file.
899 =head2 Error messages
901 Type constraints can also specify custom error messages, for when they fail to
902 validate. This is provided as just another coderef, which receives the invalid
903 value in C<$_>, as in:
905 subtype 'PositiveInt',
908 message { "$_ is not a positive integer!" };
910 If no message is specified, a default message will be used, which indicates
911 which type constraint was being used and what value failed. If
912 L<Devel::PartialDump> (version 0.14 or higher) is installed, it will be used to
913 display the invalid value, otherwise it will just be printed as is.
917 =head2 Type Constraint Constructors
919 The following functions are used to create type constraints. They
920 will also register the type constraints your create in a global
921 registry that is used to look types up by name.
923 See the L</SYNOPSIS> for an example of how to use these.
927 =item B<< subtype 'Name', as 'Parent', where { } ... >>
929 This creates a named subtype.
931 If you provide a parent that Moose does not recognize, it will
932 automatically create a new class type constraint for this name.
934 When creating a named type, the C<subtype> function should either be
935 called with the sugar helpers (C<where>, C<message>, etc), or with a
936 name and a hashref of parameters:
938 subtype( 'Foo', { where => ..., message => ... } );
940 The valid hashref keys are C<as> (the parent), C<where>, C<message>,
943 =item B<< subtype as 'Parent', where { } ... >>
945 This creates an unnamed subtype and will return the type
946 constraint meta-object, which will be an instance of
947 L<Moose::Meta::TypeConstraint>.
949 When creating an anonymous type, the C<subtype> function should either
950 be called with the sugar helpers (C<where>, C<message>, etc), or with
951 just a hashref of parameters:
953 subtype( { where => ..., message => ... } );
955 =item B<class_type ($class, ?$options)>
957 Creates a new subtype of C<Object> with the name C<$class> and the
958 metaclass L<Moose::Meta::TypeConstraint::Class>.
960 # Create a type called 'Box' which tests for objects which ->isa('Box')
963 By default, the name of the type and the name of the class are the same, but
964 you can specify both separately.
966 # Create a type called 'Box' which tests for objects which ->isa('ObjectLibrary::Box');
967 class_type 'Box', { class => 'ObjectLibrary::Box' };
969 =item B<role_type ($role, ?$options)>
971 Creates a C<Role> type constraint with the name C<$role> and the
972 metaclass L<Moose::Meta::TypeConstraint::Role>.
974 # Create a type called 'Walks' which tests for objects which ->does('Walks')
977 By default, the name of the type and the name of the role are the same, but
978 you can specify both separately.
980 # Create a type called 'Walks' which tests for objects which ->does('MooseX::Role::Walks');
981 role_type 'Walks', { role => 'MooseX::Role::Walks' };
983 =item B<maybe_type ($type)>
985 Creates a type constraint for either C<undef> or something of the
988 =item B<duck_type ($name, \@methods)>
990 This will create a subtype of Object and test to make sure the value
991 C<can()> do the methods in C<\@methods>.
993 This is intended as an easy way to accept non-Moose objects that
994 provide a certain interface. If you're using Moose classes, we
995 recommend that you use a C<requires>-only Role instead.
997 =item B<duck_type (\@methods)>
999 If passed an ARRAY reference as the only parameter instead of the
1000 C<$name>, C<\@methods> pair, this will create an unnamed duck type.
1001 This can be used in an attribute definition like so:
1005 isa => duck_type( [qw( get_set )] ),
1008 =item B<enum ($name, \@values)>
1010 This will create a basic subtype for a given set of strings.
1011 The resulting constraint will be a subtype of C<Str> and
1012 will match any of the items in C<\@values>. It is case sensitive.
1013 See the L</SYNOPSIS> for a simple example.
1015 B<NOTE:> This is not a true proper enum type, it is simply
1016 a convenient constraint builder.
1018 =item B<enum (\@values)>
1020 If passed an ARRAY reference as the only parameter instead of the
1021 C<$name>, C<\@values> pair, this will create an unnamed enum. This
1022 can then be used in an attribute definition like so:
1024 has 'sort_order' => (
1026 isa => enum([qw[ ascending descending ]]),
1029 =item B<union ($name, \@constraints)>
1031 This will create a basic subtype where any of the provided constraints
1032 may match in order to satisfy this constraint.
1034 =item B<union (\@constraints)>
1036 If passed an ARRAY reference as the only parameter instead of the
1037 C<$name>, C<\@constraints> pair, this will create an unnamed union.
1038 This can then be used in an attribute definition like so:
1042 isa => union([qw[ Str ArrayRef ]]),
1045 This is similar to the existing string union:
1047 isa => 'Str|ArrayRef'
1049 except that it supports anonymous elements as child constraints:
1053 isa => union([ 'Int', enum([qw[ red green blue ]]) ]),
1056 =item B<as 'Parent'>
1058 This is just sugar for the type constraint construction syntax.
1060 It takes a single argument, which is the name of a parent type.
1062 =item B<where { ... }>
1064 This is just sugar for the type constraint construction syntax.
1066 It takes a subroutine reference as an argument. When the type
1067 constraint is tested, the reference is run with the value to be tested
1068 in C<$_>. This reference should return true or false to indicate
1069 whether or not the constraint check passed.
1071 =item B<message { ... }>
1073 This is just sugar for the type constraint construction syntax.
1075 It takes a subroutine reference as an argument. When the type
1076 constraint fails, then the code block is run with the value provided
1077 in C<$_>. This reference should return a string, which will be used in
1078 the text of the exception thrown.
1080 =item B<inline_as { ... }>
1082 This can be used to define a "hand optimized" inlinable version of your type
1085 You provide a subroutine which will be called I<as a method> on a
1086 L<Moose::Meta::TypeConstraint> object. It will receive a single parameter, the
1087 name of the variable to check, typically something like C<"$_"> or C<"$_[0]">.
1089 The subroutine should return a code string suitable for inlining. You can
1090 assume that the check will be wrapped in parentheses when it is inlined.
1092 The inlined code should include any checks that your type's parent types
1093 do. For example, the C<Value> type's inlining sub looks like this:
1096 'defined(' . $_[1] . ')'
1097 . ' && !ref(' . $_[1] . ')'
1100 Note that it checks if the variable is defined, since it is a subtype of
1101 the C<Defined> type. However, to avoid repeating code, this can be optimized as:
1104 $_[0]->parent()->_inline_check($_[1])
1105 . ' && !ref(' . $_[1] . ')'
1108 =item B<optimize_as { ... }>
1110 B<This feature is deprecated, use C<inline_as> instead.>
1112 This can be used to define a "hand optimized" version of your
1113 type constraint which can be used to avoid traversing a subtype
1114 constraint hierarchy.
1116 B<NOTE:> You should only use this if you know what you are doing.
1117 All the built in types use this, so your subtypes (assuming they
1118 are shallow) will not likely need to use this.
1120 =item B<< type 'Name', where { } ... >>
1122 This creates a base type, which has no parent.
1124 The C<type> function should either be called with the sugar helpers
1125 (C<where>, C<message>, etc), or with a name and a hashref of
1128 type( 'Foo', { where => ..., message => ... } );
1130 The valid hashref keys are C<where>, C<message>, and C<inlined_as>.
1134 =head2 Type Constraint Utilities
1138 =item B<< match_on_type $value => ( $type => \&action, ... ?\&default ) >>
1140 This is a utility function for doing simple type based dispatching similar to
1141 match/case in OCaml and case/of in Haskell. It is not as featureful as those
1142 languages, nor does not it support any kind of automatic destructuring
1143 bind. Here is a simple Perl pretty printer dispatching over the core Moose
1148 match_on_type $x => (
1153 join ", " => map { $_ . ' => ' . ppprint( $hash->{$_} ) }
1159 '[ ' . ( join ", " => map { ppprint($_) } @$array ) . ' ]';
1161 CodeRef => sub {'sub { ... }'},
1162 RegexpRef => sub { 'qr/' . $_ . '/' },
1163 GlobRef => sub { '*' . B::svref_2object($_)->NAME },
1164 Object => sub { $_->can('to_string') ? $_->to_string : $_ },
1165 ScalarRef => sub { '\\' . ppprint( ${$_} ) },
1167 Str => sub { '"' . $_ . '"' },
1168 Undef => sub {'undef'},
1169 => sub { die "I don't know what $_ is" }
1173 Or a simple JSON serializer:
1177 match_on_type $x => (
1183 map { '"' . $_ . '" : ' . to_json( $hash->{$_} ) }
1189 '[ ' . ( join ", " => map { to_json($_) } @$array ) . ' ]';
1192 Str => sub { '"' . $_ . '"' },
1193 Undef => sub {'null'},
1194 => sub { die "$_ is not acceptable json type" }
1198 The matcher is done by mapping a C<$type> to an C<\&action>. The C<$type> can
1199 be either a string type or a L<Moose::Meta::TypeConstraint> object, and
1200 C<\&action> is a subroutine reference. This function will dispatch on the
1201 first match for C<$value>. It is possible to have a catch-all by providing an
1202 additional subroutine reference as the final argument to C<match_on_type>.
1206 =head2 Type Coercion Constructors
1208 You can define coercions for type constraints, which allow you to
1209 automatically transform values to something valid for the type
1210 constraint. If you ask your accessor to coerce, then Moose will run
1211 the type-coercion code first, followed by the type constraint
1212 check. This feature should be used carefully as it is very powerful
1213 and could easily take off a limb if you are not careful.
1215 See the L</SYNOPSIS> for an example of how to use these.
1219 =item B<< coerce 'Name', from 'OtherName', via { ... } >>
1221 This defines a coercion from one type to another. The C<Name> argument
1222 is the type you are coercing I<to>.
1224 To define multiple coercions, supply more sets of from/via pairs:
1227 from 'OtherName', via { ... },
1228 from 'ThirdName', via { ... };
1230 =item B<from 'OtherName'>
1232 This is just sugar for the type coercion construction syntax.
1234 It takes a single type name (or type object), which is the type being
1237 =item B<via { ... }>
1239 This is just sugar for the type coercion construction syntax.
1241 It takes a subroutine reference. This reference will be called with
1242 the value to be coerced in C<$_>. It is expected to return a new value
1243 of the proper type for the coercion.
1247 =head2 Creating and Finding Type Constraints
1249 These are additional functions for creating and finding type
1250 constraints. Most of these functions are not available for
1251 importing. The ones that are importable as specified.
1255 =item B<find_type_constraint($type_name)>
1257 This function can be used to locate the L<Moose::Meta::TypeConstraint>
1258 object for a named type.
1260 This function is importable.
1262 =item B<register_type_constraint($type_object)>
1264 This function will register a L<Moose::Meta::TypeConstraint> with the
1265 global type registry.
1267 This function is importable.
1269 =item B<normalize_type_constraint_name($type_constraint_name)>
1271 This method takes a type constraint name and returns the normalized
1272 form. This removes any whitespace in the string.
1274 =item B<create_type_constraint_union($pipe_separated_types | @type_constraint_names)>
1276 =item B<create_named_type_constraint_union($name, $pipe_separated_types | @type_constraint_names)>
1278 This can take a union type specification like C<'Int|ArrayRef[Int]'>,
1279 or a list of names. It returns a new
1280 L<Moose::Meta::TypeConstraint::Union> object.
1282 =item B<create_parameterized_type_constraint($type_name)>
1284 Given a C<$type_name> in the form of C<'BaseType[ContainerType]'>,
1285 this will create a new L<Moose::Meta::TypeConstraint::Parameterized>
1286 object. The C<BaseType> must exist already exist as a parameterizable
1289 =item B<create_class_type_constraint($class, $options)>
1291 Given a class name this function will create a new
1292 L<Moose::Meta::TypeConstraint::Class> object for that class name.
1294 The C<$options> is a hash reference that will be passed to the
1295 L<Moose::Meta::TypeConstraint::Class> constructor (as a hash).
1297 =item B<create_role_type_constraint($role, $options)>
1299 Given a role name this function will create a new
1300 L<Moose::Meta::TypeConstraint::Role> object for that role name.
1302 The C<$options> is a hash reference that will be passed to the
1303 L<Moose::Meta::TypeConstraint::Role> constructor (as a hash).
1305 =item B<create_enum_type_constraint($name, $values)>
1307 Given a enum name this function will create a new
1308 L<Moose::Meta::TypeConstraint::Enum> object for that enum name.
1310 =item B<create_duck_type_constraint($name, $methods)>
1312 Given a duck type name this function will create a new
1313 L<Moose::Meta::TypeConstraint::DuckType> object for that enum name.
1315 =item B<find_or_parse_type_constraint($type_name)>
1317 Given a type name, this first attempts to find a matching constraint
1318 in the global registry.
1320 If the type name is a union or parameterized type, it will create a
1321 new object of the appropriate, but if given a "regular" type that does
1322 not yet exist, it simply returns false.
1324 When given a union or parameterized type, the member or base type must
1327 If it creates a new union or parameterized type, it will add it to the
1330 =item B<find_or_create_isa_type_constraint($type_name)>
1332 =item B<find_or_create_does_type_constraint($type_name)>
1334 These functions will first call C<find_or_parse_type_constraint>. If
1335 that function does not return a type, a new type object will
1338 The C<isa> variant will use C<create_class_type_constraint> and the
1339 C<does> variant will use C<create_role_type_constraint>.
1341 =item B<get_type_constraint_registry>
1343 Returns the L<Moose::Meta::TypeConstraint::Registry> object which
1344 keeps track of all type constraints.
1346 =item B<list_all_type_constraints>
1348 This will return a list of type constraint names in the global
1349 registry. You can then fetch the actual type object using
1350 C<find_type_constraint($type_name)>.
1352 =item B<list_all_builtin_type_constraints>
1354 This will return a list of builtin type constraints, meaning those
1355 which are defined in this module. See the L<Default Type Constraints>
1356 section for a complete list.
1358 =item B<export_type_constraints_as_functions>
1360 This will export all the current type constraints as functions into
1361 the caller's namespace (C<Int()>, C<Str()>, etc). Right now, this is
1362 mostly used for testing, but it might prove useful to others.
1364 =item B<get_all_parameterizable_types>
1366 This returns all the parameterizable types that have been registered,
1367 as a list of type objects.
1369 =item B<add_parameterizable_type($type)>
1371 Adds C<$type> to the list of parameterizable types
1377 See L<Moose/BUGS> for details on reporting bugs.