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