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