| 1 | package perl5i::1::Meta; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | # Be very careful not to import anything. | ||
| 7 | require Carp; | ||
| 8 | require mro; | ||
| 9 | |||
| 10 | require perl5i::1::Meta::Instance; | ||
| 11 | require perl5i::1::Meta::Class; | ||
| 12 | |||
| 13 | sub UNIVERSAL::mo { | ||
| 14 | return perl5i::1::Meta->new($_[0]); | ||
| 15 | } | ||
| 16 | |||
| 17 | sub new { | ||
| 18 | my($class, $thing) = @_; | ||
| 19 | return bless \$thing, ref $thing ? "perl5i::1::Meta::Instance" : "perl5i::1::Meta::Class"; | ||
| 20 | } | ||
| 21 | |||
| 22 | sub ISA { | ||
| 23 | my $class = $_[0]->class; | ||
| 24 | |||
| 25 | no strict 'refs'; | ||
| 26 | return @{$class.'::ISA'}; | ||
| 27 | } | ||
| 28 | |||
| 29 | sub linear_isa { | ||
| 30 | my $self = shift; | ||
| 31 | my $class = $self->class; | ||
| 32 | |||
| 33 | # get_linear_isa() does not return UNIVERSAL | ||
| 34 | my @extra; | ||
| 35 | @extra = qw(UNIVERSAL) unless $class eq 'UNIVERSAL'; | ||
| 36 | |||
| 37 | return @{mro::get_linear_isa($class)}, @extra; | ||
| 38 | } | ||
| 39 | |||
| 40 | |||
| 41 | # A single place to put the "method not found" error. | ||
| 42 | my $method_not_found = sub { | ||
| 43 | my $class = shift; | ||
| 44 | my $method = shift; | ||
| 45 | |||
| 46 | Carp::croak sprintf q[Can't locate object method "%s" via package "%s"], | ||
| 47 | $method, $class; | ||
| 48 | }; | ||
| 49 | |||
| 50 | |||
| 51 | # caller() will return if its inside an eval, need to skip over those. | ||
| 52 | my $find_method = sub { | ||
| 53 | my $method; | ||
| 54 | my $height = 2; | ||
| 55 | do { | ||
| 56 | $method = (caller($height))[3]; | ||
| 57 | $height++; | ||
| 58 | } until( !defined $method or $method ne '(eval)' ); | ||
| 59 | |||
| 60 | return $method; | ||
| 61 | }; | ||
| 62 | |||
| 63 | |||
| 64 | sub super { | ||
| 65 | my $self = shift; | ||
| 66 | my $class = $self->class; | ||
| 67 | |||
| 68 | my $fq_method = $find_method->(); | ||
| 69 | Carp::croak "super() called outside a method" unless $fq_method; | ||
| 70 | |||
| 71 | my($parent, $method) = $fq_method =~ /^(.*)::(\w+)$/; | ||
| 72 | |||
| 73 | Carp::croak sprintf qq["%s" is not a parent class of "%s"], $parent, $class | ||
| 74 | unless $class->isa($parent); | ||
| 75 | |||
| 76 | my @isa = $self->linear_isa(); | ||
| 77 | |||
| 78 | while(@isa) { | ||
| 79 | my $class = shift @isa; | ||
| 80 | last if $class eq $parent; | ||
| 81 | } | ||
| 82 | |||
| 83 | for (@isa) { | ||
| 84 | my $code = $_->can($method); | ||
| 85 | @_ = ($$self, @_); | ||
| 86 | goto &$code if $code; | ||
| 87 | } | ||
| 88 | |||
| 89 | $class->$method_not_found($method); | ||
| 90 | } | ||
| 91 | |||
| 92 | 1; |