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