added YourClass->meta->add_attribute(foo => (is => 'ro', isa => 'Str')); support.
[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/;
8 use Mouse::Util qw/get_linear_isa/;
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 = shift;
24         my $name  = shift;
25         $METACLASS_CACHE{$name} = $class->new(name => $name)
26             if !exists($METACLASS_CACHE{$name});
27         return $METACLASS_CACHE{$name};
28     }
29 };
30
31 sub new {
32     my $class = shift;
33     my %args  = @_;
34
35     $args{attributes} = {};
36     $args{superclasses} = do {
37         no strict 'refs';
38         \@{ $args{name} . '::ISA' };
39     };
40     $args{roles} ||= [];
41
42     bless \%args, $class;
43 }
44
45 sub name { $_[0]->{name} }
46
47 sub superclasses {
48     my $self = shift;
49
50     if (@_) {
51         Mouse::load_class($_) for @_;
52         @{ $self->{superclasses} } = @_;
53     }
54
55     @{ $self->{superclasses} };
56 }
57
58 sub add_method {
59     my $self = shift;
60     my $name = shift;
61     my $code = shift;
62
63     my $pkg = $self->name;
64
65     no strict 'refs';
66     no warnings 'redefine';
67     $self->{'methods'}->{$name}++; # Moose stores meta object here.
68     *{ $pkg . '::' . $name } = $code;
69 }
70
71 # copied from Class::Inspector
72 my $get_methods_for_class = sub {
73     my $self = shift;
74     my $name = shift;
75
76     no strict 'refs';
77     # Get all the CODE symbol table entries
78     my @functions =
79       grep !/^(?:has|with|around|before|after|blessed|extends|confess|override|super)$/,
80       grep { defined &{"${name}::$_"} }
81       keys %{"${name}::"};
82     push @functions, keys %{$self->{'methods'}->{$name}} if $self;
83     wantarray ? @functions : \@functions;
84 };
85
86 sub get_method_list {
87     my $self = shift;
88     $get_methods_for_class->($self, $self->name);
89 }
90
91 sub get_all_method_names {
92     my $self = shift;
93     my %uniq;
94     return grep { $uniq{$_}++ == 0 }
95             map { $get_methods_for_class->(undef, $_) }
96             $self->linearized_isa;
97 }
98
99 sub add_attribute {
100     my $self = shift;
101
102     if (@_ == 1 && blessed($_[0])) {
103         my $attr = shift @_;
104         $self->{'attributes'}{$attr->name} = $attr;
105     } else {
106         my $names = shift @_;
107         $names = [$names] if !ref($names);
108         my $metaclass = 'Mouse::Meta::Attribute';
109         my %options = @_;
110
111         if ( my $metaclass_name = delete $options{metaclass} ) {
112             my $new_class = Mouse::Util::resolve_metaclass_alias(
113                 'Attribute',
114                 $metaclass_name
115             );
116             if ( $metaclass ne $new_class ) {
117                 $metaclass = $new_class;
118             }
119         }
120
121         for my $name (@$names) {
122             if ($name =~ s/^\+//) {
123                 $metaclass->clone_parent($self, $name, @_);
124             }
125             else {
126                 $metaclass->create($self, $name, @_);
127             }
128         }
129     }
130 }
131
132 sub compute_all_applicable_attributes {
133     my $self = shift;
134     my (@attr, %seen);
135
136     for my $class ($self->linearized_isa) {
137         my $meta = $self->_metaclass_cache($class)
138             or next;
139
140         for my $name (keys %{ $meta->get_attribute_map }) {
141             next if $seen{$name}++;
142             push @attr, $meta->get_attribute($name);
143         }
144     }
145
146     return @attr;
147 }
148
149 sub get_attribute_map { $_[0]->{attributes} }
150 sub has_attribute     { exists $_[0]->{attributes}->{$_[1]} }
151 sub get_attribute     { $_[0]->{attributes}->{$_[1]} }
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->compute_all_applicable_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         @_,
190     );
191
192     my $name = $self->name;
193     $self->{is_immutable}++;
194
195     if ($args{inline_constructor}) {
196         $self->add_method('new' => Mouse::Meta::Method::Constructor->generate_constructor_method_inline( $self ));
197     }
198
199     if ($args{inline_destructor}) {
200         $self->add_method('DESTROY' => Mouse::Meta::Method::Destructor->generate_destructor_method_inline( $self ));
201     }
202
203     # Moose's make_immutable returns true allowing calling code to skip setting an explicit true value
204     # at the end of a source file. 
205     return 1;
206 }
207
208 sub make_mutable { confess "Mouse does not currently support 'make_mutable'" }
209
210 sub is_immutable { $_[0]->{is_immutable} }
211
212 sub attribute_metaclass { "Mouse::Meta::Class" }
213
214 sub _install_modifier {
215     my ( $self, $into, $type, $name, $code ) = @_;
216
217     # which is modifer class available?
218     my $modifier_class = do {
219         if (eval "require Class::Method::Modifiers::Fast; 1") {
220             'Class::Method::Modifiers::Fast';
221         } elsif (eval "require Class::Method::Modifiers; 1") {
222             'Class::Method::Modifiers';
223         } else {
224             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.");
225         }
226     };
227     my $modifier = $modifier_class->can('_install_modifier');
228
229     # replace this method itself :)
230     {
231         no strict 'refs';
232         no warnings 'redefine';
233         *{__PACKAGE__ . '::_install_modifier'} = sub {
234             my ( $self, $into, $type, $name, $code ) = @_;
235             $modifier->(
236                 $into,
237                 $type,
238                 $name,
239                 $code
240             );
241         };
242     }
243
244     # call me. for first time.
245     $self->_install_modifier( $into, $type, $name, $code );
246 }
247
248 sub add_before_method_modifier {
249     my ( $self, $name, $code ) = @_;
250     $self->_install_modifier( $self->name, 'before', $name, $code );
251 }
252
253 sub add_around_method_modifier {
254     my ( $self, $name, $code ) = @_;
255     $self->_install_modifier( $self->name, 'around', $name, $code );
256 }
257
258 sub add_after_method_modifier {
259     my ( $self, $name, $code ) = @_;
260     $self->_install_modifier( $self->name, 'after', $name, $code );
261 }
262
263 sub roles { $_[0]->{roles} }
264
265 sub does_role {
266     my ($self, $role_name) = @_;
267
268     (defined $role_name)
269         || confess "You must supply a role name to look for";
270
271     for my $role (@{ $self->{roles} }) {
272         return 1 if $role->name eq $role_name;
273     }
274
275     return 0;
276 }
277
278 sub create {
279     my ($self, $package_name, %options) = @_;
280
281     (ref $options{superclasses} eq 'ARRAY')
282         || confess "You must pass an ARRAY ref of superclasses"
283             if exists $options{superclasses};
284
285     (ref $options{attributes} eq 'ARRAY')
286         || confess "You must pass an ARRAY ref of attributes"
287             if exists $options{attributes};
288
289     (ref $options{methods} eq 'HASH')
290         || confess "You must pass a HASH ref of methods"
291             if exists $options{methods};
292
293     do {
294         ( defined $package_name && $package_name )
295           || confess "You must pass a package name";
296
297         my $code = "package $package_name;";
298         $code .= "\$$package_name\:\:VERSION = '" . $options{version} . "';"
299           if exists $options{version};
300         $code .= "\$$package_name\:\:AUTHORITY = '" . $options{authority} . "';"
301           if exists $options{authority};
302
303         eval $code;
304         confess "creation of $package_name failed : $@" if $@;
305     };
306
307     my %initialize_options = %options;
308     delete @initialize_options{qw(
309         package
310         superclasses
311         attributes
312         methods
313         version
314         authority
315     )};
316     my $meta = $self->initialize( $package_name => %initialize_options );
317
318     # FIXME totally lame
319     $meta->add_method('meta' => sub {
320         $self->initialize(ref($_[0]) || $_[0]);
321     });
322
323     $meta->superclasses(@{$options{superclasses}})
324         if exists $options{superclasses};
325     # NOTE:
326     # process attributes first, so that they can
327     # install accessors, but locally defined methods
328     # can then overwrite them. It is maybe a little odd, but
329     # I think this should be the order of things.
330     if (exists $options{attributes}) {
331         foreach my $attr (@{$options{attributes}}) {
332             Mouse::Meta::Attribute->create($meta, $attr->{name}, %$attr);
333         }
334     }
335     if (exists $options{methods}) {
336         foreach my $method_name (keys %{$options{methods}}) {
337             $meta->add_method($method_name, $options{methods}->{$method_name});
338         }
339     }
340     return $meta;
341 }
342
343 {
344     my $ANON_CLASS_SERIAL = 0;
345     my $ANON_CLASS_PREFIX = 'Mouse::Meta::Class::__ANON__::SERIAL::';
346     sub create_anon_class {
347         my ( $class, %options ) = @_;
348         my $package_name = $ANON_CLASS_PREFIX . ++$ANON_CLASS_SERIAL;
349         return $class->create( $package_name, %options );
350     }
351 }
352
353 1;
354
355 __END__
356
357 =head1 NAME
358
359 Mouse::Meta::Class - hook into the Mouse MOP
360
361 =head1 METHODS
362
363 =head2 initialize ClassName -> Mouse::Meta::Class
364
365 Finds or creates a Mouse::Meta::Class instance for the given ClassName. Only
366 one instance should exist for a given class.
367
368 =head2 new %args -> Mouse::Meta::Class
369
370 Creates a new Mouse::Meta::Class. Don't call this directly.
371
372 =head2 name -> ClassName
373
374 Returns the name of the owner class.
375
376 =head2 superclasses -> [ClassName]
377
378 Gets (or sets) the list of superclasses of the owner class.
379
380 =head2 add_attribute (Mouse::Meta::Attribute| name => spec)
381
382 Begins keeping track of the existing L<Mouse::Meta::Attribute> for the owner
383 class.
384
385 =head2 compute_all_applicable_attributes -> (Mouse::Meta::Attribute)
386
387 Returns the list of all L<Mouse::Meta::Attribute> instances associated with
388 this class and its superclasses.
389
390 =head2 get_attribute_map -> { name => Mouse::Meta::Attribute }
391
392 Returns a mapping of attribute names to their corresponding
393 L<Mouse::Meta::Attribute> objects.
394
395 =head2 has_attribute Name -> Bool
396
397 Returns whether we have a L<Mouse::Meta::Attribute> with the given name.
398
399 =head2 get_attribute Name -> Mouse::Meta::Attribute | undef
400
401 Returns the L<Mouse::Meta::Attribute> with the given name.
402
403 =head2 linearized_isa -> [ClassNames]
404
405 Returns the list of classes in method dispatch order, with duplicates removed.
406
407 =head2 clone_object Instance -> Instance
408
409 Clones the given C<Instance> which must be an instance governed by this
410 metaclass.
411
412 =head2 clone_instance Instance, Parameters -> Instance
413
414 Clones the given C<Instance> and sets any additional parameters.
415
416 =cut
417