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 if ( my $constructor = $metaclass->find_method_by_name( $self->name ) ) {
56 my $expected_class = $self->_expected_constructor_class;
58 if ( $constructor->body != $expected_class->can('new') ) {
59 my $class = $metaclass->name;
60 warn "Not inlining a constructor for $class since it is not"
61 . " inheriting the default $expected_class constructor\n";
70 # This would be a rather weird case where we have no constructor
71 # in the inheritance chain.
75 # This is here so can_be_inlined can be inherited by MooseX modules.
76 sub _expected_constructor_class {
77 return 'Moose::Object';
82 sub options { (shift)->{'options'} }
83 sub meta_instance { (shift)->{'meta_instance'} }
84 sub attributes { (shift)->{'attributes'} }
86 sub associated_metaclass { (shift)->{'associated_metaclass'} }
90 # this was changed in 0.41, but broke MooseX::Singleton, so try to catch
91 # any other code using the original broken spelling
92 sub intialize_body { Moose->throw_error("Please correct the spelling of 'intialize_body' to 'initialize_body'") }
97 # the %options should also include a both
98 # a call 'initializer' and call 'SUPER::'
99 # options, which should cover approx 90%
100 # of the possible use cases (even if it
101 # requires some adaption on the part of
102 # the author, after all, nothing is free)
103 my $source = 'sub {';
104 $source .= "\n" . 'my $class = shift;';
106 $source .= "\n" . 'return $class->Moose::Object::new(@_)';
107 $source .= "\n" . ' if $class ne \'' . $self->associated_metaclass->name . '\';';
109 $source .= "\n" . 'my $params = ' . $self->_generate_BUILDARGS('$class', '@_');
111 $source .= ";\n" . 'my $instance = ' . $self->meta_instance->inline_create_instance('$class');
113 $source .= ";\n" . (join ";\n" => map {
114 $self->_generate_slot_initializer($_)
115 } 0 .. (@{$self->attributes} - 1));
117 $source .= ";\n" . $self->_generate_triggers();
118 $source .= ";\n" . $self->_generate_BUILDALL();
120 $source .= ";\n" . 'return $instance';
121 $source .= ";\n" . '}';
122 warn $source if $self->options->{debug};
126 my $meta = $self; # FIXME for _inline_throw_error...
129 # create the nessecary lexicals
130 # to be picked up in the eval
131 my $attrs = $self->attributes;
133 # We need to check if the attribute ->can('type_constraint')
134 # since we may be trying to immutabilize a Moose meta class,
135 # which in turn has attributes which are Class::MOP::Attribute
136 # objects, rather than Moose::Meta::Attribute. And
137 # Class::MOP::Attribute attributes have no type constraints.
138 # However we need to make sure we leave an undef value there
139 # because the inlined code is using the index of the attributes
140 # to determine where to find the type constraint
142 my @type_constraints = map {
143 $_->can('type_constraint') ? $_->type_constraint : undef
146 my @type_constraint_bodies = map {
147 defined $_ ? $_->_compiled_type_constraint : undef;
150 $code = eval $source;
151 $self->throw_error("Could not eval the constructor :\n\n$source\n\nbecause :\n\n$@", error => $@, data => $source ) if $@;
153 $self->{'body'} = $code;
156 sub _generate_BUILDARGS {
157 my ( $self, $class, $args ) = @_;
159 my $buildargs = $self->associated_metaclass->find_method_by_name("BUILDARGS");
161 if ( $args eq '@_' and ( !$buildargs or $buildargs->body == \&Moose::Object::BUILDARGS ) ) {
164 $self->_inline_throw_error('"Single parameters to new() must be a HASH ref"', 'data => $_[0]'),
165 ' if scalar @_ == 1 && defined $_[0] && ref($_[0]) ne q{HASH};',
166 '(scalar @_ == 1) ? {%{$_[0]}} : {@_};',
170 return $class . "->BUILDARGS($args)";
174 sub _generate_BUILDALL {
177 foreach my $method (reverse $self->associated_metaclass->find_all_methods_by_name('BUILD')) {
178 push @BUILD_calls => '$instance->' . $method->{class} . '::BUILD($params)';
180 return join ";\n" => @BUILD_calls;
183 sub _generate_triggers {
186 foreach my $i (0 .. $#{ $self->attributes }) {
187 my $attr = $self->attributes->[$i];
188 if ($attr->can('has_trigger') && $attr->has_trigger) {
189 if (defined(my $init_arg = $attr->init_arg)) {
190 push @trigger_calls => (
191 '(exists $params->{\'' . $init_arg . '\'}) && do {' . "\n "
192 . '$attrs->[' . $i . ']->trigger->('
194 . $self->meta_instance->inline_get_slot_value(
196 ("'" . $attr->name . "'")
199 . '$attrs->[' . $i . ']'
206 return join ";\n" => @trigger_calls;
209 sub _generate_slot_initializer {
213 my $attr = $self->attributes->[$index];
215 my @source = ('## ' . $attr->name);
217 my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
219 if ($is_moose && defined($attr->init_arg) && $attr->is_required && !$attr->has_default && !$attr->has_builder) {
220 push @source => ('(exists $params->{\'' . $attr->init_arg . '\'}) ' .
221 '|| ' . $self->_inline_throw_error('"Attribute (' . $attr->name . ') is required"') .';');
224 if (($attr->has_default || $attr->has_builder) && !($is_moose && $attr->is_lazy)) {
226 if ( defined( my $init_arg = $attr->init_arg ) ) {
227 push @source => 'if (exists $params->{\'' . $init_arg . '\'}) {';
228 push @source => ('my $val = $params->{\'' . $init_arg . '\'};');
229 push @source => $self->_generate_type_constraint_and_coercion($attr, $index)
231 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
232 push @source => "} else {";
235 if ( $attr->has_default ) {
236 $default = $self->_generate_default_value($attr, $index);
239 my $builder = $attr->builder;
240 $default = '$instance->' . $builder;
243 push @source => '{'; # wrap this to avoid my $val overwrite warnings
244 push @source => ('my $val = ' . $default . ';');
245 push @source => $self->_generate_type_constraint_and_coercion($attr, $index)
247 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
248 push @source => '}'; # close - wrap this to avoid my $val overrite warnings
250 push @source => "}" if defined $attr->init_arg;
252 elsif ( defined( my $init_arg = $attr->init_arg ) ) {
253 push @source => '(exists $params->{\'' . $init_arg . '\'}) && do {';
255 push @source => ('my $val = $params->{\'' . $init_arg . '\'};');
256 if ($is_moose && $attr->has_type_constraint) {
257 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
258 push @source => $self->_generate_type_coercion(
260 '$type_constraints[' . $index . ']',
265 push @source => $self->_generate_type_constraint_check(
267 '$type_constraint_bodies[' . $index . ']',
268 '$type_constraints[' . $index . ']',
272 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
277 return join "\n" => @source;
280 sub _generate_slot_assignment {
281 my ($self, $attr, $value, $index) = @_;
285 if ($attr->has_initializer) {
287 '$attrs->[' . $index . ']->set_initial_value($instance, ' . $value . ');'
292 $self->meta_instance->inline_set_slot_value(
294 ("'" . $attr->name . "'"),
300 my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
302 if ($is_moose && $attr->is_weak_ref) {
305 $self->meta_instance->inline_weaken_slot_value(
307 ("'" . $attr->name . "'")
309 ' if ref ' . $value . ';'
316 sub _generate_type_constraint_and_coercion {
317 my ($self, $attr, $index) = @_;
319 return unless $attr->has_type_constraint;
322 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
323 push @source => $self->_generate_type_coercion(
325 '$type_constraints[' . $index . ']',
330 push @source => $self->_generate_type_constraint_check(
332 ('$type_constraint_bodies[' . $index . ']'),
333 ('$type_constraints[' . $index . ']'),
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 . ');');
344 sub _generate_type_constraint_check {
345 my ($self, $attr, $type_constraint_cv, $type_constraint_obj, $value_name) = @_;
347 $self->_inline_throw_error('"Attribute (' # FIXME add 'dad'
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 . ');'
355 sub _generate_default_value {
356 my ($self, $attr, $index) = @_;
358 # default values can either be CODE refs
359 # in which case we need to call them. Or
360 # they can be scalars (strings/numbers)
361 # in which case we can just deal with them
362 # in the code we eval.
363 if ($attr->is_default_a_coderef) {
364 return '$attrs->[' . $index . ']->default($instance)';
367 my $default = $attr->default;
368 # make sure to quote strings ...
382 Moose::Meta::Method::Constructor - Method Meta Object for constructors
386 This is a subclass of L<Class::MOP::Method> which handles
387 constructing an approprate Constructor methods. This is primarily
388 used in the making of immutable metaclasses, otherwise it is
389 not particularly useful.
399 =item B<meta_instance>
403 =item B<initialize_body>
405 =item B<associated_metaclass>
411 Stevan Little E<lt>stevan@iinteractive.comE<gt>
413 =head1 COPYRIGHT AND LICENSE
415 Copyright 2006-2008 by Infinity Interactive, Inc.
417 L<http://www.iinteractive.com>
419 This library is free software; you can redistribute it and/or modify
420 it under the same terms as Perl itself.