Merge 'trunk' into 'Moose-moosex_compile_support'
[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.03';
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     my $self = bless {
24         # from our superclass
25         '&!body'          => undef,
26         # specific to this subclass
27         '%!options'       => $options{options},
28         '$!meta_instance' => $options{metaclass}->get_meta_instance,
29         '@!attributes'    => [ $options{metaclass}->compute_all_applicable_attributes ],
30         # ...
31         '$!associated_metaclass' => $options{metaclass},
32     } => $class;
33
34     # we don't want this creating
35     # a cycle in the code, if not
36     # needed
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         my @type_constraints = map { $_->type_constraint } @$attrs;
91
92         $code = eval $source;
93         confess "Could not eval the constructor :\n\n$source\n\nbecause :\n\n$@" if $@;
94     }
95     $self->{'&!body'} = $code;
96 }
97
98 sub _generate_BUILDALL {
99     my $self = shift;
100     my @BUILD_calls;
101     foreach my $method (reverse $self->associated_metaclass->find_all_methods_by_name('BUILD')) {
102         push @BUILD_calls => '$instance->' . $method->{class} . '::BUILD(\%params)';
103     }
104     return join ";\n" => @BUILD_calls;
105 }
106
107 sub _generate_slot_initializer {
108     my $self  = shift;
109     my $index = shift;
110
111     my $attr = $self->attributes->[$index];
112
113     my @source = ('## ' . $attr->name);
114
115     my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
116
117     if ($is_moose && $attr->is_required && !$attr->has_default && !$attr->has_builder) {
118         push @source => ('(exists $params{\'' . $attr->init_arg . '\'}) ' .
119                         '|| confess "Attribute (' . $attr->name . ') is required";');
120     }
121
122     if (($attr->has_default || $attr->has_builder) && !($is_moose && $attr->is_lazy)) {
123
124         push @source => 'if (exists $params{\'' . $attr->init_arg . '\'}) {';
125
126             push @source => ('my $val = $params{\'' . $attr->init_arg . '\'};');
127             if ($is_moose && $attr->has_type_constraint) {
128                 push @source => ('my $type_constraint = $type_constraints[' . $index . '];');
129             
130                 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
131                     push @source => $self->_generate_type_coercion($attr, '$type_constraint', '$val', '$val');
132                 }
133                 push @source => $self->_generate_type_constraint_check($attr, '$type_constraint', '$val');
134             }
135             push @source => $self->_generate_slot_assignment($attr, '$val');
136
137         push @source => "} else {";
138
139             my $default;
140             if ( $attr->has_default ) {
141                 $default = $self->_generate_default_value($attr, $index);
142             } 
143             else {
144                my $builder = $attr->builder;
145                $default = '$instance->' . $builder;
146             }
147             push @source => ('my $val = ' . $default . ';');
148             push @source => $self->_generate_type_constraint_check(
149                 $attr,
150                 ('$type_constraints[' . $index . ']'),
151                 '$val'
152             ) if ($is_moose && $attr->has_type_constraint);
153             push @source => $self->_generate_slot_assignment($attr, $default);
154
155         push @source => "}";
156     }
157     else {
158         push @source => '(exists $params{\'' . $attr->init_arg . '\'}) && do {';
159
160             push @source => ('my $val = $params{\'' . $attr->init_arg . '\'};');
161             if ($is_moose && $attr->has_type_constraint) {
162                 push @source => ('my $type_constraint = $type_constraints[' . $index . '];');
163
164                 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
165                     push @source => $self->_generate_type_coercion($attr, '$type_constraint', '$val', '$val');
166                 }
167                 push @source => $self->_generate_type_constraint_check($attr, '$type_constraint', '$val');
168             }
169             push @source => $self->_generate_slot_assignment($attr, '$val');
170
171         push @source => "}";
172     }
173
174     return join "\n" => @source;
175 }
176
177 sub _generate_slot_assignment {
178     my ($self, $attr, $value) = @_;
179     my $source = (
180         $self->meta_instance->inline_set_slot_value(
181             '$instance',
182             ("'" . $attr->name . "'"),
183             $value
184         ) . ';'
185     );
186
187     my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
188
189     if ($is_moose && $attr->is_weak_ref) {
190         $source .= (
191             "\n" .
192             $self->meta_instance->inline_weaken_slot_value(
193                 '$instance',
194                 ("'" . $attr->name . "'")
195             ) .
196             ' if ref ' . $value . ';'
197         );
198     }
199
200     return $source;
201 }
202
203 sub _generate_type_coercion {
204     my ($self, $attr, $type_constraint_name, $value_name, $return_value_name) = @_;
205     return ($return_value_name . ' = ' . $type_constraint_name .  '->coerce(' . $value_name . ');');
206 }
207
208 sub _generate_type_constraint_check {
209     my ($self, $attr, $type_constraint_name, $value_name) = @_;
210     return (
211         'defined(' . $type_constraint_name . '->_compiled_type_constraint->(' . $value_name . '))'
212         . "\n\t" . '|| confess "Attribute (' . $attr->name . ') does not pass the type constraint ('
213         . $attr->type_constraint->name
214         . ') with " . (defined(' . $value_name . ') ? (Scalar::Util::blessed(' . $value_name . ') && overload::Overloaded(' . $value_name . ') ? overload::StrVal(' . $value_name . ') : ' . $value_name . ') : "undef");'
215     );
216 }
217
218 sub _generate_default_value {
219     my ($self, $attr, $index) = @_;
220     # NOTE:
221     # default values can either be CODE refs
222     # in which case we need to call them. Or
223     # they can be scalars (strings/numbers)
224     # in which case we can just deal with them
225     # in the code we eval.
226     if ($attr->is_default_a_coderef) {
227         return '$attrs->[' . $index . ']->default($instance)';
228     }
229     else {
230         my $default = $attr->default;
231         # make sure to quote strings ...
232         unless (looks_like_number($default)) {
233             $default = "'$default'";
234         }
235
236         return $default;
237     }
238 }
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 DESCRIPTION
251
252 This is a subclass of L<Class::MOP::Method> which handles
253 constructing an approprate Constructor methods. This is primarily
254 used in the making of immutable metaclasses, otherwise it is
255 not particularly useful.
256
257 =head1 METHODS
258
259 =over 4
260
261 =item B<new>
262
263 =item B<attributes>
264
265 =item B<meta_instance>
266
267 =item B<options>
268
269 =item B<intialize_body>
270
271 =item B<associated_metaclass>
272
273 =back
274
275 =head1 AUTHORS
276
277 Stevan Little E<lt>stevan@iinteractive.comE<gt>
278
279 =head1 COPYRIGHT AND LICENSE
280
281 Copyright 2006-2008 by Infinity Interactive, Inc.
282
283 L<http://www.iinteractive.com>
284
285 This library is free software; you can redistribute it and/or modify
286 it under the same terms as Perl itself.
287
288 =cut
289