Add various 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 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     #return Mouse::Meta::Class->initialize($class)->new_object(%args)
27     #    if $class ne __PACKAGE__;
28
29     return bless \%args, $class;
30 }
31
32 sub create_anon_class{
33     my $self = shift;
34     return $self->create(undef, @_);
35 }
36
37 sub is_anon_class{
38     return exists $_[0]->{anon_serial_id};
39 }
40
41 sub roles { $_[0]->{roles} }
42
43 sub superclasses {
44     my $self = shift;
45
46     if (@_) {
47         Mouse::load_class($_) for @_;
48         @{ $self->{superclasses} } = @_;
49     }
50
51     @{ $self->{superclasses} };
52 }
53
54 sub get_all_method_names {
55     my $self = shift;
56     my %uniq;
57     return grep { $uniq{$_}++ == 0 }
58             map { Mouse::Meta::Class->initialize($_)->get_method_list() }
59             $self->linearized_isa;
60 }
61
62 sub add_attribute {
63     my $self = shift;
64
65     if (@_ == 1 && blessed($_[0])) {
66         my $attr = shift @_;
67         $self->{'attributes'}{$attr->name} = $attr;
68     }
69     else {
70         my $names = shift @_;
71         $names = [$names] if !ref($names);
72         my $metaclass = 'Mouse::Meta::Attribute';
73         my %options   = (@_ == 1 ? %{$_[0]} : @_);
74
75         if ( my $metaclass_name = delete $options{metaclass} ) {
76             my $new_class = Mouse::Util::resolve_metaclass_alias(
77                 'Attribute',
78                 $metaclass_name
79             );
80             if ( $metaclass ne $new_class ) {
81                 $metaclass = $new_class;
82             }
83         }
84
85         for my $name (@$names) {
86             if ($name =~ s/^\+//) {
87                 $metaclass->clone_parent($self, $name, %options);
88             }
89             else {
90                 $metaclass->create($self, $name, %options);
91             }
92         }
93     }
94 }
95
96 sub compute_all_applicable_attributes { shift->get_all_attributes(@_) }
97 sub get_all_attributes {
98     my $self = shift;
99     my (@attr, %seen);
100
101     for my $class ($self->linearized_isa) {
102         my $meta = $self->_metaclass_cache($class)
103             or next;
104
105         for my $name (keys %{ $meta->get_attribute_map }) {
106             next if $seen{$name}++;
107             push @attr, $meta->get_attribute($name);
108         }
109     }
110
111     return @attr;
112 }
113
114 sub linearized_isa { @{ get_linear_isa($_[0]->name) } }
115
116 sub new_object {
117     my $self = shift;
118     my %args = (@_ == 1 ? %{$_[0]} : @_);
119
120     my $instance = bless {}, $self->name;
121
122     foreach my $attribute ($self->get_all_attributes) {
123         my $from = $attribute->init_arg;
124         my $key  = $attribute->name;
125
126         if (defined($from) && exists($args{$from})) {
127             $args{$from} = $attribute->coerce_constraint($args{$from})
128                 if $attribute->should_coerce;
129             $attribute->verify_against_type_constraint($args{$from});
130
131             $instance->{$key} = $args{$from};
132
133             weaken($instance->{$key})
134                 if ref($instance->{$key}) && $attribute->is_weak_ref;
135
136             if ($attribute->has_trigger) {
137                 $attribute->trigger->($instance, $args{$from});
138             }
139         }
140         else {
141             if ($attribute->has_default || $attribute->has_builder) {
142                 unless ($attribute->is_lazy) {
143                     my $default = $attribute->default;
144                     my $builder = $attribute->builder;
145                     my $value = $attribute->has_builder
146                               ? $instance->$builder
147                               : ref($default) eq 'CODE'
148                                   ? $default->($instance)
149                                   : $default;
150
151                     $value = $attribute->coerce_constraint($value)
152                         if $attribute->should_coerce;
153                     $attribute->verify_against_type_constraint($value);
154
155                     $instance->{$key} = $value;
156
157                     weaken($instance->{$key})
158                         if ref($instance->{$key}) && $attribute->is_weak_ref;
159                 }
160             }
161             else {
162                 if ($attribute->is_required) {
163                     $self->throw_error("Attribute (".$attribute->name.") is required");
164                 }
165             }
166         }
167     }
168     return $instance;
169 }
170
171 sub clone_object {
172     my $class    = shift;
173     my $instance = shift;
174
175     (blessed($instance) && $instance->isa($class->name))
176         || $class->throw_error("You must pass an instance of the metaclass (" . $class->name . "), not ($instance)");
177
178     $class->clone_instance($instance, @_);
179 }
180
181 sub clone_instance {
182     my ($class, $instance, %params) = @_;
183
184     (blessed($instance))
185         || $class->throw_error("You can only clone instances, ($instance) is not a blessed instance");
186
187     my $clone = bless { %$instance }, ref $instance;
188
189     foreach my $attr ($class->get_all_attributes()) {
190         if ( defined( my $init_arg = $attr->init_arg ) ) {
191             if (exists $params{$init_arg}) {
192                 $clone->{ $attr->name } = $params{$init_arg};
193             }
194         }
195     }
196
197     return $clone;
198
199 }
200
201 sub make_immutable {
202     my $self = shift;
203     my %args = (
204         inline_constructor => 1,
205         inline_destructor  => 1,
206         @_,
207     );
208
209     $self->{is_immutable}++;
210
211     if ($args{inline_constructor}) {
212         $self->add_method('new' => Mouse::Meta::Method::Constructor->generate_constructor_method_inline( $self ));
213     }
214
215     if ($args{inline_destructor}) {
216         $self->add_method('DESTROY' => Mouse::Meta::Method::Destructor->generate_destructor_method_inline( $self ));
217     }
218
219     # Moose's make_immutable returns true allowing calling code to skip setting an explicit true value
220     # at the end of a source file. 
221     return 1;
222 }
223
224 sub make_mutable { not_supported }
225
226 sub is_immutable {  $_[0]->{is_immutable} }
227 sub is_mutable   { !$_[0]->{is_immutable} }
228
229 sub _install_modifier {
230     my ( $self, $into, $type, $name, $code ) = @_;
231
232     # which is modifer class available?
233     my $modifier_class = do {
234         if (eval "require Class::Method::Modifiers::Fast; 1") {
235             'Class::Method::Modifiers::Fast';
236         } elsif (eval "require Class::Method::Modifiers; 1") {
237             'Class::Method::Modifiers';
238         } else {
239             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.");
240         }
241     };
242     my $modifier = $modifier_class->can('_install_modifier');
243
244     # replace this method itself :)
245     {
246         no warnings 'redefine';
247         *_install_modifier = sub {
248             my ( $self, $into, $type, $name, $code ) = @_;
249             $modifier->(
250                 $into,
251                 $type,
252                 $name,
253                 $code
254             );
255             $self->{methods}{$name}++; # register it to the method map
256             return;
257         };
258     }
259
260     # call me. for first time.
261     $self->_install_modifier( $into, $type, $name, $code );
262 }
263
264 sub add_before_method_modifier {
265     my ( $self, $name, $code ) = @_;
266     $self->_install_modifier( $self->name, 'before', $name, $code );
267 }
268
269 sub add_around_method_modifier {
270     my ( $self, $name, $code ) = @_;
271     $self->_install_modifier( $self->name, 'around', $name, $code );
272 }
273
274 sub add_after_method_modifier {
275     my ( $self, $name, $code ) = @_;
276     $self->_install_modifier( $self->name, 'after', $name, $code );
277 }
278
279 sub add_override_method_modifier {
280     my ($self, $name, $code) = @_;
281
282     my $package = $self->name;
283
284     my $body = $package->can($name)
285         or $self->throw_error("You cannot override '$name' because it has no super method");
286
287     $self->add_method($name => sub { $code->($package, $body, @_) });
288 }
289
290 sub does_role {
291     my ($self, $role_name) = @_;
292
293     (defined $role_name)
294         || $self->throw_error("You must supply a role name to look for");
295
296     for my $class ($self->linearized_isa) {
297         my $meta = Mouse::Meta::Module::class_of($class);
298         next unless $meta && $meta->can('roles');
299
300         for my $role (@{ $meta->roles }) {
301
302             return 1 if $role->does_role($role_name);
303         }
304     }
305
306     return 0;
307 }
308
309 1;
310
311 __END__
312
313 =head1 NAME
314
315 Mouse::Meta::Class - hook into the Mouse MOP
316
317 =head1 METHODS
318
319 =head2 initialize ClassName -> Mouse::Meta::Class
320
321 Finds or creates a Mouse::Meta::Class instance for the given ClassName. Only
322 one instance should exist for a given class.
323
324 =head2 new %args -> Mouse::Meta::Class
325
326 Creates a new Mouse::Meta::Class. Don't call this directly.
327
328 =head2 name -> ClassName
329
330 Returns the name of the owner class.
331
332 =head2 superclasses -> [ClassName]
333
334 Gets (or sets) the list of superclasses of the owner class.
335
336 =head2 add_attribute (Mouse::Meta::Attribute| name => spec)
337
338 Begins keeping track of the existing L<Mouse::Meta::Attribute> for the owner
339 class.
340
341 =head2 get_all_attributes -> (Mouse::Meta::Attribute)
342
343 Returns the list of all L<Mouse::Meta::Attribute> instances associated with
344 this class and its superclasses.
345
346 =head2 get_attribute_map -> { name => Mouse::Meta::Attribute }
347
348 Returns a mapping of attribute names to their corresponding
349 L<Mouse::Meta::Attribute> objects.
350
351 =head2 get_attribute_list -> { name => Mouse::Meta::Attribute }
352
353 This returns a list of attribute names which are defined in the local
354 class. If you want a list of all applicable attributes for a class,
355 use the C<get_all_attributes> method.
356
357 =head2 has_attribute Name -> Bool
358
359 Returns whether we have a L<Mouse::Meta::Attribute> with the given name.
360
361 =head2 get_attribute Name -> Mouse::Meta::Attribute | undef
362
363 Returns the L<Mouse::Meta::Attribute> with the given name.
364
365 =head2 linearized_isa -> [ClassNames]
366
367 Returns the list of classes in method dispatch order, with duplicates removed.
368
369 =head2 clone_object Instance -> Instance
370
371 Clones the given C<Instance> which must be an instance governed by this
372 metaclass.
373
374 =head2 clone_instance Instance, Parameters -> Instance
375
376 The clone_instance method has been made private.
377 The public version is deprecated.
378
379 =cut
380