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