This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
make <expr> always overload if expr is overloaded
[perl5.git] / lib / overload.t
index 8a632a5..df91544 100644 (file)
@@ -47,7 +47,8 @@ sub numify { 0 + "${$_[0]}" } # Not needed, additional overhead
 package main;
 
 $| = 1;
-use Test::More tests => 4826;
+BEGIN { require './test.pl' }
+plan tests => 4980;
 
 use Scalar::Util qw(tainted);
 
@@ -706,13 +707,7 @@ is($c, "bareword");
   sub iter { my ($x) = @_; return undef if $$x < 0; return $$x--; }
 }
 
-# XXX iterator overload not intended to work with CORE::GLOBAL?
-if (defined &CORE::GLOBAL::glob) {
-  is('1', '1');
-  is('1', '1');
-  is('1', '1');
-}
-else {
+{
   my $iter = iterator->new(5);
   my $acc = '';
   my $out;
@@ -1372,11 +1367,11 @@ foreach my $op (qw(<=> == != < <= > >=)) {
     $obj = bless do {my $a; \$a}, 'Shklitza';
     $ref = $obj;
 
-    is ($obj, "CLiK KLAK");
-    is ($ref, "CLiK KLAK");
+    is ("$obj", "CLiK KLAK");
+    is ("$ref", "CLiK KLAK");
 
     weaken $ref;
-    is ($ref, "CLiK KLAK");
+    is ("$ref", "CLiK KLAK");
 
     bless $obj, 'Ksshfwoom';
 
@@ -1722,38 +1717,24 @@ foreach my $op (qw(<=> == != < <= > >=)) {
            #   SCALAR FETCH: initial, sub=,  sub+=, eval-return,
            #          STORE: copy, mutator
            # for fallback, we just stringify, so eval-return and copy skipped
-           #
-           # XXX TODO concat LH overload with fallback calls "" and FETCH
-           # too often
-           if ($_ eq '.') {
-               push @tests, [ 18, $e, "(=)($_=)", '("")("")',
-                       [ 3, 4, 2,     2, 4, 1 ], 1 ];
-           }
-           else {
-               push @tests, [ 18, $e, "(=)($_=)", '("")',
-                       [ 3, 4, 2,     2, 3, 1 ], 1 ];
-           }
+
+           push @tests, [ 18, $e, "(=)($_=)", '("")',
+                           [ 3, 4, 2,     2, 3, 1 ], 1 ];
 
            $subs{$_} =
                "do { my \$arg = %s; \$_[2] ? (3 $op \$arg) : (\$arg $op 3) }";
            # ARRAY  FETCH: initial
            # SCALAR FETCH: initial eval-return,
-           # with fallback, we just stringify, so eval-return skipped
-
-           # XXX TODO concat overload with fallback calls FETCH too often
-           if ($_ eq '.') {
-               push @tests, [ 18, "%s $op 3", "($_)", '("")',
-                               [ 1, 2, 0,     1, 2, 0 ], 1 ];
-               push @tests, [ 18, "3 $op %s", "($_)", '("")',
-                               [ 1, 2, 0,     1, 2, 0 ], 1 ];
-           }
-           else {
-               push @tests, [ 18, "%s $op 3", "($_)", '("")',
-                               [ 1, 2, 0,     1, 1, 0 ], 1 ];
-               next if $_ eq 'x'; # repeat only overloads on LHS
-               push @tests, [ 18, "3 $op %s", "($_)", '("")',
-                               [ 1, 2, 0,     1, 1, 0 ], 1 ];
-           }
+           # with fallback, we just stringify, so eval-return skipped,
+           #    but an extra FETCH happens in sub"", except for 'x',
+           #    which passes a copy of the RV to sub"", avoiding the
+           #    second FETCH
+
+           push @tests, [ 18, "%s $op 3", "($_)", '("")',
+                           [ 1, 2, 0,     1, ($_ eq '.' ? 2 : 1), 0 ], 1 ];
+           next if $_ eq 'x'; # repeat only overloads on LHS
+           push @tests, [ 18, "3 $op %s", "($_)", '("")',
+                           [ 1, 2, 0,     1, 2, 0 ], 1 ];
        }
 
        for (qw(++ --)) {
@@ -1812,10 +1793,7 @@ foreach my $op (qw(<=> == != < <= > >=)) {
 
        # note: this is testing unary qr, not binary =~
        $subs{qr} = '(qr/%s/)';
-       # XXX TODO qr overload with fallback calls "" and FETCH too often
-       #push @tests, [ "abc", '"abc" =~ (%s)', '(qr)', '("")', [ 1, 2, 0 ], 0 ];
-       push @tests, [ "abc", '"abc" =~ (%s)', '(qr)', '("")("")',
-                           [ 1, 2, 0,  1, 5, 0 ], 0 ];
+       push @tests, [ "abc", '"abc" =~ (%s)', '(qr)', '("")', [ 1, 2, 0 ], 0 ];
 
        $e = '"abc" ~~ (%s)';
        $subs{'~~'} = $e;
@@ -1832,17 +1810,7 @@ foreach my $op (qw(<=> == != < <= > >=)) {
        # long as the tied and untied versions return the same value.
        # The flags below are chosen to test all uses of tryAMAGICftest_MG
        for (qw(r e f l t T)) {
-           # XXX TODO -X overload with fallback calls FETCH too often
-           # XXX and -t calls "" too often too
-           #push @tests, [ 'TEST', "-$_ (%s)", '(-X)', '("")', [ 1, 2, 0 ], 0 ];
-           if ($_ eq 't') {
-               push @tests, [ 'TEST', "-$_ (%s)", '(-X)', '("")("")',
-                                   [ 1, 2, 0,    1, 5, 0 ], 0 ];
-           }
-           else {
-               push @tests, [ 'TEST', "-$_ (%s)", '(-X)', '("")',
-                                   [ 1, 2, 0,    1, 3, 0 ], 0 ];
-           }
+           push @tests, [ 'TEST', "-$_ (%s)", '(-X)', '("")', [ 1, 2, 0 ], 0 ];
        }
 
        $subs{'${}'} = '%s';
@@ -1865,7 +1833,16 @@ foreach my $op (qw(<=> == != < <= > >=)) {
        push @tests, [ \*RT57012A, '*RT57012B = *{%s}; our $RT57012B',
                '(*{})', undef, [ 1, 1, 0 ], 0 ];
 
-       # XXX TODO: '<>'
+       my $iter_text = ("some random text\n" x 100) . $^X;
+       open my $iter_fh, '<', \$iter_text
+           or die "open of \$iter_text gave ($!)\n";
+       $subs{'<>'} = '<$iter_fh>';
+       push @tests, [ $iter_fh, '<%s>', '(<>)', undef, [ 1, 1, 0 ], 1 ];
+
+       # eval should do tie, overload on its arg before checking taint */
+       push @tests, [ '1;', 'eval q(eval %s); $@ =~ /Insecure/',
+               '("")', '("")', [ 1, 2, 0 ], 0 ];
+
 
        for my $sub (keys %subs) {
            my $term = $subs{$sub};
@@ -1961,7 +1938,6 @@ foreach my $op (qw(<=> == != < <= > >=)) {
                        "<$plain_term> taint of expected return");
 
            for my $ov_pkg (qw(RT57012_OV RT57012_OV_FB)) {
-               # the deref ops don't support fallback
                next if $ov_pkg eq 'RT57012_OV_FB'
                        and  not defined $exp_fb_funcs;
                my ($exp_fetch_a, $exp_fetch_s, $exp_store) =
@@ -1974,7 +1950,9 @@ foreach my $op (qw(<=> == != < <= > >=)) {
                $ta[0]    = bless [ $tainted_val ], $ov_pkg;
                my $oload = bless [ $tainted_val ], $ov_pkg;
 
-               for my $var ('$ta[0]', '$ts', '$oload') {
+               for my $var ('$ta[0]', '$ts', '$oload',
+                           ($sub_term eq '<%s>' ? '${ts}' : ())
+               ) {
 
                    $funcs = '';
                    $fetches = 0;
@@ -1990,7 +1968,6 @@ foreach my $op (qw(<=> == != < <= > >=)) {
                    $res = "$res" if $res_term =~ /\+\+|--/;
                    is(tainted($res), $exp_taint,
                            "$desc taint of result return");
-                   #XXX$res = "$res";
                    is($res, $exp, "$desc return value");
                    my $fns =($ov_pkg eq 'RT57012_OV_FB')
                                ? $exp_fb_funcs : $exp_funcs;
@@ -2013,4 +1990,183 @@ foreach my $op (qw(<=> == != < <= > >=)) {
     }
 }
 
+# Test overload from the main package
+fresh_perl_is
+ '$^W = 1; use overload q\""\ => sub {"ning"}; print bless []',
+ 'ning',
+  { switches => ['-wl'], stderr => 1 },
+ 'use overload from the main package'
+;
+
+{
+    package blessed_methods;
+    use overload '+' => sub {};
+    bless overload::Method __PACKAGE__,'+';
+    eval { overload::Method __PACKAGE__,'+' };
+    ::is($@, '', 'overload::Method and blessed overload methods');
+}
+
+{
+    # fallback to 'cmp' and '<=>' with heterogeneous operands
+    # [perl #71286]
+    my $not_found = 'no method found';
+    my $used = 0;
+    package CmpBase;
+    sub new {
+        my $n = $_[1] || 0;
+        bless \$n, ref $_[0] || $_[0];
+    }
+    sub cmp {
+        $used = \$_[0];
+        (${$_[0]} <=> ${$_[1]}) * ($_[2] ? -1 : 1);
+    }
+
+    package NCmp;
+    use base 'CmpBase';
+    use overload '<=>' => 'cmp';
+
+    package SCmp;
+    use base 'CmpBase';
+    use overload 'cmp' => 'cmp';
+
+    package main;
+    my $n = NCmp->new(5);
+    my $s = SCmp->new(3);
+    my $res;
+
+    eval { $res = $n > $s; };
+    $res = $not_found if $@ =~ /$not_found/;
+    is($res, 1, 'A>B using A<=> when B overloaded, no B<=>');
+
+    eval { $res = $s < $n; };
+    $res = $not_found if $@ =~ /$not_found/;
+    is($res, 1, 'A<B using B<=> when A overloaded, no A<=>');
+
+    eval { $res = $s lt $n; };
+    $res = $not_found if $@ =~ /$not_found/;
+    is($res, 1, 'A lt B using A:cmp when B overloaded, no B:cmp');
+
+    eval { $res = $n gt $s; };
+    $res = $not_found if $@ =~ /$not_found/;
+    is($res, 1, 'A gt B using B:cmp when A overloaded, no A:cmp');
+
+    my $o = NCmp->new(9);
+    $res = $n < $o;
+    is($used, \$n, 'A < B uses <=> from A in preference to B');
+
+    my $t = SCmp->new(7);
+    $res = $s lt $t;
+    is($used, \$s, 'A lt B uses cmp from A in preference to B');
+}
+
+{
+    # Combinatorial testing of 'fallback' and 'nomethod'
+    # [perl #71286]
+    package NuMB;
+    use overload '0+' => sub { ${$_[0]}; },
+        '""' => 'str';
+    sub new {
+        my $self = shift;
+        my $n = @_ ? shift : 0;
+        bless my $obj = \$n, ref $self || $self;
+    }
+    sub str {
+        no strict qw/refs/;
+        my $s = "(${$_[0]} ";
+        $s .= "nomethod, " if defined ${ref($_[0]).'::(nomethod'};
+        my $fb = ${ref($_[0]).'::()'};
+        $s .= "fb=" . (defined $fb ? 0 + $fb : 'undef') . ")";
+    }
+    sub nomethod { "${$_[0]}.nomethod"; }
+
+    # create classes for tests
+    package main;
+    my @falls = (0, 'undef', 1);
+    my @nomethods = ('', 'nomethod');
+    my $not_found = 'no method found';
+    for my $fall (@falls) {
+        for my $nomethod (@nomethods) {
+            my $nomethod_decl = $nomethod
+                ? $nomethod . "=>'nomethod'," : '';
+            eval qq{
+                    package NuMB$fall$nomethod;
+                    use base qw/NuMB/;
+                    use overload $nomethod_decl
+                    fallback => $fall;
+                };
+        }
+    }
+
+    # operation and precedence of 'fallback' and 'nomethod'
+    # for all combinations with 2 overloaded operands
+    for my $nomethod2 (@nomethods) {
+        for my $nomethod1 (@nomethods) {
+            for my $fall2 (@falls) {
+                my $pack2 = "NuMB$fall2$nomethod2";
+                for my $fall1 (@falls) {
+                    my $pack1 = "NuMB$fall1$nomethod1";
+                    my ($test, $out, $exp);
+                    eval qq{
+                            my \$x = $pack1->new(2);
+                            my \$y = $pack2->new(3);
+                            \$test = "\$x" . ' * ' . "\$y";
+                            \$out = \$x * \$y;
+                        };
+                    $out = $not_found if $@ =~ /$not_found/;
+                    $exp = $nomethod1 ? '2.nomethod' :
+                         $nomethod2 ? '3.nomethod' :
+                         $fall1 eq '1' && $fall2 eq '1' ? 6
+                         : $not_found;
+                    is($out, $exp, "$test --> $exp");
+                }
+            }
+        }
+    }
+
+    # operation of 'fallback' and 'nomethod'
+    # where the other operand is not overloaded
+    for my $nomethod (@nomethods) {
+        for my $fall (@falls) {
+            my ($test, $out, $exp);
+            eval qq{
+                    my \$x = NuMB$fall$nomethod->new(2);
+                    \$test = "\$x" . ' * 3';
+                    \$out = \$x * 3;
+                };
+            $out = $not_found if $@ =~ /$not_found/;
+            $exp = $nomethod ? '2.nomethod' :
+                $fall eq '1' ? 6
+                : $not_found;
+            is($out, $exp, "$test --> $exp");
+
+            eval qq{
+                    my \$x = NuMB$fall$nomethod->new(2);
+                    \$test = '3 * ' . "\$x";
+                    \$out = 3 * \$x;
+                };
+            $out = $not_found if $@ =~ /$not_found/;
+            is($out, $exp, "$test --> $exp");
+        }
+    }
+}
+
+# since 5.6 overloaded <> was leaving an extra arg on the stack!
+
+{
+    package Iter1;
+    use overload '<>' => sub { 11 };
+    package main;
+    my $a = bless [], 'Iter1';
+    my $x;
+    my @a = (10, ($x = <$a>), 12);
+    is ($a[0], 10, 'Iter1: a[0]');
+    is ($a[1], 11, 'Iter1: a[1]');
+    is ($a[2], 12, 'Iter1: a[2]');
+    @a = (10, ($x .= <$a>), 12);
+    is ($a[0],   10, 'Iter1: a[0] concat');
+    is ($a[1], 1111, 'Iter1: a[1] concat');
+    is ($a[2],   12, 'Iter1: a[2] concat');
+}
+
+
 # EOF