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