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