Deprecate clone_instance
[gitmo/Mouse.git] / lib / Mouse / Meta / Module.pm
1 package Mouse::Meta::Module;
2 use strict;
3 use warnings;
4
5 use Carp ();
6 use Scalar::Util qw/blessed weaken/;
7
8 use Mouse::Util qw/get_code_info not_supported load_class/;
9
10 {
11     my %METACLASS_CACHE;
12
13     # because Mouse doesn't introspect existing classes, we're forced to
14     # only pay attention to other Mouse classes
15     sub _metaclass_cache {
16         my($class, $name) = @_;
17         return $METACLASS_CACHE{$name};
18     }
19
20     sub initialize {
21         my($class, $package_name, @args) = @_;
22
23         ($package_name && !ref($package_name))
24             || $class->throw_error("You must pass a package name and it cannot be blessed");
25
26         return $METACLASS_CACHE{$package_name}
27             ||= $class->_construct_meta(package => $package_name, @args);
28     }
29
30     sub class_of{
31         my($class_or_instance) = @_;
32         return undef unless defined $class_or_instance;
33         return $METACLASS_CACHE{ blessed($class_or_instance) || $class_or_instance };
34     }
35
36     # Means of accessing all the metaclasses that have
37     # been initialized thus far
38     sub get_all_metaclasses         {        %METACLASS_CACHE         }
39     sub get_all_metaclass_instances { values %METACLASS_CACHE         }
40     sub get_all_metaclass_names     { keys   %METACLASS_CACHE         }
41     sub get_metaclass_by_name       { $METACLASS_CACHE{$_[0]}         }
42     sub store_metaclass_by_name     { $METACLASS_CACHE{$_[0]} = $_[1] }
43     sub weaken_metaclass            { weaken($METACLASS_CACHE{$_[0]}) }
44     sub does_metaclass_exist        { defined $METACLASS_CACHE{$_[0]} }
45     sub remove_metaclass_by_name    { delete $METACLASS_CACHE{$_[0]}  }
46
47 }
48
49 sub meta{ Mouse::Meta::Class->initialize(ref $_[0] || $_[0]) }
50
51 sub _new{ Carp::croak("Mouse::Meta::Module is an abstract class") }
52
53 sub name { $_[0]->{package} }
54
55 sub version   { no strict 'refs'; ${shift->name.'::VERSION'}   }
56 sub authority { no strict 'refs'; ${shift->name.'::AUTHORITY'} }
57 sub identifier {
58     my $self = shift;
59     return join '-' => (
60         $self->name,
61         ($self->version   || ()),
62         ($self->authority || ()),
63     );
64 }
65
66 # add_attribute is an abstract method
67
68 sub get_attribute_map {        $_[0]->{attributes}          }
69 sub has_attribute     { exists $_[0]->{attributes}->{$_[1]} }
70 sub get_attribute     {        $_[0]->{attributes}->{$_[1]} }
71 sub get_attribute_list{ keys %{$_[0]->{attributes}}         }
72 sub remove_attribute  { delete $_[0]->{attributes}->{$_[1]} }
73
74 sub namespace{
75     my $name = $_[0]->{package};
76     no strict 'refs';
77     return \%{ $name . '::' };
78 }
79
80 sub add_method {
81     my($self, $name, $code) = @_;
82
83     if(!defined $name){
84         $self->throw_error('You must pass a defined name');
85     }
86     if(!defined $code){
87         $self->throw_error('You must pass a defined code');
88     }
89
90     if(ref($code) ne 'CODE'){
91         not_supported 'add_method for a method object';
92     }
93
94     $self->{methods}->{$name}++; # Moose stores meta object here.
95
96     my $pkg = $self->name;
97     no strict 'refs';
98     no warnings 'redefine';
99     *{ $pkg . '::' . $name } = $code;
100 }
101
102 sub _code_is_mine { # taken from Class::MOP::Class
103     my ( $self, $code ) = @_;
104
105     my ( $code_package, $code_name ) = get_code_info($code);
106
107     return $code_package && $code_package eq $self->name
108         || ( $code_package eq 'constant' && $code_name eq '__ANON__' );
109 }
110
111 sub has_method {
112     my($self, $method_name) = @_;
113
114     return 1 if $self->{methods}->{$method_name};
115     my $code = $self->name->can($method_name);
116
117     return $code && $self->_code_is_mine($code);
118 }
119
120 sub get_method{
121     my($self, $method_name) = @_;
122
123     if($self->has_method($method_name)){
124         my $method_metaclass = $self->method_metaclass;
125         load_class($method_metaclass);
126
127         my $package = $self->name;
128         return $method_metaclass->new(
129             body    => $package->can($method_name),
130             name    => $method_name,
131             package => $package,
132         );
133     }
134
135     return undef;
136 }
137
138 sub get_method_list {
139     my($self) = @_;
140
141     return grep { $self->has_method($_) } keys %{ $self->namespace };
142 }
143
144 {
145     my $ANON_SERIAL = 0;
146     my $ANON_PREFIX = 'Mouse::Meta::Module::__ANON__::';
147
148     my %IMMORTALS;
149
150     sub create {
151         my ($class, $package_name, %options) = @_;
152
153         $class->throw_error('You must pass a package name') if @_ == 1;
154
155
156         if(exists $options{superclasses}){
157             if($class->isa('Mouse::Meta::Class')){
158                 (ref $options{superclasses} eq 'ARRAY')
159                     || $class->throw_error("You must pass an ARRAY ref of superclasses");
160             }
161             else{ # role
162                 delete $options{superclasses};
163             }
164         }
165
166         my $attributes;
167         if(exists $options{attributes}){
168             $attributes = delete $options{attributes};
169            (ref $attributes eq 'ARRAY' || ref $attributes eq 'HASH')
170                || $class->throw_error("You must pass an ARRAY ref of attributes")
171            }
172
173         (ref $options{methods} eq 'HASH')
174             || $class->throw_error("You must pass a HASH ref of methods")
175                 if exists $options{methods};
176
177         (ref $options{roles} eq 'ARRAY')
178             || $class->throw_error("You must pass an ARRAY ref of roles")
179                 if exists $options{roles};
180
181
182         my @extra_options;
183         my $mortal;
184         my $cache_key;
185
186         if(!defined $package_name){ # anonymous
187             $mortal = !$options{cache};
188
189             # anonymous but immortal
190             if(!$mortal){
191                     # something like Super::Class|Super::Class::2=Role|Role::1
192                     $cache_key = join '=' => (
193                         join('|',      @{$options{superclasses} || []}),
194                         join('|', sort @{$options{roles}        || []}),
195                     );
196                     return $IMMORTALS{$cache_key} if exists $IMMORTALS{$cache_key};
197             }
198             $package_name = $ANON_PREFIX . ++$ANON_SERIAL;
199
200             push @extra_options, (anon_serial_id => $ANON_SERIAL);
201         }
202
203         # instantiate a module
204         {
205             no strict 'refs';
206             ${ $package_name . '::VERSION'   } = delete $options{version}   if exists $options{version};
207             ${ $package_name . '::AUTHORITY' } = delete $options{authority} if exists $options{authority};
208         }
209
210         my %initialize_options = %options;
211         delete @initialize_options{qw(
212             package
213             superclasses
214             attributes
215             methods
216             roles
217         )};
218         my $meta = $class->initialize( $package_name, %initialize_options, @extra_options);
219
220         Mouse::Meta::Module::weaken_metaclass($package_name)
221             if $mortal;
222
223         # FIXME totally lame
224         $meta->add_method('meta' => sub {
225             $class->initialize(ref($_[0]) || $_[0]);
226         });
227
228         $meta->superclasses(@{$options{superclasses}})
229             if exists $options{superclasses};
230
231         # NOTE:
232         # process attributes first, so that they can
233         # install accessors, but locally defined methods
234         # can then overwrite them. It is maybe a little odd, but
235         # I think this should be the order of things.
236         if (defined $attributes) {
237             if(ref($attributes) eq 'ARRAY'){
238                 foreach my $attr (@{$attributes}) {
239                     $meta->add_attribute($attr->{name} => $attr);
240                 }
241             }
242             else{
243                 while(my($name, $attr) = each %{$attributes}){
244                     $meta->add_attribute($name => $attr);
245                 }
246             }
247         }
248         if (exists $options{methods}) {
249             foreach my $method_name (keys %{$options{methods}}) {
250                 $meta->add_method($method_name, $options{methods}->{$method_name});
251             }
252         }
253         if (exists $options{roles}){
254             Mouse::Util::apply_all_roles($package_name, @{$options{roles}});
255         }
256
257         if(!$mortal && exists $meta->{anon_serial_id}){
258             $IMMORTALS{$cache_key} = $meta;
259         }
260
261         return $meta;
262     }
263
264     sub DESTROY{
265         my($self) = @_;
266
267         my $serial_id = $self->{anon_serial_id};
268
269         return if !$serial_id;
270
271         my $stash = $self->namespace;
272
273         @{$self->{superclasses}} = () if exists $self->{superclasses};
274         %{$stash} = ();
275         Mouse::Meta::Module::remove_metaclass_by_name($self->name);
276
277         no strict 'refs';
278         delete ${$ANON_PREFIX}{ $serial_id . '::' };
279
280         return;
281     }
282 }
283
284 sub throw_error{
285     my($class, $message, %args) = @_;
286
287     local $Carp::CarpLevel  = $Carp::CarpLevel + 1 + ($args{depth} || 0);
288     local $Carp::MaxArgNums = 20; # default is 8, usually we use named args which gets messier though
289
290     if(exists $args{longmess} && !$args{longmess}){ # intentionaly longmess => 0
291         Carp::croak($message);
292     }
293     else{
294         Carp::confess($message);
295     }
296 }
297
298 1;
299
300 __END__
301
302 =head1 NAME
303
304 Mouse::Meta::Module - Common base class for Mouse::Meta::Class and Mouse::Meta::Role
305
306 =cut
307