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