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