Checking in changes prior to tagging of version 0.50_03. Changelog diff is:
[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         $tc = $args->{type_constraint} = Mouse::Util::TypeConstraints::find_or_create_isa_type_constraint($args->{isa});
451     }
452
453     if(exists $args->{does}){
454         if(defined $tc){ # both isa and does supplied
455             my $does_ok = do{
456                 local $@;
457                 eval{ "$tc"->does($args) };
458             };
459             if(!$does_ok){
460                 $class->throw_error("Cannot have both an isa option and a does option because '$tc' does not do '$args->{does}' on attribute ($name)");
461             }
462         }
463         else {
464             $tc = $args->{type_constraint} = Mouse::Util::TypeConstraints::find_or_create_does_type_constraint($args->{does});
465         }
466     }
467
468     if($args->{coerce}){
469         defined($tc)
470             || $class->throw_error("You cannot have coercion without specifying a type constraint on attribute ($name)");
471
472         $args->{weak_ref}
473             && $class->throw_error("You cannot have a weak reference to a coerced value on attribute ($name)");
474     }
475
476     if ($args->{lazy_build}) {
477         exists($args->{default})
478             && $class->throw_error("You can not use lazy_build and default for the same attribute ($name)");
479
480         $args->{lazy}      = 1;
481         $args->{builder} ||= "_build_${name}";
482         if ($name =~ /^_/) {
483             $args->{clearer}   ||= "_clear${name}";
484             $args->{predicate} ||= "_has${name}";
485         }
486         else {
487             $args->{clearer}   ||= "clear_${name}";
488             $args->{predicate} ||= "has_${name}";
489         }
490     }
491
492     if ($args->{auto_deref}) {
493         defined($tc)
494             || $class->throw_error("You cannot auto-dereference without specifying a type constraint on attribute ($name)");
495
496         ( $tc->is_a_type_of('ArrayRef') || $tc->is_a_type_of('HashRef') )
497             || $class->throw_error("You cannot auto-dereference anything other than a ArrayRef or HashRef on attribute ($name)");
498     }
499
500     if (exists $args->{trigger}) {
501         ('CODE' eq ref $args->{trigger})
502             || $class->throw_error("Trigger must be a CODE ref on attribute ($name)");
503     }
504
505     if ($args->{lazy}) {
506         (exists $args->{default} || defined $args->{builder})
507             || $class->throw_error("You cannot have lazy attribute ($name) without specifying a default value for it");
508     }
509
510     return;
511 }
512
513
514 package Mouse::Meta::TypeConstraint;
515
516 sub name    { $_[0]->{name}    }
517 sub parent  { $_[0]->{parent}  }
518 sub message { $_[0]->{message} }
519
520 sub type_parameter { $_[0]->{type_parameter} }
521 sub __is_parameterized { exists $_[0]->{type_parameter} }
522
523 sub _compiled_type_constraint{ $_[0]->{compiled_type_constraint} }
524
525 sub _compiled_type_coercion  { $_[0]->{_compiled_type_coercion}  }
526
527 sub has_coercion{ exists $_[0]->{_compiled_type_coercion} }
528
529
530 sub compile_type_constraint{
531     my($self) = @_;
532
533     # add parents first
534     my @checks;
535     for(my $parent = $self->{parent}; defined $parent; $parent = $parent->{parent}){
536          if($parent->{hand_optimized_type_constraint}){
537             unshift @checks, $parent->{hand_optimized_type_constraint};
538             last; # a hand optimized constraint must include all the parents
539         }
540         elsif($parent->{constraint}){
541             unshift @checks, $parent->{constraint};
542         }
543     }
544
545     # then add child
546     if($self->{constraint}){
547         push @checks, $self->{constraint};
548     }
549
550     if($self->{type_constraints}){ # Union
551         my @types = map{ $_->{compiled_type_constraint} } @{ $self->{type_constraints} };
552         push @checks, sub{
553             foreach my $c(@types){
554                 return 1 if $c->($_[0]);
555             }
556             return 0;
557         };
558     }
559
560     if(@checks == 0){
561         $self->{compiled_type_constraint} = \&Mouse::Util::TypeConstraints::Any;
562     }
563     else{
564         $self->{compiled_type_constraint} =  sub{
565             my(@args) = @_;
566             local $_ = $args[0];
567             foreach my $c(@checks){
568                 return undef if !$c->(@args);
569             }
570             return 1;
571         };
572     }
573     return;
574 }
575
576 package Mouse::Object;
577
578
579 sub BUILDARGS {
580     my $class = shift;
581
582     if (scalar @_ == 1) {
583         (ref($_[0]) eq 'HASH')
584             || $class->meta->throw_error("Single parameters to new() must be a HASH ref");
585
586         return {%{$_[0]}};
587     }
588     else {
589         return {@_};
590     }
591 }
592
593 sub new {
594     my $class = shift;
595
596     $class->meta->throw_error('Cannot call new() on an instance') if ref $class;
597
598     my $args = $class->BUILDARGS(@_);
599
600     my $meta = Mouse::Meta::Class->initialize($class);
601     my $self = $meta->new_object($args);
602
603     # BUILDALL
604     if( $self->can('BUILD') ) {
605         for my $class (reverse $meta->linearized_isa) {
606             my $build = Mouse::Util::get_code_ref($class, 'BUILD')
607                 || next;
608
609             $self->$build($args);
610         }
611     }
612
613     return $self;
614 }
615
616 sub DESTROY {
617     my $self = shift;
618
619     return unless $self->can('DEMOLISH'); # short circuit
620
621     local $?;
622
623     my $e = do{
624         local $@;
625         eval{
626
627             # DEMOLISHALL
628
629             # We cannot count on being able to retrieve a previously made
630             # metaclass, _or_ being able to make a new one during global
631             # destruction. However, we should still be able to use mro at
632             # that time (at least tests suggest so ;)
633
634             foreach my $class (@{ Mouse::Util::get_linear_isa(ref $self) }) {
635                 my $demolish = Mouse::Util::get_code_ref($class, 'DEMOLISH')
636                     || next;
637
638                 $self->$demolish($Mouse::Util::in_global_destruction);
639             }
640         };
641         $@;
642     };
643
644     no warnings 'misc';
645     die $e if $e; # rethrow
646 }
647
648 sub BUILDALL {
649     my $self = shift;
650
651     # short circuit
652     return unless $self->can('BUILD');
653
654     for my $class (reverse $self->meta->linearized_isa) {
655         my $build = Mouse::Util::get_code_ref($class, 'BUILD')
656             || next;
657
658         $self->$build(@_);
659     }
660     return;
661 }
662
663 sub DEMOLISHALL;
664 *DEMOLISHALL = \&DESTROY;
665
666 1;
667 __END__
668
669 =head1 NAME
670
671 Mouse::PurePerl - A Mouse guts in pure Perl
672
673 =head1 VERSION
674
675 This document describes Mouse version 0.50_03
676
677 =head1 SEE ALSO
678
679 L<Mouse::XS>
680
681 =cut