c06a6514d0162a59f935bbaef424f1ec2a963b87
[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.06';
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         # We need to check if the attribute ->can('type_constraint')
91         # since we may be trying to immutabilize a Moose meta class,
92         # which in turn has attributes which are Class::MOP::Attribute
93         # objects, rather than Moose::Meta::Attribute. And 
94         # Class::MOP::Attribute attributes have no type constraints.
95         my @type_constraints = map { $_->type_constraint } grep { $_->can('type_constraint') } @$attrs;
96         my @type_constraint_bodies = map {
97             $_ && $_->_compiled_type_constraint;
98         } @type_constraints;
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     my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
124
125     if ($is_moose && $attr->is_required && !$attr->has_default && !$attr->has_builder) {
126         push @source => ('(exists $params{\'' . $attr->init_arg . '\'}) ' .
127                         '|| confess "Attribute (' . $attr->name . ') is required";');
128     }
129
130     if (($attr->has_default || $attr->has_builder) && !($is_moose && $attr->is_lazy)) {
131
132         push @source => 'if (exists $params{\'' . $attr->init_arg . '\'}) {';
133
134             push @source => ('my $val = $params{\'' . $attr->init_arg . '\'};');
135             if ($is_moose && $attr->has_type_constraint) {
136                 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
137                     push @source => $self->_generate_type_coercion($attr, '$type_constraints[' . $index . ']', '$val', '$val');
138                 }
139                 push @source => $self->_generate_type_constraint_check($attr, '$type_constraint_bodies[' . $index . ']', '$val');
140             }
141             push @source => $self->_generate_slot_assignment($attr, '$val');
142
143         push @source => "} else {";
144
145             my $default;
146             if ( $attr->has_default ) {
147                 $default = $self->_generate_default_value($attr, $index);
148             } 
149             else {
150                my $builder = $attr->builder;
151                $default = '$instance->' . $builder;
152             }
153             push @source => ('my $val = ' . $default . ';');
154             push @source => $self->_generate_type_constraint_check(
155                 $attr,
156                 ('$type_constraint_bodies[' . $index . ']'),
157                 '$val'
158             ) if ($is_moose && $attr->has_type_constraint);
159             push @source => $self->_generate_slot_assignment($attr, $default);
160
161         push @source => "}";
162     }
163     else {
164         push @source => '(exists $params{\'' . $attr->init_arg . '\'}) && do {';
165
166             push @source => ('my $val = $params{\'' . $attr->init_arg . '\'};');
167             if ($is_moose && $attr->has_type_constraint) {
168                 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
169                     push @source => $self->_generate_type_coercion($attr, '$type_constraints[' . $index . ']', '$val', '$val');
170                 }
171                 push @source => $self->_generate_type_constraint_check($attr, '$type_constraint_bodies[' . $index . ']', '$val');
172             }
173             push @source => $self->_generate_slot_assignment($attr, '$val');
174
175         push @source => "}";
176     }
177
178     return join "\n" => @source;
179 }
180
181 sub _generate_slot_assignment {
182     my ($self, $attr, $value) = @_;
183     my $source = (
184         $self->meta_instance->inline_set_slot_value(
185             '$instance',
186             ("'" . $attr->name . "'"),
187             $value
188         ) . ';'
189     );
190
191     my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
192
193     if ($is_moose && $attr->is_weak_ref) {
194         $source .= (
195             "\n" .
196             $self->meta_instance->inline_weaken_slot_value(
197                 '$instance',
198                 ("'" . $attr->name . "'")
199             ) .
200             ' if ref ' . $value . ';'
201         );
202     }
203
204     return $source;
205 }
206
207 sub _generate_type_coercion {
208     my ($self, $attr, $type_constraint_name, $value_name, $return_value_name) = @_;
209     return ($return_value_name . ' = ' . $type_constraint_name .  '->coerce(' . $value_name . ');');
210 }
211
212 sub _generate_type_constraint_check {
213     my ($self, $attr, $type_constraint_cv, $value_name) = @_;
214     return (
215         $type_constraint_cv . '->(' . $value_name . ')'
216         . "\n\t" . '|| confess "Attribute (' . $attr->name . ') does not pass the type constraint ('
217         . $attr->type_constraint->name
218         . ') with " . (defined(' . $value_name . ') ? overload::StrVal(' . $value_name . ') : "undef");'
219     );
220 }
221
222 sub _generate_default_value {
223     my ($self, $attr, $index) = @_;
224     # NOTE:
225     # default values can either be CODE refs
226     # in which case we need to call them. Or
227     # they can be scalars (strings/numbers)
228     # in which case we can just deal with them
229     # in the code we eval.
230     if ($attr->is_default_a_coderef) {
231         return '$attrs->[' . $index . ']->default($instance)';
232     }
233     else {
234         my $default = $attr->default;
235         # make sure to quote strings ...
236         unless (looks_like_number($default)) {
237             $default = "'$default'";
238         }
239
240         return $default;
241     }
242 }
243
244 1;
245
246 __END__
247
248 =pod
249
250 =head1 NAME
251
252 Moose::Meta::Method::Constructor - Method Meta Object for constructors
253
254 =head1 DESCRIPTION
255
256 This is a subclass of L<Class::MOP::Method> which handles
257 constructing an approprate Constructor methods. This is primarily
258 used in the making of immutable metaclasses, otherwise it is
259 not particularly useful.
260
261 =head1 METHODS
262
263 =over 4
264
265 =item B<new>
266
267 =item B<attributes>
268
269 =item B<meta_instance>
270
271 =item B<options>
272
273 =item B<intialize_body>
274
275 =item B<associated_metaclass>
276
277 =back
278
279 =head1 AUTHORS
280
281 Stevan Little E<lt>stevan@iinteractive.comE<gt>
282
283 =head1 COPYRIGHT AND LICENSE
284
285 Copyright 2006-2008 by Infinity Interactive, Inc.
286
287 L<http://www.iinteractive.com>
288
289 This library is free software; you can redistribute it and/or modify
290 it under the same terms as Perl itself.
291
292 =cut
293