add cache attribute to M::Meta::Class->create_anon_class
[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         'confess';
8 use Scalar::Util 'blessed', 'reftype';
9 use Sub::Exporter;
10
11 our $VERSION   = '0.22';
12 our $AUTHORITY = 'cpan:STEVAN';
13
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
19 # compiled.
20
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         ($);
28
29 # dah sugah!
30 sub type        ($$;$$);
31 sub subtype     ($$;$$$);
32 sub class_type  ($);
33 sub coerce      ($@);
34 sub as          ($);
35 sub from        ($);
36 sub where       (&);
37 sub via         (&);
38 sub message     (&);
39 sub optimize_as (&);
40 sub enum        ($;@);
41
42 ## private stuff ...
43 sub _create_type_constraint ($$$;$$);
44 sub _install_type_coercions ($$);
45
46 ## --------------------------------------------------------
47
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;
56
57 my @exports = qw/
58     type subtype class_type as where message optimize_as
59     coerce from via
60     enum
61     find_type_constraint
62     register_type_constraint
63 /;
64
65 Sub::Exporter::setup_exporter({
66     exports => \@exports,
67     groups  => { default => [':all'] }
68 });
69
70 sub unimport {
71     no strict 'refs';
72     my $class = caller();
73     # loop through the exports ...
74     foreach my $name (@exports) {
75         # if we find one ...
76         if (defined &{$class . '::' . $name}) {
77             my $keyword = \&{$class . '::' . $name};
78
79             # make sure it is from Moose
80             my ($pkg_name) = Class::MOP::get_code_info($keyword);
81             next if $@;
82             next if $pkg_name ne 'Moose::Util::TypeConstraints';
83
84             # and if it is from Moose then undef the slot
85             delete ${$class . '::'}{$name};
86         }
87     }
88 }
89
90 ## --------------------------------------------------------
91 ## type registry and some useful functions for it
92 ## --------------------------------------------------------
93
94 my $REGISTRY = Moose::Meta::TypeConstraint::Registry->new;
95
96 sub get_type_constraint_registry         { $REGISTRY }
97 sub list_all_type_constraints            { keys %{$REGISTRY->type_constraints} }
98 sub export_type_constraints_as_functions {
99     my $pkg = caller();
100     no strict 'refs';
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 };
104     }
105 }
106
107 sub create_type_constraint_union (@) {
108     my @type_constraint_names;
109
110     if (scalar @_ == 1 && _detect_type_constraint_union($_[0])) {
111         @type_constraint_names = _parse_type_constraint_union($_[0]);
112     }
113     else {
114         @type_constraint_names = @_;
115     }
116
117     (scalar @type_constraint_names >= 2)
118         || confess "You must pass in at least 2 type names to make a union";
119
120     ($REGISTRY->has_type_constraint($_))
121         || confess "Could not locate type constraint ($_) for the union"
122             foreach @type_constraint_names;
123
124     return Moose::Meta::TypeConstraint::Union->new(
125         type_constraints => [
126             map {
127                 $REGISTRY->get_type_constraint($_)
128             } @type_constraint_names
129         ],
130     );
131 }
132
133 sub create_parameterized_type_constraint ($) {
134     my $type_constraint_name = shift;
135
136     my ($base_type, $type_parameter) = _parse_parameterized_type_constraint($type_constraint_name);
137
138     (defined $base_type && defined $type_parameter)
139         || confess "Could not parse type name ($type_constraint_name) correctly";
140
141     ($REGISTRY->has_type_constraint($base_type))
142         || confess "Could not locate the base type ($base_type)";
143
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(
148             $type_parameter => {
149                 parent     => $REGISTRY->get_type_constraint('Object'),
150                 constraint => sub { $_[0]->isa($type_parameter) }
151             }
152         ),
153     );
154 }
155
156 sub create_class_type_constraint ($) {
157     my $class = shift;
158
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";
162
163     Moose::Meta::TypeConstraint::Class->new( name => $class );
164 }
165
166 sub find_or_create_type_constraint ($;$) {
167     my ($type_constraint_name, $options_for_anon_type) = @_;
168
169     return $REGISTRY->get_type_constraint($type_constraint_name)
170         if $REGISTRY->has_type_constraint($type_constraint_name);
171
172     my $constraint;
173
174     if (_detect_type_constraint_union($type_constraint_name)) {
175         $constraint = create_type_constraint_union($type_constraint_name);
176     }
177     elsif (_detect_parameterized_type_constraint($type_constraint_name)) {
178         $constraint = create_parameterized_type_constraint($type_constraint_name);
179     }
180     else {
181         # NOTE:
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;        
186
187         # NOTE:
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     $REGISTRY->add_type_constraint($constraint);
201     return $constraint;
202 }
203
204 ## --------------------------------------------------------
205 ## exported functions ...
206 ## --------------------------------------------------------
207
208 sub find_type_constraint ($) { $REGISTRY->get_type_constraint(@_) }
209
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);
214 }
215
216 # type constructors
217
218 sub type ($$;$$) {
219     splice(@_, 1, 0, undef);
220     goto &_create_type_constraint;
221 }
222
223 sub subtype ($$;$$$) {
224     # NOTE:
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
232     # - SL
233     unshift @_ => undef if scalar @_ <= 2 && (reftype($_[1]) || '') eq 'CODE';
234     goto &_create_type_constraint;
235 }
236
237 sub class_type ($) {
238     register_type_constraint( create_class_type_constraint(shift) );
239 }
240
241 sub coerce ($@) {
242     my ($type_name, @coercion_map) = @_;
243     _install_type_coercions($type_name, \@coercion_map);
244 }
245
246 sub as      ($) { $_[0] }
247 sub from    ($) { $_[0] }
248 sub where   (&) { $_[0] }
249 sub via     (&) { $_[0] }
250
251 sub message     (&) { +{ message   => $_[0] } }
252 sub optimize_as (&) { +{ optimized => $_[0] } }
253
254 sub enum ($;@) {
255     my ($type_name, @values) = @_;
256     # NOTE: 
257     # if only an array-ref is passed then 
258     # you get an anon-enum
259     # - SL
260     if (ref $type_name eq 'ARRAY' && !@values) {
261         @values    = @$type_name;
262         $type_name = undef;
263     }
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(
268         $type_name,
269         'Str',
270         sub { $valid{$_} }
271     );
272 }
273
274 ## --------------------------------------------------------
275 ## desugaring functions ...
276 ## --------------------------------------------------------
277
278 sub _create_type_constraint ($$$;$$) {
279     my $name   = shift;
280     my $parent = shift;
281     my $check  = shift;
282
283     my ($message, $optimized);
284     for (@_) {
285         $message   = $_->{message}   if exists $_->{message};
286         $optimized = $_->{optimized} if exists $_->{optimized};
287     }
288
289     my $pkg_defined_in = scalar(caller(0));
290
291     if (defined $name) {
292         my $type = $REGISTRY->get_type_constraint($name);
293
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 "
297                        . $pkg_defined_in)
298                  if defined $type;
299     }
300
301     $parent = find_or_create_type_constraint($parent) if defined $parent;
302     
303     my $constraint = Moose::Meta::TypeConstraint->new(
304         name               => $name || '__ANON__',
305         package_defined_in => $pkg_defined_in,
306
307         ($parent    ? (parent     => $parent )   : ()),
308         ($check     ? (constraint => $check)     : ()),
309         ($message   ? (message    => $message)   : ()),
310         ($optimized ? (optimized  => $optimized) : ()),
311     );
312     
313     # NOTE:
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.
318     # - SL
319     if (not(defined $check) 
320         && $parent->isa('Moose::Meta::TypeConstraint::Union') 
321         && $parent->has_coercion 
322         ){
323         $constraint->coercion(Moose::Meta::TypeCoercion::Union->new(
324             type_constraint => $parent
325         ));
326     }    
327
328     $REGISTRY->add_type_constraint($constraint)
329         if defined $name;
330
331     return $constraint;
332 }
333
334 sub _install_type_coercions ($$) {
335     my ($type_name, $coercion_map) = @_;
336     my $type = $REGISTRY->get_type_constraint($type_name);
337     (defined $type)
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);
341     }
342     else {
343         my $type_coercion = Moose::Meta::TypeCoercion->new(
344             type_coercion_map => $coercion_map,
345             type_constraint   => $type
346         );
347         $type->coercion($type_coercion);
348     }
349 }
350
351 ## --------------------------------------------------------
352 ## type notation parsing ...
353 ## --------------------------------------------------------
354
355 {
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)
360     # - SL
361
362     use re "eval";
363
364     my $valid_chars = qr{[\w:]};
365     my $type_atom   = qr{ $valid_chars+ };
366
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;
370
371     my $op_union = qr{ \s* \| \s* }x;
372     my $union    = qr{ $type (?: $op_union $type )+ }x;
373
374     our $any = qr{ $type | $union }x;
375
376     sub _parse_parameterized_type_constraint {
377         $_[0] =~ m{ $type_capture_parts }x;
378         return ($1, $2);
379     }
380
381     sub _detect_parameterized_type_constraint {
382         $_[0] =~ m{ ^ $type_with_parameter $ }x;
383     }
384
385     sub _parse_type_constraint_union {
386         my $given = shift;
387         my @rv;
388         while ( $given =~ m{ \G (?: $op_union )? ($type) }gcx ) {
389                 push @rv => $1;
390         }
391         (pos($given) eq length($given))
392             || confess "'$given' didn't parse (parse-pos="
393                      . pos($given)
394                      . " and str-length="
395                      . length($given)
396                      . ")";
397         @rv;
398     }
399
400     sub _detect_type_constraint_union {
401         $_[0] =~ m{^ $type $op_union $type ( $op_union .* )? $}x;
402     }
403 }
404
405 ## --------------------------------------------------------
406 # define some basic built-in types
407 ## --------------------------------------------------------
408
409 type 'Any'  => where { 1 }; # meta-type including all
410 type 'Item' => where { 1 }; # base-type
411
412 subtype 'Undef'   => as 'Item' => where { !defined($_) };
413 subtype 'Defined' => as 'Item' => where {  defined($_) };
414
415 subtype 'Bool'
416     => as 'Item'
417     => where { !defined($_) || $_ eq "" || "$_" eq '1' || "$_" eq '0' };
418
419 subtype 'Value'
420     => as 'Defined'
421     => where { !ref($_) }
422     => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Value;
423
424 subtype 'Ref'
425     => as 'Defined'
426     => where {  ref($_) }
427     => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Ref;
428
429 subtype 'Str'
430     => as 'Value'
431     => where { 1 }
432     => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Str;
433
434 subtype 'Num'
435     => as 'Value'
436     => where { Scalar::Util::looks_like_number($_) }
437     => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Num;
438
439 subtype 'Int'
440     => as 'Num'
441     => where { "$_" =~ /^-?[0-9]+$/ }
442     => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Int;
443
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;
448
449 # NOTE:
450 # scalar filehandles are GLOB refs,
451 # but a GLOB ref is not always a filehandle
452 subtype 'FileHandle'
453     => as 'GlobRef'
454     => where { Scalar::Util::openhandle($_) || ( blessed($_) && $_->isa("IO::Handle") ) }
455     => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::FileHandle;
456
457 # NOTE:
458 # blessed(qr/.../) returns true,.. how odd
459 subtype 'Object'
460     => as 'Ref'
461     => where { blessed($_) && blessed($_) ne 'Regexp' }
462     => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Object;
463
464 subtype 'Role'
465     => as 'Object'
466     => where { $_->can('does') }
467     => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Role;
468
469 my $_class_name_checker = sub {
470     return if ref($_[0]);
471     return unless defined($_[0]) && length($_[0]);
472
473     # walk the symbol table tree to avoid autovififying
474     # \*{${main::}{"Foo::"}} == \*main::Foo::
475
476     my $pack = \*::;
477     foreach my $part (split('::', $_[0])) {
478         return unless exists ${$$pack}{"${part}::"};
479         $pack = \*{${$$pack}{"${part}::"}};
480     }
481
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};
487
488     # check for any method
489     foreach ( keys %{$$pack} ) {
490         next if substr($_, -2, 2) eq '::';
491         return 1 if defined *{${$$pack}{$_}}{CODE};
492     }
493
494     # fail
495     return;
496 };
497
498 subtype 'ClassName'
499     => as 'Str'
500     => $_class_name_checker # where ...
501     => { optimize => $_class_name_checker };
502
503 ## --------------------------------------------------------
504 # parameterizable types ...
505
506 $REGISTRY->add_type_constraint(
507     Moose::Meta::TypeConstraint::Parameterizable->new(
508         name                 => 'ArrayRef',
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;
515             return sub {
516                 foreach my $x (@$_) {
517                     ($type_parameter->check($x)) || return
518                 } 1;
519             }
520         }
521     )
522 );
523
524 $REGISTRY->add_type_constraint(
525     Moose::Meta::TypeConstraint::Parameterizable->new(
526         name                 => 'HashRef',
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;            
533             return sub {
534                 foreach my $x (values %$_) {
535                     ($type_parameter->check($x)) || return
536                 } 1;
537             }
538         }
539     )
540 );
541
542 $REGISTRY->add_type_constraint(
543     Moose::Meta::TypeConstraint::Parameterizable->new(
544         name                 => 'Maybe',
545         package_defined_in   => __PACKAGE__,
546         parent               => find_type_constraint('Item'),
547         constraint           => sub { 1 },
548         constraint_generator => sub {
549             my $type_parameter = shift;            
550             return sub {
551                 return 1 if not(defined($_)) || $type_parameter->check($_);
552                 return;
553             }
554         }
555     )
556 );
557
558 my @PARAMETERIZABLE_TYPES = map { 
559     $REGISTRY->get_type_constraint($_) 
560 } qw[ArrayRef HashRef Maybe];
561
562 sub get_all_parameterizable_types { @PARAMETERIZABLE_TYPES }
563 sub add_parameterizable_type { 
564     my $type = shift;
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;
568 }    
569
570 ## --------------------------------------------------------
571 # end of built-in types ...
572 ## --------------------------------------------------------
573
574 {
575     my @BUILTINS = list_all_type_constraints();
576     sub list_all_builtin_type_constraints { @BUILTINS }
577 }
578
579 1;
580
581 __END__
582
583 =pod
584
585 =head1 NAME
586
587 Moose::Util::TypeConstraints - Type constraint system for Moose
588
589 =head1 SYNOPSIS
590
591   use Moose::Util::TypeConstraints;
592
593   type 'Num' => where { Scalar::Util::looks_like_number($_) };
594
595   subtype 'Natural'
596       => as 'Num'
597       => where { $_ > 0 };
598
599   subtype 'NaturalLessThanTen'
600       => as 'Natural'
601       => where { $_ < 10 }
602       => message { "This number ($_) is not less than ten!" };
603
604   coerce 'Num'
605       => from 'Str'
606         => via { 0+$_ };
607
608   enum 'RGBColors' => qw(red green blue);
609
610 =head1 DESCRIPTION
611
612 This module provides Moose with the ability to create custom type
613 contraints to be used in attribute definition.
614
615 =head2 Important Caveat
616
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.
620
621 This is simply a means of creating small constraint functions which
622 can be used to simplify your own type-checking code.
623
624 =head2 Slightly Less Important Caveat
625
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.
631
632 So for instance, this:
633
634   subtype DateTime => as Object => where { $_->isa('DateTime') };
635
636 will I<Just Work>, while this:
637
638   use DateTime;
639   subtype DateTime => as Object => where { $_->isa('DateTime') };
640
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:
644
645   use DateTime;
646   subtype 'DateTime' => as 'Object' => where { $_->isa('DateTime') };
647
648 =head2 Default Type Constraints
649
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.
652
653   Any
654   Item
655       Bool
656       Maybe[`a]
657       Undef
658       Defined
659           Value
660               Num
661                 Int
662               Str
663                 ClassName
664           Ref
665               ScalarRef
666               ArrayRef[`a]
667               HashRef[`a]
668               CodeRef
669               RegexpRef
670               GlobRef
671                 FileHandle
672               Object
673                   Role
674
675 Suggestions for improvement are welcome.
676
677 B<NOTE:> Any type followed by a type parameter C<[`a]> can be 
678 parameterized, this means you can say:
679
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
683
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 
686 sparringly.
687
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.
692
693 =head2 Use with Other Constraint Modules
694
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.
701
702 For instance, this is how you could use it with
703 L<Declare::Constraints::Simple> to declare a completely new type.
704
705   type 'HashOfArrayOfObjects'
706       => IsHashRef(
707           -keys   => HasLength,
708           -values => IsArrayRef( IsObject ));
709
710 For more examples see the F<t/204_example_w_DCS.t> test file.
711
712 Here is an example of using L<Test::Deep> and it's non-test
713 related C<eq_deeply> function.
714
715   type 'ArrayOfHashOfBarsAndRandomNumbers'
716       => where {
717           eq_deeply($_,
718               array_each(subhashof({
719                   bar           => isa('Bar'),
720                   random_number => ignore()
721               })))
722         };
723
724 For a complete example see the F<t/205_example_w_TestDeep.t>
725 test file.
726
727 =head1 FUNCTIONS
728
729 =head2 Type Constraint Construction & Locating
730
731 =over 4
732
733 =item B<create_type_constraint_union ($pipe_seperated_types | @type_constraint_names)>
734
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.
737
738 =item B<create_parameterized_type_constraint ($type_name)>
739
740 Given a C<$type_name> in the form of:
741
742   BaseType[ContainerType]
743
744 this will extract the base type and container type and build an instance of
745 L<Moose::Meta::TypeConstraint::Parameterized> for it. 
746
747 =item B<create_class_type_constraint ($class)>
748
749 Given a class name it will create a new L<Moose::Meta::TypeConstraint::Class>
750 object for that class name.
751
752 =item B<find_or_create_type_constraint ($type_name, ?$options_for_anon_type)>
753
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
760 return.
761
762 =item B<find_type_constraint ($type_name)>
763
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 :)
767
768 =item B<register_type_constraint ($type_object)>
769
770 This function will register a named type constraint with the type registry.
771
772 =item B<get_type_constraint_registry>
773
774 Fetch the L<Moose::Meta::TypeConstraint::Registry> object which
775 keeps track of all type constraints.
776
777 =item B<list_all_type_constraints>
778
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
781 want to.
782
783 =item B<list_all_builtin_type_constraints>
784
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.
788
789 =item B<export_type_constraints_as_functions>
790
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.
794
795 =item B<get_all_parameterizable_types>
796
797 This returns all the parameterizable types that have been registered.
798
799 =item B<add_parameterizable_type ($type)>
800
801 Adds C<$type> to the list of parameterizable types
802
803 =back
804
805 =head2 Type Constraint Constructors
806
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.
810
811 See the L<SYNOPSIS> for an example of how to use these.
812
813 =over 4
814
815 =item B<type ($name, $where_clause)>
816
817 This creates a base type, which has no parent.
818
819 =item B<subtype ($name, $parent, $where_clause, ?$message)>
820
821 This creates a named subtype.
822
823 =item B<subtype ($parent, $where_clause, ?$message)>
824
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>.
828
829 =item B<class_type ($class)>
830
831 Creates a type constraint with the name C<$class> and the metaclass
832 L<Moose::Meta::TypeConstraint::Class>.
833
834 =item B<enum ($name, @values)>
835
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.
840
841 B<NOTE:> This is not a true proper enum type, it is simple
842 a convient constraint builder.
843
844 =item B<enum (\@values)>
845
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
848 definition like so:
849
850   has 'sort_order' => (
851       is  => 'ro',
852       isa => enum([qw[ ascending descending ]]),   
853   );
854
855 =item B<as>
856
857 This is just sugar for the type constraint construction syntax.
858
859 =item B<where>
860
861 This is just sugar for the type constraint construction syntax.
862
863 =item B<message>
864
865 This is just sugar for the type constraint construction syntax.
866
867 =item B<optimize_as>
868
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.
872
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.
876
877 =back
878
879 =head2 Type Coercion Constructors
880
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.
886
887 See the L<SYNOPSIS> for an example of how to use these.
888
889 =over 4
890
891 =item B<coerce>
892
893 =item B<from>
894
895 This is just sugar for the type coercion construction syntax.
896
897 =item B<via>
898
899 This is just sugar for the type coercion construction syntax.
900
901 =back
902
903 =head2 Namespace Management
904
905 =over 4
906
907 =item B<unimport>
908
909 This will remove all the type constraint keywords from the
910 calling class namespace.
911
912 =back
913
914 =head1 BUGS
915
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
918 to cpan-RT.
919
920 =head1 AUTHOR
921
922 Stevan Little E<lt>stevan@iinteractive.comE<gt>
923
924 =head1 COPYRIGHT AND LICENSE
925
926 Copyright 2006-2008 by Infinity Interactive, Inc.
927
928 L<http://www.iinteractive.com>
929
930 This library is free software; you can redistribute it and/or modify
931 it under the same terms as Perl itself.
932
933 =cut