Tweaks for coercions
[gitmo/Mouse.git] / lib / Mouse / Meta / TypeConstraint.pm
1 package Mouse::Meta::TypeConstraint;
2 use Mouse::Util qw(:meta); # enables strict and warnings
3
4 sub new {
5     my $class = shift;
6     my %args  = @_ == 1 ? %{$_[0]} : @_;
7
8     $args{name} = '__ANON__' if !defined $args{name};
9
10     my $type_parameter;
11     if(defined $args{parent}) { # subtyping
12         %args = (%{$args{parent}}, %args);
13
14         # a child type must not inherit 'compiled_type_constraint'
15         # and 'hand_optimized_type_constraint' from the parent
16         delete $args{compiled_type_constraint};       # don't inherit it
17         delete $args{hand_optimized_type_constraint}; # don't inherit it
18
19         $type_parameter = $args{type_parameter};
20         if(defined(my $parent_tp = $args{parent}{type_parameter})) {
21             if($parent_tp != $type_parameter) {
22                 $type_parameter->is_a_type_of($parent_tp)
23                     or $class->throw_error(
24                         "$type_parameter is not a subtype of $parent_tp",
25                     );
26             }
27             else {
28                 $type_parameter = undef;
29             }
30         }
31     }
32
33     my $check;
34
35     if($check = delete $args{optimized}) { # likely to be builtins
36         $args{hand_optimized_type_constraint} = $check;
37         $args{compiled_type_constraint}       = $check;
38     }
39     elsif(defined $type_parameter) { # parameterizing
40         my $generator = $args{constraint_generator}
41             || $class->throw_error(
42                   "The $args{name} constraint cannot be used,"
43                 . " because $type_parameter doesn't subtype"
44                 . " from a parameterizable type");
45
46         my $parameterized_check = $generator->($type_parameter);
47         if(defined(my $my_check = $args{constraint})) {
48             $check = sub {
49                 return $parameterized_check->($_) && $my_check->($_);
50             };
51         }
52         else {
53             $check = $parameterized_check;
54         }
55         $args{constraint} = $check;
56     }
57     else { # common cases
58         $check = $args{constraint};
59     }
60
61     if(defined($check) && ref($check) ne 'CODE'){
62         $class->throw_error(
63             "Constraint for $args{name} is not a CODE reference");
64     }
65
66     my $self = bless \%args, $class;
67     $self->compile_type_constraint()
68         if !$args{hand_optimized_type_constraint};
69
70     if($args{type_constraints}) {
71         $self->_compile_union_type_coercion();
72     }
73     return $self;
74 }
75
76 sub create_child_type {
77     my $self = shift;
78     return ref($self)->new(@_, parent => $self);
79 }
80
81 sub name;
82 sub parent;
83 sub message;
84 sub has_coercion;
85
86 sub check;
87
88 sub type_parameter;
89 sub __is_parameterized;
90
91 sub _compiled_type_constraint;
92 sub _compiled_type_coercion;
93
94 sub compile_type_constraint;
95
96
97 sub _add_type_coercions { # ($self, @pairs)
98     my $self = shift;
99
100     if(exists $self->{type_constraints}){ # union type
101         $self->throw_error(
102             "Cannot add additional type coercions to Union types '$self'");
103     }
104
105     my $coercion_map = ($self->{coercion_map} ||= []);
106     my %has          = map{ $_->[0]->name => undef } @{$coercion_map};
107
108     for(my $i = 0; $i < @_; $i++){
109         my $from   = $_[  $i];
110         my $action = $_[++$i];
111
112         if(exists $has{$from}){
113             $self->throw_error("A coercion action already exists for '$from'");
114         }
115
116         my $type = Mouse::Util::TypeConstraints::find_or_parse_type_constraint($from)
117             or $self->throw_error(
118                 "Could not find the type constraint ($from) to coerce from");
119
120         push @{$coercion_map}, [ $type => $action ];
121     }
122
123     $self->_compile_type_coercion();
124     return;
125 }
126
127 sub _compile_type_coercion {
128     my($self) = @_;
129
130     my @coercions;
131
132     foreach my $pair(@{$self->{coercion_map}}) {
133         push @coercions, [ $pair->[0]->_compiled_type_constraint, $pair->[1] ];
134     }
135
136     $self->{_compiled_type_coercion} = sub {
137        my($thing) = @_;
138        foreach my $pair (@coercions) {
139             #my ($constraint, $converter) = @$pair;
140             if ($pair->[0]->($thing)) {
141               local $_ = $thing;
142               return $pair->[1]->($thing);
143             }
144        }
145        return $thing;
146     };
147     return;
148 }
149
150 sub _compile_union_type_coercion {
151     my($self) = @_;
152
153     my @coercions;
154     foreach my $type(@{$self->{type_constraints}}){
155         if($type->has_coercion){
156             push @coercions, $type;
157         }
158     }
159     if(@coercions){
160         $self->{_compiled_type_coercion} = sub {
161             my($thing) = @_;
162             foreach my $type(@coercions){
163                 my $value = $type->coerce($thing);
164                 return $value if $self->check($value);
165             }
166             return $thing;
167         };
168     }
169     return;
170 }
171
172 sub coerce {
173     my $self = shift;
174     return $_[0] if $self->check(@_);
175
176     my $coercion = $self->{_compiled_type_coercion}
177         or $self->throw_error("Cannot coerce without a type coercion");
178     return  $coercion->(@_);
179 }
180
181 sub get_message {
182     my ($self, $value) = @_;
183     if ( my $msg = $self->message ) {
184         local $_ = $value;
185         return $msg->($value);
186     }
187     else {
188         if(not defined $value) {
189             $value = 'undef';
190         }
191         elsif( ref($value) && defined(&overload::StrVal) ) {
192             $value = overload::StrVal($value);
193         }
194         return "Validation failed for '$self' with value $value";
195     }
196 }
197
198 sub is_a_type_of {
199     my($self, $other) = @_;
200
201     # ->is_a_type_of('__ANON__') is always false
202     return 0 if !ref($other) && $other eq '__ANON__';
203
204     (my $other_name = $other) =~ s/\s+//g;
205
206     return 1 if $self->name eq $other_name;
207
208     if(exists $self->{type_constraints}){ # union
209         foreach my $type(@{$self->{type_constraints}}) {
210             return 1 if $type->name eq $other_name;
211         }
212     }
213
214     for(my $p = $self->parent; defined $p; $p = $p->parent) {
215         return 1 if $p->name eq $other_name;
216     }
217
218     return 0;
219 }
220
221 # See also Moose::Meta::TypeConstraint::Parameterizable
222 sub parameterize {
223     my($self, $param, $name) = @_;
224
225     if(!ref $param){
226         require Mouse::Util::TypeConstraints;
227         $param = Mouse::Util::TypeConstraints::find_or_create_isa_type_constraint($param);
228     }
229
230     $name ||= sprintf '%s[%s]', $self->name, $param->name;
231     return Mouse::Meta::TypeConstraint->new(
232         name           => $name,
233         parent         => $self,
234         type_parameter => $param,
235     );
236 }
237
238 sub assert_valid {
239     my ($self, $value) = @_;
240
241     if(!$self->check($value)){
242         $self->throw_error($self->get_message($value));
243     }
244     return 1;
245 }
246
247 # overloading stuff
248
249 sub _as_string { $_[0]->name } # overload ""
250 sub _identity;                 # overload 0+
251
252 sub _unite { # overload infix:<|>
253     my($lhs, $rhs) = @_;
254     require Mouse::Util::TypeConstraints;
255     return Mouse::Util::TypeConstraints::find_or_parse_type_constraint(
256        " $lhs | $rhs",
257     );
258 }
259
260 1;
261 __END__
262
263 =head1 NAME
264
265 Mouse::Meta::TypeConstraint - The Mouse Type Constraint metaclass
266
267 =head1 VERSION
268
269 This document describes Mouse version 0.86
270
271 =head1 DESCRIPTION
272
273 This class represents a type constraint, including built-in
274 type constraints, union type constraints, parameterizable/
275 parameterized type constraints, as well as custom type
276 constraints
277
278 =head1 METHODS
279
280 =over
281
282 =item C<< Mouse::Meta::TypeConstraint->new(%options) >>
283
284 =item C<< $constraint->name >>
285
286 =item C<< $constraint->parent >>
287
288 =item C<< $constraint->constraint >>
289
290 =item C<< $constraint->has_coercion >>
291
292 =item C<< $constraint->message >>
293
294 =item C<< $constraint->is_a_type_of($name or $object) >>
295
296 =item C<< $constraint->coerce($value) >>
297
298 =item C<< $constraint->check($value) >>
299
300 =item C<< $constraint->assert_valid($value) >>
301
302 =item C<< $constraint->get_message($value) >>
303
304 =item C<< $constraint->create_child_type(%options) >>
305
306 =back
307
308 =head1 SEE ALSO
309
310 L<Moose::Meta::TypeConstraint>
311
312 =cut
313