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