Skip to content

fix: throw ArithmeticError when a PHP# int is raised to a negative power - #97

Merged
heyJordanParker merged 2 commits into
masterfrom
feat/int-power
Oct 11, 2026
Merged

heyJordanParker merged 2 commits into
masterfrom
feat/int-power

Conversation

@heyJordanParker

Copy link
Copy Markdown
Owner

Problem

The checker types int ** int as int, but the engine followed PHP for a negative exponent: 2 ** -1 in PHP# code became the float 0.5. A value typed int could hold a float at runtime. Spec section 24 already refuses that silent change to float for an overflow.

Solution

checked_pow_function is the one path every PHP# ** and **= takes, in the VM, the opcache and both JITs. It now throws ArithmeticError, "Integer raised to a negative power", before it computes the power. As an overflow does, it keeps the left operand's int in the result, so a typed property keeps its old value. zend_binary_op_produces_error refuses to fold a PHP# int ** int with a negative exponent, so neither the compiler nor the optimizer turns it into 0.5. A float on either side, and plain PHP code, keep PHP's result.

PHP# ** and **=  (ZEND_POW, ZEND_ASSIGN_*_OP with ZEND_SHARP_OPERATOR)
  ├─ VM handler, and both JITs, which call the VM handler for POW
  ├─ zend_binary_op → get_binary_op(POW | SHARP)
  └─ constant expressions → get_binary_op
        └─ checked_pow_function            (zend_operators.c)
             ├─ int, int, b < 0  → ArithmeticError "Integer raised to a negative power"
             ├─ int, int, overflow → ArithmeticError "Integer overflow"
             └─ a float operand   → pow_function, PHP's result

Folding: compiler, SCCP, pass1, block_pass
        └─ zend_binary_op_produces_error  (zend_compile.c) refuses a PHP# int ** negative int

The spec states the rule in section 24, and decision 75 records it, with the choice to keep **. The checker's compile error for a negative literal exponent is mago-sharp #129. This PR does not re-pin Mago.

Tests

overflow_pow.phpt, overflow_pow_jit_function.phpt and overflow_pow_jit_tracing.phpt run the cases in overflow_pow.inc. Each failed at origin/master and passes here.

  • Negative exponents that throw:
    • ** on two ints, including 0 ** -1.
    • A constant that the optimizer propagates.
    • **= on a typed property, which keeps its old int.
    • **= on an untyped property.
    • Dead ** and dead **=.
  • A float operand: ((float) a) ** b, 2.0 ** -1 and an int raised to a float exponent each give a float.
  • Plain PHP: 2 ** -1 gives float(0.5), from a function and from a literal.

Local runs:

  • sharp/bin/test --opcache --repeat --passes --census --differential on the power tests: all 22 modes pass.
  • sharp/bin/test: 171 of 171 pass.

Problem:
The checker types `int ** int` as `int`, but the engine followed PHP for a
negative exponent: `2 ** -1` in PHP# code became the float 0.5. A value typed
`int` could hold a float at runtime, the silent change to float that spec
section 24 already refuses for an overflow.

Solution:
`checked_pow_function`, the one path every PHP# `**` and `**=` takes in the
VM, the opcache and both JITs, throws "Integer raised to a negative power"
before it computes the power, and keeps the left operand's int in the result
as an overflow does. `zend_binary_op_produces_error` refuses to fold a PHP#
`int ** int` with a negative exponent, so the compiler and the optimizer leave
it to the runtime. A float on either side and plain PHP keep PHP's result.
The spec states the rule in section 24, and decision 75 records it with the
choice to keep `**`.

Zend/
├── zend_operators.c       <- checked_pow_function throws on a negative int exponent
├── zend_compile.c         <- zend_binary_op_produces_error: no compile-time fold of it
└── tests/sharp/
    ├── Overflow.sharp     <- inverse and half take a float base; floatExponent, constantNegativePower
    ├── overflow_pow.inc   <- negative exponents for **, **=, typed and untyped properties,
    │                         dead code, a float operand, and plain PHP
    └── overflow_pow*.phpt <- plain, function JIT and tracing JIT expectations
