2 package Mouse::TypeRegistry;
6 use Mouse::Util qw/blessed looks_like_number openhandle/;
14 my $caller = caller(0);
16 $SUBTYPE->{$caller} ||= +{};
17 $COERCE->{$caller} ||= +{};
19 if (defined $args{'-export'} && ref($args{'-export'}) eq 'ARRAY') {
21 *{"$caller\::import"} = sub { _import(@_) };
25 *{"$caller\::subtype"} = \&_subtype;
26 *{"$caller\::coerce"} = \&_coerce;
27 *{"$caller\::class_type"} = \&_class_type;
28 *{"$caller\::role_type"} = \&_role_type;
32 my($class, @types) = @_;
33 return unless exists $SUBTYPE->{$class} && exists $COERCE->{$class};
36 copy_types($class, $pkg, @types);
41 my($name, $stuff) = @_;
42 if (ref $stuff eq 'HASH') {
43 my $as = $stuff->{as};
44 $stuff = optimized_constraints()->{$as};
46 $SUBTYPE->{$pkg}->{$name} = $stuff;
51 my($name, $conf) = @_;
52 $COERCE->{$pkg}->{$name} = $conf;
57 $SUBTYPE->{$pkg} ||= +{};
58 my($name, $conf) = @_;
59 my $class = $conf->{class};
60 $SUBTYPE->{$pkg}->{$name} = sub {
61 defined $_ && ref($_) eq $class;
67 $SUBTYPE->{$pkg} ||= +{};
68 my($name, $conf) = @_;
69 my $role = $conf->{role};
70 $SUBTYPE->{$pkg}->{$name} = sub {
71 return unless defined $_ && ref($_) && $_->isa('Mouse::Object');
72 $_->meta->does_role($role);
76 sub typecast_constraints {
77 my($class, $pkg, $type, $value) = @_;
78 return $value unless defined $COERCE->{$pkg} && defined $COERCE->{$pkg}->{$type};
80 my $optimized_constraints = optimized_constraints();
81 for my $coerce_type (keys %{ $COERCE->{$pkg}->{$type} }) {
83 if ($optimized_constraints->{$coerce_type}->()) {
85 return $COERCE->{$pkg}->{$type}->{$coerce_type}->();
93 no warnings 'uninitialized';
94 my $optimized_constraints = {
98 !defined($_) || $_ eq "" || "$_" eq '1' || "$_" eq '0'
100 Undef => sub { !defined($_) },
101 Defined => sub { defined($_) },
102 Value => sub { defined($_) && !ref($_) },
103 Num => sub { !ref($_) && looks_like_number($_) },
104 Int => sub { defined($_) && !ref($_) && /^-?[0-9]+$/ },
105 Str => sub { defined($_) && !ref($_) },
106 ClassName => sub { Mouse::is_class_loaded($_) },
107 Ref => sub { ref($_) },
109 ScalarRef => sub { ref($_) eq 'SCALAR' },
110 ArrayRef => sub { ref($_) eq 'ARRAY' },
111 HashRef => sub { ref($_) eq 'HASH' },
112 CodeRef => sub { ref($_) eq 'CODE' },
113 RegexpRef => sub { ref($_) eq 'Regexp' },
114 GlobRef => sub { ref($_) eq 'GLOB' },
121 && $_->isa("IO::Handle")
124 Object => sub { blessed($_) && blessed($_) ne 'Regexp' },
126 sub optimized_constraints {
127 my($class, $pkg) = @_;
128 my $subtypes = $SUBTYPE->{$pkg} || {};
129 return { %{ $subtypes }, %{ $optimized_constraints } };
139 Mouse::TypeRegistry - simple type constraints
143 =head2 optimized_constraints -> HashRef[CODE]
145 Returns the simple type constraints that Mouse understands.