2 package Moose::Meta::Method::Constructor;
7 use Scalar::Util 'blessed', 'weaken', 'looks_like_number';
10 our $AUTHORITY = 'cpan:STEVAN';
12 use base 'Moose::Meta::Method',
13 'Class::MOP::Method::Generated';
19 my $meta = $options{metaclass};
21 (ref $options{options} eq 'HASH')
22 || $class->throw_error("You must pass a hash of options", data => $options{options});
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");
30 'package_name' => $options{package_name},
31 'name' => $options{name},
32 # specific to this subclass
33 'options' => $options{options},
34 'meta_instance' => $meta->get_meta_instance,
35 'attributes' => [ $meta->compute_all_applicable_attributes ],
37 'associated_metaclass' => $meta,
40 # we don't want this creating
41 # a cycle in the code, if not
43 weaken($self->{'associated_metaclass'});
45 $self->initialize_body;
52 sub options { (shift)->{'options'} }
53 sub meta_instance { (shift)->{'meta_instance'} }
54 sub attributes { (shift)->{'attributes'} }
56 sub associated_metaclass { (shift)->{'associated_metaclass'} }
60 # this was changed in 0.41, but broke MooseX::Singleton, so try to catch
61 # any other code using the original broken spelling
62 sub intialize_body { Moose->throw_error("Please correct the spelling of 'intialize_body' to 'initialize_body'") }
67 # the %options should also include a both
68 # a call 'initializer' and call 'SUPER::'
69 # options, which should cover approx 90%
70 # of the possible use cases (even if it
71 # requires some adaption on the part of
72 # the author, after all, nothing is free)
74 $source .= "\n" . 'my $class = shift;';
76 $source .= "\n" . 'return $class->Moose::Object::new(@_)';
77 $source .= "\n" . ' if $class ne \'' . $self->associated_metaclass->name . '\';';
79 $source .= "\n" . 'my $params = ' . $self->_generate_BUILDARGS('$class', '@_');
81 $source .= ";\n" . 'my $instance = ' . $self->meta_instance->inline_create_instance('$class');
83 $source .= ";\n" . (join ";\n" => map {
84 $self->_generate_slot_initializer($_)
85 } 0 .. (@{$self->attributes} - 1));
87 $source .= ";\n" . $self->_generate_triggers();
88 $source .= ";\n" . $self->_generate_BUILDALL();
90 $source .= ";\n" . 'return $instance';
91 $source .= ";\n" . '}';
92 warn $source if $self->options->{debug};
96 my $meta = $self; # FIXME for _inline_throw_error...
99 # create the nessecary lexicals
100 # to be picked up in the eval
101 my $attrs = $self->attributes;
103 # We need to check if the attribute ->can('type_constraint')
104 # since we may be trying to immutabilize a Moose meta class,
105 # which in turn has attributes which are Class::MOP::Attribute
106 # objects, rather than Moose::Meta::Attribute. And
107 # Class::MOP::Attribute attributes have no type constraints.
108 # However we need to make sure we leave an undef value there
109 # because the inlined code is using the index of the attributes
110 # to determine where to find the type constraint
112 my @type_constraints = map {
113 $_->can('type_constraint') ? $_->type_constraint : undef
116 my @type_constraint_bodies = map {
117 defined $_ ? $_->_compiled_type_constraint : undef;
120 $code = eval $source;
121 $self->throw_error("Could not eval the constructor :\n\n$source\n\nbecause :\n\n$@", error => $@, data => $source ) if $@;
123 $self->{'body'} = $code;
126 sub _generate_BUILDARGS {
127 my ( $self, $class, $args ) = @_;
129 my $buildargs = $self->associated_metaclass->find_method_by_name("BUILDARGS");
131 if ( $args eq '@_' and ( !$buildargs or $buildargs->body == \&Moose::Object::BUILDARGS ) ) {
134 $self->_inline_throw_error('"Single parameters to new() must be a HASH ref"', 'data => $_[0]'),
135 ' if scalar @_ == 1 && defined $_[0] && ref($_[0]) ne q{HASH};',
136 '(scalar @_ == 1) ? {%{$_[0]}} : {@_};',
140 return $class . "->BUILDARGS($args)";
144 sub _generate_BUILDALL {
147 foreach my $method (reverse $self->associated_metaclass->find_all_methods_by_name('BUILD')) {
148 push @BUILD_calls => '$instance->' . $method->{class} . '::BUILD($params)';
150 return join ";\n" => @BUILD_calls;
153 sub _generate_triggers {
156 foreach my $i (0 .. $#{ $self->attributes }) {
157 my $attr = $self->attributes->[$i];
158 if ($attr->can('has_trigger') && $attr->has_trigger) {
159 if (defined(my $init_arg = $attr->init_arg)) {
160 push @trigger_calls => (
161 '(exists $params->{\'' . $init_arg . '\'}) && do {' . "\n "
162 . '$attrs->[' . $i . ']->trigger->('
164 . $self->meta_instance->inline_get_slot_value(
166 ("'" . $attr->name . "'")
169 . '$attrs->[' . $i . ']'
176 return join ";\n" => @trigger_calls;
179 sub _generate_slot_initializer {
183 my $attr = $self->attributes->[$index];
185 my @source = ('## ' . $attr->name);
187 my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
189 if ($is_moose && defined($attr->init_arg) && $attr->is_required && !$attr->has_default && !$attr->has_builder) {
190 push @source => ('(exists $params->{\'' . $attr->init_arg . '\'}) ' .
191 '|| ' . $self->_inline_throw_error('"Attribute (' . $attr->name . ') is required"') .';');
194 if (($attr->has_default || $attr->has_builder) && !($is_moose && $attr->is_lazy)) {
196 if ( defined( my $init_arg = $attr->init_arg ) ) {
197 push @source => 'if (exists $params->{\'' . $init_arg . '\'}) {';
198 push @source => ('my $val = $params->{\'' . $init_arg . '\'};');
199 push @source => $self->_generate_type_constraint_and_coercion($attr, $index)
201 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
202 push @source => "} else {";
205 if ( $attr->has_default ) {
206 $default = $self->_generate_default_value($attr, $index);
209 my $builder = $attr->builder;
210 $default = '$instance->' . $builder;
213 push @source => '{'; # wrap this to avoid my $val overwrite warnings
214 push @source => ('my $val = ' . $default . ';');
215 push @source => $self->_generate_type_constraint_and_coercion($attr, $index)
217 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
218 push @source => '}'; # close - wrap this to avoid my $val overrite warnings
220 push @source => "}" if defined $attr->init_arg;
222 elsif ( defined( my $init_arg = $attr->init_arg ) ) {
223 push @source => '(exists $params->{\'' . $init_arg . '\'}) && do {';
225 push @source => ('my $val = $params->{\'' . $init_arg . '\'};');
226 if ($is_moose && $attr->has_type_constraint) {
227 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
228 push @source => $self->_generate_type_coercion(
230 '$type_constraints[' . $index . ']',
235 push @source => $self->_generate_type_constraint_check(
237 '$type_constraint_bodies[' . $index . ']',
238 '$type_constraints[' . $index . ']',
242 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
247 return join "\n" => @source;
250 sub _generate_slot_assignment {
251 my ($self, $attr, $value, $index) = @_;
255 if ($attr->has_initializer) {
257 '$attrs->[' . $index . ']->set_initial_value($instance, ' . $value . ');'
262 $self->meta_instance->inline_set_slot_value(
264 ("'" . $attr->name . "'"),
270 my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
272 if ($is_moose && $attr->is_weak_ref) {
275 $self->meta_instance->inline_weaken_slot_value(
277 ("'" . $attr->name . "'")
279 ' if ref ' . $value . ';'
286 sub _generate_type_constraint_and_coercion {
287 my ($self, $attr, $index) = @_;
289 return unless $attr->has_type_constraint;
292 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
293 push @source => $self->_generate_type_coercion(
295 '$type_constraints[' . $index . ']',
300 push @source => $self->_generate_type_constraint_check(
302 ('$type_constraint_bodies[' . $index . ']'),
303 ('$type_constraints[' . $index . ']'),
309 sub _generate_type_coercion {
310 my ($self, $attr, $type_constraint_name, $value_name, $return_value_name) = @_;
311 return ($return_value_name . ' = ' . $type_constraint_name . '->coerce(' . $value_name . ');');
314 sub _generate_type_constraint_check {
315 my ($self, $attr, $type_constraint_cv, $type_constraint_obj, $value_name) = @_;
317 $self->_inline_throw_error('"Attribute (' # FIXME add 'dad'
319 . ') does not pass the type constraint because: " . '
320 . $type_constraint_obj . '->get_message(' . $value_name . ')')
321 . "\n\t unless " . $type_constraint_cv . '->(' . $value_name . ');'
325 sub _generate_default_value {
326 my ($self, $attr, $index) = @_;
328 # default values can either be CODE refs
329 # in which case we need to call them. Or
330 # they can be scalars (strings/numbers)
331 # in which case we can just deal with them
332 # in the code we eval.
333 if ($attr->is_default_a_coderef) {
334 return '$attrs->[' . $index . ']->default($instance)';
337 my $default = $attr->default;
338 # make sure to quote strings ...
352 Moose::Meta::Method::Constructor - Method Meta Object for constructors
356 This is a subclass of L<Class::MOP::Method> which handles
357 constructing an approprate Constructor methods. This is primarily
358 used in the making of immutable metaclasses, otherwise it is
359 not particularly useful.
369 =item B<meta_instance>
373 =item B<initialize_body>
375 =item B<associated_metaclass>
381 Stevan Little E<lt>stevan@iinteractive.comE<gt>
383 =head1 COPYRIGHT AND LICENSE
385 Copyright 2006-2008 by Infinity Interactive, Inc.
387 L<http://www.iinteractive.com>
389 This library is free software; you can redistribute it and/or modify
390 it under the same terms as Perl itself.