Mouse::Meta::Class and Mouse::Meta::Role are now extensible by extends()
[gitmo/Mouse.git] / lib / Mouse / Meta / Class.pm
1 package Mouse::Meta::Class;
2 use strict;
3 use warnings;
4
5 use Scalar::Util qw/blessed weaken/;
6
7 use Mouse::Util qw/:meta get_linear_isa not_supported/;
8
9 use Mouse::Meta::Method::Constructor;
10 use Mouse::Meta::Method::Destructor;
11 use Mouse::Meta::Module;
12 our @ISA = qw(Mouse::Meta::Module);
13
14 sub method_metaclass(){ 'Mouse::Meta::Method' } # required for get_method()
15
16 sub _construct_meta {
17     my($class, %args) = @_;
18
19     $args{attributes} ||= {};
20     $args{methods}    ||= {};
21     $args{roles}      ||= [];
22
23     $args{superclasses} = do {
24         no strict 'refs';
25         \@{ $args{package} . '::ISA' };
26     };
27
28     my $self = bless \%args, ref($class) || $class;
29     if($class ne __PACKAGE__){
30         $self->meta->_initialize_object($self, \%args);
31     }
32     return $self;
33 }
34
35 sub create_anon_class{
36     my $self = shift;
37     return $self->create(undef, @_);
38 }
39
40 sub is_anon_class{
41     return exists $_[0]->{anon_serial_id};
42 }
43
44 sub roles { $_[0]->{roles} }
45
46 sub superclasses {
47     my $self = shift;
48
49     if (@_) {
50         Mouse::load_class($_) for @_;
51         @{ $self->{superclasses} } = @_;
52     }
53
54     return @{ $self->{superclasses} };
55 }
56
57 sub find_method_by_name{
58     my($self, $method_name) = @_;
59     defined($method_name)
60         or $self->throw_error('You must define a method name to find');
61     foreach my $class( $self->linearized_isa ){
62         my $method = $self->initialize($class)->get_method($method_name);
63         return $method if defined $method;
64     }
65     return undef;
66 }
67
68 sub get_all_methods {
69     my($self) = @_;
70     return map{ $self->find_method_by_name($_) } $self->get_all_method_names;
71 }
72
73 sub get_all_method_names {
74     my $self = shift;
75     my %uniq;
76     return grep { $uniq{$_}++ == 0 }
77             map { Mouse::Meta::Class->initialize($_)->get_method_list() }
78             $self->linearized_isa;
79 }
80
81 sub add_attribute {
82     my $self = shift;
83
84     my($attr, $name);
85
86     if(blessed $_[0]){
87         $attr = $_[0];
88
89         $attr->isa('Mouse::Meta::Attribute')
90             || $self->throw_error("Your attribute must be an instance of Mouse::Meta::Attribute (or a subclass)");
91
92         $name = $attr->name;
93     }
94     else{
95         # _process_attribute
96         $name = shift;
97
98         my %args = (@_ == 1) ? %{$_[0]} : @_;
99
100         defined($name)
101             or $self->throw_error('You must provide a name for the attribute');
102
103         if ($name =~ s/^\+//) { # inherited attributes
104             my $inherited_attr;
105
106             foreach my $class($self->linearized_isa){
107                 my $meta = Mouse::Util::get_metaclass_by_name($class) or next;
108                 $inherited_attr = $meta->get_attribute($name) and last;
109             }
110
111             defined($inherited_attr)
112                 or $self->throw_error("Could not find an attribute by the name of '$name' to inherit from in ".$self->name);
113
114             $attr = $inherited_attr->clone_and_inherit_options($name, \%args);
115         }
116         else{
117             my($attribute_class, @traits) = Mouse::Meta::Attribute->interpolate_class($name, \%args);
118             $args{traits} = \@traits if @traits;
119
120             $attr = $attribute_class->new($name, \%args);
121         }
122     }
123
124     weaken( $attr->{associated_class} = $self );
125
126     $self->{attributes}{$attr->name} = $attr;
127     $attr->install_accessors();
128
129     if(_MOUSE_VERBOSE && !$attr->{associated_methods} && ($attr->{is} || '') ne 'bare'){
130         Carp::cluck(qq{Attribute (}.$attr->name.qq{) of class }.$self->name.qq{ has no associated methods (did you mean to provide an "is" argument?)});
131     }
132     return $attr;
133 }
134
135 sub compute_all_applicable_attributes {
136     Carp::cluck('compute_all_applicable_attributes() has been deprecated');
137     return shift->get_all_attributes(@_)
138 }
139
140 sub get_all_attributes {
141     my $self = shift;
142     my (@attr, %seen);
143
144     for my $class ($self->linearized_isa) {
145         my $meta = Mouse::Util::get_metaclass_by_name($class)
146             or next;
147
148         for my $name ($meta->get_attribute_list) {
149             next if $seen{$name}++;
150             push @attr, $meta->get_attribute($name);
151         }
152     }
153
154     return @attr;
155 }
156
157 sub linearized_isa { @{ get_linear_isa($_[0]->name) } }
158
159 sub new_object {
160     my $self = shift;
161     my %args = (@_ == 1 ? %{$_[0]} : @_);
162
163     my $object = bless {}, $self->name;
164
165     $self->_initialize_object($object, \%args);
166     return $object;
167 }
168
169 sub _initialize_object{
170     my($self, $object, $args) = @_;
171
172     my @triggers_queue;
173
174     foreach my $attribute ($self->get_all_attributes) {
175         my $from = $attribute->init_arg;
176         my $key  = $attribute->name;
177
178         if (defined($from) && exists($args->{$from})) {
179             $object->{$key} = $attribute->_coerce_and_verify($args->{$from});
180
181             weaken($object->{$key})
182                 if ref($object->{$key}) && $attribute->is_weak_ref;
183
184             if ($attribute->has_trigger) {
185                 push @triggers_queue, [ $attribute->trigger, $object->{$key} ];
186             }
187         }
188         else {
189             if ($attribute->has_default || $attribute->has_builder) {
190                 unless ($attribute->is_lazy) {
191                     my $default = $attribute->default;
192                     my $builder = $attribute->builder;
193                     my $value =   $builder                ? $object->$builder()
194                                 : ref($default) eq 'CODE' ? $object->$default()
195                                 :                           $default;
196
197                     # XXX: we cannot use $attribute->set_value() because it invokes triggers.
198                     $object->{$key} = $attribute->_coerce_and_verify($value, $object);;
199
200                     weaken($object->{$key})
201                         if ref($object->{$key}) && $attribute->is_weak_ref;
202                 }
203             }
204             else {
205                 if ($attribute->is_required) {
206                     $self->throw_error("Attribute (".$attribute->name.") is required");
207                 }
208             }
209         }
210     }
211
212     foreach my $trigger_and_value(@triggers_queue){
213         my($trigger, $value) = @{$trigger_and_value};
214         $trigger->($object, $value);
215     }
216
217     if($self->is_anon_class){
218         $object->{__METACLASS__} = $self;
219     }
220
221     return $object;
222 }
223
224 sub clone_object {
225     my $class  = shift;
226     my $object = shift;
227     my %params = (@_ == 1) ? %{$_[0]} : @_;
228
229     (blessed($object) && $object->isa($class->name))
230         || $class->throw_error("You must pass an instance of the metaclass (" . $class->name . "), not ($object)");
231
232     my $cloned = bless { %$object }, ref $object;
233     $class->_initialize_object($cloned, \%params);
234
235     return $cloned;
236 }
237
238 sub clone_instance {
239     my ($class, $instance, %params) = @_;
240
241     Carp::cluck('clone_instance has been deprecated. Use clone_object instead')
242         if _MOUSE_VERBOSE;
243     return $class->clone_object($instance, %params);
244 }
245
246 sub make_immutable {
247     my $self = shift;
248     my %args = (
249         inline_constructor => 1,
250         inline_destructor  => 1,
251         @_,
252     );
253
254     $self->{is_immutable}++;
255
256     if ($args{inline_constructor}) {
257         $self->add_method('new' => Mouse::Meta::Method::Constructor->generate_constructor_method_inline( $self ));
258     }
259
260     if ($args{inline_destructor}) {
261         $self->add_method('DESTROY' => Mouse::Meta::Method::Destructor->generate_destructor_method_inline( $self ));
262     }
263
264     # Moose's make_immutable returns true allowing calling code to skip setting an explicit true value
265     # at the end of a source file. 
266     return 1;
267 }
268
269 sub make_mutable { not_supported }
270
271 sub is_immutable {  $_[0]->{is_immutable} }
272 sub is_mutable   { !$_[0]->{is_immutable} }
273
274 sub _install_modifier_pp{
275     my( $self, $into, $type, $name, $code ) = @_;
276
277     my $original = $into->can($name)
278         or $self->throw_error("The method '$name' is not found in the inheritance hierarchy for class $into");
279
280     my $modifier_table = $self->{modifiers}{$name};
281
282     if(!$modifier_table){
283         my(@before, @after, @around, $cache, $modified);
284
285         $cache = $original;
286
287         $modified = sub {
288             for my $c (@before) { $c->(@_) }
289
290             if(wantarray){ # list context
291                 my @rval = $cache->(@_);
292
293                 for my $c(@after){ $c->(@_) }
294                 return @rval;
295             }
296             elsif(defined wantarray){ # scalar context
297                 my $rval = $cache->(@_);
298
299                 for my $c(@after){ $c->(@_) }
300                 return $rval;
301             }
302             else{ # void context
303                 $cache->(@_);
304
305                 for my $c(@after){ $c->(@_) }
306                 return;
307             }
308         };
309
310         $self->{modifiers}{$name} = $modifier_table = {
311             original => $original,
312
313             before   => \@before,
314             after    => \@after,
315             around   => \@around,
316
317             cache    => \$cache, # cache for around modifiers
318         };
319
320         $self->add_method($name => $modified);
321     }
322
323     if($type eq 'before'){
324         unshift @{$modifier_table->{before}}, $code;
325     }
326     elsif($type eq 'after'){
327         push @{$modifier_table->{after}}, $code;
328     }
329     else{ # around
330         push @{$modifier_table->{around}}, $code;
331
332         my $next = ${ $modifier_table->{cache} };
333         ${ $modifier_table->{cache} } = sub{ $code->($next, @_) };
334     }
335
336     return;
337 }
338
339 sub _install_modifier {
340     my ( $self, $into, $type, $name, $code ) = @_;
341
342     # load Class::Method::Modifiers first
343     my $no_cmm_fast = do{
344         local $@;
345         eval q{ require Class::Method::Modifiers::Fast };
346         $@;
347     };
348
349     my $impl;
350     if($no_cmm_fast){
351         $impl = \&_install_modifier_pp;
352     }
353     else{
354         my $install_modifier = Class::Method::Modifiers::Fast->can('_install_modifier');
355         $impl = sub {
356             my ( $self, $into, $type, $name, $code ) = @_;
357             $install_modifier->(
358                 $into,
359                 $type,
360                 $name,
361                 $code
362             );
363             $self->{methods}{$name}++; # register it to the method map
364             return;
365         };
366     }
367
368     # replace this method itself :)
369     {
370         no warnings 'redefine';
371         *_install_modifier = $impl;
372     }
373
374     $self->$impl( $into, $type, $name, $code );
375 }
376
377 sub add_before_method_modifier {
378     my ( $self, $name, $code ) = @_;
379     $self->_install_modifier( $self->name, 'before', $name, $code );
380 }
381
382 sub add_around_method_modifier {
383     my ( $self, $name, $code ) = @_;
384     $self->_install_modifier( $self->name, 'around', $name, $code );
385 }
386
387 sub add_after_method_modifier {
388     my ( $self, $name, $code ) = @_;
389     $self->_install_modifier( $self->name, 'after', $name, $code );
390 }
391
392 sub add_override_method_modifier {
393     my ($self, $name, $code) = @_;
394
395     my $package = $self->name;
396
397     my $body = $package->can($name)
398         or $self->throw_error("You cannot override '$name' because it has no super method");
399
400     $self->add_method($name => sub { $code->($package, $body, @_) });
401 }
402
403 sub does_role {
404     my ($self, $role_name) = @_;
405
406     (defined $role_name)
407         || $self->throw_error("You must supply a role name to look for");
408
409     for my $class ($self->linearized_isa) {
410         my $meta = Mouse::Util::get_metaclass_by_name($class);
411         next unless $meta && $meta->can('roles');
412
413         for my $role (@{ $meta->roles }) {
414
415             return 1 if $role->does_role($role_name);
416         }
417     }
418
419     return 0;
420 }
421
422 1;
423
424 __END__
425
426 =head1 NAME
427
428 Mouse::Meta::Class - The Mouse class metaclass
429
430 =head1 METHODS
431
432 =head2 C<< initialize(ClassName) -> Mouse::Meta::Class >>
433
434 Finds or creates a C<Mouse::Meta::Class> instance for the given ClassName. Only
435 one instance should exist for a given class.
436
437 =head2 C<< name -> ClassName >>
438
439 Returns the name of the owner class.
440
441 =head2 C<< superclasses -> ClassNames >> C<< superclass(ClassNames) >>
442
443 Gets (or sets) the list of superclasses of the owner class.
444
445 =head2 C<< add_method(name => CodeRef) >>
446
447 Adds a method to the owner class.
448
449 =head2 C<< has_method(name) -> Bool >>
450
451 Returns whether we have a method with the given name.
452
453 =head2 C<< get_method(name) -> Mouse::Meta::Method | undef >>
454
455 Returns a L<Mouse::Meta::Method> with the given name.
456
457 Note that you can also use C<< $metaclass->name->can($name) >> for a method body.
458
459 =head2 C<< get_method_list -> Names >>
460
461 Returns a list of method names which are defined in the local class.
462 If you want a list of all applicable methods for a class, use the
463 C<get_all_methods> method.
464
465 =head2 C<< get_all_methods -> (Mouse::Meta::Method) >>
466
467 Return the list of all L<Mouse::Meta::Method> instances associated with
468 the class and its superclasses.
469
470 =head2 C<< add_attribute(name => spec | Mouse::Meta::Attribute) >>
471
472 Begins keeping track of the existing L<Mouse::Meta::Attribute> for the owner
473 class.
474
475 =head2 C<< has_attribute(Name) -> Bool >>
476
477 Returns whether we have a L<Mouse::Meta::Attribute> with the given name.
478
479 =head2 C<< get_attribute Name -> Mouse::Meta::Attribute | undef >>
480
481 Returns the L<Mouse::Meta::Attribute> with the given name.
482
483 =head2 C<< get_attribute_list -> Names >>
484
485 Returns a list of attribute names which are defined in the local
486 class. If you want a list of all applicable attributes for a class,
487 use the C<get_all_attributes> method.
488
489 =head2 C<< get_all_attributes -> (Mouse::Meta::Attribute) >>
490
491 Returns the list of all L<Mouse::Meta::Attribute> instances associated with
492 this class and its superclasses.
493
494 =head2 C<< linearized_isa -> [ClassNames] >>
495
496 Returns the list of classes in method dispatch order, with duplicates removed.
497
498 =head2 C<< new_object(Parameters) -> Instance >>
499
500 Creates a new instance.
501
502 =head2 C<< clone_object(Instance, Parameters) -> Instance >>
503
504 Clones the given instance which must be an instance governed by this
505 metaclass.
506
507 =head2 C<< throw_error(Message, Parameters) >>
508
509 Throws an error with the given message.
510
511 =head1 SEE ALSO
512
513 L<Moose::Meta::Class>
514
515 L<Class::MOP::Class>
516
517 =cut
518