- Create branch BUILDARGS
[gitmo/Moose.git] / lib / Moose / Meta / Method / Constructor.pm
CommitLineData
5cf3dbcf 1
2package Moose::Meta::Method::Constructor;
3
4use strict;
5use warnings;
6
7use Carp 'confess';
8use Scalar::Util 'blessed', 'weaken', 'looks_like_number';
9
eaa35e6e 10our $VERSION = '0.50';
5cf3dbcf 11our $AUTHORITY = 'cpan:STEVAN';
12
badb7e89 13use base 'Moose::Meta::Method',
14 'Class::MOP::Method::Generated';
5cf3dbcf 15
16sub new {
17 my $class = shift;
18 my %options = @_;
7a5b07b3 19
5cf3dbcf 20 (exists $options{options} && ref $options{options} eq 'HASH')
7a5b07b3 21 || confess "You must pass a hash of options";
22
1b2aea39 23 ($options{package_name} && $options{name})
d3308256 24 || confess "You must supply the package_name and name parameters $Class::MOP::Method::UPGRADE_ERROR_TEXT";
1b2aea39 25
5cf3dbcf 26 my $self = bless {
27 # from our superclass
1b2aea39 28 '&!body' => undef,
29 '$!package_name' => $options{package_name},
30 '$!name' => $options{name},
5cf3dbcf 31 # specific to this subclass
32 '%!options' => $options{options},
587ae0d2 33 '$!meta_instance' => $options{metaclass}->get_meta_instance,
7a5b07b3 34 '@!attributes' => [ $options{metaclass}->compute_all_applicable_attributes ],
5cf3dbcf 35 # ...
36 '$!associated_metaclass' => $options{metaclass},
37 } => $class;
38
7a5b07b3 39 # we don't want this creating
40 # a cycle in the code, if not
5cf3dbcf 41 # needed
7a5b07b3 42 weaken($self->{'$!associated_metaclass'});
5cf3dbcf 43
415e6f85 44 $self->initialize_body;
5cf3dbcf 45
7a5b07b3 46 return $self;
5cf3dbcf 47}
48
7a5b07b3 49## accessors
5cf3dbcf 50
51sub options { (shift)->{'%!options'} }
52sub meta_instance { (shift)->{'$!meta_instance'} }
53sub attributes { (shift)->{'@!attributes'} }
54
55sub associated_metaclass { (shift)->{'$!associated_metaclass'} }
56
57## method
58
384c126d 59# this was changed in 0.41, but broke MooseX::Singleton, so try to catch
60# any other code using the original broken spelling
61sub intialize_body { confess "Please correct the spelling of 'intialize_body' to 'initialize_body'" }
62
415e6f85 63sub initialize_body {
5cf3dbcf 64 my $self = shift;
65 # TODO:
7a5b07b3 66 # the %options should also include a both
67 # a call 'initializer' and call 'SUPER::'
68 # options, which should cover approx 90%
69 # of the possible use cases (even if it
70 # requires some adaption on the part of
5cf3dbcf 71 # the author, after all, nothing is free)
72 my $source = 'sub {';
1f779926 73 $source .= "\n" . 'my $class = shift;';
7a5b07b3 74
587ae0d2 75 $source .= "\n" . 'return $class->Moose::Object::new(@_)';
7a5b07b3 76 $source .= "\n" . ' if $class ne \'' . $self->associated_metaclass->name . '\';';
77
93e98578 78 $source .= "\n" . 'confess "Single parameters to new() must be a HASH ref"';
79 $source .= "\n" . ' if scalar @_ == 1 && defined $_[0] && ref($_[0]) ne q{HASH};';
80
7a5b07b3 81 $source .= "\n" . 'my %params = (scalar @_ == 1) ? %{$_[0]} : @_;';
82
5cf3dbcf 83 $source .= "\n" . 'my $instance = ' . $self->meta_instance->inline_create_instance('$class');
7a5b07b3 84
85 $source .= ";\n" . (join ";\n" => map {
86 $self->_generate_slot_initializer($_)
5cf3dbcf 87 } 0 .. (@{$self->attributes} - 1));
7a5b07b3 88
1b55c340 89 $source .= ";\n" . $self->_generate_triggers();
5cf3dbcf 90 $source .= ";\n" . $self->_generate_BUILDALL();
7a5b07b3 91
5cf3dbcf 92 $source .= ";\n" . 'return $instance';
7a5b07b3 93 $source .= ";\n" . '}';
94 warn $source if $self->options->{debug};
95
5cf3dbcf 96 my $code;
97 {
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;
121 confess "Could not eval the constructor :\n\n$source\n\nbecause :\n\n$@" if $@;
122 }
123 $self->{'&!body'} = $code;
124}
125
126sub _generate_BUILDALL {
127 my $self = shift;
128 my @BUILD_calls;
1f779926 129 foreach my $method (reverse $self->associated_metaclass->find_all_methods_by_name('BUILD')) {
7a5b07b3 130 push @BUILD_calls => '$instance->' . $method->{class} . '::BUILD(\%params)';
5cf3dbcf 131 }
7a5b07b3 132 return join ";\n" => @BUILD_calls;
5cf3dbcf 133}
134
1b55c340 135sub _generate_triggers {
136 my $self = shift;
137 my @trigger_calls;
138 foreach my $i (0 .. $#{ $self->attributes }) {
139 my $attr = $self->attributes->[$i];
140 if ($attr->can('has_trigger') && $attr->has_trigger) {
141 if (defined(my $init_arg = $attr->init_arg)) {
142 push @trigger_calls => (
143 '(exists $params{\'' . $init_arg . '\'}) && do {' . "\n "
144 . '$attrs->[' . $i . ']->trigger->('
145 . '$instance, '
146 . $self->meta_instance->inline_get_slot_value(
147 '$instance',
148 ("'" . $attr->name . "'")
149 )
150 . ', '
151 . '$attrs->[' . $i . ']'
152 . ');'
153 ."\n}"
154 );
155 }
156 }
157 }
158 return join ";\n" => @trigger_calls;
159}
160
5cf3dbcf 161sub _generate_slot_initializer {
162 my $self = shift;
163 my $index = shift;
7a5b07b3 164
5cf3dbcf 165 my $attr = $self->attributes->[$index];
7a5b07b3 166
5cf3dbcf 167 my @source = ('## ' . $attr->name);
d66bea3c 168
169 my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
7a5b07b3 170
84981146 171 if ($is_moose && defined($attr->init_arg) && $attr->is_required && !$attr->has_default && !$attr->has_builder) {
7a5b07b3 172 push @source => ('(exists $params{\'' . $attr->init_arg . '\'}) ' .
5cf3dbcf 173 '|| confess "Attribute (' . $attr->name . ') is required";');
174 }
7a5b07b3 175
ca168e89 176 if (($attr->has_default || $attr->has_builder) && !($is_moose && $attr->is_lazy)) {
7a5b07b3 177
84981146 178 if ( defined( my $init_arg = $attr->init_arg ) ) {
179 push @source => 'if (exists $params{\'' . $init_arg . '\'}) {';
8ecb1fa0 180
84981146 181 push @source => ('my $val = $params{\'' . $init_arg . '\'};');
182
183 if ($is_moose && $attr->has_type_constraint) {
184 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
688fcdda 185 push @source => $self->_generate_type_coercion(
186 $attr,
187 '$type_constraints[' . $index . ']',
188 '$val',
189 '$val'
190 );
84981146 191 }
688fcdda 192 push @source => $self->_generate_type_constraint_check(
193 $attr,
194 '$type_constraint_bodies[' . $index . ']',
195 '$type_constraints[' . $index . ']',
196 '$val'
197 );
8ecb1fa0 198 }
9df136d0 199 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
7a5b07b3 200
84981146 201 push @source => "} else {";
202 }
ca168e89 203 my $default;
97e11ef5 204 if ( $attr->has_default ) {
ca168e89 205 $default = $self->_generate_default_value($attr, $index);
97e11ef5 206 }
207 else {
ca168e89 208 my $builder = $attr->builder;
209 $default = '$instance->' . $builder;
210 }
688fcdda 211
3db3ea82 212 push @source => '{'; # wrap this to avoid my $val overwrite warnings
5cf3dbcf 213 push @source => ('my $val = ' . $default . ';');
214 push @source => $self->_generate_type_constraint_check(
215 $attr,
c9183ffc 216 ('$type_constraint_bodies[' . $index . ']'),
688fcdda 217 ('$type_constraints[' . $index . ']'),
5cf3dbcf 218 '$val'
7a5b07b3 219 ) if ($is_moose && $attr->has_type_constraint);
bad76b8e 220
51c107ef 221 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
bad76b8e 222 push @source => '}'; # close - wrap this to avoid my $val overrite warnings
7a5b07b3 223
84981146 224 push @source => "}" if defined $attr->init_arg;
7a5b07b3 225 }
84981146 226 elsif ( defined( my $init_arg = $attr->init_arg ) ) {
227 push @source => '(exists $params{\'' . $init_arg . '\'}) && do {';
8ecb1fa0 228
84981146 229 push @source => ('my $val = $params{\'' . $init_arg . '\'};');
d66bea3c 230 if ($is_moose && $attr->has_type_constraint) {
7a5b07b3 231 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
688fcdda 232 push @source => $self->_generate_type_coercion(
233 $attr,
234 '$type_constraints[' . $index . ']',
235 '$val',
236 '$val'
237 );
8ecb1fa0 238 }
688fcdda 239 push @source => $self->_generate_type_constraint_check(
240 $attr,
241 '$type_constraint_bodies[' . $index . ']',
242 '$type_constraints[' . $index . ']',
243 '$val'
244 );
8ecb1fa0 245 }
9df136d0 246 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
7a5b07b3 247
248 push @source => "}";
5cf3dbcf 249 }
7a5b07b3 250
5cf3dbcf 251 return join "\n" => @source;
252}
253
254sub _generate_slot_assignment {
9df136d0 255 my ($self, $attr, $value, $index) = @_;
256
257 my $source;
258
259 if ($attr->has_initializer) {
260 $source = (
261 '$attrs->[' . $index . ']->set_initial_value($instance, ' . $value . ');'
262 );
263 }
264 else {
265 $source = (
266 $self->meta_instance->inline_set_slot_value(
267 '$instance',
268 ("'" . $attr->name . "'"),
269 $value
270 ) . ';'
271 );
272 }
273
274 my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
7a5b07b3 275
d66bea3c 276 if ($is_moose && $attr->is_weak_ref) {
5cf3dbcf 277 $source .= (
278 "\n" .
279 $self->meta_instance->inline_weaken_slot_value(
7a5b07b3 280 '$instance',
5cf3dbcf 281 ("'" . $attr->name . "'")
7a5b07b3 282 ) .
5cf3dbcf 283 ' if ref ' . $value . ';'
7a5b07b3 284 );
285 }
286
5cf3dbcf 287 return $source;
288}
289
290sub _generate_type_coercion {
291 my ($self, $attr, $type_constraint_name, $value_name, $return_value_name) = @_;
292 return ($return_value_name . ' = ' . $type_constraint_name . '->coerce(' . $value_name . ');');
293}
294
295sub _generate_type_constraint_check {
688fcdda 296 my ($self, $attr, $type_constraint_cv, $type_constraint_obj, $value_name) = @_;
5cf3dbcf 297 return (
c9183ffc 298 $type_constraint_cv . '->(' . $value_name . ')'
688fcdda 299 . "\n\t" . '|| confess "Attribute ('
300 . $attr->name
301 . ') does not pass the type constraint because: " . '
302 . $type_constraint_obj . '->get_message(' . $value_name . ');'
7a5b07b3 303 );
5cf3dbcf 304}
305
306sub _generate_default_value {
307 my ($self, $attr, $index) = @_;
308 # NOTE:
309 # default values can either be CODE refs
7a5b07b3 310 # in which case we need to call them. Or
5cf3dbcf 311 # they can be scalars (strings/numbers)
312 # in which case we can just deal with them
313 # in the code we eval.
314 if ($attr->is_default_a_coderef) {
315 return '$attrs->[' . $index . ']->default($instance)';
316 }
317 else {
318 my $default = $attr->default;
319 # make sure to quote strings ...
320 unless (looks_like_number($default)) {
321 $default = "'$default'";
322 }
7a5b07b3 323
5cf3dbcf 324 return $default;
7a5b07b3 325 }
5cf3dbcf 326}
327
3281;
329
5cf3dbcf 330__END__
331
332=pod
333
7a5b07b3 334=head1 NAME
5cf3dbcf 335
336Moose::Meta::Method::Constructor - Method Meta Object for constructors
337
5cf3dbcf 338=head1 DESCRIPTION
339
7a5b07b3 340This is a subclass of L<Class::MOP::Method> which handles
341constructing an approprate Constructor methods. This is primarily
342used in the making of immutable metaclasses, otherwise it is
d44714be 343not particularly useful.
344
5cf3dbcf 345=head1 METHODS
346
347=over 4
348
349=item B<new>
350
351=item B<attributes>
352
353=item B<meta_instance>
354
355=item B<options>
356
415e6f85 357=item B<initialize_body>
5cf3dbcf 358
359=item B<associated_metaclass>
360
361=back
362
363=head1 AUTHORS
364
365Stevan Little E<lt>stevan@iinteractive.comE<gt>
366
367=head1 COPYRIGHT AND LICENSE
368
778db3ac 369Copyright 2006-2008 by Infinity Interactive, Inc.
5cf3dbcf 370
371L<http://www.iinteractive.com>
372
373This library is free software; you can redistribute it and/or modify
7a5b07b3 374it under the same terms as Perl itself.
5cf3dbcf 375
376=cut
377