clean up trait test and add check for init_arg => undef
[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||$_->name }
106         (
107           (grep { $_->has_init_arg }
108              $meta->attribute_metaclass->meta->get_all_attributes),
109           grep { $_->has_init_arg ? defined($_->init_arg) : 1 }
110           map {
111             my $meta = Moose::Util::resolve_metatrait_alias('Attribute', $_)
112                          ->meta;
113             map $meta->get_attribute($_), $meta->get_attribute_list
114           }  @{$spec{traits}||[]}
115         )
116       );
117
118       $spec{is} = 'ro' if $spec{is} eq 'lazy' or $spec{is} eq 'rwp';
119       my $coerce = $spec{coerce};
120       if (my $isa = $spec{isa}) {
121         my $tc = $spec{isa} = do {
122           if (my $mapped = $TYPE_MAP{$isa}) {
123             my $type = $mapped->();
124             Scalar::Util::blessed($type) && $type->isa("Moose::Meta::TypeConstraint")
125               or die "error inflating attribute '$name' for package '$_[0]': \$TYPE_MAP{$isa} did not return a valid type constraint'";
126             $coerce ? $type->create_child_type(name => $type->name) : $type;
127           } else {
128             Moose::Meta::TypeConstraint->new(
129               constraint => sub { eval { &$isa; 1 } }
130             );
131           }
132         };
133         if ($coerce) {
134           $tc->coercion(Moose::Meta::TypeCoercion->new)
135              ->_compiled_type_coercion($coerce);
136           $spec{coerce} = 1;
137         }
138       } elsif ($coerce) {
139         my $attr = perlstring($name);
140         my $tc = Moose::Meta::TypeConstraint->new(
141                    constraint => sub { die "This is not going to work" },
142                    inlined => sub {
143                       'my $r = $_[42]{'.$attr.'}; $_[42]{'.$attr.'} = 1; $r'
144                    },
145                  );
146         $tc->coercion(Moose::Meta::TypeCoercion->new)
147            ->_compiled_type_coercion($coerce);
148         $spec{isa} = $tc;
149         $spec{coerce} = 1;
150       }
151       %spec =
152         map { $spec_map{$_} => $spec{$_} }
153         grep { exists $spec_map{$_} }
154         keys %spec;
155       push @attrs, $meta->add_attribute($name => %spec);
156     }
157     foreach my $mouse (do { our %MOUSE; @{$MOUSE{$name}||[]} }) {
158       foreach my $attr ($mouse->get_all_attributes) {
159         my %spec = %{$attr};
160         delete @spec{qw(
161           associated_class associated_methods __METACLASS__
162           provides curries
163         )};
164         my $name = delete $spec{name};
165         next if $seen_name{$name}++;
166         push @attrs, $meta->add_attribute($name => %spec);
167       }
168     }
169   }
170   for my $meth_name (keys %methods) {
171     my $meth_code = $methods{$meth_name};
172     $meta->add_method($meth_name, $meth_code) if $meth_code;
173   }
174
175   if ($am_role) {
176     my $info = $Moo::Role::INFO{$name};
177     $meta->add_required_methods(@{$info->{requires}});
178     foreach my $modifier (@{$info->{modifiers}}) {
179       my ($type, @args) = @$modifier;
180       $meta->${\"add_${type}_method_modifier"}(@args);
181     }
182   } else {
183     foreach my $attr (@attrs) {
184       foreach my $method (@{$attr->associated_methods}) {
185         $method->{body} = $name->can($method->name);
186       }
187     }
188     bless(
189       $meta->find_method_by_name('new'),
190       'Moo::HandleMoose::FakeConstructor',
191     );
192   }
193   $meta->add_role(Class::MOP::class_of($_))
194     for grep !/\|/ && $_ ne $name, # reject Foo|Bar and same-role-as-self
195       do { no warnings 'once'; keys %{$Role::Tiny::APPLIED_TO{$name}} };
196   $DID_INJECT{$name} = 1;
197   $meta;
198 }
199
200 1;