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