Comments
[gitmo/Mouse.git] / lib / Mouse / Meta / Class.pm
CommitLineData
306290e8 1package Mouse::Meta::Class;
bc76ed1c 2use Mouse::Util qw/:meta/; # enables strict and warnings
c3398f5b 3
1d76ae62 4use Scalar::Util ();
6d28c5cf 5
6d28c5cf 6use Mouse::Meta::Module;
f3bb863f 7our @ISA = qw(Mouse::Meta::Module);
3a63a2e7 8
3b48bcc8 9our @CARP_NOT = qw(Mouse); # trust Mouse
10
e058b279 11sub attribute_metaclass;
d9659f80 12sub method_metaclass;
3a63a2e7 13
e058b279 14sub constructor_class;
15sub destructor_class;
380e1cd7 16
d9659f80 17
8e64d0fa 18sub _construct_meta {
88ed7189 19 my($class, %args) = @_;
c3398f5b 20
5132ec42 21 $args{attributes} = {};
22 $args{methods} = {};
23 $args{roles} = [];
8536d351 24
c3398f5b 25 $args{superclasses} = do {
26 no strict 'refs';
88ed7189 27 \@{ $args{package} . '::ISA' };
c3398f5b 28 };
29
8d40c3b8 30 my $self = bless \%args, ref($class) || $class;
7eb3a8d5 31 if(ref($self) ne __PACKAGE__){
9009aca1 32 $self->meta->_initialize_object($self, \%args);
8d40c3b8 33 }
34 return $self;
7a50b450 35}
36
37sub create_anon_class{
38 my $self = shift;
39 return $self->create(undef, @_);
40}
41
43165725 42sub is_anon_class;
c3398f5b 43
43165725 44sub roles;
c3398f5b 45
e7264861 46sub calculate_all_roles {
47 my $self = shift;
48 my %seen;
49 return grep { !$seen{ $_->name }++ }
50 map { $_->calculate_all_roles } @{ $self->roles };
51}
52
c3398f5b 53sub superclasses {
54 my $self = shift;
55
56 if (@_) {
9d0686b2 57 foreach my $super(@_){
58 Mouse::Util::load_class($super);
902174eb 59 my $meta = Mouse::Util::get_metaclass_by_name($super);
7778ab1e 60 next if $self->verify_superclass($super, $meta);
b6369395 61 $self->_reconcile_with_superclass_meta($meta);
9d0686b2 62 }
7778ab1e 63 return @{ $self->{superclasses} } = @_;
c3398f5b 64 }
65
8e64d0fa 66 return @{ $self->{superclasses} };
67}
902174eb 68
7778ab1e 69sub 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.
9293fc99 81 # See also Mouse::Foreign::Meta::Role::Class.
7778ab1e 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
902174eb 94sub 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."
98278c01 98 . " Please consider using MouseX::Foreign");
902174eb 99 return;
100}
101
c0b18afd 102my @MetaClassTypes = (
103 'attribute', # Mouse::Meta::Attribute
104 'method', # Mouse::Meta::Method
105 'constructor', # Mouse::Meta::Method::Constructor
106 'destructor', # Mouse::Meta::Method::Destructor
107);
8e64d0fa 108
b6369395 109sub _reconcile_with_superclass_meta {
c0b18afd 110 my($self, $other) = @_;
b6369395 111
733f404b 112 # find incompatible traits
c0b18afd 113 my %metaroles;
b6369395 114 foreach my $metaclass_type(@MetaClassTypes){
c0b18afd 115 my $accessor = $self->can($metaclass_type . '_metaclass')
116 || $self->can($metaclass_type . '_class');
b6369395 117
c0b18afd 118 my $other_c = $other->$accessor();
119 my $self_c = $self->$accessor();
b6369395 120
c0b18afd 121 if(!$self_c->isa($other_c)){
122 $metaroles{$metaclass_type}
123 = [ $self_c->meta->_collect_roles($other_c->meta) ];
d9659f80 124 }
125 }
126
c0b18afd 127 $metaroles{class} = [$self->meta->_collect_roles($other->meta)];
128
129 #use Data::Dumper; print Data::Dumper->new([\%metaroles], ['*metaroles'])->Indent(1)->Dump;
d9659f80 130
131 require Mouse::Util::MetaRole;
c0b18afd 132 $_[0] = Mouse::Util::MetaRole::apply_metaroles(
133 for => $self,
134 class_metaroles => \%metaroles,
d9659f80 135 );
b6369395 136 return;
137}
138
c0b18afd 139sub _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;
a4b15169 158 return sort grep { !$seen{$_}++ } ## no critic
c0b18afd 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
79345849 165sub find_method_by_name {
8e64d0fa 166 my($self, $method_name) = @_;
167 defined($method_name)
168 or $self->throw_error('You must define a method name to find');
0126c27c 169
8e64d0fa 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
177sub get_all_methods {
178 my($self) = @_;
612d3e1a 179 return map{ $self->find_method_by_name($_) } $self->get_all_method_names;
c3398f5b 180}
181
60cfc6ad 182sub get_all_method_names {
183 my $self = shift;
184 my %uniq;
185 return grep { $uniq{$_}++ == 0 }
3a63a2e7 186 map { Mouse::Meta::Class->initialize($_)->get_method_list() }
60cfc6ad 187 $self->linearized_isa;
188}
189
abbcd124 190sub find_attribute_by_name {
2b908b79 191 my($self, $name) = @_;
79345849 192 defined($name)
193 or $self->throw_error('You must define an attribute name to find');
abbcd124 194 foreach my $attr($self->get_all_attributes) {
195 return $attr if $attr->name eq $name;
2b908b79 196 }
abbcd124 197 return undef;
2b908b79 198}
199
87ca293b 200sub add_attribute {
c3398f5b 201 my $self = shift;
60f6eba9 202
87ca293b 203 my($attr, $name);
1b9e472d 204
1d76ae62 205 if(Scalar::Util::blessed($_[0])){
87ca293b 206 $attr = $_[0];
1b9e472d 207
87ca293b 208 $attr->isa('Mouse::Meta::Attribute')
209 || $self->throw_error("Your attribute must be an instance of Mouse::Meta::Attribute (or a subclass)");
1b9e472d 210
87ca293b 211 $name = $attr->name;
1b9e472d 212 }
213 else{
87ca293b 214 # _process_attribute
215 $name = shift;
1b9e472d 216
87ca293b 217 my %args = (@_ == 1) ? %{$_[0]} : @_;
1b9e472d 218
87ca293b 219 defined($name)
220 or $self->throw_error('You must provide a name for the attribute');
1b9e472d 221
87ca293b 222 if ($name =~ s/^\+//) { # inherited attributes
2b908b79 223 my $inherited_attr = $self->find_attribute_by_name($name)
87ca293b 224 or $self->throw_error("Could not find an attribute by the name of '$name' to inherit from in ".$self->name);
225
8cf51b82 226 $attr = $inherited_attr->clone_and_inherit_options(%args);
87ca293b 227 }
228 else{
8cf51b82 229 my($attribute_class, @traits) = $self->attribute_metaclass->interpolate_class(\%args);
87ca293b 230 $args{traits} = \@traits if @traits;
231
2a464664 232 $attr = $attribute_class->new($name, %args);
87ca293b 233 }
234 }
1b9e472d 235
1d76ae62 236 Scalar::Util::weaken( $attr->{associated_class} = $self );
1b9e472d 237
df7e4729 238 # install accessors first
239 $attr->install_accessors();
240
241 # then register the attribute to the metaclass
abbcd124 242 $attr->{insertion_order} = keys %{ $self->{attributes} };
243 $self->{attributes}{$name} = $attr;
244 delete $self->{_mouse_cache}; # clears internal cache
1b9e472d 245
3b48bcc8 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?)});
60f6eba9 249 }
abbcd124 250 return $attr;
251}
74de0f8b 252
abbcd124 253sub _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;
a3a09e38 264 }
abbcd124 265 return [reverse @all_attrs];
c3398f5b 266}
267
cccb83de 268sub linearized_isa;
8536d351 269
ba153b33 270sub new_object;
13b99908 271sub clone_object;
1b9e472d 272
cfef75f0 273sub immutable_options {
274 my ( $self, @args ) = @_;
275
276 return (
7efbc77d 277 inline_constructor => 1,
e578d610 278 inline_destructor => 1,
2a464664 279 constructor_name => 'new',
cfef75f0 280 @args,
6a1d1835 281 );
cfef75f0 282}
283
cfef75f0 284sub make_immutable {
285 my $self = shift;
286 my %args = $self->immutable_options(@_);
6a1d1835 287
fc1d8369 288 $self->{is_immutable}++;
c7a6403f 289
6a1d1835 290 if ($args{inline_constructor}) {
380e1cd7 291 $self->add_method($args{constructor_name} =>
637d4f17 292 Mouse::Util::load_class($self->constructor_class)
293 ->_generate_constructor($self, \%args));
c7a6403f 294 }
295
8632b6fe 296 if ($args{inline_destructor}) {
380e1cd7 297 $self->add_method(DESTROY =>
637d4f17 298 Mouse::Util::load_class($self->destructor_class)
299 ->_generate_destructor($self, \%args));
8632b6fe 300 }
2276cb14 301
89681b0b 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.
2276cb14 304 return 1;
fc1d8369 305}
ad958001 306
32490a72 307sub make_mutable {
308 my($self) = @_;
309 $self->{is_immutable} = 0;
310 return;
311}
ad958001 312
80efe911 313sub is_immutable;
314sub is_mutable { !$_[0]->is_immutable }
84ef660f 315
8d5287a7 316sub _install_modifier {
8d59c723 317 my( $self, $type, $name, $code ) = @_;
318 my $into = $self->name;
3fbade18 319
320 my $original = $into->can($name)
083e49a5 321 or $self->throw_error("The method '$name' was not found in the inheritance hierarchy for $into");
3fbade18 322
323 my $modifier_table = $self->{modifiers}{$name};
324
325 if(!$modifier_table){
d686eec5 326 my(@before, @after, @around);
327 my $cache = $original;
1b490891 328 my $modified = sub {
d686eec5 329 if(@before) {
330 for my $c (@before) { $c->(@_) }
331 }
332 unless(@after) {
1b490891 333 return $cache->(@_);
334 }
335
3fbade18 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,
d686eec5 361 around => \@around,
3fbade18 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
50dc6ee5 385sub add_before_method_modifier {
4859d490 386 my ( $self, $name, $code ) = @_;
8d59c723 387 $self->_install_modifier( 'before', $name, $code );
50dc6ee5 388}
389
390sub add_around_method_modifier {
4859d490 391 my ( $self, $name, $code ) = @_;
8d59c723 392 $self->_install_modifier( 'around', $name, $code );
50dc6ee5 393}
394
395sub add_after_method_modifier {
4859d490 396 my ( $self, $name, $code ) = @_;
8d59c723 397 $self->_install_modifier( 'after', $name, $code );
50dc6ee5 398}
399
67199842 400sub add_override_method_modifier {
401 my ($self, $name, $code) = @_;
402
768804c0 403 if($self->has_method($name)){
404 $self->throw_error("Cannot add an override method if a local method is already present");
85bd3f44 405 }
406
6cfa1e5e 407 my $package = $self->name;
67199842 408
85bd3f44 409 my $super_body = $package->can($name)
6cfa1e5e 410 or $self->throw_error("You cannot override '$name' because it has no super method");
67199842 411
85bd3f44 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
417 $code->(@_);
418 });
419 return;
67199842 420}
421
768804c0 422sub add_augment_method_modifier {
423 my ($self, $name, $code) = @_;
424 if($self->has_method($name)){
425 $self->throw_error("Cannot add an augment method if a local method is already present");
426 }
427
428 my $super = $self->find_method_by_name($name)
429 or $self->throw_error("You cannot augment '$name' because it has no super method");
430
431 my $super_package = $super->package_name;
432 my $super_body = $super->body;
433
434 $self->add_method($name => sub{
435 local $Mouse::INNER_BODY{$super_package} = $code;
436 local $Mouse::INNER_ARGS{$super_package} = [@_];
437 $super_body->(@_);
438 });
439 return;
440}
441
47f36c05 442sub does_role {
443 my ($self, $role_name) = @_;
ad958001 444
47f36c05 445 (defined $role_name)
fce211ae 446 || $self->throw_error("You must supply a role name to look for");
ad958001 447
f3e11122 448 $role_name = $role_name->name if ref $role_name;
449
f7fec86c 450 for my $class ($self->linearized_isa) {
95ecd6f1 451 my $meta = Mouse::Util::get_metaclass_by_name($class)
452 or next;
3a63a2e7 453
454 for my $role (@{ $meta->roles }) {
ff687069 455
3a63a2e7 456 return 1 if $role->does_role($role_name);
f7fec86c 457 }
47f36c05 458 }
ad958001 459
47f36c05 460 return 0;
461}
462
c3398f5b 4631;
c3398f5b 464__END__
465
466=head1 NAME
467
1820fffe 468Mouse::Meta::Class - The Mouse class metaclass
c3398f5b 469
a25ca8d6 470=head1 VERSION
471
a7e3b78e 472This document describes Mouse version 0.76
a25ca8d6 473
503ed648 474=head1 DESCRIPTION
475
476This class is a meta object protocol for Mouse classes,
477which is a subset of Moose::Meta:::Class.
478
c3398f5b 479=head1 METHODS
480
612d3e1a 481=head2 C<< initialize(ClassName) -> Mouse::Meta::Class >>
c3398f5b 482
31c5194b 483Finds or creates a C<Mouse::Meta::Class> instance for the given ClassName. Only
306290e8 484one instance should exist for a given class.
c3398f5b 485
612d3e1a 486=head2 C<< name -> ClassName >>
c3398f5b 487
488Returns the name of the owner class.
489
612d3e1a 490=head2 C<< superclasses -> ClassNames >> C<< superclass(ClassNames) >>
c3398f5b 491
492Gets (or sets) the list of superclasses of the owner class.
493
31c5194b 494=head2 C<< add_method(name => CodeRef) >>
c3398f5b 495
31c5194b 496Adds a method to the owner class.
c3398f5b 497
31c5194b 498=head2 C<< has_method(name) -> Bool >>
72b88a88 499
31c5194b 500Returns whether we have a method with the given name.
72b88a88 501
31c5194b 502=head2 C<< get_method(name) -> Mouse::Meta::Method | undef >>
c68b4110 503
31c5194b 504Returns a L<Mouse::Meta::Method> with the given name.
505
506Note that you can also use C<< $metaclass->name->can($name) >> for a method body.
507
508=head2 C<< get_method_list -> Names >>
509
510Returns a list of method names which are defined in the local class.
511If you want a list of all applicable methods for a class, use the
512C<get_all_methods> method.
513
514=head2 C<< get_all_methods -> (Mouse::Meta::Method) >>
515
516Return the list of all L<Mouse::Meta::Method> instances associated with
517the class and its superclasses.
518
519=head2 C<< add_attribute(name => spec | Mouse::Meta::Attribute) >>
520
521Begins keeping track of the existing L<Mouse::Meta::Attribute> for the owner
522class.
c68b4110 523
612d3e1a 524=head2 C<< has_attribute(Name) -> Bool >>
66eea168 525
526Returns whether we have a L<Mouse::Meta::Attribute> with the given name.
527
31c5194b 528=head2 C<< get_attribute Name -> Mouse::Meta::Attribute | undef >>
c3398f5b 529
306290e8 530Returns the L<Mouse::Meta::Attribute> with the given name.
c3398f5b 531
31c5194b 532=head2 C<< get_attribute_list -> Names >>
533
534Returns a list of attribute names which are defined in the local
535class. If you want a list of all applicable attributes for a class,
536use the C<get_all_attributes> method.
537
538=head2 C<< get_all_attributes -> (Mouse::Meta::Attribute) >>
539
540Returns the list of all L<Mouse::Meta::Attribute> instances associated with
541this class and its superclasses.
542
612d3e1a 543=head2 C<< linearized_isa -> [ClassNames] >>
c3398f5b 544
545Returns the list of classes in method dispatch order, with duplicates removed.
546
612d3e1a 547=head2 C<< new_object(Parameters) -> Instance >>
2cea7a5f 548
612d3e1a 549Creates a new instance.
2cea7a5f 550
612d3e1a 551=head2 C<< clone_object(Instance, Parameters) -> Instance >>
f7b11a21 552
31c5194b 553Clones the given instance which must be an instance governed by this
f7b11a21 554metaclass.
555
31c5194b 556=head2 C<< throw_error(Message, Parameters) >>
557
558Throws an error with the given message.
559
1820fffe 560=head1 SEE ALSO
f7b11a21 561
6b82419e 562L<Mouse::Meta::Module>
563
1820fffe 564L<Moose::Meta::Class>
f7b11a21 565
31c5194b 566L<Class::MOP::Class>
567
c3398f5b 568=cut
569