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