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