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