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