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