+sub _wrap {
+ my ($name, $proto, $i, $args, $coderefs, $opts) = @_;
+
+ while ($proto =~ s/(\\?)(\[[^\]]+\]|[^\];])//) {
+ my ($ref, $sigil) = ($1, $2);
+ $sigil = $1 if $sigil =~ /^\[([^\]]+)\]/;
+
+ my $cur = "\$_[$i]";
+
+ if ($ref) {
+ if (length $sigil > 1) {
+ my $code = "my \$r = $opts->{ref}($cur); ";
+ my @branches = map {
+ my $subcall = _wrap(
+ $name, $proto, ($i + 1), $args . "$_\{$cur}, ", $coderefs, $opts
+ );
+ "if (\$r eq '$reftypes{$_}') { $subcall }";
+ } split //, $sigil;
+ $code .= join ' els', @branches, "e { $opts->{wrong_ref} }";
+ return $code;
+ } else {
+ $args .= "$sigil\{$cur}, ";
+ }
+ } elsif ($sigil =~ /[\@\%]/) {
+ $args .= '@_[' . $i . '..$#_]';
+ } elsif ($sigil =~ /\&/) {
+ my %h = do { my $c; map { $_ => $c++ } @$coderefs };
+ my $j;
+ if (exists $h{$i}) {
+ $j = int $h{$i};
+ } else {
+ push @$coderefs, $i;
+ $j = $#{$coderefs};
+ }
+ $args .= "sub{&{\$c[$j]}}, ";
+ } elsif ($sigil eq '_') {
+ $args .= "((\@_ > $i) ? $cur : \$_), ";
+ } else {
+ $args .= "$cur, ";
+ }
+ } continue {
+ ++$i;
+ }
+
+ $args =~ s/,\s*$//;
+
+ return "$name($args)";
+}
+
+sub _check_name {
+ my ($name) = @_;
+ croak 'No subroutine specified' unless $name;
+
+ my $proto;
+ my $r = ref $name;
+ if (!$r) {
+ $proto = prototype $name;
+ } elsif ($r eq 'HASH') {
+ croak 'Forced prototype hash reference must contain exactly one key/value pair' unless keys %$name == 1;
+ ($name, $proto) = %$name;
+ } else {
+ croak 'Unhandled ' . $r . ' reference as first argument';
+ }
+