regsiter maybe_type
[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
1aab4011 12our $VERSION = '0.64';
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
e85d2a5d 29## private stuff ...
d9b40005 30sub _create_type_constraint ($$$;$$);
31sub _install_type_coercions ($$);
32
33## --------------------------------------------------------
8c4acc60 34
4e036ee4 35use Moose::Meta::TypeConstraint;
3726f905 36use Moose::Meta::TypeConstraint::Union;
0fbd4b0a 37use Moose::Meta::TypeConstraint::Parameterized;
7e4e1ad4 38use Moose::Meta::TypeConstraint::Parameterizable;
620db045 39use Moose::Meta::TypeConstraint::Class;
40use Moose::Meta::TypeConstraint::Role;
dabed765 41use Moose::Meta::TypeConstraint::Enum;
2ca63f5d 42use Moose::Meta::TypeCoercion;
3726f905 43use Moose::Meta::TypeCoercion::Union;
22aed3c0 44use Moose::Meta::TypeConstraint::Registry;
28ffb449 45use Moose::Util::TypeConstraints::OptimizedConstraints;
4e036ee4 46
e606ae5f 47Moose::Exporter->setup_import_methods(
48 as_is => [
49 qw(
1b2c9bda 50 type subtype class_type role_type maybe_type
51 as where message optimize_as
e606ae5f 52 coerce from via
53 enum
54 find_type_constraint
55 register_type_constraint )
56 ],
57 _export_to_main => 1,
58);
a15dff8d 59
d9b40005 60## --------------------------------------------------------
61## type registry and some useful functions for it
62## --------------------------------------------------------
63
22aed3c0 64my $REGISTRY = Moose::Meta::TypeConstraint::Registry->new;
587ae0d2 65
d9b40005 66sub get_type_constraint_registry { $REGISTRY }
e85d2a5d 67sub list_all_type_constraints { keys %{$REGISTRY->type_constraints} }
d9b40005 68sub export_type_constraints_as_functions {
69 my $pkg = caller();
70 no strict 'refs';
a0f8153d 71 foreach my $constraint (keys %{$REGISTRY->type_constraints}) {
42bc21a4 72 my $tc = $REGISTRY->get_type_constraint($constraint)->_compiled_type_constraint;
d2f0f6e9 73 *{"${pkg}::${constraint}"} = sub { $tc->($_[0]) ? 1 : undef }; # the undef is for compat
a0f8153d 74 }
d9b40005 75}
182134e8 76
0c015f1b 77sub create_type_constraint_union {
d9b40005 78 my @type_constraint_names;
e85d2a5d 79
f1917f58 80 if (scalar @_ == 1 && _detect_type_constraint_union($_[0])) {
81 @type_constraint_names = _parse_type_constraint_union($_[0]);
d9b40005 82 }
83 else {
84 @type_constraint_names = @_;
429ccc11 85 }
eb4c4e82 86
3726f905 87 (scalar @type_constraint_names >= 2)
c245d69b 88 || Moose->throw_error("You must pass in at least 2 type names to make a union");
e85d2a5d 89
84a9c64c 90 my @type_constraints = map {
08380fdb 91 find_or_parse_type_constraint($_) ||
fa92d705 92 Moose->throw_error("Could not locate type constraint ($_) for the union");
08380fdb 93 } @type_constraint_names;
84a9c64c 94
3726f905 95 return Moose::Meta::TypeConstraint::Union->new(
fa92d705 96 type_constraints => \@type_constraints
e85d2a5d 97 );
182134e8 98}
a15dff8d 99
0c015f1b 100sub create_parameterized_type_constraint {
d9b40005 101 my $type_constraint_name = shift;
98407b93 102 my ($base_type, $type_parameter) = _parse_parameterized_type_constraint($type_constraint_name);
e85d2a5d 103
98407b93 104 (defined $base_type && defined $type_parameter)
c245d69b 105 || Moose->throw_error("Could not parse type name ($type_constraint_name) correctly");
e85d2a5d 106
90e78884 107 if ($REGISTRY->has_type_constraint($base_type)) {
108 my $base_type_tc = $REGISTRY->get_type_constraint($base_type);
109 return _create_parameterized_type_constraint(
110 $base_type_tc,
111 $type_parameter
112 );
113 } else {
114 Moose->throw_error("Could not locate the base type ($base_type)");
115 }
22aed3c0 116}
117
90e78884 118sub _create_parameterized_type_constraint {
119 my ( $base_type_tc, $type_parameter ) = @_;
120 if ( $base_type_tc->can('parameterize') ) {
121 return $base_type_tc->parameterize($type_parameter);
122 } else {
123 return Moose::Meta::TypeConstraint::Parameterized->new(
124 name => $base_type_tc->name . '[' . $type_parameter . ']',
125 parent => $base_type_tc,
126 type_parameter => find_or_create_isa_type_constraint($type_parameter),
127 );
128 }
129}
130
4ab662d6 131#should we also support optimized checks?
0c015f1b 132sub create_class_type_constraint {
620db045 133 my ( $class, $options ) = @_;
134
3fef8ce8 135 # too early for this check
136 #find_type_constraint("ClassName")->check($class)
c245d69b 137 # || Moose->throw_error("Can't create a class type constraint because '$class' is not a class name");
3fef8ce8 138
620db045 139 my %options = (
140 class => $class,
141 name => $class,
142 %{ $options || {} },
4ab662d6 143 );
620db045 144
145 $options{name} ||= "__ANON__";
146
147 Moose::Meta::TypeConstraint::Class->new( %options );
3fef8ce8 148}
149
0c015f1b 150sub create_role_type_constraint {
620db045 151 my ( $role, $options ) = @_;
e85d2a5d 152
620db045 153 # too early for this check
154 #find_type_constraint("ClassName")->check($class)
c245d69b 155 # || Moose->throw_error("Can't create a class type constraint because '$class' is not a class name");
e85d2a5d 156
620db045 157 my %options = (
158 role => $role,
159 name => $role,
160 %{ $options || {} },
161 );
e85d2a5d 162
620db045 163 $options{name} ||= "__ANON__";
164
165 Moose::Meta::TypeConstraint::Role->new( %options );
166}
167
168
0c015f1b 169sub find_or_create_type_constraint {
620db045 170 my ( $type_constraint_name, $options_for_anon_type ) = @_;
171
172 if ( my $constraint = find_or_parse_type_constraint($type_constraint_name) ) {
173 return $constraint;
d9b40005 174 }
620db045 175 elsif ( defined $options_for_anon_type ) {
d9b40005 176 # NOTE:
4ab662d6 177 # if there is no $options_for_anon_type
178 # specified, then we assume they don't
f3c4e20e 179 # want to create one, and return nothing.
f3c4e20e 180
d9b40005 181 # otherwise assume that we should create
e85d2a5d 182 # an ANON type with the $options_for_anon_type
d9b40005 183 # options which can be passed in. It should
e85d2a5d 184 # be noted that these don't get registered
d9b40005 185 # so we need to return it.
186 # - SL
187 return Moose::Meta::TypeConstraint->new(
188 name => '__ANON__',
e85d2a5d 189 %{$options_for_anon_type}
d9b40005 190 );
191 }
e85d2a5d 192
620db045 193 return;
194}
195
0c015f1b 196sub find_or_create_isa_type_constraint {
620db045 197 my $type_constraint_name = shift;
5e2ada84 198 find_or_parse_type_constraint($type_constraint_name) || create_class_type_constraint($type_constraint_name)
620db045 199}
200
0c015f1b 201sub find_or_create_does_type_constraint {
620db045 202 my $type_constraint_name = shift;
5e2ada84 203 find_or_parse_type_constraint($type_constraint_name) || create_role_type_constraint($type_constraint_name)
620db045 204}
205
0c015f1b 206sub find_or_parse_type_constraint {
eb4c4e82 207 my $type_constraint_name = normalize_type_constraint_name(shift);
620db045 208 my $constraint;
e606ae5f 209
210 if ($constraint = find_type_constraint($type_constraint_name)) {
211 return $constraint;
212 } elsif (_detect_type_constraint_union($type_constraint_name)) {
620db045 213 $constraint = create_type_constraint_union($type_constraint_name);
08380fdb 214 } elsif (_detect_parameterized_type_constraint($type_constraint_name)) {
620db045 215 $constraint = create_parameterized_type_constraint($type_constraint_name);
216 } else {
217 return;
218 }
bb6c8335 219
d9b40005 220 $REGISTRY->add_type_constraint($constraint);
e85d2a5d 221 return $constraint;
d9b40005 222}
22aed3c0 223
eb4c4e82 224sub normalize_type_constraint_name {
84a9c64c 225 my $type_constraint_name = shift;
c8f663b2 226 $type_constraint_name =~ s/\s//g;
eb4c4e82 227 return $type_constraint_name;
228}
229
5f223879 230sub _confess {
231 my $error = shift;
232
233 local $Carp::CarpLevel = $Carp::CarpLevel + 1;
234 Carp::confess($error);
235}
236
22aed3c0 237## --------------------------------------------------------
238## exported functions ...
239## --------------------------------------------------------
240
0c015f1b 241sub find_type_constraint {
eeedfc8a 242 my $type = shift;
243
244 if ( blessed $type and $type->isa("Moose::Meta::TypeConstraint") ) {
245 return $type;
e606ae5f 246 }
247 else {
248 return unless $REGISTRY->has_type_constraint($type);
eeedfc8a 249 return $REGISTRY->get_type_constraint($type);
250 }
251}
22aed3c0 252
0c015f1b 253sub register_type_constraint {
3fef8ce8 254 my $constraint = shift;
c245d69b 255 Moose->throw_error("can't register an unnamed type constraint") unless defined $constraint->name;
3fef8ce8 256 $REGISTRY->add_type_constraint($constraint);
dabed765 257 return $constraint;
3fef8ce8 258}
259
7c13858b 260# type constructors
a15dff8d 261
9c27968f 262sub type {
1b7df21f 263 splice(@_, 1, 0, undef);
a0f8153d 264 goto &_create_type_constraint;
a15dff8d 265}
266
9c27968f 267sub subtype {
86629f93 268 # NOTE:
269 # this adds an undef for the name
270 # if this is an anon-subtype:
271 # subtype(Num => where { $_ % 2 == 0 }) # anon 'even' subtype
e3979c3e 272 # or
273 # subtype(Num => where { $_ % 2 == 0 }) message { "$_ must be an even number" }
274 #
275 # but if the last arg is not a code ref then it is a subtype
276 # alias:
277 #
86629f93 278 # subtype(MyNumbers => as Num); # now MyNumbers is the same as Num
e85d2a5d 279 # ... yeah I know it's ugly code
86629f93 280 # - SL
e3979c3e 281 unshift @_ => undef if scalar @_ == 2 && ( 'CODE' eq ref( $_[-1] ) );
282 unshift @_ => undef
283 if scalar @_ == 3 && all { ref($_) =~ /^(?:CODE|HASH)$/ } @_[ 1, 2 ];
a0f8153d 284 goto &_create_type_constraint;
a15dff8d 285}
286
9c27968f 287sub class_type {
4ab662d6 288 register_type_constraint(
289 create_class_type_constraint(
290 $_[0],
291 ( defined($_[1]) ? $_[1] : () ),
292 )
293 );
3fef8ce8 294}
295
620db045 296sub role_type ($;$) {
297 register_type_constraint(
298 create_role_type_constraint(
299 $_[0],
300 ( defined($_[1]) ? $_[1] : () ),
301 )
302 );
303}
304
1b2c9bda 305sub maybe_type {
306 my ($type_parameter) = @_;
307
28ce1444 308 register_type_constraint(
309 Moose::Meta::TypeConstraint->new(
310 parent => find_type_constraint('Item'),
311 constraint => sub {
312 my $check = $type_parameter->_compiled_type_constraint;
313 return 1 if not(defined($_)) || $check->($_);
314 return;
315 }
316 )
317 );
1b2c9bda 318}
319
9c27968f 320sub coerce {
e85d2a5d 321 my ($type_name, @coercion_map) = @_;
7c13858b 322 _install_type_coercions($type_name, \@coercion_map);
182134e8 323}
324
9c27968f 325sub as { @_ }
326sub from { @_ }
76d37e5a 327sub where (&) { $_[0] }
328sub via (&) { $_[0] }
8ecb1fa0 329
330sub message (&) { +{ message => $_[0] } }
331sub optimize_as (&) { +{ optimized => $_[0] } }
a15dff8d 332
9c27968f 333sub enum {
fcec2383 334 my ($type_name, @values) = @_;
4ab662d6 335 # NOTE:
336 # if only an array-ref is passed then
9f4334a1 337 # you get an anon-enum
338 # - SL
339 if (ref $type_name eq 'ARRAY' && !@values) {
340 @values = @$type_name;
341 $type_name = undef;
342 }
2c0cbef7 343 (scalar @values >= 2)
c245d69b 344 || Moose->throw_error("You must have at least two values to enumerate through");
c4fe165f 345 my %valid = map { $_ => 1 } @values;
dabed765 346
347 register_type_constraint(
348 create_enum_type_constraint(
349 $type_name,
350 \@values,
351 )
352 );
353}
354
0c015f1b 355sub create_enum_type_constraint {
dabed765 356 my ( $type_name, $values ) = @_;
e606ae5f 357
dabed765 358 Moose::Meta::TypeConstraint::Enum->new(
359 name => $type_name || '__ANON__',
360 values => $values,
a0f8153d 361 );
fcec2383 362}
363
d9b40005 364## --------------------------------------------------------
365## desugaring functions ...
366## --------------------------------------------------------
367
e85d2a5d 368sub _create_type_constraint ($$$;$$) {
d9b40005 369 my $name = shift;
370 my $parent = shift;
8de73ff1 371 my $check = shift;
e85d2a5d 372
1da6728b 373 my ( $message, $optimized );
d9b40005 374 for (@_) {
375 $message = $_->{message} if exists $_->{message};
e85d2a5d 376 $optimized = $_->{optimized} if exists $_->{optimized};
d9b40005 377 }
378
1da6728b 379 my $pkg_defined_in = scalar( caller(0) );
e85d2a5d 380
1da6728b 381 if ( defined $name ) {
d9b40005 382 my $type = $REGISTRY->get_type_constraint($name);
e85d2a5d 383
5f223879 384 ( $type->_package_defined_in eq $pkg_defined_in )
385 || _confess(
386 "The type constraint '$name' has already been created in "
387 . $type->_package_defined_in
388 . " and cannot be created again in "
389 . $pkg_defined_in )
390 if defined $type;
e85d2a5d 391 }
1da6728b 392
9ceb576e 393 my %opts = (
ec8b7b21 394 name => $name,
d9b40005 395 package_defined_in => $pkg_defined_in,
e85d2a5d 396
1da6728b 397 ( $check ? ( constraint => $check ) : () ),
398 ( $message ? ( message => $message ) : () ),
399 ( $optimized ? ( optimized => $optimized ) : () ),
d9b40005 400 );
1da6728b 401
9ceb576e 402 my $constraint;
1da6728b 403 if ( defined $parent
404 and $parent
405 = blessed $parent ? $parent : find_or_parse_type_constraint($parent) )
406 {
85a9908f 407 $constraint = $parent->create_child_type(%opts);
1da6728b 408 }
409 else {
410 $constraint = Moose::Meta::TypeConstraint->new(%opts);
4ab662d6 411 }
d9b40005 412
413 $REGISTRY->add_type_constraint($constraint)
414 if defined $name;
415
416 return $constraint;
417}
418
e85d2a5d 419sub _install_type_coercions ($$) {
d9b40005 420 my ($type_name, $coercion_map) = @_;
e606ae5f 421 my $type = find_type_constraint($type_name);
6f9ff1af 422 (defined $type)
c245d69b 423 || Moose->throw_error("Cannot find type '$type_name', perhaps you forgot to load it.");
41e007e4 424 if ($type->has_coercion) {
425 $type->coercion->add_type_coercions(@$coercion_map);
426 }
427 else {
428 my $type_coercion = Moose::Meta::TypeCoercion->new(
429 type_coercion_map => $coercion_map,
430 type_constraint => $type
431 );
432 $type->coercion($type_coercion);
433 }
d9b40005 434}
435
436## --------------------------------------------------------
f1917f58 437## type notation parsing ...
438## --------------------------------------------------------
439
440{
e85d2a5d 441 # All I have to say is mugwump++ cause I know
442 # do not even have enough regexp-fu to be able
443 # to have written this (I can only barely
f1917f58 444 # understand it as it is)
e85d2a5d 445 # - SL
446
f1917f58 447 use re "eval";
448
3796382a 449 my $valid_chars = qr{[\w:]};
f1917f58 450 my $type_atom = qr{ $valid_chars+ };
451
be722745 452 my $any;
453
369a74ee 454 my $type = qr{ $valid_chars+ (?: \[ \s* (??{$any}) \s* \] )? }x;
08380fdb 455 my $type_capture_parts = qr{ ($valid_chars+) (?: \[ \s* ((??{$any})) \s* \] )? }x;
369a74ee 456 my $type_with_parameter = qr{ $valid_chars+ \[ \s* (??{$any}) \s* \] }x;
f1917f58 457
3796382a 458 my $op_union = qr{ \s* \| \s* }x;
f1917f58 459 my $union = qr{ $type (?: $op_union $type )+ }x;
460
84a9c64c 461 $any = qr{ $type | $union }x;
f1917f58 462
0fbd4b0a 463 sub _parse_parameterized_type_constraint {
be722745 464 { no warnings 'void'; $any; } # force capture of interpolated lexical
84a9c64c 465 $_[0] =~ m{ $type_capture_parts }x;
466 return ($1, $2);
f1917f58 467 }
468
0fbd4b0a 469 sub _detect_parameterized_type_constraint {
be722745 470 { no warnings 'void'; $any; } # force capture of interpolated lexical
e85d2a5d 471 $_[0] =~ m{ ^ $type_with_parameter $ }x;
f1917f58 472 }
473
474 sub _parse_type_constraint_union {
be722745 475 { no warnings 'void'; $any; } # force capture of interpolated lexical
e85d2a5d 476 my $given = shift;
477 my @rv;
478 while ( $given =~ m{ \G (?: $op_union )? ($type) }gcx ) {
82a5b1a7 479 push @rv => $1;
e85d2a5d 480 }
481 (pos($given) eq length($given))
c245d69b 482 || Moose->throw_error("'$given' didn't parse (parse-pos="
e85d2a5d 483 . pos($given)
484 . " and str-length="
485 . length($given)
4c0b3599 486 . ")");
e85d2a5d 487 @rv;
f1917f58 488 }
489
490 sub _detect_type_constraint_union {
be722745 491 { no warnings 'void'; $any; } # force capture of interpolated lexical
e85d2a5d 492 $_[0] =~ m{^ $type $op_union $type ( $op_union .* )? $}x;
f1917f58 493 }
494}
495
496## --------------------------------------------------------
d9b40005 497# define some basic built-in types
498## --------------------------------------------------------
a15dff8d 499
3cae4250 500# By making these classes immutable before creating all the types we
501# below, we avoid repeatedly calling the slow MOP-based accessors.
502$_->make_immutable(
503 inline_constructor => 1,
504 constructor_name => "_new",
505
506 # these are Class::MOP accessors, so they need inlining
507 inline_accessors => 1
508 ) for grep { $_->is_mutable }
509 map { $_->meta }
510 qw(
511 Moose::Meta::TypeConstraint
512 Moose::Meta::TypeConstraint::Union
513 Moose::Meta::TypeConstraint::Parameterized
514 Moose::Meta::TypeConstraint::Parameterizable
515 Moose::Meta::TypeConstraint::Class
516 Moose::Meta::TypeConstraint::Role
517 Moose::Meta::TypeConstraint::Enum
518 Moose::Meta::TypeConstraint::Registry
519);
520
f65cb534 521type 'Any' => where { 1 }; # meta-type including all
e85d2a5d 522type 'Item' => where { 1 }; # base-type
a15dff8d 523
fd542f49 524subtype 'Undef' => as 'Item' => where { !defined($_) };
525subtype 'Defined' => as 'Item' => where { defined($_) };
a15dff8d 526
8ecb1fa0 527subtype 'Bool'
e85d2a5d 528 => as 'Item'
8ecb1fa0 529 => where { !defined($_) || $_ eq "" || "$_" eq '1' || "$_" eq '0' };
5a4c5493 530
e85d2a5d 531subtype 'Value'
532 => as 'Defined'
533 => where { !ref($_) }
28ffb449 534 => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Value;
e85d2a5d 535
8ecb1fa0 536subtype 'Ref'
e85d2a5d 537 => as 'Defined'
538 => where { ref($_) }
28ffb449 539 => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Ref;
8ecb1fa0 540
e85d2a5d 541subtype 'Str'
542 => as 'Value'
543 => where { 1 }
28ffb449 544 => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Str;
8ecb1fa0 545
e85d2a5d 546subtype 'Num'
547 => as 'Value'
548 => where { Scalar::Util::looks_like_number($_) }
28ffb449 549 => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Num;
e85d2a5d 550
551subtype 'Int'
552 => as 'Num'
8ecb1fa0 553 => where { "$_" =~ /^-?[0-9]+$/ }
28ffb449 554 => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Int;
8ecb1fa0 555
28ffb449 556subtype 'ScalarRef' => as 'Ref' => where { ref($_) eq 'SCALAR' } => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::ScalarRef;
28ffb449 557subtype 'CodeRef' => as 'Ref' => where { ref($_) eq 'CODE' } => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::CodeRef;
558subtype 'RegexpRef' => as 'Ref' => where { ref($_) eq 'Regexp' } => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::RegexpRef;
559subtype 'GlobRef' => as 'Ref' => where { ref($_) eq 'GLOB' } => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::GlobRef;
a15dff8d 560
0a5bd159 561# NOTE:
e85d2a5d 562# scalar filehandles are GLOB refs,
0a5bd159 563# but a GLOB ref is not always a filehandle
e85d2a5d 564subtype 'FileHandle'
565 => as 'GlobRef'
128c601e 566 => where { Scalar::Util::openhandle($_) || ( blessed($_) && $_->isa("IO::Handle") ) }
28ffb449 567 => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::FileHandle;
0a5bd159 568
e85d2a5d 569# NOTE:
a15dff8d 570# blessed(qr/.../) returns true,.. how odd
e85d2a5d 571subtype 'Object'
572 => as 'Ref'
8ecb1fa0 573 => where { blessed($_) && blessed($_) ne 'Regexp' }
28ffb449 574 => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Object;
a15dff8d 575
e85d2a5d 576subtype 'Role'
577 => as 'Object'
8ecb1fa0 578 => where { $_->can('does') }
28ffb449 579 => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::Role;
e85d2a5d 580
0e0709ea 581my $_class_name_checker = sub {
0e0709ea 582};
583
e85d2a5d 584subtype 'ClassName'
585 => as 'Str'
e151db23 586 => where { Class::MOP::is_class_loaded($_) }
587 => optimize_as \&Moose::Util::TypeConstraints::OptimizedConstraints::ClassName;
02a0fb52 588
d9b40005 589## --------------------------------------------------------
7e4e1ad4 590# parameterizable types ...
591
592$REGISTRY->add_type_constraint(
593 Moose::Meta::TypeConstraint::Parameterizable->new(
594 name => 'ArrayRef',
595 package_defined_in => __PACKAGE__,
596 parent => find_type_constraint('Ref'),
597 constraint => sub { ref($_) eq 'ARRAY' },
598 optimized => \&Moose::Util::TypeConstraints::OptimizedConstraints::ArrayRef,
599 constraint_generator => sub {
600 my $type_parameter = shift;
dabed765 601 my $check = $type_parameter->_compiled_type_constraint;
7e4e1ad4 602 return sub {
603 foreach my $x (@$_) {
dabed765 604 ($check->($x)) || return
7e4e1ad4 605 } 1;
606 }
607 }
608 )
609);
610
611$REGISTRY->add_type_constraint(
612 Moose::Meta::TypeConstraint::Parameterizable->new(
613 name => 'HashRef',
614 package_defined_in => __PACKAGE__,
615 parent => find_type_constraint('Ref'),
616 constraint => sub { ref($_) eq 'HASH' },
617 optimized => \&Moose::Util::TypeConstraints::OptimizedConstraints::HashRef,
618 constraint_generator => sub {
4ab662d6 619 my $type_parameter = shift;
dabed765 620 my $check = $type_parameter->_compiled_type_constraint;
7e4e1ad4 621 return sub {
622 foreach my $x (values %$_) {
dabed765 623 ($check->($x)) || return
7e4e1ad4 624 } 1;
625 }
626 }
627 )
628);
629
630$REGISTRY->add_type_constraint(
631 Moose::Meta::TypeConstraint::Parameterizable->new(
632 name => 'Maybe',
633 package_defined_in => __PACKAGE__,
634 parent => find_type_constraint('Item'),
635 constraint => sub { 1 },
636 constraint_generator => sub {
4ab662d6 637 my $type_parameter = shift;
dabed765 638 my $check = $type_parameter->_compiled_type_constraint;
7e4e1ad4 639 return sub {
dabed765 640 return 1 if not(defined($_)) || $check->($_);
7e4e1ad4 641 return;
642 }
643 }
644 )
645);
646
4ab662d6 647my @PARAMETERIZABLE_TYPES = map {
648 $REGISTRY->get_type_constraint($_)
7e4e1ad4 649} qw[ArrayRef HashRef Maybe];
650
651sub get_all_parameterizable_types { @PARAMETERIZABLE_TYPES }
4ab662d6 652sub add_parameterizable_type {
7e4e1ad4 653 my $type = shift;
654 (blessed $type && $type->isa('Moose::Meta::TypeConstraint::Parameterizable'))
c245d69b 655 || Moose->throw_error("Type must be a Moose::Meta::TypeConstraint::Parameterizable not $type");
7e4e1ad4 656 push @PARAMETERIZABLE_TYPES => $type;
4ab662d6 657}
7e4e1ad4 658
659## --------------------------------------------------------
d9b40005 660# end of built-in types ...
661## --------------------------------------------------------
662
943596a6 663{
664 my @BUILTINS = list_all_type_constraints();
665 sub list_all_builtin_type_constraints { @BUILTINS }
666}
667
a15dff8d 6681;
669
670__END__
671
672=pod
673
674=head1 NAME
675
e522431d 676Moose::Util::TypeConstraints - Type constraint system for Moose
a15dff8d 677
678=head1 SYNOPSIS
679
680 use Moose::Util::TypeConstraints;
681
2c0cbef7 682 type 'Num' => where { Scalar::Util::looks_like_number($_) };
e85d2a5d 683
684 subtype 'Natural'
e606ae5f 685 => as 'Int'
a15dff8d 686 => where { $_ > 0 };
e85d2a5d 687
688 subtype 'NaturalLessThanTen'
2c0cbef7 689 => as 'Natural'
79592a54 690 => where { $_ < 10 }
691 => message { "This number ($_) is not less than ten!" };
e85d2a5d 692
693 coerce 'Num'
2c0cbef7 694 => from 'Str'
e85d2a5d 695 => via { 0+$_ };
696
2c0cbef7 697 enum 'RGBColors' => qw(red green blue);
a15dff8d 698
699=head1 DESCRIPTION
700
e85d2a5d 701This module provides Moose with the ability to create custom type
702contraints to be used in attribute definition.
e522431d 703
6ba6d68c 704=head2 Important Caveat
705
e85d2a5d 706This is B<NOT> a type system for Perl 5. These are type constraints,
707and they are not used by Moose unless you tell it to. No type
708inference is performed, expression are not typed, etc. etc. etc.
6ba6d68c 709
e85d2a5d 710This is simply a means of creating small constraint functions which
e606ae5f 711can be used to simplify your own type-checking code, with the added
004222dc 712side benefit of making your intentions clearer through self-documentation.
6ba6d68c 713
2c0cbef7 714=head2 Slightly Less Important Caveat
715
004222dc 716It is B<always> a good idea to quote your type and subtype names.
717
e85d2a5d 718This is to prevent perl from trying to execute the call as an indirect
2c0cbef7 719object call. This issue only seems to come up when you have a subtype
e85d2a5d 720the same name as a valid class, but when the issue does arise it tends
721to be quite annoying to debug.
2c0cbef7 722
723So for instance, this:
e85d2a5d 724
2c0cbef7 725 subtype DateTime => as Object => where { $_->isa('DateTime') };
726
727will I<Just Work>, while this:
728
729 use DateTime;
730 subtype DateTime => as Object => where { $_->isa('DateTime') };
731
e85d2a5d 732will fail silently and cause many headaches. The simple way to solve
733this, as well as future proof your subtypes from classes which have
2c0cbef7 734yet to have been created yet, is to simply do this:
735
736 use DateTime;
d44714be 737 subtype 'DateTime' => as 'Object' => where { $_->isa('DateTime') };
2c0cbef7 738
6ba6d68c 739=head2 Default Type Constraints
e522431d 740
e606ae5f 741This module also provides a simple hierarchy for Perl 5 types, here is
004222dc 742that hierarchy represented visually.
e522431d 743
744 Any
e85d2a5d 745 Item
5a4c5493 746 Bool
7e4e1ad4 747 Maybe[`a]
f65cb534 748 Undef
749 Defined
5a4c5493 750 Value
751 Num
752 Int
753 Str
9af1d28b 754 ClassName
5a4c5493 755 Ref
756 ScalarRef
7e4e1ad4 757 ArrayRef[`a]
758 HashRef[`a]
5a4c5493 759 CodeRef
760 RegexpRef
3f7376b0 761 GlobRef
0a5bd159 762 FileHandle
e85d2a5d 763 Object
5a4c5493 764 Role
e522431d 765
4ab662d6 766B<NOTE:> Any type followed by a type parameter C<[`a]> can be
7e4e1ad4 767parameterized, this means you can say:
768
757e07ef 769 ArrayRef[Int] # an array of integers
7e4e1ad4 770 HashRef[CodeRef] # a hash of str to CODE ref mappings
771 Maybe[Str] # value may be a string, may be undefined
772
e606ae5f 773B<NOTE:> Unless you parameterize a type, then it is invalid to
774include the square brackets. I.e. C<ArrayRef[]> will be
775literally interpreted as a type name.
776
4ab662d6 777B<NOTE:> The C<Undef> type constraint for the most part works
778correctly now, but edge cases may still exist, please use it
7e4e1ad4 779sparringly.
703e92fb 780
7e4e1ad4 781B<NOTE:> The C<ClassName> type constraint does a complex package
4ab662d6 782existence check. This means that your class B<must> be loaded for
783this type constraint to pass. I know this is not ideal for all,
7e4e1ad4 784but it is a saner restriction than most others.
9af1d28b 785
e606ae5f 786=head2 Type Constraint Naming
004222dc 787
e606ae5f 788Since the types created by this module are global, it is suggested
789that you namespace your types just as you would namespace your
004222dc 790modules. So instead of creating a I<Color> type for your B<My::Graphics>
791module, you would call the type I<My::Graphics::Color> instead.
792
703e92fb 793=head2 Use with Other Constraint Modules
794
e85d2a5d 795This module should play fairly nicely with other constraint
796modules with only some slight tweaking. The C<where> clause
703e92fb 797in types is expected to be a C<CODE> reference which checks
004222dc 798it's first argument and returns a boolean. Since most constraint
e85d2a5d 799modules work in a similar way, it should be simple to adapt
703e92fb 800them to work with Moose.
801
e85d2a5d 802For instance, this is how you could use it with
803L<Declare::Constraints::Simple> to declare a completely new type.
703e92fb 804
e85d2a5d 805 type 'HashOfArrayOfObjects'
703e92fb 806 => IsHashRef(
807 -keys => HasLength,
808 -values => IsArrayRef( IsObject ));
809
e606ae5f 810For more examples see the F<t/200_examples/204_example_w_DCS.t>
004222dc 811test file.
703e92fb 812
e85d2a5d 813Here is an example of using L<Test::Deep> and it's non-test
814related C<eq_deeply> function.
703e92fb 815
e85d2a5d 816 type 'ArrayOfHashOfBarsAndRandomNumbers'
703e92fb 817 => where {
e85d2a5d 818 eq_deeply($_,
703e92fb 819 array_each(subhashof({
820 bar => isa('Bar'),
821 random_number => ignore()
e85d2a5d 822 })))
703e92fb 823 };
824
e606ae5f 825For a complete example see the
004222dc 826F<t/200_examples/205_example_w_TestDeep.t> test file.
e85d2a5d 827
a15dff8d 828=head1 FUNCTIONS
829
830=head2 Type Constraint Constructors
831
e85d2a5d 832The following functions are used to create type constraints.
833They will then register the type constraints in a global store
834where Moose can get to them if it needs to.
a15dff8d 835
25f2c3fc 836See the L<SYNOPSIS> for an example of how to use these.
a15dff8d 837
6ba6d68c 838=over 4
a15dff8d 839
6ba6d68c 840=item B<type ($name, $where_clause)>
a15dff8d 841
e85d2a5d 842This creates a base type, which has no parent.
a15dff8d 843
79592a54 844=item B<subtype ($name, $parent, $where_clause, ?$message)>
182134e8 845
e85d2a5d 846This creates a named subtype.
d6e2d9a1 847
79592a54 848=item B<subtype ($parent, $where_clause, ?$message)>
182134e8 849
e85d2a5d 850This creates an unnamed subtype and will return the type
851constraint meta-object, which will be an instance of
852L<Moose::Meta::TypeConstraint>.
a15dff8d 853
620db045 854=item B<class_type ($class, ?$options)>
3fef8ce8 855
856Creates a type constraint with the name C<$class> and the metaclass
857L<Moose::Meta::TypeConstraint::Class>.
858
620db045 859=item B<role_type ($role, ?$options)>
860
861Creates a type constraint with the name C<$role> and the metaclass
862L<Moose::Meta::TypeConstraint::Role>.
863
1b2c9bda 864=item B<maybe_type ($type)>
865
866Creates a type constraint for either C<undef> or something of the
867given type.
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
ae55929d 1004Attempts to parse the type name using C<find_or_parse_type_constraint> and if
620db045 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