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