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