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