bump version to 0.89_02 and set release date
[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 Scalar::Util 'blessed', 'weaken', 'looks_like_number', 'refaddr';
8
9 our $VERSION   = '0.89_02';
10 our $AUTHORITY = 'cpan:STEVAN';
11
12 use base 'Moose::Meta::Method',
13          'Class::MOP::Method::Constructor';
14
15 sub new {
16     my $class   = shift;
17     my %options = @_;
18
19     my $meta = $options{metaclass};
20
21     (ref $options{options} eq 'HASH')
22         || $class->throw_error("You must pass a hash of options", data => $options{options});
23
24     ($options{package_name} && $options{name})
25         || $class->throw_error("You must supply the package_name and name parameters $Class::MOP::Method::UPGRADE_ERROR_TEXT");
26
27     my $self = bless {
28         'body'          => undef,
29         'package_name'  => $options{package_name},
30         'name'          => $options{name},
31         'options'       => $options{options},
32         'associated_metaclass' => $meta,
33         '_expected_method_class' => $options{_expected_method_class} || 'Moose::Object',
34     } => $class;
35
36     # we don't want this creating
37     # a cycle in the code, if not
38     # needed
39     weaken($self->{'associated_metaclass'});
40
41     $self->_initialize_body;
42
43     return $self;
44 }
45
46 # This is here so can_be_inlined can be inherited by MooseX modules.
47 sub _expected_constructor_class {
48     return 'Moose::Object';
49 }
50
51 ## method
52
53 sub _initialize_body {
54     my $self = shift;
55     # TODO:
56     # the %options should also include a both
57     # a call 'initializer' and call 'SUPER::'
58     # options, which should cover approx 90%
59     # of the possible use cases (even if it
60     # requires some adaption on the part of
61     # the author, after all, nothing is free)
62     my $source = 'sub {';
63     $source .= "\n" . 'my $_instance = shift;';
64     $source .= "\n" . 'my $class = Scalar::Util::blessed($_instance) || $_instance;';
65
66     $source .= "\n" . 'return $class->Moose::Object::new(@_)';
67     $source .= "\n    if \$class ne '" . $self->associated_metaclass->name
68             .  "';\n";
69
70     $source .= $self->_generate_params('$params', '$class');
71     $source .= $self->_generate_instance('$instance', '$class');
72     $source .= $self->_generate_slot_initializers;
73
74     $source .= $self->_generate_triggers();
75     $source .= ";\n" . $self->_generate_BUILDALL();
76
77     $source .= ";\nreturn \$instance";
78     $source .= ";\n" . '}';
79     warn $source if $self->options->{debug};
80
81     # We need to check if the attribute ->can('type_constraint')
82     # since we may be trying to immutabilize a Moose meta class,
83     # which in turn has attributes which are Class::MOP::Attribute
84     # objects, rather than Moose::Meta::Attribute. And
85     # Class::MOP::Attribute attributes have no type constraints.
86     # However we need to make sure we leave an undef value there
87     # because the inlined code is using the index of the attributes
88     # to determine where to find the type constraint
89
90     my $attrs = $self->_attributes;
91
92     my @type_constraints = map {
93         $_->can('type_constraint') ? $_->type_constraint : undef
94     } @$attrs;
95
96     my @type_constraint_bodies = map {
97         defined $_ ? $_->_compiled_type_constraint : undef;
98     } @type_constraints;
99
100     my ( $code, $e ) = $self->_compile_code(
101         code => $source,
102         environment => {
103             '$meta'  => \$self,
104             '$attrs' => \$attrs,
105             '@type_constraints' => \@type_constraints,
106             '@type_constraint_bodies' => \@type_constraint_bodies,
107         },
108     );
109
110     $self->throw_error(
111         "Could not eval the constructor :\n\n$source\n\nbecause :\n\n$e",
112         error => $e, data => $source )
113         if $e;
114
115     $self->{'body'} = $code;
116 }
117
118 sub _generate_params {
119     my ( $self, $var, $class_var ) = @_;
120     "my $var = " . $self->_generate_BUILDARGS( $class_var, '@_' ) . ";\n";
121 }
122
123 sub _generate_instance {
124     my ( $self, $var, $class_var ) = @_;
125     "my $var = "
126         . $self->_meta_instance->inline_create_instance($class_var) . ";\n";
127 }
128
129 sub _generate_slot_initializers {
130     my ($self) = @_;
131     return (join ";\n" => map {
132         $self->_generate_slot_initializer($_)
133     } 0 .. (@{$self->_attributes} - 1)) . ";\n";
134 }
135
136 sub _generate_BUILDARGS {
137     my ( $self, $class, $args ) = @_;
138
139     my $buildargs = $self->associated_metaclass->find_method_by_name("BUILDARGS");
140
141     if ( $args eq '@_' and ( !$buildargs or $buildargs->body == \&Moose::Object::BUILDARGS ) ) {
142         return join("\n",
143             'do {',
144             $self->_inline_throw_error('"Single parameters to new() must be a HASH ref"', 'data => $_[0]'),
145             '    if scalar @_ == 1 && !( defined $_[0] && ref $_[0] eq q{HASH} );',
146             '(scalar @_ == 1) ? {%{$_[0]}} : {@_};',
147             '}',
148         );
149     } else {
150         return $class . "->BUILDARGS($args)";
151     }
152 }
153
154 sub _generate_BUILDALL {
155     my $self = shift;
156     my @BUILD_calls;
157     foreach my $method (reverse $self->associated_metaclass->find_all_methods_by_name('BUILD')) {
158         push @BUILD_calls => '$instance->' . $method->{class} . '::BUILD($params)';
159     }
160     return join ";\n" => @BUILD_calls;
161 }
162
163 sub _generate_triggers {
164     my $self = shift;
165     my @trigger_calls;
166     foreach my $i ( 0 .. $#{ $self->_attributes } ) {
167         my $attr = $self->_attributes->[$i];
168
169         next unless $attr->can('has_trigger') && $attr->has_trigger;
170
171         my $init_arg = $attr->init_arg;
172
173         next unless defined $init_arg;
174
175         push @trigger_calls => '(exists $params->{\''
176             . $init_arg
177             . '\'}) && do {'
178             . "\n    "
179             . '$attrs->['
180             . $i
181             . ']->trigger->('
182             . '$instance, '
183             . $self->_meta_instance->inline_get_slot_value(
184                   '$instance',
185                   $attr->name,
186               )
187             . ', '
188             . ');' . "\n}";
189     }
190
191     return join ";\n" => @trigger_calls;
192 }
193
194 sub _generate_slot_initializer {
195     my $self  = shift;
196     my $index = shift;
197
198     my $attr = $self->_attributes->[$index];
199
200     my @source = ('## ' . $attr->name);
201
202     my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
203
204     if ($is_moose && defined($attr->init_arg) && $attr->is_required && !$attr->has_default && !$attr->has_builder) {
205         push @source => ('(exists $params->{\'' . $attr->init_arg . '\'}) ' .
206                         '|| ' . $self->_inline_throw_error('"Attribute (' . $attr->name . ') is required"') .';');
207     }
208
209     if (($attr->has_default || $attr->has_builder) && !($is_moose && $attr->is_lazy)) {
210
211         if ( defined( my $init_arg = $attr->init_arg ) ) {
212             push @source => 'if (exists $params->{\'' . $init_arg . '\'}) {';
213             push @source => ('my $val = $params->{\'' . $init_arg . '\'};');
214             push @source => $self->_generate_type_constraint_and_coercion($attr, $index)
215                 if $is_moose;
216             push @source => $self->_generate_slot_assignment($attr, '$val', $index);
217             push @source => "} else {";
218         }
219             my $default;
220             if ( $attr->has_default ) {
221                 $default = $self->_generate_default_value($attr, $index);
222             }
223             else {
224                my $builder = $attr->builder;
225                $default = '$instance->' . $builder;
226             }
227
228             push @source => '{'; # wrap this to avoid my $val overwrite warnings
229             push @source => ('my $val = ' . $default . ';');
230             push @source => $self->_generate_type_constraint_and_coercion($attr, $index)
231                 if $is_moose;
232             push @source => $self->_generate_slot_assignment($attr, '$val', $index);
233             push @source => '}'; # close - wrap this to avoid my $val overrite warnings
234
235         push @source => "}" if defined $attr->init_arg;
236     }
237     elsif ( defined( my $init_arg = $attr->init_arg ) ) {
238         push @source => '(exists $params->{\'' . $init_arg . '\'}) && do {';
239
240             push @source => ('my $val = $params->{\'' . $init_arg . '\'};');
241             if ($is_moose && $attr->has_type_constraint) {
242                 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
243                     push @source => $self->_generate_type_coercion(
244                         $attr,
245                         '$type_constraints[' . $index . ']',
246                         '$val',
247                         '$val'
248                     );
249                 }
250                 push @source => $self->_generate_type_constraint_check(
251                     $attr,
252                     '$type_constraint_bodies[' . $index . ']',
253                     '$type_constraints[' . $index . ']',
254                     '$val'
255                 );
256             }
257             push @source => $self->_generate_slot_assignment($attr, '$val', $index);
258
259         push @source => "}";
260     }
261
262     return join "\n" => @source;
263 }
264
265 sub _generate_slot_assignment {
266     my ($self, $attr, $value, $index) = @_;
267
268     my $source;
269
270     if ($attr->has_initializer) {
271         $source = (
272             '$attrs->[' . $index . ']->set_initial_value($instance, ' . $value . ');'
273         );
274     }
275     else {
276         $source = (
277             $self->_meta_instance->inline_set_slot_value(
278                 '$instance',
279                 $attr->name,
280                 $value
281             ) . ';'
282         );
283     }
284
285     my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
286
287     if ($is_moose && $attr->is_weak_ref) {
288         $source .= (
289             "\n" .
290             $self->_meta_instance->inline_weaken_slot_value(
291                 '$instance',
292                 $attr->name
293             ) .
294             ' if ref ' . $value . ';'
295         );
296     }
297
298     return $source;
299 }
300
301 sub _generate_type_constraint_and_coercion {
302     my ($self, $attr, $index) = @_;
303
304     return unless $attr->has_type_constraint;
305
306     my @source;
307     if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
308         push @source => $self->_generate_type_coercion(
309             $attr,
310             '$type_constraints[' . $index . ']',
311             '$val',
312             '$val'
313         );
314     }
315     push @source => $self->_generate_type_constraint_check(
316         $attr,
317         ('$type_constraint_bodies[' . $index . ']'),
318         ('$type_constraints[' . $index . ']'),
319         '$val'
320     );
321     return @source;
322 }
323
324 sub _generate_type_coercion {
325     my ($self, $attr, $type_constraint_name, $value_name, $return_value_name) = @_;
326     return ($return_value_name . ' = ' . $type_constraint_name .  '->coerce(' . $value_name . ');');
327 }
328
329 sub _generate_type_constraint_check {
330     my ($self, $attr, $type_constraint_cv, $type_constraint_obj, $value_name) = @_;
331     return (
332         $self->_inline_throw_error('"Attribute (' # FIXME add 'dad'
333         . $attr->name
334         . ') does not pass the type constraint because: " . '
335         . $type_constraint_obj . '->get_message(' . $value_name . ')')
336         . "\n\t unless " .  $type_constraint_cv . '->(' . $value_name . ');'
337     );
338 }
339
340 sub _generate_default_value {
341     my ($self, $attr, $index) = @_;
342     # NOTE:
343     # default values can either be CODE refs
344     # in which case we need to call them. Or
345     # they can be scalars (strings/numbers)
346     # in which case we can just deal with them
347     # in the code we eval.
348     if ($attr->is_default_a_coderef) {
349         return '$attrs->[' . $index . ']->default($instance)';
350     }
351     else {
352         return q{"} . quotemeta( $attr->default ) . q{"};
353     }
354 }
355
356 1;
357
358 __END__
359
360 =pod
361
362 =head1 NAME
363
364 Moose::Meta::Method::Constructor - Method Meta Object for constructors
365
366 =head1 DESCRIPTION
367
368 This class is a subclass of L<Class::MOP::Class::Constructor> that
369 provides additional Moose-specific functionality
370
371 To understand this class, you should read the the
372 L<Class::MOP::Class::Constructor> documentation as well.
373
374 =head1 INHERITANCE
375
376 C<Moose::Meta::Method::Constructor> is a subclass of
377 L<Moose::Meta::Method> I<and> L<Class::MOP::Method::Constructor>.
378
379 =head1 AUTHORS
380
381 Stevan Little E<lt>stevan@iinteractive.comE<gt>
382
383 =head1 COPYRIGHT AND LICENSE
384
385 Copyright 2006-2009 by Infinity Interactive, Inc.
386
387 L<http://www.iinteractive.com>
388
389 This library is free software; you can redistribute it and/or modify
390 it under the same terms as Perl itself.
391
392 =cut
393