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