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