MRO::Compat already does various version fiddling, no need to duplicate
[gitmo/Class-MOP.git] / lib / Class / MOP.pm
CommitLineData
94b19069 1
2package Class::MOP;
3
4use strict;
5use warnings;
6
3cf322a0 7use MRO::Compat;
8
4c105333 9use Carp 'confess';
10use Scalar::Util 'weaken';
8b978dd5 11
2eb717d5 12use Class::MOP::Class;
13use Class::MOP::Attribute;
14use Class::MOP::Method;
15
c23184fc 16use Class::MOP::Immutable;
857f87a7 17
b1f5f41d 18BEGIN {
70ad0655 19
2e5c1a3f 20 our $VERSION = '0.65';
b1f5f41d 21 our $AUTHORITY = 'cpan:STEVAN';
22
11b56828 23 *IS_RUNNING_ON_5_10 = ($] < 5.009_005)
24 ? sub () { 0 }
4c105333 25 : sub () { 1 };
46b23b44 26
4c105333 27 # NOTE:
28 # we may not use this yet, but once
29 # the get_code_info XS gets merged
30 # upstream to it, we will always use
31 # it. But for now it is just kinda
32 # extra overhead.
33 # - SL
34 require Sub::Identify;
35
36 # stash these for a sec, and see how things go
37 my $_PP_subname = sub { $_[1] };
a982eca7 38 my $_PP_get_code_info = \&Sub::Identify::get_code_info;
4c105333 39
e2d4fc55 40 if ($ENV{CLASS_MOP_NO_XS}) {
4c105333 41 # NOTE:
42 # this is if you really want things
43 # to be slow, then you can force the
44 # no-XS rule this way, otherwise we
45 # make an effort to load as much of
46 # the XS as possible.
47 # - SL
48 no warnings 'prototype', 'redefine';
6c34db07 49
3c489bcb 50 # this is either part of core or set up appropriately by MRO::Compat
51 *check_package_cache_flag = \&mro::get_pkg_gen;
52
4c105333 53 # our own version of Sub::Name
54 *subname = $_PP_subname;
55 # and the Sub::Identify version of the get_code_info
56 *get_code_info = $_PP_get_code_info;
57 }
58 else {
59 # now try our best to get as much
60 # of the XS loaded as possible
61 {
62 local $@;
63 eval {
64 require XSLoader;
65 XSLoader::load( 'Class::MOP', $VERSION );
66 };
67 die $@ if $@ && $@ !~ /object version|loadable object/;
68
69 # okay, so the XS failed to load, so
70 # use the pure perl one instead.
71 *get_code_info = $_PP_get_code_info if $@;
72 }
73
74 # get it from MRO::Compat
75 *check_package_cache_flag = \&mro::get_pkg_gen;
76
77 # now try and load the Sub::Name
78 # module and use that as a means
79 # for naming our CVs, if not, we
80 # use the workaround instead.
81 if ( eval { require Sub::Name } ) {
6c34db07 82 *subname = \&Sub::Name::subname;
4c105333 83 }
84 else {
85 *subname = $_PP_subname;
86 }
87 }
b1f5f41d 88}
e0e4674a 89
be7677c7 90{
91 # Metaclasses are singletons, so we cache them here.
92 # there is no need to worry about destruction though
93 # because they should die only when the program dies.
94 # After all, do package definitions even get reaped?
1d68af04 95 my %METAS;
96
97 # means of accessing all the metaclasses that have
be7677c7 98 # been initialized thus far (for mugwumps obj browser)
1d68af04 99 sub get_all_metaclasses { %METAS }
100 sub get_all_metaclass_instances { values %METAS }
101 sub get_all_metaclass_names { keys %METAS }
be7677c7 102 sub get_metaclass_by_name { $METAS{$_[0]} }
1d68af04 103 sub store_metaclass_by_name { $METAS{$_[0]} = $_[1] }
104 sub weaken_metaclass { weaken($METAS{$_[0]}) }
be7677c7 105 sub does_metaclass_exist { exists $METAS{$_[0]} && defined $METAS{$_[0]} }
1d68af04 106 sub remove_metaclass_by_name { $METAS{$_[0]} = undef }
107
be7677c7 108 # NOTE:
1d68af04 109 # We only cache metaclasses, meaning instances of
110 # Class::MOP::Class. We do not cache instance of
be7677c7 111 # Class::MOP::Package or Class::MOP::Module. Mostly
1d68af04 112 # because I don't yet see a good reason to do so.
be7677c7 113}
114
448b6e55 115sub load_class {
116 my $class = shift;
ab5e2f48 117
118 if (ref($class) || !defined($class) || !length($class)) {
119 my $display = defined($class) ? $class : 'undef';
120 confess "Invalid class name ($display)";
121 }
122
07940968 123 # if the class is not already loaded in the symbol table..
124 unless (is_class_loaded($class)) {
125 # require it
126 my $file = $class . '.pm';
127 $file =~ s{::}{/}g;
128 eval { CORE::require($file) };
129 confess "Could not load class ($class) because : $@" if $@;
130 }
131
132 # initialize a metaclass if necessary
448b6e55 133 unless (does_metaclass_exist($class)) {
134 eval { Class::MOP::Class->initialize($class) };
1d68af04 135 confess "Could not initialize class ($class) because : $@" if $@;
448b6e55 136 }
07940968 137
138 return get_metaclass_by_name($class);
448b6e55 139}
140
141sub is_class_loaded {
c1d5345a 142 my $class = shift;
26fcef27 143
144 return 0 if ref($class) || !defined($class) || !length($class);
145
146 # walk the symbol table tree to avoid autovififying
147 # \*{${main::}{"Foo::"}} == \*main::Foo::
148
149 my $pack = \*::;
150 foreach my $part (split('::', $class)) {
151 return 0 unless exists ${$$pack}{"${part}::"};
152 $pack = \*{${$$pack}{"${part}::"}};
c1d5345a 153 }
26fcef27 154
155 # check for $VERSION or @ISA
156 return 1 if exists ${$$pack}{VERSION}
157 && defined *{${$$pack}{VERSION}}{SCALAR};
158 return 1 if exists ${$$pack}{ISA}
159 && defined *{${$$pack}{ISA}}{ARRAY};
160
161 # check for any method
162 foreach ( keys %{$$pack} ) {
163 next if substr($_, -2, 2) eq '::';
d5be3722 164
165 my $glob = ${$$pack}{$_} || next;
166
9e275e86 167 # constant subs
d5be3722 168 if ( IS_RUNNING_ON_5_10 ) {
169 return 1 if ref $glob eq 'SCALAR';
170 }
171
172 return 1 if defined *{$glob}{CODE};
26fcef27 173 }
174
175 # fail
c1d5345a 176 return 0;
448b6e55 177}
178
179
aa448b16 180## ----------------------------------------------------------------------------
181## Setting up our environment ...
182## ----------------------------------------------------------------------------
1d68af04 183## Class::MOP needs to have a few things in the global perl environment so
aa448b16 184## that it can operate effectively. Those things are done here.
185## ----------------------------------------------------------------------------
186
3bf7644b 187# ... nothing yet actually ;)
8b978dd5 188
b51af7f9 189## ----------------------------------------------------------------------------
1d68af04 190## Bootstrapping
b51af7f9 191## ----------------------------------------------------------------------------
1d68af04 192## The code below here is to bootstrap our MOP with itself. This is also
b51af7f9 193## sometimes called "tying the knot". By doing this, we make it much easier
194## to extend the MOP through subclassing and such since now you can use the
1d68af04 195## MOP itself to extend itself.
196##
b51af7f9 197## Yes, I know, thats weird and insane, but it's a good thing, trust me :)
1d68af04 198## ----------------------------------------------------------------------------
727919c5 199
1d68af04 200# We need to add in the meta-attributes here so that
201# any subclass of Class::MOP::* will be able to
727919c5 202# inherit them using &construct_instance
203
f0480c45 204## --------------------------------------------------------
6d5355c3 205## Class::MOP::Package
727919c5 206
6d5355c3 207Class::MOP::Package->meta->add_attribute(
8683db0e 208 Class::MOP::Attribute->new('package' => (
b880e0de 209 reader => {
1d68af04 210 # NOTE: we need to do this in order
211 # for the instance meta-object to
b880e0de 212 # not fall into meta-circular death
1d68af04 213 #
ce2ae40f 214 # we just alias the original method
1d68af04 215 # rather than re-produce it here
ce2ae40f 216 'name' => \&Class::MOP::Package::name
b880e0de 217 },
c23184fc 218 init_arg => 'package',
727919c5 219 ))
220);
221
a5e51f0b 222Class::MOP::Package->meta->add_attribute(
8683db0e 223 Class::MOP::Attribute->new('namespace' => (
a5e51f0b 224 reader => {
56dcfc1a 225 # NOTE:
ce2ae40f 226 # we just alias the original method
227 # rather than re-produce it here
228 'namespace' => \&Class::MOP::Package::namespace
a5e51f0b 229 },
2e877f58 230 init_arg => undef,
c4260b45 231 default => sub { \undef }
a5e51f0b 232 ))
233);
234
9d6dce77 235# NOTE:
236# use the metaclass to construct the meta-package
237# which is a superclass of the metaclass itself :P
238Class::MOP::Package->meta->add_method('initialize' => sub {
239 my $class = shift;
240 my $package_name = shift;
1d68af04 241 $class->meta->new_object('package' => $package_name, @_);
9d6dce77 242});
243
f0480c45 244## --------------------------------------------------------
245## Class::MOP::Module
246
247# NOTE:
1d68af04 248# yeah this is kind of stretching things a bit,
f0480c45 249# but truthfully the version should be an attribute
1d68af04 250# of the Module, the weirdness comes from having to
251# stick to Perl 5 convention and store it in the
252# $VERSION package variable. Basically if you just
253# squint at it, it will look how you want it to look.
f0480c45 254# Either as a package variable, or as a attribute of
255# the metaclass, isn't abstraction great :)
256
257Class::MOP::Module->meta->add_attribute(
8683db0e 258 Class::MOP::Attribute->new('version' => (
f0480c45 259 reader => {
ce2ae40f 260 # NOTE:
261 # we just alias the original method
1d68af04 262 # rather than re-produce it here
ce2ae40f 263 'version' => \&Class::MOP::Module::version
f0480c45 264 },
2e877f58 265 init_arg => undef,
c4260b45 266 default => sub { \undef }
f0480c45 267 ))
268);
269
270# NOTE:
1d68af04 271# By following the same conventions as version here,
272# we are opening up the possibility that people can
273# use the $AUTHORITY in non-Class::MOP modules as
274# well.
f0480c45 275
276Class::MOP::Module->meta->add_attribute(
8683db0e 277 Class::MOP::Attribute->new('authority' => (
f0480c45 278 reader => {
ce2ae40f 279 # NOTE:
280 # we just alias the original method
1d68af04 281 # rather than re-produce it here
ce2ae40f 282 'authority' => \&Class::MOP::Module::authority
1d68af04 283 },
2e877f58 284 init_arg => undef,
c4260b45 285 default => sub { \undef }
f0480c45 286 ))
287);
288
289## --------------------------------------------------------
6d5355c3 290## Class::MOP::Class
291
727919c5 292Class::MOP::Class->meta->add_attribute(
8683db0e 293 Class::MOP::Attribute->new('attributes' => (
f7259199 294 reader => {
1d68af04 295 # NOTE: we need to do this in order
296 # for the instance meta-object to
297 # not fall into meta-circular death
298 #
ce2ae40f 299 # we just alias the original method
1d68af04 300 # rather than re-produce it here
ce2ae40f 301 'get_attribute_map' => \&Class::MOP::Class::get_attribute_map
f7259199 302 },
c23184fc 303 init_arg => 'attributes',
727919c5 304 default => sub { {} }
305 ))
306);
307
351bd7d4 308Class::MOP::Class->meta->add_attribute(
8683db0e 309 Class::MOP::Attribute->new('methods' => (
c23184fc 310 init_arg => 'methods',
1d68af04 311 reader => {
ce2ae40f 312 # NOTE:
313 # we just alias the original method
1d68af04 314 # rather than re-produce it here
ce2ae40f 315 'get_method_map' => \&Class::MOP::Class::get_method_map
92330ee2 316 },
7855ddba 317 default => sub { {} }
c4260b45 318 ))
319);
320
321Class::MOP::Class->meta->add_attribute(
8683db0e 322 Class::MOP::Attribute->new('superclasses' => (
c23184fc 323 accessor => {
324 # NOTE:
325 # we just alias the original method
1d68af04 326 # rather than re-produce it here
c23184fc 327 'superclasses' => \&Class::MOP::Class::superclasses
328 },
2e877f58 329 init_arg => undef,
c23184fc 330 default => sub { \undef }
331 ))
332);
333
334Class::MOP::Class->meta->add_attribute(
8683db0e 335 Class::MOP::Attribute->new('attribute_metaclass' => (
1d68af04 336 reader => {
6d2118a4 337 # NOTE:
338 # we just alias the original method
1d68af04 339 # rather than re-produce it here
6d2118a4 340 'attribute_metaclass' => \&Class::MOP::Class::attribute_metaclass
1d68af04 341 },
c23184fc 342 init_arg => 'attribute_metaclass',
351bd7d4 343 default => 'Class::MOP::Attribute',
344 ))
345);
346
347Class::MOP::Class->meta->add_attribute(
8683db0e 348 Class::MOP::Attribute->new('method_metaclass' => (
1d68af04 349 reader => {
6d2118a4 350 # NOTE:
351 # we just alias the original method
1d68af04 352 # rather than re-produce it here
6d2118a4 353 'method_metaclass' => \&Class::MOP::Class::method_metaclass
354 },
c23184fc 355 init_arg => 'method_metaclass',
1d68af04 356 default => 'Class::MOP::Method',
351bd7d4 357 ))
358);
359
2bab2be6 360Class::MOP::Class->meta->add_attribute(
8683db0e 361 Class::MOP::Attribute->new('instance_metaclass' => (
b880e0de 362 reader => {
1d68af04 363 # NOTE: we need to do this in order
364 # for the instance meta-object to
365 # not fall into meta-circular death
366 #
ce2ae40f 367 # we just alias the original method
1d68af04 368 # rather than re-produce it here
ce2ae40f 369 'instance_metaclass' => \&Class::MOP::Class::instance_metaclass
b880e0de 370 },
c23184fc 371 init_arg => 'instance_metaclass',
1d68af04 372 default => 'Class::MOP::Instance',
2bab2be6 373 ))
374);
375
9d6dce77 376# NOTE:
1d68af04 377# we don't actually need to tie the knot with
378# Class::MOP::Class here, it is actually handled
379# within Class::MOP::Class itself in the
380# construct_class_instance method.
9d6dce77 381
f0480c45 382## --------------------------------------------------------
727919c5 383## Class::MOP::Attribute
384
7b31baf4 385Class::MOP::Attribute->meta->add_attribute(
8683db0e 386 Class::MOP::Attribute->new('name' => (
c23184fc 387 init_arg => 'name',
388 reader => {
1d68af04 389 # NOTE: we need to do this in order
390 # for the instance meta-object to
391 # not fall into meta-circular death
392 #
ce2ae40f 393 # we just alias the original method
1d68af04 394 # rather than re-produce it here
ce2ae40f 395 'name' => \&Class::MOP::Attribute::name
b880e0de 396 }
7b31baf4 397 ))
398);
399
400Class::MOP::Attribute->meta->add_attribute(
8683db0e 401 Class::MOP::Attribute->new('associated_class' => (
c23184fc 402 init_arg => 'associated_class',
403 reader => {
1d68af04 404 # NOTE: we need to do this in order
405 # for the instance meta-object to
406 # not fall into meta-circular death
407 #
ce2ae40f 408 # we just alias the original method
1d68af04 409 # rather than re-produce it here
ce2ae40f 410 'associated_class' => \&Class::MOP::Attribute::associated_class
b880e0de 411 }
7b31baf4 412 ))
413);
414
415Class::MOP::Attribute->meta->add_attribute(
8683db0e 416 Class::MOP::Attribute->new('accessor' => (
c23184fc 417 init_arg => 'accessor',
6d2118a4 418 reader => { 'accessor' => \&Class::MOP::Attribute::accessor },
419 predicate => { 'has_accessor' => \&Class::MOP::Attribute::has_accessor },
7b31baf4 420 ))
421);
422
423Class::MOP::Attribute->meta->add_attribute(
8683db0e 424 Class::MOP::Attribute->new('reader' => (
c23184fc 425 init_arg => 'reader',
6d2118a4 426 reader => { 'reader' => \&Class::MOP::Attribute::reader },
427 predicate => { 'has_reader' => \&Class::MOP::Attribute::has_reader },
7b31baf4 428 ))
429);
430
431Class::MOP::Attribute->meta->add_attribute(
8683db0e 432 Class::MOP::Attribute->new('initializer' => (
0ab65f99 433 init_arg => 'initializer',
8ee74136 434 reader => { 'initializer' => \&Class::MOP::Attribute::initializer },
435 predicate => { 'has_initializer' => \&Class::MOP::Attribute::has_initializer },
0ab65f99 436 ))
437);
438
439Class::MOP::Attribute->meta->add_attribute(
8683db0e 440 Class::MOP::Attribute->new('writer' => (
c23184fc 441 init_arg => 'writer',
6d2118a4 442 reader => { 'writer' => \&Class::MOP::Attribute::writer },
443 predicate => { 'has_writer' => \&Class::MOP::Attribute::has_writer },
7b31baf4 444 ))
445);
446
447Class::MOP::Attribute->meta->add_attribute(
8683db0e 448 Class::MOP::Attribute->new('predicate' => (
c23184fc 449 init_arg => 'predicate',
6d2118a4 450 reader => { 'predicate' => \&Class::MOP::Attribute::predicate },
451 predicate => { 'has_predicate' => \&Class::MOP::Attribute::has_predicate },
7b31baf4 452 ))
453);
454
455Class::MOP::Attribute->meta->add_attribute(
8683db0e 456 Class::MOP::Attribute->new('clearer' => (
c23184fc 457 init_arg => 'clearer',
6d2118a4 458 reader => { 'clearer' => \&Class::MOP::Attribute::clearer },
459 predicate => { 'has_clearer' => \&Class::MOP::Attribute::has_clearer },
7d28758b 460 ))
461);
462
463Class::MOP::Attribute->meta->add_attribute(
8683db0e 464 Class::MOP::Attribute->new('builder' => (
1d68af04 465 init_arg => 'builder',
466 reader => { 'builder' => \&Class::MOP::Attribute::builder },
467 predicate => { 'has_builder' => \&Class::MOP::Attribute::has_builder },
468 ))
469);
470
471Class::MOP::Attribute->meta->add_attribute(
8683db0e 472 Class::MOP::Attribute->new('init_arg' => (
c23184fc 473 init_arg => 'init_arg',
6d2118a4 474 reader => { 'init_arg' => \&Class::MOP::Attribute::init_arg },
475 predicate => { 'has_init_arg' => \&Class::MOP::Attribute::has_init_arg },
7b31baf4 476 ))
477);
478
479Class::MOP::Attribute->meta->add_attribute(
8683db0e 480 Class::MOP::Attribute->new('default' => (
c23184fc 481 init_arg => 'default',
7b31baf4 482 # default has a custom 'reader' method ...
1d68af04 483 predicate => { 'has_default' => \&Class::MOP::Attribute::has_default },
7b31baf4 484 ))
485);
486
3545c727 487Class::MOP::Attribute->meta->add_attribute(
8683db0e 488 Class::MOP::Attribute->new('associated_methods' => (
c23184fc 489 init_arg => 'associated_methods',
490 reader => { 'associated_methods' => \&Class::MOP::Attribute::associated_methods },
1d68af04 491 default => sub { [] }
3545c727 492 ))
493);
727919c5 494
495# NOTE: (meta-circularity)
496# This should be one of the last things done
497# it will "tie the knot" with Class::MOP::Attribute
1d68af04 498# so that it uses the attributes meta-objects
499# to construct itself.
727919c5 500Class::MOP::Attribute->meta->add_method('new' => sub {
649efb63 501 my ( $class, @args ) = @_;
502
503 unshift @args, "name" if @args % 2 == 1;
504 my %options = @args;
505
506 my $name = $options{name};
1d68af04 507
727919c5 508 (defined $name && $name)
509 || confess "You must provide a name for the attribute";
1d68af04 510 $options{init_arg} = $name
5659d76e 511 if not exists $options{init_arg};
1d68af04 512
513 if(exists $options{builder}){
514 confess("builder must be a defined scalar value which is a method name")
515 if ref $options{builder} || !(defined $options{builder});
516 confess("Setting both default and builder is not allowed.")
517 if exists $options{default};
8fe581e5 518 } else {
519 (Class::MOP::Attribute::is_default_a_coderef(\%options))
520 || confess("References are not allowed as default values, you must ".
3c0a8087 521 "wrap the default of '$name' in a CODE reference (ex: sub { [] } and not [])")
8fe581e5 522 if exists $options{default} && ref $options{default};
1d68af04 523 }
8683db0e 524
5659d76e 525 # return the new object
649efb63 526 $class->meta->new_object(%options);
5659d76e 527});
528
529Class::MOP::Attribute->meta->add_method('clone' => sub {
a740253a 530 my $self = shift;
1d68af04 531 $self->meta->clone_object($self, @_);
727919c5 532});
533
f0480c45 534## --------------------------------------------------------
b6164407 535## Class::MOP::Method
b6164407 536Class::MOP::Method->meta->add_attribute(
8683db0e 537 Class::MOP::Attribute->new('body' => (
c23184fc 538 init_arg => 'body',
539 reader => { 'body' => \&Class::MOP::Method::body },
b6164407 540 ))
541);
542
4c105333 543Class::MOP::Method->meta->add_attribute(
8683db0e 544 Class::MOP::Attribute->new('package_name' => (
4c105333 545 init_arg => 'package_name',
546 reader => { 'package_name' => \&Class::MOP::Method::package_name },
547 ))
548);
549
550Class::MOP::Method->meta->add_attribute(
8683db0e 551 Class::MOP::Attribute->new('name' => (
4c105333 552 init_arg => 'name',
553 reader => { 'name' => \&Class::MOP::Method::name },
554 ))
555);
556
557Class::MOP::Method->meta->add_method('wrap' => sub {
5caf45ce 558 my ( $class, @args ) = @_;
559
560 unshift @args, 'body' if @args % 2 == 1;
561
562 my %options = @args;
563 my $code = $options{body};
4c105333 564
9b522fc4 565 ('CODE' eq ref($code))
4c105333 566 || confess "You must supply a CODE reference to bless, not (" . ($code || 'undef') . ")";
567
b38f3848 568 ($options{package_name} && $options{name})
569 || confess "You must supply the package_name and name parameters";
570
4c105333 571 # return the new object
5caf45ce 572 $class->meta->new_object(%options);
4c105333 573});
574
575Class::MOP::Method->meta->add_method('clone' => sub {
576 my $self = shift;
577 $self->meta->clone_object($self, @_);
578});
579
b6164407 580## --------------------------------------------------------
581## Class::MOP::Method::Wrapped
582
583# NOTE:
1d68af04 584# the way this item is initialized, this
585# really does not follow the standard
586# practices of attributes, but we put
b6164407 587# it here for completeness
588Class::MOP::Method::Wrapped->meta->add_attribute(
8683db0e 589 Class::MOP::Attribute->new('modifier_table')
b6164407 590);
591
592## --------------------------------------------------------
565f0cbb 593## Class::MOP::Method::Generated
594
595Class::MOP::Method::Generated->meta->add_attribute(
8683db0e 596 Class::MOP::Attribute->new('is_inline' => (
565f0cbb 597 init_arg => 'is_inline',
598 reader => { 'is_inline' => \&Class::MOP::Method::Generated::is_inline },
4c105333 599 default => 0,
1d68af04 600 ))
565f0cbb 601);
602
4c105333 603Class::MOP::Method::Generated->meta->add_method('new' => sub {
604 my ($class, %options) = @_;
b38f3848 605 ($options{package_name} && $options{name})
606 || confess "You must supply the package_name and name parameters";
4c105333 607 my $self = $class->meta->new_object(%options);
608 $self->initialize_body;
609 $self;
610});
611
565f0cbb 612## --------------------------------------------------------
d90b42a6 613## Class::MOP::Method::Accessor
614
615Class::MOP::Method::Accessor->meta->add_attribute(
8683db0e 616 Class::MOP::Attribute->new('attribute' => (
c23184fc 617 init_arg => 'attribute',
1d68af04 618 reader => {
619 'associated_attribute' => \&Class::MOP::Method::Accessor::associated_attribute
d90b42a6 620 },
1d68af04 621 ))
d90b42a6 622);
623
624Class::MOP::Method::Accessor->meta->add_attribute(
8683db0e 625 Class::MOP::Attribute->new('accessor_type' => (
c23184fc 626 init_arg => 'accessor_type',
627 reader => { 'accessor_type' => \&Class::MOP::Method::Accessor::accessor_type },
1d68af04 628 ))
d90b42a6 629);
630
4c105333 631Class::MOP::Method::Accessor->meta->add_method('new' => sub {
632 my $class = shift;
633 my %options = @_;
634
635 (exists $options{attribute})
636 || confess "You must supply an attribute to construct with";
637
638 (exists $options{accessor_type})
639 || confess "You must supply an accessor_type to construct with";
640
641 (Scalar::Util::blessed($options{attribute}) && $options{attribute}->isa('Class::MOP::Attribute'))
642 || confess "You must supply an attribute which is a 'Class::MOP::Attribute' instance";
643
b38f3848 644 ($options{package_name} && $options{name})
645 || confess "You must supply the package_name and name parameters";
646
4c105333 647 # return the new object
648 my $self = $class->meta->new_object(%options);
649
650 # we don't want this creating
651 # a cycle in the code, if not
652 # needed
8683db0e 653 Scalar::Util::weaken($self->{'attribute'});
4c105333 654
655 $self->initialize_body;
656
657 $self;
658});
659
d90b42a6 660
661## --------------------------------------------------------
662## Class::MOP::Method::Constructor
663
664Class::MOP::Method::Constructor->meta->add_attribute(
8683db0e 665 Class::MOP::Attribute->new('options' => (
c23184fc 666 init_arg => 'options',
1d68af04 667 reader => {
668 'options' => \&Class::MOP::Method::Constructor::options
d90b42a6 669 },
4c105333 670 default => sub { +{} }
1d68af04 671 ))
d90b42a6 672);
673
674Class::MOP::Method::Constructor->meta->add_attribute(
8683db0e 675 Class::MOP::Attribute->new('associated_metaclass' => (
c23184fc 676 init_arg => 'metaclass',
1d68af04 677 reader => {
678 'associated_metaclass' => \&Class::MOP::Method::Constructor::associated_metaclass
679 },
680 ))
d90b42a6 681);
682
4c105333 683Class::MOP::Method::Constructor->meta->add_method('new' => sub {
684 my $class = shift;
685 my %options = @_;
686
687 (Scalar::Util::blessed $options{metaclass} && $options{metaclass}->isa('Class::MOP::Class'))
688 || confess "You must pass a metaclass instance if you want to inline"
689 if $options{is_inline};
690
b38f3848 691 ($options{package_name} && $options{name})
692 || confess "You must supply the package_name and name parameters";
693
4c105333 694 # return the new object
695 my $self = $class->meta->new_object(%options);
696
697 # we don't want this creating
698 # a cycle in the code, if not
699 # needed
8683db0e 700 Scalar::Util::weaken($self->{'associated_metaclass'});
4c105333 701
702 $self->initialize_body;
703
704 $self;
705});
706
d90b42a6 707## --------------------------------------------------------
86482605 708## Class::MOP::Instance
709
710# NOTE:
1d68af04 711# these don't yet do much of anything, but are just
86482605 712# included for completeness
713
714Class::MOP::Instance->meta->add_attribute(
63d08a9e 715 Class::MOP::Attribute->new('associated_metaclass')
86482605 716);
717
718Class::MOP::Instance->meta->add_attribute(
32bfc810 719 Class::MOP::Attribute->new('attributes')
720);
721
722Class::MOP::Instance->meta->add_attribute(
8683db0e 723 Class::MOP::Attribute->new('slots')
86482605 724);
725
63d08a9e 726Class::MOP::Instance->meta->add_attribute(
727 Class::MOP::Attribute->new('slot_hash')
728);
729
730
caa051fa 731# we need the meta instance of the meta instance to be created now, in order
732# for the constructor to be able to use it
733Class::MOP::Instance->meta->get_meta_instance;
734
735Class::MOP::Instance->meta->add_method('new' => sub {
736 my $class = shift;
737 my $options = $class->BUILDARGS(@_);
738
739 my $self = $class->meta->new_object(%$options);
740
741 Scalar::Util::weaken($self->{'associated_metaclass'});
742
743 $self;
744});
745
746# pretend the add_method never happenned. it hasn't yet affected anything
747undef Class::MOP::Instance->meta->{_package_cache_flag};
748
86482605 749## --------------------------------------------------------
f0480c45 750## Now close all the Class::MOP::* classes
4d47b77f 751
0b9372a2 752# NOTE:
1d68af04 753# we don't need to inline the
754# constructors or the accessors
755# this only lengthens the compile
756# time of the MOP, and gives us
0b9372a2 757# no actual benefits.
758
759$_->meta->make_immutable(
760 inline_constructor => 0,
761 inline_accessors => 0,
762) for qw/
1d68af04 763 Class::MOP::Package
764 Class::MOP::Module
765 Class::MOP::Class
766
0b9372a2 767 Class::MOP::Attribute
1d68af04 768 Class::MOP::Method
769 Class::MOP::Instance
770
771 Class::MOP::Object
0b9372a2 772
565f0cbb 773 Class::MOP::Method::Generated
1d68af04 774
ba38bf08 775 Class::MOP::Method::Accessor
1d68af04 776 Class::MOP::Method::Constructor
777 Class::MOP::Method::Wrapped
0b9372a2 778/;
b6164407 779
94b19069 7801;
781
782__END__
783
784=pod
785
1d68af04 786=head1 NAME
94b19069 787
788Class::MOP - A Meta Object Protocol for Perl 5
789
94b19069 790=head1 DESCRIPTON
791
127d39a7 792This module is a fully functioning meta object protocol for the
1d68af04 793Perl 5 object system. It makes no attempt to change the behavior or
794characteristics of the Perl 5 object system, only to create a
27e31eaf 795protocol for its manipulation and introspection.
94b19069 796
1d68af04 797That said, it does attempt to create the tools for building a rich
798set of extensions to the Perl 5 object system. Every attempt has been
799made for these tools to keep to the spirit of the Perl 5 object
94b19069 800system that we all know and love.
801
1d68af04 802This documentation is admittedly sparse on details, as time permits
803I will try to improve them. For now, I suggest looking at the items
804listed in the L<SEE ALSO> section for more information. In particular
805the book "The Art of the Meta Object Protocol" was very influential
40483095 806in the development of this system.
807
bfe4d0fc 808=head2 What is a Meta Object Protocol?
809
1d68af04 810A meta object protocol is an API to an object system.
bfe4d0fc 811
1d68af04 812To be more specific, it is a set of abstractions of the components of
813an object system (typically things like; classes, object, methods,
814object attributes, etc.). These abstractions can then be used to both
bfe4d0fc 815inspect and manipulate the object system which they describe.
816
1d68af04 817It can be said that there are two MOPs for any object system; the
818implicit MOP, and the explicit MOP. The implicit MOP handles things
819like method dispatch or inheritance, which happen automatically as
820part of how the object system works. The explicit MOP typically
821handles the introspection/reflection features of the object system.
822All object systems have implicit MOPs, without one, they would not
823work. Explict MOPs however as less common, and depending on the
824language can vary from restrictive (Reflection in Java or C#) to
825wide open (CLOS is a perfect example).
bfe4d0fc 826
e16da3e6 827=head2 Yet Another Class Builder!! Why?
828
1d68af04 829This is B<not> a class builder so much as it is a I<class builder
830B<builder>>. My intent is that an end user does not use this module
831directly, but instead this module is used by module authors to
832build extensions and features onto the Perl 5 object system.
e16da3e6 833
94b19069 834=head2 Who is this module for?
835
1d68af04 836This module is specifically for anyone who has ever created or
837wanted to create a module for the Class:: namespace. The tools which
838this module will provide will hopefully make it easier to do more
839complex things with Perl 5 classes by removing such barriers as
840the need to hack the symbol tables, or understand the fine details
841of method dispatch.
94b19069 842
bfe4d0fc 843=head2 What changes do I have to make to use this module?
844
1d68af04 845This module was designed to be as unintrusive as possible. Many of
846its features are accessible without B<any> change to your existsing
847code at all. It is meant to be a compliment to your existing code and
848not an intrusion on your code base. Unlike many other B<Class::>
849modules, this module B<does not> require you subclass it, or even that
850you C<use> it in within your module's package.
bfe4d0fc 851
1d68af04 852The only features which requires additions to your code are the
2eb717d5 853attribute handling and instance construction features, and these are
1d68af04 854both completely optional features. The only reason for this is because
855Perl 5's object system does not actually have these features built
2eb717d5 856in. More information about this feature can be found below.
bfe4d0fc 857
858=head2 A Note about Performance?
859
1d68af04 860It is a common misconception that explict MOPs are performance drains.
861But this is not a universal truth at all, it is an side-effect of
862specific implementations. For instance, using Java reflection is much
863slower because the JVM cannot take advantage of any compiler
864optimizations, and the JVM has to deal with much more runtime type
865information as well. Reflection in C# is marginally better as it was
866designed into the language and runtime (the CLR). In contrast, CLOS
867(the Common Lisp Object System) was built to support an explicit MOP,
868and so performance is tuned for it.
869
870This library in particular does it's absolute best to avoid putting
871B<any> drain at all upon your code's performance. In fact, by itself
872it does nothing to affect your existing code. So you only pay for
2eb717d5 873what you actually use.
bfe4d0fc 874
550d56db 875=head2 About Metaclass compatibility
876
1d68af04 877This module makes sure that all metaclasses created are both upwards
878and downwards compatible. The topic of metaclass compatibility is
879highly esoteric and is something only encountered when doing deep and
880involved metaclass hacking. There are two basic kinds of metaclass
881incompatibility; upwards and downwards.
550d56db 882
1d68af04 883Upwards metaclass compatibility means that the metaclass of a
884given class is either the same as (or a subclass of) all of the
550d56db 885class's ancestors.
886
1d68af04 887Downward metaclass compatibility means that the metaclasses of a
888given class's anscestors are all either the same as (or a subclass
550d56db 889of) that metaclass.
890
1d68af04 891Here is a diagram showing a set of two classes (C<A> and C<B>) and
892two metaclasses (C<Meta::A> and C<Meta::B>) which have correct
550d56db 893metaclass compatibility both upwards and downwards.
894
895 +---------+ +---------+
896 | Meta::A |<----| Meta::B | <....... (instance of )
1d68af04 897 +---------+ +---------+ <------- (inherits from)
550d56db 898 ^ ^
899 : :
900 +---------+ +---------+
901 | A |<----| B |
902 +---------+ +---------+
903
1d68af04 904As I said this is a highly esoteric topic and one you will only run
905into if you do a lot of subclassing of B<Class::MOP::Class>. If you
906are interested in why this is an issue see the paper
907I<Uniform and safe metaclass composition> linked to in the
550d56db 908L<SEE ALSO> section of this document.
909
aa448b16 910=head2 Using custom metaclasses
911
1d68af04 912Always use the metaclass pragma when using a custom metaclass, this
913will ensure the proper initialization order and not accidentely
914create an incorrect type of metaclass for you. This is a very rare
915problem, and one which can only occur if you are doing deep metaclass
aa448b16 916programming. So in other words, don't worry about it.
917
94b19069 918=head1 PROTOCOLS
919
127d39a7 920The protocol is divided into 4 main sub-protocols:
94b19069 921
922=over 4
923
924=item The Class protocol
925
1d68af04 926This provides a means of manipulating and introspecting a Perl 5
927class. It handles all of symbol table hacking for you, and provides
94b19069 928a rich set of methods that go beyond simple package introspection.
929
552e3d24 930See L<Class::MOP::Class> for more details.
931
94b19069 932=item The Attribute protocol
933
1d68af04 934This provides a consistent represenation for an attribute of a
935Perl 5 class. Since there are so many ways to create and handle
127d39a7 936attributes in Perl 5 OO, this attempts to provide as much of a
1d68af04 937unified approach as possible, while giving the freedom and
94b19069 938flexibility to subclass for specialization.
939
552e3d24 940See L<Class::MOP::Attribute> for more details.
941
94b19069 942=item The Method protocol
943
1d68af04 944This provides a means of manipulating and introspecting methods in
945the Perl 5 object system. As with attributes, there are many ways to
946approach this topic, so we try to keep it pretty basic, while still
94b19069 947making it possible to extend the system in many ways.
948
552e3d24 949See L<Class::MOP::Method> for more details.
94b19069 950
127d39a7 951=item The Instance protocol
952
953This provides a layer of abstraction for creating object instances.
954Since the other layers use this protocol, it is relatively easy to
955change the type of your instances from the default HASH ref to other
956types of references. Several examples are provided in the F<examples/>
957directory included in this distribution.
958
959See L<Class::MOP::Instance> for more details.
960
94b19069 961=back
962
be7677c7 963=head1 FUNCTIONS
964
c1d5345a 965=head2 Constants
966
967=over 4
968
969=item I<IS_RUNNING_ON_5_10>
970
971We set this constant depending on what version perl we are on, this
972allows us to take advantage of new 5.10 features and stay backwards
973compat.
974
975=back
976
448b6e55 977=head2 Utility functions
978
979=over 4
980
981=item B<load_class ($class_name)>
982
1d68af04 983This will load a given C<$class_name> and if it does not have an
448b6e55 984already initialized metaclass, then it will intialize one for it.
127d39a7 985This function can be used in place of tricks like
986C<eval "use $module"> or using C<require>.
448b6e55 987
988=item B<is_class_loaded ($class_name)>
989
1d68af04 990This will return a boolean depending on if the C<$class_name> has
991been loaded.
448b6e55 992
1d68af04 993NOTE: This does a basic check of the symbol table to try and
448b6e55 994determine as best it can if the C<$class_name> is loaded, it
1d68af04 995is probably correct about 99% of the time.
448b6e55 996
b1f5f41d 997=item B<check_package_cache_flag ($pkg)>
e0e4674a 998
127d39a7 999This will return an integer that is managed by C<Class::MOP::Class>
1000to determine if a module's symbol table has been altered.
1001
1002In Perl 5.10 or greater, this flag is package specific. However in
1003versions prior to 5.10, this will use the C<PL_sub_generation> variable
1004which is not package specific.
1005
e0e4674a 1006=item B<get_code_info ($code)>
1007
127d39a7 1008This function returns two values, the name of the package the C<$code>
1009is from and the name of the C<$code> itself. This is used by several
1010elements of the MOP to detemine where a given C<$code> reference is from.
1011
4c105333 1012=item B<subname ($name, $code)>
1013
1014B<NOTE: DO NOT USE THIS FUNCTION, IT IS FOR INTERNAL USE ONLY!>
1015
1016If possible, we will load the L<Sub::Name> module and this will function
1017as C<Sub::Name::subname> does, otherwise it will just return the C<$code>
1018argument.
1019
448b6e55 1020=back
1021
1022=head2 Metaclass cache functions
1023
1d68af04 1024Class::MOP holds a cache of metaclasses, the following are functions
1025(B<not methods>) which can be used to access that cache. It is not
1026recommended that you mess with this, bad things could happen. But if
be7677c7 1027you are brave and willing to risk it, go for it.
1028
1029=over 4
1030
1031=item B<get_all_metaclasses>
1032
1d68af04 1033This will return an hash of all the metaclass instances that have
1034been cached by B<Class::MOP::Class> keyed by the package name.
b9d9fc0b 1035
be7677c7 1036=item B<get_all_metaclass_instances>
1037
1d68af04 1038This will return an array of all the metaclass instances that have
b9d9fc0b 1039been cached by B<Class::MOP::Class>.
1040
be7677c7 1041=item B<get_all_metaclass_names>
1042
1d68af04 1043This will return an array of all the metaclass names that have
b9d9fc0b 1044been cached by B<Class::MOP::Class>.
1045
be7677c7 1046=item B<get_metaclass_by_name ($name)>
1047
127d39a7 1048This will return a cached B<Class::MOP::Class> instance of nothing
1049if no metaclass exist by that C<$name>.
1050
be7677c7 1051=item B<store_metaclass_by_name ($name, $meta)>
1052
127d39a7 1053This will store a metaclass in the cache at the supplied C<$key>.
1054
be7677c7 1055=item B<weaken_metaclass ($name)>
1056
127d39a7 1057In rare cases it is desireable to store a weakened reference in
1058the metaclass cache. This function will weaken the reference to
1059the metaclass stored in C<$name>.
1060
be7677c7 1061=item B<does_metaclass_exist ($name)>
1062
127d39a7 1063This will return true of there exists a metaclass stored in the
1064C<$name> key and return false otherwise.
1065
be7677c7 1066=item B<remove_metaclass_by_name ($name)>
1067
127d39a7 1068This will remove a the metaclass stored in the C<$name> key.
1069
be7677c7 1070=back
1071
552e3d24 1072=head1 SEE ALSO
8b978dd5 1073
552e3d24 1074=head2 Books
8b978dd5 1075
1d68af04 1076There are very few books out on Meta Object Protocols and Metaclasses
1077because it is such an esoteric topic. The following books are really
1078the only ones I have found. If you know of any more, B<I<please>>
a2e85e6c 1079email me and let me know, I would love to hear about them.
1080
8b978dd5 1081=over 4
1082
552e3d24 1083=item "The Art of the Meta Object Protocol"
8b978dd5 1084
552e3d24 1085=item "Advances in Object-Oriented Metalevel Architecture and Reflection"
8b978dd5 1086
b51af7f9 1087=item "Putting MetaClasses to Work"
1088
a2e85e6c 1089=item "Smalltalk: The Language"
1090
94b19069 1091=back
1092
550d56db 1093=head2 Papers
1094
1095=over 4
1096
1097=item Uniform and safe metaclass composition
1098
1d68af04 1099An excellent paper by the people who brought us the original Traits paper.
1100This paper is on how Traits can be used to do safe metaclass composition,
1101and offers an excellent introduction section which delves into the topic of
550d56db 1102metaclass compatibility.
1103
1104L<http://www.iam.unibe.ch/~scg/Archive/Papers/Duca05ySafeMetaclassTrait.pdf>
1105
1106=item Safe Metaclass Programming
1107
1d68af04 1108This paper seems to precede the above paper, and propose a mix-in based
1109approach as opposed to the Traits based approach. Both papers have similar
1110information on the metaclass compatibility problem space.
550d56db 1111
1112L<http://citeseer.ist.psu.edu/37617.html>
1113
1114=back
1115
552e3d24 1116=head2 Prior Art
8b978dd5 1117
1118=over 4
1119
7184ca14 1120=item The Perl 6 MetaModel work in the Pugs project
8b978dd5 1121
1122=over 4
1123
552e3d24 1124=item L<http://svn.openfoundry.org/pugs/perl5/Perl6-MetaModel>
8b978dd5 1125
552e3d24 1126=item L<http://svn.openfoundry.org/pugs/perl5/Perl6-ObjectSpace>
8b978dd5 1127
1128=back
1129
94b19069 1130=back
1131
1d68af04 1132=head2 Articles
f8dfcfb7 1133
1134=over 4
1135
1d68af04 1136=item CPAN Module Review of Class::MOP
f8dfcfb7 1137
1138L<http://www.oreillynet.com/onlamp/blog/2006/06/cpan_module_review_classmop.html>
1139
1140=back
1141
a2e85e6c 1142=head1 SIMILAR MODULES
1143
1d68af04 1144As I have said above, this module is a class-builder-builder, so it is
1145not the same thing as modules like L<Class::Accessor> and
1146L<Class::MethodMaker>. That being said there are very few modules on CPAN
1147with similar goals to this module. The one I have found which is most
1148like this module is L<Class::Meta>, although it's philosophy and the MOP it
1149creates are very different from this modules.
94b19069 1150
a2e85e6c 1151=head1 BUGS
1152
1d68af04 1153All complex software has bugs lurking in it, and this module is no
a2e85e6c 1154exception. If you find a bug please either email me, or add the bug
1155to cpan-RT.
1156
1157=head1 ACKNOWLEDGEMENTS
1158
1159=over 4
1160
b9d9fc0b 1161=item Rob Kinyon
a2e85e6c 1162
1d68af04 1163Thanks to Rob for actually getting the development of this module kick-started.
a2e85e6c 1164
1165=back
1166
1a09d9cc 1167=head1 AUTHORS
94b19069 1168
a2e85e6c 1169Stevan Little E<lt>stevan@iinteractive.comE<gt>
552e3d24 1170
9c8cda90 1171B<with contributions from:>
1172
1173Brandon (blblack) Black
1174
1175Guillermo (groditi) Roditi
1176
9195ddff 1177Matt (mst) Trout
1178
9c8cda90 1179Rob (robkinyon) Kinyon
1180
1181Yuval (nothingmuch) Kogman
1a09d9cc 1182
f430cfa4 1183Scott (konobi) McWhirter
1184
94b19069 1185=head1 COPYRIGHT AND LICENSE
1186
69e3ab0a 1187Copyright 2006-2008 by Infinity Interactive, Inc.
94b19069 1188
1189L<http://www.iinteractive.com>
1190
1191This library is free software; you can redistribute it and/or modify
1d68af04 1192it under the same terms as Perl itself.
94b19069 1193
1194=cut