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