use Scalar::Util directly
[gitmo/Mouse.git] / lib / Mouse / Meta / Class.pm
1 #!/usr/bin/env perl
2 package Mouse::Meta::Class;
3 use strict;
4 use warnings;
5
6 use Mouse::Meta::Method::Constructor;
7 use Mouse::Meta::Method::Destructor;
8 use Scalar::Util qw/blessed/;
9 use Mouse::Util qw/get_linear_isa/;
10 use Carp 'confess';
11
12 do {
13     my %METACLASS_CACHE;
14
15     # because Mouse doesn't introspect existing classes, we're forced to
16     # only pay attention to other Mouse classes
17     sub _metaclass_cache {
18         my $class = shift;
19         my $name  = shift;
20         return $METACLASS_CACHE{$name};
21     }
22
23     sub initialize {
24         my $class = shift;
25         my $name  = shift;
26         $METACLASS_CACHE{$name} = $class->new(name => $name)
27             if !exists($METACLASS_CACHE{$name});
28         return $METACLASS_CACHE{$name};
29     }
30 };
31
32 sub new {
33     my $class = shift;
34     my %args  = @_;
35
36     $args{attributes} = {};
37     $args{superclasses} = do {
38         no strict 'refs';
39         \@{ $args{name} . '::ISA' };
40     };
41     $args{roles} ||= [];
42
43     bless \%args, $class;
44 }
45
46 sub name { $_[0]->{name} }
47
48 sub superclasses {
49     my $self = shift;
50
51     if (@_) {
52         Mouse::load_class($_) for @_;
53         @{ $self->{superclasses} } = @_;
54     }
55
56     @{ $self->{superclasses} };
57 }
58
59 sub add_method {
60     my $self = shift;
61     my $name = shift;
62     my $code = shift;
63
64     my $pkg = $self->name;
65
66     no strict 'refs';
67     *{ $pkg . '::' . $name } = $code;
68 }
69
70 # copied from Class::Inspector
71 sub get_method_list {
72     my $self = shift;
73     my $name = $self->name;
74
75     no strict 'refs';
76     # Get all the CODE symbol table entries
77     my @functions = grep !/^meta$/,
78       grep { /\A[^\W\d]\w*\z/o }
79       grep { defined &{"${name}::$_"} }
80       keys %{"${name}::"};
81     wantarray ? @functions : \@functions;
82 }
83
84 sub add_attribute {
85     my $self = shift;
86     my $attr = shift;
87
88     $self->{'attributes'}{$attr->name} = $attr;
89 }
90
91 sub compute_all_applicable_attributes {
92     my $self = shift;
93     my (@attr, %seen);
94
95     for my $class ($self->linearized_isa) {
96         my $meta = $self->_metaclass_cache($class)
97             or next;
98
99         for my $name (keys %{ $meta->get_attribute_map }) {
100             next if $seen{$name}++;
101             push @attr, $meta->get_attribute($name);
102         }
103     }
104
105     return @attr;
106 }
107
108 sub get_attribute_map { $_[0]->{attributes} }
109 sub has_attribute     { exists $_[0]->{attributes}->{$_[1]} }
110 sub get_attribute     { $_[0]->{attributes}->{$_[1]} }
111
112 sub linearized_isa { @{ get_linear_isa($_[0]->name) } }
113
114 sub clone_object {
115     my $class    = shift;
116     my $instance = shift;
117
118     (blessed($instance) && $instance->isa($class->name))
119         || confess "You must pass an instance of the metaclass (" . $class->name . "), not ($instance)";
120
121     $class->clone_instance($instance, @_);
122 }
123
124 sub clone_instance {
125     my ($class, $instance, %params) = @_;
126
127     (blessed($instance))
128         || confess "You can only clone instances, ($instance) is not a blessed instance";
129
130     my $clone = bless { %$instance }, ref $instance;
131
132     foreach my $attr ($class->compute_all_applicable_attributes()) {
133         if ( defined( my $init_arg = $attr->init_arg ) ) {
134             if (exists $params{$init_arg}) {
135                 $clone->{ $attr->name } = $params{$init_arg};
136             }
137         }
138     }
139
140     return $clone;
141
142 }
143
144 sub make_immutable {
145     my $self = shift;
146     my $name = $self->name;
147     $self->{is_immutable}++;
148     no strict 'refs';
149     *{"$name\::new"}     = Mouse::Meta::Method::Constructor->generate_constructor_method_inline( $self );
150     *{"$name\::DESTROY"} = Mouse::Meta::Method::Destructor->generate_destructor_method_inline( $self );
151 }
152 sub make_mutable {
153     Carp::croak "Mouse::Meta::Class->make_mutable does not supported by Mouse";
154 }
155 sub is_immutable { $_[0]->{is_immutable} }
156
157 sub attribute_metaclass { "Mouse::Meta::Class" }
158
159 sub add_before_method_modifier {
160     my ($self, $name, $code) = @_;
161     require Class::Method::Modifiers;
162     Class::Method::Modifiers::_install_modifier(
163         $self->name,
164         'before',
165         $name,
166         $code,
167     );
168 }
169
170 sub add_around_method_modifier {
171     my ($self, $name, $code) = @_;
172     require Class::Method::Modifiers;
173     Class::Method::Modifiers::_install_modifier(
174         $self->name,
175         'around',
176         $name,
177         $code,
178     );
179 }
180
181 sub add_after_method_modifier {
182     my ($self, $name, $code) = @_;
183     require Class::Method::Modifiers;
184     Class::Method::Modifiers::_install_modifier(
185         $self->name,
186         'after',
187         $name,
188         $code,
189     );
190 }
191
192 sub roles { $_[0]->{roles} }
193
194 sub does_role {
195     my ($self, $role_name) = @_;
196     (defined $role_name)
197         || confess "You must supply a role name to look for";
198     for my $role (@{ $self->{roles} }) {
199         return 1 if $role->name eq $role_name;
200     }
201     return 0;
202 }
203
204 sub create {
205     my ( $class, @args ) = @_;
206
207     unshift @args, 'package' if @args % 2 == 1;
208
209     my (%options) = @args;
210     my $package_name = $options{package};
211
212     (ref $options{superclasses} eq 'ARRAY')
213         || confess "You must pass an ARRAY ref of superclasses"
214             if exists $options{superclasses};
215             
216     (ref $options{attributes} eq 'ARRAY')
217         || confess "You must pass an ARRAY ref of attributes"
218             if exists $options{attributes};      
219             
220     (ref $options{methods} eq 'HASH')
221         || confess "You must pass a HASH ref of methods"
222             if exists $options{methods};                  
223
224     do {
225         # XXX should I implement Mouse::Meta::Module?
226         my $package_name = $options{package};
227
228         ( defined $package_name && $package_name )
229           || confess "You must pass a package name";
230
231         my $code = "package $package_name;";
232         $code .= "\$$package_name\:\:VERSION = '" . $options{version} . "';"
233           if exists $options{version};
234         $code .= "\$$package_name\:\:AUTHORITY = '" . $options{authority} . "';"
235           if exists $options{authority};
236
237         eval $code;
238         confess "creation of $package_name failed : $@" if $@;
239     };
240
241     my (%initialize_options) = @args;
242     delete @initialize_options{qw(
243         package
244         superclasses
245         attributes
246         methods
247         version
248         authority
249     )};
250     my $meta = $class->initialize( $package_name => %initialize_options );
251
252     # FIXME totally lame
253     $meta->add_method('meta' => sub {
254         $class->initialize(ref($_[0]) || $_[0]);
255     });
256
257     $meta->superclasses(@{$options{superclasses}})
258         if exists $options{superclasses};
259     # NOTE:
260     # process attributes first, so that they can
261     # install accessors, but locally defined methods
262     # can then overwrite them. It is maybe a little odd, but
263     # I think this should be the order of things.
264     if (exists $options{attributes}) {
265         foreach my $attr (@{$options{attributes}}) {
266             Mouse::Meta::Attribute->create($meta, $attr->{name}, %$attr);
267         }
268     }
269     if (exists $options{methods}) {
270         foreach my $method_name (keys %{$options{methods}}) {
271             $meta->add_method($method_name, $options{methods}->{$method_name});
272         }
273     }
274     return $meta;
275 }
276
277 {
278     my $ANON_CLASS_SERIAL = 0;
279     my $ANON_CLASS_PREFIX = 'Mouse::Meta::Class::__ANON__::SERIAL::';
280     sub create_anon_class {
281         my ( $class, %options ) = @_;
282         my $package_name = $ANON_CLASS_PREFIX . ++$ANON_CLASS_SERIAL;
283         return $class->create( $package_name, %options );
284     }
285 }
286
287 1;
288
289 __END__
290
291 =head1 NAME
292
293 Mouse::Meta::Class - hook into the Mouse MOP
294
295 =head1 METHODS
296
297 =head2 initialize ClassName -> Mouse::Meta::Class
298
299 Finds or creates a Mouse::Meta::Class instance for the given ClassName. Only
300 one instance should exist for a given class.
301
302 =head2 new %args -> Mouse::Meta::Class
303
304 Creates a new Mouse::Meta::Class. Don't call this directly.
305
306 =head2 name -> ClassName
307
308 Returns the name of the owner class.
309
310 =head2 superclasses -> [ClassName]
311
312 Gets (or sets) the list of superclasses of the owner class.
313
314 =head2 add_attribute Mouse::Meta::Attribute
315
316 Begins keeping track of the existing L<Mouse::Meta::Attribute> for the owner
317 class.
318
319 =head2 compute_all_applicable_attributes -> (Mouse::Meta::Attribute)
320
321 Returns the list of all L<Mouse::Meta::Attribute> instances associated with
322 this class and its superclasses.
323
324 =head2 get_attribute_map -> { name => Mouse::Meta::Attribute }
325
326 Returns a mapping of attribute names to their corresponding
327 L<Mouse::Meta::Attribute> objects.
328
329 =head2 has_attribute Name -> Boool
330
331 Returns whether we have a L<Mouse::Meta::Attribute> with the given name.
332
333 =head2 get_attribute Name -> Mouse::Meta::Attribute | undef
334
335 Returns the L<Mouse::Meta::Attribute> with the given name.
336
337 =head2 linearized_isa -> [ClassNames]
338
339 Returns the list of classes in method dispatch order, with duplicates removed.
340
341 =head2 clone_object Instance -> Instance
342
343 Clones the given C<Instance> which must be an instance governed by this
344 metaclass.
345
346 =head2 clone_instance Instance, Parameters -> Instance
347
348 Clones the given C<Instance> and sets any additional parameters.
349
350 =cut
351