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