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