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