This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
541d671b69a60014e866e183b93b065837a3a85a
[perl5.git] / t / op / bop.t
1 #!./perl
2
3 #
4 # test the bit operators '&', '|', '^', '~', '<<', and '>>'
5 #
6
7 use warnings;
8
9 BEGIN {
10     chdir 't' if -d 't';
11     require "./test.pl";
12     set_up_inc('../lib');
13     require "./charset_tools.pl";
14     require Config;
15 }
16
17 # Tests don't have names yet.
18 # If you find tests are failing, please try adding names to tests to track
19 # down where the failure is, and supply your new names as a patch.
20 # (Just-in-time test naming)
21 plan tests => 471;
22
23 # numerics
24 ok ((0xdead & 0xbeef) == 0x9ead);
25 ok ((0xdead | 0xbeef) == 0xfeef);
26 ok ((0xdead ^ 0xbeef) == 0x6042);
27 ok ((~0xdead & 0xbeef) == 0x2042);
28
29 # shifts
30 ok ((257 << 7) == 32896);
31 ok ((33023 >> 7) == 257);
32
33 # signed vs. unsigned
34 ok ((~0 > 0 && do { use integer; ~0 } == -1));
35
36 my $bits = 0;
37 for (my $i = ~0; $i; $i >>= 1) { ++$bits; }
38 my $cusp = 1 << ($bits - 1);
39
40
41 ok (($cusp & -1) > 0 && do { use integer; $cusp & -1 } < 0);
42 ok (($cusp | 1) > 0 && do { use integer; $cusp | 1 } < 0);
43 ok (($cusp ^ 1) > 0 && do { use integer; $cusp ^ 1 } < 0);
44 ok ((1 << ($bits - 1)) == $cusp &&
45     do { use integer; 1 << ($bits - 1) } == -$cusp);
46 ok (($cusp >> 1) == ($cusp / 2) &&
47     do { use integer; abs($cusp >> 1) } == ($cusp / 2));
48
49 $Aaz = chr(ord("A") & ord("z"));
50 $Aoz = chr(ord("A") | ord("z"));
51 $Axz = chr(ord("A") ^ ord("z"));
52
53 # short strings
54 is (("AAAAA" & "zzzzz"), ($Aaz x 5));
55 is (("AAAAA" | "zzzzz"), ($Aoz x 5));
56 is (("AAAAA" ^ "zzzzz"), ($Axz x 5));
57
58 # long strings
59 $foo = "A" x 150;
60 $bar = "z" x 75;
61 $zap = "A" x 75;
62 # & truncates
63 is (($foo & $bar), ($Aaz x 75 ));
64 # | does not truncate
65 is (($foo | $bar), ($Aoz x 75 . $zap));
66 # ^ does not truncate
67 is (($foo ^ $bar), ($Axz x 75 . $zap));
68
69 # string constants.  These tests expect the bit patterns of these strings in
70 # ASCII, so convert to that.
71 sub _and($) { $_[0] & native_to_uni("+0") }
72 sub _oar($) { $_[0] | native_to_uni("+0") }
73 sub _xor($) { $_[0] ^ native_to_uni("+0") }
74 is _and native_to_uni("waf"), native_to_uni('# '),  'str var & const str'; # [perl #20661]
75 is _and native_to_uni("waf"), native_to_uni('# '),  'str var & const str again'; # [perl #20661]
76 is _oar native_to_uni("yit"), native_to_uni('{yt'), 'str var | const str';
77 is _oar native_to_uni("yit"), native_to_uni('{yt'), 'str var | const str again';
78 is _xor native_to_uni("yit"), native_to_uni('RYt'), 'str var ^ const str';
79 is _xor native_to_uni("yit"), native_to_uni('RYt'), 'str var ^ const str again';
80
81 SKIP: {
82     skip "Converting a numeric doesn't work with EBCDIC unlike the above tests",
83          3 if $::IS_EBCDIC;
84     is _and  0, '0',   'num var & const str';     # [perl #20661]
85     is _oar  0, '0',   'num var | const str';
86     is _xor  0, '0',   'num var ^ const str';
87 }
88
89 # But don’t mistake a COW for a constant when assigning to it
90 %h=(150=>1);
91 $i=(keys %h)[0];
92 $i |= 105;
93 is $i, 255, '[perl #108480] $cow |= number';
94 $i=(keys %h)[0];
95 $i &= 105;
96 is $i, 0, '[perl #108480] $cow &= number';
97 $i=(keys %h)[0];
98 $i ^= 105;
99 is $i, 255, '[perl #108480] $cow ^= number';
100
101 #
102 is ("ok \xFF\xFF\n" & "ok 19\n", "ok 19\n");
103 is ("ok 20\n" | "ok \0\0\n", "ok 20\n");
104 is ("o\000 \0001\000" ^ "\000k\0002\000\n", "ok 21\n");
105
106 #
107 is ("ok \x{FF}\x{FF}\n" & "ok 22\n", "ok 22\n");
108 is ("ok 23\n" | "ok \x{0}\x{0}\n", "ok 23\n");
109 is ("o\x{0} \x{0}4\x{0}" ^ "\x{0}k\x{0}2\x{0}\n", "ok 24\n");
110
111 # More variations on 19 and 22.
112 is ("ok \xFF\x{FF}\n" & "ok 41\n", "ok 41\n");
113 is ("ok \x{FF}\xFF\n" & "ok 42\n", "ok 42\n");
114
115 # Tests to see if you really can do casts negative floats to unsigned properly
116 $neg1 = -1.0;
117 ok (~ $neg1 == 0);
118 $neg7 = -7.0;
119 ok (~ $neg7 == 6);
120
121
122 # double magic tests
123
124 sub TIESCALAR { bless { value => $_[1], orig => $_[1] } }
125 sub STORE { $_[0]{store}++; $_[0]{value} = $_[1] }
126 sub FETCH { $_[0]{fetch}++; $_[0]{value} }
127 sub stores { tied($_[0])->{value} = tied($_[0])->{orig};
128              delete(tied($_[0])->{store}) || 0 }
129 sub fetches { delete(tied($_[0])->{fetch}) || 0 }
130
131 # numeric double magic tests
132
133 tie $x, "main", 1;
134 tie $y, "main", 3;
135
136 is(($x | $y), 3);
137 is(fetches($x), 1);
138 is(fetches($y), 1);
139 is(stores($x), 0);
140 is(stores($y), 0);
141
142 is(($x & $y), 1);
143 is(fetches($x), 1);
144 is(fetches($y), 1);
145 is(stores($x), 0);
146 is(stores($y), 0);
147
148 is(($x ^ $y), 2);
149 is(fetches($x), 1);
150 is(fetches($y), 1);
151 is(stores($x), 0);
152 is(stores($y), 0);
153
154 is(($x |= $y), 3);
155 is(fetches($x), 2);
156 is(fetches($y), 1);
157 is(stores($x), 1);
158 is(stores($y), 0);
159
160 is(($x &= $y), 1);
161 is(fetches($x), 2);
162 is(fetches($y), 1);
163 is(stores($x), 1);
164 is(stores($y), 0);
165
166 is(($x ^= $y), 2);
167 is(fetches($x), 2);
168 is(fetches($y), 1);
169 is(stores($x), 1);
170 is(stores($y), 0);
171
172 is(~~$y, 3);
173 is(fetches($y), 1);
174 is(stores($y), 0);
175
176 { use integer;
177
178 is(($x | $y), 3);
179 is(fetches($x), 1);
180 is(fetches($y), 1);
181 is(stores($x), 0);
182 is(stores($y), 0);
183
184 is(($x & $y), 1);
185 is(fetches($x), 1);
186 is(fetches($y), 1);
187 is(stores($x), 0);
188 is(stores($y), 0);
189
190 is(($x ^ $y), 2);
191 is(fetches($x), 1);
192 is(fetches($y), 1);
193 is(stores($x), 0);
194 is(stores($y), 0);
195
196 is(($x |= $y), 3);
197 is(fetches($x), 2);
198 is(fetches($y), 1);
199 is(stores($x), 1);
200 is(stores($y), 0);
201
202 is(($x &= $y), 1);
203 is(fetches($x), 2);
204 is(fetches($y), 1);
205 is(stores($x), 1);
206 is(stores($y), 0);
207
208 is(($x ^= $y), 2);
209 is(fetches($x), 2);
210 is(fetches($y), 1);
211 is(stores($x), 1);
212 is(stores($y), 0);
213
214 is(~$y, -4);
215 is(fetches($y), 1);
216 is(stores($y), 0);
217
218 } # end of use integer;
219
220 # stringwise double magic tests
221
222 tie $x, "main", "a";
223 tie $y, "main", "c";
224
225 is(($x | $y), ("a" | "c"));
226 is(fetches($x), 1);
227 is(fetches($y), 1);
228 is(stores($x), 0);
229 is(stores($y), 0);
230
231 is(($x & $y), ("a" & "c"));
232 is(fetches($x), 1);
233 is(fetches($y), 1);
234 is(stores($x), 0);
235 is(stores($y), 0);
236
237 is(($x ^ $y), ("a" ^ "c"));
238 is(fetches($x), 1);
239 is(fetches($y), 1);
240 is(stores($x), 0);
241 is(stores($y), 0);
242
243 is(($x |= $y), ("a" | "c"));
244 is(fetches($x), 2);
245 is(fetches($y), 1);
246 is(stores($x), 1);
247 is(stores($y), 0);
248
249 is(($x &= $y), ("a" & "c"));
250 is(fetches($x), 2);
251 is(fetches($y), 1);
252 is(stores($x), 1);
253 is(stores($y), 0);
254
255 is(($x ^= $y), ("a" ^ "c"));
256 is(fetches($x), 2);
257 is(fetches($y), 1);
258 is(stores($x), 1);
259 is(stores($y), 0);
260
261 is(~~$y, "c");
262 is(fetches($y), 1);
263 is(stores($y), 0);
264
265 $a = "\0\x{100}"; chop($a);
266 ok(utf8::is_utf8($a)); # make sure UTF8 flag is still there
267 $a = ~$a;
268 is($a, "\xFF", "~ works with utf-8");
269 ok(! utf8::is_utf8($a), "    and turns off the UTF-8 flag");
270
271 $a = "\0\x{100}"; chop($a);
272 undef $b;
273 $b = $a | "\xFF";
274 ok(utf8::is_utf8($b), "Verify UTF-8 | non-UTF-8 retains UTF-8 flag");
275 undef $b;
276 $b = "\xFF" | $a;
277 ok(utf8::is_utf8($b), "Verify non-UTF-8 | UTF-8 retains UTF-8 flag");
278 undef $b;
279 $b = $a & "\xFF";
280 ok(utf8::is_utf8($b), "Verify UTF-8 & non-UTF-8 retains UTF-8 flag");
281 undef $b;
282 $b = "\xFF" & $a;
283 ok(utf8::is_utf8($b), "Verify non-UTF-8 & UTF-8 retains UTF-8 flag");
284 undef $b;
285 $b = $a ^ "\xFF";
286 ok(utf8::is_utf8($b), "Verify UTF-8 ^ non-UTF-8 retains UTF-8 flag");
287 undef $b;
288 $b = "\xFF" ^ $a;
289 ok(utf8::is_utf8($b), "Verify non-UTF-8 ^ UTF-8 retains UTF-8 flag");
290
291
292 # [rt.perl.org 33003]
293 # This would cause a segfault without malloc wrap
294 SKIP: {
295   skip "No malloc wrap checks" unless $Config::Config{usemallocwrap};
296   like( runperl(prog => 'eval q($#a>>=1); print 1'), qr/^1\n?/ );
297 }
298
299 # [perl #37616] Bug in &= (string) and/or m//
300 {
301     $a = "aa";
302     $a &= "a";
303     ok($a =~ /a+$/, 'ASCII "a" is NUL-terminated');
304
305     $b = "bb\x{FF}";
306     utf8::upgrade($b);
307     $b &= "b";
308     ok($b =~ /b+$/, 'Unicode "b" is NUL-terminated');
309 }
310
311 # New string- and number-specific bitwise ops
312 {
313   use feature "bitwise";
314   no warnings "experimental::bitwise";
315   is "22" & "66", 2,    'numeric & with strings';
316   is "22" | "66", 86,   'numeric | with strings';
317   is "22" ^ "66", 84,   'numeric ^ with strings';
318   is ~"22" & 0xff, 233, 'numeric ~ with string';
319   is 22 &. 66, 22,     '&. with numbers';
320   is 22 |. 66, 66,     '|. with numbers';
321   is 22 ^. 66, "\4\4", '^. with numbers';
322   if ($::IS_EBCDIC) {
323     # ord('2') is 0xF2 on EBCDIC
324     is ~.22, "\x0d\x0d", '~. with number';
325   }
326   else {
327     # ord('2') is 0x32 on ASCII
328     is ~.22, "\xcd\xcd", '~. with number';
329   }
330   $_ = "22";
331   is $_ &= "66", 2,  'numeric &= with strings';
332   $_ = "22";
333   is $_ |= "66", 86, 'numeric |= with strings';
334   $_ = "22";
335   is $_ ^= "66", 84, 'numeric ^= with strings';
336   $_ = 22;
337   is $_ &.= 66, 22,     '&.= with numbers';
338   $_ = 22;
339   is $_ |.= 66, 66,     '|.= with numbers';
340   $_ = 22;
341   is $_ ^.= 66, "\4\4", '^.= with numbers';
342
343  # signed vs. unsigned
344  ok ((~0 > 0 && do { use integer; ~0 } == -1));
345
346  my $bits = 0;
347  for (my $i = ~0; $i; $i >>= 1) { ++$bits; }
348  my $cusp = 1 << ($bits - 1);
349
350  ok (($cusp & -1) > 0 && do { use integer; $cusp & -1 } < 0);
351  ok (($cusp | 1) > 0 && do { use integer; $cusp | 1 } < 0);
352  ok (($cusp ^ 1) > 0 && do { use integer; $cusp ^ 1 } < 0);
353  ok ((1 << ($bits - 1)) == $cusp &&
354      do { use integer; 1 << ($bits - 1) } == -$cusp);
355  ok (($cusp >> 1) == ($cusp / 2) &&
356     do { use integer; abs($cusp >> 1) } == ($cusp / 2));
357 }
358
359 # ref tests
360
361 my %res;
362
363 for my $str ("x", "\x{B6}") {
364     utf8::upgrade($str) if $str !~ /x/;
365     for my $chr (qw/S A H G X ( * F/) {
366         for my $op (qw/| & ^/) {
367             my $co = ord $chr;
368             my $so = ord $str;
369             $res{"$chr$op$str"} = eval qq/chr($co $op $so)/;
370         }
371     }
372     $res{"undef|$str"} = $str;
373     $res{"undef&$str"} = "";
374     $res{"undef^$str"} = $str;
375 }
376
377 sub PVBM () { "X" }
378 1 if index "foo", PVBM;
379
380 my $warn = 0;
381 local $^W = 1;
382 local $SIG{__WARN__} = sub { $warn++ };
383
384 sub is_first {
385     my ($got, $orig, $op, $str, $name) = @_;
386     is(substr($got, 0, 1), $res{"$orig$op$str"}, $name);
387 }
388
389 for (
390     # [object to test, first char of stringification, name]
391     [undef,             "undef",    "undef"         ],
392     [\1,                "S",        "scalar ref"    ],
393     [[],                "A",        "array ref"     ],
394     [{},                "H",        "hash ref"      ],
395     [qr/x/,             "(",        "qr//"          ],
396     [*foo,              "*",        "glob"          ],
397     [\*foo,             "G",        "glob ref"      ],
398     [PVBM,              "X",        "PVBM"          ],
399     [\PVBM,             "S",        "PVBM ref"      ],
400     [bless([], "Foo"),  "F",        "object"        ],
401 ) {
402     my ($val, $orig, $type) = @$_;
403
404     for (["x", "string"], ["\x{B6}", "utf8"]) {
405         my ($str, $desc) = @$_;
406         utf8::upgrade($str) if $desc =~ /utf8/;
407
408         $warn = 0;
409
410         is_first($val | $str, $orig, "|", $str, "$type | $desc");
411         is_first($val & $str, $orig, "&", $str, "$type & $desc");
412         is_first($val ^ $str, $orig, "^", $str, "$type ^ $desc");
413
414         is_first($str | $val, $orig, "|", $str, "$desc | $type");
415         is_first($str & $val, $orig, "&", $str, "$desc & $type");
416         is_first($str ^ $val, $orig, "^", $str, "$desc ^ $type");
417
418         my $new;
419         ($new = $val) |= $str;
420         is_first($new, $orig, "|", $str, "$type |= $desc");
421         ($new = $val) &= $str;
422         is_first($new, $orig, "&", $str, "$type &= $desc");
423         ($new = $val) ^= $str;
424         is_first($new, $orig, "^", $str, "$type ^= $desc");
425
426         ($new = $str) |= $val;
427         is_first($new, $orig, "|", $str, "$desc |= $type");
428         ($new = $str) &= $val;
429         is_first($new, $orig, "&", $str, "$desc &= $type");
430         ($new = $str) ^= $val;
431         is_first($new, $orig, "^", $str, "$desc ^= $type");
432
433         if ($orig eq "undef") {
434             # undef |= and undef ^= don't warn
435             is($warn, 10, "no duplicate warnings");
436         }
437         else {
438             is($warn, 0, "no warnings");
439         }
440     }
441 }
442
443 delete $SIG{__WARN__};
444
445 my $strval;
446
447 {
448     package Bar;
449     use overload q/""/ => sub { $strval };
450
451     package Baz;
452     use overload q/|/ => sub { "y" };
453 }
454
455 ok(!eval { 1 if bless([], "Bar") | "x"; 1 },"string overload can't use |");
456 like($@, qr/no method found/,               "correct error");
457 is(eval { bless([], "Baz") | "x" }, "y",    "| overload works");
458
459 my $obj = bless [], "Bar";
460 $strval = "x";
461 eval { $obj |= "Q" };
462 $strval = "z";
463 is("$obj", "z", "|= doesn't break string overload");
464
465 # [perl #29070]
466 $^A .= new version ~$_ for eval sprintf('"\\x%02x"', 0xff - ord("1")),
467                            $::IS_EBCDIC ? v13 : v205, # 255 - ord('2')
468                            eval sprintf('"\\x%02x"', 0xff - ord("3"));
469 is $^A, "123", '~v0 clears vstring magic on retval';
470
471 {
472     my $w = $Config::Config{ivsize} * 8;
473
474     fail("unexpected w $w") unless $w == 32 || $w == 64;
475
476     is(1 << 1, 2, "UV 1 left shift 1");
477     is(1 >> 1, 0, "UV 1 right shift 1");
478
479     is(0x7b << -4, 0x007, "UV left negative shift == right shift");
480     is(0x7b >> -4, 0x7b0, "UV right negative shift == left shift");
481
482     is(0x7b <<  0, 0x07b, "UV left  zero shift == identity");
483     is(0x7b >>  0, 0x07b, "UV right zero shift == identity");
484
485     is(0x0 << -1, 0x0, "zero left  negative shift == zero");
486     is(0x0 >> -1, 0x0, "zero right negative shift == zero");
487
488     cmp_ok(1 << $w - 1, '==', 2 ** ($w - 1), # not is() because NV stringify.
489        "UV left $w - 1 shift == 2 ** ($w - 1)");
490     is(1 << $w,     0, "UV left shift $w     == zero");
491     is(1 << $w + 1, 0, "UV left shift $w + 1 == zero");
492
493     is(1 >> $w - 1, 0, "UV right shift $w - 1 == zero");
494     is(1 >> $w,     0, "UV right shift $w     == zero");
495     is(1 >> $w + 1, 0, "UV right shift $w + 1 == zero");
496
497     # Negative shiftees get promoted to UVs before shifting.  This is
498     # not necessarily the ideal behavior, but that is what is happening.
499     if ($w == 64) {
500         no warnings "portable";
501         no warnings "overflow"; # prevent compile-time warning for ivsize=4
502         is(-1 << 1, 0xFFFF_FFFF_FFFF_FFFE,
503            "neg UV (sic) left shift  = 0xFF..E");
504         is(-1 >> 1, 0x7FFF_FFFF_FFFF_FFFF,
505            "neg UV (sic) right right = 0x7F..F");
506     } elsif ($w == 32) {
507         no warnings "portable";
508         is(-1 << 1, 0xFFFF_FFFE, "neg left shift  == 0xFF..E");
509         is(-1 >> 1, 0x7FFF_FFFF, "neg right right == 0x7F..F");
510     }
511
512     {
513         # 'use integer' means use IVs instead of UVs.
514         use integer;
515
516         # No surprises here.
517         is(1 << 1, 2, "IV 1 left shift 1  == 2");
518         is(1 >> 1, 0, "IV 1 right shift 1 == 0");
519
520         # The left overshift should behave like without 'use integer',
521         # that is, return zero.
522         is(1 << $w,     0, "IV 1 left shift $w     == 0");
523         is(1 << $w + 1, 0, "IV 1 left shift $w + 1 == 0");
524         is(-1 << $w,     0, "IV -1 left shift $w     == 0");
525         is(-1 << $w + 1, 0, "IV -1 left shift $w + 1 == 0");
526
527         # Even for negative IVs, left shift is multiplication.
528         # But right shift should display the stuckiness to -1.
529         is(-1 <<      1, -2, "IV -1 left shift       1 == -2");
530         is(-1 >>      1, -1, "IV -1 right shift      1 == -1");
531
532         # As for UVs, negative shifting means the reverse shift.
533         is(-1 <<     -1, -1, "IV -1 left shift      -1 == -1");
534         is(-1 >>     -1, -2, "IV -1 right shift     -1 == -2");
535
536         # Test also at and around wordsize, expect stuckiness to -1.
537         is(-1 >> $w - 1, -1, "IV -1 right shift $w - 1 == -1");
538         is(-1 >> $w,     -1, "IV -1 right shift $w     == -1");
539         is(-1 >> $w + 1, -1, "IV -1 right shift $w + 1 == -1");
540     }
541 }
542
543 # [perl #129287] UTF8 & was not providing a trailing null byte.
544 # This test is a bit convoluted, as we want to make sure that the string
545 # allocated for &’s target contains memory initialised to something other
546 # than a null byte.  Uninitialised memory does not make for a reliable
547 # test.  So we do &. on a longer non-utf8 string first.
548 for (["aaa","aaa"],[substr ("a\x{100}",0,1), "a"]) {
549     use feature "bitwise";
550     no warnings "experimental::bitwise", "pack";
551     $byte = substr unpack("P2", pack "P", $$_[0] &. $$_[1]), -1;
552 }
553 is $byte, "\0", "utf8 &. appends null byte";
554
555 # only visible under sanitize
556 fresh_perl_is('$x = "UUUUUUUV"; $y = "xxxxxxx"; $x |= $y; print $x',
557               ( $::IS_EBCDIC) ? 'XXXXXXXV' : '}}}}}}}V',
558               {}, "[perl #129995] access to freed memory");
559
560
561 #
562 # Using code points above 0xFF is fatal
563 #
564 foreach my $op_info ([and => "&"], [or => "|"], [xor => "^"]) {
565     my ($op_name, $op) = @$op_info;
566     local $@;
567     eval '$_ = "\xFF" ' . $op . ' "\x{100}";';
568     like $@, qr /^Use of strings with code points over 0xFF as arguments (?#
569                  )to bitwise $op_name \Q($op)\E operator is not allowed/,
570          "Use of code points above 0xFF as arguments to bitwise " .
571          "$op_name ($op) is not allowed";
572 }
573
574 {
575     local $@;
576     eval '$_ = ~ "\x{100}";';
577     like $@, qr /^Use of strings with code points over 0xFF as arguments (?#
578                  )to 1's complement \(~\) operator is not allowed/,
579          "Use of code points above 0xFF as argument to 1's complement " .
580          "(~) is not allowed";
581 }