1
0
mirror of https://github.com/danog/psalm.git synced 2024-11-27 04:45:20 +01:00

Merge pull request #7103 from AndrolGenhald/feature/3938-decimal-operator-overloads

This commit is contained in:
Bruce Weirdan 2021-12-08 23:22:24 +02:00 committed by GitHub
commit eb2f4dca89
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 611 additions and 0 deletions

View File

@ -81,6 +81,7 @@ jobs:
php-version: '8.0'
tools: composer:v2
coverage: none
extensions: decimal
- uses: actions/checkout@v2

View File

@ -1969,6 +1969,11 @@ class Config
$this->internal_stubs[] = $ext_mysqli_path;
}
if (extension_loaded('decimal')) {
$ext_decimal_path = $dir_lvl_2 . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR . 'decimal.phpstub';
$this->internal_stubs[] = $ext_decimal_path;
}
foreach ($this->internal_stubs as $stub_path) {
if (!file_exists($stub_path)) {
throw new UnexpectedValueException('Cannot locate ' . $stub_path);

View File

@ -36,6 +36,7 @@ use Psalm\Type\Atomic\TMixed;
use Psalm\Type\Atomic\TNamedObject;
use Psalm\Type\Atomic\TNull;
use Psalm\Type\Atomic\TNumeric;
use Psalm\Type\Atomic\TNumericString;
use Psalm\Type\Atomic\TPositiveInt;
use Psalm\Type\Atomic\TTemplateParam;
@ -611,6 +612,49 @@ class ArithmeticOpAnalyzer
return null;
}
if ($parent instanceof PhpParser\Node\Expr\BinaryOp\Plus
|| $parent instanceof PhpParser\Node\Expr\BinaryOp\Minus
|| $parent instanceof PhpParser\Node\Expr\BinaryOp\Mul
|| $parent instanceof PhpParser\Node\Expr\BinaryOp\Div
|| $parent instanceof PhpParser\Node\Expr\BinaryOp\Mod
|| $parent instanceof PhpParser\Node\Expr\BinaryOp\Pow
) {
$non_decimal_type = null;
if ($left_type_part instanceof TNamedObject
&& strtolower($left_type_part->value) === "decimal\\decimal"
) {
$non_decimal_type = $right_type_part;
} elseif ($right_type_part instanceof TNamedObject
&& strtolower($right_type_part->value) === "decimal\\decimal"
) {
$non_decimal_type = $left_type_part;
}
if ($non_decimal_type !== null) {
if ($non_decimal_type instanceof TInt
|| $non_decimal_type instanceof TNumericString
|| $non_decimal_type instanceof TNamedObject
&& strtolower($non_decimal_type->value) === "decimal\\decimal"
) {
$result_type = Type::combineUnionTypes(
new Type\Union([new TNamedObject("Decimal\\Decimal")]),
$result_type
);
} else {
if ($statements_source) {
IssueBuffer::maybeAdd(
new InvalidOperand(
"Cannot add Decimal\\Decimal to {$non_decimal_type->getId()}",
new CodeLocation($statements_source, $parent)
),
$statements_source->getSuppressedIssues()
);
}
}
return null;
}
}
if ($left_type_part instanceof Type\Atomic\TLiteralString) {
if (preg_match('/^\-?\d+$/', $left_type_part->value)) {
$left_type_part = new Type\Atomic\TLiteralInt((int) $left_type_part->value);

492
stubs/decimal.phpstub Normal file
View File

@ -0,0 +1,492 @@
<?php
namespace Decimal;
/**
* Copied from https://github.com/php-decimal/stubs/blob/master/Decimal.php
*
* The MIT License (MIT)
* Copyright (c) 2018 Rudi Theunissen
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
* THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
final class Decimal implements \JsonSerializable
{
/**
* These constants are for auto-complete only.
*/
const ROUND_UP = 101; /* Round away from zero. */
const ROUND_DOWN = 102; /* Round towards zero. */
const ROUND_CEILING = 103; /* Round towards positive infinity */
const ROUND_FLOOR = 104; /* Round towards negative infinity */
const ROUND_HALF_UP = 105; /* Round to nearest, ties away from zero. */
const ROUND_HALF_DOWN = 106; /* Round to nearest, ties towards zero. */
const ROUND_HALF_EVEN = 107; /* Round to nearest, ties towards even. */
const ROUND_HALF_ODD = 108; /* Round to nearest, ties towards odd. */
const ROUND_TRUNCATE = 109; /* Truncate, keeping infinity. */
const DEFAULT_ROUNDING = Decimal::ROUND_HALF_EVEN;
const DEFAULT_PRECISION = 28;
const MIN_PRECISION = 1;
const MAX_PRECISION = 0; /* This value may change across platforms */
/**
* Constructor
*
* Initializes a new instance using a given value and minimum precision.
*
* @param Decimal|string|int $value
* @param int $precision
*
* @throws \BadMethodCallException if already constructed.
* @throws \TypeError if the value is not a decimal, string, or integer.
* @throws \DomainException is the type is supported but the value could not
* be converted to decimal.
*/
public function __construct($value, int $precision = Decimal::DEFAULT_PRECISION) {}
/**
* Sum
*
* The precision of the result will be the max of all precisions that were
* encountered during the calculation. The given precision should therefore
* be considered the minimum precision of the result.
*
* This method is equivalent to adding each value individually.
*
* @param array|\Traversable $values
* @param int $precision Minimum precision of the sum.
*
* @return Decimal the sum of all given values.
*
* @throws \TypeError if an unsupported type is encountered.
* @throws \ArithmeticError if addition is undefined, eg. INF + -INF
*/
public static function sum($values, int $precision = Decimal::DEFAULT_PRECISION): Decimal {}
/**
* Average
*
* The precision of the result will be the max of all precisions that were
* encountered during the calculation. The given precision should therefore
* be considered the minimum precision of the result.
*
* This method is equivalent to adding each value individually,
* then dividing by the number of values.
*
* @param array|\Traversable $values
* @param int $precision Minimum precision of the average.
*
* @return Decimal the average of all given values.
*
* @throws \TypeError if an unsupported type is encountered.
* @throws \ArithmeticError if addition is undefined, eg. INF + -INF
*/
public static function avg($values, int $precision = Decimal::DEFAULT_PRECISION): Decimal {}
/**
* Copy
*
* @param int $precision The precision of the return value, which defaults
* to the precision of this decimal.
*
* @return Decimal a copy of this decimal.
*/
public function copy(int $precision = null): Decimal {}
/**
* Add
*
* This method is equivalent to the `+` operator.
*
* The precision of the result will be the max of this decimal's precision
* and the given value's precision, where scalar values assume the default.
*
* @param Decimal|string|int $value
*
* @return Decimal the result of adding this decimal to the given value.
*
* @throws \TypeError if the value is not a decimal, string or integer.
*/
public function add($value): Decimal {}
/**
* Subtract
*
* This method is equivalent to the `-` operator.
*
* The precision of the result will be the max of this decimal's precision
* and the given value's precision, where scalar values assume the default.
*
* @param Decimal|string|int $value
*
* @return Decimal the result of subtracting a given value from this decimal.
*
* @throws \TypeError if the value is not a decimal, string or integer.
*/
public function sub($value): Decimal {}
/**
* Multiply
*
* This method is equivalent to the `*` operator.
*
* The precision of the result will be the max of this decimal's precision
* and the given value's precision, where scalar values assume the default.
*
* @param Decimal|string|int $value
*
* @return Decimal the result of multiplying this decimal by the given value.
*
* @throws \TypeError if the given value is not a decimal, string or integer.
*/
public function mul($value): Decimal {}
/**
* Divide
*
* This method is equivalent to the `/` operator.
*
* The precision of the result will be the max of this decimal's precision
* and the given value's precision, where scalar values assume the default.
*
* @param Decimal|string|int $value
*
* @return Decimal the result of dividing this decimal by the given value.
*
* @throws \TypeError if the value is not a decimal, string or integer.
* @throws \DivisionByZeroError if dividing by zero.
* @throws \ArithmeticError if division is undefined, eg. INF / -INF
*/
public function div($value): Decimal {}
/**
* Modulo (integer)
*
* This method is equivalent to the `%` operator.
*
* The precision of the result will be the max of this decimal's precision
* and the given value's precision, where scalar values assume the default.
*
* @see Decimal::rem for the decimal remainder.
*
* @param Decimal|string|int $value
*
* @return Decimal the remainder after dividing the integer value of this
* decimal by the integer value of the given value
*
* @throws \TypeError if the value is not a decimal, string or integer.
* @throws \DivisionByZeroError if the integer value of $value is zero.
* @throws \ArithmeticError if the operation is undefined, eg. INF % -INF
*/
public function mod($value): Decimal {}
/**
* Remainder
*
* The precision of the result will be the max of this decimal's precision
* and the given value's precision, where scalar values assume the default.
*
* @param Decimal|string|int $value
*
* @return Decimal the remainder after dividing this decimal by a given value.
*
* @throws \TypeError if the value is not a decimal, string or integer.
* @throws \DivisionByZeroError if the integer value of $value is zero.
* @throws \ArithmeticError if the operation is undefined, eg. INF, -INF
*/
public function rem($value): Decimal {}
/**
* Power
*
* This method is equivalent to the `**` operator.
*
* The precision of the result will be the max of this decimal's precision
* and the given value's precision, where scalar values assume the default.
*
* @param Decimal|string|int $exponent The power to raise this decimal to.
*
* @return Decimal the result of raising this decimal to a given power.
*
* @throws \TypeError if the exponent is not a decimal, string or integer.
*/
public function pow($exponent): Decimal {}
/**
* Natural logarithm
*
* This method is equivalent in function to PHP's `log`.
*
* @return Decimal the natural logarithm of this decimal (log base e),
* with the same precision as this decimal.
*/
public function ln(): Decimal {}
/**
* Exponent
*
* @return Decimal the exponent of this decimal, ie. e to the power of this,
* with the same precision as this decimal.
*/
public function exp(): Decimal {}
/**
* Base-10 logarithm
*
* @return Decimal the base-10 logarithm of this decimal, with the same
* precision as this decimal.
*/
public function log10(): Decimal {}
/**
* Square root
*
* @return Decimal the square root of this decimal, with the same precision
* as this decimal.
*/
public function sqrt(): Decimal {}
/**
* Floor
*
* @return Decimal the closest integer towards negative infinity.
*/
public function floor(): Decimal {}
/**
* Ceiling
*
* @return Decimal the closest integer towards positive infinity.
*/
public function ceil(): Decimal {}
/**
* Truncate
*
* @return Decimal the integer value of this decimal.
*/
public function truncate(): Decimal {}
/**
* Round
*
* @param int $places The number of places behind the decimal to round to.
* @param int $mode The rounding mode, which are constants of Decimal.
*
* @return Decimal the value of this decimal with the same precision,
* rounded according to the specified number of decimal
* places and rounding mode
*
* @throws \InvalidArgumentException if the rounding mode is not supported.
*/
public function round(int $places = 0, int $mode = Decimal::DEFAULT_ROUNDING): Decimal {}
/**
* Decimal point shift.
*
* @param int $places The number of places to shift the decimal point by.
* A positive shift moves the decimal point to the right,
* a negative shift moves the decimal point to the left.
*
* @return Decimal A copy of this decimal with its decimal place shifted.
*/
public function shift(int $places): Decimal {}
/**
* Trims trailing zeroes.
*
* @return Decimal A copy of this decimal without trailing zeroes.
*/
public function trim(): Decimal {}
/**
* Precision
*
* @return int the precision of this decimal.
*/
public function precision(): int {}
/**
* Signum
*
* @return int 0 if zero, -1 if negative, or 1 if positive.
*/
public function signum(): int {}
/**
* Parity (integer)
*
* @return int 0 if the integer value of this decimal is even, 1 if odd.
* Special numbers like NAN and INF will return 1.
*/
public function parity(): int {}
/**
* Absolute
*
* @return Decimal the absolute (positive) value of this decimal.
*/
public function abs(): Decimal {}
/**
* Negate
*
* @return Decimal the same value as this decimal, but the sign inverted.
*/
public function negate(): Decimal {}
/**
* @return bool TRUE if this decimal is an integer and even, FALSE otherwise.
*/
public function isEven(): bool {}
/**
* @return bool TRUE if this decimal is an integer and odd, FALSE otherwise.
*/
public function isOdd(): bool {}
/**
* @return bool TRUE if this decimal is positive, FALSE otherwise.
*/
public function isPositive(): bool {}
/**
* @return bool TRUE if this decimal is negative, FALSE otherwise.
*/
public function isNegative(): bool {}
/**
* @return bool TRUE if this decimal is not a defined number.
*/
public function isNaN(): bool {}
/**
* @return bool TRUE if this decimal represents infinity, FALSE otherwise.
*/
public function isInf(): bool {}
/**
* @return bool TRUE if this decimal is an integer, ie. does not have
* significant figures behind the decimal point, otherwise FALSE.
*/
public function isInteger(): bool {}
/**
* @return bool TRUE if this decimal is either positive or negative zero.
*/
public function isZero(): bool {}
/**
* @param int $places The number of places behind the decimal point.
* @param bool $commas TRUE if thousands should be separated by a comma.
* @param int $rounding
*
* @return string the value of this decimal formatted to a fixed number of
* decimal places, optionally with thousands comma-separated,
* using a given rounding mode.
*/
public function toFixed(int $places = 0, bool $commas = false, int $rounding = Decimal::DEFAULT_ROUNDING): string {}
/**
* String representation.
*
* This method is equivalent to a cast to string.
*
* This method should not be used as a canonical representation of this
* decimal, because values can be represented in more than one way. However,
* this method does guarantee that a decimal instantiated by its output with
* the same precision will be exactly equal to this decimal.
*
* @return string the value of this decimal represented exactly, in either
* fixed or scientific form, depending on the value.
*/
public function toString(): string {}
/**
* Integer representation.
*
* This method is equivalent to a cast to int.
*
* @return int the integer value of this decimal.
*
* @throws \OverflowException if the value is greater than PHP_INT_MAX.
*/
public function toInt(): int {}
/**
* Binary floating point representation.
*
* This method is equivalent to a cast to float, and is not affected by the
* 'precision' INI setting.
*
* @return float the native PHP floating point value of this decimal.
*
* @throws \OverflowException if the value is greater than PHP_FLOAT_MAX.
* @throws \UnderflowException if the value is smaller than PHP_FLOAT_MIN.
*/
public function toFloat(): float {}
/**
* Equality
*
* This method is equivalent to the `==` operator.
*
* @param mixed $other
*
* @return bool TRUE if this decimal is considered equal to the given value.
* Equal decimal values tie-break on precision.
*/
public function equals($other): bool {}
/**
* Ordering
*
* This method is equivalent to the `<=>` operator.
*
* @param mixed $other
*
* @return int 0 if this decimal is considered is equal to $other,
* -1 if this decimal should be placed before $other,
* 1 if this decimal should be placed after $other.
*/
public function compareTo($other): int {}
/**
* String representation.
*
* This method is equivalent to a cast to string, as well as `toString`.
*
* @return string the value of this decimal represented exactly, in either
* fixed or scientific form, depending on the value.
*/
public function __toString(): string {}
/**
* JSON
*
* This method is only here to honour the interface, and is equivalent to
* `toString`. JSON does not have a decimal type so all decimals are encoded
* as strings in the same format as `toString`.
*
* @return string
*/
public function jsonSerialize() {}
}

View File

@ -85,6 +85,75 @@ class BinaryOperationTest extends TestCase
$this->assertSame($assertions, $actual_vars);
}
public function testDecimalOperations(): void
{
if (!class_exists('Decimal\\Decimal')) {
$this->markTestSkipped('Cannot run test, base class "Decimal\\Decimal" does not exist!');
}
$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;
$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);
}
public function testStrictTrueEquivalence(): void
{
$config = Config::getInstance();