0003a9b3ee4c09a762c4070c091fd2555904835b
[gitmo/Mouse.git] / lib / Mouse / PurePerl.pm
1 package Mouse::PurePerl;
2
3 require Mouse::Util;
4
5 package Mouse::Util;
6
7 use strict;
8 use warnings;
9
10 use warnings FATAL => 'redefine'; # to avoid to load Mouse::PurePerl
11
12 use B ();
13
14
15 # taken from Class/MOP.pm
16 sub is_valid_class_name {
17     my $class = shift;
18
19     return 0 if ref($class);
20     return 0 unless defined($class);
21
22     return 1 if $class =~ /\A \w+ (?: :: \w+ )* \z/xms;
23
24     return 0;
25 }
26
27 sub is_class_loaded {
28     my $class = shift;
29
30     return 0 if ref($class) || !defined($class) || !length($class);
31
32     # walk the symbol table tree to avoid autovififying
33     # \*{${main::}{"Foo::"}{"Bar::"}} == \*main::Foo::Bar::
34
35     my $pack = \%::;
36     foreach my $part (split('::', $class)) {
37         $part .= '::';
38         return 0 if !exists $pack->{$part};
39
40         my $entry = \$pack->{$part};
41         return 0 if ref($entry) ne 'GLOB';
42         $pack = *{$entry}{HASH};
43     }
44
45     return 0 if !%{$pack};
46
47     # check for $VERSION or @ISA
48     return 1 if exists $pack->{VERSION}
49              && defined *{$pack->{VERSION}}{SCALAR} && defined ${ $pack->{VERSION} };
50     return 1 if exists $pack->{ISA}
51              && defined *{$pack->{ISA}}{ARRAY} && @{ $pack->{ISA} } != 0;
52
53     # check for any method
54     foreach my $name( keys %{$pack} ) {
55         my $entry = \$pack->{$name};
56         return 1 if ref($entry) ne 'GLOB' || defined *{$entry}{CODE};
57     }
58
59     # fail
60     return 0;
61 }
62
63
64 # taken from Sub::Identify
65 sub get_code_info {
66     my ($coderef) = @_;
67     ref($coderef) or return;
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, $gv->NAME);
76 }
77
78 sub get_code_package{
79     my($coderef) = @_;
80
81     my $cv = B::svref_2object($coderef);
82     $cv->isa('B::CV') or return '';
83
84     my $gv = $cv->GV;
85     $gv->isa('B::GV') or return '';
86
87     return $gv->STASH->NAME;
88 }
89
90 sub get_code_ref{
91     my($package, $name) = @_;
92     no strict 'refs';
93     no warnings 'once';
94     use warnings FATAL => 'uninitialized';
95     return *{$package . '::' . $name}{CODE};
96 }
97
98 sub generate_isa_predicate_for {
99     my($for_class, $name) = @_;
100
101     my $predicate = sub{ Scalar::Util::blessed($_[0]) && $_[0]->isa($for_class) };
102
103     if(defined $name){
104         Mouse::Util::install_subroutines(scalar caller, $name => $predicate);
105         return;
106     }
107
108     return $predicate;
109 }
110
111 sub generate_can_predicate_for {
112     my($methods_ref, $name) = @_;
113
114     my @methods = @{$methods_ref};
115
116     my $predicate = sub{
117         my($instance) = @_;
118         if(Scalar::Util::blessed($instance)){
119             foreach my $method(@methods){
120                 if(!$instance->can($method)){
121                     return 0;
122                 }
123             }
124             return 1;
125         }
126         return 0;
127     };
128
129     if(defined $name){
130         Mouse::Util::install_subroutines(scalar caller, $name => $predicate);
131         return;
132     }
133
134     return $predicate;
135 }
136
137 package Mouse::Util::TypeConstraints;
138
139 use Scalar::Util qw(blessed looks_like_number openhandle);
140
141 sub Any        { 1 }
142 sub Item       { 1 }
143
144 sub Bool       { $_[0] ? $_[0] eq '1' : 1 }
145 sub Undef      { !defined($_[0]) }
146 sub Defined    {  defined($_[0])  }
147 sub Value      {  defined($_[0]) && !ref($_[0]) }
148 sub Num        { !ref($_[0]) && looks_like_number($_[0]) }
149 sub Int        {  defined($_[0]) && !ref($_[0]) && $_[0] =~ /^-?[0-9]+$/ }
150 sub Str        {
151     my($value) = @_;
152     return defined($value) && ref(\$value) eq 'SCALAR';
153 }
154
155 sub Ref        { ref($_[0]) }
156 sub ScalarRef  {
157     my($value) = @_;
158     return ref($value) eq 'SCALAR'
159 }
160 sub ArrayRef   { ref($_[0]) eq 'ARRAY'  }
161 sub HashRef    { ref($_[0]) eq 'HASH'   }
162 sub CodeRef    { ref($_[0]) eq 'CODE'   }
163 sub RegexpRef  { ref($_[0]) eq 'Regexp' }
164 sub GlobRef    { ref($_[0]) eq 'GLOB'   }
165
166 sub FileHandle {
167     return openhandle($_[0])  || (blessed($_[0]) && $_[0]->isa("IO::Handle"))
168 }
169
170 sub Object     { blessed($_[0]) && blessed($_[0]) ne 'Regexp' }
171
172 sub ClassName  { Mouse::Util::is_class_loaded($_[0]) }
173 sub RoleName   { (Mouse::Util::class_of($_[0]) || return 0)->isa('Mouse::Meta::Role') }
174
175 sub _parameterize_ArrayRef_for {
176     my($type_parameter) = @_;
177     my $check = $type_parameter->_compiled_type_constraint;
178
179     return sub {
180         foreach my $value (@{$_}) {
181             return undef unless $check->($value);
182         }
183         return 1;
184     }
185 }
186
187 sub _parameterize_HashRef_for {
188     my($type_parameter) = @_;
189     my $check = $type_parameter->_compiled_type_constraint;
190
191     return sub {
192         foreach my $value(values %{$_}){
193             return undef unless $check->($value);
194         }
195         return 1;
196     };
197 }
198
199 # 'Maybe' type accepts 'Any', so it requires parameters
200 sub _parameterize_Maybe_for {
201     my($type_parameter) = @_;
202     my $check = $type_parameter->_compiled_type_constraint;
203
204     return sub{
205         return !defined($_) || $check->($_);
206     };
207 }
208
209 package Mouse::Meta::Module;
210
211 sub name          { $_[0]->{package} }
212
213 sub _method_map   { $_[0]->{methods} }
214 sub _attribute_map{ $_[0]->{attributes} }
215
216 sub namespace{
217     my $name = $_[0]->{package};
218     no strict 'refs';
219     return \%{ $name . '::' };
220 }
221
222 sub add_method {
223     my($self, $name, $code) = @_;
224
225     if(!defined $name){
226         $self->throw_error('You must pass a defined name');
227     }
228     if(!defined $code){
229         $self->throw_error('You must pass a defined code');
230     }
231
232     if(ref($code) ne 'CODE'){
233         $code = \&{$code}; # coerce
234     }
235
236     $self->{methods}->{$name} = $code; # Moose stores meta object here.
237
238     Mouse::Util::install_subroutines($self->name,
239         $name => $code,
240     );
241     return;
242 }
243
244 package Mouse::Meta::Class;
245
246 sub method_metaclass    { $_[0]->{method_metaclass}    || 'Mouse::Meta::Method'    }
247 sub attribute_metaclass { $_[0]->{attribute_metaclass} || 'Mouse::Meta::Attribute' }
248
249 sub constructor_class { $_[0]->{constructor_class} || 'Mouse::Meta::Method::Constructor' }
250 sub destructor_class  { $_[0]->{destructor_class}  || 'Mouse::Meta::Method::Destructor'  }
251
252 sub is_anon_class{
253     return exists $_[0]->{anon_serial_id};
254 }
255
256 sub roles { $_[0]->{roles} }
257
258 sub linearized_isa { @{ get_linear_isa($_[0]->{package}) } }
259
260 sub get_all_attributes {
261     my($self) = @_;
262     my %attrs = map { %{ $self->initialize($_)->{attributes} } } reverse $self->linearized_isa;
263     return values %attrs;
264 }
265
266 sub new_object {
267     my $self = shift;
268     my %args = (@_ == 1 ? %{$_[0]} : @_);
269
270     my $object = bless {}, $self->name;
271
272     $self->_initialize_object($object, \%args);
273     return $object;
274 }
275
276 sub _initialize_object{
277     my($self, $object, $args, $ignore_triggers) = @_;
278
279     my @triggers_queue;
280
281     foreach my $attribute ($self->get_all_attributes) {
282         my $init_arg = $attribute->init_arg;
283         my $slot     = $attribute->name;
284
285         if (defined($init_arg) && exists($args->{$init_arg})) {
286             $object->{$slot} = $attribute->_coerce_and_verify($args->{$init_arg}, $object);
287
288             weaken($object->{$slot})
289                 if ref($object->{$slot}) && $attribute->is_weak_ref;
290
291             if ($attribute->has_trigger) {
292                 push @triggers_queue, [ $attribute->trigger, $object->{$slot} ];
293             }
294         }
295         else { # no init arg
296             if ($attribute->has_default || $attribute->has_builder) {
297                 if (!$attribute->is_lazy) {
298                     my $default = $attribute->default;
299                     my $builder = $attribute->builder;
300                     my $value =   $builder                ? $object->$builder()
301                                 : ref($default) eq 'CODE' ? $object->$default()
302                                 :                           $default;
303
304                     $object->{$slot} = $attribute->_coerce_and_verify($value, $object);
305
306                     weaken($object->{$slot})
307                         if ref($object->{$slot}) && $attribute->is_weak_ref;
308                 }
309             }
310             elsif($attribute->is_required) {
311                 $self->throw_error("Attribute (".$attribute->name.") is required");
312             }
313         }
314     }
315
316     if(!$ignore_triggers){
317         foreach my $trigger_and_value(@triggers_queue){
318             my($trigger, $value) = @{$trigger_and_value};
319             $trigger->($object, $value);
320         }
321     }
322
323     if($self->is_anon_class){
324         $object->{__METACLASS__} = $self;
325     }
326
327     return;
328 }
329
330 sub is_immutable {  $_[0]->{is_immutable} }
331
332 sub __strict_constructor{ $_[0]->{strict_constructor} }
333
334 package Mouse::Meta::Role;
335
336 sub method_metaclass{ $_[0]->{method_metaclass} || 'Mouse::Meta::Role::Method' }
337
338 sub is_anon_role{
339     return exists $_[0]->{anon_serial_id};
340 }
341
342 sub get_roles { $_[0]->{roles} }
343
344 sub add_before_method_modifier {
345     my ($self, $method_name, $method) = @_;
346
347     push @{ $self->{before_method_modifiers}{$method_name} ||= [] }, $method;
348     return;
349 }
350 sub add_around_method_modifier {
351     my ($self, $method_name, $method) = @_;
352
353     push @{ $self->{around_method_modifiers}{$method_name} ||= [] }, $method;
354     return;
355 }
356 sub add_after_method_modifier {
357     my ($self, $method_name, $method) = @_;
358
359     push @{ $self->{after_method_modifiers}{$method_name} ||= [] }, $method;
360     return;
361 }
362
363 sub get_before_method_modifiers {
364     my ($self, $method_name) = @_;
365     return @{ $self->{before_method_modifiers}{$method_name} ||= [] }
366 }
367 sub get_around_method_modifiers {
368     my ($self, $method_name) = @_;
369     return @{ $self->{around_method_modifiers}{$method_name} ||= [] }
370 }
371 sub get_after_method_modifiers {
372     my ($self, $method_name) = @_;
373     return @{ $self->{after_method_modifiers}{$method_name} ||= [] }
374 }
375
376 package Mouse::Meta::Attribute;
377
378 require Mouse::Meta::Method::Accessor;
379
380 sub accessor_metaclass{ $_[0]->{accessor_metaclass} || 'Mouse::Meta::Method::Accessor' }
381
382 # readers
383
384 sub name                 { $_[0]->{name}                   }
385 sub associated_class     { $_[0]->{associated_class}       }
386
387 sub accessor             { $_[0]->{accessor}               }
388 sub reader               { $_[0]->{reader}                 }
389 sub writer               { $_[0]->{writer}                 }
390 sub predicate            { $_[0]->{predicate}              }
391 sub clearer              { $_[0]->{clearer}                }
392 sub handles              { $_[0]->{handles}                }
393
394 sub _is_metadata         { $_[0]->{is}                     }
395 sub is_required          { $_[0]->{required}               }
396 sub default              { $_[0]->{default}                }
397 sub is_lazy              { $_[0]->{lazy}                   }
398 sub is_lazy_build        { $_[0]->{lazy_build}             }
399 sub is_weak_ref          { $_[0]->{weak_ref}               }
400 sub init_arg             { $_[0]->{init_arg}               }
401 sub type_constraint      { $_[0]->{type_constraint}        }
402
403 sub trigger              { $_[0]->{trigger}                }
404 sub builder              { $_[0]->{builder}                }
405 sub should_auto_deref    { $_[0]->{auto_deref}             }
406 sub should_coerce        { $_[0]->{coerce}                 }
407
408 sub documentation        { $_[0]->{documentation}          }
409
410 # predicates
411
412 sub has_accessor         { exists $_[0]->{accessor}        }
413 sub has_reader           { exists $_[0]->{reader}          }
414 sub has_writer           { exists $_[0]->{writer}          }
415 sub has_predicate        { exists $_[0]->{predicate}       }
416 sub has_clearer          { exists $_[0]->{clearer}         }
417 sub has_handles          { exists $_[0]->{handles}         }
418
419 sub has_default          { exists $_[0]->{default}         }
420 sub has_type_constraint  { exists $_[0]->{type_constraint} }
421 sub has_trigger          { exists $_[0]->{trigger}         }
422 sub has_builder          { exists $_[0]->{builder}         }
423
424 sub has_documentation    { exists $_[0]->{documentation}   }
425
426 sub _process_options{
427     my($class, $name, $args) = @_;
428
429     # taken from Class::MOP::Attribute::new
430
431     defined($name)
432         or $class->throw_error('You must provide a name for the attribute');
433
434     if(!exists $args->{init_arg}){
435         $args->{init_arg} = $name;
436     }
437
438     # 'required' requires eigher 'init_arg', 'builder', or 'default'
439     my $can_be_required = defined( $args->{init_arg} );
440
441     if(exists $args->{builder}){
442         # XXX:
443         # Moose refuses a CODE ref builder, but Mouse doesn't for backward compatibility
444         # This feature will be changed in a future. (gfx)
445         $class->throw_error('builder must be a defined scalar value which is a method name')
446             #if ref $args->{builder} || !defined $args->{builder};
447             if !defined $args->{builder};
448
449         $can_be_required++;
450     }
451     elsif(exists $args->{default}){
452         if(ref $args->{default} && ref($args->{default}) ne 'CODE'){
453             $class->throw_error("References are not allowed as default values, you must "
454                               . "wrap the default of '$name' in a CODE reference (ex: sub { [] } and not [])");
455         }
456         $can_be_required++;
457     }
458
459     if( $args->{required} && !$can_be_required ) {
460         $class->throw_error("You cannot have a required attribute ($name) without a default, builder, or an init_arg");
461     }
462
463     # taken from Mouse::Meta::Attribute->new and ->_process_args
464
465     if(exists $args->{is}){
466         my $is = $args->{is};
467
468         if($is eq 'ro'){
469             $args->{reader} ||= $name;
470         }
471         elsif($is eq 'rw'){
472             if(exists $args->{writer}){
473                 $args->{reader} ||= $name;
474              }
475              else{
476                 $args->{accessor} ||= $name;
477              }
478         }
479         elsif($is eq 'bare'){
480             # do nothing, but don't complain (later) about missing methods
481         }
482         else{
483             $is = 'undef' if !defined $is;
484             $class->throw_error("I do not understand this option (is => $is) on attribute ($name)");
485         }
486     }
487
488     my $tc;
489     if(exists $args->{isa}){
490         $tc = $args->{type_constraint} = Mouse::Util::TypeConstraints::find_or_create_isa_type_constraint($args->{isa});
491     }
492
493     if(exists $args->{does}){
494         if(defined $tc){ # both isa and does supplied
495             my $does_ok = do{
496                 local $@;
497                 eval{ "$tc"->does($args) };
498             };
499             if(!$does_ok){
500                 $class->throw_error("Cannot have both an isa option and a does option because '$tc' does not do '$args->{does}' on attribute ($name)");
501             }
502         }
503         else {
504             $tc = $args->{type_constraint} = Mouse::Util::TypeConstraints::find_or_create_does_type_constraint($args->{does});
505         }
506     }
507
508     if($args->{coerce}){
509         defined($tc)
510             || $class->throw_error("You cannot have coercion without specifying a type constraint on attribute ($name)");
511
512         $args->{weak_ref}
513             && $class->throw_error("You cannot have a weak reference to a coerced value on attribute ($name)");
514     }
515
516     if ($args->{lazy_build}) {
517         exists($args->{default})
518             && $class->throw_error("You can not use lazy_build and default for the same attribute ($name)");
519
520         $args->{lazy}      = 1;
521         $args->{builder} ||= "_build_${name}";
522         if ($name =~ /^_/) {
523             $args->{clearer}   ||= "_clear${name}";
524             $args->{predicate} ||= "_has${name}";
525         }
526         else {
527             $args->{clearer}   ||= "clear_${name}";
528             $args->{predicate} ||= "has_${name}";
529         }
530     }
531
532     if ($args->{auto_deref}) {
533         defined($tc)
534             || $class->throw_error("You cannot auto-dereference without specifying a type constraint on attribute ($name)");
535
536         ( $tc->is_a_type_of('ArrayRef') || $tc->is_a_type_of('HashRef') )
537             || $class->throw_error("You cannot auto-dereference anything other than a ArrayRef or HashRef on attribute ($name)");
538     }
539
540     if (exists $args->{trigger}) {
541         ('CODE' eq ref $args->{trigger})
542             || $class->throw_error("Trigger must be a CODE ref on attribute ($name)");
543     }
544
545     if ($args->{lazy}) {
546         (exists $args->{default} || defined $args->{builder})
547             || $class->throw_error("You cannot have lazy attribute ($name) without specifying a default value for it");
548     }
549
550     return;
551 }
552
553
554 package Mouse::Meta::TypeConstraint;
555
556 sub name    { $_[0]->{name}    }
557 sub parent  { $_[0]->{parent}  }
558 sub message { $_[0]->{message} }
559
560 sub type_parameter           { $_[0]->{type_parameter} }
561 sub _compiled_type_constraint{ $_[0]->{compiled_type_constraint} }
562 sub _compiled_type_coercion  { $_[0]->{_compiled_type_coercion}  }
563
564 sub __is_parameterized { exists $_[0]->{type_parameter} }
565 sub has_coercion {       exists $_[0]->{_compiled_type_coercion} }
566
567
568 sub compile_type_constraint{
569     my($self) = @_;
570
571     # add parents first
572     my @checks;
573     for(my $parent = $self->{parent}; defined $parent; $parent = $parent->{parent}){
574          if($parent->{hand_optimized_type_constraint}){
575             unshift @checks, $parent->{hand_optimized_type_constraint};
576             last; # a hand optimized constraint must include all the parents
577         }
578         elsif($parent->{constraint}){
579             unshift @checks, $parent->{constraint};
580         }
581     }
582
583     # then add child
584     if($self->{constraint}){
585         push @checks, $self->{constraint};
586     }
587
588     if($self->{type_constraints}){ # Union
589         my @types = map{ $_->{compiled_type_constraint} } @{ $self->{type_constraints} };
590         push @checks, sub{
591             foreach my $c(@types){
592                 return 1 if $c->($_[0]);
593             }
594             return 0;
595         };
596     }
597
598     if(@checks == 0){
599         $self->{compiled_type_constraint} = \&Mouse::Util::TypeConstraints::Any;
600     }
601     else{
602         $self->{compiled_type_constraint} =  sub{
603             my(@args) = @_;
604             local $_ = $args[0];
605             foreach my $c(@checks){
606                 return undef if !$c->(@args);
607             }
608             return 1;
609         };
610     }
611     return;
612 }
613
614 package Mouse::Object;
615
616 sub BUILDARGS {
617     my $class = shift;
618
619     if (scalar @_ == 1) {
620         (ref($_[0]) eq 'HASH')
621             || $class->meta->throw_error("Single parameters to new() must be a HASH ref");
622
623         return {%{$_[0]}};
624     }
625     else {
626         return {@_};
627     }
628 }
629
630 sub new {
631     my $class = shift;
632
633     $class->meta->throw_error('Cannot call new() on an instance') if ref $class;
634
635     my $args = $class->BUILDARGS(@_);
636
637     my $meta = Mouse::Meta::Class->initialize($class);
638     my $self = $meta->new_object($args);
639
640     # BUILDALL
641     if( $self->can('BUILD') ) {
642         for my $class (reverse $meta->linearized_isa) {
643             my $build = Mouse::Util::get_code_ref($class, 'BUILD')
644                 || next;
645
646             $self->$build($args);
647         }
648     }
649
650     return $self;
651 }
652
653 sub DESTROY {
654     my $self = shift;
655
656     return unless $self->can('DEMOLISH'); # short circuit
657
658     local $?;
659
660     my $e = do{
661         local $@;
662         eval{
663             # DEMOLISHALL
664
665             # We cannot count on being able to retrieve a previously made
666             # metaclass, _or_ being able to make a new one during global
667             # destruction. However, we should still be able to use mro at
668             # that time (at least tests suggest so ;)
669
670             foreach my $class (@{ Mouse::Util::get_linear_isa(ref $self) }) {
671                 my $demolish = Mouse::Util::get_code_ref($class, 'DEMOLISH')
672                     || next;
673
674                 $self->$demolish($Mouse::Util::in_global_destruction);
675             }
676         };
677         $@;
678     };
679
680     no warnings 'misc';
681     die $e if $e; # rethrow
682 }
683
684 sub BUILDALL {
685     my $self = shift;
686
687     # short circuit
688     return unless $self->can('BUILD');
689
690     for my $class (reverse $self->meta->linearized_isa) {
691         my $build = Mouse::Util::get_code_ref($class, 'BUILD')
692             || next;
693
694         $self->$build(@_);
695     }
696     return;
697 }
698
699 sub DEMOLISHALL;
700 *DEMOLISHALL = \&DESTROY;
701
702 1;
703 __END__
704
705 =head1 NAME
706
707 Mouse::PurePerl - A Mouse guts in pure Perl
708
709 =head1 VERSION
710
711 This document describes Mouse version 0.50_03
712
713 =head1 SEE ALSO
714
715 L<Mouse::XS>
716
717 =cut