docs/
├── spec.md                <- section 24: int ** int is an int, a negative exponent throws
└── decisions/075-int-power.md  <- the decision, its options and precedent
@heyJordanParker

Copy link
Copy Markdown
Owner Author

Review verdict: CHANGES NEEDED

The engine is correct. I found no path that turns a PHP# int ** negative int into a float, and plain PHP is unchanged. One line of the fold guard has no test, and it is the line that keeps 0 ** -1 free of a deprecation.

Changes

  1. Zend/tests/sharp/Overflow.sharp, overflow_pow.inc and the three overflow_pow*.phpt files: no test covers the new early return in zend_binary_op_produces_error.

    For a non-zero base the early return is redundant. The next line calls PHP's own pow_function, which returns a float for a negative exponent, so the function already returns true. For a base of 0 the early return is the only thing that stops the optimizer from calling pow_function(0, -1). That call goes through safe_pow and raises E_DEPRECATED "Power of base 0 and negative exponent is deprecated" while the .sharp file compiles.

    if (opcode == ZEND_POW && Z_LVAL_P(op2) < 0) {
    	return 1;                                   // only load-bearing for a base of 0
    }
    get_binary_op(opcode)(&result, (zval *) op1, (zval *) op2);   // plain pow_function
    return Z_TYPE(result) == IS_DOUBLE;

    Overflow::power(0, -1) passes its values at runtime, so the optimizer never folds it. constantNegativePower uses a base of 2. If someone deletes those three lines, every current test still passes, and PHP# code under opcache prints a deprecation that the spec rules out.

    Do this: add a case where the optimizer propagates a base of 0. Then --passes with SCCP alone fails if the guard goes away.

    +    public static int zeroNegativePower()
    +    {
    +        let z = 0;
    +        let n = -1;
    +        return z ** n;
    +    }
         attempt(fn () => Overflow::constantNegativePower());
    +    attempt(fn () => Overflow::zeroNegativePower());

    Each of the three .phpt files then expects one more ArithmeticError: Integer raised to a negative power line, with no Deprecated line.

    I checked this on the engine at df3a006221. My copy of that method dumps as T0 = POW int(0) int(-1) after the optimizer (opcache.opt_debug_level=0x20000). It throws ArithmeticError with no deprecation in all 22 modes. So the PR's code is right, and the test only protects it.

Verified on the engine

The engine was built at df3a006221 in sharp-worktrees/2, with Mago 449377ad4f. I ran a probe .phpt outside the tree, through sharp/bin/test --opcache --repeat --passes <probe>. It passed in all 22 modes. The PR's three tests also passed in all 22 modes, 3 of 3 in each.

Every PHP# case throws ArithmeticError: Integer raised to a negative power at the right .sharp line:

  • a ** b with (2, -1), (0, -1), (-2, -3), (1, -1) and (2, PHP_INT_MIN). (2, 0) gives int(1).
  • The literals 2 ** -1 and 0 ** -1, and x **= -1. The pinned checker still accepts these, so they exercise the compiler's fold path.
  • A class constant HALF = 2 ** Constants.NEG, read from PHP# and from PHP.
  • A parameter default int a = 2 ** Constants.NEG.
  • A field default private int field = 2 ** Constants.NEG.
  • A static field **= -1. The field keeps int(2).
  • A typed property **= -1. The property keeps int(2).
  • A typed property that plain PHP holds by reference, $r = &$box->value. Both keep int(3).
  • A local passed to a plain PHP int &$x parameter, then **= -1.
  • A match arm 1 => 2 ** b.
  • A propagated constant 0 ** -1, with no deprecation.

The opcache file cache is covered by the priming and using modes.

The checker refuses every array or collection element **= in PHP# code: List, Map, and a PHP array property. So ASSIGN_DIM_OP with the PHP# mark cannot be reached today.

