psalm icon indicating copy to clipboard operation
psalm copied to clipboard

Math on FFI\CData is not supported

Open bwoebi opened this issue 1 year ago • 3 comments

https://psalm.dev/r/105180030a

A simple $cdata + 1 will emit InvalidOperand and assume the result is int|float.

bwoebi avatar Jan 14 '24 21:01 bwoebi

I found these snippets:

https://psalm.dev/r/105180030a
<?php

function math(): FFI\CData {
	$var = new FFI\CData;
	return $var + 1;
}
Psalm output (using commit a75d26a):

ERROR: InvalidOperand - 5:9 - Cannot perform a numeric operation with a non-numeric type FFI\CData

ERROR: InvalidReturnStatement - 5:9 - The inferred type 'float|int' does not match the declared return type 'FFI\CData' for math

ERROR: InvalidReturnType - 3:18 - The declared return type 'FFI\CData' for math is incorrect, got 'float|int'

psalm-github-bot[bot] avatar Jan 14 '24 21:01 psalm-github-bot[bot]

Running the following on PHP 8.3.2 produces PHP Fatal error: Uncaught TypeError: Unsupported operand types: FFI\CData + int, so what make you think Psalm is wrong to report InvalidOperand?

<?php
var_dump(PHP_VERSION);
function math(): FFI\CData
{
    $var = FFI::new('int');
    var_dump($var);
    return $var + 1;
}
math();
/home/weirdan/src/php-src/q.php:2:
string(5) "8.3.2"
/home/weirdan/src/php-src/q.php:6:
class FFI\CData#1 (1) {
  public $cdata =>
  int(0)
}
PHP Fatal error:  Uncaught TypeError: Unsupported operand types: FFI\CData + int in /home/weirdan/src/php-src/q.php:7
Stack trace:
#0 /home/weirdan/src/php-src/q.php(9): math()
#1 {main}
  thrown in /home/weirdan/src/php-src/q.php on line 7

weirdan avatar Jan 28 '24 03:01 weirdan

@weirdan Try using FFI::new('int*') instead of FFI::new('int') - pointer arithmetic is allowed, arithmetic on non-pointers is not. Psalm has no idea whether a FFI\CData value is pointer or not and should just allow it.

bwoebi avatar Feb 06 '24 21:02 bwoebi