Added support for fancy triggers, and a test.
[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 Carp         'confess';
8 use Scalar::Util 'blessed', 'weaken', 'looks_like_number';
9
10 our $VERSION   = '0.55';
11 our $AUTHORITY = 'cpan:STEVAN';
12
13 use base 'Moose::Meta::Method',
14          'Class::MOP::Method::Generated';
15
16 sub new {
17     my $class   = shift;
18     my %options = @_;
19
20     (exists $options{options} && ref $options{options} eq 'HASH')
21         || confess "You must pass a hash of options";
22
23     ($options{package_name} && $options{name})
24         || confess "You must supply the package_name and name parameters $Class::MOP::Method::UPGRADE_ERROR_TEXT";
25
26     my $self = bless {
27         # from our superclass
28         '&!body'          => undef, 
29         '$!package_name'  => $options{package_name},
30         '$!name'          => $options{name},
31         # specific to this subclass
32         '%!options'       => $options{options},
33         '$!meta_instance' => $options{metaclass}->get_meta_instance,
34         '@!attributes'    => [ $options{metaclass}->compute_all_applicable_attributes ],
35         # ...
36         '$!associated_metaclass' => $options{metaclass},
37     } => $class;
38
39     # we don't want this creating
40     # a cycle in the code, if not
41     # needed
42     weaken($self->{'$!associated_metaclass'});
43
44     $self->initialize_body;
45
46     return $self;
47 }
48
49 ## accessors
50
51 sub options       { (shift)->{'%!options'}       }
52 sub meta_instance { (shift)->{'$!meta_instance'} }
53 sub attributes    { (shift)->{'@!attributes'}    }
54
55 sub associated_metaclass { (shift)->{'$!associated_metaclass'} }
56
57 ## method
58
59 # this was changed in 0.41, but broke MooseX::Singleton, so try to catch
60 # any other code using the original broken spelling
61 sub intialize_body { confess "Please correct the spelling of 'intialize_body' to 'initialize_body'" }
62
63 sub initialize_body {
64     my $self = shift;
65     # TODO:
66     # the %options should also include a both
67     # a call 'initializer' and call 'SUPER::'
68     # options, which should cover approx 90%
69     # of the possible use cases (even if it
70     # requires some adaption on the part of
71     # the author, after all, nothing is free)
72     my $source = 'sub {';
73     $source .= "\n" . 'my $class = shift;';
74
75     $source .= "\n" . 'return $class->Moose::Object::new(@_)';
76     $source .= "\n" . '    if $class ne \'' . $self->associated_metaclass->name . '\';';
77
78     $source .= "\n" . 'my $params = ' . $self->_generate_BUILDARGS('$class', '@_');
79
80     $source .= ";\n" . 'my $instance = ' . $self->meta_instance->inline_create_instance('$class');
81
82     $source .= ";\n" . (join ";\n" => map {
83         $self->_generate_slot_initializer($_)
84     } 0 .. (@{$self->attributes} - 1));
85
86     $source .= ";\n" . $self->_generate_BUILDALL();
87
88     $source .= ";\n" . 'return $instance';
89     $source .= ";\n" . '}';
90     warn $source if $self->options->{debug};
91
92     my $code;
93     {
94         # NOTE:
95         # create the nessecary lexicals
96         # to be picked up in the eval
97         my $attrs = $self->attributes;
98
99         # We need to check if the attribute ->can('type_constraint')
100         # since we may be trying to immutabilize a Moose meta class,
101         # which in turn has attributes which are Class::MOP::Attribute
102         # objects, rather than Moose::Meta::Attribute. And 
103         # Class::MOP::Attribute attributes have no type constraints.
104         # However we need to make sure we leave an undef value there
105         # because the inlined code is using the index of the attributes
106         # to determine where to find the type constraint
107         
108         my @type_constraints = map { 
109             $_->can('type_constraint') ? $_->type_constraint : undef
110         } @$attrs;
111         
112         my @type_constraint_bodies = map {
113             defined $_ ? $_->_compiled_type_constraint : undef;
114         } @type_constraints;
115
116         $code = eval $source;
117         confess "Could not eval the constructor :\n\n$source\n\nbecause :\n\n$@" if $@;
118     }
119     $self->{'&!body'} = $code;
120 }
121
122 sub _generate_BUILDARGS {
123     my ( $self, $class, $args ) = @_;
124
125     my $buildargs = $self->associated_metaclass->find_method_by_name("BUILDARGS");
126
127     if ( $args eq '@_' and ( !$buildargs or $buildargs->body == \&Moose::Object::BUILDARGS ) ) {
128         return join("\n",
129             'do {',
130             'confess "Single parameters to new() must be a HASH ref"',
131             '    if scalar @_ == 1 && defined $_[0] && ref($_[0]) ne q{HASH};',
132             '(scalar @_ == 1) ? {%{$_[0]}} : {@_};',
133             '}',
134         );
135     } else {
136         return $class . "->BUILDARGS($args)";
137     }
138 }
139
140 sub _generate_BUILDALL {
141     my $self = shift;
142     my @BUILD_calls;
143     foreach my $method (reverse $self->associated_metaclass->find_all_methods_by_name('BUILD')) {
144         push @BUILD_calls => '$instance->' . $method->{class} . '::BUILD($params)';
145     }
146     return join ";\n" => @BUILD_calls;
147 }
148
149 sub _generate_slot_initializer {
150     my $self  = shift;
151     my $index = shift;
152
153     my $attr = $self->attributes->[$index];
154
155     my @source = ('## ' . $attr->name);
156
157     my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
158
159     if ($is_moose && defined($attr->init_arg) && $attr->is_required && !$attr->has_default && !$attr->has_builder) {
160         push @source => ('(exists $params->{\'' . $attr->init_arg . '\'}) ' .
161                         '|| confess "Attribute (' . $attr->name . ') is required";');
162     }
163
164     if (($attr->has_default || $attr->has_builder) && !($is_moose && $attr->is_lazy)) {
165
166         if ( defined( my $init_arg = $attr->init_arg ) ) {
167             push @source => 'if (exists $params->{\'' . $init_arg . '\'}) {';
168
169                 push @source => ('my $val = $params->{\'' . $init_arg . '\'};');
170
171                 if ($is_moose && $attr->has_type_constraint) {
172                     if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
173                         push @source => $self->_generate_type_coercion(
174                             $attr, 
175                             '$type_constraints[' . $index . ']', 
176                             '$val', 
177                             '$val'
178                         );
179                     }
180                     push @source => $self->_generate_type_constraint_check(
181                         $attr, 
182                         '$type_constraint_bodies[' . $index . ']', 
183                         '$type_constraints[' . $index . ']',                         
184                         '$val'
185                     );
186                 }
187                 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
188
189             push @source => "} else {";
190         }
191             my $default;
192             if ( $attr->has_default ) {
193                 $default = $self->_generate_default_value($attr, $index);
194             } 
195             else {
196                my $builder = $attr->builder;
197                $default = '$instance->' . $builder;
198             }
199             
200             push @source => '{'; # wrap this to avoid my $val overwrite warnings
201             push @source => ('my $val = ' . $default . ';');
202             push @source => $self->_generate_type_constraint_check(
203                 $attr,
204                 ('$type_constraint_bodies[' . $index . ']'),
205                 ('$type_constraints[' . $index . ']'),                
206                 '$val'
207             ) if ($is_moose && $attr->has_type_constraint);
208             
209             push @source => $self->_generate_slot_assignment($attr, '$val', $index);
210             push @source => '}'; # close - wrap this to avoid my $val overrite warnings           
211
212         push @source => "}" if defined $attr->init_arg;
213     }
214     elsif ( defined( my $init_arg = $attr->init_arg ) ) {
215         push @source => '(exists $params->{\'' . $init_arg . '\'}) && do {';
216
217             push @source => ('my $val = $params->{\'' . $init_arg . '\'};');
218             if ($is_moose && $attr->has_type_constraint) {
219                 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
220                     push @source => $self->_generate_type_coercion(
221                         $attr, 
222                         '$type_constraints[' . $index . ']', 
223                         '$val', 
224                         '$val'
225                     );
226                 }
227                 push @source => $self->_generate_type_constraint_check(
228                     $attr, 
229                     '$type_constraint_bodies[' . $index . ']', 
230                     '$type_constraints[' . $index . ']',                     
231                     '$val'
232                 );
233             }
234             push @source => $self->_generate_slot_assignment($attr, '$val', $index);
235
236         push @source => "}";
237     }
238
239     return join "\n" => @source;
240 }
241
242 sub _generate_slot_assignment {
243     my ($self, $attr, $value, $index) = @_;
244
245     my $attr_name = "\$attrs->[$index]";
246     my $mi = $self->meta_instance;
247
248     my $gen_code = sub {
249         my ($ins_name, $val_name, $attr_name) = @_;
250         my @miargs = ($ins_name, (sprintf "'%s'", $attr->name), $val_name);
251         my $source;
252
253         if ($attr->has_initializer) {
254            $source = "$attr_name->set_initial_value($ins_name, $val_name);\n"; 
255         }
256         else {
257             $source = $mi->inline_set_slot_value(@miargs) . ";\n";
258         }
259
260         my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME        
261
262         if ($is_moose && $attr->is_weak_ref) {
263             $source .= $mi->inline_weaken_slot_value(@miargs)
264                     .  "if ref $val_name;\n";
265         }
266
267         return $source;
268     };
269     
270     if ($attr->can('_with_inline_triggers')) {
271         return $attr->_with_inline_triggers(
272             '$instance', $value, $attr_name, $gen_code);
273     }
274
275     return $gen_code->('$instance', $value, $attr_name);
276 }
277
278 sub _generate_type_coercion {
279     my ($self, $attr, $type_constraint_name, $value_name, $return_value_name) = @_;
280     return ($return_value_name . ' = ' . $type_constraint_name .  '->coerce(' . $value_name . ');');
281 }
282
283 sub _generate_type_constraint_check {
284     my ($self, $attr, $type_constraint_cv, $type_constraint_obj, $value_name) = @_;
285     return (
286         $type_constraint_cv . '->(' . $value_name . ')'
287         . "\n\t" . '|| confess "Attribute (' 
288         . $attr->name 
289         . ') does not pass the type constraint because: " . ' 
290         . $type_constraint_obj . '->get_message(' . $value_name . ');'
291     );
292 }
293
294 sub _generate_default_value {
295     my ($self, $attr, $index) = @_;
296     # NOTE:
297     # default values can either be CODE refs
298     # in which case we need to call them. Or
299     # they can be scalars (strings/numbers)
300     # in which case we can just deal with them
301     # in the code we eval.
302     if ($attr->is_default_a_coderef) {
303         return '$attrs->[' . $index . ']->default($instance)';
304     }
305     else {
306         my $default = $attr->default;
307         # make sure to quote strings ...
308         unless (looks_like_number($default)) {
309             $default = "'$default'";
310         }
311
312         return $default;
313     }
314 }
315
316 1;
317
318 __END__
319
320 =pod
321
322 =head1 NAME
323
324 Moose::Meta::Method::Constructor - Method Meta Object for constructors
325
326 =head1 DESCRIPTION
327
328 This is a subclass of L<Class::MOP::Method> which handles
329 constructing an approprate Constructor methods. This is primarily
330 used in the making of immutable metaclasses, otherwise it is
331 not particularly useful.
332
333 =head1 METHODS
334
335 =over 4
336
337 =item B<new>
338
339 =item B<attributes>
340
341 =item B<meta_instance>
342
343 =item B<options>
344
345 =item B<initialize_body>
346
347 =item B<associated_metaclass>
348
349 =back
350
351 =head1 AUTHORS
352
353 Stevan Little E<lt>stevan@iinteractive.comE<gt>
354
355 =head1 COPYRIGHT AND LICENSE
356
357 Copyright 2006-2008 by Infinity Interactive, Inc.
358
359 L<http://www.iinteractive.com>
360
361 This library is free software; you can redistribute it and/or modify
362 it under the same terms as Perl itself.
363
364 =cut
365