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