bump version to 1.10 so we can dep on it in Moose
[gitmo/Class-MOP.git] / lib / Class / MOP / Method / Constructor.pm
1
2 package Class::MOP::Method::Constructor;
3
4 use strict;
5 use warnings;
6
7 use Carp         'confess';
8 use Scalar::Util 'blessed', 'weaken';
9
10 our $VERSION   = '1.10';
11 $VERSION = eval $VERSION;
12 our $AUTHORITY = 'cpan:STEVAN';
13
14 use base 'Class::MOP::Method::Inlined';
15
16 sub new {
17     my $class   = shift;
18     my %options = @_;
19
20     (blessed $options{metaclass} && $options{metaclass}->isa('Class::MOP::Class'))
21         || confess "You must pass a metaclass instance if you want to inline"
22             if $options{is_inline};
23
24     ($options{package_name} && $options{name})
25         || confess "You must supply the package_name and name parameters $Class::MOP::Method::UPGRADE_ERROR_TEXT";
26
27     my $self = $class->_new(\%options);
28
29     # we don't want this creating
30     # a cycle in the code, if not
31     # needed
32     weaken($self->{'associated_metaclass'});
33
34     $self->_initialize_body;
35
36     return $self;
37 }
38
39 sub _new {
40     my $class = shift;
41
42     return Class::MOP::Class->initialize($class)->new_object(@_)
43         if $class ne __PACKAGE__;
44
45     my $params = @_ == 1 ? $_[0] : {@_};
46
47     return bless {
48         # inherited from Class::MOP::Method
49         body                 => $params->{body},
50         # associated_metaclass => $params->{associated_metaclass}, # overriden
51         package_name         => $params->{package_name},
52         name                 => $params->{name},
53         original_method      => $params->{original_method},
54
55         # inherited from Class::MOP::Generated
56         is_inline            => $params->{is_inline} || 0,
57         definition_context   => $params->{definition_context},
58
59         # inherited from Class::MOP::Inlined
60         _expected_method_class => $params->{_expected_method_class},
61
62         # defined in this subclass
63         options              => $params->{options} || {},
64         associated_metaclass => $params->{metaclass},
65     }, $class;
66 }
67
68 ## accessors
69
70 sub options              { (shift)->{'options'}              }
71 sub associated_metaclass { (shift)->{'associated_metaclass'} }
72
73 ## cached values ...
74
75 sub _attributes {
76     my $self = shift;
77     $self->{'attributes'} ||= [ $self->associated_metaclass->get_all_attributes ]
78 }
79
80 ## method
81
82 sub _initialize_body {
83     my $self        = shift;
84     my $method_name = '_generate_constructor_method';
85
86     $method_name .= '_inline' if $self->is_inline;
87
88     $self->{'body'} = $self->$method_name;
89 }
90
91 sub _generate_constructor_method {
92     return sub { Class::MOP::Class->initialize(shift)->new_object(@_) }
93 }
94
95 sub _generate_constructor_method_inline {
96     my $self = shift;
97
98     my $defaults = [map { $_->default } @{ $self->_attributes }];
99
100     my $close_over = {
101         '$defaults' => \$defaults,
102     };
103
104     my $source = 'sub {';
105     $source .= "\n" . 'my $class = shift;';
106
107     $source .= "\n" . 'return Class::MOP::Class->initialize($class)->new_object(@_)';
108     $source .= "\n" . '    if $class ne \'' . $self->associated_metaclass->name . '\';';
109
110     $source .= "\n" . 'my $params = @_ == 1 ? $_[0] : {@_};';
111
112     $source .= "\n" . 'my $instance = ' . $self->associated_metaclass->inline_create_instance('$class');
113     my $idx = 0;
114     $source .= ";\n" . (join ";\n" => map {
115         $self->_generate_slot_initializer($_, $idx++)
116     } @{ $self->_attributes });
117     $source .= ";\n" . 'return $instance';
118     $source .= ";\n" . '}';
119     warn $source if $self->options->{debug};
120
121     my ( $code, $e ) = $self->_eval_closure(
122         $close_over,
123         $source
124     );
125     confess "Could not eval the constructor :\n\n$source\n\nbecause :\n\n$e" if $e;
126
127     return $code;
128 }
129
130 sub _generate_slot_initializer {
131     my $self  = shift;
132     my $attr  = shift;
133     my $idx   = shift;
134
135     my $default;
136     if ($attr->has_default) {
137         $default = $self->_generate_default_value($attr, $idx);
138     } elsif( $attr->has_builder ) {
139         $default = '$instance->'.$attr->builder;
140     }
141
142     if ( defined( my $init_arg = $attr->init_arg ) ) {
143         return (
144                   'if(exists $params->{\'' 
145                 . $init_arg . '\'}){' . "\n"
146                 . $attr->inline_set(
147                 '$instance',
148                 '$params->{\'' . $init_arg . '\'}'
149                 )
150                 . "\n" . '} '
151                 . (
152                 !defined $default ? '' : 'else {' . "\n"
153                     . $attr->inline_set(
154                     '$instance',
155                     $default
156                     )
157                     . "\n" . '}'
158                 )
159         );
160     }
161     elsif ( defined $default ) {
162         return (
163             $attr->inline_set(
164                 '$instance',
165                 $default
166                 )
167                 . "\n"
168         );
169     }
170     else {
171         return '';
172     }
173 }
174
175 sub _generate_default_value {
176     my ($self, $attr, $index) = @_;
177     # NOTE:
178     # default values can either be CODE refs
179     # in which case we need to call them. Or
180     # they can be scalars (strings/numbers)
181     # in which case we can just deal with them
182     # in the code we eval.
183     if ($attr->is_default_a_coderef) {
184         return '$defaults->[' . $index . ']->($instance)';
185     }
186     else {
187         return '$defaults->[' . $index . ']';
188     }
189 }
190
191 1;
192
193 __END__
194
195 =pod
196
197 =head1 NAME
198
199 Class::MOP::Method::Constructor - Method Meta Object for constructors
200
201 =head1 SYNOPSIS
202
203   use Class::MOP::Method::Constructor;
204
205   my $constructor = Class::MOP::Method::Constructor->new(
206       metaclass => $metaclass,
207       options   => {
208           debug => 1, # this is all for now
209       },
210   );
211
212   # calling the constructor ...
213   $constructor->body->execute($metaclass->name, %params);
214
215 =head1 DESCRIPTION
216
217 This is a subclass of C<Class::MOP::Method> which generates
218 constructor methods.
219
220 =head1 METHODS
221
222 =over 4
223
224 =item B<< Class::MOP::Method::Constructor->new(%options) >>
225
226 This creates a new constructor object. It accepts a hash reference of
227 options.
228
229 =over 8
230
231 =item * metaclass
232
233 This should be a L<Class::MOP::Class> object. It is required.
234
235 =item * name
236
237 The method name (without a package name). This is required.
238
239 =item * package_name
240
241 The package name for the method. This is required.
242
243 =item * is_inline
244
245 This indicates whether or not the constructor should be inlined. This
246 defaults to false.
247
248 =back
249
250 =item B<< $metamethod->is_inline >>
251
252 Returns a boolean indicating whether or not the constructor is
253 inlined.
254
255 =item B<< $metamethod->associated_metaclass >>
256
257 This returns the L<Class::MOP::Class> object for the method.
258
259 =back
260
261 =head1 AUTHORS
262
263 Stevan Little E<lt>stevan@iinteractive.comE<gt>
264
265 =head1 COPYRIGHT AND LICENSE
266
267 Copyright 2006-2010 by Infinity Interactive, Inc.
268
269 L<http://www.iinteractive.com>
270
271 This library is free software; you can redistribute it and/or modify
272 it under the same terms as Perl itself.
273
274 =cut
275