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