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 new method. The assumption is that an inlined new
56 # method provided by a parent does not actually get used by
59 grep { $_->is_immutable }
60 map { ( ref $metaclass )->initialize($_) }
61 $metaclass->linearized_isa
63 my $transformer = $meta->get_immutable_transformer;
65 return 1 if $transformer->inlined_constructor;
68 if ( my $constructor = $metaclass->find_method_by_name( $self->name ) ) {
69 my $class = $self->associated_metaclass->name;
70 my $expected_class = $self->_expected_constructor_class;
72 if ( $constructor->body != $expected_class->can('new') ) {
73 warn "Not inlining a constructor for $class since it is not"
74 . " inheriting the default $expected_class constructor\n";
83 # This would be a rather weird case where we have no constructor
84 # in the inheritance chain.
88 # This is here so can_be_inlined can be inherited by MooseX modules.
89 sub _expected_constructor_class {
90 return 'Moose::Object';
95 sub options { (shift)->{'options'} }
96 sub meta_instance { (shift)->{'meta_instance'} }
97 sub attributes { (shift)->{'attributes'} }
99 sub associated_metaclass { (shift)->{'associated_metaclass'} }
103 # this was changed in 0.41, but broke MooseX::Singleton, so try to catch
104 # any other code using the original broken spelling
105 sub intialize_body { Moose->throw_error("Please correct the spelling of 'intialize_body' to 'initialize_body'") }
107 sub initialize_body {
110 # the %options should also include a both
111 # a call 'initializer' and call 'SUPER::'
112 # options, which should cover approx 90%
113 # of the possible use cases (even if it
114 # requires some adaption on the part of
115 # the author, after all, nothing is free)
116 my $source = 'sub {';
117 $source .= "\n" . 'my $class = shift;';
119 $source .= "\n" . 'return $class->Moose::Object::new(@_)';
120 $source .= "\n" . ' if $class ne \'' . $self->associated_metaclass->name . '\';';
122 $source .= "\n" . 'my $params = ' . $self->_generate_BUILDARGS('$class', '@_');
124 $source .= ";\n" . 'my $instance = ' . $self->meta_instance->inline_create_instance('$class');
126 $source .= ";\n" . (join ";\n" => map {
127 $self->_generate_slot_initializer($_)
128 } 0 .. (@{$self->attributes} - 1));
130 $source .= ";\n" . $self->_generate_triggers();
131 $source .= ";\n" . $self->_generate_BUILDALL();
133 $source .= ";\n" . 'return $instance';
134 $source .= ";\n" . '}';
135 warn $source if $self->options->{debug};
139 my $meta = $self; # FIXME for _inline_throw_error...
142 # create the nessecary lexicals
143 # to be picked up in the eval
144 my $attrs = $self->attributes;
146 # We need to check if the attribute ->can('type_constraint')
147 # since we may be trying to immutabilize a Moose meta class,
148 # which in turn has attributes which are Class::MOP::Attribute
149 # objects, rather than Moose::Meta::Attribute. And
150 # Class::MOP::Attribute attributes have no type constraints.
151 # However we need to make sure we leave an undef value there
152 # because the inlined code is using the index of the attributes
153 # to determine where to find the type constraint
155 my @type_constraints = map {
156 $_->can('type_constraint') ? $_->type_constraint : undef
159 my @type_constraint_bodies = map {
160 defined $_ ? $_->_compiled_type_constraint : undef;
163 $code = eval $source;
164 $self->throw_error("Could not eval the constructor :\n\n$source\n\nbecause :\n\n$@", error => $@, data => $source ) if $@;
166 $self->{'body'} = $code;
169 sub _generate_BUILDARGS {
170 my ( $self, $class, $args ) = @_;
172 my $buildargs = $self->associated_metaclass->find_method_by_name("BUILDARGS");
174 if ( $args eq '@_' and ( !$buildargs or $buildargs->body == \&Moose::Object::BUILDARGS ) ) {
177 $self->_inline_throw_error('"Single parameters to new() must be a HASH ref"', 'data => $_[0]'),
178 ' if scalar @_ == 1 && defined $_[0] && ref($_[0]) ne q{HASH};',
179 '(scalar @_ == 1) ? {%{$_[0]}} : {@_};',
183 return $class . "->BUILDARGS($args)";
187 sub _generate_BUILDALL {
190 foreach my $method (reverse $self->associated_metaclass->find_all_methods_by_name('BUILD')) {
191 push @BUILD_calls => '$instance->' . $method->{class} . '::BUILD($params)';
193 return join ";\n" => @BUILD_calls;
196 sub _generate_triggers {
199 foreach my $i (0 .. $#{ $self->attributes }) {
200 my $attr = $self->attributes->[$i];
201 if ($attr->can('has_trigger') && $attr->has_trigger) {
202 if (defined(my $init_arg = $attr->init_arg)) {
203 push @trigger_calls => (
204 '(exists $params->{\'' . $init_arg . '\'}) && do {' . "\n "
205 . '$attrs->[' . $i . ']->trigger->('
207 . $self->meta_instance->inline_get_slot_value(
209 ("'" . $attr->name . "'")
212 . '$attrs->[' . $i . ']'
219 return join ";\n" => @trigger_calls;
222 sub _generate_slot_initializer {
226 my $attr = $self->attributes->[$index];
228 my @source = ('## ' . $attr->name);
230 my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
232 if ($is_moose && defined($attr->init_arg) && $attr->is_required && !$attr->has_default && !$attr->has_builder) {
233 push @source => ('(exists $params->{\'' . $attr->init_arg . '\'}) ' .
234 '|| ' . $self->_inline_throw_error('"Attribute (' . $attr->name . ') is required"') .';');
237 if (($attr->has_default || $attr->has_builder) && !($is_moose && $attr->is_lazy)) {
239 if ( defined( my $init_arg = $attr->init_arg ) ) {
240 push @source => 'if (exists $params->{\'' . $init_arg . '\'}) {';
241 push @source => ('my $val = $params->{\'' . $init_arg . '\'};');
242 push @source => $self->_generate_type_constraint_and_coercion($attr, $index)
244 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
245 push @source => "} else {";
248 if ( $attr->has_default ) {
249 $default = $self->_generate_default_value($attr, $index);
252 my $builder = $attr->builder;
253 $default = '$instance->' . $builder;
256 push @source => '{'; # wrap this to avoid my $val overwrite warnings
257 push @source => ('my $val = ' . $default . ';');
258 push @source => $self->_generate_type_constraint_and_coercion($attr, $index)
260 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
261 push @source => '}'; # close - wrap this to avoid my $val overrite warnings
263 push @source => "}" if defined $attr->init_arg;
265 elsif ( defined( my $init_arg = $attr->init_arg ) ) {
266 push @source => '(exists $params->{\'' . $init_arg . '\'}) && do {';
268 push @source => ('my $val = $params->{\'' . $init_arg . '\'};');
269 if ($is_moose && $attr->has_type_constraint) {
270 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
271 push @source => $self->_generate_type_coercion(
273 '$type_constraints[' . $index . ']',
278 push @source => $self->_generate_type_constraint_check(
280 '$type_constraint_bodies[' . $index . ']',
281 '$type_constraints[' . $index . ']',
285 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
290 return join "\n" => @source;
293 sub _generate_slot_assignment {
294 my ($self, $attr, $value, $index) = @_;
298 if ($attr->has_initializer) {
300 '$attrs->[' . $index . ']->set_initial_value($instance, ' . $value . ');'
305 $self->meta_instance->inline_set_slot_value(
307 ("'" . $attr->name . "'"),
313 my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
315 if ($is_moose && $attr->is_weak_ref) {
318 $self->meta_instance->inline_weaken_slot_value(
320 ("'" . $attr->name . "'")
322 ' if ref ' . $value . ';'
329 sub _generate_type_constraint_and_coercion {
330 my ($self, $attr, $index) = @_;
332 return unless $attr->has_type_constraint;
335 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
336 push @source => $self->_generate_type_coercion(
338 '$type_constraints[' . $index . ']',
343 push @source => $self->_generate_type_constraint_check(
345 ('$type_constraint_bodies[' . $index . ']'),
346 ('$type_constraints[' . $index . ']'),
352 sub _generate_type_coercion {
353 my ($self, $attr, $type_constraint_name, $value_name, $return_value_name) = @_;
354 return ($return_value_name . ' = ' . $type_constraint_name . '->coerce(' . $value_name . ');');
357 sub _generate_type_constraint_check {
358 my ($self, $attr, $type_constraint_cv, $type_constraint_obj, $value_name) = @_;
360 $self->_inline_throw_error('"Attribute (' # FIXME add 'dad'
362 . ') does not pass the type constraint because: " . '
363 . $type_constraint_obj . '->get_message(' . $value_name . ')')
364 . "\n\t unless " . $type_constraint_cv . '->(' . $value_name . ');'
368 sub _generate_default_value {
369 my ($self, $attr, $index) = @_;
371 # default values can either be CODE refs
372 # in which case we need to call them. Or
373 # they can be scalars (strings/numbers)
374 # in which case we can just deal with them
375 # in the code we eval.
376 if ($attr->is_default_a_coderef) {
377 return '$attrs->[' . $index . ']->default($instance)';
380 my $default = $attr->default;
381 # make sure to quote strings ...
395 Moose::Meta::Method::Constructor - Method Meta Object for constructors
399 This is a subclass of L<Class::MOP::Method> which handles
400 constructing an approprate Constructor methods. This is primarily
401 used in the making of immutable metaclasses, otherwise it is
402 not particularly useful.
412 =item B<meta_instance>
416 =item B<initialize_body>
418 =item B<associated_metaclass>
424 Stevan Little E<lt>stevan@iinteractive.comE<gt>
426 =head1 COPYRIGHT AND LICENSE
428 Copyright 2006-2008 by Infinity Interactive, Inc.
430 L<http://www.iinteractive.com>
432 This library is free software; you can redistribute it and/or modify
433 it under the same terms as Perl itself.