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