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