Tidy _generate_destructor
[gitmo/Mouse.git] / lib / Mouse / Meta / Module.pm
index 51e1a6d..14990ee 100755 (executable)
 package Mouse::Meta::Module;
-use strict;
-use warnings;
+use Mouse::Util qw/:meta get_code_package get_code_ref not_supported/; # enables strict and warnings
 
-use Carp ();
-use Scalar::Util qw/blessed weaken/;
+use Carp         ();
+use Scalar::Util ();
 
-use Mouse::Util qw/get_code_info not_supported load_class/;
+my %METAS;
 
-{
-    my %METACLASS_CACHE;
+if(Mouse::Util::MOUSE_XS){
+    # register meta storage for performance
+    Mouse::Util::__register_metaclass_storage(\%METAS, 0);
 
-    # because Mouse doesn't introspect existing classes, we're forced to
-    # only pay attention to other Mouse classes
-    sub _metaclass_cache {
-        my($class, $name) = @_;
-        return $METACLASS_CACHE{$name};
-    }
+    # ensure thread safety
+    *CLONE = sub { Mouse::Util::__register_metaclass_storage(\%METAS, 1) };
+}
 
-    sub initialize {
-        my($class, $package_name, @args) = @_;
+sub _metaclass_cache { # DEPRECATED
+    my($class, $name) = @_;
+    Carp::cluck('_metaclass_cache() has been deprecated. Use Mouse::Util::get_metaclass_by_name() instead');
+    return $METAS{$name};
+}
 
-        ($package_name && !ref($package_name))
-            || $class->throw_error("You must pass a package name and it cannot be blessed");
+sub initialize {
+    my($class, $package_name, @args) = @_;
 
-        return $METACLASS_CACHE{$package_name}
-            ||= $class->_construct_meta(package => $package_name, @args);
-    }
+    ($package_name && !ref($package_name))
+        || $class->throw_error("You must pass a package name and it cannot be blessed");
 
-    sub class_of{
-        my($class_or_instance) = @_;
-        return undef unless defined $class_or_instance;
-        return $METACLASS_CACHE{ blessed($class_or_instance) || $class_or_instance };
-    }
+    return $METAS{$package_name}
+        ||= $class->_construct_meta(package => $package_name, @args);
+}
+
+sub reinitialize {
+    my($class, $package_name, @args) = @_;
 
-    # Means of accessing all the metaclasses that have
-    # been initialized thus far
-    sub get_all_metaclasses         {        %METACLASS_CACHE         }
-    sub get_all_metaclass_instances { values %METACLASS_CACHE         }
-    sub get_all_metaclass_names     { keys   %METACLASS_CACHE         }
-    sub get_metaclass_by_name       { $METACLASS_CACHE{$_[0]}         }
-    sub store_metaclass_by_name     { $METACLASS_CACHE{$_[0]} = $_[1] }
-    sub weaken_metaclass            { weaken($METACLASS_CACHE{$_[0]}) }
-    sub does_metaclass_exist        { defined $METACLASS_CACHE{$_[0]} }
-    sub remove_metaclass_by_name    { delete $METACLASS_CACHE{$_[0]}  }
+    $package_name = $package_name->name if ref $package_name;
 
+    ($package_name && !ref($package_name))
+        || $class->throw_error("You must pass a package name and it cannot be blessed");
+
+    delete $METAS{$package_name};
+    return $class->initialize($package_name, @args);
 }
 
-sub meta{ Mouse::Meta::Class->initialize(ref $_[0] || $_[0]) }
+sub _class_of{
+    my($class_or_instance) = @_;
+    return undef unless defined $class_or_instance;
+    return $METAS{ ref($class_or_instance) || $class_or_instance };
+}
 
-sub _new{ Carp::croak("Mouse::Meta::Module is an abstract class") }
+# Means of accessing all the metaclasses that have
+# been initialized thus far
+#sub _get_all_metaclasses         {        %METAS         }
+sub _get_all_metaclass_instances { values %METAS         }
+sub _get_all_metaclass_names     { keys   %METAS         }
+sub _get_metaclass_by_name       { $METAS{$_[0]}         }
+#sub _store_metaclass_by_name     { $METAS{$_[0]} = $_[1] }
+#sub _weaken_metaclass            { weaken($METAS{$_[0]}) }
+#sub _does_metaclass_exist        { defined $METAS{$_[0]} }
+#sub _remove_metaclass_by_name    { delete $METAS{$_[0]}  }
 
-sub name { $_[0]->{package} }
+sub name;
 
-sub version   { no strict 'refs'; ${shift->name.'::VERSION'}   }
-sub authority { no strict 'refs'; ${shift->name.'::AUTHORITY'} }
-sub identifier {
-    my $self = shift;
-    return join '-' => (
-        $self->name,
-        ($self->version   || ()),
-        ($self->authority || ()),
-    );
-}
+sub namespace;
 
 # add_attribute is an abstract method
 
-sub get_attribute_map {        $_[0]->{attributes}          }
+sub get_attribute_map { # DEPRECATED
+    Carp::cluck('get_attribute_map() has been deprecated. Use get_attribute_list() and get_attribute() instead');
+    return $_[0]->{attributes};
+}
+
 sub has_attribute     { exists $_[0]->{attributes}->{$_[1]} }
 sub get_attribute     {        $_[0]->{attributes}->{$_[1]} }
-sub get_attribute_list{ keys %{$_[0]->{attributes}}         }
 sub remove_attribute  { delete $_[0]->{attributes}->{$_[1]} }
 
-sub namespace{
-    my $name = $_[0]->{package};
-    no strict 'refs';
-    return \%{ $name . '::' };
-}
-
-sub add_method {
-    my($self, $name, $code) = @_;
-
-    if(!defined $name){
-        $self->throw_error("You must pass a defined name");
-    }
-    if(ref($code) ne 'CODE'){
-        not_supported 'add_method for a method object';
-    }
+sub get_attribute_list{ keys   %{$_[0]->{attributes}} }
 
-    $self->{methods}->{$name}++; # Moose stores meta object here.
+# XXX: for backward compatibility
+my %foreign = map{ $_ => undef } qw(
+    Mouse Mouse::Role Mouse::Util Mouse::Util::TypeConstraints
+    Carp Scalar::Util List::Util
+);
+sub _code_is_mine{
+#    my($self, $code) = @_;
 
-    my $pkg = $self->name;
-    no strict 'refs';
-    no warnings 'redefine';
-    *{ $pkg . '::' . $name } = $code;
+    return !exists $foreign{ get_code_package($_[1]) };
 }
 
-sub _code_is_mine { # taken from Class::MOP::Class
-    my ( $self, $code ) = @_;
+sub add_method;
 
-    my ( $code_package, $code_name ) = get_code_info($code);
+sub has_method {
+    my($self, $method_name) = @_;
 
-    return $code_package && $code_package eq $self->name
-        || ( $code_package eq 'constant' && $code_name eq '__ANON__' );
+    defined($method_name)
+        or $self->throw_error('You must define a method name');
+
+    return defined($self->{methods}{$method_name}) || do{
+        my $code = get_code_ref($self->{package}, $method_name);
+        $code && $self->_code_is_mine($code);
+    };
 }
 
-sub has_method {
+sub get_method_body {
     my($self, $method_name) = @_;
 
-    return 1 if $self->{methods}->{$method_name};
-    my $code = $self->name->can($method_name);
+    defined($method_name)
+        or $self->throw_error('You must define a method name');
 
-    return $code && $self->_code_is_mine($code);
+    return $self->{methods}{$method_name} ||= do{
+        my $code = get_code_ref($self->{package}, $method_name);
+        $code && $self->_code_is_mine($code) ? $code : undef;
+    };
 }
 
 sub get_method{
     my($self, $method_name) = @_;
 
-    if($self->has_method($method_name)){
-        my $method_metaclass = $self->method_metaclass;
-        load_class($method_metaclass);
-
-        my $package = $self->name;
-        return $method_metaclass->new(
-            body    => $package->can($method_name),
-            name    => $method_name,
-            package => $package,
+    if(my $code = $self->get_method_body($method_name)){
+        return Mouse::Util::load_class($self->method_metaclass)->wrap(
+            body                 => $code,
+            name                 => $method_name,
+            package              => $self->name,
+            associated_metaclass => $self,
         );
     }
 
@@ -137,144 +134,170 @@ sub get_method_list {
     return grep { $self->has_method($_) } keys %{ $self->namespace };
 }
 
-{
-    my $ANON_SERIAL = 0;
-    my $ANON_PREFIX = 'Mouse::Meta::Module::__ANON__::';
+sub _collect_methods { # Mouse specific
+    my($meta, @args) = @_;
 
-    my %IMMORTALS;
+    my @methods;
+    foreach my $arg(@args){
+        if(my $type = ref $arg){
+            if($type eq 'Regexp'){
+                push @methods, grep { $_ =~ $arg } $meta->get_all_method_names;
+            }
+            elsif($type eq 'ARRAY'){
+                push @methods, @{$arg};
+            }
+            else{
+                my $subname = ( caller(1) )[3];
+                $meta->throw_error(
+                    sprintf(
+                        'Methods passed to %s must be provided as a list, ArrayRef or regular expression, not %s',
+                        $subname,
+                        $type,
+                    )
+                );
+            }
+         }
+         else{
+            push @methods, $arg;
+         }
+     }
+     return @methods;
+}
 
-    sub create {
-        my ($class, $package_name, %options) = @_;
+my $ANON_SERIAL = 0;  # anonymous class/role id
+my %IMMORTALS;        # immortal anonymous classes
 
-        $class->throw_error('You must pass a package name') if @_ == 1;
+sub create {
+    my($self, $package_name, %options) = @_;
 
+    my $class = ref($self) || $self;
+    $self->throw_error('You must pass a package name') if @_ < 2;
 
-        if(exists $options{superclasses}){
-            if($class->isa('Mouse::Meta::Class')){
-                (ref $options{superclasses} eq 'ARRAY')
-                    || $class->throw_error("You must pass an ARRAY ref of superclasses");
-            }
-            else{ # role
-                delete $options{superclasses};
-            }
+    my $superclasses;
+    if(exists $options{superclasses}){
+        if(Mouse::Util::is_a_metarole($self)){
+            delete $options{superclasses};
         }
-
-        my $attributes;
-        if(exists $options{attributes}){
-            $attributes = delete $options{attributes};
-           (ref $attributes eq 'ARRAY' || ref $attributes eq 'HASH')
-               || $class->throw_error("You must pass an ARRAY ref of attributes")
-           }
-
-        (ref $options{methods} eq 'HASH')
-            || $class->throw_error("You must pass a HASH ref of methods")
-                if exists $options{methods};
-
-        (ref $options{roles} eq 'ARRAY')
-            || $class->throw_error("You must pass an ARRAY ref of roles")
-                if exists $options{roles};
-
-
-        my @extra_options;
-        my $mortal;
-        my $cache_key;
-
-        if(!defined $package_name){ # anonymous
-            $mortal = !$options{cache};
-
-            # anonymous but immortal
-            if(!$mortal){
-                    # something like Super::Class|Super::Class::2=Role|Role::1
-                    $cache_key = join '=' => (
-                        join('|',      @{$options{superclasses} || []}),
-                        join('|', sort @{$options{roles}        || []}),
-                    );
-                    return $IMMORTALS{$cache_key} if exists $IMMORTALS{$cache_key};
-            }
-            $package_name = $ANON_PREFIX . ++$ANON_SERIAL;
-
-            push @extra_options, (anon_serial_id => $ANON_SERIAL);
+        else{
+            $superclasses = delete $options{superclasses};
+            (ref $superclasses eq 'ARRAY')
+                || $self->throw_error("You must pass an ARRAY ref of superclasses");
         }
+    }
 
-        # instantiate a module
-        {
-            no strict 'refs';
-            ${ $package_name . '::VERSION'   } = delete $options{version}   if exists $options{version};
-            ${ $package_name . '::AUTHORITY' } = delete $options{authority} if exists $options{authority};
+    my $attributes = delete $options{attributes};
+    if(defined $attributes){
+        (ref $attributes eq 'ARRAY' || ref $attributes eq 'HASH')
+            || $self->throw_error("You must pass an ARRAY ref of attributes");
+    }
+    my $methods = delete $options{methods};
+    if(defined $methods){
+        (ref $methods eq 'HASH')
+            || $self->throw_error("You must pass a HASH ref of methods");
+    }
+    my $roles = delete $options{roles};
+    if(defined $roles){
+        (ref $roles eq 'ARRAY')
+            || $self->throw_error("You must pass an ARRAY ref of roles");
+    }
+    my $mortal;
+    my $cache_key;
+
+    if(!defined $package_name){ # anonymous
+        $mortal = !$options{cache};
+
+        # anonymous but immortal
+        if(!$mortal){
+                # something like Super::Class|Super::Class::2=Role|Role::1
+                $cache_key = join '=' => (
+                    join('|',      @{$superclasses || []}),
+                    join('|', sort @{$roles        || []}),
+                );
+                return $IMMORTALS{$cache_key} if exists $IMMORTALS{$cache_key};
         }
+        $options{anon_serial_id} = ++$ANON_SERIAL;
+        $package_name = $class . '::__ANON__::' . $ANON_SERIAL;
+    }
 
-        my %initialize_options = %options;
-        delete @initialize_options{qw(
-            package
-            superclasses
-            attributes
-            methods
-            roles
-        )};
-        my $meta = $class->initialize( $package_name, %initialize_options, @extra_options);
-
-        Mouse::Meta::Module::weaken_metaclass($package_name)
-            if $mortal;
-
-        # FIXME totally lame
-        $meta->add_method('meta' => sub {
-            $class->initialize(ref($_[0]) || $_[0]);
-        });
-
-        $meta->superclasses(@{$options{superclasses}})
-            if exists $options{superclasses};
-
-        # NOTE:
-        # process attributes first, so that they can
-        # install accessors, but locally defined methods
-        # can then overwrite them. It is maybe a little odd, but
-        # I think this should be the order of things.
-        if (defined $attributes) {
-            if(ref($attributes) eq 'ARRAY'){
-                foreach my $attr (@{$attributes}) {
-                    $meta->add_attribute($attr->{name} => $attr);
-                }
-            }
-            else{
-                while(my($name, $attr) = each %{$attributes}){
-                    $meta->add_attribute($name => $attr);
-                }
+    # instantiate a module
+    {
+        no strict 'refs';
+        ${ $package_name . '::VERSION'   } = delete $options{version}   if exists $options{version};
+        ${ $package_name . '::AUTHORITY' } = delete $options{authority} if exists $options{authority};
+    }
+
+    my $meta = $self->initialize( $package_name, %options);
+
+    Scalar::Util::weaken $METAS{$package_name}
+        if $mortal;
+
+    $meta->add_method(meta => sub{
+        $self->initialize(ref($_[0]) || $_[0]);
+    });
+
+    $meta->superclasses(@{$superclasses})
+        if defined $superclasses;
+
+    # NOTE:
+    # process attributes first, so that they can
+    # install accessors, but locally defined methods
+    # can then overwrite them. It is maybe a little odd, but
+    # I think this should be the order of things.
+    if (defined $attributes) {
+        if(ref($attributes) eq 'ARRAY'){
+            # array of Mouse::Meta::Attribute
+            foreach my $attr (@{$attributes}) {
+                $meta->add_attribute($attr);
             }
         }
-        if (exists $options{methods}) {
-            foreach my $method_name (keys %{$options{methods}}) {
-                $meta->add_method($method_name, $options{methods}->{$method_name});
+        else{
+            # hash map of name and attribute spec pairs
+            while(my($name, $attr) = each %{$attributes}){
+                $meta->add_attribute($name => $attr);
             }
         }
-        if (exists $options{roles}){
-            Mouse::Util::apply_all_roles($package_name, @{$options{roles}});
-        }
-
-        if(!$mortal && exists $meta->{anon_serial_id}){
-            $IMMORTALS{$cache_key} = $meta;
+    }
+    if (defined $methods) {
+        while(my($method_name, $method_body) = each %{$methods}){
+            $meta->add_method($method_name, $method_body);
         }
+    }
+    if (defined $roles){
+        Mouse::Util::apply_all_roles($package_name, @{$roles});
+    }
 
-        return $meta;
+    if($cache_key){
+        $IMMORTALS{$cache_key} = $meta;
     }
 
-    sub DESTROY{
-        my($self) = @_;
+    return $meta;
+}
 
-        my $serial_id = $self->{anon_serial_id};
+sub DESTROY{
+    my($self) = @_;
 
-        return if !$serial_id;
+    return if $Mouse::Util::in_global_destruction;
 
-        my $stash = $self->namespace;
+    my $serial_id = $self->{anon_serial_id};
 
-        @{$self->{superclasses}} = () if exists $self->{superclasses};
-        %{$stash} = ();
-        Mouse::Meta::Module::remove_metaclass_by_name($self->name);
+    return if !$serial_id;
+    # mortal anonymous class
 
-        no strict 'refs';
-        delete ${$ANON_PREFIX}{ $serial_id . '::' };
+    # @ISA is a magical variable, so we clear it manually.
+    @{$self->{superclasses}} = () if exists $self->{superclasses};
 
-        return;
-    }
+    # Then, clear the symbol table hash
+    %{$self->namespace} = ();
+
+    my $name = $self->name;
+    delete $METAS{$name};
+
+    $name =~ s/ $serial_id \z//xms;
+
+    no strict 'refs';
+    delete ${$name}{ $serial_id . '::' };
+
+    return;
 }
 
 sub throw_error{
@@ -292,11 +315,23 @@ sub throw_error{
 }
 
 1;
-
 __END__
 
 =head1 NAME
 
-Mouse::Meta::Module - Common base class for Mouse::Meta::Class and Mouse::Meta::Role
+Mouse::Meta::Module - The base class for Mouse::Meta::Class and Mouse::Meta::Role
+
+=head1 VERSION
+
+This document describes Mouse version 0.50_03
+
+=head1 SEE ALSO
+
+L<Class::MOP::Class>
+
+L<Class::MOP::Module>
+
+L<Class::MOP::Package>
 
 =cut
+