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