also include attributes from attribute traits on inflate
[gitmo/Moo.git] / lib / Moo / HandleMoose.pm
1 package Moo::HandleMoose;
2
3 use strictures 1;
4 use Moo::_Utils;
5 use B qw(perlstring);
6
7 our %TYPE_MAP;
8
9 our $SETUP_DONE;
10
11 sub import { return if $SETUP_DONE; inject_all(); $SETUP_DONE = 1; }
12
13 sub inject_all {
14   require Class::MOP;
15   inject_fake_metaclass_for($_)
16     for grep $_ ne 'Moo::Object', do { no warnings 'once'; keys %Moo::MAKERS };
17   inject_fake_metaclass_for($_) for keys %Moo::Role::INFO;
18   require Moose::Meta::Method::Constructor;
19   @Moo::HandleMoose::FakeConstructor::ISA = 'Moose::Meta::Method::Constructor';
20 }
21
22 sub maybe_reinject_fake_metaclass_for {
23   my ($name) = @_;
24   our %DID_INJECT;
25   if (delete $DID_INJECT{$name}) {
26     unless ($Moo::Role::INFO{$name}) {
27       Moo->_constructor_maker_for($name)->install_delayed;
28     }
29     inject_fake_metaclass_for($name);
30   }
31 }
32
33 sub inject_fake_metaclass_for {
34   my ($name) = @_;
35   require Class::MOP;
36   require Moo::HandleMoose::FakeMetaClass;
37   Class::MOP::store_metaclass_by_name(
38     $name, bless({ name => $name }, 'Moo::HandleMoose::FakeMetaClass')
39   );
40   require Moose::Util::TypeConstraints;
41   if ($Moo::Role::INFO{$name}) {
42     Moose::Util::TypeConstraints::find_or_create_does_type_constraint($name);
43   } else {
44     Moose::Util::TypeConstraints::find_or_create_isa_type_constraint($name);
45   }
46 }
47
48 {
49   package Moo::HandleMoose::FakeConstructor;
50
51   sub _uninlined_body { \&Moose::Object::new }
52 }
53     
54
55 sub inject_real_metaclass_for {
56   my ($name) = @_;
57   our %DID_INJECT;
58   return Class::MOP::get_metaclass_by_name($name) if $DID_INJECT{$name};
59   require Moose; require Moo; require Moo::Role; require Scalar::Util;
60   Class::MOP::remove_metaclass_by_name($name);
61   my ($am_role, $meta, $attr_specs, $attr_order) = do {
62     if (my $info = $Moo::Role::INFO{$name}) {
63       my @attr_info = @{$info->{attributes}||[]};
64       (1, Moose::Meta::Role->initialize($name),
65        { @attr_info },
66        [ @attr_info[grep !($_ % 2), 0..$#attr_info] ]
67       )
68     } elsif ( my $cmaker = Moo->_constructor_maker_for($name) ) {
69       my $specs = $cmaker->all_attribute_specs;
70       (0, Moose::Meta::Class->initialize($name), $specs,
71        [ sort { $specs->{$a}{index} <=> $specs->{$b}{index} } keys %$specs ]
72       );
73     } else {
74        # This codepath is used if $name does not exist in $Moo::MAKERS
75        (0, Moose::Meta::Class->initialize($name), {}, [] )
76     }
77   };
78
79   for my $spec (values %$attr_specs) {
80     if (my $inflators = delete $spec->{moosify}) {
81       $_->($spec) for @$inflators;
82     }
83   }
84
85   my %methods = %{Role::Tiny->_concrete_methods_of($name)};
86
87   # if stuff gets added afterwards, _maybe_reset_handlemoose should
88   # trigger the recreation of the metaclass but we need to ensure the
89   # Role::Tiny cache is cleared so we don't confuse Moo itself.
90   if (my $info = $Role::Tiny::INFO{$name}) {
91     delete $info->{methods};
92   }
93
94   # needed to ensure the method body is stable and get things named
95   Sub::Defer::undefer_sub($_) for grep defined, values %methods;
96   my @attrs;
97   {
98     # This local is completely not required for roles but harmless
99     local @{_getstash($name)}{keys %methods};
100     my %seen_name;
101     foreach my $name (@$attr_order) {
102       $seen_name{$name} = 1;
103       my %spec = %{$attr_specs->{$name}};
104       my %spec_map = (
105         map { $_->name => $_->init_arg }
106         grep { $_->has_init_arg }
107         $meta->attribute_metaclass->meta->get_all_attributes
108       );
109       for my $trait (@{$spec{traits}||[]}) {
110         my $trait_meta = Moose::Util::resolve_metatrait_alias('Attribute', $trait)->meta;
111         my @trait_attrs =
112           map { $trait_meta->get_attribute($_) }
113           $trait_meta->get_attribute_list;
114         for my $trait_attr (@trait_attrs) {
115           my $orig = $trait_attr->original_options;
116           my $init_arg = (exists $orig->{init_arg} ? $orig->{init_arg} : $trait_attr->name)
117             or next;
118           $spec_map{$trait_attr->name} = $init_arg;
119         }
120       }
121
122       $spec{is} = 'ro' if $spec{is} eq 'lazy' or $spec{is} eq 'rwp';
123       my $coerce = $spec{coerce};
124       if (my $isa = $spec{isa}) {
125         my $tc = $spec{isa} = do {
126           if (my $mapped = $TYPE_MAP{$isa}) {
127             my $type = $mapped->();
128             Scalar::Util::blessed($type) && $type->isa("Moose::Meta::TypeConstraint")
129               or die "error inflating attribute '$name' for package '$_[0]': \$TYPE_MAP{$isa} did not return a valid type constraint'";
130             $coerce ? $type->create_child_type(name => $type->name) : $type;
131           } else {
132             Moose::Meta::TypeConstraint->new(
133               constraint => sub { eval { &$isa; 1 } }
134             );
135           }
136         };
137         if ($coerce) {
138           $tc->coercion(Moose::Meta::TypeCoercion->new)
139              ->_compiled_type_coercion($coerce);
140           $spec{coerce} = 1;
141         }
142       } elsif ($coerce) {
143         my $attr = perlstring($name);
144         my $tc = Moose::Meta::TypeConstraint->new(
145                    constraint => sub { die "This is not going to work" },
146                    inlined => sub {
147                       'my $r = $_[42]{'.$attr.'}; $_[42]{'.$attr.'} = 1; $r'
148                    },
149                  );
150         $tc->coercion(Moose::Meta::TypeCoercion->new)
151            ->_compiled_type_coercion($coerce);
152         $spec{isa} = $tc;
153         $spec{coerce} = 1;
154       }
155       %spec =
156         map { $spec_map{$_} => $spec{$_} }
157         grep { exists $spec_map{$_} }
158         keys %spec;
159       push @attrs, $meta->add_attribute($name => %spec);
160     }
161     foreach my $mouse (do { our %MOUSE; @{$MOUSE{$name}||[]} }) {
162       foreach my $attr ($mouse->get_all_attributes) {
163         my %spec = %{$attr};
164         delete @spec{qw(
165           associated_class associated_methods __METACLASS__
166           provides curries
167         )};
168         my $name = delete $spec{name};
169         next if $seen_name{$name}++;
170         push @attrs, $meta->add_attribute($name => %spec);
171       }
172     }
173   }
174   for my $meth_name (keys %methods) {
175     my $meth_code = $methods{$meth_name};
176     $meta->add_method($meth_name, $meth_code) if $meth_code;
177   }
178
179   if ($am_role) {
180     my $info = $Moo::Role::INFO{$name};
181     $meta->add_required_methods(@{$info->{requires}});
182     foreach my $modifier (@{$info->{modifiers}}) {
183       my ($type, @args) = @$modifier;
184       $meta->${\"add_${type}_method_modifier"}(@args);
185     }
186   } else {
187     foreach my $attr (@attrs) {
188       foreach my $method (@{$attr->associated_methods}) {
189         $method->{body} = $name->can($method->name);
190       }
191     }
192     bless(
193       $meta->find_method_by_name('new'),
194       'Moo::HandleMoose::FakeConstructor',
195     );
196   }
197   $meta->add_role(Class::MOP::class_of($_))
198     for grep !/\|/ && $_ ne $name, # reject Foo|Bar and same-role-as-self
199       do { no warnings 'once'; keys %{$Role::Tiny::APPLIED_TO{$name}} };
200   $DID_INJECT{$name} = 1;
201   $meta;
202 }
203
204 1;