2689f85a6f00eef44d854cdf2934a0fd618feda4
[gitmo/Mouse.git] / lib / Mouse / Meta / Class.pm
1 package Mouse::Meta::Class;
2 use strict;
3 use warnings;
4
5 use Mouse::Meta::Method::Constructor;
6 use Mouse::Meta::Method::Destructor;
7 use Scalar::Util qw/blessed weaken/;
8 use Mouse::Util qw/get_linear_isa not_supported/;
9
10 use base qw(Mouse::Meta::Module);
11
12 sub method_metaclass(){ 'Mouse::Meta::Method' } # required for get_method()
13
14 sub _new {
15     my($class, %args) = @_;
16
17     $args{attributes} ||= {};
18     $args{methods}    ||= {};
19     $args{roles}      ||= [];
20
21     $args{superclasses} = do {
22         no strict 'refs';
23         \@{ $args{package} . '::ISA' };
24     };
25
26     bless \%args, $class;
27 }
28
29 sub roles { $_[0]->{roles} }
30
31 sub superclasses {
32     my $self = shift;
33
34     if (@_) {
35         Mouse::load_class($_) for @_;
36         @{ $self->{superclasses} } = @_;
37     }
38
39     @{ $self->{superclasses} };
40 }
41
42 sub get_all_method_names {
43     my $self = shift;
44     my %uniq;
45     return grep { $uniq{$_}++ == 0 }
46             map { Mouse::Meta::Class->initialize($_)->get_method_list() }
47             $self->linearized_isa;
48 }
49
50 sub add_attribute {
51     my $self = shift;
52
53     if (@_ == 1 && blessed($_[0])) {
54         my $attr = shift @_;
55         $self->{'attributes'}{$attr->name} = $attr;
56     } else {
57         my $names = shift @_;
58         $names = [$names] if !ref($names);
59         my $metaclass = 'Mouse::Meta::Attribute';
60         my %options = @_;
61
62         if ( my $metaclass_name = delete $options{metaclass} ) {
63             my $new_class = Mouse::Util::resolve_metaclass_alias(
64                 'Attribute',
65                 $metaclass_name
66             );
67             if ( $metaclass ne $new_class ) {
68                 $metaclass = $new_class;
69             }
70         }
71
72         for my $name (@$names) {
73             if ($name =~ s/^\+//) {
74                 $metaclass->clone_parent($self, $name, @_);
75             }
76             else {
77                 $metaclass->create($self, $name, @_);
78             }
79         }
80     }
81 }
82
83 sub compute_all_applicable_attributes { shift->get_all_attributes(@_) }
84 sub get_all_attributes {
85     my $self = shift;
86     my (@attr, %seen);
87
88     for my $class ($self->linearized_isa) {
89         my $meta = $self->_metaclass_cache($class)
90             or next;
91
92         for my $name (keys %{ $meta->get_attribute_map }) {
93             next if $seen{$name}++;
94             push @attr, $meta->get_attribute($name);
95         }
96     }
97
98     return @attr;
99 }
100
101 sub linearized_isa { @{ get_linear_isa($_[0]->name) } }
102
103 sub new_object {
104     my $self = shift;
105     my $args = (@_ == 1) ? $_[0] : { @_ };
106
107     my $instance = bless {}, $self->name;
108
109     foreach my $attribute ($self->get_all_attributes) {
110         my $from = $attribute->init_arg;
111         my $key  = $attribute->name;
112
113         if (defined($from) && exists($args->{$from})) {
114             $args->{$from} = $attribute->coerce_constraint($args->{$from})
115                 if $attribute->should_coerce;
116             $attribute->verify_against_type_constraint($args->{$from});
117
118             $instance->{$key} = $args->{$from};
119
120             weaken($instance->{$key})
121                 if ref($instance->{$key}) && $attribute->is_weak_ref;
122
123             if ($attribute->has_trigger) {
124                 $attribute->trigger->($instance, $args->{$from});
125             }
126         }
127         else {
128             if ($attribute->has_default || $attribute->has_builder) {
129                 unless ($attribute->is_lazy) {
130                     my $default = $attribute->default;
131                     my $builder = $attribute->builder;
132                     my $value = $attribute->has_builder
133                               ? $instance->$builder
134                               : ref($default) eq 'CODE'
135                                   ? $default->($instance)
136                                   : $default;
137
138                     $value = $attribute->coerce_constraint($value)
139                         if $attribute->should_coerce;
140                     $attribute->verify_against_type_constraint($value);
141
142                     $instance->{$key} = $value;
143
144                     weaken($instance->{$key})
145                         if ref($instance->{$key}) && $attribute->is_weak_ref;
146                 }
147             }
148             else {
149                 if ($attribute->is_required) {
150                     $self->throw_error("Attribute (".$attribute->name.") is required");
151                 }
152             }
153         }
154     }
155     return $instance;
156 }
157
158 sub clone_object {
159     my $class    = shift;
160     my $instance = shift;
161
162     (blessed($instance) && $instance->isa($class->name))
163         || $class->throw_error("You must pass an instance of the metaclass (" . $class->name . "), not ($instance)");
164
165     $class->clone_instance($instance, @_);
166 }
167
168 sub clone_instance {
169     my ($class, $instance, %params) = @_;
170
171     (blessed($instance))
172         || $class->throw_error("You can only clone instances, ($instance) is not a blessed instance");
173
174     my $clone = bless { %$instance }, ref $instance;
175
176     foreach my $attr ($class->get_all_attributes()) {
177         if ( defined( my $init_arg = $attr->init_arg ) ) {
178             if (exists $params{$init_arg}) {
179                 $clone->{ $attr->name } = $params{$init_arg};
180             }
181         }
182     }
183
184     return $clone;
185
186 }
187
188 sub make_immutable {
189     my $self = shift;
190     my %args = (
191         inline_constructor => 1,
192         inline_destructor  => 1,
193         @_,
194     );
195
196     $self->{is_immutable}++;
197
198     if ($args{inline_constructor}) {
199         $self->add_method('new' => Mouse::Meta::Method::Constructor->generate_constructor_method_inline( $self ));
200     }
201
202     if ($args{inline_destructor}) {
203         $self->add_method('DESTROY' => Mouse::Meta::Method::Destructor->generate_destructor_method_inline( $self ));
204     }
205
206     # Moose's make_immutable returns true allowing calling code to skip setting an explicit true value
207     # at the end of a source file. 
208     return 1;
209 }
210
211 sub make_mutable { not_supported }
212
213 sub is_immutable {  $_[0]->{is_immutable} }
214 sub is_mutable   { !$_[0]->{is_immutable} }
215
216 sub _install_modifier {
217     my ( $self, $into, $type, $name, $code ) = @_;
218
219     # which is modifer class available?
220     my $modifier_class = do {
221         if (eval "require Class::Method::Modifiers::Fast; 1") {
222             'Class::Method::Modifiers::Fast';
223         } elsif (eval "require Class::Method::Modifiers; 1") {
224             'Class::Method::Modifiers';
225         } else {
226             Carp::croak("Method modifiers require the use of Class::Method::Modifiers or Class::Method::Modifiers::Fast. Please install it from CPAN and file a bug report with this application.");
227         }
228     };
229     my $modifier = $modifier_class->can('_install_modifier');
230
231     # replace this method itself :)
232     {
233         no warnings 'redefine';
234         *_install_modifier = sub {
235             my ( $self, $into, $type, $name, $code ) = @_;
236             $modifier->(
237                 $into,
238                 $type,
239                 $name,
240                 $code
241             );
242             $self->{methods}{$name}++; # register it to the method map
243             return;
244         };
245     }
246
247     # call me. for first time.
248     $self->_install_modifier( $into, $type, $name, $code );
249 }
250
251 sub add_before_method_modifier {
252     my ( $self, $name, $code ) = @_;
253     $self->_install_modifier( $self->name, 'before', $name, $code );
254 }
255
256 sub add_around_method_modifier {
257     my ( $self, $name, $code ) = @_;
258     $self->_install_modifier( $self->name, 'around', $name, $code );
259 }
260
261 sub add_after_method_modifier {
262     my ( $self, $name, $code ) = @_;
263     $self->_install_modifier( $self->name, 'after', $name, $code );
264 }
265
266 sub add_override_method_modifier {
267     my ($self, $name, $code) = @_;
268
269     my $package = $self->name;
270
271     my $body = $package->can($name)
272         or $self->throw_error("You cannot override '$name' because it has no super method");
273
274     $self->add_method($name => sub { $code->($package, $body, @_) });
275 }
276
277 sub does_role {
278     my ($self, $role_name) = @_;
279
280     (defined $role_name)
281         || $self->throw_error("You must supply a role name to look for");
282
283     for my $class ($self->linearized_isa) {
284         my $meta = Mouse::Meta::Module::class_of($class);
285         next unless $meta && $meta->can('roles');
286
287         for my $role (@{ $meta->roles }) {
288
289             return 1 if $role->does_role($role_name);
290         }
291     }
292
293     return 0;
294 }
295
296 sub create {
297     my ($class, $package_name, %options) = @_;
298
299     (ref $options{superclasses} eq 'ARRAY')
300         || $class->throw_error("You must pass an ARRAY ref of superclasses")
301             if exists $options{superclasses};
302
303     (ref $options{attributes} eq 'ARRAY')
304         || $class->throw_error("You must pass an ARRAY ref of attributes")
305             if exists $options{attributes};
306
307     (ref $options{methods} eq 'HASH')
308         || $class->throw_error("You must pass a HASH ref of methods")
309             if exists $options{methods};
310
311     (ref $options{roles} eq 'ARRAY')
312         || $class->throw_error("You must pass an ARRAY ref of roles")
313             if exists $options{roles};
314
315     # instantiate a module
316     {
317         ( defined $package_name && $package_name )
318           || $class->throw_error("You must pass a package name");
319
320         no strict 'refs';
321         ${ $package_name . '::VERSION'   } = $options{version}   if exists $options{version};
322         ${ $package_name . '::AUTHORITY' } = $options{authority} if exists $options{authority};
323     }
324
325     my %initialize_options = %options;
326     delete @initialize_options{qw(
327         package
328         superclasses
329         attributes
330         methods
331         roles
332         version
333         authority
334     )};
335     my $meta = $class->initialize( $package_name => %initialize_options );
336
337     # FIXME totally lame
338     $meta->add_method('meta' => sub {
339         Mouse::Meta::Class->initialize(ref($_[0]) || $_[0]);
340     });
341
342     $meta->superclasses(@{$options{superclasses}})
343         if exists $options{superclasses};
344
345     # NOTE:
346     # process attributes first, so that they can
347     # install accessors, but locally defined methods
348     # can then overwrite them. It is maybe a little odd, but
349     # I think this should be the order of things.
350     if (exists $options{attributes}) {
351         foreach my $attr (@{$options{attributes}}) {
352             Mouse::Meta::Attribute->create($meta, $attr->{name}, %$attr);
353         }
354     }
355     if (exists $options{methods}) {
356         foreach my $method_name (keys %{$options{methods}}) {
357             $meta->add_method($method_name, $options{methods}->{$method_name});
358         }
359     }
360     if (exists $options{roles}){
361         Mouse::Util::apply_all_roles($package_name, @{$options{roles}});
362     }
363     return $meta;
364 }
365
366 {
367     my $ANON_CLASS_SERIAL = 0;
368     my $ANON_CLASS_PREFIX = 'Mouse::Meta::Class::__ANON__::SERIAL::';
369
370     my %IMMORTAL_ANON_CLASSES;
371     sub create_anon_class {
372         my ( $class, %options ) = @_;
373
374         my $cache = $options{cache};
375         my $cache_key;
376
377         if($cache){ # anonymous but not mortal
378                 # something like Super::Class|Super::Class::2=Role|Role::1\r
379                 $cache_key = join '=' => (\r
380                     join('|', @{$options{superclasses} || []}),\r
381                     join('|', sort @{$options{roles}   || []}),\r
382                 );
383                 return $IMMORTAL_ANON_CLASSES{$cache_key} if exists $IMMORTAL_ANON_CLASSES{$cache_key};
384         }
385         my $package_name = $ANON_CLASS_PREFIX . ++$ANON_CLASS_SERIAL;
386         my $meta = $class->create( $package_name, anon_class_id => $ANON_CLASS_SERIAL, %options );
387
388         if($cache){
389             $IMMORTAL_ANON_CLASSES{$cache_key} = $meta;
390         }
391         else{
392             Mouse::Meta::Module::weaken_metaclass($package_name);
393         }
394         return $meta;
395     }
396
397     sub is_anon_class{
398         return exists $_[0]->{anon_class_id};
399     }
400
401
402     sub DESTROY{
403         my($self) = @_;
404
405         my $serial_id = $self->{anon_class_id};
406
407         return if !$serial_id;
408
409         my $stash = $self->namespace;
410
411         @{$self->{sperclasses}} = ();
412         %{$stash} = ();
413         Mouse::Meta::Module::remove_metaclass_by_name($self->name);
414
415         no strict 'refs';
416         delete ${$ANON_CLASS_PREFIX}{ $serial_id . '::' };
417
418         return;
419     }
420
421 }
422
423 1;
424
425 __END__
426
427 =head1 NAME
428
429 Mouse::Meta::Class - hook into the Mouse MOP
430
431 =head1 METHODS
432
433 =head2 initialize ClassName -> Mouse::Meta::Class
434
435 Finds or creates a Mouse::Meta::Class instance for the given ClassName. Only
436 one instance should exist for a given class.
437
438 =head2 new %args -> Mouse::Meta::Class
439
440 Creates a new Mouse::Meta::Class. Don't call this directly.
441
442 =head2 name -> ClassName
443
444 Returns the name of the owner class.
445
446 =head2 superclasses -> [ClassName]
447
448 Gets (or sets) the list of superclasses of the owner class.
449
450 =head2 add_attribute (Mouse::Meta::Attribute| name => spec)
451
452 Begins keeping track of the existing L<Mouse::Meta::Attribute> for the owner
453 class.
454
455 =head2 get_all_attributes -> (Mouse::Meta::Attribute)
456
457 Returns the list of all L<Mouse::Meta::Attribute> instances associated with
458 this class and its superclasses.
459
460 =head2 get_attribute_map -> { name => Mouse::Meta::Attribute }
461
462 Returns a mapping of attribute names to their corresponding
463 L<Mouse::Meta::Attribute> objects.
464
465 =head2 get_attribute_list -> { name => Mouse::Meta::Attribute }
466
467 This 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 has_attribute Name -> Bool
472
473 Returns whether we have a L<Mouse::Meta::Attribute> with the given name.
474
475 =head2 get_attribute Name -> Mouse::Meta::Attribute | undef
476
477 Returns the L<Mouse::Meta::Attribute> with the given name.
478
479 =head2 linearized_isa -> [ClassNames]
480
481 Returns the list of classes in method dispatch order, with duplicates removed.
482
483 =head2 clone_object Instance -> Instance
484
485 Clones the given C<Instance> which must be an instance governed by this
486 metaclass.
487
488 =head2 clone_instance Instance, Parameters -> Instance
489
490 The clone_instance method has been made private.
491 The public version is deprecated.
492
493 =cut
494