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