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 any of our parents have been made immutable, we are okay to
55 # inline our own method as long as the parent's constructor class
56 # is the same as $self.
57 for my $meta ( grep { $_->is_immutable }
58 map { ( ref $metaclass )->initialize($_) }
59 $metaclass->linearized_isa ) {
60 my $transformer = $meta->get_immutable_transformer;
62 my $constructor = $transformer->inlined_constructor
65 return ref $constructor eq ref $self;
68 if ( my $constructor = $metaclass->find_method_by_name( $self->name ) ) {
70 my $expected_class = $self->_expected_constructor_class;
72 if ( $constructor->body != $expected_class->can('new') ) {
73 my $class = $metaclass->name;
74 warn "Not inlining a constructor for $class since it is not"
75 . " inheriting the default $expected_class constructor\n";
84 # This would be a rather weird case where we have no constructor
85 # in the inheritance chain.
89 # This is here so can_be_inlined can be inherited by MooseX modules.
90 sub _expected_constructor_class {
91 return 'Moose::Object';
96 sub options { (shift)->{'options'} }
97 sub meta_instance { (shift)->{'meta_instance'} }
98 sub attributes { (shift)->{'attributes'} }
100 sub associated_metaclass { (shift)->{'associated_metaclass'} }
104 # this was changed in 0.41, but broke MooseX::Singleton, so try to catch
105 # any other code using the original broken spelling
106 sub intialize_body { Moose->throw_error("Please correct the spelling of 'intialize_body' to 'initialize_body'") }
108 sub initialize_body {
111 # the %options should also include a both
112 # a call 'initializer' and call 'SUPER::'
113 # options, which should cover approx 90%
114 # of the possible use cases (even if it
115 # requires some adaption on the part of
116 # the author, after all, nothing is free)
117 my $source = 'sub {';
118 $source .= "\n" . 'my $class = shift;';
120 $source .= "\n" . 'return $class->Moose::Object::new(@_)';
121 $source .= "\n" . ' if $class ne \'' . $self->associated_metaclass->name . '\';';
123 $source .= "\n" . 'my $params = ' . $self->_generate_BUILDARGS('$class', '@_');
125 $source .= ";\n" . 'my $instance = ' . $self->meta_instance->inline_create_instance('$class');
127 $source .= ";\n" . (join ";\n" => map {
128 $self->_generate_slot_initializer($_)
129 } 0 .. (@{$self->attributes} - 1));
131 $source .= ";\n" . $self->_generate_triggers();
132 $source .= ";\n" . $self->_generate_BUILDALL();
134 $source .= ";\n" . 'return $instance';
135 $source .= ";\n" . '}';
136 warn $source if $self->options->{debug};
140 my $meta = $self; # FIXME for _inline_throw_error...
143 # create the nessecary lexicals
144 # to be picked up in the eval
145 my $attrs = $self->attributes;
147 # We need to check if the attribute ->can('type_constraint')
148 # since we may be trying to immutabilize a Moose meta class,
149 # which in turn has attributes which are Class::MOP::Attribute
150 # objects, rather than Moose::Meta::Attribute. And
151 # Class::MOP::Attribute attributes have no type constraints.
152 # However we need to make sure we leave an undef value there
153 # because the inlined code is using the index of the attributes
154 # to determine where to find the type constraint
156 my @type_constraints = map {
157 $_->can('type_constraint') ? $_->type_constraint : undef
160 my @type_constraint_bodies = map {
161 defined $_ ? $_->_compiled_type_constraint : undef;
164 $code = eval $source;
165 $self->throw_error("Could not eval the constructor :\n\n$source\n\nbecause :\n\n$@", error => $@, data => $source ) if $@;
167 $self->{'body'} = $code;
170 sub _generate_BUILDARGS {
171 my ( $self, $class, $args ) = @_;
173 my $buildargs = $self->associated_metaclass->find_method_by_name("BUILDARGS");
175 if ( $args eq '@_' and ( !$buildargs or $buildargs->body == \&Moose::Object::BUILDARGS ) ) {
178 $self->_inline_throw_error('"Single parameters to new() must be a HASH ref"', 'data => $_[0]'),
179 ' if scalar @_ == 1 && defined $_[0] && ref($_[0]) ne q{HASH};',
180 '(scalar @_ == 1) ? {%{$_[0]}} : {@_};',
184 return $class . "->BUILDARGS($args)";
188 sub _generate_BUILDALL {
191 foreach my $method (reverse $self->associated_metaclass->find_all_methods_by_name('BUILD')) {
192 push @BUILD_calls => '$instance->' . $method->{class} . '::BUILD($params)';
194 return join ";\n" => @BUILD_calls;
197 sub _generate_triggers {
200 foreach my $i (0 .. $#{ $self->attributes }) {
201 my $attr = $self->attributes->[$i];
202 if ($attr->can('has_trigger') && $attr->has_trigger) {
203 if (defined(my $init_arg = $attr->init_arg)) {
204 push @trigger_calls => (
205 '(exists $params->{\'' . $init_arg . '\'}) && do {' . "\n "
206 . '$attrs->[' . $i . ']->trigger->('
208 . $self->meta_instance->inline_get_slot_value(
210 ("'" . $attr->name . "'")
213 . '$attrs->[' . $i . ']'
220 return join ";\n" => @trigger_calls;
223 sub _generate_slot_initializer {
227 my $attr = $self->attributes->[$index];
229 my @source = ('## ' . $attr->name);
231 my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
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 (' . $attr->name . ') is required"') .';');
238 if (($attr->has_default || $attr->has_builder) && !($is_moose && $attr->is_lazy)) {
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)
245 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
246 push @source => "} else {";
249 if ( $attr->has_default ) {
250 $default = $self->_generate_default_value($attr, $index);
253 my $builder = $attr->builder;
254 $default = '$instance->' . $builder;
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)
261 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
262 push @source => '}'; # close - wrap this to avoid my $val overrite warnings
264 push @source => "}" if defined $attr->init_arg;
266 elsif ( defined( my $init_arg = $attr->init_arg ) ) {
267 push @source => '(exists $params->{\'' . $init_arg . '\'}) && do {';
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(
274 '$type_constraints[' . $index . ']',
279 push @source => $self->_generate_type_constraint_check(
281 '$type_constraint_bodies[' . $index . ']',
282 '$type_constraints[' . $index . ']',
286 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
291 return join "\n" => @source;
294 sub _generate_slot_assignment {
295 my ($self, $attr, $value, $index) = @_;
299 if ($attr->has_initializer) {
301 '$attrs->[' . $index . ']->set_initial_value($instance, ' . $value . ');'
306 $self->meta_instance->inline_set_slot_value(
308 ("'" . $attr->name . "'"),
314 my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
316 if ($is_moose && $attr->is_weak_ref) {
319 $self->meta_instance->inline_weaken_slot_value(
321 ("'" . $attr->name . "'")
323 ' if ref ' . $value . ';'
330 sub _generate_type_constraint_and_coercion {
331 my ($self, $attr, $index) = @_;
333 return unless $attr->has_type_constraint;
336 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
337 push @source => $self->_generate_type_coercion(
339 '$type_constraints[' . $index . ']',
344 push @source => $self->_generate_type_constraint_check(
346 ('$type_constraint_bodies[' . $index . ']'),
347 ('$type_constraints[' . $index . ']'),
353 sub _generate_type_coercion {
354 my ($self, $attr, $type_constraint_name, $value_name, $return_value_name) = @_;
355 return ($return_value_name . ' = ' . $type_constraint_name . '->coerce(' . $value_name . ');');
358 sub _generate_type_constraint_check {
359 my ($self, $attr, $type_constraint_cv, $type_constraint_obj, $value_name) = @_;
361 $self->_inline_throw_error('"Attribute (' # FIXME add 'dad'
363 . ') does not pass the type constraint because: " . '
364 . $type_constraint_obj . '->get_message(' . $value_name . ')')
365 . "\n\t unless " . $type_constraint_cv . '->(' . $value_name . ');'
369 sub _generate_default_value {
370 my ($self, $attr, $index) = @_;
372 # default values can either be CODE refs
373 # in which case we need to call them. Or
374 # they can be scalars (strings/numbers)
375 # in which case we can just deal with them
376 # in the code we eval.
377 if ($attr->is_default_a_coderef) {
378 return '$attrs->[' . $index . ']->default($instance)';
381 my $default = $attr->default;
382 # make sure to quote strings ...
396 Moose::Meta::Method::Constructor - Method Meta Object for constructors
400 This is a subclass of L<Class::MOP::Method> which handles
401 constructing an approprate Constructor methods. This is primarily
402 used in the making of immutable metaclasses, otherwise it is
403 not particularly useful.
413 =item B<meta_instance>
417 =item B<initialize_body>
419 =item B<associated_metaclass>
425 Stevan Little E<lt>stevan@iinteractive.comE<gt>
427 =head1 COPYRIGHT AND LICENSE
429 Copyright 2006-2008 by Infinity Interactive, Inc.
431 L<http://www.iinteractive.com>
433 This library is free software; you can redistribute it and/or modify
434 it under the same terms as Perl itself.