063439d5261c98f4f6fe64c677d5bf67e92c1e52
[gitmo/Moose.git] / lib / Moose / Util / TypeConstraints.pm
1
2 package Moose::Util::TypeConstraints;
3
4 use Carp ();
5 use List::MoreUtils qw( all any );
6 use Scalar::Util qw( blessed reftype );
7 use Moose::Exporter;
8
9 ## --------------------------------------------------------
10 # Prototyped subs must be predeclared because we have a
11 # circular dependency with Moose::Meta::Attribute et. al.
12 # so in case of us being use'd first the predeclaration
13 # ensures the prototypes are in scope when consumers are
14 # compiled.
15
16 # dah sugah!
17 sub where (&);
18 sub via (&);
19 sub message (&);
20 sub optimize_as (&);
21 sub inline_as (&);
22
23 ## --------------------------------------------------------
24
25 use Moose::Deprecated;
26 use Moose::Meta::TypeConstraint;
27 use Moose::Meta::TypeConstraint::Union;
28 use Moose::Meta::TypeConstraint::Intersection;
29 use Moose::Meta::TypeConstraint::Parameterized;
30 use Moose::Meta::TypeConstraint::Parameterizable;
31 use Moose::Meta::TypeConstraint::Class;
32 use Moose::Meta::TypeConstraint::Role;
33 use Moose::Meta::TypeConstraint::Enum;
34 use Moose::Meta::TypeConstraint::DuckType;
35 use Moose::Meta::TypeCoercion;
36 use Moose::Meta::TypeCoercion::Union;
37 use Moose::Meta::TypeCoercion::Intersection;
38 use Moose::Meta::TypeConstraint::Registry;
39
40 Moose::Exporter->setup_import_methods(
41     as_is => [
42         qw(
43             type subtype class_type role_type maybe_type duck_type
44             as where message optimize_as inline_as
45             coerce from via
46             enum union
47             find_type_constraint
48             register_type_constraint
49             match_on_type )
50     ],
51 );
52
53 ## --------------------------------------------------------
54 ## type registry and some useful functions for it
55 ## --------------------------------------------------------
56
57 my $REGISTRY = Moose::Meta::TypeConstraint::Registry->new;
58
59 sub get_type_constraint_registry {$REGISTRY}
60 sub list_all_type_constraints    { keys %{ $REGISTRY->type_constraints } }
61
62 sub export_type_constraints_as_functions {
63     my $pkg = caller();
64     no strict 'refs';
65     foreach my $constraint ( keys %{ $REGISTRY->type_constraints } ) {
66         my $tc = $REGISTRY->get_type_constraint($constraint)
67             ->_compiled_type_constraint;
68         *{"${pkg}::${constraint}"}
69             = sub { $tc->( $_[0] ) ? 1 : undef };    # the undef is for compat
70     }
71 }
72
73 sub create_type_constraint_union {
74     _create_type_constraint_union(\@_);
75 }
76
77 sub create_named_type_constraint_union {
78     my $name = shift;
79     _create_type_constraint_union($name, \@_);
80 }
81
82 sub _create_type_constraint_union {
83     my $name;
84     $name = shift if @_ > 1;
85     my @tcs = @{ shift() };
86
87     my @type_constraint_names;
88
89     if ( scalar @tcs == 1 && _detect_type_constraint_union( $tcs[0] ) ) {
90         @type_constraint_names = _parse_type_constraint_union( $tcs[0] );
91     }
92     else {
93         @type_constraint_names = @tcs;
94     }
95
96     ( scalar @type_constraint_names >= 2 )
97         || __PACKAGE__->_throw_error(
98         "You must pass in at least 2 type names to make a union");
99
100     my @type_constraints = map {
101         find_or_parse_type_constraint($_)
102             || __PACKAGE__->_throw_error(
103             "Could not locate type constraint ($_) for the union");
104     } @type_constraint_names;
105
106     my %options = (
107       type_constraints => \@type_constraints
108     );
109     $options{name} = $name if defined $name;
110
111     return Moose::Meta::TypeConstraint::Union->new(%options);
112 }
113
114 sub create_type_constraint_intersection {
115     my @type_constraint_names;
116
117     if (scalar @_ == 1 && _detect_type_constraint_intersection($_[0])) {
118         @type_constraint_names = _parse_type_constraint_intersection($_[0]);
119     }
120     else {
121         @type_constraint_names = @_;
122     }
123
124     (scalar @type_constraint_names >= 2)
125         || __PACKAGE__->_throw_error("You must pass in at least 2 type names to make an intersection");
126
127     my @type_constraints = map {
128         find_or_parse_type_constraint($_) ||
129          __PACKAGE__->_throw_error("Could not locate type constraint ($_) for the intersection");
130     } @type_constraint_names;
131
132     return Moose::Meta::TypeConstraint::Intersection->new(
133         type_constraints => \@type_constraints
134     );
135 }
136
137 sub create_parameterized_type_constraint {
138     my $type_constraint_name = shift;
139     my ( $base_type, $type_parameter )
140         = _parse_parameterized_type_constraint($type_constraint_name);
141
142     ( defined $base_type && defined $type_parameter )
143         || __PACKAGE__->_throw_error(
144         "Could not parse type name ($type_constraint_name) correctly");
145
146     if ( $REGISTRY->has_type_constraint($base_type) ) {
147         my $base_type_tc = $REGISTRY->get_type_constraint($base_type);
148         return _create_parameterized_type_constraint(
149             $base_type_tc,
150             $type_parameter
151         );
152     }
153     else {
154         __PACKAGE__->_throw_error(
155             "Could not locate the base type ($base_type)");
156     }
157 }
158
159 sub _create_parameterized_type_constraint {
160     my ( $base_type_tc, $type_parameter ) = @_;
161     if ( $base_type_tc->can('parameterize') ) {
162         return $base_type_tc->parameterize($type_parameter);
163     }
164     else {
165         return Moose::Meta::TypeConstraint::Parameterized->new(
166             name   => $base_type_tc->name . '[' . $type_parameter . ']',
167             parent => $base_type_tc,
168             type_parameter =>
169                 find_or_create_isa_type_constraint($type_parameter),
170         );
171     }
172 }
173
174 #should we also support optimized checks?
175 sub create_class_type_constraint {
176     my ( $class, $options ) = @_;
177
178 # too early for this check
179 #find_type_constraint("ClassName")->check($class)
180 #    || __PACKAGE__->_throw_error("Can't create a class type constraint because '$class' is not a class name");
181
182     my %options = (
183         class => $class,
184         name  => $class,
185         %{ $options || {} },
186     );
187
188     $options{name} ||= "__ANON__";
189
190     Moose::Meta::TypeConstraint::Class->new(%options);
191 }
192
193 sub create_role_type_constraint {
194     my ( $role, $options ) = @_;
195
196 # too early for this check
197 #find_type_constraint("ClassName")->check($class)
198 #    || __PACKAGE__->_throw_error("Can't create a class type constraint because '$class' is not a class name");
199
200     my %options = (
201         role => $role,
202         name => $role,
203         %{ $options || {} },
204     );
205
206     $options{name} ||= "__ANON__";
207
208     Moose::Meta::TypeConstraint::Role->new(%options);
209 }
210
211 sub find_or_create_type_constraint {
212     my ( $type_constraint_name, $options_for_anon_type ) = @_;
213
214     if ( my $constraint
215         = find_or_parse_type_constraint($type_constraint_name) ) {
216         return $constraint;
217     }
218     elsif ( defined $options_for_anon_type ) {
219
220         # NOTE:
221         # if there is no $options_for_anon_type
222         # specified, then we assume they don't
223         # want to create one, and return nothing.
224
225         # otherwise assume that we should create
226         # an ANON type with the $options_for_anon_type
227         # options which can be passed in. It should
228         # be noted that these don't get registered
229         # so we need to return it.
230         # - SL
231         return Moose::Meta::TypeConstraint->new(
232             name => '__ANON__',
233             %{$options_for_anon_type}
234         );
235     }
236
237     return;
238 }
239
240 sub find_or_create_isa_type_constraint {
241     my $type_constraint_name = shift;
242     find_or_parse_type_constraint($type_constraint_name)
243         || create_class_type_constraint($type_constraint_name);
244 }
245
246 sub find_or_create_does_type_constraint {
247     my $type_constraint_name = shift;
248     find_or_parse_type_constraint($type_constraint_name)
249         || create_role_type_constraint($type_constraint_name);
250 }
251
252 sub find_or_parse_type_constraint {
253     my $type_constraint_name = normalize_type_constraint_name(shift);
254     my $constraint;
255
256     if ( $constraint = find_type_constraint($type_constraint_name) ) {
257         return $constraint;
258     }
259     elsif (_detect_type_constraint_intersection($type_constraint_name)) {
260         $constraint = create_type_constraint_intersection($type_constraint_name);
261     }
262     elsif (_detect_type_constraint_union($type_constraint_name)) {
263         $constraint = create_type_constraint_union($type_constraint_name);
264     }
265     elsif ( _detect_parameterized_type_constraint($type_constraint_name) ) {
266         $constraint
267             = create_parameterized_type_constraint($type_constraint_name);
268     }
269     else {
270         return;
271     }
272
273     $REGISTRY->add_type_constraint($constraint);
274     return $constraint;
275 }
276
277 sub normalize_type_constraint_name {
278     my $type_constraint_name = shift;
279     $type_constraint_name =~ s/\s//g;
280     return $type_constraint_name;
281 }
282
283 sub _confess {
284     my $error = shift;
285
286     local $Carp::CarpLevel = $Carp::CarpLevel + 1;
287     Carp::confess($error);
288 }
289
290 ## --------------------------------------------------------
291 ## exported functions ...
292 ## --------------------------------------------------------
293
294 sub find_type_constraint {
295     my $type = shift;
296
297     if ( blessed $type and $type->isa("Moose::Meta::TypeConstraint") ) {
298         return $type;
299     }
300     else {
301         return unless $REGISTRY->has_type_constraint($type);
302         return $REGISTRY->get_type_constraint($type);
303     }
304 }
305
306 sub register_type_constraint {
307     my $constraint = shift;
308     __PACKAGE__->_throw_error("can't register an unnamed type constraint")
309         unless defined $constraint->name;
310     $REGISTRY->add_type_constraint($constraint);
311     return $constraint;
312 }
313
314 # type constructors
315
316 sub type {
317     my $name = shift;
318
319     my %p = map { %{$_} } @_;
320
321     return _create_type_constraint(
322         $name, undef, $p{where}, $p{message},
323         $p{optimize_as}, $p{inline_as},
324     );
325 }
326
327 sub subtype {
328     if ( @_ == 1 && !ref $_[0] ) {
329         __PACKAGE__->_throw_error(
330             'A subtype cannot consist solely of a name, it must have a parent'
331         );
332     }
333
334     # The blessed check is mostly to accommodate MooseX::Types, which
335     # uses an object which overloads stringification as a type name.
336     my $name = ref $_[0] && !blessed $_[0] ? undef : shift;
337
338     my %p = map { %{$_} } @_;
339
340     # subtype Str => where { ... };
341     if ( !exists $p{as} ) {
342         $p{as} = $name;
343         $name = undef;
344     }
345
346     return _create_type_constraint(
347         $name, $p{as}, $p{where}, $p{message},
348         $p{optimize_as}, $p{inline_as},
349     );
350 }
351
352 sub class_type {
353     register_type_constraint(
354         create_class_type_constraint(
355             $_[0],
356             ( defined( $_[1] ) ? $_[1] : () ),
357         )
358     );
359 }
360
361 sub role_type ($;$) {
362     register_type_constraint(
363         create_role_type_constraint(
364             $_[0],
365             ( defined( $_[1] ) ? $_[1] : () ),
366         )
367     );
368 }
369
370 sub maybe_type {
371     my ($type_parameter) = @_;
372
373     register_type_constraint(
374         $REGISTRY->get_type_constraint('Maybe')->parameterize($type_parameter)
375     );
376 }
377
378 sub duck_type {
379     my ( $type_name, @methods ) = @_;
380     if ( ref $type_name eq 'ARRAY' && !@methods ) {
381         @methods   = @$type_name;
382         $type_name = undef;
383     }
384     if ( @methods == 1 && ref $methods[0] eq 'ARRAY' ) {
385         @methods = @{ $methods[0] };
386     }
387
388     register_type_constraint(
389         create_duck_type_constraint(
390             $type_name,
391             \@methods,
392         )
393     );
394 }
395
396 sub coerce {
397     my ( $type_name, @coercion_map ) = @_;
398     _install_type_coercions( $type_name, \@coercion_map );
399 }
400
401 # The trick of returning @_ lets us avoid having to specify a
402 # prototype. Perl will parse this:
403 #
404 # subtype 'Foo'
405 #     => as 'Str'
406 #     => where { ... }
407 #
408 # as this:
409 #
410 # subtype( 'Foo', as( 'Str', where { ... } ) );
411 #
412 # If as() returns all its extra arguments, this just works, and
413 # preserves backwards compatibility.
414 sub as { { as => shift }, @_ }
415 sub where (&)       { { where       => $_[0] } }
416 sub message (&)     { { message     => $_[0] } }
417 sub optimize_as (&) { { optimize_as => $_[0] } }
418 sub inline_as (&)   { { inline_as   => $_[0] } }
419
420 sub from    {@_}
421 sub via (&) { $_[0] }
422
423 sub enum {
424     my ( $type_name, @values ) = @_;
425
426     # NOTE:
427     # if only an array-ref is passed then
428     # you get an anon-enum
429     # - SL
430     if ( ref $type_name eq 'ARRAY' ) {
431         @values == 0
432             || __PACKAGE__->_throw_error("enum called with an array reference and additional arguments. Did you mean to parenthesize the enum call's parameters?");
433
434         @values    = @$type_name;
435         $type_name = undef;
436     }
437     if ( @values == 1 && ref $values[0] eq 'ARRAY' ) {
438         @values = @{ $values[0] };
439     }
440
441     register_type_constraint(
442         create_enum_type_constraint(
443             $type_name,
444             \@values,
445         )
446     );
447 }
448
449 sub union {
450   my ( $type_name, @constraints ) = @_;
451   if ( ref $type_name eq 'ARRAY' ) {
452     @constraints == 0
453       || __PACKAGE__->_throw_error("union called with an array reference and additional arguments.");
454     @constraints = @$type_name;
455     $type_name   = undef;
456   }
457   if ( @constraints == 1 && ref $constraints[0] eq 'ARRAY' ) {
458     @constraints = @{ $constraints[0] };
459   }
460   if ( defined $type_name ) {
461     return register_type_constraint(
462       create_named_type_constraint_union( $type_name, @constraints )
463     );
464   }
465   return create_type_constraint_union( @constraints );
466 }
467
468 sub create_enum_type_constraint {
469     my ( $type_name, $values ) = @_;
470
471     Moose::Meta::TypeConstraint::Enum->new(
472         name => $type_name || '__ANON__',
473         values => $values,
474     );
475 }
476
477 sub create_duck_type_constraint {
478     my ( $type_name, $methods ) = @_;
479
480     Moose::Meta::TypeConstraint::DuckType->new(
481         name => $type_name || '__ANON__',
482         methods => $methods,
483     );
484 }
485
486 sub match_on_type {
487     my ($to_match, @cases) = @_;
488     my $default;
489     if (@cases % 2 != 0) {
490         $default = pop @cases;
491         (ref $default eq 'CODE')
492             || __PACKAGE__->_throw_error("Default case must be a CODE ref, not $default");
493     }
494     while (@cases) {
495         my ($type, $action) = splice @cases, 0, 2;
496
497         unless (blessed $type && $type->isa('Moose::Meta::TypeConstraint')) {
498             $type = find_or_parse_type_constraint($type)
499                  || __PACKAGE__->_throw_error("Cannot find or parse the type '$type'")
500         }
501
502         (ref $action eq 'CODE')
503             || __PACKAGE__->_throw_error("Match action must be a CODE ref, not $action");
504
505         if ($type->check($to_match)) {
506             local $_ = $to_match;
507             return $action->($to_match);
508         }
509     }
510     (defined $default)
511         || __PACKAGE__->_throw_error("No cases matched for $to_match");
512     {
513         local $_ = $to_match;
514         return $default->($to_match);
515     }
516 }
517
518
519 ## --------------------------------------------------------
520 ## desugaring functions ...
521 ## --------------------------------------------------------
522
523 sub _create_type_constraint ($$$;$$) {
524     my $name      = shift;
525     my $parent    = shift;
526     my $check     = shift;
527     my $message   = shift;
528     my $optimized = shift;
529     my $inlined   = shift;
530
531     my $pkg_defined_in = scalar( caller(1) );
532
533     if ( defined $name ) {
534         my $type = $REGISTRY->get_type_constraint($name);
535
536         ( $type->_package_defined_in eq $pkg_defined_in )
537             || _confess(
538                   "The type constraint '$name' has already been created in "
539                 . $type->_package_defined_in
540                 . " and cannot be created again in "
541                 . $pkg_defined_in )
542             if defined $type;
543
544         $name =~ /^[\w:\.]+$/
545             or die qq{$name contains invalid characters for a type name.}
546             . qq{ Names can contain alphanumeric character, ":", and "."\n};
547     }
548
549     my %opts = (
550         name               => $name,
551         package_defined_in => $pkg_defined_in,
552
553         ( $check     ? ( constraint => $check )     : () ),
554         ( $message   ? ( message    => $message )   : () ),
555         ( $optimized ? ( optimized  => $optimized ) : () ),
556         ( $inlined   ? ( inlined    => $inlined )   : () ),
557     );
558
559     my $constraint;
560     if (
561         defined $parent
562         and $parent
563         = blessed $parent
564         ? $parent
565         : find_or_create_isa_type_constraint($parent)
566         ) {
567         $constraint = $parent->create_child_type(%opts);
568     }
569     else {
570         $constraint = Moose::Meta::TypeConstraint->new(%opts);
571     }
572
573     $REGISTRY->add_type_constraint($constraint)
574         if defined $name;
575
576     return $constraint;
577 }
578
579 sub _install_type_coercions ($$) {
580     my ( $type_name, $coercion_map ) = @_;
581     my $type = find_type_constraint($type_name);
582     ( defined $type )
583         || __PACKAGE__->_throw_error(
584         "Cannot find type '$type_name', perhaps you forgot to load it");
585     if ( $type->has_coercion ) {
586         $type->coercion->add_type_coercions(@$coercion_map);
587     }
588     else {
589         my $type_coercion = Moose::Meta::TypeCoercion->new(
590             type_coercion_map => $coercion_map,
591             type_constraint   => $type
592         );
593         $type->coercion($type_coercion);
594     }
595 }
596
597 ## --------------------------------------------------------
598 ## type notation parsing ...
599 ## --------------------------------------------------------
600
601 {
602
603     # All I have to say is mugwump++ cause I know
604     # do not even have enough regexp-fu to be able
605     # to have written this (I can only barely
606     # understand it as it is)
607     # - SL
608
609     use re "eval";
610
611     my $valid_chars = qr{[\w:\.]};
612     my $type_atom   = qr{ (?>$valid_chars+) }x;
613     my $ws          = qr{ (?>\s*) }x;
614     my $op_union    = qr{ $ws \| $ws }x;
615     my $op_intersection = qr{ $ws & $ws }x;
616
617     my ($type, $type_capture_parts, $type_with_parameter, $union, $any, $intersection);
618     if (Class::MOP::IS_RUNNING_ON_5_10) {
619         my $type_pattern
620             = q{  (?&type_atom)  (?: \[ (?&ws)  (?&any)  (?&ws) \] )? };
621         my $type_capture_parts_pattern
622             = q{ ((?&type_atom)) (?: \[ (?&ws) ((?&any)) (?&ws) \] )? };
623         my $type_with_parameter_pattern
624             = q{  (?&type_atom)      \[ (?&ws)  (?&any)  (?&ws) \]    };
625         my $union_pattern
626             = q{ (?&type) (?> (?: (?&op_union) (?&type) )+ ) };
627         my $intersection_pattern
628             = q{ (?&type) (?> (?: (?&op_intersection) (?&type) )+ ) };
629         my $any_pattern
630             = q{ (?&type) | (?&union) | (?&intersection) };
631
632         my $defines = qr{(?(DEFINE)
633             (?<valid_chars>         $valid_chars)
634             (?<type_atom>           $type_atom)
635             (?<ws>                  $ws)
636             (?<op_union>            $op_union)
637             (?<op_intersection>     $op_intersection)
638             (?<type>                $type_pattern)
639             (?<type_capture_parts>  $type_capture_parts_pattern)
640             (?<type_with_parameter> $type_with_parameter_pattern)
641             (?<union>               $union_pattern)
642             (?<intersection>        $intersection_pattern)
643             (?<any>                 $any_pattern)
644         )}x;
645
646         $type                = qr{ $type_pattern                $defines }x;
647         $type_capture_parts  = qr{ $type_capture_parts_pattern  $defines }x;
648         $type_with_parameter = qr{ $type_with_parameter_pattern $defines }x;
649         $union               = qr{ $union_pattern               $defines }x;
650         $intersection        = qr{ $intersection_pattern        $defines }x;
651         $any                 = qr{ $any_pattern                 $defines }x;
652     }
653     else {
654         $type
655             = qr{  $type_atom  (?: \[ $ws  (??{$any})  $ws \] )? }x;
656         $type_capture_parts
657             = qr{ ($type_atom) (?: \[ $ws ((??{$any})) $ws \] )? }x;
658         $type_with_parameter
659             = qr{  $type_atom      \[ $ws  (??{$any})  $ws \]    }x;
660         $union
661             = qr{ $type (?> (?: $op_union $type )+ ) }x;
662         $intersection
663             = qr{ $type (?> (?: $op_intersection $type )+ ) }x;
664         $any
665             = qr{ $type | $union | $intersection }x;
666     }
667
668
669     sub _parse_parameterized_type_constraint {
670         { no warnings 'void'; $any; }  # force capture of interpolated lexical
671         $_[0] =~ m{ $type_capture_parts }x;
672         return ( $1, $2 );
673     }
674
675     sub _detect_parameterized_type_constraint {
676         { no warnings 'void'; $any; }  # force capture of interpolated lexical
677         $_[0] =~ m{ ^ $type_with_parameter $ }x;
678     }
679
680     sub _parse_type_constraint_union {
681         { no warnings 'void'; $any; }  # force capture of interpolated lexical
682         my $given = shift;
683         my @rv;
684         while ( $given =~ m{ \G (?: $op_union )? ($type) }gcx ) {
685             push @rv => $1;
686         }
687         ( pos($given) eq length($given) )
688             || __PACKAGE__->_throw_error( "'$given' didn't parse (parse-pos="
689                 . pos($given)
690                 . " and str-length="
691                 . length($given)
692                 . ")" );
693         @rv;
694     }
695
696     sub _parse_type_constraint_intersection {
697         { no warnings 'void'; $any; } # force capture of interpolated lexical
698         my $given = shift;
699         my @rv;
700         while ( $given =~ m{ \G (?: $op_intersection )? ($type) }gcx ) {
701             push @rv => $1;
702         }
703         (pos($given) eq length($given))
704             || __PACKAGE__->_throw_error("'$given' didn't parse (parse-pos="
705                      . pos($given)
706                      . " and str-length="
707                      . length($given)
708                      . ")");
709         @rv;
710     }
711
712     sub _detect_type_constraint_union {
713         { no warnings 'void'; $any; }  # force capture of interpolated lexical
714         $_[0] =~ m{^ $type $op_union $type ( $op_union .* )? $}x;
715     }
716
717     sub _detect_type_constraint_intersection {
718         { no warnings 'void'; $any; } # force capture of interpolated lexical
719         $_[0] =~ m{^ $type $op_intersection $type ( $op_intersection .* )? $}x;
720     }
721 }
722
723 ## --------------------------------------------------------
724 # define some basic built-in types
725 ## --------------------------------------------------------
726
727 # By making these classes immutable before creating all the types in
728 # Moose::Util::TypeConstraints::Builtin , we avoid repeatedly calling the slow
729 # MOP-based accessors.
730 $_->make_immutable(
731     inline_constructor => 1,
732     constructor_name   => "_new",
733
734     # these are Class::MOP accessors, so they need inlining
735     inline_accessors => 1
736     ) for grep { $_->is_mutable }
737     map { Class::MOP::class_of($_) }
738     qw(
739     Moose::Meta::TypeConstraint
740     Moose::Meta::TypeConstraint::Union
741     Moose::Meta::TypeConstraint::Intersection
742     Moose::Meta::TypeConstraint::Parameterized
743     Moose::Meta::TypeConstraint::Parameterizable
744     Moose::Meta::TypeConstraint::Class
745     Moose::Meta::TypeConstraint::Role
746     Moose::Meta::TypeConstraint::Enum
747     Moose::Meta::TypeConstraint::DuckType
748     Moose::Meta::TypeConstraint::Registry
749 );
750
751 require Moose::Util::TypeConstraints::Builtins;
752 Moose::Util::TypeConstraints::Builtins::define_builtins($REGISTRY);
753
754 my @PARAMETERIZABLE_TYPES
755     = map { $REGISTRY->get_type_constraint($_) } qw[ScalarRef ArrayRef HashRef Maybe];
756
757 sub get_all_parameterizable_types {@PARAMETERIZABLE_TYPES}
758
759 sub add_parameterizable_type {
760     my $type = shift;
761     ( blessed $type
762             && $type->isa('Moose::Meta::TypeConstraint::Parameterizable') )
763         || __PACKAGE__->_throw_error(
764         "Type must be a Moose::Meta::TypeConstraint::Parameterizable not $type"
765         );
766     push @PARAMETERIZABLE_TYPES => $type;
767 }
768
769 ## --------------------------------------------------------
770 # end of built-in types ...
771 ## --------------------------------------------------------
772
773 {
774     my @BUILTINS = list_all_type_constraints();
775     sub list_all_builtin_type_constraints {@BUILTINS}
776 }
777
778 sub _throw_error {
779     shift;
780     require Moose;
781     unshift @_, 'Moose';
782     goto &Moose::throw_error;
783 }
784
785 1;
786
787 # ABSTRACT: Type constraint system for Moose
788
789 __END__
790
791 =pod
792
793 =head1 SYNOPSIS
794
795   use Moose::Util::TypeConstraints;
796
797   subtype 'Natural',
798       as 'Int',
799       where { $_ > 0 };
800
801   subtype 'NaturalLessThanTen',
802       as 'Natural',
803       where { $_ < 10 },
804       message { "This number ($_) is not less than ten!" };
805
806   coerce 'Num',
807       from 'Str',
808       via { 0+$_ };
809
810   enum 'RGBColors', [qw(red green blue)];
811
812   union 'StringOrArray', [qw( String Array )];
813
814   no Moose::Util::TypeConstraints;
815
816 =head1 DESCRIPTION
817
818 This module provides Moose with the ability to create custom type
819 constraints to be used in attribute definition.
820
821 =head2 Important Caveat
822
823 This is B<NOT> a type system for Perl 5. These are type constraints,
824 and they are not used by Moose unless you tell it to. No type
825 inference is performed, expressions are not typed, etc. etc. etc.
826
827 A type constraint is at heart a small "check if a value is valid"
828 function. A constraint can be associated with an attribute. This
829 simplifies parameter validation, and makes your code clearer to read,
830 because you can refer to constraints by name.
831
832 =head2 Slightly Less Important Caveat
833
834 It is B<always> a good idea to quote your type names.
835
836 This prevents Perl from trying to execute the call as an indirect
837 object call. This can be an issue when you have a subtype with the
838 same name as a valid class.
839
840 For instance:
841
842   subtype DateTime => as Object => where { $_->isa('DateTime') };
843
844 will I<just work>, while this:
845
846   use DateTime;
847   subtype DateTime => as Object => where { $_->isa('DateTime') };
848
849 will fail silently and cause many headaches. The simple way to solve
850 this, as well as future proof your subtypes from classes which have
851 yet to have been created, is to quote the type name:
852
853   use DateTime;
854   subtype 'DateTime', as 'Object', where { $_->isa('DateTime') };
855
856 =head2 Default Type Constraints
857
858 This module also provides a simple hierarchy for Perl 5 types, here is
859 that hierarchy represented visually.
860
861   Any
862   Item
863       Bool
864       Maybe[`a]
865       Undef
866       Defined
867           Value
868               Str
869                   Num
870                       Int
871                   ClassName
872                   RoleName
873           Ref
874               ScalarRef[`a]
875               ArrayRef[`a]
876               HashRef[`a]
877               CodeRef
878               RegexpRef
879               GlobRef
880               FileHandle
881               Object
882
883 B<NOTE:> Any type followed by a type parameter C<[`a]> can be
884 parameterized, this means you can say:
885
886   ArrayRef[Int]    # an array of integers
887   HashRef[CodeRef] # a hash of str to CODE ref mappings
888   ScalarRef[Int]   # a reference to an integer
889   Maybe[Str]       # value may be a string, may be undefined
890
891 If Moose finds a name in brackets that it does not recognize as an
892 existing type, it assumes that this is a class name, for example
893 C<ArrayRef[DateTime]>.
894
895 B<NOTE:> Unless you parameterize a type, then it is invalid to include
896 the square brackets. I.e. C<ArrayRef[]> will be treated as a new type
897 name, I<not> as a parameterization of C<ArrayRef>.
898
899 B<NOTE:> The C<Undef> type constraint for the most part works
900 correctly now, but edge cases may still exist, please use it
901 sparingly.
902
903 B<NOTE:> The C<ClassName> type constraint does a complex package
904 existence check. This means that your class B<must> be loaded for this
905 type constraint to pass.
906
907 B<NOTE:> The C<RoleName> constraint checks a string is a I<package
908 name> which is a role, like C<'MyApp::Role::Comparable'>.
909
910 =head2 Type Constraint Naming
911
912 Type name declared via this module can only contain alphanumeric
913 characters, colons (:), and periods (.).
914
915 Since the types created by this module are global, it is suggested
916 that you namespace your types just as you would namespace your
917 modules. So instead of creating a I<Color> type for your
918 B<My::Graphics> module, you would call the type
919 I<My::Graphics::Types::Color> instead.
920
921 =head2 Use with Other Constraint Modules
922
923 This module can play nicely with other constraint modules with some
924 slight tweaking. The C<where> clause in types is expected to be a
925 C<CODE> reference which checks its first argument and returns a
926 boolean. Since most constraint modules work in a similar way, it
927 should be simple to adapt them to work with Moose.
928
929 For instance, this is how you could use it with
930 L<Declare::Constraints::Simple> to declare a completely new type.
931
932   type 'HashOfArrayOfObjects',
933       where {
934           IsHashRef(
935               -keys   => HasLength,
936               -values => IsArrayRef(IsObject)
937           )->(@_);
938       };
939
940 For more examples see the F<t/examples/example_w_DCS.t> test
941 file.
942
943 Here is an example of using L<Test::Deep> and its non-test
944 related C<eq_deeply> function.
945
946   type 'ArrayOfHashOfBarsAndRandomNumbers',
947       where {
948           eq_deeply($_,
949               array_each(subhashof({
950                   bar           => isa('Bar'),
951                   random_number => ignore()
952               })))
953         };
954
955 For a complete example see the
956 F<t/examples/example_w_TestDeep.t> test file.
957
958 =head2 Error messages
959
960 Type constraints can also specify custom error messages, for when they fail to
961 validate. This is provided as just another coderef, which receives the invalid
962 value in C<$_>, as in:
963
964   subtype 'PositiveInt',
965        as 'Int',
966        where { $_ > 0 },
967        message { "$_ is not a positive integer!" };
968
969 If no message is specified, a default message will be used, which indicates
970 which type constraint was being used and what value failed. If
971 L<Devel::PartialDump> (version 0.14 or higher) is installed, it will be used to
972 display the invalid value, otherwise it will just be printed as is.
973
974 =head1 FUNCTIONS
975
976 =head2 Type Constraint Constructors
977
978 The following functions are used to create type constraints.  They
979 will also register the type constraints your create in a global
980 registry that is used to look types up by name.
981
982 See the L</SYNOPSIS> for an example of how to use these.
983
984 =over 4
985
986 =item B<< subtype 'Name', as 'Parent', where { } ... >>
987
988 This creates a named subtype.
989
990 If you provide a parent that Moose does not recognize, it will
991 automatically create a new class type constraint for this name.
992
993 When creating a named type, the C<subtype> function should either be
994 called with the sugar helpers (C<where>, C<message>, etc), or with a
995 name and a hashref of parameters:
996
997  subtype( 'Foo', { where => ..., message => ... } );
998
999 The valid hashref keys are C<as> (the parent), C<where>, C<message>,
1000 and C<optimize_as>.
1001
1002 =item B<< subtype as 'Parent', where { } ... >>
1003
1004 This creates an unnamed subtype and will return the type
1005 constraint meta-object, which will be an instance of
1006 L<Moose::Meta::TypeConstraint>.
1007
1008 When creating an anonymous type, the C<subtype> function should either
1009 be called with the sugar helpers (C<where>, C<message>, etc), or with
1010 just a hashref of parameters:
1011
1012  subtype( { where => ..., message => ... } );
1013
1014 =item B<class_type ($class, ?$options)>
1015
1016 Creates a new subtype of C<Object> with the name C<$class> and the
1017 metaclass L<Moose::Meta::TypeConstraint::Class>.
1018
1019 =item B<role_type ($role, ?$options)>
1020
1021 Creates a C<Role> type constraint with the name C<$role> and the
1022 metaclass L<Moose::Meta::TypeConstraint::Role>.
1023
1024 =item B<maybe_type ($type)>
1025
1026 Creates a type constraint for either C<undef> or something of the
1027 given type.
1028
1029 =item B<duck_type ($name, \@methods)>
1030
1031 This will create a subtype of Object and test to make sure the value
1032 C<can()> do the methods in C<\@methods>.
1033
1034 This is intended as an easy way to accept non-Moose objects that
1035 provide a certain interface. If you're using Moose classes, we
1036 recommend that you use a C<requires>-only Role instead.
1037
1038 =item B<duck_type (\@methods)>
1039
1040 If passed an ARRAY reference as the only parameter instead of the
1041 C<$name>, C<\@methods> pair, this will create an unnamed duck type.
1042 This can be used in an attribute definition like so:
1043
1044   has 'cache' => (
1045       is  => 'ro',
1046       isa => duck_type( [qw( get_set )] ),
1047   );
1048
1049 =item B<enum ($name, \@values)>
1050
1051 This will create a basic subtype for a given set of strings.
1052 The resulting constraint will be a subtype of C<Str> and
1053 will match any of the items in C<\@values>. It is case sensitive.
1054 See the L</SYNOPSIS> for a simple example.
1055
1056 B<NOTE:> This is not a true proper enum type, it is simply
1057 a convenient constraint builder.
1058
1059 =item B<enum (\@values)>
1060
1061 If passed an ARRAY reference as the only parameter instead of the
1062 C<$name>, C<\@values> pair, this will create an unnamed enum. This
1063 can then be used in an attribute definition like so:
1064
1065   has 'sort_order' => (
1066       is  => 'ro',
1067       isa => enum([qw[ ascending descending ]]),
1068   );
1069
1070 =item B<union ($name, \@constraints)>
1071
1072 This will create a basic subtype where any of the provided constraints
1073 may match in order to satisfy this constraint.
1074
1075 =item B<union (\@constraints)>
1076
1077 If passed an ARRAY reference as the only parameter instead of the
1078 C<$name>, C<\@constraints> pair, this will create an unnamed union.
1079 This can then be used in an attribute definition like so:
1080
1081   has 'items' => (
1082       is => 'ro',
1083       isa => union([qw[ Str ArrayRef ]]),
1084   );
1085
1086 This is similar to the existing string union:
1087
1088   isa => 'Str|ArrayRef'
1089
1090 except that it supports anonymous elements as child constraints:
1091
1092   has 'color' => (
1093     isa => 'ro',
1094     isa => union([ 'Int',  enum([qw[ red green blue ]]) ]),
1095   );
1096
1097 =item B<as 'Parent'>
1098
1099 This is just sugar for the type constraint construction syntax.
1100
1101 It takes a single argument, which is the name of a parent type.
1102
1103 =item B<where { ... }>
1104
1105 This is just sugar for the type constraint construction syntax.
1106
1107 It takes a subroutine reference as an argument. When the type
1108 constraint is tested, the reference is run with the value to be tested
1109 in C<$_>. This reference should return true or false to indicate
1110 whether or not the constraint check passed.
1111
1112 =item B<message { ... }>
1113
1114 This is just sugar for the type constraint construction syntax.
1115
1116 It takes a subroutine reference as an argument. When the type
1117 constraint fails, then the code block is run with the value provided
1118 in C<$_>. This reference should return a string, which will be used in
1119 the text of the exception thrown.
1120
1121 =item B<inline_as { ... }>
1122
1123 This can be used to define a "hand optimized" inlinable version of your type
1124 constraint.
1125
1126 You provide a subroutine which will be called I<as a method> on a
1127 L<Moose::Meta::TypeConstraint> object. It will receive a single parameter, the
1128 name of the variable to check, typically something like C<"$_"> or C<"$_[0]">.
1129
1130 The subroutine should return a code string suitable for inlining. You can
1131 assume that the check will be wrapped in parentheses when it is inlined.
1132
1133 The inlined code should include any checks that your type's parent types
1134 do. For example, the C<Value> type's inlining sub looks like this:
1135
1136     sub {
1137         'defined(' . $_[1] . ')'
1138         . ' && !ref(' . $_[1] . ')'
1139     }
1140
1141 Note that it checks if the variable is defined, since it is a subtype of
1142 the C<Defined> type.  However, to avoid repeating code, this can be optimized as:
1143
1144     sub {
1145         $_[0]->parent()->_inline_check($_[1])
1146         . ' && !ref(' . $_[1] . ')'
1147     }
1148
1149 =item B<optimize_as { ... }>
1150
1151 B<This feature is deprecated, use C<inline_as> instead.>
1152
1153 This can be used to define a "hand optimized" version of your
1154 type constraint which can be used to avoid traversing a subtype
1155 constraint hierarchy.
1156
1157 B<NOTE:> You should only use this if you know what you are doing.
1158 All the built in types use this, so your subtypes (assuming they
1159 are shallow) will not likely need to use this.
1160
1161 =item B<< type 'Name', where { } ... >>
1162
1163 This creates a base type, which has no parent.
1164
1165 The C<type> function should either be called with the sugar helpers
1166 (C<where>, C<message>, etc), or with a name and a hashref of
1167 parameters:
1168
1169   type( 'Foo', { where => ..., message => ... } );
1170
1171 The valid hashref keys are C<where>, C<message>, and C<inlined_as>.
1172
1173 =back
1174
1175 =head2 Type Constraint Utilities
1176
1177 =over 4
1178
1179 =item B<< match_on_type $value => ( $type => \&action, ... ?\&default ) >>
1180
1181 This is a utility function for doing simple type based dispatching similar to
1182 match/case in OCaml and case/of in Haskell. It is not as featureful as those
1183 languages, nor does not it support any kind of automatic destructuring
1184 bind. Here is a simple Perl pretty printer dispatching over the core Moose
1185 types.
1186
1187   sub ppprint {
1188       my $x = shift;
1189       match_on_type $x => (
1190           HashRef => sub {
1191               my $hash = shift;
1192               '{ '
1193                   . (
1194                   join ", " => map { $_ . ' => ' . ppprint( $hash->{$_} ) }
1195                       sort keys %$hash
1196                   ) . ' }';
1197           },
1198           ArrayRef => sub {
1199               my $array = shift;
1200               '[ ' . ( join ", " => map { ppprint($_) } @$array ) . ' ]';
1201           },
1202           CodeRef   => sub {'sub { ... }'},
1203           RegexpRef => sub { 'qr/' . $_ . '/' },
1204           GlobRef   => sub { '*' . B::svref_2object($_)->NAME },
1205           Object    => sub { $_->can('to_string') ? $_->to_string : $_ },
1206           ScalarRef => sub { '\\' . ppprint( ${$_} ) },
1207           Num       => sub {$_},
1208           Str       => sub { '"' . $_ . '"' },
1209           Undef     => sub {'undef'},
1210           => sub { die "I don't know what $_ is" }
1211       );
1212   }
1213
1214 Or a simple JSON serializer:
1215
1216   sub to_json {
1217       my $x = shift;
1218       match_on_type $x => (
1219           HashRef => sub {
1220               my $hash = shift;
1221               '{ '
1222                   . (
1223                   join ", " =>
1224                       map { '"' . $_ . '" : ' . to_json( $hash->{$_} ) }
1225                       sort keys %$hash
1226                   ) . ' }';
1227           },
1228           ArrayRef => sub {
1229               my $array = shift;
1230               '[ ' . ( join ", " => map { to_json($_) } @$array ) . ' ]';
1231           },
1232           Num   => sub {$_},
1233           Str   => sub { '"' . $_ . '"' },
1234           Undef => sub {'null'},
1235           => sub { die "$_ is not acceptable json type" }
1236       );
1237   }
1238
1239 The matcher is done by mapping a C<$type> to an C<\&action>. The C<$type> can
1240 be either a string type or a L<Moose::Meta::TypeConstraint> object, and
1241 C<\&action> is a subroutine reference. This function will dispatch on the
1242 first match for C<$value>. It is possible to have a catch-all by providing an
1243 additional subroutine reference as the final argument to C<match_on_type>.
1244
1245 =back
1246
1247 =head2 Type Coercion Constructors
1248
1249 You can define coercions for type constraints, which allow you to
1250 automatically transform values to something valid for the type
1251 constraint. If you ask your accessor to coerce, then Moose will run
1252 the type-coercion code first, followed by the type constraint
1253 check. This feature should be used carefully as it is very powerful
1254 and could easily take off a limb if you are not careful.
1255
1256 See the L</SYNOPSIS> for an example of how to use these.
1257
1258 =over 4
1259
1260 =item B<< coerce 'Name', from 'OtherName', via { ... }  >>
1261
1262 This defines a coercion from one type to another. The C<Name> argument
1263 is the type you are coercing I<to>.
1264
1265 To define multiple coercions, supply more sets of from/via pairs:
1266
1267   coerce 'Name',
1268     from 'OtherName', via { ... },
1269     from 'ThirdName', via { ... };
1270
1271 =item B<from 'OtherName'>
1272
1273 This is just sugar for the type coercion construction syntax.
1274
1275 It takes a single type name (or type object), which is the type being
1276 coerced I<from>.
1277
1278 =item B<via { ... }>
1279
1280 This is just sugar for the type coercion construction syntax.
1281
1282 It takes a subroutine reference. This reference will be called with
1283 the value to be coerced in C<$_>. It is expected to return a new value
1284 of the proper type for the coercion.
1285
1286 =back
1287
1288 =head2 Creating and Finding Type Constraints
1289
1290 These are additional functions for creating and finding type
1291 constraints. Most of these functions are not available for
1292 importing. The ones that are importable as specified.
1293
1294 =over 4
1295
1296 =item B<find_type_constraint($type_name)>
1297
1298 This function can be used to locate the L<Moose::Meta::TypeConstraint>
1299 object for a named type.
1300
1301 This function is importable.
1302
1303 =item B<register_type_constraint($type_object)>
1304
1305 This function will register a L<Moose::Meta::TypeConstraint> with the
1306 global type registry.
1307
1308 This function is importable.
1309
1310 =item B<normalize_type_constraint_name($type_constraint_name)>
1311
1312 This method takes a type constraint name and returns the normalized
1313 form. This removes any whitespace in the string.
1314
1315 =item B<create_type_constraint_union($pipe_separated_types | @type_constraint_names)>
1316
1317 =item B<create_named_type_constraint_union($name, $pipe_separated_types | @type_constraint_names)>
1318
1319 This can take a union type specification like C<'Int|ArrayRef[Int]'>,
1320 or a list of names. It returns a new
1321 L<Moose::Meta::TypeConstraint::Union> object.
1322
1323 =item B<create_type_constraint_intersection ($pipe_separated_types | @type_constraint_names)>
1324
1325 Given string with C<$pipe_separated_types> or a list of C<@type_constraint_names>,
1326 this will return a L<Moose::Meta::TypeConstraint::Intersection> instance.
1327
1328 =item B<create_parameterized_type_constraint($type_name)>
1329
1330 Given a C<$type_name> in the form of C<'BaseType[ContainerType]'>,
1331 this will create a new L<Moose::Meta::TypeConstraint::Parameterized>
1332 object. The C<BaseType> must exist already exist as a parameterizable
1333 type.
1334
1335 =item B<create_class_type_constraint($class, $options)>
1336
1337 Given a class name this function will create a new
1338 L<Moose::Meta::TypeConstraint::Class> object for that class name.
1339
1340 The C<$options> is a hash reference that will be passed to the
1341 L<Moose::Meta::TypeConstraint::Class> constructor (as a hash).
1342
1343 =item B<create_role_type_constraint($role, $options)>
1344
1345 Given a role name this function will create a new
1346 L<Moose::Meta::TypeConstraint::Role> object for that role name.
1347
1348 The C<$options> is a hash reference that will be passed to the
1349 L<Moose::Meta::TypeConstraint::Role> constructor (as a hash).
1350
1351 =item B<create_enum_type_constraint($name, $values)>
1352
1353 Given a enum name this function will create a new
1354 L<Moose::Meta::TypeConstraint::Enum> object for that enum name.
1355
1356 =item B<create_duck_type_constraint($name, $methods)>
1357
1358 Given a duck type name this function will create a new
1359 L<Moose::Meta::TypeConstraint::DuckType> object for that enum name.
1360
1361 =item B<find_or_parse_type_constraint($type_name)>
1362
1363 Given a type name, this first attempts to find a matching constraint
1364 in the global registry.
1365
1366 If the type name is a union or parameterized type, it will create a
1367 new object of the appropriate, but if given a "regular" type that does
1368 not yet exist, it simply returns false.
1369
1370 When given a union or parameterized type, the member or base type must
1371 already exist.
1372
1373 If it creates a new union or parameterized type, it will add it to the
1374 global registry.
1375
1376 =item B<find_or_create_isa_type_constraint($type_name)>
1377
1378 =item B<find_or_create_does_type_constraint($type_name)>
1379
1380 These functions will first call C<find_or_parse_type_constraint>. If
1381 that function does not return a type, a new type object will
1382 be created.
1383
1384 The C<isa> variant will use C<create_class_type_constraint> and the
1385 C<does> variant will use C<create_role_type_constraint>.
1386
1387 =item B<get_type_constraint_registry>
1388
1389 Returns the L<Moose::Meta::TypeConstraint::Registry> object which
1390 keeps track of all type constraints.
1391
1392 =item B<list_all_type_constraints>
1393
1394 This will return a list of type constraint names in the global
1395 registry. You can then fetch the actual type object using
1396 C<find_type_constraint($type_name)>.
1397
1398 =item B<list_all_builtin_type_constraints>
1399
1400 This will return a list of builtin type constraints, meaning those
1401 which are defined in this module. See the L<Default Type Constraints>
1402 section for a complete list.
1403
1404 =item B<export_type_constraints_as_functions>
1405
1406 This will export all the current type constraints as functions into
1407 the caller's namespace (C<Int()>, C<Str()>, etc). Right now, this is
1408 mostly used for testing, but it might prove useful to others.
1409
1410 =item B<get_all_parameterizable_types>
1411
1412 This returns all the parameterizable types that have been registered,
1413 as a list of type objects.
1414
1415 =item B<add_parameterizable_type($type)>
1416
1417 Adds C<$type> to the list of parameterizable types
1418
1419 =back
1420
1421 =head1 BUGS
1422
1423 See L<Moose/BUGS> for details on reporting bugs.
1424
1425 =cut