From be86d988821e1921a392130b1d4229afd043a406 Mon Sep 17 00:00:00 2001 From: youknowdot Date: Tue, 1 Dec 2026 14:28:21 +0900 Subject: [PATCH 1/6] Restore selectable BigInt backends Centralize BigInt backend selection in rustpython-bigint, preserving Malachite by default and allowing a mutually exclusive num-bigint build. Route the same selection through the frozen-standard-library compiler and pymath. Revives the approach proposed by h7kanna in #5131. Assisted-by: Codex:GPT-6.2 --- .github/workflows/ci.yaml | 20 +- .github/workflows/cron-ci.yaml | 4 +- .github/workflows/release.yml | 4 +- .github/workflows/update-caches.yml | 2 +- AGENTS.md | 2 +- Cargo.lock | 31 +-- Cargo.toml | 28 +-- README.md | 16 +- crates/bigint/Cargo.toml | 25 +++ crates/bigint/src/lib.rs | 179 ++++++++++++++++++ crates/capi/Cargo.toml | 7 +- crates/capi/src/abstract_/number.rs | 2 +- crates/capi/src/longobject.rs | 2 +- crates/codegen/Cargo.toml | 6 +- crates/codegen/src/compile.rs | 2 +- crates/codegen/src/ir.rs | 2 +- crates/codegen/src/preprocess.rs | 2 +- crates/common/Cargo.toml | 8 +- crates/common/src/cformat.rs | 2 +- crates/common/src/float_ops.rs | 4 +- crates/common/src/format.rs | 33 ++-- crates/common/src/hash.rs | 2 +- crates/common/src/int.rs | 21 +- crates/compiler-core/Cargo.toml | 7 +- crates/compiler-core/src/bytecode.rs | 2 +- crates/compiler-core/src/marshal.rs | 2 +- crates/compiler/Cargo.toml | 7 +- crates/derive-impl/Cargo.toml | 5 + crates/derive/Cargo.toml | 5 + crates/jit/Cargo.toml | 5 + crates/literal/Cargo.toml | 9 +- crates/literal/src/float.rs | 21 +- crates/pylib/Cargo.toml | 3 + crates/stdlib/Cargo.toml | 8 +- crates/stdlib/src/_datetime.rs | 2 +- crates/stdlib/src/_sqlite3.rs | 2 +- crates/stdlib/src/cjkcodecs/multibytecodec.rs | 2 +- crates/stdlib/src/hashlib.rs | 2 +- crates/stdlib/src/json.rs | 2 +- crates/stdlib/src/math.rs | 4 +- crates/stdlib/src/overlapped.rs | 2 +- crates/stdlib/src/pickle.rs | 2 +- crates/stdlib/src/random.rs | 2 +- crates/vm/Cargo.toml | 10 +- crates/vm/src/buffer.rs | 2 +- crates/vm/src/builtins/code.rs | 2 +- crates/vm/src/builtins/descriptor.rs | 6 +- crates/vm/src/builtins/enumerate.rs | 2 +- crates/vm/src/builtins/float.rs | 2 +- crates/vm/src/builtins/int.rs | 2 +- crates/vm/src/builtins/memory/format.rs | 2 +- crates/vm/src/builtins/range.rs | 2 +- crates/vm/src/builtins/slice.rs | 2 +- crates/vm/src/bytes_inner.rs | 2 +- crates/vm/src/convert/try_from.rs | 2 +- crates/vm/src/frame.rs | 2 +- crates/vm/src/function/number.rs | 2 +- crates/vm/src/macros.rs | 4 +- crates/vm/src/sliceable.rs | 2 +- crates/vm/src/stdlib/_ast/constant.rs | 2 +- crates/vm/src/stdlib/_ctypes/simple.rs | 2 +- crates/vm/src/stdlib/_io.rs | 2 +- crates/vm/src/stdlib/_stat.rs | 2 +- crates/vm/src/stdlib/gc.rs | 2 +- crates/vm/src/stdlib/marshal.rs | 4 +- crates/vm/src/stdlib/posix.rs | 4 +- crates/vm/src/stdlib/posix/xattr.rs | 2 +- crates/vm/src/stdlib/posix_compat.rs | 2 +- crates/vm/src/stdlib/winreg.rs | 2 +- crates/vm/src/vm/context.rs | 2 +- crates/vm/src/vm/interpreter.rs | 2 +- crates/wasm/Cargo.toml | 6 +- example_projects/barebone/Cargo.toml | 2 +- example_projects/frozen_stdlib/Cargo.toml | 6 +- .../rustpython-without-js/Cargo.toml | 2 +- host_env_proposal.md | 6 +- scripts/release-wapm.sh | 2 +- scripts/whats_left.py | 5 +- 78 files changed, 422 insertions(+), 179 deletions(-) create mode 100644 crates/bigint/Cargo.toml create mode 100644 crates/bigint/src/lib.rs diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index f9378b403a1..8890aac4a7f 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -19,8 +19,8 @@ concurrency: cancel-in-progress: true env: - CARGO_ARGS: --no-default-features --features stdlib,importlib,stdio,encodings,sqlite,ssl-rustls-aws-lc,host_env,doc,ucd_3_2_0 - CARGO_ARGS_NO_SSL: --no-default-features --features stdlib,importlib,stdio,encodings,sqlite,host_env,doc,ucd_3_2_0 + CARGO_ARGS: --no-default-features --features malachite-bigint,stdlib,importlib,stdio,encodings,sqlite,ssl-rustls-aws-lc,host_env,doc,ucd_3_2_0 + CARGO_ARGS_NO_SSL: --no-default-features --features malachite-bigint,stdlib,importlib,stdio,encodings,sqlite,host_env,doc,ucd_3_2_0 CARGO_ARGS_MOST_FEATS: --features capi,encodings,jit,sqlite,threading # Crates excluded from workspace builds: # - rustpython_wasm: requires wasm target @@ -319,13 +319,13 @@ jobs: - name: check compilation without host_env (sandbox mode) if: env.RUN_RUST_TESTS == 'true' && runner.os == 'Linux' run: | - cargo check --locked -p rustpython-vm --no-default-features --features compiler - cargo check --locked -p rustpython-stdlib --no-default-features --features compiler - cargo build --locked --no-default-features --features stdlib,importlib,stdio,encodings,freeze-stdlib + cargo check --locked -p rustpython-vm --no-default-features --features malachite-bigint,compiler + cargo check --locked -p rustpython-stdlib --no-default-features --features malachite-bigint,compiler + cargo build --locked --no-default-features --features malachite-bigint,stdlib,importlib,stdio,encodings,freeze-stdlib - name: Test FileIO without other host modules if: env.RUN_RUST_TESTS == 'true' && runner.os == 'Linux' - run: cargo test --locked -p rustpython-vm --no-default-features --features compiler,host_io --test host_io + run: cargo test --locked -p rustpython-vm --no-default-features --features malachite-bigint,compiler,host_io --test host_io - name: sandbox smoke test if: env.RUN_RUST_TESTS == 'true' && runner.os == 'Linux' @@ -336,7 +336,7 @@ jobs: - name: Test openssl build if: env.RUN_RUST_TESTS == 'true' && runner.os == 'Linux' run: | - cargo build --locked --no-default-features --features ssl-openssl + cargo build --locked --no-default-features --features malachite-bigint,ssl-openssl cargo build --locked --release --features threading,jit,ssl-openssl ${{ env.CARGO_ARGS_NO_SSL }} target/release/rustpython -B extra_tests/snippets/stdlib_ssl.py target/release/rustpython -B -m test -v --single-process --timeout=300 test_ssl @@ -344,7 +344,7 @@ jobs: - name: Test vendored OpenSSL build if: env.RUN_RUST_TESTS == 'true' && runner.os == 'Linux' - run: cargo build --locked --no-default-features --features ssl-openssl-vendor + run: cargo build --locked --no-default-features --features malachite-bigint,ssl-openssl-vendor # - name: Install tk-dev for tkinter build # run: sudo apt-get update && sudo apt-get install -y tk-dev @@ -507,7 +507,7 @@ jobs: # `cargo check` does not link, so it cannot catch an undefined symbol. - name: Link the wasm32-wasip2 build if: ${{ matrix.target == 'wasm32-wasip2' }} - run: cargo build --locked --target wasm32-wasip2 --no-default-features --features freeze-stdlib,stdlib,stdio,importlib,host_env,doc,ucd_3_2_0 + run: cargo build --locked --target wasm32-wasip2 --no-default-features --features malachite-bigint,freeze-stdlib,stdlib,stdio,importlib,host_env,doc,ucd_3_2_0 - name: Check compilation with ssl if: ${{ !matrix.skip_ssl }} @@ -1240,7 +1240,7 @@ jobs: - name: build rustpython if: env.RUN_WASM_WASI == 'true' - run: cargo build --locked --profile wasm-release --target wasm32-wasip1 --no-default-features --features freeze-stdlib,stdlib,stdio,importlib,host_env,doc,ucd_3_2_0 --verbose + run: cargo build --locked --profile wasm-release --target wasm32-wasip1 --no-default-features --features malachite-bigint,freeze-stdlib,stdlib,stdio,importlib,host_env,doc,ucd_3_2_0 --verbose - name: Check WASI FileIO contract if: env.RUN_WASM_WASI == 'true' run: | diff --git a/.github/workflows/cron-ci.yaml b/.github/workflows/cron-ci.yaml index 7dcbb56131f..d72f7fc8d77 100644 --- a/.github/workflows/cron-ci.yaml +++ b/.github/workflows/cron-ci.yaml @@ -14,7 +14,7 @@ on: - .github/workflows/cron-ci.yaml env: - CARGO_ARGS: --no-default-features --features stdlib,importlib,stdio,encodings,ssl-rustls-aws-lc,jit,host_env,doc,ucd_3_2_0 + CARGO_ARGS: --no-default-features --features malachite-bigint,stdlib,importlib,stdio,encodings,ssl-rustls-aws-lc,jit,host_env,doc,ucd_3_2_0 jobs: # codecov collects code coverage data from the rust tests, python snippets and python test suite. @@ -42,7 +42,7 @@ jobs: - run: sudo apt-get update && sudo apt-get -y install lcov - name: Run cargo-llvm-cov with Rust tests. - run: cargo llvm-cov --no-report --workspace --exclude rustpython_wasm --exclude rustpython-venvlauncher --exclude rustpython-capi --verbose --no-default-features --features stdlib,importlib,stdio,encodings,ssl-rustls-aws-lc,jit,host_env,doc,ucd_3_2_0 + run: cargo llvm-cov --no-report --workspace --exclude rustpython_wasm --exclude rustpython-venvlauncher --exclude rustpython-capi --verbose --no-default-features --features malachite-bigint,stdlib,importlib,stdio,encodings,ssl-rustls-aws-lc,jit,host_env,doc,ucd_3_2_0 - name: Run cargo-llvm-cov with Python snippets. run: python scripts/cargo-llvm-cov.py diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3a93913e85f..b6902f21ac6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -75,7 +75,7 @@ jobs: libtool: true - name: Build RustPython - run: cargo build --release --target=${{ matrix.target }} --verbose --no-default-features --features stdlib,stdio,importlib,encodings,sqlite,host_env,ssl-rustls-aws-lc,threading,jit,doc + run: cargo build --release --target=${{ matrix.target }} --verbose --no-default-features --features malachite-bigint,stdlib,stdio,importlib,encodings,sqlite,host_env,ssl-rustls-aws-lc,threading,jit,doc - name: Rename Binary run: cp target/${{ matrix.target }}/release/rustpython target/rustpython-release-${{ runner.os }}-${{ matrix.target }} @@ -107,7 +107,7 @@ jobs: targets: wasm32-wasip1 - name: Build RustPython - run: cargo build --target wasm32-wasip1 --no-default-features --features freeze-stdlib,stdlib,doc --release + run: cargo build --target wasm32-wasip1 --no-default-features --features malachite-bigint,freeze-stdlib,stdlib,doc --release - name: Rename Binary run: cp target/wasm32-wasip1/release/rustpython.wasm target/rustpython-release-wasm32-wasip1.wasm diff --git a/.github/workflows/update-caches.yml b/.github/workflows/update-caches.yml index ae4e3edb509..14c1072c16f 100644 --- a/.github/workflows/update-caches.yml +++ b/.github/workflows/update-caches.yml @@ -20,7 +20,7 @@ env: CARGO_PROFILE_DEV_DEBUG: 0 CARGO_PROFILE_RELEASE_DEBUG: 0 # Keep feature list in sync with CI's release build in .github/workflows/ci.yaml. - CARGO_ARGS: --workspace --no-default-features --features stdlib,importlib,stdio,encodings,sqlite,ssl-rustls-aws-lc,host_env,threading,jit,doc --exclude rustpython_wasm --exclude rustpython-venvlauncher + CARGO_ARGS: --workspace --no-default-features --features malachite-bigint,stdlib,importlib,stdio,encodings,sqlite,ssl-rustls-aws-lc,host_env,threading,jit,doc --exclude rustpython_wasm --exclude rustpython-venvlauncher jobs: build-caches: diff --git a/AGENTS.md b/AGENTS.md index c8a1d2a14cc..3f0c8b4862e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -102,7 +102,7 @@ Markers take one of these forms: ## Other Notes -- **WebAssembly**: `cargo build --target wasm32-wasip1 --no-default-features --features freeze-stdlib,stdlib --release` +- **WebAssembly**: `cargo build --target wasm32-wasip1 --no-default-features --features malachite-bigint,freeze-stdlib,stdlib --release` - **Linux build and debug on macOS**: see [CONTRIBUTING.md](CONTRIBUTING.md#testing-on-linux-from-macos). - **venvlauncher (Windows)**: all 4 venvlauncher binaries use the same source code. Do NOT add multiple `[[bin]]` entries to Cargo.toml. Build once and copy with different names. - **CI workflows**: a change to any file under `.github/workflows/` must pass a [zizmor](https://docs.zizmor.sh/) scan in CI. diff --git a/Cargo.lock b/Cargo.lock index 1db5bd0c1a7..ab15d6fb882 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3311,6 +3311,7 @@ dependencies = [ "libc", "libm", "malachite-bigint", + "num-bigint", "num-complex", "num-integer", "num-traits", @@ -3877,6 +3878,18 @@ dependencies = [ "winresource", ] +[[package]] +name = "rustpython-bigint" +version = "0.6.1" +dependencies = [ + "malachite-base", + "malachite-bigint", + "malachite-q", + "num-bigint", + "num-integer", + "num-traits", +] + [[package]] name = "rustpython-capi" version = "0.6.1" @@ -3884,9 +3897,9 @@ dependencies = [ "bitflags 2.13.2", "itertools 0.15.0", "libc", - "malachite-bigint", "num-complex", "pyo3", + "rustpython-bigint", "rustpython-pylib", "rustpython-stdlib", "rustpython-vm", @@ -3901,11 +3914,11 @@ dependencies = [ "indexmap", "itertools 0.15.0", "log", - "malachite-bigint", "memchr", "num-complex", "num-traits", "rapidhash", + "rustpython-bigint", "rustpython-compiler-core", "rustpython-literal", "rustpython-ruff_python_ast", @@ -3931,15 +3944,13 @@ dependencies = [ "libc", "libz-rs-sys", "lock_api", - "malachite-base", - "malachite-bigint", - "malachite-q", "md-5", "memchr", "num-complex", "num-traits", "parking_lot", "radium", + "rustpython-bigint", "rustpython-literal", "rustpython-unicode", "rustpython-wtf8", @@ -3976,9 +3987,9 @@ dependencies = [ "bitflagset", "itertools 0.15.0", "lz4_flex", - "malachite-bigint", "num-complex", "num-traits", + "rustpython-bigint", "rustpython-ruff_source_file", "rustpython-wtf8", ] @@ -4078,11 +4089,9 @@ dependencies = [ "hexf-parse", "is-macro", "lexical-parse-float", - "malachite-base", - "malachite-bigint", - "malachite-q", "num-traits", "rand 0.10.4", + "rustpython-bigint", "rustpython-unicode", "rustpython-wtf8", ] @@ -4203,7 +4212,6 @@ dependencies = [ "itertools 0.15.0", "libc", "libsqlite3-sys", - "malachite-bigint", "memchr", "mt19937", "num-complex", @@ -4220,6 +4228,7 @@ dependencies = [ "rapidhash", "rustls", "rustls-pemfile", + "rustpython-bigint", "rustpython-common", "rustpython-derive", "rustpython-host_env", @@ -4280,7 +4289,6 @@ dependencies = [ "jiff 1.0.3", "libc", "log", - "malachite-bigint", "memchr", "num-complex", "num-integer", @@ -4293,6 +4301,7 @@ dependencies = [ "psm", "rapidhash", "result-like", + "rustpython-bigint", "rustpython-codegen", "rustpython-common", "rustpython-compiler", diff --git a/Cargo.toml b/Cargo.toml index 1834a773272..e0c3dfd7d8f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,7 +11,9 @@ license.workspace = true [features] capi = ["dep:rustpython-capi", "threading"] -default = ["threading", "stdlib", "stdio", "importlib", "ssl-rustls-aws-lc", "host_env", "mimalloc", "doc", "ucd_3_2_0"] +default = ["malachite-bigint", "threading", "stdlib", "stdio", "importlib", "ssl-rustls-aws-lc", "host_env", "mimalloc", "doc", "ucd_3_2_0"] +malachite-bigint = ["rustpython-capi?/malachite-bigint", "rustpython-pylib?/malachite-bigint", "rustpython-stdlib?/malachite-bigint", "rustpython-vm/malachite-bigint", "rustpython-compiler/malachite-bigint"] +num-bigint = ["rustpython-capi?/num-bigint", "rustpython-pylib?/num-bigint", "rustpython-stdlib?/num-bigint", "rustpython-vm/num-bigint", "rustpython-compiler/num-bigint"] doc = ["rustpython-vm/doc", "rustpython-stdlib?/doc"] mimalloc = ["dep:mimalloc"] host_env = ["rustpython-vm/host_env", "rustpython-stdlib?/host_env"] @@ -183,18 +185,19 @@ repository = "https://github.com/RustPython/RustPython" license = "MIT" [workspace.dependencies] -rustpython-capi = { path = "crates/capi", version = "0.6.1" } -rustpython-compiler-core = { path = "crates/compiler-core", version = "0.6.1" } -rustpython-compiler = { path = "crates/compiler", version = "0.6.1" } -rustpython-codegen = { path = "crates/codegen", version = "0.6.1" } -rustpython-common = { path = "crates/common", version = "0.6.1" } +rustpython-bigint = { path = "crates/bigint", version = "0.6.1", default-features = false } +rustpython-capi = { path = "crates/capi", version = "0.6.1", default-features = false } +rustpython-compiler-core = { path = "crates/compiler-core", version = "0.6.1", default-features = false } +rustpython-compiler = { path = "crates/compiler", version = "0.6.1", default-features = false } +rustpython-codegen = { path = "crates/codegen", version = "0.6.1", default-features = false } +rustpython-common = { path = "crates/common", version = "0.6.1", default-features = false } rustpython-host_env = { path = "crates/host_env", version = "0.6.1" } -rustpython-derive = { path = "crates/derive", version = "0.6.1" } -rustpython-derive-impl = { path = "crates/derive-impl", version = "0.6.1" } -rustpython-jit = { path = "crates/jit", version = "0.6.1" } -rustpython-literal = { path = "crates/literal", version = "0.6.1" } +rustpython-derive = { path = "crates/derive", version = "0.6.1", default-features = false } +rustpython-derive-impl = { path = "crates/derive-impl", version = "0.6.1", default-features = false } +rustpython-jit = { path = "crates/jit", version = "0.6.1", default-features = false } +rustpython-literal = { path = "crates/literal", version = "0.6.1", default-features = false } rustpython-vm = { path = "crates/vm", default-features = false, version = "0.6.1" } -rustpython-pylib = { path = "crates/pylib", version = "0.6.1" } +rustpython-pylib = { path = "crates/pylib", version = "0.6.1", default-features = false } rustpython-stdlib = { path = "crates/stdlib", default-features = false, version = "0.6.1" } rustpython-sre_engine = { path = "crates/sre_engine", version = "0.6.1" } rustpython-unicode = { path = "crates/unicode", default-features = false, version = "0.6.1" } @@ -261,6 +264,7 @@ lz4_flex = "0.14" nix = { version = "0.32", features = ["fs", "user", "process", "term", "time", "signal", "ioctl", "socket", "sched", "zerocopy", "dir", "hostname", "net", "poll"] } mac_address = "1.2.1" mach2 = "0.7.0" +num-bigint = "0.4" malachite-bigint = "0.15.0" malachite-q = "0.15.0" malachite-base = "0.15.0" @@ -284,7 +288,7 @@ pem-rfc7468 = "1.0" pkcs8 = "0.11" proc-macro2 = "1.0.105" psm = "0.1" -pymath = { git = "https://github.com/RustPython/pymath.git", rev = "6992bbfc853707545d0fb4b91931a2f36df89abe", features = ["mul_add", "malachite-bigint", "complex"] } +pymath = { git = "https://github.com/RustPython/pymath.git", rev = "6992bbfc853707545d0fb4b91931a2f36df89abe", features = ["mul_add", "complex"] } pyo3 = "0.30" quote = "1.0.45" radium = "1.1.1" diff --git a/README.md b/README.md index c422a954320..b00598f4538 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,20 @@ Note that to use OpenSSL on Windows, you may need to install OpenSSL, or you can which compiles OpenSSL for you but requires a C compiler, perl, and `make`. OpenSSL version 3 is expected and tested in CI. Older versions may not work. +### Big integer backends + +RustPython uses Malachite by default. A build with `--no-default-features` +must select `malachite-bigint` or `num-bigint` explicitly. For example: + +```sh +cargo build --no-default-features --features num-bigint,stdlib,stdio,host_env,threading +``` + +Cargo features are additive, so don't combine both backends or enable +`num-bigint` on top of the default features. Embedders that directly depend +on more than one RustPython crate must select the same backend for all of +them, disabling each dependency's defaults for the `num-bigint` build. + ### WASI You can compile RustPython to a standalone WebAssembly WASI module so it can run anywhere. @@ -115,7 +129,7 @@ You can compile RustPython to a standalone WebAssembly WASI module so it can run Build ```bash -cargo build --target wasm32-wasip1 --no-default-features --features freeze-stdlib,stdlib --release +cargo build --target wasm32-wasip1 --no-default-features --features malachite-bigint,freeze-stdlib,stdlib --release ``` Run by wasmer diff --git a/crates/bigint/Cargo.toml b/crates/bigint/Cargo.toml new file mode 100644 index 00000000000..748a0f98b7f --- /dev/null +++ b/crates/bigint/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "rustpython-bigint" +description = "Big integer backend selection for RustPython" +version.workspace = true +authors.workspace = true +edition.workspace = true +rust-version.workspace = true +repository.workspace = true +license.workspace = true + +[features] +default = ["malachite-bigint"] +malachite-bigint = ["dep:malachite-bigint", "dep:malachite-base", "dep:malachite-q"] +num-bigint = ["dep:num-bigint", "dep:num-integer", "dep:num-traits"] + +[dependencies] +malachite-bigint = { workspace = true, optional = true } +malachite-base = { workspace = true, optional = true } +malachite-q = { workspace = true, optional = true } +num-bigint = { workspace = true, optional = true } +num-integer = { workspace = true, optional = true } +num-traits = { workspace = true, optional = true } + +[lints] +workspace = true diff --git a/crates/bigint/src/lib.rs b/crates/bigint/src/lib.rs new file mode 100644 index 00000000000..a5166aab057 --- /dev/null +++ b/crates/bigint/src/lib.rs @@ -0,0 +1,179 @@ +//! RustPython's shared arbitrary-precision integer types and backend adapters. +#![no_std] + +#[cfg(all(feature = "malachite-bigint", feature = "num-bigint"))] +compile_error!("select either malachite-bigint or num-bigint, not both"); +#[cfg(not(any(feature = "malachite-bigint", feature = "num-bigint")))] +compile_error!("select a BigInt backend: malachite-bigint or num-bigint"); + +#[cfg(feature = "malachite-bigint")] +pub use malachite_bigint::{BigInt, BigUint, Sign, ToBigInt}; +#[cfg(all(feature = "num-bigint", not(feature = "malachite-bigint")))] +pub use num_bigint::{BigInt, BigUint, Sign, ToBigInt}; + +/// Express a finite binary64 value as a reduced ratio with a positive denominator. +#[cfg(feature = "malachite-bigint")] +#[must_use] +pub fn float_to_ratio(value: f64) -> Option<(BigInt, BigInt)> { + use core::cmp::Ordering; + use malachite_q::Rational; + + let sign = match value.partial_cmp(&0.0)? { + Ordering::Less => Sign::Minus, + Ordering::Equal => return Some((0.into(), 1.into())), + Ordering::Greater => Sign::Plus, + }; + Rational::try_from(value).ok().map(|x| { + let (numer, denom) = x.into_numerator_and_denominator(); + ( + BigInt::from_biguint(sign, numer.into()), + BigUint::from(denom).into(), + ) + }) +} + +#[cfg(all(feature = "num-bigint", not(feature = "malachite-bigint")))] +#[must_use] +pub fn float_to_ratio(value: f64) -> Option<(BigInt, BigInt)> { + let bits = value.to_bits(); + let raw_exponent = ((bits >> 52) & 0x7ff) as i32; + if raw_exponent == 0x7ff { + return None; + } + let mut mantissa = bits & ((1 << 52) - 1); + if raw_exponent != 0 { + mantissa |= 1 << 52; + } + if mantissa == 0 { + return Some((0.into(), 1.into())); + } + let zeros = mantissa.trailing_zeros(); + mantissa >>= zeros; + let exponent = raw_exponent.max(1) - 1075 + zeros as i32; + let mut numerator = BigInt::from(mantissa); + if bits >> 63 != 0 { + numerator = -numerator; + } + Some(if exponent >= 0 { + (numerator << exponent as usize, 1.into()) + } else { + (numerator, BigInt::from(1) << (-exponent as usize)) + }) +} + +/// Round the quotient of two integers to a binary64 float. Denominator must be nonzero. +#[cfg(feature = "malachite-bigint")] +#[must_use] +pub fn true_div(numerator: &BigInt, denominator: &BigInt) -> f64 { + use malachite_base::{num::conversion::traits::RoundingInto, rounding_modes::RoundingMode}; + use malachite_q::Rational; + + if numerator.sign() == Sign::NoSign && denominator.sign() == Sign::Minus { + return -0.0; + } + let rational = Rational::from_integers_ref(numerator.into(), denominator.into()); + rational.rounding_into(RoundingMode::Nearest).0 +} + +#[cfg(all(feature = "num-bigint", not(feature = "malachite-bigint")))] +#[must_use] +pub fn true_div(numerator: &BigInt, denominator: &BigInt) -> f64 { + use core::cmp::Ordering; + use num_integer::Integer; + use num_traits::ToPrimitive; + + let sign = + u64::from((numerator.sign() == Sign::Minus) ^ (denominator.sign() == Sign::Minus)) << 63; + let numerator = numerator.magnitude(); + let denominator = denominator.magnitude(); + assert!(denominator.bits() > 0, "division by zero"); + if numerator.bits() == 0 { + return f64::from_bits(sign); + } + + // Estimate the exponent by the length difference, then compare the + // normalized integers to resolve the one-bit uncertainty. + let mut exponent = i128::from(numerator.bits()) - i128::from(denominator.bits()); + if exponent > 1024 { + return f64::from_bits(sign | (0x7ff << 52)); + } + if exponent < -1075 { + return f64::from_bits(sign); + } + let below_power = if exponent >= 0 { + numerator < &(denominator << exponent as usize) + } else { + &(numerator << (-exponent as usize)) < denominator + }; + if below_power { + exponent -= 1; + } + if exponent > 1023 { + return f64::from_bits(sign | (0x7ff << 52)); + } + if exponent < -1075 { + return f64::from_bits(sign); + } + + // Round once, directly to a normal or subnormal significand. + let hidden = 1u64 << 52; + let shift = 52 - exponent.max(-1022); + let (quotient, rem, divisor) = if shift >= 0 { + let (q, r) = (numerator << shift as usize).div_rem(denominator); + (q, r, alloc::borrow::Cow::Borrowed(denominator)) + } else { + let divisor = denominator << (-shift as usize); + let (q, r) = numerator.div_rem(&divisor); + (q, r, alloc::borrow::Cow::Owned(divisor)) + }; + let mut significand = quotient.to_u64().expect("binary64 significand fits u64"); + let round_up = match (rem << 1usize).cmp(divisor.as_ref()) { + Ordering::Greater => true, + Ordering::Equal => significand & 1 != 0, + Ordering::Less => false, + }; + significand += u64::from(round_up); + let magnitude = if exponent < -1022 { + // Rounding the largest subnormal upwards produces the first normal. + significand + } else { + // A carry out of the significand increments the biased exponent. + ((exponent + 1023) as u64 * hidden) + significand - hidden + }; + f64::from_bits(sign | magnitude) +} + +#[cfg(all(feature = "num-bigint", not(feature = "malachite-bigint")))] +extern crate alloc; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn exact_float_ratios() { + assert_eq!(float_to_ratio(-0.0), Some((0.into(), 1.into()))); + assert_eq!(float_to_ratio(-1.25), Some(((-5).into(), 4.into()))); + assert_eq!(float_to_ratio(f64::INFINITY), None); + assert_eq!(float_to_ratio(f64::NAN), None); + assert_eq!( + float_to_ratio(f64::from_bits(1)), + Some((1.into(), BigInt::from(1) << 1074usize)) + ); + } + + #[test] + fn integer_division_rounds_once_to_nearest_even() { + let one = BigInt::from(1); + let d = &one << 53usize; + assert_eq!(true_div(&(&d + 1), &d).to_bits(), 1.0f64.to_bits()); + assert_eq!(true_div(&(&d + 3), &d).to_bits(), 1.0f64.to_bits() + 2); + let d = &one << 1075usize; + assert_eq!(true_div(&(-&one), &d).to_bits(), (-0.0f64).to_bits()); + assert_eq!(true_div(&BigInt::from(3), &d).to_bits(), 2); + let threshold = (&one << 1024usize) - (&one << 970usize); + assert_eq!(true_div(&(&threshold - 1), &one), f64::MAX); + assert_eq!(true_div(&threshold, &one), f64::INFINITY); + assert_eq!(true_div(&0.into(), &(-one)).to_bits(), (-0.0f64).to_bits()); + } +} diff --git a/crates/capi/Cargo.toml b/crates/capi/Cargo.toml index 08c102b4a64..dc5949d3557 100644 --- a/crates/capi/Cargo.toml +++ b/crates/capi/Cargo.toml @@ -11,11 +11,16 @@ license.workspace = true [lib] crate-type = ["cdylib", "rlib"] +[features] +default = ["malachite-bigint"] +malachite-bigint = ["rustpython-bigint/malachite-bigint", "rustpython-pylib/malachite-bigint", "rustpython-stdlib/malachite-bigint", "rustpython-vm/malachite-bigint"] +num-bigint = ["rustpython-bigint/num-bigint", "rustpython-pylib/num-bigint", "rustpython-stdlib/num-bigint", "rustpython-vm/num-bigint"] + [dependencies] bitflags = { workspace = true } itertools = { workspace = true } libc = { workspace = true } -malachite-bigint = { workspace = true } +rustpython-bigint = { workspace = true } num-complex = { workspace = true } rustpython-vm = { workspace = true, features = ["threading", "compiler", "importlib", "host_env"] } rustpython-stdlib = {workspace = true, features = ["threading"] } diff --git a/crates/capi/src/abstract_/number.rs b/crates/capi/src/abstract_/number.rs index a0e11025b4b..eabbb8a9c82 100644 --- a/crates/capi/src/abstract_/number.rs +++ b/crates/capi/src/abstract_/number.rs @@ -1,7 +1,7 @@ use crate::util::FfiPtrExt; use crate::{PyObject, pystate::with_vm}; use core::ffi::c_int; -use malachite_bigint::Sign; +use rustpython_bigint::Sign; use rustpython_vm::protocol::PyNumber; #[unsafe(no_mangle)] diff --git a/crates/capi/src/longobject.rs b/crates/capi/src/longobject.rs index f68548d5b00..a0f62d9d57a 100644 --- a/crates/capi/src/longobject.rs +++ b/crates/capi/src/longobject.rs @@ -3,7 +3,7 @@ use crate::util::FfiPtrExt; use crate::{PyObject, pystate::with_vm}; use bitflags::bitflags; use core::ffi::{CStr, c_char, c_double, c_int, c_long, c_longlong, c_ulong, c_ulonglong, c_void}; -use malachite_bigint::{BigInt, BigUint, Sign}; +use rustpython_bigint::{BigInt, BigUint, Sign}; use rustpython_vm::builtins::{PyInt, try_bigint_to_f64, try_f64_to_bigint}; use rustpython_vm::common::int::bytes_to_int; use rustpython_vm::protocol::handle_bytes_to_int_err; diff --git a/crates/codegen/Cargo.toml b/crates/codegen/Cargo.toml index c43bf1bcb08..c6960eaa3a7 100644 --- a/crates/codegen/Cargo.toml +++ b/crates/codegen/Cargo.toml @@ -9,7 +9,9 @@ repository.workspace = true license.workspace = true [features] -default = ["std"] +default = ["malachite-bigint", "std"] +malachite-bigint = ["rustpython-bigint/malachite-bigint", "rustpython-compiler-core/malachite-bigint", "rustpython-literal/malachite-bigint"] +num-bigint = ["rustpython-bigint/num-bigint", "rustpython-compiler-core/num-bigint", "rustpython-literal/num-bigint"] std = ["thiserror/std", "itertools/use_std"] [dependencies] @@ -27,7 +29,7 @@ log = { workspace = true } num-complex = { workspace = true } num-traits = { workspace = true } thiserror = { workspace = true } -malachite-bigint = { workspace = true } +rustpython-bigint = { workspace = true } memchr = { workspace = true } rapidhash = { workspace = true } diff --git a/crates/codegen/src/compile.rs b/crates/codegen/src/compile.rs index ae6492c0772..00444447fc4 100644 --- a/crates/codegen/src/compile.rs +++ b/crates/codegen/src/compile.rs @@ -22,11 +22,11 @@ use crate::{ }; use alloc::borrow::Cow; use core::{mem, slice}; -use malachite_bigint::BigInt; use num_complex::Complex; use num_traits::{Num, ToPrimitive, Zero}; use ruff_python_ast::{self as ast, HasNodeIndex, name::Name}; use ruff_text_size::{Ranged, TextRange, TextSize, TextSlice}; +use rustpython_bigint::BigInt; use rustpython_compiler_core::{ AstLocations, Mode, OneIndexed, PositionEncoding, SourceFile, SourceLocation, SourceLocationRange, diff --git a/crates/codegen/src/ir.rs b/crates/codegen/src/ir.rs index f176df9fd85..b5c55af0c59 100644 --- a/crates/codegen/src/ir.rs +++ b/crates/codegen/src/ir.rs @@ -1,9 +1,9 @@ use core::ops::{Deref, DerefMut, Index, IndexMut}; use crate::{IndexMap, IndexSet, error::InternalError}; -use malachite_bigint::BigInt; use num_complex::Complex; use num_traits::{ToPrimitive, Zero}; +use rustpython_bigint::BigInt; use rustpython_wtf8::Wtf8Buf; use rustpython_compiler_core::{ diff --git a/crates/codegen/src/preprocess.rs b/crates/codegen/src/preprocess.rs index 8bd16f106a8..be5b5939b3b 100644 --- a/crates/codegen/src/preprocess.rs +++ b/crates/codegen/src/preprocess.rs @@ -3,8 +3,8 @@ use alloc::{ string::{String, ToString}, vec::Vec, }; -use malachite_bigint::BigInt; use num_traits::ToPrimitive; +use rustpython_bigint::BigInt; use ruff_python_ast::{ self as ast, AtomicNodeIndex, ConversionFlag, Expr, ExprFString, FString, FStringFlags, diff --git a/crates/common/Cargo.toml b/crates/common/Cargo.toml index ea31322575e..f1690ce35f0 100644 --- a/crates/common/Cargo.toml +++ b/crates/common/Cargo.toml @@ -9,7 +9,9 @@ repository.workspace = true license.workspace = true [features] -default = ["std"] +default = ["malachite-bigint", "std"] +malachite-bigint = ["rustpython-bigint/malachite-bigint", "rustpython-literal/malachite-bigint"] +num-bigint = ["rustpython-bigint/num-bigint", "rustpython-literal/num-bigint"] binascii = ["dep:crc32fast"] bz2 = ["std", "dep:bzip2"] cjk-codecs = [] @@ -48,9 +50,7 @@ getrandom = { workspace = true } itertools = { workspace = true } libc = { workspace = true } libz-rs-sys = { workspace = true, optional = true } -malachite-bigint = { workspace = true } -malachite-q = { workspace = true } -malachite-base = { workspace = true } +rustpython-bigint = { workspace = true } md-5 = { workspace = true, optional = true } memchr = { workspace = true, optional = true } num-traits = { workspace = true } diff --git a/crates/common/src/cformat.rs b/crates/common/src/cformat.rs index 263b4776a69..958198cfb36 100644 --- a/crates/common/src/cformat.rs +++ b/crates/common/src/cformat.rs @@ -8,8 +8,8 @@ use core::{ str::FromStr, }; use itertools::Itertools; -use malachite_bigint::{BigInt, Sign}; use num_traits::Signed; +use rustpython_bigint::{BigInt, Sign}; use rustpython_literal::{float, format::Case}; use crate::wtf8::{CodePoint, Wtf8, Wtf8Buf}; diff --git a/crates/common/src/float_ops.rs b/crates/common/src/float_ops.rs index 6cfabecf973..fa0196f5f29 100644 --- a/crates/common/src/float_ops.rs +++ b/crates/common/src/float_ops.rs @@ -1,6 +1,6 @@ use core::f64::consts::LOG10_2; -use malachite_bigint::{BigInt, ToBigInt}; use num_traits::{Signed, ToPrimitive}; +use rustpython_bigint::{BigInt, ToBigInt}; #[must_use] pub const fn decompose_float(value: f64) -> (f64, i32) { @@ -29,7 +29,7 @@ pub const fn decompose_float(value: f64) -> (f64, i32) { /// # Examples /// /// ``` -/// use malachite_bigint::BigInt; +/// use rustpython_bigint::BigInt; /// use rustpython_common::float_ops::eq_int; /// let a = 1.0f64; /// let b = BigInt::from(1); diff --git a/crates/common/src/format.rs b/crates/common/src/format.rs index ef38774ffe7..4d0c7aecad7 100644 --- a/crates/common/src/format.rs +++ b/crates/common/src/format.rs @@ -1,11 +1,10 @@ // spell-checker:ignore ddfe DTSF use core::ops::Deref; use core::{cmp, str::FromStr}; -use malachite_base::num::basic::floats::PrimitiveFloat; -use malachite_bigint::{BigInt, Sign}; use num_complex::Complex64; use num_traits::FromPrimitive; use num_traits::{Signed, cast::ToPrimitive}; +use rustpython_bigint::{BigInt, Sign}; use rustpython_literal::float; use rustpython_literal::format::Case; @@ -1158,22 +1157,24 @@ impl FormatSpec { fn format_complex_re_im(&self, num: &Complex64) -> Result<(String, String), FormatSpecError> { // Format real part - let formatted_re = - if num.re != 0.0 || num.re.is_negative_zero() || self.format_type.is_some() { - let re = self.format_complex_float(num.re)?; - let sign_re = if self.is_negative_after_zero_coercion(num.re, &re) { - "-" - } else { - match self.sign.unwrap_or(FormatSign::Minus) { - FormatSign::Plus => "+", - FormatSign::Minus => "", - FormatSign::MinusOrSpace => " ", - } - }; - format!("{sign_re}{re}") + let formatted_re = if num.re != 0.0 + || num.re.to_bits() == (-0.0f64).to_bits() + || self.format_type.is_some() + { + let re = self.format_complex_float(num.re)?; + let sign_re = if self.is_negative_after_zero_coercion(num.re, &re) { + "-" } else { - String::new() + match self.sign.unwrap_or(FormatSign::Minus) { + FormatSign::Plus => "+", + FormatSign::Minus => "", + FormatSign::MinusOrSpace => " ", + } }; + format!("{sign_re}{re}") + } else { + String::new() + }; // Format imaginary part let im = self.format_complex_float(num.im)?; diff --git a/crates/common/src/hash.rs b/crates/common/src/hash.rs index 3635442a85a..ca0cdfd2c5b 100644 --- a/crates/common/src/hash.rs +++ b/crates/common/src/hash.rs @@ -1,6 +1,6 @@ use core::hash::{BuildHasher, Hash, Hasher}; -use malachite_bigint::BigInt; use num_traits::ToPrimitive; +use rustpython_bigint::BigInt; use siphasher::sip::SipHasher24; pub type PyHash = isize; diff --git a/crates/common/src/int.rs b/crates/common/src/int.rs index 07bb97a65ff..316aedf9d54 100644 --- a/crates/common/src/int.rs +++ b/crates/common/src/int.rs @@ -1,24 +1,7 @@ -use malachite_bigint::{BigInt, BigUint, Sign}; -use malachite_q::Rational; use num_traits::{One, ToPrimitive, Zero}; +use rustpython_bigint::{BigInt, BigUint, Sign}; -pub use rustpython_literal::float::true_div; - -#[must_use] -pub fn float_to_ratio(value: f64) -> Option<(BigInt, BigInt)> { - let sign = match core::cmp::PartialOrd::partial_cmp(&value, &0.0)? { - core::cmp::Ordering::Less => Sign::Minus, - core::cmp::Ordering::Equal => return Some((BigInt::zero(), BigInt::one())), - core::cmp::Ordering::Greater => Sign::Plus, - }; - Rational::try_from(value).ok().map(|x| { - let (numer, denom) = x.into_numerator_and_denominator(); - ( - BigInt::from_biguint(sign, numer.into()), - BigUint::from(denom).into(), - ) - }) -} +pub use rustpython_bigint::{float_to_ratio, true_div}; #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum BytesToIntError { diff --git a/crates/compiler-core/Cargo.toml b/crates/compiler-core/Cargo.toml index 22201597d90..4fac7ee0c94 100644 --- a/crates/compiler-core/Cargo.toml +++ b/crates/compiler-core/Cargo.toml @@ -8,6 +8,11 @@ rust-version.workspace = true repository.workspace = true license.workspace = true +[features] +default = ["malachite-bigint"] +malachite-bigint = ["rustpython-bigint/malachite-bigint"] +num-bigint = ["rustpython-bigint/num-bigint"] + [dependencies] # rustpython-parser-core = { workspace = true, features=["location"] } ruff_source_file = { workspace = true } @@ -16,7 +21,7 @@ rustpython-wtf8 = { workspace = true } bitflags = { workspace = true } bitflagset = { workspace = true } itertools = { workspace = true } -malachite-bigint = { workspace = true } +rustpython-bigint = { workspace = true } num-complex = { workspace = true } num-traits = { workspace = true } diff --git a/crates/compiler-core/src/bytecode.rs b/crates/compiler-core/src/bytecode.rs index 022c4e8cbb3..b0c5686e9fb 100644 --- a/crates/compiler-core/src/bytecode.rs +++ b/crates/compiler-core/src/bytecode.rs @@ -15,9 +15,9 @@ use core::{ sync::atomic::{AtomicU8, AtomicU16, AtomicUsize, Ordering}, }; use itertools::Itertools; -use malachite_bigint::BigInt; use num_complex::Complex64; use num_traits::Zero; +use rustpython_bigint::BigInt; use rustpython_wtf8::{Wtf8, Wtf8Buf}; pub use crate::bytecode::{ diff --git a/crates/compiler-core/src/marshal.rs b/crates/compiler-core/src/marshal.rs index 3358af46b27..113cdc6de8e 100644 --- a/crates/compiler-core/src/marshal.rs +++ b/crates/compiler-core/src/marshal.rs @@ -1,8 +1,8 @@ use crate::{OneIndexed, SourceLocation, bytecode::*}; use alloc::{boxed::Box, vec::Vec}; use core::convert::Infallible; -use malachite_bigint::{BigInt, Sign}; use num_complex::Complex64; +use rustpython_bigint::{BigInt, Sign}; use rustpython_wtf8::Wtf8; pub const FORMAT_VERSION: u32 = 6; diff --git a/crates/compiler/Cargo.toml b/crates/compiler/Cargo.toml index d41bfb70aa7..9ed6e37dbc2 100644 --- a/crates/compiler/Cargo.toml +++ b/crates/compiler/Cargo.toml @@ -8,8 +8,13 @@ rust-version.workspace = true repository.workspace = true license.workspace = true +[features] +default = ["malachite-bigint"] +malachite-bigint = ["rustpython-compiler-core/malachite-bigint", "rustpython-codegen/malachite-bigint"] +num-bigint = ["rustpython-compiler-core/num-bigint", "rustpython-codegen/num-bigint"] + [dependencies] -rustpython-codegen = { workspace = true } +rustpython-codegen = { workspace = true, features = ["std"] } rustpython-compiler-core = { workspace = true } rustpython-unicode = { workspace = true } ruff_python_parser = { workspace = true } diff --git a/crates/derive-impl/Cargo.toml b/crates/derive-impl/Cargo.toml index 9106d8697b4..9541be6c2a8 100644 --- a/crates/derive-impl/Cargo.toml +++ b/crates/derive-impl/Cargo.toml @@ -8,6 +8,11 @@ rust-version.workspace = true repository.workspace = true license.workspace = true +[features] +default = ["malachite-bigint"] +malachite-bigint = ["rustpython-compiler-core/malachite-bigint"] +num-bigint = ["rustpython-compiler-core/num-bigint"] + [dependencies] rustpython-compiler-core = { workspace = true } # rustpython-parser-core = { workspace = true } diff --git a/crates/derive/Cargo.toml b/crates/derive/Cargo.toml index 5ecd490cf94..f991cdabc69 100644 --- a/crates/derive/Cargo.toml +++ b/crates/derive/Cargo.toml @@ -11,6 +11,11 @@ license.workspace = true [lib] proc-macro = true +[features] +default = ["malachite-bigint"] +malachite-bigint = ["rustpython-compiler/malachite-bigint", "rustpython-derive-impl/malachite-bigint"] +num-bigint = ["rustpython-compiler/num-bigint", "rustpython-derive-impl/num-bigint"] + [dependencies] rustpython-compiler = { workspace = true } rustpython-derive-impl = { workspace = true } diff --git a/crates/jit/Cargo.toml b/crates/jit/Cargo.toml index 5dcf0f4c31b..ecafe4de608 100644 --- a/crates/jit/Cargo.toml +++ b/crates/jit/Cargo.toml @@ -10,6 +10,11 @@ license.workspace = true autotests = false +[features] +default = ["malachite-bigint"] +malachite-bigint = ["rustpython-compiler-core/malachite-bigint"] +num-bigint = ["rustpython-compiler-core/num-bigint"] + [dependencies] rustpython-compiler-core = { workspace = true } diff --git a/crates/literal/Cargo.toml b/crates/literal/Cargo.toml index e42dfd14af4..2d4894e189c 100644 --- a/crates/literal/Cargo.toml +++ b/crates/literal/Cargo.toml @@ -11,6 +11,11 @@ rust-version = { workspace = true } [lints] workspace = true +[features] +default = ["malachite-bigint"] +malachite-bigint = ["rustpython-bigint/malachite-bigint"] +num-bigint = ["rustpython-bigint/num-bigint"] + [dependencies] rustpython-unicode = { workspace = true } rustpython-wtf8 = { workspace = true } @@ -18,9 +23,7 @@ rustpython-wtf8 = { workspace = true } hexf-parse = { workspace = true } is-macro.workspace = true lexical-parse-float = { workspace = true, features = ["format"] } -malachite-base = { workspace = true } -malachite-bigint = { workspace = true } -malachite-q = { workspace = true } +rustpython-bigint = { workspace = true } num-traits = { workspace = true } [dev-dependencies] diff --git a/crates/literal/src/float.rs b/crates/literal/src/float.rs index 2e8ed658c46..6e0377a2883 100644 --- a/crates/literal/src/float.rs +++ b/crates/literal/src/float.rs @@ -2,27 +2,8 @@ use crate::format::Case; use alloc::borrow::ToOwned; use alloc::format; use alloc::string::{String, ToString}; -use malachite_base::{num::conversion::traits::RoundingInto, rounding_modes::RoundingMode}; -use malachite_bigint::{BigInt, Sign}; -use malachite_q::Rational; use num_traits::Zero; - -/// Round the exact quotient of two integers to a Python float. -/// -/// The denominator must be nonzero. -#[must_use] -pub fn true_div(numerator: &BigInt, denominator: &BigInt) -> f64 { - // Rational has no signed zero. Preserve the division sign before - // converting a zero numerator, as CPython's long_true_divide does. - if numerator.is_zero() && denominator.sign() == Sign::Minus { - return -0.0; - } - let rational = Rational::from_integers_ref(numerator.into(), denominator.into()); - // Nearest rounding can return the largest finite value for a quotient - // slightly beyond it; overflow starts at the halfway rounding boundary. - let (rounded, _) = rational.rounding_into(RoundingMode::Nearest); - rounded -} +pub use rustpython_bigint::true_div; #[must_use] pub fn parse_str(literal: &str) -> Option { diff --git a/crates/pylib/Cargo.toml b/crates/pylib/Cargo.toml index b1962409af4..529e0c16471 100644 --- a/crates/pylib/Cargo.toml +++ b/crates/pylib/Cargo.toml @@ -10,6 +10,9 @@ rust-version.workspace = true repository.workspace = true [features] +default = ["malachite-bigint"] +malachite-bigint = ["rustpython-compiler-core?/malachite-bigint", "rustpython-derive?/malachite-bigint"] +num-bigint = ["rustpython-compiler-core?/num-bigint", "rustpython-derive?/num-bigint"] freeze-stdlib = ["dep:rustpython-compiler-core", "dep:rustpython-derive", "dep:sha2"] [dependencies] diff --git a/crates/stdlib/Cargo.toml b/crates/stdlib/Cargo.toml index c435a2932ae..4c6c9c6211f 100644 --- a/crates/stdlib/Cargo.toml +++ b/crates/stdlib/Cargo.toml @@ -11,7 +11,9 @@ license.workspace = true # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [features] -default = ["compiler", "host_env", "doc", "ucd_3_2_0"] +default = ["malachite-bigint", "compiler", "host_env", "doc", "ucd_3_2_0"] +malachite-bigint = ["rustpython-bigint/malachite-bigint", "rustpython-common/malachite-bigint", "rustpython-derive/malachite-bigint", "rustpython-vm/malachite-bigint", "pymath/malachite-bigint", "rustpython-pylib/malachite-bigint"] +num-bigint = ["rustpython-bigint/num-bigint", "rustpython-common/num-bigint", "rustpython-derive/num-bigint", "rustpython-vm/num-bigint", "pymath/num-bigint", "rustpython-pylib/num-bigint"] ucd_3_2_0 = ["rustpython-unicode/ucd_3_2_0"] doc = ["rustpython-vm/doc"] host_env = ["rustpython-vm/host_env", "dep:uuid"] @@ -32,7 +34,7 @@ __ssl-rustls = ["ssl", "rustpython-host_env/ssl", "rustpython-host_env/rustls", # rustpython crates rustpython-derive = { workspace = true } rustpython-vm = { workspace = true, default-features = false, features = ["compiler"]} -rustpython-common = { workspace = true, features = ["binascii", "bz2", "cjk-codecs", "hashlib", "inet", "json", "lzma", "zlib"] } +rustpython-common = { workspace = true, features = ["std", "binascii", "bz2", "cjk-codecs", "hashlib", "inet", "json", "lzma", "zlib"] } rustpython-host_env = { workspace = true } rustpython-unicode = { workspace = true } @@ -51,7 +53,7 @@ itertools = { workspace = true } indexmap = { workspace = true } libc = { workspace = true } num-complex = { workspace = true } -malachite-bigint = { workspace = true } +rustpython-bigint = { workspace = true } num-traits = { workspace = true } num_enum = { workspace = true } parking_lot = { workspace = true } diff --git a/crates/stdlib/src/_datetime.rs b/crates/stdlib/src/_datetime.rs index 6b989a7a20a..bfb78878b23 100644 --- a/crates/stdlib/src/_datetime.rs +++ b/crates/stdlib/src/_datetime.rs @@ -27,8 +27,8 @@ mod _datetime { types::{AsNumber, Comparable, Constructor, Hashable, PyComparisonOp, Representable}, }; use crossbeam_utils::atomic::AtomicCell; - use malachite_bigint::{BigInt, ToBigInt}; use num_traits::{Signed, ToPrimitive, Zero}; + use rustpython_bigint::{BigInt, ToBigInt}; #[pyattr] const MINYEAR: i32 = 1; diff --git a/crates/stdlib/src/_sqlite3.rs b/crates/stdlib/src/_sqlite3.rs index 10cd141bc6b..d8809242c58 100644 --- a/crates/stdlib/src/_sqlite3.rs +++ b/crates/stdlib/src/_sqlite3.rs @@ -45,8 +45,8 @@ mod _sqlite3 { sqlite3_value_blob, sqlite3_value_bytes, sqlite3_value_double, sqlite3_value_int64, sqlite3_value_text, sqlite3_value_type, }; - use malachite_bigint::Sign; use num_traits::ToPrimitive; + use rustpython_bigint::Sign; use rustpython_common::{ atomic::{Ordering, PyAtomic, Radium}, hash::PyHash, diff --git a/crates/stdlib/src/cjkcodecs/multibytecodec.rs b/crates/stdlib/src/cjkcodecs/multibytecodec.rs index 313f1335cf2..92d4ae6b24b 100644 --- a/crates/stdlib/src/cjkcodecs/multibytecodec.rs +++ b/crates/stdlib/src/cjkcodecs/multibytecodec.rs @@ -16,7 +16,7 @@ mod _multibytecodec { protocol::PySequence, types::{Constructor, Initializer}, }; - use malachite_bigint::{BigInt, Sign}; + use rustpython_bigint::{BigInt, Sign}; /// Pending code points an encoder may hold between calls. const MAXENCPENDING: usize = 2; diff --git a/crates/stdlib/src/hashlib.rs b/crates/stdlib/src/hashlib.rs index 2eddb1aedcd..9c6980f0b2c 100644 --- a/crates/stdlib/src/hashlib.rs +++ b/crates/stdlib/src/hashlib.rs @@ -1047,7 +1047,7 @@ pub(crate) mod _hashlib { return Ok(0); }; let value = obj.try_index(vm)?; - if value.as_bigint().sign() == malachite_bigint::Sign::Minus { + if value.as_bigint().sign() == rustpython_bigint::Sign::Minus { return Err(vm.new_value_error("Cannot convert negative int")); } let overflow = || vm.new_overflow_error(format!("Python int too large for C {c_type}")); diff --git a/crates/stdlib/src/json.rs b/crates/stdlib/src/json.rs index 280f7011333..4a7d0cba803 100644 --- a/crates/stdlib/src/json.rs +++ b/crates/stdlib/src/json.rs @@ -15,7 +15,7 @@ mod _json { }; use core::cell::RefCell; use core::str::FromStr; - use malachite_bigint::BigInt; + use rustpython_bigint::BigInt; use rustpython_common::{ json, wtf8::{Wtf8, Wtf8Buf}, diff --git a/crates/stdlib/src/math.rs b/crates/stdlib/src/math.rs index c09dcb40e35..bd7bc71acd9 100644 --- a/crates/stdlib/src/math.rs +++ b/crates/stdlib/src/math.rs @@ -15,8 +15,8 @@ mod math { identifier, }; use itertools::Itertools; - use malachite_bigint::BigInt; use num_traits::{Signed, ToPrimitive}; + use rustpython_bigint::BigInt; use super::{float_repr, pymath_exception}; @@ -791,8 +791,8 @@ mod integer_functions { PyResult, VirtualMachine, function::{ArgIndex, NameIntegers, PosArgs}, }; - use malachite_bigint::BigInt; use num_traits::{Signed, ToPrimitive}; + use rustpython_bigint::BigInt; // Integer functions: #[pyfunction] diff --git a/crates/stdlib/src/overlapped.rs b/crates/stdlib/src/overlapped.rs index 0656c8b2b93..02c6d8b1df4 100644 --- a/crates/stdlib/src/overlapped.rs +++ b/crates/stdlib/src/overlapped.rs @@ -222,7 +222,7 @@ mod _overlapped { let int = obj .downcast_ref::() .ok_or_else(|| vm.new_type_error("an integer is required"))?; - if int.as_bigint().sign() == malachite_bigint::Sign::Minus { + if int.as_bigint().sign() == rustpython_bigint::Sign::Minus { int.try_to_primitive_in_range::(vm) } else { Ok(int.try_to_primitive_in_range::(vm)? as isize) diff --git a/crates/stdlib/src/pickle.rs b/crates/stdlib/src/pickle.rs index 9b92d6ac4e2..1e87ac8ac61 100644 --- a/crates/stdlib/src/pickle.rs +++ b/crates/stdlib/src/pickle.rs @@ -22,8 +22,8 @@ mod _pickle { }; use alloc::collections::TryReserveError; use core::sync::atomic::{AtomicI32, Ordering}; - use malachite_bigint::BigInt; use num_traits::{ToPrimitive, Zero}; + use rustpython_bigint::BigInt; use std::collections::HashMap; // The highest protocol number `_pickle` knows how to read. diff --git a/crates/stdlib/src/random.rs b/crates/stdlib/src/random.rs index 746ec6d6cb8..ff2dd802fc1 100644 --- a/crates/stdlib/src/random.rs +++ b/crates/stdlib/src/random.rs @@ -11,10 +11,10 @@ mod _random { types::{Constructor, Initializer}, }; use itertools::Itertools; - use malachite_bigint::{BigInt, BigUint, Sign}; use mt19937::MT19937; use num_traits::{Signed, Zero}; use rand::{Rng, SeedableRng}; + use rustpython_bigint::{BigInt, BigUint, Sign}; use rustpython_vm::types::DefaultConstructor; #[pyattr] diff --git a/crates/vm/Cargo.toml b/crates/vm/Cargo.toml index 7c1935d208d..9e5d1d383c7 100644 --- a/crates/vm/Cargo.toml +++ b/crates/vm/Cargo.toml @@ -10,7 +10,9 @@ repository.workspace = true license.workspace = true [features] -default = ["compiler", "wasmbind", "gc", "host_env", "stdio", "doc"] +default = ["malachite-bigint", "compiler", "wasmbind", "gc", "host_env", "stdio", "doc"] +malachite-bigint = ["rustpython-bigint/malachite-bigint", "rustpython-common/malachite-bigint", "rustpython-compiler?/malachite-bigint", "rustpython-compiler-core/malachite-bigint", "rustpython-codegen?/malachite-bigint", "rustpython-derive/malachite-bigint", "rustpython-jit?/malachite-bigint", "rustpython-literal/malachite-bigint"] +num-bigint = ["rustpython-bigint/num-bigint", "rustpython-common/num-bigint", "rustpython-compiler?/num-bigint", "rustpython-compiler-core/num-bigint", "rustpython-codegen?/num-bigint", "rustpython-derive/num-bigint", "rustpython-jit?/num-bigint", "rustpython-literal/num-bigint"] doc = ["dep:rustpython-doc", "dep:xz"] host_env = ["host_io", "rustpython-host_env/ctypes"] # FileIO without unrelated host modules such as ctypes, subprocess and signals. @@ -34,8 +36,8 @@ wasmbind = ["rustpython-common/wasm_js", "jiff/js", "wasm-bindgen"] [dependencies] rustpython-compiler = { workspace = true, optional = true } -rustpython-codegen = { workspace = true, optional = true } -rustpython-common = { workspace = true } +rustpython-codegen = { workspace = true, optional = true, features = ["std"] } +rustpython-common = { workspace = true, features = ["std"] } rustpython-doc = { workspace = true, optional = true } rustpython-derive = { workspace = true } rustpython-host_env = { workspace = true } @@ -63,7 +65,7 @@ itoa = { workspace = true } is-macro = { workspace = true } libc = { workspace = true } log = { workspace = true } -malachite-bigint = { workspace = true } +rustpython-bigint = { workspace = true } num-complex = { workspace = true } num-integer = { workspace = true } num-traits = { workspace = true } diff --git a/crates/vm/src/buffer.rs b/crates/vm/src/buffer.rs index a3f9342241e..7e85f5687f8 100644 --- a/crates/vm/src/buffer.rs +++ b/crates/vm/src/buffer.rs @@ -12,9 +12,9 @@ use rustpython_common::wtf8::Wtf8Buf; use core::{fmt, iter::Peekable, mem}; use half::f16; use itertools::Itertools; -use malachite_bigint::BigInt; use num_complex::Complex64; use num_traits::{PrimInt, ToPrimitive}; +use rustpython_bigint::BigInt; use std::{collections::HashMap, os::raw}; type PackFunc = fn(&VirtualMachine, FormatType, &PyObject, &mut dyn FnMut(&[u8])) -> PyResult<()>; diff --git a/crates/vm/src/builtins/code.rs b/crates/vm/src/builtins/code.rs index 86218bb8078..1af4a7ab593 100644 --- a/crates/vm/src/builtins/code.rs +++ b/crates/vm/src/builtins/code.rs @@ -27,8 +27,8 @@ use core::{ ops::Deref, sync::atomic::{AtomicPtr, AtomicU64, Ordering}, }; -use malachite_bigint::BigInt; use num_traits::Zero; +use rustpython_bigint::BigInt; use rustpython_common::wtf8::Wtf8Buf; use rustpython_compiler_core::{OneIndexed, bytecode::CodeUnits, bytecode::PyCodeLocationInfoKind}; diff --git a/crates/vm/src/builtins/descriptor.rs b/crates/vm/src/builtins/descriptor.rs index fcc51dbc93a..efd65527511 100644 --- a/crates/vm/src/builtins/descriptor.rs +++ b/crates/vm/src/builtins/descriptor.rs @@ -1107,7 +1107,7 @@ fn member_uint_value( ) -> PyResult<(u32, Option<&'static str>)> { let int_obj = value.try_index(vm)?; let big = int_obj.as_bigint(); - if big.sign() == malachite_bigint::Sign::Minus { + if big.sign() == rustpython_bigint::Sign::Minus { let long_val = core::ffi::c_long::try_from(big) .map_err(|_| vm.new_overflow_error("Python int too large to convert to C long"))?; // Keeps the low 32 bits whether `c_long` is 32 or 64 bits wide. @@ -1469,7 +1469,7 @@ fn member_ulong_value( ) -> PyResult<(core::ffi::c_ulong, Option<&'static str>)> { let int_obj = value.try_index(vm)?; let big = int_obj.as_bigint(); - if big.sign() == malachite_bigint::Sign::Minus { + if big.sign() == rustpython_bigint::Sign::Minus { let long_val = core::ffi::c_long::try_from(big) .map_err(|_| vm.new_overflow_error("Python int too large to convert to C long"))?; return Ok(( @@ -1488,7 +1488,7 @@ fn member_ulonglong_value( ) -> PyResult<(u64, Option<&'static str>)> { let int_obj = value.try_index(vm)?; let big = int_obj.as_bigint(); - if big.sign() == malachite_bigint::Sign::Minus { + if big.sign() == rustpython_bigint::Sign::Minus { let long_val = core::ffi::c_long::try_from(big) .map_err(|_| vm.new_overflow_error("Python int too large to convert to C long"))?; return Ok(( diff --git a/crates/vm/src/builtins/enumerate.rs b/crates/vm/src/builtins/enumerate.rs index d55443b184f..6a656f88cc2 100644 --- a/crates/vm/src/builtins/enumerate.rs +++ b/crates/vm/src/builtins/enumerate.rs @@ -11,8 +11,8 @@ use crate::{ raise_if_stop, types::{Constructor, IterNext, Iterable, SelfIter, drop_kwargs_if_init_overridden}, }; -use malachite_bigint::BigInt; use num_traits::ToPrimitive; +use rustpython_bigint::BigInt; /// Fast-path counter for `enumerate`. /// diff --git a/crates/vm/src/builtins/float.rs b/crates/vm/src/builtins/float.rs index 0e56f4a668c..2f31006552a 100644 --- a/crates/vm/src/builtins/float.rs +++ b/crates/vm/src/builtins/float.rs @@ -18,9 +18,9 @@ use crate::{ use core::cell::Cell; use core::ptr::NonNull; -use malachite_bigint::{BigInt, ToBigInt}; use num_complex::Complex64; use num_traits::{Signed, ToPrimitive, Zero}; +use rustpython_bigint::{BigInt, ToBigInt}; use rustpython_common::int::float_to_ratio; #[pyclass(module = false, name = "float")] diff --git a/crates/vm/src/builtins/int.rs b/crates/vm/src/builtins/int.rs index b9d897fdff9..d5d309d7516 100644 --- a/crates/vm/src/builtins/int.rs +++ b/crates/vm/src/builtins/int.rs @@ -22,9 +22,9 @@ use alloc::fmt; use core::cell::Cell; use core::ops::{Neg, Not}; use core::ptr::NonNull; -use malachite_bigint::{BigInt, BigUint, Sign}; use num_integer::{ExtendedGcd, Integer}; use num_traits::{One, Pow, PrimInt, Signed, ToPrimitive, Zero}; +use rustpython_bigint::{BigInt, BigUint, Sign}; use rustpython_common::wtf8::wtf8_concat; #[pyclass(module = false, name = "int")] diff --git a/crates/vm/src/builtins/memory/format.rs b/crates/vm/src/builtins/memory/format.rs index 91fb8b87e99..da43aee6e0e 100644 --- a/crates/vm/src/builtins/memory/format.rs +++ b/crates/vm/src/builtins/memory/format.rs @@ -6,8 +6,8 @@ use crate::{ common::rc::PyRc, function::{ArgIntoBool, ArgIntoComplex, ArgIntoFloat}, }; -use malachite_bigint::{BigInt, Sign}; use num_traits::PrimInt; +use rustpython_bigint::{BigInt, Sign}; use std::os::raw; /// A scalar format accepted by memoryview, rather than the full struct grammar. diff --git a/crates/vm/src/builtins/range.rs b/crates/vm/src/builtins/range.rs index 680d8e2478c..51c10799d07 100644 --- a/crates/vm/src/builtins/range.rs +++ b/crates/vm/src/builtins/range.rs @@ -19,9 +19,9 @@ use core::cell::Cell; use core::ffi::c_long; use core::ptr::NonNull; use crossbeam_utils::atomic::AtomicCell; -use malachite_bigint::{BigInt, Sign}; use num_integer::Integer; use num_traits::{One, Signed, ToPrimitive, Zero}; +use rustpython_bigint::{BigInt, Sign}; #[pyclass(module = false, name = "range")] #[derive(Debug, Clone)] diff --git a/crates/vm/src/builtins/slice.rs b/crates/vm/src/builtins/slice.rs index 7525a859eea..97ad991fe02 100644 --- a/crates/vm/src/builtins/slice.rs +++ b/crates/vm/src/builtins/slice.rs @@ -15,8 +15,8 @@ use crate::{ types::{Comparable, Constructor, Hashable, PyComparisonOp, Representable}, utils::collection_repr, }; -use malachite_bigint::{BigInt, ToBigInt}; use num_traits::{One, Signed, Zero}; +use rustpython_bigint::{BigInt, ToBigInt}; #[pyclass(module = false, name = "slice", unhashable = true, traverse = "manual")] #[derive(Debug)] diff --git a/crates/vm/src/bytes_inner.rs b/crates/vm/src/bytes_inner.rs index aa01847e40a..0ad955b18fa 100644 --- a/crates/vm/src/bytes_inner.rs +++ b/crates/vm/src/bytes_inner.rs @@ -28,8 +28,8 @@ pub(crate) type FromObject = fn(&VirtualMachine, &PyObject) -> PyResult> use alloc::borrow::Cow; use bstr::ByteSlice; use itertools::Itertools; -use malachite_bigint::BigInt; use num_traits::ToPrimitive; +use rustpython_bigint::BigInt; const STRING_WITHOUT_ENCODING: &str = "string argument without an encoding"; const ENCODING_WITHOUT_STRING: &str = "encoding without a string argument"; diff --git a/crates/vm/src/convert/try_from.rs b/crates/vm/src/convert/try_from.rs index fb6dd803585..6bf4a1a016b 100644 --- a/crates/vm/src/convert/try_from.rs +++ b/crates/vm/src/convert/try_from.rs @@ -1,5 +1,5 @@ -use malachite_bigint::Sign; use num_traits::ToPrimitive; +use rustpython_bigint::Sign; use crate::{ Py, VirtualMachine, diff --git a/crates/vm/src/frame.rs b/crates/vm/src/frame.rs index 966123afbf5..10082b57bbd 100644 --- a/crates/vm/src/frame.rs +++ b/crates/vm/src/frame.rs @@ -46,8 +46,8 @@ use core::ptr::NonNull; use core::sync::atomic; use core::sync::atomic::Ordering::{Acquire, Relaxed}; use itertools::Itertools; -use malachite_bigint::BigInt; use num_traits::{ToPrimitive, Zero}; +use rustpython_bigint::BigInt; use rustpython_common::atomic::{PyAtomic, Radium}; use rustpython_common::{ lock::{OnceCell, PyMutex}, diff --git a/crates/vm/src/function/number.rs b/crates/vm/src/function/number.rs index 9cbf716d808..5830775ff4a 100644 --- a/crates/vm/src/function/number.rs +++ b/crates/vm/src/function/number.rs @@ -4,9 +4,9 @@ use crate::{ builtins::{PyComplex, PyFloat, PyInt, PyIntRef}, }; use core::{ffi::c_int, ops::Deref}; -use malachite_bigint::BigInt; use num_complex::Complex64; use num_traits::{PrimInt, ToPrimitive}; +use rustpython_bigint::BigInt; /// A Python complex-like object. /// diff --git a/crates/vm/src/macros.rs b/crates/vm/src/macros.rs index 340e5461571..f30111b000c 100644 --- a/crates/vm/src/macros.rs +++ b/crates/vm/src/macros.rs @@ -81,7 +81,7 @@ macro_rules! py_namespace { /// # Examples /// /// ```rust -/// use malachite_bigint::ToBigInt; +/// use rustpython_bigint::ToBigInt; /// use num_traits::Zero; /// /// use rustpython_vm::{PyPayload, match_class}; @@ -104,7 +104,7 @@ macro_rules! py_namespace { /// With a binding to the downcasted type: /// /// ```rust -/// use malachite_bigint::ToBigInt; +/// use rustpython_bigint::ToBigInt; /// use num_traits::Zero; /// /// use rustpython_vm::{PyPayload, match_class}; diff --git a/crates/vm/src/sliceable.rs b/crates/vm/src/sliceable.rs index d2a141f7a24..b54ec04710b 100644 --- a/crates/vm/src/sliceable.rs +++ b/crates/vm/src/sliceable.rs @@ -4,8 +4,8 @@ use crate::{ builtins::{int::PyInt, slice::PySlice}, }; use core::ops::Range; -use malachite_bigint::BigInt; use num_traits::{Signed, ToPrimitive}; +use rustpython_bigint::BigInt; pub trait SliceableSequenceMutOp where diff --git a/crates/vm/src/stdlib/_ast/constant.rs b/crates/vm/src/stdlib/_ast/constant.rs index 29789f5519e..0ce25c44391 100644 --- a/crates/vm/src/stdlib/_ast/constant.rs +++ b/crates/vm/src/stdlib/_ast/constant.rs @@ -1,7 +1,7 @@ use super::*; use crate::builtins::{PyComplex, PyFrozenSet, PyIntRef, PyTuple}; use ast::str_prefix::StringLiteralPrefix; -use malachite_bigint::BigInt; +use rustpython_bigint::BigInt; use rustpython_codegen::compile::ruff_int_to_bigint; use rustpython_common::wtf8::Wtf8Buf; use rustpython_compiler_core::bytecode::ConstantData; diff --git a/crates/vm/src/stdlib/_ctypes/simple.rs b/crates/vm/src/stdlib/_ctypes/simple.rs index 91e04cd2e25..e4ca7b75fca 100644 --- a/crates/vm/src/stdlib/_ctypes/simple.rs +++ b/crates/vm/src/stdlib/_ctypes/simple.rs @@ -89,7 +89,7 @@ fn new_simple_type( Ok(PyCSimple(PyCData::from_bytes(zeroed_bytes(size), None))) } -pub(super) fn bigint_to_i128_wrapping(value: &malachite_bigint::BigInt) -> i128 { +pub(super) fn bigint_to_i128_wrapping(value: &rustpython_bigint::BigInt) -> i128 { if let Some(value) = value.to_i128() { return value; } diff --git a/crates/vm/src/stdlib/_io.rs b/crates/vm/src/stdlib/_io.rs index db39e204d14..22b9f9dffed 100644 --- a/crates/vm/src/stdlib/_io.rs +++ b/crates/vm/src/stdlib/_io.rs @@ -195,8 +195,8 @@ mod _io { sync::atomic::{AtomicBool, Ordering}, }; use crossbeam_utils::atomic::AtomicCell; - use malachite_bigint::BigInt; use num_traits::ToPrimitive; + use rustpython_bigint::BigInt; use std::io::{self, Cursor, SeekFrom, prelude::*}; fn validate_whence(whence: i32) -> bool { diff --git a/crates/vm/src/stdlib/_stat.rs b/crates/vm/src/stdlib/_stat.rs index ece04140373..8de6ede1b23 100644 --- a/crates/vm/src/stdlib/_stat.rs +++ b/crates/vm/src/stdlib/_stat.rs @@ -7,8 +7,8 @@ mod _stat { #[cfg(windows)] use rustpython_host_env::nt as host_nt; - use malachite_bigint::Sign; use num_traits::ToPrimitive; + use rustpython_bigint::Sign; use crate::{PyObjectRef, PyResult, VirtualMachine, convert::TryFromObject}; diff --git a/crates/vm/src/stdlib/gc.rs b/crates/vm/src/stdlib/gc.rs index cacf4df9ca0..cbf053a4c92 100644 --- a/crates/vm/src/stdlib/gc.rs +++ b/crates/vm/src/stdlib/gc.rs @@ -94,7 +94,7 @@ mod gc { i32::try_from(index.as_bigint()).map(Self).map_err(|_| { let message = if core::ffi::c_long::try_from(index.as_bigint()).is_err() { "Python int too large to convert to C long" - } else if index.as_bigint().sign() == malachite_bigint::Sign::Minus { + } else if index.as_bigint().sign() == rustpython_bigint::Sign::Minus { "signed integer is less than minimum" } else { "signed integer is greater than maximum" diff --git a/crates/vm/src/stdlib/marshal.rs b/crates/vm/src/stdlib/marshal.rs index 36e5ecd43d0..625c9810c87 100644 --- a/crates/vm/src/stdlib/marshal.rs +++ b/crates/vm/src/stdlib/marshal.rs @@ -19,8 +19,8 @@ mod decl { object::{AsObject, PyPayload}, }; use core::cell::RefCell; - use malachite_bigint::BigInt; use num_traits::{ToPrimitive, Zero}; + use rustpython_bigint::BigInt; use rustpython_compiler_core::marshal::{self, DumpableValue}; #[pyattr(name = "version")] @@ -316,7 +316,7 @@ mod decl { digits.pop(); } let n = digits.len() as i32; - let n = if sign == malachite_bigint::Sign::Minus { + let n = if sign == rustpython_bigint::Sign::Minus { -n } else { n diff --git a/crates/vm/src/stdlib/posix.rs b/crates/vm/src/stdlib/posix.rs index ff95a6c59e5..5444efaf0ab 100644 --- a/crates/vm/src/stdlib/posix.rs +++ b/crates/vm/src/stdlib/posix.rs @@ -1120,7 +1120,7 @@ pub mod module { ))) })?; let fd = i32::try_from(fd.as_bigint()).map_err(|_| { - let message = if fd.as_bigint().sign() == malachite_bigint::Sign::Minus { + let message = if fd.as_bigint().sign() == rustpython_bigint::Sign::Minus { "fd is less than minimum" } else { "fd is greater than maximum" @@ -1393,7 +1393,7 @@ pub mod module { ))) })?; i32::try_from(fd.as_bigint()).map(Self).map_err(|_| { - let message = if fd.as_bigint().sign() == malachite_bigint::Sign::Minus { + let message = if fd.as_bigint().sign() == rustpython_bigint::Sign::Minus { "fd is less than minimum" } else { "fd is greater than maximum" diff --git a/crates/vm/src/stdlib/posix/xattr.rs b/crates/vm/src/stdlib/posix/xattr.rs index 8af5eb8861d..f4cc7811f50 100644 --- a/crates/vm/src/stdlib/posix/xattr.rs +++ b/crates/vm/src/stdlib/posix/xattr.rs @@ -52,7 +52,7 @@ pub(super) mod _xattr { warn_if_bool_fd(&obj, vm)?; let fd = fd?; let fd = i32::try_from(fd.as_bigint()).map_err(|_| { - let message = if fd.as_bigint().sign() == malachite_bigint::Sign::Minus { + let message = if fd.as_bigint().sign() == rustpython_bigint::Sign::Minus { "fd is less than minimum" } else { "fd is greater than maximum" diff --git a/crates/vm/src/stdlib/posix_compat.rs b/crates/vm/src/stdlib/posix_compat.rs index dfc99175dcb..2704063427a 100644 --- a/crates/vm/src/stdlib/posix_compat.rs +++ b/crates/vm/src/stdlib/posix_compat.rs @@ -52,7 +52,7 @@ pub(crate) mod module { ))) })?; let fd = i32::try_from(fd.as_bigint()).map_err(|_| { - vm.new_overflow_error(if fd.as_bigint().sign() == malachite_bigint::Sign::Minus { + vm.new_overflow_error(if fd.as_bigint().sign() == rustpython_bigint::Sign::Minus { "fd is less than minimum" } else { "fd is greater than maximum" diff --git a/crates/vm/src/stdlib/winreg.rs b/crates/vm/src/stdlib/winreg.rs index e3e0dc66096..26c2574cc68 100644 --- a/crates/vm/src/stdlib/winreg.rs +++ b/crates/vm/src/stdlib/winreg.rs @@ -16,8 +16,8 @@ mod winreg { use crate::{Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine}; use core::ptr; use crossbeam_utils::atomic::AtomicCell; - use malachite_bigint::Sign; use num_traits::ToPrimitive; + use rustpython_bigint::Sign; use rustpython_common::wtf8::Wtf8Buf; use rustpython_host_env::windows::ToWideString; use rustpython_host_env::winreg as host_winreg; diff --git a/crates/vm/src/vm/context.rs b/crates/vm/src/vm/context.rs index e0547451d34..6e8f99fc7e8 100644 --- a/crates/vm/src/vm/context.rs +++ b/crates/vm/src/vm/context.rs @@ -25,9 +25,9 @@ use crate::{ types::{PyTypeFlags, PyTypeSlots, TypeZoo}, }; use core::ffi::{CStr, c_void}; -use malachite_bigint::BigInt; use num_complex::Complex64; use num_traits::ToPrimitive; +use rustpython_bigint::BigInt; use rustpython_common::lock::PyRwLock; #[derive(Debug)] diff --git a/crates/vm/src/vm/interpreter.rs b/crates/vm/src/vm/interpreter.rs index 74c1befb4bd..654cd1b8263 100644 --- a/crates/vm/src/vm/interpreter.rs +++ b/crates/vm/src/vm/interpreter.rs @@ -1053,7 +1053,7 @@ mod tests { builtins::{PyStr, int}, vm::{MAIN_INTERPRETER_ID, runtime}, }; - use malachite_bigint::ToBigInt; + use rustpython_bigint::ToBigInt; #[test] fn add_py_integers() { diff --git a/crates/wasm/Cargo.toml b/crates/wasm/Cargo.toml index def85c07298..0d25b500ee2 100644 --- a/crates/wasm/Cargo.toml +++ b/crates/wasm/Cargo.toml @@ -12,14 +12,16 @@ license.workspace = true crate-type = ["cdylib", "rlib"] [features] -default = ["freeze-stdlib", "doc", "ucd_3_2_0"] +default = ["malachite-bigint", "freeze-stdlib", "doc", "ucd_3_2_0"] +malachite-bigint = ["rustpython-common/malachite-bigint", "rustpython-pylib?/malachite-bigint", "rustpython-stdlib?/malachite-bigint", "rustpython-vm/malachite-bigint"] +num-bigint = ["rustpython-common/num-bigint", "rustpython-pylib?/num-bigint", "rustpython-stdlib?/num-bigint", "rustpython-vm/num-bigint"] doc = ["rustpython-vm/doc", "rustpython-stdlib?/doc"] freeze-stdlib = ["rustpython-vm/freeze-stdlib", "rustpython-pylib/freeze-stdlib", "rustpython-stdlib", "rustpython-stdlib/ssl"] ucd_3_2_0 = ["rustpython-stdlib?/ucd_3_2_0"] no-start-func = [] [dependencies] -rustpython-common = { workspace = true } +rustpython-common = { workspace = true, features = ["std"] } rustpython-pylib = { workspace = true, optional = true } rustpython-stdlib = { workspace = true, default-features = false, optional = true, features = ["doc"] } ruff_text_size = { workspace = true } diff --git a/example_projects/barebone/Cargo.toml b/example_projects/barebone/Cargo.toml index f622b65f75e..98f9c2b59e8 100644 --- a/example_projects/barebone/Cargo.toml +++ b/example_projects/barebone/Cargo.toml @@ -4,7 +4,7 @@ version = "0.1.0" edition = "2021" [dependencies] -rustpython-vm = { path = "../../crates/vm", default-features = false, features = ["stdio"] } +rustpython-vm = { path = "../../crates/vm", default-features = false, features = ["malachite-bigint", "stdio"] } [workspace] diff --git a/example_projects/frozen_stdlib/Cargo.toml b/example_projects/frozen_stdlib/Cargo.toml index 91bb14a083b..42abbb69743 100644 --- a/example_projects/frozen_stdlib/Cargo.toml +++ b/example_projects/frozen_stdlib/Cargo.toml @@ -4,9 +4,9 @@ version = "0.1.0" edition = "2021" [dependencies] -rustpython = { path = "../../", default-features = false, features = ["freeze-stdlib"] } -rustpython-vm = { path = "../../crates/vm", default-features = false, features = ["freeze-stdlib"] } -rustpython-pylib = { path = "../../crates/pylib", default-features = false, features = ["freeze-stdlib"] } +rustpython = { path = "../../", default-features = false, features = ["malachite-bigint", "freeze-stdlib"] } +rustpython-vm = { path = "../../crates/vm", default-features = false, features = ["malachite-bigint", "freeze-stdlib"] } +rustpython-pylib = { path = "../../crates/pylib", default-features = false, features = ["malachite-bigint", "freeze-stdlib"] } [workspace] diff --git a/example_projects/wasm32_without_js/rustpython-without-js/Cargo.toml b/example_projects/wasm32_without_js/rustpython-without-js/Cargo.toml index a47a2369981..f19be18619f 100644 --- a/example_projects/wasm32_without_js/rustpython-without-js/Cargo.toml +++ b/example_projects/wasm32_without_js/rustpython-without-js/Cargo.toml @@ -11,7 +11,7 @@ host-io = ["rustpython-vm/host_io"] [dependencies] getrandom = "0.4" -rustpython-vm = { path = "../../../crates/vm", default-features = false, features = ["compiler"] } +rustpython-vm = { path = "../../../crates/vm", default-features = false, features = ["malachite-bigint", "compiler"] } [workspace] diff --git a/host_env_proposal.md b/host_env_proposal.md index fdff49938cf..2b3e6b49561 100644 --- a/host_env_proposal.md +++ b/host_env_proposal.md @@ -184,7 +184,7 @@ rustpython-host_env = { workspace = true, optional = true } ```bash cargo check -p rustpython-host_env cargo test -cargo check -p rustpython-vm --no-default-features --features compiler,gc # sandbox build +cargo check -p rustpython-vm --no-default-features --features malachite-bigint,compiler,gc # sandbox build ``` ## Phase 2: Extract host functions from vm/stdlib modules @@ -430,8 +430,8 @@ disallowed_methods = "deny" Build without `host_env` feature to catch any code that accidentally compiles without the feature gate: ```bash -cargo check -p rustpython-vm --no-default-features --features compiler,gc -cargo check -p rustpython-stdlib --no-default-features --features compiler +cargo check -p rustpython-vm --no-default-features --features malachite-bigint,compiler,gc +cargo check -p rustpython-stdlib --no-default-features --features malachite-bigint,compiler ``` ### Layer 4: Whitelist-based module audit (CI script) diff --git a/scripts/release-wapm.sh b/scripts/release-wapm.sh index 62171fbe61c..ed0e121a6ee 100644 --- a/scripts/release-wapm.sh +++ b/scripts/release-wapm.sh @@ -3,7 +3,7 @@ set -e cd "$(dirname "$(dirname "$0")")" -FEATURES_FOR_WAPM=(stdlib zlib) +FEATURES_FOR_WAPM=(malachite-bigint stdlib zlib) export BUILDTIME_RUSTPYTHONPATH="/lib/rustpython" diff --git a/scripts/whats_left.py b/scripts/whats_left.py index 0fa09dbe013..3b4c17a782c 100755 --- a/scripts/whats_left.py +++ b/scripts/whats_left.py @@ -65,7 +65,10 @@ def parse_args(): parser.add_argument( "--no-default-features", action="store_true", - help="disable default features when building RustPython", + help=( + "disable default features; select malachite-bigint or num-bigint " + "with --features" + ), ) parser.add_argument( "--features", From b2247449641953b8c3e5b7340d2eb57fe2a1379b Mon Sep 17 00:00:00 2001 From: youknowdot Date: Tue, 1 Dec 2026 14:54:38 +0900 Subject: [PATCH 2/6] Keep the BigInt default on the executable only Let RustPython library users opt into one backend without disabling unrelated defaults. Select Malachite explicitly for the existing standalone CAPI, Miri and browser build commands. Assisted-by: Codex:GPT-6.2 --- .github/workflows/ci.yaml | 12 ++++++------ AGENTS.md | 4 ++-- README.md | 9 +++++---- crates/bigint/Cargo.toml | 1 - crates/capi/Cargo.toml | 1 - crates/codegen/Cargo.toml | 2 +- crates/common/Cargo.toml | 2 +- crates/compiler-core/Cargo.toml | 1 - crates/compiler/Cargo.toml | 1 - crates/derive-impl/Cargo.toml | 1 - crates/derive/Cargo.toml | 1 - crates/jit/Cargo.toml | 1 - crates/literal/Cargo.toml | 1 - crates/pylib/Cargo.toml | 1 - crates/stdlib/Cargo.toml | 2 +- crates/vm/Cargo.toml | 2 +- crates/wasm/Cargo.toml | 2 +- wasm/demo/webpack.config.js | 1 + wasm/notebook/webpack.config.js | 1 + 19 files changed, 20 insertions(+), 26 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 8890aac4a7f..178ddf714b5 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -300,17 +300,17 @@ jobs: - name: Build c-api tests if: env.RUN_RUST_TESTS == 'true' && runner.os != 'Windows' # Requires pyo3 0.29+ on Windows working-directory: crates/capi - run: cargo test --no-run --locked + run: cargo test --no-run --locked --features malachite-bigint - name: run c-api tests if: env.RUN_RUST_TESTS == 'true' && runner.os != 'Windows' # Requires pyo3 0.29+ on Windows working-directory: crates/capi - run: cargo test --locked --lib --bins --tests + run: cargo test --locked --features malachite-bigint --lib --bins --tests - name: Run c-api doctests if: env.RUN_RUST_TESTS == 'true' && runner.os != 'Windows' # Requires pyo3 0.29+ on Windows working-directory: crates/capi - run: cargo test --doc --locked + run: cargo test --doc --locked --features malachite-bigint - name: Check host_env without ctypes if: env.RUN_RUST_TESTS == 'true' && runner.os == 'Windows' @@ -901,12 +901,12 @@ jobs: ${{ runner.os }}- - name: Build tests under miri - run: cargo +${{ env.NIGHTLY_CHANNEL }} miri test --no-run --locked -p rustpython-vm -- miri_test + run: cargo +${{ env.NIGHTLY_CHANNEL }} miri test --no-run --locked -p rustpython-vm --features malachite-bigint -- miri_test env: MIRIFLAGS: "-Zmiri-ignore-leaks -Zmiri-permissive-provenance" - name: Run tests under miri - run: cargo +${{ env.NIGHTLY_CHANNEL }} miri test --locked -p rustpython-vm -- miri_test + run: cargo +${{ env.NIGHTLY_CHANNEL }} miri test --locked -p rustpython-vm --features malachite-bigint -- miri_test env: # miri-ignore-leaks because the type-object circular reference means that there will always be # a memory leak, at least until we have proper cyclic gc @@ -953,7 +953,7 @@ jobs: ${{ runner.os }}- - name: cargo clippy - run: cargo --locked clippy --keep-going --manifest-path=crates/wasm/Cargo.toml -- -Dwarnings + run: cargo --locked clippy --keep-going --manifest-path=crates/wasm/Cargo.toml --features malachite-bigint -- -Dwarnings - name: install wasm-pack run: curl https://wasm-bindgen.github.io/wasm-pack/installer/init.sh -sSf | sh diff --git a/AGENTS.md b/AGENTS.md index 3f0c8b4862e..1e5b15a0cf0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -40,11 +40,11 @@ Before completing a task, run the checks that match the change: cargo test --workspace --exclude rustpython_wasm --exclude rustpython-venvlauncher --exclude rustpython-capi # C-API tests, from their directory so their separate Cargo config applies -(cd crates/capi && cargo test) +(cd crates/capi && cargo test --features malachite-bigint) # Clippy, with the same C-API separation cargo clippy --workspace --all-targets --exclude rustpython_wasm --exclude rustpython-venvlauncher --exclude rustpython-capi -(cd crates/capi && cargo clippy --all-targets) +(cd crates/capi && cargo clippy --features malachite-bigint --all-targets) # A Python test module, or one test in it (release mode: faster to run) cargo run --release -- -m test test_unicode diff --git a/README.md b/README.md index b00598f4538..bbb0c3377b2 100644 --- a/README.md +++ b/README.md @@ -110,8 +110,9 @@ OpenSSL version 3 is expected and tested in CI. Older versions may not work. ### Big integer backends -RustPython uses Malachite by default. A build with `--no-default-features` -must select `malachite-bigint` or `num-bigint` explicitly. For example: +Only the `rustpython` executable package enables Malachite by default. +Library consumers and executable builds using `--no-default-features` must +select `malachite-bigint` or `num-bigint` explicitly. For example: ```sh cargo build --no-default-features --features num-bigint,stdlib,stdio,host_env,threading @@ -119,8 +120,8 @@ cargo build --no-default-features --features num-bigint,stdlib,stdio,host_env,th Cargo features are additive, so don't combine both backends or enable `num-bigint` on top of the default features. Embedders that directly depend -on more than one RustPython crate must select the same backend for all of -them, disabling each dependency's defaults for the `num-bigint` build. +on more than one RustPython crate should select the same backend throughout. +RustPython library defaults do not select a backend. ### WASI diff --git a/crates/bigint/Cargo.toml b/crates/bigint/Cargo.toml index 748a0f98b7f..07324d43e3e 100644 --- a/crates/bigint/Cargo.toml +++ b/crates/bigint/Cargo.toml @@ -9,7 +9,6 @@ repository.workspace = true license.workspace = true [features] -default = ["malachite-bigint"] malachite-bigint = ["dep:malachite-bigint", "dep:malachite-base", "dep:malachite-q"] num-bigint = ["dep:num-bigint", "dep:num-integer", "dep:num-traits"] diff --git a/crates/capi/Cargo.toml b/crates/capi/Cargo.toml index dc5949d3557..070bd29122c 100644 --- a/crates/capi/Cargo.toml +++ b/crates/capi/Cargo.toml @@ -12,7 +12,6 @@ license.workspace = true crate-type = ["cdylib", "rlib"] [features] -default = ["malachite-bigint"] malachite-bigint = ["rustpython-bigint/malachite-bigint", "rustpython-pylib/malachite-bigint", "rustpython-stdlib/malachite-bigint", "rustpython-vm/malachite-bigint"] num-bigint = ["rustpython-bigint/num-bigint", "rustpython-pylib/num-bigint", "rustpython-stdlib/num-bigint", "rustpython-vm/num-bigint"] diff --git a/crates/codegen/Cargo.toml b/crates/codegen/Cargo.toml index c6960eaa3a7..637ea527903 100644 --- a/crates/codegen/Cargo.toml +++ b/crates/codegen/Cargo.toml @@ -9,7 +9,7 @@ repository.workspace = true license.workspace = true [features] -default = ["malachite-bigint", "std"] +default = ["std"] malachite-bigint = ["rustpython-bigint/malachite-bigint", "rustpython-compiler-core/malachite-bigint", "rustpython-literal/malachite-bigint"] num-bigint = ["rustpython-bigint/num-bigint", "rustpython-compiler-core/num-bigint", "rustpython-literal/num-bigint"] std = ["thiserror/std", "itertools/use_std"] diff --git a/crates/common/Cargo.toml b/crates/common/Cargo.toml index f1690ce35f0..4ae1b558717 100644 --- a/crates/common/Cargo.toml +++ b/crates/common/Cargo.toml @@ -9,7 +9,7 @@ repository.workspace = true license.workspace = true [features] -default = ["malachite-bigint", "std"] +default = ["std"] malachite-bigint = ["rustpython-bigint/malachite-bigint", "rustpython-literal/malachite-bigint"] num-bigint = ["rustpython-bigint/num-bigint", "rustpython-literal/num-bigint"] binascii = ["dep:crc32fast"] diff --git a/crates/compiler-core/Cargo.toml b/crates/compiler-core/Cargo.toml index 4fac7ee0c94..09dd78c60d6 100644 --- a/crates/compiler-core/Cargo.toml +++ b/crates/compiler-core/Cargo.toml @@ -9,7 +9,6 @@ repository.workspace = true license.workspace = true [features] -default = ["malachite-bigint"] malachite-bigint = ["rustpython-bigint/malachite-bigint"] num-bigint = ["rustpython-bigint/num-bigint"] diff --git a/crates/compiler/Cargo.toml b/crates/compiler/Cargo.toml index 9ed6e37dbc2..d4e137361ec 100644 --- a/crates/compiler/Cargo.toml +++ b/crates/compiler/Cargo.toml @@ -9,7 +9,6 @@ repository.workspace = true license.workspace = true [features] -default = ["malachite-bigint"] malachite-bigint = ["rustpython-compiler-core/malachite-bigint", "rustpython-codegen/malachite-bigint"] num-bigint = ["rustpython-compiler-core/num-bigint", "rustpython-codegen/num-bigint"] diff --git a/crates/derive-impl/Cargo.toml b/crates/derive-impl/Cargo.toml index 9541be6c2a8..42f1b52bdc3 100644 --- a/crates/derive-impl/Cargo.toml +++ b/crates/derive-impl/Cargo.toml @@ -9,7 +9,6 @@ repository.workspace = true license.workspace = true [features] -default = ["malachite-bigint"] malachite-bigint = ["rustpython-compiler-core/malachite-bigint"] num-bigint = ["rustpython-compiler-core/num-bigint"] diff --git a/crates/derive/Cargo.toml b/crates/derive/Cargo.toml index f991cdabc69..8eeceb37a4f 100644 --- a/crates/derive/Cargo.toml +++ b/crates/derive/Cargo.toml @@ -12,7 +12,6 @@ license.workspace = true proc-macro = true [features] -default = ["malachite-bigint"] malachite-bigint = ["rustpython-compiler/malachite-bigint", "rustpython-derive-impl/malachite-bigint"] num-bigint = ["rustpython-compiler/num-bigint", "rustpython-derive-impl/num-bigint"] diff --git a/crates/jit/Cargo.toml b/crates/jit/Cargo.toml index ecafe4de608..6f554dcf475 100644 --- a/crates/jit/Cargo.toml +++ b/crates/jit/Cargo.toml @@ -11,7 +11,6 @@ license.workspace = true autotests = false [features] -default = ["malachite-bigint"] malachite-bigint = ["rustpython-compiler-core/malachite-bigint"] num-bigint = ["rustpython-compiler-core/num-bigint"] diff --git a/crates/literal/Cargo.toml b/crates/literal/Cargo.toml index 2d4894e189c..83cfe34e0f3 100644 --- a/crates/literal/Cargo.toml +++ b/crates/literal/Cargo.toml @@ -12,7 +12,6 @@ rust-version = { workspace = true } workspace = true [features] -default = ["malachite-bigint"] malachite-bigint = ["rustpython-bigint/malachite-bigint"] num-bigint = ["rustpython-bigint/num-bigint"] diff --git a/crates/pylib/Cargo.toml b/crates/pylib/Cargo.toml index 529e0c16471..6fe7d8337e2 100644 --- a/crates/pylib/Cargo.toml +++ b/crates/pylib/Cargo.toml @@ -10,7 +10,6 @@ rust-version.workspace = true repository.workspace = true [features] -default = ["malachite-bigint"] malachite-bigint = ["rustpython-compiler-core?/malachite-bigint", "rustpython-derive?/malachite-bigint"] num-bigint = ["rustpython-compiler-core?/num-bigint", "rustpython-derive?/num-bigint"] freeze-stdlib = ["dep:rustpython-compiler-core", "dep:rustpython-derive", "dep:sha2"] diff --git a/crates/stdlib/Cargo.toml b/crates/stdlib/Cargo.toml index 4c6c9c6211f..22544902638 100644 --- a/crates/stdlib/Cargo.toml +++ b/crates/stdlib/Cargo.toml @@ -11,7 +11,7 @@ license.workspace = true # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [features] -default = ["malachite-bigint", "compiler", "host_env", "doc", "ucd_3_2_0"] +default = ["compiler", "host_env", "doc", "ucd_3_2_0"] malachite-bigint = ["rustpython-bigint/malachite-bigint", "rustpython-common/malachite-bigint", "rustpython-derive/malachite-bigint", "rustpython-vm/malachite-bigint", "pymath/malachite-bigint", "rustpython-pylib/malachite-bigint"] num-bigint = ["rustpython-bigint/num-bigint", "rustpython-common/num-bigint", "rustpython-derive/num-bigint", "rustpython-vm/num-bigint", "pymath/num-bigint", "rustpython-pylib/num-bigint"] ucd_3_2_0 = ["rustpython-unicode/ucd_3_2_0"] diff --git a/crates/vm/Cargo.toml b/crates/vm/Cargo.toml index 9e5d1d383c7..300431c116b 100644 --- a/crates/vm/Cargo.toml +++ b/crates/vm/Cargo.toml @@ -10,7 +10,7 @@ repository.workspace = true license.workspace = true [features] -default = ["malachite-bigint", "compiler", "wasmbind", "gc", "host_env", "stdio", "doc"] +default = ["compiler", "wasmbind", "gc", "host_env", "stdio", "doc"] malachite-bigint = ["rustpython-bigint/malachite-bigint", "rustpython-common/malachite-bigint", "rustpython-compiler?/malachite-bigint", "rustpython-compiler-core/malachite-bigint", "rustpython-codegen?/malachite-bigint", "rustpython-derive/malachite-bigint", "rustpython-jit?/malachite-bigint", "rustpython-literal/malachite-bigint"] num-bigint = ["rustpython-bigint/num-bigint", "rustpython-common/num-bigint", "rustpython-compiler?/num-bigint", "rustpython-compiler-core/num-bigint", "rustpython-codegen?/num-bigint", "rustpython-derive/num-bigint", "rustpython-jit?/num-bigint", "rustpython-literal/num-bigint"] doc = ["dep:rustpython-doc", "dep:xz"] diff --git a/crates/wasm/Cargo.toml b/crates/wasm/Cargo.toml index 0d25b500ee2..93083fb5569 100644 --- a/crates/wasm/Cargo.toml +++ b/crates/wasm/Cargo.toml @@ -12,7 +12,7 @@ license.workspace = true crate-type = ["cdylib", "rlib"] [features] -default = ["malachite-bigint", "freeze-stdlib", "doc", "ucd_3_2_0"] +default = ["freeze-stdlib", "doc", "ucd_3_2_0"] malachite-bigint = ["rustpython-common/malachite-bigint", "rustpython-pylib?/malachite-bigint", "rustpython-stdlib?/malachite-bigint", "rustpython-vm/malachite-bigint"] num-bigint = ["rustpython-common/num-bigint", "rustpython-pylib?/num-bigint", "rustpython-stdlib?/num-bigint", "rustpython-vm/num-bigint"] doc = ["rustpython-vm/doc", "rustpython-stdlib?/doc"] diff --git a/wasm/demo/webpack.config.js b/wasm/demo/webpack.config.js index 6c798d2ca4f..9a3fc533aaa 100644 --- a/wasm/demo/webpack.config.js +++ b/wasm/demo/webpack.config.js @@ -65,6 +65,7 @@ module.exports = (env = {}) => { if (!env.noWasmPack) { config.plugins.push( new WasmPackPlugin({ + extraArgs: '-- --features malachite-bigint', crateDirectory: path.join(__dirname, '../../crates/wasm'), }), ); diff --git a/wasm/notebook/webpack.config.js b/wasm/notebook/webpack.config.js index a3e3f8ef713..08a66e568b5 100644 --- a/wasm/notebook/webpack.config.js +++ b/wasm/notebook/webpack.config.js @@ -64,6 +64,7 @@ module.exports = (env = {}) => { if (!env.noWasmPack) { config.plugins.push( new WasmPackPlugin({ + extraArgs: '-- --features malachite-bigint', crateDirectory: path.join(__dirname, '../lib'), forceMode: 'release', }), From 798dd48630e59ade069dc2e8214be308afad94ee Mon Sep 17 00:00:00 2001 From: youknowdot Date: Tue, 1 Dec 2026 16:10:23 +0900 Subject: [PATCH 3/6] Preserve integer-to-float overflow across BigInt backends Share the finite conversion used by int.__float__ with constant folding, match patterns, and integer float formatting. Reject an overflowing negative exponent before powf can turn it into zero, without changing legitimate underflow. Keep exact rounding immediately below the overflow midpoint and restore the original signed-zero and rounding notes for integer division. --- crates/bigint/Cargo.toml | 4 +-- crates/bigint/src/lib.rs | 29 ++++++++++++++++++++ crates/codegen/src/compile.rs | 18 +++++++++++-- crates/codegen/src/ir.rs | 45 ++++++++++++++++++-------------- crates/codegen/src/preprocess.rs | 9 ++----- crates/common/src/format.rs | 19 ++++++++++++-- crates/common/src/int.rs | 17 +++--------- crates/vm/src/format.rs | 4 ++- 8 files changed, 97 insertions(+), 48 deletions(-) diff --git a/crates/bigint/Cargo.toml b/crates/bigint/Cargo.toml index 07324d43e3e..8060092f816 100644 --- a/crates/bigint/Cargo.toml +++ b/crates/bigint/Cargo.toml @@ -10,7 +10,7 @@ license.workspace = true [features] malachite-bigint = ["dep:malachite-bigint", "dep:malachite-base", "dep:malachite-q"] -num-bigint = ["dep:num-bigint", "dep:num-integer", "dep:num-traits"] +num-bigint = ["dep:num-bigint", "dep:num-integer"] [dependencies] malachite-bigint = { workspace = true, optional = true } @@ -18,7 +18,7 @@ malachite-base = { workspace = true, optional = true } malachite-q = { workspace = true, optional = true } num-bigint = { workspace = true, optional = true } num-integer = { workspace = true, optional = true } -num-traits = { workspace = true, optional = true } +num-traits.workspace = true [lints] workspace = true diff --git a/crates/bigint/src/lib.rs b/crates/bigint/src/lib.rs index a5166aab057..2ed70ff68d5 100644 --- a/crates/bigint/src/lib.rs +++ b/crates/bigint/src/lib.rs @@ -11,6 +11,20 @@ pub use malachite_bigint::{BigInt, BigUint, Sign, ToBigInt}; #[cfg(all(feature = "num-bigint", not(feature = "malachite-bigint")))] pub use num_bigint::{BigInt, BigUint, Sign, ToBigInt}; +/// Convert an integer to a finite float, or return None when it overflows. +#[inline(always)] +#[must_use] +pub fn bigint_to_finite_float(int: &BigInt) -> Option { + use num_traits::{One, ToPrimitive}; + + // malachite-bigint's ToPrimitive returns None when the input exceeds + // the largest finite magnitude, even when nearest rounding is finite. + let value = int + .to_f64() + .unwrap_or_else(|| true_div(int, &BigInt::one())); + value.is_finite().then_some(value) +} + /// Express a finite binary64 value as a reduced ratio with a positive denominator. #[cfg(feature = "malachite-bigint")] #[must_use] @@ -68,10 +82,14 @@ pub fn true_div(numerator: &BigInt, denominator: &BigInt) -> f64 { use malachite_base::{num::conversion::traits::RoundingInto, rounding_modes::RoundingMode}; use malachite_q::Rational; + // Rational has no signed zero. Preserve the division sign before + // converting a zero numerator, as CPython's long_true_divide does. if numerator.sign() == Sign::NoSign && denominator.sign() == Sign::Minus { return -0.0; } let rational = Rational::from_integers_ref(numerator.into(), denominator.into()); + // Nearest rounding can return the largest finite value for a quotient + // slightly beyond it; overflow starts at the halfway rounding boundary. rational.rounding_into(RoundingMode::Nearest).0 } @@ -150,6 +168,17 @@ extern crate alloc; mod tests { use super::*; + #[test] + fn integer_to_float_checks_the_halfway_overflow_boundary() { + let one = BigInt::from(1); + let halfway = (&one << 1024usize) - (&one << 970usize); + let just_below = &halfway - &one; + assert_eq!(bigint_to_finite_float(&just_below), Some(f64::MAX)); + assert_eq!(bigint_to_finite_float(&-&just_below), Some(-f64::MAX)); + assert_eq!(bigint_to_finite_float(&halfway), None); + assert_eq!(bigint_to_finite_float(&-&halfway), None); + } + #[test] fn exact_float_ratios() { assert_eq!(float_to_ratio(-0.0), Some((0.into(), 1.into()))); diff --git a/crates/codegen/src/compile.rs b/crates/codegen/src/compile.rs index 00444447fc4..8b4500d4090 100644 --- a/crates/codegen/src/compile.rs +++ b/crates/codegen/src/compile.rs @@ -26,7 +26,7 @@ use num_complex::Complex; use num_traits::{Num, ToPrimitive, Zero}; use ruff_python_ast::{self as ast, HasNodeIndex, name::Name}; use ruff_text_size::{Ranged, TextRange, TextSize, TextSlice}; -use rustpython_bigint::BigInt; +use rustpython_bigint::{BigInt, bigint_to_finite_float}; use rustpython_compiler_core::{ AstLocations, Mode, OneIndexed, PositionEncoding, SourceFile, SourceLocation, SourceLocationRange, @@ -12134,7 +12134,7 @@ impl<'warnings> Compiler<'warnings> { right: &ConstantData, ) -> Option { let left = match left { - ConstantData::Integer { value } => value.to_f64()?, + ConstantData::Integer { value } => bigint_to_finite_float(value)?, ConstantData::Float { value } => *value, _ => return None, }; @@ -14799,6 +14799,20 @@ match x: compile_top(ast, source_file, Mode::Exec, CompileOpts::default()).unwrap(); } + #[test] + fn match_literal_rejects_an_overflowing_real_component() { + let one = BigInt::from(1); + let halfway = (&one << 1024usize) - (&one << 970usize); + let just_below = &halfway - &one; + for n in [&halfway, &-&halfway] { + assert_eq!( + compile_exec_error_message(&format!("match x:\n case {n} + 1j: pass\n")), + "patterns may only match literals and attribute lookups" + ); + } + compile_exec(&format!("match x:\n case {just_below} + 1j: pass\n")); + } + #[test] fn match_literal_binop_folding_uses_cpython_complex_shape() { assert!( diff --git a/crates/codegen/src/ir.rs b/crates/codegen/src/ir.rs index b5c55af0c59..6bd8422164f 100644 --- a/crates/codegen/src/ir.rs +++ b/crates/codegen/src/ir.rs @@ -3,7 +3,7 @@ use core::ops::{Deref, DerefMut, Index, IndexMut}; use crate::{IndexMap, IndexSet, error::InternalError}; use num_complex::Complex; use num_traits::{ToPrimitive, Zero}; -use rustpython_bigint::BigInt; +use rustpython_bigint::{BigInt, bigint_to_finite_float}; use rustpython_wtf8::Wtf8Buf; use rustpython_compiler_core::{ @@ -4749,14 +4749,11 @@ fn const_folding_safe_power(left: &ConstantData, right: &ConstantData) -> Option if l.is_zero() { return None; } - let base = l.to_f64()?; - if !base.is_finite() { - return None; - } + let base = bigint_to_finite_float(l)?; let result = if let Some(exp) = r.to_i32() { base.powi(exp) } else { - base.powf(r.to_f64()?) + base.powf(bigint_to_finite_float(r)?) }; if !result.is_finite() { return None; @@ -5223,7 +5220,7 @@ fn eval_const_binop( } // Int op Float or Float op Int → Float (ConstantData::Integer { value: l }, ConstantData::Float { value: r }) => { - let l_f = l.to_f64()?; + let l_f = bigint_to_finite_float(l)?; eval_const_binop( &ConstantData::Float { value: l_f }, &ConstantData::Float { value: *r }, @@ -5231,7 +5228,7 @@ fn eval_const_binop( ) } (ConstantData::Float { value: l }, ConstantData::Integer { value: r }) => { - let r_f = r.to_f64()?; + let r_f = bigint_to_finite_float(r)?; eval_const_binop( &ConstantData::Float { value: *l }, &ConstantData::Float { value: r_f }, @@ -5239,20 +5236,10 @@ fn eval_const_binop( ) } (ConstantData::Integer { value: l }, ConstantData::Complex { value: r }) => { - eval_const_mixed_complex_binop( - l.to_f64().filter(|value| value.is_finite())?, - *r, - true, - op, - ) + eval_const_mixed_complex_binop(bigint_to_finite_float(l)?, *r, true, op) } (ConstantData::Complex { value: l }, ConstantData::Integer { value: r }) => { - eval_const_mixed_complex_binop( - r.to_f64().filter(|value| value.is_finite())?, - *l, - false, - op, - ) + eval_const_mixed_complex_binop(bigint_to_finite_float(r)?, *l, false, op) } (ConstantData::Float { value: l }, ConstantData::Complex { value: r }) => { eval_const_mixed_complex_binop(*l, *r, true, op) @@ -7191,6 +7178,24 @@ mod tests { ConstantData::Float { value: f64::NAN } } + #[test] + fn mixed_numeric_folding_leaves_overflow_to_runtime() { + let integer = ConstantData::Integer { + value: BigInt::from(1) << 1024usize, + }; + let float = ConstantData::Float { value: 0.0 }; + assert!(eval_const_binop(&integer, &float, oparg::BinaryOperator::Add).is_none()); + assert!(eval_const_binop(&float, &integer, oparg::BinaryOperator::Add).is_none()); + let exponent = ConstantData::Integer { + value: -(BigInt::from(1) << 1024usize), + }; + assert!(const_folding_safe_power(&int_const(2), &exponent).is_none()); + assert!(matches!( + const_folding_safe_power(&int_const(2), &int_const(-1075)), + Some(ConstantData::Float { value: 0.0 }) + )); + } + #[test] fn constant_pool_frozenset_key_ignores_order_and_duplicates_like_cpython() { let mut pool = ConstantPool::default(); diff --git a/crates/codegen/src/preprocess.rs b/crates/codegen/src/preprocess.rs index be5b5939b3b..1b271fcb600 100644 --- a/crates/codegen/src/preprocess.rs +++ b/crates/codegen/src/preprocess.rs @@ -3,8 +3,7 @@ use alloc::{ string::{String, ToString}, vec::Vec, }; -use num_traits::ToPrimitive; -use rustpython_bigint::BigInt; +use rustpython_bigint::{BigInt, bigint_to_finite_float}; use ruff_python_ast::{ self as ast, AtomicNodeIndex, ConversionFlag, Expr, ExprFString, FString, FStringFlags, @@ -946,11 +945,7 @@ fn fold_match_number_binop(left: &Expr, op: Operator, right: &Expr) -> Option { // CPython refuses to convert an overflowing integer to float and // leaves the binary expression unfolded in this optimization pass. - let value = value.to_f64()?; - if !value.is_finite() { - return None; - } - value + bigint_to_finite_float(&value)? } MatchNumber::Float(value) => value, MatchNumber::Complex { diff --git a/crates/common/src/format.rs b/crates/common/src/format.rs index 4d0c7aecad7..109c974cd06 100644 --- a/crates/common/src/format.rs +++ b/crates/common/src/format.rs @@ -4,7 +4,7 @@ use core::{cmp, str::FromStr}; use num_complex::Complex64; use num_traits::FromPrimitive; use num_traits::{Signed, cast::ToPrimitive}; -use rustpython_bigint::{BigInt, Sign}; +use rustpython_bigint::{BigInt, Sign, bigint_to_finite_float}; use rustpython_literal::float; use rustpython_literal::format::Case; @@ -1069,7 +1069,7 @@ impl FormatSpec { | FormatType::FixedPoint(_) | FormatType::Exponent(_) | FormatType::Percentage, - ) => match num.to_f64() { + ) => match bigint_to_finite_float(num) { Some(float) => return self.format_float(float), _ => Err(FormatSpecError::UnableToConvert), }, @@ -2047,6 +2047,21 @@ mod tests { ); } + #[test] + fn integer_float_formats_check_overflow_before_formatting() { + let one = BigInt::from(1); + let halfway = (&one << 1024usize) - (&one << 970usize); + let just_below = &halfway - &one; + for spec in ["e", "f", "g", "%"] { + let spec = FormatSpec::parse(spec).unwrap(); + assert_eq!( + spec.format_int(&halfway), + Err(FormatSpecError::UnableToConvert) + ); + assert_eq!(spec.format_int(&just_below), spec.format_float(f64::MAX)); + } + } + #[test] fn format_int() { assert_eq!( diff --git a/crates/common/src/int.rs b/crates/common/src/int.rs index 316aedf9d54..d61fd17da24 100644 --- a/crates/common/src/int.rs +++ b/crates/common/src/int.rs @@ -1,7 +1,7 @@ -use num_traits::{One, ToPrimitive, Zero}; +use num_traits::Zero; use rustpython_bigint::{BigInt, BigUint, Sign}; -pub use rustpython_bigint::{float_to_ratio, true_div}; +pub use rustpython_bigint::{bigint_to_finite_float, float_to_ratio, true_div}; #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum BytesToIntError { @@ -174,21 +174,10 @@ fn word_all_ascii_digits(word: u64) -> bool { (below | above) & 0x8080_8080_8080_8080 == 0 } -/// Convert an integer to a finite float, or return None when it overflows. -#[inline(always)] -#[must_use] -pub fn bigint_to_finite_float(int: &BigInt) -> Option { - // malachite-bigint's ToPrimitive returns None when the input exceeds - // the largest finite magnitude, even when nearest rounding is finite. - let value = int - .to_f64() - .unwrap_or_else(|| true_div(int, &BigInt::one())); - value.is_finite().then_some(value) -} - #[cfg(test)] mod tests { use super::*; + use num_traits::One; #[test] fn true_div_signed_zero() { diff --git a/crates/vm/src/format.rs b/crates/vm/src/format.rs index 4c9b93bab09..6443729e5c5 100644 --- a/crates/vm/src/format.rs +++ b/crates/vm/src/format.rs @@ -84,7 +84,9 @@ pub(crate) fn format_spec_error( FormatSpecError::NotAllowed(s) => { vm.new_value_error(format!("{s} not allowed with integer format specifier 'c'")) } - FormatSpecError::UnableToConvert => vm.new_value_error("Unable to convert int to float"), + FormatSpecError::UnableToConvert => { + vm.new_overflow_error("int too large to convert to float") + } FormatSpecError::CodeNotInRange => vm.new_overflow_error("%c arg not in range(0x110000)"), FormatSpecError::IntTooLargeForCLong => { vm.new_overflow_error("Python int too large to convert to C long") From 8054d4d0d97658da1f9f7ad76e48fd8fb548f26f Mon Sep 17 00:00:00 2001 From: youknowdot Date: Tue, 1 Dec 2026 19:23:40 +0900 Subject: [PATCH 4/6] Keep backend selection separate from the float conversion fix --- crates/bigint/Cargo.toml | 4 +-- crates/bigint/src/lib.rs | 25 ------------------ crates/codegen/src/compile.rs | 18 ++----------- crates/codegen/src/ir.rs | 45 ++++++++++++++------------------ crates/codegen/src/preprocess.rs | 9 +++++-- crates/common/src/format.rs | 19 ++------------ crates/common/src/int.rs | 17 +++++++++--- crates/vm/src/format.rs | 4 +-- 8 files changed, 48 insertions(+), 93 deletions(-) diff --git a/crates/bigint/Cargo.toml b/crates/bigint/Cargo.toml index 8060092f816..07324d43e3e 100644 --- a/crates/bigint/Cargo.toml +++ b/crates/bigint/Cargo.toml @@ -10,7 +10,7 @@ license.workspace = true [features] malachite-bigint = ["dep:malachite-bigint", "dep:malachite-base", "dep:malachite-q"] -num-bigint = ["dep:num-bigint", "dep:num-integer"] +num-bigint = ["dep:num-bigint", "dep:num-integer", "dep:num-traits"] [dependencies] malachite-bigint = { workspace = true, optional = true } @@ -18,7 +18,7 @@ malachite-base = { workspace = true, optional = true } malachite-q = { workspace = true, optional = true } num-bigint = { workspace = true, optional = true } num-integer = { workspace = true, optional = true } -num-traits.workspace = true +num-traits = { workspace = true, optional = true } [lints] workspace = true diff --git a/crates/bigint/src/lib.rs b/crates/bigint/src/lib.rs index 2ed70ff68d5..5c45635df77 100644 --- a/crates/bigint/src/lib.rs +++ b/crates/bigint/src/lib.rs @@ -11,20 +11,6 @@ pub use malachite_bigint::{BigInt, BigUint, Sign, ToBigInt}; #[cfg(all(feature = "num-bigint", not(feature = "malachite-bigint")))] pub use num_bigint::{BigInt, BigUint, Sign, ToBigInt}; -/// Convert an integer to a finite float, or return None when it overflows. -#[inline(always)] -#[must_use] -pub fn bigint_to_finite_float(int: &BigInt) -> Option { - use num_traits::{One, ToPrimitive}; - - // malachite-bigint's ToPrimitive returns None when the input exceeds - // the largest finite magnitude, even when nearest rounding is finite. - let value = int - .to_f64() - .unwrap_or_else(|| true_div(int, &BigInt::one())); - value.is_finite().then_some(value) -} - /// Express a finite binary64 value as a reduced ratio with a positive denominator. #[cfg(feature = "malachite-bigint")] #[must_use] @@ -168,17 +154,6 @@ extern crate alloc; mod tests { use super::*; - #[test] - fn integer_to_float_checks_the_halfway_overflow_boundary() { - let one = BigInt::from(1); - let halfway = (&one << 1024usize) - (&one << 970usize); - let just_below = &halfway - &one; - assert_eq!(bigint_to_finite_float(&just_below), Some(f64::MAX)); - assert_eq!(bigint_to_finite_float(&-&just_below), Some(-f64::MAX)); - assert_eq!(bigint_to_finite_float(&halfway), None); - assert_eq!(bigint_to_finite_float(&-&halfway), None); - } - #[test] fn exact_float_ratios() { assert_eq!(float_to_ratio(-0.0), Some((0.into(), 1.into()))); diff --git a/crates/codegen/src/compile.rs b/crates/codegen/src/compile.rs index 8b4500d4090..00444447fc4 100644 --- a/crates/codegen/src/compile.rs +++ b/crates/codegen/src/compile.rs @@ -26,7 +26,7 @@ use num_complex::Complex; use num_traits::{Num, ToPrimitive, Zero}; use ruff_python_ast::{self as ast, HasNodeIndex, name::Name}; use ruff_text_size::{Ranged, TextRange, TextSize, TextSlice}; -use rustpython_bigint::{BigInt, bigint_to_finite_float}; +use rustpython_bigint::BigInt; use rustpython_compiler_core::{ AstLocations, Mode, OneIndexed, PositionEncoding, SourceFile, SourceLocation, SourceLocationRange, @@ -12134,7 +12134,7 @@ impl<'warnings> Compiler<'warnings> { right: &ConstantData, ) -> Option { let left = match left { - ConstantData::Integer { value } => bigint_to_finite_float(value)?, + ConstantData::Integer { value } => value.to_f64()?, ConstantData::Float { value } => *value, _ => return None, }; @@ -14799,20 +14799,6 @@ match x: compile_top(ast, source_file, Mode::Exec, CompileOpts::default()).unwrap(); } - #[test] - fn match_literal_rejects_an_overflowing_real_component() { - let one = BigInt::from(1); - let halfway = (&one << 1024usize) - (&one << 970usize); - let just_below = &halfway - &one; - for n in [&halfway, &-&halfway] { - assert_eq!( - compile_exec_error_message(&format!("match x:\n case {n} + 1j: pass\n")), - "patterns may only match literals and attribute lookups" - ); - } - compile_exec(&format!("match x:\n case {just_below} + 1j: pass\n")); - } - #[test] fn match_literal_binop_folding_uses_cpython_complex_shape() { assert!( diff --git a/crates/codegen/src/ir.rs b/crates/codegen/src/ir.rs index 6bd8422164f..b5c55af0c59 100644 --- a/crates/codegen/src/ir.rs +++ b/crates/codegen/src/ir.rs @@ -3,7 +3,7 @@ use core::ops::{Deref, DerefMut, Index, IndexMut}; use crate::{IndexMap, IndexSet, error::InternalError}; use num_complex::Complex; use num_traits::{ToPrimitive, Zero}; -use rustpython_bigint::{BigInt, bigint_to_finite_float}; +use rustpython_bigint::BigInt; use rustpython_wtf8::Wtf8Buf; use rustpython_compiler_core::{ @@ -4749,11 +4749,14 @@ fn const_folding_safe_power(left: &ConstantData, right: &ConstantData) -> Option if l.is_zero() { return None; } - let base = bigint_to_finite_float(l)?; + let base = l.to_f64()?; + if !base.is_finite() { + return None; + } let result = if let Some(exp) = r.to_i32() { base.powi(exp) } else { - base.powf(bigint_to_finite_float(r)?) + base.powf(r.to_f64()?) }; if !result.is_finite() { return None; @@ -5220,7 +5223,7 @@ fn eval_const_binop( } // Int op Float or Float op Int → Float (ConstantData::Integer { value: l }, ConstantData::Float { value: r }) => { - let l_f = bigint_to_finite_float(l)?; + let l_f = l.to_f64()?; eval_const_binop( &ConstantData::Float { value: l_f }, &ConstantData::Float { value: *r }, @@ -5228,7 +5231,7 @@ fn eval_const_binop( ) } (ConstantData::Float { value: l }, ConstantData::Integer { value: r }) => { - let r_f = bigint_to_finite_float(r)?; + let r_f = r.to_f64()?; eval_const_binop( &ConstantData::Float { value: *l }, &ConstantData::Float { value: r_f }, @@ -5236,10 +5239,20 @@ fn eval_const_binop( ) } (ConstantData::Integer { value: l }, ConstantData::Complex { value: r }) => { - eval_const_mixed_complex_binop(bigint_to_finite_float(l)?, *r, true, op) + eval_const_mixed_complex_binop( + l.to_f64().filter(|value| value.is_finite())?, + *r, + true, + op, + ) } (ConstantData::Complex { value: l }, ConstantData::Integer { value: r }) => { - eval_const_mixed_complex_binop(bigint_to_finite_float(r)?, *l, false, op) + eval_const_mixed_complex_binop( + r.to_f64().filter(|value| value.is_finite())?, + *l, + false, + op, + ) } (ConstantData::Float { value: l }, ConstantData::Complex { value: r }) => { eval_const_mixed_complex_binop(*l, *r, true, op) @@ -7178,24 +7191,6 @@ mod tests { ConstantData::Float { value: f64::NAN } } - #[test] - fn mixed_numeric_folding_leaves_overflow_to_runtime() { - let integer = ConstantData::Integer { - value: BigInt::from(1) << 1024usize, - }; - let float = ConstantData::Float { value: 0.0 }; - assert!(eval_const_binop(&integer, &float, oparg::BinaryOperator::Add).is_none()); - assert!(eval_const_binop(&float, &integer, oparg::BinaryOperator::Add).is_none()); - let exponent = ConstantData::Integer { - value: -(BigInt::from(1) << 1024usize), - }; - assert!(const_folding_safe_power(&int_const(2), &exponent).is_none()); - assert!(matches!( - const_folding_safe_power(&int_const(2), &int_const(-1075)), - Some(ConstantData::Float { value: 0.0 }) - )); - } - #[test] fn constant_pool_frozenset_key_ignores_order_and_duplicates_like_cpython() { let mut pool = ConstantPool::default(); diff --git a/crates/codegen/src/preprocess.rs b/crates/codegen/src/preprocess.rs index 1b271fcb600..be5b5939b3b 100644 --- a/crates/codegen/src/preprocess.rs +++ b/crates/codegen/src/preprocess.rs @@ -3,7 +3,8 @@ use alloc::{ string::{String, ToString}, vec::Vec, }; -use rustpython_bigint::{BigInt, bigint_to_finite_float}; +use num_traits::ToPrimitive; +use rustpython_bigint::BigInt; use ruff_python_ast::{ self as ast, AtomicNodeIndex, ConversionFlag, Expr, ExprFString, FString, FStringFlags, @@ -945,7 +946,11 @@ fn fold_match_number_binop(left: &Expr, op: Operator, right: &Expr) -> Option { // CPython refuses to convert an overflowing integer to float and // leaves the binary expression unfolded in this optimization pass. - bigint_to_finite_float(&value)? + let value = value.to_f64()?; + if !value.is_finite() { + return None; + } + value } MatchNumber::Float(value) => value, MatchNumber::Complex { diff --git a/crates/common/src/format.rs b/crates/common/src/format.rs index 109c974cd06..4d0c7aecad7 100644 --- a/crates/common/src/format.rs +++ b/crates/common/src/format.rs @@ -4,7 +4,7 @@ use core::{cmp, str::FromStr}; use num_complex::Complex64; use num_traits::FromPrimitive; use num_traits::{Signed, cast::ToPrimitive}; -use rustpython_bigint::{BigInt, Sign, bigint_to_finite_float}; +use rustpython_bigint::{BigInt, Sign}; use rustpython_literal::float; use rustpython_literal::format::Case; @@ -1069,7 +1069,7 @@ impl FormatSpec { | FormatType::FixedPoint(_) | FormatType::Exponent(_) | FormatType::Percentage, - ) => match bigint_to_finite_float(num) { + ) => match num.to_f64() { Some(float) => return self.format_float(float), _ => Err(FormatSpecError::UnableToConvert), }, @@ -2047,21 +2047,6 @@ mod tests { ); } - #[test] - fn integer_float_formats_check_overflow_before_formatting() { - let one = BigInt::from(1); - let halfway = (&one << 1024usize) - (&one << 970usize); - let just_below = &halfway - &one; - for spec in ["e", "f", "g", "%"] { - let spec = FormatSpec::parse(spec).unwrap(); - assert_eq!( - spec.format_int(&halfway), - Err(FormatSpecError::UnableToConvert) - ); - assert_eq!(spec.format_int(&just_below), spec.format_float(f64::MAX)); - } - } - #[test] fn format_int() { assert_eq!( diff --git a/crates/common/src/int.rs b/crates/common/src/int.rs index d61fd17da24..316aedf9d54 100644 --- a/crates/common/src/int.rs +++ b/crates/common/src/int.rs @@ -1,7 +1,7 @@ -use num_traits::Zero; +use num_traits::{One, ToPrimitive, Zero}; use rustpython_bigint::{BigInt, BigUint, Sign}; -pub use rustpython_bigint::{bigint_to_finite_float, float_to_ratio, true_div}; +pub use rustpython_bigint::{float_to_ratio, true_div}; #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum BytesToIntError { @@ -174,10 +174,21 @@ fn word_all_ascii_digits(word: u64) -> bool { (below | above) & 0x8080_8080_8080_8080 == 0 } +/// Convert an integer to a finite float, or return None when it overflows. +#[inline(always)] +#[must_use] +pub fn bigint_to_finite_float(int: &BigInt) -> Option { + // malachite-bigint's ToPrimitive returns None when the input exceeds + // the largest finite magnitude, even when nearest rounding is finite. + let value = int + .to_f64() + .unwrap_or_else(|| true_div(int, &BigInt::one())); + value.is_finite().then_some(value) +} + #[cfg(test)] mod tests { use super::*; - use num_traits::One; #[test] fn true_div_signed_zero() { diff --git a/crates/vm/src/format.rs b/crates/vm/src/format.rs index 6443729e5c5..4c9b93bab09 100644 --- a/crates/vm/src/format.rs +++ b/crates/vm/src/format.rs @@ -84,9 +84,7 @@ pub(crate) fn format_spec_error( FormatSpecError::NotAllowed(s) => { vm.new_value_error(format!("{s} not allowed with integer format specifier 'c'")) } - FormatSpecError::UnableToConvert => { - vm.new_overflow_error("int too large to convert to float") - } + FormatSpecError::UnableToConvert => vm.new_value_error("Unable to convert int to float"), FormatSpecError::CodeNotInRange => vm.new_overflow_error("%c arg not in range(0x110000)"), FormatSpecError::IntTooLargeForCLong => { vm.new_overflow_error("Python int too large to convert to C long") From 2b3fb00414c675ed04df5202ec95fb6a44bb9c4c Mon Sep 17 00:00:00 2001 From: youknowdot Date: Wed, 2 Dec 2026 09:02:30 +0900 Subject: [PATCH 5/6] Use the selected BigInt backend for pathconf overflow Assisted-by: Codex:GPT-6.2 --- crates/vm/src/stdlib/posix.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/vm/src/stdlib/posix.rs b/crates/vm/src/stdlib/posix.rs index 927fd81bf1f..7782bc773ee 100644 --- a/crates/vm/src/stdlib/posix.rs +++ b/crates/vm/src/stdlib/posix.rs @@ -2744,7 +2744,8 @@ pub mod module { warn_if_bool_fd(&obj, vm)?; let index = index?; let fd = i32::try_from(index.as_bigint()).map_err(|_| { - let message = if index.as_bigint().sign() == malachite_bigint::Sign::Minus { + let message = if index.as_bigint().sign() == rustpython_bigint::Sign::Minus + { "fd is less than minimum" } else { "fd is greater than maximum" From 1c894bf65cc8579d6f2a75b250d7dcb8f2c74868 Mon Sep 17 00:00:00 2001 From: youknowdot Date: Wed, 2 Dec 2026 11:01:44 +0900 Subject: [PATCH 6/6] Select BigInt backends for isolated docs and JIT tests Assisted-by: Codex:GPT-6.2 --- CONTRIBUTING.md | 2 +- crates/bigint/Cargo.toml | 3 +++ crates/capi/Cargo.toml | 3 +++ crates/codegen/Cargo.toml | 3 +++ crates/common/Cargo.toml | 3 +++ crates/compiler-core/Cargo.toml | 3 +++ crates/compiler/Cargo.toml | 3 +++ crates/derive-impl/Cargo.toml | 3 +++ crates/derive/Cargo.toml | 3 +++ crates/jit/Cargo.toml | 7 +++++-- crates/literal/Cargo.toml | 3 +++ crates/stdlib/Cargo.toml | 3 +++ crates/vm/Cargo.toml | 3 +++ crates/wasm/Cargo.toml | 3 +++ 14 files changed, 42 insertions(+), 3 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 710bb2cafd3..762639ed0f7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -97,7 +97,7 @@ separate `cargo` config that only applies there: ```shell $ cd crates/capi -$ cargo test +$ cargo test --features malachite-bigint ``` Python unit tests can be run by compiling RustPython and running the test module: diff --git a/crates/bigint/Cargo.toml b/crates/bigint/Cargo.toml index 07324d43e3e..0660a25ef8c 100644 --- a/crates/bigint/Cargo.toml +++ b/crates/bigint/Cargo.toml @@ -8,6 +8,9 @@ rust-version.workspace = true repository.workspace = true license.workspace = true +[package.metadata.docs.rs] +features = ["malachite-bigint"] + [features] malachite-bigint = ["dep:malachite-bigint", "dep:malachite-base", "dep:malachite-q"] num-bigint = ["dep:num-bigint", "dep:num-integer", "dep:num-traits"] diff --git a/crates/capi/Cargo.toml b/crates/capi/Cargo.toml index 070bd29122c..ab02fff93c5 100644 --- a/crates/capi/Cargo.toml +++ b/crates/capi/Cargo.toml @@ -11,6 +11,9 @@ license.workspace = true [lib] crate-type = ["cdylib", "rlib"] +[package.metadata.docs.rs] +features = ["malachite-bigint"] + [features] malachite-bigint = ["rustpython-bigint/malachite-bigint", "rustpython-pylib/malachite-bigint", "rustpython-stdlib/malachite-bigint", "rustpython-vm/malachite-bigint"] num-bigint = ["rustpython-bigint/num-bigint", "rustpython-pylib/num-bigint", "rustpython-stdlib/num-bigint", "rustpython-vm/num-bigint"] diff --git a/crates/codegen/Cargo.toml b/crates/codegen/Cargo.toml index 637ea527903..28729601a94 100644 --- a/crates/codegen/Cargo.toml +++ b/crates/codegen/Cargo.toml @@ -8,6 +8,9 @@ rust-version.workspace = true repository.workspace = true license.workspace = true +[package.metadata.docs.rs] +features = ["malachite-bigint"] + [features] default = ["std"] malachite-bigint = ["rustpython-bigint/malachite-bigint", "rustpython-compiler-core/malachite-bigint", "rustpython-literal/malachite-bigint"] diff --git a/crates/common/Cargo.toml b/crates/common/Cargo.toml index 4ae1b558717..4b9ea98c384 100644 --- a/crates/common/Cargo.toml +++ b/crates/common/Cargo.toml @@ -8,6 +8,9 @@ rust-version.workspace = true repository.workspace = true license.workspace = true +[package.metadata.docs.rs] +features = ["malachite-bigint"] + [features] default = ["std"] malachite-bigint = ["rustpython-bigint/malachite-bigint", "rustpython-literal/malachite-bigint"] diff --git a/crates/compiler-core/Cargo.toml b/crates/compiler-core/Cargo.toml index 09dd78c60d6..448a683f0e3 100644 --- a/crates/compiler-core/Cargo.toml +++ b/crates/compiler-core/Cargo.toml @@ -8,6 +8,9 @@ rust-version.workspace = true repository.workspace = true license.workspace = true +[package.metadata.docs.rs] +features = ["malachite-bigint"] + [features] malachite-bigint = ["rustpython-bigint/malachite-bigint"] num-bigint = ["rustpython-bigint/num-bigint"] diff --git a/crates/compiler/Cargo.toml b/crates/compiler/Cargo.toml index d4e137361ec..a2848f9f333 100644 --- a/crates/compiler/Cargo.toml +++ b/crates/compiler/Cargo.toml @@ -8,6 +8,9 @@ rust-version.workspace = true repository.workspace = true license.workspace = true +[package.metadata.docs.rs] +features = ["malachite-bigint"] + [features] malachite-bigint = ["rustpython-compiler-core/malachite-bigint", "rustpython-codegen/malachite-bigint"] num-bigint = ["rustpython-compiler-core/num-bigint", "rustpython-codegen/num-bigint"] diff --git a/crates/derive-impl/Cargo.toml b/crates/derive-impl/Cargo.toml index 42f1b52bdc3..93f31daed59 100644 --- a/crates/derive-impl/Cargo.toml +++ b/crates/derive-impl/Cargo.toml @@ -8,6 +8,9 @@ rust-version.workspace = true repository.workspace = true license.workspace = true +[package.metadata.docs.rs] +features = ["malachite-bigint"] + [features] malachite-bigint = ["rustpython-compiler-core/malachite-bigint"] num-bigint = ["rustpython-compiler-core/num-bigint"] diff --git a/crates/derive/Cargo.toml b/crates/derive/Cargo.toml index 8eeceb37a4f..afb05ce8ee6 100644 --- a/crates/derive/Cargo.toml +++ b/crates/derive/Cargo.toml @@ -11,6 +11,9 @@ license.workspace = true [lib] proc-macro = true +[package.metadata.docs.rs] +features = ["malachite-bigint"] + [features] malachite-bigint = ["rustpython-compiler/malachite-bigint", "rustpython-derive-impl/malachite-bigint"] num-bigint = ["rustpython-compiler/num-bigint", "rustpython-derive-impl/num-bigint"] diff --git a/crates/jit/Cargo.toml b/crates/jit/Cargo.toml index 6f554dcf475..1805a1e5d58 100644 --- a/crates/jit/Cargo.toml +++ b/crates/jit/Cargo.toml @@ -10,9 +10,12 @@ license.workspace = true autotests = false +[package.metadata.docs.rs] +features = ["malachite-bigint"] + [features] -malachite-bigint = ["rustpython-compiler-core/malachite-bigint"] -num-bigint = ["rustpython-compiler-core/num-bigint"] +malachite-bigint = ["rustpython-compiler-core/malachite-bigint", "rustpython-derive/malachite-bigint"] +num-bigint = ["rustpython-compiler-core/num-bigint", "rustpython-derive/num-bigint"] [dependencies] rustpython-compiler-core = { workspace = true } diff --git a/crates/literal/Cargo.toml b/crates/literal/Cargo.toml index 83cfe34e0f3..b0f737c6ca3 100644 --- a/crates/literal/Cargo.toml +++ b/crates/literal/Cargo.toml @@ -11,6 +11,9 @@ rust-version = { workspace = true } [lints] workspace = true +[package.metadata.docs.rs] +features = ["malachite-bigint"] + [features] malachite-bigint = ["rustpython-bigint/malachite-bigint"] num-bigint = ["rustpython-bigint/num-bigint"] diff --git a/crates/stdlib/Cargo.toml b/crates/stdlib/Cargo.toml index 22544902638..f8712c98b7c 100644 --- a/crates/stdlib/Cargo.toml +++ b/crates/stdlib/Cargo.toml @@ -10,6 +10,9 @@ license.workspace = true # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[package.metadata.docs.rs] +features = ["malachite-bigint"] + [features] default = ["compiler", "host_env", "doc", "ucd_3_2_0"] malachite-bigint = ["rustpython-bigint/malachite-bigint", "rustpython-common/malachite-bigint", "rustpython-derive/malachite-bigint", "rustpython-vm/malachite-bigint", "pymath/malachite-bigint", "rustpython-pylib/malachite-bigint"] diff --git a/crates/vm/Cargo.toml b/crates/vm/Cargo.toml index 300431c116b..3422bfc2265 100644 --- a/crates/vm/Cargo.toml +++ b/crates/vm/Cargo.toml @@ -9,6 +9,9 @@ rust-version.workspace = true repository.workspace = true license.workspace = true +[package.metadata.docs.rs] +features = ["malachite-bigint"] + [features] default = ["compiler", "wasmbind", "gc", "host_env", "stdio", "doc"] malachite-bigint = ["rustpython-bigint/malachite-bigint", "rustpython-common/malachite-bigint", "rustpython-compiler?/malachite-bigint", "rustpython-compiler-core/malachite-bigint", "rustpython-codegen?/malachite-bigint", "rustpython-derive/malachite-bigint", "rustpython-jit?/malachite-bigint", "rustpython-literal/malachite-bigint"] diff --git a/crates/wasm/Cargo.toml b/crates/wasm/Cargo.toml index 93083fb5569..675525e1177 100644 --- a/crates/wasm/Cargo.toml +++ b/crates/wasm/Cargo.toml @@ -11,6 +11,9 @@ license.workspace = true [lib] crate-type = ["cdylib", "rlib"] +[package.metadata.docs.rs] +features = ["malachite-bigint"] + [features] default = ["freeze-stdlib", "doc", "ucd_3_2_0"] malachite-bigint = ["rustpython-common/malachite-bigint", "rustpython-pylib?/malachite-bigint", "rustpython-stdlib?/malachite-bigint", "rustpython-vm/malachite-bigint"]