Bump version to 1.05
[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.05';
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 _meta_instance {
76     my $self = shift;
77     $self->{'meta_instance'} ||= $self->associated_metaclass->get_meta_instance;
78 }
79
80 sub _attributes {
81     my $self = shift;
82     $self->{'attributes'} ||= [ $self->associated_metaclass->get_all_attributes ]
83 }
84
85 ## method
86
87 sub _initialize_body {
88     my $self        = shift;
89     my $method_name = '_generate_constructor_method';
90
91     $method_name .= '_inline' if $self->is_inline;
92
93     $self->{'body'} = $self->$method_name;
94 }
95
96 sub _generate_constructor_method {
97     return sub { Class::MOP::Class->initialize(shift)->new_object(@_) }
98 }
99
100 sub _generate_constructor_method_inline {
101     my $self = shift;
102
103     my $defaults = [map { $_->default } @{ $self->_attributes }];
104
105     my $close_over = {
106         '$defaults' => \$defaults,
107     };
108
109     my $source = 'sub {';
110     $source .= "\n" . 'my $class = shift;';
111
112     $source .= "\n" . 'return Class::MOP::Class->initialize($class)->new_object(@_)';
113     $source .= "\n" . '    if $class ne \'' . $self->associated_metaclass->name . '\';';
114
115     $source .= "\n" . 'my $params = @_ == 1 ? $_[0] : {@_};';
116
117     $source .= "\n" . 'my $instance = ' . $self->_meta_instance->inline_create_instance('$class');
118     my $idx = 0;
119     $source .= ";\n" . (join ";\n" => map {
120         $self->_generate_slot_initializer($_, $idx++)
121     } @{ $self->_attributes });
122     $source .= ";\n" . 'return $instance';
123     $source .= ";\n" . '}';
124     warn $source if $self->options->{debug};
125
126     my ( $code, $e ) = $self->_eval_closure(
127         $close_over,
128         $source
129     );
130     confess "Could not eval the constructor :\n\n$source\n\nbecause :\n\n$e" if $e;
131
132     return $code;
133 }
134
135 sub _generate_slot_initializer {
136     my $self  = shift;
137     my $attr  = shift;
138     my $idx   = shift;
139
140     my $default;
141     if ($attr->has_default) {
142         $default = $self->_generate_default_value($attr, $idx);
143     } elsif( $attr->has_builder ) {
144         $default = '$instance->'.$attr->builder;
145     }
146
147     if ( defined( my $init_arg = $attr->init_arg ) ) {
148         my $mi        = $self->_meta_instance;
149         my $attr_name = $attr->name;
150
151         return (
152                   'if(exists $params->{\'' 
153                 . $init_arg . '\'}){' . "\n"
154                 . $mi->inline_set_slot_value(
155                 '$instance',
156                 $attr_name,
157                 '$params->{\'' . $init_arg . '\'}'
158                 )
159                 . "\n" . '} '
160                 . (
161                 !defined $default ? '' : 'else {' . "\n"
162                     . $mi->inline_set_slot_value(
163                     '$instance',
164                     $attr_name,
165                     $default
166                     )
167                     . "\n" . '}'
168                 )
169         );
170     }
171     elsif ( defined $default ) {
172         return (
173             $self->_meta_instance->inline_set_slot_value(
174                 '$instance',
175                 $attr->name,
176                 $default
177                 )
178                 . "\n"
179         );
180     }
181     else {
182         return '';
183     }
184 }
185
186 sub _generate_default_value {
187     my ($self, $attr, $index) = @_;
188     # NOTE:
189     # default values can either be CODE refs
190     # in which case we need to call them. Or
191     # they can be scalars (strings/numbers)
192     # in which case we can just deal with them
193     # in the code we eval.
194     if ($attr->is_default_a_coderef) {
195         return '$defaults->[' . $index . ']->($instance)';
196     }
197     else {
198         return '$defaults->[' . $index . ']';
199     }
200 }
201
202 1;
203
204 __END__
205
206 =pod
207
208 =head1 NAME
209
210 Class::MOP::Method::Constructor - Method Meta Object for constructors
211
212 =head1 SYNOPSIS
213
214   use Class::MOP::Method::Constructor;
215
216   my $constructor = Class::MOP::Method::Constructor->new(
217       metaclass => $metaclass,
218       options   => {
219           debug => 1, # this is all for now
220       },
221   );
222
223   # calling the constructor ...
224   $constructor->body->execute($metaclass->name, %params);
225
226 =head1 DESCRIPTION
227
228 This is a subclass of C<Class::MOP::Method> which generates
229 constructor methods.
230
231 =head1 METHODS
232
233 =over 4
234
235 =item B<< Class::MOP::Method::Constructor->new(%options) >>
236
237 This creates a new constructor object. It accepts a hash reference of
238 options.
239
240 =over 8
241
242 =item * metaclass
243
244 This should be a L<Class::MOP::Class> object. It is required.
245
246 =item * name
247
248 The method name (without a package name). This is required.
249
250 =item * package_name
251
252 The package name for the method. This is required.
253
254 =item * is_inline
255
256 This indicates whether or not the constructor should be inlined. This
257 defaults to false.
258
259 =back
260
261 =item B<< $metamethod->is_inline >>
262
263 Returns a boolean indicating whether or not the constructor is
264 inlined.
265
266 =item B<< $metamethod->associated_metaclass >>
267
268 This returns the L<Class::MOP::Class> object for the method.
269
270 =back
271
272 =head1 AUTHORS
273
274 Stevan Little E<lt>stevan@iinteractive.comE<gt>
275
276 =head1 COPYRIGHT AND LICENSE
277
278 Copyright 2006-2010 by Infinity Interactive, Inc.
279
280 L<http://www.iinteractive.com>
281
282 This library is free software; you can redistribute it and/or modify
283 it under the same terms as Perl itself.
284
285 =cut
286