Plain PHP keeps PHP's result:

  • 2 ** -1 in a .php file gives float(0.5). The optimizer folds it to RETURN float(0.5), so the fold guard does not affect plain PHP.
  • 0 ** -1 in a .php file prints PHP's own deprecation and gives float(INF). It stays unfolded, as upstream.
  • PHP# calls a plain PHP function that does $a ** $b or $x **= $b: it gives float(0.5). With (0, -1) it gives PHP's deprecation and float(INF).
  • ((float) a) ** b and 2.0 ** -1 in PHP# give float(0.5).

Code, spec and decision

  • checked_pow_function checks the negative exponent before pow_function_base, so a PHP# int never reaches safe_pow. checked_negative_exponent keeps the left operand's long, as checked_overflow does. zend_binary_assign_op_typed_prop and zend_binary_assign_op_typed_ref assign the result even on failure, so that write is load-bearing. The powProperty(new Cell(2), -1) test with its var_dump protects it.
  • Both JITs leave ** and **= to the VM handler, because zend_jit_supported_binary_op returns false for ZEND_POW. zend_may_throw_ex already marks a PHP# POW on longs as throwing, so dead-code elimination keeps deadPower and deadPowAssign. Their tests show it.
  • docs/spec.md section 24: the code block is exactly the four approved lines. The bullet text matches the approved wording.
  • docs/decisions/075-int-power.md uses 073's sections: Decision, Options with Chosen and Rejected code blocks, Precedent, and Spec. It holds the three type options and the two syntax options Jordan was shown, with Option 1 and "keep **" chosen. Every precedent claim is accurate. Unlike 073 and 074, its precedent has no source links or quotes, as its task asked. No change is needed.
  • Every other test in the PR proves a rule and fails on a real bug. None pins incidental output.

Problem:
`zend_binary_op_produces_error` refuses to fold a PHP# `int ** int` with a
negative exponent, but no test covered it. Without those three lines, the
optimizer folds `0 ** -1` with PHP's pow. PHP prints "Power of base 0 and
negative exponent is deprecated" at compile time, under opcache, in PHP#
code the spec says only throws. Every test still passed with the guard
removed, because no case raised a constant zero base to a negative power.

Solution:
`Overflow::zeroNegativePower` raises a constant-propagated `0 ** -1`. Each
of the three pow tests expects one ArithmeticError "Integer raised to a
negative power" at its line and no Deprecated line. With the guard removed,
the tracing JIT and function JIT runs of overflow_pow.phpt fail on that
Deprecated line.

Zend/tests/sharp/
├── Overflow.sharp      <- zeroNegativePower, appended so no earlier line moves
├── overflow_pow.inc    <- calls it after constantNegativePower
└── overflow_pow*.phpt  <- plain, function JIT and tracing JIT expect its throw
@heyJordanParker

Copy link
Copy Markdown
Owner Author

team-lead approval: APPROVED at head 26da919, once CI_PASSED passes on it.

  • The review found the engine correct, with one test missing: fix: throw ArithmeticError when a PHP# int is raised to a negative power #97 (comment).
  • 26da919 adds exactly that test, and team-lead read every line of the diff from df3a006:
    • Overflow::zeroNegativePower() (let z = 0; let n = -1; return z ** n;), appended so no earlier line moves
    • its attempt(…) call in overflow_pow.inc
    • one more ArithmeticError: Integer raised to a negative power in Overflow.sharp on line 349 in each of the three .phpt files, with no Deprecated line
  • The spec bullet holds exactly the four lines Jordan approved, and decision 075 records both of his ** choices.

Merge after CI_PASSED passes, with --match-head-commit 26da919efc53f444b4c996178a9a5174c203446c.

@heyJordanParker
heyJordanParker merged commit 741cd4e into master Oct 11, 2026
10 checks passed
@heyJordanParker
heyJordanParker deleted the feat/int-power branch November 3, 2026 22:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant