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