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