97534e4aa709af6dd285f71a610e00c1bed8fb0d
[gitmo/Mouse.git] / lib / Mouse / PurePerl.pm
1 package Mouse::PurePerl;
2
3 require Mouse::Util;
4
5 package
6     Mouse::Util;
7
8 use strict;
9 use warnings;
10
11 use warnings FATAL => 'redefine'; # to avoid to load Mouse::PurePerl
12
13 use B ();
14
15 sub is_class_loaded {
16     my $class = shift;
17
18     return 0 if ref($class) || !defined($class) || !length($class);
19
20     # walk the symbol table tree to avoid autovififying
21     # \*{${main::}{"Foo::"}{"Bar::"}} == \*main::Foo::Bar::
22
23     my $pack = \%::;
24     foreach my $part (split('::', $class)) {
25         $part .= '::';
26         return 0 if !exists $pack->{$part};
27
28         my $entry = \$pack->{$part};
29         return 0 if ref($entry) ne 'GLOB';
30         $pack = *{$entry}{HASH};
31     }
32
33     return 0 if !%{$pack};
34
35     # check for $VERSION or @ISA
36     return 1 if exists $pack->{VERSION}
37              && defined *{$pack->{VERSION}}{SCALAR} && defined ${ $pack->{VERSION} };
38     return 1 if exists $pack->{ISA}
39              && defined *{$pack->{ISA}}{ARRAY} && @{ $pack->{ISA} } != 0;
40
41     # check for any method
42     foreach my $name( keys %{$pack} ) {
43         my $entry = \$pack->{$name};
44         return 1 if ref($entry) ne 'GLOB' || defined *{$entry}{CODE};
45     }
46
47     # fail
48     return 0;
49 }
50
51
52 # taken from Sub::Identify
53 sub get_code_info {
54     my ($coderef) = @_;
55     ref($coderef) or return;
56
57     my $cv = B::svref_2object($coderef);
58     $cv->isa('B::CV') or return;
59
60     my $gv = $cv->GV;
61     $gv->isa('B::GV') or return;
62
63     return ($gv->STASH->NAME, $gv->NAME);
64 }
65
66 sub get_code_package{
67     my($coderef) = @_;
68
69     my $cv = B::svref_2object($coderef);
70     $cv->isa('B::CV') or return '';
71
72     my $gv = $cv->GV;
73     $gv->isa('B::GV') or return '';
74
75     return $gv->STASH->NAME;
76 }
77
78 sub get_code_ref{
79     my($package, $name) = @_;
80     no strict 'refs';
81     no warnings 'once';
82     use warnings FATAL => 'uninitialized';
83     return *{$package . '::' . $name}{CODE};
84 }
85
86 sub generate_isa_predicate_for {
87     my($for_class, $name) = @_;
88
89     my $predicate = sub{ Scalar::Util::blessed($_[0]) && $_[0]->isa($for_class) };
90
91     if(defined $name){
92         no strict 'refs';
93         *{ caller() . '::' . $name } = $predicate;
94         return;
95     }
96
97     return $predicate;
98 }
99
100 sub generate_can_predicate_for {
101     my($methods_ref, $name) = @_;
102
103     my @methods = @{$methods_ref};
104
105     my $predicate = sub{
106         my($instance) = @_;
107         if(Scalar::Util::blessed($instance)){
108             foreach my $method(@methods){
109                 if(!$instance->can($method)){
110                     return 0;
111                 }
112             }
113             return 1;
114         }
115         return 0;
116     };
117
118     if(defined $name){
119         no strict 'refs';
120         *{ caller() . '::' . $name } = $predicate;
121         return;
122     }
123
124     return $predicate;
125 }
126
127 package
128     Mouse::Util::TypeConstraints;
129
130 use Scalar::Util qw(blessed looks_like_number openhandle);
131
132 sub Any        { 1 }
133 sub Item       { 1 }
134
135 sub Bool       { $_[0] ? $_[0] eq '1' : 1 }
136 sub Undef      { !defined($_[0]) }
137 sub Defined    {  defined($_[0])  }
138 sub Value      {  defined($_[0]) && !ref($_[0]) }
139 sub Num        { !ref($_[0]) && looks_like_number($_[0]) }
140 sub Int        {  defined($_[0]) && !ref($_[0]) && $_[0] =~ /^-?[0-9]+$/ }
141 sub Str        {
142     my($value) = @_;
143     return defined($value) && ref(\$value) eq 'SCALAR';
144 }
145
146 sub Ref        { ref($_[0]) }
147 sub ScalarRef  {
148     my($value) = @_;
149     return ref($value) eq 'SCALAR'
150 }
151 sub ArrayRef   { ref($_[0]) eq 'ARRAY'  }
152 sub HashRef    { ref($_[0]) eq 'HASH'   }
153 sub CodeRef    { ref($_[0]) eq 'CODE'   }
154 sub RegexpRef  { ref($_[0]) eq 'Regexp' }
155 sub GlobRef    { ref($_[0]) eq 'GLOB'   }
156
157 sub FileHandle {
158     return openhandle($_[0])  || (blessed($_[0]) && $_[0]->isa("IO::Handle"))
159 }
160
161 sub Object     { blessed($_[0]) && blessed($_[0]) ne 'Regexp' }
162
163 sub ClassName  { Mouse::Util::is_class_loaded($_[0]) }
164 sub RoleName   { (Mouse::Util::class_of($_[0]) || return 0)->isa('Mouse::Meta::Role') }
165
166 sub _parameterize_ArrayRef_for {
167     my($type_parameter) = @_;
168     my $check = $type_parameter->_compiled_type_constraint;
169
170     return sub {
171         foreach my $value (@{$_}) {
172             return undef unless $check->($value);
173         }
174         return 1;
175     }
176 }
177
178 sub _parameterize_HashRef_for {
179     my($type_parameter) = @_;
180     my $check = $type_parameter->_compiled_type_constraint;
181
182     return sub {
183         foreach my $value(values %{$_}){
184             return undef unless $check->($value);
185         }
186         return 1;
187     };
188 }
189
190 # 'Maybe' type accepts 'Any', so it requires parameters
191 sub _parameterize_Maybe_for {
192     my($type_parameter) = @_;
193     my $check = $type_parameter->_compiled_type_constraint;
194
195     return sub{
196         return !defined($_) || $check->($_);
197     };
198 };
199
200
201
202 package
203     Mouse::Meta::Module;
204
205 sub name          { $_[0]->{package} }
206
207 sub _method_map   { $_[0]->{methods} }
208 sub _attribute_map{ $_[0]->{attributes} }
209
210 sub namespace{
211     my $name = $_[0]->{package};
212     no strict 'refs';
213     return \%{ $name . '::' };
214 }
215
216 sub add_method {
217     my($self, $name, $code) = @_;
218
219     if(!defined $name){
220         $self->throw_error('You must pass a defined name');
221     }
222     if(!defined $code){
223         $self->throw_error('You must pass a defined code');
224     }
225
226     if(ref($code) ne 'CODE'){
227         $code = \&{$code}; # coerce
228     }
229
230     $self->{methods}->{$name} = $code; # Moose stores meta object here.
231
232     my $pkg = $self->name;
233     no strict 'refs';
234     no warnings 'redefine', 'once';
235     *{ $pkg . '::' . $name } = $code;
236     return;
237 }
238
239 package
240     Mouse::Meta::Class;
241
242 sub method_metaclass    { $_[0]->{method_metaclass}    || 'Mouse::Meta::Method'    }
243 sub attribute_metaclass { $_[0]->{attribute_metaclass} || 'Mouse::Meta::Attribute' }
244
245 sub constructor_class { $_[0]->{constructor_class} || 'Mouse::Meta::Method::Constructor' }
246 sub destructor_class  { $_[0]->{destructor_class}  || 'Mouse::Meta::Method::Destructor'  }
247
248 sub is_anon_class{
249     return exists $_[0]->{anon_serial_id};
250 }
251
252 sub roles { $_[0]->{roles} }
253
254 sub linearized_isa { @{ get_linear_isa($_[0]->{package}) } }
255
256 sub get_all_attributes {
257     my($self) = @_;
258     my %attrs = map { %{ $self->initialize($_)->{attributes} } } reverse $self->linearized_isa;
259     return values %attrs;
260 }
261
262 sub new_object {
263     my $self = shift;
264     my %args = (@_ == 1 ? %{$_[0]} : @_);
265
266     my $object = bless {}, $self->name;
267
268     $self->_initialize_object($object, \%args);
269     return $object;
270 }
271
272 sub _initialize_object{
273     my($self, $object, $args, $ignore_triggers) = @_;
274
275     my @triggers_queue;
276
277     foreach my $attribute ($self->get_all_attributes) {
278         my $init_arg = $attribute->init_arg;
279         my $slot     = $attribute->name;
280
281         if (defined($init_arg) && exists($args->{$init_arg})) {
282             $object->{$slot} = $attribute->_coerce_and_verify($args->{$init_arg}, $object);
283
284             weaken($object->{$slot})
285                 if ref($object->{$slot}) && $attribute->is_weak_ref;
286
287             if ($attribute->has_trigger) {
288                 push @triggers_queue, [ $attribute->trigger, $object->{$slot} ];
289             }
290         }
291         else { # no init arg
292             if ($attribute->has_default || $attribute->has_builder) {
293                 if (!$attribute->is_lazy) {
294                     my $default = $attribute->default;
295                     my $builder = $attribute->builder;
296                     my $value =   $builder                ? $object->$builder()
297                                 : ref($default) eq 'CODE' ? $object->$default()
298                                 :                           $default;
299
300                     $object->{$slot} = $attribute->_coerce_and_verify($value, $object);
301
302                     weaken($object->{$slot})
303                         if ref($object->{$slot}) && $attribute->is_weak_ref;
304                 }
305             }
306             elsif($attribute->is_required) {
307                 $self->throw_error("Attribute (".$attribute->name.") is required");
308             }
309         }
310     }
311
312     if(!$ignore_triggers){
313         foreach my $trigger_and_value(@triggers_queue){
314             my($trigger, $value) = @{$trigger_and_value};
315             $trigger->($object, $value);
316         }
317     }
318
319     if($self->is_anon_class){
320         $object->{__METACLASS__} = $self;
321     }
322
323     return;
324 }
325
326 sub is_immutable {  $_[0]->{is_immutable} }
327
328 package
329     Mouse::Meta::Role;
330
331 sub method_metaclass{ $_[0]->{method_metaclass} || 'Mouse::Meta::Role::Method' }
332
333 sub is_anon_role{
334     return exists $_[0]->{anon_serial_id};
335 }
336
337 sub get_roles { $_[0]->{roles} }
338
339 package
340     Mouse::Meta::Attribute;
341
342 require Mouse::Meta::Method::Accessor;
343
344 sub accessor_metaclass{ $_[0]->{accessor_metaclass} || 'Mouse::Meta::Method::Accessor' }
345
346 # readers
347
348 sub name                 { $_[0]->{name}                   }
349 sub associated_class     { $_[0]->{associated_class}       }
350
351 sub accessor             { $_[0]->{accessor}               }
352 sub reader               { $_[0]->{reader}                 }
353 sub writer               { $_[0]->{writer}                 }
354 sub predicate            { $_[0]->{predicate}              }
355 sub clearer              { $_[0]->{clearer}                }
356 sub handles              { $_[0]->{handles}                }
357
358 sub _is_metadata         { $_[0]->{is}                     }
359 sub is_required          { $_[0]->{required}               }
360 sub default              { $_[0]->{default}                }
361 sub is_lazy              { $_[0]->{lazy}                   }
362 sub is_lazy_build        { $_[0]->{lazy_build}             }
363 sub is_weak_ref          { $_[0]->{weak_ref}               }
364 sub init_arg             { $_[0]->{init_arg}               }
365 sub type_constraint      { $_[0]->{type_constraint}        }
366
367 sub trigger              { $_[0]->{trigger}                }
368 sub builder              { $_[0]->{builder}                }
369 sub should_auto_deref    { $_[0]->{auto_deref}             }
370 sub should_coerce        { $_[0]->{coerce}                 }
371
372 sub documentation        { $_[0]->{documentation}          }
373
374 # predicates
375
376 sub has_accessor         { exists $_[0]->{accessor}        }
377 sub has_reader           { exists $_[0]->{reader}          }
378 sub has_writer           { exists $_[0]->{writer}          }
379 sub has_predicate        { exists $_[0]->{predicate}       }
380 sub has_clearer          { exists $_[0]->{clearer}         }
381 sub has_handles          { exists $_[0]->{handles}         }
382
383 sub has_default          { exists $_[0]->{default}         }
384 sub has_type_constraint  { exists $_[0]->{type_constraint} }
385 sub has_trigger          { exists $_[0]->{trigger}         }
386 sub has_builder          { exists $_[0]->{builder}         }
387
388 sub has_documentation    { exists $_[0]->{documentation}   }
389
390 package
391     Mouse::Meta::TypeConstraint;
392
393 sub name    { $_[0]->{name}    }
394 sub parent  { $_[0]->{parent}  }
395 sub message { $_[0]->{message} }
396
397 sub _compiled_type_constraint{ $_[0]->{compiled_type_constraint} }
398
399 sub _compiled_type_coercion  { $_[0]->{_compiled_type_coercion}  }
400
401 sub has_coercion{ exists $_[0]->{_compiled_type_coercion} }
402
403
404 sub compile_type_constraint{
405     my($self) = @_;
406
407     # add parents first
408     my @checks;
409     for(my $parent = $self->{parent}; defined $parent; $parent = $parent->{parent}){
410          if($parent->{hand_optimized_type_constraint}){
411             unshift @checks, $parent->{hand_optimized_type_constraint};
412             last; # a hand optimized constraint must include all the parents
413         }
414         elsif($parent->{constraint}){
415             unshift @checks, $parent->{constraint};
416         }
417     }
418
419     # then add child
420     if($self->{constraint}){
421         push @checks, $self->{constraint};
422     }
423
424     if($self->{type_constraints}){ # Union
425         my @types = map{ $_->{compiled_type_constraint} } @{ $self->{type_constraints} };
426         push @checks, sub{
427             foreach my $c(@types){
428                 return 1 if $c->($_[0]);
429             }
430             return 0;
431         };
432     }
433
434     if(@checks == 0){
435         $self->{compiled_type_constraint} = \&Mouse::Util::TypeConstraints::Any;
436     }
437     else{
438         $self->{compiled_type_constraint} =  sub{
439             my(@args) = @_;
440             local $_ = $args[0];
441             foreach my $c(@checks){
442                 return undef if !$c->(@args);
443             }
444             return 1;
445         };
446     }
447     return;
448 }
449
450 package
451     Mouse::Object;
452
453
454 sub BUILDARGS {
455     my $class = shift;
456
457     if (scalar @_ == 1) {
458         (ref($_[0]) eq 'HASH')
459             || $class->meta->throw_error("Single parameters to new() must be a HASH ref");
460
461         return {%{$_[0]}};
462     }
463     else {
464         return {@_};
465     }
466 }
467
468 sub new {
469     my $class = shift;
470
471     $class->meta->throw_error('Cannot call new() on an instance') if ref $class;
472
473     my $args = $class->BUILDARGS(@_);
474
475     my $meta = Mouse::Meta::Class->initialize($class);
476     my $self = $meta->new_object($args);
477
478     # BUILDALL
479     if( $self->can('BUILD') ) {
480         for my $class (reverse $meta->linearized_isa) {
481             my $build = Mouse::Util::get_code_ref($class, 'BUILD')
482                 || next;
483
484             $self->$build($args);
485         }
486     }
487
488     return $self;
489 }
490
491 sub DESTROY {
492     my $self = shift;
493
494     return unless $self->can('DEMOLISH'); # short circuit
495
496     local $?;
497
498     my $e = do{
499         local $@;
500         eval{
501
502             # DEMOLISHALL
503
504             # We cannot count on being able to retrieve a previously made
505             # metaclass, _or_ being able to make a new one during global
506             # destruction. However, we should still be able to use mro at
507             # that time (at least tests suggest so ;)
508
509             foreach my $class (@{ Mouse::Util::get_linear_isa(ref $self) }) {
510                 my $demolish = Mouse::Util::get_code_ref($class, 'DEMOLISH')
511                     || next;
512
513                 $self->$demolish();
514             }
515         };
516         $@;
517     };
518
519     no warnings 'misc';
520     die $e if $e; # rethrow
521 }
522
523 sub BUILDALL {
524     my $self = shift;
525
526     # short circuit
527     return unless $self->can('BUILD');
528
529     for my $class (reverse $self->meta->linearized_isa) {
530         my $build = Mouse::Util::get_code_ref($class, 'BUILD')
531             || next;
532
533         $self->$build(@_);
534     }
535     return;
536 }
537
538 sub DEMOLISHALL;
539 *DEMOLISHALL = \&DESTROY;
540
541 1;
542 __END__
543
544 =head1 NAME
545
546 Mouse::PurePerl - A Mouse guts in pure Perl
547
548 =head1 VERSION
549
550 This document describes Mouse version 0.46
551
552 =head1 SEE ALSO
553
554 L<Mouse::XS>
555
556 =cut