latest moose inlining destructor by default
[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 { shift->get_all_attributes(@_) }
151 sub get_all_attributes {
152     my $self = shift;
153     my (@attr, %seen);
154
155     for my $class ($self->linearized_isa) {
156         my $meta = $self->_metaclass_cache($class)
157             or next;
158
159         for my $name (keys %{ $meta->get_attribute_map }) {
160             next if $seen{$name}++;
161             push @attr, $meta->get_attribute($name);
162         }
163     }
164
165     return @attr;
166 }
167
168 sub get_attribute_map { $_[0]->{attributes} }
169 sub has_attribute     { exists $_[0]->{attributes}->{$_[1]} }
170 sub get_attribute     { $_[0]->{attributes}->{$_[1]} }
171 sub get_attribute_list {
172     my $self = shift;
173     keys %{$self->get_attribute_map};
174 }
175
176 sub linearized_isa { @{ get_linear_isa($_[0]->name) } }
177
178 sub clone_object {
179     my $class    = shift;
180     my $instance = shift;
181
182     (blessed($instance) && $instance->isa($class->name))
183         || confess "You must pass an instance of the metaclass (" . $class->name . "), not ($instance)";
184
185     $class->clone_instance($instance, @_);
186 }
187
188 sub clone_instance {
189     my ($class, $instance, %params) = @_;
190
191     (blessed($instance))
192         || confess "You can only clone instances, ($instance) is not a blessed instance";
193
194     my $clone = bless { %$instance }, ref $instance;
195
196     foreach my $attr ($class->get_all_attributes()) {
197         if ( defined( my $init_arg = $attr->init_arg ) ) {
198             if (exists $params{$init_arg}) {
199                 $clone->{ $attr->name } = $params{$init_arg};
200             }
201         }
202     }
203
204     return $clone;
205
206 }
207
208 sub make_immutable {
209     my $self = shift;
210     my %args = (
211         inline_constructor => 1,
212         inline_destructor  => 1,
213         @_,
214     );
215
216     my $name = $self->name;
217     $self->{is_immutable}++;
218
219     if ($args{inline_constructor}) {
220         $self->add_method('new' => Mouse::Meta::Method::Constructor->generate_constructor_method_inline( $self ));
221     }
222
223     if ($args{inline_destructor}) {
224         $self->add_method('DESTROY' => Mouse::Meta::Method::Destructor->generate_destructor_method_inline( $self ));
225     }
226
227     # Moose's make_immutable returns true allowing calling code to skip setting an explicit true value
228     # at the end of a source file. 
229     return 1;
230 }
231
232 sub make_mutable { confess "Mouse does not currently support 'make_mutable'" }
233
234 sub is_immutable { $_[0]->{is_immutable} }
235
236 sub attribute_metaclass { "Mouse::Meta::Class" }
237
238 sub _install_modifier {
239     my ( $self, $into, $type, $name, $code ) = @_;
240
241     # which is modifer class available?
242     my $modifier_class = do {
243         if (eval "require Class::Method::Modifiers::Fast; 1") {
244             'Class::Method::Modifiers::Fast';
245         } elsif (eval "require Class::Method::Modifiers; 1") {
246             'Class::Method::Modifiers';
247         } else {
248             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.");
249         }
250     };
251     my $modifier = $modifier_class->can('_install_modifier');
252
253     # replace this method itself :)
254     {
255         no strict 'refs';
256         no warnings 'redefine';
257         *{__PACKAGE__ . '::_install_modifier'} = sub {
258             my ( $self, $into, $type, $name, $code ) = @_;
259             $modifier->(
260                 $into,
261                 $type,
262                 $name,
263                 $code
264             );
265         };
266     }
267
268     # call me. for first time.
269     $self->_install_modifier( $into, $type, $name, $code );
270 }
271
272 sub add_before_method_modifier {
273     my ( $self, $name, $code ) = @_;
274     $self->_install_modifier( $self->name, 'before', $name, $code );
275 }
276
277 sub add_around_method_modifier {
278     my ( $self, $name, $code ) = @_;
279     $self->_install_modifier( $self->name, 'around', $name, $code );
280 }
281
282 sub add_after_method_modifier {
283     my ( $self, $name, $code ) = @_;
284     $self->_install_modifier( $self->name, 'after', $name, $code );
285 }
286
287 sub add_override_method_modifier {
288     my ($self, $name, $code) = @_;
289
290     my $pkg = $self->name;
291     my $method = "${pkg}::${name}";
292
293     # Class::Method::Modifiers won't do this for us, so do it ourselves
294
295     my $body = $pkg->can($name)
296         or confess "You cannot override '$method' because it has no super method";
297
298     no strict 'refs';
299     *$method = sub { $code->($pkg, $body, @_) };
300 }
301
302
303 sub roles { $_[0]->{roles} }
304
305 sub does_role {
306     my ($self, $role_name) = @_;
307
308     (defined $role_name)
309         || confess "You must supply a role name to look for";
310
311     for my $class ($self->linearized_isa) {
312         next unless $class->can('meta') and $class->meta->can('roles');
313         for my $role (@{ $class->meta->roles }) {
314             return 1 if $role->name eq $role_name;
315         }
316     }
317
318     return 0;
319 }
320
321 sub create {
322     my ($self, $package_name, %options) = @_;
323
324     (ref $options{superclasses} eq 'ARRAY')
325         || confess "You must pass an ARRAY ref of superclasses"
326             if exists $options{superclasses};
327
328     (ref $options{attributes} eq 'ARRAY')
329         || confess "You must pass an ARRAY ref of attributes"
330             if exists $options{attributes};
331
332     (ref $options{methods} eq 'HASH')
333         || confess "You must pass a HASH ref of methods"
334             if exists $options{methods};
335
336     do {
337         ( defined $package_name && $package_name )
338           || confess "You must pass a package name";
339
340         my $code = "package $package_name;";
341         $code .= "\$$package_name\:\:VERSION = '" . $options{version} . "';"
342           if exists $options{version};
343         $code .= "\$$package_name\:\:AUTHORITY = '" . $options{authority} . "';"
344           if exists $options{authority};
345
346         eval $code;
347         confess "creation of $package_name failed : $@" if $@;
348     };
349
350     my %initialize_options = %options;
351     delete @initialize_options{qw(
352         package
353         superclasses
354         attributes
355         methods
356         version
357         authority
358     )};
359     my $meta = $self->initialize( $package_name => %initialize_options );
360
361     # FIXME totally lame
362     $meta->add_method('meta' => sub {
363         $self->initialize(ref($_[0]) || $_[0]);
364     });
365
366     $meta->superclasses(@{$options{superclasses}})
367         if exists $options{superclasses};
368     # NOTE:
369     # process attributes first, so that they can
370     # install accessors, but locally defined methods
371     # can then overwrite them. It is maybe a little odd, but
372     # I think this should be the order of things.
373     if (exists $options{attributes}) {
374         foreach my $attr (@{$options{attributes}}) {
375             Mouse::Meta::Attribute->create($meta, $attr->{name}, %$attr);
376         }
377     }
378     if (exists $options{methods}) {
379         foreach my $method_name (keys %{$options{methods}}) {
380             $meta->add_method($method_name, $options{methods}->{$method_name});
381         }
382     }
383     return $meta;
384 }
385
386 {
387     my $ANON_CLASS_SERIAL = 0;
388     my $ANON_CLASS_PREFIX = 'Mouse::Meta::Class::__ANON__::SERIAL::';
389     sub create_anon_class {
390         my ( $class, %options ) = @_;
391         my $package_name = $ANON_CLASS_PREFIX . ++$ANON_CLASS_SERIAL;
392         return $class->create( $package_name, %options );
393     }
394 }
395
396 1;
397
398 __END__
399
400 =head1 NAME
401
402 Mouse::Meta::Class - hook into the Mouse MOP
403
404 =head1 METHODS
405
406 =head2 initialize ClassName -> Mouse::Meta::Class
407
408 Finds or creates a Mouse::Meta::Class instance for the given ClassName. Only
409 one instance should exist for a given class.
410
411 =head2 new %args -> Mouse::Meta::Class
412
413 Creates a new Mouse::Meta::Class. Don't call this directly.
414
415 =head2 name -> ClassName
416
417 Returns the name of the owner class.
418
419 =head2 superclasses -> [ClassName]
420
421 Gets (or sets) the list of superclasses of the owner class.
422
423 =head2 add_attribute (Mouse::Meta::Attribute| name => spec)
424
425 Begins keeping track of the existing L<Mouse::Meta::Attribute> for the owner
426 class.
427
428 =head2 get_all_attributes -> (Mouse::Meta::Attribute)
429
430 Returns the list of all L<Mouse::Meta::Attribute> instances associated with
431 this class and its superclasses.
432
433 =head2 get_attribute_map -> { name => Mouse::Meta::Attribute }
434
435 Returns a mapping of attribute names to their corresponding
436 L<Mouse::Meta::Attribute> objects.
437
438 =head2 get_attribute_list -> { name => Mouse::Meta::Attribute }
439
440 This returns a list of attribute names which are defined in the local
441 class. If you want a list of all applicable attributes for a class,
442 use the C<get_all_attributes> method.
443
444 =head2 has_attribute Name -> Bool
445
446 Returns whether we have a L<Mouse::Meta::Attribute> with the given name.
447
448 =head2 get_attribute Name -> Mouse::Meta::Attribute | undef
449
450 Returns the L<Mouse::Meta::Attribute> with the given name.
451
452 =head2 linearized_isa -> [ClassNames]
453
454 Returns the list of classes in method dispatch order, with duplicates removed.
455
456 =head2 clone_object Instance -> Instance
457
458 Clones the given C<Instance> which must be an instance governed by this
459 metaclass.
460
461 =head2 clone_instance Instance, Parameters -> Instance
462
463 The clone_instance method has been made private.
464 The public version is deprecated.
465
466 =cut
467