2 package Moose::Util::TypeConstraints;
5 use List::MoreUtils qw( all any );
6 use Scalar::Util qw( blessed reftype );
10 ## --------------------------------------------------------
11 # Prototyped subs must be predeclared because we have a
12 # circular dependency with Moose::Meta::Attribute et. al.
13 # so in case of us being use'd first the predeclaration
14 # ensures the prototypes are in scope when consumers are
24 ## --------------------------------------------------------
26 use Moose::Deprecated;
27 use Moose::Meta::TypeConstraint;
28 use Moose::Meta::TypeConstraint::Union;
29 use Moose::Meta::TypeConstraint::Parameterized;
30 use Moose::Meta::TypeConstraint::Parameterizable;
31 use Moose::Meta::TypeConstraint::Class;
32 use Moose::Meta::TypeConstraint::Role;
33 use Moose::Meta::TypeConstraint::Enum;
34 use Moose::Meta::TypeConstraint::DuckType;
35 use Moose::Meta::TypeCoercion;
36 use Moose::Meta::TypeCoercion::Union;
37 use Moose::Meta::TypeConstraint::Registry;
39 Moose::Exporter->setup_import_methods(
42 type subtype class_type role_type maybe_type duck_type
43 as where message optimize_as inline_as
47 register_type_constraint
52 ## --------------------------------------------------------
53 ## type registry and some useful functions for it
54 ## --------------------------------------------------------
56 my $REGISTRY = Moose::Meta::TypeConstraint::Registry->new;
58 sub get_type_constraint_registry {$REGISTRY}
59 sub list_all_type_constraints { keys %{ $REGISTRY->type_constraints } }
61 sub export_type_constraints_as_functions {
64 foreach my $constraint ( keys %{ $REGISTRY->type_constraints } ) {
65 my $tc = $REGISTRY->get_type_constraint($constraint)
66 ->_compiled_type_constraint;
67 *{"${pkg}::${constraint}"}
68 = sub { $tc->( $_[0] ) ? 1 : undef }; # the undef is for compat
72 sub create_type_constraint_union {
73 _create_type_constraint_union(\@_);
76 sub create_named_type_constraint_union {
78 _create_type_constraint_union($name, \@_);
81 sub _create_type_constraint_union {
83 $name = shift if @_ > 1;
84 my @tcs = @{ shift() };
86 my @type_constraint_names;
88 if ( scalar @tcs == 1 && _detect_type_constraint_union( $tcs[0] ) ) {
89 @type_constraint_names = _parse_type_constraint_union( $tcs[0] );
92 @type_constraint_names = @tcs;
95 ( scalar @type_constraint_names >= 2 )
96 || __PACKAGE__->_throw_error(
97 "You must pass in at least 2 type names to make a union");
99 my @type_constraints = map {
100 find_or_parse_type_constraint($_)
101 || __PACKAGE__->_throw_error(
102 "Could not locate type constraint ($_) for the union");
103 } @type_constraint_names;
106 type_constraints => \@type_constraints
108 $options{name} = $name if defined $name;
110 return Moose::Meta::TypeConstraint::Union->new(%options);
114 sub create_parameterized_type_constraint {
115 my $type_constraint_name = shift;
116 my ( $base_type, $type_parameter )
117 = _parse_parameterized_type_constraint($type_constraint_name);
119 ( defined $base_type && defined $type_parameter )
120 || __PACKAGE__->_throw_error(
121 "Could not parse type name ($type_constraint_name) correctly");
123 if ( $REGISTRY->has_type_constraint($base_type) ) {
124 my $base_type_tc = $REGISTRY->get_type_constraint($base_type);
125 return _create_parameterized_type_constraint(
131 __PACKAGE__->_throw_error(
132 "Could not locate the base type ($base_type)");
136 sub _create_parameterized_type_constraint {
137 my ( $base_type_tc, $type_parameter ) = @_;
138 if ( $base_type_tc->can('parameterize') ) {
139 return $base_type_tc->parameterize($type_parameter);
142 return Moose::Meta::TypeConstraint::Parameterized->new(
143 name => $base_type_tc->name . '[' . $type_parameter . ']',
144 parent => $base_type_tc,
146 find_or_create_isa_type_constraint($type_parameter),
151 #should we also support optimized checks?
152 sub create_class_type_constraint {
153 my ( $class, $options ) = @_;
155 # too early for this check
156 #find_type_constraint("ClassName")->check($class)
157 # || __PACKAGE__->_throw_error("Can't create a class type constraint because '$class' is not a class name");
159 my $pkg_defined_in = $options->{package_defined_in} || scalar( caller(1) );
161 if (my $type = $REGISTRY->get_type_constraint($class)) {
162 if (!($type->isa('Moose::Meta::TypeConstraint::Class') && $type->class eq $class)) {
164 "The type constraint '$class' has already been created in "
165 . $type->_package_defined_in
166 . " and cannot be created again in "
177 package_defined_in => $pkg_defined_in,
181 $options{name} ||= "__ANON__";
183 my $tc = Moose::Meta::TypeConstraint::Class->new(%options);
184 $REGISTRY->add_type_constraint($tc);
188 sub create_role_type_constraint {
189 my ( $role, $options ) = @_;
191 # too early for this check
192 #find_type_constraint("ClassName")->check($class)
193 # || __PACKAGE__->_throw_error("Can't create a class type constraint because '$class' is not a class name");
195 my $pkg_defined_in = $options->{package_defined_in} || scalar( caller(1) );
197 if (my $type = $REGISTRY->get_type_constraint($role)) {
198 if (!($type->isa('Moose::Meta::TypeConstraint::Role') && $type->role eq $role)) {
200 "The type constraint '$role' has already been created in "
201 . $type->_package_defined_in
202 . " and cannot be created again in "
213 package_defined_in => $pkg_defined_in,
217 $options{name} ||= "__ANON__";
219 my $tc = Moose::Meta::TypeConstraint::Role->new(%options);
220 $REGISTRY->add_type_constraint($tc);
224 sub find_or_create_type_constraint {
225 my ( $type_constraint_name, $options_for_anon_type ) = @_;
228 = find_or_parse_type_constraint($type_constraint_name) ) {
231 elsif ( defined $options_for_anon_type ) {
234 # if there is no $options_for_anon_type
235 # specified, then we assume they don't
236 # want to create one, and return nothing.
238 # otherwise assume that we should create
239 # an ANON type with the $options_for_anon_type
240 # options which can be passed in. It should
241 # be noted that these don't get registered
242 # so we need to return it.
244 return Moose::Meta::TypeConstraint->new(
246 %{$options_for_anon_type}
253 sub find_or_create_isa_type_constraint {
254 my ($type_constraint_name, $options) = @_;
255 find_or_parse_type_constraint($type_constraint_name)
256 || create_class_type_constraint($type_constraint_name, $options);
259 sub find_or_create_does_type_constraint {
260 my ($type_constraint_name, $options) = @_;
261 find_or_parse_type_constraint($type_constraint_name)
262 || create_role_type_constraint($type_constraint_name, $options);
265 sub find_or_parse_type_constraint {
266 my $type_constraint_name = normalize_type_constraint_name(shift);
269 if ( $constraint = find_type_constraint($type_constraint_name) ) {
272 elsif ( _detect_type_constraint_union($type_constraint_name) ) {
273 $constraint = create_type_constraint_union($type_constraint_name);
275 elsif ( _detect_parameterized_type_constraint($type_constraint_name) ) {
277 = create_parameterized_type_constraint($type_constraint_name);
283 $REGISTRY->add_type_constraint($constraint);
287 sub normalize_type_constraint_name {
288 my $type_constraint_name = shift;
289 $type_constraint_name =~ s/\s//g;
290 return $type_constraint_name;
296 local $Carp::CarpLevel = $Carp::CarpLevel + 1;
297 Carp::confess($error);
300 ## --------------------------------------------------------
301 ## exported functions ...
302 ## --------------------------------------------------------
304 sub find_type_constraint {
307 if ( blessed $type and $type->isa("Moose::Meta::TypeConstraint") ) {
311 return unless $REGISTRY->has_type_constraint($type);
312 return $REGISTRY->get_type_constraint($type);
316 sub register_type_constraint {
317 my $constraint = shift;
318 __PACKAGE__->_throw_error("can't register an unnamed type constraint")
319 unless defined $constraint->name;
320 $REGISTRY->add_type_constraint($constraint);
329 my %p = map { %{$_} } @_;
331 return _create_type_constraint(
332 $name, undef, $p{where}, $p{message},
333 $p{optimize_as}, $p{inline_as},
338 if ( @_ == 1 && !ref $_[0] ) {
339 __PACKAGE__->_throw_error(
340 'A subtype cannot consist solely of a name, it must have a parent'
344 # The blessed check is mostly to accommodate MooseX::Types, which
345 # uses an object which overloads stringification as a type name.
346 my $name = ref $_[0] && !blessed $_[0] ? undef : shift;
348 my %p = map { %{$_} } @_;
350 # subtype Str => where { ... };
351 if ( !exists $p{as} ) {
356 return _create_type_constraint(
357 $name, $p{as}, $p{where}, $p{message},
358 $p{optimize_as}, $p{inline_as},
363 create_class_type_constraint(@_);
366 sub role_type ($;$) {
367 create_role_type_constraint(@_);
371 my ($type_parameter) = @_;
373 register_type_constraint(
374 $REGISTRY->get_type_constraint('Maybe')->parameterize($type_parameter)
379 my ( $type_name, @methods ) = @_;
380 if ( ref $type_name eq 'ARRAY' && !@methods ) {
381 @methods = ($type_name);
384 if ( @methods == 1 && ref $methods[0] eq 'ARRAY' ) {
385 @methods = @{ $methods[0] };
388 Moose::Deprecated::deprecated(
389 feature => 'non-arrayref form of duck_type',
390 message => "Passing a list of values to duck_type is deprecated. "
391 . "The method names should be wrapped in an arrayref.",
395 register_type_constraint(
396 create_duck_type_constraint(
404 my ( $type_name, @coercion_map ) = @_;
405 _install_type_coercions( $type_name, \@coercion_map );
408 # The trick of returning @_ lets us avoid having to specify a
409 # prototype. Perl will parse this:
417 # subtype( 'Foo', as( 'Str', where { ... } ) );
419 # If as() returns all its extra arguments, this just works, and
420 # preserves backwards compatibility.
421 sub as { { as => shift }, @_ }
422 sub where (&) { { where => $_[0] } }
423 sub message (&) { { message => $_[0] } }
424 sub optimize_as (&) { { optimize_as => $_[0] } }
425 sub inline_as (&) { { inline_as => $_[0] } }
428 sub via (&) { $_[0] }
431 my ( $type_name, @values ) = @_;
434 # if only an array-ref is passed then
435 # you get an anon-enum
437 if ( ref $type_name eq 'ARRAY' ) {
439 || __PACKAGE__->_throw_error("enum called with an array reference and additional arguments. Did you mean to parenthesize the enum call's parameters?");
441 @values = ($type_name);
444 if ( @values == 1 && ref $values[0] eq 'ARRAY' ) {
445 @values = @{ $values[0] };
448 Moose::Deprecated::deprecated(
449 feature => 'non-arrayref form of enum',
450 message => "Passing a list of values to enum is deprecated. "
451 . "Enum values should be wrapped in an arrayref.",
455 register_type_constraint(
456 create_enum_type_constraint(
464 my ( $type_name, @constraints ) = @_;
465 if ( ref $type_name eq 'ARRAY' ) {
467 || __PACKAGE__->_throw_error("union called with an array reference and additional arguments.");
468 @constraints = @$type_name;
471 if ( @constraints == 1 && ref $constraints[0] eq 'ARRAY' ) {
472 @constraints = @{ $constraints[0] };
474 if ( defined $type_name ) {
475 return register_type_constraint(
476 create_named_type_constraint_union( $type_name, @constraints )
479 return create_type_constraint_union( @constraints );
482 sub create_enum_type_constraint {
483 my ( $type_name, $values ) = @_;
485 Moose::Meta::TypeConstraint::Enum->new(
486 name => $type_name || '__ANON__',
491 sub create_duck_type_constraint {
492 my ( $type_name, $methods ) = @_;
494 Moose::Meta::TypeConstraint::DuckType->new(
495 name => $type_name || '__ANON__',
501 my ($to_match, @cases) = @_;
503 if (@cases % 2 != 0) {
504 $default = pop @cases;
505 (ref $default eq 'CODE')
506 || __PACKAGE__->_throw_error("Default case must be a CODE ref, not $default");
509 my ($type, $action) = splice @cases, 0, 2;
511 unless (blessed $type && $type->isa('Moose::Meta::TypeConstraint')) {
512 $type = find_or_parse_type_constraint($type)
513 || __PACKAGE__->_throw_error("Cannot find or parse the type '$type'")
516 (ref $action eq 'CODE')
517 || __PACKAGE__->_throw_error("Match action must be a CODE ref, not $action");
519 if ($type->check($to_match)) {
520 local $_ = $to_match;
521 return $action->($to_match);
525 || __PACKAGE__->_throw_error("No cases matched for $to_match");
527 local $_ = $to_match;
528 return $default->($to_match);
533 ## --------------------------------------------------------
534 ## desugaring functions ...
535 ## --------------------------------------------------------
537 sub _create_type_constraint ($$$;$$) {
542 my $optimized = shift;
545 my $pkg_defined_in = scalar( caller(1) );
547 if ( defined $name ) {
548 my $type = $REGISTRY->get_type_constraint($name);
550 ( $type->_package_defined_in eq $pkg_defined_in )
552 "The type constraint '$name' has already been created in "
553 . $type->_package_defined_in
554 . " and cannot be created again in "
558 $name =~ /^[\w:\.]+$/
559 or die qq{$name contains invalid characters for a type name.}
560 . qq{ Names can contain alphanumeric character, ":", and "."\n};
565 package_defined_in => $pkg_defined_in,
567 ( $check ? ( constraint => $check ) : () ),
568 ( $message ? ( message => $message ) : () ),
569 ( $optimized ? ( optimized => $optimized ) : () ),
570 ( $inlined ? ( inlined => $inlined ) : () ),
579 : find_or_create_isa_type_constraint($parent)
581 $constraint = $parent->create_child_type(%opts);
584 $constraint = Moose::Meta::TypeConstraint->new(%opts);
587 $REGISTRY->add_type_constraint($constraint)
593 sub _install_type_coercions ($$) {
594 my ( $type_name, $coercion_map ) = @_;
595 my $type = find_type_constraint($type_name);
597 || __PACKAGE__->_throw_error(
598 "Cannot find type '$type_name', perhaps you forgot to load it");
599 if ( $type->has_coercion ) {
600 $type->coercion->add_type_coercions(@$coercion_map);
603 my $type_coercion = Moose::Meta::TypeCoercion->new(
604 type_coercion_map => $coercion_map,
605 type_constraint => $type
607 $type->coercion($type_coercion);
611 ## --------------------------------------------------------
612 ## type notation parsing ...
613 ## --------------------------------------------------------
617 # All I have to say is mugwump++ cause I know
618 # do not even have enough regexp-fu to be able
619 # to have written this (I can only barely
620 # understand it as it is)
625 my $valid_chars = qr{[\w:\.]};
626 my $type_atom = qr{ (?>$valid_chars+) }x;
627 my $ws = qr{ (?>\s*) }x;
628 my $op_union = qr{ $ws \| $ws }x;
630 my ($type, $type_capture_parts, $type_with_parameter, $union, $any);
631 if (Class::MOP::IS_RUNNING_ON_5_10) {
633 = q{ (?&type_atom) (?: \[ (?&ws) (?&any) (?&ws) \] )? };
634 my $type_capture_parts_pattern
635 = q{ ((?&type_atom)) (?: \[ (?&ws) ((?&any)) (?&ws) \] )? };
636 my $type_with_parameter_pattern
637 = q{ (?&type_atom) \[ (?&ws) (?&any) (?&ws) \] };
639 = q{ (?&type) (?> (?: (?&op_union) (?&type) )+ ) };
641 = q{ (?&type) | (?&union) };
643 my $defines = qr{(?(DEFINE)
644 (?<valid_chars> $valid_chars)
645 (?<type_atom> $type_atom)
647 (?<op_union> $op_union)
648 (?<type> $type_pattern)
649 (?<type_capture_parts> $type_capture_parts_pattern)
650 (?<type_with_parameter> $type_with_parameter_pattern)
651 (?<union> $union_pattern)
652 (?<any> $any_pattern)
655 $type = qr{ $type_pattern $defines }x;
656 $type_capture_parts = qr{ $type_capture_parts_pattern $defines }x;
657 $type_with_parameter = qr{ $type_with_parameter_pattern $defines }x;
658 $union = qr{ $union_pattern $defines }x;
659 $any = qr{ $any_pattern $defines }x;
663 = qr{ $type_atom (?: \[ $ws (??{$any}) $ws \] )? }x;
665 = qr{ ($type_atom) (?: \[ $ws ((??{$any})) $ws \] )? }x;
667 = qr{ $type_atom \[ $ws (??{$any}) $ws \] }x;
669 = qr{ $type (?> (?: $op_union $type )+ ) }x;
671 = qr{ $type | $union }x;
675 sub _parse_parameterized_type_constraint {
676 { no warnings 'void'; $any; } # force capture of interpolated lexical
677 $_[0] =~ m{ $type_capture_parts }x;
681 sub _detect_parameterized_type_constraint {
682 { no warnings 'void'; $any; } # force capture of interpolated lexical
683 $_[0] =~ m{ ^ $type_with_parameter $ }x;
686 sub _parse_type_constraint_union {
687 { no warnings 'void'; $any; } # force capture of interpolated lexical
690 while ( $given =~ m{ \G (?: $op_union )? ($type) }gcx ) {
693 ( pos($given) eq length($given) )
694 || __PACKAGE__->_throw_error( "'$given' didn't parse (parse-pos="
702 sub _detect_type_constraint_union {
703 { no warnings 'void'; $any; } # force capture of interpolated lexical
704 $_[0] =~ m{^ $type $op_union $type ( $op_union .* )? $}x;
708 ## --------------------------------------------------------
709 # define some basic built-in types
710 ## --------------------------------------------------------
712 # By making these classes immutable before creating all the types in
713 # Moose::Util::TypeConstraints::Builtin , we avoid repeatedly calling the slow
714 # MOP-based accessors.
716 inline_constructor => 1,
717 constructor_name => "_new",
719 # these are Class::MOP accessors, so they need inlining
720 inline_accessors => 1
721 ) for grep { $_->is_mutable }
722 map { Class::MOP::class_of($_) }
724 Moose::Meta::TypeConstraint
725 Moose::Meta::TypeConstraint::Union
726 Moose::Meta::TypeConstraint::Parameterized
727 Moose::Meta::TypeConstraint::Parameterizable
728 Moose::Meta::TypeConstraint::Class
729 Moose::Meta::TypeConstraint::Role
730 Moose::Meta::TypeConstraint::Enum
731 Moose::Meta::TypeConstraint::DuckType
732 Moose::Meta::TypeConstraint::Registry
735 require Moose::Util::TypeConstraints::Builtins;
736 Moose::Util::TypeConstraints::Builtins::define_builtins($REGISTRY);
738 my @PARAMETERIZABLE_TYPES
739 = map { $REGISTRY->get_type_constraint($_) } qw[ScalarRef ArrayRef HashRef Maybe];
741 sub get_all_parameterizable_types {@PARAMETERIZABLE_TYPES}
743 sub add_parameterizable_type {
746 && $type->isa('Moose::Meta::TypeConstraint::Parameterizable') )
747 || __PACKAGE__->_throw_error(
748 "Type must be a Moose::Meta::TypeConstraint::Parameterizable not $type"
750 push @PARAMETERIZABLE_TYPES => $type;
753 ## --------------------------------------------------------
754 # end of built-in types ...
755 ## --------------------------------------------------------
758 my @BUILTINS = list_all_type_constraints();
759 sub list_all_builtin_type_constraints {@BUILTINS}
766 goto &Moose::throw_error;
771 # ABSTRACT: Type constraint system for Moose
779 use Moose::Util::TypeConstraints;
785 subtype 'NaturalLessThanTen',
788 message { "This number ($_) is not less than ten!" };
794 class_type 'DateTimeClass', { class => 'DateTime' };
796 role_type 'Barks', { role => 'Some::Library::Role::Barks' };
798 enum 'RGBColors', [qw(red green blue)];
800 union 'StringOrArray', [qw( String Array )];
802 no Moose::Util::TypeConstraints;
806 This module provides Moose with the ability to create custom type
807 constraints to be used in attribute definition.
809 =head2 Important Caveat
811 This is B<NOT> a type system for Perl 5. These are type constraints,
812 and they are not used by Moose unless you tell it to. No type
813 inference is performed, expressions are not typed, etc. etc. etc.
815 A type constraint is at heart a small "check if a value is valid"
816 function. A constraint can be associated with an attribute. This
817 simplifies parameter validation, and makes your code clearer to read,
818 because you can refer to constraints by name.
820 =head2 Slightly Less Important Caveat
822 It is B<always> a good idea to quote your type names.
824 This prevents Perl from trying to execute the call as an indirect
825 object call. This can be an issue when you have a subtype with the
826 same name as a valid class.
830 subtype DateTime => as Object => where { $_->isa('DateTime') };
832 will I<just work>, while this:
835 subtype DateTime => as Object => where { $_->isa('DateTime') };
837 will fail silently and cause many headaches. The simple way to solve
838 this, as well as future proof your subtypes from classes which have
839 yet to have been created, is to quote the type name:
842 subtype 'DateTime', as 'Object', where { $_->isa('DateTime') };
844 =head2 Default Type Constraints
846 This module also provides a simple hierarchy for Perl 5 types, here is
847 that hierarchy represented visually.
871 B<NOTE:> Any type followed by a type parameter C<[`a]> can be
872 parameterized, this means you can say:
874 ArrayRef[Int] # an array of integers
875 HashRef[CodeRef] # a hash of str to CODE ref mappings
876 ScalarRef[Int] # a reference to an integer
877 Maybe[Str] # value may be a string, may be undefined
879 If Moose finds a name in brackets that it does not recognize as an
880 existing type, it assumes that this is a class name, for example
881 C<ArrayRef[DateTime]>.
883 B<NOTE:> Unless you parameterize a type, then it is invalid to include
884 the square brackets. I.e. C<ArrayRef[]> will be treated as a new type
885 name, I<not> as a parameterization of C<ArrayRef>.
887 B<NOTE:> The C<Undef> type constraint for the most part works
888 correctly now, but edge cases may still exist, please use it
891 B<NOTE:> The C<ClassName> type constraint does a complex package
892 existence check. This means that your class B<must> be loaded for this
893 type constraint to pass.
895 B<NOTE:> The C<RoleName> constraint checks a string is a I<package
896 name> which is a role, like C<'MyApp::Role::Comparable'>.
898 =head2 Type Constraint Naming
900 Type name declared via this module can only contain alphanumeric
901 characters, colons (:), and periods (.).
903 Since the types created by this module are global, it is suggested
904 that you namespace your types just as you would namespace your
905 modules. So instead of creating a I<Color> type for your
906 B<My::Graphics> module, you would call the type
907 I<My::Graphics::Types::Color> instead.
909 =head2 Use with Other Constraint Modules
911 This module can play nicely with other constraint modules with some
912 slight tweaking. The C<where> clause in types is expected to be a
913 C<CODE> reference which checks its first argument and returns a
914 boolean. Since most constraint modules work in a similar way, it
915 should be simple to adapt them to work with Moose.
917 For instance, this is how you could use it with
918 L<Declare::Constraints::Simple> to declare a completely new type.
920 type 'HashOfArrayOfObjects',
924 -values => IsArrayRef(IsObject)
928 For more examples see the F<t/examples/example_w_DCS.t> test
931 Here is an example of using L<Test::Deep> and its non-test
932 related C<eq_deeply> function.
934 type 'ArrayOfHashOfBarsAndRandomNumbers',
937 array_each(subhashof({
939 random_number => ignore()
943 For a complete example see the
944 F<t/examples/example_w_TestDeep.t> test file.
946 =head2 Error messages
948 Type constraints can also specify custom error messages, for when they fail to
949 validate. This is provided as just another coderef, which receives the invalid
950 value in C<$_>, as in:
952 subtype 'PositiveInt',
955 message { "$_ is not a positive integer!" };
957 If no message is specified, a default message will be used, which indicates
958 which type constraint was being used and what value failed. If
959 L<Devel::PartialDump> (version 0.14 or higher) is installed, it will be used to
960 display the invalid value, otherwise it will just be printed as is.
964 =head2 Type Constraint Constructors
966 The following functions are used to create type constraints. They
967 will also register the type constraints your create in a global
968 registry that is used to look types up by name.
970 See the L</SYNOPSIS> for an example of how to use these.
974 =item B<< subtype 'Name', as 'Parent', where { } ... >>
976 This creates a named subtype.
978 If you provide a parent that Moose does not recognize, it will
979 automatically create a new class type constraint for this name.
981 When creating a named type, the C<subtype> function should either be
982 called with the sugar helpers (C<where>, C<message>, etc), or with a
983 name and a hashref of parameters:
985 subtype( 'Foo', { where => ..., message => ... } );
987 The valid hashref keys are C<as> (the parent), C<where>, C<message>,
990 =item B<< subtype as 'Parent', where { } ... >>
992 This creates an unnamed subtype and will return the type
993 constraint meta-object, which will be an instance of
994 L<Moose::Meta::TypeConstraint>.
996 When creating an anonymous type, the C<subtype> function should either
997 be called with the sugar helpers (C<where>, C<message>, etc), or with
998 just a hashref of parameters:
1000 subtype( { where => ..., message => ... } );
1002 =item B<class_type ($class, ?$options)>
1004 Creates a new subtype of C<Object> with the name C<$class> and the
1005 metaclass L<Moose::Meta::TypeConstraint::Class>.
1007 # Create a type called 'Box' which tests for objects which ->isa('Box')
1010 By default, the name of the type and the name of the class are the same, but
1011 you can specify both separately.
1013 # Create a type called 'Box' which tests for objects which ->isa('ObjectLibrary::Box');
1014 class_type 'Box', { class => 'ObjectLibrary::Box' };
1016 =item B<role_type ($role, ?$options)>
1018 Creates a C<Role> type constraint with the name C<$role> and the
1019 metaclass L<Moose::Meta::TypeConstraint::Role>.
1021 # Create a type called 'Walks' which tests for objects which ->does('Walks')
1024 By default, the name of the type and the name of the role are the same, but
1025 you can specify both separately.
1027 # Create a type called 'Walks' which tests for objects which ->does('MooseX::Role::Walks');
1028 role_type 'Walks', { role => 'MooseX::Role::Walks' };
1030 =item B<maybe_type ($type)>
1032 Creates a type constraint for either C<undef> or something of the
1035 =item B<duck_type ($name, \@methods)>
1037 This will create a subtype of Object and test to make sure the value
1038 C<can()> do the methods in C<\@methods>.
1040 This is intended as an easy way to accept non-Moose objects that
1041 provide a certain interface. If you're using Moose classes, we
1042 recommend that you use a C<requires>-only Role instead.
1044 =item B<duck_type (\@methods)>
1046 If passed an ARRAY reference as the only parameter instead of the
1047 C<$name>, C<\@methods> pair, this will create an unnamed duck type.
1048 This can be used in an attribute definition like so:
1052 isa => duck_type( [qw( get_set )] ),
1055 =item B<enum ($name, \@values)>
1057 This will create a basic subtype for a given set of strings.
1058 The resulting constraint will be a subtype of C<Str> and
1059 will match any of the items in C<\@values>. It is case sensitive.
1060 See the L</SYNOPSIS> for a simple example.
1062 B<NOTE:> This is not a true proper enum type, it is simply
1063 a convenient constraint builder.
1065 =item B<enum (\@values)>
1067 If passed an ARRAY reference as the only parameter instead of the
1068 C<$name>, C<\@values> pair, this will create an unnamed enum. This
1069 can then be used in an attribute definition like so:
1071 has 'sort_order' => (
1073 isa => enum([qw[ ascending descending ]]),
1076 =item B<union ($name, \@constraints)>
1078 This will create a basic subtype where any of the provided constraints
1079 may match in order to satisfy this constraint.
1081 =item B<union (\@constraints)>
1083 If passed an ARRAY reference as the only parameter instead of the
1084 C<$name>, C<\@constraints> pair, this will create an unnamed union.
1085 This can then be used in an attribute definition like so:
1089 isa => union([qw[ Str ArrayRef ]]),
1092 This is similar to the existing string union:
1094 isa => 'Str|ArrayRef'
1096 except that it supports anonymous elements as child constraints:
1100 isa => union([ 'Int', enum([qw[ red green blue ]]) ]),
1103 =item B<as 'Parent'>
1105 This is just sugar for the type constraint construction syntax.
1107 It takes a single argument, which is the name of a parent type.
1109 =item B<where { ... }>
1111 This is just sugar for the type constraint construction syntax.
1113 It takes a subroutine reference as an argument. When the type
1114 constraint is tested, the reference is run with the value to be tested
1115 in C<$_>. This reference should return true or false to indicate
1116 whether or not the constraint check passed.
1118 =item B<message { ... }>
1120 This is just sugar for the type constraint construction syntax.
1122 It takes a subroutine reference as an argument. When the type
1123 constraint fails, then the code block is run with the value provided
1124 in C<$_>. This reference should return a string, which will be used in
1125 the text of the exception thrown.
1127 =item B<inline_as { ... }>
1129 This can be used to define a "hand optimized" inlinable version of your type
1132 You provide a subroutine which will be called I<as a method> on a
1133 L<Moose::Meta::TypeConstraint> object. It will receive a single parameter, the
1134 name of the variable to check, typically something like C<"$_"> or C<"$_[0]">.
1136 The subroutine should return a code string suitable for inlining. You can
1137 assume that the check will be wrapped in parentheses when it is inlined.
1139 The inlined code should include any checks that your type's parent types
1140 do. If your parent type constraint defines its own inlining, you can simply use
1141 that to avoid repeating code. For example, here is the inlining code for the
1142 C<Value> type, which is a subtype of C<Defined>:
1145 $_[0]->parent()->_inline_check($_[1])
1146 . ' && !ref(' . $_[1] . ')'
1149 =item B<optimize_as { ... }>
1151 B<This feature is deprecated, use C<inline_as> instead.>
1153 This can be used to define a "hand optimized" version of your
1154 type constraint which can be used to avoid traversing a subtype
1155 constraint hierarchy.
1157 B<NOTE:> You should only use this if you know what you are doing.
1158 All the built in types use this, so your subtypes (assuming they
1159 are shallow) will not likely need to use this.
1161 =item B<< type 'Name', where { } ... >>
1163 This creates a base type, which has no parent.
1165 The C<type> function should either be called with the sugar helpers
1166 (C<where>, C<message>, etc), or with a name and a hashref of
1169 type( 'Foo', { where => ..., message => ... } );
1171 The valid hashref keys are C<where>, C<message>, and C<inlined_as>.
1175 =head2 Type Constraint Utilities
1179 =item B<< match_on_type $value => ( $type => \&action, ... ?\&default ) >>
1181 This is a utility function for doing simple type based dispatching similar to
1182 match/case in OCaml and case/of in Haskell. It is not as featureful as those
1183 languages, nor does not it support any kind of automatic destructuring
1184 bind. Here is a simple Perl pretty printer dispatching over the core Moose
1189 match_on_type $x => (
1194 join ", " => map { $_ . ' => ' . ppprint( $hash->{$_} ) }
1200 '[ ' . ( join ", " => map { ppprint($_) } @$array ) . ' ]';
1202 CodeRef => sub {'sub { ... }'},
1203 RegexpRef => sub { 'qr/' . $_ . '/' },
1204 GlobRef => sub { '*' . B::svref_2object($_)->NAME },
1205 Object => sub { $_->can('to_string') ? $_->to_string : $_ },
1206 ScalarRef => sub { '\\' . ppprint( ${$_} ) },
1208 Str => sub { '"' . $_ . '"' },
1209 Undef => sub {'undef'},
1210 => sub { die "I don't know what $_ is" }
1214 Or a simple JSON serializer:
1218 match_on_type $x => (
1224 map { '"' . $_ . '" : ' . to_json( $hash->{$_} ) }
1230 '[ ' . ( join ", " => map { to_json($_) } @$array ) . ' ]';
1233 Str => sub { '"' . $_ . '"' },
1234 Undef => sub {'null'},
1235 => sub { die "$_ is not acceptable json type" }
1239 The matcher is done by mapping a C<$type> to an C<\&action>. The C<$type> can
1240 be either a string type or a L<Moose::Meta::TypeConstraint> object, and
1241 C<\&action> is a subroutine reference. This function will dispatch on the
1242 first match for C<$value>. It is possible to have a catch-all by providing an
1243 additional subroutine reference as the final argument to C<match_on_type>.
1247 =head2 Type Coercion Constructors
1249 You can define coercions for type constraints, which allow you to
1250 automatically transform values to something valid for the type
1251 constraint. If you ask your accessor to coerce, then Moose will run
1252 the type-coercion code first, followed by the type constraint
1253 check. This feature should be used carefully as it is very powerful
1254 and could easily take off a limb if you are not careful.
1256 See the L</SYNOPSIS> for an example of how to use these.
1260 =item B<< coerce 'Name', from 'OtherName', via { ... } >>
1262 This defines a coercion from one type to another. The C<Name> argument
1263 is the type you are coercing I<to>.
1265 To define multiple coercions, supply more sets of from/via pairs:
1268 from 'OtherName', via { ... },
1269 from 'ThirdName', via { ... };
1271 =item B<from 'OtherName'>
1273 This is just sugar for the type coercion construction syntax.
1275 It takes a single type name (or type object), which is the type being
1278 =item B<via { ... }>
1280 This is just sugar for the type coercion construction syntax.
1282 It takes a subroutine reference. This reference will be called with
1283 the value to be coerced in C<$_>. It is expected to return a new value
1284 of the proper type for the coercion.
1288 =head2 Creating and Finding Type Constraints
1290 These are additional functions for creating and finding type
1291 constraints. Most of these functions are not available for
1292 importing. The ones that are importable as specified.
1296 =item B<find_type_constraint($type_name)>
1298 This function can be used to locate the L<Moose::Meta::TypeConstraint>
1299 object for a named type.
1301 This function is importable.
1303 =item B<register_type_constraint($type_object)>
1305 This function will register a L<Moose::Meta::TypeConstraint> with the
1306 global type registry.
1308 This function is importable.
1310 =item B<normalize_type_constraint_name($type_constraint_name)>
1312 This method takes a type constraint name and returns the normalized
1313 form. This removes any whitespace in the string.
1315 =item B<create_type_constraint_union($pipe_separated_types | @type_constraint_names)>
1317 =item B<create_named_type_constraint_union($name, $pipe_separated_types | @type_constraint_names)>
1319 This can take a union type specification like C<'Int|ArrayRef[Int]'>,
1320 or a list of names. It returns a new
1321 L<Moose::Meta::TypeConstraint::Union> object.
1323 =item B<create_parameterized_type_constraint($type_name)>
1325 Given a C<$type_name> in the form of C<'BaseType[ContainerType]'>,
1326 this will create a new L<Moose::Meta::TypeConstraint::Parameterized>
1327 object. The C<BaseType> must exist already exist as a parameterizable
1330 =item B<create_class_type_constraint($class, $options)>
1332 Given a class name this function will create a new
1333 L<Moose::Meta::TypeConstraint::Class> object for that class name.
1335 The C<$options> is a hash reference that will be passed to the
1336 L<Moose::Meta::TypeConstraint::Class> constructor (as a hash).
1338 =item B<create_role_type_constraint($role, $options)>
1340 Given a role name this function will create a new
1341 L<Moose::Meta::TypeConstraint::Role> object for that role name.
1343 The C<$options> is a hash reference that will be passed to the
1344 L<Moose::Meta::TypeConstraint::Role> constructor (as a hash).
1346 =item B<create_enum_type_constraint($name, $values)>
1348 Given a enum name this function will create a new
1349 L<Moose::Meta::TypeConstraint::Enum> object for that enum name.
1351 =item B<create_duck_type_constraint($name, $methods)>
1353 Given a duck type name this function will create a new
1354 L<Moose::Meta::TypeConstraint::DuckType> object for that enum name.
1356 =item B<find_or_parse_type_constraint($type_name)>
1358 Given a type name, this first attempts to find a matching constraint
1359 in the global registry.
1361 If the type name is a union or parameterized type, it will create a
1362 new object of the appropriate, but if given a "regular" type that does
1363 not yet exist, it simply returns false.
1365 When given a union or parameterized type, the member or base type must
1368 If it creates a new union or parameterized type, it will add it to the
1371 =item B<find_or_create_isa_type_constraint($type_name)>
1373 =item B<find_or_create_does_type_constraint($type_name)>
1375 These functions will first call C<find_or_parse_type_constraint>. If
1376 that function does not return a type, a new type object will
1379 The C<isa> variant will use C<create_class_type_constraint> and the
1380 C<does> variant will use C<create_role_type_constraint>.
1382 =item B<get_type_constraint_registry>
1384 Returns the L<Moose::Meta::TypeConstraint::Registry> object which
1385 keeps track of all type constraints.
1387 =item B<list_all_type_constraints>
1389 This will return a list of type constraint names in the global
1390 registry. You can then fetch the actual type object using
1391 C<find_type_constraint($type_name)>.
1393 =item B<list_all_builtin_type_constraints>
1395 This will return a list of builtin type constraints, meaning those
1396 which are defined in this module. See the L<Default Type Constraints>
1397 section for a complete list.
1399 =item B<export_type_constraints_as_functions>
1401 This will export all the current type constraints as functions into
1402 the caller's namespace (C<Int()>, C<Str()>, etc). Right now, this is
1403 mostly used for testing, but it might prove useful to others.
1405 =item B<get_all_parameterizable_types>
1407 This returns all the parameterizable types that have been registered,
1408 as a list of type objects.
1410 =item B<add_parameterizable_type($type)>
1412 Adds C<$type> to the list of parameterizable types
1418 See L<Moose/BUGS> for details on reporting bugs.