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