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