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