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