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