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