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