add_method() accepts method objects
[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/:meta get_code_package not_supported load_class/;
9
10
11 my %METAS;
12
13 sub _metaclass_cache { # DEPRECATED
14     my($class, $name) = @_;
15     return $METAS{$name};
16 }
17
18 sub initialize {
19     my($class, $package_name, @args) = @_;
20
21     ($package_name && !ref($package_name))
22         || $class->throw_error("You must pass a package name and it cannot be blessed");
23
24     return $METAS{$package_name}
25         ||= $class->_construct_meta(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 $METAS{ ref($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         {        %METAS         }
37 sub get_all_metaclass_instances { values %METAS         }
38 sub get_all_metaclass_names     { keys   %METAS         }
39 sub get_metaclass_by_name       { $METAS{$_[0]}         }
40 #sub store_metaclass_by_name     { $METAS{$_[0]} = $_[1] }
41 #sub weaken_metaclass            { weaken($METAS{$_[0]}) }
42 #sub does_metaclass_exist        { defined $METAS{$_[0]} }
43 #sub remove_metaclass_by_name    { delete $METAS{$_[0]}  }
44
45
46
47 sub name { $_[0]->{package} }
48
49 # The followings are Class::MOP specific methods
50
51 #sub version   { no strict 'refs'; ${shift->name.'::VERSION'}   }
52 #sub authority { no strict 'refs'; ${shift->name.'::AUTHORITY'} }
53 #sub identifier {
54 #    my $self = shift;
55 #    return join '-' => (
56 #       $self->name,
57 #        ($self->version   || ()),
58 #        ($self->authority || ()),
59 #    );
60 #}
61
62 # add_attribute is an abstract method
63
64 sub get_attribute_map { # DEPRECATED
65     Carp::cluck('get_attribute_map() has been deprecated');
66     return $_[0]->{attributes};
67 }
68
69 sub has_attribute     { exists $_[0]->{attributes}->{$_[1]} }
70 sub get_attribute     {        $_[0]->{attributes}->{$_[1]} }
71 sub get_attribute_list{ keys %{$_[0]->{attributes}}         }
72 sub remove_attribute  { delete $_[0]->{attributes}->{$_[1]} }
73
74 sub namespace{
75     my $name = $_[0]->{package};
76     no strict 'refs';
77     return \%{ $name . '::' };
78 }
79
80 sub add_method {
81     my($self, $name, $code) = @_;
82
83     if(!defined $name){
84         $self->throw_error('You must pass a defined name');
85     }
86     if(!defined $code){
87         $self->throw_error('You must pass a defined code');
88     }
89
90     if(ref($code) ne 'CODE'){
91         $code = \&{$code}; # coerce
92     }
93
94     $self->{methods}->{$name}++; # Moose stores meta object here.
95
96     my $pkg = $self->name;
97     no strict 'refs';
98     no warnings 'redefine';
99     *{ $pkg . '::' . $name } = $code;
100 }
101
102 # XXX: for backward compatibility
103 my %foreign = map{ $_ => undef } qw(
104     Mouse Mouse::Role Mouse::Util Mouse::Util::TypeConstraints
105     Carp Scalar::Util
106 );
107 sub _code_is_mine{
108     my($self, $code) = @_;
109
110     my $package = get_code_package($code);
111
112     return !exists $foreign{$package};
113 }
114
115 sub has_method {
116     my($self, $method_name) = @_;
117
118     defined($method_name)
119         or $self->throw_error('You must define a method name');
120
121     return 1 if $self->{methods}->{$method_name};
122
123     my $code = do{ no strict 'refs'; *{$self->{package} . '::' . $method_name}{CODE} };
124
125     return $code && $self->_code_is_mine($code);
126 }
127
128 sub get_method{
129     my($self, $method_name) = @_;
130
131     if($self->has_method($method_name)){
132         my $method_metaclass = $self->method_metaclass;
133         load_class($method_metaclass);
134
135         my $package = $self->name;
136         return $method_metaclass->new(
137             body    => $package->can($method_name),
138             name    => $method_name,
139             package => $package,
140         );
141     }
142
143     return undef;
144 }
145
146 sub get_method_list {
147     my($self) = @_;
148
149     return grep { $self->has_method($_) } keys %{ $self->namespace };
150 }
151
152 {
153     my $ANON_SERIAL = 0;
154
155     my %IMMORTALS;
156
157     sub create {
158         my($self, $package_name, %options) = @_;
159
160         my $class = ref($self) || $self;
161         $self->throw_error('You must pass a package name') if @_ < 2;
162
163         my $superclasses;
164         if(exists $options{superclasses}){
165             if($self->isa('Mouse::Meta::Role')){
166                 delete $options{superclasses};
167             }
168             else{
169                 $superclasses = delete $options{superclasses};
170                 (ref $superclasses eq 'ARRAY')
171                     || $self->throw_error("You must pass an ARRAY ref of superclasses");
172             }
173         }
174
175         my $attributes = delete $options{attributes};
176         if(defined $attributes){
177             (ref $attributes eq 'ARRAY' || ref $attributes eq 'HASH')
178                 || $self->throw_error("You must pass an ARRAY ref of attributes");
179         }
180         my $methods = delete $options{methods};
181         if(defined $methods){
182             (ref $methods eq 'HASH')
183                 || $self->throw_error("You must pass a HASH ref of methods");
184         }
185         my $roles = delete $options{roles};
186         if(defined $roles){
187             (ref $roles eq 'ARRAY')
188                 || $self->throw_error("You must pass an ARRAY ref of roles");
189         }
190         my $mortal;
191         my $cache_key;
192
193         if(!defined $package_name){ # anonymous
194             $mortal = !$options{cache};
195
196             # anonymous but immortal
197             if(!$mortal){
198                     # something like Super::Class|Super::Class::2=Role|Role::1
199                     $cache_key = join '=' => (
200                         join('|',      @{$superclasses || []}),
201                         join('|', sort @{$roles        || []}),
202                     );
203                     return $IMMORTALS{$cache_key} if exists $IMMORTALS{$cache_key};
204             }
205             $options{anon_serial_id} = ++$ANON_SERIAL;
206             $package_name = $class . '::__ANON__::' . $ANON_SERIAL;
207         }
208
209         # instantiate a module
210         {
211             no strict 'refs';
212             ${ $package_name . '::VERSION'   } = delete $options{version}   if exists $options{version};
213             ${ $package_name . '::AUTHORITY' } = delete $options{authority} if exists $options{authority};
214         }
215
216         my $meta = $self->initialize( $package_name, %options);
217
218         weaken $METAS{$package_name}
219             if $mortal;
220
221         $meta->add_method(meta => sub{
222             $self->initialize(ref($_[0]) || $_[0]);
223         });
224
225         $meta->superclasses(@{$superclasses})
226             if defined $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                 # array of Mouse::Meta::Attribute
236                 foreach my $attr (@{$attributes}) {
237                     $meta->add_attribute($attr);
238                 }
239             }
240             else{
241                 # hash map of name and attribute spec pairs
242                 while(my($name, $attr) = each %{$attributes}){
243                     $meta->add_attribute($name => $attr);
244                 }
245             }
246         }
247         if (defined $methods) {
248             while(my($method_name, $method_body) = each %{$methods}){
249                 $meta->add_method($method_name, $method_body);
250             }
251         }
252         if (defined $roles){
253             Mouse::Util::apply_all_roles($package_name, @{$roles});
254         }
255
256         if($cache_key){
257             $IMMORTALS{$cache_key} = $meta;
258         }
259
260         return $meta;
261     }
262
263     sub DESTROY{
264         my($self) = @_;
265
266         my $serial_id = $self->{anon_serial_id};
267
268         return if !$serial_id;
269
270         # @ISA is a magical variable, so we clear it manually.
271         @{$self->{superclasses}} = () if exists $self->{superclasses};
272
273         # Then, clear the symbol table hash
274         %{$self->namespace} = ();
275
276         my $name = $self->name;
277         delete $METAS{$name};
278
279         $name =~ s/ $serial_id \z//xms;
280
281         no strict 'refs';
282         delete ${$name}{ $serial_id . '::' };
283
284         return;
285     }
286 }
287
288 sub throw_error{
289     my($class, $message, %args) = @_;
290
291     local $Carp::CarpLevel  = $Carp::CarpLevel + 1 + ($args{depth} || 0);
292     local $Carp::MaxArgNums = 20; # default is 8, usually we use named args which gets messier though
293
294     if(exists $args{longmess} && !$args{longmess}){ # intentionaly longmess => 0
295         Carp::croak($message);
296     }
297     else{
298         Carp::confess($message);
299     }
300 }
301
302 1;
303
304 __END__
305
306 =head1 NAME
307
308 Mouse::Meta::Module - The base class for Mouse::Meta::Class and Mouse::Meta::Role
309
310 =head1 SEE ALSO
311
312 L<Class::MOP::Class>
313
314 L<Class::MOP::Module>
315
316 L<Class::MOP::Package>
317
318 =cut
319