3069250c9ea82985882bb9be69eda2abaef5a2bd
[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
42
43 sub name { $_[0]->{package} }
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 namespace{
71     my $name = $_[0]->{package};
72     no strict 'refs';
73     return \%{ $name . '::' };
74 }
75
76 sub add_method {
77     my($self, $name, $code) = @_;
78
79     if(!defined $name){
80         $self->throw_error('You must pass a defined name');
81     }
82     if(!defined $code){
83         $self->throw_error('You must pass a defined code');
84     }
85
86     if(ref($code) ne 'CODE'){
87         $code = \&{$code}; # coerce
88     }
89
90     $self->{methods}->{$name} = $code; # Moose stores meta object here.
91
92     my $pkg = $self->name;
93     no strict 'refs';
94     no warnings 'redefine';
95     *{ $pkg . '::' . $name } = $code;
96 }
97
98 # XXX: for backward compatibility
99 my %foreign = map{ $_ => undef } qw(
100     Mouse Mouse::Role Mouse::Util Mouse::Util::TypeConstraints
101     Carp Scalar::Util
102 );
103 sub _code_is_mine{
104     my($self, $code) = @_;
105
106     my $package = get_code_package($code);
107
108     return !exists $foreign{$package};
109 }
110
111 sub has_method {
112     my($self, $method_name) = @_;
113
114     defined($method_name)
115         or $self->throw_error('You must define a method name');
116
117     return 1 if $self->{methods}->{$method_name};
118
119     my $code = do{ no strict 'refs'; *{$self->{package} . '::' . $method_name}{CODE} };
120
121     return $code && $self->_code_is_mine($code);
122 }
123
124 sub get_method_body{
125     my($self, $method_name) = @_;
126
127     defined($method_name)
128         or $self->throw_error('You must define a method name');
129
130     return $self->{methods}{$method_name} ||= do{
131         my $code = do{ no strict 'refs'; *{$self->{package} . '::' . $method_name}{CODE} };
132
133         $code && $self->_code_is_mine($code) && $code;
134     };
135 }
136
137 sub get_method{
138     my($self, $method_name) = @_;
139
140     if($self->has_method($method_name)){
141         my $method_metaclass = $self->method_metaclass;
142         load_class($method_metaclass);
143
144         my $package = $self->name;
145         return $method_metaclass->new(
146             body    => $package->can($method_name),
147             name    => $method_name,
148             package => $package,
149         );
150     }
151
152     return undef;
153 }
154
155 sub get_method_list {
156     my($self) = @_;
157
158     return grep { $self->has_method($_) } keys %{ $self->namespace };
159 }
160
161 {
162     my $ANON_SERIAL = 0;
163
164     my %IMMORTALS;
165
166     sub create {
167         my($self, $package_name, %options) = @_;
168
169         my $class = ref($self) || $self;
170         $self->throw_error('You must pass a package name') if @_ < 2;
171
172         my $superclasses;
173         if(exists $options{superclasses}){
174             if($self->isa('Mouse::Meta::Role')){
175                 delete $options{superclasses};
176             }
177             else{
178                 $superclasses = delete $options{superclasses};
179                 (ref $superclasses eq 'ARRAY')
180                     || $self->throw_error("You must pass an ARRAY ref of superclasses");
181             }
182         }
183
184         my $attributes = delete $options{attributes};
185         if(defined $attributes){
186             (ref $attributes eq 'ARRAY' || ref $attributes eq 'HASH')
187                 || $self->throw_error("You must pass an ARRAY ref of attributes");
188         }
189         my $methods = delete $options{methods};
190         if(defined $methods){
191             (ref $methods eq 'HASH')
192                 || $self->throw_error("You must pass a HASH ref of methods");
193         }
194         my $roles = delete $options{roles};
195         if(defined $roles){
196             (ref $roles eq 'ARRAY')
197                 || $self->throw_error("You must pass an ARRAY ref of roles");
198         }
199         my $mortal;
200         my $cache_key;
201
202         if(!defined $package_name){ # anonymous
203             $mortal = !$options{cache};
204
205             # anonymous but immortal
206             if(!$mortal){
207                     # something like Super::Class|Super::Class::2=Role|Role::1
208                     $cache_key = join '=' => (
209                         join('|',      @{$superclasses || []}),
210                         join('|', sort @{$roles        || []}),
211                     );
212                     return $IMMORTALS{$cache_key} if exists $IMMORTALS{$cache_key};
213             }
214             $options{anon_serial_id} = ++$ANON_SERIAL;
215             $package_name = $class . '::__ANON__::' . $ANON_SERIAL;
216         }
217
218         # instantiate a module
219         {
220             no strict 'refs';
221             ${ $package_name . '::VERSION'   } = delete $options{version}   if exists $options{version};
222             ${ $package_name . '::AUTHORITY' } = delete $options{authority} if exists $options{authority};
223         }
224
225         my $meta = $self->initialize( $package_name, %options);
226
227         weaken $METAS{$package_name}
228             if $mortal;
229
230         $meta->add_method(meta => sub{
231             $self->initialize(ref($_[0]) || $_[0]);
232         });
233
234         $meta->superclasses(@{$superclasses})
235             if defined $superclasses;
236
237         # NOTE:
238         # process attributes first, so that they can
239         # install accessors, but locally defined methods
240         # can then overwrite them. It is maybe a little odd, but
241         # I think this should be the order of things.
242         if (defined $attributes) {
243             if(ref($attributes) eq 'ARRAY'){
244                 # array of Mouse::Meta::Attribute
245                 foreach my $attr (@{$attributes}) {
246                     $meta->add_attribute($attr);
247                 }
248             }
249             else{
250                 # hash map of name and attribute spec pairs
251                 while(my($name, $attr) = each %{$attributes}){
252                     $meta->add_attribute($name => $attr);
253                 }
254             }
255         }
256         if (defined $methods) {
257             while(my($method_name, $method_body) = each %{$methods}){
258                 $meta->add_method($method_name, $method_body);
259             }
260         }
261         if (defined $roles){
262             Mouse::Util::apply_all_roles($package_name, @{$roles});
263         }
264
265         if($cache_key){
266             $IMMORTALS{$cache_key} = $meta;
267         }
268
269         return $meta;
270     }
271
272     sub DESTROY{
273         my($self) = @_;
274
275         my $serial_id = $self->{anon_serial_id};
276
277         return if !$serial_id;
278
279         # @ISA is a magical variable, so we clear it manually.
280         @{$self->{superclasses}} = () if exists $self->{superclasses};
281
282         # Then, clear the symbol table hash
283         %{$self->namespace} = ();
284
285         my $name = $self->name;
286         delete $METAS{$name};
287
288         $name =~ s/ $serial_id \z//xms;
289
290         no strict 'refs';
291         delete ${$name}{ $serial_id . '::' };
292
293         return;
294     }
295 }
296
297 sub throw_error{
298     my($class, $message, %args) = @_;
299
300     local $Carp::CarpLevel  = $Carp::CarpLevel + 1 + ($args{depth} || 0);
301     local $Carp::MaxArgNums = 20; # default is 8, usually we use named args which gets messier though
302
303     if(exists $args{longmess} && !$args{longmess}){ # intentionaly longmess => 0
304         Carp::croak($message);
305     }
306     else{
307         Carp::confess($message);
308     }
309 }
310
311 1;
312
313 __END__
314
315 =head1 NAME
316
317 Mouse::Meta::Module - The base class for Mouse::Meta::Class and Mouse::Meta::Role
318
319 =head1 SEE ALSO
320
321 L<Class::MOP::Class>
322
323 L<Class::MOP::Module>
324
325 L<Class::MOP::Package>
326
327 =cut
328