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