fix typo in initialize_body method
[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         'confess';
8 use Scalar::Util 'blessed', 'weaken', 'looks_like_number';
9
10 our $VERSION   = '0.09';
11 our $AUTHORITY = 'cpan:STEVAN';
12
13 use base 'Moose::Meta::Method',
14          'Class::MOP::Method::Generated';
15
16 sub new {
17     my $class   = shift;
18     my %options = @_;
19
20     (exists $options{options} && ref $options{options} eq 'HASH')
21         || confess "You must pass a hash of options";
22
23     my $self = bless {
24         # from our superclass
25         '&!body'          => undef,
26         # specific to this subclass
27         '%!options'       => $options{options},
28         '$!meta_instance' => $options{metaclass}->get_meta_instance,
29         '@!attributes'    => [ $options{metaclass}->compute_all_applicable_attributes ],
30         # ...
31         '$!associated_metaclass' => $options{metaclass},
32     } => $class;
33
34     # we don't want this creating
35     # a cycle in the code, if not
36     # needed
37     weaken($self->{'$!associated_metaclass'});
38
39     $self->initialize_body;
40
41     return $self;
42 }
43
44 ## accessors
45
46 sub options       { (shift)->{'%!options'}       }
47 sub meta_instance { (shift)->{'$!meta_instance'} }
48 sub attributes    { (shift)->{'@!attributes'}    }
49
50 sub associated_metaclass { (shift)->{'$!associated_metaclass'} }
51
52 ## method
53
54 sub initialize_body {
55     my $self = shift;
56     # TODO:
57     # the %options should also include a both
58     # a call 'initializer' and call 'SUPER::'
59     # options, which should cover approx 90%
60     # of the possible use cases (even if it
61     # requires some adaption on the part of
62     # the author, after all, nothing is free)
63     my $source = 'sub {';
64     $source .= "\n" . 'my $class = shift;';
65
66     $source .= "\n" . 'return $class->Moose::Object::new(@_)';
67     $source .= "\n" . '    if $class ne \'' . $self->associated_metaclass->name . '\';';
68
69     $source .= "\n" . 'my %params = (scalar @_ == 1) ? %{$_[0]} : @_;';
70
71     $source .= "\n" . 'my $instance = ' . $self->meta_instance->inline_create_instance('$class');
72
73     $source .= ";\n" . (join ";\n" => map {
74         $self->_generate_slot_initializer($_)
75     } 0 .. (@{$self->attributes} - 1));
76
77     $source .= ";\n" . $self->_generate_BUILDALL();
78
79     $source .= ";\n" . 'return $instance';
80     $source .= ";\n" . '}';
81     warn $source if $self->options->{debug};
82
83     my $code;
84     {
85         # NOTE:
86         # create the nessecary lexicals
87         # to be picked up in the eval
88         my $attrs = $self->attributes;
89
90         # We need to check if the attribute ->can('type_constraint')
91         # since we may be trying to immutabilize a Moose meta class,
92         # which in turn has attributes which are Class::MOP::Attribute
93         # objects, rather than Moose::Meta::Attribute. And 
94         # Class::MOP::Attribute attributes have no type constraints.
95         # However we need to make sure we leave an undef value there
96         # because the inlined code is using the index of the attributes
97         # to determine where to find the type constraint
98         
99         my @type_constraints = map { 
100             $_->can('type_constraint') ? $_->type_constraint : undef
101         } @$attrs;
102         
103         my @type_constraint_bodies = map {
104             defined $_ ? $_->_compiled_type_constraint : undef;
105         } @type_constraints;
106
107         $code = eval $source;
108         confess "Could not eval the constructor :\n\n$source\n\nbecause :\n\n$@" if $@;
109     }
110     $self->{'&!body'} = $code;
111 }
112
113 sub _generate_BUILDALL {
114     my $self = shift;
115     my @BUILD_calls;
116     foreach my $method (reverse $self->associated_metaclass->find_all_methods_by_name('BUILD')) {
117         push @BUILD_calls => '$instance->' . $method->{class} . '::BUILD(\%params)';
118     }
119     return join ";\n" => @BUILD_calls;
120 }
121
122 sub _generate_slot_initializer {
123     my $self  = shift;
124     my $index = shift;
125
126     my $attr = $self->attributes->[$index];
127
128     my @source = ('## ' . $attr->name);
129
130     my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
131
132     if ($is_moose && defined($attr->init_arg) && $attr->is_required && !$attr->has_default && !$attr->has_builder) {
133         push @source => ('(exists $params{\'' . $attr->init_arg . '\'}) ' .
134                         '|| confess "Attribute (' . $attr->name . ') is required";');
135     }
136
137     if (($attr->has_default || $attr->has_builder) && !($is_moose && $attr->is_lazy)) {
138
139         if ( defined( my $init_arg = $attr->init_arg ) ) {
140             push @source => 'if (exists $params{\'' . $init_arg . '\'}) {';
141
142                 push @source => ('my $val = $params{\'' . $init_arg . '\'};');
143
144                 if ($is_moose && $attr->has_type_constraint) {
145                     if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
146                         push @source => $self->_generate_type_coercion(
147                             $attr, 
148                             '$type_constraints[' . $index . ']', 
149                             '$val', 
150                             '$val'
151                         );
152                     }
153                     push @source => $self->_generate_type_constraint_check(
154                         $attr, 
155                         '$type_constraint_bodies[' . $index . ']', 
156                         '$type_constraints[' . $index . ']',                         
157                         '$val'
158                     );
159                 }
160                 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
161
162             push @source => "} else {";
163         }
164             my $default;
165             if ( $attr->has_default ) {
166                 $default = $self->_generate_default_value($attr, $index);
167             } 
168             else {
169                my $builder = $attr->builder;
170                $default = '$instance->' . $builder;
171             }
172             
173             push @source => '{'; # wrap this to avoid my $val overwrite warnings
174             push @source => ('my $val = ' . $default . ';');
175             push @source => $self->_generate_type_constraint_check(
176                 $attr,
177                 ('$type_constraint_bodies[' . $index . ']'),
178                 ('$type_constraints[' . $index . ']'),                
179                 '$val'
180             ) if ($is_moose && $attr->has_type_constraint);
181             
182             push @source => $self->_generate_slot_assignment($attr, '$val', $index);
183             push @source => '}'; # close - wrap this to avoid my $val overrite warnings           
184
185         push @source => "}" if defined $attr->init_arg;
186     }
187     elsif ( defined( my $init_arg = $attr->init_arg ) ) {
188         push @source => '(exists $params{\'' . $init_arg . '\'}) && do {';
189
190             push @source => ('my $val = $params{\'' . $init_arg . '\'};');
191             if ($is_moose && $attr->has_type_constraint) {
192                 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
193                     push @source => $self->_generate_type_coercion(
194                         $attr, 
195                         '$type_constraints[' . $index . ']', 
196                         '$val', 
197                         '$val'
198                     );
199                 }
200                 push @source => $self->_generate_type_constraint_check(
201                     $attr, 
202                     '$type_constraint_bodies[' . $index . ']', 
203                     '$type_constraints[' . $index . ']',                     
204                     '$val'
205                 );
206             }
207             push @source => $self->_generate_slot_assignment($attr, '$val', $index);
208
209         push @source => "}";
210     }
211
212     return join "\n" => @source;
213 }
214
215 sub _generate_slot_assignment {
216     my ($self, $attr, $value, $index) = @_;
217
218     my $source;
219     
220     if ($attr->has_initializer) {
221         $source = (
222             '$attrs->[' . $index . ']->set_initial_value($instance, ' . $value . ');'
223         );        
224     }
225     else {
226         $source = (
227             $self->meta_instance->inline_set_slot_value(
228                 '$instance',
229                 ("'" . $attr->name . "'"),
230                 $value
231             ) . ';'
232         );        
233     }
234     
235     my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME        
236
237     if ($is_moose && $attr->is_weak_ref) {
238         $source .= (
239             "\n" .
240             $self->meta_instance->inline_weaken_slot_value(
241                 '$instance',
242                 ("'" . $attr->name . "'")
243             ) .
244             ' if ref ' . $value . ';'
245         );
246     }
247
248     return $source;
249 }
250
251 sub _generate_type_coercion {
252     my ($self, $attr, $type_constraint_name, $value_name, $return_value_name) = @_;
253     return ($return_value_name . ' = ' . $type_constraint_name .  '->coerce(' . $value_name . ');');
254 }
255
256 sub _generate_type_constraint_check {
257     my ($self, $attr, $type_constraint_cv, $type_constraint_obj, $value_name) = @_;
258     return (
259         $type_constraint_cv . '->(' . $value_name . ')'
260         . "\n\t" . '|| confess "Attribute (' 
261         . $attr->name 
262         . ') does not pass the type constraint because: " . ' 
263         . $type_constraint_obj . '->get_message(' . $value_name . ');'
264     );
265 }
266
267 sub _generate_default_value {
268     my ($self, $attr, $index) = @_;
269     # NOTE:
270     # default values can either be CODE refs
271     # in which case we need to call them. Or
272     # they can be scalars (strings/numbers)
273     # in which case we can just deal with them
274     # in the code we eval.
275     if ($attr->is_default_a_coderef) {
276         return '$attrs->[' . $index . ']->default($instance)';
277     }
278     else {
279         my $default = $attr->default;
280         # make sure to quote strings ...
281         unless (looks_like_number($default)) {
282             $default = "'$default'";
283         }
284
285         return $default;
286     }
287 }
288
289 1;
290
291 __END__
292
293 =pod
294
295 =head1 NAME
296
297 Moose::Meta::Method::Constructor - Method Meta Object for constructors
298
299 =head1 DESCRIPTION
300
301 This is a subclass of L<Class::MOP::Method> which handles
302 constructing an approprate Constructor methods. This is primarily
303 used in the making of immutable metaclasses, otherwise it is
304 not particularly useful.
305
306 =head1 METHODS
307
308 =over 4
309
310 =item B<new>
311
312 =item B<attributes>
313
314 =item B<meta_instance>
315
316 =item B<options>
317
318 =item B<initialize_body>
319
320 =item B<associated_metaclass>
321
322 =back
323
324 =head1 AUTHORS
325
326 Stevan Little E<lt>stevan@iinteractive.comE<gt>
327
328 =head1 COPYRIGHT AND LICENSE
329
330 Copyright 2006-2008 by Infinity Interactive, Inc.
331
332 L<http://www.iinteractive.com>
333
334 This library is free software; you can redistribute it and/or modify
335 it under the same terms as Perl itself.
336
337 =cut
338