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 || $meta->throw_error("You must pass a hash of options", data => $options{options});
24 ($options{package_name} && $options{name})
25 || $meta->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 sub options { (shift)->{'%!options'} }
53 sub meta_instance { (shift)->{'$!meta_instance'} }
54 sub attributes { (shift)->{'@!attributes'} }
56 sub associated_metaclass { (shift)->{'$!associated_metaclass'} }
60 # this was changed in 0.41, but broke MooseX::Singleton, so try to catch
61 # any other code using the original broken spelling
62 sub intialize_body { Carp::confess "Please correct the spelling of 'intialize_body' to 'initialize_body'" }
67 # the %options should also include a both
68 # a call 'initializer' and call 'SUPER::'
69 # options, which should cover approx 90%
70 # of the possible use cases (even if it
71 # requires some adaption on the part of
72 # the author, after all, nothing is free)
74 $source .= "\n" . 'my $class = shift;';
76 $source .= "\n" . 'return $class->Moose::Object::new(@_)';
77 $source .= "\n" . ' if $class ne \'' . $self->associated_metaclass->name . '\';';
79 $source .= "\n" . $self->_inline_throw_error('"Single parameters to new() must be a HASH ref"', 'data => $_[0]');
80 $source .= "\n" . ' if scalar @_ == 1 && ref($_[0]) ne q{HASH};';
82 $source .= "\n" . 'my %params = (scalar @_ == 1) ? %{$_[0]} : @_;';
84 $source .= "\n" . 'my $instance = ' . $self->meta_instance->inline_create_instance('$class');
86 $source .= ";\n" . (join ";\n" => map {
87 $self->_generate_slot_initializer($_)
88 } 0 .. (@{$self->attributes} - 1));
90 $source .= ";\n" . $self->_generate_triggers();
91 $source .= ";\n" . $self->_generate_BUILDALL();
93 $source .= ";\n" . 'return $instance';
94 $source .= ";\n" . '}';
95 warn $source if $self->options->{debug};
99 my $meta = $self; # FIXME for _inline_throw_error...
102 # create the nessecary lexicals
103 # to be picked up in the eval
104 my $attrs = $self->attributes;
106 # We need to check if the attribute ->can('type_constraint')
107 # since we may be trying to immutabilize a Moose meta class,
108 # which in turn has attributes which are Class::MOP::Attribute
109 # objects, rather than Moose::Meta::Attribute. And
110 # Class::MOP::Attribute attributes have no type constraints.
111 # However we need to make sure we leave an undef value there
112 # because the inlined code is using the index of the attributes
113 # to determine where to find the type constraint
115 my @type_constraints = map {
116 $_->can('type_constraint') ? $_->type_constraint : undef
119 my @type_constraint_bodies = map {
120 defined $_ ? $_->_compiled_type_constraint : undef;
123 $code = eval $source;
124 $self->throw_error("Could not eval the constructor :\n\n$source\n\nbecause :\n\n$@", error => $@, data => $source ) if $@;
126 $self->{'&!body'} = $code;
129 sub _generate_BUILDALL {
132 foreach my $method (reverse $self->associated_metaclass->find_all_methods_by_name('BUILD')) {
133 push @BUILD_calls => '$instance->' . $method->{class} . '::BUILD(\%params)';
135 return join ";\n" => @BUILD_calls;
138 sub _generate_triggers {
141 foreach my $i (0 .. $#{ $self->attributes }) {
142 my $attr = $self->attributes->[$i];
143 if ($attr->can('has_trigger') && $attr->has_trigger) {
144 if (defined(my $init_arg = $attr->init_arg)) {
145 push @trigger_calls => (
146 '(exists $params{\'' . $init_arg . '\'}) && do {' . "\n "
147 . '$attrs->[' . $i . ']->trigger->('
149 . $self->meta_instance->inline_get_slot_value(
151 ("'" . $attr->name . "'")
154 . '$attrs->[' . $i . ']'
161 return join ";\n" => @trigger_calls;
164 sub _generate_slot_initializer {
168 my $attr = $self->attributes->[$index];
170 my @source = ('## ' . $attr->name);
172 my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
174 if ($is_moose && defined($attr->init_arg) && $attr->is_required && !$attr->has_default && !$attr->has_builder) {
175 push @source => ('(exists $params{\'' . $attr->init_arg . '\'}) ' .
176 '|| ' . $self->_inline_throw_error('"Attribute (' . $attr->name . ') is required"') .';');
179 if (($attr->has_default || $attr->has_builder) && !($is_moose && $attr->is_lazy)) {
181 if ( defined( my $init_arg = $attr->init_arg ) ) {
182 push @source => 'if (exists $params{\'' . $init_arg . '\'}) {';
184 push @source => ('my $val = $params{\'' . $init_arg . '\'};');
186 if ($is_moose && $attr->has_type_constraint) {
187 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
188 push @source => $self->_generate_type_coercion(
190 '$type_constraints[' . $index . ']',
195 push @source => $self->_generate_type_constraint_check(
197 '$type_constraint_bodies[' . $index . ']',
198 '$type_constraints[' . $index . ']',
202 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
204 push @source => "} else {";
207 if ( $attr->has_default ) {
208 $default = $self->_generate_default_value($attr, $index);
211 my $builder = $attr->builder;
212 $default = '$instance->' . $builder;
215 push @source => '{'; # wrap this to avoid my $val overwrite warnings
216 push @source => ('my $val = ' . $default . ';');
217 push @source => $self->_generate_type_constraint_check(
219 ('$type_constraint_bodies[' . $index . ']'),
220 ('$type_constraints[' . $index . ']'),
222 ) if ($is_moose && $attr->has_type_constraint);
224 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
225 push @source => '}'; # close - wrap this to avoid my $val overrite warnings
227 push @source => "}" if defined $attr->init_arg;
229 elsif ( defined( my $init_arg = $attr->init_arg ) ) {
230 push @source => '(exists $params{\'' . $init_arg . '\'}) && do {';
232 push @source => ('my $val = $params{\'' . $init_arg . '\'};');
233 if ($is_moose && $attr->has_type_constraint) {
234 if ($attr->should_coerce && $attr->type_constraint->has_coercion) {
235 push @source => $self->_generate_type_coercion(
237 '$type_constraints[' . $index . ']',
242 push @source => $self->_generate_type_constraint_check(
244 '$type_constraint_bodies[' . $index . ']',
245 '$type_constraints[' . $index . ']',
249 push @source => $self->_generate_slot_assignment($attr, '$val', $index);
254 return join "\n" => @source;
257 sub _generate_slot_assignment {
258 my ($self, $attr, $value, $index) = @_;
262 if ($attr->has_initializer) {
264 '$attrs->[' . $index . ']->set_initial_value($instance, ' . $value . ');'
269 $self->meta_instance->inline_set_slot_value(
271 ("'" . $attr->name . "'"),
277 my $is_moose = $attr->isa('Moose::Meta::Attribute'); # XXX FIXME
279 if ($is_moose && $attr->is_weak_ref) {
282 $self->meta_instance->inline_weaken_slot_value(
284 ("'" . $attr->name . "'")
286 ' if ref ' . $value . ';'
293 sub _generate_type_coercion {
294 my ($self, $attr, $type_constraint_name, $value_name, $return_value_name) = @_;
295 return ($return_value_name . ' = ' . $type_constraint_name . '->coerce(' . $value_name . ');');
298 sub _generate_type_constraint_check {
299 my ($self, $attr, $type_constraint_cv, $type_constraint_obj, $value_name) = @_;
301 $self->_inline_throw_error('"Attribute (' # FIXME add 'dad'
303 . ') does not pass the type constraint because: " . '
304 . $type_constraint_obj . '->get_message(' . $value_name . ')')
305 . "\n\t unless " . $type_constraint_cv . '->(' . $value_name . ');'
309 sub _generate_default_value {
310 my ($self, $attr, $index) = @_;
312 # default values can either be CODE refs
313 # in which case we need to call them. Or
314 # they can be scalars (strings/numbers)
315 # in which case we can just deal with them
316 # in the code we eval.
317 if ($attr->is_default_a_coderef) {
318 return '$attrs->[' . $index . ']->default($instance)';
321 my $default = $attr->default;
322 # make sure to quote strings ...
323 unless (looks_like_number($default)) {
324 $default = "'$default'";
339 Moose::Meta::Method::Constructor - Method Meta Object for constructors
343 This is a subclass of L<Class::MOP::Method> which handles
344 constructing an approprate Constructor methods. This is primarily
345 used in the making of immutable metaclasses, otherwise it is
346 not particularly useful.
356 =item B<meta_instance>
360 =item B<initialize_body>
362 =item B<associated_metaclass>
368 Stevan Little E<lt>stevan@iinteractive.comE<gt>
370 =head1 COPYRIGHT AND LICENSE
372 Copyright 2006-2008 by Infinity Interactive, Inc.
374 L<http://www.iinteractive.com>
376 This library is free software; you can redistribute it and/or modify
377 it under the same terms as Perl itself.