2 package Moose::Meta::Method::Constructor;
7 use Scalar::Util 'blessed', 'weaken', 'looks_like_number';
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 $expected_class = $self->_expected_constructor_class;
56 # If any of our parents have been made immutable, we are okay to
57 # inline our own new method. The assumption is that an inlined new
58 # method provided by a parent does not actually get used by
61 grep { $_->is_immutable }
62 map { ( ref $metaclass )->initialize($_) }
63 grep { $_ ne $expected_class }
64 $metaclass->linearized_isa
66 my $transformer = $meta->get_immutable_transformer;
68 # This is actually a false positive if we're in a subclass of
69 # this class, _and_ the expected class is not overridden (but
70 # should be), and the real expected class is actually
71 # immutable itself (see Fey::Object::Table for an example of
72 # how this can happen). I'm not sure how to actually handle
73 # that case, since it's effectively a bug in the subclass (for
74 # not overriding _expected_constructor_class).
75 return 1 if $transformer->inlined_constructor;
78 if ( my $constructor = $metaclass->find_method_by_name( $self->name ) ) {
79 my $class = $self->associated_metaclass->name;
81 if ( $constructor->body != $expected_class->can('new') ) {
83 = "Not inlining a constructor for $class since it is not"
84 . " inheriting the default $expected_class constructor\n";
86 $warning .= " (constructor has method modifiers which would be lost if it were inlined)\n"
87 if $constructor->isa('Class::MOP::Method::Wrapped');
98 # This would be a rather weird case where we have no constructor
99 # in the inheritance chain.
103 # This is here so can_be_inlined can be inherited by MooseX modules.
104 sub _expected_constructor_class {
105 return 'Moose::Object';
110 sub options { (shift)->{'options'} }
111 sub meta_instance { (shift)->{'meta_instance'} }
112 sub attributes { (shift)->{'attributes'} }
114 sub associated_metaclass { (shift)->{'associated_metaclass'} }
118 # this was changed in 0.41, but broke MooseX::Singleton, so try to catch
119 # any other code using the original broken spelling
120 sub intialize_body { Moose->throw_error("Please correct the spelling of 'intialize_body' to 'initialize_body'") }
122 sub initialize_body {
125 # the %options should also include a both
126 # a call 'initializer' and call 'SUPER::'
127 # options, which should cover approx 90%
128 # of the possible use cases (even if it
129 # requires some adaption on the part of
130 # the author, after all, nothing is free)
131 my $source = 'sub {';
132 $source .= "\n" . 'my $class = shift;';
134 $source .= "\n" . 'return $class->Moose::Object::new(@_)';
135 $source .= "\n" . ' if $class ne \'' . $self->associated_metaclass->name . '\';';
137 $source .= "\n" . 'my $params = ' . $self->_generate_BUILDARGS('$class', '@_');
139 $source .= ";\n" . 'my $instance = ' . $self->meta_instance->inline_create_instance('$class');
141 $source .= ";\n" . (join ";\n" => map {
142 $self->_generate_slot_initializer($_)
143 } 0 .. (@{$self->attributes} - 1));
145 $source .= ";\n" . $self->_generate_triggers();
146 $source .= ";\n" . $self->_generate_BUILDALL();
148 $source .= ";\n" . 'return $instance';
149 $source .= ";\n" . '}';
150 warn $source if $self->options->{debug};
153 my $attrs = $self->attributes;
154 my @type_constraints = map {
155 $_->can('type_constraint') ? $_->type_constraint : undef
159 # lexicals for the scope within which we will be constructed
161 '$meta' => \$self, # FIXME for _inline_throw_error...
164 # We need to check if the attribute ->can('type_constraint')
165 # since we may be trying to immutabilize a Moose meta class,
166 # which in turn has attributes which are Class::MOP::Attribute
167 # objects, rather than Moose::Meta::Attribute. And
168 # Class::MOP::Attribute attributes have no type constraints.
169 # However we need to make sure we leave an undef value there
170 # because the inlined code is using the index of the attributes
171 # to determine where to find the type constraint
173 '@type_constraints' => \@type_constraints,
175 '@type_constraint_bodies' => [ map {
176 defined $_ ? $_->_compiled_type_constraint : undef;
177 } @type_constraints ]
179 $code = $self->_eval_closure($environment, $source);
180 $self->throw_error("Could not eval the constructor :\n\n$source\n\nbecause :\n\n$@", error => $@, data => $source ) if $@;
181 $self->{'body'} = $code;
184 sub _generate_BUILDARGS {
185 my ( $self, $class, $args ) = @_;
187 my $buildargs = $self->associated_metaclass->find_method_by_name("BUILDARGS");
189 if ( $args eq '@_' and ( !$buildargs or $buildargs->body == \&Moose::Object::BUILDARGS ) ) {
192 $self->_inline_throw_error('"Single parameters to new() must be a HASH ref"', 'data => $_[0]'),
193 ' if scalar @_ == 1 && defined $_[0] && ref($_[0]) ne q{HASH};',
194 '(scalar @_ == 1) ? {%{$_[0]}} : {@_};',
198 return $class . "->BUILDARGS($args)";
202 sub _generate_BUILDALL {
205 foreach my $method (reverse $self->associated_metaclass->find_all_methods_by_name('BUILD')) {
206 push @BUILD_calls => '$instance->' . $method->{class} . '::BUILD($params)';
208 return join ";\n" => @BUILD_calls;
211 sub _generate_triggers {
214 foreach my $i (0 .. $#{ $self->attributes }) {
215 my $attr = $self->attributes->[$i];
216 if ($attr->can('has_trigger') && $attr->has_trigger) {
217 if (defined(my $init_arg = $attr->init_arg)) {
218 push @trigger_calls => (
219 '(exists $params->{\'' . $init_arg . '\'}) && do {' . "\n "
220 . '$attrs->[' . $i . ']->trigger->('
222 . $self->meta_instance->inline_get_slot_value(
224 ("'" . $attr->name . "'")
232 return join ";\n" => @trigger_calls;
235 sub _generate_slot_initializer {
239 my $attr = $self->attributes->[$index];
241 my @source = ('## ' . $attr->name);
243 my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
245 if ($is_moose && defined($attr->init_arg) && $attr->is_required && !$attr->has_default && !$attr->has_builder) {
246 push @source => ('(exists $params->{\'' . $attr->init_arg . '\'}) ' .
247 '|| ' . $self->_inline_throw_error('"Attribute (' . $attr->name . ') is required"') .';');
250 if (($attr->has_default || $attr->has_builder) && !($is_moose && $attr->is_lazy)) {
252 if ( defined( my $init_arg = $attr->init_arg ) ) {
253 push @source => 'if (exists $params->{\'' . $init_arg . '\'}) {';
254 push @source => ('my $val = $params->{\'' . $init_arg . '\'};');
255 push @source => $self->_generate_type_constraint_and_coercion($attr, $index)
257 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
258 push @source => "} else {";
261 if ( $attr->has_default ) {
262 $default = $self->_generate_default_value($attr, $index);
265 my $builder = $attr->builder;
266 $default = '$instance->' . $builder;
269 push @source => '{'; # wrap this to avoid my $val overwrite warnings
270 push @source => ('my $val = ' . $default . ';');
271 push @source => $self->_generate_type_constraint_and_coercion($attr, $index)
273 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
274 push @source => '}'; # close - wrap this to avoid my $val overrite warnings
276 push @source => "}" if defined $attr->init_arg;
278 elsif ( defined( my $init_arg = $attr->init_arg ) ) {
279 push @source => '(exists $params->{\'' . $init_arg . '\'}) && do {';
281 push @source => ('my $val = $params->{\'' . $init_arg . '\'};');
282 if ($is_moose && $attr->has_type_constraint) {
283 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
284 push @source => $self->_generate_type_coercion(
286 '$type_constraints[' . $index . ']',
291 push @source => $self->_generate_type_constraint_check(
293 '$type_constraint_bodies[' . $index . ']',
294 '$type_constraints[' . $index . ']',
298 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
303 return join "\n" => @source;
306 sub _generate_slot_assignment {
307 my ($self, $attr, $value, $index) = @_;
311 if ($attr->has_initializer) {
313 '$attrs->[' . $index . ']->set_initial_value($instance, ' . $value . ');'
318 $self->meta_instance->inline_set_slot_value(
320 ("'" . $attr->name . "'"),
326 my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
328 if ($is_moose && $attr->is_weak_ref) {
331 $self->meta_instance->inline_weaken_slot_value(
333 ("'" . $attr->name . "'")
335 ' if ref ' . $value . ';'
342 sub _generate_type_constraint_and_coercion {
343 my ($self, $attr, $index) = @_;
345 return unless $attr->has_type_constraint;
348 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
349 push @source => $self->_generate_type_coercion(
351 '$type_constraints[' . $index . ']',
356 push @source => $self->_generate_type_constraint_check(
358 ('$type_constraint_bodies[' . $index . ']'),
359 ('$type_constraints[' . $index . ']'),
365 sub _generate_type_coercion {
366 my ($self, $attr, $type_constraint_name, $value_name, $return_value_name) = @_;
367 return ($return_value_name . ' = ' . $type_constraint_name . '->coerce(' . $value_name . ');');
370 sub _generate_type_constraint_check {
371 my ($self, $attr, $type_constraint_cv, $type_constraint_obj, $value_name) = @_;
373 $self->_inline_throw_error('"Attribute (' # FIXME add 'dad'
375 . ') does not pass the type constraint because: " . '
376 . $type_constraint_obj . '->get_message(' . $value_name . ')')
377 . "\n\t unless " . $type_constraint_cv . '->(' . $value_name . ');'
381 sub _generate_default_value {
382 my ($self, $attr, $index) = @_;
384 # default values can either be CODE refs
385 # in which case we need to call them. Or
386 # they can be scalars (strings/numbers)
387 # in which case we can just deal with them
388 # in the code we eval.
389 if ($attr->is_default_a_coderef) {
390 return '$attrs->[' . $index . ']->default($instance)';
393 return q{"} . quotemeta( $attr->default ) . q{"};
405 Moose::Meta::Method::Constructor - Method Meta Object for constructors
409 This is a subclass of L<Class::MOP::Method> which handles
410 constructing an approprate Constructor methods. This is primarily
411 used in the making of immutable metaclasses, otherwise it is
412 not particularly useful.
420 =item B<can_be_inlined>
424 =item B<meta_instance>
428 =item B<initialize_body>
430 =item B<associated_metaclass>
432 =item B<can_be_inlined>
438 Stevan Little E<lt>stevan@iinteractive.comE<gt>
440 =head1 COPYRIGHT AND LICENSE
442 Copyright 2006-2008 by Infinity Interactive, Inc.
444 L<http://www.iinteractive.com>
446 This library is free software; you can redistribute it and/or modify
447 it under the same terms as Perl itself.