2 package Moose::Util::TypeConstraints;
8 use Scalar::Util 'blessed', 'reftype';
11 our $VERSION = '0.22';
12 our $AUTHORITY = 'cpan:STEVAN';
14 ## --------------------------------------------------------
15 # Prototyped subs must be predeclared because we have a
16 # circular dependency with Moose::Meta::Attribute et. al.
17 # so in case of us being use'd first the predeclaration
18 # ensures the prototypes are in scope when consumers are
21 # creation and location
22 sub find_type_constraint ($);
23 sub register_type_constraint ($);
24 sub find_or_create_type_constraint ($;$);
25 sub create_type_constraint_union (@);
26 sub create_parameterized_type_constraint ($);
27 sub create_class_type_constraint ($);
43 sub _create_type_constraint ($$$;$$);
44 sub _install_type_coercions ($$);
46 ## --------------------------------------------------------
48 use Moose::Meta::TypeConstraint;
49 use Moose::Meta::TypeConstraint::Union;
50 use Moose::Meta::TypeConstraint::Parameterized;
51 use Moose::Meta::TypeConstraint::Parameterizable;
52 use Moose::Meta::TypeCoercion;
53 use Moose::Meta::TypeCoercion::Union;
54 use Moose::Meta::TypeConstraint::Registry;
55 use Moose::Util::TypeConstraints::OptimizedConstraints;
58 type subtype class_type as where message optimize_as
62 register_type_constraint
65 Sub::Exporter::setup_exporter({
67 groups => { default => [':all'] }
73 # loop through the exports ...
74 foreach my $name (@exports) {
76 if (defined &{$class . '::' . $name}) {
77 my $keyword = \&{$class . '::' . $name};
79 # make sure it is from Moose
80 my ($pkg_name) = Class::MOP::get_code_info($keyword);
82 next if $pkg_name ne 'Moose::Util::TypeConstraints';
84 # and if it is from Moose then undef the slot
85 delete ${$class . '::'}{$name};
90 ## --------------------------------------------------------
91 ## type registry and some useful functions for it
92 ## --------------------------------------------------------
94 my $REGISTRY = Moose::Meta::TypeConstraint::Registry->new;
96 sub get_type_constraint_registry { $REGISTRY }
97 sub list_all_type_constraints { keys %{$REGISTRY->type_constraints} }
98 sub export_type_constraints_as_functions {
101 foreach my $constraint (keys %{$REGISTRY->type_constraints}) {
102 my $tc = $REGISTRY->get_type_constraint($constraint)->_compiled_type_constraint;
103 *{"${pkg}::${constraint}"} = sub { $tc->($_[0]) ? 1 : undef };
107 sub create_type_constraint_union (@) {
108 my @type_constraint_names;
110 if (scalar @_ == 1 && _detect_type_constraint_union($_[0])) {
111 @type_constraint_names = _parse_type_constraint_union($_[0]);
114 @type_constraint_names = @_;
117 (scalar @type_constraint_names >= 2)
118 || confess "You must pass in at least 2 type names to make a union";
120 ($REGISTRY->has_type_constraint($_))
121 || confess "Could not locate type constraint ($_) for the union"
122 foreach @type_constraint_names;
124 return Moose::Meta::TypeConstraint::Union->new(
125 type_constraints => [
127 $REGISTRY->get_type_constraint($_)
128 } @type_constraint_names
133 sub create_parameterized_type_constraint ($) {
134 my $type_constraint_name = shift;
136 my ($base_type, $type_parameter) = _parse_parameterized_type_constraint($type_constraint_name);
138 (defined $base_type && defined $type_parameter)
139 || confess "Could not parse type name ($type_constraint_name) correctly";
141 ($REGISTRY->has_type_constraint($base_type))
142 || confess "Could not locate the base type ($base_type)";
144 return Moose::Meta::TypeConstraint::Parameterized->new(
145 name => $type_constraint_name,
146 parent => $REGISTRY->get_type_constraint($base_type),
147 type_parameter => find_or_create_type_constraint(
149 parent => $REGISTRY->get_type_constraint('Object'),
150 constraint => sub { $_[0]->isa($type_parameter) }
156 sub create_class_type_constraint ($) {
159 # too early for this check
160 #find_type_constraint("ClassName")->check($class)
161 # || confess "Can't create a class type constraint because '$class' is not a class name";
163 Moose::Meta::TypeConstraint::Class->new( name => $class );
166 sub find_or_create_type_constraint ($;$) {
167 my ($type_constraint_name, $options_for_anon_type) = @_;
169 return $REGISTRY->get_type_constraint($type_constraint_name)
170 if $REGISTRY->has_type_constraint($type_constraint_name);
174 if (_detect_type_constraint_union($type_constraint_name)) {
175 $constraint = create_type_constraint_union($type_constraint_name);
177 elsif (_detect_parameterized_type_constraint($type_constraint_name)) {
178 $constraint = create_parameterized_type_constraint($type_constraint_name);
182 # if there is no $options_for_anon_type
183 # specified, then we assume they don't
184 # want to create one, and return nothing.
185 return unless defined $options_for_anon_type;
188 # otherwise assume that we should create
189 # an ANON type with the $options_for_anon_type
190 # options which can be passed in. It should
191 # be noted that these don't get registered
192 # so we need to return it.
194 return Moose::Meta::TypeConstraint->new(
196 %{$options_for_anon_type}
200 $REGISTRY->add_type_constraint($constraint);
204 ## --------------------------------------------------------
205 ## exported functions ...
206 ## --------------------------------------------------------
208 sub find_type_constraint ($) { $REGISTRY->get_type_constraint(@_) }
210 sub register_type_constraint ($) {
211 my $constraint = shift;
212 confess "can't register an unnamed type constraint" unless defined $constraint->name;
213 $REGISTRY->add_type_constraint($constraint);
219 splice(@_, 1, 0, undef);
220 goto &_create_type_constraint;
223 sub subtype ($$;$$$) {
225 # this adds an undef for the name
226 # if this is an anon-subtype:
227 # subtype(Num => where { $_ % 2 == 0 }) # anon 'even' subtype
228 # but if the last arg is not a code
229 # ref then it is a subtype alias:
230 # subtype(MyNumbers => as Num); # now MyNumbers is the same as Num
231 # ... yeah I know it's ugly code
233 unshift @_ => undef if scalar @_ <= 2 && (reftype($_[1]) || '') eq 'CODE';
234 goto &_create_type_constraint;
238 register_type_constraint( create_class_type_constraint(shift) );
242 my ($type_name, @coercion_map) = @_;
243 _install_type_coercions($type_name, \@coercion_map);
247 sub from ($) { $_[0] }
248 sub where (&) { $_[0] }
249 sub via (&) { $_[0] }
251 sub message (&) { +{ message => $_[0] } }
252 sub optimize_as (&) { +{ optimized => $_[0] } }
255 my ($type_name, @values) = @_;
257 # if only an array-ref is passed then
258 # you get an anon-enum
260 if (ref $type_name eq 'ARRAY' && !@values) {
261 @values = @$type_name;
264 (scalar @values >= 2)
265 || confess "You must have at least two values to enumerate through";
266 my %valid = map { $_ => 1 } @values;
267 _create_type_constraint(
274 ## --------------------------------------------------------
275 ## desugaring functions ...
276 ## --------------------------------------------------------
278 sub _create_type_constraint ($$$;$$) {
283 my ($message, $optimized);
285 $message = $_->{message} if exists $_->{message};
286 $optimized = $_->{optimized} if exists $_->{optimized};
289 my $pkg_defined_in = scalar(caller(0));
292 my $type = $REGISTRY->get_type_constraint($name);
294 ($type->_package_defined_in eq $pkg_defined_in)
295 || confess ("The type constraint '$name' has already been created in "
296 . $type->_package_defined_in . " and cannot be created again in "
301 $parent = find_or_create_type_constraint($parent) if defined $parent;
303 my $constraint = Moose::Meta::TypeConstraint->new(
304 name => $name || '__ANON__',
305 package_defined_in => $pkg_defined_in,
307 ($parent ? (parent => $parent ) : ()),
308 ($check ? (constraint => $check) : ()),
309 ($message ? (message => $message) : ()),
310 ($optimized ? (optimized => $optimized) : ()),
314 # if we have a type constraint union, and no
315 # type check, this means we are just aliasing
316 # the union constraint, which means we need to
317 # handle this differently.
319 if (not(defined $check)
320 && $parent->isa('Moose::Meta::TypeConstraint::Union')
321 && $parent->has_coercion
323 $constraint->coercion(Moose::Meta::TypeCoercion::Union->new(
324 type_constraint => $parent
328 $REGISTRY->add_type_constraint($constraint)
334 sub _install_type_coercions ($$) {
335 my ($type_name, $coercion_map) = @_;
336 my $type = $REGISTRY->get_type_constraint($type_name);
338 || confess "Cannot find type '$type_name', perhaps you forgot to load it.";
339 if ($type->has_coercion) {
340 $type->coercion->add_type_coercions(@$coercion_map);
343 my $type_coercion = Moose::Meta::TypeCoercion->new(
344 type_coercion_map => $coercion_map,
345 type_constraint => $type
347 $type->coercion($type_coercion);
351 ## --------------------------------------------------------
352 ## type notation parsing ...
353 ## --------------------------------------------------------
356 # All I have to say is mugwump++ cause I know
357 # do not even have enough regexp-fu to be able
358 # to have written this (I can only barely
359 # understand it as it is)
364 my $valid_chars = qr{[\w:]};
365 my $type_atom = qr{ $valid_chars+ };
367 my $type = qr{ $valid_chars+ (?: \[ (??{$any}) \] )? }x;
368 my $type_capture_parts = qr{ ($valid_chars+) (?: \[ ((??{$any})) \] )? }x;
369 my $type_with_parameter = qr{ $valid_chars+ \[ (??{$any}) \] }x;
371 my $op_union = qr{ \s* \| \s* }x;
372 my $union = qr{ $type (?: $op_union $type )+ }x;
374 our $any = qr{ $type | $union }x;
376 sub _parse_parameterized_type_constraint {
377 $_[0] =~ m{ $type_capture_parts }x;
381 sub _detect_parameterized_type_constraint {
382 $_[0] =~ m{ ^ $type_with_parameter $ }x;
385 sub _parse_type_constraint_union {
388 while ( $given =~ m{ \G (?: $op_union )? ($type) }gcx ) {
391 (pos($given) eq length($given))
392 || confess "'$given' didn't parse (parse-pos="
400 sub _detect_type_constraint_union {
401 $_[0] =~ m{^ $type $op_union $type ( $op_union .* )? $}x;
405 ## --------------------------------------------------------
406 # define some basic built-in types
407 ## --------------------------------------------------------
409 type 'Any' => where { 1 }; # meta-type including all
410 type 'Item' => where { 1 }; # base-type
412 subtype 'Undef' => as 'Item' => where { !defined($_) };
413 subtype 'Defined' => as 'Item' => where { defined($_) };
417 => where { !defined($_) || $_ eq "" || "$_" eq '1' || "$_" eq '0' };
421 => where { !ref($_) }
422 => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Value;
427 => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Ref;
432 => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Str;
436 => where { Scalar::Util::looks_like_number($_) }
437 => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Num;
441 => where { "$_" =~ /^-?[0-9]+$/ }
442 => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Int;
444 subtype 'ScalarRef' => as 'Ref' => where { ref($_) eq 'SCALAR' } => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::ScalarRef;
445 subtype 'CodeRef' => as 'Ref' => where { ref($_) eq 'CODE' } => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::CodeRef;
446 subtype 'RegexpRef' => as 'Ref' => where { ref($_) eq 'Regexp' } => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::RegexpRef;
447 subtype 'GlobRef' => as 'Ref' => where { ref($_) eq 'GLOB' } => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::GlobRef;
450 # scalar filehandles are GLOB refs,
451 # but a GLOB ref is not always a filehandle
454 => where { Scalar::Util::openhandle($_) || ( blessed($_) && $_->isa("IO::Handle") ) }
455 => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::FileHandle;
458 # blessed(qr/.../) returns true,.. how odd
461 => where { blessed($_) && blessed($_) ne 'Regexp' }
462 => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Object;
466 => where { $_->can('does') }
467 => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Role;
469 my $_class_name_checker = sub {
470 return if ref($_[0]);
471 return unless defined($_[0]) && length($_[0]);
473 # walk the symbol table tree to avoid autovififying
474 # \*{${main::}{"Foo::"}} == \*main::Foo::
477 foreach my $part (split('::', $_[0])) {
478 return unless exists ${$$pack}{"${part}::"};
479 $pack = \*{${$$pack}{"${part}::"}};
482 # check for $VERSION or @ISA
483 return 1 if exists ${$$pack}{VERSION}
484 && defined *{${$$pack}{VERSION}}{SCALAR};
485 return 1 if exists ${$$pack}{ISA}
486 && defined *{${$$pack}{ISA}}{ARRAY};
488 # check for any method
489 foreach ( keys %{$$pack} ) {
490 next if substr($_, -2, 2) eq '::';
491 return 1 if defined *{${$$pack}{$_}}{CODE};
500 => $_class_name_checker # where ...
501 => { optimize => $_class_name_checker };
503 ## --------------------------------------------------------
504 # parameterizable types ...
506 $REGISTRY->add_type_constraint(
507 Moose::Meta::TypeConstraint::Parameterizable->new(
509 package_defined_in => __PACKAGE__,
510 parent => find_type_constraint('Ref'),
511 constraint => sub { ref($_) eq 'ARRAY' },
512 optimized => \&Moose::Util::TypeConstraints::OptimizedConstraints::ArrayRef,
513 constraint_generator => sub {
514 my $type_parameter = shift;
516 foreach my $x (@$_) {
517 ($type_parameter->check($x)) || return
524 $REGISTRY->add_type_constraint(
525 Moose::Meta::TypeConstraint::Parameterizable->new(
527 package_defined_in => __PACKAGE__,
528 parent => find_type_constraint('Ref'),
529 constraint => sub { ref($_) eq 'HASH' },
530 optimized => \&Moose::Util::TypeConstraints::OptimizedConstraints::HashRef,
531 constraint_generator => sub {
532 my $type_parameter = shift;
534 foreach my $x (values %$_) {
535 ($type_parameter->check($x)) || return
542 $REGISTRY->add_type_constraint(
543 Moose::Meta::TypeConstraint::Parameterizable->new(
545 package_defined_in => __PACKAGE__,
546 parent => find_type_constraint('Item'),
547 constraint => sub { 1 },
548 constraint_generator => sub {
549 my $type_parameter = shift;
551 return 1 if not(defined($_)) || $type_parameter->check($_);
558 my @PARAMETERIZABLE_TYPES = map {
559 $REGISTRY->get_type_constraint($_)
560 } qw[ArrayRef HashRef Maybe];
562 sub get_all_parameterizable_types { @PARAMETERIZABLE_TYPES }
563 sub add_parameterizable_type {
565 (blessed $type && $type->isa('Moose::Meta::TypeConstraint::Parameterizable'))
566 || confess "Type must be a Moose::Meta::TypeConstraint::Parameterizable not $type";
567 push @PARAMETERIZABLE_TYPES => $type;
570 ## --------------------------------------------------------
571 # end of built-in types ...
572 ## --------------------------------------------------------
575 my @BUILTINS = list_all_type_constraints();
576 sub list_all_builtin_type_constraints { @BUILTINS }
587 Moose::Util::TypeConstraints - Type constraint system for Moose
591 use Moose::Util::TypeConstraints;
593 type 'Num' => where { Scalar::Util::looks_like_number($_) };
599 subtype 'NaturalLessThanTen'
602 => message { "This number ($_) is not less than ten!" };
608 enum 'RGBColors' => qw(red green blue);
612 This module provides Moose with the ability to create custom type
613 contraints to be used in attribute definition.
615 =head2 Important Caveat
617 This is B<NOT> a type system for Perl 5. These are type constraints,
618 and they are not used by Moose unless you tell it to. No type
619 inference is performed, expression are not typed, etc. etc. etc.
621 This is simply a means of creating small constraint functions which
622 can be used to simplify your own type-checking code.
624 =head2 Slightly Less Important Caveat
626 It is almost always a good idea to quote your type and subtype names.
627 This is to prevent perl from trying to execute the call as an indirect
628 object call. This issue only seems to come up when you have a subtype
629 the same name as a valid class, but when the issue does arise it tends
630 to be quite annoying to debug.
632 So for instance, this:
634 subtype DateTime => as Object => where { $_->isa('DateTime') };
636 will I<Just Work>, while this:
639 subtype DateTime => as Object => where { $_->isa('DateTime') };
641 will fail silently and cause many headaches. The simple way to solve
642 this, as well as future proof your subtypes from classes which have
643 yet to have been created yet, is to simply do this:
646 subtype 'DateTime' => as 'Object' => where { $_->isa('DateTime') };
648 =head2 Default Type Constraints
650 This module also provides a simple hierarchy for Perl 5 types, this
651 could probably use some work, but it works for me at the moment.
675 Suggestions for improvement are welcome.
677 B<NOTE:> Any type followed by a type parameter C<[`a]> can be
678 parameterized, this means you can say:
680 ArrayRef[Int] # an array of intergers
681 HashRef[CodeRef] # a hash of str to CODE ref mappings
682 Maybe[Str] # value may be a string, may be undefined
684 B<NOTE:> The C<Undef> type constraint for the most part works
685 correctly now, but edge cases may still exist, please use it
688 B<NOTE:> The C<ClassName> type constraint does a complex package
689 existence check. This means that your class B<must> be loaded for
690 this type constraint to pass. I know this is not ideal for all,
691 but it is a saner restriction than most others.
693 =head2 Use with Other Constraint Modules
695 This module should play fairly nicely with other constraint
696 modules with only some slight tweaking. The C<where> clause
697 in types is expected to be a C<CODE> reference which checks
698 it's first argument and returns a bool. Since most constraint
699 modules work in a similar way, it should be simple to adapt
700 them to work with Moose.
702 For instance, this is how you could use it with
703 L<Declare::Constraints::Simple> to declare a completely new type.
705 type 'HashOfArrayOfObjects'
708 -values => IsArrayRef( IsObject ));
710 For more examples see the F<t/204_example_w_DCS.t> test file.
712 Here is an example of using L<Test::Deep> and it's non-test
713 related C<eq_deeply> function.
715 type 'ArrayOfHashOfBarsAndRandomNumbers'
718 array_each(subhashof({
720 random_number => ignore()
724 For a complete example see the F<t/205_example_w_TestDeep.t>
729 =head2 Type Constraint Construction & Locating
733 =item B<create_type_constraint_union ($pipe_seperated_types | @type_constraint_names)>
735 Given string with C<$pipe_seperated_types> or a list of C<@type_constraint_names>,
736 this will return a L<Moose::Meta::TypeConstraint::Union> instance.
738 =item B<create_parameterized_type_constraint ($type_name)>
740 Given a C<$type_name> in the form of:
742 BaseType[ContainerType]
744 this will extract the base type and container type and build an instance of
745 L<Moose::Meta::TypeConstraint::Parameterized> for it.
747 =item B<create_class_type_constraint ($class)>
749 Given a class name it will create a new L<Moose::Meta::TypeConstraint::Class>
750 object for that class name.
752 =item B<find_or_create_type_constraint ($type_name, ?$options_for_anon_type)>
754 This will attempt to find or create a type constraint given the a C<$type_name>.
755 If it cannot find it in the registry, it will see if it should be a union or
756 container type an create one if appropriate, and lastly if nothing can be
757 found or created that way, it will create an anon-type using the
758 C<$options_for_anon_type> HASH ref to populate it. If the C<$options_for_anon_type>
759 is not specified (it is C<undef>), then it will not create anything and simply
762 =item B<find_type_constraint ($type_name)>
764 This function can be used to locate a specific type constraint
765 meta-object, of the class L<Moose::Meta::TypeConstraint> or a
766 derivative. What you do with it from there is up to you :)
768 =item B<register_type_constraint ($type_object)>
770 This function will register a named type constraint with the type registry.
772 =item B<get_type_constraint_registry>
774 Fetch the L<Moose::Meta::TypeConstraint::Registry> object which
775 keeps track of all type constraints.
777 =item B<list_all_type_constraints>
779 This will return a list of type constraint names, you can then
780 fetch them using C<find_type_constraint ($type_name)> if you
783 =item B<list_all_builtin_type_constraints>
785 This will return a list of builtin type constraints, meaning,
786 those which are defined in this module. See the section
787 labeled L<Default Type Constraints> for a complete list.
789 =item B<export_type_constraints_as_functions>
791 This will export all the current type constraints as functions
792 into the caller's namespace. Right now, this is mostly used for
793 testing, but it might prove useful to others.
795 =item B<get_all_parameterizable_types>
797 This returns all the parameterizable types that have been registered.
799 =item B<add_parameterizable_type ($type)>
801 Adds C<$type> to the list of parameterizable types
805 =head2 Type Constraint Constructors
807 The following functions are used to create type constraints.
808 They will then register the type constraints in a global store
809 where Moose can get to them if it needs to.
811 See the L<SYNOPSIS> for an example of how to use these.
815 =item B<type ($name, $where_clause)>
817 This creates a base type, which has no parent.
819 =item B<subtype ($name, $parent, $where_clause, ?$message)>
821 This creates a named subtype.
823 =item B<subtype ($parent, $where_clause, ?$message)>
825 This creates an unnamed subtype and will return the type
826 constraint meta-object, which will be an instance of
827 L<Moose::Meta::TypeConstraint>.
829 =item B<class_type ($class)>
831 Creates a type constraint with the name C<$class> and the metaclass
832 L<Moose::Meta::TypeConstraint::Class>.
834 =item B<enum ($name, @values)>
836 This will create a basic subtype for a given set of strings.
837 The resulting constraint will be a subtype of C<Str> and
838 will match any of the items in C<@values>. It is case sensitive.
839 See the L<SYNOPSIS> for a simple example.
841 B<NOTE:> This is not a true proper enum type, it is simple
842 a convient constraint builder.
844 =item B<enum (\@values)>
846 If passed an ARRAY reference instead of the C<$name>, C<@values> pair,
847 this will create an unnamed enum. This can then be used in an attribute
850 has 'sort_order' => (
852 isa => enum([qw[ ascending descending ]]),
857 This is just sugar for the type constraint construction syntax.
861 This is just sugar for the type constraint construction syntax.
865 This is just sugar for the type constraint construction syntax.
869 This can be used to define a "hand optimized" version of your
870 type constraint which can be used to avoid traversing a subtype
871 constraint heirarchy.
873 B<NOTE:> You should only use this if you know what you are doing,
874 all the built in types use this, so your subtypes (assuming they
875 are shallow) will not likely need to use this.
879 =head2 Type Coercion Constructors
881 Type constraints can also contain type coercions as well. If you
882 ask your accessor to coerce, then Moose will run the type-coercion
883 code first, followed by the type constraint check. This feature
884 should be used carefully as it is very powerful and could easily
885 take off a limb if you are not careful.
887 See the L<SYNOPSIS> for an example of how to use these.
895 This is just sugar for the type coercion construction syntax.
899 This is just sugar for the type coercion construction syntax.
903 =head2 Namespace Management
909 This will remove all the type constraint keywords from the
910 calling class namespace.
916 All complex software has bugs lurking in it, and this module is no
917 exception. If you find a bug please either email me, or add the bug
922 Stevan Little E<lt>stevan@iinteractive.comE<gt>
924 =head1 COPYRIGHT AND LICENSE
926 Copyright 2006-2008 by Infinity Interactive, Inc.
928 L<http://www.iinteractive.com>
930 This library is free software; you can redistribute it and/or modify
931 it under the same terms as Perl itself.