Skip to content

fix(compiler): bitwise not of string and bool operands - #148

Open
Giandonn wants to merge 1 commit into
swoole:masterfrom
Giandonn:fix/bitwise-not-operands
Open

Giandonn wants to merge 1 commit into
swoole:masterfrom
Giandonn:fix/bitwise-not-operands

Conversation

@Giandonn

@Giandonn Giandonn commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

Fixes #147

parseBitwiseNot() converted every operand to int.

The change

  • A statically string, bool or array operand goes through the Variant operator, i.e. Zend's bitwise_not_function(): a string has its bytes inverted, bool/array raise TypeError. ~$string is inferred as a string.
  • int, float and operands of unknown type keep the native ~. A first version also routed unknown types through Variant, which broke NativePropertyTest::testNativeIntPropertyAssignOpConvertsBitwiseNotClassConst: class constants are not typed statically, so $flags &= ~ReflectionClassConstant::IS_PUBLIC (and the common ~self::FLAG idiom) would have lost the native operator. That is kept as it was.

Not covered: ~$mixed holding a string at runtime still goes through the int path, as on master.

Verified on a binary

PHP 8.4.26 ZTS with embed, GCC 11, Linux x64. 11 cases (~false, ~true, ~"abc", ~"", ~"1e3", $x = ~"ab", ~~"xyz", ~5, ~PHP_INT_MIN, ~1.5, ~$mixed int):

master this PR
program with the 11 cases does not compile identical to PHP
new operator/bitwise-not-operands.phpt FAIL PASS
tests/compiler (full) — 1248 passed, 0 failed, 27 skipped
PHPUnit (full) — 2408 tests OK, 4 skipped

Found with a differential fuzzer.

parseBitwiseNot() converted every operand to int. PHP's ~ inverts the bytes
of a string and returns a string, and raises "Cannot perform bitwise not on
<type>" for bool and array:

    function f(string $s): mixed { return ~$s; }
    bin2hex(f("abc"));   // PHP: 9e9d9c   compiled: "-1" (2d31)
    ~false;              // PHP: TypeError   compiled: -1

and `$x = ~"ab"` in a function returning string did not compile (ambiguous
conversion from php::Int to php::Str).

A statically string, bool or array operand now goes through the Variant
operator, i.e. Zend's bitwise_not_function(), and ~$string is inferred as a
string. int, float and operands of unknown type keep the native operator, so
idioms such as `$flags &= ~self::FLAG` (class constants are not typed
statically) still compile to a plain C++ ~.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

~ converts string and bool operands to int

1 participant