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