2 package Moose::Meta::Method::Constructor;
7 use Scalar::Util 'blessed', 'weaken', 'looks_like_number';
9 our $VERSION = '0.62_01';
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 my $metaclass = $self->associated_metaclass;
54 my $class = $self->associated_metaclass->name;
56 # If any of our parents have been made immutable, we are okay to
57 # inline our own method as long as the parent's constructor class
58 # is the same as $self.
59 for my $meta ( grep { $_->is_immutable }
60 map { ( ref $metaclass )->initialize($_) }
61 $metaclass->linearized_isa ) {
62 my $transformer = $meta->get_immutable_transformer;
64 my $constructor = $transformer->inlined_constructor
67 return 1 if ref $constructor eq ref $self;
69 my $parent_name = $meta->name;
70 my $constructor_class = ref $constructor;
71 my $self_class = ref $self;
73 # This case is fairly unlikely. In most normal cases,
74 # incompatibility between constructor classes will be caught
75 # by the code that fixes metaclass incompatibility in
76 # Moose::Meta::Class. However, if the parent passes a
77 # constructor_class directly to
78 # Parent->meta->make_immutable(), this could happen.
79 warn "Not inlining a constructor for $class. It has a parent class ($parent_name)"
80 . " which was inlined using $constructor_class, but $class is using $self_class\n";
85 if ( my $constructor = $metaclass->find_method_by_name( $self->name ) ) {
87 my $expected_class = $self->_expected_constructor_class;
89 if ( $constructor->body != $expected_class->can('new') ) {
90 warn "Not inlining a constructor for $class since it is not"
91 . " inheriting the default $expected_class constructor\n";
100 # This would be a rather weird case where we have no constructor
101 # in the inheritance chain.
105 # This is here so can_be_inlined can be inherited by MooseX modules.
106 sub _expected_constructor_class {
107 return 'Moose::Object';
112 sub options { (shift)->{'options'} }
113 sub meta_instance { (shift)->{'meta_instance'} }
114 sub attributes { (shift)->{'attributes'} }
116 sub associated_metaclass { (shift)->{'associated_metaclass'} }
120 # this was changed in 0.41, but broke MooseX::Singleton, so try to catch
121 # any other code using the original broken spelling
122 sub intialize_body { Moose->throw_error("Please correct the spelling of 'intialize_body' to 'initialize_body'") }
124 sub initialize_body {
127 # the %options should also include a both
128 # a call 'initializer' and call 'SUPER::'
129 # options, which should cover approx 90%
130 # of the possible use cases (even if it
131 # requires some adaption on the part of
132 # the author, after all, nothing is free)
133 my $source = 'sub {';
134 $source .= "\n" . 'my $class = shift;';
136 $source .= "\n" . 'return $class->Moose::Object::new(@_)';
137 $source .= "\n" . ' if $class ne \'' . $self->associated_metaclass->name . '\';';
139 $source .= "\n" . 'my $params = ' . $self->_generate_BUILDARGS('$class', '@_');
141 $source .= ";\n" . 'my $instance = ' . $self->meta_instance->inline_create_instance('$class');
143 $source .= ";\n" . (join ";\n" => map {
144 $self->_generate_slot_initializer($_)
145 } 0 .. (@{$self->attributes} - 1));
147 $source .= ";\n" . $self->_generate_triggers();
148 $source .= ";\n" . $self->_generate_BUILDALL();
150 $source .= ";\n" . 'return $instance';
151 $source .= ";\n" . '}';
152 warn $source if $self->options->{debug};
156 my $meta = $self; # FIXME for _inline_throw_error...
159 # create the nessecary lexicals
160 # to be picked up in the eval
161 my $attrs = $self->attributes;
163 # We need to check if the attribute ->can('type_constraint')
164 # since we may be trying to immutabilize a Moose meta class,
165 # which in turn has attributes which are Class::MOP::Attribute
166 # objects, rather than Moose::Meta::Attribute. And
167 # Class::MOP::Attribute attributes have no type constraints.
168 # However we need to make sure we leave an undef value there
169 # because the inlined code is using the index of the attributes
170 # to determine where to find the type constraint
172 my @type_constraints = map {
173 $_->can('type_constraint') ? $_->type_constraint : undef
176 my @type_constraint_bodies = map {
177 defined $_ ? $_->_compiled_type_constraint : undef;
180 $code = eval $source;
181 $self->throw_error("Could not eval the constructor :\n\n$source\n\nbecause :\n\n$@", error => $@, data => $source ) if $@;
183 $self->{'body'} = $code;
186 sub _generate_BUILDARGS {
187 my ( $self, $class, $args ) = @_;
189 my $buildargs = $self->associated_metaclass->find_method_by_name("BUILDARGS");
191 if ( $args eq '@_' and ( !$buildargs or $buildargs->body == \&Moose::Object::BUILDARGS ) ) {
194 $self->_inline_throw_error('"Single parameters to new() must be a HASH ref"', 'data => $_[0]'),
195 ' if scalar @_ == 1 && defined $_[0] && ref($_[0]) ne q{HASH};',
196 '(scalar @_ == 1) ? {%{$_[0]}} : {@_};',
200 return $class . "->BUILDARGS($args)";
204 sub _generate_BUILDALL {
207 foreach my $method (reverse $self->associated_metaclass->find_all_methods_by_name('BUILD')) {
208 push @BUILD_calls => '$instance->' . $method->{class} . '::BUILD($params)';
210 return join ";\n" => @BUILD_calls;
213 sub _generate_triggers {
216 foreach my $i (0 .. $#{ $self->attributes }) {
217 my $attr = $self->attributes->[$i];
218 if ($attr->can('has_trigger') && $attr->has_trigger) {
219 if (defined(my $init_arg = $attr->init_arg)) {
220 push @trigger_calls => (
221 '(exists $params->{\'' . $init_arg . '\'}) && do {' . "\n "
222 . '$attrs->[' . $i . ']->trigger->('
224 . $self->meta_instance->inline_get_slot_value(
226 ("'" . $attr->name . "'")
229 . '$attrs->[' . $i . ']'
236 return join ";\n" => @trigger_calls;
239 sub _generate_slot_initializer {
243 my $attr = $self->attributes->[$index];
245 my @source = ('## ' . $attr->name);
247 my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
249 if ($is_moose && defined($attr->init_arg) && $attr->is_required && !$attr->has_default && !$attr->has_builder) {
250 push @source => ('(exists $params->{\'' . $attr->init_arg . '\'}) ' .
251 '|| ' . $self->_inline_throw_error('"Attribute (' . $attr->name . ') is required"') .';');
254 if (($attr->has_default || $attr->has_builder) && !($is_moose && $attr->is_lazy)) {
256 if ( defined( my $init_arg = $attr->init_arg ) ) {
257 push @source => 'if (exists $params->{\'' . $init_arg . '\'}) {';
258 push @source => ('my $val = $params->{\'' . $init_arg . '\'};');
259 push @source => $self->_generate_type_constraint_and_coercion($attr, $index)
261 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
262 push @source => "} else {";
265 if ( $attr->has_default ) {
266 $default = $self->_generate_default_value($attr, $index);
269 my $builder = $attr->builder;
270 $default = '$instance->' . $builder;
273 push @source => '{'; # wrap this to avoid my $val overwrite warnings
274 push @source => ('my $val = ' . $default . ';');
275 push @source => $self->_generate_type_constraint_and_coercion($attr, $index)
277 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
278 push @source => '}'; # close - wrap this to avoid my $val overrite warnings
280 push @source => "}" if defined $attr->init_arg;
282 elsif ( defined( my $init_arg = $attr->init_arg ) ) {
283 push @source => '(exists $params->{\'' . $init_arg . '\'}) && do {';
285 push @source => ('my $val = $params->{\'' . $init_arg . '\'};');
286 if ($is_moose && $attr->has_type_constraint) {
287 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
288 push @source => $self->_generate_type_coercion(
290 '$type_constraints[' . $index . ']',
295 push @source => $self->_generate_type_constraint_check(
297 '$type_constraint_bodies[' . $index . ']',
298 '$type_constraints[' . $index . ']',
302 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
307 return join "\n" => @source;
310 sub _generate_slot_assignment {
311 my ($self, $attr, $value, $index) = @_;
315 if ($attr->has_initializer) {
317 '$attrs->[' . $index . ']->set_initial_value($instance, ' . $value . ');'
322 $self->meta_instance->inline_set_slot_value(
324 ("'" . $attr->name . "'"),
330 my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
332 if ($is_moose && $attr->is_weak_ref) {
335 $self->meta_instance->inline_weaken_slot_value(
337 ("'" . $attr->name . "'")
339 ' if ref ' . $value . ';'
346 sub _generate_type_constraint_and_coercion {
347 my ($self, $attr, $index) = @_;
349 return unless $attr->has_type_constraint;
352 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
353 push @source => $self->_generate_type_coercion(
355 '$type_constraints[' . $index . ']',
360 push @source => $self->_generate_type_constraint_check(
362 ('$type_constraint_bodies[' . $index . ']'),
363 ('$type_constraints[' . $index . ']'),
369 sub _generate_type_coercion {
370 my ($self, $attr, $type_constraint_name, $value_name, $return_value_name) = @_;
371 return ($return_value_name . ' = ' . $type_constraint_name . '->coerce(' . $value_name . ');');
374 sub _generate_type_constraint_check {
375 my ($self, $attr, $type_constraint_cv, $type_constraint_obj, $value_name) = @_;
377 $self->_inline_throw_error('"Attribute (' # FIXME add 'dad'
379 . ') does not pass the type constraint because: " . '
380 . $type_constraint_obj . '->get_message(' . $value_name . ')')
381 . "\n\t unless " . $type_constraint_cv . '->(' . $value_name . ');'
385 sub _generate_default_value {
386 my ($self, $attr, $index) = @_;
388 # default values can either be CODE refs
389 # in which case we need to call them. Or
390 # they can be scalars (strings/numbers)
391 # in which case we can just deal with them
392 # in the code we eval.
393 if ($attr->is_default_a_coderef) {
394 return '$attrs->[' . $index . ']->default($instance)';
397 my $default = $attr->default;
398 # make sure to quote strings ...
412 Moose::Meta::Method::Constructor - Method Meta Object for constructors
416 This is a subclass of L<Class::MOP::Method> which handles
417 constructing an approprate Constructor methods. This is primarily
418 used in the making of immutable metaclasses, otherwise it is
419 not particularly useful.
429 =item B<meta_instance>
433 =item B<initialize_body>
435 =item B<associated_metaclass>
441 Stevan Little E<lt>stevan@iinteractive.comE<gt>
443 =head1 COPYRIGHT AND LICENSE
445 Copyright 2006-2008 by Infinity Interactive, Inc.
447 L<http://www.iinteractive.com>
449 This library is free software; you can redistribute it and/or modify
450 it under the same terms as Perl itself.