play jenga
[gitmo/Moo.git] / lib / Moo / HandleMoose.pm
index 08f49a6..1103126 100644 (file)
@@ -3,12 +3,18 @@ package Moo::HandleMoose;
 use strictures 1;
 use Moo::_Utils;
 
-sub import { inject_all() }
+our %TYPE_MAP;
+
+our $SETUP_DONE;
+
+sub import { return if $SETUP_DONE; inject_all(); $SETUP_DONE = 1; }
 
 sub inject_all {
   require Class::MOP;
   inject_fake_metaclass_for($_) for grep $_ ne 'Moo::Object', keys %Moo::MAKERS;
   inject_fake_metaclass_for($_) for keys %Moo::Role::INFO;
+  require Moose::Meta::Method::Constructor;
+  @Moo::HandleMoose::FakeConstructor::ISA = 'Moose::Meta::Method::Constructor';
 }
 
 sub inject_fake_metaclass_for {
@@ -21,6 +27,13 @@ sub inject_fake_metaclass_for {
 
 our %DID_INJECT;
 
+{
+  package Moo::HandleMoose::FakeConstructor;
+
+  sub _uninlined_body { \&Moose::Object::new }
+}
+    
+
 sub inject_real_metaclass_for {
   my ($name) = @_;
   return Class::MOP::get_metaclass_by_name($name) if $DID_INJECT{$name};
@@ -37,18 +50,46 @@ sub inject_real_metaclass_for {
   my %methods = %{Role::Tiny->_concrete_methods_of($name)};
   my @attrs;
   {
+    # This local is completely not required for roles but harmless
     local @{_getstash($name)}{keys %methods};
     foreach my $name (keys %$attr_specs) {
-      push @attrs, $meta->add_attribute($name => %{$attr_specs->{$name}});
+      my %spec = %{$attr_specs->{$name}};
+      $spec{is} = 'ro' if $spec{is} eq 'lazy' or $spec{is} eq 'rwp';
+      delete $spec{asserter};
+      if (my $isa = $spec{isa}) {
+        $spec{isa} = do {
+          if (my $mapped = $TYPE_MAP{$isa}) {
+            $mapped->();
+          } else {
+            Moose::Meta::TypeConstraint->new(
+              constraint => sub { eval { &$isa; 1 } }
+            );
+          }
+        };
+      }
+      push @attrs, $meta->add_attribute($name => %spec);
     }
   }
-  unless ($am_role) {
+  if ($am_role) {
+    my $info = $Moo::Role::INFO{$name};
+    $meta->add_required_methods(@{$info->{requires}});
+    foreach my $modifier (@{$info->{modifiers}}) {
+      my ($type, @args) = @$modifier;
+      $meta->${\"add_${type}_method_modifier"}(@args);
+    }
+  } else {
     foreach my $attr (@attrs) {
       foreach my $method (@{$attr->associated_methods}) {
         $method->{body} = $name->can($method->name);
       }
     }
+    bless(
+      $meta->find_method_by_name('new'),
+      'Moo::HandleMoose::FakeConstructor',
+    );
   }
+  $meta->add_role(Class::MOP::class_of($_))
+    for keys %{$Role::Tiny::APPLIED_TO{$name}};
   $DID_INJECT{$name} = 1;
   $meta;
 }