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