refactor this to use _eval_environment
[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 _eval_environment {
97     my $self = shift;
98     my $defaults = [map { $_->default } @{ $self->_attributes }];
99     return {
100         '$defaults' => \$defaults,
101     };
102 }
103
104 sub _generate_constructor_method_inline {
105     my $self = shift;
106
107     my $meta = $self->associated_metaclass;
108
109     my $idx = 0;
110     my @source = (
111         'sub {',
112             'my $class = shift;',
113             'return Class::MOP::Class->initialize($class)->new_object(@_)',
114                 'if $class ne \'' . $meta->name . '\';',
115             'my $params = @_ == 1 ? $_[0] : {@_};',
116             'my $instance = ' . $meta->inline_create_instance('$class') . ';',
117             (map { $self->_generate_slot_initializer($_, $idx++) }
118                  @{ $self->_attributes }),
119             $self->_preserve_weak_metaclasses,
120             'return $instance',
121         '}',
122     );
123
124     warn join("\n", @source) if $self->options->{debug};
125
126     my $code = try {
127         $self->_compile_code(\@source);
128     }
129     catch {
130         my $source = join("\n", @source);
131         confess "Could not eval the constructor :\n\n$source\n\nbecause :\n\n$_";
132     };
133
134     return $code;
135 }
136
137 sub _generate_slot_initializer {
138     my $self  = shift;
139     my ($attr, $idx) = @_;
140
141     my $default = $self->_generate_default_value($attr, $idx);
142
143     if (defined(my $init_arg = $attr->init_arg)) {
144         my @source = (
145             'if (exists $params->{\'' . $init_arg . '\'}) {',
146                 $attr->inline_set(
147                     '$instance', '$params->{\'' . $init_arg . '\'}'
148                 ) . ';',
149             '}',
150         );
151         if (defined $default) {
152             push @source, (
153                 'else {',
154                     $attr->inline_set('$instance', $default) . ';',
155                 '}',
156             );
157         }
158         return @source;
159     }
160     elsif (defined $default) {
161         return ($attr->inline_set('$instance', $default) . ';');
162     }
163     else {
164         return ();
165     }
166 }
167
168 sub _preserve_weak_metaclasses {
169     my $self = shift;
170     my $meta = $self->associated_metaclass;
171     if (Class::MOP::metaclass_is_weak($meta->name)) {
172         return (
173             $meta->_inline_set_mop_slot(
174                 '$instance', 'Class::MOP::class_of($class)'
175             ) . ';'
176         );
177     }
178     else {
179         return ();
180     }
181 }
182
183 sub _generate_default_value {
184     my $self = shift;
185     my ($attr, $index) = @_;
186
187     if ($attr->has_default) {
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     elsif ($attr->has_builder) {
202         return '$instance->' . $attr->builder;
203     }
204     else {
205         return;
206     }
207 }
208
209 1;
210
211 __END__
212
213 =pod
214
215 =head1 NAME
216
217 Class::MOP::Method::Constructor - Method Meta Object for constructors
218
219 =head1 SYNOPSIS
220
221   use Class::MOP::Method::Constructor;
222
223   my $constructor = Class::MOP::Method::Constructor->new(
224       metaclass => $metaclass,
225       options   => {
226           debug => 1, # this is all for now
227       },
228   );
229
230   # calling the constructor ...
231   $constructor->body->execute($metaclass->name, %params);
232
233 =head1 DESCRIPTION
234
235 This is a subclass of C<Class::MOP::Method> which generates
236 constructor methods.
237
238 =head1 METHODS
239
240 =over 4
241
242 =item B<< Class::MOP::Method::Constructor->new(%options) >>
243
244 This creates a new constructor object. It accepts a hash reference of
245 options.
246
247 =over 8
248
249 =item * metaclass
250
251 This should be a L<Class::MOP::Class> object. It is required.
252
253 =item * name
254
255 The method name (without a package name). This is required.
256
257 =item * package_name
258
259 The package name for the method. This is required.
260
261 =item * is_inline
262
263 This indicates whether or not the constructor should be inlined. This
264 defaults to false.
265
266 =back
267
268 =item B<< $metamethod->is_inline >>
269
270 Returns a boolean indicating whether or not the constructor is
271 inlined.
272
273 =item B<< $metamethod->associated_metaclass >>
274
275 This returns the L<Class::MOP::Class> object for the method.
276
277 =back
278
279 =head1 AUTHORS
280
281 Stevan Little E<lt>stevan@iinteractive.comE<gt>
282
283 =head1 COPYRIGHT AND LICENSE
284
285 Copyright 2006-2010 by Infinity Interactive, Inc.
286
287 L<http://www.iinteractive.com>
288
289 This library is free software; you can redistribute it and/or modify
290 it under the same terms as Perl itself.
291
292 =cut
293