fix: prevent PHP scalar values from over-promoting array dtype - #33
Merged
Merged
Conversation
CodeWithKyrian
force-pushed
the
fix/scalar-promotion-over-widening
branch
from
June 15, 2026 12:01
12ef70e to
3ea1438
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This PR fixes scalar dtype promotion so that a plain PHP scalar does not force up-widening of the array's dtype — matching the intuitive expectation that
$float32Array->add(5.0)stays Float32.Motivation and Context
Previously,
DType::promote()was used for both array×array and array×scalar operations. Since PHP'sDType::fromValue(5.0)always returns Float64, a Float32 array combined with a PHP float scalar would promote to Float64, silently doubling memory usage and precision. Similarly, a UInt8 array plus an Int scalar would promote to Int64. This was inconsistent with how scalars combine with arrays in other numerical libraries where plain scalar values don't force up-widening.What's Changed
DType::promote_scalar()— scalar promotion that keeps float array width and integral array type, except where conversion is required (int+float → float, UInt64+signed → Float64 for overflow safety)scalar_op_arithmeticandscalar_op_comparisonmacros to usepromote_scalarget_scalar_as_u8/u16/u32/u64TypePromotionTestcovering Float32+5.0, UInt8+5, Int32+10, UInt64+-1Breaking Changes
Any code relying on scalar operations producing Float64 from Float32 arrays will now get Float32. This is a narrowing change that could affect downstream precision-sensitive code.