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