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