factor out a small part of the constructor inlining
[gitmo/Moose.git] / lib / Moose / Meta / Method / Constructor.pm
CommitLineData
5cf3dbcf 1
2package Moose::Meta::Method::Constructor;
3
4use strict;
5use warnings;
6
0fa70d03 7use Scalar::Util 'blessed', 'weaken', 'looks_like_number', 'refaddr';
5cf3dbcf 8
16db8ee6 9our $VERSION = '1.07';
5cf3dbcf 10our $AUTHORITY = 'cpan:STEVAN';
11
badb7e89 12use base 'Moose::Meta::Method',
bc89e9b5 13 'Class::MOP::Method::Constructor';
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 {
d03bd989 28 'body' => undef,
e606ae5f 29 'package_name' => $options{package_name},
30 'name' => $options{name},
e606ae5f 31 'options' => $options{options},
e606ae5f 32 'associated_metaclass' => $meta,
0fa70d03 33 '_expected_method_class' => $options{_expected_method_class} || 'Moose::Object',
5cf3dbcf 34 } => $class;
35
7a5b07b3 36 # we don't want this creating
37 # a cycle in the code, if not
5cf3dbcf 38 # needed
e606ae5f 39 weaken($self->{'associated_metaclass'});
5cf3dbcf 40
f5b0af77 41 $self->_initialize_body;
5cf3dbcf 42
7a5b07b3 43 return $self;
5cf3dbcf 44}
45
5cf3dbcf 46## method
47
f5b0af77 48sub _initialize_body {
5cf3dbcf 49 my $self = shift;
50 # TODO:
7a5b07b3 51 # the %options should also include a both
52 # a call 'initializer' and call 'SUPER::'
53 # options, which should cover approx 90%
54 # of the possible use cases (even if it
55 # requires some adaption on the part of
5cf3dbcf 56 # the author, after all, nothing is free)
57 my $source = 'sub {';
5d27ac73 58 $source .= "\n" . 'my $_instance = shift;';
62c8675e 59
5d27ac73 60 $source .= "\n" . 'my $class = Scalar::Util::blessed($_instance) || $_instance;';
7a5b07b3 61
5117b888 62 $source .= "\n" . "if (\$class ne '" . $self->associated_metaclass->name
63 . "') {";
64 $source .= "\n return "
65 . $self->_generate_fallback_constructor('$class') . ";";
66 $source .= "\n}\n";
93e98578 67
ac070e13 68 $source .= $self->_generate_params('$params', '$class');
69 $source .= $self->_generate_instance('$instance', '$class');
70 $source .= $self->_generate_slot_initializers;
7a5b07b3 71
ac070e13 72 $source .= $self->_generate_triggers();
5cf3dbcf 73 $source .= ";\n" . $self->_generate_BUILDALL();
7a5b07b3 74
ac070e13 75 $source .= ";\nreturn \$instance";
7a5b07b3 76 $source .= ";\n" . '}';
77 warn $source if $self->options->{debug};
78
5442a061 79 # We need to check if the attribute ->can('type_constraint')
80 # since we may be trying to immutabilize a Moose meta class,
81 # which in turn has attributes which are Class::MOP::Attribute
82 # objects, rather than Moose::Meta::Attribute. And
83 # Class::MOP::Attribute attributes have no type constraints.
84 # However we need to make sure we leave an undef value there
85 # because the inlined code is using the index of the attributes
86 # to determine where to find the type constraint
87
0772362a 88 my $attrs = $self->_attributes;
5442a061 89
90 my @type_constraints = map {
91 $_->can('type_constraint') ? $_->type_constraint : undef
92 } @$attrs;
93
94 my @type_constraint_bodies = map {
95 defined $_ ? $_->_compiled_type_constraint : undef;
96 } @type_constraints;
97
34aab661 98 my ( $code, $e ) = $self->_compile_code(
5442a061 99 code => $source,
100 environment => {
101 '$meta' => \$self,
102 '$attrs' => \$attrs,
103 '@type_constraints' => \@type_constraints,
104 '@type_constraint_bodies' => \@type_constraint_bodies,
105 },
34aab661 106 );
107
108 $self->throw_error(
109 "Could not eval the constructor :\n\n$source\n\nbecause :\n\n$e",
110 error => $e, data => $source )
111 if $e;
d03bd989 112
e606ae5f 113 $self->{'body'} = $code;
114}
115
5117b888 116sub _generate_fallback_constructor {
117 my ( $self, $class_var ) = @_;
118 "${class_var}->Moose::Object::new(\@_)";
119}
120
b905f0db 121sub _generate_params {
122 my ( $self, $var, $class_var ) = @_;
123 "my $var = " . $self->_generate_BUILDARGS( $class_var, '@_' ) . ";\n";
124}
125
126sub _generate_instance {
127 my ( $self, $var, $class_var ) = @_;
128 "my $var = "
0772362a 129 . $self->_meta_instance->inline_create_instance($class_var) . ";\n";
b905f0db 130}
131
132sub _generate_slot_initializers {
133 my ($self) = @_;
134 return (join ";\n" => map {
135 $self->_generate_slot_initializer($_)
0772362a 136 } 0 .. (@{$self->_attributes} - 1)) . ";\n";
b905f0db 137}
138
e606ae5f 139sub _generate_BUILDARGS {
140 my ( $self, $class, $args ) = @_;
141
142 my $buildargs = $self->associated_metaclass->find_method_by_name("BUILDARGS");
143
144 if ( $args eq '@_' and ( !$buildargs or $buildargs->body == \&Moose::Object::BUILDARGS ) ) {
145 return join("\n",
146 'do {',
147 $self->_inline_throw_error('"Single parameters to new() must be a HASH ref"', 'data => $_[0]'),
a62dcd43 148 ' if scalar @_ == 1 && !( defined $_[0] && ref $_[0] eq q{HASH} );',
e606ae5f 149 '(scalar @_ == 1) ? {%{$_[0]}} : {@_};',
150 '}',
151 );
152 } else {
153 return $class . "->BUILDARGS($args)";
154 }
5cf3dbcf 155}
156
157sub _generate_BUILDALL {
158 my $self = shift;
159 my @BUILD_calls;
1f779926 160 foreach my $method (reverse $self->associated_metaclass->find_all_methods_by_name('BUILD')) {
e606ae5f 161 push @BUILD_calls => '$instance->' . $method->{class} . '::BUILD($params)';
5cf3dbcf 162 }
7a5b07b3 163 return join ";\n" => @BUILD_calls;
5cf3dbcf 164}
165
1b55c340 166sub _generate_triggers {
167 my $self = shift;
168 my @trigger_calls;
0772362a 169 foreach my $i ( 0 .. $#{ $self->_attributes } ) {
170 my $attr = $self->_attributes->[$i];
708b4070 171
172 next unless $attr->can('has_trigger') && $attr->has_trigger;
173
174 my $init_arg = $attr->init_arg;
175
176 next unless defined $init_arg;
177
178 push @trigger_calls => '(exists $params->{\''
179 . $init_arg
180 . '\'}) && do {'
181 . "\n "
182 . '$attrs->['
183 . $i
184 . ']->trigger->('
185 . '$instance, '
0772362a 186 . $self->_meta_instance->inline_get_slot_value(
708b4070 187 '$instance',
188 $attr->name,
189 )
190 . ', '
c2685d20 191 . ');' . "\n}";
1b55c340 192 }
708b4070 193
194 return join ";\n" => @trigger_calls;
1b55c340 195}
196
5cf3dbcf 197sub _generate_slot_initializer {
198 my $self = shift;
199 my $index = shift;
7a5b07b3 200
0772362a 201 my $attr = $self->_attributes->[$index];
7a5b07b3 202
5cf3dbcf 203 my @source = ('## ' . $attr->name);
d66bea3c 204
205 my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
7a5b07b3 206
84981146 207 if ($is_moose && defined($attr->init_arg) && $attr->is_required && !$attr->has_default && !$attr->has_builder) {
e606ae5f 208 push @source => ('(exists $params->{\'' . $attr->init_arg . '\'}) ' .
95d922a2 209 '|| ' . $self->_inline_throw_error('"Attribute (' . quotemeta($attr->name) . ') is required"') .';');
5cf3dbcf 210 }
7a5b07b3 211
ca168e89 212 if (($attr->has_default || $attr->has_builder) && !($is_moose && $attr->is_lazy)) {
7a5b07b3 213
84981146 214 if ( defined( my $init_arg = $attr->init_arg ) ) {
e606ae5f 215 push @source => 'if (exists $params->{\'' . $init_arg . '\'}) {';
216 push @source => ('my $val = $params->{\'' . $init_arg . '\'};');
217 push @source => $self->_generate_type_constraint_and_coercion($attr, $index)
218 if $is_moose;
219 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
84981146 220 push @source => "} else {";
221 }
ca168e89 222 my $default;
97e11ef5 223 if ( $attr->has_default ) {
ca168e89 224 $default = $self->_generate_default_value($attr, $index);
d03bd989 225 }
97e11ef5 226 else {
ca168e89 227 my $builder = $attr->builder;
228 $default = '$instance->' . $builder;
229 }
d03bd989 230
3db3ea82 231 push @source => '{'; # wrap this to avoid my $val overwrite warnings
5cf3dbcf 232 push @source => ('my $val = ' . $default . ';');
e606ae5f 233 push @source => $self->_generate_type_constraint_and_coercion($attr, $index)
d03bd989 234 if $is_moose;
51c107ef 235 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
d03bd989 236 push @source => '}'; # close - wrap this to avoid my $val overrite warnings
7a5b07b3 237
84981146 238 push @source => "}" if defined $attr->init_arg;
7a5b07b3 239 }
84981146 240 elsif ( defined( my $init_arg = $attr->init_arg ) ) {
e606ae5f 241 push @source => '(exists $params->{\'' . $init_arg . '\'}) && do {';
8ecb1fa0 242
e606ae5f 243 push @source => ('my $val = $params->{\'' . $init_arg . '\'};');
d66bea3c 244 if ($is_moose && $attr->has_type_constraint) {
7a5b07b3 245 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
688fcdda 246 push @source => $self->_generate_type_coercion(
d03bd989 247 $attr,
248 '$type_constraints[' . $index . ']',
249 '$val',
688fcdda 250 '$val'
251 );
8ecb1fa0 252 }
688fcdda 253 push @source => $self->_generate_type_constraint_check(
d03bd989 254 $attr,
255 '$type_constraint_bodies[' . $index . ']',
256 '$type_constraints[' . $index . ']',
688fcdda 257 '$val'
258 );
8ecb1fa0 259 }
9df136d0 260 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
7a5b07b3 261
262 push @source => "}";
5cf3dbcf 263 }
7a5b07b3 264
5cf3dbcf 265 return join "\n" => @source;
266}
267
268sub _generate_slot_assignment {
9df136d0 269 my ($self, $attr, $value, $index) = @_;
270
271 my $source;
d03bd989 272
9df136d0 273 if ($attr->has_initializer) {
274 $source = (
275 '$attrs->[' . $index . ']->set_initial_value($instance, ' . $value . ');'
d03bd989 276 );
9df136d0 277 }
278 else {
279 $source = (
0772362a 280 $self->_meta_instance->inline_set_slot_value(
9df136d0 281 '$instance',
eae37c67 282 $attr->name,
9df136d0 283 $value
284 ) . ';'
d03bd989 285 );
9df136d0 286 }
d03bd989 287
288 my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
7a5b07b3 289
d66bea3c 290 if ($is_moose && $attr->is_weak_ref) {
5cf3dbcf 291 $source .= (
292 "\n" .
0772362a 293 $self->_meta_instance->inline_weaken_slot_value(
7a5b07b3 294 '$instance',
eae37c67 295 $attr->name
7a5b07b3 296 ) .
5cf3dbcf 297 ' if ref ' . $value . ';'
7a5b07b3 298 );
299 }
300
5cf3dbcf 301 return $source;
302}
303
e606ae5f 304sub _generate_type_constraint_and_coercion {
305 my ($self, $attr, $index) = @_;
d03bd989 306
e606ae5f 307 return unless $attr->has_type_constraint;
d03bd989 308
e606ae5f 309 my @source;
310 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
311 push @source => $self->_generate_type_coercion(
312 $attr,
313 '$type_constraints[' . $index . ']',
314 '$val',
315 '$val'
316 );
317 }
318 push @source => $self->_generate_type_constraint_check(
319 $attr,
320 ('$type_constraint_bodies[' . $index . ']'),
d03bd989 321 ('$type_constraints[' . $index . ']'),
e606ae5f 322 '$val'
323 );
324 return @source;
325}
326
5cf3dbcf 327sub _generate_type_coercion {
328 my ($self, $attr, $type_constraint_name, $value_name, $return_value_name) = @_;
329 return ($return_value_name . ' = ' . $type_constraint_name . '->coerce(' . $value_name . ');');
330}
331
332sub _generate_type_constraint_check {
688fcdda 333 my ($self, $attr, $type_constraint_cv, $type_constraint_obj, $value_name) = @_;
5cf3dbcf 334 return (
3e504337 335 $self->_inline_throw_error('"Attribute (' # FIXME add 'dad'
95d922a2 336 . quotemeta( $attr->name )
d03bd989 337 . ') does not pass the type constraint because: " . '
3e504337 338 . $type_constraint_obj . '->get_message(' . $value_name . ')')
339 . "\n\t unless " . $type_constraint_cv . '->(' . $value_name . ');'
7a5b07b3 340 );
5cf3dbcf 341}
342
343sub _generate_default_value {
344 my ($self, $attr, $index) = @_;
345 # NOTE:
346 # default values can either be CODE refs
7a5b07b3 347 # in which case we need to call them. Or
5cf3dbcf 348 # they can be scalars (strings/numbers)
349 # in which case we can just deal with them
350 # in the code we eval.
351 if ($attr->is_default_a_coderef) {
352 return '$attrs->[' . $index . ']->default($instance)';
353 }
354 else {
4aa3d405 355 return q{"} . quotemeta( $attr->default ) . q{"};
7a5b07b3 356 }
5cf3dbcf 357}
358
3591;
360
5cf3dbcf 361__END__
362
363=pod
364
7a5b07b3 365=head1 NAME
5cf3dbcf 366
367Moose::Meta::Method::Constructor - Method Meta Object for constructors
368
5cf3dbcf 369=head1 DESCRIPTION
370
cec39889 371This class is a subclass of L<Class::MOP::Method::Constructor> that
cefc9e36 372provides additional Moose-specific functionality
373
374To understand this class, you should read the the
cec39889 375L<Class::MOP::Method::Constructor> documentation as well.
d44714be 376
bc89e9b5 377=head1 INHERITANCE
378
379C<Moose::Meta::Method::Constructor> is a subclass of
380L<Moose::Meta::Method> I<and> L<Class::MOP::Method::Constructor>.
381
c5fc2c21 382=head1 BUGS
383
384See L<Moose/BUGS> for details on reporting bugs.
385
5cf3dbcf 386=head1 AUTHORS
387
388Stevan Little E<lt>stevan@iinteractive.comE<gt>
389
390=head1 COPYRIGHT AND LICENSE
391
7e0492d3 392Copyright 2006-2010 by Infinity Interactive, Inc.
5cf3dbcf 393
394L<http://www.iinteractive.com>
395
396This library is free software; you can redistribute it and/or modify
7a5b07b3 397it under the same terms as Perl itself.
5cf3dbcf 398
399=cut
400