Cleanup
[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/:meta get_code_package not_supported load_class/;
9
10
11 my %METAS;
12
13 sub _metaclass_cache { # DEPRECATED
14     my($class, $name) = @_;
15     return $METAS{$name};
16 }
17
18 sub initialize {
19     my($class, $package_name, @args) = @_;
20
21     ($package_name && !ref($package_name))
22         || $class->throw_error("You must pass a package name and it cannot be blessed");
23
24     return $METAS{$package_name}
25         ||= $class->_construct_meta(package => $package_name, @args);
26 }
27
28 sub class_of{
29     my($class_or_instance) = @_;
30     return undef unless defined $class_or_instance;
31     return $METAS{ ref($class_or_instance) || $class_or_instance };
32 }
33
34 # Means of accessing all the metaclasses that have
35 # been initialized thus far
36 #sub get_all_metaclasses         {        %METAS         }
37 sub get_all_metaclass_instances { values %METAS         }
38 sub get_all_metaclass_names     { keys   %METAS         }
39 sub get_metaclass_by_name       { $METAS{$_[0]}         }
40 #sub store_metaclass_by_name     { $METAS{$_[0]} = $_[1] }
41 #sub weaken_metaclass            { weaken($METAS{$_[0]}) }
42 #sub does_metaclass_exist        { defined $METAS{$_[0]} }
43 #sub remove_metaclass_by_name    { delete $METAS{$_[0]}  }
44
45
46
47 sub name { $_[0]->{package} }
48
49 # The followings are Class::MOP specific methods
50
51 #sub version   { no strict 'refs'; ${shift->name.'::VERSION'}   }
52 #sub authority { no strict 'refs'; ${shift->name.'::AUTHORITY'} }
53 #sub identifier {
54 #    my $self = shift;
55 #    return join '-' => (
56 #       $self->name,
57 #        ($self->version   || ()),
58 #        ($self->authority || ()),
59 #    );
60 #}
61
62 # add_attribute is an abstract method
63
64 sub get_attribute_map { # DEPRECATED
65     Carp::cluck('get_attribute_map() has been deprecated');
66     return $_[0]->{attributes};
67 }
68
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 # XXX: for backward compatibility
103 my %foreign = map{ $_ => undef } qw(
104     Mouse Mouse::Role Mouse::Util Mouse::Util::TypeConstraints
105     Carp Scalar::Util
106 );
107 sub _code_is_mine{
108     my($self, $code) = @_;
109
110     my $package = get_code_package($code);
111
112     return !exists $foreign{$package};
113 }
114
115 sub has_method {
116     my($self, $method_name) = @_;
117
118     return 1 if $self->{methods}->{$method_name};
119
120     my $code = do{ no strict 'refs'; *{$self->{package} . '::' . $method_name}{CODE} };
121
122     return $code && $self->_code_is_mine($code);
123 }
124
125 sub get_method{
126     my($self, $method_name) = @_;
127
128     if($self->has_method($method_name)){
129         my $method_metaclass = $self->method_metaclass;
130         load_class($method_metaclass);
131
132         my $package = $self->name;
133         return $method_metaclass->new(
134             body    => $package->can($method_name),
135             name    => $method_name,
136             package => $package,
137         );
138     }
139
140     return undef;
141 }
142
143 sub get_method_list {
144     my($self) = @_;
145
146     return grep { $self->has_method($_) } keys %{ $self->namespace };
147 }
148
149 {
150     my $ANON_SERIAL = 0;
151
152     my %IMMORTALS;
153
154     sub create {
155         my($class, $package_name, %options) = @_;
156
157         $class->throw_error('You must pass a package name') if @_ < 2;
158
159         my $superclasses;
160         if(exists $options{superclasses}){
161             if($class->isa('Mouse::Meta::Role')){
162                 delete $options{superclasses};
163             }
164             else{
165                 $superclasses = delete $options{superclasses};
166                 (ref $superclasses eq 'ARRAY')
167                     || $class->throw_error("You must pass an ARRAY ref of superclasses");
168             }
169         }
170
171         my $attributes = delete $options{attributes};
172         if(defined $attributes){
173             (ref $attributes eq 'ARRAY' || ref $attributes eq 'HASH')
174                 || $class->throw_error("You must pass an ARRAY ref of attributes");
175         }
176         my $methods = delete $options{methods};
177         if(defined $methods){
178             (ref $methods eq 'HASH')
179                 || $class->throw_error("You must pass a HASH ref of methods");
180         }
181         my $roles = delete $options{roles};
182         if(defined $roles){
183             (ref $roles eq 'ARRAY')
184                 || $class->throw_error("You must pass an ARRAY ref of roles");
185         }
186         my $mortal;
187         my $cache_key;
188
189         if(!defined $package_name){ # anonymous
190             $mortal = !$options{cache};
191
192             # anonymous but immortal
193             if(!$mortal){
194                     # something like Super::Class|Super::Class::2=Role|Role::1
195                     $cache_key = join '=' => (
196                         join('|',      @{$superclasses || []}),
197                         join('|', sort @{$roles        || []}),
198                     );
199                     return $IMMORTALS{$cache_key} if exists $IMMORTALS{$cache_key};
200             }
201             $options{anon_serial_id} = ++$ANON_SERIAL;
202             $package_name = $class . '::__ANON__::' . $ANON_SERIAL;
203         }
204
205         # instantiate a module
206         {
207             no strict 'refs';
208             ${ $package_name . '::VERSION'   } = delete $options{version}   if exists $options{version};
209             ${ $package_name . '::AUTHORITY' } = delete $options{authority} if exists $options{authority};
210         }
211
212         my $meta = $class->initialize( $package_name, %options);
213
214         weaken $METAS{$package_name}
215             if $mortal;
216
217         # FIXME totally lame
218         $meta->add_method('meta' => sub {
219             $class->initialize(ref($_[0]) || $_[0]);
220         });
221
222         $meta->superclasses(@{$superclasses})
223             if defined $superclasses;
224
225         # NOTE:
226         # process attributes first, so that they can
227         # install accessors, but locally defined methods
228         # can then overwrite them. It is maybe a little odd, but
229         # I think this should be the order of things.
230         if (defined $attributes) {
231             if(ref($attributes) eq 'ARRAY'){
232                 # array of Mouse::Meta::Attribute
233                 foreach my $attr (@{$attributes}) {
234                     $meta->add_attribute($attr);
235                 }
236             }
237             else{
238                 # hash map of name and attribute spec pairs
239                 while(my($name, $attr) = each %{$attributes}){
240                     $meta->add_attribute($name => $attr);
241                 }
242             }
243         }
244         if (defined $methods) {
245             while(my($method_name, $method_body) = each %{$methods}){
246                 $meta->add_method($method_name, $method_body);
247             }
248         }
249         if (defined $roles){
250             Mouse::Util::apply_all_roles($package_name, @{$roles});
251         }
252
253         if($cache_key){
254             $IMMORTALS{$cache_key} = $meta;
255         }
256
257         return $meta;
258     }
259
260     sub DESTROY{
261         my($self) = @_;
262
263         my $serial_id = $self->{anon_serial_id};
264
265         return if !$serial_id;
266
267         # @ISA is a magical variable, so we clear it manually.
268         @{$self->{superclasses}} = () if exists $self->{superclasses};
269
270         # Then, clear the symbol table hash
271         %{$self->namespace} = ();
272
273         my $name = $self->name;
274         delete $METAS{$name};
275
276         $name =~ s/ $serial_id \z//xms;
277
278         no strict 'refs';
279         delete ${$name}{ $serial_id . '::' };
280
281         return;
282     }
283 }
284
285 sub throw_error{
286     my($class, $message, %args) = @_;
287
288     local $Carp::CarpLevel  = $Carp::CarpLevel + 1 + ($args{depth} || 0);
289     local $Carp::MaxArgNums = 20; # default is 8, usually we use named args which gets messier though
290
291     if(exists $args{longmess} && !$args{longmess}){ # intentionaly longmess => 0
292         Carp::croak($message);
293     }
294     else{
295         Carp::confess($message);
296     }
297 }
298
299 1;
300
301 __END__
302
303 =head1 NAME
304
305 Mouse::Meta::Module - The base class for Mouse::Meta::Class and Mouse::Meta::Role
306
307 =head1 SEE ALSO
308
309 L<Class::MOP::Class>
310
311 L<Class::MOP::Module>
312
313 L<Class::MOP::Package>
314
315 =cut
316