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