ac6802c1598fb3184891efee934a1f94b8a913e3
[gitmo/Moose.git] / lib / Moose / Util / TypeConstraints.pm
1
2 package Moose::Util::TypeConstraints;
3
4 use strict;
5 use warnings;
6
7 use Carp ();
8 use Scalar::Util 'blessed';
9 use Moose::Exporter;
10
11 our $VERSION   = '0.57';
12 $VERSION = eval $VERSION;
13 our $AUTHORITY = 'cpan:STEVAN';
14
15 ## --------------------------------------------------------
16 # Prototyped subs must be predeclared because we have a
17 # circular dependency with Moose::Meta::Attribute et. al.
18 # so in case of us being use'd first the predeclaration
19 # ensures the prototypes are in scope when consumers are
20 # compiled.
21
22 # creation and location
23 sub find_type_constraint                 ($);
24 sub register_type_constraint             ($);
25 sub find_or_create_type_constraint       ($;$);
26 sub find_or_parse_type_constraint        ($);
27 sub find_or_create_isa_type_constraint   ($);
28 sub find_or_create_does_type_constraint  ($);
29 sub create_type_constraint_union         (@);
30 sub create_parameterized_type_constraint ($);
31 sub create_class_type_constraint         ($;$);
32 sub create_role_type_constraint          ($;$);
33 sub create_enum_type_constraint          ($$);
34
35 # dah sugah!
36 sub type        ($$;$$);
37 sub subtype     ($$;$$$);
38 sub class_type  ($;$);
39 sub coerce      ($@);
40 sub as          ($);
41 sub from        ($);
42 sub where       (&);
43 sub via         (&);
44 sub message     (&);
45 sub optimize_as (&);
46 sub enum        ($;@);
47
48 ## private stuff ...
49 sub _create_type_constraint ($$$;$$);
50 sub _install_type_coercions ($$);
51
52 ## --------------------------------------------------------
53
54 use Moose::Meta::TypeConstraint;
55 use Moose::Meta::TypeConstraint::Union;
56 use Moose::Meta::TypeConstraint::Parameterized;
57 use Moose::Meta::TypeConstraint::Parameterizable;
58 use Moose::Meta::TypeConstraint::Class;
59 use Moose::Meta::TypeConstraint::Role;
60 use Moose::Meta::TypeConstraint::Enum;
61 use Moose::Meta::TypeCoercion;
62 use Moose::Meta::TypeCoercion::Union;
63 use Moose::Meta::TypeConstraint::Registry;
64 use Moose::Util::TypeConstraints::OptimizedConstraints;
65
66 Moose::Exporter->setup_import_methods(
67     as_is => [
68         qw(
69             type subtype class_type role_type as where message optimize_as
70             coerce from via
71             enum
72             find_type_constraint
73             register_type_constraint )
74     ],
75     _export_to_main => 1,
76 );
77
78 ## --------------------------------------------------------
79 ## type registry and some useful functions for it
80 ## --------------------------------------------------------
81
82 my $REGISTRY = Moose::Meta::TypeConstraint::Registry->new;
83
84 sub get_type_constraint_registry         { $REGISTRY }
85 sub list_all_type_constraints            { keys %{$REGISTRY->type_constraints} }
86 sub export_type_constraints_as_functions {
87     my $pkg = caller();
88     no strict 'refs';
89     foreach my $constraint (keys %{$REGISTRY->type_constraints}) {
90         my $tc = $REGISTRY->get_type_constraint($constraint)->_compiled_type_constraint;
91         *{"${pkg}::${constraint}"} = sub { $tc->($_[0]) ? 1 : undef }; # the undef is for compat
92     }
93 }
94
95 sub create_type_constraint_union (@) {
96     my @type_constraint_names;
97
98     if (scalar @_ == 1 && _detect_type_constraint_union($_[0])) {
99         @type_constraint_names = _parse_type_constraint_union($_[0]);
100     }
101     else {
102         @type_constraint_names = @_;
103     }
104
105     (scalar @type_constraint_names >= 2)
106         || Moose->throw_error("You must pass in at least 2 type names to make a union");
107
108     ($REGISTRY->has_type_constraint($_))
109         || Moose->throw_error("Could not locate type constraint ($_) for the union")
110             foreach @type_constraint_names;
111
112     return Moose::Meta::TypeConstraint::Union->new(
113         type_constraints => [
114             map {
115                 $REGISTRY->get_type_constraint($_)
116             } @type_constraint_names
117         ],
118     );
119 }
120
121 sub create_parameterized_type_constraint ($) {
122     my $type_constraint_name = shift;
123
124     my ($base_type, $type_parameter_str) = _parse_parameterized_type_constraint($type_constraint_name);
125
126     (defined $base_type && defined $type_parameter_str)
127         || Moose->throw_error("Could not parse type name ($type_constraint_name) correctly");
128
129     if ($REGISTRY->has_type_constraint($base_type)) {
130         my $base_type_tc = $REGISTRY->get_type_constraint($base_type);
131         return _create_parameterized_type_constraint(
132             $type_constraint_name,
133             $base_type_tc,
134             $type_parameter_str,
135         );
136     } else {
137         Moose->throw_error("Could not locate the base type ($base_type)");
138     }
139 }
140
141 sub _create_parameterized_type_constraint {
142     my ($tc_name, $base_type_tc, $type_parameter_str) = @_;
143     my @type_parameters_tc = map {find_or_create_isa_type_constraint($_)} ($type_parameter_str);
144     if($base_type_tc->can('parameterize')) {
145         return $base_type_tc->parameterize($tc_name,@type_parameters_tc);
146     } else {
147         return Moose::Meta::TypeConstraint::Parameterized->new(
148             name           => $tc_name,
149             parent         => $base_type_tc,
150             type_parameter => $type_parameters_tc[0],
151         );
152     } 
153 }
154
155 #should we also support optimized checks?
156 sub create_class_type_constraint ($;$) {
157     my ( $class, $options ) = @_;
158
159     # too early for this check
160     #find_type_constraint("ClassName")->check($class)
161     #    || Moose->throw_error("Can't create a class type constraint because '$class' is not a class name");
162
163     my %options = (
164         class => $class,
165         name  => $class,
166         %{ $options || {} },
167     );
168
169     $options{name} ||= "__ANON__";
170
171     Moose::Meta::TypeConstraint::Class->new( %options );
172 }
173
174 sub create_role_type_constraint ($;$) {
175     my ( $role, $options ) = @_;
176
177     # too early for this check
178     #find_type_constraint("ClassName")->check($class)
179     #    || Moose->throw_error("Can't create a class type constraint because '$class' is not a class name");
180
181     my %options = (
182         role => $role,
183         name => $role,
184         %{ $options || {} },
185     );
186
187     $options{name} ||= "__ANON__";
188
189     Moose::Meta::TypeConstraint::Role->new( %options );
190 }
191
192
193 sub find_or_create_type_constraint ($;$) {
194     my ( $type_constraint_name, $options_for_anon_type ) = @_;
195
196     if ( my $constraint = find_or_parse_type_constraint($type_constraint_name) ) {
197         return $constraint;
198     }
199     elsif ( defined $options_for_anon_type ) {
200         # NOTE:
201         # if there is no $options_for_anon_type
202         # specified, then we assume they don't
203         # want to create one, and return nothing.
204
205         # otherwise assume that we should create
206         # an ANON type with the $options_for_anon_type
207         # options which can be passed in. It should
208         # be noted that these don't get registered
209         # so we need to return it.
210         # - SL
211         return Moose::Meta::TypeConstraint->new(
212             name => '__ANON__',
213             %{$options_for_anon_type}
214         );
215     }
216
217     return;
218 }
219
220 sub find_or_create_isa_type_constraint ($) {
221     my $type_constraint_name = shift;
222     find_or_parse_type_constraint($type_constraint_name) || create_class_type_constraint($type_constraint_name)
223 }
224
225 sub find_or_create_does_type_constraint ($) {
226     my $type_constraint_name = shift;
227     find_or_parse_type_constraint($type_constraint_name) || create_role_type_constraint($type_constraint_name)
228 }
229
230 sub find_or_parse_type_constraint ($) {
231     my $type_constraint_name = shift;
232     my $constraint;
233     
234     if ($constraint = find_type_constraint($type_constraint_name)) {
235         return $constraint;
236     } elsif (_detect_type_constraint_union($type_constraint_name)) {
237         $constraint = create_type_constraint_union($type_constraint_name);
238     } elsif (_detect_parameterized_type_constraint($type_constraint_name)) {     
239         $constraint = create_parameterized_type_constraint($type_constraint_name);
240     } else {
241         return;
242     }
243     
244     $REGISTRY->add_type_constraint($constraint);
245     return $constraint;
246 }
247
248 ## --------------------------------------------------------
249 ## exported functions ...
250 ## --------------------------------------------------------
251
252 sub find_type_constraint ($) {
253     my $type = shift;
254
255     if ( blessed $type and $type->isa("Moose::Meta::TypeConstraint") ) {
256         return $type;
257     }
258     else {
259         return unless $REGISTRY->has_type_constraint($type);
260         return $REGISTRY->get_type_constraint($type);
261     }
262 }
263
264 sub register_type_constraint ($) {
265     my $constraint = shift;
266     Moose->throw_error("can't register an unnamed type constraint") unless defined $constraint->name;
267     $REGISTRY->add_type_constraint($constraint);
268     return $constraint;
269 }
270
271 # type constructors
272
273 sub type ($$;$$) {
274     splice(@_, 1, 0, undef);
275     goto &_create_type_constraint;
276 }
277
278 sub subtype ($$;$$$) {
279     # NOTE:
280     # this adds an undef for the name
281     # if this is an anon-subtype:
282     #   subtype(Num => where { $_ % 2 == 0 }) # anon 'even' subtype
283     # but if the last arg is not a code
284     # ref then it is a subtype alias:
285     #   subtype(MyNumbers => as Num); # now MyNumbers is the same as Num
286     # ... yeah I know it's ugly code
287     # - SL
288     unshift @_ => undef if scalar @_ <= 2 && ('CODE' eq ref($_[1]));
289     goto &_create_type_constraint;
290 }
291
292 sub class_type ($;$) {
293     register_type_constraint(
294         create_class_type_constraint(
295             $_[0],
296             ( defined($_[1]) ? $_[1] : () ),
297         )
298     );
299 }
300
301 sub role_type ($;$) {
302     register_type_constraint(
303         create_role_type_constraint(
304             $_[0],
305             ( defined($_[1]) ? $_[1] : () ),
306         )
307     );
308 }
309
310 sub coerce ($@) {
311     my ($type_name, @coercion_map) = @_;
312     _install_type_coercions($type_name, \@coercion_map);
313 }
314
315 sub as      ($) { $_[0] }
316 sub from    ($) { $_[0] }
317 sub where   (&) { $_[0] }
318 sub via     (&) { $_[0] }
319
320 sub message     (&) { +{ message   => $_[0] } }
321 sub optimize_as (&) { +{ optimized => $_[0] } }
322
323 sub enum ($;@) {
324     my ($type_name, @values) = @_;
325     # NOTE:
326     # if only an array-ref is passed then
327     # you get an anon-enum
328     # - SL
329     if (ref $type_name eq 'ARRAY' && !@values) {
330         @values    = @$type_name;
331         $type_name = undef;
332     }
333     (scalar @values >= 2)
334         || Moose->throw_error("You must have at least two values to enumerate through");
335     my %valid = map { $_ => 1 } @values;
336
337     register_type_constraint(
338         create_enum_type_constraint(
339             $type_name,
340             \@values,
341         )
342     );
343 }
344
345 sub create_enum_type_constraint ($$) {
346     my ( $type_name, $values ) = @_;
347
348     Moose::Meta::TypeConstraint::Enum->new(
349         name   => $type_name || '__ANON__',
350         values => $values,
351     );
352 }
353
354 ## --------------------------------------------------------
355 ## desugaring functions ...
356 ## --------------------------------------------------------
357
358 sub _create_type_constraint ($$$;$$) {
359     my $name   = shift;
360     my $parent = shift;
361     my $check  = shift;
362
363     my ($message, $optimized);
364     for (@_) {
365         $message   = $_->{message}   if exists $_->{message};
366         $optimized = $_->{optimized} if exists $_->{optimized};
367     }
368
369     my $pkg_defined_in = scalar(caller(0));
370
371     if (defined $name) {
372         my $type = $REGISTRY->get_type_constraint($name);
373
374         ($type->_package_defined_in eq $pkg_defined_in)
375             || confess ("The type constraint '$name' has already been created in "
376                        . $type->_package_defined_in . " and cannot be created again in "
377                        . $pkg_defined_in)
378                  if defined $type;
379     }
380
381     my $class = "Moose::Meta::TypeConstraint";
382
383     # FIXME should probably not be a special case
384     if ( defined $parent and $parent = find_or_parse_type_constraint($parent) ) {
385         $class = "Moose::Meta::TypeConstraint::Parameterizable"
386             if $parent->isa("Moose::Meta::TypeConstraint::Parameterizable");
387     }
388
389     my $constraint = $class->new(
390         name               => $name || '__ANON__',
391         package_defined_in => $pkg_defined_in,
392
393         ($parent    ? (parent     => $parent )   : ()),
394         ($check     ? (constraint => $check)     : ()),
395         ($message   ? (message    => $message)   : ()),
396         ($optimized ? (optimized  => $optimized) : ()),
397     );
398
399     # NOTE:
400     # if we have a type constraint union, and no
401     # type check, this means we are just aliasing
402     # the union constraint, which means we need to
403     # handle this differently.
404     # - SL
405     if (not(defined $check)
406         && $parent->isa('Moose::Meta::TypeConstraint::Union')
407         && $parent->has_coercion
408         ){
409         $constraint->coercion(Moose::Meta::TypeCoercion::Union->new(
410             type_constraint => $parent
411         ));
412     }
413
414     $REGISTRY->add_type_constraint($constraint)
415         if defined $name;
416
417     return $constraint;
418 }
419
420 sub _install_type_coercions ($$) {
421     my ($type_name, $coercion_map) = @_;
422     my $type = find_type_constraint($type_name);
423     (defined $type)
424         || Moose->throw_error("Cannot find type '$type_name', perhaps you forgot to load it.");
425     if ($type->has_coercion) {
426         $type->coercion->add_type_coercions(@$coercion_map);
427     }
428     else {
429         my $type_coercion = Moose::Meta::TypeCoercion->new(
430             type_coercion_map => $coercion_map,
431             type_constraint   => $type
432         );
433         $type->coercion($type_coercion);
434     }
435 }
436
437 ## --------------------------------------------------------
438 ## type notation parsing ...
439 ## --------------------------------------------------------
440
441 {
442     # All I have to say is mugwump++ cause I know
443     # do not even have enough regexp-fu to be able
444     # to have written this (I can only barely
445     # understand it as it is)
446     # - SL
447
448     use re "eval";
449
450     my $valid_chars = qr{[\w:]};
451     my $type_atom   = qr{ $valid_chars+ };
452
453     my $any;
454
455     my $type                = qr{  $valid_chars+  (?: \[  (??{$any})  \] )? }x;
456     my $type_capture_parts  = qr{ ($valid_chars+) (?: \[ ((??{$any})) \] )? }x;
457     my $type_with_parameter = qr{  $valid_chars+      \[  (??{$any})  \]    }x;
458
459     my $op_union = qr{ \s* \| \s* }x;
460     my $union    = qr{ $type (?: $op_union $type )+ }x;
461
462     $any = qr{ $type | $union }x;
463
464     sub _parse_parameterized_type_constraint {
465         { no warnings 'void'; $any; } # force capture of interpolated lexical
466         $_[0] =~ m{ $type_capture_parts }x;
467         return ($1, $2);
468     }
469
470     sub _detect_parameterized_type_constraint {
471         { no warnings 'void'; $any; } # force capture of interpolated lexical
472         $_[0] =~ m{ ^ $type_with_parameter $ }x;
473     }
474
475     sub _parse_type_constraint_union {
476         { no warnings 'void'; $any; } # force capture of interpolated lexical
477         my $given = shift;
478         my @rv;
479         while ( $given =~ m{ \G (?: $op_union )? ($type) }gcx ) {
480             push @rv => $1;
481         }
482         (pos($given) eq length($given))
483             || Moose->throw_error("'$given' didn't parse (parse-pos="
484                      . pos($given)
485                      . " and str-length="
486                      . length($given)
487                      . ")");
488         @rv;
489     }
490
491     sub _detect_type_constraint_union {
492         { no warnings 'void'; $any; } # force capture of interpolated lexical
493         $_[0] =~ m{^ $type $op_union $type ( $op_union .* )? $}x;
494     }
495 }
496
497 ## --------------------------------------------------------
498 # define some basic built-in types
499 ## --------------------------------------------------------
500
501 type 'Any'  => where { 1 }; # meta-type including all
502 type 'Item' => where { 1 }; # base-type
503
504 subtype 'Undef'   => as 'Item' => where { !defined($_) };
505 subtype 'Defined' => as 'Item' => where {  defined($_) };
506
507 subtype 'Bool'
508     => as 'Item'
509     => where { !defined($_) || $_ eq "" || "$_" eq '1' || "$_" eq '0' };
510
511 subtype 'Value'
512     => as 'Defined'
513     => where { !ref($_) }
514     => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Value;
515
516 subtype 'Ref'
517     => as 'Defined'
518     => where {  ref($_) }
519     => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Ref;
520
521 subtype 'Str'
522     => as 'Value'
523     => where { 1 }
524     => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Str;
525
526 subtype 'Num'
527     => as 'Value'
528     => where { Scalar::Util::looks_like_number($_) }
529     => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Num;
530
531 subtype 'Int'
532     => as 'Num'
533     => where { "$_" =~ /^-?[0-9]+$/ }
534     => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Int;
535
536 subtype 'ScalarRef' => as 'Ref' => where { ref($_) eq 'SCALAR' } => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::ScalarRef;
537 subtype 'CodeRef'   => as 'Ref' => where { ref($_) eq 'CODE'   } => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::CodeRef;
538 subtype 'RegexpRef' => as 'Ref' => where { ref($_) eq 'Regexp' } => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::RegexpRef;
539 subtype 'GlobRef'   => as 'Ref' => where { ref($_) eq 'GLOB'   } => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::GlobRef;
540
541 # NOTE:
542 # scalar filehandles are GLOB refs,
543 # but a GLOB ref is not always a filehandle
544 subtype 'FileHandle'
545     => as 'GlobRef'
546     => where { Scalar::Util::openhandle($_) || ( blessed($_) && $_->isa("IO::Handle") ) }
547     => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::FileHandle;
548
549 # NOTE:
550 # blessed(qr/.../) returns true,.. how odd
551 subtype 'Object'
552     => as 'Ref'
553     => where { blessed($_) && blessed($_) ne 'Regexp' }
554     => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Object;
555
556 subtype 'Role'
557     => as 'Object'
558     => where { $_->can('does') }
559     => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Role;
560
561 my $_class_name_checker = sub {
562 };
563
564 subtype 'ClassName'
565     => as 'Str'
566     => where { Class::MOP::is_class_loaded($_) }
567     => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::ClassName;
568
569 ## --------------------------------------------------------
570 # parameterizable types ...
571
572 $REGISTRY->add_type_constraint(
573     Moose::Meta::TypeConstraint::Parameterizable->new(
574         name                 => 'ArrayRef',
575         package_defined_in   => __PACKAGE__,
576         parent               => find_type_constraint('Ref'),
577         constraint           => sub { ref($_) eq 'ARRAY'  },
578         optimized            => \&Moose::Util::TypeConstraints::OptimizedConstraints::ArrayRef,
579         constraint_generator => sub {
580             my $type_parameter = shift;
581             my $check = $type_parameter->_compiled_type_constraint;
582             return sub {
583                 foreach my $x (@$_) {
584                     ($check->($x)) || return
585                 } 1;
586             }
587         }
588     )
589 );
590
591 $REGISTRY->add_type_constraint(
592     Moose::Meta::TypeConstraint::Parameterizable->new(
593         name                 => 'HashRef',
594         package_defined_in   => __PACKAGE__,
595         parent               => find_type_constraint('Ref'),
596         constraint           => sub { ref($_) eq 'HASH'  },
597         optimized            => \&Moose::Util::TypeConstraints::OptimizedConstraints::HashRef,
598         constraint_generator => sub {
599             my $type_parameter = shift;
600             my $check = $type_parameter->_compiled_type_constraint;
601             return sub {
602                 foreach my $x (values %$_) {
603                     ($check->($x)) || return
604                 } 1;
605             }
606         }
607     )
608 );
609
610 $REGISTRY->add_type_constraint(
611     Moose::Meta::TypeConstraint::Parameterizable->new(
612         name                 => 'Maybe',
613         package_defined_in   => __PACKAGE__,
614         parent               => find_type_constraint('Item'),
615         constraint           => sub { 1 },
616         constraint_generator => sub {
617             my $type_parameter = shift;
618             my $check = $type_parameter->_compiled_type_constraint;
619             return sub {
620                 return 1 if not(defined($_)) || $check->($_);
621                 return;
622             }
623         }
624     )
625 );
626
627 my @PARAMETERIZABLE_TYPES = map {
628     $REGISTRY->get_type_constraint($_)
629 } qw[ArrayRef HashRef Maybe];
630
631 sub get_all_parameterizable_types { @PARAMETERIZABLE_TYPES }
632 sub add_parameterizable_type {
633     my $type = shift;
634     (blessed $type && $type->isa('Moose::Meta::TypeConstraint::Parameterizable'))
635         || Moose->throw_error("Type must be a Moose::Meta::TypeConstraint::Parameterizable not $type");
636     push @PARAMETERIZABLE_TYPES => $type;
637 }
638
639 ## --------------------------------------------------------
640 # end of built-in types ...
641 ## --------------------------------------------------------
642
643 {
644     my @BUILTINS = list_all_type_constraints();
645     sub list_all_builtin_type_constraints { @BUILTINS }
646 }
647
648 1;
649
650 __END__
651
652 =pod
653
654 =head1 NAME
655
656 Moose::Util::TypeConstraints - Type constraint system for Moose
657
658 =head1 SYNOPSIS
659
660   use Moose::Util::TypeConstraints;
661
662   type 'Num' => where { Scalar::Util::looks_like_number($_) };
663
664   subtype 'Natural'
665       => as 'Int'
666       => where { $_ > 0 };
667
668   subtype 'NaturalLessThanTen'
669       => as 'Natural'
670       => where { $_ < 10 }
671       => message { "This number ($_) is not less than ten!" };
672
673   coerce 'Num'
674       => from 'Str'
675         => via { 0+$_ };
676
677   enum 'RGBColors' => qw(red green blue);
678
679 =head1 DESCRIPTION
680
681 This module provides Moose with the ability to create custom type
682 contraints to be used in attribute definition.
683
684 =head2 Important Caveat
685
686 This is B<NOT> a type system for Perl 5. These are type constraints,
687 and they are not used by Moose unless you tell it to. No type
688 inference is performed, expression are not typed, etc. etc. etc.
689
690 This is simply a means of creating small constraint functions which
691 can be used to simplify your own type-checking code, with the added
692 side benefit of making your intentions clearer through self-documentation.
693
694 =head2 Slightly Less Important Caveat
695
696 It is B<always> a good idea to quote your type and subtype names.
697
698 This is to prevent perl from trying to execute the call as an indirect
699 object call. This issue only seems to come up when you have a subtype
700 the same name as a valid class, but when the issue does arise it tends
701 to be quite annoying to debug.
702
703 So for instance, this:
704
705   subtype DateTime => as Object => where { $_->isa('DateTime') };
706
707 will I<Just Work>, while this:
708
709   use DateTime;
710   subtype DateTime => as Object => where { $_->isa('DateTime') };
711
712 will fail silently and cause many headaches. The simple way to solve
713 this, as well as future proof your subtypes from classes which have
714 yet to have been created yet, is to simply do this:
715
716   use DateTime;
717   subtype 'DateTime' => as 'Object' => where { $_->isa('DateTime') };
718
719 =head2 Default Type Constraints
720
721 This module also provides a simple hierarchy for Perl 5 types, here is
722 that hierarchy represented visually.
723
724   Any
725   Item
726       Bool
727       Maybe[`a]
728       Undef
729       Defined
730           Value
731               Num
732                 Int
733               Str
734                 ClassName
735           Ref
736               ScalarRef
737               ArrayRef[`a]
738               HashRef[`a]
739               CodeRef
740               RegexpRef
741               GlobRef
742                 FileHandle
743               Object
744                   Role
745
746 B<NOTE:> Any type followed by a type parameter C<[`a]> can be
747 parameterized, this means you can say:
748
749   ArrayRef[Int]    # an array of intergers
750   HashRef[CodeRef] # a hash of str to CODE ref mappings
751   Maybe[Str]       # value may be a string, may be undefined
752
753 B<NOTE:> Unless you parameterize a type, then it is invalid to
754 include the square brackets. I.e. C<ArrayRef[]> will be
755 literally interpreted as a type name.
756
757 B<NOTE:> The C<Undef> type constraint for the most part works
758 correctly now, but edge cases may still exist, please use it
759 sparringly.
760
761 B<NOTE:> The C<ClassName> type constraint does a complex package
762 existence check. This means that your class B<must> be loaded for
763 this type constraint to pass. I know this is not ideal for all,
764 but it is a saner restriction than most others.
765
766 =head2 Type Constraint Naming
767
768 Since the types created by this module are global, it is suggested
769 that you namespace your types just as you would namespace your
770 modules. So instead of creating a I<Color> type for your B<My::Graphics>
771 module, you would call the type I<My::Graphics::Color> instead.
772
773 =head2 Use with Other Constraint Modules
774
775 This module should play fairly nicely with other constraint
776 modules with only some slight tweaking. The C<where> clause
777 in types is expected to be a C<CODE> reference which checks
778 it's first argument and returns a boolean. Since most constraint
779 modules work in a similar way, it should be simple to adapt
780 them to work with Moose.
781
782 For instance, this is how you could use it with
783 L<Declare::Constraints::Simple> to declare a completely new type.
784
785   type 'HashOfArrayOfObjects'
786       => IsHashRef(
787           -keys   => HasLength,
788           -values => IsArrayRef( IsObject ));
789
790 For more examples see the F<t/200_examples/204_example_w_DCS.t>
791 test file.
792
793 Here is an example of using L<Test::Deep> and it's non-test
794 related C<eq_deeply> function.
795
796   type 'ArrayOfHashOfBarsAndRandomNumbers'
797       => where {
798           eq_deeply($_,
799               array_each(subhashof({
800                   bar           => isa('Bar'),
801                   random_number => ignore()
802               })))
803         };
804
805 For a complete example see the
806 F<t/200_examples/205_example_w_TestDeep.t> test file.
807
808 =head1 FUNCTIONS
809
810 =head2 Type Constraint Constructors
811
812 The following functions are used to create type constraints.
813 They will then register the type constraints in a global store
814 where Moose can get to them if it needs to.
815
816 See the L<SYNOPSIS> for an example of how to use these.
817
818 =over 4
819
820 =item B<type ($name, $where_clause)>
821
822 This creates a base type, which has no parent.
823
824 =item B<subtype ($name, $parent, $where_clause, ?$message)>
825
826 This creates a named subtype.
827
828 =item B<subtype ($parent, $where_clause, ?$message)>
829
830 This creates an unnamed subtype and will return the type
831 constraint meta-object, which will be an instance of
832 L<Moose::Meta::TypeConstraint>.
833
834 =item B<class_type ($class, ?$options)>
835
836 Creates a type constraint with the name C<$class> and the metaclass
837 L<Moose::Meta::TypeConstraint::Class>.
838
839 =item B<role_type ($role, ?$options)>
840
841 Creates a type constraint with the name C<$role> and the metaclass
842 L<Moose::Meta::TypeConstraint::Role>.
843
844 =item B<enum ($name, @values)>
845
846 This will create a basic subtype for a given set of strings.
847 The resulting constraint will be a subtype of C<Str> and
848 will match any of the items in C<@values>. It is case sensitive.
849 See the L<SYNOPSIS> for a simple example.
850
851 B<NOTE:> This is not a true proper enum type, it is simple
852 a convient constraint builder.
853
854 =item B<enum (\@values)>
855
856 If passed an ARRAY reference instead of the C<$name>, C<@values> pair,
857 this will create an unnamed enum. This can then be used in an attribute
858 definition like so:
859
860   has 'sort_order' => (
861       is  => 'ro',
862       isa => enum([qw[ ascending descending ]]),
863   );
864
865 =item B<as>
866
867 This is just sugar for the type constraint construction syntax.
868
869 =item B<where>
870
871 This is just sugar for the type constraint construction syntax.
872
873 Takes a block/code ref as an argument. When the type constraint is
874 tested, the supplied code is run with the value to be tested in
875 $_. This block should return true or false to indicate whether or not
876 the constraint check passed.
877
878 =item B<message>
879
880 This is just sugar for the type constraint construction syntax.
881
882 Takes a block/code ref as an argument. When the type constraint fails,
883 then the code block is run (with the value provided in $_). This code
884 ref should return a string, which will be used in the text of the
885 exception thrown.
886
887 =item B<optimize_as>
888
889 This can be used to define a "hand optimized" version of your
890 type constraint which can be used to avoid traversing a subtype
891 constraint heirarchy.
892
893 B<NOTE:> You should only use this if you know what you are doing,
894 all the built in types use this, so your subtypes (assuming they
895 are shallow) will not likely need to use this.
896
897 =back
898
899 =head2 Type Coercion Constructors
900
901 Type constraints can also contain type coercions as well. If you
902 ask your accessor to coerce, then Moose will run the type-coercion
903 code first, followed by the type constraint check. This feature
904 should be used carefully as it is very powerful and could easily
905 take off a limb if you are not careful.
906
907 See the L<SYNOPSIS> for an example of how to use these.
908
909 =over 4
910
911 =item B<coerce>
912
913 =item B<from>
914
915 This is just sugar for the type coercion construction syntax.
916
917 =item B<via>
918
919 This is just sugar for the type coercion construction syntax.
920
921 =back
922
923 =head2 Type Constraint Construction & Locating
924
925 =over 4
926
927 =item B<create_type_constraint_union ($pipe_seperated_types | @type_constraint_names)>
928
929 Given string with C<$pipe_seperated_types> or a list of C<@type_constraint_names>,
930 this will return a L<Moose::Meta::TypeConstraint::Union> instance.
931
932 =item B<create_parameterized_type_constraint ($type_name)>
933
934 Given a C<$type_name> in the form of:
935
936   BaseType[ContainerType]
937
938 this will extract the base type and container type and build an instance of
939 L<Moose::Meta::TypeConstraint::Parameterized> for it.
940
941 =item B<create_class_type_constraint ($class, ?$options)>
942
943 Given a class name it will create a new L<Moose::Meta::TypeConstraint::Class>
944 object for that class name.
945
946 =item B<create_role_type_constraint ($role, ?$options)>
947
948 Given a role name it will create a new L<Moose::Meta::TypeConstraint::Role>
949 object for that role name.
950
951 =item B<create_enum_type_constraint ($name, $values)>
952
953 =item B<find_or_parse_type_constraint ($type_name)>
954
955 This will attempt to find or create a type constraint given the a C<$type_name>.
956 If it cannot find it in the registry, it will see if it should be a union or
957 container type an create one if appropriate
958
959 =item B<find_or_create_type_constraint ($type_name, ?$options_for_anon_type)>
960
961 This function will first call C<find_or_parse_type_constraint> with the type name.
962
963 If no type is found or created, but C<$options_for_anon_type> are provided, it
964 will create the corresponding type.
965
966 This was used by the C<does> and C<isa> parameters to L<Moose::Meta::Attribute>
967 and are now superseded by C<find_or_create_isa_type_constraint> and
968 C<find_or_create_does_type_constraint>.
969
970 =item B<find_or_create_isa_type_constraint ($type_name)>
971
972 =item B<find_or_create_does_type_constraint ($type_name)>
973
974 Attempts to parse the type name using L<find_or_parse_type_constraint> and if
975 no appropriate constraint is found will create a new anonymous one.
976
977 The C<isa> variant will use C<create_class_type_constraint> and the C<does>
978 variant will use C<create_role_type_constraint>.
979
980 =item B<find_type_constraint ($type_name)>
981
982 This function can be used to locate a specific type constraint
983 meta-object, of the class L<Moose::Meta::TypeConstraint> or a
984 derivative. What you do with it from there is up to you :)
985
986 =item B<register_type_constraint ($type_object)>
987
988 This function will register a named type constraint with the type registry.
989
990 =item B<get_type_constraint_registry>
991
992 Fetch the L<Moose::Meta::TypeConstraint::Registry> object which
993 keeps track of all type constraints.
994
995 =item B<list_all_type_constraints>
996
997 This will return a list of type constraint names, you can then
998 fetch them using C<find_type_constraint ($type_name)> if you
999 want to.
1000
1001 =item B<list_all_builtin_type_constraints>
1002
1003 This will return a list of builtin type constraints, meaning,
1004 those which are defined in this module. See the section
1005 labeled L<Default Type Constraints> for a complete list.
1006
1007 =item B<export_type_constraints_as_functions>
1008
1009 This will export all the current type constraints as functions
1010 into the caller's namespace. Right now, this is mostly used for
1011 testing, but it might prove useful to others.
1012
1013 =item B<get_all_parameterizable_types>
1014
1015 This returns all the parameterizable types that have been registered.
1016
1017 =item B<add_parameterizable_type ($type)>
1018
1019 Adds C<$type> to the list of parameterizable types
1020
1021 =back
1022
1023 =head1 Error Management
1024
1025 =over 4
1026
1027 =item B<confess>
1028
1029 If the caller is a Moose metaclass, use its L<Moose::Meta::Class/throw_error>
1030 routine, otherwise use L<Carp/confess>.
1031
1032 =back
1033
1034 =head2 Namespace Management
1035
1036 =over 4
1037
1038 =item B<unimport>
1039
1040 This will remove all the type constraint keywords from the
1041 calling class namespace.
1042
1043 =back
1044
1045 =head1 BUGS
1046
1047 All complex software has bugs lurking in it, and this module is no
1048 exception. If you find a bug please either email me, or add the bug
1049 to cpan-RT.
1050
1051 =head1 AUTHOR
1052
1053 Stevan Little E<lt>stevan@iinteractive.comE<gt>
1054
1055 =head1 COPYRIGHT AND LICENSE
1056
1057 Copyright 2006-2008 by Infinity Interactive, Inc.
1058
1059 L<http://www.iinteractive.com>
1060
1061 This library is free software; you can redistribute it and/or modify
1062 it under the same terms as Perl itself.
1063
1064 =cut