93b37ee92d7f2735aa501d219f038c74cf28e723
[gitmo/Moose.git] / lib / Moose / Meta / Class.pm
1
2 package Moose::Meta::Class;
3
4 use strict;
5 use warnings;
6
7 use Class::MOP;
8
9 use Carp         'confess';
10 use Scalar::Util 'weaken', 'blessed';
11
12 our $VERSION   = '0.56';
13 our $AUTHORITY = 'cpan:STEVAN';
14
15 use Moose::Meta::Method::Overriden;
16 use Moose::Meta::Method::Augmented;
17
18 use base 'Class::MOP::Class';
19
20 __PACKAGE__->meta->add_attribute('roles' => (
21     reader  => 'roles',
22     default => sub { [] }
23 ));
24
25 sub initialize {
26     my $class = shift;
27     my $pkg   = shift;
28     return Class::MOP::get_metaclass_by_name($pkg) 
29         || $class->SUPER::initialize($pkg,
30                 'attribute_metaclass' => 'Moose::Meta::Attribute',
31                 'method_metaclass'    => 'Moose::Meta::Method',
32                 'instance_metaclass'  => 'Moose::Meta::Instance',
33                 @_
34             );    
35 }
36
37 sub create {
38     my ($self, $package_name, %options) = @_;
39     
40     (ref $options{roles} eq 'ARRAY')
41         || confess "You must pass an ARRAY ref of roles"
42             if exists $options{roles};
43     
44     my $class = $self->SUPER::create($package_name, %options);
45     
46     if (exists $options{roles}) {
47         Moose::Util::apply_all_roles($class, @{$options{roles}});
48     }
49     
50     return $class;
51 }
52
53 my %ANON_CLASSES;
54
55 sub create_anon_class {
56     my ($self, %options) = @_;
57
58     my $cache_ok = delete $options{cache};
59     
60     # something like Super::Class|Super::Class::2=Role|Role::1
61     my $cache_key = join '=' => (
62         join('|', sort @{$options{superclasses} || []}),
63         join('|', sort @{$options{roles}        || []}),
64     );
65     
66     if ($cache_ok && defined $ANON_CLASSES{$cache_key}) {
67         return $ANON_CLASSES{$cache_key};
68     }
69     
70     my $new_class = $self->SUPER::create_anon_class(%options);
71
72     $ANON_CLASSES{$cache_key} = $new_class
73         if $cache_ok;
74
75     return $new_class;
76 }
77
78 sub add_role {
79     my ($self, $role) = @_;
80     (blessed($role) && $role->isa('Moose::Meta::Role'))
81         || confess "Roles must be instances of Moose::Meta::Role";
82     push @{$self->roles} => $role;
83 }
84
85 sub calculate_all_roles {
86     my $self = shift;
87     my %seen;
88     grep { !$seen{$_->name}++ } map { $_->calculate_all_roles } @{ $self->roles };
89 }
90
91 sub does_role {
92     my ($self, $role_name) = @_;
93     (defined $role_name)
94         || confess "You must supply a role name to look for";
95     foreach my $class ($self->class_precedence_list) {
96         next unless $class->can('meta') && $class->meta->can('roles');
97         foreach my $role (@{$class->meta->roles}) {
98             return 1 if $role->does_role($role_name);
99         }
100     }
101     return 0;
102 }
103
104 sub excludes_role {
105     my ($self, $role_name) = @_;
106     (defined $role_name)
107         || confess "You must supply a role name to look for";
108     foreach my $class ($self->class_precedence_list) {
109         next unless $class->can('meta');
110         # NOTE:
111         # in the pretty rare instance when a Moose metaclass
112         # is itself extended with a role, this check needs to
113         # be done since some items in the class_precedence_list
114         # might in fact be Class::MOP based still.
115         next unless $class->meta->can('roles');
116         foreach my $role (@{$class->meta->roles}) {
117             return 1 if $role->excludes_role($role_name);
118         }
119     }
120     return 0;
121 }
122
123 sub new_object {
124     my ($class, %params) = @_;
125     my $self = $class->SUPER::new_object(%params);
126     foreach my $attr ($class->compute_all_applicable_attributes()) {
127         # if we have a trigger, then ...
128         if ($attr->can('has_trigger') && $attr->has_trigger) {
129             # make sure we have an init-arg ...
130             if (defined(my $init_arg = $attr->init_arg)) {
131                 # now make sure an init-arg was passes ...
132                 if (exists $params{$init_arg}) {
133                     # and if get here, fire the trigger
134                     $attr->trigger->(
135                         $self, 
136                         # check if there is a coercion
137                         ($attr->should_coerce
138                             # and if so, we need to grab the 
139                             # value that is actually been stored
140                             ? $attr->get_read_method_ref->($self)
141                             # otherwise, just get the value from
142                             # the constructor params
143                             : $params{$init_arg}), 
144                         $attr
145                     );
146                 }
147             }       
148         }
149     }
150     return $self;
151 }
152
153 sub construct_instance {
154     my ($class, %params) = @_;
155     my $meta_instance = $class->get_meta_instance;
156     # FIXME:
157     # the code below is almost certainly incorrect
158     # but this is foreign inheritence, so we might
159     # have to kludge it in the end.
160     my $instance = $params{'__INSTANCE__'} || $meta_instance->create_instance();
161     foreach my $attr ($class->compute_all_applicable_attributes()) {
162         $attr->initialize_instance_slot($meta_instance, $instance, \%params);
163     }
164     return $instance;
165 }
166
167 # FIXME:
168 # This is ugly
169 sub get_method_map {
170     my $self = shift;
171
172     if (defined $self->{'_package_cache_flag'} &&
173                 $self->{'_package_cache_flag'} == Class::MOP::check_package_cache_flag($self->meta->name)) {
174         return $self->{'methods'};
175     }
176
177     my $map  = $self->{'methods'};
178
179     my $class_name       = $self->name;
180     my $method_metaclass = $self->method_metaclass;
181
182     my %all_code = $self->get_all_package_symbols('CODE');
183
184     foreach my $symbol (keys %all_code) {
185         my $code = $all_code{$symbol};
186
187         next if exists  $map->{$symbol} &&
188                 defined $map->{$symbol} &&
189                         $map->{$symbol}->body == $code;
190
191         my ($pkg, $name) = Class::MOP::get_code_info($code);
192
193         if ($pkg->can('meta')
194             # NOTE:
195             # we don't know what ->meta we are calling
196             # here, so we need to be careful cause it
197             # just might blow up at us, or just complain
198             # loudly (in the case of Curses.pm) so we
199             # just be a little overly cautious here.
200             # - SL
201             && eval { no warnings; blessed($pkg->meta) }
202             && $pkg->meta->isa('Moose::Meta::Role')) {
203             #my $role = $pkg->meta->name;
204             #next unless $self->does_role($role);
205         }
206         else {
207             
208             # NOTE:
209             # in 5.10 constant.pm the constants show up 
210             # as being in the right package, but in pre-5.10
211             # they show up as constant::__ANON__ so we 
212             # make an exception here to be sure that things
213             # work as expected in both.
214             # - SL
215             unless ($pkg eq 'constant' && $name eq '__ANON__') {
216                 next if ($pkg  || '') ne $class_name ||
217                         (($name || '') ne '__ANON__' && ($pkg  || '') ne $class_name);
218             }
219
220         }
221
222         $map->{$symbol} = $method_metaclass->wrap(
223             $code,
224             package_name => $class_name,
225             name         => $symbol
226         );
227     }
228
229     return $map;
230 }
231
232 ### ---------------------------------------------
233
234 sub add_attribute {
235     my $self = shift;
236     $self->SUPER::add_attribute(
237         (blessed $_[0] && $_[0]->isa('Class::MOP::Attribute')
238             ? $_[0] 
239             : $self->_process_attribute(@_))    
240     );
241 }
242
243 sub add_override_method_modifier {
244     my ($self, $name, $method, $_super_package) = @_;
245
246     (!$self->has_method($name))
247         || confess "Cannot add an override method if a local method is already present";
248
249     $self->add_method($name => Moose::Meta::Method::Overriden->new(
250         method  => $method,
251         class   => $self,
252         package => $_super_package, # need this for roles
253         name    => $name,
254     ));
255 }
256
257 sub add_augment_method_modifier {
258     my ($self, $name, $method) = @_;
259     (!$self->has_method($name))
260         || confess "Cannot add an augment method if a local method is already present";
261
262     $self->add_method($name => Moose::Meta::Method::Augmented->new(
263         method  => $method,
264         class   => $self,
265         name    => $name,
266     ));
267 }
268
269 ## Private Utility methods ...
270
271 sub _find_next_method_by_name_which_is_not_overridden {
272     my ($self, $name) = @_;
273     foreach my $method ($self->find_all_methods_by_name($name)) {
274         return $method->{code}
275             if blessed($method->{code}) && !$method->{code}->isa('Moose::Meta::Method::Overriden');
276     }
277     return undef;
278 }
279
280 sub _fix_metaclass_incompatability {
281     my ($self, @superclasses) = @_;
282     foreach my $super (@superclasses) {
283         # don't bother if it does not have a meta.
284         next unless $super->can('meta');
285         next unless $super->meta->isa("Class::MOP::Class");
286         # get the name, make sure we take
287         # immutable classes into account
288         my $super_meta_name = ($super->meta->is_immutable
289                                 ? $super->meta->get_mutable_metaclass_name
290                                 : blessed($super->meta));
291         # if it's meta is a vanilla Moose,
292         # then we can safely ignore it.
293         next if $super_meta_name eq 'Moose::Meta::Class';
294         # but if we have anything else,
295         # we need to check it out ...
296         unless (# see if of our metaclass is incompatible
297                 ($self->isa($super_meta_name) &&
298                  # and see if our instance metaclass is incompatible
299                  $self->instance_metaclass->isa($super->meta->instance_metaclass)) &&
300                 # ... and if we are just a vanilla Moose
301                 $self->isa('Moose::Meta::Class')) {
302             # re-initialize the meta ...
303             my $super_meta = $super->meta;
304             # NOTE:
305             # We might want to consider actually
306             # transfering any attributes from the
307             # original meta into this one, but in
308             # general you should not have any there
309             # at this point anyway, so it's very
310             # much an obscure edge case anyway
311             $self = $super_meta->reinitialize($self->name => (
312                 'attribute_metaclass' => $super_meta->attribute_metaclass,
313                 'method_metaclass'    => $super_meta->method_metaclass,
314                 'instance_metaclass'  => $super_meta->instance_metaclass,
315             ));
316         }
317     }
318     return $self;
319 }
320
321 # NOTE:
322 # this was crap anyway, see
323 # Moose::Util::apply_all_roles
324 # instead
325 sub _apply_all_roles { 
326     Carp::croak 'DEPRECATED: use Moose::Util::apply_all_roles($meta, @roles) instead' 
327 }
328
329 sub _process_attribute {
330     my ( $self, $name, @args ) = @_;
331
332     @args = %{$args[0]} if scalar @args == 1 && ref($args[0]) eq 'HASH';
333
334     if ($name =~ /^\+(.*)/) {
335         return $self->_process_inherited_attribute($1, @args);
336     }
337     else {
338         return $self->_process_new_attribute($name, @args);
339     }
340 }
341
342 sub _process_new_attribute {
343     my ( $self, $name, @args ) = @_;
344
345     $self->attribute_metaclass->interpolate_class_and_new($name, @args);
346 }
347
348 sub _process_inherited_attribute {
349     my ($self, $attr_name, %options) = @_;
350     my $inherited_attr = $self->find_attribute_by_name($attr_name);
351     (defined $inherited_attr)
352         || confess "Could not find an attribute by the name of '$attr_name' to inherit from";
353     if ($inherited_attr->isa('Moose::Meta::Attribute')) {
354         return $inherited_attr->clone_and_inherit_options(%options);
355     }
356     else {
357         # NOTE:
358         # kind of a kludge to handle Class::MOP::Attributes
359         return $inherited_attr->Moose::Meta::Attribute::clone_and_inherit_options(%options);
360     }
361 }
362
363 ## -------------------------------------------------
364
365 use Moose::Meta::Method::Constructor;
366 use Moose::Meta::Method::Destructor;
367
368 # This could be done by using SUPER and altering ->options
369 # I am keeping it this way to make it more explicit.
370 sub create_immutable_transformer {
371     my $self = shift;
372     my $class = Class::MOP::Immutable->new($self, {
373        read_only   => [qw/superclasses/],
374        cannot_call => [qw/
375            add_method
376            alias_method
377            remove_method
378            add_attribute
379            remove_attribute
380            remove_package_symbol
381            add_role
382        /],
383        memoize     => {
384            class_precedence_list             => 'ARRAY',
385            compute_all_applicable_attributes => 'ARRAY',
386            get_meta_instance                 => 'SCALAR',
387            get_method_map                    => 'SCALAR',
388            # maybe ....
389            calculate_all_roles               => 'ARRAY',
390        },
391        # NOTE:
392        # this is ugly, but so are typeglobs, 
393        # so whattayahgonnadoboutit
394        # - SL
395        wrapped => { 
396            add_package_symbol => sub {
397                my $original = shift;
398                confess "Cannot add package symbols to an immutable metaclass" 
399                    unless (caller(2))[3] eq 'Class::MOP::Package::get_package_symbol'; 
400                goto $original->body;
401            },
402        },       
403     });
404     return $class;
405 }
406
407 sub make_immutable {
408     my $self = shift;
409     $self->SUPER::make_immutable
410       (
411        constructor_class => 'Moose::Meta::Method::Constructor',
412        destructor_class  => 'Moose::Meta::Method::Destructor',
413        inline_destructor => 1,
414        # NOTE:
415        # no need to do this,
416        # Moose always does it
417        inline_accessors  => 0,
418        @_,
419       );
420 }
421
422 1;
423
424 __END__
425
426 =pod
427
428 =head1 NAME
429
430 Moose::Meta::Class - The Moose metaclass
431
432 =head1 DESCRIPTION
433
434 This is a subclass of L<Class::MOP::Class> with Moose specific
435 extensions.
436
437 For the most part, the only time you will ever encounter an
438 instance of this class is if you are doing some serious deep
439 introspection. To really understand this class, you need to refer
440 to the L<Class::MOP::Class> documentation.
441
442 =head1 METHODS
443
444 =over 4
445
446 =item B<initialize>
447
448 =item B<create>
449
450 Overrides original to accept a list of roles to apply to
451 the created class.
452
453    my $metaclass = Moose::Meta::Class->create( 'New::Class', roles => [...] );
454
455 =item B<create_anon_class>
456
457 Overrides original to support roles and caching.
458
459    my $metaclass = Moose::Meta::Class->create_anon_class(
460        superclasses => ['Foo'],
461        roles        => [qw/Some Roles Go Here/],
462        cache        => 1,
463    );
464
465 =item B<make_immutable>
466
467 Override original to add default options for inlining destructor
468 and altering the Constructor metaclass.
469
470 =item B<create_immutable_transformer>
471
472 Override original to lock C<add_role> and memoize C<calculate_all_roles>
473
474 =item B<new_object>
475
476 We override this method to support the C<trigger> attribute option.
477
478 =item B<construct_instance>
479
480 This provides some Moose specific extensions to this method, you
481 almost never call this method directly unless you really know what
482 you are doing.
483
484 This method makes sure to handle the moose weak-ref, type-constraint
485 and type coercion features.
486
487 =item B<get_method_map>
488
489 This accommodates Moose::Meta::Role::Method instances, which are
490 aliased, instead of added, but still need to be counted as valid
491 methods.
492
493 =item B<add_override_method_modifier ($name, $method)>
494
495 This will create an C<override> method modifier for you, and install
496 it in the package.
497
498 =item B<add_augment_method_modifier ($name, $method)>
499
500 This will create an C<augment> method modifier for you, and install
501 it in the package.
502
503 =item B<calculate_all_roles>
504
505 =item B<roles>
506
507 This will return an array of C<Moose::Meta::Role> instances which are
508 attached to this class.
509
510 =item B<add_role ($role)>
511
512 This takes an instance of C<Moose::Meta::Role> in C<$role>, and adds it
513 to the list of associated roles.
514
515 =item B<does_role ($role_name)>
516
517 This will test if this class C<does> a given C<$role_name>. It will
518 not only check it's local roles, but ask them as well in order to
519 cascade down the role hierarchy.
520
521 =item B<excludes_role ($role_name)>
522
523 This will test if this class C<excludes> a given C<$role_name>. It will
524 not only check it's local roles, but ask them as well in order to
525 cascade down the role hierarchy.
526
527 =item B<add_attribute ($attr_name, %params|$params)>
528
529 This method does the same thing as L<Class::MOP::Class::add_attribute>, but adds
530 support for taking the C<$params> as a HASH ref.
531
532 =back
533
534 =head1 BUGS
535
536 All complex software has bugs lurking in it, and this module is no
537 exception. If you find a bug please either email me, or add the bug
538 to cpan-RT.
539
540 =head1 AUTHOR
541
542 Stevan Little E<lt>stevan@iinteractive.comE<gt>
543
544 =head1 COPYRIGHT AND LICENSE
545
546 Copyright 2006-2008 by Infinity Interactive, Inc.
547
548 L<http://www.iinteractive.com>
549
550 This library is free software; you can redistribute it and/or modify
551 it under the same terms as Perl itself.
552
553 =cut
554