Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions phpunit/code/float-numeric-string-arithmetic.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php
function floatNumericStringQuotient(): float
{
return "1e2" / 4;
}
function floatNumericStringAssign(): void
{
$x = "1e2" / 4;
var_dump($x);
$y = "1.5" * 2;
var_dump($y);
}
function intNumericStringArithmetic(): void
{
var_dump("10" / 2);
}
2 changes: 1 addition & 1 deletion phpunit/src/CompilerBaseApiTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -399,7 +399,7 @@ public function testGeneratedCValuesAreAlwaysSourceCodeStrings(): void
public function testNumericStringIdentifiersGenerateSourceCodeStrings(): void
{
$this->assertSame(
(string) floatval('0.2'),
'2e-1',
$this->invokeMethod('parseNumericIdentifier', new \PhpParser\Node\Scalar\String_('0.2'))
);
$this->assertSame(
Expand Down
33 changes: 33 additions & 0 deletions phpunit/src/FloatNumericStringArithmeticTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

use TypePhp\CompilerTest;

final class FloatNumericStringArithmeticTest extends \BaseTest
{
public function testFloatNumericStringOperandsKeepFloatSemantics(): void
{
global $translator;

$compiler = CompilerTest::create(TYPEPHP_ROOT_PATH);
$translator = $compiler;
$source = TYPEPHP_ROOT_PATH . '/phpunit/code/float-numeric-string-arithmetic.php';
$compiler->addFiles([$source]);
$compiler->prepareFile($source);
$code = file_get_contents($compiler->convertFile($source));
self::assertIsString($code);

// "1e2" must convert to a C++ double literal, not an integer literal,
// so the division stays in the floating-point domain.
self::assertStringContainsString('((1e+2) / (4L))', $code);
self::assertDoesNotMatchRegularExpression('/\(\(100\) \/ \(4L\)\)/', $code);

// The inferred storage of an assignment from float-valued numeric
// string arithmetic is php::Float, not php::Int.
self::assertMatchesRegularExpression('/php::Float x = /', $code);
self::assertMatchesRegularExpression('/php::Float y = /', $code);
self::assertMatchesRegularExpression('/php::Float php_floatnumericstringquotient\(\)/', $code);

// Integer-syntax numeric strings keep native integer arithmetic.
self::assertStringContainsString('((10) / (2L))', $code);
}
}
26 changes: 23 additions & 3 deletions src/CompilerBase.php
Original file line number Diff line number Diff line change
Expand Up @@ -2427,12 +2427,16 @@ protected function parseEcho(mixed $v): string
protected function parseNumericIdentifier(NodeAbstract $expr): string
{
if ($expr instanceof Node\Scalar\String_) {
if ($this->isFloatStr($expr->value)) {
return (string) floatval($expr->value);
$floatValue = floatval($expr->value);
if ($this->isFloatNumericString($expr->value) && is_finite($floatValue)) {
return $this->shortestFloatRepr($floatValue);
}
if ($this->isIntStr($expr->value)) {
return (string) intval($expr->value);
}
if ($this->isFloatStr($expr->value)) {
return (string) floatval($expr->value);
}
if ($expr->value === '0') {
return '0';
}
Expand Down Expand Up @@ -3542,7 +3546,23 @@ protected function detectTypeOfExpr($expr): string
if ($leftType === Type::FLOAT || $rightType === Type::FLOAT) {
return Type::FLOAT;
}
if ($this->varIntTypes && $leftType === Type::INT && $rightType === Type::INT) {
if (in_array($exprType, [
'Expr_BinaryOp_Plus',
'Expr_BinaryOp_Minus',
'Expr_BinaryOp_Mul',
'Expr_BinaryOp_Div',
'Expr_BinaryOp_Pow',
], true)
&& (($leftType === Type::STR && $this->isFloatNumericStringExpr($expr->left))
|| ($rightType === Type::STR && $this->isFloatNumericStringExpr($expr->right)))
) {
return Type::FLOAT;
}
$leftIntLike = $leftType === Type::INT
|| ($leftType === Type::STR && $this->isIntNumericStringExpr($expr->left));
$rightIntLike = $rightType === Type::INT
|| ($rightType === Type::STR && $this->isIntNumericStringExpr($expr->right));
if ($this->varIntTypes && $leftIntLike && $rightIntLike) {
$op = match ($exprType) {
'Expr_BinaryOp_Plus' => '+',
'Expr_BinaryOp_Minus' => '-',
Expand Down
10 changes: 10 additions & 0 deletions src/Parser/BinaryOpTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -463,6 +463,16 @@ protected function constantNumericValue(NodeAbstract $expr, bool $nativeSemantic
if ($expr instanceof Node\Scalar\Float_) {
return $expr->value;
}
if ($expr instanceof Node\Scalar\String_) {
if ($this->isIntNumericString($expr->value)) {
return intval($expr->value);
}
if ($this->isFloatNumericString($expr->value)) {
$floatValue = floatval($expr->value);
return is_finite($floatValue) ? $floatValue : null;
}
return null;
}
if ($expr instanceof Node\Expr\UnaryPlus) {
return $this->constantNumericValue($expr->expr, $nativeSemantics);
}
Expand Down
44 changes: 44 additions & 0 deletions src/Parser/TypeDetectionTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,50 @@ protected function isFloatStr(string $str): bool
return filter_var($str, FILTER_VALIDATE_FLOAT) !== false;
}

/**
* Whether the value is an integer-syntax numeric string (one that PHP
* juggles as an int in arithmetic): optionally signed decimal digits
* with optional surrounding whitespace, within the int64 range.
* Matches "5", " 10 ", but not "1.5", "1e2", or "9223372036854775808"
* (out of int64 range — PHP promotes those to float).
*/
protected function isIntNumericString(string $value): bool
{
if (!is_numeric($value)
|| !preg_match('/^[\t\n\r\v\f ]*([+-]?)([0-9]+)[\t\n\r\v\f ]*$/', $value, $m)) {
return false;
}
$digits = ltrim($m[2], '0');
if ($digits === '') {
return true;
}
$len = strlen($digits);
if ($len < 19) {
return true;
}
if ($len > 19) {
return false;
}
// Exactly 19 digits: must fit in int64. PHP_INT_MAX is
// 9223372036854775807; negative values may reach |PHP_INT_MIN|.
return strcmp($digits, $m[1] === '-' ? '9223372036854775808' : '9223372036854775807') <= 0;
}

protected function isFloatNumericString(string $value): bool
{
return is_numeric($value) && !$this->isIntNumericString($value);
}

protected function isFloatNumericStringExpr(NodeAbstract $expr): bool
{
return $expr instanceof Node\Scalar\String_ && $this->isFloatNumericString($expr->value);
}

protected function isIntNumericStringExpr(NodeAbstract $expr): bool
{
return $expr instanceof Node\Scalar\String_ && $this->isIntNumericString($expr->value);
}

protected function isIntStr(string $str): bool
{
return filter_var($str, FILTER_VALIDATE_INT) !== false;
Expand Down
55 changes: 55 additions & 0 deletions tests/compiler/operator/float-numeric-string-arithmetic.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
--TEST--
Float-valued numeric string arithmetic keeps PHP float semantics
--FILE--
<?php
function main(): void
{
var_dump("1e2" / 4);
var_dump("1e2" + 0);
var_dump("2e1" * 2);
var_dump("2e1" ** 2);
var_dump("-2e1" + 0);
var_dump(".5" + 0);
var_dump(" 1.5 " + 0);
$x = "1e2" / 4;
var_dump($x);
$y = "1.5" * 2;
var_dump($y);
$f = "1e2";
var_dump($f / 4);
var_dump("5" + 1);
var_dump("10" / 2);
var_dump("1e400" + 0.0);
var_dump(is_float("9223372036854775808" + 0));
var_dump("9223372036854775807" + 0);
$x = "9223372036854775808" * 2;
var_dump(is_float($x));
var_dump($x > PHP_INT_MAX);
var_dump("2.5" ** "2");
var_dump("9223372036854775807" ** 2);
var_dump("1e300" * "1e300");
var_dump("1.5" < 2);
}
?>
--EXPECT--
float(25)
float(100)
float(40)
float(400)
float(-20)
float(0.5)
float(1.5)
float(25)
float(3)
float(25)
int(6)
int(5)
float(INF)
bool(true)
int(9223372036854775807)
bool(true)
bool(true)
float(6.25)
float(8.507059173023462E+37)
float(INF)
bool(true)
24 changes: 24 additions & 0 deletions tests/compiler/operator/numeric-string-varint-types.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
--TEST--
Integer-syntax numeric strings follow varint_types PHP semantics
--FILE--
<?php
use varint_types;

function main(): void
{
var_dump("9223372036854775807" * 2);
var_dump("9223372036854775807" + 0);
var_dump("5" / 2);
var_dump("10" / 2);
$n = 2;
var_dump("5" / $n);
try { var_dump("5" / "0"); } catch (DivisionByZeroError $e) { echo "DivisionByZeroError\n"; }
}
?>
--EXPECT--
float(1.8446744073709552E+19)
int(9223372036854775807)
float(2.5)
int(5)
float(2.5)
DivisionByZeroError
Loading