Make sure that whenever we don't inline, we warn, and add tests.
[gitmo/Moose.git] / lib / Moose / Meta / Method / Constructor.pm
CommitLineData
5cf3dbcf 1
2package Moose::Meta::Method::Constructor;
3
4use strict;
5use warnings;
6
5cf3dbcf 7use Scalar::Util 'blessed', 'weaken', 'looks_like_number';
8
82750a8a 9our $VERSION = '0.62_01';
5cf3dbcf 10our $AUTHORITY = 'cpan:STEVAN';
11
badb7e89 12use base 'Moose::Meta::Method',
13 'Class::MOP::Method::Generated';
5cf3dbcf 14
15sub new {
16 my $class = shift;
17 my %options = @_;
7a5b07b3 18
3e504337 19 my $meta = $options{metaclass};
20
21 (ref $options{options} eq 'HASH')
a9538ac9 22 || $class->throw_error("You must pass a hash of options", data => $options{options});
7a5b07b3 23
1b2aea39 24 ($options{package_name} && $options{name})
a9538ac9 25 || $class->throw_error("You must supply the package_name and name parameters $Class::MOP::Method::UPGRADE_ERROR_TEXT");
1b2aea39 26
5cf3dbcf 27 my $self = bless {
28 # from our superclass
e606ae5f 29 'body' => undef,
30 'package_name' => $options{package_name},
31 'name' => $options{name},
5cf3dbcf 32 # specific to this subclass
e606ae5f 33 'options' => $options{options},
34 'meta_instance' => $meta->get_meta_instance,
35 'attributes' => [ $meta->compute_all_applicable_attributes ],
5cf3dbcf 36 # ...
e606ae5f 37 'associated_metaclass' => $meta,
5cf3dbcf 38 } => $class;
39
7a5b07b3 40 # we don't want this creating
41 # a cycle in the code, if not
5cf3dbcf 42 # needed
e606ae5f 43 weaken($self->{'associated_metaclass'});
5cf3dbcf 44
415e6f85 45 $self->initialize_body;
5cf3dbcf 46
7a5b07b3 47 return $self;
5cf3dbcf 48}
49
308e04fa 50sub can_be_inlined {
51 my $self = shift;
52 my $metaclass = $self->associated_metaclass;
53
db058da6 54 my $class = $self->associated_metaclass->name;
55
12875d6e 56 # If any of our parents have been made immutable, we are okay to
57 # inline our own method as long as the parent's constructor class
58 # is the same as $self.
59 for my $meta ( grep { $_->is_immutable }
60 map { ( ref $metaclass )->initialize($_) }
61 $metaclass->linearized_isa ) {
62 my $transformer = $meta->get_immutable_transformer;
63
64 my $constructor = $transformer->inlined_constructor
65 or next;
66
db058da6 67 return 1 if ref $constructor eq ref $self;
68
69 my $parent_name = $meta->name;
70 my $constructor_class = ref $constructor;
71 my $self_class = ref $self;
72
73 # This case is fairly unlikely. In most normal cases,
74 # incompatibility between constructor classes will be caught
75 # by the code that fixes metaclass incompatibility in
76 # Moose::Meta::Class. However, if the parent passes a
77 # constructor_class directly to
78 # Parent->meta->make_immutable(), this could happen.
79 warn "Not inlining a constructor for $class. It has a parent class ($parent_name)"
80 . " which was inlined using $constructor_class, but $class is using $self_class\n";
81
82 return 0;
12875d6e 83 }
84
308e04fa 85 if ( my $constructor = $metaclass->find_method_by_name( $self->name ) ) {
86
87 my $expected_class = $self->_expected_constructor_class;
88
89 if ( $constructor->body != $expected_class->can('new') ) {
e94a703f 90 warn "Not inlining a constructor for $class since it is not"
91 . " inheriting the default $expected_class constructor\n";
308e04fa 92
93 return 0;
94 }
95 else {
96 return 1;
97 }
98 }
99
100 # This would be a rather weird case where we have no constructor
101 # in the inheritance chain.
102 return 1;
103}
104
105# This is here so can_be_inlined can be inherited by MooseX modules.
106sub _expected_constructor_class {
107 return 'Moose::Object';
108}
109
7a5b07b3 110## accessors
5cf3dbcf 111
e606ae5f 112sub options { (shift)->{'options'} }
113sub meta_instance { (shift)->{'meta_instance'} }
114sub attributes { (shift)->{'attributes'} }
5cf3dbcf 115
e606ae5f 116sub associated_metaclass { (shift)->{'associated_metaclass'} }
5cf3dbcf 117
118## method
119
384c126d 120# this was changed in 0.41, but broke MooseX::Singleton, so try to catch
121# any other code using the original broken spelling
c245d69b 122sub intialize_body { Moose->throw_error("Please correct the spelling of 'intialize_body' to 'initialize_body'") }
384c126d 123
415e6f85 124sub initialize_body {
5cf3dbcf 125 my $self = shift;
126 # TODO:
7a5b07b3 127 # the %options should also include a both
128 # a call 'initializer' and call 'SUPER::'
129 # options, which should cover approx 90%
130 # of the possible use cases (even if it
131 # requires some adaption on the part of
5cf3dbcf 132 # the author, after all, nothing is free)
133 my $source = 'sub {';
1f779926 134 $source .= "\n" . 'my $class = shift;';
7a5b07b3 135
587ae0d2 136 $source .= "\n" . 'return $class->Moose::Object::new(@_)';
7a5b07b3 137 $source .= "\n" . ' if $class ne \'' . $self->associated_metaclass->name . '\';';
138
e606ae5f 139 $source .= "\n" . 'my $params = ' . $self->_generate_BUILDARGS('$class', '@_');
93e98578 140
e606ae5f 141 $source .= ";\n" . 'my $instance = ' . $self->meta_instance->inline_create_instance('$class');
7a5b07b3 142
143 $source .= ";\n" . (join ";\n" => map {
144 $self->_generate_slot_initializer($_)
5cf3dbcf 145 } 0 .. (@{$self->attributes} - 1));
7a5b07b3 146
1b55c340 147 $source .= ";\n" . $self->_generate_triggers();
5cf3dbcf 148 $source .= ";\n" . $self->_generate_BUILDALL();
7a5b07b3 149
5cf3dbcf 150 $source .= ";\n" . 'return $instance';
7a5b07b3 151 $source .= ";\n" . '}';
152 warn $source if $self->options->{debug};
153
5cf3dbcf 154 my $code;
155 {
3e504337 156 my $meta = $self; # FIXME for _inline_throw_error...
157
5cf3dbcf 158 # NOTE:
159 # create the nessecary lexicals
7a5b07b3 160 # to be picked up in the eval
5cf3dbcf 161 my $attrs = $self->attributes;
7a5b07b3 162
475042d0 163 # We need to check if the attribute ->can('type_constraint')
164 # since we may be trying to immutabilize a Moose meta class,
165 # which in turn has attributes which are Class::MOP::Attribute
7701d0aa 166 # objects, rather than Moose::Meta::Attribute. And
167 # Class::MOP::Attribute attributes have no type constraints.
238b424d 168 # However we need to make sure we leave an undef value there
169 # because the inlined code is using the index of the attributes
170 # to determine where to find the type constraint
171
172 my @type_constraints = map {
173 $_->can('type_constraint') ? $_->type_constraint : undef
174 } @$attrs;
175
c9183ffc 176 my @type_constraint_bodies = map {
238b424d 177 defined $_ ? $_->_compiled_type_constraint : undef;
c9183ffc 178 } @type_constraints;
7c4f0d32 179
5cf3dbcf 180 $code = eval $source;
3e504337 181 $self->throw_error("Could not eval the constructor :\n\n$source\n\nbecause :\n\n$@", error => $@, data => $source ) if $@;
5cf3dbcf 182 }
e606ae5f 183 $self->{'body'} = $code;
184}
185
186sub _generate_BUILDARGS {
187 my ( $self, $class, $args ) = @_;
188
189 my $buildargs = $self->associated_metaclass->find_method_by_name("BUILDARGS");
190
191 if ( $args eq '@_' and ( !$buildargs or $buildargs->body == \&Moose::Object::BUILDARGS ) ) {
192 return join("\n",
193 'do {',
194 $self->_inline_throw_error('"Single parameters to new() must be a HASH ref"', 'data => $_[0]'),
195 ' if scalar @_ == 1 && defined $_[0] && ref($_[0]) ne q{HASH};',
196 '(scalar @_ == 1) ? {%{$_[0]}} : {@_};',
197 '}',
198 );
199 } else {
200 return $class . "->BUILDARGS($args)";
201 }
5cf3dbcf 202}
203
204sub _generate_BUILDALL {
205 my $self = shift;
206 my @BUILD_calls;
1f779926 207 foreach my $method (reverse $self->associated_metaclass->find_all_methods_by_name('BUILD')) {
e606ae5f 208 push @BUILD_calls => '$instance->' . $method->{class} . '::BUILD($params)';
5cf3dbcf 209 }
7a5b07b3 210 return join ";\n" => @BUILD_calls;
5cf3dbcf 211}
212
1b55c340 213sub _generate_triggers {
214 my $self = shift;
215 my @trigger_calls;
216 foreach my $i (0 .. $#{ $self->attributes }) {
217 my $attr = $self->attributes->[$i];
218 if ($attr->can('has_trigger') && $attr->has_trigger) {
219 if (defined(my $init_arg = $attr->init_arg)) {
220 push @trigger_calls => (
e606ae5f 221 '(exists $params->{\'' . $init_arg . '\'}) && do {' . "\n "
1b55c340 222 . '$attrs->[' . $i . ']->trigger->('
223 . '$instance, '
224 . $self->meta_instance->inline_get_slot_value(
225 '$instance',
226 ("'" . $attr->name . "'")
227 )
228 . ', '
229 . '$attrs->[' . $i . ']'
230 . ');'
231 ."\n}"
232 );
233 }
234 }
235 }
236 return join ";\n" => @trigger_calls;
237}
238
5cf3dbcf 239sub _generate_slot_initializer {
240 my $self = shift;
241 my $index = shift;
7a5b07b3 242
5cf3dbcf 243 my $attr = $self->attributes->[$index];
7a5b07b3 244
5cf3dbcf 245 my @source = ('## ' . $attr->name);
d66bea3c 246
247 my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
7a5b07b3 248
84981146 249 if ($is_moose && defined($attr->init_arg) && $attr->is_required && !$attr->has_default && !$attr->has_builder) {
e606ae5f 250 push @source => ('(exists $params->{\'' . $attr->init_arg . '\'}) ' .
3e504337 251 '|| ' . $self->_inline_throw_error('"Attribute (' . $attr->name . ') is required"') .';');
5cf3dbcf 252 }
7a5b07b3 253
ca168e89 254 if (($attr->has_default || $attr->has_builder) && !($is_moose && $attr->is_lazy)) {
7a5b07b3 255
84981146 256 if ( defined( my $init_arg = $attr->init_arg ) ) {
e606ae5f 257 push @source => 'if (exists $params->{\'' . $init_arg . '\'}) {';
258 push @source => ('my $val = $params->{\'' . $init_arg . '\'};');
259 push @source => $self->_generate_type_constraint_and_coercion($attr, $index)
260 if $is_moose;
261 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
84981146 262 push @source => "} else {";
263 }
ca168e89 264 my $default;
97e11ef5 265 if ( $attr->has_default ) {
ca168e89 266 $default = $self->_generate_default_value($attr, $index);
97e11ef5 267 }
268 else {
ca168e89 269 my $builder = $attr->builder;
270 $default = '$instance->' . $builder;
271 }
688fcdda 272
3db3ea82 273 push @source => '{'; # wrap this to avoid my $val overwrite warnings
5cf3dbcf 274 push @source => ('my $val = ' . $default . ';');
e606ae5f 275 push @source => $self->_generate_type_constraint_and_coercion($attr, $index)
276 if $is_moose;
51c107ef 277 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
bad76b8e 278 push @source => '}'; # close - wrap this to avoid my $val overrite warnings
7a5b07b3 279
84981146 280 push @source => "}" if defined $attr->init_arg;
7a5b07b3 281 }
84981146 282 elsif ( defined( my $init_arg = $attr->init_arg ) ) {
e606ae5f 283 push @source => '(exists $params->{\'' . $init_arg . '\'}) && do {';
8ecb1fa0 284
e606ae5f 285 push @source => ('my $val = $params->{\'' . $init_arg . '\'};');
d66bea3c 286 if ($is_moose && $attr->has_type_constraint) {
7a5b07b3 287 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
688fcdda 288 push @source => $self->_generate_type_coercion(
289 $attr,
290 '$type_constraints[' . $index . ']',
291 '$val',
292 '$val'
293 );
8ecb1fa0 294 }
688fcdda 295 push @source => $self->_generate_type_constraint_check(
296 $attr,
297 '$type_constraint_bodies[' . $index . ']',
298 '$type_constraints[' . $index . ']',
299 '$val'
300 );
8ecb1fa0 301 }
9df136d0 302 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
7a5b07b3 303
304 push @source => "}";
5cf3dbcf 305 }
7a5b07b3 306
5cf3dbcf 307 return join "\n" => @source;
308}
309
310sub _generate_slot_assignment {
9df136d0 311 my ($self, $attr, $value, $index) = @_;
312
313 my $source;
314
315 if ($attr->has_initializer) {
316 $source = (
317 '$attrs->[' . $index . ']->set_initial_value($instance, ' . $value . ');'
318 );
319 }
320 else {
321 $source = (
322 $self->meta_instance->inline_set_slot_value(
323 '$instance',
324 ("'" . $attr->name . "'"),
325 $value
326 ) . ';'
327 );
328 }
329
330 my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
7a5b07b3 331
d66bea3c 332 if ($is_moose && $attr->is_weak_ref) {
5cf3dbcf 333 $source .= (
334 "\n" .
335 $self->meta_instance->inline_weaken_slot_value(
7a5b07b3 336 '$instance',
5cf3dbcf 337 ("'" . $attr->name . "'")
7a5b07b3 338 ) .
5cf3dbcf 339 ' if ref ' . $value . ';'
7a5b07b3 340 );
341 }
342
5cf3dbcf 343 return $source;
344}
345
e606ae5f 346sub _generate_type_constraint_and_coercion {
347 my ($self, $attr, $index) = @_;
348
349 return unless $attr->has_type_constraint;
350
351 my @source;
352 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
353 push @source => $self->_generate_type_coercion(
354 $attr,
355 '$type_constraints[' . $index . ']',
356 '$val',
357 '$val'
358 );
359 }
360 push @source => $self->_generate_type_constraint_check(
361 $attr,
362 ('$type_constraint_bodies[' . $index . ']'),
363 ('$type_constraints[' . $index . ']'),
364 '$val'
365 );
366 return @source;
367}
368
5cf3dbcf 369sub _generate_type_coercion {
370 my ($self, $attr, $type_constraint_name, $value_name, $return_value_name) = @_;
371 return ($return_value_name . ' = ' . $type_constraint_name . '->coerce(' . $value_name . ');');
372}
373
374sub _generate_type_constraint_check {
688fcdda 375 my ($self, $attr, $type_constraint_cv, $type_constraint_obj, $value_name) = @_;
5cf3dbcf 376 return (
3e504337 377 $self->_inline_throw_error('"Attribute (' # FIXME add 'dad'
688fcdda 378 . $attr->name
379 . ') does not pass the type constraint because: " . '
3e504337 380 . $type_constraint_obj . '->get_message(' . $value_name . ')')
381 . "\n\t unless " . $type_constraint_cv . '->(' . $value_name . ');'
7a5b07b3 382 );
5cf3dbcf 383}
384
385sub _generate_default_value {
386 my ($self, $attr, $index) = @_;
387 # NOTE:
388 # default values can either be CODE refs
7a5b07b3 389 # in which case we need to call them. Or
5cf3dbcf 390 # they can be scalars (strings/numbers)
391 # in which case we can just deal with them
392 # in the code we eval.
393 if ($attr->is_default_a_coderef) {
394 return '$attrs->[' . $index . ']->default($instance)';
395 }
396 else {
397 my $default = $attr->default;
398 # make sure to quote strings ...
f3a93494 399 return "'$default'";
400
7a5b07b3 401 }
5cf3dbcf 402}
403
4041;
405
5cf3dbcf 406__END__
407
408=pod
409
7a5b07b3 410=head1 NAME
5cf3dbcf 411
412Moose::Meta::Method::Constructor - Method Meta Object for constructors
413
5cf3dbcf 414=head1 DESCRIPTION
415
7a5b07b3 416This is a subclass of L<Class::MOP::Method> which handles
417constructing an approprate Constructor methods. This is primarily
418used in the making of immutable metaclasses, otherwise it is
d44714be 419not particularly useful.
420
5cf3dbcf 421=head1 METHODS
422
423=over 4
424
425=item B<new>
426
427=item B<attributes>
428
429=item B<meta_instance>
430
431=item B<options>
432
415e6f85 433=item B<initialize_body>
5cf3dbcf 434
435=item B<associated_metaclass>
436
437=back
438
439=head1 AUTHORS
440
441Stevan Little E<lt>stevan@iinteractive.comE<gt>
442
443=head1 COPYRIGHT AND LICENSE
444
778db3ac 445Copyright 2006-2008 by Infinity Interactive, Inc.
5cf3dbcf 446
447L<http://www.iinteractive.com>
448
449This library is free software; you can redistribute it and/or modify
7a5b07b3 450it under the same terms as Perl itself.
5cf3dbcf 451
452=cut
453