_enw for Method::Constructor
[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', 'looks_like_number';
9
10 our $VERSION   = '0.65';
11 our $AUTHORITY = 'cpan:STEVAN';
12
13 use base 'Class::MOP::Method::Generated';
14
15 sub new {
16     my $class   = shift;
17     my %options = @_;
18
19     (blessed $options{metaclass} && $options{metaclass}->isa('Class::MOP::Class'))
20         || confess "You must pass a metaclass instance if you want to inline"
21             if $options{is_inline};
22
23     ($options{package_name} && $options{name})
24         || confess "You must supply the package_name and name parameters $Class::MOP::Method::UPGRADE_ERROR_TEXT";
25
26     my $self = $class->_new(%options);
27
28     # we don't want this creating
29     # a cycle in the code, if not
30     # needed
31     weaken($self->{'associated_metaclass'});
32
33     $self->initialize_body;
34
35     return $self;
36 }
37
38 sub _new {
39     my ( $class, %options ) = @_;
40
41     bless {
42         # from our superclass
43         'body'                 => undef,
44         'package_name'         => $options{package_name},
45         'name'                 => $options{name},        
46         # specific to this subclass
47         'options'              => $options{options} || {},
48         'associated_metaclass' => $options{metaclass},
49         'is_inline'            => ($options{is_inline} || 0),
50     }, $class;
51 }
52
53 ## accessors
54
55 sub options              { (shift)->{'options'}              }
56 sub associated_metaclass { (shift)->{'associated_metaclass'} }
57
58 ## cached values ...
59
60 sub meta_instance {
61     my $self = shift;
62     $self->{'meta_instance'} ||= $self->associated_metaclass->get_meta_instance;
63 }
64
65 sub attributes {
66     my $self = shift;
67     $self->{'attributes'} ||= [ $self->associated_metaclass->compute_all_applicable_attributes ]
68 }
69
70 ## method
71
72 sub initialize_body {
73     my $self        = shift;
74     my $method_name = 'generate_constructor_method';
75
76     $method_name .= '_inline' if $self->is_inline;
77
78     $self->{'body'} = $self->$method_name;
79 }
80
81 sub generate_constructor_method {
82     return sub { Class::MOP::Class->initialize(shift)->new_object(@_) }
83 }
84
85 sub generate_constructor_method_inline {
86     my $self = shift;
87
88     my $source = 'sub {';
89     $source .= "\n" . 'my ($class, %params) = @_;';
90
91     $source .= "\n" . 'return Class::MOP::Class->initialize($class)->new_object(%params)';
92     $source .= "\n" . '    if $class ne \'' . $self->associated_metaclass->name . '\';';
93
94     $source .= "\n" . 'my $instance = ' . $self->meta_instance->inline_create_instance('$class');
95     $source .= ";\n" . (join ";\n" => map {
96         $self->_generate_slot_initializer($_)
97     } 0 .. (@{$self->attributes} - 1));
98     $source .= ";\n" . 'return $instance';
99     $source .= ";\n" . '}';
100     warn $source if $self->options->{debug};
101
102     my $code;
103     {
104         # NOTE:
105         # create the nessecary lexicals
106         # to be picked up in the eval
107         my $attrs = $self->attributes;
108
109         $code = eval $source;
110         confess "Could not eval the constructor :\n\n$source\n\nbecause :\n\n$@" if $@;
111     }
112     return $code;
113 }
114
115 sub _generate_slot_initializer {
116     my $self  = shift;
117     my $index = shift;
118
119     my $attr = $self->attributes->[$index];
120
121     my $default;
122     if ($attr->has_default) {
123         # NOTE:
124         # default values can either be CODE refs
125         # in which case we need to call them. Or
126         # they can be scalars (strings/numbers)
127         # in which case we can just deal with them
128         # in the code we eval.
129         if ($attr->is_default_a_coderef) {
130             $default = '$attrs->[' . $index . ']->default($instance)';
131         }
132         else {
133             $default = $attr->default;
134             # make sure to quote strings ...
135             unless (looks_like_number($default)) {
136                 $default = "'$default'";
137             }
138         }
139     } elsif( $attr->has_builder ) {
140         $default = '$instance->'.$attr->builder;
141     }
142
143     if ( defined $attr->init_arg ) {
144       return (
145           'if(exists $params{\'' . $attr->init_arg . '\'}){' . "\n" .
146                 $self->meta_instance->inline_set_slot_value(
147                     '$instance',
148                     ("'" . $attr->name . "'"),
149                     '$params{\'' . $attr->init_arg . '\'}' ) . "\n" .
150            '} ' . (!defined $default ? '' : 'else {' . "\n" .
151                 $self->meta_instance->inline_set_slot_value(
152                     '$instance',
153                     ("'" . $attr->name . "'"),
154                      $default ) . "\n" .
155            '}')
156         );
157     } elsif ( defined $default ) {
158         return (
159             $self->meta_instance->inline_set_slot_value(
160                 '$instance',
161                 ("'" . $attr->name . "'"),
162                  $default ) . "\n"
163         );
164     } else { return '' }
165 }
166
167 1;
168
169 __END__
170
171 =pod
172
173 =head1 NAME
174
175 Class::MOP::Method::Constructor - Method Meta Object for constructors
176
177 =head1 SYNOPSIS
178
179   use Class::MOP::Method::Constructor;
180
181   my $constructor = Class::MOP::Method::Constructor->new(
182       metaclass => $metaclass,
183       options   => {
184           debug => 1, # this is all for now
185       },
186   );
187
188   # calling the constructor ...
189   $constructor->body->($metaclass->name, %params);
190
191 =head1 DESCRIPTION
192
193 This is a subclass of C<Class::MOP::Method> which deals with
194 class constructors. This is used when making a class immutable
195 to generate an optimized constructor.
196
197 =head1 METHODS
198
199 =over 4
200
201 =item B<new (metaclass => $meta, options => \%options)>
202
203 =item B<options>
204
205 This returns the options HASH which is passed into C<new>.
206
207 =item B<associated_metaclass>
208
209 This returns the metaclass which is passed into C<new>.
210
211 =item B<attributes>
212
213 This returns the list of attributes which are associated with the
214 metaclass which is passed into C<new>.
215
216 =item B<meta_instance>
217
218 This returns the meta instance which is associated with the
219 metaclass which is passed into C<new>.
220
221 =item B<is_inline>
222
223 This returns a boolean, but since constructors are very rarely
224 not inlined, this always returns true for now.
225
226 =item B<initialize_body>
227
228 This creates the code reference for the constructor itself.
229
230 =back
231
232 =head2 Method Generators 
233
234 =over 4
235
236 =item B<generate_constructor_method>
237
238 =item B<generate_constructor_method_inline>
239
240 =back
241
242 =head1 AUTHORS
243
244 Stevan Little E<lt>stevan@iinteractive.comE<gt>
245
246 =head1 COPYRIGHT AND LICENSE
247
248 Copyright 2006-2008 by Infinity Interactive, Inc.
249
250 L<http://www.iinteractive.com>
251
252 This library is free software; you can redistribute it and/or modify
253 it under the same terms as Perl itself.
254
255 =cut
256