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