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