Added metaclass cache accessor methods (straight from Class::MOP).
[gitmo/Mouse.git] / lib / Mouse / Meta / Class.pm
1 package Mouse::Meta::Class;
2 use strict;
3 use warnings;
4
5 use Mouse::Meta::Method::Constructor;
6 use Mouse::Meta::Method::Destructor;
7 use Scalar::Util qw/blessed weaken/;
8 use Mouse::Util qw/get_linear_isa version authority identifier/;
9 use Carp 'confess';
10
11 do {
12     my %METACLASS_CACHE;
13
14     # because Mouse doesn't introspect existing classes, we're forced to
15     # only pay attention to other Mouse classes
16     sub _metaclass_cache {
17         my $class = shift;
18         my $name  = shift;
19         return $METACLASS_CACHE{$name};
20     }
21
22     sub initialize {
23         my $class = blessed($_[0]) || $_[0];
24         my $name  = $_[1];
25
26         $METACLASS_CACHE{$name} = $class->new(name => $name)
27             if !exists($METACLASS_CACHE{$name});
28         return $METACLASS_CACHE{$name};
29     }
30
31     # Means of accessing all the metaclasses that have
32     # been initialized thus far
33     sub get_all_metaclasses         {        %METACLASS_CACHE         }
34     sub get_all_metaclass_instances { values %METACLASS_CACHE         }
35     sub get_all_metaclass_names     { keys   %METACLASS_CACHE         }
36     sub get_metaclass_by_name       { $METACLASS_CACHE{$_[0]}         }
37     sub store_metaclass_by_name     { $METACLASS_CACHE{$_[0]} = $_[1] }
38     sub weaken_metaclass            { weaken($METACLASS_CACHE{$_[0]}) }
39     sub does_metaclass_exist        { exists $METACLASS_CACHE{$_[0]} && defined $METACLASS_CACHE{$_[0]} }
40     sub remove_metaclass_by_name    { $METACLASS_CACHE{$_[0]} = undef }
41 };
42
43 sub new {
44     my $class = shift;
45     my %args  = @_;
46
47     $args{attributes} = {};
48     $args{superclasses} = do {
49         no strict 'refs';
50         \@{ $args{name} . '::ISA' };
51     };
52     $args{roles} ||= [];
53
54     bless \%args, $class;
55 }
56
57 sub name { $_[0]->{name} }
58
59 sub superclasses {
60     my $self = shift;
61
62     if (@_) {
63         Mouse::load_class($_) for @_;
64         @{ $self->{superclasses} } = @_;
65     }
66
67     @{ $self->{superclasses} };
68 }
69
70 sub add_method {
71     my $self = shift;
72     my $name = shift;
73     my $code = shift;
74
75     my $pkg = $self->name;
76
77     no strict 'refs';
78     no warnings 'redefine';
79     $self->{'methods'}->{$name}++; # Moose stores meta object here.
80     *{ $pkg . '::' . $name } = $code;
81 }
82
83 sub has_method {
84     my $self = shift;
85     my $name = shift;
86     $self->name->can($name);
87 }
88
89 # copied from Class::Inspector
90 my $get_methods_for_class = sub {
91     my $self = shift;
92     my $name = shift;
93
94     no strict 'refs';
95     # Get all the CODE symbol table entries
96     my @functions =
97       grep !/^(?:has|with|around|before|after|augment|inner|blessed|extends|confess|override|super)$/,
98       grep { defined &{"${name}::$_"} }
99       keys %{"${name}::"};
100     push @functions, keys %{$self->{'methods'}->{$name}} if $self;
101     wantarray ? @functions : \@functions;
102 };
103
104 sub get_method_list {
105     my $self = shift;
106     $get_methods_for_class->($self, $self->name);
107 }
108
109 sub get_all_method_names {
110     my $self = shift;
111     my %uniq;
112     return grep { $uniq{$_}++ == 0 }
113             map { $get_methods_for_class->(undef, $_) }
114             $self->linearized_isa;
115 }
116
117 sub add_attribute {
118     my $self = shift;
119
120     if (@_ == 1 && blessed($_[0])) {
121         my $attr = shift @_;
122         $self->{'attributes'}{$attr->name} = $attr;
123     } else {
124         my $names = shift @_;
125         $names = [$names] if !ref($names);
126         my $metaclass = 'Mouse::Meta::Attribute';
127         my %options = @_;
128
129         if ( my $metaclass_name = delete $options{metaclass} ) {
130             my $new_class = Mouse::Util::resolve_metaclass_alias(
131                 'Attribute',
132                 $metaclass_name
133             );
134             if ( $metaclass ne $new_class ) {
135                 $metaclass = $new_class;
136             }
137         }
138
139         for my $name (@$names) {
140             if ($name =~ s/^\+//) {
141                 $metaclass->clone_parent($self, $name, @_);
142             }
143             else {
144                 $metaclass->create($self, $name, @_);
145             }
146         }
147     }
148 }
149
150 sub compute_all_applicable_attributes {
151     my $self = shift;
152     my (@attr, %seen);
153
154     for my $class ($self->linearized_isa) {
155         my $meta = $self->_metaclass_cache($class)
156             or next;
157
158         for my $name (keys %{ $meta->get_attribute_map }) {
159             next if $seen{$name}++;
160             push @attr, $meta->get_attribute($name);
161         }
162     }
163
164     return @attr;
165 }
166
167 sub get_attribute_map { $_[0]->{attributes} }
168 sub has_attribute     { exists $_[0]->{attributes}->{$_[1]} }
169 sub get_attribute     { $_[0]->{attributes}->{$_[1]} }
170 sub get_attribute_list {
171     my $self = shift;
172     keys %{$self->get_attribute_map};
173 }
174
175 sub linearized_isa { @{ get_linear_isa($_[0]->name) } }
176
177 sub clone_object {
178     my $class    = shift;
179     my $instance = shift;
180
181     (blessed($instance) && $instance->isa($class->name))
182         || confess "You must pass an instance of the metaclass (" . $class->name . "), not ($instance)";
183
184     $class->clone_instance($instance, @_);
185 }
186
187 sub clone_instance {
188     my ($class, $instance, %params) = @_;
189
190     (blessed($instance))
191         || confess "You can only clone instances, ($instance) is not a blessed instance";
192
193     my $clone = bless { %$instance }, ref $instance;
194
195     foreach my $attr ($class->compute_all_applicable_attributes()) {
196         if ( defined( my $init_arg = $attr->init_arg ) ) {
197             if (exists $params{$init_arg}) {
198                 $clone->{ $attr->name } = $params{$init_arg};
199             }
200         }
201     }
202
203     return $clone;
204
205 }
206
207 sub make_immutable {
208     my $self = shift;
209     my %args = (
210         inline_constructor => 1,
211         @_,
212     );
213
214     my $name = $self->name;
215     $self->{is_immutable}++;
216
217     if ($args{inline_constructor}) {
218         $self->add_method('new' => Mouse::Meta::Method::Constructor->generate_constructor_method_inline( $self ));
219     }
220
221     if ($args{inline_destructor}) {
222         $self->add_method('DESTROY' => Mouse::Meta::Method::Destructor->generate_destructor_method_inline( $self ));
223     }
224
225     # Moose's make_immutable returns true allowing calling code to skip setting an explicit true value
226     # at the end of a source file. 
227     return 1;
228 }
229
230 sub make_mutable { confess "Mouse does not currently support 'make_mutable'" }
231
232 sub is_immutable { $_[0]->{is_immutable} }
233
234 sub attribute_metaclass { "Mouse::Meta::Class" }
235
236 sub _install_modifier {
237     my ( $self, $into, $type, $name, $code ) = @_;
238
239     # which is modifer class available?
240     my $modifier_class = do {
241         if (eval "require Class::Method::Modifiers::Fast; 1") {
242             'Class::Method::Modifiers::Fast';
243         } elsif (eval "require Class::Method::Modifiers; 1") {
244             'Class::Method::Modifiers';
245         } else {
246             Carp::croak("Method modifiers require the use of Class::Method::Modifiers or Class::Method::Modifiers::Fast. Please install it from CPAN and file a bug report with this application.");
247         }
248     };
249     my $modifier = $modifier_class->can('_install_modifier');
250
251     # replace this method itself :)
252     {
253         no strict 'refs';
254         no warnings 'redefine';
255         *{__PACKAGE__ . '::_install_modifier'} = sub {
256             my ( $self, $into, $type, $name, $code ) = @_;
257             $modifier->(
258                 $into,
259                 $type,
260                 $name,
261                 $code
262             );
263         };
264     }
265
266     # call me. for first time.
267     $self->_install_modifier( $into, $type, $name, $code );
268 }
269
270 sub add_before_method_modifier {
271     my ( $self, $name, $code ) = @_;
272     $self->_install_modifier( $self->name, 'before', $name, $code );
273 }
274
275 sub add_around_method_modifier {
276     my ( $self, $name, $code ) = @_;
277     $self->_install_modifier( $self->name, 'around', $name, $code );
278 }
279
280 sub add_after_method_modifier {
281     my ( $self, $name, $code ) = @_;
282     $self->_install_modifier( $self->name, 'after', $name, $code );
283 }
284
285 sub add_override_method_modifier {
286     my ($self, $name, $code) = @_;
287
288     my $pkg = $self->name;
289     my $method = "${pkg}::${name}";
290
291     # Class::Method::Modifiers won't do this for us, so do it ourselves
292
293     my $body = $pkg->can($name)
294         or confess "You cannot override '$method' because it has no super method";
295
296     no strict 'refs';
297     *$method = sub { $code->($pkg, $body, @_) };
298 }
299
300
301 sub roles { $_[0]->{roles} }
302
303 sub does_role {
304     my ($self, $role_name) = @_;
305
306     (defined $role_name)
307         || confess "You must supply a role name to look for";
308
309     for my $class ($self->linearized_isa) {
310         next unless $class->can('meta') and $class->meta->can('roles');
311         for my $role (@{ $self->roles }) {
312             return 1 if $role->name eq $role_name;
313         }
314     }
315
316     return 0;
317 }
318
319 sub create {
320     my ($self, $package_name, %options) = @_;
321
322     (ref $options{superclasses} eq 'ARRAY')
323         || confess "You must pass an ARRAY ref of superclasses"
324             if exists $options{superclasses};
325
326     (ref $options{attributes} eq 'ARRAY')
327         || confess "You must pass an ARRAY ref of attributes"
328             if exists $options{attributes};
329
330     (ref $options{methods} eq 'HASH')
331         || confess "You must pass a HASH ref of methods"
332             if exists $options{methods};
333
334     do {
335         ( defined $package_name && $package_name )
336           || confess "You must pass a package name";
337
338         my $code = "package $package_name;";
339         $code .= "\$$package_name\:\:VERSION = '" . $options{version} . "';"
340           if exists $options{version};
341         $code .= "\$$package_name\:\:AUTHORITY = '" . $options{authority} . "';"
342           if exists $options{authority};
343
344         eval $code;
345         confess "creation of $package_name failed : $@" if $@;
346     };
347
348     my %initialize_options = %options;
349     delete @initialize_options{qw(
350         package
351         superclasses
352         attributes
353         methods
354         version
355         authority
356     )};
357     my $meta = $self->initialize( $package_name => %initialize_options );
358
359     # FIXME totally lame
360     $meta->add_method('meta' => sub {
361         $self->initialize(ref($_[0]) || $_[0]);
362     });
363
364     $meta->superclasses(@{$options{superclasses}})
365         if exists $options{superclasses};
366     # NOTE:
367     # process attributes first, so that they can
368     # install accessors, but locally defined methods
369     # can then overwrite them. It is maybe a little odd, but
370     # I think this should be the order of things.
371     if (exists $options{attributes}) {
372         foreach my $attr (@{$options{attributes}}) {
373             Mouse::Meta::Attribute->create($meta, $attr->{name}, %$attr);
374         }
375     }
376     if (exists $options{methods}) {
377         foreach my $method_name (keys %{$options{methods}}) {
378             $meta->add_method($method_name, $options{methods}->{$method_name});
379         }
380     }
381     return $meta;
382 }
383
384 {
385     my $ANON_CLASS_SERIAL = 0;
386     my $ANON_CLASS_PREFIX = 'Mouse::Meta::Class::__ANON__::SERIAL::';
387     sub create_anon_class {
388         my ( $class, %options ) = @_;
389         my $package_name = $ANON_CLASS_PREFIX . ++$ANON_CLASS_SERIAL;
390         return $class->create( $package_name, %options );
391     }
392 }
393
394 1;
395
396 __END__
397
398 =head1 NAME
399
400 Mouse::Meta::Class - hook into the Mouse MOP
401
402 =head1 METHODS
403
404 =head2 initialize ClassName -> Mouse::Meta::Class
405
406 Finds or creates a Mouse::Meta::Class instance for the given ClassName. Only
407 one instance should exist for a given class.
408
409 =head2 new %args -> Mouse::Meta::Class
410
411 Creates a new Mouse::Meta::Class. Don't call this directly.
412
413 =head2 name -> ClassName
414
415 Returns the name of the owner class.
416
417 =head2 superclasses -> [ClassName]
418
419 Gets (or sets) the list of superclasses of the owner class.
420
421 =head2 add_attribute (Mouse::Meta::Attribute| name => spec)
422
423 Begins keeping track of the existing L<Mouse::Meta::Attribute> for the owner
424 class.
425
426 =head2 compute_all_applicable_attributes -> (Mouse::Meta::Attribute)
427
428 Returns the list of all L<Mouse::Meta::Attribute> instances associated with
429 this class and its superclasses.
430
431 =head2 get_attribute_map -> { name => Mouse::Meta::Attribute }
432
433 Returns a mapping of attribute names to their corresponding
434 L<Mouse::Meta::Attribute> objects.
435
436 =head2 get_attribute_list -> { name => Mouse::Meta::Attribute }
437
438 This returns a list of attribute names which are defined in the local
439 class. If you want a list of all applicable attributes for a class,
440 use the C<compute_all_applicable_attributes> method.
441
442 =head2 has_attribute Name -> Bool
443
444 Returns whether we have a L<Mouse::Meta::Attribute> with the given name.
445
446 =head2 get_attribute Name -> Mouse::Meta::Attribute | undef
447
448 Returns the L<Mouse::Meta::Attribute> with the given name.
449
450 =head2 linearized_isa -> [ClassNames]
451
452 Returns the list of classes in method dispatch order, with duplicates removed.
453
454 =head2 clone_object Instance -> Instance
455
456 Clones the given C<Instance> which must be an instance governed by this
457 metaclass.
458
459 =head2 clone_instance Instance, Parameters -> Instance
460
461 Clones the given C<Instance> and sets any additional parameters.
462
463 =cut
464