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