eilaras bug fixed and tested
[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.02';
11 our $AUTHORITY = 'cpan:STEVAN';
12
13 use base 'Moose::Meta::Method';
14
15 sub new {
16     my $class   = shift;
17     my %options = @_;
18         
19     (exists $options{options} && ref $options{options} eq 'HASH')
20         || confess "You must pass a hash of options"; 
21     
22     my $self = bless {
23         # from our superclass
24         '&!body'          => undef,
25         # specific to this subclass
26         '%!options'       => $options{options},
27         '$!meta_instance' => $options{metaclass}->get_meta_instance,
28         '@!attributes'    => [ $options{metaclass}->compute_all_applicable_attributes ], 
29         # ...
30         '$!associated_metaclass' => $options{metaclass},
31     } => $class;
32
33     # we don't want this creating 
34     # a cycle in the code, if not 
35     # needed
36     weaken($self->{'$!associated_metaclass'});    
37
38     $self->intialize_body;
39
40     return $self;    
41 }
42
43 ## accessors 
44
45 sub options       { (shift)->{'%!options'}       }
46 sub meta_instance { (shift)->{'$!meta_instance'} }
47 sub attributes    { (shift)->{'@!attributes'}    }
48
49 sub associated_metaclass { (shift)->{'$!associated_metaclass'} }
50
51 ## method
52
53 sub intialize_body {
54     my $self = shift;
55     # TODO:
56     # the %options should also include a both 
57     # a call 'initializer' and call 'SUPER::' 
58     # options, which should cover approx 90% 
59     # of the possible use cases (even if it 
60     # requires some adaption on the part of 
61     # the author, after all, nothing is free)
62     my $source = 'sub {';
63     $source .= "\n" . 'my $class = shift;';
64     
65     $source .= "\n" . 'return $class->Moose::Object::new(@_)';
66     $source .= "\n" . '    if $class ne \'' . $self->associated_metaclass->name . '\';';    
67     
68     $source .= "\n" . 'my %params = (scalar @_ == 1) ? %{$_[0]} : @_;';    
69     
70     $source .= "\n" . 'my $instance = ' . $self->meta_instance->inline_create_instance('$class');
71     
72     $source .= ";\n" . (join ";\n" => map { 
73         $self->_generate_slot_initializer($_) 
74     } 0 .. (@{$self->attributes} - 1));
75     
76     $source .= ";\n" . $self->_generate_BUILDALL();
77     
78     $source .= ";\n" . 'return $instance';
79     $source .= ";\n" . '}'; 
80     warn $source if $self->options->{debug};   
81     
82     my $code;
83     {
84         # NOTE:
85         # create the nessecary lexicals
86         # to be picked up in the eval 
87         my $attrs = $self->attributes;
88         
89         $code = eval $source;
90         confess "Could not eval the constructor :\n\n$source\n\nbecause :\n\n$@" if $@;
91     }
92     $self->{'&!body'} = $code;
93 }
94
95 sub _generate_BUILDALL {
96     my $self = shift;
97     my @BUILD_calls;
98     foreach my $method (reverse $self->associated_metaclass->find_all_methods_by_name('BUILD')) {
99         push @BUILD_calls => '$instance->' . $method->{class} . '::BUILD(\%params)';    
100     }
101     return join ";\n" => @BUILD_calls; 
102 }
103
104 sub _generate_slot_initializer {
105     my $self  = shift;
106     my $index = shift;
107     
108     my $attr = $self->attributes->[$index];
109     
110     my @source = ('## ' . $attr->name);
111
112     my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
113     
114     if ($is_moose && $attr->is_required && !$attr->has_default) {
115         push @source => ('(exists $params{\'' . $attr->init_arg . '\'}) ' . 
116                         '|| confess "Attribute (' . $attr->name . ') is required";');
117     }
118     
119     if ($attr->has_default && !($is_moose &&$attr->is_lazy)) {
120         
121         push @source => 'if (exists $params{\'' . $attr->init_arg . '\'}) {';
122
123             push @source => ('my $val = $params{\'' . $attr->init_arg . '\'};');
124             if ($is_moose && $attr->has_type_constraint) {
125                 push @source => ('my $type_constraint = $attrs->[' . $index . ']->type_constraint;');
126
127                 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {                    
128                     push @source => $self->_generate_type_coercion($attr, '$type_constraint', '$val', '$val');        
129                 }
130                 push @source => $self->_generate_type_constraint_check($attr, '$type_constraint', '$val');        
131             }
132             push @source => $self->_generate_slot_assignment($attr, '$val');        
133         
134         
135         push @source => "} else {";            
136         
137             my $default = $self->_generate_default_value($attr, $index);  
138         
139             push @source => ('my $val = ' . $default . ';');
140             push @source => $self->_generate_type_constraint_check(
141                 $attr,
142                 ('$attrs->[' . $index . ']->type_constraint'), 
143                 '$val'
144             ) if ($is_moose && $attr->has_type_constraint);            
145             push @source => $self->_generate_slot_assignment($attr, $default);                
146                   
147         push @source => "}";            
148     }          
149     else {
150         push @source => '(exists $params{\'' . $attr->init_arg . '\'}) && do {';
151
152             push @source => ('my $val = $params{\'' . $attr->init_arg . '\'};');
153             if ($is_moose && $attr->has_type_constraint) {
154                 push @source => ('my $type_constraint = $attrs->[' . $index . ']->type_constraint;');
155
156                 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {                    
157                     push @source => $self->_generate_type_coercion($attr, '$type_constraint', '$val', '$val');        
158                 }
159                 push @source => $self->_generate_type_constraint_check($attr, '$type_constraint', '$val');        
160             }
161             push @source => $self->_generate_slot_assignment($attr, '$val');        
162         
163         push @source => "}";            
164     }
165     
166     return join "\n" => @source;
167 }
168
169 sub _generate_slot_assignment {
170     my ($self, $attr, $value) = @_;
171     my $source = (
172         $self->meta_instance->inline_set_slot_value(
173             '$instance', 
174             ("'" . $attr->name . "'"), 
175             $value
176         ) . ';'
177     ); 
178
179     my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
180     
181     if ($is_moose && $attr->is_weak_ref) {
182         $source .= (
183             "\n" .
184             $self->meta_instance->inline_weaken_slot_value(
185                 '$instance', 
186                 ("'" . $attr->name . "'")
187             ) . 
188             ' if ref ' . $value . ';'
189         );    
190     }   
191     
192     return $source;
193 }
194
195 sub _generate_type_coercion {
196     my ($self, $attr, $type_constraint_name, $value_name, $return_value_name) = @_;
197     return ($return_value_name . ' = ' . $type_constraint_name .  '->coerce(' . $value_name . ');');
198 }
199
200 sub _generate_type_constraint_check {
201     my ($self, $attr, $type_constraint_name, $value_name) = @_;
202     return (
203         'defined(' . $type_constraint_name . '->_compiled_type_constraint->(' . $value_name . '))'
204         . "\n\t" . '|| confess "Attribute (' . $attr->name . ') does not pass the type constraint ('
205         . $attr->type_constraint->name 
206         . ') with " . (defined(' . $value_name . ') ? (Scalar::Util::blessed(' . $value_name . ') && overload::Overloaded(' . $value_name . ') ? overload::StrVal(' . $value_name . ') : ' . $value_name . ') : "undef");'
207     );    
208 }
209
210 sub _generate_default_value {
211     my ($self, $attr, $index) = @_;
212     # NOTE:
213     # default values can either be CODE refs
214     # in which case we need to call them. Or 
215     # they can be scalars (strings/numbers)
216     # in which case we can just deal with them
217     # in the code we eval.
218     if ($attr->is_default_a_coderef) {
219         return '$attrs->[' . $index . ']->default($instance)';
220     }
221     else {
222         my $default = $attr->default;
223         # make sure to quote strings ...
224         unless (looks_like_number($default)) {
225             $default = "'$default'";
226         }
227         
228         return $default;
229     }    
230 }
231
232 1;
233
234 __END__
235
236 =pod
237
238 =head1 NAME 
239
240 Moose::Meta::Method::Constructor - Method Meta Object for constructors
241
242 =head1 DESCRIPTION
243
244 This is a subclass of L<Class::MOP::Method> which handles 
245 constructing an approprate Constructor methods. This is primarily 
246 used in the making of immutable metaclasses, otherwise it is 
247 not particularly useful.
248
249 =head1 METHODS
250
251 =over 4
252
253 =item B<new>
254
255 =item B<attributes>
256
257 =item B<meta_instance>
258
259 =item B<options>
260
261 =item B<intialize_body>
262
263 =item B<associated_metaclass>
264
265 =back
266
267 =head1 AUTHORS
268
269 Stevan Little E<lt>stevan@iinteractive.comE<gt>
270
271 =head1 COPYRIGHT AND LICENSE
272
273 Copyright 2006, 2007 by Infinity Interactive, Inc.
274
275 L<http://www.iinteractive.com>
276
277 This library is free software; you can redistribute it and/or modify
278 it under the same terms as Perl itself. 
279
280 =cut
281