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