This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
undo temporarily reverted lib/overload.t tests"
[perl5.git] / lib / overload.t
1 #!./perl -T
2
3 BEGIN {
4     chdir 't' if -d 't';
5     @INC = '../lib';
6     require Config;
7     if (($Config::Config{'extensions'} !~ m!\bList/Util\b!) ){
8         print "1..0 # Skip -- Perl configured without List::Util module\n";
9         exit 0;
10     }
11 }
12
13 package Oscalar;
14 use overload ( 
15                                 # Anonymous subroutines:
16 '+'     =>      sub {new Oscalar $ {$_[0]}+$_[1]},
17 '-'     =>      sub {new Oscalar
18                        $_[2]? $_[1]-${$_[0]} : ${$_[0]}-$_[1]},
19 '<=>'   =>      sub {new Oscalar
20                        $_[2]? $_[1]-${$_[0]} : ${$_[0]}-$_[1]},
21 'cmp'   =>      sub {new Oscalar
22                        $_[2]? ($_[1] cmp ${$_[0]}) : (${$_[0]} cmp $_[1])},
23 '*'     =>      sub {new Oscalar ${$_[0]}*$_[1]},
24 '/'     =>      sub {new Oscalar 
25                        $_[2]? $_[1]/${$_[0]} :
26                          ${$_[0]}/$_[1]},
27 '%'     =>      sub {new Oscalar
28                        $_[2]? $_[1]%${$_[0]} : ${$_[0]}%$_[1]},
29 '**'    =>      sub {new Oscalar
30                        $_[2]? $_[1]**${$_[0]} : ${$_[0]}-$_[1]},
31
32 qw(
33 ""      stringify
34 0+      numify)                 # Order of arguments insignificant
35 );
36
37 sub new {
38   my $foo = $_[1];
39   bless \$foo, $_[0];
40 }
41
42 sub stringify { "${$_[0]}" }
43 sub numify { 0 + "${$_[0]}" }   # Not needed, additional overhead
44                                 # comparing to direct compilation based on
45                                 # stringify
46
47 package main;
48
49 $| = 1;
50 BEGIN { require './test.pl' }
51 plan tests => 5059;
52
53 use Scalar::Util qw(tainted);
54
55 $a = new Oscalar "087";
56 $b= "$a";
57
58 is($b, $a);
59 is($b, "087");
60 is(ref $a, "Oscalar");
61 is($a, $a);
62 is($a, "087");
63
64 $c = $a + 7;
65
66 is(ref $c, "Oscalar");
67 isnt($c, $a);
68 is($c, "94");
69
70 $b=$a;
71
72 is(ref $a, "Oscalar");
73
74 $b++;
75
76 is(ref $b, "Oscalar");
77 is($a, "087");
78 is($b, "88");
79 is(ref $a, "Oscalar");
80
81 $c=$b;
82 $c-=$a;
83
84 is(ref $c, "Oscalar");
85 is($a, "087");
86 is($c, "1");
87 is(ref $a, "Oscalar");
88
89 $b=1;
90 $b+=$a;
91
92 is(ref $b, "Oscalar");
93 is($a, "087");
94 is($b, "88");
95 is(ref $a, "Oscalar");
96
97 eval q[ package Oscalar; use overload ('++' => sub { $ {$_[0]}++;$_[0] } ) ];
98
99 $b=$a;
100
101 is(ref $a, "Oscalar");
102
103 $b++;
104
105 is(ref $b, "Oscalar");
106 is($a, "087");
107 is($b, "88");
108 is(ref $a, "Oscalar");
109
110 package Oscalar;
111 $dummy=bless \$dummy;           # Now cache of method should be reloaded
112 package main;
113
114 $b=$a;
115 $b++;                           
116
117 is(ref $b, "Oscalar");
118 is($a, "087");
119 is($b, "88");
120 is(ref $a, "Oscalar");
121
122 undef $b;                       # Destroying updates tables too...
123
124 eval q[package Oscalar; use overload ('++' => sub { $ {$_[0]} += 2; $_[0] } ) ];
125
126 $b=$a;
127
128 is(ref $a, "Oscalar");
129
130 $b++;
131
132 is(ref $b, "Oscalar");
133 is($a, "087");
134 is($b, "88");
135 is(ref $a, "Oscalar");
136
137 package Oscalar;
138 $dummy=bless \$dummy;           # Now cache of method should be reloaded
139 package main;
140
141 $b++;                           
142
143 is(ref $b, "Oscalar");
144 is($a, "087");
145 is($b, "90");
146 is(ref $a, "Oscalar");
147
148 $b=$a;
149 $b++;
150
151 is(ref $b, "Oscalar");
152 is($a, "087");
153 is($b, "89");
154 is(ref $a, "Oscalar");
155
156
157 ok($b? 1:0);
158
159 eval q[ package Oscalar; use overload ('=' => sub {$main::copies++; 
160                                                    package Oscalar;
161                                                    local $new=$ {$_[0]};
162                                                    bless \$new } ) ];
163
164 $b=new Oscalar "$a";
165
166 is(ref $b, "Oscalar");
167 is($a, "087");
168 is($b, "087");
169 is(ref $a, "Oscalar");
170
171 $b++;
172
173 is(ref $b, "Oscalar");
174 is($a, "087");
175 is($b, "89");
176 is(ref $a, "Oscalar");
177 is($copies, undef);
178
179 $b+=1;
180
181 is(ref $b, "Oscalar");
182 is($a, "087");
183 is($b, "90");
184 is(ref $a, "Oscalar");
185 is($copies, undef);
186
187 $b=$a;
188 $b+=1;
189
190 is(ref $b, "Oscalar");
191 is($a, "087");
192 is($b, "88");
193 is(ref $a, "Oscalar");
194 is($copies, undef);
195
196 $b=$a;
197 $b++;
198
199 is(ref $b, "Oscalar");
200 is($a, "087");
201 is($b, "89");
202 is(ref $a, "Oscalar");
203 is($copies, 1);
204
205 eval q[package Oscalar; use overload ('+=' => sub {$ {$_[0]} += 3*$_[1];
206                                                    $_[0] } ) ];
207 $c=new Oscalar;                 # Cause rehash
208
209 $b=$a;
210 $b+=1;
211
212 is(ref $b, "Oscalar");
213 is($a, "087");
214 is($b, "90");
215 is(ref $a, "Oscalar");
216 is($copies, 2);
217
218 $b+=$b;
219
220 is(ref $b, "Oscalar");
221 is($b, "360");
222 is($copies, 2);
223 $b=-$b;
224
225 is(ref $b, "Oscalar");
226 is($b, "-360");
227 is($copies, 2);
228
229 $b=abs($b);
230
231 is(ref $b, "Oscalar");
232 is($b, "360");
233 is($copies, 2);
234
235 $b=abs($b);
236
237 is(ref $b, "Oscalar");
238 is($b, "360");
239 is($copies, 2);
240
241 eval q[package Oscalar; 
242        use overload ('x' => sub {new Oscalar ( $_[2] ? "_.$_[1]._" x $ {$_[0]}
243                                               : "_.${$_[0]}._" x $_[1])}) ];
244
245 $a=new Oscalar "yy";
246 $a x= 3;
247 is($a, "_.yy.__.yy.__.yy._");
248
249 eval q[package Oscalar; 
250        use overload ('.' => sub {new Oscalar ( $_[2] ? 
251                                               "_.$_[1].__.$ {$_[0]}._"
252                                               : "_.$ {$_[0]}.__.$_[1]._")}) ];
253
254 $a=new Oscalar "xx";
255
256 is("b${a}c", "_._.b.__.xx._.__.c._");
257
258 # Check inheritance of overloading;
259 {
260   package OscalarI;
261   @ISA = 'Oscalar';
262 }
263
264 $aI = new OscalarI "$a";
265 is(ref $aI, "OscalarI");
266 is("$aI", "xx");
267 is($aI, "xx");
268 is("b${aI}c", "_._.b.__.xx._.__.c._");
269
270 # Here we test blessing to a package updates hash
271
272 eval "package Oscalar; no overload '.'";
273
274 is("b${a}", "_.b.__.xx._");
275 $x="1";
276 bless \$x, Oscalar;
277 is("b${a}c", "bxxc");
278 new Oscalar 1;
279 is("b${a}c", "bxxc");
280
281 # Negative overloading:
282
283 $na = eval { ~$a };
284 like($@, qr/no method found/);
285
286 # Check AUTOLOADING:
287
288 *Oscalar::AUTOLOAD = 
289   sub { *{"Oscalar::$AUTOLOAD"} = sub {"_!_" . shift() . "_!_"} ;
290         goto &{"Oscalar::$AUTOLOAD"}};
291
292 eval "package Oscalar; sub comple; use overload '~' => 'comple'";
293
294 $na = eval { ~$a };             # Hash was not updated
295 like($@, qr/no method found/);
296
297 bless \$x, Oscalar;
298
299 $na = eval { ~$a };             # Hash updated
300 warn "'$na', $@" if $@;
301 ok !$@;
302 is($na, '_!_xx_!_');
303
304 $na = 0;
305
306 $na = eval { ~$aI };            # Hash was not updated
307 like($@, qr/no method found/);
308
309 bless \$x, OscalarI;
310
311 $na = eval { ~$aI };
312 print $@;
313
314 ok(!$@);
315 is($na, '_!_xx_!_');
316
317 eval "package Oscalar; sub rshft; use overload '>>' => 'rshft'";
318
319 $na = eval { $aI >> 1 };        # Hash was not updated
320 like($@, qr/no method found/);
321
322 bless \$x, OscalarI;
323
324 $na = 0;
325
326 $na = eval { $aI >> 1 };
327 print $@;
328
329 ok(!$@);
330 is($na, '_!_xx_!_');
331
332 # warn overload::Method($a, '0+'), "\n";
333 is(overload::Method($a, '0+'), \&Oscalar::numify);
334 is(overload::Method($aI,'0+'), \&Oscalar::numify);
335 ok(overload::Overloaded($aI));
336 ok(!overload::Overloaded('overload'));
337
338 ok(! defined overload::Method($aI, '<<'));
339 ok(! defined overload::Method($a, '<'));
340
341 like (overload::StrVal($aI), qr/^OscalarI=SCALAR\(0x[\da-fA-F]+\)$/);
342 is(overload::StrVal(\$aI), "@{[\$aI]}");
343
344 # Check overloading by methods (specified deep in the ISA tree).
345 {
346   package OscalarII;
347   @ISA = 'OscalarI';
348   sub Oscalar::lshft {"_<<_" . shift() . "_<<_"}
349   eval "package OscalarI; use overload '<<' => 'lshft', '|' => 'lshft'";
350 }
351
352 $aaII = "087";
353 $aII = \$aaII;
354 bless $aII, 'OscalarII';
355 bless \$fake, 'OscalarI';               # update the hash
356 is(($aI | 3), '_<<_xx_<<_');
357 # warn $aII << 3;
358 is(($aII << 3), '_<<_087_<<_');
359
360 {
361   BEGIN { $int = 7; overload::constant 'integer' => sub {$int++; shift}; }
362   $out = 2**10;
363 }
364 is($int, 9);
365 is($out, 1024);
366 is($int, 9);
367 {
368   BEGIN { overload::constant 'integer' => sub {$int++; shift()+1}; }
369   eval q{$out = 42};
370 }
371 is($int, 10);
372 is($out, 43);
373
374 $foo = 'foo';
375 $foo1 = 'f\'o\\o';
376 {
377   BEGIN { $q = $qr = 7; 
378           overload::constant 'q' => sub {$q++; push @q, shift, ($_[1] || 'none'); shift},
379                              'qr' => sub {$qr++; push @qr, shift, ($_[1] || 'none'); shift}; }
380   $out = 'foo';
381   $out1 = 'f\'o\\o';
382   $out2 = "a\a$foo,\,";
383   /b\b$foo.\./;
384 }
385
386 is($out, 'foo');
387 is($out, $foo);
388 is($out1, 'f\'o\\o');
389 is($out1, $foo1);
390 is($out2, "a\afoo,\,");
391 is("@q", "foo q f'o\\\\o q a\\a qq ,\\, qq");
392 is($q, 11);
393 is("@qr", "b\\b qq .\\. qq");
394 is($qr, 9);
395
396 {
397   $_ = '!<b>!foo!<-.>!';
398   BEGIN { overload::constant 'q' => sub {push @q1, shift, ($_[1] || 'none'); "_<" . (shift) . ">_"},
399                              'qr' => sub {push @qr1, shift, ($_[1] || 'none'); "!<" . (shift) . ">!"}; }
400   $out = 'foo';
401   $out1 = 'f\'o\\o';
402   $out2 = "a\a$foo,\,";
403   $res = /b\b$foo.\./;
404   $a = <<EOF;
405 oups
406 EOF
407   $b = <<'EOF';
408 oups1
409 EOF
410   $c = bareword;
411   m'try it';
412   s'first part'second part';
413   s/yet another/tail here/;
414   tr/A-Z/a-z/;
415 }
416
417 is($out, '_<foo>_');
418 is($out1, '_<f\'o\\o>_');
419 is($out2, "_<a\a>_foo_<,\,>_");
420 is("@q1", "foo q f'o\\\\o q a\\a qq ,\\, qq oups
421  qq oups1
422  q second part q tail here s A-Z tr a-z tr");
423 is("@qr1", "b\\b qq .\\. qq try it q first part q yet another qq");
424 is($res, 1);
425 is($a, "_<oups
426 >_");
427 is($b, "_<oups1
428 >_");
429 is($c, "bareword");
430
431 {
432   package symbolic;             # Primitive symbolic calculator
433   use overload nomethod => \&wrap, '""' => \&str, '0+' => \&num,
434       '=' => \&cpy, '++' => \&inc, '--' => \&dec;
435
436   sub new { shift; bless ['n', @_] }
437   sub cpy {
438     my $self = shift;
439     bless [@$self], ref $self;
440   }
441   sub inc { $_[0] = bless ['++', $_[0], 1]; }
442   sub dec { $_[0] = bless ['--', $_[0], 1]; }
443   sub wrap {
444     my ($obj, $other, $inv, $meth) = @_;
445     if ($meth eq '++' or $meth eq '--') {
446       @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
447       return $obj;
448     }
449     ($obj, $other) = ($other, $obj) if $inv;
450     bless [$meth, $obj, $other];
451   }
452   sub str {
453     my ($meth, $a, $b) = @{+shift};
454     $a = 'u' unless defined $a;
455     if (defined $b) {
456       "[$meth $a $b]";
457     } else {
458       "[$meth $a]";
459     }
460   } 
461   my %subr = ( 'n' => sub {$_[0]} );
462   foreach my $op (split " ", $overload::ops{with_assign}) {
463     $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
464   }
465   my @bins = qw(binary 3way_comparison num_comparison str_comparison);
466   foreach my $op (split " ", "@overload::ops{ @bins }") {
467     $subr{$op} = eval "sub {shift() $op shift()}";
468   }
469   foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
470     $subr{$op} = eval "sub {$op shift()}";
471   }
472   $subr{'++'} = $subr{'+'};
473   $subr{'--'} = $subr{'-'};
474   
475   sub num {
476     my ($meth, $a, $b) = @{+shift};
477     my $subr = $subr{$meth} 
478       or die "Do not know how to ($meth) in symbolic";
479     $a = $a->num if ref $a eq __PACKAGE__;
480     $b = $b->num if ref $b eq __PACKAGE__;
481     $subr->($a,$b);
482   }
483   sub TIESCALAR { my $pack = shift; $pack->new(@_) }
484   sub FETCH { shift }
485   sub nop {  }          # Around a bug
486   sub vars { my $p = shift; tie($_, $p), $_->nop foreach @_; }
487   sub STORE { 
488     my $obj = shift; 
489     $#$obj = 1; 
490     $obj->[1] = shift;
491   }
492 }
493
494 {
495   my $foo = new symbolic 11;
496   my $baz = $foo++;
497   is((sprintf "%d", $foo), '12');
498   is((sprintf "%d", $baz), '11');
499   my $bar = $foo;
500   $baz = ++$foo;
501   is((sprintf "%d", $foo), '13');
502   is((sprintf "%d", $bar), '12');
503   is((sprintf "%d", $baz), '13');
504   my $ban = $foo;
505   $baz = ($foo += 1);
506   is((sprintf "%d", $foo), '14');
507   is((sprintf "%d", $bar), '12');
508   is((sprintf "%d", $baz), '14');
509   is((sprintf "%d", $ban), '13');
510   $baz = 0;
511   $baz = $foo++;
512   is((sprintf "%d", $foo), '15');
513   is((sprintf "%d", $baz), '14');
514   is("$foo", '[++ [+= [++ [++ [n 11] 1] 1] 1] 1]');
515 }
516
517 {
518   my $iter = new symbolic 2;
519   my $side = new symbolic 1;
520   my $cnt = $iter;
521   
522   while ($cnt) {
523     $cnt = $cnt - 1;            # The "simple" way
524     $side = (sqrt(1 + $side**2) - 1)/$side;
525   }
526   my $pi = $side*(2**($iter+2));
527   is("$side", '[/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]] 2]]] 1] [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]');
528   is((sprintf "%f", $pi), '3.182598');
529 }
530
531 {
532   my $iter = new symbolic 2;
533   my $side = new symbolic 1;
534   my $cnt = $iter;
535   
536   while ($cnt--) {
537     $side = (sqrt(1 + $side**2) - 1)/$side;
538   }
539   my $pi = $side*(2**($iter+2));
540   is("$side", '[/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]] 2]]] 1] [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]');
541   is((sprintf "%f", $pi), '3.182598');
542 }
543
544 {
545   my ($a, $b);
546   symbolic->vars($a, $b);
547   my $c = sqrt($a**2 + $b**2);
548   $a = 3; $b = 4;
549   is((sprintf "%d", $c), '5');
550   $a = 12; $b = 5;
551   is((sprintf "%d", $c), '13');
552 }
553
554 {
555   package symbolic1;            # Primitive symbolic calculator
556   # Mutator inc/dec
557   use overload nomethod => \&wrap, '""' => \&str, '0+' => \&num, '=' => \&cpy;
558
559   sub new { shift; bless ['n', @_] }
560   sub cpy {
561     my $self = shift;
562     bless [@$self], ref $self;
563   }
564   sub wrap {
565     my ($obj, $other, $inv, $meth) = @_;
566     if ($meth eq '++' or $meth eq '--') {
567       @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
568       return $obj;
569     }
570     ($obj, $other) = ($other, $obj) if $inv;
571     bless [$meth, $obj, $other];
572   }
573   sub str {
574     my ($meth, $a, $b) = @{+shift};
575     $a = 'u' unless defined $a;
576     if (defined $b) {
577       "[$meth $a $b]";
578     } else {
579       "[$meth $a]";
580     }
581   } 
582   my %subr = ( 'n' => sub {$_[0]} );
583   foreach my $op (split " ", $overload::ops{with_assign}) {
584     $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
585   }
586   my @bins = qw(binary 3way_comparison num_comparison str_comparison);
587   foreach my $op (split " ", "@overload::ops{ @bins }") {
588     $subr{$op} = eval "sub {shift() $op shift()}";
589   }
590   foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
591     $subr{$op} = eval "sub {$op shift()}";
592   }
593   $subr{'++'} = $subr{'+'};
594   $subr{'--'} = $subr{'-'};
595   
596   sub num {
597     my ($meth, $a, $b) = @{+shift};
598     my $subr = $subr{$meth} 
599       or die "Do not know how to ($meth) in symbolic";
600     $a = $a->num if ref $a eq __PACKAGE__;
601     $b = $b->num if ref $b eq __PACKAGE__;
602     $subr->($a,$b);
603   }
604   sub TIESCALAR { my $pack = shift; $pack->new(@_) }
605   sub FETCH { shift }
606   sub vars { my $p = shift; tie($_, $p) foreach @_; }
607   sub STORE { 
608     my $obj = shift; 
609     $#$obj = 1; 
610     $obj->[1] = shift;
611   }
612 }
613
614 {
615   my $foo = new symbolic1 11;
616   my $baz = $foo++;
617   is((sprintf "%d", $foo), '12');
618   is((sprintf "%d", $baz), '11');
619   my $bar = $foo;
620   $baz = ++$foo;
621   is((sprintf "%d", $foo), '13');
622   is((sprintf "%d", $bar), '12');
623   is((sprintf "%d", $baz), '13');
624   my $ban = $foo;
625   $baz = ($foo += 1);
626   is((sprintf "%d", $foo), '14');
627   is((sprintf "%d", $bar), '12');
628   is((sprintf "%d", $baz), '14');
629   is((sprintf "%d", $ban), '13');
630   $baz = 0;
631   $baz = $foo++;
632   is((sprintf "%d", $foo), '15');
633   is((sprintf "%d", $baz), '14');
634   is("$foo", '[++ [+= [++ [++ [n 11] 1] 1] 1] 1]');
635 }
636
637 {
638   my $iter = new symbolic1 2;
639   my $side = new symbolic1 1;
640   my $cnt = $iter;
641   
642   while ($cnt) {
643     $cnt = $cnt - 1;            # The "simple" way
644     $side = (sqrt(1 + $side**2) - 1)/$side;
645   }
646   my $pi = $side*(2**($iter+2));
647   is("$side", '[/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]] 2]]] 1] [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]');
648   is((sprintf "%f", $pi), '3.182598');
649 }
650
651 {
652   my $iter = new symbolic1 2;
653   my $side = new symbolic1 1;
654   my $cnt = $iter;
655   
656   while ($cnt--) {
657     $side = (sqrt(1 + $side**2) - 1)/$side;
658   }
659   my $pi = $side*(2**($iter+2));
660   is("$side", '[/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]] 2]]] 1] [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]');
661   is((sprintf "%f", $pi), '3.182598');
662 }
663
664 {
665   my ($a, $b);
666   symbolic1->vars($a, $b);
667   my $c = sqrt($a**2 + $b**2);
668   $a = 3; $b = 4;
669   is((sprintf "%d", $c), '5');
670   $a = 12; $b = 5;
671   is((sprintf "%d", $c), '13');
672 }
673
674 {
675   package two_face;             # Scalars with separate string and
676                                 # numeric values.
677   sub new { my $p = shift; bless [@_], $p }
678   use overload '""' => \&str, '0+' => \&num, fallback => 1;
679   sub num {shift->[1]}
680   sub str {shift->[0]}
681 }
682
683 {
684   my $seven = new two_face ("vii", 7);
685   is((sprintf "seven=$seven, seven=%d, eight=%d", $seven, $seven+1),
686         'seven=vii, seven=7, eight=8');
687   is(scalar ($seven =~ /i/), '1');
688 }
689
690 {
691   package sorting;
692   use overload 'cmp' => \&comp;
693   sub new { my ($p, $v) = @_; bless \$v, $p }
694   sub comp { my ($x,$y) = @_; ($$x * 3 % 10) <=> ($$y * 3 % 10) or $$x cmp $$y }
695 }
696 {
697   my @arr = map sorting->new($_), 0..12;
698   my @sorted1 = sort @arr;
699   my @sorted2 = map $$_, @sorted1;
700   is("@sorted2", '0 10 7 4 1 11 8 5 12 2 9 6 3');
701 }
702 {
703   package iterator;
704   use overload '<>' => \&iter;
705   sub new { my ($p, $v) = @_; bless \$v, $p }
706   sub iter { my ($x) = @_; return undef if $$x < 0; return $$x--; }
707 }
708
709 {
710   my $iter = iterator->new(5);
711   my $acc = '';
712   my $out;
713   $acc .= " $out" while $out = <${iter}>;
714   is($acc, ' 5 4 3 2 1 0');
715   $iter = iterator->new(5);
716   is(scalar <${iter}>, '5');
717   $acc = '';
718   $acc .= " $out" while $out = <$iter>;
719   is($acc, ' 4 3 2 1 0');
720 }
721 {
722   package deref;
723   use overload '%{}' => \&hderef, '&{}' => \&cderef, 
724     '*{}' => \&gderef, '${}' => \&sderef, '@{}' => \&aderef;
725   sub new { my ($p, $v) = @_; bless \$v, $p }
726   sub deref {
727     my ($self, $key) = (shift, shift);
728     my $class = ref $self;
729     bless $self, 'deref::dummy'; # Disable overloading of %{} 
730     my $out = $self->{$key};
731     bless $self, $class;        # Restore overloading
732     $out;
733   }
734   sub hderef {shift->deref('h')}
735   sub aderef {shift->deref('a')}
736   sub cderef {shift->deref('c')}
737   sub gderef {shift->deref('g')}
738   sub sderef {shift->deref('s')}
739 }
740 {
741   my $deref = bless { h => { foo => 5 , fake => 23 },
742                       c => sub {return shift() + 34},
743                       's' => \123,
744                       a => [11..13],
745                       g => \*srt,
746                     }, 'deref';
747   # Hash:
748   my @cont = sort %$deref;
749   if ("\t" eq "\011") { # ASCII
750       is("@cont", '23 5 fake foo');
751   } 
752   else {                # EBCDIC alpha-numeric sort order
753       is("@cont", 'fake foo 23 5');
754   }
755   my @keys = sort keys %$deref;
756   is("@keys", 'fake foo');
757   my @val = sort values %$deref;
758   is("@val", '23 5');
759   is($deref->{foo}, 5);
760   is(defined $deref->{bar}, '');
761   my $key;
762   @keys = ();
763   push @keys, $key while $key = each %$deref;
764   @keys = sort @keys;
765   is("@keys", 'fake foo');
766   is(exists $deref->{bar}, '');
767   is(exists $deref->{foo}, 1);
768   # Code:
769   is($deref->(5), 39);
770   is(&$deref(6), 40);
771   sub xxx_goto { goto &$deref }
772   is(xxx_goto(7), 41);
773   my $srt = bless { c => sub {$b <=> $a}
774                   }, 'deref';
775   *srt = \&$srt;
776   my @sorted = sort srt 11, 2, 5, 1, 22;
777   is("@sorted", '22 11 5 2 1');
778   # Scalar
779   is($$deref, 123);
780   # Code
781   @sorted = sort $srt 11, 2, 5, 1, 22;
782   is("@sorted", '22 11 5 2 1');
783   # Array
784   is("@$deref", '11 12 13');
785   is($#$deref, '2');
786   my $l = @$deref;
787   is($l, 3);
788   is($deref->[2], '13');
789   $l = pop @$deref;
790   is($l, 13);
791   $l = 1;
792   is($deref->[$l], '12');
793   # Repeated dereference
794   my $double = bless { h => $deref,
795                      }, 'deref';
796   is($double->{foo}, 5);
797 }
798
799 {
800   package two_refs;
801   use overload '%{}' => \&gethash, '@{}' => sub { ${shift()} };
802   sub new { 
803     my $p = shift; 
804     bless \ [@_], $p;
805   }
806   sub gethash {
807     my %h;
808     my $self = shift;
809     tie %h, ref $self, $self;
810     \%h;
811   }
812
813   sub TIEHASH { my $p = shift; bless \ shift, $p }
814   my %fields;
815   my $i = 0;
816   $fields{$_} = $i++ foreach qw{zero one two three};
817   sub STORE { 
818     my $self = ${shift()};
819     my $key = $fields{shift()};
820     defined $key or die "Out of band access";
821     $$self->[$key] = shift;
822   }
823   sub FETCH { 
824     my $self = ${shift()};
825     my $key = $fields{shift()};
826     defined $key or die "Out of band access";
827     $$self->[$key];
828   }
829 }
830
831 my $bar = new two_refs 3,4,5,6;
832 $bar->[2] = 11;
833 is($bar->{two}, 11);
834 $bar->{three} = 13;
835 is($bar->[3], 13);
836
837 {
838   package two_refs_o;
839   @ISA = ('two_refs');
840 }
841
842 $bar = new two_refs_o 3,4,5,6;
843 $bar->[2] = 11;
844 is($bar->{two}, 11);
845 $bar->{three} = 13;
846 is($bar->[3], 13);
847
848 {
849   package two_refs1;
850   use overload '%{}' => sub { ${shift()}->[1] },
851                '@{}' => sub { ${shift()}->[0] };
852   sub new { 
853     my $p = shift; 
854     my $a = [@_];
855     my %h;
856     tie %h, $p, $a;
857     bless \ [$a, \%h], $p;
858   }
859   sub gethash {
860     my %h;
861     my $self = shift;
862     tie %h, ref $self, $self;
863     \%h;
864   }
865
866   sub TIEHASH { my $p = shift; bless \ shift, $p }
867   my %fields;
868   my $i = 0;
869   $fields{$_} = $i++ foreach qw{zero one two three};
870   sub STORE { 
871     my $a = ${shift()};
872     my $key = $fields{shift()};
873     defined $key or die "Out of band access";
874     $a->[$key] = shift;
875   }
876   sub FETCH { 
877     my $a = ${shift()};
878     my $key = $fields{shift()};
879     defined $key or die "Out of band access";
880     $a->[$key];
881   }
882 }
883
884 $bar = new two_refs_o 3,4,5,6;
885 $bar->[2] = 11;
886 is($bar->{two}, 11);
887 $bar->{three} = 13;
888 is($bar->[3], 13);
889
890 {
891   package two_refs1_o;
892   @ISA = ('two_refs1');
893 }
894
895 $bar = new two_refs1_o 3,4,5,6;
896 $bar->[2] = 11;
897 is($bar->{two}, 11);
898 $bar->{three} = 13;
899 is($bar->[3], 13);
900
901 {
902   package B;
903   use overload bool => sub { ${+shift} };
904 }
905
906 my $aaa;
907 { my $bbbb = 0; $aaa = bless \$bbbb, B }
908
909 is !$aaa, 1;
910
911 unless ($aaa) {
912   pass();
913 } else {
914   fail();
915 }
916
917 # check that overload isn't done twice by join
918 { my $c = 0;
919   package Join;
920   use overload '""' => sub { $c++ };
921   my $x = join '', bless([]), 'pq', bless([]);
922   main::is $x, '0pq1';
923 };
924
925 # Test module-specific warning
926 {
927     # check the Odd number of arguments for overload::constant warning
928     my $a = "" ;
929     local $SIG{__WARN__} = sub {$a = $_[0]} ;
930     $x = eval ' overload::constant "integer" ; ' ;
931     is($a, "");
932     use warnings 'overload' ;
933     $x = eval ' overload::constant "integer" ; ' ;
934     like($a, qr/^Odd number of arguments for overload::constant at/);
935 }
936
937 {
938     # check the '$_[0]' is not an overloadable type warning
939     my $a = "" ;
940     local $SIG{__WARN__} = sub {$a = $_[0]} ;
941     $x = eval ' overload::constant "fred" => sub {} ; ' ;
942     is($a, "");
943     use warnings 'overload' ;
944     $x = eval ' overload::constant "fred" => sub {} ; ' ;
945     like($a, qr/^'fred' is not an overloadable type at/);
946 }
947
948 {
949     # check the '$_[1]' is not a code reference warning
950     my $a = "" ;
951     local $SIG{__WARN__} = sub {$a = $_[0]} ;
952     $x = eval ' overload::constant "integer" => 1; ' ;
953     is($a, "");
954     use warnings 'overload' ;
955     $x = eval ' overload::constant "integer" => 1; ' ;
956     like($a, qr/^'1' is not a code reference at/);
957 }
958
959 {
960     # check the invalid argument warning [perl #74098]
961     my $a = "" ;
962     local $SIG{__WARN__} = sub {$a = $_[0]} ;
963     $x = eval ' use overload "~|_|~" => sub{} ' ;
964     is($a, "");
965     use warnings 'overload' ;
966     $x = eval ' use overload "~|_|~" => sub{} ' ;
967     like($a, qr/^overload arg '~\|_\|~' is invalid at \(eval \d+\) line /,
968         'invalid arg warning');
969 }
970
971 {
972   my $c = 0;
973   package ov_int1;
974   use overload '""'    => sub { 3+shift->[0] },
975                '0+'    => sub { 10+shift->[0] },
976                'int'   => sub { 100+shift->[0] };
977   sub new {my $p = shift; bless [shift], $p}
978
979   package ov_int2;
980   use overload '""'    => sub { 5+shift->[0] },
981                '0+'    => sub { 30+shift->[0] },
982                'int'   => sub { 'ov_int1'->new(1000+shift->[0]) };
983   sub new {my $p = shift; bless [shift], $p}
984
985   package noov_int;
986   use overload '""'    => sub { 2+shift->[0] },
987                '0+'    => sub { 9+shift->[0] };
988   sub new {my $p = shift; bless [shift], $p}
989
990   package main;
991
992   my $x = new noov_int 11;
993   my $int_x = int $x;
994   main::is("$int_x", 20);
995   $x = new ov_int1 31;
996   $int_x = int $x;
997   main::is("$int_x", 131);
998   $x = new ov_int2 51;
999   $int_x = int $x;
1000   main::is("$int_x", 1054);
1001 }
1002
1003 # make sure that we don't infinitely recurse
1004 {
1005   my $c = 0;
1006   package Recurse;
1007   use overload '""'    => sub { shift },
1008                '0+'    => sub { shift },
1009                'bool'  => sub { shift },
1010                fallback => 1;
1011   my $x = bless([]);
1012   # For some reason beyond me these have to be oks rather than likes.
1013   main::ok("$x" =~ /Recurse=ARRAY/);
1014   main::ok($x);
1015   main::ok($x+0 =~ qr/Recurse=ARRAY/);
1016 }
1017
1018 # BugID 20010422.003
1019 package Foo;
1020
1021 use overload
1022   'bool' => sub { return !$_[0]->is_zero() || undef; }
1023 ;
1024  
1025 sub is_zero
1026   {
1027   my $self = shift;
1028   return $self->{var} == 0;
1029   }
1030
1031 sub new
1032   {
1033   my $class = shift;
1034   my $self =  {};
1035   $self->{var} = shift;
1036   bless $self,$class;
1037   }
1038
1039 package main;
1040
1041 use strict;
1042
1043 my $r = Foo->new(8);
1044 $r = Foo->new(0);
1045
1046 is(($r || 0), 0);
1047
1048 package utf8_o;
1049
1050 use overload 
1051   '""'  =>  sub { return $_[0]->{var}; }
1052   ;
1053   
1054 sub new
1055   {
1056     my $class = shift;
1057     my $self =  {};
1058     $self->{var} = shift;
1059     bless $self,$class;
1060   }
1061
1062 package main;
1063
1064
1065 my $utfvar = new utf8_o 200.2.1;
1066 is("$utfvar", 200.2.1); # 223 - stringify
1067 is("a$utfvar", "a".200.2.1); # 224 - overload via sv_2pv_flags
1068
1069 # 225..227 -- more %{} tests.  Hangs in 5.6.0, okay in later releases.
1070 # Basically this example implements strong encapsulation: if Hderef::import()
1071 # were to eval the overload code in the caller's namespace, the privatisation
1072 # would be quite transparent.
1073 package Hderef;
1074 use overload '%{}' => sub { (caller(0))[0] eq 'Foo' ? $_[0] : die "zap" };
1075 package Foo;
1076 @Foo::ISA = 'Hderef';
1077 sub new { bless {}, shift }
1078 sub xet { @_ == 2 ? $_[0]->{$_[1]} :
1079           @_ == 3 ? ($_[0]->{$_[1]} = $_[2]) : undef }
1080 package main;
1081 my $a = Foo->new;
1082 $a->xet('b', 42);
1083 is ($a->xet('b'), 42);
1084 ok (!defined eval { $a->{b} });
1085 like ($@, qr/zap/);
1086
1087 {
1088    package t229;
1089    use overload '='  => sub { 42 },
1090                 '++' => sub { my $x = ${$_[0]}; $_[0] };
1091    sub new { my $x = 42; bless \$x }
1092
1093    my $warn;
1094    {  
1095      local $SIG{__WARN__} = sub { $warn++ };
1096       my $x = t229->new;
1097       my $y = $x;
1098       eval { $y++ };
1099    }
1100    main::ok (!$warn);
1101 }
1102
1103 {
1104     my ($int, $out1, $out2);
1105     {
1106         BEGIN { $int = 0; overload::constant 'integer' => sub {$int++; 17}; }
1107         $out1 = 0;
1108         $out2 = 1;
1109     }
1110     is($int,  2,  "#24313");    # 230
1111     is($out1, 17, "#24313");    # 231
1112     is($out2, 17, "#24313");    # 232
1113 }
1114
1115 {
1116     package Numify;
1117     use overload (qw(0+ numify fallback 1));
1118
1119     sub new {
1120         my $val = $_[1];
1121         bless \$val, $_[0];
1122     }
1123
1124     sub numify { ${$_[0]} }
1125 }
1126
1127 {
1128     package perl31793;
1129     use overload cmp => sub { 0 };
1130     package perl31793_fb;
1131     use overload cmp => sub { 0 }, fallback => 1;
1132     package main;
1133     my $o  = bless [], 'perl31793';
1134     my $of = bless [], 'perl31793_fb';
1135     my $no = bless [], 'no_overload';
1136     like(overload::StrVal(\"scalar"), qr/^SCALAR\(0x[0-9a-f]+\)$/);
1137     like(overload::StrVal([]),        qr/^ARRAY\(0x[0-9a-f]+\)$/);
1138     like(overload::StrVal({}),        qr/^HASH\(0x[0-9a-f]+\)$/);
1139     like(overload::StrVal(sub{1}),    qr/^CODE\(0x[0-9a-f]+\)$/);
1140     like(overload::StrVal(\*GLOB),    qr/^GLOB\(0x[0-9a-f]+\)$/);
1141     like(overload::StrVal(\$o),       qr/^REF\(0x[0-9a-f]+\)$/);
1142     like(overload::StrVal(qr/a/),     qr/^Regexp=REGEXP\(0x[0-9a-f]+\)$/);
1143     like(overload::StrVal($o),        qr/^perl31793=ARRAY\(0x[0-9a-f]+\)$/);
1144     like(overload::StrVal($of),       qr/^perl31793_fb=ARRAY\(0x[0-9a-f]+\)$/);
1145     like(overload::StrVal($no),       qr/^no_overload=ARRAY\(0x[0-9a-f]+\)$/);
1146 }
1147
1148 # These are all check that overloaded values rather than reference addresses
1149 # are what is getting tested.
1150 my ($two, $one, $un, $deux) = map {new Numify $_} 2, 1, 1, 2;
1151 my ($ein, $zwei) = (1, 2);
1152
1153 my %map = (one => 1, un => 1, ein => 1, deux => 2, two => 2, zwei => 2);
1154 foreach my $op (qw(<=> == != < <= > >=)) {
1155     foreach my $l (keys %map) {
1156         foreach my $r (keys %map) {
1157             my $ocode = "\$$l $op \$$r";
1158             my $rcode = "$map{$l} $op $map{$r}";
1159
1160             my $got = eval $ocode;
1161             die if $@;
1162             my $expect = eval $rcode;
1163             die if $@;
1164             is ($got, $expect, $ocode) or print "# $rcode\n";
1165         }
1166     }
1167 }
1168 {
1169     # check that overloading works in regexes
1170     {
1171         package Foo493;
1172         use overload
1173             '""' => sub { "^$_[0][0]\$" },
1174             '.'  => sub { 
1175                     bless [
1176                              $_[2]
1177                             ? (ref $_[1] ? $_[1][0] : $_[1]) . ':' .$_[0][0] 
1178                             : $_[0][0] . ':' . (ref $_[1] ? $_[1][0] : $_[1])
1179                     ], 'Foo493'
1180                         };
1181     }
1182
1183     my $a = bless [ "a" ], 'Foo493';
1184     like('a', qr/$a/);
1185     like('x:a', qr/x$a/);
1186     like('x:a:=', qr/x$a=$/);
1187     like('x:a:a:=', qr/x$a$a=$/);
1188
1189 }
1190
1191 {
1192     {
1193         package QRonly;
1194         use overload qr => sub { qr/x/ }, fallback => 1;
1195     }
1196     {
1197         my $x = bless [], "QRonly";
1198
1199         # like tries to be too clever, and decides that $x-stringified
1200         # doesn't look like a regex
1201         ok("x" =~ $x, "qr-only matches");
1202         ok("y" !~ $x, "qr-only doesn't match what it shouldn't");
1203         ok("x" =~ /^(??{$x})$/, "qr-only with ?? matches");
1204         ok("y" !~ /^(??{$x})$/, "qr-only with ?? doesn't match what it shouldn't");
1205         ok("xx" =~ /x$x/, "qr-only matches with concat");
1206         like("$x", qr/^QRonly=ARRAY/, "qr-only doesn't have string overload");
1207
1208         my $qr = bless qr/y/, "QRonly";
1209         ok("x" =~ $qr, "qr with qr-overload uses overload");
1210         ok("y" !~ $qr, "qr with qr-overload uses overload");
1211         {
1212             local $::TODO = '?? fails with "qr with qr"' ;
1213             ok("x" =~ /^(??{$qr})$/, "qr with qr-overload with ?? uses overload");
1214             ok("y" !~ /^(??{$qr})$/, "qr with qr-overload with ?? uses overload");
1215         }
1216         is("$qr", "".qr/y/, "qr with qr-overload stringify");
1217
1218         my $rx = $$qr;
1219         ok("y" =~ $rx, "bare rx with qr-overload doesn't overload match");
1220         ok("x" !~ $rx, "bare rx with qr-overload doesn't overload match");
1221         ok("y" =~ /^(??{$rx})$/, "bare rx with qr-overload with ?? doesn't overload match");
1222         ok("x" !~ /^(??{$rx})$/, "bare rx with qr-overload with ?? doesn't overload match");
1223         is("$rx", "".qr/y/, "bare rx with qr-overload stringify");
1224     }
1225     {
1226         package QRandSTR;
1227         use overload qr => sub { qr/x/ }, q/""/ => sub { "y" };
1228     }
1229     {
1230         my $x = bless [], "QRandSTR";
1231         ok("x" =~ $x, "qr+str uses qr for match");
1232         ok("y" !~ $x, "qr+str uses qr for match");
1233         ok("xx" =~ /x$x/, "qr+str uses qr for match with concat");
1234         is("$x", "y", "qr+str uses str for stringify");
1235
1236         my $qr = bless qr/z/, "QRandSTR";
1237         is("$qr", "y", "qr with qr+str uses str for stringify");
1238         ok("xx" =~ /x$x/, "qr with qr+str uses qr for match");
1239
1240         my $rx = $$qr;
1241         ok("z" =~ $rx, "bare rx with qr+str doesn't overload match");
1242         is("$rx", "".qr/z/, "bare rx with qr+str doesn't overload stringify");
1243     }
1244     {
1245         package QRany;
1246         use overload qr => sub { $_[0]->(@_) };
1247
1248         package QRself;
1249         use overload qr => sub { $_[0] };
1250     }
1251     {
1252         my $rx = bless sub { ${ qr/x/ } }, "QRany";
1253         ok("x" =~ $rx, "qr overload accepts a bare rx");
1254         ok("y" !~ $rx, "qr overload accepts a bare rx");
1255
1256         my $str = bless sub { "x" }, "QRany";
1257         ok(!eval { "x" =~ $str }, "qr overload doesn't accept a string");
1258         like($@, qr/^Overloaded qr did not return a REGEXP/, "correct error");
1259
1260         my $oqr = bless qr/z/, "QRandSTR";
1261         my $oqro = bless sub { $oqr }, "QRany";
1262         ok("z" =~ $oqro, "qr overload doesn't recurse");
1263
1264         my $qrs = bless qr/z/, "QRself";
1265         ok("z" =~ $qrs, "qr overload can return self");
1266     }
1267     {
1268         package STRonly;
1269         use overload q/""/ => sub { "x" };
1270
1271         package STRonlyFB;
1272         use overload q/""/ => sub { "x" }, fallback => 1;
1273     }
1274     {
1275         my $fb = bless [], "STRonlyFB";
1276         ok("x" =~ $fb, "qr falls back to \"\"");
1277         ok("y" !~ $fb, "qr falls back to \"\"");
1278
1279         my $nofb = bless [], "STRonly";
1280         ok("x" =~ $nofb, "qr falls back even without fallback");
1281         ok("y" !~ $nofb, "qr falls back even without fallback");
1282     }
1283 }
1284
1285 {
1286     my $twenty_three = 23;
1287     # Check that constant overloading propagates into evals
1288     BEGIN { overload::constant integer => sub { 23 } }
1289     is(eval "17", $twenty_three);
1290 }
1291
1292 {
1293     package Sklorsh;
1294     use overload
1295         bool     => sub { shift->is_cool };
1296
1297     sub is_cool {
1298         $_[0]->{name} eq 'cool';
1299     }
1300
1301     sub delete {
1302         undef %{$_[0]};
1303         bless $_[0], 'Brap';
1304         return 1;
1305     }
1306
1307     sub delete_with_self {
1308         my $self = shift;
1309         undef %$self;
1310         bless $self, 'Brap';
1311         return 1;
1312     }
1313
1314     package Brap;
1315
1316     1;
1317
1318     package main;
1319
1320     my $obj;
1321     $obj = bless {name => 'cool'}, 'Sklorsh';
1322     $obj->delete;
1323     ok(eval {if ($obj) {1}; 1}, $@ || 'reblessed into nonexistent namespace');
1324
1325     $obj = bless {name => 'cool'}, 'Sklorsh';
1326     $obj->delete_with_self;
1327     ok (eval {if ($obj) {1}; 1}, $@);
1328     
1329     my $a = $b = {name => 'hot'};
1330     bless $b, 'Sklorsh';
1331     is(ref $a, 'Sklorsh');
1332     is(ref $b, 'Sklorsh');
1333     ok(!$b, "Expect overloaded boolean");
1334     ok(!$a, "Expect overloaded boolean");
1335 }
1336
1337 {
1338     package Flrbbbbb;
1339     use overload
1340         bool     => sub { shift->{truth} eq 'yes' },
1341         '0+'     => sub { shift->{truth} eq 'yes' ? '1' : '0' },
1342         '!'      => sub { shift->{truth} eq 'no' },
1343         fallback => 1;
1344
1345     sub new { my $class = shift; bless { truth => shift }, $class }
1346
1347     package main;
1348
1349     my $yes = Flrbbbbb->new('yes');
1350     my $x;
1351     $x = 1 if $yes;                     is($x, 1);
1352     $x = 2 unless $yes;                 is($x, 1);
1353     $x = 3 if !$yes;                    is($x, 1);
1354     $x = 4 unless !$yes;                is($x, 4);
1355
1356     my $no = Flrbbbbb->new('no');
1357     $x = 0;
1358     $x = 1 if $no;                      is($x, 0);
1359     $x = 2 unless $no;                  is($x, 2);
1360     $x = 3 if !$no;                     is($x, 3);
1361     $x = 4 unless !$no;                 is($x, 3);
1362
1363     $x = 0;
1364     $x = 1 if !$no && $yes;             is($x, 1);
1365     $x = 2 unless !$no && $yes;         is($x, 1);
1366     $x = 3 if $no || !$yes;             is($x, 1);
1367     $x = 4 unless $no || !$yes;         is($x, 4);
1368
1369     $x = 0;
1370     $x = 1 if !$no || !$yes;            is($x, 1);
1371     $x = 2 unless !$no || !$yes;        is($x, 1);
1372     $x = 3 if !$no && !$yes;            is($x, 1);
1373     $x = 4 unless !$no && !$yes;        is($x, 4);
1374 }
1375
1376 {
1377     use Scalar::Util 'weaken';
1378
1379     package Shklitza;
1380     use overload '""' => sub {"CLiK KLAK"};
1381
1382     package Ksshfwoom;
1383
1384     package main;
1385
1386     my ($obj, $ref);
1387     $obj = bless do {my $a; \$a}, 'Shklitza';
1388     $ref = $obj;
1389
1390     is ("$obj", "CLiK KLAK");
1391     is ("$ref", "CLiK KLAK");
1392
1393     weaken $ref;
1394     is ("$ref", "CLiK KLAK");
1395
1396     bless $obj, 'Ksshfwoom';
1397
1398     like ($obj, qr/^Ksshfwoom=/);
1399     like ($ref, qr/^Ksshfwoom=/);
1400
1401     undef $obj;
1402     is ($ref, undef);
1403 }
1404
1405 {
1406     package bit;
1407     # bit operations have overloadable assignment variants too
1408
1409     sub new { bless \$_[1], $_[0] }
1410
1411     use overload
1412           "&=" => sub { bit->new($_[0]->val . ' & ' . $_[1]->val) }, 
1413           "^=" => sub { bit->new($_[0]->val . ' ^ ' . $_[1]->val) },
1414           "|"  => sub { bit->new($_[0]->val . ' | ' . $_[1]->val) }, # |= by fallback
1415           ;
1416
1417     sub val { ${$_[0]} }
1418
1419     package main;
1420
1421     my $a = bit->new(my $va = 'a');
1422     my $b = bit->new(my $vb = 'b');
1423
1424     $a &= $b;
1425     is($a->val, 'a & b', "overloaded &= works");
1426
1427     my $c = bit->new(my $vc = 'c');
1428
1429     $b ^= $c;
1430     is($b->val, 'b ^ c', "overloaded ^= works");
1431
1432     my $d = bit->new(my $vd = 'd');
1433
1434     $c |= $d;
1435     is($c->val, 'c | d', "overloaded |= (by fallback) works");
1436 }
1437
1438 {
1439     # comparison operators with nomethod (bug 41546)
1440     my $warning = "";
1441     my $method;
1442
1443     package nomethod_false;
1444     use overload nomethod => sub { $method = 'nomethod'; 0 };
1445
1446     package nomethod_true;
1447     use overload nomethod => sub { $method= 'nomethod'; 'true' };
1448
1449     package main;
1450     local $^W = 1;
1451     local $SIG{__WARN__} = sub { $warning = $_[0] };
1452
1453     my $f = bless [], 'nomethod_false';
1454     ($warning, $method) = ("", "");
1455     is($f eq 'whatever', 0, 'nomethod makes eq return 0');
1456     is($method, 'nomethod');
1457
1458     my $t = bless [], 'nomethod_true';
1459     ($warning, $method) = ("", "");
1460     is($t eq 'whatever', 'true', 'nomethod makes eq return "true"');
1461     is($method, 'nomethod');
1462     is($warning, "", 'nomethod eq need not return number');
1463
1464     eval q{ 
1465         package nomethod_false;
1466         use overload cmp => sub { $method = 'cmp'; 0 };
1467     };
1468     $f = bless [], 'nomethod_false';
1469     ($warning, $method) = ("", "");
1470     ok($f eq 'whatever', 'eq falls back to cmp (nomethod not called)');
1471     is($method, 'cmp');
1472
1473     eval q{
1474         package nomethod_true;
1475         use overload cmp => sub { $method = 'cmp'; 'true' };
1476     };
1477     $t = bless [], 'nomethod_true';
1478     ($warning, $method) = ("", "");
1479     ok($t eq 'whatever', 'eq falls back to cmp (nomethod not called)');
1480     is($method, 'cmp');
1481     like($warning, qr/isn't numeric/, 'cmp should return number');
1482
1483 }
1484
1485 {
1486     # nomethod called for '!' after attempted fallback
1487     my $nomethod_called = 0;
1488
1489     package nomethod_not;
1490     use overload nomethod => sub { $nomethod_called = 'yes'; };
1491
1492     package main;
1493     my $o = bless [], 'nomethod_not';
1494     my $res = ! $o;
1495
1496     is($nomethod_called, 'yes', "nomethod() is called for '!'");
1497     is($res, 'yes', "nomethod(..., '!') return value propagates");
1498 }
1499
1500 {
1501     # Subtle bug pre 5.10, as a side effect of the overloading flag being
1502     # stored on the reference rather than the referent. Despite the fact that
1503     # objects can only be accessed via references (even internally), the
1504     # referent actually knows that it's blessed, not the references. So taking
1505     # a new, unrelated, reference to it gives an object. However, the
1506     # overloading-or-not flag was on the reference prior to 5.10, and taking
1507     # a new reference didn't (use to) copy it.
1508
1509     package kayo;
1510
1511     use overload '""' => sub {${$_[0]}};
1512
1513     sub Pie {
1514         return "$_[0], $_[1]";
1515     }
1516
1517     package main;
1518
1519     my $class = 'kayo';
1520     my $string = 'bam';
1521     my $crunch_eth = bless \$string, $class;
1522
1523     is("$crunch_eth", $string);
1524     is ($crunch_eth->Pie("Meat"), "$string, Meat");
1525
1526     my $wham_eth = \$string;
1527
1528     is("$wham_eth", $string,
1529        'This reference did not have overloading in 5.8.8 and earlier');
1530     is ($crunch_eth->Pie("Apple"), "$string, Apple");
1531
1532     my $class = ref $wham_eth;
1533     $class =~ s/=.*//;
1534
1535     # Bless it back into its own class!
1536     bless $wham_eth, $class;
1537
1538     is("$wham_eth", $string);
1539     is ($crunch_eth->Pie("Blackbird"), "$string, Blackbird");
1540 }
1541
1542 {
1543     package numify_int;
1544     use overload "0+" => sub { $_[0][0] += 1; 42 };
1545     package numify_self;
1546     use overload "0+" => sub { $_[0][0]++; $_[0] };
1547     package numify_other;
1548     use overload "0+" => sub { $_[0][0]++; $_[0][1] = bless [], 'numify_int' };
1549     package numify_by_fallback;
1550     use overload fallback => 1;
1551
1552     package main;
1553     my $o = bless [], 'numify_int';
1554     is(int($o), 42, 'numifies to integer');
1555     is($o->[0], 1, 'int() numifies only once');
1556
1557     my $aref = [];
1558     my $num_val = int($aref);
1559     my $r = bless $aref, 'numify_self';
1560     is(int($r), $num_val, 'numifies to self');
1561     is($r->[0], 1, 'int() numifies once when returning self');
1562
1563     my $s = bless [], 'numify_other';
1564     is(int($s), 42, 'numifies to numification of other object');
1565     is($s->[0], 1, 'int() numifies once when returning other object');
1566     is($s->[1][0], 1, 'returned object numifies too');
1567
1568     my $m = bless $aref, 'numify_by_fallback';
1569     is(int($m), $num_val, 'numifies to usual reference value');
1570     is(abs($m), $num_val, 'numifies to usual reference value');
1571     is(-$m, -$num_val, 'numifies to usual reference value');
1572     is(0+$m, $num_val, 'numifies to usual reference value');
1573     is($m+0, $num_val, 'numifies to usual reference value');
1574     is($m+$m, 2*$num_val, 'numifies to usual reference value');
1575     is(0-$m, -$num_val, 'numifies to usual reference value');
1576     is(1*$m, $num_val, 'numifies to usual reference value');
1577     is(int($m/1), $num_val, 'numifies to usual reference value');
1578     is($m%100, $num_val%100, 'numifies to usual reference value');
1579     is($m**1, $num_val, 'numifies to usual reference value');
1580
1581     is(abs($aref), $num_val, 'abs() of ref');
1582     is(-$aref, -$num_val, 'negative of ref');
1583     is(0+$aref, $num_val, 'ref addition');
1584     is($aref+0, $num_val, 'ref addition');
1585     is($aref+$aref, 2*$num_val, 'ref addition');
1586     is(0-$aref, -$num_val, 'subtraction of ref');
1587     is(1*$aref, $num_val, 'multiplicaton of ref');
1588     is(int($aref/1), $num_val, 'division of ref');
1589     is($aref%100, $num_val%100, 'modulo of ref');
1590     is($aref**1, $num_val, 'exponentiation of ref');
1591 }
1592
1593 {
1594     package CopyConstructorFallback;
1595     use overload
1596         '++'        => sub { "$_[0]"; $_[0] },
1597         fallback    => 1;
1598     sub new { bless {} => shift }
1599
1600     package main;
1601
1602     my $o = CopyConstructorFallback->new;
1603     my $x = $o++; # would segfault
1604     my $y = ++$o;
1605     is($x, $o, "copy constructor falls back to assignment (postinc)");
1606     is($y, $o, "copy constructor falls back to assignment (preinc)");
1607 }
1608
1609 # only scalar 'x' should currently overload
1610
1611 {
1612     package REPEAT;
1613
1614     my ($x,$n, $nm);
1615
1616     use overload
1617         'x'        => sub { $x++; 1 },
1618         '0+'       => sub { $n++; 1 },
1619         'nomethod' => sub { $nm++; 1 },
1620         'fallback' => 0,
1621     ;
1622
1623     my $s = bless {};
1624
1625     package main;
1626
1627     my @a;
1628     my $count = 3;
1629
1630     ($x,$n,$nm) = (0,0,0);
1631     @a = ((1,2,$s) x $count);
1632     is("$x-$n-$nm", "0-0-0", 'repeat 1');
1633
1634     ($x,$n,$nm) = (0,0,0);
1635     @a = ((1,$s,3) x $count);
1636     is("$x-$n-$nm", "0-0-0", 'repeat 2');
1637
1638     ($x,$n,$nm) = (0,0,0);
1639     @a = ((1,2,3) x $s);
1640     is("$x-$n-$nm", "0-1-0", 'repeat 3');
1641 }
1642
1643
1644
1645 # RT #57012: magic items need to have mg_get() called before testing for
1646 # overload. Lack of this means that overloaded values returned by eg a
1647 # tied array didn't call overload methods.
1648 # We test here both a tied array and scalar, since the implementation of
1649 # tied  arrays (and hashes) is such that in rvalue context, mg_get is
1650 # called prior to executing the op, while it isn't for a tied scalar.
1651 # We also check that return values are correctly tainted.
1652 # We try against two overload packages; one has all expected methods, the
1653 # other uses only fallback methods.
1654
1655 {
1656
1657     # @tests holds a list of test cases. Each elem is an array ref with
1658     # the following entries:
1659     #
1660     #  * the value that the overload method should return
1661     #
1662     #  * the expression to be evaled. %s is replaced with the
1663     #       variable being tested ($ta[0], $ts, or $plain)
1664     #
1665     #  * a string listing what functions we expect to be called.
1666     #       Each method appends its name in parentheses, so "(=)(+)" means
1667     #       we expect the copy constructor and then the add method to be
1668     #       called.
1669     #
1670     #  * like above, but what should be called for the fallback-only test
1671     #      (in this case, nomethod() identifies itself as "(NM:*)" where *
1672     #      is the op).  If this value is undef, fallback tests are skipped.
1673     #
1674     #  * An array ref of expected counts of calls to FETCH/STORE.
1675     #      The first three values are:
1676     #         1. the expected number of FETCHs for a tied array
1677     #         2. the expected number of FETCHs for a tied scalar
1678     #         3. the expected number of STOREs
1679     #       If there are a further three elements present, then
1680     #       these represent the expected counts for the fallback
1681     #       version of the tests. If absent, they are assumed to
1682     #       be the same as for the full method test
1683     #
1684     #  * Under the taint version of the tests,  whether we expect
1685     #       the result to be tainted (for example comparison ops
1686     #       like '==' don't return a tainted value, even if their
1687     #       args are.
1688     my @tests;
1689
1690     my %subs;
1691     my $funcs;
1692     my $use_int;
1693
1694     BEGIN {
1695         # A note on what methods to expect to be called, and
1696         # how many times FETCH/STORE is called:
1697         #
1698         # Mutating ops (+=, ++ etc) trigger a copy ('='), since
1699         # the code can't distinguish between something that's been copied:
1700         #    $a = foo->new(0); $b = $a; refcnt($$b) == 2
1701         # and overloaded objects stored in ties which will have extra
1702         # refcounts due to the tied_obj magic and entries on the tmps
1703         # stack when returning from FETCH etc. So we always copy.
1704
1705         # This accounts for a '=', and an extra STORE.
1706         # We also have a FETCH returning the final value from the eval,
1707         # plus a FETCH in the overload subs themselves: ($_[0][0])
1708         # triggers one. However, tied aggregates have a mechanism to prevent
1709         # multiple fetches between STOREs, which means that the tied
1710         # hash skips doing a FETCH during '='.
1711
1712         for (qw(+ - * / % ** << >> & | ^)) {
1713             my $op = $_;
1714             $op = '%%' if $op eq '%';
1715             my $e = "%s $op= 3";
1716             $subs{"$_="} = $e;
1717             # ARRAY  FETCH: initial,        sub+=, eval-return,
1718             # SCALAR FETCH: initial, sub=,  sub+=, eval-return,
1719             # STORE:        copy, mutator
1720             push @tests, [ 18, $e, "(=)($_=)", "(=)(NM:$_=)", [ 3, 4, 2 ], 1 ];
1721
1722             $subs{$_} =
1723                 "do { my \$arg = %s; \$_[2] ? (3 $op \$arg) : (\$arg $op 3) }";
1724             # ARRAY  FETCH: initial
1725             # SCALAR FETCH: initial eval-return,
1726             push @tests, [ 18, "%s $op 3", "($_)", "(NM:$_)", [ 1, 2, 0 ], 1 ];
1727             push @tests, [ 18, "3 $op %s", "($_)", "(NM:$_)", [ 1, 2, 0 ], 1 ];
1728         }
1729
1730         # these use string fallback rather than nomethod
1731         for (qw(x .)) {
1732             my $op = $_;
1733             my $e = "%s $op= 3";
1734             $subs{"$_="} = $e;
1735             # For normal case:
1736             #   ARRAY  FETCH: initial,        sub+=, eval-return,
1737             #   SCALAR FETCH: initial, sub=,  sub+=, eval-return,
1738             #          STORE: copy, mutator
1739             # for fallback, we just stringify, so eval-return and copy skipped
1740
1741             push @tests, [ 18, $e, "(=)($_=)", '("")',
1742                             [ 3, 4, 2,     2, 3, 1 ], 1 ];
1743
1744             $subs{$_} =
1745                 "do { my \$arg = %s; \$_[2] ? (3 $op \$arg) : (\$arg $op 3) }";
1746             # ARRAY  FETCH: initial
1747             # SCALAR FETCH: initial eval-return,
1748             # with fallback, we just stringify, so eval-return skipped,
1749             #    but an extra FETCH happens in sub"", except for 'x',
1750             #    which passes a copy of the RV to sub"", avoiding the
1751             #    second FETCH
1752
1753             push @tests, [ 18, "%s $op 3", "($_)", '("")',
1754                             [ 1, 2, 0,     1, ($_ eq '.' ? 2 : 1), 0 ], 1 ];
1755             next if $_ eq 'x'; # repeat only overloads on LHS
1756             push @tests, [ 18, "3 $op %s", "($_)", '("")',
1757                             [ 1, 2, 0,     1, 2, 0 ], 1 ];
1758         }
1759
1760         for (qw(++ --)) {
1761             my $pre  = "$_%s";
1762             my $post = "%s$_";
1763             $subs{$_} = $pre;
1764             push @tests,
1765                 # ARRAY  FETCH: initial,        sub+=, eval-return,
1766                 # SCALAR FETCH: initial, sub=,  sub+=, eval-return,
1767                 # STORE:        copy, mutator
1768                 [ 18, $pre, "(=)($_)(\"\")", "(=)(NM:$_)(\"\")", [ 3, 4, 2 ], 1 ],
1769                 # ARRAY  FETCH: initial,        sub+=
1770                 # SCALAR FETCH: initial, sub=,  sub+=
1771                 # STORE:        copy, mutator
1772                 [ 18, $post, "(=)($_)(\"\")", "(=)(NM:$_)(\"\")", [ 2, 3, 2 ], 1 ];
1773         }
1774
1775         # For the non-mutator ops, we have a initial FETCH,
1776         # an extra FETCH within the sub itself for the scalar option,
1777         # and no STOREs
1778
1779         for (qw(< <= >  >= == != lt le gt ge eq ne)) {
1780             my $e = "%s $_ 3";
1781             $subs{$_} = $e;
1782             push @tests, [ 3, $e, "($_)", "(NM:$_)", [ 1, 2, 0 ], 0 ];
1783         }
1784         for (qw(<=> cmp)) {
1785             my $e = "%s $_ 3";
1786             $subs{$_} = $e;
1787             push @tests, [ 3, $e, "($_)", "(NM:$_)", [ 1, 2, 0 ], 1 ];
1788         }
1789         for (qw(atan2)) {
1790             my $e = "$_ %s, 3";
1791             $subs{$_} = $e;
1792             push @tests, [ 18, $e, "($_)", "(NM:$_)", [ 1, 2, 0 ], 1 ];
1793         }
1794         for (qw(cos sin exp abs log sqrt int ~)) {
1795             my $e = "$_(%s)";
1796             $subs{$_} = $e;
1797             push @tests, [ 1.23, $e, "($_)",
1798                     ($_ eq 'int' ? '(0+)' : "(NM:$_)") , [ 1, 2, 0 ], 1 ];
1799         }
1800         for (qw(!)) {
1801             my $e = "$_(%s)";
1802             $subs{$_} = $e;
1803             push @tests, [ 1.23, $e, "($_)", '(0+)', [ 1, 2, 0 ], 0 ];
1804         }
1805         for (qw(-)) {
1806             my $e = "$_(%s)";
1807             $subs{neg} = $e;
1808             push @tests, [ 18, $e, '(neg)', '(NM:neg)', [ 1, 2, 0 ], 1 ];
1809         }
1810         my $e = '(%s) ? 1 : 0';
1811         $subs{bool} = $e;
1812         push @tests, [ 18, $e, '(bool)', '(0+)', [ 1, 2, 0 ], 0 ];
1813
1814         # note: this is testing unary qr, not binary =~
1815         $subs{qr} = '(qr/%s/)';
1816         push @tests, [ "abc", '"abc" =~ (%s)', '(qr)', '("")', [ 1, 2, 0 ], 0 ];
1817         push @tests, [ chr 256, 'chr(256) =~ (%s)', '(qr)', '("")',
1818                                                           [ 1, 2, 0 ], 0 ];
1819
1820         $e = '"abc" ~~ (%s)';
1821         $subs{'~~'} = $e;
1822         push @tests, [ "abc", $e, '(~~)', '(NM:~~)', [ 1, 1, 0 ], 0 ];
1823
1824         $subs{'-X'} = 'do { my $f = (%s);'
1825                     . '$_[1] eq "r" ? (-r ($f)) :'
1826                     . '$_[1] eq "e" ? (-e ($f)) :'
1827                     . '$_[1] eq "f" ? (-f ($f)) :'
1828                     . '$_[1] eq "l" ? (-l ($f)) :'
1829                     . '$_[1] eq "t" ? (-t ($f)) :'
1830                     . '$_[1] eq "T" ? (-T ($f)) : 0;}';
1831         # Note - we don't care what these file tests return, as
1832         # long as the tied and untied versions return the same value.
1833         # The flags below are chosen to test all uses of tryAMAGICftest_MG
1834         for (qw(r e f l t T)) {
1835             push @tests, [ 'TEST', "-$_ (%s)", '(-X)', '("")', [ 1, 2, 0 ], 0 ];
1836         }
1837
1838         $subs{'${}'} = '%s';
1839         push @tests, [ do {my $s=99; \$s}, '${%s}', '(${})', undef, [ 1, 1, 0 ], 0 ];
1840
1841         # we skip testing '@{}' here because too much of this test
1842         # framework involves array dereferences!
1843
1844         $subs{'%{}'} = '%s';
1845         push @tests, [ {qw(a 1 b 2 c 3)}, 'join "", sort keys %%{%s}',
1846                         '(%{})', undef, [ 1, 1, 0 ], 0 ];
1847
1848         $subs{'&{}'} = '%s';
1849         push @tests, [ sub {99}, 'do {&{%s} for 1,2}',
1850                             '(&{})(&{})', undef, [ 2, 2, 0 ], 0 ];
1851
1852         our $RT57012A = 88;
1853         our $RT57012B;
1854         $subs{'*{}'} = '%s';
1855         push @tests, [ \*RT57012A, '*RT57012B = *{%s}; our $RT57012B',
1856                 '(*{})', undef, [ 1, 1, 0 ], 0 ];
1857
1858         my $iter_text = ("some random text\n" x 100) . $^X;
1859         open my $iter_fh, '<', \$iter_text
1860             or die "open of \$iter_text gave ($!)\n";
1861         $subs{'<>'} = '<$iter_fh>';
1862         push @tests, [ $iter_fh, '<%s>', '(<>)', undef, [ 1, 1, 0 ], 1 ];
1863
1864         # eval should do tie, overload on its arg before checking taint */
1865         push @tests, [ '1;', 'eval q(eval %s); $@ =~ /Insecure/',
1866                 '("")', '("")', [ 1, 2, 0 ], 0 ];
1867
1868
1869         for my $sub (keys %subs) {
1870             my $term = $subs{$sub};
1871             my $t = sprintf $term, '$_[0][0]';
1872             my $e ="sub { \$funcs .= '($sub)'; my \$r; if (\$use_int) {"
1873                 . "use integer; \$r = ($t) } else { \$r = ($t) } \$r }";
1874             $subs{$sub} = eval $e;
1875             die "Compiling sub gave error:\n<$e>\n<$@>\n" if $@;
1876         }
1877     }
1878
1879     my $fetches;
1880     my $stores;
1881
1882     package RT57012_OV;
1883
1884     use overload
1885         %subs,
1886         "="   => sub { $funcs .= '(=)';  bless [ $_[0][0] ] },
1887         '0+'  => sub { $funcs .= '(0+)'; 0 + $_[0][0] },
1888         '""'  => sub { $funcs .= '("")'; "$_[0][0]"   },
1889         ;
1890
1891     package RT57012_OV_FB; # only contains fallback conversion functions
1892
1893     use overload
1894         "="   => sub { $funcs .= '(=)';  bless [ $_[0][0] ] },
1895         '0+'  => sub { $funcs .= '(0+)'; 0 + $_[0][0] },
1896         '""'  => sub { $funcs .= '("")'; "$_[0][0]"   },
1897         "nomethod" => sub {
1898                         $funcs .= "(NM:$_[3])";
1899                         my $e = defined($_[1])
1900                                 ? $_[3] eq 'atan2'
1901                                     ? $_[2]
1902                                        ? "atan2(\$_[1],\$_[0][0])"
1903                                        : "atan2(\$_[0][0],\$_[1])"
1904                                     : $_[2]
1905                                         ? "\$_[1] $_[3] \$_[0][0]"
1906                                         : "\$_[0][0] $_[3] \$_[1]"
1907                                 : $_[3] eq 'neg'
1908                                     ? "-\$_[0][0]"
1909                                     : "$_[3](\$_[0][0])";
1910                         my $r;
1911                         if ($use_int) {
1912                             use integer; $r = eval $e;
1913                         }
1914                         else {
1915                             $r = eval $e;
1916                         }
1917                         ::diag("eval of nomethod <$e> gave <$@>") if $@;
1918                         $r;
1919                     }
1920
1921         ;
1922
1923     package RT57012_TIE_S;
1924
1925     my $tie_val;
1926     sub TIESCALAR { bless [ bless [ $tie_val ], $_[1] ] }
1927     sub FETCH     { $fetches++; $_[0][0] }
1928     sub STORE     { $stores++;  $_[0][0] = $_[1] }
1929
1930     package RT57012_TIE_A;
1931
1932     sub TIEARRAY  { bless [] }
1933     sub FETCH     { $fetches++; $_[0][0] }
1934     sub STORE     { $stores++;  $_[0][$_[1]] = $_[2] }
1935
1936     package main;
1937
1938     for my $test (@tests) {
1939         my ($val, $sub_term, $exp_funcs, $exp_fb_funcs,
1940             $exp_counts, $exp_taint) = @$test;
1941
1942         my $tainted_val;
1943         {
1944             # create tainted version of $val (unless its a ref)
1945             my $t = substr($^X,0,0);
1946             my $t0 = $t."0";
1947             my $val1 = $val; # use a copy to avoid stringifying original
1948             $tainted_val = ref($val1) ? $val :
1949                         ($val1 =~ /^[\d\.]+$/) ? $val+$t0 : $val.$t;
1950         }
1951         $tie_val = $tainted_val;
1952
1953         for my $int ('', 'use integer; ') {
1954             $use_int = ($int ne '');
1955             my $plain = $tainted_val;
1956             my $plain_term = $int . sprintf $sub_term, '$plain';
1957             my $exp = eval $plain_term;
1958             diag("eval of plain_term <$plain_term> gave <$@>") if $@;
1959             is(tainted($exp), $exp_taint,
1960                         "<$plain_term> taint of expected return");
1961
1962             for my $ov_pkg (qw(RT57012_OV RT57012_OV_FB)) {
1963                 next if $ov_pkg eq 'RT57012_OV_FB'
1964                         and  not defined $exp_fb_funcs;
1965                 my ($exp_fetch_a, $exp_fetch_s, $exp_store) =
1966                     ($ov_pkg eq 'RT57012_OV' || @$exp_counts < 4)
1967                         ? @$exp_counts[0,1,2]
1968                         : @$exp_counts[3,4,5];
1969
1970                 tie my $ts, 'RT57012_TIE_S', $ov_pkg;
1971                 tie my @ta, 'RT57012_TIE_A';
1972                 $ta[0]    = bless [ $tainted_val ], $ov_pkg;
1973                 my $oload = bless [ $tainted_val ], $ov_pkg;
1974
1975                 for my $var ('$ta[0]', '$ts', '$oload',
1976                             ($sub_term eq '<%s>' ? '${ts}' : ())
1977                 ) {
1978
1979                     $funcs = '';
1980                     $fetches = 0;
1981                     $stores = 0;
1982
1983                     my $res_term  = $int . sprintf $sub_term, $var;
1984                     my $desc =  "<$res_term> $ov_pkg" ;
1985                     my $res = eval $res_term;
1986                     diag("eval of res_term $desc gave <$@>") if $@;
1987                     # uniquely, the inc/dec ops return the original
1988                     # ref rather than a copy, so stringify it to
1989                     # find out if its tainted
1990                     $res = "$res" if $res_term =~ /\+\+|--/;
1991                     is(tainted($res), $exp_taint,
1992                             "$desc taint of result return");
1993                     is($res, $exp, "$desc return value");
1994                     my $fns =($ov_pkg eq 'RT57012_OV_FB')
1995                                 ? $exp_fb_funcs : $exp_funcs;
1996                     if ($var eq '$oload' && $res_term !~ /oload(\+\+|--)/) {
1997                         # non-tied overloading doesn't trigger a copy
1998                         # except for post inc/dec
1999                         $fns =~ s/^\(=\)//;
2000                     }
2001                     is($funcs, $fns, "$desc methods called");
2002                     next if $var eq '$oload';
2003                     my $exp_fetch = ($var eq '$ts') ?
2004                             $exp_fetch_s : $exp_fetch_a;
2005                     is($fetches, $exp_fetch, "$desc FETCH count");
2006                     is($stores, $exp_store, "$desc STORE count");
2007
2008                 }
2009
2010             }
2011         }
2012     }
2013 }
2014
2015 # Test overload from the main package
2016 fresh_perl_is
2017  '$^W = 1; use overload q\""\ => sub {"ning"}; print bless []',
2018  'ning',
2019   { switches => ['-wl'], stderr => 1 },
2020  'use overload from the main package'
2021 ;
2022
2023 {
2024     package blessed_methods;
2025     use overload '+' => sub {};
2026     bless overload::Method __PACKAGE__,'+';
2027     eval { overload::Method __PACKAGE__,'+' };
2028     ::is($@, '', 'overload::Method and blessed overload methods');
2029 }
2030
2031 {
2032     # fallback to 'cmp' and '<=>' with heterogeneous operands
2033     # [perl #71286]
2034     my $not_found = 'no method found';
2035     my $used = 0;
2036     package CmpBase;
2037     sub new {
2038         my $n = $_[1] || 0;
2039         bless \$n, ref $_[0] || $_[0];
2040     }
2041     sub cmp {
2042         $used = \$_[0];
2043         (${$_[0]} <=> ${$_[1]}) * ($_[2] ? -1 : 1);
2044     }
2045
2046     package NCmp;
2047     use base 'CmpBase';
2048     use overload '<=>' => 'cmp';
2049
2050     package SCmp;
2051     use base 'CmpBase';
2052     use overload 'cmp' => 'cmp';
2053
2054     package main;
2055     my $n = NCmp->new(5);
2056     my $s = SCmp->new(3);
2057     my $res;
2058
2059     eval { $res = $n > $s; };
2060     $res = $not_found if $@ =~ /$not_found/;
2061     is($res, 1, 'A>B using A<=> when B overloaded, no B<=>');
2062
2063     eval { $res = $s < $n; };
2064     $res = $not_found if $@ =~ /$not_found/;
2065     is($res, 1, 'A<B using B<=> when A overloaded, no A<=>');
2066
2067     eval { $res = $s lt $n; };
2068     $res = $not_found if $@ =~ /$not_found/;
2069     is($res, 1, 'A lt B using A:cmp when B overloaded, no B:cmp');
2070
2071     eval { $res = $n gt $s; };
2072     $res = $not_found if $@ =~ /$not_found/;
2073     is($res, 1, 'A gt B using B:cmp when A overloaded, no A:cmp');
2074
2075     my $o = NCmp->new(9);
2076     $res = $n < $o;
2077     is($used, \$n, 'A < B uses <=> from A in preference to B');
2078
2079     my $t = SCmp->new(7);
2080     $res = $s lt $t;
2081     is($used, \$s, 'A lt B uses cmp from A in preference to B');
2082 }
2083
2084 {
2085     # Combinatorial testing of 'fallback' and 'nomethod'
2086     # [perl #71286]
2087     package NuMB;
2088     use overload '0+' => sub { ${$_[0]}; },
2089         '""' => 'str';
2090     sub new {
2091         my $self = shift;
2092         my $n = @_ ? shift : 0;
2093         bless my $obj = \$n, ref $self || $self;
2094     }
2095     sub str {
2096         no strict qw/refs/;
2097         my $s = "(${$_[0]} ";
2098         $s .= "nomethod, " if defined ${ref($_[0]).'::(nomethod'};
2099         my $fb = ${ref($_[0]).'::()'};
2100         $s .= "fb=" . (defined $fb ? 0 + $fb : 'undef') . ")";
2101     }
2102     sub nomethod { "${$_[0]}.nomethod"; }
2103
2104     # create classes for tests
2105     package main;
2106     my @falls = (0, 'undef', 1);
2107     my @nomethods = ('', 'nomethod');
2108     my $not_found = 'no method found';
2109     for my $fall (@falls) {
2110         for my $nomethod (@nomethods) {
2111             my $nomethod_decl = $nomethod
2112                 ? $nomethod . "=>'nomethod'," : '';
2113             eval qq{
2114                     package NuMB$fall$nomethod;
2115                     use base qw/NuMB/;
2116                     use overload $nomethod_decl
2117                     fallback => $fall;
2118                 };
2119         }
2120     }
2121
2122     # operation and precedence of 'fallback' and 'nomethod'
2123     # for all combinations with 2 overloaded operands
2124     for my $nomethod2 (@nomethods) {
2125         for my $nomethod1 (@nomethods) {
2126             for my $fall2 (@falls) {
2127                 my $pack2 = "NuMB$fall2$nomethod2";
2128                 for my $fall1 (@falls) {
2129                     my $pack1 = "NuMB$fall1$nomethod1";
2130                     my ($test, $out, $exp);
2131                     eval qq{
2132                             my \$x = $pack1->new(2);
2133                             my \$y = $pack2->new(3);
2134                             \$test = "\$x" . ' * ' . "\$y";
2135                             \$out = \$x * \$y;
2136                         };
2137                     $out = $not_found if $@ =~ /$not_found/;
2138                     $exp = $nomethod1 ? '2.nomethod' :
2139                          $nomethod2 ? '3.nomethod' :
2140                          $fall1 eq '1' && $fall2 eq '1' ? 6
2141                          : $not_found;
2142                     is($out, $exp, "$test --> $exp");
2143                 }
2144             }
2145         }
2146     }
2147
2148     # operation of 'fallback' and 'nomethod'
2149     # where the other operand is not overloaded
2150     for my $nomethod (@nomethods) {
2151         for my $fall (@falls) {
2152             my ($test, $out, $exp);
2153             eval qq{
2154                     my \$x = NuMB$fall$nomethod->new(2);
2155                     \$test = "\$x" . ' * 3';
2156                     \$out = \$x * 3;
2157                 };
2158             $out = $not_found if $@ =~ /$not_found/;
2159             $exp = $nomethod ? '2.nomethod' :
2160                 $fall eq '1' ? 6
2161                 : $not_found;
2162             is($out, $exp, "$test --> $exp");
2163
2164             eval qq{
2165                     my \$x = NuMB$fall$nomethod->new(2);
2166                     \$test = '3 * ' . "\$x";
2167                     \$out = 3 * \$x;
2168                 };
2169             $out = $not_found if $@ =~ /$not_found/;
2170             is($out, $exp, "$test --> $exp");
2171         }
2172     }
2173 }
2174
2175 # since 5.6 overloaded <> was leaving an extra arg on the stack!
2176
2177 {
2178     package Iter1;
2179     use overload '<>' => sub { 11 };
2180     package main;
2181     my $a = bless [], 'Iter1';
2182     my $x;
2183     my @a = (10, ($x = <$a>), 12);
2184     is ($a[0], 10, 'Iter1: a[0]');
2185     is ($a[1], 11, 'Iter1: a[1]');
2186     is ($a[2], 12, 'Iter1: a[2]');
2187     @a = (10, ($x .= <$a>), 12);
2188     is ($a[0],   10, 'Iter1: a[0] concat');
2189     is ($a[1], 1111, 'Iter1: a[1] concat');
2190     is ($a[2],   12, 'Iter1: a[2] concat');
2191 }
2192
2193 # Some tests for error messages
2194 {
2195     package Justus;
2196     use overload '+' => 'justice';
2197     eval {bless[]};
2198     ::like $@, qr/^Can't resolve method "justice" overloading "\+" in p(?x:
2199                   )ackage "Justus" at /,
2200       'Error message when explicitly named overload method does not exist';
2201
2202     package JustUs;
2203     our @ISA = 'JustYou';
2204     package JustYou { use overload '+' => 'injustice'; }
2205     "JustUs"->${\"(+"};
2206     eval {bless []};
2207     ::like $@, qr/^Stub found while resolving method "\?{3}" overloadin(?x:
2208                   )g "\+" in package "JustUs" at /,
2209       'Error message when sub stub is encountered';
2210 }
2211
2212 {
2213     # check that the right number of stringifications
2214     # and the correct un-utf8-ifying happen on regex compile
2215     package utf8_match;
2216     my $c;
2217     use overload '""' => sub { $c++; $_[0][0] ? "^\x{100}\$" : "^A\$"; };
2218     my $o = bless [0], 'utf8_match';
2219
2220     $o->[0] = 0;
2221     $c = 0;
2222     ::ok("A" =~  "^A\$",        "regex stringify utf8=0 ol=0 bytes=0");
2223     ::ok("A" =~ $o,             "regex stringify utf8=0 ol=1 bytes=0");
2224     ::is($c, 1,                 "regex stringify utf8=0 ol=1 bytes=0 count");
2225
2226     $o->[0] = 1;
2227     $c = 0;
2228     ::ok("\x{100}" =~ "^\x{100}\$",
2229                                 "regex stringify utf8=1 ol=0 bytes=0");
2230     ::ok("\x{100}" =~ $o,       "regex stringify utf8=1 ol=1 bytes=0");
2231     ::is($c, 1,                 "regex stringify utf8=1 ol=1 bytes=0 count");
2232
2233     use bytes;
2234
2235     $o->[0] = 0;
2236     $c = 0;
2237     ::ok("A" =~  "^A\$",        "regex stringify utf8=0 ol=0 bytes=1");
2238     ::ok("A" =~ $o,             "regex stringify utf8=0 ol=1 bytes=1");
2239     ::is($c, 1,                 "regex stringify utf8=0 ol=1 bytes=1 count");
2240
2241     $o->[0] = 1;
2242     $c = 0;
2243     ::ok("\xc4\x80" =~ "^\x{100}\$",
2244                                 "regex stringify utf8=1 ol=0 bytes=1");
2245     ::ok("\xc4\x80" =~ $o,      "regex stringify utf8=1 ol=1 bytes=1");
2246     ::is($c, 1,                 "regex stringify utf8=1 ol=1 bytes=1 count");
2247
2248
2249 }
2250
2251 { # undefining the overload stash -- KEEP THIS TEST LAST
2252     package ant;
2253     use overload '+' => 'onion';
2254     $_ = \&overload::nil;
2255     undef %overload::;
2256     bless[];
2257     ::ok(1, 'no crash when undefining %overload::');
2258 }
2259
2260 # [perl #40333]
2261 # overload::Overloaded should not use a ->can designed for autoloading.
2262 # This example attempts to be as realistic as possible.  The o class has a
2263 # default singleton object, but can have instances, too.  The proxy class
2264 # represents proxies for o objects, but class methods delegate to the
2265 # singleton.
2266 # overload::Overloaded used to return incorrect results for proxy objects.
2267 package proxy {
2268     sub new { bless [$_[1]], $_[0] }
2269     sub AUTOLOAD {
2270        our $AUTOLOAD =~ s/.*:://;
2271        &_self->$AUTOLOAD;
2272     }
2273     sub can      { SUPER::can{@_} || &_self->can($_[1]) }
2274     sub _self { ref $_[0] ? $_[0][0] : $o::singleton }
2275 }
2276 package o     { use overload '""' => sub { 'keck' };
2277                 sub new { bless[], $_[0] }
2278                 our $singleton = o->new; }
2279 ok !overload::Overloaded(new proxy new o),
2280  'overload::Overloaded does not incorrectly return true for proxy classes';
2281
2282 # Another test, based on the type of explosive test class for which
2283 # perl #40333 was filed.
2284 {
2285     package broken_can;
2286     sub can {}
2287     use overload '""' => sub {"Ahoy!"};
2288
2289     package main;
2290     my $obj = bless [], 'broken_can';
2291     ok(overload::Overloaded($obj));
2292 }
2293
2294
2295 # EOF