Implement compile_type_constraint in XS
[gitmo/Mouse.git] / lib / Mouse / PurePerl.pm
1 package Mouse::PurePerl;
2
3 package
4     Mouse::Util;
5
6 use strict;
7 use warnings;
8
9 use warnings FATAL => 'redefine'; # to avoid to load Mouse::PurePerl
10
11 use B ();
12
13 sub is_class_loaded {
14     my $class = shift;
15
16     return 0 if ref($class) || !defined($class) || !length($class);
17
18     # walk the symbol table tree to avoid autovififying
19     # \*{${main::}{"Foo::"}} == \*main::Foo::
20
21     my $pack = \%::;
22     foreach my $part (split('::', $class)) {
23         my $entry = \$pack->{$part . '::'};
24         return 0 if ref($entry) ne 'GLOB';
25         $pack = *{$entry}{HASH} or return 0;
26     }
27
28     # check for $VERSION or @ISA
29     return 1 if exists $pack->{VERSION}
30              && defined *{$pack->{VERSION}}{SCALAR} && defined ${ $pack->{VERSION} };
31     return 1 if exists $pack->{ISA}
32              && defined *{$pack->{ISA}}{ARRAY} && @{ $pack->{ISA} } != 0;
33
34     # check for any method
35     foreach my $name( keys %{$pack} ) {
36         my $entry = \$pack->{$name};
37         return 1 if ref($entry) ne 'GLOB' || defined *{$entry}{CODE};
38     }
39
40     # fail
41     return 0;
42 }
43
44
45 # taken from Sub::Identify
46 sub get_code_info {
47     my ($coderef) = @_;
48     ref($coderef) or return;
49
50     my $cv = B::svref_2object($coderef);
51     $cv->isa('B::CV') or return;
52
53     my $gv = $cv->GV;
54     $gv->isa('B::GV') or return;
55
56     return ($gv->STASH->NAME, $gv->NAME);
57 }
58
59 sub get_code_package{
60     my($coderef) = @_;
61
62     my $cv = B::svref_2object($coderef);
63     $cv->isa('B::CV') or return '';
64
65     my $gv = $cv->GV;
66     $gv->isa('B::GV') or return '';
67
68     return $gv->STASH->NAME;
69 }
70
71 sub get_code_ref{
72     my($package, $name) = @_;
73     no strict 'refs';
74     no warnings 'once';
75     use warnings FATAL => 'uninitialized';
76     return *{$package . '::' . $name}{CODE};
77 }
78
79 sub generate_isa_predicate_for {
80     my($for_class, $name) = @_;
81
82     my $predicate = sub{ Scalar::Util::blessed($_[0]) && $_[0]->isa($for_class) };
83
84     if(defined $name){
85         no strict 'refs';
86         *{ caller() . '::' . $name } = $predicate;
87         return;
88     }
89
90     return $predicate;
91 }
92
93
94 package
95     Mouse::Util::TypeConstraints;
96
97 use Scalar::Util qw(blessed looks_like_number openhandle);
98
99 sub Any        { 1 }
100 sub Item       { 1 }
101
102 sub Bool       { $_[0] ? $_[0] eq '1' : 1 }
103 sub Undef      { !defined($_[0]) }
104 sub Defined    {  defined($_[0])  }
105 sub Value      {  defined($_[0]) && !ref($_[0]) }
106 sub Num        { !ref($_[0]) && looks_like_number($_[0]) }
107 sub Int        {  defined($_[0]) && !ref($_[0]) && $_[0] =~ /^-?[0-9]+$/ }
108 sub Str        {  defined($_[0]) && !ref($_[0]) }
109
110 sub Ref        { ref($_[0]) }
111 sub ScalarRef  { ref($_[0]) eq 'SCALAR' }
112 sub ArrayRef   { ref($_[0]) eq 'ARRAY'  }
113 sub HashRef    { ref($_[0]) eq 'HASH'   }
114 sub CodeRef    { ref($_[0]) eq 'CODE'   }
115 sub RegexpRef  { ref($_[0]) eq 'Regexp' }
116 sub GlobRef    { ref($_[0]) eq 'GLOB'   }
117
118 sub FileHandle {
119     openhandle($_[0])  || (blessed($_[0]) && $_[0]->isa("IO::Handle"))
120 }
121
122 sub Object     { blessed($_[0]) && blessed($_[0]) ne 'Regexp' }
123
124 sub ClassName  { Mouse::Util::is_class_loaded($_[0]) }
125 sub RoleName   { (Mouse::Util::class_of($_[0]) || return 0)->isa('Mouse::Meta::Role') }
126
127 sub _parameterize_ArrayRef_for {
128     my($type_parameter) = @_;
129     my $check = $type_parameter->_compiled_type_constraint;
130
131     return sub {
132         foreach my $value (@{$_}) {
133             return undef unless $check->($value);
134         }
135         return 1;
136     }
137 }
138
139 sub _parameterize_HashRef_for {
140     my($type_parameter) = @_;
141     my $check = $type_parameter->_compiled_type_constraint;
142
143     return sub {
144         foreach my $value(values %{$_}){
145             return undef unless $check->($value);
146         }
147         return 1;
148     };
149 }
150
151 # 'Maybe' type accepts 'Any', so it requires parameters
152 sub _parameterize_Maybe_for {
153     my($type_parameter) = @_;
154     my $check = $type_parameter->_compiled_type_constraint;
155
156     return sub{
157         return !defined($_) || $check->($_);
158     };
159 };
160
161
162
163 package
164     Mouse::Meta::Module;
165
166 sub name          { $_[0]->{package} }
167
168 sub _method_map   { $_[0]->{methods} }
169 sub _attribute_map{ $_[0]->{attribute_map} }
170
171 sub namespace{
172     my $name = $_[0]->{package};
173     no strict 'refs';
174     return \%{ $name . '::' };
175 }
176
177 sub add_method {
178     my($self, $name, $code) = @_;
179
180     if(!defined $name){
181         $self->throw_error('You must pass a defined name');
182     }
183     if(!defined $code){
184         $self->throw_error('You must pass a defined code');
185     }
186
187     if(ref($code) ne 'CODE'){
188         $code = \&{$code}; # coerce
189     }
190
191     $self->{methods}->{$name} = $code; # Moose stores meta object here.
192
193     my $pkg = $self->name;
194     no strict 'refs';
195     no warnings 'redefine', 'once';
196     *{ $pkg . '::' . $name } = $code;
197     return;
198 }
199
200
201 package
202     Mouse::Meta::Class;
203
204 sub is_anon_class{
205     return exists $_[0]->{anon_serial_id};
206 }
207
208 sub roles { $_[0]->{roles} }
209
210 sub linearized_isa { @{ get_linear_isa($_[0]->{package}) } }
211
212 package
213     Mouse::Meta::Role;
214
215 sub is_anon_role{
216     return exists $_[0]->{anon_serial_id};
217 }
218
219 sub get_roles { $_[0]->{roles} }
220
221 package
222     Mouse::Meta::Attribute;
223
224 use Mouse::Meta::Method::Accessor;
225
226 # readers
227
228 sub name                 { $_[0]->{name}                   }
229 sub associated_class     { $_[0]->{associated_class}       }
230
231 sub accessor             { $_[0]->{accessor}               }
232 sub reader               { $_[0]->{reader}                 }
233 sub writer               { $_[0]->{writer}                 }
234 sub predicate            { $_[0]->{predicate}              }
235 sub clearer              { $_[0]->{clearer}                }
236 sub handles              { $_[0]->{handles}                }
237
238 sub _is_metadata         { $_[0]->{is}                     }
239 sub is_required          { $_[0]->{required}               }
240 sub default              { $_[0]->{default}                }
241 sub is_lazy              { $_[0]->{lazy}                   }
242 sub is_lazy_build        { $_[0]->{lazy_build}             }
243 sub is_weak_ref          { $_[0]->{weak_ref}               }
244 sub init_arg             { $_[0]->{init_arg}               }
245 sub type_constraint      { $_[0]->{type_constraint}        }
246
247 sub trigger              { $_[0]->{trigger}                }
248 sub builder              { $_[0]->{builder}                }
249 sub should_auto_deref    { $_[0]->{auto_deref}             }
250 sub should_coerce        { $_[0]->{coerce}                 }
251
252 sub documentation        { $_[0]->{documentation}          }
253
254 # predicates
255
256 sub has_accessor         { exists $_[0]->{accessor}        }
257 sub has_reader           { exists $_[0]->{reader}          }
258 sub has_writer           { exists $_[0]->{writer}          }
259 sub has_predicate        { exists $_[0]->{predicate}       }
260 sub has_clearer          { exists $_[0]->{clearer}         }
261 sub has_handles          { exists $_[0]->{handles}         }
262
263 sub has_default          { exists $_[0]->{default}         }
264 sub has_type_constraint  { exists $_[0]->{type_constraint} }
265 sub has_trigger          { exists $_[0]->{trigger}         }
266 sub has_builder          { exists $_[0]->{builder}         }
267
268 sub has_documentation    { exists $_[0]->{documentation}   }
269
270 sub accessor_metaclass(){ 'Mouse::Meta::Method::Accessor' }
271
272 package
273     Mouse::Meta::TypeConstraint;
274
275 sub name    { $_[0]->{name}    }
276 sub parent  { $_[0]->{parent}  }
277 sub message { $_[0]->{message} }
278
279 sub _compiled_type_constraint{ $_[0]->{compiled_type_constraint} }
280
281 sub _compiled_type_coercion  { $_[0]->{_compiled_type_coercion}  }
282
283 sub has_coercion{ exists $_[0]->{_compiled_type_coercion} }
284
285
286 sub compile_type_constraint{
287     my($self) = @_;
288
289     # add parents first
290     my @checks;
291     for(my $parent = $self->{parent}; defined $parent; $parent = $parent->{parent}){
292          if($parent->{hand_optimized_type_constraint}){
293             unshift @checks, $parent->{hand_optimized_type_constraint};
294             last; # a hand optimized constraint must include all the parents
295         }
296         elsif($parent->{constraint}){
297             unshift @checks, $parent->{constraint};
298         }
299     }
300
301     # then add child
302     if($self->{constraint}){
303         push @checks, $self->{constraint};
304     }
305
306     if($self->{type_constraints}){ # Union
307         my @types = map{ $_->{compiled_type_constraint} } @{ $self->{type_constraints} };
308         push @checks, sub{
309             foreach my $c(@types){
310                 return 1 if $c->($_[0]);
311             }
312             return 0;
313         };
314     }
315
316     if(@checks == 0){
317         $self->{compiled_type_constraint} = \&Mouse::Util::TypeConstraints::Any;
318     }
319     else{
320         $self->{compiled_type_constraint} =  sub{
321             my(@args) = @_;
322             local $_ = $args[0];
323             foreach my $c(@checks){
324                 return undef if !$c->(@args);
325             }
326             return 1;
327         };
328     }
329     return;
330 }
331
332
333
334 1;
335 __END__
336
337 =head1 NAME
338
339 Mouse::PurePerl - A Mouse guts in pure Perl
340
341 =head1 VERSION
342
343 This document describes Mouse version 0.40_03
344
345 =head1 SEE ALSO
346
347 L<Mouse::XS>
348
349 =cut