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 inheriting the default $expected_class constructor\n";
69 # This would be a rather weird case where we have no constructor
70 # in the inheritance chain.
74 # This is here so can_be_inlined can be inherited by MooseX modules.
75 sub _expected_constructor_class {
76 return 'Moose::Object';
81 sub options { (shift)->{'options'} }
82 sub meta_instance { (shift)->{'meta_instance'} }
83 sub attributes { (shift)->{'attributes'} }
85 sub associated_metaclass { (shift)->{'associated_metaclass'} }
89 # this was changed in 0.41, but broke MooseX::Singleton, so try to catch
90 # any other code using the original broken spelling
91 sub intialize_body { Moose->throw_error("Please correct the spelling of 'intialize_body' to 'initialize_body'") }
96 # the %options should also include a both
97 # a call 'initializer' and call 'SUPER::'
98 # options, which should cover approx 90%
99 # of the possible use cases (even if it
100 # requires some adaption on the part of
101 # the author, after all, nothing is free)
102 my $source = 'sub {';
103 $source .= "\n" . 'my $class = shift;';
105 $source .= "\n" . 'return $class->Moose::Object::new(@_)';
106 $source .= "\n" . ' if $class ne \'' . $self->associated_metaclass->name . '\';';
108 $source .= "\n" . 'my $params = ' . $self->_generate_BUILDARGS('$class', '@_');
110 $source .= ";\n" . 'my $instance = ' . $self->meta_instance->inline_create_instance('$class');
112 $source .= ";\n" . (join ";\n" => map {
113 $self->_generate_slot_initializer($_)
114 } 0 .. (@{$self->attributes} - 1));
116 $source .= ";\n" . $self->_generate_triggers();
117 $source .= ";\n" . $self->_generate_BUILDALL();
119 $source .= ";\n" . 'return $instance';
120 $source .= ";\n" . '}';
121 warn $source if $self->options->{debug};
125 my $meta = $self; # FIXME for _inline_throw_error...
128 # create the nessecary lexicals
129 # to be picked up in the eval
130 my $attrs = $self->attributes;
132 # We need to check if the attribute ->can('type_constraint')
133 # since we may be trying to immutabilize a Moose meta class,
134 # which in turn has attributes which are Class::MOP::Attribute
135 # objects, rather than Moose::Meta::Attribute. And
136 # Class::MOP::Attribute attributes have no type constraints.
137 # However we need to make sure we leave an undef value there
138 # because the inlined code is using the index of the attributes
139 # to determine where to find the type constraint
141 my @type_constraints = map {
142 $_->can('type_constraint') ? $_->type_constraint : undef
145 my @type_constraint_bodies = map {
146 defined $_ ? $_->_compiled_type_constraint : undef;
149 $code = eval $source;
150 $self->throw_error("Could not eval the constructor :\n\n$source\n\nbecause :\n\n$@", error => $@, data => $source ) if $@;
152 $self->{'body'} = $code;
155 sub _generate_BUILDARGS {
156 my ( $self, $class, $args ) = @_;
158 my $buildargs = $self->associated_metaclass->find_method_by_name("BUILDARGS");
160 if ( $args eq '@_' and ( !$buildargs or $buildargs->body == \&Moose::Object::BUILDARGS ) ) {
163 $self->_inline_throw_error('"Single parameters to new() must be a HASH ref"', 'data => $_[0]'),
164 ' if scalar @_ == 1 && defined $_[0] && ref($_[0]) ne q{HASH};',
165 '(scalar @_ == 1) ? {%{$_[0]}} : {@_};',
169 return $class . "->BUILDARGS($args)";
173 sub _generate_BUILDALL {
176 foreach my $method (reverse $self->associated_metaclass->find_all_methods_by_name('BUILD')) {
177 push @BUILD_calls => '$instance->' . $method->{class} . '::BUILD($params)';
179 return join ";\n" => @BUILD_calls;
182 sub _generate_triggers {
185 foreach my $i (0 .. $#{ $self->attributes }) {
186 my $attr = $self->attributes->[$i];
187 if ($attr->can('has_trigger') && $attr->has_trigger) {
188 if (defined(my $init_arg = $attr->init_arg)) {
189 push @trigger_calls => (
190 '(exists $params->{\'' . $init_arg . '\'}) && do {' . "\n "
191 . '$attrs->[' . $i . ']->trigger->('
193 . $self->meta_instance->inline_get_slot_value(
195 ("'" . $attr->name . "'")
198 . '$attrs->[' . $i . ']'
205 return join ";\n" => @trigger_calls;
208 sub _generate_slot_initializer {
212 my $attr = $self->attributes->[$index];
214 my @source = ('## ' . $attr->name);
216 my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
218 if ($is_moose && defined($attr->init_arg) && $attr->is_required && !$attr->has_default && !$attr->has_builder) {
219 push @source => ('(exists $params->{\'' . $attr->init_arg . '\'}) ' .
220 '|| ' . $self->_inline_throw_error('"Attribute (' . $attr->name . ') is required"') .';');
223 if (($attr->has_default || $attr->has_builder) && !($is_moose && $attr->is_lazy)) {
225 if ( defined( my $init_arg = $attr->init_arg ) ) {
226 push @source => 'if (exists $params->{\'' . $init_arg . '\'}) {';
227 push @source => ('my $val = $params->{\'' . $init_arg . '\'};');
228 push @source => $self->_generate_type_constraint_and_coercion($attr, $index)
230 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
231 push @source => "} else {";
234 if ( $attr->has_default ) {
235 $default = $self->_generate_default_value($attr, $index);
238 my $builder = $attr->builder;
239 $default = '$instance->' . $builder;
242 push @source => '{'; # wrap this to avoid my $val overwrite warnings
243 push @source => ('my $val = ' . $default . ';');
244 push @source => $self->_generate_type_constraint_and_coercion($attr, $index)
246 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
247 push @source => '}'; # close - wrap this to avoid my $val overrite warnings
249 push @source => "}" if defined $attr->init_arg;
251 elsif ( defined( my $init_arg = $attr->init_arg ) ) {
252 push @source => '(exists $params->{\'' . $init_arg . '\'}) && do {';
254 push @source => ('my $val = $params->{\'' . $init_arg . '\'};');
255 if ($is_moose && $attr->has_type_constraint) {
256 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
257 push @source => $self->_generate_type_coercion(
259 '$type_constraints[' . $index . ']',
264 push @source => $self->_generate_type_constraint_check(
266 '$type_constraint_bodies[' . $index . ']',
267 '$type_constraints[' . $index . ']',
271 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
276 return join "\n" => @source;
279 sub _generate_slot_assignment {
280 my ($self, $attr, $value, $index) = @_;
284 if ($attr->has_initializer) {
286 '$attrs->[' . $index . ']->set_initial_value($instance, ' . $value . ');'
291 $self->meta_instance->inline_set_slot_value(
293 ("'" . $attr->name . "'"),
299 my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
301 if ($is_moose && $attr->is_weak_ref) {
304 $self->meta_instance->inline_weaken_slot_value(
306 ("'" . $attr->name . "'")
308 ' if ref ' . $value . ';'
315 sub _generate_type_constraint_and_coercion {
316 my ($self, $attr, $index) = @_;
318 return unless $attr->has_type_constraint;
321 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
322 push @source => $self->_generate_type_coercion(
324 '$type_constraints[' . $index . ']',
329 push @source => $self->_generate_type_constraint_check(
331 ('$type_constraint_bodies[' . $index . ']'),
332 ('$type_constraints[' . $index . ']'),
338 sub _generate_type_coercion {
339 my ($self, $attr, $type_constraint_name, $value_name, $return_value_name) = @_;
340 return ($return_value_name . ' = ' . $type_constraint_name . '->coerce(' . $value_name . ');');
343 sub _generate_type_constraint_check {
344 my ($self, $attr, $type_constraint_cv, $type_constraint_obj, $value_name) = @_;
346 $self->_inline_throw_error('"Attribute (' # FIXME add 'dad'
348 . ') does not pass the type constraint because: " . '
349 . $type_constraint_obj . '->get_message(' . $value_name . ')')
350 . "\n\t unless " . $type_constraint_cv . '->(' . $value_name . ');'
354 sub _generate_default_value {
355 my ($self, $attr, $index) = @_;
357 # default values can either be CODE refs
358 # in which case we need to call them. Or
359 # they can be scalars (strings/numbers)
360 # in which case we can just deal with them
361 # in the code we eval.
362 if ($attr->is_default_a_coderef) {
363 return '$attrs->[' . $index . ']->default($instance)';
366 my $default = $attr->default;
367 # make sure to quote strings ...
381 Moose::Meta::Method::Constructor - Method Meta Object for constructors
385 This is a subclass of L<Class::MOP::Method> which handles
386 constructing an approprate Constructor methods. This is primarily
387 used in the making of immutable metaclasses, otherwise it is
388 not particularly useful.
398 =item B<meta_instance>
402 =item B<initialize_body>
404 =item B<associated_metaclass>
410 Stevan Little E<lt>stevan@iinteractive.comE<gt>
412 =head1 COPYRIGHT AND LICENSE
414 Copyright 2006-2008 by Infinity Interactive, Inc.
416 L<http://www.iinteractive.com>
418 This library is free software; you can redistribute it and/or modify
419 it under the same terms as Perl itself.