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