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