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