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