diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index f9378b403a1..178ddf714b5 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 @@ -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' @@ -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 }} @@ -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 @@ -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..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 @@ -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/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/Cargo.lock b/Cargo.lock index 2ca2eae12f0..efd36924dfa 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..bbb0c3377b2 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,21 @@ 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 + +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 +``` + +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 should select the same backend throughout. +RustPython library defaults do not select a backend. + ### WASI You can compile RustPython to a standalone WebAssembly WASI module so it can run anywhere. @@ -115,7 +130,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..0660a25ef8c --- /dev/null +++ b/crates/bigint/Cargo.toml @@ -0,0 +1,27 @@ +[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 + +[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"] + +[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..5c45635df77 --- /dev/null +++ b/crates/bigint/src/lib.rs @@ -0,0 +1,183 @@ +//! 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; + + // 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 +} + +#[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..ab02fff93c5 100644 --- a/crates/capi/Cargo.toml +++ b/crates/capi/Cargo.toml @@ -11,11 +11,18 @@ 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"] + [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..28729601a94 100644 --- a/crates/codegen/Cargo.toml +++ b/crates/codegen/Cargo.toml @@ -8,8 +8,13 @@ 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"] +num-bigint = ["rustpython-bigint/num-bigint", "rustpython-compiler-core/num-bigint", "rustpython-literal/num-bigint"] std = ["thiserror/std", "itertools/use_std"] [dependencies] @@ -27,7 +32,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 c48766e99d5..d2fcb52a088 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 42cffdb5723..374d91a9755 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::{Signed, ToPrimitive, Zero}; +use rustpython_bigint::BigInt; use rustpython_literal::float::bigint_to_finite_float; use rustpython_wtf8::Wtf8Buf; diff --git a/crates/codegen/src/preprocess.rs b/crates/codegen/src/preprocess.rs index 5019e965f38..ab3135121e4 100644 --- a/crates/codegen/src/preprocess.rs +++ b/crates/codegen/src/preprocess.rs @@ -3,7 +3,7 @@ use alloc::{ string::{String, ToString}, vec::Vec, }; -use malachite_bigint::BigInt; +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..4b9ea98c384 100644 --- a/crates/common/Cargo.toml +++ b/crates/common/Cargo.toml @@ -8,8 +8,13 @@ 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"] +num-bigint = ["rustpython-bigint/num-bigint", "rustpython-literal/num-bigint"] binascii = ["dep:crc32fast"] bz2 = ["std", "dep:bzip2"] cjk-codecs = [] @@ -48,9 +53,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 cd3da6f9c66..1cd034efc06 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 fc28a6a8b32..5a170eb2b8d 100644 --- a/crates/common/src/int.rs +++ b/crates/common/src/int.rs @@ -1,24 +1,8 @@ -use malachite_bigint::{BigInt, BigUint, Sign}; -use malachite_q::Rational; -use num_traits::{One, Zero}; +use num_traits::Zero; +use rustpython_bigint::{BigInt, BigUint, Sign}; -pub use rustpython_literal::float::{bigint_to_finite_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}; +pub use rustpython_literal::float::bigint_to_finite_float; #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum BytesToIntError { @@ -194,6 +178,7 @@ fn word_all_ascii_digits(word: u64) -> bool { #[cfg(test)] mod tests { use super::*; + use num_traits::One; #[test] fn true_div_signed_zero() { diff --git a/crates/compiler-core/Cargo.toml b/crates/compiler-core/Cargo.toml index 22201597d90..448a683f0e3 100644 --- a/crates/compiler-core/Cargo.toml +++ b/crates/compiler-core/Cargo.toml @@ -8,6 +8,13 @@ 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"] + [dependencies] # rustpython-parser-core = { workspace = true, features=["location"] } ruff_source_file = { workspace = true } @@ -16,7 +23,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..a2848f9f333 100644 --- a/crates/compiler/Cargo.toml +++ b/crates/compiler/Cargo.toml @@ -8,8 +8,15 @@ 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"] + [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..93f31daed59 100644 --- a/crates/derive-impl/Cargo.toml +++ b/crates/derive-impl/Cargo.toml @@ -8,6 +8,13 @@ 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"] + [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..afb05ce8ee6 100644 --- a/crates/derive/Cargo.toml +++ b/crates/derive/Cargo.toml @@ -11,6 +11,13 @@ 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"] + [dependencies] rustpython-compiler = { workspace = true } rustpython-derive-impl = { workspace = true } diff --git a/crates/jit/Cargo.toml b/crates/jit/Cargo.toml index 5dcf0f4c31b..1805a1e5d58 100644 --- a/crates/jit/Cargo.toml +++ b/crates/jit/Cargo.toml @@ -10,6 +10,13 @@ license.workspace = true autotests = false +[package.metadata.docs.rs] +features = ["malachite-bigint"] + +[features] +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 e42dfd14af4..b0f737c6ca3 100644 --- a/crates/literal/Cargo.toml +++ b/crates/literal/Cargo.toml @@ -11,6 +11,13 @@ 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"] + [dependencies] rustpython-unicode = { workspace = true } rustpython-wtf8 = { workspace = true } @@ -18,9 +25,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 84f786c0107..b61168e6af3 100644 --- a/crates/literal/src/float.rs +++ b/crates/literal/src/float.rs @@ -2,10 +2,9 @@ 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; +use rustpython_bigint::BigInt; +pub use rustpython_bigint::true_div; /// Convert an integer to a finite float, or return None when it overflows. #[inline(always)] @@ -21,23 +20,6 @@ pub fn bigint_to_finite_float(int: &BigInt) -> Option { value.is_finite().then_some(value) } -/// 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 -} - #[must_use] pub fn parse_str(literal: &str) -> Option { parse_inner(literal.trim().as_bytes()) diff --git a/crates/pylib/Cargo.toml b/crates/pylib/Cargo.toml index b1962409af4..6fe7d8337e2 100644 --- a/crates/pylib/Cargo.toml +++ b/crates/pylib/Cargo.toml @@ -10,6 +10,8 @@ rust-version.workspace = true repository.workspace = true [features] +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..f8712c98b7c 100644 --- a/crates/stdlib/Cargo.toml +++ b/crates/stdlib/Cargo.toml @@ -10,8 +10,13 @@ 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"] +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 +37,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 +56,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..3422bfc2265 100644 --- a/crates/vm/Cargo.toml +++ b/crates/vm/Cargo.toml @@ -9,8 +9,13 @@ 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"] +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 +39,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 +68,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 cee62dfd16b..7782bc773ee 100644 --- a/crates/vm/src/stdlib/posix.rs +++ b/crates/vm/src/stdlib/posix.rs @@ -1121,7 +1121,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" @@ -1401,7 +1401,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" @@ -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" 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..675525e1177 100644 --- a/crates/wasm/Cargo.toml +++ b/crates/wasm/Cargo.toml @@ -11,15 +11,20 @@ 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"] +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", 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', }),