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