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