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