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