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