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