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