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 = $options->{package_defined_in} || scalar( caller(1) );
160 if (my $type = $REGISTRY->get_type_constraint($class)) {
161 if (!($type->isa('Moose::Meta::TypeConstraint::Class') && $type->class eq $class)) {
163 "The type constraint '$class' has already been created in "
164 . $type->_package_defined_in
165 . " and cannot be created again in "
176 package_defined_in => $pkg_defined_in,
180 $options{name} ||= "__ANON__";
182 my $tc = Moose::Meta::TypeConstraint::Class->new(%options);
183 $REGISTRY->add_type_constraint($tc);
187 sub create_role_type_constraint {
188 my ( $role, $options ) = @_;
190 # too early for this check
191 #find_type_constraint("ClassName")->check($class)
192 # || __PACKAGE__->_throw_error("Can't create a class type constraint because '$class' is not a class name");
194 my $pkg_defined_in = $options->{package_defined_in} || scalar( caller(1) );
196 if (my $type = $REGISTRY->get_type_constraint($role)) {
197 if (!($type->isa('Moose::Meta::TypeConstraint::Role') && $type->role eq $role)) {
199 "The type constraint '$role' has already been created in "
200 . $type->_package_defined_in
201 . " and cannot be created again in "
212 package_defined_in => $pkg_defined_in,
216 $options{name} ||= "__ANON__";
218 my $tc = Moose::Meta::TypeConstraint::Role->new(%options);
219 $REGISTRY->add_type_constraint($tc);
223 sub find_or_create_type_constraint {
224 my ( $type_constraint_name, $options_for_anon_type ) = @_;
227 = find_or_parse_type_constraint($type_constraint_name) ) {
230 elsif ( defined $options_for_anon_type ) {
233 # if there is no $options_for_anon_type
234 # specified, then we assume they don't
235 # want to create one, and return nothing.
237 # otherwise assume that we should create
238 # an ANON type with the $options_for_anon_type
239 # options which can be passed in. It should
240 # be noted that these don't get registered
241 # so we need to return it.
243 return Moose::Meta::TypeConstraint->new(
245 %{$options_for_anon_type}
252 sub find_or_create_isa_type_constraint {
253 my ($type_constraint_name, $options) = @_;
254 find_or_parse_type_constraint($type_constraint_name)
255 || create_class_type_constraint($type_constraint_name, $options);
258 sub find_or_create_does_type_constraint {
259 my ($type_constraint_name, $options) = @_;
260 find_or_parse_type_constraint($type_constraint_name)
261 || create_role_type_constraint($type_constraint_name, $options);
264 sub find_or_parse_type_constraint {
265 my $type_constraint_name = normalize_type_constraint_name(shift);
268 if ( $constraint = find_type_constraint($type_constraint_name) ) {
271 elsif ( _detect_type_constraint_union($type_constraint_name) ) {
272 $constraint = create_type_constraint_union($type_constraint_name);
274 elsif ( _detect_parameterized_type_constraint($type_constraint_name) ) {
276 = create_parameterized_type_constraint($type_constraint_name);
282 $REGISTRY->add_type_constraint($constraint);
286 sub normalize_type_constraint_name {
287 my $type_constraint_name = shift;
288 $type_constraint_name =~ s/\s//g;
289 return $type_constraint_name;
295 local $Carp::CarpLevel = $Carp::CarpLevel + 1;
296 Carp::confess($error);
299 ## --------------------------------------------------------
300 ## exported functions ...
301 ## --------------------------------------------------------
303 sub find_type_constraint {
306 if ( blessed $type and $type->isa("Moose::Meta::TypeConstraint") ) {
310 return unless $REGISTRY->has_type_constraint($type);
311 return $REGISTRY->get_type_constraint($type);
315 sub register_type_constraint {
316 my $constraint = shift;
317 __PACKAGE__->_throw_error("can't register an unnamed type constraint")
318 unless defined $constraint->name;
319 $REGISTRY->add_type_constraint($constraint);
328 my %p = map { %{$_} } @_;
330 return _create_type_constraint(
331 $name, undef, $p{where}, $p{message},
332 $p{optimize_as}, $p{inline_as},
337 if ( @_ == 1 && !ref $_[0] ) {
338 __PACKAGE__->_throw_error(
339 'A subtype cannot consist solely of a name, it must have a parent'
343 # The blessed check is mostly to accommodate MooseX::Types, which
344 # uses an object which overloads stringification as a type name.
345 my $name = ref $_[0] && !blessed $_[0] ? undef : shift;
347 my %p = map { %{$_} } @_;
349 # subtype Str => where { ... };
350 if ( !exists $p{as} ) {
355 return _create_type_constraint(
356 $name, $p{as}, $p{where}, $p{message},
357 $p{optimize_as}, $p{inline_as},
362 create_class_type_constraint(@_);
365 sub role_type ($;$) {
366 create_role_type_constraint(@_);
370 my ($type_parameter) = @_;
372 register_type_constraint(
373 $REGISTRY->get_type_constraint('Maybe')->parameterize($type_parameter)
378 my ( $type_name, @methods ) = @_;
379 if ( ref $type_name eq 'ARRAY' && !@methods ) {
380 @methods = @$type_name;
383 if ( @methods == 1 && ref $methods[0] eq 'ARRAY' ) {
384 @methods = @{ $methods[0] };
387 register_type_constraint(
388 create_duck_type_constraint(
396 my ( $type_name, @coercion_map ) = @_;
397 _install_type_coercions( $type_name, \@coercion_map );
400 # The trick of returning @_ lets us avoid having to specify a
401 # prototype. Perl will parse this:
409 # subtype( 'Foo', as( 'Str', where { ... } ) );
411 # If as() returns all its extra arguments, this just works, and
412 # preserves backwards compatibility.
413 sub as { { as => shift }, @_ }
414 sub where (&) { { where => $_[0] } }
415 sub message (&) { { message => $_[0] } }
416 sub optimize_as (&) { { optimize_as => $_[0] } }
417 sub inline_as (&) { { inline_as => $_[0] } }
420 sub via (&) { $_[0] }
423 my ( $type_name, @values ) = @_;
426 # if only an array-ref is passed then
427 # you get an anon-enum
429 if ( ref $type_name eq 'ARRAY' ) {
431 || __PACKAGE__->_throw_error("enum called with an array reference and additional arguments. Did you mean to parenthesize the enum call's parameters?");
433 @values = @$type_name;
436 if ( @values == 1 && ref $values[0] eq 'ARRAY' ) {
437 @values = @{ $values[0] };
440 register_type_constraint(
441 create_enum_type_constraint(
449 my ( $type_name, @constraints ) = @_;
450 if ( ref $type_name eq 'ARRAY' ) {
452 || __PACKAGE__->_throw_error("union called with an array reference and additional arguments.");
453 @constraints = @$type_name;
456 if ( @constraints == 1 && ref $constraints[0] eq 'ARRAY' ) {
457 @constraints = @{ $constraints[0] };
459 if ( defined $type_name ) {
460 return register_type_constraint(
461 create_named_type_constraint_union( $type_name, @constraints )
464 return create_type_constraint_union( @constraints );
467 sub create_enum_type_constraint {
468 my ( $type_name, $values ) = @_;
470 Moose::Meta::TypeConstraint::Enum->new(
471 name => $type_name || '__ANON__',
476 sub create_duck_type_constraint {
477 my ( $type_name, $methods ) = @_;
479 Moose::Meta::TypeConstraint::DuckType->new(
480 name => $type_name || '__ANON__',
486 my ($to_match, @cases) = @_;
488 if (@cases % 2 != 0) {
489 $default = pop @cases;
490 (ref $default eq 'CODE')
491 || __PACKAGE__->_throw_error("Default case must be a CODE ref, not $default");
494 my ($type, $action) = splice @cases, 0, 2;
496 unless (blessed $type && $type->isa('Moose::Meta::TypeConstraint')) {
497 $type = find_or_parse_type_constraint($type)
498 || __PACKAGE__->_throw_error("Cannot find or parse the type '$type'")
501 (ref $action eq 'CODE')
502 || __PACKAGE__->_throw_error("Match action must be a CODE ref, not $action");
504 if ($type->check($to_match)) {
505 local $_ = $to_match;
506 return $action->($to_match);
510 || __PACKAGE__->_throw_error("No cases matched for $to_match");
512 local $_ = $to_match;
513 return $default->($to_match);
518 ## --------------------------------------------------------
519 ## desugaring functions ...
520 ## --------------------------------------------------------
522 sub _create_type_constraint ($$$;$$) {
527 my $optimized = shift;
530 my $pkg_defined_in = scalar( caller(1) );
532 if ( defined $name ) {
533 my $type = $REGISTRY->get_type_constraint($name);
535 ( $type->_package_defined_in eq $pkg_defined_in )
537 "The type constraint '$name' has already been created in "
538 . $type->_package_defined_in
539 . " and cannot be created again in "
543 $name =~ /^[\w:\.]+$/
544 or die qq{$name contains invalid characters for a type name.}
545 . qq{ Names can contain alphanumeric character, ":", and "."\n};
550 package_defined_in => $pkg_defined_in,
552 ( $check ? ( constraint => $check ) : () ),
553 ( $message ? ( message => $message ) : () ),
554 ( $optimized ? ( optimized => $optimized ) : () ),
555 ( $inlined ? ( inlined => $inlined ) : () ),
564 : find_or_create_isa_type_constraint($parent)
566 $constraint = $parent->create_child_type(%opts);
569 $constraint = Moose::Meta::TypeConstraint->new(%opts);
572 $REGISTRY->add_type_constraint($constraint)
578 sub _install_type_coercions ($$) {
579 my ( $type_name, $coercion_map ) = @_;
580 my $type = find_type_constraint($type_name);
582 || __PACKAGE__->_throw_error(
583 "Cannot find type '$type_name', perhaps you forgot to load it");
584 if ( $type->has_coercion ) {
585 $type->coercion->add_type_coercions(@$coercion_map);
588 my $type_coercion = Moose::Meta::TypeCoercion->new(
589 type_coercion_map => $coercion_map,
590 type_constraint => $type
592 $type->coercion($type_coercion);
596 ## --------------------------------------------------------
597 ## type notation parsing ...
598 ## --------------------------------------------------------
602 # All I have to say is mugwump++ cause I know
603 # do not even have enough regexp-fu to be able
604 # to have written this (I can only barely
605 # understand it as it is)
610 my $valid_chars = qr{[\w:\.]};
611 my $type_atom = qr{ (?>$valid_chars+) }x;
612 my $ws = qr{ (?>\s*) }x;
613 my $op_union = qr{ $ws \| $ws }x;
615 my ($type, $type_capture_parts, $type_with_parameter, $union, $any);
616 if (Class::MOP::IS_RUNNING_ON_5_10) {
618 = q{ (?&type_atom) (?: \[ (?&ws) (?&any) (?&ws) \] )? };
619 my $type_capture_parts_pattern
620 = q{ ((?&type_atom)) (?: \[ (?&ws) ((?&any)) (?&ws) \] )? };
621 my $type_with_parameter_pattern
622 = q{ (?&type_atom) \[ (?&ws) (?&any) (?&ws) \] };
624 = q{ (?&type) (?> (?: (?&op_union) (?&type) )+ ) };
626 = q{ (?&type) | (?&union) };
628 my $defines = qr{(?(DEFINE)
629 (?<valid_chars> $valid_chars)
630 (?<type_atom> $type_atom)
632 (?<op_union> $op_union)
633 (?<type> $type_pattern)
634 (?<type_capture_parts> $type_capture_parts_pattern)
635 (?<type_with_parameter> $type_with_parameter_pattern)
636 (?<union> $union_pattern)
637 (?<any> $any_pattern)
640 $type = qr{ $type_pattern $defines }x;
641 $type_capture_parts = qr{ $type_capture_parts_pattern $defines }x;
642 $type_with_parameter = qr{ $type_with_parameter_pattern $defines }x;
643 $union = qr{ $union_pattern $defines }x;
644 $any = qr{ $any_pattern $defines }x;
648 = qr{ $type_atom (?: \[ $ws (??{$any}) $ws \] )? }x;
650 = qr{ ($type_atom) (?: \[ $ws ((??{$any})) $ws \] )? }x;
652 = qr{ $type_atom \[ $ws (??{$any}) $ws \] }x;
654 = qr{ $type (?> (?: $op_union $type )+ ) }x;
656 = qr{ $type | $union }x;
660 sub _parse_parameterized_type_constraint {
661 { no warnings 'void'; $any; } # force capture of interpolated lexical
662 $_[0] =~ m{ $type_capture_parts }x;
666 sub _detect_parameterized_type_constraint {
667 { no warnings 'void'; $any; } # force capture of interpolated lexical
668 $_[0] =~ m{ ^ $type_with_parameter $ }x;
671 sub _parse_type_constraint_union {
672 { no warnings 'void'; $any; } # force capture of interpolated lexical
675 while ( $given =~ m{ \G (?: $op_union )? ($type) }gcx ) {
678 ( pos($given) eq length($given) )
679 || __PACKAGE__->_throw_error( "'$given' didn't parse (parse-pos="
687 sub _detect_type_constraint_union {
688 { no warnings 'void'; $any; } # force capture of interpolated lexical
689 $_[0] =~ m{^ $type $op_union $type ( $op_union .* )? $}x;
693 ## --------------------------------------------------------
694 # define some basic built-in types
695 ## --------------------------------------------------------
697 # By making these classes immutable before creating all the types in
698 # Moose::Util::TypeConstraints::Builtin , we avoid repeatedly calling the slow
699 # MOP-based accessors.
701 inline_constructor => 1,
702 constructor_name => "_new",
704 # these are Class::MOP accessors, so they need inlining
705 inline_accessors => 1
706 ) for grep { $_->is_mutable }
707 map { Class::MOP::class_of($_) }
709 Moose::Meta::TypeConstraint
710 Moose::Meta::TypeConstraint::Union
711 Moose::Meta::TypeConstraint::Parameterized
712 Moose::Meta::TypeConstraint::Parameterizable
713 Moose::Meta::TypeConstraint::Class
714 Moose::Meta::TypeConstraint::Role
715 Moose::Meta::TypeConstraint::Enum
716 Moose::Meta::TypeConstraint::DuckType
717 Moose::Meta::TypeConstraint::Registry
720 require Moose::Util::TypeConstraints::Builtins;
721 Moose::Util::TypeConstraints::Builtins::define_builtins($REGISTRY);
723 my @PARAMETERIZABLE_TYPES
724 = map { $REGISTRY->get_type_constraint($_) } qw[ScalarRef ArrayRef HashRef Maybe];
726 sub get_all_parameterizable_types {@PARAMETERIZABLE_TYPES}
728 sub add_parameterizable_type {
731 && $type->isa('Moose::Meta::TypeConstraint::Parameterizable') )
732 || __PACKAGE__->_throw_error(
733 "Type must be a Moose::Meta::TypeConstraint::Parameterizable not $type"
735 push @PARAMETERIZABLE_TYPES => $type;
738 ## --------------------------------------------------------
739 # end of built-in types ...
740 ## --------------------------------------------------------
743 my @BUILTINS = list_all_type_constraints();
744 sub list_all_builtin_type_constraints {@BUILTINS}
751 goto &Moose::throw_error;
756 # ABSTRACT: Type constraint system for Moose
764 use Moose::Util::TypeConstraints;
770 subtype 'NaturalLessThanTen',
773 message { "This number ($_) is not less than ten!" };
779 class_type 'DateTimeClass', { class => 'DateTime' };
781 role_type 'Barks', { role => 'Some::Library::Role::Barks' };
783 enum 'RGBColors', [qw(red green blue)];
785 union 'StringOrArray', [qw( String Array )];
787 no Moose::Util::TypeConstraints;
791 This module provides Moose with the ability to create custom type
792 constraints to be used in attribute definition.
794 =head2 Important Caveat
796 This is B<NOT> a type system for Perl 5. These are type constraints,
797 and they are not used by Moose unless you tell it to. No type
798 inference is performed, expressions are not typed, etc. etc. etc.
800 A type constraint is at heart a small "check if a value is valid"
801 function. A constraint can be associated with an attribute. This
802 simplifies parameter validation, and makes your code clearer to read,
803 because you can refer to constraints by name.
805 =head2 Slightly Less Important Caveat
807 It is B<always> a good idea to quote your type names.
809 This prevents Perl from trying to execute the call as an indirect
810 object call. This can be an issue when you have a subtype with the
811 same name as a valid class.
815 subtype DateTime => as Object => where { $_->isa('DateTime') };
817 will I<just work>, while this:
820 subtype DateTime => as Object => where { $_->isa('DateTime') };
822 will fail silently and cause many headaches. The simple way to solve
823 this, as well as future proof your subtypes from classes which have
824 yet to have been created, is to quote the type name:
827 subtype 'DateTime', as 'Object', where { $_->isa('DateTime') };
829 =head2 Default Type Constraints
831 This module also provides a simple hierarchy for Perl 5 types, here is
832 that hierarchy represented visually.
856 B<NOTE:> Any type followed by a type parameter C<[`a]> can be
857 parameterized, this means you can say:
859 ArrayRef[Int] # an array of integers
860 HashRef[CodeRef] # a hash of str to CODE ref mappings
861 ScalarRef[Int] # a reference to an integer
862 Maybe[Str] # value may be a string, may be undefined
864 If Moose finds a name in brackets that it does not recognize as an
865 existing type, it assumes that this is a class name, for example
866 C<ArrayRef[DateTime]>.
868 B<NOTE:> Unless you parameterize a type, then it is invalid to include
869 the square brackets. I.e. C<ArrayRef[]> will be treated as a new type
870 name, I<not> as a parameterization of C<ArrayRef>.
872 B<NOTE:> The C<Undef> type constraint for the most part works
873 correctly now, but edge cases may still exist, please use it
876 B<NOTE:> The C<ClassName> type constraint does a complex package
877 existence check. This means that your class B<must> be loaded for this
878 type constraint to pass.
880 B<NOTE:> The C<RoleName> constraint checks a string is a I<package
881 name> which is a role, like C<'MyApp::Role::Comparable'>.
883 =head2 Type Constraint Naming
885 Type name declared via this module can only contain alphanumeric
886 characters, colons (:), and periods (.).
888 Since the types created by this module are global, it is suggested
889 that you namespace your types just as you would namespace your
890 modules. So instead of creating a I<Color> type for your
891 B<My::Graphics> module, you would call the type
892 I<My::Graphics::Types::Color> instead.
894 =head2 Use with Other Constraint Modules
896 This module can play nicely with other constraint modules with some
897 slight tweaking. The C<where> clause in types is expected to be a
898 C<CODE> reference which checks its first argument and returns a
899 boolean. Since most constraint modules work in a similar way, it
900 should be simple to adapt them to work with Moose.
902 For instance, this is how you could use it with
903 L<Declare::Constraints::Simple> to declare a completely new type.
905 type 'HashOfArrayOfObjects',
909 -values => IsArrayRef(IsObject)
913 For more examples see the F<t/examples/example_w_DCS.t> test
916 Here is an example of using L<Test::Deep> and its non-test
917 related C<eq_deeply> function.
919 type 'ArrayOfHashOfBarsAndRandomNumbers',
922 array_each(subhashof({
924 random_number => ignore()
928 For a complete example see the
929 F<t/examples/example_w_TestDeep.t> test file.
931 =head2 Error messages
933 Type constraints can also specify custom error messages, for when they fail to
934 validate. This is provided as just another coderef, which receives the invalid
935 value in C<$_>, as in:
937 subtype 'PositiveInt',
940 message { "$_ is not a positive integer!" };
942 If no message is specified, a default message will be used, which indicates
943 which type constraint was being used and what value failed. If
944 L<Devel::PartialDump> (version 0.14 or higher) is installed, it will be used to
945 display the invalid value, otherwise it will just be printed as is.
949 =head2 Type Constraint Constructors
951 The following functions are used to create type constraints. They
952 will also register the type constraints your create in a global
953 registry that is used to look types up by name.
955 See the L</SYNOPSIS> for an example of how to use these.
959 =item B<< subtype 'Name', as 'Parent', where { } ... >>
961 This creates a named subtype.
963 If you provide a parent that Moose does not recognize, it will
964 automatically create a new class type constraint for this name.
966 When creating a named type, the C<subtype> function should either be
967 called with the sugar helpers (C<where>, C<message>, etc), or with a
968 name and a hashref of parameters:
970 subtype( 'Foo', { where => ..., message => ... } );
972 The valid hashref keys are C<as> (the parent), C<where>, C<message>,
975 =item B<< subtype as 'Parent', where { } ... >>
977 This creates an unnamed subtype and will return the type
978 constraint meta-object, which will be an instance of
979 L<Moose::Meta::TypeConstraint>.
981 When creating an anonymous type, the C<subtype> function should either
982 be called with the sugar helpers (C<where>, C<message>, etc), or with
983 just a hashref of parameters:
985 subtype( { where => ..., message => ... } );
987 =item B<class_type ($class, ?$options)>
989 Creates a new subtype of C<Object> with the name C<$class> and the
990 metaclass L<Moose::Meta::TypeConstraint::Class>.
992 # Create a type called 'Box' which tests for objects which ->isa('Box')
995 By default, the name of the type and the name of the class are the same, but
996 you can specify both separately.
998 # Create a type called 'Box' which tests for objects which ->isa('ObjectLibrary::Box');
999 class_type 'Box', { class => 'ObjectLibrary::Box' };
1001 =item B<role_type ($role, ?$options)>
1003 Creates a C<Role> type constraint with the name C<$role> and the
1004 metaclass L<Moose::Meta::TypeConstraint::Role>.
1006 # Create a type called 'Walks' which tests for objects which ->does('Walks')
1009 By default, the name of the type and the name of the role are the same, but
1010 you can specify both separately.
1012 # Create a type called 'Walks' which tests for objects which ->does('MooseX::Role::Walks');
1013 role_type 'Walks', { role => 'MooseX::Role::Walks' };
1015 =item B<maybe_type ($type)>
1017 Creates a type constraint for either C<undef> or something of the
1020 =item B<duck_type ($name, \@methods)>
1022 This will create a subtype of Object and test to make sure the value
1023 C<can()> do the methods in C<\@methods>.
1025 This is intended as an easy way to accept non-Moose objects that
1026 provide a certain interface. If you're using Moose classes, we
1027 recommend that you use a C<requires>-only Role instead.
1029 =item B<duck_type (\@methods)>
1031 If passed an ARRAY reference as the only parameter instead of the
1032 C<$name>, C<\@methods> pair, this will create an unnamed duck type.
1033 This can be used in an attribute definition like so:
1037 isa => duck_type( [qw( get_set )] ),
1040 =item B<enum ($name, \@values)>
1042 This will create a basic subtype for a given set of strings.
1043 The resulting constraint will be a subtype of C<Str> and
1044 will match any of the items in C<\@values>. It is case sensitive.
1045 See the L</SYNOPSIS> for a simple example.
1047 B<NOTE:> This is not a true proper enum type, it is simply
1048 a convenient constraint builder.
1050 =item B<enum (\@values)>
1052 If passed an ARRAY reference as the only parameter instead of the
1053 C<$name>, C<\@values> pair, this will create an unnamed enum. This
1054 can then be used in an attribute definition like so:
1056 has 'sort_order' => (
1058 isa => enum([qw[ ascending descending ]]),
1061 =item B<union ($name, \@constraints)>
1063 This will create a basic subtype where any of the provided constraints
1064 may match in order to satisfy this constraint.
1066 =item B<union (\@constraints)>
1068 If passed an ARRAY reference as the only parameter instead of the
1069 C<$name>, C<\@constraints> pair, this will create an unnamed union.
1070 This can then be used in an attribute definition like so:
1074 isa => union([qw[ Str ArrayRef ]]),
1077 This is similar to the existing string union:
1079 isa => 'Str|ArrayRef'
1081 except that it supports anonymous elements as child constraints:
1085 isa => union([ 'Int', enum([qw[ red green blue ]]) ]),
1088 =item B<as 'Parent'>
1090 This is just sugar for the type constraint construction syntax.
1092 It takes a single argument, which is the name of a parent type.
1094 =item B<where { ... }>
1096 This is just sugar for the type constraint construction syntax.
1098 It takes a subroutine reference as an argument. When the type
1099 constraint is tested, the reference is run with the value to be tested
1100 in C<$_>. This reference should return true or false to indicate
1101 whether or not the constraint check passed.
1103 =item B<message { ... }>
1105 This is just sugar for the type constraint construction syntax.
1107 It takes a subroutine reference as an argument. When the type
1108 constraint fails, then the code block is run with the value provided
1109 in C<$_>. This reference should return a string, which will be used in
1110 the text of the exception thrown.
1112 =item B<inline_as { ... }>
1114 This can be used to define a "hand optimized" inlinable version of your type
1117 You provide a subroutine which will be called I<as a method> on a
1118 L<Moose::Meta::TypeConstraint> object. It will receive a single parameter, the
1119 name of the variable to check, typically something like C<"$_"> or C<"$_[0]">.
1121 The subroutine should return a code string suitable for inlining. You can
1122 assume that the check will be wrapped in parentheses when it is inlined.
1124 The inlined code should include any checks that your type's parent types
1125 do. If your parent type constraint defines its own inlining, you can simply use
1126 that to avoid repeating code. For example, here is the inlining code for the
1127 C<Value> type, which is a subtype of C<Defined>:
1130 $_[0]->parent()->_inline_check($_[1])
1131 . ' && !ref(' . $_[1] . ')'
1134 =item B<optimize_as { ... }>
1136 B<This feature is deprecated, use C<inline_as> instead.>
1138 This can be used to define a "hand optimized" version of your
1139 type constraint which can be used to avoid traversing a subtype
1140 constraint hierarchy.
1142 B<NOTE:> You should only use this if you know what you are doing.
1143 All the built in types use this, so your subtypes (assuming they
1144 are shallow) will not likely need to use this.
1146 =item B<< type 'Name', where { } ... >>
1148 This creates a base type, which has no parent.
1150 The C<type> function should either be called with the sugar helpers
1151 (C<where>, C<message>, etc), or with a name and a hashref of
1154 type( 'Foo', { where => ..., message => ... } );
1156 The valid hashref keys are C<where>, C<message>, and C<inlined_as>.
1160 =head2 Type Constraint Utilities
1164 =item B<< match_on_type $value => ( $type => \&action, ... ?\&default ) >>
1166 This is a utility function for doing simple type based dispatching similar to
1167 match/case in OCaml and case/of in Haskell. It is not as featureful as those
1168 languages, nor does not it support any kind of automatic destructuring
1169 bind. Here is a simple Perl pretty printer dispatching over the core Moose
1174 match_on_type $x => (
1179 join ", " => map { $_ . ' => ' . ppprint( $hash->{$_} ) }
1185 '[ ' . ( join ", " => map { ppprint($_) } @$array ) . ' ]';
1187 CodeRef => sub {'sub { ... }'},
1188 RegexpRef => sub { 'qr/' . $_ . '/' },
1189 GlobRef => sub { '*' . B::svref_2object($_)->NAME },
1190 Object => sub { $_->can('to_string') ? $_->to_string : $_ },
1191 ScalarRef => sub { '\\' . ppprint( ${$_} ) },
1193 Str => sub { '"' . $_ . '"' },
1194 Undef => sub {'undef'},
1195 => sub { die "I don't know what $_ is" }
1199 Or a simple JSON serializer:
1203 match_on_type $x => (
1209 map { '"' . $_ . '" : ' . to_json( $hash->{$_} ) }
1215 '[ ' . ( join ", " => map { to_json($_) } @$array ) . ' ]';
1218 Str => sub { '"' . $_ . '"' },
1219 Undef => sub {'null'},
1220 => sub { die "$_ is not acceptable json type" }
1224 The matcher is done by mapping a C<$type> to an C<\&action>. The C<$type> can
1225 be either a string type or a L<Moose::Meta::TypeConstraint> object, and
1226 C<\&action> is a subroutine reference. This function will dispatch on the
1227 first match for C<$value>. It is possible to have a catch-all by providing an
1228 additional subroutine reference as the final argument to C<match_on_type>.
1232 =head2 Type Coercion Constructors
1234 You can define coercions for type constraints, which allow you to
1235 automatically transform values to something valid for the type
1236 constraint. If you ask your accessor to coerce, then Moose will run
1237 the type-coercion code first, followed by the type constraint
1238 check. This feature should be used carefully as it is very powerful
1239 and could easily take off a limb if you are not careful.
1241 See the L</SYNOPSIS> for an example of how to use these.
1245 =item B<< coerce 'Name', from 'OtherName', via { ... } >>
1247 This defines a coercion from one type to another. The C<Name> argument
1248 is the type you are coercing I<to>.
1250 To define multiple coercions, supply more sets of from/via pairs:
1253 from 'OtherName', via { ... },
1254 from 'ThirdName', via { ... };
1256 =item B<from 'OtherName'>
1258 This is just sugar for the type coercion construction syntax.
1260 It takes a single type name (or type object), which is the type being
1263 =item B<via { ... }>
1265 This is just sugar for the type coercion construction syntax.
1267 It takes a subroutine reference. This reference will be called with
1268 the value to be coerced in C<$_>. It is expected to return a new value
1269 of the proper type for the coercion.
1273 =head2 Creating and Finding Type Constraints
1275 These are additional functions for creating and finding type
1276 constraints. Most of these functions are not available for
1277 importing. The ones that are importable as specified.
1281 =item B<find_type_constraint($type_name)>
1283 This function can be used to locate the L<Moose::Meta::TypeConstraint>
1284 object for a named type.
1286 This function is importable.
1288 =item B<register_type_constraint($type_object)>
1290 This function will register a L<Moose::Meta::TypeConstraint> with the
1291 global type registry.
1293 This function is importable.
1295 =item B<normalize_type_constraint_name($type_constraint_name)>
1297 This method takes a type constraint name and returns the normalized
1298 form. This removes any whitespace in the string.
1300 =item B<create_type_constraint_union($pipe_separated_types | @type_constraint_names)>
1302 =item B<create_named_type_constraint_union($name, $pipe_separated_types | @type_constraint_names)>
1304 This can take a union type specification like C<'Int|ArrayRef[Int]'>,
1305 or a list of names. It returns a new
1306 L<Moose::Meta::TypeConstraint::Union> object.
1308 =item B<create_parameterized_type_constraint($type_name)>
1310 Given a C<$type_name> in the form of C<'BaseType[ContainerType]'>,
1311 this will create a new L<Moose::Meta::TypeConstraint::Parameterized>
1312 object. The C<BaseType> must exist already exist as a parameterizable
1315 =item B<create_class_type_constraint($class, $options)>
1317 Given a class name this function will create a new
1318 L<Moose::Meta::TypeConstraint::Class> object for that class name.
1320 The C<$options> is a hash reference that will be passed to the
1321 L<Moose::Meta::TypeConstraint::Class> constructor (as a hash).
1323 =item B<create_role_type_constraint($role, $options)>
1325 Given a role name this function will create a new
1326 L<Moose::Meta::TypeConstraint::Role> object for that role name.
1328 The C<$options> is a hash reference that will be passed to the
1329 L<Moose::Meta::TypeConstraint::Role> constructor (as a hash).
1331 =item B<create_enum_type_constraint($name, $values)>
1333 Given a enum name this function will create a new
1334 L<Moose::Meta::TypeConstraint::Enum> object for that enum name.
1336 =item B<create_duck_type_constraint($name, $methods)>
1338 Given a duck type name this function will create a new
1339 L<Moose::Meta::TypeConstraint::DuckType> object for that enum name.
1341 =item B<find_or_parse_type_constraint($type_name)>
1343 Given a type name, this first attempts to find a matching constraint
1344 in the global registry.
1346 If the type name is a union or parameterized type, it will create a
1347 new object of the appropriate, but if given a "regular" type that does
1348 not yet exist, it simply returns false.
1350 When given a union or parameterized type, the member or base type must
1353 If it creates a new union or parameterized type, it will add it to the
1356 =item B<find_or_create_isa_type_constraint($type_name)>
1358 =item B<find_or_create_does_type_constraint($type_name)>
1360 These functions will first call C<find_or_parse_type_constraint>. If
1361 that function does not return a type, a new type object will
1364 The C<isa> variant will use C<create_class_type_constraint> and the
1365 C<does> variant will use C<create_role_type_constraint>.
1367 =item B<get_type_constraint_registry>
1369 Returns the L<Moose::Meta::TypeConstraint::Registry> object which
1370 keeps track of all type constraints.
1372 =item B<list_all_type_constraints>
1374 This will return a list of type constraint names in the global
1375 registry. You can then fetch the actual type object using
1376 C<find_type_constraint($type_name)>.
1378 =item B<list_all_builtin_type_constraints>
1380 This will return a list of builtin type constraints, meaning those
1381 which are defined in this module. See the L<Default Type Constraints>
1382 section for a complete list.
1384 =item B<export_type_constraints_as_functions>
1386 This will export all the current type constraints as functions into
1387 the caller's namespace (C<Int()>, C<Str()>, etc). Right now, this is
1388 mostly used for testing, but it might prove useful to others.
1390 =item B<get_all_parameterizable_types>
1392 This returns all the parameterizable types that have been registered,
1393 as a list of type objects.
1395 =item B<add_parameterizable_type($type)>
1397 Adds C<$type> to the list of parameterizable types
1403 See L<Moose/BUGS> for details on reporting bugs.