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