Implement own method modifiers
[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/get_linear_isa not_supported/;
8
9 use Mouse::Meta::Method::Constructor;
10 use Mouse::Meta::Method::Destructor;
11 use Mouse::Meta::Module;
12
13 use base qw(Mouse::Meta::Module);
14
15 sub method_metaclass(){ 'Mouse::Meta::Method' } # required for get_method()
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     #return Mouse::Meta::Class->initialize($class)->new_object(%args)
30     #    if $class ne __PACKAGE__;
31
32     return bless \%args, ref($class) || $class;
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) } $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::Meta::Module::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(!$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 { shift->get_all_attributes(@_) }
136 sub get_all_attributes {
137     my $self = shift;
138     my (@attr, %seen);
139
140     for my $class ($self->linearized_isa) {
141         my $meta = $self->_metaclass_cache($class)
142             or next;
143
144         for my $name (keys %{ $meta->get_attribute_map }) {
145             next if $seen{$name}++;
146             push @attr, $meta->get_attribute($name);
147         }
148     }
149
150     return @attr;
151 }
152
153 sub linearized_isa { @{ get_linear_isa($_[0]->name) } }
154
155 sub new_object {
156     my $self = shift;
157     my %args = (@_ == 1 ? %{$_[0]} : @_);
158
159     my $instance = bless {}, $self->name;
160
161     $self->_initialize_instance($instance, \%args);
162     return $instance;
163 }
164
165 sub _initialize_instance{
166     my($self, $instance, $args) = @_;
167
168     my @triggers_queue;
169
170     foreach my $attribute ($self->get_all_attributes) {
171         my $from = $attribute->init_arg;
172         my $key  = $attribute->name;
173
174         if (defined($from) && exists($args->{$from})) {
175             $args->{$from} = $attribute->coerce_constraint($args->{$from})
176                 if $attribute->should_coerce;
177
178             $attribute->verify_against_type_constraint($args->{$from});
179
180             $instance->{$key} = $args->{$from};
181
182             weaken($instance->{$key})
183                 if ref($instance->{$key}) && $attribute->is_weak_ref;
184
185             if ($attribute->has_trigger) {
186                 push @triggers_queue, [ $attribute->trigger, $args->{$from} ];
187             }
188         }
189         else {
190             if ($attribute->has_default || $attribute->has_builder) {
191                 unless ($attribute->is_lazy) {
192                     my $default = $attribute->default;
193                     my $builder = $attribute->builder;
194                     my $value = $attribute->has_builder
195                               ? $instance->$builder
196                               : ref($default) eq 'CODE'
197                                   ? $default->($instance)
198                                   : $default;
199
200                     $value = $attribute->coerce_constraint($value)
201                         if $attribute->should_coerce;
202                     $attribute->verify_against_type_constraint($value);
203
204                     $instance->{$key} = $value;
205
206                     weaken($instance->{$key})
207                         if ref($instance->{$key}) && $attribute->is_weak_ref;
208                 }
209             }
210             else {
211                 if ($attribute->is_required) {
212                     $self->throw_error("Attribute (".$attribute->name.") is required");
213                 }
214             }
215         }
216     }
217
218     foreach my $trigger_and_value(@triggers_queue){
219         my($trigger, $value) = @{$trigger_and_value};
220         $trigger->($instance, $value);
221     }
222
223     if($self->is_anon_class){
224         $instance->{__METACLASS__} = $self;
225     }
226
227     return $instance;
228 }
229
230 sub clone_object {
231     my $class    = shift;
232     my $instance = shift;
233     my %params   = (@_ == 1) ? %{$_[0]} : @_;
234
235     (blessed($instance) && $instance->isa($class->name))
236         || $class->throw_error("You must pass an instance of the metaclass (" . $class->name . "), not ($instance)");
237
238     my $clone = bless { %$instance }, ref $instance;
239
240     foreach my $attr ($class->get_all_attributes()) {
241         if ( defined( my $init_arg = $attr->init_arg ) ) {
242             if (exists $params{$init_arg}) {
243                 $clone->{ $attr->name } = $params{$init_arg};
244             }
245         }
246     }
247
248     return $clone;
249 }
250
251 sub clone_instance {
252     my ($class, $instance, %params) = @_;
253
254     Carp::cluck('clone_instance has been deprecated. Use clone_object instead');
255     return $class->clone_object($instance, %params);
256 }
257
258 sub make_immutable {
259     my $self = shift;
260     my %args = (
261         inline_constructor => 1,
262         inline_destructor  => 1,
263         @_,
264     );
265
266     $self->{is_immutable}++;
267
268     if ($args{inline_constructor}) {
269         $self->add_method('new' => Mouse::Meta::Method::Constructor->generate_constructor_method_inline( $self ));
270     }
271
272     if ($args{inline_destructor}) {
273         $self->add_method('DESTROY' => Mouse::Meta::Method::Destructor->generate_destructor_method_inline( $self ));
274     }
275
276     # Moose's make_immutable returns true allowing calling code to skip setting an explicit true value
277     # at the end of a source file. 
278     return 1;
279 }
280
281 sub make_mutable { not_supported }
282
283 sub is_immutable {  $_[0]->{is_immutable} }
284 sub is_mutable   { !$_[0]->{is_immutable} }
285
286 sub _install_modifier_pp{
287     my( $self, $into, $type, $name, $code ) = @_;
288
289     my $original = $into->can($name)
290         or $self->throw_error("The method '$name' is not found in the inheritance hierarchy for class $into");
291
292     my $modifier_table = $self->{modifiers}{$name};
293
294     if(!$modifier_table){
295         my(@before, @after, @around, $cache, $modified);
296
297         $cache = $original;
298
299         $modified = sub {
300             for my $c (@before) { $c->(@_) }
301
302             if(wantarray){ # list context
303                 my @rval = $cache->(@_);
304
305                 for my $c(@after){ $c->(@_) }
306                 return @rval;
307             }
308             elsif(defined wantarray){ # scalar context
309                 my $rval = $cache->(@_);
310
311                 for my $c(@after){ $c->(@_) }
312                 return $rval;
313             }
314             else{ # void context
315                 $cache->(@_);
316
317                 for my $c(@after){ $c->(@_) }
318                 return;
319             }
320         };
321
322         $self->{modifiers}{$name} = $modifier_table = {
323             original => $original,
324
325             before   => \@before,
326             after    => \@after,
327             around   => \@around,
328
329             cache    => \$cache, # cache for around modifiers
330         };
331
332         $self->add_method($name => $modified);
333     }
334
335     if($type eq 'before'){
336         unshift @{$modifier_table->{before}}, $code;
337     }
338     elsif($type eq 'after'){
339         push @{$modifier_table->{after}}, $code;
340     }
341     else{ # around
342         push @{$modifier_table->{around}}, $code;
343
344         my $next = ${ $modifier_table->{cache} };
345         ${ $modifier_table->{cache} } = sub{ $code->($next, @_) };
346     }
347
348     return;
349 }
350
351 sub _install_modifier {
352     my ( $self, $into, $type, $name, $code ) = @_;
353
354     # load Class::Method::Modifiers first
355     my $no_cmm_fast = $ENV{MOUSE_NO_CMM_FAST} || do{
356         local $@;
357         eval q{ require Class::Method::Modifiers::Fast };
358         $@;
359     };
360
361     my $impl;
362     if($no_cmm_fast){
363         $impl = \&_install_modifier_pp;
364     }
365     else{
366         my $install_modifier = Class::Method::Modifiers::Fast->can('_install_modifier');
367         $impl = sub {
368             my ( $self, $into, $type, $name, $code ) = @_;
369             $install_modifier->(
370                 $into,
371                 $type,
372                 $name,
373                 $code
374             );
375             $self->{methods}{$name}++; # register it to the method map
376             return;
377         };
378     }
379
380     # replace this method itself :)
381     {
382         no warnings 'redefine';
383         *_install_modifier = $impl;
384     }
385
386     $self->$impl( $into, $type, $name, $code );
387 }
388
389 sub add_before_method_modifier {
390     my ( $self, $name, $code ) = @_;
391     $self->_install_modifier( $self->name, 'before', $name, $code );
392 }
393
394 sub add_around_method_modifier {
395     my ( $self, $name, $code ) = @_;
396     $self->_install_modifier( $self->name, 'around', $name, $code );
397 }
398
399 sub add_after_method_modifier {
400     my ( $self, $name, $code ) = @_;
401     $self->_install_modifier( $self->name, 'after', $name, $code );
402 }
403
404 sub add_override_method_modifier {
405     my ($self, $name, $code) = @_;
406
407     my $package = $self->name;
408
409     my $body = $package->can($name)
410         or $self->throw_error("You cannot override '$name' because it has no super method");
411
412     $self->add_method($name => sub { $code->($package, $body, @_) });
413 }
414
415 sub does_role {
416     my ($self, $role_name) = @_;
417
418     (defined $role_name)
419         || $self->throw_error("You must supply a role name to look for");
420
421     for my $class ($self->linearized_isa) {
422         my $meta = Mouse::Meta::Module::class_of($class);
423         next unless $meta && $meta->can('roles');
424
425         for my $role (@{ $meta->roles }) {
426
427             return 1 if $role->does_role($role_name);
428         }
429     }
430
431     return 0;
432 }
433
434 1;
435
436 __END__
437
438 =head1 NAME
439
440 Mouse::Meta::Class - The Mouse class metaclass
441
442 =head1 METHODS
443
444 =head2 initialize ClassName -> Mouse::Meta::Class
445
446 Finds or creates a Mouse::Meta::Class instance for the given ClassName. Only
447 one instance should exist for a given class.
448
449 =head2 name -> ClassName
450
451 Returns the name of the owner class.
452
453 =head2 superclasses -> [ClassName]
454
455 Gets (or sets) the list of superclasses of the owner class.
456
457 =head2 add_attribute (name => spec | Mouse::Meta::Attribute)
458
459 Begins keeping track of the existing L<Mouse::Meta::Attribute> for the owner
460 class.
461
462 =head2 get_all_attributes -> (Mouse::Meta::Attribute)
463
464 Returns the list of all L<Mouse::Meta::Attribute> instances associated with
465 this class and its superclasses.
466
467 =head2 get_attribute_map -> { name => Mouse::Meta::Attribute }
468
469 Returns a mapping of attribute names to their corresponding
470 L<Mouse::Meta::Attribute> objects.
471
472 =head2 get_attribute_list -> { name => Mouse::Meta::Attribute }
473
474 This returns a list of attribute names which are defined in the local
475 class. If you want a list of all applicable attributes for a class,
476 use the C<get_all_attributes> method.
477
478 =head2 has_attribute Name -> Bool
479
480 Returns whether we have a L<Mouse::Meta::Attribute> with the given name.
481
482 =head2 get_attribute Name -> Mouse::Meta::Attribute | undef
483
484 Returns the L<Mouse::Meta::Attribute> with the given name.
485
486 =head2 linearized_isa -> [ClassNames]
487
488 Returns the list of classes in method dispatch order, with duplicates removed.
489
490 =head2 new_object Parameters -> Instance
491
492 Create a new instance.
493
494 =head2 clone_object Instance -> Instance
495
496 Clones the given C<Instance> which must be an instance governed by this
497 metaclass.
498
499 =head1 SEE ALSO
500
501 L<Moose::Meta::Class>
502
503 =cut
504