Skip to content

Preserve imaginary zero signs when adding real values to complex numbers#7421

Open
moreal wants to merge 4 commits intoRustPython:mainfrom
moreal:fix/fail-builtin-test-sum
Open

Preserve imaginary zero signs when adding real values to complex numbers#7421
moreal wants to merge 4 commits intoRustPython:mainfrom
moreal:fix/fail-builtin-test-sum

Conversation

@moreal
Copy link
Contributor

@moreal moreal commented Mar 13, 2026

This pull request lets complex + float operations preserve the zero sign of the imag part.

Arithmetic operations use PyComplex::number_op, which converts float (real) to Complex64 to simplify logic, but it loses the zero sign. For instance, in CPython, complex(1, -0.0j) + 1 becomes 2-0j, and complex(1, -0.0j) + complex(1, 0.0j) becomes 2+0j. However, PyComplex::number_op converts float to complex, so it becomes complex(1, 0.0j), which differs from CPython.

Summary by CodeRabbit

  • Refactor
    • Internal consolidation of complex-number arithmetic logic for improved maintainability and consistency.
    • No changes to public APIs or observable behavior; users should see no functional differences.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 13, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: e8d9fb06-d631-4aa3-bedd-f91ea972453a

📥 Commits

Reviewing files that changed from the base of the PR and between df60617 and 2c45f61.

📒 Files selected for processing (1)
  • crates/vm/src/builtins/complex.rs

📝 Walkthrough

Walkthrough

Adds a private helper PyComplex::complex_real_binop to centralize binary operations between complex and real operands and updates PyComplex::as_number to use it for addition and subtraction; no public API changes.

Changes

Cohort / File(s) Summary
Complex number logic
crates/vm/src/builtins/complex.rs
Added private helper PyComplex::complex_real_binop<...> to unify complex↔real binary ops; replaced inline add/sub implementations in PyComplex::as_number with calls to that helper. Multiply and other ops unchanged.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • youknowone

Poem

🐰 I hop through signs both real and bright,
I joined their steps in one small bite.
Imaginary whiskers, numbers play,
One helper guides them on their way. ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly describes the main change: preserving imaginary zero signs when adding real values to complex numbers, which aligns with the core objective of the PR.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions
Copy link
Contributor

github-actions bot commented Mar 13, 2026

📦 Library Dependencies

The following Lib/ modules were modified. Here are their dependencies:

[x] test: cpython/Lib/test/test_builtin.py (TODO: 18)

dependencies:

dependent tests: (no tests depend on builtin)

Legend:

  • [+] path exists in CPython
  • [x] up-to-date, [ ] outdated

@moreal moreal marked this pull request as ready for review March 14, 2026 04:03
static AS_NUMBER: PyNumberMethods = PyNumberMethods {
add: Some(|a, b, vm| PyComplex::number_op(a, b, |a, b, _vm| a + b, vm)),
add: Some(complex_add),
subtract: Some(|a, b, vm| PyComplex::number_op(a, b, |a, b, _vm| a - b, vm)),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how about subtract? is this okay without change?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In subtract case, it may work because -0.0 - 0.0 (i.e., "minus-sign zero" - "plus-sign zero") is evaluated as -0.0.

fn main() {
    let val: f64 = -0f64 - 0f64;
    println!("{val:?}"); // -0.0
}

fn main() {
    let val: f64 = -0f64 + 0f64;
    println!("{val:?}"); // 0.0
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

$ python3 -c 'print(1 - (1+0j))'
-0j
$ cargo run --  -c 'print(1 - (1+0j))'
0j

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't check real - complex. I'll look into it more.

Copy link
Contributor Author

@moreal moreal Mar 14, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The issue was that only the real part should have been touched, but because of the conversion process to Complex64, the imaginary part was also being affected; so it was actually strange that there were no issues with subtraction. Thank you.

In CPython, these are handled by writing separate logic for each case, similar to _Py_{c,cr,rc}_xx. Accordingly, I created a helper function called complex_real_binop, like number_op, and used it to write separate logic for each case in addition and subtraction (df60617). (As for the function naming... if you have any alternatives, please let me know.)

$ cargo run -q --  -c 'print(1 - (1+0j))'
-0j

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
crates/vm/src/builtins/complex.rs (1)

291-303: Generic type parameter ordering is inconsistent with function parameter ordering.

The generic type parameters are declared as CCF, RCF, CRF, but the function parameters are ordered as cc_op, cr_op, rc_op. This mismatch is confusing—RCF (second generic) corresponds to rc_op (third parameter), while CRF (third generic) corresponds to cr_op (second parameter).

🔧 Suggested fix: reorder generic type parameters
-    fn complex_real_binop<CCF, RCF, CRF, R>(
+    fn complex_real_binop<CCF, CRF, RCF, R>(
         a: &PyObject,
         b: &PyObject,
         cc_op: CCF,
         cr_op: CRF,
         rc_op: RCF,
         vm: &VirtualMachine,
     ) -> PyResult
     where
         CCF: FnOnce(Complex64, Complex64, &VirtualMachine) -> R,
-        CRF: FnOnce(Complex64, f64, &VirtualMachine) -> R,
-        RCF: FnOnce(f64, Complex64, &VirtualMachine) -> R,
+        CRF: FnOnce(Complex64, f64, &VirtualMachine) -> R,
+        RCF: FnOnce(f64, Complex64, &VirtualMachine) -> R,
         R: ToPyResult,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/vm/src/builtins/complex.rs` around lines 291 - 303, The generic type
parameter order in complex_real_binop is inconsistent with the function
parameter order; reorder the type parameters from CCF, RCF, CRF to CCF, CRF, RCF
so that CCF -> cc_op, CRF -> cr_op, and RCF -> rc_op (update the where-clause
and all uses of these type parameters in the signature accordingly).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@crates/vm/src/builtins/complex.rs`:
- Around line 291-303: The generic type parameter order in complex_real_binop is
inconsistent with the function parameter order; reorder the type parameters from
CCF, RCF, CRF to CCF, CRF, RCF so that CCF -> cc_op, CRF -> cr_op, and RCF ->
rc_op (update the where-clause and all uses of these type parameters in the
signature accordingly).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: a2505c85-3f96-4a3a-bb84-d9d2f68c7ba1

📥 Commits

Reviewing files that changed from the base of the PR and between c3fba4b and df60617.

📒 Files selected for processing (1)
  • crates/vm/src/builtins/complex.rs

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.

2 participants