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