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