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