5f62a98ca16a7d02702a16d4814b62da733e0ae7
[gitmo/Role-Tiny.git] / lib / Moo / _Utils.pm
1 package Moo::_Utils;
2
3 no warnings 'once'; # guard against -w
4
5 sub _getglob { \*{$_[0]} }
6 sub _getstash { \%{"$_[0]::"} }
7
8 BEGIN {
9   *lt_5_8_3 = $] < 5.008003
10     ? sub () { 1 }
11     : sub () { 0 }
12   ;
13 }
14
15 use strictures 1;
16 use Module::Runtime qw(require_module);
17 use base qw(Exporter);
18 use Moo::_mro;
19
20 our @EXPORT = qw(
21     _getglob _install_modifier _load_module _maybe_load_module
22     _get_linear_isa
23 );
24
25 sub _install_modifier {
26   my ($into, $type, $name, $code) = @_;
27
28   if (my $to_modify = $into->can($name)) { # CMM will throw for us if not
29     require Sub::Defer;
30     Sub::Defer::undefer_sub($to_modify);
31   }
32
33   Class::Method::Modifiers::install_modifier(@_);
34 }
35
36 our %MAYBE_LOADED;
37
38 sub _load_module {
39   (my $proto = $_[0]) =~ s/::/\//g;
40   return 1 if $INC{"${proto}.pm"};
41   # can't just ->can('can') because a sub-package Foo::Bar::Baz
42   # creates a 'Baz::' key in Foo::Bar's symbol table
43   return 1 if grep !/::$/, keys %{_getstash($_[0])||{}};
44   require_module($_[0]);
45   return 1;
46 }
47
48 sub _maybe_load_module {
49   return $MAYBE_LOADED{$_[0]} if exists $MAYBE_LOADED{$_[0]};
50   (my $proto = $_[0]) =~ s/::/\//g;
51   local $@;
52   if (eval { require "${proto}.pm"; 1 }) {
53     $MAYBE_LOADED{$_[0]} = 1;
54   } else {
55     if (exists $INC{"${proto}.pm"}) {
56       warn "$_[0] exists but failed to load with error: $@";
57     }
58     $MAYBE_LOADED{$_[0]} = 0;
59   }
60   return $MAYBE_LOADED{$_[0]};
61 }
62
63 sub _get_linear_isa {
64     return mro::get_linear_isa($_[0]);
65 }
66
67 our $_in_global_destruction = 0;
68 END { $_in_global_destruction = 1 }
69
70 sub STANDARD_DESTROY {
71   my $self = shift;
72
73   my $e = do {
74     local $?;
75     local $@;
76     eval {
77       $self->DEMOLISHALL($_in_global_destruction);
78     };
79     $@;
80   };
81
82   no warnings 'misc';
83   die $e if $e; # rethrow
84 }
85
86 1;