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