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