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