Move type coercion mechanism from Util/TypeConstraints.pm to Meta/TypeConstraint.pm
[gitmo/Mouse.git] / lib / Mouse / Meta / Class.pm
CommitLineData
306290e8 1package Mouse::Meta::Class;
c3398f5b 2use strict;
3use warnings;
4
cecfb973 5use Scalar::Util qw/blessed weaken/;
6d28c5cf 6
04493075 7use Mouse::Util qw/:meta get_linear_isa not_supported/;
72b88a88 8
6d28c5cf 9use Mouse::Meta::Method::Constructor;
10use Mouse::Meta::Method::Destructor;
11use Mouse::Meta::Module;
f3bb863f 12our @ISA = qw(Mouse::Meta::Module);
3a63a2e7 13
6cfa1e5e 14sub method_metaclass(){ 'Mouse::Meta::Method' } # required for get_method()
3a63a2e7 15
8e64d0fa 16sub _construct_meta {
88ed7189 17 my($class, %args) = @_;
c3398f5b 18
8536d351 19 $args{attributes} ||= {};
20 $args{methods} ||= {};
21 $args{roles} ||= [];
22
c3398f5b 23 $args{superclasses} = do {
24 no strict 'refs';
88ed7189 25 \@{ $args{package} . '::ISA' };
c3398f5b 26 };
27
7a50b450 28 #return Mouse::Meta::Class->initialize($class)->new_object(%args)
29 # if $class ne __PACKAGE__;
30
8e64d0fa 31 return bless \%args, ref($class) || $class;
7a50b450 32}
33
34sub create_anon_class{
35 my $self = shift;
36 return $self->create(undef, @_);
37}
38
39sub is_anon_class{
40 return exists $_[0]->{anon_serial_id};
c3398f5b 41}
42
afc73948 43sub roles { $_[0]->{roles} }
c3398f5b 44
45sub superclasses {
46 my $self = shift;
47
48 if (@_) {
49 Mouse::load_class($_) for @_;
50 @{ $self->{superclasses} } = @_;
51 }
52
8e64d0fa 53 return @{ $self->{superclasses} };
54}
55
56sub find_method_by_name{
57 my($self, $method_name) = @_;
58 defined($method_name)
59 or $self->throw_error('You must define a method name to find');
60 foreach my $class( $self->linearized_isa ){
61 my $method = $self->initialize($class)->get_method($method_name);
62 return $method if defined $method;
63 }
64 return undef;
65}
66
67sub get_all_methods {
68 my($self) = @_;
612d3e1a 69 return map{ $self->find_method_by_name($_) } $self->get_all_method_names;
c3398f5b 70}
71
60cfc6ad 72sub get_all_method_names {
73 my $self = shift;
74 my %uniq;
75 return grep { $uniq{$_}++ == 0 }
3a63a2e7 76 map { Mouse::Meta::Class->initialize($_)->get_method_list() }
60cfc6ad 77 $self->linearized_isa;
78}
79
87ca293b 80sub add_attribute {
c3398f5b 81 my $self = shift;
60f6eba9 82
87ca293b 83 my($attr, $name);
1b9e472d 84
87ca293b 85 if(blessed $_[0]){
86 $attr = $_[0];
1b9e472d 87
87ca293b 88 $attr->isa('Mouse::Meta::Attribute')
89 || $self->throw_error("Your attribute must be an instance of Mouse::Meta::Attribute (or a subclass)");
1b9e472d 90
87ca293b 91 $name = $attr->name;
1b9e472d 92 }
93 else{
87ca293b 94 # _process_attribute
95 $name = shift;
1b9e472d 96
87ca293b 97 my %args = (@_ == 1) ? %{$_[0]} : @_;
1b9e472d 98
87ca293b 99 defined($name)
100 or $self->throw_error('You must provide a name for the attribute');
1b9e472d 101
87ca293b 102 if ($name =~ s/^\+//) { # inherited attributes
103 my $inherited_attr;
104
105 foreach my $class($self->linearized_isa){
106 my $meta = Mouse::Meta::Module::get_metaclass_by_name($class) or next;
107 $inherited_attr = $meta->get_attribute($name) and last;
108 }
109
110 defined($inherited_attr)
111 or $self->throw_error("Could not find an attribute by the name of '$name' to inherit from in ".$self->name);
112
113 $attr = $inherited_attr->clone_and_inherit_options($name, \%args);
114 }
115 else{
116 my($attribute_class, @traits) = Mouse::Meta::Attribute->interpolate_class($name, \%args);
117 $args{traits} = \@traits if @traits;
118
119 $attr = $attribute_class->new($name, \%args);
120 }
121 }
1b9e472d 122
123 weaken( $attr->{associated_class} = $self );
124
125 $self->{attributes}{$attr->name} = $attr;
126 $attr->install_accessors();
127
04493075 128 if(_MOUSE_VERBOSE && !$attr->{associated_methods} && ($attr->{is} || '') ne 'bare'){
1b9e472d 129 Carp::cluck(qq{Attribute (}.$attr->name.qq{) of class }.$self->name.qq{ has no associated methods (did you mean to provide an "is" argument?)});
60f6eba9 130 }
1b9e472d 131 return $attr;
c3398f5b 132}
133
d60824af 134sub compute_all_applicable_attributes { shift->get_all_attributes(@_) }
135sub get_all_attributes {
72b88a88 136 my $self = shift;
137 my (@attr, %seen);
138
139 for my $class ($self->linearized_isa) {
140 my $meta = $self->_metaclass_cache($class)
141 or next;
142
143 for my $name (keys %{ $meta->get_attribute_map }) {
144 next if $seen{$name}++;
145 push @attr, $meta->get_attribute($name);
146 }
147 }
148
149 return @attr;
150}
151
8536d351 152sub linearized_isa { @{ get_linear_isa($_[0]->name) } }
153
154sub new_object {
c68b4110 155 my $self = shift;
7a50b450 156 my %args = (@_ == 1 ? %{$_[0]} : @_);
c3398f5b 157
fce211ae 158 my $instance = bless {}, $self->name;
159
1b9e472d 160 $self->_initialize_instance($instance, \%args);
161 return $instance;
162}
163
164sub _initialize_instance{
165 my($self, $instance, $args) = @_;
166
53c495ce 167 my @triggers_queue;
168
fce211ae 169 foreach my $attribute ($self->get_all_attributes) {
8536d351 170 my $from = $attribute->init_arg;
171 my $key = $attribute->name;
172
1b9e472d 173 if (defined($from) && exists($args->{$from})) {
ffbbf459 174 $instance->{$key} = $attribute->_coerce_and_verify($args->{$from});
8536d351 175
176 weaken($instance->{$key})
fce211ae 177 if ref($instance->{$key}) && $attribute->is_weak_ref;
8536d351 178
179 if ($attribute->has_trigger) {
ffbbf459 180 push @triggers_queue, [ $attribute->trigger, $instance->{$from} ];
8536d351 181 }
182 }
183 else {
184 if ($attribute->has_default || $attribute->has_builder) {
185 unless ($attribute->is_lazy) {
186 my $default = $attribute->default;
187 my $builder = $attribute->builder;
188 my $value = $attribute->has_builder
189 ? $instance->$builder
190 : ref($default) eq 'CODE'
191 ? $default->($instance)
192 : $default;
193
194 $value = $attribute->coerce_constraint($value)
195 if $attribute->should_coerce;
196 $attribute->verify_against_type_constraint($value);
197
198 $instance->{$key} = $value;
199
200 weaken($instance->{$key})
fce211ae 201 if ref($instance->{$key}) && $attribute->is_weak_ref;
8536d351 202 }
203 }
204 else {
205 if ($attribute->is_required) {
fce211ae 206 $self->throw_error("Attribute (".$attribute->name.") is required");
8536d351 207 }
208 }
209 }
210 }
53c495ce 211
212 foreach my $trigger_and_value(@triggers_queue){
213 my($trigger, $value) = @{$trigger_and_value};
214 $trigger->($instance, $value);
215 }
216
2efc0af1 217 if($self->is_anon_class){
218 $instance->{__METACLASS__} = $self;
219 }
220
8536d351 221 return $instance;
222}
c3398f5b 223
7a59f4e8 224sub clone_object {
225 my $class = shift;
226 my $instance = shift;
2cea7a5f 227 my %params = (@_ == 1) ? %{$_[0]} : @_;
7a59f4e8 228
229 (blessed($instance) && $instance->isa($class->name))
fce211ae 230 || $class->throw_error("You must pass an instance of the metaclass (" . $class->name . "), not ($instance)");
7a59f4e8 231
7a59f4e8 232 my $clone = bless { %$instance }, ref $instance;
233
d60824af 234 foreach my $attr ($class->get_all_attributes()) {
7a59f4e8 235 if ( defined( my $init_arg = $attr->init_arg ) ) {
236 if (exists $params{$init_arg}) {
237 $clone->{ $attr->name } = $params{$init_arg};
238 }
239 }
240 }
241
242 return $clone;
2cea7a5f 243}
7a59f4e8 244
2cea7a5f 245sub clone_instance {
246 my ($class, $instance, %params) = @_;
247
04493075 248 Carp::cluck('clone_instance has been deprecated. Use clone_object instead')
249 if _MOUSE_VERBOSE;
2cea7a5f 250 return $class->clone_object($instance, %params);
7a59f4e8 251}
252
fc1d8369 253sub make_immutable {
254 my $self = shift;
6a1d1835 255 my %args = (
256 inline_constructor => 1,
e578d610 257 inline_destructor => 1,
6a1d1835 258 @_,
259 );
260
fc1d8369 261 $self->{is_immutable}++;
c7a6403f 262
6a1d1835 263 if ($args{inline_constructor}) {
c7a6403f 264 $self->add_method('new' => Mouse::Meta::Method::Constructor->generate_constructor_method_inline( $self ));
265 }
266
8632b6fe 267 if ($args{inline_destructor}) {
268 $self->add_method('DESTROY' => Mouse::Meta::Method::Destructor->generate_destructor_method_inline( $self ));
269 }
2276cb14 270
271 # Moose's make_immutable returns true allowing calling code to skip setting an explicit true value
272 # at the end of a source file.
273 return 1;
fc1d8369 274}
ad958001 275
fce211ae 276sub make_mutable { not_supported }
ad958001 277
6cfa1e5e 278sub is_immutable { $_[0]->{is_immutable} }
279sub is_mutable { !$_[0]->{is_immutable} }
84ef660f 280
3fbade18 281sub _install_modifier_pp{
282 my( $self, $into, $type, $name, $code ) = @_;
283
284 my $original = $into->can($name)
285 or $self->throw_error("The method '$name' is not found in the inheritance hierarchy for class $into");
286
287 my $modifier_table = $self->{modifiers}{$name};
288
289 if(!$modifier_table){
290 my(@before, @after, @around, $cache, $modified);
291
292 $cache = $original;
293
294 $modified = sub {
295 for my $c (@before) { $c->(@_) }
296
297 if(wantarray){ # list context
298 my @rval = $cache->(@_);
299
300 for my $c(@after){ $c->(@_) }
301 return @rval;
302 }
303 elsif(defined wantarray){ # scalar context
304 my $rval = $cache->(@_);
305
306 for my $c(@after){ $c->(@_) }
307 return $rval;
308 }
309 else{ # void context
310 $cache->(@_);
311
312 for my $c(@after){ $c->(@_) }
313 return;
314 }
315 };
316
317 $self->{modifiers}{$name} = $modifier_table = {
318 original => $original,
319
320 before => \@before,
321 after => \@after,
322 around => \@around,
323
324 cache => \$cache, # cache for around modifiers
325 };
326
327 $self->add_method($name => $modified);
328 }
329
330 if($type eq 'before'){
331 unshift @{$modifier_table->{before}}, $code;
332 }
333 elsif($type eq 'after'){
334 push @{$modifier_table->{after}}, $code;
335 }
336 else{ # around
337 push @{$modifier_table->{around}}, $code;
338
339 my $next = ${ $modifier_table->{cache} };
340 ${ $modifier_table->{cache} } = sub{ $code->($next, @_) };
341 }
342
343 return;
344}
345
4859d490 346sub _install_modifier {
347 my ( $self, $into, $type, $name, $code ) = @_;
4f5b44a0 348
3fbade18 349 # load Class::Method::Modifiers first
7ca5c5fb 350 my $no_cmm_fast = do{
3fbade18 351 local $@;
352 eval q{ require Class::Method::Modifiers::Fast };
353 $@;
4f5b44a0 354 };
4f5b44a0 355
3fbade18 356 my $impl;
357 if($no_cmm_fast){
358 $impl = \&_install_modifier_pp;
359 }
360 else{
361 my $install_modifier = Class::Method::Modifiers::Fast->can('_install_modifier');
362 $impl = sub {
4f5b44a0 363 my ( $self, $into, $type, $name, $code ) = @_;
3fbade18 364 $install_modifier->(
4f5b44a0 365 $into,
366 $type,
367 $name,
368 $code
369 );
6cfa1e5e 370 $self->{methods}{$name}++; # register it to the method map
371 return;
4f5b44a0 372 };
1b79a118 373 }
4f5b44a0 374
3fbade18 375 # replace this method itself :)
376 {
377 no warnings 'redefine';
378 *_install_modifier = $impl;
379 }
380
381 $self->$impl( $into, $type, $name, $code );
4859d490 382}
383
50dc6ee5 384sub add_before_method_modifier {
4859d490 385 my ( $self, $name, $code ) = @_;
386 $self->_install_modifier( $self->name, 'before', $name, $code );
50dc6ee5 387}
388
389sub add_around_method_modifier {
4859d490 390 my ( $self, $name, $code ) = @_;
391 $self->_install_modifier( $self->name, 'around', $name, $code );
50dc6ee5 392}
393
394sub add_after_method_modifier {
4859d490 395 my ( $self, $name, $code ) = @_;
396 $self->_install_modifier( $self->name, 'after', $name, $code );
50dc6ee5 397}
398
67199842 399sub add_override_method_modifier {
400 my ($self, $name, $code) = @_;
401
6cfa1e5e 402 my $package = $self->name;
67199842 403
6cfa1e5e 404 my $body = $package->can($name)
405 or $self->throw_error("You cannot override '$name' because it has no super method");
67199842 406
6cfa1e5e 407 $self->add_method($name => sub { $code->($package, $body, @_) });
67199842 408}
409
47f36c05 410sub does_role {
411 my ($self, $role_name) = @_;
ad958001 412
47f36c05 413 (defined $role_name)
fce211ae 414 || $self->throw_error("You must supply a role name to look for");
ad958001 415
f7fec86c 416 for my $class ($self->linearized_isa) {
08f7a8db 417 my $meta = Mouse::Meta::Module::class_of($class);
3a63a2e7 418 next unless $meta && $meta->can('roles');
419
420 for my $role (@{ $meta->roles }) {
ff687069 421
3a63a2e7 422 return 1 if $role->does_role($role_name);
f7fec86c 423 }
47f36c05 424 }
ad958001 425
47f36c05 426 return 0;
427}
428
c3398f5b 4291;
430
431__END__
432
433=head1 NAME
434
1820fffe 435Mouse::Meta::Class - The Mouse class metaclass
c3398f5b 436
437=head1 METHODS
438
612d3e1a 439=head2 C<< initialize(ClassName) -> Mouse::Meta::Class >>
c3398f5b 440
31c5194b 441Finds or creates a C<Mouse::Meta::Class> instance for the given ClassName. Only
306290e8 442one instance should exist for a given class.
c3398f5b 443
612d3e1a 444=head2 C<< name -> ClassName >>
c3398f5b 445
446Returns the name of the owner class.
447
612d3e1a 448=head2 C<< superclasses -> ClassNames >> C<< superclass(ClassNames) >>
c3398f5b 449
450Gets (or sets) the list of superclasses of the owner class.
451
31c5194b 452=head2 C<< add_method(name => CodeRef) >>
c3398f5b 453
31c5194b 454Adds a method to the owner class.
c3398f5b 455
31c5194b 456=head2 C<< has_method(name) -> Bool >>
72b88a88 457
31c5194b 458Returns whether we have a method with the given name.
72b88a88 459
31c5194b 460=head2 C<< get_method(name) -> Mouse::Meta::Method | undef >>
c68b4110 461
31c5194b 462Returns a L<Mouse::Meta::Method> with the given name.
463
464Note that you can also use C<< $metaclass->name->can($name) >> for a method body.
465
466=head2 C<< get_method_list -> Names >>
467
468Returns a list of method names which are defined in the local class.
469If you want a list of all applicable methods for a class, use the
470C<get_all_methods> method.
471
472=head2 C<< get_all_methods -> (Mouse::Meta::Method) >>
473
474Return the list of all L<Mouse::Meta::Method> instances associated with
475the class and its superclasses.
476
477=head2 C<< add_attribute(name => spec | Mouse::Meta::Attribute) >>
478
479Begins keeping track of the existing L<Mouse::Meta::Attribute> for the owner
480class.
c68b4110 481
612d3e1a 482=head2 C<< has_attribute(Name) -> Bool >>
66eea168 483
484Returns whether we have a L<Mouse::Meta::Attribute> with the given name.
485
31c5194b 486=head2 C<< get_attribute Name -> Mouse::Meta::Attribute | undef >>
c3398f5b 487
306290e8 488Returns the L<Mouse::Meta::Attribute> with the given name.
c3398f5b 489
31c5194b 490=head2 C<< get_attribute_list -> Names >>
491
492Returns a list of attribute names which are defined in the local
493class. If you want a list of all applicable attributes for a class,
494use the C<get_all_attributes> method.
495
496=head2 C<< get_all_attributes -> (Mouse::Meta::Attribute) >>
497
498Returns the list of all L<Mouse::Meta::Attribute> instances associated with
499this class and its superclasses.
500
612d3e1a 501=head2 C<< linearized_isa -> [ClassNames] >>
c3398f5b 502
503Returns the list of classes in method dispatch order, with duplicates removed.
504
612d3e1a 505=head2 C<< new_object(Parameters) -> Instance >>
2cea7a5f 506
612d3e1a 507Creates a new instance.
2cea7a5f 508
612d3e1a 509=head2 C<< clone_object(Instance, Parameters) -> Instance >>
f7b11a21 510
31c5194b 511Clones the given instance which must be an instance governed by this
f7b11a21 512metaclass.
513
31c5194b 514=head2 C<< throw_error(Message, Parameters) >>
515
516Throws an error with the given message.
517
1820fffe 518=head1 SEE ALSO
f7b11a21 519
1820fffe 520L<Moose::Meta::Class>
f7b11a21 521
31c5194b 522L<Class::MOP::Class>
523
c3398f5b 524=cut
525