Make Meta::Method::Constructor easier to subclass
[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
4b2189ce 9our $VERSION = '0.72';
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
5d826cfa 54 my $expected_class = $self->_expected_constructor_class;
55
12875d6e 56 # If any of our parents have been made immutable, we are okay to
e4c7477b 57 # inline our own new method. The assumption is that an inlined new
58 # method provided by a parent does not actually get used by
59 # children anyway.
60 for my $meta (
61 grep { $_->is_immutable }
62 map { ( ref $metaclass )->initialize($_) }
5d826cfa 63 grep { $_ ne $expected_class }
e4c7477b 64 $metaclass->linearized_isa
65 ) {
12875d6e 66 my $transformer = $meta->get_immutable_transformer;
67
5d826cfa 68 # This is actually a false positive if we're in a subclass of
69 # this class, _and_ the expected class is not overridden (but
70 # should be), and the real expected class is actually
71 # immutable itself (see Fey::Object::Table for an example of
72 # how this can happen). I'm not sure how to actually handle
73 # that case, since it's effectively a bug in the subclass (for
74 # not overriding _expected_constructor_class).
e4c7477b 75 return 1 if $transformer->inlined_constructor;
12875d6e 76 }
77
308e04fa 78 if ( my $constructor = $metaclass->find_method_by_name( $self->name ) ) {
e4c7477b 79 my $class = $self->associated_metaclass->name;
308e04fa 80
81 if ( $constructor->body != $expected_class->can('new') ) {
81766020 82 my $warning
83 = "Not inlining a constructor for $class since it is not"
37236439 84 . " inheriting the default $expected_class constructor\n"
85 . "If you are certain you don't need to inline your"
86 . " constructor, specify inline_constructor => 0 in your"
87 . " call to $class->meta->make_immutable\n";
308e04fa 88
81766020 89 $warning .= " (constructor has method modifiers which would be lost if it were inlined)\n"
90 if $constructor->isa('Class::MOP::Method::Wrapped');
91
92 warn $warning;
93
308e04fa 94 return 0;
95 }
96 else {
97 return 1;
98 }
99 }
100
101 # This would be a rather weird case where we have no constructor
102 # in the inheritance chain.
103 return 1;
104}
105
106# This is here so can_be_inlined can be inherited by MooseX modules.
107sub _expected_constructor_class {
108 return 'Moose::Object';
109}
110
7a5b07b3 111## accessors
5cf3dbcf 112
e606ae5f 113sub options { (shift)->{'options'} }
114sub meta_instance { (shift)->{'meta_instance'} }
115sub attributes { (shift)->{'attributes'} }
5cf3dbcf 116
e606ae5f 117sub associated_metaclass { (shift)->{'associated_metaclass'} }
5cf3dbcf 118
119## method
120
384c126d 121# this was changed in 0.41, but broke MooseX::Singleton, so try to catch
122# any other code using the original broken spelling
70ea9161 123sub intialize_body { $_[0]->throw_error("Please correct the spelling of 'intialize_body' to 'initialize_body'") }
384c126d 124
ac070e13 125sub _generate_params {
126 my ($self, $var, $class_var) = @_;
127 "my $var = " . $self->_generate_BUILDARGS($class_var, '@_') . ";\n";
128}
129
130sub _generate_instance {
131 my ($self, $var, $class_var) = @_;
132 "my $var = " . $self->meta_instance->inline_create_instance($class_var)
133 . ";\n";
134}
135
136sub _generate_slot_initializers {
137 my ($self) = @_;
138 return (join ";\n" => map {
139 $self->_generate_slot_initializer($_)
140 } 0 .. (@{$self->attributes} - 1)) . ";\n";
141}
142
415e6f85 143sub initialize_body {
5cf3dbcf 144 my $self = shift;
145 # TODO:
7a5b07b3 146 # the %options should also include a both
147 # a call 'initializer' and call 'SUPER::'
148 # options, which should cover approx 90%
149 # of the possible use cases (even if it
150 # requires some adaption on the part of
5cf3dbcf 151 # the author, after all, nothing is free)
152 my $source = 'sub {';
1f779926 153 $source .= "\n" . 'my $class = shift;';
7a5b07b3 154
587ae0d2 155 $source .= "\n" . 'return $class->Moose::Object::new(@_)';
ac070e13 156 $source .= "\n if \$class ne '" . $self->associated_metaclass->name
157 . "';\n";
93e98578 158
ac070e13 159 $source .= $self->_generate_params('$params', '$class');
160 $source .= $self->_generate_instance('$instance', '$class');
161 $source .= $self->_generate_slot_initializers;
7a5b07b3 162
ac070e13 163 $source .= $self->_generate_triggers();
5cf3dbcf 164 $source .= ";\n" . $self->_generate_BUILDALL();
7a5b07b3 165
ac070e13 166 $source .= ";\nreturn \$instance";
7a5b07b3 167 $source .= ";\n" . '}';
168 warn $source if $self->options->{debug};
169
5442a061 170 # We need to check if the attribute ->can('type_constraint')
171 # since we may be trying to immutabilize a Moose meta class,
172 # which in turn has attributes which are Class::MOP::Attribute
173 # objects, rather than Moose::Meta::Attribute. And
174 # Class::MOP::Attribute attributes have no type constraints.
175 # However we need to make sure we leave an undef value there
176 # because the inlined code is using the index of the attributes
177 # to determine where to find the type constraint
178
179 my $attrs = $self->attributes;
180
181 my @type_constraints = map {
182 $_->can('type_constraint') ? $_->type_constraint : undef
183 } @$attrs;
184
185 my @type_constraint_bodies = map {
186 defined $_ ? $_->_compiled_type_constraint : undef;
187 } @type_constraints;
188
189 my $code = $self->_compile_code(
190 code => $source,
191 environment => {
192 '$meta' => \$self,
193 '$attrs' => \$attrs,
194 '@type_constraints' => \@type_constraints,
195 '@type_constraint_bodies' => \@type_constraint_bodies,
196 },
197 ) or $self->throw_error("Could not eval the constructor :\n\n$source\n\nbecause :\n\n$@", error => $@, data => $source );
a62dcd43 198
e606ae5f 199 $self->{'body'} = $code;
200}
201
202sub _generate_BUILDARGS {
203 my ( $self, $class, $args ) = @_;
204
205 my $buildargs = $self->associated_metaclass->find_method_by_name("BUILDARGS");
206
207 if ( $args eq '@_' and ( !$buildargs or $buildargs->body == \&Moose::Object::BUILDARGS ) ) {
208 return join("\n",
209 'do {',
210 $self->_inline_throw_error('"Single parameters to new() must be a HASH ref"', 'data => $_[0]'),
a62dcd43 211 ' if scalar @_ == 1 && !( defined $_[0] && ref $_[0] eq q{HASH} );',
e606ae5f 212 '(scalar @_ == 1) ? {%{$_[0]}} : {@_};',
213 '}',
214 );
215 } else {
216 return $class . "->BUILDARGS($args)";
217 }
5cf3dbcf 218}
219
220sub _generate_BUILDALL {
221 my $self = shift;
222 my @BUILD_calls;
1f779926 223 foreach my $method (reverse $self->associated_metaclass->find_all_methods_by_name('BUILD')) {
e606ae5f 224 push @BUILD_calls => '$instance->' . $method->{class} . '::BUILD($params)';
5cf3dbcf 225 }
7a5b07b3 226 return join ";\n" => @BUILD_calls;
5cf3dbcf 227}
228
1b55c340 229sub _generate_triggers {
230 my $self = shift;
231 my @trigger_calls;
232 foreach my $i (0 .. $#{ $self->attributes }) {
233 my $attr = $self->attributes->[$i];
234 if ($attr->can('has_trigger') && $attr->has_trigger) {
235 if (defined(my $init_arg = $attr->init_arg)) {
236 push @trigger_calls => (
e606ae5f 237 '(exists $params->{\'' . $init_arg . '\'}) && do {' . "\n "
1b55c340 238 . '$attrs->[' . $i . ']->trigger->('
239 . '$instance, '
240 . $self->meta_instance->inline_get_slot_value(
241 '$instance',
eae37c67 242 $attr->name,
1b55c340 243 )
59f5bbde 244 . ', '
245 . '$attrs->[' . $i . ']'
1b55c340 246 . ');'
247 ."\n}"
248 );
249 }
250 }
251 }
252 return join ";\n" => @trigger_calls;
253}
254
5cf3dbcf 255sub _generate_slot_initializer {
256 my $self = shift;
257 my $index = shift;
7a5b07b3 258
5cf3dbcf 259 my $attr = $self->attributes->[$index];
7a5b07b3 260
5cf3dbcf 261 my @source = ('## ' . $attr->name);
d66bea3c 262
263 my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
7a5b07b3 264
84981146 265 if ($is_moose && defined($attr->init_arg) && $attr->is_required && !$attr->has_default && !$attr->has_builder) {
e606ae5f 266 push @source => ('(exists $params->{\'' . $attr->init_arg . '\'}) ' .
3e504337 267 '|| ' . $self->_inline_throw_error('"Attribute (' . $attr->name . ') is required"') .';');
5cf3dbcf 268 }
7a5b07b3 269
ca168e89 270 if (($attr->has_default || $attr->has_builder) && !($is_moose && $attr->is_lazy)) {
7a5b07b3 271
84981146 272 if ( defined( my $init_arg = $attr->init_arg ) ) {
e606ae5f 273 push @source => 'if (exists $params->{\'' . $init_arg . '\'}) {';
274 push @source => ('my $val = $params->{\'' . $init_arg . '\'};');
275 push @source => $self->_generate_type_constraint_and_coercion($attr, $index)
276 if $is_moose;
277 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
84981146 278 push @source => "} else {";
279 }
ca168e89 280 my $default;
97e11ef5 281 if ( $attr->has_default ) {
ca168e89 282 $default = $self->_generate_default_value($attr, $index);
97e11ef5 283 }
284 else {
ca168e89 285 my $builder = $attr->builder;
286 $default = '$instance->' . $builder;
287 }
688fcdda 288
3db3ea82 289 push @source => '{'; # wrap this to avoid my $val overwrite warnings
5cf3dbcf 290 push @source => ('my $val = ' . $default . ';');
e606ae5f 291 push @source => $self->_generate_type_constraint_and_coercion($attr, $index)
292 if $is_moose;
51c107ef 293 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
bad76b8e 294 push @source => '}'; # close - wrap this to avoid my $val overrite warnings
7a5b07b3 295
84981146 296 push @source => "}" if defined $attr->init_arg;
7a5b07b3 297 }
84981146 298 elsif ( defined( my $init_arg = $attr->init_arg ) ) {
e606ae5f 299 push @source => '(exists $params->{\'' . $init_arg . '\'}) && do {';
8ecb1fa0 300
e606ae5f 301 push @source => ('my $val = $params->{\'' . $init_arg . '\'};');
d66bea3c 302 if ($is_moose && $attr->has_type_constraint) {
7a5b07b3 303 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
688fcdda 304 push @source => $self->_generate_type_coercion(
305 $attr,
306 '$type_constraints[' . $index . ']',
307 '$val',
308 '$val'
309 );
8ecb1fa0 310 }
688fcdda 311 push @source => $self->_generate_type_constraint_check(
312 $attr,
313 '$type_constraint_bodies[' . $index . ']',
314 '$type_constraints[' . $index . ']',
315 '$val'
316 );
8ecb1fa0 317 }
9df136d0 318 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
7a5b07b3 319
320 push @source => "}";
5cf3dbcf 321 }
7a5b07b3 322
5cf3dbcf 323 return join "\n" => @source;
324}
325
326sub _generate_slot_assignment {
9df136d0 327 my ($self, $attr, $value, $index) = @_;
328
329 my $source;
330
331 if ($attr->has_initializer) {
332 $source = (
333 '$attrs->[' . $index . ']->set_initial_value($instance, ' . $value . ');'
334 );
335 }
336 else {
337 $source = (
338 $self->meta_instance->inline_set_slot_value(
339 '$instance',
eae37c67 340 $attr->name,
9df136d0 341 $value
342 ) . ';'
343 );
344 }
345
346 my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
7a5b07b3 347
d66bea3c 348 if ($is_moose && $attr->is_weak_ref) {
5cf3dbcf 349 $source .= (
350 "\n" .
351 $self->meta_instance->inline_weaken_slot_value(
7a5b07b3 352 '$instance',
eae37c67 353 $attr->name
7a5b07b3 354 ) .
5cf3dbcf 355 ' if ref ' . $value . ';'
7a5b07b3 356 );
357 }
358
5cf3dbcf 359 return $source;
360}
361
e606ae5f 362sub _generate_type_constraint_and_coercion {
363 my ($self, $attr, $index) = @_;
364
365 return unless $attr->has_type_constraint;
366
367 my @source;
368 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
369 push @source => $self->_generate_type_coercion(
370 $attr,
371 '$type_constraints[' . $index . ']',
372 '$val',
373 '$val'
374 );
375 }
376 push @source => $self->_generate_type_constraint_check(
377 $attr,
378 ('$type_constraint_bodies[' . $index . ']'),
379 ('$type_constraints[' . $index . ']'),
380 '$val'
381 );
382 return @source;
383}
384
5cf3dbcf 385sub _generate_type_coercion {
386 my ($self, $attr, $type_constraint_name, $value_name, $return_value_name) = @_;
387 return ($return_value_name . ' = ' . $type_constraint_name . '->coerce(' . $value_name . ');');
388}
389
390sub _generate_type_constraint_check {
688fcdda 391 my ($self, $attr, $type_constraint_cv, $type_constraint_obj, $value_name) = @_;
5cf3dbcf 392 return (
3e504337 393 $self->_inline_throw_error('"Attribute (' # FIXME add 'dad'
688fcdda 394 . $attr->name
395 . ') does not pass the type constraint because: " . '
3e504337 396 . $type_constraint_obj . '->get_message(' . $value_name . ')')
397 . "\n\t unless " . $type_constraint_cv . '->(' . $value_name . ');'
7a5b07b3 398 );
5cf3dbcf 399}
400
401sub _generate_default_value {
402 my ($self, $attr, $index) = @_;
403 # NOTE:
404 # default values can either be CODE refs
7a5b07b3 405 # in which case we need to call them. Or
5cf3dbcf 406 # they can be scalars (strings/numbers)
407 # in which case we can just deal with them
408 # in the code we eval.
409 if ($attr->is_default_a_coderef) {
410 return '$attrs->[' . $index . ']->default($instance)';
411 }
412 else {
4aa3d405 413 return q{"} . quotemeta( $attr->default ) . q{"};
7a5b07b3 414 }
5cf3dbcf 415}
416
4171;
418
5cf3dbcf 419__END__
420
421=pod
422
7a5b07b3 423=head1 NAME
5cf3dbcf 424
425Moose::Meta::Method::Constructor - Method Meta Object for constructors
426
5cf3dbcf 427=head1 DESCRIPTION
428
7a5b07b3 429This is a subclass of L<Class::MOP::Method> which handles
6549b0d1 430constructing an appropriate Constructor methods. This is primarily
7a5b07b3 431used in the making of immutable metaclasses, otherwise it is
d44714be 432not particularly useful.
433
5cf3dbcf 434=head1 METHODS
435
436=over 4
437
438=item B<new>
439
a1257460 440=item B<can_be_inlined>
441
5cf3dbcf 442=item B<attributes>
443
444=item B<meta_instance>
445
446=item B<options>
447
415e6f85 448=item B<initialize_body>
5cf3dbcf 449
450=item B<associated_metaclass>
451
452=back
453
454=head1 AUTHORS
455
456Stevan Little E<lt>stevan@iinteractive.comE<gt>
457
458=head1 COPYRIGHT AND LICENSE
459
2840a3b2 460Copyright 2006-2009 by Infinity Interactive, Inc.
5cf3dbcf 461
462L<http://www.iinteractive.com>
463
464This library is free software; you can redistribute it and/or modify
7a5b07b3 465it under the same terms as Perl itself.
5cf3dbcf 466
467=cut
468