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