1
0
mirror of https://github.com/danog/psalm.git synced 2024-11-30 04:39:00 +01:00
psalm/tests/BinaryOperationTest.php

1130 lines
36 KiB
PHP
Raw Normal View History

2016-12-24 00:52:34 +01:00
<?php
2016-12-24 00:52:34 +01:00
namespace Psalm\Tests;
2021-12-03 20:11:20 +01:00
use Psalm\Config;
use Psalm\Context;
2021-12-03 20:29:06 +01:00
use Psalm\Exception\CodeException;
2021-12-04 21:55:53 +01:00
use Psalm\Tests\Traits\InvalidCodeAnalysisTestTrait;
use Psalm\Tests\Traits\ValidCodeAnalysisTestTrait;
2021-12-03 20:11:20 +01:00
use const DIRECTORY_SEPARATOR;
class BinaryOperationTest extends TestCase
2016-12-24 00:52:34 +01:00
{
2021-12-04 21:55:53 +01:00
use InvalidCodeAnalysisTestTrait;
use ValidCodeAnalysisTestTrait;
2016-12-24 00:52:34 +01:00
public function testGMPOperations(): void
{
$this->addFile(
'somefile.php',
'<?php
$a = gmp_init(2);
$b = gmp_init(4);
$c = $a + $b;
$d = $c + 3;
echo $d;
$f = $a / $b;
$g = $a ** $b;
$h = $a % $b;
$i = 6 + $b;
$j = 6 - $b;
$k = 6 * $b;
$l = 6 / $b;
$m = 6 ** $b;
$n = 6 % $b;
$o = $a + 6;
$p = $a - 6;
$q = $a * 6;
$r = $a / 6;
$s = $a ** 6;
2022-12-18 17:15:15 +01:00
$t = $a % 6;',
);
$assertions = [
'$a' => 'GMP',
'$b' => 'GMP',
'$c' => 'GMP',
'$d' => 'GMP',
'$f' => 'GMP',
'$g' => 'GMP',
'$h' => 'GMP',
'$i' => 'GMP',
'$j' => 'GMP',
'$k' => 'GMP',
'$l' => 'GMP',
'$m' => 'GMP',
'$n' => 'GMP',
'$o' => 'GMP',
'$p' => 'GMP',
'$q' => 'GMP',
'$r' => 'GMP',
'$s' => 'GMP',
'$t' => 'GMP',
];
2021-12-03 20:11:20 +01:00
$context = new Context();
$this->analyzeFile('somefile.php', $context);
$actual_vars = [];
foreach ($assertions as $var => $_) {
if (isset($context->vars_in_scope[$var])) {
$actual_vars[$var] = (string)$context->vars_in_scope[$var];
}
}
$this->assertSame($assertions, $actual_vars);
}
public function testDecimalOperations(): void
{
$this->addFile(
'somefile.php',
'<?php
$a = new \Decimal\Decimal(2);
$b = new \Decimal\Decimal(4);
$c = $a + $b;
$d = $c + 3;
echo $d;
$f = $a / $b;
$g = $a ** $b;
$h = $a % $b;
$i = 6 + $b;
$j = 6 - $b;
$k = 6 * $b;
$l = 6 / $b;
$m = 6 ** $b;
$n = 6 % $b;
$o = $a + 6;
$p = $a - 6;
$q = $a * 6;
$r = $a / 6;
$s = $a ** 6;
2022-12-18 17:15:15 +01:00
$t = $a % 6;',
);
$assertions = [
'$a' => 'Decimal\\Decimal',
'$b' => 'Decimal\\Decimal',
'$c' => 'Decimal\\Decimal',
'$d' => 'Decimal\\Decimal',
'$f' => 'Decimal\\Decimal',
'$g' => 'Decimal\\Decimal',
'$h' => 'Decimal\\Decimal',
'$i' => 'Decimal\\Decimal',
'$j' => 'Decimal\\Decimal',
'$k' => 'Decimal\\Decimal',
'$l' => 'Decimal\\Decimal',
'$m' => 'Decimal\\Decimal',
'$n' => 'Decimal\\Decimal',
'$o' => 'Decimal\\Decimal',
'$p' => 'Decimal\\Decimal',
'$q' => 'Decimal\\Decimal',
'$r' => 'Decimal\\Decimal',
'$s' => 'Decimal\\Decimal',
'$t' => 'Decimal\\Decimal',
];
$context = new Context();
$this->analyzeFile('somefile.php', $context);
$actual_vars = [];
foreach ($assertions as $var => $_) {
if (isset($context->vars_in_scope[$var])) {
$actual_vars[$var] = (string)$context->vars_in_scope[$var];
}
}
$this->assertSame($assertions, $actual_vars);
}
2022-10-12 11:40:29 +02:00
public function testMatchOnBoolean(): void
{
$config = Config::getInstance();
$config->strict_binary_operands = true;
Add support for strict arrays, fix type alias intersection, fix array_is_list assertion on non-lists (#8395) * Immutable CodeLocation * Remove excess clones * Remove external clones * Remove leftover clones * Fix final clone issue * Immutable storages * Refactoring * Fixes * Fixes * Fix * Fix * Fixes * Simplify * Fixes * Fix * Fixes * Update * Fix * Cache global types * Fix * Update * Update * Fixes * Fixes * Refactor * Fixes * Fix * Fix * More caching * Fix * Fix * Update * Update * Fix * Fixes * Update * Refactor * Update * Fixes * Break one more test * Fix * FIx * Fix * Fix * Fix * Fix * Improve performance and readability * Equivalent logic * Fixes * Revert * Revert "Revert" This reverts commit f9175100c8452c80559234200663fd4c4f4dd889. * Fix * Fix reference bug * Make default TypeVisitor immutable * Bugfix * Remove clones * Partial refactoring * Refactoring * Fixes * Fix * Fixes * Fixes * cs-fix * Fix final bugs * Add test * Misc fixes * Update * Fixes * Experiment with removing different property * revert "Experiment with removing different property" This reverts commit ac1156e077fc4ea633530d51096d27b6e88bfdf9. * Uniform naming * Uniform naming * Hack hotfix * Clean up $_FILES ref #8621 * Undo hack, try fixing properly * Helper method * Remove redundant call * Partially fix bugs * Cleanup * Change defaults * Fix bug * Fix (?, hope this doesn't break anything else) * cs-fix * Review fixes * Bugfix * Bugfix * Improve logic * Add support for list{} and callable-list{} types, properly implement array_is_list assertions (fixes #8389) * Default to sealed arrays * Fix array_merge bug * Fixes * Fix * Sealed type checks * Properly infer properties-of and get_object_vars on final classes * Fix array_map zipping * Fix tests * Fixes * Fixes * Fix more stuff * Recursively resolve type aliases * Fix typo * Fixes * Fix array_is_list assertion on keyed array * Add BC docs * Fixes * fix * Update * Update * Update * Update * Seal arrays with count assertions * Fix #8528 * Fix * Update * Improve sealed array foreach logic * get_object_vars on template properties * Fix sealed array assertion reconciler logic * Improved reconciler * Add tests * Single source of truth for test types * Fix tests * Fixup tests * Fixup tests * Fixup tests * Update * Fix tests * Fix tests * Final fixes * Fixes * Use list syntax only when needed * Fix tests * Cs-fix * Update docs * Update docs * Update docs * Update docs * Update docs * Document missing types * Update docs * Improve class-string-map docs * Update * Update * I love working on psalm :) * Keep arrays unsealed by default * Fixup tests * Fix syntax mistake * cs-fix * Fix typo * Re-import missing types * Keep strict types only in return types * argc/argv fixes * argc/argv fixes * Fix test * Comment-out valinor code, pinging @romm pls merge https://github.com/CuyZ/Valinor/pull/246 so we can add valinor to the psalm docs :)
2022-11-05 22:34:42 +01:00
2022-10-12 11:40:29 +02:00
$this->addFile(
'somefile.php',
'<?php
class a {}
class b {}
/** @var a|b */
$obj = new a;
$result1 = match (true) {
$obj instanceof a => 123,
$obj instanceof b => 321,
};
$result2 = match (false) {
$obj instanceof a => 123,
$obj instanceof b => 321,
};
2022-12-18 17:15:15 +01:00
',
2022-10-12 11:40:29 +02:00
);
$assertions = [
'$obj' => 'a|b',
'$result1' => '123|321',
'$result2' => '123|321',
];
$context = new Context();
$this->project_analyzer->setPhpVersion('8.0', 'tests');
$this->analyzeFile('somefile.php', $context);
$actual_vars = [];
foreach ($assertions as $var => $_) {
if (isset($context->vars_in_scope[$var])) {
$actual_vars[$var] = $context->vars_in_scope[$var]->getId(true);
}
}
$this->assertSame($assertions, $actual_vars);
}
public function testStrictTrueEquivalence(): void
{
2021-12-03 20:11:20 +01:00
$config = Config::getInstance();
$config->strict_binary_operands = true;
$this->addFile(
'somefile.php',
'<?php
function returnsABool(): bool {
return rand(1, 2) === 1;
}
if (returnsABool() === true) {
echo "hi!";
2022-12-18 17:15:15 +01:00
}',
);
2021-12-03 20:29:06 +01:00
$this->expectException(CodeException::class);
$this->expectExceptionMessage('RedundantIdentityWithTrue');
2021-12-03 20:11:20 +01:00
$this->analyzeFile('somefile.php', new Context());
}
public function testStringFalseInequivalence(): void
{
2021-12-03 20:11:20 +01:00
$config = Config::getInstance();
$config->strict_binary_operands = true;
$this->addFile(
'somefile.php',
'<?php
function returnsABool(): bool {
return rand(1, 2) === 1;
}
if (returnsABool() !== false) {
echo "hi!";
2022-12-18 17:15:15 +01:00
}',
);
2021-12-03 20:29:06 +01:00
$this->expectException(CodeException::class);
$this->expectExceptionMessage('RedundantIdentityWithTrue');
2021-12-03 20:11:20 +01:00
$this->analyzeFile('somefile.php', new Context());
}
public function testDifferingNumericLiteralTypesAdditionInStrictMode(): void
{
$config = Config::getInstance();
$config->strict_binary_operands = true;
$this->addFile(
'somefile.php',
'<?php
2022-12-18 17:15:15 +01:00
$a = 5 + 4.1;',
);
$this->expectException(CodeException::class);
$this->expectExceptionMessage('InvalidOperand');
$this->analyzeFile('somefile.php', new Context());
}
public function testDifferingNumericTypesAdditionInStrictMode(): void
{
$config = Config::getInstance();
$config->strict_binary_operands = true;
$this->addFile(
'somefile.php',
'<?php
/** @var float */
$b = 4.1;
2022-12-18 17:15:15 +01:00
$a = 5 + $b;',
);
$this->expectException(CodeException::class);
$this->expectExceptionMessage('InvalidOperand');
$this->analyzeFile('somefile.php', new Context());
}
public function testConcatenationWithNumberInStrictMode(): void
{
$config = Config::getInstance();
$config->strict_binary_operands = true;
$this->addFile(
'somefile.php',
'<?php
2022-12-18 17:15:15 +01:00
$a = "hi" . 5;',
);
$this->expectException(CodeException::class);
$this->expectExceptionMessage('InvalidOperand');
$this->analyzeFile('somefile.php', new Context());
}
public function testImplicitStringConcatenation(): void
{
$config = Config::getInstance();
$config->strict_binary_operands = true;
$this->addFile(
'somefile.php',
'<?php
interface I {
public function __toString();
}
function takesI(I $i): void
{
$a = $i . "hello";
2022-12-18 17:15:15 +01:00
}',
);
$this->expectException(CodeException::class);
$this->expectExceptionMessage('ImplicitToStringCast');
$this->analyzeFile('somefile.php', new Context());
}
public function providerValidCodeParse(): iterable
2016-12-24 00:52:34 +01:00
{
return [
'regularAddition' => [
'code' => '<?php
2017-05-27 02:05:57 +02:00
$a = 5 + 4;',
'assertions' => [
'$a' => 'int',
],
],
'differingNumericTypesAdditionInWeakMode' => [
'code' => '<?php
2017-05-27 02:05:57 +02:00
$a = 5 + 4.1;',
'assertions' => [
'$a' => 'float',
],
],
'modulo' => [
'code' => '<?php
$a = 25 % 2;
$b = 25.4 % 2;
$c = 25 % 2.5;
$d = 25.5 % 2.5;
$e = 25 % 1;',
'assertions' => [
2020-10-13 02:25:46 +02:00
'$a' => 'int',
'$b' => 'int',
'$c' => 'int',
'$d' => 'int',
'$e' => 'int',
],
],
'numericAddition' => [
'code' => '<?php
$a = "5";
if (is_numeric($a)) {
$b = $a + 4;
2017-05-27 02:05:57 +02:00
}',
],
'concatenation' => [
'code' => '<?php
2017-05-27 02:05:57 +02:00
$a = "Hey " . "Jude,";',
],
'concatenationWithNumberInWeakMode' => [
'code' => '<?php
2017-05-27 02:05:57 +02:00
$a = "hi" . 5;',
],
'concatenationWithTwoLiteralInt' => [
'code' => '<?php
$a = 7 . 5;',
'assertions' => [
'$a' => 'string',//will contain "75"
2022-12-18 17:15:15 +01:00
],
],
'concatenationWithTwoInt' => [
'code' => '<?php
/**
* @param positive-int|0 $b
* @return numeric-string
*/
function scope(int $a, int $b): string{
return $a . $b;
}',
],
'concatenateUnion' => [
'code' => '<?php
$arr = ["foobar" => false, "foobaz" => true, "barbaz" => true];
$foo = random_int(0, 1) ? "foo" : "bar";
$foo .= "baz";
$val = $arr[$foo];
',
'assertions' => ['$val' => 'true'],
],
'concatenateLiteralIntAndString' => [
'code' => '<?php
$arr = ["foobar" => false, "foo123" => true];
$foo = "foo";
$foo .= 123;
$val = $arr[$foo];
',
'assertions' => ['$val' => 'true'],
],
'concatenateNonEmptyResultsInNonEmpty' => [
'code' => '<?php
/** @param non-empty-lowercase-string $arg */
function foobar($arg): string
{
return $arg;
}
$foo = rand(0, 1) ? "a" : "b";
$bar = rand(0, 1) ? "c" : "d";
$baz = $foo . $bar;
foobar($baz);
',
],
'concatenateEmptyWithNonemptyCast' => [
'code' => '<?php
class A
{
/** @psalm-return non-empty-lowercase-string */
public function __toString(): string
{
return "foo";
}
}
/** @param non-empty-lowercase-string $arg */
function foo($arg): string
{
return $arg;
}
$bar = new A();
foo("" . $bar);
',
],
'concatenateNegativeIntLeftSideIsNumeric' => [
'code' => '<?php
/**
* @param numeric-string $bar
* @return int
*/
function foo(string $bar): int
{
return (int) $bar;
}
foo(foo("-123") . 456);
',
],
'castToIntPreserveNarrowerIntType' => [
'code' => '<?php
/**
* @param positive-int $i
* @return positive-int
*/
function takesAnInt(int $i) {
/** @psalm-suppress RedundantCast */
return (int)$i;
}
',
],
'concatenateFloatWithInt' => [
'code' => '<?php
/**
* @param numeric-string $bar
* @return numeric-string
*/
function foo(string $bar): string
{
return $bar;
}
foo(-123.456 . 789);
',
],
'concatenateIntIsLowercase' => [
'code' => '<?php
/**
* @param non-empty-lowercase-string $bar
* @return non-empty-lowercase-string
*/
function foobar(string $bar): string
{
return $bar;
}
/** @var lowercase-string */
$foo = "abc";
/** @var int */
$bar = 123;
foobar($foo . $bar);
',
],
'possiblyInvalidAdditionOnBothSides' => [
'code' => '<?php
function foo(string $s) : int {
return strpos($s, "a") + strpos($s, "b");
}',
'assertions' => [],
'ignored_issues' => ['PossiblyFalseOperand'],
],
'bitwiseoperations' => [
'code' => '<?php
$a = 4 & 5;
$b = 2 | 3;
$c = 4 ^ 3;
$d = 1 << 2;
2018-04-17 00:19:18 +02:00
$e = 15 >> 2;
$f = "a" & "b";',
'assertions' => [
'$a' => 'int',
'$b' => 'int',
'$c' => 'int',
'$d' => 'int',
'$e' => 'int',
2018-04-17 00:19:18 +02:00
'$f' => 'string',
],
],
'ComplexLiteralBitwise' => [
'code' => '<?php
/**
* @return 7
*/
function scope(){
return 1 | 2 | 4 | (1 & 0);
}',
],
'booleanXor' => [
'code' => '<?php
$a = 4 ^ 1;
$b = 3 ^ 1;
$c = (true xor false);
$d = (false xor false);',
'assertions' => [
'$a' => 'int',
'$b' => 'int',
'$c' => 'bool',
'$d' => 'bool',
],
],
'ternaryAssignment' => [
'code' => '<?php
rand(0, 1) ? $a = 1 : $a = 2;
echo $a;',
],
'assignmentInRHS' => [
'code' => '<?php
2018-09-17 18:15:45 +02:00
$name = rand(0, 1) ? "hello" : null;
if ($name !== null || ($name = rand(0, 1) ? "hello" : null) !== null) {}',
],
'floatIncrement' => [
'code' => '<?php
$a = 1.1;
$a++;
$b = 1.1;
$b += 1;',
'assertions' => [
'$a' => 'float',
'$b' => 'float',
],
],
'exponent' => [
'code' => '<?php
$b = 4 ** 5;',
'assertions' => [
'$b' => 'int',
],
],
2019-04-13 16:11:25 +02:00
'bitwiseNot' => [
'code' => '<?php
2019-04-13 16:11:25 +02:00
$a = ~4;
$b = ~4.0;
$c = ~4.4;
$d = ~"a";',
'assertions' => [
'$a' => 'int',
'$b' => 'int',
'$c' => 'int',
'$d' => 'string',
],
],
'stringIncrementSuppressed' => [
'code' => '<?php
$a = "hello";
/** @psalm-suppress StringIncrement */
$a++;',
'assertions' => [
'$a' => 'string',
],
],
'stringIncrementWithCheck' => [
'code' => '<?php
/** @psalm-suppress StringIncrement */
for($a = "a"; $a != "z"; $a++){
if($a === "b"){
echo "b reached";
}
}',
'assertions' => [
'$a===' => 'non-empty-string',
],
],
'nullCoalescingAssignment' => [
'code' => '<?php
function foo(?string $s): string {
$s ??= "Hello";
return $s;
Test parallelization (#4045) * Run tests in random order Being able to run tests in any order is a pre-requisite for being able to run them in parallel. * Reset type coverage between tests, fix affected tests * Reset parser and lexer between test runs and on php version change Previously lexer was reset, but parser kept the reference to the old one, and reference to the parser was kept by StatementsProvider. This resulted in order-dependent tests - if the parser was first initialized with phpVersion set to 7.4 then arrow functions worked fine, but were failing when the parser was initially constructed with settings for 7.3 This can be demonstrated on current master by upgrading to nikic/php-parser:4.9 and running: ``` vendor/bin/phpunit --no-coverage --filter="inferredArgArrowFunction" tests/ClosureTest.php ``` Now all tests using PHP 7.4 features must set the PHP version accordingly. * Marked more tests using 7.4 syntax * Reset newline-between-annotation flag between tests * Resolve real paths before passing them to checkPaths When checkPaths is called from psalm.php the paths are resolved, so we just mimicking SUT behaviour here. * Restore newline-between-annotations in DocCommentTest * Tweak Appveyor caches * Tweak TravisCI caches * Tweak CircleCI caches * Run tests in parallel Use `vendor/bin/paratest` instead of `vendor/bin/phpunit` * Use default paratest runner on Windows WrapperRunner is not supported on Windows. * TRAVIS_TAG could be empty * Restore appveyor conditional caching
2020-08-23 16:32:07 +02:00
}',
'assertions' => [],
'ignored_issues' => [],
'php_version' => '7.4',
],
'nullCoalescingArrayAssignment' => [
'code' => '<?php
/**
* @param array<string> $arr
*/
function foo(array $arr) : void {
$b = [];
foreach ($arr as $a) {
$b[0] ??= $a;
}
Test parallelization (#4045) * Run tests in random order Being able to run tests in any order is a pre-requisite for being able to run them in parallel. * Reset type coverage between tests, fix affected tests * Reset parser and lexer between test runs and on php version change Previously lexer was reset, but parser kept the reference to the old one, and reference to the parser was kept by StatementsProvider. This resulted in order-dependent tests - if the parser was first initialized with phpVersion set to 7.4 then arrow functions worked fine, but were failing when the parser was initially constructed with settings for 7.3 This can be demonstrated on current master by upgrading to nikic/php-parser:4.9 and running: ``` vendor/bin/phpunit --no-coverage --filter="inferredArgArrowFunction" tests/ClosureTest.php ``` Now all tests using PHP 7.4 features must set the PHP version accordingly. * Marked more tests using 7.4 syntax * Reset newline-between-annotation flag between tests * Resolve real paths before passing them to checkPaths When checkPaths is called from psalm.php the paths are resolved, so we just mimicking SUT behaviour here. * Restore newline-between-annotations in DocCommentTest * Tweak Appveyor caches * Tweak TravisCI caches * Tweak CircleCI caches * Run tests in parallel Use `vendor/bin/paratest` instead of `vendor/bin/phpunit` * Use default paratest runner on Windows WrapperRunner is not supported on Windows. * TRAVIS_TAG could be empty * Restore appveyor conditional caching
2020-08-23 16:32:07 +02:00
}',
'assertions' => [],
'ignored_issues' => [],
'php_version' => '7.4',
],
'addArrays' => [
'code' => '<?php
/**
* @param array{host?:string} $opts
* @return array{host:string|int}
*/
function a(array $opts): array {
return $opts + ["host" => 5];
2022-12-18 17:15:15 +01:00
}',
],
'addIntToZero' => [
'code' => '<?php
$tick = 0;
test($tick + 1);
$tick++;
test($tick);
/**
* @psalm-param positive-int $tickedTimes
*/
2022-12-18 17:15:15 +01:00
function test(int $tickedTimes): void {}',
],
2020-10-08 00:01:41 +02:00
'numericPlusIntegerIsIntOrFloat' => [
'code' => '<?php
2020-10-08 00:01:41 +02:00
/** @param numeric-string $s */
function foo(string $s) : void {
$s = $s + 1;
if (is_int($s)) {}
2022-12-18 17:15:15 +01:00
}',
2020-10-08 00:01:41 +02:00
],
'interpolatedStringNotEmpty' => [
'code' => '<?php
/**
* @psalm-param non-empty-string $i
*/
function func($i): string
{
return $i;
}
function foo(string $a) : void {
func("asdasdasd $a");
2022-12-18 17:15:15 +01:00
}',
],
'spaceshipOpIsLiteralUnionType' => [
'code' => '<?php
/**
* @psalm-param -1|0|1 $i
*/
function onlyZeroOrPlusMinusOne(int $i): int {
return $i;
}
/**
* @psalm-param mixed $a
* @psalm-param mixed $b
*/
function foo($a, $b): void {
onlyZeroOrPlusMinusOne($a <=> $b);
2022-12-18 17:15:15 +01:00
}',
],
'notAlwaysPositiveBitOperations' => [
'code' => '<?php
$a = 1;
$b = 1;
$c = 32;
$d = 64;
$e = 2;
if (0 === ($a ^ $b)) {
echo "Actually, zero\n";
}
if (0 === ($a & $e)) {
echo "Actually, zero\n";
}
if (0 === ($a >> $b)) {
echo "Actually, zero\n";
}
if (8 === PHP_INT_SIZE) {
if (0 === ($a << $d)) {
echo "Actually, zero\n";
}
2022-12-18 17:15:15 +01:00
}',
2021-03-12 19:24:00 +01:00
],
2021-03-29 21:09:44 +02:00
'IntOverflowMul' => [
'code' => '<?php
2021-03-12 19:24:00 +01:00
$a = (1024 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024);',
'assertions' => [
2022-12-18 17:15:15 +01:00
'$a' => 'float',
2021-03-12 19:24:00 +01:00
],
2021-03-29 21:09:44 +02:00
],
'IntOverflowPow' => [
'code' => '<?php
2021-03-29 21:09:44 +02:00
$a = 2 ** 80;',
'assertions' => [
2022-12-18 17:15:15 +01:00
'$a' => 'float',
2021-03-29 21:09:44 +02:00
],
],
2021-06-13 12:40:54 +02:00
'IntOverflowPlus' => [
'code' => '<?php
$a = 2**62 - 1 + 2**62;
2021-06-13 12:40:54 +02:00
$b = 2**62 + 2**62 - 1; // plus results in a float',
'assertions' => [
'$a' => 'int',
'$b' => 'float',
],
],
2021-06-13 12:04:12 +02:00
'IntOverflowPowSub' => [
'code' => '<?php
2021-06-13 12:04:12 +02:00
$a = 2 ** 63;',
'assertions' => [
2022-12-18 17:15:15 +01:00
'$a' => 'float',
2021-06-13 12:04:12 +02:00
],
],
'IntOverflowSub' => [
'code' => '<?php
$a = (1 << 63) - (1 << 20);',
'assertions' => [
2022-12-18 17:15:15 +01:00
'$a' => 'float',
],
],
'literalConcatCreatesLiteral' => [
'code' => '<?php
/**
* @param literal-string $s1
* @param literal-string $s2
* @return literal-string
*/
function foo(string $s1, string $s2): string {
return $s1 . $s2;
}',
],
'literalConcatCreatesLiteral2' => [
'code' => '<?php
/**
* @param literal-string $s1
* @return literal-string
*/
function foo(string $s1): string {
return $s1 . 2;
}',
],
'encapsedStringIncludingLiterals' => [
'code' => '<?php
/**
* @param literal-string $s1
* @param literal-string $s2
* @return literal-string
*/
function foo(string $s1, string $s2): string {
return "Hello $s1 $s2";
}',
],
'encapsedStringIncludingLiterals2' => [
'code' => '<?php
/**
* @param literal-string $s1
* @return literal-string
*/
function foo(string $s1): string {
$s2 = 2;
return "Hello $s1 $s2";
}',
],
'encapsedStringIsInferredAsLiteral' => [
2022-07-07 07:21:35 +02:00
'code' => '<?php
$int = 1;
$float = 2.3;
$string = "foobar";
$interpolated = "{$int}{$float}{$string}";
',
2022-07-07 07:21:35 +02:00
'assertions' => ['$interpolated===' => "'12.3foobar'"],
],
'concatenatedStringIsInferredAsLiteral' => [
2022-07-07 07:21:35 +02:00
'code' => '<?php
$int = 1;
$float = 2.3;
$string = "foobar";
$concatenated = $int . $float . $string;
',
2022-07-07 07:21:35 +02:00
'assertions' => ['$concatenated===' => "'12.3foobar'"],
],
'encapsedNonEmptyNonSpecificLiteralString' => [
2022-07-07 07:21:35 +02:00
'code' => '<?php
/** @var non-empty-literal-string */
$string = "foobar";
$interpolated = "$string";
',
'assertions' => ['$interpolated===' => 'non-empty-literal-string'],
],
'concatenatedNonEmptyNonSpecificLiteralString' => [
2022-07-07 07:21:35 +02:00
'code' => '<?php
/** @var non-empty-literal-string */
$string = "foobar";
$concatenated = $string . "";
',
'assertions' => ['$concatenated===' => 'non-empty-literal-string'],
],
2022-06-25 03:28:04 +02:00
'encapsedPossiblyEmptyLiteralString' => [
2022-07-07 07:21:35 +02:00
'code' => '<?php
2022-06-25 03:28:04 +02:00
/** @var "foo"|"" */
$foo = "";
/** @var "bar"|"" */
$bar = "";
$interpolated = "{$foo}{$bar}";
',
'assertions' => ['$interpolated===' => 'literal-string'],
],
'literalIntConcatCreatesLiteral' => [
'code' => '<?php
/**
* @param literal-string $s1
* @param literal-int $s2
* @return literal-string
*/
function foo(string $s1, int $s2): string {
return $s1 . $s2;
}',
],
'literalIntConcatCreatesLiteral2' => [
'code' => '<?php
/**
* @param literal-int $s1
* @return literal-string
*/
function foo(int $s1): string {
return "foo" . $s1;
}',
],
'numericWithInt' => [
'code' => '<?php
/** @return numeric */
function getNumeric(){
return 1;
}
$a = getNumeric();
$a++;
$b = getNumeric() * 2;
$c = 1 - getNumeric();
$d = 2;
$d -= getNumeric();
',
'assertions' => [
'$a' => 'float|int',
'$b' => 'float|int',
'$c' => 'float|int',
'$d' => 'float|int',
],
],
'encapsedStringWithIntIncludingLiterals' => [
'code' => '<?php
/**
* @param literal-int $s1
* @param literal-int $s2
* @return literal-string
*/
function foo(int $s1, int $s2): string {
return "Hello $s1 $s2";
}',
],
'encapsedStringWithIntIncludingLiterals2' => [
'code' => '<?php
/**
* @param literal-int $s1
* @return literal-string
*/
function foo(int $s1): string {
$s2 = "foo";
return "Hello $s1 $s2";
}',
],
2021-07-23 21:22:00 +02:00
'NumericStringIncrement' => [
'code' => '<?php
2021-07-23 21:22:00 +02:00
function scope(array $a): int|float {
$offset = array_search("foo", $a);
if(is_numeric($offset)){
return $offset++;
}
else{
return 0;
}
}',
2022-01-22 01:00:45 +01:00
'assertions' => [],
'ignored_issues' => [],
'php_version' => '8.0',
2021-07-23 21:22:00 +02:00
],
'NumericStringIncrementLiteral' => [
'code' => '<?php
$a = "123";
$b = "123";
$a++;
++$b;
',
'assertions' => [
'$a' => 'float|int',
'$b' => 'float|int',
],
],
'coalesceFilterOutNullEvenWithTernary' => [
'code' => '<?php
interface FooInterface
{
public function toString(): ?string;
}
function example(object $foo): string
{
return ($foo instanceof FooInterface ? $foo->toString() : null) ?? "Not a stringable foo";
}',
2022-01-24 20:55:23 +01:00
],
'handleLiteralInequalityWithInts' => [
'code' => '<?php
/**
* @param int<0, max> $i
* @return int<1, max>
*/
function toPositiveInt(int $i): int
{
if ($i !== 0) {
return $i;
}
return 1;
}',
],
'calculateLiteralResultForFloats' => [
'code' => '<?php
$foo = 1.0 + 2.0;
',
'assertions' => ['$foo===' => 'float(3)'],
],
'concatNonEmptyReturnNonFalsyString' => [
'code' => '<?php
/** @var non-empty-string $s1 */
$s1 = "0";
/** @var non-empty-string $s1 */
$s2 = "0";
$a = $s1.$s2;',
'assertions' => [
'$a===' => 'non-falsy-string',
],
],
'concatNumericWithNonEmptyReturnNonFalsyString' => [
'code' => '<?php
/** @var numeric-string $s1 */
$s1 = "1";
/** @var non-empty-string $s2 */
$s2 = "0";
$a = $s1.$s2;
$b = $s2.$s1;',
'assertions' => [
'$a===' => 'non-falsy-string',
'$b===' => 'non-falsy-string',
],
],
];
2016-12-24 00:52:34 +01:00
}
public function providerInvalidCodeParse(): iterable
2016-12-24 00:52:34 +01:00
{
return [
'badAddition' => [
'code' => '<?php
$a = "b" + 5;',
2017-05-27 02:05:57 +02:00
'error_message' => 'InvalidOperand',
],
'addArrayToNumber' => [
'code' => '<?php
$a = [1] + 1;',
'error_message' => 'InvalidOperand',
],
'concatenateNegativeIntRightSideIsNotNumeric' => [
'code' => '<?php
/**
* @param numeric-string $bar
* @return int
*/
function foo(string $bar): int
{
return (int) $bar;
}
foo(foo("123") . foo("-456"));
',
'error_message' => 'ArgumentTypeCoercion',
],
'additionWithClassInWeakMode' => [
'code' => '<?php
$a = "hi" + (new stdClass);',
'error_message' => 'InvalidOperand',
],
'possiblyInvalidOperand' => [
'code' => '<?php
$b = rand(0, 1) ? [] : 4;
echo $b + 5;',
'error_message' => 'PossiblyInvalidOperand',
],
'possiblyInvalidConcat' => [
'code' => '<?php
$b = rand(0, 1) ? [] : "hello";
echo $b . "goodbye";',
'error_message' => 'PossiblyInvalidOperand',
],
2018-05-05 18:59:30 +02:00
'invalidGMPOperation' => [
'code' => '<?php
2018-05-05 18:59:30 +02:00
$a = gmp_init(2);
$b = "a" + $a;',
2019-02-27 22:00:44 +01:00
'error_message' => 'InvalidOperand - src' . DIRECTORY_SEPARATOR . 'somefile.php:3:26 - Cannot add GMP to non-numeric type',
2018-05-05 18:59:30 +02:00
],
'stringIncrement' => [
'code' => '<?php
$a = "hello";
$a++;',
'error_message' => 'StringIncrement',
],
'falseIncrement' => [
'code' => '<?php
$a = false;
$a++;',
'error_message' => 'FalseOperand',
],
'trueIncrement' => [
'code' => '<?php
$a = true;
$a++;',
'error_message' => 'InvalidOperand',
],
'possiblyDivByZero' => [
'code' => '<?php
$a = 5 / (rand(0, 1) ? 2 : null);',
'error_message' => 'PossiblyNullOperand',
],
'invalidExponent' => [
'code' => '<?php
$a = "x" ^ 1;',
'error_message' => 'InvalidOperand',
],
'invalidBitwiseOr' => [
'code' => '<?php
$a = "x" | new stdClass;',
'error_message' => 'InvalidOperand',
],
2019-04-13 16:11:25 +02:00
'invalidBitwiseNot' => [
'code' => '<?php
2019-04-13 16:11:25 +02:00
$a = ~new stdClass;',
'error_message' => 'InvalidOperand',
],
'possiblyInvalidBitwiseNot' => [
'code' => '<?php
2019-04-13 16:11:25 +02:00
$a = ~(rand(0, 1) ? 2 : null);',
'error_message' => 'PossiblyInvalidOperand',
],
'invalidBooleanBitwiseNot' => [
'code' => '<?php
2019-04-13 16:11:25 +02:00
$a = ~true;',
'error_message' => 'InvalidOperand',
],
'substrImpossible' => [
'code' => '<?php
class HelloWorld
{
public function sayHello(string $s): void
{
if (substr($s, 0, 6) === "abc") {}
}
}',
'error_message' => 'TypeDoesNotContainType',
],
'literalConcatWithStringCreatesString' => [
'code' => '<?php
/**
* @param literal-string $s2
* @return literal-string
*/
function foo(string $s1, string $s2): string {
return $s1 . $s2;
}',
'error_message' => 'LessSpecificReturnStatement',
],
'encapsedConcatWithStringCreatesString' => [
'code' => '<?php
/**
* @param literal-string $s2
* @return literal-string
*/
function foo(string $s1, string $s2): string {
return "hello $s1 $s2";
}',
'error_message' => 'LessSpecificReturnStatement',
],
];
2016-12-24 00:52:34 +01:00
}
}